Search is not available for this dataset
query
stringlengths
7
355k
document
stringlengths
9
341k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
This is supposed to consolidate common fields w/o revealing them. It takes care of multiple field values. For eg. if name on 3 sites is Joe and 2 others is John, it will create name1: ["site1", "site2", "site3"] name2: ["site4", "site5"]
function calculate_common_fields() { var r = get_all_pi_data(); var vpfvi = pii_vault.aggregate_data.pi_field_value_identifiers; var common_fields = {}; for (f in r) { for (v in r[f]) { var value_identifier = undefined; if (v in vpfvi) { value_identifier = vpfvi[v]; } else { var j = 1; var identifier_array = Object.keys(vpfvi).map(function(key){ return vpfvi[key]; }); //Just to check that this identifier does not already exist. while(1) { value_identifier = f + j; if (identifier_array.indexOf(value_identifier) == -1) { break; } j++; } vpfvi[v] = value_identifier; } common_fields[value_identifier] = r[f][v].substring(0, r[f][v].length - 2 ).split(","); } } pii_vault.current_report.common_fields = common_fields; flush_selective_entries("current_report", ["common_fields"]); flush_selective_entries("aggregate_data", ["pi_field_value_identifiers"]); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_fields2request(includeEmpty) {\n let result = [];\n\n for (const name of this.uniqueFieldNames) {\n var newName = name;\n\n // send clonables as list (even if there's only one field) and other fields as plain values\n let potentialClones = this.fields.filter(f =>\n f.name === name && (typeof f.value !== 'undefined') && (f.value !== \"\" || includeEmpty)\n );\n\n if (potentialClones.length === 0) continue;\n\n // encode ArrayBuffer as Base64 and change field name as a flag\n let encodeValue = (val) => {\n if (val instanceof ArrayBuffer) {\n newName = `_encoded_base64_${name}`;\n return btoa(String.fromCharCode(...new Uint8Array(val)));\n }\n else {\n return val;\n }\n };\n\n let value = potentialClones[0].clonable\n ? potentialClones.map(c => encodeValue(c.value)) // array for clonable fields\n : encodeValue(potentialClones[0].value) // or plain value otherwise\n // setting 'result' must be separate step as encodeValue() modifies 'newName'\n result[newName] = value;\n\n debug(`${name} = ${ potentialClones[0].clonable ? `[${result[newName]}]` : `\"${result[newName]}\"` }`);\n }\n return result;\n }", "function getCorrectData(sites){\r\n\tvar data = [];\r\n\t\r\n\tfor(var i in sites){\r\n\t\tvar id = Number(sites[i].siteID);\r\n\t\tvar lat = Number(sites[i].siteLat);\r\n\t\tvar lng = Number(sites[i].siteLong);\r\n\t\tvar name = sites[i].siteName;\r\n\t\t\r\n\t\tdata.push({siteID: id, siteLat: lat, siteLong: lng, siteName: name});\t\t\t\t\t\r\n\t}\r\n\treturn data;\r\n}", "function sites(u) {\n let utl = []\n u.forEach(function (element) {\n utl = [...utl, element.website]\n });\n return utl\n}", "function getFieldsValues(fields) { // 1230\n var doc = {}; // 1231\n _.each(fields, function formValuesEach(field) { // 1232\n var name = field.getAttribute(\"data-schema-key\"); // 1233\n var val = field.value || field.getAttribute('contenteditable') && field.innerHTML; //value is undefined for contenteditable\n var type = field.getAttribute(\"type\") || \"\"; // 1235\n type = type.toLowerCase(); // 1236\n var tagName = field.tagName || \"\"; // 1237\n tagName = tagName.toLowerCase(); // 1238\n // 1239\n // Handle select // 1240\n if (tagName === \"select\") { // 1241\n if (val === \"true\") { //boolean select // 1242\n doc[name] = true; // 1243\n } else if (val === \"false\") { //boolean select // 1244\n doc[name] = false; // 1245\n } else if (field.hasAttribute(\"multiple\")) { // 1246\n //multiple select, so we want an array value // 1247\n doc[name] = Utility.getSelectValues(field); // 1248\n } else { // 1249\n doc[name] = val; // 1250\n } // 1251\n return; // 1252\n } // 1253\n // 1254\n // Handle checkbox // 1255\n if (type === \"checkbox\") { // 1256\n if (val === \"true\") { //boolean checkbox // 1257\n doc[name] = field.checked; // 1258\n } else { //array checkbox // 1259\n // Add empty array no matter what, // 1260\n // to ensure that unchecking all boxes // 1261\n // will empty the array. // 1262\n if (!_.isArray(doc[name])) { // 1263\n doc[name] = []; // 1264\n } // 1265\n // Add the value to the array only // 1266\n // if checkbox is selected. // 1267\n field.checked && doc[name].push(val); // 1268\n } // 1269\n return; // 1270\n } // 1271\n // 1272\n // Handle radio // 1273\n if (type === \"radio\") { // 1274\n if (field.checked) { // 1275\n if (val === \"true\") { //boolean radio // 1276\n doc[name] = true; // 1277\n } else if (val === \"false\") { //boolean radio // 1278\n doc[name] = false; // 1279\n } else { // 1280\n doc[name] = val; // 1281\n } // 1282\n } // 1283\n return; // 1284\n } // 1285\n // 1286\n // Handle number // 1287\n if (type === \"select\") { // 1288\n doc[name] = Utility.maybeNum(val); // 1289\n return; // 1290\n } // 1291\n // 1292\n // Handle date inputs // 1293\n if (type === \"date\") { // 1294\n if (Utility.isValidDateString(val)) { // 1295\n //Date constructor will interpret val as UTC and create // 1296\n //date at mignight in the morning of val date in UTC time zone // 1297\n doc[name] = new Date(val); // 1298\n } else { // 1299\n doc[name] = null; // 1300\n } // 1301\n return; // 1302\n } // 1303\n // 1304\n // Handle date inputs // 1305\n if (type === \"datetime\") { // 1306\n val = (typeof val === \"string\") ? val.replace(/ /g, \"T\") : val; // 1307\n if (Utility.isValidNormalizedForcedUtcGlobalDateAndTimeString(val)) { // 1308\n //Date constructor will interpret val as UTC due to ending \"Z\" // 1309\n doc[name] = new Date(val); // 1310\n } else { // 1311\n doc[name] = null; // 1312\n } // 1313\n return; // 1314\n } // 1315\n // 1316\n // Handle date inputs // 1317\n if (type === \"datetime-local\") { // 1318\n val = (typeof val === \"string\") ? val.replace(/ /g, \"T\") : val; // 1319\n var offset = field.getAttribute(\"data-offset\") || \"Z\"; // 1320\n if (Utility.isValidNormalizedLocalDateAndTimeString(val)) { // 1321\n doc[name] = new Date(val + offset); // 1322\n } else { // 1323\n doc[name] = null; // 1324\n } // 1325\n return; // 1326\n } // 1327\n // 1328\n // Handle all other inputs // 1329\n doc[name] = val; // 1330\n }); // 1331\n // 1332\n return doc; // 1333\n} // 1334", "function copyFields(source, fieldList, target={}) {\n return fieldList.reduce((orig, field) => {\n if (source[field] && isNonBlank(source[field])) orig[field] = source[field]\n return orig\n }, target)\n}", "get clonedFields() {\n \n // check result\n if(this.record.data) {\n //define an array key, value to be sent \n let clonedFields = [];\n \n for (let i=0; i< this.fields.length; i++) {\n //extract the short fieldName from the full name to be sent to the lightning-form component\n const tmpArray = this.fields[i].split(\".\");\n \n let fieldName = tmpArray[1];\n // get the value of each field\n let fieldValue = getFieldValue(this.record.data, this.fields[i]);\n //push fieldName and fieldValue for each field\n clonedFields.push({key : fieldName, value : fieldValue });\n }\n \n return clonedFields;\n }\n else return null;\n \n }", "function getGroupVals(field, $obj) {\n var $selector;\n var temp_val;\n var value = [];\n\n if ($obj && $obj.length) {\n $selector = $obj;\n } else {\n if (field === \"topic\") {\n $selector = $(\".ia_topic .available_topics option:selected\");\n } else if ((ia_data.live.dev_milestone !== \"live\" && ia_data.live.dev_milestone !== \"deprecated\") && (field === \"developer\")) {\n $selector = $(\".developer_username input[type='text']\");\n } else {\n $selector = $(\".\" + field).children(\"input\");\n }\n }\n\n $selector.each(function(index) {\n if (field === \"developer\") {\n var $li_item = (ia_data.live.dev_milestone !== \"live\" && ia_data.live.dev_milestone !== \"deprecated\")? $(this).parent().parent().parent() : $(this).parent().parent();\n\n temp_val = {};\n temp_val.name = $.trim($(this).val());\n temp_val.type = $.trim($li_item.find(\".available_types\").find(\"option:selected\").text()) || \"legacy\";\n temp_val.username = $.trim($li_item.find(\".developer_username input[type='text']\").val());\n \n if (!temp_val.username) {\n return;\n }\n } else {\n if (field === \"topic\") {\n temp_val = $(this).attr(\"value\").length? $.trim($(this).text()) : \"\";\n } else {\n temp_val = $.trim($(this).val());\n }\n }\n\n if (temp_val && $.inArray(temp_val, value) === -1) {\n value.push(temp_val);\n }\n });\n\n return value;\n }", "player_fields(fields) { // Fields element in parameter\n let player_field = this.players.map((player, player_index) =>\n fields.reduce(function (acc, obj, index, array) {\n let key = array[player_index].className;\n let player_name = player.name;\n if (!acc[player_name]) {\n acc[player_name] = [];\n }\n\n if (obj.className === key) {\n acc[player_name].push(obj)\n }\n return acc;\n }, []))\n\n return player_field;\n }", "function wrapFields(fields) {\n return [{\"Field\": fields}];\n}", "function allUniqFields(syms,pref=\"\") {\n const names = new Set()\n for(const sym of syms) {\n let name = `${pref}${sym.orig}`\n for(let cnt = 0;names.has(name);cnt++,name = `${pref}${sym.orig}${cnt}`){}\n names.add(name)\n sym.fieldName = name\n }\n}", "static packViewedFields(fields) {\n return [this.FieldsPrefix, fields.length, ...new Set(fields).values()];\n }", "function setupCommonData () {\n for (const field in commonFields) {\n setSharedData(field, getSharedDataInitialValue(field, commonFields[field]))\n }\n }", "getBodySiteInfo(metagenomes, siteData) {\n var order = {};\n var color = {};\n\n for (var i = 0; i < metagenomes.length; i++) {\n var mg = metagenomes[i];\n var site = siteData.site[mg];\n if (!(site in order)) {\n order[site] = siteData.order[mg];\n color[site] = siteData.color[mg];\n }\n }\n\n return {\n order: order,\n color: color\n };\n }", "formatFields(fields, data) {\n let formattedData = [];\n // For every data returned from Neo4j\n for(let i = 0; i < data.length; i++) {\n let obj = {};\n // For every fields\n for(let j = 0; j < data[i]._fields.length; j++) {\n let key = fields[j];\n obj[key] = data[i]._fields[j];\n }\n formattedData.push(obj);\n }\n return this.wrapData(formattedData);\n }", "function getOnlyFullValues(formName, fieldName, otherFieldNames)\r\n{\r\n if(otherFieldNames)\r\n {\r\n var retValues = new Array();\r\n var len = 0;\r\n if(eval('document.'+formName+'.'+fieldName)) \r\n len = eval('document.'+formName+'.'+fieldName).length;\r\n \r\n if(len != 0 && len == null )\r\n {\r\n retValues[0] = new Array();\r\n for(var j=1; j<=otherFieldNames.length; j++)\r\n\t {\r\n\t\t\tif( eval('document.'+formName+'.'+otherFieldNames[j-1]).value != null \r\n\t\t\t\t&& eval('document.'+formName+'.'+otherFieldNames[j-1]).value != \"\")\r\n\t\t {\r\n\t\t\t\tretValues[0][j] = eval('document.'+formName+'.'+otherFieldNames[j-1]).value;\r\n\t\t\t\tretValues[0][0] = eval('document.'+formName+'.'+fieldName).value;\r\n\t\t }\r\n\t }\r\n }\r\n else\r\n {\r\n var i=0;\r\n for(var cnt=0; cnt < len; cnt++)\r\n {\r\n \r\n\r\n for(var j=1; j<=otherFieldNames.length; j++)\r\n\t\t {\r\n\t\t\t if(eval('document.'+formName+'.'+otherFieldNames[j-1])[cnt].value != null \r\n\t\t\t\t && eval('document.'+formName+'.'+otherFieldNames[j-1])[cnt].value != \"\")\r\n\t\t\t {\r\n\t\t\t\t\t retValues[i] = new Array();\r\n\t\t\t\tretValues[i][j] = eval('document.'+formName+'.'+otherFieldNames[j-1])[cnt].value;\r\n\t\t\t\tretValues[i][0] = eval('document.'+formName+'.'+fieldName)[cnt].value;\r\n\t\t\t\ti++;\r\n\t\t\t }\r\n\t\t }\r\n }\r\n }\r\n return retValues;\r\n }\r\n }", "static copyField(source, destination, name) {\n const parentNames = name.split(\".\");\n const fieldName = parentNames.pop();\n let sourceParent = source;\n let destinationParent = destination;\n for (let parentName of parentNames) {\n if (!sourceParent.hasOwnProperty(parentName)) {\n return;\n }\n sourceParent = sourceParent[parentName];\n if (!destinationParent.hasOwnProperty(parentName)) {\n destinationParent[parentName] = {};\n }\n destinationParent = destinationParent[parentName];\n }\n destinationParent[fieldName] = sourceParent[fieldName];\n }", "function FieldList(platformName) {\n var fields = { \n 'exclusiveAtLaunch' : 'proposal.plannedPlatforms[#PLATFORM#].exclusiveAtLaunch',\n 'plannedRegions' : 'proposal.plannedPlatforms[#PLATFORM#].plannedRegions',\n 'plannedLanguages' : 'proposal.plannedPlatforms[#PLATFORM#].plannedLanguages',\n 'businessModel' : 'proposal.plannedPlatforms[#PLATFORM#].businessModel',\n 'offlineMultiplayer' : 'proposal.plannedPlatforms[#PLATFORM#].offlineMultiplayer',\n 'onlineMultiplayer' : 'proposal.plannedPlatforms[#PLATFORM#].onlineMultiplayer',\n 'dlcIntension' : 'proposal.plannedPlatforms[#PLATFORM#].dlcIntension',\n 'plannedPeripherals' : 'proposal.plannedPlatforms[#PLATFORM#].plannedPeripherals',\n 'plannedFeatures' : 'proposal.plannedPlatforms[#PLATFORM#].plannedFeatures',\n 'plannedDistributionMedia': 'proposal.plannedPlatforms[#PLATFORM#].plannedDistributionMedia'\n };\n angular.extend(this, fields);\n\n //replace #PLATFORM# with platform name \n //i.e: PS4, PS4\n for (var field in this) {\n this[field] = this[field].replace('#PLATFORM#', platformName); \n }\n }", "function setAddressRelatedFieldValues(record){\r\n record.setFieldValue('billaddresslist', record.getFieldValue('billaddresslist') || '');\r\n record.setFieldValue('billaddress', record.getFieldValue('billaddress') || '');\r\n record.setFieldValue('shipaddresslist', record.getFieldValue('shipaddresslist') || '');\r\n record.setFieldValue('shipaddress', record.getFieldValue('shipaddress') || '');\r\n}", "function populateDataFields() {}", "addFieldsToParam(searchParam) {\n let allFields = this.fields.split(',');\n allFields.push('Id');\n allFields.push('Name');\n let cleanFields = this.dedupeArray(allFields).join(',');\n searchParam.fieldsToQuery = cleanFields;\n }", "_setRequiredFields() {\n const that = this;\n\n if (!that.requiredFields || !that.requiredFields.length) {\n return;\n }\n\n const currentValue = that.value;\n let reqGroup = [];\n\n for (let i = 0; i < that.requiredFields.length; i++) {\n const reqField = that.requiredFields[i],\n field = that.fields.find(field => field.dataField === reqField);\n\n if (field) {\n let valueRecords = [];\n\n if (currentValue) {\n let i = 0;\n\n //Doing a lookup on the value for records that contain 'requiredFields'\n //Modifies the value dynamically\n while (i < currentValue.length) {\n const val = currentValue[i];\n\n if (Array.isArray(val)) {\n let r = 0;\n\n while (r < val.length) {\n let record = val[r];\n\n if (record && record[0] === field.dataField) {\n valueRecords.push(record);\n val.splice(r > 0 ? r - 1 : r, 2);\n continue;\n }\n\n r++;\n }\n }\n\n if (!val.length) {\n currentValue.splice(i, 2);\n continue;\n }\n\n i++;\n }\n }\n\n //Check if group records exist inside value\n if (valueRecords) {\n for (let r = 0; r < valueRecords.length; r++) {\n reqGroup.push(valueRecords[r]);\n reqGroup.push('and');\n }\n }\n else {\n //If no records create a placeholder\n reqGroup.push([reqField]);\n reqGroup.push('and');\n }\n }\n }\n\n //Remove the lastly added 'and' condition\n if (typeof reqGroup[reqGroup.length - 1] === 'string') {\n reqGroup.pop();\n }\n\n //Add the Required Fields on Top of the value\n that.value.unshift(reqGroup, 'and')\n }", "function makeMultipleFilters(field, data) {\n var filterObject;\n filterObject = [];\n lodash.collections.forEach(data, function (value) {\n filterObject.push(makeSingleFilter(field, value));\n });\n return filterObject;\n}", "function setUpFields(fields){\n\n\t_.forEach(fields, function(value, key){\n\t\tif(value.type == 'date'){\n\t\t\t$scope.data.thisContent[value.field || value.key] = {\n\t\t\t\tstartDate: $scope.data.thisContent[value.field || value.key] || null,\n\t\t\t\tendDate: null //have to stub but don't use all the time\n\t\t\t}\n\t\t}\n\t})\n\n\treturn fields;\n\n}", "function mapValueFieldNames(dataValues, fields, Model) {\n const values = {};\n\n for (const attr of fields) {\n if (dataValues[attr] !== undefined && !Model._isVirtualAttribute(attr)) {\n // Field name mapping\n if (Model.rawAttributes[attr] && Model.rawAttributes[attr].field && Model.rawAttributes[attr].field !== attr) {\n values[Model.rawAttributes[attr].field] = dataValues[attr];\n } else {\n values[attr] = dataValues[attr];\n }\n }\n }\n\n return values;\n}", "function splitFieldIntoAry() {\n var nullRefAry = [];\n var splitField = entityObj.splitField;\n var newRecrdObj = {};\n var recrdsObj = entityObj.curRcrds;\n\n for (var key in recrdsObj) { newRecrdObj[key] = splitFields(key); }\n\n if (nullRefAry.length > 0) { addNullReqRefs(); }\n\n entityObj.curRcrds = newRecrdObj;\n /**\n * Splits a specified field of each record into an array on commas.\n * @param {str} key Top key for an array of records sharing unqKey field\n */\n function splitFields(key) { // console.log(\"splitFields called. recrdsObj[key] = %O\", recrdsObj[key])\n var newRecrds = recrdsObj[key].map(function(recrd) {\n recrd[splitField] = recrd[splitField] === null ? procNullField(recrd, key) : splitAndTrimField(recrd);\n return recrd;\n });\n return newRecrds;\n }\n function splitAndTrimField(recrd) { //console.log(\"splitAndTrimField called. recrd = %O\", recrd);\n var collectionAry = recrd[splitField].split(\",\");\n var trimmedAry = collectionAry.map(function(valueStr){\n return valueStr.trim();\n });\n return trimmedAry;\n }\n function procNullField(recrd, key) {\n if (entityObj.reqRef !== undefined) {\n nullRefAry.push(recrd);\n return null;\n } else {\n return [];\n }\n }\n function addNullReqRefs() { //console.log(\"addNullReqRefs. nullRefAry = %O\", nullRefAry);\n nullRefAry.forEach(function(rcrd) { delete newRecrdObj[rcrd.citId] });\n entityObj.validationResults.rcrdsWithNullReqFields = {\n recordCnt: nullRefAry.length,\n recrds: nullRefAry,\n unqKey: entityObj.reqRef\n }\n }\n }", "get fields() {\n const allFields = [\n fields.projectLocation,\n fields.projectLocationDescription,\n fields.projectPostcode,\n ];\n return conditionalFields(\n allFields,\n has('projectCountry')(data) ? allFields : []\n );\n }", "extractFields(fields) {\n\t\treturn fields.map(field => (\n\t\t\t<div key={`div_${field.id}`} id={field.id}>\n\t\t\t\t<Field\n\t\t\t\t\tkey={field.id}\n\t\t\t\t\tvalue={field}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t));\n\t}", "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': ['[email protected]'],\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}", "_mapFieldsToMenu() {\n const that = this;\n\n if (!that.fields && !that._valueFields) {\n return;\n }\n\n that._fields = (that.fields || that._valueFields).concat(that._manuallyAddedFields).map(field => {\n return { label: field.label, value: field.dataField, dataType: field.dataType, filterOperations: field.filterOperations, lookup: field.lookup };\n });\n }", "function processSubProperties(boundFieldName) {\n var array = [],\n subPropertyName,\n parts = boundFieldName.split(\"/\"),\n dataItemKey = parts[1];\n\n $.each(cache[boundFieldName], function (index, $elements) {\n $.each($elements.data(\"repeater\"), function (dataItemId, arrayOfInputDefs) {\n var obj = {};\n\n $.each(arrayOfInputDefs, function () {\n var inputDef = this;\n var $elementDataBind = inputDef[\"el\"];\n subPropertyName = inputDef[\"prop\"];\n\n if (subPropertyName == dataItemKey) {\n // First checks if is selected before adding it.\n if (!($elementDataBind.is(\":checked\") || $elementDataBind.is(\":selected\"))) {\n // Don't save anything.\n obj = null;\n return false;\n }\n }\n\n if ($elementDataBind.is(\"input:radio\") || $elementDataBind.is(\"input:checkbox\")) {\n if ($elementDataBind.is(\":checked\"))\n createInnerObject(subPropertyName, $elementDataBind.val(), obj);\n }\n else\n createInnerObject(subPropertyName, $elementDataBind.val(), obj);\n });\n\n // Finally, add the key property\n if (obj) {\n createInnerObject(dataItemKey, dataItemId, obj);\n array.push(obj);\n }\n });\n });\n return array;\n }", "function normalizeDataItem(data,fieldName)\n{\n var returnArray = []; // empty array returned for no field or null value\n\n // make sure the target field exists and is non-null\n\n if(data.hasOwnProperty(fieldName) && data[fieldName] !== null) {\n\n\t// check to see if it is an object (multiple values)\n\t// (normally you'd need to check for null, because null also has typeof 'object'\n\t// but we already checked for null above)\n\t\n\tif(typeof data[fieldName] === 'object') {\n\t for(var prop in data[fieldName]) {\n\t\tif(data[fieldName].hasOwnProperty(prop)) {\n\t\t returnArray.push(data[fieldName][prop]);\n\t\t}\n\t }\n\t} else {\n\t returnArray.push(data[fieldName]); \t // single value\n\t}\n }\n return(returnArray);\n}", "list(request, response, next) {\n SiteModel.find(\n (error, siteDocs) => {\n const sites = siteDocs.reduce((previous, site) => {\n previous[site.title] = site.data;\n return previous;\n }, {});\n response.json({sites});\n }\n );\n }", "function populatePeople(names){\n return names.map(named => {\n name = named.split(\" \");\n const [firstName,lastName]=name \n return {\n firstName,\n lastName,\n }\n })\n }", "function generateNamedFieldExtractors(input) {\n var names = input.filter(function(matcher, index, array) {\n // has a name?\n return matcher.name;\n });\n // has duplicates?\n names.forEach(function(matcher, index, array) {\n var isDuplicate = array.slice(0, index).some(function(previousMatcher) {\n return previousMatcher.name == matcher.name;\n });\n if (isDuplicate) {\n throw new Error(\"duplicate named field '\" + matcher.name + \"'\");\n }\n });\n return names;\n}", "massageData(data) {\n // Grab the unique list of counties from the dataset\n this.listOfCounties = [...new Set(data.map((x) => x.res_geo_short))].sort();\n\n // Group data by residential county\n const groupedData = this.groupBy(data, (item) => item.res_geo_short);\n\n // Convert necessary string to ints and add aggregate fields\n groupedData.forEach((county) => this.convertStrings(county));\n return groupedData;\n }", "function makeFields$static(config/*:LinkListDropAreaWithSuggestions*/)/*:Array*/ {\n var result/*:Array*/ = [];\n if (AS3.getBindable(config,\"defaultFields\")) {\n result = result.concat(AS3.getBindable(config,\"defaultFields\"));\n }\n if (AS3.getBindable(config,\"extraFields\")) {\n result = result.concat(AS3.getBindable(config,\"extraFields\"));\n }\n return result;\n }", "function reduceToObjects(cols,data) {\n\t\tvar fieldNameMap = $.map(cols, function(col) { return col.fieldName; });\n\t\tvar dataToReturn = $.map(data, function(d) {\n\t\t\t\t\t\t\t\t\t\treturn d.reduce(function(memo, value, idx) {\n\t\t\t\t\t\t\t\t\t\t\tmemo[fieldNameMap[idx]] = value.value; return memo;\n\t\t\t\t\t\t\t\t\t\t}, {});\n });\n //console.log(fieldNameMap);\n //console.log(dataToReturn);\n\t\treturn dataToReturn;\n\t}", "function getCustomValues(siteData) {\n try {\n var customValues = {\n host: window.location.host.toLowerCase(),\n currentFullURL: window.location.href.toLowerCase(),\n currentURL: window.location.protocol.toLowerCase() + \"//\" + window.location.host.toLowerCase() + window.location.pathname.toLowerCase(),\n referringDomain: document.referrer.toLowerCase(),\n pageName: \"\",\n pageNameBreadCrumbs: \"\",\n pageTitle: \"\",\n localPageTitle: \"\",\n parentSection: \"\",\n sectionLevel1: \"\",\n sectionLevel2: \"\",\n sectionLevel3: \"\",\n sectionLevel4: \"\",\n sectionLevel5: \"\",\n country: siteData.siteName + \":\" + siteData.countryCode,\n language: siteData.languageCode,\n locale: siteData.locale,\n currencyCode: siteData.currencyCode,\n distributorId: siteData.dsId,\n distributorTeam: siteData.dsTeam,\n countryOfProcessing: siteData.countryOfProcessing,\n dsIsBizworksSubscriber: siteData.dsIsBizworksSubscriber,\n dsIsDwsOwner: siteData.dsIsDwsOwner,\n bizworksPageTitle: s_omntr.Util.getQueryParam('ReportType').toLowerCase(),\n titleQueryStringExists: s_omntr.Util.getQueryParam('Title').toLowerCase(),\n loggedStatus: \"\",\n WaitingRoom: siteData.WaitingRoom,\n events: siteData.events,\n hierarchy1: \"\",\n clientIpAddress: \"\",\n purchaseId: \"\",\n productDetail: \"\",\n productName: \"\",\n products: \"\"\n };\n\n var path = window.location.pathname.toLowerCase();\n var arrPath = path.split('/');\n var subSections = [];\n\n // Parsing the current URL\n for (var i = 1; i < arrPath.length; i++) {\n if (i + 1 == arrPath.length && arrPath[i] != \"\") {\n if (customValues.titleQueryStringExists != \"\") {\n customValues.pageTitle = customValues.titleQueryStringExists;\n } else if (customValues.bizworksPageTitle != \"\") {\n customValues.pageTitle = arrPath[i].substring(0, arrPath[i].indexOf('.')) + \":\" + customValues.bizworksPageTitle;\n } else if (arrPath[i].substring(0, arrPath[i].indexOf('.')) == \"\") {\n customValues.pageTitle = arrPath[i];\n } else {\n customValues.pageTitle = arrPath[i].substring(0, arrPath[i].indexOf('.'));\n }\n } else {\n if (arrPath[i] != \"default\" && arrPath[i] != \"\") {\n subSections.push(arrPath[i]);\n }\n }\n }\n\n function pageTitleExists(previousPageName) {\n var newPageName = previousPageName;\n if (customValues.pageTitle != \"\") {\n newPageName = newPageName + \":\" + customValues.pageTitle;\n }\n\n return newPageName;\n }\n\n // Sets the values for the Omniture pageName variable and also for the section and subsections variables ex: myhl:us:en:ordering:shoppingCart\n function formatPageName() {\n customValues.pageName = customValues.sectionLevel1;\n customValues.hierarchy1 = customValues.pageName;\n if (subSections.length > 0) {\n customValues.parentSection = customValues.parentSection + \":\" + subSections[0];\n customValues.sectionLevel1 = customValues.sectionLevel1 + \":\" + subSections[0];\n\n for (var j = 0; j < subSections.length; j++) {\n customValues.pageName = customValues.pageName + \":\" + subSections[j];\n customValues.hierarchy1 = customValues.hierarchy1 + \"|\" + customValues.pageName;\n if (j + 1 == subSections.length) {\n customValues.pageName = pageTitleExists(customValues.pageName);\n customValues.hierarchy1 = customValues.hierarchy1 + \"|\" + customValues.pageName;\n if (j >= 1) {\n customValues.sectionLevel2 = customValues.sectionLevel1 + \":\" + subSections[1];\n if (siteData.bcLevel2 != \"\") {\n customValues.pageNameBreadCrumbs = customValues.pageNameBreadCrumbs + \":\" + siteData.bcLevel2;\n }\n if (j >= 2) {\n if (siteData.bcLevel3 != \"\") {\n customValues.pageNameBreadCrumbs = customValues.pageNameBreadCrumbs + \":\" + siteData.bcLevel3;\n }\n customValues.sectionLevel3 = customValues.sectionLevel2 + \":\" + subSections[2];\n if (j >= 3) {\n customValues.sectionLevel4 = customValues.sectionLevel3 + \":\" + subSections[3];\n if (j >= 4) {\n customValues.sectionLevel5 = customValues.sectionLevel4 + \":\" + subSections[4];\n }\n }\n }\n }\n }\n }\n } else {\n customValues.pageName = pageTitleExists(customValues.pageName);\n customValues.hierarchy1 = customValues.pageName;\n }\n }\n\n // Concatenate the values from the Parsed URL\n customValues.localPageTitle = s_omntr.normalizeText(siteData.localPageTitle);\n customValues.parentSection = siteData.fullSiteName;\n customValues.sectionLevel1 = siteData.siteName + \":\" + siteData.countryCode + \":\" + siteData.languageCode;\n if (siteData.bcLevel1 != \"\") {\n customValues.pageNameBreadCrumbs = customValues.sectionLevel1 + \":\" + siteData.bcLevel1;\n }\n\n if (siteData.isLoggedIn == false) {\n customValues.loggedStatus = \"not logged in\";\n customValues.parentSection = customValues.parentSection + \":\" + \"distributor login\";\n customValues.sectionLevel1 = customValues.sectionLevel1 + \":\" + \"distributor login\";\n } else {\n customValues.loggedStatus = \"logged in\";\n }\n\n formatPageName();\n\n // Products Detail\n if (siteData.productDetail != null) {\n var skus = \"\";\n for (var y = 0; y < siteData.productDetail.Skus.length; y++) {\n skus = skus + siteData.productDetail.Skus[y];\n }\n var product = s_omntr.normalizeText(siteData.productDetail.Name);\n var category = siteData.productDetail.Category;\n\n customValues.productName = product;\n customValues.productDetail = \";\" + product + \" (\" + skus + \");;;;evar18=\" + category.toString();\n }\n\n // Shopping Cart \n if (siteData.products != null) {\n customValues.purchaseId = siteData.orderId;\n var productsArr = [];\n var shippingCost = 0;\n var tax = 0;\n $(siteData.products).each(function () {\n shippingCost = parseInt(this.Freight);\n tax = parseInt(this.ItemTax);\n var description = s_omntr.normalizeText(this.Description) + \" (\" + this.Sku + \")\";\n description = description.replace(/,/g, \" \");\n var quantity = this.Quantity;\n var productTotalCost = this.DiscountedPrice;\n var product = \";\" + description + \";\" + quantity.toString() + \";\" + productTotalCost.toString();\n productsArr.push(product);\n });\n\n for (var x = 0; x < productsArr.length; x++) {\n if (x + 1 == productsArr.length) {\n customValues.products = customValues.products + productsArr[x];\n } else {\n customValues.products = customValues.products + productsArr[x] + \",\";\n }\n }\n }\n\n\n return customValues;\n } catch (err) {\n errorHandling(err);\n }\n }", "function Generate_DictConcatFieldInput() {\n Intern_DictConcatInput = {};\n //var firstRun = true;\n $.each(Intern_ArrayOfValues, function (index, value) {\n if (index === 0) {\n $.each(value, function (index1, value1) {\n Intern_DictConcatInput[index1] = value1 + Intern_Delimiter;\n });\n }\n else {\n $.each(value, function (index1, value1) {\n Intern_DictConcatInput[index1] = Intern_DictConcatInput[index1] + value1 + Intern_Delimiter;\n });\n }\n });\n }", "function preprocess(dataset_list) {\n var dataset_dict = {};\n var organism_list = [];\n var alphabet_list = [];\n var dataset_list_count = dataset_list.length;\n for (var i = 0; i < dataset_list_count; i++) {\n var entry = dataset_list[i];\n var data_type = entry[0];\n var alphabet = entry[1];\n var file_name = entry[2];\n var organism_name = entry[3];\n var description = entry[4];\n if (!(organism_name in dataset_dict)) {\n dataset_dict[organism_name] = {};\n organism_list.push(organism_name);\n //console.log(organism_name);\n }\n if (!(alphabet in dataset_dict[organism_name])) {\n dataset_dict[organism_name][alphabet] = [];\n }\n if ($.inArray(alphabet, alphabet_list) < 0) {\n alphabet_list.push(alphabet);\n }\n dataset_dict[organism_name][alphabet].push([file_name, data_type, description]); // add info\n }\n return [dataset_dict, organism_list, alphabet_list];\n}", "function format_users() {\n\tvar users_fields = [];\n\tusers_data.forEach(function (user) {\n\t\tvar fields = [];\n\t\tfields.push(user.email);\n\t\tfields.push(user.user_name);\n\t\tfields.push(user.name.first);\n\t\tfields.push(user.name.last);\n\t\tfields.push(\"u of t\");\t\t//university\n\t\tfields.push(\"CS\");\t\t// departmnet\n\t\tfields.push(user.password);\n\t\tfields.push(user.phone);\n\n \t// console.log(fields);\n\t\tusers_fields.push(fields);\n\t});\n\n\treturn users_fields;\n}", "function mergeDuplicateOrganismData(allDisplayData) {\n const mergedDuplicates = [];\n for(const organismData of allDisplayData) {\n const existingData = mergedDuplicates\n .find((element) => element.name === organismData.name);\n\n /**\n * Add organismData's sightings to the existing sightings of that\n * organism in mergedDuplicates\n */\n if (existingData != undefined) {\n existingData.sightings.push(...organismData.sightings);\n } else {\n /**\n * Not a duplicate organism; add all of its data to the\n * mergedDuplicates array\n */\n mergedDuplicates.push(organismData);\n }\n }\n\n return mergedDuplicates;\n }", "static all () {\n return [{\n ids: ['CITY OF TAMPA'],\n name: 'City of Tampa',\n // address: '',\n phone: '8132748811',\n // fax: '',\n // email: '',\n website: 'https://www.tampagov.net/solid-waste/programs'\n },\n {\n ids: ['TEMPLE TERRACE'],\n name: 'City of Temple Terrace',\n // address: '',\n phone: '8135066570',\n // fax: '',\n email: '[email protected]',\n website: 'http://templeterrace.com/188/Sanitation/'\n },\n {\n ids: ['CITY OF PLANT CITY'],\n name: 'City of Plant City',\n address: '1802 Spooner Drive, Plant City, FL 33563',\n phone: '8137579208',\n fax: '8137579049',\n email: '[email protected]',\n website: 'https://www.plantcitygov.com/64/Solid-Waste'\n }]\n }", "ensureFields() {\n if (this.options.fields === undefined) {\n this.options.fields = this.config.fieldNames.reduce((fields, field) => {\n fields[field] = field;\n return fields;\n }, {});\n }\n }", "function groupValues(values) {\n var groups = [], currentGroup;\n for (var i = 0, len = values.length; i < len; i++) {\n var value = values[i];\n if (!currentGroup || currentGroup.identity !== value.identity) {\n currentGroup = {\n values: []\n };\n if (value.identity) {\n currentGroup.identity = value.identity;\n var source = value.source;\n // allow null, which will be formatted as (Blank).\n if (source.groupName !== undefined) {\n currentGroup.name = source.groupName;\n }\n else if (source.displayName) {\n currentGroup.name = source.displayName;\n }\n }\n groups.push(currentGroup);\n }\n currentGroup.values.push(value);\n }\n return groups;\n }", "function BundleNames() {\n var list = $(\".guest-list\");\n if (list.length <= 0) {return false;}\n\n var guests = \"\";\n var names = $(\".guest-list .name\");\n for (var i = 0; i < names.length; i++) {\n var first = $(names[i]).find(\".first\").val();\n var last = $(names[i]).find(\".last\").val();\n if(i != names.length-1)\n guests += first + \" \" + last + \",\";\n else\n guests += first + \" \" + last;\n }\n $(\"#guestlist-field\").val(guests);\n }", "function updateHeaderFields() {\n data.fields.forEach(field => {\n let id = GatherComponent.idByGatherTeamField(gatherMakers, gatherMakers.team, field);\n field.attributes.name = elementById(id).value;\n });\n}", "distinct(...fields) {\n if (fields[0] === false) {\n this.setOption('distinct', false);\n } else {\n this.setOption('distinct', true);\n }\n\n return this.addFields(fields);\n }", "parseTextFilter() {\n const raw = this.filterText;\n\n const result = new Map();\n if (!raw.length) return result;\n\n let matches = raw.match(pairSplitRE);\n if (matches === null && raw.length) matches = [`name=${raw}`];\n\n return matches.reduce((result, pair) => {\n const [field, val] = pair.split(\"=\");\n const cleanField = field.replace(scrubFieldRE, \"\");\n\n if (validTextFields.has(cleanField)) {\n const cleanVal = val.replace(scrubQuotesRE, \"\").replace(scrubSpaceRE, \" \");\n result.set(cleanField, cleanVal);\n }\n\n return result;\n }, result);\n }", "function mergeHelper(objValue, srcValue) {\n\n //combine any dropdowns with the same label\n _.forEach(objValue, function (val) {\n var match;\n\n if (match = _.find(srcValue, {label: val.label})) {\n val.items = match.items = _.unionWith(val.items, match.items, function (obj1, obj2) {\n if (obj1.label == obj2.label) {\n return true;\n }\n });\n val.id = match.id = val.id; //fix not matched IDs\n }\n });\n\n\n if (_.isArray(objValue)) {\n //concat but prevent duplicate tab items (like Account)\n return _.unionWith(objValue, srcValue, _.isEqual);\n }\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 separateDuplicatedDataTypes() {\n var selectDataTypes = $scope.dataTypes.sourceCollection;\n var i,j;\n var financeCubeDataTypes = $scope.financeCube.dataTypes;\n var ifHavedByFinanceCube = false;\n var lenght = 0;\n for (i = 0; i < selectDataTypes.length; i++) {\n for (j = 0; j < financeCubeDataTypes.length; j++) {\n\n if (financeCubeDataTypes[j].dataTypeId === selectDataTypes[i].dataTypeId) {\n ifHavedByFinanceCube = true;\n }\n\n }\n if (ifHavedByFinanceCube == false) {\n $scope.separate[lenght] = selectDataTypes[i];\n lenght++;\n }\n ifHavedByFinanceCube = false;\n }\n }", "async createFieldsMapping(mapping) {\n const dopplerFields = await this.getFieldsAsync();\n\n return mapping.map(m => {\n const dopplerField = dopplerFields.find(df => df.name === m.doppler);\n if (!dopplerField)\n throw new Error(\n `Error when mapping Shopify field \"${m.shopify}\": Doppler field \"${\n m.doppler\n }\" does not exist.`\n );\n\n const shopifyField = shopify.customerFields.find(\n cf => cf.path === m.shopify\n );\n if (!shopifyField)\n throw new Error(\n `Error when mapping Shopify field \"${\n m.shopify\n }\": The field does not exist.`\n );\n\n if (dopplerField.type !== shopifyField.type)\n throw new Error(\n `Error when mapping Shopify field \"${\n shopifyField.name\n }\" with Doppler field \"${dopplerField.name}\": different types.`\n );\n\n return { ...dopplerField, value: shopifyField.path };\n });\n }", "function setCommonFields(solrRecord, vprRecord) {\n\tsetStringFromSimple(solrRecord, 'uid', vprRecord, 'uid');\n\tsetStringFromSimple(solrRecord, 'pid', vprRecord, 'pid');\n\tsetStringFromSimple(solrRecord, 'facility_code', vprRecord, 'facilityCode');\n\tsetStringFromSimple(solrRecord, 'facility_name', vprRecord, 'facilityName');\n\tsetStringFromSimple(solrRecord, 'kind', vprRecord, 'kind');\n\tsetStringFromSimple(solrRecord, 'summary', vprRecord, 'summary');\n setStringFromSimple(solrRecord, 'removed', vprRecord, 'removed');\n\tsetStringArrayFromObjectArrayField(solrRecord, 'codes_code', vprRecord, 'codes', 'code');\n\tsetStringArrayFromObjectArrayField(solrRecord, 'codes_system', vprRecord, 'codes', 'system');\n\tsetStringArrayFromObjectArrayField(solrRecord, 'codes_display', vprRecord, 'codes', 'display');\n\tsetDateTimes(solrRecord, vprRecord);\n}", "function mergeMetaFields(matched) {\r\n return matched.reduce((meta, record) => assign(meta, record.meta), {});\r\n}", "function calcMetaDataField_flatten(data,params,field)\n{\n var retArray = [];\n\n if(!field.hasOwnProperty('target')) {\n\tconsole.log('flatten in field ' + field.name + ' missing target (empty array returned)');\n } else {\n\n\t// if target exists, it will be an array of targets (at least one)\n\tfor(var i=0; i < field.target.length; i++) {\n\n\t let item = normalizeDataItem(data,field.target[i]); \t// item is normalized into array of values\n\t // for the given field (may be zero length)\n\t if(item.length != 0) {\n\t\tfor(var j=0; j < item.length; j++) {\n\n\t\t // flatten is often used for higher-level metadata, where the fields\n\t\t // of lower-levels are combined into an array by this machinery.\n\t\t // In this case, we can arrays of arrays for things like events,\n\t\t // or arrays of arrays of objects for things like imagemap points.\n\n\t\t if(Array.isArray(item[j])) { // flatten FIRST array level if it exists\n\t\t\tfor(var k=0; k < item[j].length; k++) {\n\t\t\t retArray.push(item[j][k]);\n\t\t\t}\n\t\t } else {\n\t\t\tretArray.push(item[j]); // otherwise, just use the current item\n\t\t }\n\t\t}\n\t }\n\t}\n }\n \n return(retArray);\n}", "function combineColVals(cols=[], vals=[], method, split=\", \", sanitise=true){\n // Creating an empty string, upon which each col/val pair will be added\n var colVals = \"\";\n\n // Looping through all the columns\n for(var i=0; i<cols.length; i++){\n // Creating an empty value variable, to store the sanitised values \n var value;\n\n // If this is a SET or INSERT method, then there will be user generated\n // data that needs to be sanitised\n if(method == \"set\" || method == \"insert\"){\n // Checking if this data is to be sanitised or not (i.e. when creating a\n // new user, none of the data should be sanitised, as none of it is\n // user generated\n if(sanitise){\n if(cols[i] == \"google_access_token\" || cols[i] == \"access_levels\"){\n // Neither of these columns should be sanitised, as they contain objects\n // that are generated server side.\n value = vals[i];\n } else if(cols[i] == \"custom_css\"){\n // Sanitising this data, but setting CSS characters such as {}\n // to be allowed\n value = validation.sanitise(vals[i], true);\n } else if(cols[i] == \"read_origins\" || cols[i] == \"update_origins\"){\n // Sanitising this data, but allowing HTML characters such as /\n // = and \\ to be included (as these will contain URLS)\n value = validation.sanitise(vals[i], false, true);\n } else {\n // Sanitising this data, replacing special characters\n // with their entity values i.e. & becomes &amp;\n value = validation.sanitise(vals[i]);\n }\n } else {\n // Since this data does not need to be sanitised, setting it to \n // its initial value\n value = vals[i];\n }\n\n // Checking if this column needs to be encrypted\n if(encryptedColumns.indexOf(cols[i]) > -1 && value != null){\n // Wrapping the escaped and sanitised value in an AES_ENCRYPT method, \n // passing it to the key that will be used to encrypt/decrypt it\n value = \"AES_ENCRYPT(\" + dbconn.escape(value) + \", \" + dbconn.escape(process.env.DATABASE_KEY) + \")\";\n } else {\n // Since this is not an encrypted column, just escaping the sanitised data\n value = dbconn.escape(value);\n }\n }\n \n // Determining how to join the column/values based on the SQL method that \n // will be used i.e if the col was \"user_id\" and the value was \"k123456\"\n if(method == \"set\"){\n // i.e. user_id=k123456\n colVals += cols[i] + \"=\" + value;\n } else if(method == \"insert\"){\n // i.e. k123456\n colVals += value;\n } else if(method == \"where\"){\n // Creating a temporary variable to store the column name, as it may \n // need to be wrapped in a decryption method first\n var col = cols[i];\n\n // Checking if this column is encrypted\n if(encryptedColumns.indexOf(cols[i]) > -1){\n // Wrapping the original column name in an AES_DECRYPT method, passing\n // in the database key that was used to encrypt the data\n // i.e. AES_DECRYPT(user_id, *****)\n col = \"AES_DECRYPT(\" + cols[i] + \", \" + dbconn.escape(process.env.DATABASE_KEY) + \")\";\n }\n // i.e. user_id=k123456\n colVals += col + \"=\" + dbconn.escape(vals[i]);\n }\n \n // While the current column is not the last column, adding\n // the appropriate \"split\" value i.e. for WHERE the split \n // is usually \"AND\", while for INSERT it is always \", \"\n if(i < cols.length - 1){\n colVals += split;\n }\n }\n\n // Returning the joined column/values string, with all encrypted columns\n // set to be decrypted (for WHERE statements), all values sanitised and\n // escaped, and all encrypted columns data set to be encrypted (for\n // INSERT and UPDATE statements)\n return colVals;\n}", "function aggsFromFields() {\n // Remove current query from queries list (do not react to self)\n function withoutOwnQueries() {\n const q = new Map(queries);\n q.delete(id);\n return q;\n }\n // Transform a single field to agg query\n function aggFromField(field) {\n const t = { field, order: { _count: \"desc\" }, size };\n if (filterValue) {\n t.include = !filterValueModifier\n ? `.*${filterValue}.*`\n : filterValueModifier(filterValue);\n }\n return { [field]: { terms: t } };\n }\n // Actually build the query from fields\n let result = {};\n fields.forEach((f) => {\n result = { ...result, ...aggFromField(f) };\n });\n return { query: queryFrom(withoutOwnQueries()), size: 0, aggs: result };\n }", "function buildValueArray(name, mod, map, fn) {\n var field = name, all = [], setMap;\n if (!loc[field]) {\n field += 's';\n }\n if (!map) {\n map = {};\n setMap = true;\n }\n forAllAlternates(field, function(alt, j, i) {\n var idx = j * mod + i, val;\n val = fn ? fn(i) : i;\n map[alt] = val;\n map[alt.toLowerCase()] = val;\n all[idx] = alt;\n });\n loc[field] = all;\n if (setMap) {\n loc[name + 'Map'] = map;\n }\n }", "cloneData(data) {\n const results = [];\n for (const item of data) {\n const copy = {\n name: item['name']\n };\n if (item['value'] !== undefined) {\n copy['value'] = item['value'];\n }\n if (item['series'] !== undefined) {\n copy['series'] = [];\n for (const seriesItem of item['series']) {\n const seriesItemCopy = Object.assign({}, seriesItem);\n copy['series'].push(seriesItemCopy);\n }\n }\n if (item['extra'] !== undefined) {\n copy['extra'] = JSON.parse(JSON.stringify(item['extra']));\n }\n results.push(copy);\n }\n return results;\n }", "cloneData(data) {\n const results = [];\n for (const item of data) {\n const copy = {\n name: item['name']\n };\n if (item['value'] !== undefined) {\n copy['value'] = item['value'];\n }\n if (item['series'] !== undefined) {\n copy['series'] = [];\n for (const seriesItem of item['series']) {\n const seriesItemCopy = Object.assign({}, seriesItem);\n copy['series'].push(seriesItemCopy);\n }\n }\n if (item['extra'] !== undefined) {\n copy['extra'] = JSON.parse(JSON.stringify(item['extra']));\n }\n results.push(copy);\n }\n return results;\n }", "_mapFieldsToMenu() {\n const that = this;\n\n if (!that.fields && !that._valueFields) {\n return;\n }\n\n that._fields = (that.fields || that._valueFields).map(field => {\n let menuField = {};\n\n menuField.label = field.label;\n menuField.value = field.dataField;\n menuField.dataType = field.dataType;\n\n return menuField;\n });\n }", "function createDynamicFields(name) {\n\tvar fields = '';\n\n\tfor (var i = 1; i <= g_maxFormFields; i++) {\n\t\tfields += '<div class=\"floatElement select select_' + i + '\"><select size=\"1\" id=\"' + name + 'Text' + i + '\">' + createOptions(name) + '</select></div>';\n\n\t\tif (i < g_maxFormFields) {\n\t\t\tfields += '<div class=\"floatElement table table_' + i + '\"><table class=\"inline\" id=\"' + name + 'RadioTable' + i + '\"><tr><td><input type=\"radio\" name=\"' + name + 'Radio' + i + '\" value=\"1\" onclick=\"handleRadio(\\'' + name + '\\', ' + i + ')\"/> und</td></tr><tr><td><input type=\"radio\" name=\"' + name + 'Radio' + i + '\" value=\"2\" onclick=\"handleRadio(\\'' + name + '\\', ' + i + ')\"/> bis</td></tr></table></div>';\n\t\t}\n\t}\n\n\treturn fields;\n}", "function filterDuplicates(integrations) {\n\t const integrationsByName = {};\n\n\t integrations.forEach(currentInstance => {\n\t const { name } = currentInstance;\n\n\t const existingInstance = integrationsByName[name];\n\n\t // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n\t // default instance to overwrite an existing user instance\n\t if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n\t return;\n\t }\n\n\t integrationsByName[name] = currentInstance;\n\t });\n\n\t return Object.values(integrationsByName);\n\t}", "assignFields(scope) {\n const fields = Object\n .keys(scope.source)\n .filter((field) => this.assignFilter(scope.source, field, scope));\n return Promise.all(\n fields.map((fieldName) => this.assignField(fieldName, scope)),\n );\n }", "function generateSchema(fields) {\r\n var schema = [];\r\n\r\n for (var i in fields) {\r\n var f = {};\r\n f['s0'] = fields[i].name;\r\n f['s1'] = fields[i].dataTypeID;\r\n f['s2'] = 'a' + i;\r\n\r\n // add it to the fields\r\n schema.push(f);\r\n }\r\n\r\n return schema;\r\n}", "configureFields() {\n let fields = {}\n\n for(let fieldName in this.props.schema.fields) {\n let field = this.props.schema.fields[fieldName]\n\n fields[fieldName] = {}\n fields[fieldName].value = undefined\n fields[fieldName].isValid = false\n fields[fieldName].required = false\n\n if(\n field.type === 'select'\n || field.type === 'checkbox'\n ) {\n fields[fieldName].isValid = true\n }\n }\n\n if(this.props.schema.required) {\n this.props.schema.required.forEach(fieldName => {\n fields[fieldName].required = true\n })\n }\n\n return fields\n }", "function removeDuplicatedFields() {\n var duplicatedFields = $(\".requestField input\").filter(function (index, elem) {\n return $(\".responseField #\" + elem.id).length > 0;\n });\n\n $(duplicatedFields).each(function (index, duplicatedField) {\n $(\".responseField #\" + duplicatedField.id).closest('.responseField ').remove();\n });\n\n refreshInputElements();\n}", "function removeDuplicatedFields() {\n var duplicatedFields = $(\".requestField input\").filter(function (index, elem) {\n return $(\".responseField #\" + elem.id).length > 0;\n });\n\n $(duplicatedFields).each(function (index, duplicatedField) {\n $(\".responseField #\" + duplicatedField.id).closest('.responseField ').remove();\n });\n\n refreshInputElements();\n}", "splitFilters (activeFilters) {\n const filters = activeFilters.map((f)=> { \n\t\t\t\t\t\n let filterString = `${f.filterName}:${f.value.trim()}`;\n return filterString\n })\n\n \n\n return filters.join().trim();\n }", "function LaserficheFields()\n{\n var self = this;\n function LoadData() {\n if (window.parent !== window && window.parent.webAccessApi !== undefined) {\n var metadata = window.parent.webAccessApi.getFields();\n self.fieldData = metadata.fields.templateFields.concat(metadata.fields.supplementalFields);\n return self.fieldData;\n }\n else {\n return undefined;\n }\n }\n function GetField(fieldName) {\n var self = this;\n var fieldData = self.FieldData;\n return $(fieldData).filter(function(i, e) { return e.name === fieldName; });\n }\n function FillFields(fieldName, suppress) {\n var self = this;\n var fields;\n var i;\n var j;\n var selector;\n var element;\n var tempDate;\n var target;\n var field;\n var fieldType;\n var fieldData;\n var values;\n var val;\n \n suppress = (suppress === true);\n fieldData = self.FieldData;\n //If no field name is given fill all fields\n if(fieldName === undefined) {\n fields = fieldData;\n }\n else {\n //Find the field name and add it to the processing queue\n fields = self.GetField(fieldName);\n }\n \n if (typeof fields === 'undefined')\n return;\n \n \n //Fill the fields\n for(i = 0; i < fields.length; i += 1) {\n element = undefined; //reset value\n tempDate = undefined;\n target = undefined;\n field = undefined;\n fieldType = undefined;\n values = undefined;\n v = undefined;\n \n field = fields[i];\n \n \n\n var inTable = false;\n element = $('li.form-q[attr=\"' + field.name.replace(/\\W/g, '_') + '\"]')\n \n if(element.length > 0) {\n //Assume we are only supporting text and dropdowns.\n fieldType = GetFieldType(element);\n target = GetDataFields(element, fieldType);\n \n //If a multivalued field click ADD enough times to get the correct number of fields.\n if(Array.isArray(field.value) && target.length < field.value.length) {\n if (inTable) {\n var tableParent = element.closest(\".cf-table_parent\");\n for(j = 0; j < field.value.length - target.length; j += 1) {\n tableParent.find('.cf-table-add-row').click();\n }\n\n element = tableParent.find('td[data-title=\"' + field.name + '\"]');\n }\n else {\n for(j = 0; j < field.value.length - target.length; j += 1) {\n $('a[ref-id=\"' + element.attr('id') + '\"]').click();\n }\n }\n \n target = GetDataFields(element, fieldType);\n }\n\n \n //Handle multivalue fields\n field.value = Array.isArray(field.value) ? field.value : [field.value];\n target.each(function(index, element){\n v = field.value[index];\n element = element instanceof jQuery ? element : $(element);\n if(v) {\n \t//add allowed field types here\n if(fieldType === 'text' || fieldType === 'longtext' || fieldType === 'number' || fieldType === 'email' || fieldType === 'currency') { \n element.val(v);\n }\n //The dropdown menu may be filled by a lookup. In this case the option does not\n //exist. Add the option and then reselect it.\n else if(fieldType === 'select') {\n element.val(v);\n if(element.val() === null) {\n element.append('<option value=\"' + v + '\">' + v + '</option>') \n .val(v);\n }\n }\n //Format date strings so that we omit timestamps and convert to a user-readable format\n \t//JavaScript epoc date is 1/1/1900\n \t//JavaScript months are base 0\n else if(fieldType === 'date' && v !== null) {\n tempDate = new Date(v);\n element.val((tempDate.getMonth() + 1) + '/' + tempDate.getDate() + '/' + (tempDate.getYear() + 1900));\n } \n }\n });\n }\n }\n }\n \n\n self.FieldData = LoadData();\n self.Refresh = LoadData;\n self.Fill = FillFields;\n self.GetField = GetField;\n \n return this;\n}", "function syncFields(fields,rv,fitsData) {\n const newFields= clone(fields);\n if (Number.parseInt(rv.lowerWhich)!==ZSCALE) {\n newFields.lowerRange= clone(fields.lowerRange, computeLowerRangeField(fields,rv,fitsData));\n newFields.upperRange= clone(fields.upperRange, computeUpperRangeField(fields,rv,fitsData));\n }\n\n newFields.algorithm= clone(fields.algorithm, {value: rv.algorithm});\n newFields.lowerWhich= clone(fields.lowerWhich, {value: rv.lowerWhich});\n newFields.upperWhich= clone(fields.upperWhich, {value: rv.upperWhich});\n if (newFields.lowerWhich.value===ZSCALE) newFields.lowerWhich.value= PERCENTAGE;\n if (newFields.upperWhich.value===ZSCALE) newFields.upperWhich.value= PERCENTAGE;\n\n return newFields;\n}", "function reduceNames (docset, field) {\n\n\t\tvar names = docset.filter(function removeDupes (doc, index, docs) {\n\n\t\t\tvar prevDoc = docs[index - 1];\n\t\t\treturn prevDoc ? doc[field] !== prevDoc[field] : true;\n\n\t\t}).map(function retrieveField (doc) {\n\t\t\treturn doc[field];\n\t\t});\n\n\t\treturn names;\n\n\t}", "function searchAndAssign(name, value, inputs) {\n return inputs.map((input) => {\n if(input.name === name) {\n input.value = value;\n return input;\n }\n else if(input.dependants) {\n input.dependants = searchAndAssign(name, value, input.dependants);\n return input;\n }\n return input;\n })\n }", "function CHMgetValues(formName, fieldName, otherFieldNames)\r\n{\r\n if(otherFieldNames)\r\n {\r\n var retValues = new Array();\r\n var len = 0;\r\n if(eval('document.'+formName+'.'+fieldName)) \r\n len = eval('document.'+formName+'.'+fieldName).length;\r\n \r\n if(len != 0 && len == null )\r\n {\r\n retValues[0] = new Array();\r\n retValues[0][0] = eval('document.'+formName+'.'+fieldName).value;\r\n for(var j=1; j<=otherFieldNames.length; j++)\r\n retValues[0][j] = eval('document.'+formName+'.'+otherFieldNames[j-1]).value;\r\n }\r\n else\r\n {\r\n var i=0;\r\n for(var cnt=0; cnt < len; cnt++)\r\n {\r\n retValues[i] = new Array();\r\n retValues[i][0] = eval('document.'+formName+'.'+fieldName)[cnt].value;\r\n for(var j=1; j<=otherFieldNames.length; j++)\r\n retValues[i][j] = eval('document.'+formName+'.'+otherFieldNames[j-1])[cnt].value;\r\n\r\n i++;\r\n }\r\n }\r\n \t\t\t\r\n return retValues;\r\n }\r\n }", "function buildValueArray(name, mod, map, fn) {\n var field = name, all = [], setMap;\n if (!loc[field]) {\n field += 's';\n }\n if (!map) {\n map = {};\n setMap = true;\n }\n forAllAlternates(field, function(alt, j, i) {\n var idx = j * mod + i, val;\n val = fn ? fn(i) : i;\n map[alt] = val;\n map[alt.toLowerCase()] = val;\n all[idx] = alt;\n });\n loc[field] = all;\n if (setMap) {\n loc[name + 'Map'] = map;\n }\n }", "function configMerge(fields) {\n var cfgList = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n cfgList[_i - 1] = arguments[_i];\n }\n var dstConfig = {};\n fields.forEach(function (f) {\n cfgList.forEach(function (srcConfig) {\n var o = srcConfig[f];\n var t = typeof o;\n if (t != 'undefined') {\n if (Array.isArray(o) || t != 'object' || o == null)\n dstConfig[f] = o;\n else\n dstConfig[f] = Object.assign({}, dstConfig[f], configMerge(Object.keys(o), o));\n }\n });\n });\n return dstConfig;\n }", "function buildData(form) {\n return $(form).serializeArray().reduce(function(obj, item) {\n obj[item.name] = item.value.trim();\n\n if (obj[item.name]) {\n obj[item.name] = item.value.toLowerCase();\n }\n\n return obj;\n }, {});\n}", "function launchesFormHelper(data) {\n\tif (!data.hasOwnProperty('rocket') && data.hasOwnProperty('rocket_id') && data.hasOwnProperty('rocket_name')) {\n\t\tdata['rocket'] = {rocket_id: data['rocket_id'], rocket_name: data['rocket_name']};\n\t}\n\tif (!data.hasOwnProperty('launch_site') && data.hasOwnProperty('site_id') && data.hasOwnProperty('site_name_long')) {\n\t\tdata['launch_site'] = {site_id: data['site_id'], site_name_long:data['site_name_long']};\n\t}\n\tconsole.log(data);\n}", "function filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n }", "function mapSingleTypedValuesFields(options) {\n var valueFields = [];\n var valueField;\n \n if (options.typeField !== null) {\n valueField = {};\n valueField.value = options.typeField;\n valueField.customValueField = options.customValueField;\n valueField.types = options.types;\n valueField.title = $.i18n(options.i180nPackage, options.group);\n valueField.i180nPackage = options.i180nPackage;\n valueField.type = \"select\";\n valueFields.push(valueField);\n }\n\n //var prop = null;\n for (var prop in options.mapping) {\n valueField = {};\n valueField.value = options.mapping[prop];\n valueField.title = $.i18n(options.i180nPackage, options.group + '-' + prop);\n valueField.type = \"text\";\n valueField.rules = options.rules[prop];\n valueFields.push(valueField);\n }\n options.valueFields = valueFields;\n\n // $.extend (options, contactInfoEditorParams);\n\n }", "function doCleanUp (first ,second) {\n return [first.replace(/\\s/g,'').toLowerCase() , second.replace(/\\s/g,'').toLowerCase()]\n }", "function cjAdminSaveEmptyFieldList(targetFieldId) {\n var e = document.getElementById(targetFieldId);\n var c = document.getElementsByTagName(\"input\");\n for (i = 0; i < c.length; i++) {\n if (c[i].type == \"checkbox\") {\n if (c[i].checked == false) {\n e.value += c[i].name + \",\"\n }\n } else if (c[i].type == \"radio\") {\n if (c[i].checked == false) {\n e.value += c[i].name + \",\"\n }\n } else if (c[i].value == \"\") {\n e.value += c[i].name + \",\"\n }\n }\n c = document.getElementsByTagName(\"select\");\n for (i = 0; i < c.length; i++) {\n if (c[i].value == \"\") {\n e.value += c[i].name + \",\"\n }\n }\n}", "_getFieldsFromValue() {\n const that = this,\n items = that._valueFlat,\n fieldsNames = [],\n fields = [];\n\n for (let i = 0; i < items.length; i++) {\n if (items[i].type === 'condition') {\n const fieldName = items[i].data[0];\n\n if (fieldsNames.indexOf(fieldName) === -1) {\n const fieldElement = { label: fieldName, dataField: fieldName, dataType: 'string', format: null };\n\n fieldsNames.push(fieldName);\n fields.push(fieldElement);\n }\n }\n }\n\n that._valueFields = fields;\n }", "function mergeMetaFields(matched) {\n return matched.reduce((meta, record) => assign(meta, record.meta), {});\n}", "function fields(fieldname, recs) {\n\tif (!recs.length) return [];\n\treturn [recs[0][fieldname]].concat(fields(fieldname, recs.slice(1)));\n}", "function formatData(items) {\n\n const tempItem = items.map((item) => {\n\n const id = item.sys.id;\n\n const images = item.fields.images.map((image) => { return image.fields.file.url });\n\n const room = { ...item.fields, images, id };\n\n return room;\n\n });\n\n return tempItem;\n\n }", "function group_dbs(all_dbs) {\n\tconst ret = {};\n\tfor (let i in all_dbs) {\n\t\tconst db_full_name = all_dbs[i];\n\t\tconst siid = get_siid(db_full_name);\n\t\tconst db_type = get_db_type(db_full_name);\n\n\t\tif (!ret[siid]) {\t\t\t\t\t\t\t// safe init\n\t\t\tret[siid] = {};\n\t\t}\n\t\tif (!ret[siid].types) {\n\t\t\tret[siid].types = [];\n\t\t}\n\t\tif (!ret[siid].full_names) {\n\t\t\tret[siid].full_names = [];\n\t\t}\n\n\t\tret[siid].types.push(db_type);\n\t\tret[siid].full_names.push(db_full_name);\n\t}\n\treturn ret;\n}", "formatData(items) {\n let tempItems = items.map((item) => {\n let id = item.sys.id;\n let images = item.fields.images.map((image) => image.fields.file.url); // Iteramos cada Image destructurando\n //\n // Queremos guardar todo en ROOM.\n // 1- Creamos un object que contenga TODO(item.fields)\n // 2- images del object sea igual a mi images mapeado\n let room = { ...item.fields, images, id };\n return room;\n });\n return tempItems;\n }", "function insertFieldValues(lyr, fieldName, values) {\n var size = getFeatureCount(lyr) || values.length,\n table = lyr.data = (lyr.data || new DataTable(size)),\n records = table.getRecords(),\n rec, val;\n\n for (var i=0, n=records.length; i<n; i++) {\n rec = records[i];\n val = values[i];\n if (!rec) rec = records[i] = {};\n rec[fieldName] = val === undefined ? null : val;\n }\n }", "function refactorAnalyticsFacts(analyticsFacts) {\n var customAnalyticsFacts = {};\n customAnalyticsFacts.reportSuiteId = \"\";\n customAnalyticsFacts.fullSiteName = \"myherbalife\";\n customAnalyticsFacts.siteName = \"\";\n customAnalyticsFacts.countryCode = \"\";\n customAnalyticsFacts.languageCode = \"\";\n customAnalyticsFacts.locale = \"\";\n customAnalyticsFacts.currencyCode = \"\";\n customAnalyticsFacts.localPageTitle = \"\";\n customAnalyticsFacts.searchTerms = \"\";\n customAnalyticsFacts.bcLevel1 = \"\";\n customAnalyticsFacts.bcLevel2 = \"\";\n customAnalyticsFacts.bcLevel3 = \"\";\n customAnalyticsFacts.isLoggedIn = false;\n customAnalyticsFacts.WaitingRoom = false;\n customAnalyticsFacts.dsId = \"\";\n customAnalyticsFacts.dsTeam = \"\";\n customAnalyticsFacts.countryOfProcessing = \"\";\n customAnalyticsFacts.dsIsBizworksSubscriber = \"false\";\n customAnalyticsFacts.dsIsDwsOwner = \"false\";\n customAnalyticsFacts.productDetail = null;\n customAnalyticsFacts.orderId = \"\";\n customAnalyticsFacts.products = null;\n customAnalyticsFacts.events = \"\";\n\n if (typeof analyticsFacts.OmnitureSiteId && analyticsFacts.OmnitureSiteId != \"\" && analyticsFacts.OmnitureSiteId != null) {\n customAnalyticsFacts.reportSuiteId = analyticsFacts.OmnitureSiteId.toLowerCase();\n }\n if (typeof analyticsFacts.Events && analyticsFacts.Events != \"\" && analyticsFacts.Events != null) {\n customAnalyticsFacts.events = analyticsFacts.Events;\n }\n if (typeof analyticsFacts.OmnitureSiteCountryId != \"undefined\" && analyticsFacts.OmnitureSiteCountryId != \"\" && analyticsFacts.OmnitureSiteCountryId != null) {\n if (customAnalyticsFacts.reportSuiteId != \"\") {\n customAnalyticsFacts.reportSuiteId = customAnalyticsFacts.reportSuiteId.toLowerCase() + \",\" + analyticsFacts.OmnitureSiteCountryId.toLowerCase();\n } else {\n customAnalyticsFacts.reportSuiteId = analyticsFacts.OmnitureSiteCountryId.toLowerCase();\n }\n }\n if (typeof analyticsFacts.OmnitureSiteName && analyticsFacts.OmnitureSiteName != \"\" && analyticsFacts.OmnitureSiteName != null) {\n customAnalyticsFacts.siteName = analyticsFacts.OmnitureSiteName.toLowerCase();\n }\n\n if (typeof analyticsFacts.CountryCode != \"undefined\" && analyticsFacts.CountryCode != \"\" && analyticsFacts.CountryCode != null) {\n customAnalyticsFacts.countryCode = analyticsFacts.CountryCode.toLowerCase();\n }\n\n if (typeof analyticsFacts.CurrencyCode != \"undefined\" && analyticsFacts.CurrencyCode != \"\" && analyticsFacts.CurrencyCode != null) {\n customAnalyticsFacts.currencyCode = analyticsFacts.CurrencyCode.toUpperCase();\n }\n\n if (typeof analyticsFacts.LanguageCode != \"undefined\" && analyticsFacts.LanguageCode != \"\" && analyticsFacts.LanguageCode != null) {\n customAnalyticsFacts.languageCode = analyticsFacts.LanguageCode.toLowerCase();\n }\n\n if (customAnalyticsFacts.languageCode != \"\" && customAnalyticsFacts.countryCode != \"\" && customAnalyticsFacts.countryCode != null) {\n customAnalyticsFacts.locale = analyticsFacts.LanguageCode.toLowerCase() + \"-\" + customAnalyticsFacts.countryCode.toUpperCase();\n }\n\n if (typeof analyticsFacts.Title != \"undefined\" && analyticsFacts.Title != \"\" && analyticsFacts.Title != null) {\n customAnalyticsFacts.localPageTitle = analyticsFacts.Title.toLowerCase();\n }\n\n if (typeof analyticsFacts.SearchTerms != \"undefined\" && analyticsFacts.SearchTerms != \"\" && analyticsFacts.SearchTerms != null) {\n customAnalyticsFacts.searchTerms = analyticsFacts.SearchTerms.toLowerCase();\n }\n\n if (typeof analyticsFacts.IsLoggedIn != \"undefined\" && analyticsFacts.IsLoggedIn && analyticsFacts.IsLoggedIn != null) {\n customAnalyticsFacts.isLoggedIn = analyticsFacts.IsLoggedIn;\n }\n\n if (typeof analyticsFacts.WaitingRoom != \"undefined\" && analyticsFacts.WaitingRoom && analyticsFacts.WaitingRoom != null) {\n customAnalyticsFacts.WaitingRoom = analyticsFacts.WaitingRoom;\n }\n\n if (typeof analyticsFacts.Id != \"undefined\" && analyticsFacts.Id != \"\" && analyticsFacts.Id != null) {\n customAnalyticsFacts.dsId = analyticsFacts.Id.toUpperCase();\n }\n\n if (typeof analyticsFacts.SubtypeCode != \"undefined\" && analyticsFacts.SubtypeCode != \"\" && analyticsFacts.SubtypeCode != null) {\n customAnalyticsFacts.dsTeam = analyticsFacts.SubtypeCode.toUpperCase();\n }\n\n if (typeof analyticsFacts.ProcessingCountryCode != \"undefined\" && analyticsFacts.ProcessingCountryCode != \"\" && analyticsFacts.ProcessingCountryCode != null) {\n customAnalyticsFacts.countryOfProcessing = analyticsFacts.ProcessingCountryCode.toUpperCase();\n }\n\n var i = 0;\n if (typeof analyticsFacts.Roles != \"undefined\" && analyticsFacts.Roles != null) {\n for (i = 0; i < analyticsFacts.Roles.length; i++) {\n if (analyticsFacts.Roles[i].match(/Bizworks_(Sub|1|2|3)/i)) {\n customAnalyticsFacts.dsIsBizworksSubscriber = \"true\";\n } else if (analyticsFacts.Roles[i] == \"DWSOwner\") {\n customAnalyticsFacts.dsIsDwsOwner = \"true\";\n }\n }\n }\n\n if (typeof analyticsFacts.Breadcrumbs != \"undefined\" && analyticsFacts.Breadcrumbs != null) {\n for (i = 0; i < analyticsFacts.Breadcrumbs.length && i < 3; i++) {\n customAnalyticsFacts['bcLevel' + (i + 1)] = analyticsFacts.Breadcrumbs[i].toLowerCase();\n }\n }\n\n if (typeof analyticsFacts.ProductDetail != \"undefined\" && analyticsFacts.ProductDetail != null) {\n customAnalyticsFacts.productDetail = analyticsFacts.ProductDetail;\n }\n\n if (typeof analyticsFacts.OrderId != \"undefined\" && analyticsFacts.OrderId != \"\" && analyticsFacts.OrderId != null) {\n customAnalyticsFacts.orderId = analyticsFacts.OrderId;\n }\n\n if (typeof analyticsFacts.PricedCart != \"undefined\" && analyticsFacts.PricedCart != null) {\n customAnalyticsFacts.products = analyticsFacts.PricedCart;\n }\n\n pluginsConf(customAnalyticsFacts);\n\n }", "getInitialValues(inputs) {\n const initialValues = {};\n inputs.forEach(field => {\n if (!initialValues[field['fieldName']]) {\n initialValues[field['fieldName']] = field.value;\n }\n });\n return initialValues;\n }", "function _mergeItemsData(items, except_names) {\r\n const ret = {};\r\n const item_names = [];\r\n for (let i = 0; i < items.length; i++) {\r\n const item = items[i];\r\n if (except_names.indexOf(items[i].name) >= 0) continue;\r\n const name_key = ('0' + item.match_level).slice(-3) + '_' + item.name;\r\n if (name_key in ret) {\r\n ret[name_key].push(item);\r\n } else {\r\n ret[name_key] = [item];\r\n item_names.push(item.name);\r\n }\r\n }\r\n const keys = Object.keys(ret);\r\n const ret_sorted = [];\r\n for (let i = 0; i < keys.length; i++) {\r\n ret[keys[i]].sort(_sortItemInSameName); // sort in same item\r\n ret_sorted.push(ret[keys[i]]);\r\n }\r\n ret_sorted.sort(_sortItemByMatchLevel); // sort by match level\r\n return { result: ret_sorted, names: item_names };\r\n }", "toGroups(fields) {\n // bail on empty schemas\n if (fields.length === 0) {\n return [];\n }\n\n // bail if we're already in groups\n if (fields[0].type === 'group') {\n return fields;\n }\n\n const groups = [];\n let currentGroup = -1;\n _.each(fields, function (field) {\n if (field.contextual) {\n return;\n }\n\n if (!field.group) {\n field.group = {\n name: defaultGroup.name,\n label: defaultGroup.label\n };\n }\n // first group, or not the current group\n if (groups.length === 0 || groups[currentGroup].name !== field.group.name) {\n groups.push({\n type: 'group',\n name: field.group.name,\n label: field.group.label,\n fields: []\n });\n currentGroup++;\n }\n // add field to current group\n groups[currentGroup].fields.push(field);\n });\n return groups;\n }", "function dissection_sticky_fields_copy() {\nlogger(\"dissection_sticky_fields_copy()\");\n var vals = window.dissection_sticky_vals;\n if (vals == null) { return } // first dissection\n var sf = window.dissection_sticky_fields;\n var form = $(featherlight_selector()+\" form\");\n for (const tag in sf) {\n sf[tag].forEach(function(field) {\n var name = \"sample[\"+field+\"]\";\n var elem = form.find(tag+\"[name='\"+name+\"']\").val(vals[field]);\n if (tag == \"select\") {\n elem.trigger(\"change\");\n }\n });\n }\n}", "injectDataIntoFormFields() {\n let fields = this.injectCategoryDataIntoFormFields()\n\n\n let initialValues = {}\n fields.forEach((field) => {\n switch (field.name) {\n case \"depth\":\n initialValues[field.name] = this.state.product.dimensions.depth\n break;\n case \"width\":\n initialValues[field.name] = this.state.product.dimensions.width \n break;\n case \"height\":\n initialValues[field.name] = this.state.product.dimensions.height \n break;\n default:\n initialValues[field.name] = this.state.product[field.name]\n break;\n }\n })\n\n\n\n return initialValues\n }", "function createlstWant() {\n var lst = $(\"#iWant\").val().toLowerCase().split(\",\");\n i = 0;\n for (i = 0; i < lst.length; i++) {\n lst[i] = lst[i].trim();\n }\n curAppliedFilters[\"ingredientsToInclude\"] = lst;\n}", "function createFormFields(fields) {\n var _items = [];\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n var item = {};\n for (var key in FieldPlistMapper) {\n if (FieldPlistMapper.hasOwnProperty(key) && (field[key] !== null && field[key] !== undefined)) {\n item[FieldPlistMapper[key]] = field[key];\n }\n }\n _items.push(item);\n }\n\n return _items;\n}", "function getFieldsValues(fields, ss) {\n var doc = {};\n fields.each(function formValuesEach() {\n var fieldName, val = AutoForm.getInputValue(this, ss);\n if (val !== void 0) {\n // Get the field/schema key name\n fieldName = $(this).attr(\"data-schema-key\");\n doc[fieldName] = val;\n }\n });\n return doc;\n}", "mapFieldKeys(filters, fields) {\n return filters.reduce((map, filter) => {\n for (let field of fields) {\n if (filter.field.toUpperCase() === field.toUpperCase()) {\n return {...map,\n [filter.field]: field\n }\n }\n }\n\n return map;\n }, {});\n }" ]
[ "0.5619916", "0.5287326", "0.5254355", "0.518044", "0.5120531", "0.5117962", "0.5084541", "0.50548285", "0.50227296", "0.5005516", "0.5004088", "0.4993486", "0.4972472", "0.490241", "0.48945016", "0.4890567", "0.48803928", "0.4878614", "0.48611364", "0.4858207", "0.4847248", "0.4846482", "0.4835351", "0.48324287", "0.48092875", "0.47874328", "0.4786611", "0.47827366", "0.47775495", "0.47561395", "0.47554925", "0.4747377", "0.47434595", "0.47354132", "0.47137016", "0.471112", "0.47041413", "0.47006977", "0.4690333", "0.46695322", "0.46661296", "0.46578133", "0.46573406", "0.4651858", "0.46453157", "0.4633086", "0.46212113", "0.46190125", "0.46099493", "0.46027628", "0.4601142", "0.45862952", "0.45819107", "0.457961", "0.45790792", "0.45701966", "0.45672175", "0.45571217", "0.4555229", "0.45529157", "0.45529157", "0.45461345", "0.45444256", "0.4543527", "0.45423847", "0.4540136", "0.45313144", "0.4522092", "0.4522092", "0.45206296", "0.4520525", "0.4519353", "0.45190397", "0.4516007", "0.4515059", "0.45132974", "0.45087895", "0.45050704", "0.4500013", "0.4491206", "0.44884476", "0.44876936", "0.44860852", "0.44833168", "0.44817105", "0.4480973", "0.44803017", "0.4473517", "0.44727328", "0.44702452", "0.44658613", "0.4464251", "0.4463816", "0.4461808", "0.44595644", "0.4456443", "0.44530854", "0.44482914", "0.4445406", "0.44419655" ]
0.5532337
1
END OF FPI Code START OF Password Code
function calculate_pwd_similarity(grp_name) { var pwd_similarity = pii_vault.current_report.pwd_similarity; var pwd_groups = pii_vault.current_report.pwd_groups; var total_grps = 0; for (var g in pwd_similarity) { pwd_similarity[g].push(0); total_grps++; } pwd_similarity[grp_name] = []; for (var i = 0; i < (total_grps+1); i++) { pwd_similarity[grp_name].push(0); } flush_selective_entries("current_report", ["pwd_similarity"]); for (var i = 0; i < report_tab_ids.length; i++) { chrome.tabs.sendMessage(report_tab_ids[i], { type: "report-table-change-table", table_name: "pwd_similarity", pwd_similarity: pii_vault.current_report.pwd_similarity, pwd_groups: pii_vault.current_report.pwd_groups, }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function writePassword() {}", "function ChangePassword() {\n\t}", "static process_password(passwd){\n return passwd.padEnd(32, passwd) //passwd must be 32 long\n }", "function generate_password() {\n base.emit(\"generate-password\", {\n url: document.location.toString(),\n username: find_username(),\n });\n }", "function writePassword(len, upper,lower,num, sym) {\n \n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n // var char = upperCase + lowerCase + Numbers + Symbols;\n // var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&‘()*+,-./:;<=>?@[\\]^_`{|}~';\n \n}", "function writePassword(passwordLength, includedLowercase, includedUppercase, includedNumbers, includedSpecialCharacters ) {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var passwordLen = getpasswordLength();\n var options = getPasswordOptionSet();\n\n\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = makePassword(passwordLen, options);\n\n\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n // Reset variables\n passwordLength = 0;\n selectedCharacters = \"\";\n includeLowercase = false;\n includeUppercase = false;\n includeNumbers = false;\n includeSpecialChar = false;\n}", "function writePassword() {\n var passwordReqs = {};\n passwordReqs = passReqs(passwordReqs);\n var password = generatePassword(passwordReqs);\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n}", "function writePassword() {\n inputCharLength();\n}", "function writePassword() {\n // reset global variables for each new password\n possibleChars = [];\n lowercase = false;\n uppercase = false;\n numerals = false;\n specials = false;\n //Run the prompts and generate password\n lengthPrompt();\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function writePassword() {\n const characterAmount = charAmountNumber.value;\n const includeLowercase = includeLowercaseElement.checked\n const includeUppercase = includeUppercaseElement.checked\n const includeNumbers = includeNumbersElement.checked\n const includeSymbols = includeSymbolsElement.checked\n\n const password = generatePassword(characterAmount, includeLowercase, \n includeUppercase, includeNumbers, includeSymbols);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n\tvar params = {\n\t\tlowercase: confirm('Would you like to use lowercase characters?'),\n\t\tuppercase: confirm('Would you like to use uppercase characters?'),\n\t\tspecialChars: confirm('Would you like to use special characters?'),\n\t\tnumericChars: confirm('Would you like to use numeric characters?'),\n\t};\n\twhile (params.length < 8 || params.length > 128 || params.length === undefined) {\n\t\tparams.length = parseInt(prompt('How long would you like your password to be? Greater than 8 Less than 128'));\n\t}\n\tvar password = generatePassword(params);\n\tvar passwordText = document.querySelector('#password');\n\n\tpasswordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n passwordText.value = password;\n passwordEngine.reset();\n}", "function writePassword() {\r\n //review inputs before execution. Each function handles errors by exiting program execution with empty returns\r\n if(validateCharactersRequested() && validateLength()){\r\n password.generatePassword();\r\n passwordText.value = password.randomPassword;\r\n }\r\n\r\n}", "function writePassword() {\n \n\n arraySplit = \"\"; \n exitApplication = false; \n userInput = \"\"; \n finalPassword = \"\"; \n displayPassword = \"\"; \n window.alert(\" Lets check our password criteria options\");\n var password = generatePassword(); //different method\n \n var pLength = passlength();\n \n displayPassword = generatePasswordRandomness(userInput,pLength);\n\n\n var passwordText = document.querySelector(\"#password\"); \n \n \n document.getElementById(\"password\").readOnly = false; \n document.getElementById(\"password\").value = displayPassword; \n document.getElementById(\"password\").readOnly = true; \n\n}", "function checkPassword() {\n\n\n\n}", "function getPassowrd() {\n let eyeIconShow = document.getElementById('eye-icon-slash-1');\n eyeIconShow.style.display = 'block';\n eyeIconShow.classList = 'fas fa-eye';\n\n let changeType = document.getElementById('singup-pass');\n changeType.type = 'text';\n\n let chars = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+=-[]{}><:';\n let password = '';\n\n for (let i = 0; i < 12; i++) {\n let r = Math.floor(Math.random() * chars.length);\n password += chars[r];\n }\n document.getElementById('singup-pass').value = password;\n}", "function generatePassword() {\n return 'generatepwfx';\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "function generatePassword() {\n //prompt for password length\n var passLength = prompt(\"Please enter password length between 8 and 128\", \"8\");\n if (passLength < 8 || passLength > 128) {\n alert(\"Please enter a number between 8 and 128\");\n return;\n }\n //prompt for password complexity options\n var passUpOpt = confirm(\"would you like to include uppercase characters?\");\n var passLowOpt = confirm(\"would you like to include lowercase characters?\");\n var passNumOpt = confirm(\"would you like to include numeric characters?\");\n var passSpecOpt = confirm(\"would you like to include special characters?\");\n //array for password characters\n //let passChar = ['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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')' '_' '+'];\n var passUpChar = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var passLowChar = \"abcdefghijklmopqrstuvwxyz\";\n var passNumChar = \"1234567890\";\n var passSpecChar = \"!@#$%^&*()_+\";\n var passChar = \"\";\n \n /* if (passUpOpt = true) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecOpt = true) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } else if (passUpOpt = false) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecChar = true) {\n passChar = passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } */\n //combinations of strings\n if (passUpOpt && passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n } else if (!passUpOpt && !passLowOpt && !passNumOpt && !passSpecOpt) {\n alert(\"Please choose at least one type of character\")\n } else if (passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passLowChar + passNumChar + passSpecChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passUpOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passNumChar + passSpecChar;\n } else if (passUpOpt && passSpecOpt) {\n passChar = passUpChar + passSpecChar;\n } else if (passUpOpt && passLowOpt && passNumOpt) {\n passChar = passUpChar + passLowChar + passNumChar;\n } else if (passUpOpt && passLowOpt && passSpecChar) {\n passChar = passUpChar + passLowChar + passSpecChar;\n } else if (passUpOpt && passNumOpt) {\n passChar = passUpChar + passNumChar;\n } else if (passUpOpt) {\n passChar = passUpChar;\n } else if (passLowOpt && passNumOpt) {\n passChar = passLowChar + passNumChar;\n } else if (passLowChar) {\n passChar = passLowChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passNumOpt) {\n passChar = passNumChar;\n } else if (passUpOpt && passLowOpt) {\n passChar = passUpChar + passLowChar;\n } else if (passLowOpt && passSpecOpt) {\n passChar = passLowChar && passSpecChar;\n }\n\n console.log(passChar);\n\n\n var pass = \"\";\n //for loop to pick the characters the password will contain\n for(var i = 0; i <= passLength; i++) {\n pass = pass + passChar.charAt(Math.floor(Math.random() * Math.floor(passChar.length - 1)));\n }\n alert(pass);\n //return pass;\n document.querySelector(\"#password\").value = pass;\n\n}", "function writePassword() {\n //get character types selected by user\n var charArray = charInputsSelected();\n\n //make sure all conditions are met before generating password\n if (lengthInputTest() && charArray.length > 0 && duplicateCheck()) {\n\n // removes printed error messages\n lenErrorString.textContent = '';\n charErrorString.textContent = '';\n dupErrorString.textContent = '';\n\n var password = generatePassword(charArray);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n generatePassword()\n }", "function writePassword() {\n var characterNumbers = getCharacterNumbers()\n var characterType = getCharacterType()\n \n \n\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function secretPassword() {\n var password = 'xh38sk';\n return {\n \t//Code here\n }\n }", "function isValidPassword(password) {\n\n\n}", "function confirmCode(txt) {\n\t\tvar fullHash = hash(\"Multi-Pass Salt - \"+txt);\n\t\treturn fullHash.substring(fullHash.length-4);\n\t}", "function generatePassword() {\n var pw = mainForm.master.value,\n sh = mainForm.siteHost.value;\n\n // Don't show error message until needed\n hide(mainForm.pwIncorrect);\n\n // Only generate if a master password has been entered\n if (pw !== '') {\n if (settings.rememberPassword) {\n verifyPassword(pw, correct => {\n if (!correct) {\n // Master password is incorrect so show a warning\n show(mainForm.pwIncorrect);\n mainForm.master.select();\n }\n });\n }\n\n // Only generate if a site has been entered\n if (sh !== '') {\n mainForm.pwResult.value = '';\n mainForm.pwResult.placeholder = 'Generating...';\n\n // Generate a password to use, regardless of correct password\n uniquify(pw, sh, unique => {\n mainForm.pwResult.value = unique;\n mainForm.pwResult.placeholder = '';\n mainForm.pwResult.select();\n }, settings);\n }\n }\n }", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n // clears password variables in case user doesn't click clear button before generating a new password\n passCreate = \"\";\n password = \"\";\n}", "function writePassword() {\n var len = window.prompt(\"Enter length of password between 8 and 128 characters: \")\n /* if (len === null) {\n return;\n } */\n while (len <= 7 || len >= 129){\n var len = window.prompt(\"Invalid Entry. Enter length of password between 8 and 128 characters: \")\n }\n var upper = window.prompt(\"Include uppercase letters? (Y/N): \").toLowerCase()\n while (upper != \"y\" && upper!= \"n\" ){\n var upper = window.prompt(\"Invalid Entry. Include uppercase letters? (Y/N): \")\n } \n \n var lower = window.prompt(\"Include lowercase letters? (Y/N): \").toLowerCase()\n while (lower != \"y\" && lower!= \"n\"){\n var lower = window.prompt(\"Invalid Entry. Include lowercase letters? (Y/N): \")\n }\n\n var num = window.prompt(\"Include numbers? (Y/N): \").toLowerCase()\n while (num != \"y\" && num != \"n\"){\n var num = window.prompt(\"Invalid Entry. numbers? (Y/N): \") \n } \n\n var special = window.prompt(\"Include special characters? (Y/N): \").toLowerCase()\n while (special != \"y\" && special != \"n\"){\n var special = window.prompt(\"Invalid Entry. special characters? (Y/N): \") \n } \n\n upper = (upper == 'y') ? true : false;\n lower = (lower =='y') ? true : false;\n num = (num == 'y') ? true : false;\n special = (special == 'y') ? true : false;\n\n var password = generatePassword(len, upper, lower, num, special);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = pwCriteria();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "function passwordChanged(input, output) {\n\t\tif( input.value.length < 8 ) {\n\t\t\t// Master-password size smaller than minimum allowed size\n\t\t\t// Provide a masked partial confirm-code, to acknowledge the user input\n\t\t\tvar maskedCode='';\n\t\t\tswitch(Math.floor(input.value.length*4/8)) {\n\t\t\t\tcase 1: maskedCode='#'; break;\n\t\t\t\tcase 2: maskedCode='##'; break;\n\t\t\t\tcase 3: maskedCode='###'; break;\n\t\t\t}\n\t\t\toutput.value=maskedCode;\n\t\t} else {\n\t\t\toutput.value = confirmCode(input.value);\n\t\t}\n\t\tvaluesChanged();\n\t}", "function writePassword() {\n var criteria = passwordCriteria();\n var password = generatePassword(criteria);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function Generate()\n{\n var uri = document.hashform.domain.value;\n var domain = (new SPH_DomainExtractor()).extractDomain(uri);\n var size = SPH_kPasswordPrefix.length;\n var data = document.hashform.sitePassword.value;\n if (data.substring(0, size) == SPH_kPasswordPrefix)\n data = data.substring(size);\n var result = new String(new SPH_HashedPassword(data, domain));\n return result;\n}", "function writePassword() { \n \n\n // var Qupper = confirm(\"Would you like to add uppercase?\");\n var Qlower = confirm(\"Would you like to add lowercase?\");\n var Qnumber = confirm(\"Would you like to add numbers?\");\n var Qspec = confirm(\"Would you like to add characters?\");\n\n\n\ngeneratepassword(Qlower, Qnumber, Qspec);\n}", "function writePassword() {\n var genPassword = generatePassword();\n var passwordText = document.querySelector('#password');\n passwordText.value = genPassword;\n}", "function writePassword() {\n var password = generatePassword();\n var lowercase = confirm(\"include lowercase\");\n if (lowerCasedCharacters === true) {\n }\n var uppercase = confirm(\"include uppercase\");\n var number = confirm(\"include number\");\n var speicalcharacter = confirm(\"include speicalcharacter\");\n var pw = document.getElementById(\"password\").value;\n}", "function writePassword() {\n var password = \"\";\n for (var i = 0; i <= userLength; i++) {\n password = password + finalOptions.charAt(Math.floor(Math.random() * Math.floor(finalOptions.length - 1)));\n }\n document.getElementById(\"password\").value = password;\n }", "function onPasswordSet() {\n // Back to main form\n hide(pwSetForm);\n show(mainForm);\n\n // Password was just set, so generate right away if\n // site is filled in.\n if (mainForm.siteHost.value) {\n generatePassword();\n } else {\n // If the site has not been filled in, focus it.\n mainForm.siteHost.focus();\n }\n }", "function writePassword() {\n \n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");//id selector = html line 22 \n\n passwordText.value = password;\n\n \n}", "function writePassword() {\n var password = generatePassword(\"@password\");\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n \n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n \n passwordText.value = password;\n \n }", "function writePassword(passwordLength, includeLowercase, includeUppercase, includeNumbers, includeSpecialCharacters) {\n for (i = 0; i = passwordLength; i++) {\n Math.floor(math.random()*passwordLength)\n// Generating password\n var password = generatePassword(includedCharacters);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n return password;\n\n }\n}", "function generatePassword() {\n alert (\"Select which criteria to include in the password\");\n\n\n var passLength = parseInt(prompt(\"Choose a length of at least 8 characters and no more than 128 characters\"));\n\n //evaluate user input for password length\n while (isNaN(passLength) || passLength < 8 || passLength > 128)\n {\n \n if (passLength === null) {\n return;\n }\n\n passLength = prompt(\"choose a length of at least 8 characters and no more than 128 characters\");\n }\n\n\n var lowerCase = confirm(\"Do you want lowercase characters in your password\");\n var upperCase = confirm(\"Do you want uppercase characters in your password\");\n var numChar = confirm(\"Do you want numbers in your password?\");\n var specChar = confirm(\"Do you want special characters in your password?\");\n\n\n //evalute criteria for password generation\n if (lowerCase || upperCase || numChar || specChar)\n {\n var otherToGen = '';\n var intList = '0123456789';\n var uCharList ='ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var lCharList ='abcdefghijklmnopqrstuvwxyz'; \n var sCharList =\"!#$%&()*+,-./:;<=>?@[]^_`{|}~\";\n var remainlenght = 0;\n var criteriaMatch = 0;\n var value = '';\n\n if (numChar){\n value += genchar(1, intList);\n criteriaMatch++;\n otherToGen += intList;\n\n }\n\n if (lowerCase){\n value += genchar(1, lCharList);\n criteriaMatch++;\n otherToGen += lCharList;\n }\n\n if (upperCase) {\n value += genchar(1, uCharList);\n criteriaMatch++;\n otherToGen += uCharList;\n }\n\n\n if(specChar) {\n value += genchar(1, sCharList);\n criteriaMatch++;\n otherToGen += sCharList;\n\n }\n\n remainlenght = passLength-criteriaMatch;\n value += genchar(remainlenght, otherToGen);\n\n return value;\n}\n}", "function passwordOnChange() {\n const pattern = \"^[a-zA-Z0-9_-]{6,20}$\";\n validate(this, pattern);\n}", "function writePassword() {\n // resets password and character strings on repeat \n arrayChar = '';\n password = '';\n password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n \n\n passwordText.value = password;\n}", "function writePassword() {\n passLength = window.prompt(\"How long would you like your password?\");\n if(passLength > 128 || passLength < 8) {\n alert(\"No less than 8 and no more than 128! Refresh and try again!\");\n }\n\n\n upperConfirm = confirm(\"Do you want uppercase letters?\");\n if(upperConfirm) {\n results += upperCase;\n }\n\n lowerConfirm = confirm(\"Do you want lowercase letters?\");\n if(lowerConfirm) {\n results += lowerCase;\n }\n\n numConfirm = confirm(\"Do you want any numbers?\");\n if(numConfirm) {\n results += numCase;\n }\n\n symConfirm = confirm(\"Do you want any symbols?\");\n if(symConfirm) {\n results += symCase;\n }\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = generatePassword()\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "function writePassword() {\n var passwordLength=window.prompt(\"select a number between 8 and 128\");\n var useLowerCase=window.confirm(\"use lowercase letters\");\n var useUpperCase=window.confirm(\"use uppercase letters\");\n var useDigits=window.confirm(\"use digits\");\n var useSpecialCharacters=window.confirm(\"use special characters\");\n var password = generatePassword(passwordLength=passwordLength,useLowerCase=useLowerCase,useUpperCase=useUpperCase,useDigits=useDigits,useSpecialCharacters=useSpecialCharacters);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = generatePassword(confirmedCount, yesUpper, yesLower);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function _3writePassword(password) {\n console.log(\"writing password\")\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n \n}", "function writePassword() {\n var password = generatePassword();\n // Find the id in HTML called password to determine where it should be placed\n var passwordText = document.querySelector(\"#password\");\n // Use the element found in the HTML to display the value of the password variable\n passwordText.value = password;\n return;\n}", "processPassRep() {\n if (this.password.value !== this.passwordRepeat.value) {\n this.passwordRepeat.err = true;\n this.passwordRepeatErr.seen = true;\n this.valid = false;\n this.passwordRepeatErr.text = \"رمز عبور و تکرار آن یکسان نیستند\";\n } else {\n this.passwordRepeat.err = false;\n this.passwordRepeatErr.seen = false;\n }\n }", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector('#password');\n passwordText.value = password;\n charset = \"\";\n}", "function writePassword() {\n var userPassword = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = userPassword;\n }", "function writePassword() {\n\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }", "function writePassword() {\n\tvar passwordText = document.querySelector('#password');\n\n\tpasswordText.value = finalPassword;\n}", "function writePassword() {\n var password = passWordGen();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n if(password) {\n passwordText.value = password;\n }\n}", "function generatePassword() {\n var charCh = \"abcdefghijklmnopqrstuvwxyzABDCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*?\";\n\n var password = \"\"\n\n for (i = 0; i <= 8; i++) {\n password = password + charCh.charAt(Math.floor(Math.random() * Math.floor(charCh.length - 1)));\n }\n\n\n /****\n * WRITE YOUR CODE HERE\n */\n alert(\"Generate Password\");\n \n return password;\n }", "function beginPassword(event) {\n \n // prompt for length of password\n var promptPasswordLength = prompt('How many characters do you want in your password?', 'Please enter a number between 8 and 128.');\n \n // if the pasword length is acceptable, then prompt for characters to be used\n if (promptPasswordLength >= 8 && promptPasswordLength <= 128) {\n \n // prompt to use lowercase characters\n var promptLowercase = prompt(\"Would you like to include lowercase letters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected lowercase, then add lowercase to the char list (charUsed)\n if(promptLowercase === 'yes') {\n charUsed += lowercase;\n charTypeCount += 1;\n \n for(var i=0; i < 1; i++ )\n { \n // pick a lowercase character by random index\n startPassword = startPassword + lowercase[(Math.floor(Math.random() * lowercase.length))];\n }\n }\n \n // prompt to use uppercase characters \n var promptUppercase = prompt(\"Would you like to use UPPERCASE letters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected uppercase, then add uppercase to the char list (charUsed)\n if(promptUppercase === 'yes') {\n charUsed += uppercase;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick an uppercase character by random index\n startPassword = startPassword + uppercase[(Math.floor(Math.random() * uppercase.length))];\n }\n }\n \n // prompt to use number characters\n var promptNumber = prompt(\"Would you like to use numbers in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected number, then add number to the char list (charUsed)\n if(promptNumber === 'yes') {\n charUsed += number;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick a number character by random index\n startPassword = startPassword + number[(Math.floor(Math.random() * number.length))];\n }\n }\n \n \n // prompt to use special characters\n var promptSpecialChar = prompt(\"Would you like to use special characters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected special character, then add special char to the char list (charUsed)\n if(promptSpecialChar === 'yes') {\n charUsed += specialChar;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick a special character by random index\n startPassword = startPassword + specialChar[(Math.floor(Math.random() * specialChar.length))];\n }\n } \n } else {\n window.alert('Total characters must be between 8 and 128. Please try again!');\n return;\n }\n \n if (promptUppercase !== 'yes' && promptLowercase !== 'yes' && promptNumber !== 'yes' && promptSpecialChar !== 'yes') {\n window.alert('At least one character type must be chosen. Please try again!');\n \n return;\n \n } else {\n \n // inititate generatePassword() and pass the needed information\n generatePassword(promptPasswordLength, startPassword, charUsed, charTypeCount, password);\n }\n \n}", "function writePassword() {\n var length = getPasswordLength();\n length = parseInt(length);\n ensureCharacterType();\n var password = generatePassword(length);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "function generatePassword(conns){\n var salt = o.salt;\n if(o.dynamicSalt){\n salt = $( o.dynamicSalt).val();\n }\n var res = salt; //start our string to include the salt\n var off = o.shaOffset; //used to offset which bits we take\n var len = o.passLength; //length of password\n for(i in conns){\n res+=\"-\" + conns[i].startID;\n }\n res+=\"-\" + conns[i].endID; //make sure we get that last pin\n log(res);\n res = Sha1.hash(res, false);\n \n //make sure that we don't try to grab bits outside of our range\n if(off + len > res.length){\n off = 0; \n } \n res = res.substring(off, off + len);\n return res;\n }", "function writePassword() {\n \n plength = parseInt(prompt(\" How many characters would you like your password to be ? minimum of 8 or maximum of 128 characters\", \"\"));\n \n while (isNaN(passwordlength)) {\n plength = parseInt(prompt(\"Invalid option, Please enter a number between 8 & 128\", \"\"));\n }\n\n while ( passwordlength < 8 || passwordlength > 128) {\n passwordlength = parseInt(prompt(\"Enter a number between 8 & 128 characters\", \"\"));\n }\n\n pLowerCase = confirm(\" Would you like to include lower case letters?\");\n ptUpperCase = confirm(\"Would you like unclude upper case letters?\");\n pNumber = confirm(\"Would you like to use numbers?\"); \n pSpecial = confirm(\"Would you like to use special characters?\");\n \n var password = generatePassword();\n\n document.querySelector(\"#password\").value = password; \n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n var charSet =( userLower ? charsLower : '' )\n +( userUpper ? charsUpper : '' )\n +( userNums ? charsNumbers : '' )\n +( userSpecial ? charsSpecial : '' )\n\n passwordText.value = password;\n\n}", "function writePassword() {\r\n\r\n var password = generatePassword(),\r\n passwordText = document.querySelector(\"#password\");\r\n\r\n passwordText.value = password;\r\n \r\n}", "function writePassword() {\r\n \r\n //initilaize all global variables\r\n arraySplit = \"\"; // Used to translate input array back to the user as a string with slice\r\n exitApplication = false; // on/off switch for running the app\r\n userInput = \"\"; // Important - will be used to generate password based on criteria\r\n finalPassword = \"\"; // Important - used as a variable to store temporatly a random passoword.\r\n displayPassword = \"\"; // Impoprtant- used to display the final password on the text area of the HTML element.\r\n window.alert(\" Lets check our password criteria options\");\r\n var password = generatePassword(); // Call the generatePassword(). Global variable used instead for displayPassword.\r\n var passwordText = document.querySelector(\"#password\"); // Part of the placholder text querySelectors will be part of later modules.\r\n \r\n //passwordText.value = password;\r\n document.getElementById(\"password\").readOnly = false; // Text in enabled to allow the code to insert password into the text area.\r\n document.getElementById(\"password\").value = displayPassword; // Display password in text area.\r\n document.getElementById(\"password\").readOnly = true; // Disable the text area so user can only copy paste and not touch or modify the password provided.\r\n}", "function writePassword() {\n var password = generatePassword();\n if (password !== undefined) {\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n }\n}", "function writePassword() {\n var password = getPasswordOptions();\n var passwordText = document.querySelector('#password');\n \n passwordText.value = password;\n }", "function writePassword() {\n\t// prompt for parameters to determine password construct\n\t// 1. Parameter 1 - Password length '\n\n\tpwdLength = prompt(\n\t\t\"Password must be between 8 and 128 characters. How many characters in your password?\"\n\t);\n\n\tconsole.log(pwdLength);\n\n\t// Cancel selected on Prompt - no password\n\tif (!pwdLength) {\n\t\tpassword = \"Cancel selected - number of characters - No password generated\";\n\t\tvar passwordText = document.querySelector(\"#password\");\n\n\t\tpasswordText.value = password;\n\t\treturn password;\n\t}\n\n\t// Password length must be between 8 and 128 characters\n\n\tif (pwdLength < 8 || pwdLength > 128) {\n\t\talert(\"Number of characters must be 8 or more and 128 or less\");\n\t\treturn;\n\t}\n\n\t// 2. Parameter 2 - Include upper case letters\n\n\tinclUpper = prompt(\"Include UPPER CASE letters in your password? (y or n)\");\n\n\t// Cancel selected on Prompt - no password\n\tif (!inclUpper) {\n\t\tpassword = \"Cancel selected - include Upper Case - No password generated\";\n\t\tvar passwordText = document.querySelector(\"#password\");\n\n\t\tpasswordText.value = password;\n\t\treturn password;\n\t}\n\n\tinclUpper.toLowerCase;\n\n\t// Include upper case must be y or n\n\n\tif (inclUpper !== \"n\" && inclUpper !== \"y\") {\n\t\talert(\"Must answer y or n to including Upper Case characters\");\n\t\treturn;\n\t}\n\n\t// 3. Parameter 3 - Include lower case letters\n\n\tinclLower = prompt(\"Include lower case letters in your password? (y or n)\");\n\n\t// Cancel selected on Prompt - no password\n\tif (!inclLower) {\n\t\tpassword = \"Cancel selected - include Lower Case - No password generated\";\n\t\tvar passwordText = document.querySelector(\"#password\");\n\n\t\tpasswordText.value = password;\n\t\treturn password;\n\t}\n\n\tinclLower.toLowerCase;\n\n\t// Include lower case must be y or n\n\n\tif (inclLower !== \"n\" && inclLower !== \"y\") {\n\t\talert(\"Must answer y or n to including Lower Case characters\");\n\t\treturn;\n\t}\n\n\t// 4. Parameter 4 - Include numeric characters\n\n\tinclNumber = prompt(\"Include Numeric characters in your password? (y or n)\");\n\n\t// Cancel selected on Prompt - no password\n\tif (!inclNumber) {\n\t\tpassword = \"Cancel selected - include Numeric - No password generated\";\n\t\tvar passwordText = document.querySelector(\"#password\");\n\n\t\tpasswordText.value = password;\n\t\treturn password;\n\t}\n\n\tinclNumber.toLowerCase;\n\n\t// Include Numeric must be y or n\n\n\tif (inclNumber !== \"n\" && inclNumber !== \"y\") {\n\t\talert(\"Must answer y or n to including Numeric characters\");\n\t\treturn;\n\t}\n\n\t// 5. Parameter 5 - Include special characters\n\n\tinclSpecial = prompt(\"Include Special characters in your password? (y or n)\");\n\n\t// Cancel selected on Prompt - no password\n\tif (!inclSpecial) {\n\t\tpassword = \"Cancel selected - include Special - No password generated\";\n\t\tvar passwordText = document.querySelector(\"#password\");\n\n\t\tpasswordText.value = password;\n\t\treturn password;\n\t}\n\n\tinclSpecial.toLowerCase;\n\n\t// Include Numeric must be y or n\n\n\tif (inclSpecial !== \"n\" && inclSpecial !== \"y\") {\n\t\talert(\"Must answer y or n to including Special characters\");\n\t\treturn;\n\t}\n\n\t// All prompts answered - now generate password using selected parameters\n\tvar password = generatePassword();\n\tvar passwordText = document.querySelector(\"#password\");\n\n\tpasswordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }", "function generatePassword() {\n //debugger;\n // Prompt for password legnth\n //debugger;\n passLength = window.prompt(\n \"How long would you like your password? (Please Pick a number between 8 and 128)\"\n );\n\n var lengthOf = parseInt(passLength);\n\n if (Number.isNaN(passLength)) {\n alert(\"Password length must be a number\");\n return null;\n }\n\n if (lengthOf < 8 || lengthOf > 128) {\n alert(\"Password must be greater than 8 but less than 128\");\n return null;\n }\n\n var numbers = window.confirm(\n \"Click OK if you want to include numberical values?\"\n );\n\n var upCase = window.confirm(\n \"Click OK if you want to include uppercase letters?\"\n );\n\n var lowCase = window.confirm(\n \"Click OK if you want to include lowercase letters?\"\n );\n\n var special = window.confirm(\n \"Click OK if you want to include special characters?\"\n );\n\n if (\n numbers == false &&\n upCase == false &&\n lowCase == false &&\n special == false\n ) {\n alert(\"You must select at least one criteria.\");\n return null;\n }\n\n var userSelections = {\n numbers: numbers,\n lowCase: lowCase,\n upCase: upCase,\n special: special,\n lengthOf: lengthOf,\n };\n return combinesSelection(userSelections);\n}", "function writePassword() {\n var password = generatePassword();\n // If password is empty string, return without printing\n if (!password) {\n return;\n }\n var passwordText = document.querySelector('#password');\n\n passwordText.value = password;\n}", "function writePassword() {\n\n\n // you can create a function named generatePassword that creates the password\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n if(password) {\n passwordText.value = password;\n\n }\n}", "function writePassword() {\n // var password = generatePassword();\n // passwordText.value = password;\n\n passwordText.value = generatePassword();\n}", "function writePassword() {\n // calling the generatePassword function and assigning the outcome a variable\n var password = generatePassword();\n // assigning variable to the password field\n var passwordText = document.querySelector(\"#password\");\n // function result to password field\n passwordText.value = password;\n\n return;\n}", "function writePassword() {\n //defining parameters for genPass() and our question prompt\n const charAmount = parseInt(prompt(\"How many letters do you want for your password. Choose between 8 and 128.\"))\n const upperCase = confirm(\"Do want to include uppercase letters in your password?\")\n const incNum = confirm(\"Do want to include numbers in your password?\")\n const incSymbol = confirm(\"Do want to include symbols letters in your password?\");\n //this is assigning value to our password and links it to the Password text box.\n var newPass = genPass(charAmount, upperCase, incNum, incSymbol)\n var passwordText = document.querySelector(\"#password\");\n \n \n // my if statement in regards to user input validation\n if (charAmount < 8 || charAmount > 128) {\n alert('The password must be between 8 and 128 characters!');\n return;\n }else {\n //this code is what is displayed in the password TextBox\n passwordText.value = newPass;\n }\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n \n passwordText.value = password;\n }", "function writePassword() {\n var password = passwordGen();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n if (password) {\n var passwordText = document.querySelector('#password');\n\n passwordText.value = password;\n }\n}", "function writePassword() {\n var password = generatePassword() //the password variable is created & defined as the content of generatePassword function\n var passwordText = document.querySelector(\"#password\") //assigns passwordText to the password box on the screen\n passwordText.value = password // prints the generated password to the screen\n }", "function writePassword() {\n var password = passwordGenerator();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function generatePw() {\n var possible = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';\n var newPassword = '';\n \n for(var i=0; i < 16; i++) {\n newPassword += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n \n return newPassword;\n }", "function writePassword() { \n \n\n charSet = \"\";\n\n if(lowerCase.toLocaleLowerCase() === \"yes\"){\n charSet += \"abcdefghijklmnopqrstuvwxyz\";\n }\n if(upperCase.toLocaleLowerCase() === \"yes\"){\n charSet += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n }\n if(passNumbers.toLocaleLowerCase() === \"yes\"){\n charSet += \"0123456789\";\n }\n if(special.toLocaleLowerCase() === \"yes\"){\n charSet += \"\\\" !\\\"#$%&'()*+,-./:;<=>?@[]^_`{|}~\"\n }\n\n var password = '';\n for (var i = 0; i < len; i++) {\n \n var randomPoz = Math.floor(Math.random() * charSet.length);\n password += charSet.substring(randomPoz,randomPoz+1);\n }\n \n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n return password;\n\n}", "function pwEvent() {\r\n if (validPW()) {\r\n $password.next().hide(); //next searches through immediate following siblings\r\n } else {\r\n $password.next().show();\r\n }\r\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "function generate() {\n\tvar charset = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\";\n\t//charset = removeDuplicates(charset);\n\tcharset = charset.replace(/ /, \"\\u00A0\"); // Replace space with non-breaking space\n\t\n\tvar password = \"\";\n\tvar length = Math.floor(Math.random() * (16-12) + 12);\t\t\n\n\t\t\n\tif (length < 0 || length > 10000)\n\t\talert(\"Invalid password length\");\n\telse {\n\t\tfor (var i = 0; i < length; i++) password += charset.charAt(randomInt(charset.length));\n\t}\n\n\t$(\"#password\").val(password);\n\t$(\"#password\").pwstrength(\"forceUpdate\");\n\t\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n // .join('') to remove commas from final output \n passwordText.value = pass.join('');\n\n }", "static generatePassword() {\n return Math.floor(Math.random() * 10000);\n }", "function writePassword() {\n document.getElementById(\"password\").value = \"\";\n\n generator(customChar);\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function writePassword() {\n var password1 = \"\";\n password1 = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password1;\n}", "function writePassword() {\n var password = generatePassword(\"\");\n var passwordText = document.querySelector(\"#password\");\n \n function generatePassword() {\n //YYYY\n var answer = prompt(\"Do you want to include lowercase letters? Type yes or no\")\n if (answer == \"yes\") {\n var up = prompt(\"Do you want to inlcude Uppercase letters? Type yes or no\")\n if (up == \"yes\") {\n var number = prompt(\"Do you want to include numbers? Type yes or no\")\n if (number == \"yes\") {\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if (special == \"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}}\n } else{\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if (special == \"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}}\n else {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n }\n }\n return retVal\n //YNYY\n } else {\n var number = prompt(\"Do you want to include numbers? Type yes or no\")\n if (number == \"yes\") {\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if (special == \"yes\"){\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n return retVal\n //YNYN \n } else {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"abcdefghijklmnopqrstuvwxyz0123456789\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n return retVal\n }\n //YNNY\n } else{\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if(special == \"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"abcdefghijklmnopqrstuvwxyz!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n } //YNNN\n else {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"abcdefghijklmnopqrstuvwxyz\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n }\n }}\n return retVal\n //NYYY\n } else {\n var up = prompt(\"Do you want to include Uppercase letters? Type yes or no\")\n if (up == \"yes\") {\n var number = prompt(\"Do you want to include numbers? Type yes or no\")\n if (number == \"yes\") {\n var special = prompt(\"Do you want to inlcude special characters? Type yes or no\")\n if (special == \"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }} //NYYN\n } else {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n }\n } else {\n //NYNY\n if(number == \"no\") {\n var special = prompt(\"Do you want to include special charcters? Type yes or no\")\n if(special == \"yes\"){\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}} //NYNN\n else{\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n } \n }}\n return retVal\n //NNYY\n } else {\n var number = prompt(\"Do you want to include numbers? Type yes or no\")\n if(number == \"yes\") {\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if(special == \"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"0123456789!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n return retVal\n } //NNYN\n else {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"0123456789\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n return retVal\n }\n } //NNNY\n else {\n var special = prompt(\"Do you want to include special characters? Type yes or no\")\n if(special==\"yes\") {\n var gnum = prompt(\"How many characters would you like your password to have? Choose 8-128\")\n if (gnum > 7 && gnum < 129) {\n var length = gnum,\n charset = \"!@#$%^&*()\",\n retVal = \"\";\n for (var i =0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.floor(Math.random() * n)); \n }}\n return retVal\n }\n else\n { alert(\"Try Again\")}\n\n return retVal\n \n } \n }}}\n \n passwordText.value = password;\n }", "function generatePassword() {\n let password = \"\";\n\n // Reset the passwordDetails object to a \"clean slate\" for the current password generation attempt.\n initializePasswordDetails();\n\n // Gather user input, including criteria and desired password length.\n if (getUserInput()) {\n // If we have valid criteria and desired password length, construct the new password one character at a time.\n while (passwordDetails.desiredPasswordLength > 0) {\n password += getNextPasswordCharacter();\n passwordDetails.desiredPasswordLength--;\n }\n }\n\n // Return the new password.\n return password;\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n return;\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }" ]
[ "0.7237239", "0.6846148", "0.6846068", "0.6842233", "0.67410827", "0.66581714", "0.6628844", "0.6591153", "0.65895814", "0.65717775", "0.65686226", "0.6566629", "0.65450615", "0.6509729", "0.64774567", "0.64773583", "0.64615697", "0.6452525", "0.64434993", "0.6443209", "0.6431553", "0.64258367", "0.64232683", "0.642209", "0.6419158", "0.6417385", "0.6414953", "0.64125043", "0.64016545", "0.6400305", "0.6395909", "0.63724166", "0.6369381", "0.63679904", "0.6367845", "0.636557", "0.6363523", "0.6361991", "0.6357915", "0.63545793", "0.63538015", "0.6352382", "0.6352209", "0.63475823", "0.6343441", "0.6341422", "0.6336809", "0.63360035", "0.6334918", "0.6334665", "0.6331467", "0.63278097", "0.6327346", "0.63170105", "0.6313481", "0.63125086", "0.6306146", "0.63059825", "0.6300527", "0.62962943", "0.62953746", "0.6293389", "0.62930393", "0.6289861", "0.62858635", "0.6280139", "0.62800574", "0.6273451", "0.6273124", "0.62717474", "0.626419", "0.6263303", "0.62618184", "0.62614006", "0.6256762", "0.6250149", "0.6248404", "0.62465966", "0.6246492", "0.62405604", "0.6238199", "0.62332827", "0.6226888", "0.62265855", "0.62232", "0.6220997", "0.62206894", "0.62138474", "0.62136", "0.62128305", "0.62111485", "0.6210833", "0.62104785", "0.6209727", "0.6204175", "0.62007153", "0.6200342", "0.62000835", "0.6199429", "0.6198043", "0.619501" ]
0.0
-1
This function is supposed to generate group names such as 'A', 'B', .., 'AA', 'AB', 'AC' ..
function new_group_name(pwd_groups) { //Start at 'A' var init_group = 65; var new_name_detected = false; var new_name_arr = []; new_name_arr.push(init_group); while (!new_name_detected) { var char_new_name_arr = []; for (var i = 0; i < new_name_arr.length; i++) { char_new_name_arr.push(String.fromCharCode(new_name_arr[i])); } var new_name = char_new_name_arr.reverse().join(""); new_name_detected = !(('Grp ' + new_name) in pwd_groups); if (!new_name_detected) { var array_adjusted = false; while (!array_adjusted) { for (var j = 0; j < new_name_arr.length; j++) { new_name_arr[j] += 1; if (new_name_arr[j] <= 90) { array_adjusted = true; break; } else { new_name_arr[j] = 65; } } if (!array_adjusted) { new_name_arr.push(init_group); array_adjusted = true; } }//Adjust array infinite while } else { return new_name; } }//Find new group name infinite while }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "generateGroupID() {\n\t\treturn (Math.random() * 999).toString();\n\t}", "function prefixCategoryOptionGroups() {\n\tif (!metaData.categoryOptionGroups) return;\n\tfor (var group of metaData.categoryOptionGroups) {\n\t\tgroup.name = currentExport._prefix + \" \" + group.name;\n\t}\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x;\n /* get a char and divide by alphabet-length */\n for (x = Math.abs(code); x > charsLength; x = (x / charsLength) | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n }", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n /* get a char and divide by alphabet-length */\n\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n} // ", "function getGroupName (listUser,username_create_group){\n\t\tvar arrUsername = [];\n\t\tlistUser.each(function (){\n\t\t\tarrUsername.push($(this).text());\n\t\t});\n\t\tarrUsername.push(username_create_group);\n\t\tarrUsername.sort();\n\t\treturn arrUsername.toString();\n\t}", "function generateAlphabeticName(code) {\n var name = '';\n var x;\n /* get a char and divide by alphabet-length */\n\n for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x;\n /* get a char and divide by alphabet-length */\n\n for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x;\n /* get a char and divide by alphabet-length */\n\n for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x;\n /* get a char and divide by alphabet-length */\n\n for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n}", "function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function generateAlphabeticName(code) {\n var name = '';\n var x = void 0;\n\n /* get a char and divide by alphabet-length */\n for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return getAlphabeticChar(x % charsLength) + name;\n}", "function randomString(groupCount, groupLen) {\n let o = [];\n for (let i = 0; i < groupCount; ++i) {\n let group = [];\n for (let j = 0; j < groupLen; ++j) {\n group.push(Math.round(Math.random() * 32).toString(32));\n }\n o.push(group.join(''));\n }\n\n return o.join('-');\n }", "function buildGroupsTemplate (groups) {\n return groups.reduce((acc, group) => {\n acc[group] = []\n return acc\n }, {})\n}", "function setGroup(returnedNodes){\n\tif(returnedNodes.value == 'character70'){\n\t\treturn 'NamedCharacter70';\n\t}\n\tif(returnedNodes.value == 'character34'){\n\t\treturn 'NamedCharacter34';\n\t}\n\treturn //This is the default group.\n}", "function bandNameGenerator(str) {\n let bandName = '';\n if (str.charAt(0) === str.charAt(str.length -1)) {\n bandName = str.slice(0, -1);\n bandName += str;\n return bandName.charAt(0).toUpperCase() + bandName.slice(1);\n } else {\n bandName = 'The ' + (str.charAt(0).toUpperCase() + str.slice(1));\n console.log(bandName);\n return bandName;\n }\n}", "function nameGroup(groupID,label){\n groups[groupID].name=label;\n storeGroups();\n}", "function generateName() {\n const format = [\n '\"The \"+pick(adjective)',\n 'pick(adjective)+\" \"+pick(adjective)',\n 'pick(adjective)+\" \"+pick(noun)',\n 'pick(adjective)+\" \"+pick(place)',\n '\"2 \"+pick(adjective)+\" 2 \"+pick(verb)',\n 'pick(adjective)+\" 4 Life\"',\n '\"Team \"+pick(adjective)',\n '\"Team \"+pick(noun)',\n '\"Team \"+pick(place)',\n 'pick(noun)+\" With \"+pick(adjective)+\" \"+pick(noun)',\n 'pick(noun)+\" With \"+pick(noun)',\n 'pick(noun)+\" From \"+pick(place)',\n 'pick(noun)+\" \"+pick(verb)',\n 'pick(noun)+\" Don’t \"+pick(verb)',\n 'pick(place)+\" \"+pick(noun)',\n 'pick(place)+\"’s \"+pick(adjective)+\" \"+pick(noun)',\n 'pick(place)+\"’s Finest\"',\n 'pick(verb)+\" & \"+pick(verb)',\n '\"Keep Calm & \"+pick(verb)',\n ],\n adjective = [ // the…\n 'Delinquent',\n 'Hilary’s-Own',\n 'Surprising',\n 'Unstoppable',\n 'Great-Canadian',\n 'Trivial',\n 'Undefeated',\n 'Ghetto',\n 'Awesome',\n 'Mighty',\n 'Ratchet',\n 'Neglectful',\n 'Supreme',\n 'Almost-Ready-To-Play',\n 'PC',\n '[TRIGGERED]',\n 'Microagressive',\n 'Brave',\n 'Top-Secret',\n 'Metric',\n 'Hood-Rich',\n 'Ballin’',\n 'Twerking-Class',\n 'Raging',\n 'Trill',\n '#Winning',\n 'Twerking',\n 'Micro-Managing',\n 'Dank',\n 'Privileged',\n 'Omniscient',\n 'College-Educated',\n 'Real',\n 'Royal',\n ],\n noun = [ // the…\n 'Beavers',\n 'SJWs',\n 'Buffaloons',\n 'WOEs',\n 'Crew',\n 'Executives',\n 'Squad',\n 'Cultural Appropriation',\n 'Tumblristas',\n 'Patriots',\n 'Alex Trebek',\n 'Yankees',\n 'Canucks',\n 'Babes',\n 'OGs',\n '1%',\n 'Wikipedians',\n 'Thugs',\n 'Gangsters',\n 'Microagressions',\n 'Warriors',\n 'Trigger Warning',\n 'Bernie Sanders',\n ],\n place = [ // from…\n 'Toronto',\n 'Buffalo',\n 'America',\n 'Canada',\n 'Earth',\n 'Tumblr',\n 'The Internet',\n 'The Past',\n 'Space',\n 'Nowhere',\n 'The Right-Side-of-History',\n 'The Trap',\n 'Wikipedia',\n 'The Streets',\n 'The Occident',\n 'The 6',\n 'Rape Culture',\n 'First-Class',\n 'An Alternate Universe',\n ],\n verb = [ // who…\n 'Destroy',\n 'Can’t Even',\n 'Win',\n 'Have Guns',\n 'Get Jokes',\n 'Know Things',\n 'Trivialize',\n 'Lift',\n 'Guess Well',\n 'Lawyer Up',\n 'Care',\n ];\n\n function pick(id) {\n return id[Math.floor(Math.random() * id.length)];\n }\n\n return eval(format[Math.floor(Math.random() * format.length)]);\n}", "function armour_cg_outletter(l) {\r\n if (acgg.length >= 5) {\r\n armour_cg_outgroup();\r\n }\r\n acgg += l;\r\n}", "function nameGenerator(arr){\n var name = [];\n var x = ''; //variable initialized as string to store alphabets\n \n //Checks what alphabet is encoded for each number in the number's list\n for (var i = 0; i < arr.length; i++){\n if(arr[i] == 1){\n name.push('A'); \n }\n else if(arr[i] == 2){\n name.push('B'); \n }\n else if(arr[i] == 3){\n name.push('C'); \n }\n else if(arr[i] == 4){\n name.push('D'); \n }\n else if(arr[i] == 5){\n name.push('E'); \n }\n else if(arr[i] == 6){\n name.push('F'); \n }\n else if(arr[i] == 7){\n name.push('G'); \n }\n else if(arr[i] == 8){\n name.push('H'); \n }\n else if(arr[i] == 9){\n name.push('I'); \n }\n else if(arr[i] == 10){\n name.push('J'); \n }\n else if(arr[i] == 11){\n name.push('K');\n }\n else if(arr[i] == 12){\n name.push('L'); \n }\n else if(arr[i] == 13){\n name.push('M'); \n }\n else if(arr[i] == 14){\n name.push('N'); \n }\n else if(arr[i] == 15){\n name.push('O'); \n }\n else if(arr[i] == 16){\n name.push('P'); \n }\n else if(arr[i] == 17){\n name.push('Q'); \n }\n else if(arr[i] == 18){\n name.push('R'); \n }\n else if(arr[i] == 19){\n name.push('S'); \n }\n else if(arr[i] == 20){\n name.push('T'); \n }\n else if(arr[i] == 21){\n name.push('U'); \n }\n else if(arr[i] == 22){\n name.push('V'); \n }\n else if(arr[i] == 23){\n name.push('W'); \n }\n else if(arr[i] == 24){\n name.push('X'); \n }\n else if(arr[i] == 25){\n name.push('Y'); \n } \n else if(arr[i] == 26){\n name.push('Z'); \n }\n }\n \n //Combines all the alphabets to make one single word\n for (var i = 0; i < name.length;i++){\n x += name[i];\n }\n return x;\n}", "function d3_format_group(value) {\n var i = value.lastIndexOf(\".\"),\n f = i >= 0 ? value.substring(i) : (i = value.length, \"\"),\n t = [];\n while (i > 0) t.push(value.substring(i -= 3, i + 3));\n return t.reverse().join(\",\") + f;\n}", "function d3_format_group(value) {\n var i = value.lastIndexOf(\".\"),\n f = i >= 0 ? value.substring(i) : (i = value.length, \"\"),\n t = [];\n while (i > 0) t.push(value.substring(i -= 3, i + 3));\n return t.reverse().join(\",\") + f;\n}", "function generateName(list) {\n let total = parseInt(list[0][1])\n let sample = Math.floor(name_prng() * total);\n for (i = 1; i < list.length && sample > 0; i++) {\n sample -= parseInt(list[i][1])\n }\n return list[i][0]\n }", "function createGroups(arr, numGroups) {\n\tconst perGroup = Math.ceil(arr.length / numGroups);\n\n\treturn new Array(numGroups)\n\t\t.fill('')\n\t\t.map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));\n}", "function createGroup(g) {\n // Create the main button element\n var group = document.createElement('button');\n group.className = 'group';\n group.id = 'uniqueGroupId-' + g.name;\n\n // Create a span to contain the name on the left side of the button\n var nameSpan = document.createElement('span');\n nameSpan.className = 'alignleft'\n nameSpan.textContent = g.name;\n group.appendChild(nameSpan);\n\n // Create a span to contain the tab count on the right side of the button\n var countSpan = document.createElement('span');\n countSpan.className = 'alignright'\n countSpan.textContent = g.tabs.length;\n group.appendChild(countSpan);\n\n // Sets mouse interactions\n group.onclick = function(){openGroup(g.name)};\n\n // Adds to popup\n groupDiv.appendChild(group);\n}", "function generateName() {\n var sRnd = '';\n var sChrs = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\";\n for (var i = 0; i < 5; i++) {\n var randomPoz = Math.floor(Math.random() * sChrs.length);\n sRnd += sChrs.substring(randomPoz, randomPoz + 1);\n }\n return sRnd;\n}", "function list_to_groups(list) {\r\n\r\n\t// if our list is a single item, just return it\r\n\tif (list.length === 1)\r\n\t\treturn [list];\r\n\r\n // setup our postfix of Xs\r\n let postfix = \"X\".repeat((list[0].match(/X/g) || []).length);\r\n\r\n // modify the group to strip the postfix\r\n list = list.map(e => e.replace(postfix, \"\"));\r\n\r\n\t// use the first pattern as our anchor to which we compare the next pattern to\r\n\tlet anch = list[0];\r\n\r\n\t// establish our pattern groups array and set the group index counter to 0\r\n\tlet groups = [];\r\n\tlet g_index = 0;\r\n\r\n\t// surely we'll have at least one group to work with, so let's create it\r\n\tgroups.push([]);\r\n\r\n\t// we'll use our anchor pattern as the first member of our first group\r\n\tgroups[g_index].push(anch + postfix);\r\n\r\n\t// starting at the second pattern of the list, iterate over all patterns to see which group they belong to\r\n\tfor (let i = 1, j = list.length; i < j; i++) {\r\n\r\n\t\t// our current pattern\r\n\t\tlet curr = list[i];\r\n\r\n\t\t// is the current pattern in the same tens group as the anchor pattern?\r\n\t\t// we do this by comparing the patterns, left justified, up to, but not including the ones place\r\n\t\tif (curr.substring(0, curr.length - 1) === anch.substring(0, anch.length - 1)) {\r\n\r\n\t\t\t// yes, then we group them togther\r\n\t\t\tgroups[g_index].push(curr + postfix);\r\n\r\n\t\t} else {\r\n\r\n\t\t\t// no, then we close off the current group, start a new group, and update our anchor to the current pattern\r\n\t\t\tgroups.push([]);\r\n\t\t\tg_index++;\r\n\t\t\tgroups[g_index].push(curr + postfix);\r\n\t\t\tanch = curr;\r\n\r\n\t\t}\r\n\t}\r\n\r\n\treturn groups;\r\n}", "function make_name(a, n) {\n var sub = [];\n for (var i = 0; i < n; i++) {\n sub.push(a[i].toString());\n }\n return sub.join('.');\n}", "function generateName() {\n\n // random first name\n var possibleNames = ['Sophia', 'Jackson', 'Emma', 'Aiden', 'Olivia', 'Lucas', 'Ava', 'Liam', 'Mia', 'Noah', 'Isabella', 'Ethan', 'Riley', 'Mason', 'Aria', 'Caden', 'Zoe', 'Oliver', 'Charlotte', 'Elijah', 'Lily', 'Grayson', 'Layla', 'Jacob', 'Amelia', 'Michael', 'Emily', 'Benjamin', 'Madelyn', 'Carter', 'Aubrey', 'James', 'Adalyn', 'Jayden', 'Madison', 'Logan', 'Chloe', 'Alexander'];\n var first = possibleNames[Math.floor(Math.random() * possibleNames.length)];\n\n // random last name first character\n var possibleLastNameChar = ['A', 'B', 'C', 'D', 'F', 'G', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'V', 'W', 'Y'];\n var last = possibleLastNameChar[Math.floor(Math.random() * possibleLastNameChar.length)];\n\n // return result\n return first + \" \" + last + \".\";\n}", "function makeid()\r\n{\r\n var text = \"\";\r\n var possibleChar = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\r\n var possibleDigit = \"0123456789\";\r\n\r\n getChar = function(list) {\r\n return list.charAt(Math.floor(Math.random() * list.length));\r\n }\r\n\r\n for( var i=0; i < 3; i++ ) {\r\n text += getChar(possibleChar);\r\n }\r\n\r\n text += '-';\r\n\r\n for( var i=0; i < 3; i++ ) {\r\n text += getChar(possibleDigit);\r\n }\r\n\r\n return text;\r\n}", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "function manipulateName(name) {\n\tvar joinName = name.join('').toUpperCase();\n\tconsole.log(joinName);\n\n\tvar joinName = name.join('').toUpperCase();\n\tvar letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\tvar acc = 0;\n\tvar emptyArr = [];\n\n\tfor (var i = 0; i < letters.length; i++) {\n\t\tvar match = joinName.indexOf(letters[i]);\n\t\t//console.log(letters[i] + ' ' + match);\n\t\tif (match > -1) {\n\t\t\t//console.log('La letra ' + letters[i] + ' se repite ' + acc + ' veces');\n\t\t\temptyArr.push(letters[i])\n\t\t}\n\t}\n\tconsole.log(emptyArr);\n\n\tfor (var i = 0; i < emptyArr.length; i++) {\n\t\tvar repeat = 0;\n\t\tfor (var j = 0; j < joinName.length; j++) {\n\t\t\tif (emptyArr[i] === joinName[j]) {\n\t\t\t\trepeat++;\n\t\t\t}\n\t\t}\n\t\tconsole.log('la letra ' + emptyArr[i] + ' se repite ' + repeat);\n\t}\n}", "function d3_v3_format_group(value) {\n var i = value.lastIndexOf(\".\"),\n f = i >= 0 ? value.substring(i) : (i = value.length, \"\"),\n t = [];\n while (i > 0) t.push(value.substring(i -= 3, i + 3));\n return t.reverse().join(\",\") + f;\n}", "function generateGroup(req,res,callback) { //Generate a group name. Create new entry in collection group with the name and other attributs. the name must be used as url: api/group/\"nameGenerated\"\n var decoded = jwtDecode(req.headers.authorization.split(' ')[1]);\n var userid = decoded._id;\n req = req.body;\n \n const newGroup = new Group({\n \"fileId\" : req.fileId,\n \"name\" : shortid.generate(),\n \"userId\" : userid,\n \"status\" : false,\n \"statusGlobal\" : false\n }).save();\n \n newGroup.then(function(result) {\n callback(res, result);\n })\n}", "function makeRandomName()\n{\n\tvar text = \"\";\n\tvar possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n\tfor( var i=0; i < 10; i++ )\n\t text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n\treturn text;\n}", "function CreateImgName(longName,ending){\n if(longName.length > 1 ){\n switch(ending){\n case \"Weight\":\n case \"Patrol\":\n longName = longName.slice(0,-2);\n longName = longName.join().replace(/,/g, \" \");\n break;\n case \"Extended\": \n case \"Hammerless\": \n case \"Perosa\": \n case \"Shotgun\": \n case \"Artillerie\": \n case \"Auto\": \n case \"Patrol\": \n case \"SMG\": \n case \"Degtyarev\": \n case \"M1918A2\": \n case \"Revolver\": \n case \"Pistol\": \n case \"Automatic\": \n case \"MkVI\": \n case \"08-15\": \n case \"1903\": \n case \"1915\": \n case \"M1914\": \n case \"M1918\": \n case \"M1870\": \n case \"M1912\": \n case \"1889\": \n longName = longName.join().replace(/,/g, \" \"); \n break;\n default:\n longName = longName.slice(0,-1);\n longName = longName.join().replace(/,/g, \" \");\n }\n }\n return longName;\n}", "function formatGroups(res){\n var groups = \"\";\n for(x in res){\n groups += \n '<a class=\"courseLink\" href=\"/Group/'+res[x].studyGroupId+'\">'+\n '<div class=\"course-container2\">'+\n '<h5 class=\"courseCode2\">'+res[x].studyGroupName+'</h5>'+\n '<span class=\"badge badge-primary profile-student-count\">'+res[x].course+'</span>'+\n '</div>'+\n '</a>';\n }\n if(groups != \"\"){\n return groups;\n }\n else{\n return \"<p class='noTutorSesh'>No groups added</p>\";\n }\n \n}", "function gid() {\n return '_' + Math.random().toString(36).substr(2, 9);\n }", "addGroup() {\n\t\t//make a random group id\n\t\tlet gid = generateGroupID();\n\n\t\t//keep trying till a unique one is made\n\t\twhile(gid in this.groups) {\n\t\t\tgid = generateGroupID();\n\t\t}\n\n\t\tthis.groups[gid] = new Group();\n\n\t\treturn gid;\n\t}", "function alterGroupNaming(){\n buttons = document.getElementsByClassName('groupButtonForGraph')\n for(button of buttons){\n button.innerHTML\n if(button.innerHTML == 'FunctionalRequirementAndBehaviour'){\n button.innerHTML = 'Functional requirement & behaviour'\n }\n else if(button.innerHTML == 'UseCase'){\n button.innerHTML = 'Use case'\n }\n else if(button.innerHTML == 'UserStory'){\n button.innerHTML = 'User story'\n }\n else if(button.innerHTML == 'NonFunctionalRequirementAndBehaviour'){\n button.innerHTML = 'Non-functional requirement & behaviour'\n }\n else if(button.innerHTML == 'RequirementGeneral'){\n button.innerHTML = 'Requirements - general'\n }\n else if(button.innerHTML == 'Document_Organisation'){\n button.innerHTML = 'Document organisation'\n }\n else if(button.innerHTML == 'DevelopmentPractice'){\n button.innerHTML = 'Development practice'\n }\n else if(button.innerHTML == 'U-Architecture'){\n button.innerHTML = 'UI design - architecture'\n }\n else if(button.innerHTML == 'U-Implementation'){\n button.innerHTML = 'UI design - implementation'\n }\n else if(button.innerHTML == 'S-Architecture'){\n button.innerHTML = 'Structure - architecture'\n }\n else if(button.innerHTML == 'S-TechnologySolution'){\n button.innerHTML = 'Structure - technology solution'\n }\n else if(button.innerHTML == 'S-SourceCode'){\n button.innerHTML = 'Structure - source code'\n }\n else if(button.innerHTML == 'B-Architecture'){\n button.innerHTML = 'Behaviour - architecture'\n }\n else if(button.innerHTML == 'B-TechnologySolution'){\n button.innerHTML = 'Behaviour - technology solution'\n }\n else if(button.innerHTML == 'B-General'){\n button.innerHTML = 'Behaviour - general'\n }\n else if(button.innerHTML == 'D-Architecture'){\n button.innerHTML = 'Data - architecture'\n }\n else if(button.innerHTML == 'D-Implementation'){\n button.innerHTML = 'Data - implementation'\n }\n }\n}", "function makeid() {\n var text = \"\";\n var possibleAlpha = \"ABCDEFGHJKLMNPQRSTUVWXYZ\";\n var possibleNum = \"0123456789\";\n var possibleEnding = \"ABCDEFGHJKLMNPQRSTUVWXYZ0123456789\";\n text += possibleAlpha.charAt(Math.floor(Math.random() * possibleAlpha.length));\n\n for (var i = 0; i < 5; i++){\n text += possibleNum.charAt(Math.floor(Math.random() * possibleNum.length));\n }\n\n text += possibleEnding.charAt(Math.floor(Math.random() * possibleEnding.length));\n\n return text;\n}", "function NP_generate_input() {\n var grp = $('#uneven_grp').val();\n if (grp >= 1) {\n for (var inp_p = 1; inp_p <= grp; inp_p++) {\n var divtmp = document.createElement('div');\n var spantmp = document.createElement('span');\n var inputtmp = document.createElement('input');\n\n divtmp.className = ('input-group input-group-sm mb-3')\n spantmp.className = ('input-group-text');\n var spanit = ('Group ' + inp_p);\n spantmp.innerText = (spanit);\n var inputid = ('grp_sm_' + inp_p);\n inputtmp.id = (inputid)\n inputtmp.className = ('form-control');\n inputtmp.type = ('number');\n inputtmp.placeholder = ('# peoples in group');\n inputtmp.setAttribute('aria-label', '# peoples in group');\n\n document.getElementById('dyn_uneven').appendChild(divtmp);\n divtmp.appendChild(spantmp);\n divtmp.appendChild(inputtmp);\n }\n }\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 groupBy(s, n) {\r\n var result = \"\";\r\n for (var i = 0; i < s.length; i++) {\r\n if (i % n == 0 && i > 0) {\r\n result += \" \";\r\n }\r\n result += s[i];\r\n }\r\n return result;\r\n}", "function drawAlgoNames(){\n let buff = 3;\n for(let x = 0; x < algos.length; ++x){\n drawLetters(algos[x].name, 0, 1 + x * (buff+tc.length), false);\n }\n}", "function getSelectFieldGroupString(name, gid) {\n let first = true\n let base = `\n SELECT\n gid\n FROM\n GROUPS\n WHERE `\n\n if (name) {\n base += first ? `name = '${name}'` : `OR name = '${name}'`\n first = false\n }\n if (gid) {\n base += first ? `gid = '${gid}'` : `OR gid = '${gid}'`\n first = false\n }\n\n base += `;`\n\n console.log(base)\n\n return base\n}", "obtainGroupsNamesID (callback) {\n this.retrieveGroups((err, groups) => {\n if (err) {\n if (_.isFunction(callback)) {\n callback(err)\n }\n } else {\n if (_.isFunction(callback)) {\n groups = _.map(groups, (group) => ({\n 'id': group.id,\n 'name': group.name\n }))\n callback(null, groups)\n }\n }\n })\n }", "function makeAcronym(arry) {\nvar n = []\nvar nstr = []\nvar nestr = []\nvar arry = arry.toUpperCase()\nfor (var i = 0; i < arry.length; i++) {\n var list = arry[i]\n if (list === ' ') {\n var x = i\n n.push(x)\n }\n}\nvar y = n[0]\nvar str = arry.slice(0, y)\nnstr.push(str)\nfor (var z = 0; z < n.length; z++) {\n var a = n[z]\n var b = n[z + 1]\n var strs = arry.slice((a + 1), b)\n nstr.push(strs)\n}\nfor (var i = 0; i < nstr.length; i++) {\n var listx = nstr[i]\n var st = listx[0]\n nestr.push(st)\n var acr = nestr.join('')\n}\nreturn acr\n}", "static NoGroupName() {\n return `Sorry! We didn't catch that. Try again?`;\n }", "function accum(s) {\n\tlet result = [];\n \n for(let i = 0; i < s.length; i++) {\n let test = s[i].repeat(i + 1);\n let bucket = test.slice(0, 1).toUpperCase() + test.slice(1).toLowerCase();\n result.push(bucket);\n }\n \n return result.join('-');\n}", "function createEstablishmentCode() {\n let _lText = '';\n let _lPossible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let _i = 0; _i < 9; _i++) {\n _lText += _lPossible.charAt(Math.floor(Math.random() * _lPossible.length));\n }\n return _lText;\n}", "createCardNamesArray() {\n return (function idArray() {\n const array = [];\n const suites = ['Clubs', 'Diamonds', 'Hearts', 'Spades'];\n suites.forEach((suite) => {\n for (let i = 1; i < 14; i += 1) {\n switch (i) {\n case 1:\n array.push(`Ace-${suite}`);\n break;\n case 11:\n array.push(`Jack-${suite}`);\n break;\n case 12:\n array.push(`Queen-${suite}`);\n break;\n case 13:\n array.push(`King-${suite}`);\n break;\n default:\n array.push(`${i}-${suite}`);\n break;\n }\n }\n });\n\n return array;\n }());\n }", "function makeid()\n {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n for( var i=0; i < 5; i++ )\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return text;\n }", "function makeGroup() {\n groupClass = 'groups';\n var length = document.getElementsByClassName(groupClass).length;\n var previousItem = document.getElementsByClassName(groupClass).item(length-1);\n var index = 0;\n // handles getting the class index out of the previous div, so we don't repeat indices on delete->add\n if (previousItem != null) {\n parent = previousItem.parentElement;\n splitArray = parent.id.split(\"-\");\n index = parseInt(splitArray[1]) + 1;\n }\n \n var div = document.createElement('div');\n div.id = 'group-' + index;\n\n var newGroup = document.createElement('h4');\n newGroup.innerHTML = 'Group';\n newGroup.className = groupClass;\n div.appendChild(newGroup);\n\n var deleteGroupButton = document.createElement('input');\n deleteGroupButton.id = 'delete-group-' + index;\n deleteGroupButton.type = 'button';\n deleteGroupButton.value = 'Delete Group';\n deleteGroupButton.className = 'deleteGroupButton';\n deleteGroupButton.onclick = function() { deleteGroup(div.id); };\n div.appendChild(deleteGroupButton);\n \n var addMemButton = document.createElement('input');\n addMemButton.id = 'add-mem-group-' + index;\n addMemButton.type = 'button';\n addMemButton.value = 'Add Member';\n addMemButton.className = 'addMemButton';\n addMemButton.onclick = function() { addMember(div.id); };\n div.appendChild(addMemButton);\n\n return div;\n}", "function convertDiagrammGoupe() {\r\n var groups = []\r\n for (var idx = 0 ; idx < FMSName.length; idx++) {\r\n groups.push({\r\n id: FMSName[idx],\r\n content: FMSName[idx],\r\n className: FMSName[idx] + \"-style\",\r\n options: {\r\n drawPoints: false,\r\n interpolation: false,\r\n },\r\n });\r\n }\r\n return groups;\r\n}", "function createAlphabet(){\n // Creates an array with the letters of the alphabet\n let letters = 'abcdefghijklmnopqrstuvwxyz'.split('');\n for(let i in letters) {\n alphabet.append($(`<div class=\"alphabet\"><p>${letters[i].toUpperCase()}</p></div>`));\n }// for loop\n }// end createAlphabet", "function generateUniqueName() {\n return uuid().replace(/-/g, '')\n .replace(/1/g, 'one')\n .replace(/2/g, 'two')\n .replace(/3/g, 'three')\n .replace(/4/g, 'four')\n .replace(/5/g, 'five')\n .replace(/6/g, 'six')\n .replace(/7/g, 'seven')\n .replace(/8/g, 'eight')\n .replace(/9/g, 'nine')\n .replace(/0/g, 'zero');\n}", "function get_group_name(group_description, g_data1, g_data2)\n{\n var group_name = \"GROUP_NAME\";\n for (k=0; k<g_data1.length; k++)\n {\n if ( String(g_data2[k]) === group_description )\n {\n group_name = String(g_data1[k]);\n break;\n }\n }\n \n return group_name;\n}", "function getname() {\r\n //getting the 'order'\r\n //than making it bigger by 1\r\n //convert it to string\r\n //than add 'piece' to it for avoiding confusion between pieces and pins\r\n return ((order++).toString() + \"piece\")\r\n}", "function getTimeGroupName(groupSeqNum){\r\n\tvar grpMod = aa.timeAccounting.getTimeGroupTypeModel().getOutput();\r\n\tgrpMod.setTimeGroupSeq(groupSeqNum);\r\n\tvar grps = aa.timeAccounting.getTimeGroupTypeModels(grpMod).getOutput();\r\n\treturn grps[0].getTimeGroupName();\r\n}", "function createLettersHtml() {\r\n var html = [];\r\n for (var i = 1; i < letters.length; i++) {\r\n if (html.length === 0) {\r\n html.push('<a class=\"all\" href=\"#\">'+ opts.allText + '</a><a class=\"_\" href=\"#\">0-9</a>');\r\n }\r\n html.push('<a class=\"' + letters[i] + '\" href=\"#\">' + ((letters[i] === '-') ? '...' : letters[i].toUpperCase()) + '</a>');\r\n }\r\n return '<div class=\"ln-letters\">' + html.join('') + '</div>' + ((opts.showCounts) ? '<div class=\"ln-letter-count listNavHide\">0</div>' : '');\r\n // Remove inline styles, replace with css class\r\n // Element will be repositioned when made visible\r\n }", "function stringCreation(str) {\n var pair = \"\";\n for(var i = 0; i <= str.length; i++){\n if(str[i] === \"C\"){\n pair = pair + \"G\";\n } else if(str[i] === \"G\"){\n pair = pair + \"C\";\n } else if (str[i] === \"A\"){\n pair = pair + \"T\";\n } else if (str[i] === \"T\"){\n pair = pair + \"A\";\n }\n }\n return pair;\n}", "function makeid() {\n var text = '';\n var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n \n for (var i = 0; i < 5; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n return text;\n }", "function filterMatrixGroupName(name) {\r\n\tvar name = filterFieldName(trim(name));\r\n\t// Force 60 chars or less (and then remove any underscores on end)\r\n\tif (name.length > 60) {\t\t\t\t\t\t\r\n\t\tname = filterFieldName(name.substr(0,60));\r\n\t}\r\n\treturn name;\r\n}", "function armour_cg_outgroup() {\r\n if (acgcl.length > maxLineLength) {\r\n acgt += acgcl + \"\\n\";\r\n acgcl = \"\";\r\n }\r\n if (acgcl.length > 0) {\r\n acgcl += \" \";\r\n }\r\n acgcl += acgg;\r\n acgg = \"\";\r\n}", "function gen_uppercase() {\r\n return gen_lowercase().toUpperCase();\r\n}", "function getSubgen(name, getLongName) {\r\n var subgens = {\r\n \"Red/Blue\": \"1-0\",\r\n \"RB\": \"1-0\",\r\n \"Yellow\": \"1-1\",\r\n \"RBY\": \"1-1\",\r\n \"RBY Stadium\": \"1-2\",\r\n \"Stadium\": \"1-2\",\r\n \"RBY Tradebacks\": \"1-3\",\r\n \"Gold/Silver\": \"2-0\",\r\n \"GS\": \"2-0\",\r\n \"Crystal\": \"2-1\",\r\n \"GSC\": \"2-1\",\r\n \"GSC Stadium\": \"2-2\",\r\n \"Stadium 2\": \"2-2\",\r\n \"Stadium2\": \"2-2\",\r\n \"Ruby/Sapphire\": \"3-0\",\r\n \"RS\": \"3-0\",\r\n \"Colosseum\": \"3-1\",\r\n \"FireRed/LeafGreen\": \"3-2\",\r\n \"FRLG\": \"3-2\",\r\n \"RSE\": \"3-3\",\r\n \"Emerald\": \"3-3\",\r\n \"XD\": \"3-4\",\r\n \"Diamond/Pearl\": \"4-0\",\r\n \"DP\": \"4-0\",\r\n \"Platinum\": \"4-1\",\r\n \"DPPt\": \"4-1\",\r\n \"HeartGold/SoulSilver\": \"4-2\",\r\n \"HGSS\": \"4-2\",\r\n \"Black/White\": \"5-0\",\r\n \"BW\": \"5-0\",\r\n \"Black/White 2\": \"5-1\",\r\n \"BW2\": \"5-1\",\r\n \"XY\": \"6-0\",\r\n \"Omega Ruby/Alpha Sapphire\": \"6-1\",\r\n \"ORAS\": \"6-1\",\r\n \"1\": \"1-3\",\r\n \"2\": \"2-2\",\r\n \"3\": \"3-4\",\r\n \"4\": \"4-2\",\r\n \"5\": \"5-1\",\r\n \"6\": \"6-1\"\r\n };\r\n if (getLongName) {\r\n for (var x in subgens) {\r\n if (cmp(name,subgens[x])) {\r\n return x;\r\n }\r\n }\r\n }\r\n else {\r\n for (var y in subgens) {\r\n if (cmp(name,y)) {\r\n return subgens[y];\r\n }\r\n }\r\n }\r\n return false;\r\n}", "function makeGroup(key, keyNamePairs){\n var headerPlusKey = \"OK\" + key;\n var keys = keyNamePairs.map(x => [x[0], crypto.encrypt(headerPlusKey, x[1], props.getPriv)])\n\n var group = {\n name: groupName,\n adminName: props.getName,\n keys: keys\n }\n\n console.log(group)\n return group;\n }", "function generateAlphaNumericDash63Name(name) {\n let valid = /^[a-zA-Z0-9](-*[a-zA-Z0-9])*/ \n if (name.match(valid) && name.length <= 63) {\n return name;\n }\n \n let hashPart = shajs('sha256').update(name).digest('base64').replace(/[\\W_]+/g,'').substring(0,24); // remove all non-alphanumeric (+=/) then truncate to 144 bits\n let namePart = getAlphaNumericDash(name).substring(0,63-hashPart.length-2)+'-'; // replace all non-alphanumeric with - and truncate to the proper length\n let result = namePart + hashPart;\n while (result.startsWith('-')) { // can't start with -\n result = result.substring(1);\n }\n return result;\n}", "function NP_Main() {\n var namelist = document.getElementById('namesv').value.trim().split('\\n');\n var cleannames = namelist.filter(function(el) { return el; });\n var maxname = cleannames.length;\n var ppl = $('#peoplev').val();\n var grp = $('#groupv').val();\n\n if (namelist != \"\") {\n if (document.getElementById('uneven_ck').checked) {\n cntmode = 5\n // al_ert('mode = ' + cntmode)\n // this one is for uneven groups\n if (true) {\n\n }\n NP_clear_result()\n var grp_auto = $('#uneven_grp').val()\n var ctr = 0\n var people_in_groups = []\n var allppl = 0\n var allgrp = grp_auto\n\n for (var xa = 0; xa <= allgrp; xa++) {\n var jdl = ('#grp_sm_' + (xa+1));\n ads = Number($(jdl).val())\n allppl = allppl + ads\n if (maxname >= allppl) {\n people_in_groups.push(ads-1)\n } else {\n people_in_groups.push((ads-1) - (allppl - maxname))\n }\n }\n\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>Group ' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups[ctr]; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n // ======================================================================\n } else if (document.getElementById('group_ck').checked) {\n if (ppl >= 1) {\n if (grp > 1) {\n cntmode = 3\n // al_ert('mode = ' + cntmode)\n // this one is for if both group and people has value\n // ======================================================================\n } else {\n cntmode = 1\n // al_ert('mode = ' + cntmode)\n // this one is for people only\n if (maxname > ppl) {\n NP_clear_result()\n var grp_auto = Math.round(maxname / ppl)\n var ctr = 0\n var people_in_groups = []\n\n if ((grp_auto * ppl) > maxname && (grp_auto * ppl) != maxname) {\n NP_alert_show()\n var ads = 0\n var leftover = (grp_auto * ppl) - maxname\n // al_ert('remove ' + leftover + ' person')\n for (var xxx = 0; xxx < leftover; xxx++) {\n ads = ads + 1\n var namesum = maxname\n for (var xx = 0; xx < grp_auto; xx++) {\n if ((leftover >= 1) && (((ppl-1) - ads) >= (ppl-1))) {\n people_in_groups.push((ppl-1) - ads)\n leftover = leftover - 1\n // console.lo_g('leftover to remove ' + leftover);\n } else {\n if (ppl < namesum) {\n people_in_groups.push(ppl-1)\n namesum = (namesum - ppl)\n // console.lo_g('namesum ' + namesum);\n } else {\n people_in_groups.push(namesum-1)\n people_in_groups.reverse()\n }\n }\n }\n people_in_groups.reverse()\n }\n } else if ((grp_auto * ppl) == maxname) {\n for (var xx = 0; xx < grp_auto; xx++) {\n people_in_groups.push(ppl-1)\n }\n } else {\n NP_alert_show()\n var ads = 0\n var leftover = maxname - (grp_auto * ppl)\n grp_auto = grp_auto + 1\n // al_ert('add ' + leftover + ' person')\n for (var xxx = 0; xxx < leftover; xxx++) {\n ads = ads + 1\n var namesum = maxname\n for (var xx = 0; xx < grp_auto; xx++) {\n // console.lo_g(grp_auto);\n if ((leftover >= 1) && (((ppl-1) + ads) <= (ppl-1))) {\n people_in_groups.push((ppl-1) + ads)\n leftover = leftover - 1\n // console.lo_g('leftover to add ' + leftover);\n } else {\n if (ppl < namesum) {\n // console.lo_g('namesum3 ' + namesum);\n people_in_groups.push(ppl-1)\n namesum = (namesum - ppl)\n } else {\n people_in_groups.push(namesum-1)\n people_in_groups.reverse()\n }\n }\n }\n people_in_groups.reverse()\n }\n }\n\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>Group ' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups[ctr]; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n // // console.lo_g('sisa ' + cleannames);\n\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n } else {\n NP_alert_show()\n NP_clear_result()\n var namepool = []\n var people_in_groups = maxname-1\n for (var i = people_in_groups; i >= 0; i--) {\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n\n var lbltmp = document.createElement('label');\n var oltmp = document.createElement('ol');\n lbltmp.innerHTML = ('<b>Group 1</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n oltmp.innerHTML = (namepool.join('\\n'));\n\n }\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n // ======================================================================\n }\n } else if (grp >= 1 && grp != \"\") {\n cntmode = 2\n // al_ert('mode = ' + cntmode)\n // this one is for group only\n if (maxname >= grp) {\n NP_clear_result()\n var ppl = Math.round(maxname / grp)\n // console.lo_g(maxname / grp);\n var grp_auto = grp\n // console.lo_g(grp_auto + ' group with ' + ppl + ' people');\n var ctr = 0\n var people_in_groups = []\n\n var leftover = (grp_auto * ppl) - maxname\n if ((leftover >= ppl) && (grp_auto != ppl)) {\n ppl = ppl - 1\n // console.lo_g('ppl = ' + ppl);\n }\n\n if ((grp_auto * ppl) > maxname && ((grp_auto * ppl) != maxname)) {\n NP_alert_show()\n var ads = 0\n var leftover = (grp_auto * ppl) - maxname\n // al_ert('remove ' + leftover + ' person')\n for (var xxx = 0; xxx < leftover; xxx++) {\n ads = ads + 1\n var namesum = maxname\n for (var xx = 0; xx < grp_auto; xx++) {\n if ((leftover >= 1) && (((ppl-1) - ads) >= (ppl-1))) {\n people_in_groups.push((ppl-1) - ads)\n leftover = leftover - 1\n // console.lo_g('leftover to remove ' + leftover);\n } else {\n if (ppl < namesum) {\n people_in_groups.push(ppl-1)\n namesum = (namesum - ppl)\n // console.lo_g('namesum ' + namesum);\n // console.lo_g(people_in_groups);\n } else {\n people_in_groups.push(namesum-1)\n people_in_groups.reverse()\n }\n }\n }\n people_in_groups.reverse()\n }\n } else if ((grp_auto * ppl) == maxname) {\n for (var xx = 0; xx < grp_auto; xx++) {\n people_in_groups.push(ppl-1)\n }\n } else {\n NP_alert_show()\n var ads = 0\n var leftover = maxname - (grp_auto * ppl)\n // al_ert('add ' + leftover + ' person')\n for (var xxx = 0; xxx < leftover; xxx++) {\n ads = ads + 1\n var namesum = maxname\n for (var xx = 0; xx < grp_auto; xx++) {\n // console.lo_g(grp_auto);\n if (leftover >= 1) {\n people_in_groups.push((ppl-1) + ads)\n leftover = leftover - 1\n // console.lo_g('leftover to add ' + leftover);\n } else {\n people_in_groups.push(ppl-1)\n }\n }\n }\n }\n\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>Group ' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups[ctr]; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n } else {\n NP_alert_show()\n NP_clear_result()\n var namepool = []\n var grp_auto = maxname\n var people_in_groups = 1\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>Group ' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n }\n // ======================================================================\n } else {\n cntmode = 4\n // al_ert('mode = ' + cntmode)\n // this one is for if both group and people has no value\n NP_alert_show()\n NP_clear_result();\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = (cleannames[rand]);\n var lbltmp = document.createElement('label');\n var oltmp = document.createElement('ol');\n var litmp = document.createElement(\"li\");\n lbltmp.innerHTML = ('<b>Group 1</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n litmp.innerHTML = (pickedname);\n // console.lo_g(cleannames);\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n oltmp.appendChild(litmp);\n // ======================================================================\n }\n } else {\n cntmode = 6\n // al_ert('mode = ' + cntmode)\n NP_clear_result()\n var namepool = []\n var grp_auto = $('#winnerv').val()\n var people_in_groups = 0\n\n if ((grp_auto >= 1) && (maxname > grp_auto)) {\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>#' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n } else {\n NP_alert_show()\n grp_auto = maxname;\n for (var x = 0; x < grp_auto; x++) {\n var lbltmp = document.createElement('label');\n lbltmp.innerHTML = ('<b>#' + (x + 1) + '</b>');\n lbltmp.className = ('p-2 pt-0 pb-0');\n var namepool = []\n\n for (var b = people_in_groups; b >= 0; b--) {\n // console.lo_g('people in groups = ' + people_in_groups[ctr]);\n var rand = Math.floor(Math.random()*cleannames.length);\n var pickedname = cleannames[rand]\n namepool.push('<li>' + pickedname + '</li>')\n cleannames.splice(rand, 1);\n var oltmp = document.createElement('ol');\n oltmp.innerHTML = (namepool.join('\\n'));\n }\n ctr = ctr + 1\n // console.lo_g('counter ' + ctr);\n // console.lo_g(namepool);\n // console.lo_g(\"Ini Team \" + (x + 1) + \" \" + namepool);\n\n document.getElementById('ResultBox').appendChild(lbltmp);\n document.getElementById('ResultBox').appendChild(oltmp);\n }\n }\n }\n } else {\n NP_alert_show()\n }\n}", "i2nam(k) {\n\treturn [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"][k >> 3] + ((k & 7) + 1);\n }", "function makeid(){\n var text = \"\";\n var possible = \"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789\";\n\n for( var i=0; i < 4; i++ )\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return text;\n}", "function manipulateName(name) {\n\n\tvar joinName = name.join('').toUpperCase();\n\tvar letters = joinName;\n\tvar acc = 0;\n\tvar emptyArr = [];\n\tvar result = [];\n\n\tfor (var i = 0; i < letters.length; i++) {\n\t\tvar match = joinName.indexOf(letters[i]);\n\t\t//console.log(letters[i] + ' ' + match);\n\n\t\tif (match > -1) {\n\t\t\t//console.log('La letra ' + letters[i] + ' se repite ' + acc + ' veces');\n\t\t\temptyArr.push(letters[i]);\n\t\t}\n\t}\n\n\tfor (var i = 0; i < emptyArr.length; i++) {\n\t\tvar repeat = 0;\n\t\tfor (var j = 0; j < joinName.length; j++) {\n\t\t\tif (emptyArr[i] === joinName[j]) {\n\t\t\t\trepeat++;\n\t\t\t}\n\t\t}\n\t\tif (repeat === 1) {\n\t\t\tresult.push(emptyArr[i]);\n\t\t}\n\n\t}\n\tconsole.log('My name is ' + result.join(''));\n}", "formatId(){\n\n return this.props.group.replace(' ','').replace('.','') + ':' + this.props.code\n }", "function makeGroups() {\n\tvar x = 400, y = 0\n\tfor (var i = 0, len = genres.length; i < len; i++) {\n\t\tcategoriesXY[genres[i]] = [ y , x ]\n\t\ty += 125\n\t\tif( i + 1 == Math.ceil(len/2) ) {\n\t\t\ty = 0\n\t\t\tx += 400\n\t\t}\n\t}\n}", "function checkGroupName() {\r\n var group = \"\";\r\n var assign = new SCFile(\"assignment\");\r\n var resAssign = assign.doSelect(\"se.id=\\\"\" + $RECORD[\"se_assignment_group\"] + \"\\\"\");\r\n if (resAssign == RC_SUCCESS) {\r\n group = assign[\"name\"];\r\n }\r\n}", "function charReplacer(cBand) {\n for (i = 0; i < cBand.length; i++) {\n underscoredBand.push(\"_\");\n }\n console.log(underscoredBand);\n }", "function generateKey(){\n \n let keyString = \"\";\n \n for (let n=0; n<subsArray.length; n++){\n for (let m=0; m<subsArray[0].length; m++){\n \n function stringToId() {\n \n if (subsArray[n][m].value == \"qwertyuiopasdfghjklzxcvbnm\")\n {return \"A-\";\n } else if (subsArray[n][m].value == \"mlpnkobjivhucgyxftzdrseawq\") \n {return \"B-\";\n } else if (subsArray[n][m].value == \"bncmxzlaksjdhfgyturieowpqv\") {\n return \"C-\";\n \n } else if (n == subsArray.length -1 && m == subsArray[0].length -1)\n {return subsArray[n][m].value\n }\n else return subsArray[n][m].value + \"-\";\n }\n let char = stringToId();\n \n keyString += char;\n }\n }\n keystringElement.innerText = keyString;\n}", "function formatIndexGroup(index_group) {\n indexes_split = index_group.split(',');\n\n grouped_indexes = '';\n\n indexes_split.forEach(function(index_name) {\n if (grouped_indexes.length > 0)\n grouped_indexes += \",\";\n\n grouped_indexes += (\"{\" + index_name + \": 1}\");\n\n });\n\n return grouped_indexes;\n}", "function formatGroup(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}", "function makeid() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n for( var i=0; i < 5; i++ )\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n }", "function numberJoinerFor(start, end) {\n let numString = '';\n if (start !== end) {\n for (let i = start; i < end; i++) {\n numString += start + '_';\n start++;\n }\n numString += end;\n return numString;\n } else {\n return numString + start;\n }\n}", "function makeid() {\n var text = '';\n var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n for ( var i=0; i < 5; i++ ) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n return text;\n }" ]
[ "0.6382855", "0.6330292", "0.62532586", "0.6232897", "0.6190578", "0.61847055", "0.61847055", "0.61847055", "0.61847055", "0.6146121", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.60857606", "0.6040203", "0.6000009", "0.5957493", "0.5917546", "0.5876053", "0.5873588", "0.5846056", "0.5803209", "0.5801791", "0.5801791", "0.57801926", "0.5773215", "0.574848", "0.5742081", "0.5734946", "0.5729695", "0.57134134", "0.5709532", "0.57094914", "0.57094914", "0.57094914", "0.5708398", "0.5677433", "0.5669381", "0.56329477", "0.5623048", "0.5618327", "0.560296", "0.5602725", "0.560233", "0.559974", "0.55912066", "0.55724186", "0.5561315", "0.55568385", "0.55556", "0.5548175", "0.55401444", "0.5513388", "0.5512341", "0.55020833", "0.54891956", "0.54890263", "0.5479276", "0.5473147", "0.54600364", "0.5457522", "0.5443745", "0.54429036", "0.542709", "0.5426577", "0.542427", "0.5400413", "0.539773", "0.5395063", "0.5394339", "0.5389513", "0.53826845", "0.5373594", "0.53711957", "0.5367446", "0.53519195", "0.5344268", "0.53383315", "0.5338002", "0.533491", "0.53317463", "0.53274196", "0.5324112", "0.5321814", "0.53160155", "0.5312004", "0.53104985" ]
0.7753008
0
Remember, this pwd is iterated over a million times. Not easy to crack
function get_pwd_group(domain, full_hash, password_strength) { var pwd_groups = pii_vault.aggregate_data.pwd_groups; var previous_group = false; var current_group = false; for (var g in pwd_groups) { if (pwd_groups[g].sites.indexOf(domain) != -1) { previous_group = g; } if (pwd_groups[g].full_hash == full_hash) { current_group = g; } } if (previous_group && pwd_groups[previous_group].full_hash != full_hash) { //This means password changed .. means group change .. first delete the domain from previous group pwd_groups[previous_group].sites.splice(pwd_groups[previous_group].sites.indexOf(domain), 1); } if (current_group) { //This means that there exists a group with exact same full hash if (pwd_groups[current_group].sites.indexOf(domain) == -1) { //This means that even though the group exists, this domain is not part of it. So we will add it. pwd_groups[current_group].sites.push(domain); } } else { // This means that we will have to create a new group and increase number of different // passwords by one. var new_grp = new_group_name(pwd_groups); new_grp = 'Grp ' + new_grp; pwd_groups[new_grp] = {}; pwd_groups[new_grp].sites = [domain]; pwd_groups[new_grp].strength = password_strength; pwd_groups[new_grp].full_hash = full_hash; pii_vault.aggregate_data.num_pwds += 1; flush_selective_entries("aggregate_data", ["num_pwds", "pwd_groups"]); current_group = new_grp; } // Now do similar things for current_report var cr_pwd_groups = pii_vault.current_report.pwd_groups; var cr_previous_group = false; // First find if domain is already present in any of the groups for (var g in cr_pwd_groups) { my_log("Here here: Sites: " + JSON.stringify(cr_pwd_groups[g]), new Error); if (cr_pwd_groups[g].sites.indexOf(domain) != -1) { cr_previous_group = g; break; } } if (cr_previous_group) { //This means that domain was seen earlier in this report period if (cr_previous_group != current_group) { // This means that password has changed groups, so first delete it from previous group cr_pwd_groups[cr_previous_group].sites.splice(cr_pwd_groups[cr_previous_group].sites.indexOf(domain), 1); send_pwd_group_row_to_reports('replace', cr_previous_group, cr_pwd_groups[cr_previous_group].sites, cr_pwd_groups[cr_previous_group].strength); } } //Also add the domain to current_group if (current_group in cr_pwd_groups) { if (cr_pwd_groups[current_group].sites.indexOf(domain) == -1) { cr_pwd_groups[current_group].sites.push(domain); } } else { //Create a new group and add this entry to the list cr_pwd_groups[current_group] = {}; cr_pwd_groups[current_group].sites = pwd_groups[current_group].sites.slice(0); cr_pwd_groups[current_group].strength = password_strength; pii_vault.current_report.num_pwds += 1; flush_selective_entries("current_report", ["num_pwds"]); send_pwd_group_row_to_reports('add', current_group, cr_pwd_groups[current_group].sites, cr_pwd_groups[current_group].strength); calculate_pwd_similarity(current_group); } flush_selective_entries("current_report", ["pwd_groups"]); return current_group; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static process_password(passwd){\n return passwd.padEnd(32, passwd) //passwd must be 32 long\n }", "function randomPwd(){\n var pwdLength = prompt(\"How many characters?\");\n var upperChar = confirm(\"Upper case characters?\");\n var specialChar = confirm(\"Special characters?\");\n var numChar = confirm(\"Number characters?\");\n if (pwdLength < 8){\n pwdLength = 8;\n }\n if (pwdLength > 128){\n pwdLength = 128;\n }\n if (upperChar === true){\n char = char.concat(upper);\n }\n if (specialChar === true){\n char = char.concat(special); \n }\n if (numChar === true){\n char = char.concat(num); \n }\n for (var i = 0; i < pwdLength; i++){\n password += char.charAt(Math.floor(Math.random() * char.length));\n }\n }", "pwd(server, clientSocket, command) {\n var promises = [server.getRootDirectoryEntry()];\n if (clientSocket.currentDirectoryEntryId) {\n promises.push(fileSystem.getFileSystemEntry(clientSocket.currentDirectoryEntryId));\n }\n\n var rootEntry = null;\n var currentEntry = null;\n return Promise.all(promises)\n .then(function(results) {\n rootEntry = results[0];\n currentEntry = results[1] || results[0];\n\n var path = currentEntry.fullPath.substring(rootEntry.fullPath.length);\n if (path.length < 1) {\n path = \"/\";\n }\n\n path = escapePath(path);\n\n // The path is surrounded by double quotes.\n var response = `257 \"${path}\"\\r\\n`;\n return response;\n });\n }", "function encrypt(pwd)\n\t\t\t\t{\n\t\t\t\t\tvar pwd;\n\t\t\t\t\tvar encrypt;\n\t\t\t\t\tencrypt = \"\";\n\t\t\t\t\t\n\t\t\t\t\tfor(var i = 0; i < pwd.length-1; i++) //This code encrypts the password of the user so no one can hack into their ac\n\t\t\t\t\t{\n\t\t\t\t\t\tencrypt = encrypt + String.fromCharCode(pwd.charCodeAt(i) + 3);\n\t\t\t\t\t}\n\t\t\t\t\treturn encrypt;\n\t\t\t\t\t\n\t\t\t\t}", "function password (l,characters){\n var pwd = \"\";\n\n for ( var i = 0; i<l; i++) {\n pwd += characters.charAt(Math.floor(Math.random() * characters.length))\n }\n return pwd;\n }", "function password(l,characters){\n\t\tvar pwd = '';\n for(var i = 0; i<l; i++){\n \t\tpwd += characters.charAt(Math.floor(Math.random() * characters.length));\n }\n return pwd;\n}", "function password(length,characters)\n{\n\nvar pwd = \"\";\n\nfor(var i = 0; i < length;i++){\n pwd += characters.charAt(Math.floor(Math.random() * characters.length));\n\n}\n return pwd;\n}", "function crack(login) {\n const foundChars = []; \n let done = false;\n let charIndex = 0;\n \n while (!done) {\n const pwStealer = new Proxy({}, {\n get(target, prop, receiver) {\n if (prop === 'length') return 0;\n \n if (foundChars[prop] === undefined) {\n foundChars[prop] = pwChars[0];\n charIndex = 0;\n }\n \n if (foundChars[prop]) return foundChars[prop];\n \n return undefined; \n }\n });\n \n foundChars.pop(); // last character is always the incorrect one\n charIndex++;\n foundChars.push(pwChars[charIndex]); \n done = login(pwStealer);\n }\n \n return foundChars.join('');\n}", "function getPwdHash() {\n getPlayerNameFromCharpane();\n var player = GM_getValue(\"currentPlayer\",\"\");\n if (player==\"\")\n return;\n var page = document.documentElement.innerHTML;\n var find = 'pwdhash = '\n if (page.indexOf(find) >= 0) {\n var i = page.indexOf(find);\n var j = find.length;\n var ps = page.substr(i+j+2);\n var foundit = page.substr(i+j+1,ps.indexOf('\"')+1);\n GM_setValue(player+\"_kolhash\", foundit); // not very secure\n //GM_log('found script: '+foundit);\n } \n}", "function CalculateRandomPwd(PwdLength,Option1,Option2,Option3,Option4) \n{\n // The following arrays are potential candidates for being included in the password depending on\n // the type of characters the user selected\n var ArrayofCharacters1='\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\_\\`\\{\\|\\}\\~'.split('');\n var ArrayofCharacters2='0123456789'.split('');\n var ArrayofCharacters3='abcdefghijklmnopqrstuvwxyz'.split('');\n var ArrayofCharacters4='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n\n // Finalized the potential characters to be included in the password\n // Variable ArrayofCharacters to contain all potential candidates\n\n var ArrayofCharacters=[];\n if(Option1) {ArrayofCharacters=ArrayofCharacters.concat(ArrayofCharacters1)};\n if(Option2) {ArrayofCharacters=ArrayofCharacters.concat(ArrayofCharacters2)};\n if(Option3) {ArrayofCharacters=ArrayofCharacters.concat(ArrayofCharacters3)};\n if(Option4) {ArrayofCharacters=ArrayofCharacters.concat(ArrayofCharacters4)};\n\n var LengthOfChoices=ArrayofCharacters.length; // how many character choices we have\n var RandomIndex=0; // Random number to access the array\n var RandomPassword=\"\"; // Random password value\n\n // Calculating the random password\n for (var i=0;i<PwdLength;i++) {\n RandomIndex=Math.floor(Math.random() * (LengthOfChoices));\n RandomPassword=RandomPassword+ArrayofCharacters[RandomIndex];\n };\n\nreturn (RandomPassword);\n} // End of function CalculateRandomPwd", "function getTeamPassword() {\n var password = \"\";\n for (var i = 0; i < 5; i++) {\n var random = Math.floor(Math.random() * 74 + 48)\n while (random > 57 && random < 65 || random > 90 && random < 97){\n var random = Math.floor(Math.random() * 75 + 47)\n }\n password += String.fromCharCode(random)\n }\n\n return password\n}", "function generatePassword(){\n //returned password\n var retpass = \"\"\n // passwordLength() function call\n passwordLength()\n //confirmCharSet() function call (or confirm character set)\n confirmCharSet()\n \nfor (i=0; i < passlength; i++){\n retpass += charSet.charAt(Math.ceil(Math.random()*charSet.length))\n}\nreturn retpass\n}", "function hashPwd(pwd) {\n\tvar hashedPwd = crypto.pbkdf2Sync(pwd, 's4d54sdf54s', 10000, 64, 'sha512');\n\treturn hashedPwd\n}", "function randomizePassword() {\n for(var i = 0; i < charSelect; i++) {\n var randomIdx = Math.floor(Math.random() * passwordContainer.length);\n var randomChar = passwordContainer[randomIdx];\n finalPassword = randomChar + finalPassword;\n } \n }", "function specPass(){\n var password = \"\";\n var i;\n for (i = 0; i <= len - 1; i++) {\n password += letSpec[getRandomInt(59)];\n }\n return password;\n }", "function generatePwd(){\n password= \"\" ;\n randomPwd() ;\n document.getElementById(\"password\").value = password ;\n copyPwd();\n }", "function randomPass() {\n for (var i = 0, n = charset.length; i < length; ++i) {\n\t\tpassword += charset.charAt(Math.floor(Math.random() * n));\n\t}\n}", "function generatePassword() {\n \n var finalPassword = \"\";\n var tempChar = \"\";\n var index = passwordSizeEntry();\n var tempString = passPrompts();\n\n for (let i = 0; i < index ; i++) {\n \n finalPassword = finalPassword.concat(tempString.charAt(Math.floor(Math.random() * tempString.length)));\n }\n return(finalPassword);\n}", "function genPwd (){\n var selectChar = [];\n var pwdFinal = \"\";\n\n//set password length \n\nvar pwdLength = prompt(\" Welcome to the Secure Password Generator, Please select a password length between 8 and 128 characters\");\n\n//while loop to continuously prompt user to enter length between 8-128\n\nwhile(pwdLength < 8 || pwdLength > 138 || isNaN(pwdLength)){\n pwdLength = prompt(\"Please enter a number between 8 and 128\")\n}\n\n// if statement begins, checks and validates input of pwdLength is correct then moves to else /if statemtns \n\nif (pwdLength < 8 || pwdLength > 138 || isNaN(pwdLength)) {\n \n}\n\n// create in put for arrays for uppercase, lowercase, special characters and numbers \n// uses Array.prototype.push.apply to add user input into arrays like objects defined at the top of the \n// the page, the apply() fuction combines the arrays into one another to create selectChar\n\n//add alert to let user know they must choose at leaste on of the following criteria. \n\n\n\nelse{\n\n alert(\"please pick at lease one of the following criteria for your secure password, failure to do so will result in the termination of the password generator\"); \n\nif(confirm(\"Please click Ok to include special characters in your password\")){\n Array.prototype.push.apply(selectChar, specialCharArray);\n}\n\n if(confirm(\"Please click Ok to include lowercase letters in your password\")){\n Array.prototype.push.apply(selectChar, lowerCaseArray);\n}\n\n if(confirm(\"Please click OK to include Uppercase letters in your password\")){\n Array.prototype.push.apply(selectChar, upperCaseArray);\n\n}\n\nif(confirm(\"Please click OK to include numbers in your password\")){\n Array.prototype.push.apply(selectChar, numberArray); \n}\n\n// validates the above if statements, if user choose \"cancel\" for all criteria then\n// length === 0 and will promp the user to start again \n\nif(selectChar.length===0){\n alert(\"You did not select any password critera. Please note in order to generate your password you must select at least one of the options above. Please start over, thank you. \")\n}\n\n// for loop to validate and generate password , math.floor to round down to whole numbers\n\nelse{\n \n for(var i=0; i< pwdLength; i++) {\n var random = Math.floor(Math.random() * selectChar.length);\n pwdFinal += selectChar[random];\n }\n}\n}\n\n// print generated password to text box on site \n\ndocument.getElementById(\"password\").innerHTML = pwdFinal;\n\n}", "function numPass(){\n var password = \"\";\n var i;\n for (i = 0; i <= len - 1; i++) {\n password += letNum[getRandomInt(36)];\n }\n return password;\n }", "function forLoop() {\n var pass = \"\";\n for ( i=0; i<passwordLength; i++) {\n //pick a random character based on master array\n var num = Math.floor(Math.random()* usersChoices.length);\n pass = pass + usersChoices.charAt(num)\n console.log (pass);\n console.log (num);\n console.log(usersChoices.charAt(num));\n }\n\n return pass;\n\n}", "function generatePassword() {\n let genpass = \"\";\n const passLength = Math.floor(Math.random() * ((32-8)+1) + 8);\n \n for(let i = 1; i <= passLength; i++) {\n \n genpass += getRandomChar();\n } \n \n}", "function makePassword() {\n var password = \"\";\n var i;\n for (i = 0; i <= len - 1; i++) {\n password += letters[getRandomInt(26)];\n }\n return password;\n }", "function generatePassword(conns){\n var salt = o.salt;\n if(o.dynamicSalt){\n salt = $( o.dynamicSalt).val();\n }\n var res = salt; //start our string to include the salt\n var off = o.shaOffset; //used to offset which bits we take\n var len = o.passLength; //length of password\n for(i in conns){\n res+=\"-\" + conns[i].startID;\n }\n res+=\"-\" + conns[i].endID; //make sure we get that last pin\n log(res);\n res = Sha1.hash(res, false);\n \n //make sure that we don't try to grab bits outside of our range\n if(off + len > res.length){\n off = 0; \n } \n res = res.substring(off, off + len);\n return res;\n }", "function generatePass() {\n var options = getPasswordOption()\n var initialPass = []\n var possibleCharacters = []\n var guaranteedCharacters = []\n var finalPass = []\n\n\n if (options.pwdSpecial) { \n possibleCharacters = possibleCharacters.concat(specialCharactersArray);\n guaranteedCharacters.push(getRandom(specialCharactersArray));\n }\n\n if (options.pwdLower) {\n possibleCharacters = possibleCharacters.concat(lowerCharactersArray);\n guaranteedCharacters.push(getRandom(lowerCharactersArray));\n }\n\n if (options.pwdUpper) {\n possibleCharacters = possibleCharacters.concat(upperCharacterArray);\n guaranteedCharacters.push(getRandom(upperCharacterArray));\n }\n\n if (options.pwdNumeric) {\n possibleCharacters = possibleCharacters.concat(numericCharacterArray);\n guaranteedCharacters.push(getRandom(numericCharacterArray));\n }\n// for loop adds possible characters to the inital passwork created\n for ( var i = 0; i < (options.pwdLength - guaranteedCharacters.length); i++){\n initialPass.push(getRandom(possibleCharacters));\n }\n// adds the guaranteed characters based on the user's selected options to the inital password\n finalPass = initialPass.concat(guaranteedCharacters);\n//returns and prints the password without commas or quotations\n return finalPass.join(\"\")\n}", "testPassword (pwd) {\n // TODO : creer une regex logique pour un password\n var regexpwd = /^\\D+$/\n return regexpwd.test(pwd)\n }", "function writePassword() {\n function generatePassword() {\n // promts user to choose pass length and parses into an integer\n var passLength = prompt(\"Password length (min:8 chars, max:128 chars): \");\n var length = parseInt(passLength);\n\n var passChars = prompt(\"What type of characters would you like to use: \\nlowercase, uppercase, numeric, special characters or all\");\n var charset;\n var charset1 = \"abcdefghijklmnopqrstuvwxyz\";\n var charset2 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var charset3 = \"0123456789\";\n var charset4 = \"!@#$%&*\";\n var charset5 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*\"\n\n if (length >= 8 && length <= 128) {\n length;\n // straight up just the character set to choose from\n // The retVal kinda sets it up as both a split and gets returned as a string for the password\n if (passChars === \"lowercase\") {\n charset = charset1;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"uppercase\") {\n charset = charset2;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"numeric\") {\n charset = charset3;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"special characters\" || passChars === \"special\") {\n charset = charset4;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"all\") {\n charset = charset5;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else {\n alert(\"Please enter valid response\")\n }\n }\n\n // I honestly couldnt figure out how to do this part of connecting two inputs and thier character sets, lemme know if I was on the right track here\n // Didnt want to code every variation and couldnt figureout how to do more than one variable\n\n // else if (passChars === \"lowercase uppercase\") {\n // charset = charset1 + charset2;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase special characters\" || passChars === \"lowercase special\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"uppercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"uppercase special characters\" || passChars === \"uppercase special\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n\n // else {\n // alert(\"Please input a vaild length.\")\n // }\n }\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n}", "function generatePassword () {\n var length = getPasswordLength ();\n var selectedCharacters = writePassword ();\n var password = \"\"\nfor(var i = 0; i < length; i++) {\n password = password + selectedCharacters.charAt(Math.floor(Math.random() * selectedCharacters.length));\n}\nalert (password);\n}", "setCachedPassword(pwd){\n cachedPassword = pwd;\n }", "static generatePassword() {\n return Math.floor(Math.random() * 10000);\n }", "function generatePassword() {\n\n var password = \"\";\n for (i = 1; i <= passLength; i++) {\n var randomPass = Math.floor(Math.random() * results.length);\n\n password += results[randomPass];\n \n }\n return password;\n \n}", "function generatePw(passChars, passNum)\n{\n //initialized password string\n let password = \"\";\n //generate password. loop runs the amount of times as the password length\n for(let i = 0; i < passNum; i++)\n {\n //adds random character from the passChars array to password\n password+=passChars[parseInt(Math.random()*(passChars.length-1))];\n console.log(password);\n }\n //returns the password\n return password;\n}", "function bruteforce() {\n let crack = [];\n\n for (let j = 0; j <= password.length - 1; j++) {\n for (let i = 0; i <= allowedChars.length - 1; i++) {\n // console.log(i, allowedChars[i]);\n if (allowedChars[i] === password[j]) {\n crack.push(allowedChars[i]);\n console.log(crack.join(''));\n }\n };\n\n // console.log('From J:', j, password[j]);\n };\n}", "function generatePassword() {\n let pwd = []; //random characters get added to this array\n // parseInt to turn string value into number value.\n let passwordLength = parseInt(prompt(\"How many characters do you want in your password? (Must be between 8 - 128)\"));\n\n // if number not within range or not a number\n if (passwordLength < 8 || passwordLength > 128 || isNaN(passwordLength)) {\n alert(\"Please try again. (Must be a number between 8 - 128)\");\n generatePassword();\n }\n\n // ask to confirm different arrays. \n let confirmChar = confirm(\"Do you want to include special characters?\");\n let confirmNum = confirm(\"Do you want to include numbers?\");\n let confirmUpper = confirm(\"Do you want to include uppercase letter?\");\n let confirmLower = confirm(\"Do you want to include lower case letters?\");\n\n if (confirmChar === false && confirmNum === false && confirmUpper === false && confirmLower === false) {\n alert(\"Do you want a password or nah?\");\n return;\n }\n\n // If confirmed, push values into new array called pwd\n if (confirmChar) {\n pwd.push(char);\n }\n\n if (confirmNum) {\n pwd.push(num);\n }\n\n if (confirmUpper) {\n pwd.push(upperCase);\n }\n\n if (confirmLower) {\n pwd.push(lowerCase);\n }\n\n // new empty array which will contain new password strings after looping\n let newPwd = \"\";\n\n while (newPwd.length < passwordLength) {\n for (let i = 0; i < pwd.length; i++) {\n if (newPwd.length < passwordLength) {\n let randomChar = Math.floor(Math.random() * pwd[i].length)\n newPwd += pwd[i][randomChar]\n\n }\n }\n\n }\n return newPwd; // send the result of the function back to its call name\n}", "function generatePassword(){\n pwLength();\n uppercase();\n determineNumbers();\n determineSpecial();\n\n var characters = lowerCs;\n var password = \"\";\n if (!uppercaseCheck && !numberCheck && !splCheck) {\n return;\n\n } \n if (uppercaseCheck) {\n characters += upperCs \n;\n\n } \n if (numberCheck) {\n characters += numbers;\n;\n\n } if (uppercaseCheck) {\n characters += upperCs;\n;\n }\n\n \n if (splCheck) {\n characters += splChars;\n\n } \n // for loop / code block run and will pull random character from string stored in variables using the charAt method, them randomize it with the math.random function\n for (var i = 0; i < passwordLgth; i++) {\n password += characters.charAt(Math.floor(Math.random() * characters.length));\n }\n return password;\n\n\n\n\n}", "function generatePassword() {\n //prompt for password length\n var passLength = prompt(\"Please enter password length between 8 and 128\", \"8\");\n if (passLength < 8 || passLength > 128) {\n alert(\"Please enter a number between 8 and 128\");\n return;\n }\n //prompt for password complexity options\n var passUpOpt = confirm(\"would you like to include uppercase characters?\");\n var passLowOpt = confirm(\"would you like to include lowercase characters?\");\n var passNumOpt = confirm(\"would you like to include numeric characters?\");\n var passSpecOpt = confirm(\"would you like to include special characters?\");\n //array for password characters\n //let passChar = ['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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')' '_' '+'];\n var passUpChar = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var passLowChar = \"abcdefghijklmopqrstuvwxyz\";\n var passNumChar = \"1234567890\";\n var passSpecChar = \"!@#$%^&*()_+\";\n var passChar = \"\";\n \n /* if (passUpOpt = true) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecOpt = true) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } else if (passUpOpt = false) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecChar = true) {\n passChar = passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } */\n //combinations of strings\n if (passUpOpt && passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n } else if (!passUpOpt && !passLowOpt && !passNumOpt && !passSpecOpt) {\n alert(\"Please choose at least one type of character\")\n } else if (passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passLowChar + passNumChar + passSpecChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passUpOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passNumChar + passSpecChar;\n } else if (passUpOpt && passSpecOpt) {\n passChar = passUpChar + passSpecChar;\n } else if (passUpOpt && passLowOpt && passNumOpt) {\n passChar = passUpChar + passLowChar + passNumChar;\n } else if (passUpOpt && passLowOpt && passSpecChar) {\n passChar = passUpChar + passLowChar + passSpecChar;\n } else if (passUpOpt && passNumOpt) {\n passChar = passUpChar + passNumChar;\n } else if (passUpOpt) {\n passChar = passUpChar;\n } else if (passLowOpt && passNumOpt) {\n passChar = passLowChar + passNumChar;\n } else if (passLowChar) {\n passChar = passLowChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passNumOpt) {\n passChar = passNumChar;\n } else if (passUpOpt && passLowOpt) {\n passChar = passUpChar + passLowChar;\n } else if (passLowOpt && passSpecOpt) {\n passChar = passLowChar && passSpecChar;\n }\n\n console.log(passChar);\n\n\n var pass = \"\";\n //for loop to pick the characters the password will contain\n for(var i = 0; i <= passLength; i++) {\n pass = pass + passChar.charAt(Math.floor(Math.random() * Math.floor(passChar.length - 1)));\n }\n alert(pass);\n //return pass;\n document.querySelector(\"#password\").value = pass;\n\n}", "function generatePassword() {\n let inputPass = \"\";\n let availableCharacters =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" +\n \"abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+\";\n\n for (i = 1; i <= 30; i++) {\n let char = Math.floor(Math.random() * availableCharacters.length + 1);\n\n inputPass += availableCharacters.charAt(char);\n }\n\n return inputPass;\n}", "async pwd() {\n const res = await this.send(\"PWD\");\n // The directory is part of the return message, for example:\n // 257 \"/this/that\" is current directory.\n const parsed = res.message.match(/\"(.+)\"/);\n if (parsed === null || parsed[1] === undefined) {\n throw new Error(`Can't parse response to command 'PWD': ${res.message}`);\n }\n return parsed[1];\n }", "function generatePassword() {\n // User Input\n var askPwdLength = prompt(\"How long do you want your password to be? Your password MUST be 8 to 128 characters.\");\n\n // User can't input anything less than 8 or greater than 128 characters long\n if (askPwdLength >= 8 && askPwdLength <= 128) {\n alert(\"Your password will have \" + askPwdLength + \" characters\");\n console.log(askPwdLength);\n\n var upperCase = confirm(\"Do you want uppercase characters in your password?\")\n var lowerCase = confirm(\"Do you want lowercase characters in your password?\")\n var special = confirm(\"Do you want special characters in your password?\")\n var number = confirm(\"Do you want numbers in your password?\")\n\n var bankChar = \"\"\n var password = \"\"\n\n if (upperCase) {\n bankChar += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n }\n\n if (lowerCase) {\n bankChar += \"abcdefghijklmnopqrstuvwxyz\"\n }\n\n if (special) {\n bankChar += \"!#$%&'()*+,-./:;<=>?@_`{|}[]~\"\n }\n\n if (number) {\n bankChar += \"0123456789\"\n }\n\n for (i = 0; i < askPwdLength; i++) {\n console.log(\"i\" + i);\n password += bankChar.charAt(Math.floor(Math.random() * bankChar.length));\n console.log(\"password\" + password)\n console.log(\"bankChar\" + bankChar)\n }\n\n return (password);\n } else {\n alert(\"Your password needs to be 8-128 characters long. Try again.\");\n // var askPwdLength = prompt(\"How long do you want your password to be? Your password must be atleast 8 to 128 characters.\");\n }\n}", "function generatePassword(){\n\n //The value of length is the number passed from appropriate length\n var length = appropriateLength();\n //The value of userChars is the array generated by the function\n var userChars = appropriateCriteria();\n //This value is initialized as an empty string and will hold the randomly generated password\n var randPass = \"\";\n //The loop runs i times, where i is the length variable\n for (var i = 0; i < length; i++){\n //here we add a random character from the userChars array to our randPass string\n randPass += userChars[Math.floor(Math.random() * (userChars.length-1))]\n }\n //we can shuffle randPass to add another layer of simulated randomness\n randPass = shuffle(randPass);\n //returns the randomly generated and shuffled string to be used\n return randPass;\n}", "function generatePassword() {\n //RESET USER PROMPT GLOBAL VARIABLES FOR REUSE\n password = \"\";\n passwdlen = 0;\n reply='z';\n passwdCharSet = [];\n charsets = {\n uc: true,\n lc: true,\n sc: true,\n num: true,\n numOfSets: 4\n };\n\n //Prompt user for how long the password should be, btwn 8-128 chars\n while ((passwdlen < 8 || passwdlen > 128) || isNaN(passwdlen)) {\n passwdlen = prompt(\"Please enter a length for your password between 8-128 characters: \");\n }\n\n //prompt user - uppercase?\n reply = \"z\";\n while ((reply !== \"y\") && (reply !== \"n\")) {\n reply = prompt(\"Do you want to use Upper Case Letters? y or n\");\n if ((reply !== \"y\") && (reply !== \"n\")) {\n alert(\"Please enter only 'y' or 'n' in the reply box.\");\n }\n }\n if (reply === 'n') {\n charsets.uc = false;\n charsets.numOfSets = charsets.numOfSets - 1;\n // charsets.numOfSets --;\n }\n else {\n passwdCharSet.push(...alphaUpper);\n }\n\n //prompt user - use lower case?\n reply = \"z\";\n while ((reply !== \"y\") && (reply !== \"n\")) {\n reply = prompt(\"Do you want to use Lower Case Letters? y or n\");\n if ((reply !== \"y\") && (reply !== \"n\")) {\n alert(\"Please enter only 'y' or 'n' in the reply box.\");\n }\n }\n if (reply === 'n') {\n charsets.lc = false;\n charsets.numOfSets = charsets.numOfSets - 1;\n // charsets.numOfSets --;\n }\n else {\n passwdCharSet.push(...alphaLower);\n }\n\n //prompt user - use special chars?\n reply = \"z\";\n while ((reply !== \"y\") && (reply !== \"n\")) {\n reply = prompt(\"Do you want to use Special Characters? y or n\");\n if ((reply !== \"y\") && (reply !== \"n\")) {\n alert(\"Please enter only 'y' or 'n' in the reply box.\");\n }\n }\n console.log(reply);\n if (reply === 'n') {\n charsets.sc = false;\n charsets.numOfSets = charsets.numOfSets - 1;\n // charsets.numOfSets --;\n }\n else {\n passwdCharSet.push(...specialChars);\n }\n\n //prompt user - use numbers?\n reply = \"z\";\n while ((reply !== \"y\") && (reply !== \"n\")) {\n reply = prompt(\"Do you want to use Numbers? y or n\");\n if ((reply !== \"y\") && (reply !== \"n\")) {\n alert(\"Please enter only 'y' or 'n' in the reply box.\");\n }\n }\n if (reply === 'n') {\n charsets.num = false;\n charsets.numOfSets = charsets.numOfSets - 1;\n // charsets.numOfSets --;\n }\n else {\n passwdCharSet.push(...numbers);\n }\n\n var i;\n for(i = 0; i < passwdlen; i++) {\n getRandom = Math.floor((Math.random() * passwdCharSet.length));\n password = password + passwdCharSet[getRandom];\n }\n return password;\n}", "function genPW() {\n var newPass = [];\n var pwdLength = parseInt(prompt(\"Please enter the length of password between 8-128.\"));\n\n if(pwdLength <= 8 || pwdLength >= 128) {\n\t alert(\"Invalid entry must be a number between 8-128, Try again!\");\n\t return;\n }\n if(isNaN(pwdLength)){\n alert(\"Invalid entry must be a number between 8-128, Try again!\");\n return;\n }\n\t else if (pwdLength >= 8 && pwdLength <= 128);{\n\t }\n confirmLow = confirm(\"Click ok to confirm including lower case letters.\");\n confirmUpp = confirm(\"Click ok to confirm including upper case letters.\");\n confirmNum = confirm(\"Click ok to confirm including numbers.\");\n confirmSpl = confirm(\"Click ok to confirm including special characters.\");\n\n if (confirmUpp == true) {\n (newPass.push(UppChar));\n }\n if (confirmLow == true) {\n (newPass.push(lowChar));\n }\n if (confirmNum == true) {\n (newPass.push(numChar));\n }\n if (confirmSpl == true) {\n (newPass.push(SpeChar));\n }\n //This is validating the character selection to continue\n else if (confirmLow === false && confirmUpp === false && confirmSpl === false && confirmNum === false) {\n alert(\"You must select one of the character inputs to generate password.\");\n return;\n }\n //This is putting everything together from the selection to generate password\n var pwdStr = newPass.join(\"\");\n var password = \"\";\n \n for (var i = 0; i < pwdLength; i++) {\n var gen = pwdStr.charAt(Math.floor(Math.random() * pwdStr.length));\n password = password.concat(gen);\n }\n document.getElementById(\"passWD\").textContent = password;\n }", "function writePassword() {}", "function generatePassword() {\n\tvar password = \"\";\n\tvar validChars = \"\";\n\n\t// Use answers to prompts to build a string of allowable characters based on responses\n\n\tif (inclUpper === \"y\") {\n\t\tvalidChars = validChars + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\t}\n\n\tif (inclLower === \"y\") {\n\t\tvalidChars = validChars + \"abcdefghijklmnopqrstuvwxyz\";\n\t}\n\n\tif (inclNumber === \"y\") {\n\t\tvalidChars = validChars + \"0123456789\";\n\t}\n\n\tif (inclSpecial === \"y\") {\n\t\tvalidChars = validChars + \" !#$%&'()*+,-./:;<=>?@[]^_`{|}~\";\n\t}\n\n\tfor (let i = 0; i < pwdLength; i++) {\n\t\tvar char = Math.floor(Math.random() * validChars.length + 1);\n\n\t\tpassword += validChars.charAt(char);\n\t}\n\n\treturn password;\n}", "function writePassword() {\n var wantPass = confirm(\"Would you like to generate a random password?\");\n if (wantPass === true) {\n\n // Password Needs to be 8 - 128 characters\n var inputPass = prompt(\"How many characters would you like your password to be?\");\n for (inputPass === false; inputPass < 8 || inputPass > 128; inputPass++) {\n // if (inputPass < 8 || inputPass > 128) \n alert(\"Password needs to be between 8 - 128 characters\");\n var inputPass = prompt(\"How many characters would you like your password to be?\");\n }\n var inputPass2 = Number(inputPass);\n\n // console.log(inputPass2);\n\n for (allChar === false; !symbol && !number && !lower && !upper; allChar++) {\n alert(\"Please choose at least one type of character\");\n var symbol = confirm(\"Would you like symbol characters in your password?\");\n var number = confirm(\"Would you like number characters in your password?\");\n var lower = confirm(\"Would you like lowercase characters in your password?\");\n var upper = confirm(\"Would you like uppercase characters in your password?\");\n }\n\n // If all character types chosen\n\n if (lower === true && number === true && symbol === true && upper === true) {\n var charSet = symbolChar.concat(numberChar, upperChar, lowerChar);\n }\n\n // If three character types chosen\n else if (lower === false && number === true && symbol === true && upper === true) {\n var charSet = numberChar.concat(symbolChar, upperChar);\n } else if (lower === true && number === false && symbol === true && upper === true) {\n var charSet = lowerChar.concat(symbolChar, upperChar);\n } else if (lower === true && number === true && symbol === false && upper === true) {\n var charSet = lowerChar.concat(numberChar, upperChar);\n } else if (lower === true && number === true && symbol === true && upper === false) {\n var charSet = lowerChar.concat(numberChar, symbolChar);\n }\n\n // If two character types chosen\n else if (lower === false && number === false && symbol === true && upper === true) {\n var charSet = symbolChar.concat(upperChar);\n } else if (lower === false && number === true && symbol === true && upper === false) {\n var charSet = symbolChar.concat(numberChar);\n } else if (lower === true && number === false && symbol === true && upper === false) {\n var charSet = symbolChar.concat(lowerChar);\n } else if (lower === false && number === true && symbol === false && upper === true) {\n var charSet = numberChar.concat(upperChar);\n } else if (lower === true && number === true && symbol === false && upper === false) {\n var charSet = numberChar.concat(lowerChar);\n } else if (lower === true && number === false && symbol === false && upper === true) {\n var charSet = upperChar.concat(lowerChar);\n }\n\n // If one character type is selected\n else if (lower === false && number === false && symbol === false && upper === true) {\n var charSet = upperChar;\n } else if (lower === false && number === false && symbol === true && upper === false) {\n var charSet = symbolChar;\n } else if (lower === false && number === true && symbol === false && upper === false) {\n var charSet = numberChar;\n } else if (lower === true && number === false && symbol === false && upper === false) {\n var charSet = lowerChar;\n };\n\n // for (var i=0; i < charSet.length; i++){\n // console.log(charSet[i]);\n // }\n\n\n // this fills empty randomPassword array\n for (var k = 0; k < inputPass2; k++) {\n j = Math.floor(Math.random() * charSet.length);\n randomPassword.push(charSet[j]);\n // console.log(randomPassword);\n }\n }\n\n var randPass = randomPassword.join('');\n console.log(randPass);\n\n\n\n // var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = randPass;\n}", "function makePasswd(userArray) {\n\n var pswdLength = document.getElementById(\"pswdLength\").value;\n\n var passwd = '';\n for (i=0; i < pswdLength; i++) {\n var c = Math.floor(Math.random()*userArray.length);\n passwd += userArray[c];\n }\n writeToPage(passwd)\n }", "function generatePassword() {\n var charLength = parseInt(prompt(\"How many characters do you want in your password loser?\"));\n // makes sure the password is between 8 and 128 characters long\n if (charLength < 8 || charLength > 128) {\n alert(\"Pick a number between 8 and 128 punk.\");\n generatePassword();\n } else {\n var lcChoice = lowersChoice();\n var ucChoice = uppersChoice();\n var numChoice = numbersChoice();\n var symChoice = symbolsChoice();\n // this is our empty array that we will concat the other arrays into for the password\n var firstPass = [];\n if (!lcChoice && !ucChoice && !numChoice && !symChoice) {\n alert(\"You must pick at least one you piece of garbage!\");\n generatePassword();\n } \n if (lcChoice) {\n firstPass = firstPass.concat(lowercasechar);\n }\n if (ucChoice) {\n firstPass = firstPass.concat(uppercasechar);\n }\n if (numChoice) {\n firstPass = firstPass.concat(numboxchar);\n }\n if (symChoice) {\n firstPass = firstPass.concat(symboxchar);\n }\n for(var i = 0; i < charLength; i++) {\n password += firstPass[Math.floor(Math.random() * firstPass.length)];\n }\n }\n return password;\n}", "function writePassword() {\n // reset global variables for each new password\n possibleChars = [];\n lowercase = false;\n uppercase = false;\n numerals = false;\n specials = false;\n //Run the prompts and generate password\n lengthPrompt();\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function generatePassword() {\n alert (\"Select which criteria to include in the password\");\n\n\n var passLength = parseInt(prompt(\"Choose a length of at least 8 characters and no more than 128 characters\"));\n\n //evaluate user input for password length\n while (isNaN(passLength) || passLength < 8 || passLength > 128)\n {\n \n if (passLength === null) {\n return;\n }\n\n passLength = prompt(\"choose a length of at least 8 characters and no more than 128 characters\");\n }\n\n\n var lowerCase = confirm(\"Do you want lowercase characters in your password\");\n var upperCase = confirm(\"Do you want uppercase characters in your password\");\n var numChar = confirm(\"Do you want numbers in your password?\");\n var specChar = confirm(\"Do you want special characters in your password?\");\n\n\n //evalute criteria for password generation\n if (lowerCase || upperCase || numChar || specChar)\n {\n var otherToGen = '';\n var intList = '0123456789';\n var uCharList ='ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var lCharList ='abcdefghijklmnopqrstuvwxyz'; \n var sCharList =\"!#$%&()*+,-./:;<=>?@[]^_`{|}~\";\n var remainlenght = 0;\n var criteriaMatch = 0;\n var value = '';\n\n if (numChar){\n value += genchar(1, intList);\n criteriaMatch++;\n otherToGen += intList;\n\n }\n\n if (lowerCase){\n value += genchar(1, lCharList);\n criteriaMatch++;\n otherToGen += lCharList;\n }\n\n if (upperCase) {\n value += genchar(1, uCharList);\n criteriaMatch++;\n otherToGen += uCharList;\n }\n\n\n if(specChar) {\n value += genchar(1, sCharList);\n criteriaMatch++;\n otherToGen += sCharList;\n\n }\n\n remainlenght = passLength-criteriaMatch;\n value += genchar(remainlenght, otherToGen);\n\n return value;\n}\n}", "function generatePassword() {\n houseKeeping();\n answer = inputLength(); \n userInput()\n process();\n passwordResult = c;\n c = '';\n return passwordResult; \n \n}", "function findPassword() {\n let count = 0\n for (let i = 165432; i <= 707912; i++) {\n if (adjacentDigits(i) && doesNotDecrease(i)) {\n count++\n }\n }\n return count\n}", "function generatePassword() {\n var length = 8,\n charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) { \n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n}", "function generatePassword() {\n const passLength = parseInt(prompt('How long should your password be?'))\n\n if (passLength < 8 || passLength > 128) {\n alert('please pick a length between 8 and 128 characters.')\n generatePassword()\n }\n \n const lowC = confirm('do you want lowercase characters?')\n const upC = confirm('do you want uppercase characters?')\n const numC = +confirm('do you want numbers?')\n const specC = confirm('do you want special characters?')\n let passHolder = ''\n newPass = ''\n if (lowC){\n passHolder += lowerChar;\n }\n if (upC) {\n passHolder += upperChar;\n }\n if (numC) {\n passHolder += numberChar;\n }\n if (specC) {\n passHolder += specialChar;\n }\n if (!lowC && !upC && !numC && !specC) {\n alert('you need to choose at least one character set.')\n generatePassword()\n }\n\n for (let i=0; i < passLength; i++) {\n let randomIndex = Math.floor(Math.random() * passHolder.length)\n newPass += passHolder[randomIndex]\n }\n return newPass\n}", "function writePassword() {\n // if wants to generate new password, reset everything\n masterArray = [];\n passwordLength = 0;\n charTypeCounter = 0;\n result = \"\";\n // begin series of prompts\n // will return boolean; true if ALL VALID INPUT; or undefined for canceled prompts\n var prompts = displayPrompts();\n // if we did NOT CANCEL at any point, then generate the password!\n if (!(prompts === undefined)) {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password; // assign the password to the elements value to display\n } else {\n //generation was canceled\n alert(\"Canceled password generator!\");\n }\n}", "generatePassword(charLen, keyboardId, contextSwitchCount) {\n const currentKeyboard = this.keyboards[keyboardId];\n const switchIndices = getUniqueRandomIntsWithLimit(\n charLen,\n contextSwitchCount,\n 2\n );\n let password = \"\";\n while (password.length < charLen) {\n if (switchIndices.includes(password.length)) {\n currentKeyboard.nextContext();\n }\n password += currentKeyboard.getRandomCharacter();\n }\n return password;\n }", "function generatePassword(){\n for(i=0, n = result.length; i < charLength; i++){\n retVal += result.charAt(Math.floor(Math.random() * n))\n }\n return retVal;\n }", "checkPwd() {\n const pwd = document.getElementById('newPwd').value,\n rpt = document.getElementById('repeatPwd').value;\n\n if (pwd !== rpt) {\n alert(getLang('SAME_PWD'));\n return false;\n }\n }", "function generatePw() {\n var possible = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';\n var newPassword = '';\n \n for(var i=0; i < 16; i++) {\n newPassword += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n \n return newPassword;\n }", "function generatePassword() {\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\";\n var string_length = 8;\n var randomstring = '';\n var charCount = 0;\n var numCount = 0;\n for (var i = 0; i < string_length; i++) {\n if ((Math.floor(Math.random() * 2) == 0) && numCount < 3 || charCount >= 5) {\n var rnum = Math.floor(Math.random() * 10);\n randomstring += rnum;\n numCount += 1;\n } else {\n var rnum = Math.floor(Math.random() * chars.length);\n randomstring += chars.substring(rnum, rnum + 1);\n charCount += 1;\n }\n }\n return randomstring;\n }", "function writePassword() {\n var password = generatePassword();\n}", "function pwd_validation(pwd){ \r\n //8-20 Characters, at least one capital letter, at least one number, no spaces\r\n //one lower case letter, one upper case letter, one digit, 6-13 length, and no spaces. \r\n var pwdReg = /^(?=.*\\d)(?=.*[A-Z])(?!.*\\s).{8,20}$/;\r\n return pwdReg.test(pwd); }", "function fakeCWD() {\n return cwd() + fake;\n }", "function generatePassword() {\n var password = [];\n\n for (var i = 0; i < passwordLength; i++) {\n var returnedChar =\n allPossibleOptions[Math.floor(Math.random() * allPossibleOptions.length)];\n password.push(returnedChar);\n }\n\n return password.join(\"\");\n}", "function generatePassword(){\n\n //prompt user for length of password (must be at least 8 and no more than 128)\n var promptLength = window.prompt(\"How many characters would you like your password to contain?\");\n promptLength.trim();\n promtpLength = parseInt(promptLength);\n\n // while the prompt is out of the scope, keep prompting\n while(promptLength < 8 || promptLength > 128){\n window.alert(\"Bad length. Please provide a number between 8 and 128 inclusive\");\n promptLength = window.prompt(\"How many characters would you like your password to contain?\");\n promptLength.trim();\n promptLength = parseInt(promptLength);\n }\n\n\n /* prompt user if they wish to include Uppercase letters\n if true, add uppercase letters to the password set\n */\n var confirmUppercase = window.confirm(\"Click OK to confirm including uppercase letters\");\n if(confirmUppercase){\n passSet = passSet.concat(upperSet);\n }\n\n /* prompt user for lowercase letters\n if true, add lowercase letters to the password set\n */\n var confirmLowercase = window.confirm(\"Click OK to confirm including lowercase letters\");\n if(confirmLowercase){\n passSet = passSet.concat(lowerSet);\n }\n\n /* prompt user for numbers\n if true, add numbers to password set\n */\n var confirmNum = window.confirm(\"Click OK to confirm including numeric characters\");\n if(confirmNum){\n passSet = passSet.concat(numSet);\n }\n\n /* prompt user for special characters\n if true, randomly choose special characters\n */\n var confirmChar = window.confirm(\"Click OK to confirm including special characters\");\n if(confirmChar){\n passSet = passSet.concat(charSet);\n }\n\n // cycle through the passSet to add random characters to create the password\n for(var i = 0; i < promptLength; i++){\n passCreate += passSet[(Math.floor(Math.random() * passSet.length))];\n }\n\n /* prompt user for special characters\n if true, randomly choose special characters\n */\n var confirmChar = window.confirm(\"Click OK to confirm including special characters\");\n if(confirmChar){\n passSet = passSet.concat(charSet);\n }\n\n // cycle through the passSet to add random characters to create the password\n for(var i = 0; i < promptLength; i++){\n passCreate += passSet[(Math.floor(Math.random() * passSet.length))];\n }\n\n // we want to check if at least one of each criteria is met in the final password, if not, fix it so there is\n var passCheck = checkCriteria(passCreate, confirmChar, confirmLowercase, confirmUppercase, confirmNum, promptLength);\n\n //return the created password \n return passCheck;\n}", "function checkPassword(pass) {\n var p = pass;\n var u = 0,\n n = 0,\n s = 0;\n var splChars = \"*|,\\\":<>[]{}`\\';()@&$#%\";\n for (var i = 0; i < p.length; i++) {\n if (splChars.indexOf(p.charAt(i)) != -1) {\n s = 1;\n console.log(s);\n continue;\n }\n if ((p[i] > 0) && (p[i] < 9)) {\n n = 1;\n console.log(n);\n continue;\n }\n if (p[i].toUpperCase() == p[i]) {\n u = 1;\n console.log(u);\n }\n\n }\n\n if ((u != 0) && (n != 0) && (s != 0))\n return true;\n else\n return false;\n\n}", "function generatePassword(charLength, characters) {\n var pwd = \"\";\n var passwordText = document.querySelector(\"#password\");\n \n for (var i = 0; i < charLength; i++) {\n pwd += characters.charAt(Math.floor(Math.random() * characters.length));\n }\n console.log(pwd);\n return pwd;\n}", "function obfuscateGitPass(str) {\n const gitPass = process.env.GIT_PASS;\n return gitPass ? str.replace(gitPass, 'GIT_PASS') : str;\n}", "function generatePassword() {\n\n // get password length and buid password source string \n var pwLength = buildSourceStr();\n\n // put first letter in password string\n var ssIndex = [getRandomInt(0, (passwordSourceString.length-1))]\n var pw = passwordSourceString[ssIndex];\n\n // add the rest of the password letters\n\n for (i = 1; i < pwLength; i++) {\n ssIndex = [getRandomInt(0, (passwordSourceString.length-1))]\n pw = pw.concat(passwordSourceString[ssIndex]);\n }\n return (pw);\n}", "function getPassword() {\n \tvar stdin = process.openStdin(),\n \ttty = require('tty');\n\n process.stdout.write('Enter password for user ' + database.getUser() + ' on database ' + database.getName() +': ');\n\tprocess.stdin.resume();\n\tprocess.stdin.setEncoding('utf8');\n\tprocess.stdin.setRawMode(true);\n\tpassword = ''\n\tprocess.stdin.on('data', function (char) {\n\t char = char + \"\"\n\n\t switch (char) {\n\t \tcase \"\\n\": case \"\\r\": case \"\\u0004\":\n\t\t\t\t// They've finished typing their password\n\t\t\t\tprocess.stdin.setRawMode(false);\n\t\t\t\tconsole.log('\\n\\n');\n\t\t\t\tstdin.pause();\n\t\t\t\tdatabase.setPass(password);\n\t\t\t\tinitialize();\n\t\t\t\tbreak;\n\t \tcase \"\\u0003\":\n\t \t\t// Ctrl C\n\t\t\t\tconsole.log('Cancelled');\n\t\t\t\tprocess.exit();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t// More passsword characters\n\t\t\t\tprocess.stdout.write('');\n\t\t\t\tpassword += char;\n\t\t\t\tbreak;\n\t }\n\t});\n}", "function makePassword(characterCount) {\n for (var i = 1; i < characterCount; i++) {\n //adds the next character to password\n password += randomnum();\n }\n //Displays generated password in #passwordDisplay\n document.querySelector(\"#passwordDisplay\").innerText = password;\n //Resets the password\n return resetPassword();\n}", "function writePassword() {\n \n // Ask user how long they want their password to be.\n // Prompt is inside of a for Loop until the user enters a password length between 8 and 128.\n \n var howlongpw = prompt(\"How long would you like your password to be (between 8 and 128 characters)?\");\n if (isNaN(howlongpw) === true) {\n return alert (\"You must select a number between 8 and 128, please try again.\");\n }\n\n if (((howlongpw)<8) || ((howlongpw)>128)) {\n return alert (\"You must select a password length between 8 and 128, please try again.\");\n }\n\n // Ask user if they want to include lower case letters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionLowerCase = confirm(\"Hit OK if you would like to include lower case letters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionLowerCase ===true) {\n Array.prototype.push.apply(userPasswordCritera,lowerCaseLettersCriteria);\n }\n\n // Ask user if they want to include upper case letters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n \n var optionUpperCase = confirm(\"Hit OK if you would like to include upper case letters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionUpperCase ===true) {\n Array.prototype.push.apply(userPasswordCritera,upperCaseLettersCriteria);\n }\n\n // Ask user if they want to include numbers in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionNumbers = confirm(\"Hit OK if you would like to include numbers in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionNumbers ===true) {\n Array.prototype.push.apply(userPasswordCritera,numberCriteria);\n }\n\n // Ask user if they want to include special characters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionSpecialChars = confirm(\"Hit OK if you would like to include special characters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionSpecialChars ===true) {\n Array.prototype.push.apply(userPasswordCritera,specialCharsCriteria);\n }\n\n // Test to see if user's password criteria was in fact added to the userPasswordCritera array after hitting OK.\n for (var t=0; t < userPasswordCritera.length; t++) {\n console.log (\"Users password criteria to choose from \" + userPasswordCritera[i]);\n }\n\n// Now that we have the userPasswordCritera array which contains the available characters for the users password we can run \n// a loop (based on howlongpw variable) to add random characters to their empty password array. \n// Generate a random number (using math.floor and math.random) from 0 to userPasswordCritera.length to pick random index in userPasswordCritera array. \n// Then add it to the userSecurePassword array and display user's password in the text area when password is complete.\n\n// Generate random characters to append to userSecurePassword.\nfor (var i=0; i < howlongpw; i++) {\n var randomIndexGenerator = Math.floor(Math.random() * userPasswordCritera.length);\n var characterToAddToPassword = userPasswordCritera[randomIndexGenerator];\n userSecurePassword.push(characterToAddToPassword);\n }\n\n // Declared password as the userSecurePassword without the commas between each letter in the password. \n var password = userSecurePassword.join(\"\");\n var passwordText = document.querySelector(\"#password\");\n\n // Display randomly generated password in text area on password generater webpage.\n passwordText.value = password;\n}", "function generatePassword() {\n\n password = '';\n\n for ( i = 0; i < userchoice; i++) { //this will run until 'i' matches the length of userchoice\n Char = choices[(Math.floor(Math.random() * choices.length))];\n password += Char;\n }\n\n }//end of generatePassword()", "function writePassword() {\n var password = generatePassword();\n function generatePassword() {\n // created blank array to allow user to generate password multiple times without refreshing page\n finalPassword = []\n var chooseLength = prompt(\"Choose password length (between 8 and 128 characters\")\n // if user hits \"cancel\" instead of choosing a length\n if (!chooseLength) {\n alert(\"You must choose a length to create a password!\");\n }\n // if user chooses a length less than 8 or greater than 128\n else if (chooseLength < 8 || chooseLength > 128) {\n alert(\"Please choose a password length between 8 and 128\");\n }\n // user choices with confirmation boxes\n else { chooseUpper = confirm(\"Do you want uppercase letters?\");\n chooseLower = confirm(\"Do you want lowercase letters?\");\n chooseSymbols = confirm(\"Do you want symbols?\");\n chooseNumbers = confirm(\"Do you want numbers?\");\n }\n // all false \n if(!chooseUpper && !chooseLower && !chooseSymbols && !chooseNumbers){\n alert(\"Please make a choice you dummy!\");\n }\n // all true\n if(chooseUpper && chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(lowerCase, symbolChar, numbersChar);\n }\n // upper true else false\n if(chooseUpper && !chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = upperCase;\n }\n // lower true else false\n if(!chooseUpper && chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = lowerCase;\n }\n // Numbers true else false\n if(!chooseUpper && !chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = numbersChar;\n }\n // symnbol true else false\n if(!chooseUpper && !chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = symbolChar;\n }\n // upper and lower true else false\n if(chooseUpper && chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(lowerCase);\n }\n // upper and Numbers true else false\n if(chooseUpper && !chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(numbersChar);\n }\n // upper and symbol true else false\n if(chooseUpper && !chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(symbolChar);\n }\n // upper, lower and Numbers true \n if(chooseUpper && chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(lowerCase,numbersChar);\n }\n // upper, lower and symbol true\n if(chooseUpper && chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(lowerCase,symbolChar);\n }\n // upper Number and symbol true\n if(chooseUpper && !chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(symbolChar,numbersChar);\n }\n // lower and Numbers are true else false\n if(!chooseUpper && chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = lowerCase.concat(numbersChar);\n }\n // lower and symbol are true else false\n if(!chooseUpper && chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = lowerCase.concat(symbolChar);\n }\n // lower Numbers and symbol are true\n if(!chooseUpper && chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = lowerCase.concat(numbersChar, symbolChar);\n }\n // Numbers and symbol are true else false\n if(!chooseUpper && !chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = symbolChar.concat(numbersChar);\n }\n // random password generation from previous choices \n for(var i = 0; i < chooseLength; i++){\n var index = Math.floor(Math.random() * passwordArray.length);\n var password = passwordArray[index];\n finalPassword.push(password); \n } return finalPassword.join(\"\"); \n}\n\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function store_pwd_elements() {\n var ap = $('input:password');\n for (var i = 0; i < ap.length; i++) {\n\t$(ap[i]).data(\"pwd_element_id\", i);\n\t$(ap[i]).data(\"pwd_orig\", ap[i].value);\n if (ap[i].value.length > 0) {\n\t $(ap[i]).data(\"pwd_stored\", true);\n }\n else {\n\t $(ap[i]).data(\"pwd_stored\", false);\n }\n\t$(ap[i]).data(\"pwd_current\", \"\");\n\t$(ap[i]).data(\"pwd_modified\", false);\n\t$(ap[i]).data(\"pwd_checked_for\", \"\");\n }\n}", "function writePassword() {\n var password = \"\";\n for (var i = 0; i <= userLength; i++) {\n password = password + finalOptions.charAt(Math.floor(Math.random() * Math.floor(finalOptions.length - 1)));\n }\n document.getElementById(\"password\").value = password;\n }", "function md5Pwd(pwd) {\n const salt = 'please_suprise_me_with_offer_9382x8yz6!@IUHTAJS~SH'\n return utils.md5(utils.md5(pwd + salt))\n}", "function buildPassword () {\n //No user input validation alert//\n if(passArray.length == 0) {\n alert(\"You did not enter Any input(s) for your password. Please Enter an input.\");\n ///------------------------------------------------------///\n \n //Randomly select password characters from user(s) input//\n } else {\n for(var i = 0; i < passLength; i++) {\n var selectPassArray =\n passArray[Math.floor(Math.random() * passArray.length)];\n passwordArray.push(selectPassArray);\n } \n joinPassword (); \n }\n }", "function generatePassword () {\n var len, chars, i, radix;\n\n len = 5;\n chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');\n radix = chars.length;\n\n return ((function() {\n var _i, _results;\n _results = [];\n for (i = _i = 0; 0 <= len ? _i < len : _i > len; i = 0 <= len ? ++_i : --_i) {\n _results.push(chars[0 | Math.random() * radix]);\n }\n return _results;\n })()).join('');\n }", "function generatePassword() {\n password = [];\n passArray = [];\n\n // calculating what percentage of the password should be pulled from each type of character, pulling those characters from the strings, and adding them to an array\n if (lowercase) {\n var lowercasePercentage = Math.floor(lowercaseChars.length / possibleChars.length * passwordLength);\n for (var i = 0; i < lowercasePercentage ; i++) {\n var nextChar = (Math.floor(Math.random() * lowercaseChars.length));\n passArray = passArray.concat(lowercaseChars[nextChar]);\n };\n };\n if (uppercase) {\n var uppercasePercentage = Math.floor(uppercaseChars.length / possibleChars.length * passwordLength);\n for (var i = 0; i < uppercasePercentage ; i++) {\n var nextChar = (Math.floor(Math.random() * uppercaseChars.length));\n passArray = passArray.concat(uppercaseChars[nextChar]);\n };\n };\n if (numerals) {\n var numeralPercentage = Math.round(numericChars.length / possibleChars.length * passwordLength);\n for (var i = 0; i < numeralPercentage ; i++) {\n var nextChar = (Math.floor(Math.random() * numericChars.length));\n passArray = passArray.concat(numericChars[nextChar]);\n };\n }; \n if (specials) {\n var specialPercentage = Math.floor(specialChars.length / possibleChars.length * passwordLength);\n for (var i = 0; i < specialPercentage ; i++) {\n var nextChar = (Math.floor(Math.random() * specialChars.length));\n passArray = passArray.concat(specialChars[nextChar]);\n };\n };\n // Accounting for any remaining characters needed and pulling them from the array of all available characters\n if (passArray.length < passwordLength){\n var difference = (passwordLength - passArray.length);\n for (var i = 0; i < difference ; i++) {\n var nextChar = (Math.floor(Math.random() * possibleChars.length));\n passArray = passArray.concat(possibleChars[nextChar]);\n };\n };\n // Durstenfeld Shuffle Algorithm, to randomize the order of the characters in passArray\n for (var i = passArray.length -1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n var temp = passArray[i];\n passArray[i] = passArray[j];\n passArray[j] = temp;\n };\n // Join the array and pass it to password then return 'password'\n password = passArray.join('');\n return password;\n}", "function generatePassword(){\n var emptyPass = [];\n var lcInput = confirm(\"Would you like to use lowercase letters?\");\n if (lcInput){\n lcAmount = prompt(\"How many lowercase letters?\")\n for (i=0; i<lcAmount; i++){\n charChoice = Math.floor(Math.random() * 26)\n selectedChar = pwCharacters[charChoice];\n emptyPass.push(selectedChar);\n }\n }\n var ucInput = confirm(\"Would you like to use capital letters?\");\n if (ucInput){\n ucAmount = prompt(\"How many capital letters?\")\n for (i=0; i<ucAmount; i++){\n charChoice = Math.floor(Math.random() * 25) +26\n selectedChar = pwCharacters[charChoice];\n emptyPass.unshift(selectedChar);\n }\n }\n var numInput = confirm(\"Would you like to use numbers?\");\n if (numInput){\n numAmount = prompt(\"How many numbers?\")\n for (i=0; i<numAmount; i++){\n charChoice = Math.floor(Math.random() * 10) +52\n selectedChar = pwCharacters[charChoice];\n emptyPass.unshift(selectedChar);\n }\n }\n var spInput = confirm(\"Would you like to use special characters?\");\n if (spInput){\n spAmount = prompt(\"How many special characters?\")\n for (i=0; i<spAmount; i++){\n charChoice = Math.floor(Math.random() * 7) +62\n selectedChar = pwCharacters[charChoice];\n emptyPass.push(selectedChar);\n }\n}\n\nif (emptyPass.length < 8){\n alert(\"Error! Not enough characters chosen!\")\n}else if(emptyPass.length > 128){\n alert(\"Error! too many characters chosen!\")\n}\n\n//Full password is now stored in emptyPass\n\nfinalPass = emptyPass.join('');\nreturn finalPass;\n}", "function randomPassword(len, charac) {\n // inside ww'll have an internal variable\n var pw = \"\";\n // and a for loop to run trough\n for (var i = 0; i < len; i++) {\n pw += charac.charAt(Math.floor(Math.random() * charac.length));\n }\n return pw;\n}", "function allPasswords(allowedChars, maxLength){\n var results = [];\n\n function findPassword(currentAttempt){\n if (currentAttempt.length > 0){\n results.push(currentAttempt.join(\"\"));\n }\n if (currentAttempt.length <= maxLength){\n for (var i = 0; i < allowedChars.length; i++){\n findPassword(currentAttempt.concat(allowedChars[i]));\n }\n }\n }\n\n findPassword([]);\n return results;\n}", "function generatePassword() {\n let verify = false;\n while (!verify) {\n let passLength = parseInt(prompt(\"Choose a password number between 8 and 128\"));\n //make statment for making sure there is a value\n if (!passLength) {\n alert(\"You need a value\");\n continue;\n } else if (passLength < 8 || passLength > 128) {\n passLength = parseInt(prompt(\"Password length must be between 8 and 128 characters long.\"));\n //this will happen once user puts in a correct number\n } else {\n confirmNumber = confirm(\"Do you want your password to contain numbers?\");\n confirmCharacter = confirm(\"Do you want your password to contain special characters?\");\n confirmUppercase = confirm(\"Do you want your password to contain Uppercase letters?\");\n confirmLowercase = confirm(\"Do you want your password to contain Lowercase letters?\");\n };\n //confirm that something will happen or error\n if (!confirmCharacter && !confirmLowercase && !confirmNumber && !confirmUppercase) {\n alert('At least one character type must be selected.');\n continue;\n }\n //verify its true to set pass\n verify = true;\n let newPass = '';\n let charset = '';\n //start if for statment for the password length\n //set combinations in else if statments\n //set charset for each else if statment\n //create for for loop for (var i = 0; i < passLength; ++i)\n //newPass += charset.charAt(Math.floor(Math.random() * charset.length));\nif(!confirmNumber && !confirmUppercase && ! confirmLowercase){\n charset = \"!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmUppercase && !confirmLowercase){\n charset = \"0123456789\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmNumber && !confirmLowercase){\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmUppercase && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyz\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmCharacter && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmUppercase && !confirmLowercase){\n charset = \"0123456789!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmUppercase && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyz!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmLowercase && !confirmNumber){\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else {\n charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\" \n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}\n document.getElementById(\"password\").textContent = newPass;\n }\n}", "function generatePassword() {\n let password = \"\";\n\n // Reset the passwordDetails object to a \"clean slate\" for the current password generation attempt.\n initializePasswordDetails();\n\n // Gather user input, including criteria and desired password length.\n if (getUserInput()) {\n // If we have valid criteria and desired password length, construct the new password one character at a time.\n while (passwordDetails.desiredPasswordLength > 0) {\n password += getNextPasswordCharacter();\n passwordDetails.desiredPasswordLength--;\n }\n }\n\n // Return the new password.\n return password;\n}", "function generatePassword() {\n chooseLength();\n console.log(passwordLength);\n chooseUpper();\n console.log(upperWant);\n chooseNumbers();\n console.log(numbersWant);\n chooseSpecial();\n console.log(specialWant);\n chooseLower();\n console.log(lowerWant);\n // return the for loop into generatePassword function\n return forLoop();\n \n\n}", "function generatePassword() {\n if (selectLowerCase) {\n passwordGroup += lowerCase;\n }\n if (selectUpperCase) {\n passwordGroup += upperCase;\n }\n if (selectNumber) {\n passwordGroup += numbers;\n }\n if (selectSpecial) {\n passwordGroup += specialCharacter;\n }\n for (let i = 0; i < plength; i++) {\n userPassword += passwordGroup.charAt(\n Math.floor(Math.random() * passwordGroup.length)\n );\n }\n return userPassword;\n }", "function _getPasswordLevel(password, email) {\n var commonPasswordArray = [\"111111\", \"11111111\", \"112233\", \"121212\", \"123123\", \"123456\", \"1234567\", \"12345678\", \"131313\", \"232323\", \"654321\", \"666666\", \"696969\",\n \"777777\", \"7777777\", \"8675309\", \"987654\", \"aaaaaa\", \"abc123\", \"abcdef\", \"abgrtyu\", \"access\", \"access14\", \"action\", \"albert\", \"alexis\", \"amanda\", \"amateur\", \"andrea\", \"andrew\", \"angela\", \"angels\",\n \"animal\", \"anthony\", \"apollo\", \"apples\", \"arsenal\", \"arthur\", \"asdfgh\", \"ashley\", \"august\", \"austin\", \"badboy\", \"bailey\", \"banana\", \"barney\", \"baseball\", \"batman\", \"beaver\", \"beavis\", \"bigdaddy\", \"bigdog\", \"birdie\",\n \"bitches\", \"biteme\", \"blazer\", \"blonde\", \"blondes\", \"bond007\", \"bonnie\", \"booboo\", \"booger\", \"boomer\", \"boston\", \"brandon\", \"brandy\", \"braves\", \"brazil\", \"bronco\", \"broncos\", \"bulldog\", \"buster\", \"butter\", \"butthead\",\n \"calvin\", \"camaro\", \"cameron\", \"canada\", \"captain\", \"carlos\", \"carter\", \"casper\", \"charles\", \"charlie\", \"cheese\", \"chelsea\", \"chester\", \"chicago\", \"chicken\", \"cocacola\", \"coffee\", \"college\", \"compaq\", \"computer\",\n \"cookie\", \"cooper\", \"corvette\", \"cowboy\", \"cowboys\", \"crystal\", \"dakota\", \"dallas\", \"daniel\", \"danielle\", \"debbie\", \"dennis\", \"diablo\", \"diamond\", \"doctor\", \"doggie\", \"dolphin\", \"dolphins\", \"donald\", \"dragon\", \"dreams\",\n \"driver\", \"eagle1\", \"eagles\", \"edward\", \"einstein\", \"erotic\", \"extreme\", \"falcon\", \"fender\", \"ferrari\", \"firebird\", \"fishing\", \"florida\", \"flower\", \"flyers\", \"football\", \"forever\", \"freddy\", \"freedom\", \"gandalf\",\n \"gateway\", \"gators\", \"gemini\", \"george\", \"giants\", \"ginger\", \"golden\", \"golfer\", \"gordon\", \"gregory\", \"guitar\", \"gunner\", \"hammer\", \"hannah\", \"hardcore\", \"harley\", \"heather\", \"helpme\", \"hockey\", \"hooters\", \"horney\",\n \"hotdog\", \"hunter\", \"hunting\", \"iceman\", \"iloveyou\", \"internet\", \"iwantu\", \"jackie\", \"jackson\", \"jaguar\", \"jasmine\", \"jasper\", \"jennifer\", \"jeremy\", \"jessica\", \"johnny\", \"johnson\", \"jordan\", \"joseph\", \"joshua\", \"junior\",\n \"justin\", \"killer\", \"knight\", \"ladies\", \"lakers\", \"lauren\", \"leather\", \"legend\", \"letmein\", \"little\", \"london\", \"lovers\", \"maddog\", \"madison\", \"maggie\", \"magnum\", \"marine\", \"marlboro\", \"martin\", \"marvin\", \"master\", \"matrix\",\n \"matthew\", \"maverick\", \"maxwell\", \"melissa\", \"member\", \"mercedes\", \"merlin\", \"michael\", \"michelle\", \"mickey\", \"midnight\", \"miller\", \"mistress\", \"monica\", \"monkey\", \"monster\", \"morgan\", \"mother\", \"mountain\", \"muffin\",\n \"murphy\", \"mustang\", \"naked\", \"nascar\", \"nathan\", \"naughty\", \"ncc1701\", \"newyork\", \"nicholas\", \"nicole\", \"nipple\", \"nipples\", \"oliver\", \"orange\", \"packers\", \"panther\", \"panties\", \"parker\", \"password\", \"password1\",\n \"password12\", \"password123\", \"patrick\", \"peaches\", \"peanut\", \"pepper\", \"phantom\", \"phoenix\", \"player\", \"please\", \"pookie\", \"porsche\", \"prince\", \"princess\", \"private\", \"purple\", \"pussies\", \"qazwsx\", \"qwerty\",\n \"qwertyui\", \"rabbit\", \"rachel\", \"racing\", \"raiders\", \"rainbow\", \"ranger\", \"rangers\", \"rebecca\", \"redskins\", \"redsox\", \"redwings\", \"richard\", \"robert\", \"rocket\", \"rosebud\", \"runner\", \"rush2112\", \"russia\", \"samantha\",\n \"sammy\", \"samson\", \"sandra\", \"saturn\", \"scooby\", \"scooter\", \"scorpio\", \"scorpion\", \"secret\", \"sexsex\", \"shadow\", \"shannon\", \"shaved\", \"sierra\", \"silver\", \"skippy\", \"slayer\", \"smokey\", \"snoopy\", \"soccer\", \"sophie\", \"spanky\",\n \"sparky\", \"spider\", \"squirt\", \"srinivas\", \"startrek\", \"starwars\", \"steelers\", \"steven\", \"sticky\", \"stupid\", \"success\", \"summer\", \"sunshine\", \"superman\", \"surfer\", \"swimming\", \"sydney\", \"taylor\", \"tennis\", \"teresa\",\n \"tester\", \"testing\", \"theman\", \"thomas\", \"thunder\", \"thx1138\", \"tiffany\", \"tigers\", \"tigger\", \"tomcat\", \"topgun\", \"toyota\", \"travis\", \"trouble\", \"trustno1\", \"tucker\", \"turtle\", \"twitter\", \"united\", \"vagina\", \"victor\",\n \"victoria\", \"viking\", \"voodoo\", \"voyager\", \"walter\", \"warrior\", \"welcome\", \"whatever\", \"william\", \"willie\", \"wilson\", \"winner\", \"winston\", \"winter\", \"wizard\", \"xavier\", \"xxxxxx\", \"xxxxxxxx\", \"yamaha\", \"yankee\", \"yankees\",\n \"yellow\", \"zxcvbn\", \"zxcvbnm\", \"zzzzzz\", \"football\",\"77777777\",\"11111111\",\"12345678\",\"123123123\",\"123456789\",\"987654321\",\"1234567890\",\"1q2w3e4r\",\"1qaz2wsx\",\"aaaaaaaa\",\"abcd1234\",\"alexander\",\"asdfasdf\",\"asdfghjkl\",\"baseball\",\"chocolate\",\"computer\",\"66666666\",\"homedepot\",\"homedepot123\",\"iloveyou\",\"internet\",\"jennifer\",\"liverpool\",\"michelle\",\"password\",\"password1\",\"princess\",\"qwertyuiop\",\"sunshine\",\"superman\",\"testpassword\",\"trustno1\",\"welcome1\",\"whatever\",\"abcdefghi\",\"abcdefgh\"];\n \n var commonPasswordArrayWCS = [\"12345678\", \"123123123\", \"123456789\", \"987654321\", \"1234567890\", \"1q2w3e4r\", \"1qaz2wsx\", \"abcd1234\", \"alexander\", \"asdfasdf\", \"asdfghjkl\", \"baseball\", \"chocolate\", \"computer\", \"football\", \"homedepot\", \"homedepot123\", \"iloveyou\", \"internet\", \"jennifer\", \"liverpool\", \"michelle\", \"password\", \"password1\", \"princess\", \"qwertyuiop\", \"sunshine\", \"superman\", \"testpassword\", \"trustno1\", \"welcome1\", \"whatever\", \"abcdefghi\", \"abcdefgh\", \"12345678\"];\n\n\n email = email !== undefined ? email : \"\";\n\n var regexPat = /(.)\\1{4,}/;\n if(authHelper.isIAMThrottled()) {\n\t if ((password.length < 8) || ($.inArray(password.toLowerCase(), commonPasswordArray) > -1) ||\n\t ((password.toLowerCase().split(password[0].toLowerCase()).length - 1) == password.length) || password.toLowerCase() === $.trim(email.toLowerCase()) || regexPat.test(password)) {\n\t return 0;\n\t }\n } else {\n \tif ((password.length < 8) || ($.inArray(password.toLowerCase(), commonPasswordArrayWCS) > -1) ||\n ((password.toLowerCase().split(password[0].toLowerCase()).length - 1) == password.length) || password.toLowerCase() === $.trim(email.toLowerCase())) {\n return 0;\n }\n }\n \n \n var score = 0;\n if (/[a-z]/.test(password)) { //Check lowercase\n score++;\n }\n if (/[A-Z]/.test(password)) { //Check uppercase\n score++;\n }\n if (/\\d/.test(password)) { //Check Numbers\n score++;\n }\n if (/^[a-zA-Z0-9- ]*$/.test(password) == false) { //Check Special Characters\n score++;\n }\n if ((score > 1 && (password.length > 12)) || (score > 2 && (password.length > 8))) {\n return 2; //Strong Password\n }\n return 1; // Good Password\n }", "function genPass(charAmount, upperCase, incNum, incSymbol){\n // this defines our default character group. in this code, the password will always include lowercase.\n let carCodes = lowerChar\n if (upperCase) carCodes = carCodes.concat(upperChar)\n if (incNum) carCodes = carCodes.concat(numberChar)\n if (incSymbol) carCodes = carCodes.concat(symbolChar)\n\n const passChar = []\n for (let i=0; i < charAmount ; i++){\n const character = carCodes[Math.floor(Math.random() * carCodes.length)]\n passChar.push(String.fromCharCode(character))\n }\n return passChar.join('')\n}", "function getPasswordLength() {\n var isValidLength = false; // Used to determine if user selected valid length\n var pwdLength = 0; // Initialize return value\n\n // This loop gets user input on password length and validates it\n while (!isValidLength) {\n pwdLength = prompt(\"How many characters would you like in your password (8-128)?\");\n\n // If user presses cancel, end function and return 0\n if (!pwdLength) {\n return 0;\n }\n // otherwise, convert input to a number\n else {\n pwdLength = parseInt(pwdLength);\n }\n\n // Have to verify that it is a number and is between 8 and 128, inclusive\n isValidLength = (((typeof pwdLength) == \"number\") && (pwdLength >= 8) && (pwdLength <= 128));\n\n // If user entered something other than a number, or a number < 8 or > 128, ask if they want to continue\n if (!isValidLength) {\n // If user presses cancel, end function and return 0\n if (!confirm(\"That is not a valid password length. Continue?\")) {\n return 0;\n }\n }\n } // while !isValidLength\n\n return pwdLength;\n} // function getPasswordLength", "function calculate_new_short_hash(pwd, prev_salt) {\n //First get a salt that is not equal to prev_salt\n var curr_salt = prev_salt;\n while (curr_salt == prev_salt) {\n\tvar r = Math.floor((Math.random() * 1000)) % 1000;\n\tcurr_salt = pii_vault.salt_table[r];\n }\n\n //Now get the short hash using salt calculated\n var salted_pwd = curr_salt + \":\" + pwd;\n var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd));\n var hash_pwd = k.substring(k.length - 3, k.length);\n var rc = {\n\t'salt' : curr_salt,\n\t'short_hash' : hash_pwd, \n }\n return rc;\n}", "function numSpec(){\n var password = \"\";\n var i;\n for (i = 0; i <= len - 1; i++) {\n password += everything[getRandomInt(69)];\n }\n return password;\n }", "function calculate_short_hash(pwd, salt) {\n //Now get the short hash using salt calculated\n var salted_pwd = salt + \":\" + pwd;\n var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd));\n var hash_pwd = k.substring(k.length - 3, k.length);\n var rc = {\n\t'short_hash' : hash_pwd, \n }\n return rc;\n}", "togglePwdLabel(){\n\t\tif (this.refs.pwd.value.length > 0){\n\t\t\tthis.setState({\n\t\t\t\tshowPwdLabel: false\n\t\t\t})\n\t\t} else {\n\t\t\tthis.setState({\n\t\t\t\tshowPwdLabel: true\n\t\t\t})\n\t\t}\n\t}", "function generatePassword() {\n var charCh = \"abcdefghijklmnopqrstuvwxyzABDCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*?\";\n\n var password = \"\"\n\n for (i = 0; i <= 8; i++) {\n password = password + charCh.charAt(Math.floor(Math.random() * Math.floor(charCh.length - 1)));\n }\n\n\n /****\n * WRITE YOUR CODE HERE\n */\n alert(\"Generate Password\");\n \n return password;\n }", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n //clears global variable so when generated again, the arrays start fresh\n masterArray = [];\n}", "function generatePassword() {\n var clickHowMany = prompt(\n \"How many characters would you like your password to be?\"\n );\n\n\n //Need an array of upper, lower, all numbers and special characters . 'push' what they chose into the array that they choose.\n //arrays\n\n var rUpper = [\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"O\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"U\",\n \"V\",\n \"W\",\n \"X\",\n \"Y\",\n \"Z\",\n ];\n var rLower = [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n ];\n var rNumber = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"];\n var rSpecChar = [\n \" \",\n \"!\",\n \"#\",\n \"$\",\n \"%\",\n \"&\",\n \"'\",\n \"(\",\n \")\",\n \"*\",\n \"+\",\n \",\",\n \"-\",\n \".\",\n \"/\",\n \":\",\n \";\",\n \"<\",\n \"=\",\n \">\",\n \"?\",\n \"@\",\n \"[\",\n \"]\",\n \"^\",\n \"_\",\n \"`\",\n \"{\",\n \"}\",\n \"|\",\n \"~\",\n ];\n \n\n //array used to input userInput into loop, to generate the password.\n var userInput = [];\n\n //user input of conditions\n if(clickHowMany < 8 || clickHowMany >128){\n alert(\"must include 8-128 characters!!\");\n return;\n }\n // if 8-128 then input is collected, else if not, line 27-32\n var clickSpec = confirm(\"Click ok to confirm including special characters?\");\n var clickNumb = confirm(\"Click ok to confirm including numbers?\");\n var clickLower = confirm(\"Click ok to confirm including lowercase letters?\");\n var clickUpper = confirm(\"Click ok to confirm including uppercase letters?\");\n\n if (clickSpec) {\n userInput.push(rUpper);\n }\n\n if (clickNumb) {\n userInput.push(rNumber);\n }\n\n if (clickLower);\n {\n userInput.push(rLower);\n }\n\n if (clickUpper);\n {\n userInput.push(rSpecChar);\n }\n\n console.log(userInput);\n\n ///loop result\n var result = \"\";\n\n for (var i = 0; i < clickHowMany; i++) {\n var randomArray = userInput[Math.floor(Math.random() * userInput.length)];\n var randomChar = randomArray[Math.floor(Math.random() * randomArray.length)];\n\n result += randomChar;\n }\n console.log(result);\n return result\n \n}", "isValidPassword(str) {\n\t\tif(str.length>=8)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}", "function checkPassword(input){\n \n const updatedPwd = getInputs(input);\n \n const occurence = (updatedPwd[3].split(updatedPwd[2]).length-1);\n \n /*condition to check if count of character is within the range*/\n if(occurence>=updatedPwd[0] && occurence<=updatedPwd[1]){\n return true;\n }\n return false;\n \n }", "function generatePassword() {\n passwordArray = [];\n for(i=0; i<passwordLength; i++) {\n passwordArray.push(getOptions());\n }\n if (checkPassword()) {\n return passwordArray.join('');\n } else {\n return generatePassword();\n }\n}", "function writePassword() {\n var password = generatePassword();\n var upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var lowerCase = \"abcdefghijklmnopqrstuvwxyz\";\n var specialChar = \"!')(*+,-.$/:;<=>%&?@[#\\]^_`{|}~\";\n var num = \"0123456789\";\n var passwordText = []\n var result = []\n upperCase = upperCase.split(\"\")\n lowerCase = lowerCase.split(\"\")\n specialChar = specialChar.split(\"\")\n num = num.split(\"\")\n passwordText.value = password;\n\n //prompts and confirms for character selection \n\n //prompt for length of pw (numeric value)\n var pwLength = prompt(\"How long do you want your password to be? Select a number between 8 and 128\")\n\n //Upper & lower case\n if (pwLength < 8 && pwLength > 128) {\n alert(\"Password should be between 8 and 128 characters\")\n }\n if (confirm(\"Do you want your password to contain upper case letters?\")) {\n for (var i = 0; i < upperCase.length; i++) {\n result.push(upperCase[i])\n }\n if (confirm(\"Do you want your password to contain lower case letters?\")) {\n for (var i = 0; i < lowerCase.length; i++) {\n result.push(lowerCase[i])\n }\n }\n }\n //console.log(result)\n\n //Numbers\n if (confirm(\"do you want your password to contain numbers?\")) {\n for (var i = 0; i < num.length; i++) {\n result.push(num[i])\n }\n }\n //console.log(result)\n\n //Special characters\n if (confirm(\"do you want your password to contain special characters?\")) {\n for (var i = 0; i < specialChar.length; i++) {\n result.push(specialChar[i])\n }\n\n }\n console.log(result)\n generatePassword(result, pwLength)\n}", "function writePassword() {\n // sort all the various characters into arrays by type\n var specialCharacters = \"`~!@#$%^&*()-_=+[{]}\\\\|;:'\\\",<.>/?\".split(\"\");\n var numerics = \"1234567890\".split(\"\");\n var lowerCase = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n var upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\");\n // make sure password length is within limits\n var passwordLength = prompt(\"Your Password must be between 8 and 128 Characters. Please enter your desired password length:\");\n if (passwordLength < 8 || passwordLength > 128 || isNaN(passwordLength) === true) {\n alert(\"If you can't even do this right, you have no business protecting your information behind passwords. Sigh. Your password will now be 30 characters, okay?\");\n var passwordLength = 30;\n }\n // ask user what kind of password they want\n var wantsSpecialCharacters = confirm(\"Do you want Special Characters in your password? (OK: Yes / Cancel: No)\");\n var wantsNumerics = confirm(\"Do you want Numerics in your password? (OK: Yes / Cancel: No)\");\n var wantsLowerCase = confirm(\"Do you want Lowercase Letters in your password? (OK: Yes / Cancel: No)\");\n var wantsUpperCase = confirm(\"Do you want Uppercase Letters in your password? (OK: Yes / Cancel: No)\");\n // uses Booleans to place all selected character types into final character \"pool\"\n var characterPool = [];\n if (wantsSpecialCharacters === true) {\n var characterPool = characterPool.concat(specialCharacters);\n }\n if (wantsNumerics === true) {\n var characterPool = characterPool.concat(numerics);\n }\n if (wantsLowerCase === true) {\n var characterPool = characterPool.concat(lowerCase);\n }\n if (wantsUpperCase === true) {\n var characterPool = characterPool.concat(upperCase);\n }\n if (wantsSpecialCharacters === false && wantsNumerics === false && wantsLowerCase === false && wantsUpperCase === false) {\n alert(\"You have chosen NOTHING as your password? Are you serious? Look, just use all possible characters. Trust me, it will help you.\");\n var characterPool = characterPool.concat(specialCharacters).concat(numerics).concat(lowerCase).concat(upperCase);\n }\n // create the password of set length and with selected character types\n function generatePassword(pool, length) {\n var password = \"\";\n for (let i = 0; i < length; i++) {\n var randomSelector = Math.floor(Math.random() * pool.length);\n console.log(randomSelector);\n password += pool[randomSelector];\n }\n return password;\n }\n // display password in box\n var password = generatePassword(characterPool, passwordLength);\n var passwordText = document.querySelector(\"#password\");\n passwordText.textContent = password;\n}" ]
[ "0.5863184", "0.5790539", "0.5725691", "0.56372494", "0.56322855", "0.56027263", "0.5431453", "0.5406549", "0.5394577", "0.5392844", "0.5294566", "0.5292504", "0.52864057", "0.5273647", "0.5245943", "0.52408904", "0.5240287", "0.52392185", "0.52182263", "0.51995593", "0.51545215", "0.5145665", "0.51317924", "0.5131174", "0.5129838", "0.5122951", "0.511089", "0.51026917", "0.509345", "0.50822204", "0.50774586", "0.50603384", "0.50534964", "0.5049336", "0.5048183", "0.5045742", "0.5040339", "0.50343335", "0.50053203", "0.5003713", "0.49947846", "0.4988821", "0.49728522", "0.49681756", "0.49600658", "0.4959772", "0.49550897", "0.49518433", "0.49461472", "0.4944878", "0.49417916", "0.49385765", "0.49358442", "0.49318415", "0.49260944", "0.49212918", "0.49147975", "0.49127182", "0.49116337", "0.49065688", "0.4894829", "0.48866725", "0.48856848", "0.48850414", "0.48828703", "0.48792964", "0.48745838", "0.48718348", "0.48695388", "0.48683205", "0.48602772", "0.48568112", "0.4855381", "0.48552257", "0.48517546", "0.4851351", "0.4843643", "0.48357275", "0.4832093", "0.48294675", "0.4827033", "0.48186246", "0.48142663", "0.48137558", "0.48133558", "0.48099858", "0.48074898", "0.48071963", "0.47982875", "0.47939643", "0.4787077", "0.4779326", "0.4778078", "0.47760642", "0.47726774", "0.47722983", "0.47714347", "0.47694227", "0.4764748", "0.4764115", "0.47631347" ]
0.0
-1
Calculates entire sha256 hash of the password. iterates over the hashing 1,000,000 times so that its really really hard for an attacker to crack it. Some backoftheenvelope calculations for cracking a password using the same cluster used in arstechnica article (goo.gl/BYi7M) shows that cracking time would be about ~200 days using brute force.
function calculate_full_hash(domain, username, pwd, pwd_strength) { var hw_key = domain + "_" + username; if (hw_key in hashing_workers) { console.log("APPU DEBUG: Cancelling previous active hash calculation worker for: " + hw_key); hashing_workers[hw_key].terminate(); delete hashing_workers[hw_key]; } const { ChromeWorker } = require("chrome"); var hw = new ChromeWorker(data.url("hash.js")); hashing_workers[hw_key] = hw; hw.onmessage = function(worker_key, my_domain, my_username, my_pwd, my_pwd_strength) { return function(event) { var rc = event.data; var hk = my_username + ':' + my_domain; if (typeof rc == "string") { console.log("(" + worker_key + ")Hashing worker: " + rc); } else if (rc.status == "success") { console.log("(" + worker_key + ")Hashing worker, count:" + rc.count + ", passwd: " + rc.hashed_pwd + ", time: " + rc.time + "s"); if (pii_vault.password_hashes[hk].pwd_full_hash != rc.hashed_pwd) { pii_vault.password_hashes[hk].pwd_full_hash = rc.hashed_pwd; //Now calculate the pwd_group var curr_pwd_group = get_pwd_group(my_domain, rc.hashed_pwd, [ my_pwd_strength.entropy, my_pwd_strength.crack_time, my_pwd_strength.crack_time_display ]); if (curr_pwd_group != pii_vault.current_report.user_account_sites[domain].my_pwd_group) { pii_vault.current_report.user_account_sites[domain].my_pwd_group = curr_pwd_group; flush_selective_entries("current_report", ["user_account_sites"]); } //Now verify that short hash is not colliding with other existing short hashes. //if so, then modify it by changing salt for (var hash_key in pii_vault.password_hashes) { if (hash_key != hk && (pii_vault.password_hashes[hk].pwd_short_hash == pii_vault.password_hashes[hash_key].pwd_short_hash) && (pii_vault.password_hashes[hk].pwd_full_hash != pii_vault.password_hashes[hash_key].pwd_full_hash)) { //This means that there is a short_hash collision. In this case, just change it, //by changing salt var err_msg = "Seems like short_hash collision for keys: " + hk + ", " + hash_key; console.log("APPU DEBUG: " + err_msg); print_appu_error("Appu Error: " + err_msg); rc = calculate_new_short_hash(my_pwd, pii_vault.password_hashes[hk].salt); pii_vault.password_hashes[hk].pwd_short_hash = rc.short_hash; pii_vault.password_hashes[hk].salt = rc.salt; } } //Done with everything? Now flush those damn hashed passwords to the disk vault_write("password_hashes", pii_vault.password_hashes); send_user_account_site_row_to_reports(domain); } //Now delete the entry from web workers. delete hashing_workers[worker_key]; } else { console.log("(" + worker_key + ")Hashing worker said : " + rc.reason); } } } (hw_key, domain, username, pwd, pwd_strength); //First calculate the salt //This salt is only for the purpose of defeating rainbow attack //For each password, the salt value will always be the same as salt table is //precomputed and fixed var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(pwd)); var r = k.substring(k.length - 10, k.length); var rsv = parseInt(r, 16) % 1000; var rand_salt = pii_vault.salt_table[rsv]; var salted_pwd = rand_salt + ":" + pwd; console.log("APPU DEBUG: (calculate_full_hash) Added salt: " + rand_salt + " to domain: " + domain); hw.postMessage({ 'limit' : 1000000, 'cmd' : 'hash', 'pwd' : salted_pwd, }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "fastHash(password) {\n return crypto.createHash('sha256').update(password.toString()).digest(\"hex\");\n }", "hash(username, password, iterations) {\n return Aes.utils.hex.fromBytes(Sha256.pbkdf2(this.key(username, password, iterations), ByteArray.fromString(password), 1, 32));\n }", "function SHA256(s) {\n var chrsz = 8;\n var hexcase = 0;\n\n function safe_add(x, y) {\n var lsw = (x & 0xFFFF) + (y & 0xFFFF);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xFFFF;\n }\n\n function S(X, n) {\n return X >>> n | X << 32 - n;\n }\n\n function R(X, n) {\n return X >>> n;\n }\n\n function Ch(x, y, z) {\n return x & y ^ ~x & z;\n }\n\n function Maj(x, y, z) {\n return x & y ^ x & z ^ y & z;\n }\n\n function Sigma0256(x) {\n return S(x, 2) ^ S(x, 13) ^ S(x, 22);\n }\n\n function Sigma1256(x) {\n return S(x, 6) ^ S(x, 11) ^ S(x, 25);\n }\n\n function Gamma0256(x) {\n return S(x, 7) ^ S(x, 18) ^ R(x, 3);\n }\n\n function Gamma1256(x) {\n return S(x, 17) ^ S(x, 19) ^ R(x, 10);\n }\n\n function core_sha256(m, l) {\n var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n var W = new Array(64);\n var a, b, c, d, e, f, g, h, i, j;\n var T1, T2;\n m[l >> 5] |= 0x80 << 24 - l % 32;\n m[(l + 64 >> 9 << 4) + 15] = l;\n\n for (var i = 0; i < m.length; i += 16) {\n a = HASH[0];\n b = HASH[1];\n c = HASH[2];\n d = HASH[3];\n e = HASH[4];\n f = HASH[5];\n g = HASH[6];\n h = HASH[7];\n\n for (var j = 0; j < 64; j++) {\n if (j < 16) W[j] = m[j + i];else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\n T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\n T2 = safe_add(Sigma0256(a), Maj(a, b, c));\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n\n HASH[0] = safe_add(a, HASH[0]);\n HASH[1] = safe_add(b, HASH[1]);\n HASH[2] = safe_add(c, HASH[2]);\n HASH[3] = safe_add(d, HASH[3]);\n HASH[4] = safe_add(e, HASH[4]);\n HASH[5] = safe_add(f, HASH[5]);\n HASH[6] = safe_add(g, HASH[6]);\n HASH[7] = safe_add(h, HASH[7]);\n }\n\n return HASH;\n }\n\n function str2binb(str) {\n var bin = Array();\n var mask = (1 << chrsz) - 1;\n\n for (var i = 0; i < str.length * chrsz; i += chrsz) {\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << 24 - i % 32;\n }\n\n return bin;\n }\n\n function Utf8Encode(string) {\n // METEOR change:\n // The webtoolkit.info version of this code added this\n // Utf8Encode function (which does seem necessary for dealing\n // with arbitrary Unicode), but the following line seems\n // problematic:\n //\n // string = string.replace(/\\r\\n/g,\"\\n\");\n var utftext = \"\";\n\n for (var n = 0; n < string.length; n++) {\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode(c >> 6 | 192);\n utftext += String.fromCharCode(c & 63 | 128);\n } else {\n utftext += String.fromCharCode(c >> 12 | 224);\n utftext += String.fromCharCode(c >> 6 & 63 | 128);\n utftext += String.fromCharCode(c & 63 | 128);\n }\n }\n\n return utftext;\n }\n\n function binb2hex(binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n\n for (var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt(binarray[i >> 2] >> (3 - i % 4) * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> (3 - i % 4) * 8 & 0xF);\n }\n\n return str;\n }\n\n s = Utf8Encode(s);\n return binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n } /// METEOR WRAPPER", "function SHA256(s){\n var chrsz = 8;\n var hexcase = 0;\n\n function safe_add (x, y) {\n var lsw = (x & 0xFFFF) + (y & 0xFFFF);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xFFFF);\n }\n\n function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\n function R (X, n) { return ( X >>> n ); }\n function Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\n function Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\n function Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\n function Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\n function Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\n function Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\n\n function core_sha256 (m, l) {\n var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n var W = new Array(64);\n var a, b, c, d, e, f, g, h, i, j;\n var T1, T2;\n\n m[l >> 5] |= 0x80 << (24 - l % 32);\n m[((l + 64 >> 9) << 4) + 15] = l;\n\n for ( var i = 0; i<m.length; i+=16 ) {\n a = HASH[0];\n b = HASH[1];\n c = HASH[2];\n d = HASH[3];\n e = HASH[4];\n f = HASH[5];\n g = HASH[6];\n h = HASH[7];\n\n for ( var j = 0; j<64; j++) {\n if (j < 16) W[j] = m[j + i];\n else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\n\n T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\n T2 = safe_add(Sigma0256(a), Maj(a, b, c));\n\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n\n HASH[0] = safe_add(a, HASH[0]);\n HASH[1] = safe_add(b, HASH[1]);\n HASH[2] = safe_add(c, HASH[2]);\n HASH[3] = safe_add(d, HASH[3]);\n HASH[4] = safe_add(e, HASH[4]);\n HASH[5] = safe_add(f, HASH[5]);\n HASH[6] = safe_add(g, HASH[6]);\n HASH[7] = safe_add(h, HASH[7]);\n }\n return HASH;\n }\n\n function str2binb (str) {\n var bin = Array();\n var mask = (1 << chrsz) - 1;\n for(var i = 0; i < str.length * chrsz; i += chrsz) {\n bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);\n }\n return bin;\n }\n\n function Utf8Encode(string) {\n string = string.replace(/\\r\\n/g,\"\\n\");\n var utftext = \"\";\n\n for (var n = 0; n < string.length; n++) {\n\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n }\n else if((c > 127) && (c < 2048)) {\n utftext += String.fromCharCode((c >> 6) | 192);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n else {\n utftext += String.fromCharCode((c >> 12) | 224);\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n\n }\n\n return utftext;\n }\n\n function binb2hex (binarray) {\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n var str = \"\";\n for(var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\n hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\n }\n return str;\n }\n\n s = Utf8Encode(s);\n return binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n}", "function SHA256(s){\n var chrsz = 8;\n var hexcase = 0;\n\n function safe_add (x, y) {\n var lsw = (x & 0xFFFF) + (y & 0xFFFF);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xFFFF);\n }\n\n function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\n function R (X, n) { return ( X >>> n ); }\n function Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\n function Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\n function Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\n function Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\n function Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\n function Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\n\n function core_sha256 (m, l) {\n var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n var W = new Array(64);\n var a, b, c, d, e, f, g, h, i, j;\n var T1, T2;\n\n m[l >> 5] |= 0x80 << (24 - l % 32);\n m[((l + 64 >> 9) << 4) + 15] = l;\n\n for ( var i = 0; i<m.length; i+=16 ) {\n a = HASH[0];\n b = HASH[1];\n c = HASH[2];\n d = HASH[3];\n e = HASH[4];\n f = HASH[5];\n g = HASH[6];\n h = HASH[7];\n\n for ( var j = 0; j<64; j++) {\n if (j < 16) W[j] = m[j + i];\n else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\n\n T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\n T2 = safe_add(Sigma0256(a), Maj(a, b, c));\n\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n\n HASH[0] = safe_add(a, HASH[0]);\n HASH[1] = safe_add(b, HASH[1]);\n HASH[2] = safe_add(c, HASH[2]);\n HASH[3] = safe_add(d, HASH[3]);\n HASH[4] = safe_add(e, HASH[4]);\n HASH[5] = safe_add(f, HASH[5]);\n HASH[6] = safe_add(g, HASH[6]);\n HASH[7] = safe_add(h, HASH[7]);\n }\n return HASH;\n }\n\n function str2binb (str) {\n var bin = Array();\n var mask = (1 << chrsz) - 1;\n for(var i = 0; i < str.length * chrsz; i += chrsz) {\n bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);\n }\n return bin;\n }\n\n function Utf8Encode(string) {\n string = string.replace(/\\r\\n/g,'\\n');\n var utftext = '';\n\n for (var n = 0; n < string.length; n++) {\n\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n }\n else if((c > 127) && (c < 2048)) {\n utftext += String.fromCharCode((c >> 6) | 192);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n else {\n utftext += String.fromCharCode((c >> 12) | 224);\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n\n }\n\n return utftext;\n }\n\n function binb2hex (binarray) {\n var hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef';\n var str = '';\n for(var i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i>>2] >> ((3 - i % 4)*8+4)) & 0xF) +\n hex_tab.charAt((binarray[i>>2] >> ((3 - i % 4)*8 )) & 0xF);\n }\n return str;\n }\n\n s = Utf8Encode(s);\n return binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n}", "function sha256_transform() {\n var a;\n var b;\n var c;\n var d;\n var e;\n var f;\n var g;\n var h;\n var T1;\n var T2;\n var W = new Array(16);\n /* Initialize registers with the previous intermediate value */\n\n a = ihash[0];\n b = ihash[1];\n c = ihash[2];\n d = ihash[3];\n e = ihash[4];\n f = ihash[5];\n g = ihash[6];\n h = ihash[7];\n /* make 32-bit words */\n\n for (var i = 0; i < 16; i++) {\n W[i] = buffer[(i << 2) + 3] | buffer[(i << 2) + 2] << 8 | buffer[(i << 2) + 1] << 16 | buffer[i << 2] << 24;\n }\n\n for (var j = 0; j < 64; j++) {\n T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];\n if (j < 16) T1 += W[j];else T1 += sha256_expand(W, j);\n T2 = sha256_Sigma0(a) + majority(a, b, c);\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n /* Compute the current intermediate hash value */\n\n\n ihash[0] += a;\n ihash[1] += b;\n ihash[2] += c;\n ihash[3] += d;\n ihash[4] += e;\n ihash[5] += f;\n ihash[6] += g;\n ihash[7] += h;\n}", "function sha256_transform() {\n var a;\n var b;\n var c;\n var d;\n var e;\n var f;\n var g;\n var h;\n var T1;\n var T2;\n var W = new Array(16);\n /* Initialize registers with the previous intermediate value */\n\n a = ihash[0];\n b = ihash[1];\n c = ihash[2];\n d = ihash[3];\n e = ihash[4];\n f = ihash[5];\n g = ihash[6];\n h = ihash[7];\n /* make 32-bit words */\n\n for (var i = 0; i < 16; i++) {\n W[i] = buffer[(i << 2) + 3] | buffer[(i << 2) + 2] << 8 | buffer[(i << 2) + 1] << 16 | buffer[i << 2] << 24;\n }\n\n for (var j = 0; j < 64; j++) {\n T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];\n if (j < 16) T1 += W[j];else T1 += sha256_expand(W, j);\n T2 = sha256_Sigma0(a) + majority(a, b, c);\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n /* Compute the current intermediate hash value */\n\n\n ihash[0] += a;\n ihash[1] += b;\n ihash[2] += c;\n ihash[3] += d;\n ihash[4] += e;\n ihash[5] += f;\n ihash[6] += g;\n ihash[7] += h;\n}", "function SHA256() {\n\n}", "function SHA256(s){\r\n\r\n var chrsz = 8;\r\n var hexcase = 0;\r\n\r\n function safe_add (x, y) {\r\n var lsw = (x & 0xFFFF) + (y & 0xFFFF);\r\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\r\n return (msw << 16) | (lsw & 0xFFFF);\r\n }\r\n\r\n function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\r\n function R (X, n) { return ( X >>> n ); }\r\n function Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\r\n function Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\r\n function Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\r\n function Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\r\n function Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\r\n function Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\r\n\r\n function core_sha256 (m, l) {\r\n var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\r\n var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\r\n var W = new Array(64);\r\n var a, b, c, d, e, f, g, h, i, j;\r\n var T1, T2;\r\n\r\n m[l >> 5] |= 0x80 << (24 - l % 32);\r\n m[((l + 64 >> 9) << 4) + 15] = l;\r\n\r\n for ( var i = 0; i<m.length; i+=16 ) {\r\n a = HASH[0];\r\n b = HASH[1];\r\n c = HASH[2];\r\n d = HASH[3];\r\n e = HASH[4];\r\n f = HASH[5];\r\n g = HASH[6];\r\n h = HASH[7];\r\n\r\n for ( var j = 0; j<64; j++) {\r\n if (j < 16) W[j] = m[j + i];\r\n else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\r\n T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\r\n T2 = safe_add(Sigma0256(a), Maj(a, b, c));\r\n h = g;\r\n g = f;\r\n f = e;\r\n e = safe_add(d, T1);\r\n d = c;\r\n c = b;\r\n b = a;\r\n a = safe_add(T1, T2);\r\n }\r\n HASH[0] = safe_add(a, HASH[0]);\r\n HASH[1] = safe_add(b, HASH[1]);\r\n HASH[2] = safe_add(c, HASH[2]);\r\n HASH[3] = safe_add(d, HASH[3]);\r\n HASH[4] = safe_add(e, HASH[4]);\r\n HASH[5] = safe_add(f, HASH[5]);\r\n HASH[6] = safe_add(g, HASH[6]);\r\n HASH[7] = safe_add(h, HASH[7]);\r\n }\r\n return HASH;\r\n }\r\n\r\n function str2binb (str) {\r\n var bin = Array();\r\n var mask = (1 << chrsz) - 1;\r\n for(var i = 0; i < str.length * chrsz; i += chrsz) {\r\n bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);\r\n }\r\n return bin;\r\n }\r\n\r\n function Utf8Encode(string) {\r\n string = string.replace(/\\r\\n/g,\"\\n\");\r\n var utftext = \"\";\r\n for (var n = 0; n < string.length; n++) {\r\n var c = string.charCodeAt(n);\r\n if (c < 128) {\r\n utftext += String.fromCharCode(c);\r\n } else if((c > 127) && (c < 2048)) {\r\n utftext += String.fromCharCode((c >> 6) | 192);\r\n utftext += String.fromCharCode((c & 63) | 128);\r\n } else {\r\n utftext += String.fromCharCode((c >> 12) | 224);\r\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\r\n utftext += String.fromCharCode((c & 63) | 128);\r\n }\r\n }\r\n return utftext;\r\n }\r\n function binb2hex (binarray) {\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var str = \"\";\r\n for(var i = 0; i < binarray.length * 4; i++) {\r\n str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\r\n hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\r\n }\r\n return str;\r\n }\r\n s = Utf8Encode(s);\r\n return binb2hex(core_sha256(str2binb(s), s.length * chrsz));\r\n}", "function sha256_final() {\n var index = ((count[0] >> 3) & 0x3f);\n buffer[index++] = 0x80;\n if (index <= 56) {\n for (var i = index; i < 56; i++)\n buffer[i] = 0;\n } else {\n for (var i = index; i < 64; i++)\n buffer[i] = 0;\n sha256_transform();\n for (var i = 0; i < 56; i++)\n buffer[i] = 0;\n }\n buffer[56] = (count[1] >>> 24) & 0xff;\n buffer[57] = (count[1] >>> 16) & 0xff;\n buffer[58] = (count[1] >>> 8) & 0xff;\n buffer[59] = count[1] & 0xff;\n buffer[60] = (count[0] >>> 24) & 0xff;\n buffer[61] = (count[0] >>> 16) & 0xff;\n buffer[62] = (count[0] >>> 8) & 0xff;\n buffer[63] = count[0] & 0xff;\n sha256_transform();\n}", "function sha256_final() {\n var index = ((count[0] >> 3) & 0x3f);\n buffer[index++] = 0x80;\n if (index <= 56) {\n for (var i = index; i < 56; i++)\n buffer[i] = 0;\n } else {\n for (var i = index; i < 64; i++)\n buffer[i] = 0;\n sha256_transform();\n for (var i = 0; i < 56; i++)\n buffer[i] = 0;\n }\n buffer[56] = (count[1] >>> 24) & 0xff;\n buffer[57] = (count[1] >>> 16) & 0xff;\n buffer[58] = (count[1] >>> 8) & 0xff;\n buffer[59] = count[1] & 0xff;\n buffer[60] = (count[0] >>> 24) & 0xff;\n buffer[61] = (count[0] >>> 16) & 0xff;\n buffer[62] = (count[0] >>> 8) & 0xff;\n buffer[63] = count[0] & 0xff;\n sha256_transform();\n}", "function sha256_final() {\n var index = count[0] >> 3 & 0x3f;\n buffer[index++] = 0x80;\n\n if (index <= 56) {\n for (var i = index; i < 56; i++) {\n buffer[i] = 0;\n }\n } else {\n for (var i = index; i < 64; i++) {\n buffer[i] = 0;\n }\n\n sha256_transform();\n\n for (var i = 0; i < 56; i++) {\n buffer[i] = 0;\n }\n }\n\n buffer[56] = count[1] >>> 24 & 0xff;\n buffer[57] = count[1] >>> 16 & 0xff;\n buffer[58] = count[1] >>> 8 & 0xff;\n buffer[59] = count[1] & 0xff;\n buffer[60] = count[0] >>> 24 & 0xff;\n buffer[61] = count[0] >>> 16 & 0xff;\n buffer[62] = count[0] >>> 8 & 0xff;\n buffer[63] = count[0] & 0xff;\n sha256_transform();\n}", "function SHA256_finalize() {\n SHA256_buf[SHA256_buf.length] = 0x80;\n if (SHA256_buf.length > 64 - 8) {\n for (var i = SHA256_buf.length; i < 64; i++)\n SHA256_buf[i] = 0;\n SHA256_Hash_Byte_Block(SHA256_H, SHA256_buf);\n SHA256_buf.length = 0;\n }\n for (var i = SHA256_buf.length; i < 64 - 5; i++)\n SHA256_buf[i] = 0;\n SHA256_buf[59] = (SHA256_len >>> 29) & 0xff;\n SHA256_buf[60] = (SHA256_len >>> 21) & 0xff;\n SHA256_buf[61] = (SHA256_len >>> 13) & 0xff;\n SHA256_buf[62] = (SHA256_len >>> 5) & 0xff;\n SHA256_buf[63] = (SHA256_len << 3) & 0xff;\n SHA256_Hash_Byte_Block(SHA256_H, SHA256_buf);\n var res = new Array(32);\n for (var i = 0; i < 8; i++) {\n res[4 * i + 0] = SHA256_H[i] >>> 24;\n res[4 * i + 1] = (SHA256_H[i] >> 16) & 0xff;\n res[4 * i + 2] = (SHA256_H[i] >> 8) & 0xff;\n res[4 * i + 3] = SHA256_H[i] & 0xff;\n }\n SHA256_H = undefined;\n SHA256_buf = undefined;\n SHA256_len = undefined;\n return res;\n}", "function SHA256(s){var chrsz=8;var hexcase=0;function safe_add(x,y){var lsw=(x&0xFFFF)+(y&0xFFFF);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}\nfunction S(X,n){return(X>>>n)|(X<<(32-n));}\nfunction R(X,n){return(X>>>n);}\nfunction Ch(x,y,z){return((x&y)^((~x)&z));}\nfunction Maj(x,y,z){return((x&y)^(x&z)^(y&z));}\nfunction Sigma0256(x){return(S(x,2)^S(x,13)^S(x,22));}\nfunction Sigma1256(x){return(S(x,6)^S(x,11)^S(x,25));}\nfunction Gamma0256(x){return(S(x,7)^S(x,18)^R(x,3));}\nfunction Gamma1256(x){return(S(x,17)^S(x,19)^R(x,10));}\nfunction core_sha256(m,l){var K=new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2);var HASH=new Array(0x6A09E667,0xBB67AE85,0x3C6EF372,0xA54FF53A,0x510E527F,0x9B05688C,0x1F83D9AB,0x5BE0CD19);var W=new Array(64);var a,b,c,d,e,f,g,h,i,j;var T1,T2;m[l>>5]|=0x80<<(24-l%32);m[((l+64>>9)<<4)+15]=l;for(var i=0;i<m.length;i+=16){a=HASH[0];b=HASH[1];c=HASH[2];d=HASH[3];e=HASH[4];f=HASH[5];g=HASH[6];h=HASH[7];for(var j=0;j<64;j++){if(j<16)W[j]=m[j+i];else W[j]=safe_add(safe_add(safe_add(Gamma1256(W[j-2]),W[j-7]),Gamma0256(W[j-15])),W[j-16]);T1=safe_add(safe_add(safe_add(safe_add(h,Sigma1256(e)),Ch(e,f,g)),K[j]),W[j]);T2=safe_add(Sigma0256(a),Maj(a,b,c));h=g;g=f;f=e;e=safe_add(d,T1);d=c;c=b;b=a;a=safe_add(T1,T2);}\nHASH[0]=safe_add(a,HASH[0]);HASH[1]=safe_add(b,HASH[1]);HASH[2]=safe_add(c,HASH[2]);HASH[3]=safe_add(d,HASH[3]);HASH[4]=safe_add(e,HASH[4]);HASH[5]=safe_add(f,HASH[5]);HASH[6]=safe_add(g,HASH[6]);HASH[7]=safe_add(h,HASH[7]);}\nreturn HASH;}\nfunction str2binb(str){var bin=Array();var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz){bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(24-i%32);}\nreturn bin;}\nfunction Utf8Encode(string){string=string.replace(/\\r\\n/g,\"\\n\");var utftext=\"\";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}\nelse if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}\nelse{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}\nreturn utftext;}\nfunction binb2hex(binarray){var hex_tab=hexcase?\"0123456789ABCDEF\":\"0123456789abcdef\";var str=\"\";for(var i=0;i<binarray.length*4;i++){str+=hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8+4))&0xF)+\nhex_tab.charAt((binarray[i>>2]>>((3-i%4)*8))&0xF);}\nreturn str;}\ns=Utf8Encode(s);return binb2hex(core_sha256(str2binb(s),s.length*chrsz));}", "function sha256_transform() {\n var a, b, c, d, e, f, g, h, T1, T2;\n var W = new Array(16);\n\n /* Initialize registers with the previous intermediate value */\n a = ihash[0];\n b = ihash[1];\n c = ihash[2];\n d = ihash[3];\n e = ihash[4];\n f = ihash[5];\n g = ihash[6];\n h = ihash[7];\n\n /* make 32-bit words */\n for (var i = 0; i < 16; i++)\n W[i] = ((buffer[(i << 2) + 3]) | (buffer[(i << 2) + 2] << 8) | (buffer[(i << 2) + 1] <<\n 16) | (buffer[i << 2] << 24));\n\n for (var j = 0; j < 64; j++) {\n T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];\n if (j < 16) T1 += W[j];\n else T1 += sha256_expand(W, j);\n T2 = sha256_Sigma0(a) + majority(a, b, c);\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n\n /* Compute the current intermediate hash value */\n ihash[0] += a;\n ihash[1] += b;\n ihash[2] += c;\n ihash[3] += d;\n ihash[4] += e;\n ihash[5] += f;\n ihash[6] += g;\n ihash[7] += h;\n}", "function SHA256() {\r\n if (!this.k[0])\r\n this.precompute();\r\n this.initialize();\r\n}", "function sha256_final() {\n var index = count[0] >> 3 & 0x3f;\n buffer[index++] = 0x80;\n\n if (index <= 56) {\n for (var i = index; i < 56; i++) {\n buffer[i] = 0;\n }\n } else {\n for (var _i = index; _i < 64; _i++) {\n buffer[_i] = 0;\n }\n\n sha256_transform();\n\n for (var _i2 = 0; _i2 < 56; _i2++) {\n buffer[_i2] = 0;\n }\n }\n\n buffer[56] = count[1] >>> 24 & 0xff;\n buffer[57] = count[1] >>> 16 & 0xff;\n buffer[58] = count[1] >>> 8 & 0xff;\n buffer[59] = count[1] & 0xff;\n buffer[60] = count[0] >>> 24 & 0xff;\n buffer[61] = count[0] >>> 16 & 0xff;\n buffer[62] = count[0] >>> 8 & 0xff;\n buffer[63] = count[0] & 0xff;\n sha256_transform();\n}", "static async slowHash(password, salt) {\n\n return new Promise(function (resolve, reject) {\n\n let pb = Security.str2ab(password);\n let sb = Security.str2ab(salt);\n\n scryptAsync(pb, sb, {\n N: Math.pow(2, 14),\n r: 8,\n p: 1,\n dkLen: 64,\n encoding: 'hex'\n }, function (derivedKey) {\n resolve(derivedKey);\n });\n\n });\n }", "function SHA256(s){\n\n\tvar chrsz = 8;\n\tvar hexcase = 0;\n\n\tfunction safe_add (x, y) {\n\t\tvar lsw = (x & 0xFFFF) + (y & 0xFFFF);\n\t\tvar msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n\t\treturn (msw << 16) | (lsw & 0xFFFF);\n\t}\n\n\tfunction S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\n\tfunction R (X, n) { return ( X >>> n ); }\n\tfunction Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\n\tfunction Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\n\tfunction Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\n\tfunction Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\n\tfunction Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\n\tfunction Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\n\n\tfunction core_sha256 (m, l) {\n\t\tvar K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n\t\tvar HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n\t\tvar W = new Array(64);\n\t\tvar a, b, c, d, e, f, g, h, i, j;\n\t\tvar T1, T2;\n\n\t\tm[l >> 5] |= 0x80 << (24 - l % 32);\n\t\tm[((l + 64 >> 9) << 4) + 15] = l;\n\n\t\tfor ( var i = 0; i<m.length; i+=16 ) {\n\t\t\ta = HASH[0];\n\t\t\tb = HASH[1];\n\t\t\tc = HASH[2];\n\t\t\td = HASH[3];\n\t\t\te = HASH[4];\n\t\t\tf = HASH[5];\n\t\t\tg = HASH[6];\n\t\t\th = HASH[7];\n\n\t\t\tfor ( var j = 0; j<64; j++) {\n\t\t\t\tif (j < 16) W[j] = m[j + i];\n\t\t\t\telse W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\n\n\t\t\t\tT1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\n\t\t\t\tT2 = safe_add(Sigma0256(a), Maj(a, b, c));\n\n\t\t\t\th = g;\n\t\t\t\tg = f;\n\t\t\t\tf = e;\n\t\t\t\te = safe_add(d, T1);\n\t\t\t\td = c;\n\t\t\t\tc = b;\n\t\t\t\tb = a;\n\t\t\t\ta = safe_add(T1, T2);\n\t\t\t}\n\n\t\t\tHASH[0] = safe_add(a, HASH[0]);\n\t\t\tHASH[1] = safe_add(b, HASH[1]);\n\t\t\tHASH[2] = safe_add(c, HASH[2]);\n\t\t\tHASH[3] = safe_add(d, HASH[3]);\n\t\t\tHASH[4] = safe_add(e, HASH[4]);\n\t\t\tHASH[5] = safe_add(f, HASH[5]);\n\t\t\tHASH[6] = safe_add(g, HASH[6]);\n\t\t\tHASH[7] = safe_add(h, HASH[7]);\n\t\t}\n\t\treturn HASH;\n\t}\n\n\tfunction str2binb (str) {\n\t\tvar bin = Array();\n\t\tvar mask = (1 << chrsz) - 1;\n\t\tfor(var i = 0; i < str.length * chrsz; i += chrsz) {\n\t\t\tbin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);\n\t\t}\n\t\treturn bin;\n\t}\n\n\tfunction Utf8Encode(string) {\n\t\t// METEOR change:\n\t\t// The webtoolkit.info version of this code added this\n\t\t// Utf8Encode function (which does seem necessary for dealing\n\t\t// with arbitrary Unicode), but the following line seems\n\t\t// problematic:\n\t\t//\n\t\t// string = string.replace(/\\r\\n/g,\"\\n\");\n\t\tvar utftext = \"\";\n\n\t\tfor (var n = 0; n < string.length; n++) {\n\n\t\t\tvar c = string.charCodeAt(n);\n\n\t\t\tif (c < 128) {\n\t\t\t\tutftext += String.fromCharCode(c);\n\t\t\t}\n\t\t\telse if((c > 127) && (c < 2048)) {\n\t\t\t\tutftext += String.fromCharCode((c >> 6) | 192);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tutftext += String.fromCharCode((c >> 12) | 224);\n\t\t\t\tutftext += String.fromCharCode(((c >> 6) & 63) | 128);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n\n\t\t}\n\n\t\treturn utftext;\n\t}\n\n\tfunction binb2hex (binarray) {\n\t\tvar hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\t\tvar str = \"\";\n\t\tfor(var i = 0; i < binarray.length * 4; i++) {\n\t\t\tstr += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\n\t\t\thex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\n\t\t}\n\t\treturn str;\n\t}\n\n\ts = Utf8Encode(s);\n\treturn binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n\n}", "function SHA256(s){\n\n\tvar chrsz = 8;\n\tvar hexcase = 0;\n\n\tfunction safe_add (x, y) {\n\t\tvar lsw = (x & 0xFFFF) + (y & 0xFFFF);\n\t\tvar msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n\t\treturn (msw << 16) | (lsw & 0xFFFF);\n\t}\n\n\tfunction S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\n\tfunction R (X, n) { return ( X >>> n ); }\n\tfunction Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\n\tfunction Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\n\tfunction Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\n\tfunction Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\n\tfunction Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\n\tfunction Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\n\n\tfunction core_sha256 (m, l) {\n\t\tvar K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n\t\tvar HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n\t\tvar W = new Array(64);\n\t\tvar a, b, c, d, e, f, g, h, i, j;\n\t\tvar T1, T2;\n\n\t\tm[l >> 5] |= 0x80 << (24 - l % 32);\n\t\tm[((l + 64 >> 9) << 4) + 15] = l;\n\n\t\tfor ( var i = 0; i<m.length; i+=16 ) {\n\t\t\ta = HASH[0];\n\t\t\tb = HASH[1];\n\t\t\tc = HASH[2];\n\t\t\td = HASH[3];\n\t\t\te = HASH[4];\n\t\t\tf = HASH[5];\n\t\t\tg = HASH[6];\n\t\t\th = HASH[7];\n\n\t\t\tfor ( var j = 0; j<64; j++) {\n\t\t\t\tif (j < 16) W[j] = m[j + i];\n\t\t\t\telse W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);\n\n\t\t\t\tT1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);\n\t\t\t\tT2 = safe_add(Sigma0256(a), Maj(a, b, c));\n\n\t\t\t\th = g;\n\t\t\t\tg = f;\n\t\t\t\tf = e;\n\t\t\t\te = safe_add(d, T1);\n\t\t\t\td = c;\n\t\t\t\tc = b;\n\t\t\t\tb = a;\n\t\t\t\ta = safe_add(T1, T2);\n\t\t\t}\n\n\t\t\tHASH[0] = safe_add(a, HASH[0]);\n\t\t\tHASH[1] = safe_add(b, HASH[1]);\n\t\t\tHASH[2] = safe_add(c, HASH[2]);\n\t\t\tHASH[3] = safe_add(d, HASH[3]);\n\t\t\tHASH[4] = safe_add(e, HASH[4]);\n\t\t\tHASH[5] = safe_add(f, HASH[5]);\n\t\t\tHASH[6] = safe_add(g, HASH[6]);\n\t\t\tHASH[7] = safe_add(h, HASH[7]);\n\t\t}\n\t\treturn HASH;\n\t}\n\n\tfunction str2binb (str) {\n\t\tvar bin = Array();\n\t\tvar mask = (1 << chrsz) - 1;\n\t\tfor(var i = 0; i < str.length * chrsz; i += chrsz) {\n\t\t\tbin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);\n\t\t}\n\t\treturn bin;\n\t}\n\n\tfunction Utf8Encode(string) {\n\t\t// METEOR change:\n\t\t// The webtoolkit.info version of this code added this\n\t\t// Utf8Encode function (which does seem necessary for dealing\n\t\t// with arbitrary Unicode), but the following line seems\n\t\t// problematic:\n\t\t//\n\t\t// string = string.replace(/\\r\\n/g,\"\\n\");\n\t\tvar utftext = \"\";\n\n\t\tfor (var n = 0; n < string.length; n++) {\n\n\t\t\tvar c = string.charCodeAt(n);\n\n\t\t\tif (c < 128) {\n\t\t\t\tutftext += String.fromCharCode(c);\n\t\t\t}\n\t\t\telse if((c > 127) && (c < 2048)) {\n\t\t\t\tutftext += String.fromCharCode((c >> 6) | 192);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tutftext += String.fromCharCode((c >> 12) | 224);\n\t\t\t\tutftext += String.fromCharCode(((c >> 6) & 63) | 128);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n\n\t\t}\n\n\t\treturn utftext;\n\t}\n\n\tfunction binb2hex (binarray) {\n\t\tvar hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\t\tvar str = \"\";\n\t\tfor(var i = 0; i < binarray.length * 4; i++) {\n\t\t\tstr += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\n\t\t\thex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\n\t\t}\n\t\treturn str;\n\t}\n\n\ts = Utf8Encode(s);\n\treturn binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n\n}", "function sha256_S (X,n){return (X >>> n ) | (X << (32-n));}", "function testHashing256() {\n hashGoldenTester(new goog.crypt.Sha512_256(), '256');\n}", "function sha256_transform() {\n var a, b, c, d, e, f, g, h, T1, T2;\n var W = new Array(16);\n\n /* Initialize registers with the previous intermediate value */\n a = ihash[0];\n b = ihash[1];\n c = ihash[2];\n d = ihash[3];\n e = ihash[4];\n f = ihash[5];\n g = ihash[6];\n h = ihash[7];\n\n /* make 32-bit words */\n for (var i = 0; i < 16; i++)\n W[i] = ((buffer[(i << 2) + 3]) | (buffer[(i << 2) + 2] << 8) | (buffer[(i << 2) + 1] <<\n 16) | (buffer[i << 2] << 24));\n\n for (var j = 0; j < 64; j++) {\n T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];\n if (j < 16) T1 += W[j];\n else T1 += sha256_expand(W, j);\n T2 = sha256_Sigma0(a) + majority(a, b, c);\n h = g;\n g = f;\n f = e;\n e = safe_add(d, T1);\n d = c;\n c = b;\n b = a;\n a = safe_add(T1, T2);\n }\n\n /* Compute the current intermediate hash value */\n ihash[0] += a;\n ihash[1] += b;\n ihash[2] += c;\n ihash[3] += d;\n ihash[4] += e;\n ihash[5] += f;\n ihash[6] += g;\n ihash[7] += h;\n}", "createHash() {\n return crypto.createHash(sha256);\n }", "function betterHash(str, len) {\n let total = 0;\n let value;\n const somePrime = 11;\n console.log(str.length);\n // limits iterations for extremely long strings\n for (let i = 0; i < Math.min(str.length, 100); i++) {\n value = str.charCodeAt(i) - 96;\n console.log(value);\n total = (total * somePrime + value) % len;\n }\n return total;\n}", "function sha256(s){return rstr2hex(rstr_sha256(str2rstr_utf8(s)));}", "function hashPassword(password) {\n var hash = crypto.createHash('sha256');\n\n hash.update(password);\n return(hash.digest('hex'));\n}", "function hash(password){\n return crypto.createHash('sha512').update(password).digest('hex');\n}", "function passwordHash(password, salt) {\n var saltedPassword = password + salt;\n var hash = CryptoJS.MD5(saltedPassword);\n var hashedPassword = \"\";\n for (var i = 0; i < hash.words.length; i++) {\n hashedPassword += hash.words[i];\n }\n return hashedPassword;\n\n}", "function sha256_digest(to_hash) { \n var hash_digits = sjcl.hash.sha256.hash(to_hash); \n var hex = new String();\n for(var i=0; i<8; i++) {\n for(var j=28; j>=0; j-=4) {\n hex += sha256_hex_digits.charAt((hash_digits[i] >>> j) & 0x0f);}\n }\n return hex; \n}", "function sha256_S(X, n) {\n\t return (X >>> n) | (X << (32 - n));\n\t }", "function hash (password) {\n\treturn crypto.createHash('sha512').update(password).digest('hex');\n\t//returns hexadecimal digest of password\n\n}", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n}", "function sha256_encode_hex() {\n var output = new String();\n for (var i = 0; i < 8; i++) {\n for (var j = 28; j >= 0; j -= 4)\n output += sha256_hex_digits.charAt((ihash[i] >>> j) & 0x0f);\n }\n return output;\n}", "hash(key){\n let hashedSum = 0;\n for(let i=0; i<key.length; i++){\n let hashedChar = i*(key[i].charCodeAt());\n hashedSum = hashedSum + hashedChar;\n }\n let primeHash = hashedSum*599;\n\n return primeHash%(this.size);\n }", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n}", "function sha256_encode_hex() {\n var output = new String();\n\n for (var i = 0; i < 8; i++) {\n for (var j = 28; j >= 0; j -= 4) {\n output += sha256_hex_digits.charAt(ihash[i] >>> j & 0x0f);\n }\n }\n\n return output;\n}", "function sha256_encode_hex() {\n var output = new String();\n\n for (var i = 0; i < 8; i++) {\n for (var j = 28; j >= 0; j -= 4) {\n output += sha256_hex_digits.charAt(ihash[i] >>> j & 0x0f);\n }\n }\n\n return output;\n}", "function rstr_sha256(s){return binb2rstr(binb_sha256(rstr2binb(s),s.length*8));}", "async function hashPassword(pass) {\n const hash = await scrypt.kdf(pass, {logN: 15});\n\n return hash.toString('base64');\n}", "function hashV2(key,arrayLen){\n var total = 0;\n var WEIRD_PRIME = 31;\n for(var i = 0; i < Math.min(key.length, 100); i++){\n var char = key[i];\n var value = char.charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % arrayLen;\n }\n return total;\n}", "function sha256_encode_hex() {\n var output = new String();\n for (var i = 0; i < 8; i++) {\n for (var j = 28; j >= 0; j -= 4)\n output += sha256_hex_digits.charAt((ihash[i] >>> j) & 0x0f);\n }\n return output;\n}", "_hash(key) {\n let total = 0;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let value = key[i].charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % this.keyMap.length;\n }\n return total;\n }", "computeHMACSHA256(stringToSign) {\n return crypto.createHmac(\"sha256\", this.accountKey).update(stringToSign, \"utf8\").digest(\"base64\");\n }", "computeHMACSHA256(stringToSign) {\n return crypto.createHmac(\"sha256\", this.accountKey).update(stringToSign, \"utf8\").digest(\"base64\");\n }", "function sha256(clear) {\n return crypto.createHash('sha256').update(clear).digest('base64')\n}", "_hash(key) { //O(1)\n let hash = 0;\n for (let i = 0; i < key.length; i++) {//grab the length of 'grapes' (key)\n hash = (hash + key.charCodeAt(i) * i) % this.data.length;\n //charCodeAt(): returns an integer between 0 & 65535 \n //this.data.length: ensures the size stays between 0-50 (memory space for hash table)\n console.log(hash); // 0 14 8 44 48 23\n }\n return hash;\n }", "function calculateHashBytes (data) {\n let shaObj = new jsSHA(\"SHA-256\", \"ARRAYBUFFER\");\n shaObj.update(data);\n hash = \"0x\" + shaObj.getHash(\"HEX\");\n return hash;\n}", "function newHash(key, arrayLen){\n let total = 0;\n let WEIRD_PRIME = 31;\n for(let i = 0; i < Math.min(key.length, 100); i++){\n let char = key[i];\n let value = char.charCodeAt(0) - 96\n total = (total * WEIRD_PRIME + value) % arrayLen\n }\n console.log(total);\n}", "async function computeSha256Hash(content, encoding) {\n return crypto.createHash(\"sha256\").update(content).digest(encoding);\n}", "async function computeSha256Hash(content, encoding) {\n return crypto.createHash(\"sha256\").update(content).digest(encoding);\n}", "function get_hashed_value(pwd) {\n var h1 = CryptoJS.SHA1(pwd).toString();\n var h2 = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(pwd));\n var hashes = [];\n\n for (var i = 0; i < 10; i++) {\n\tvar curr_hash = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(h1 + i + h2));\n\thashes.push(curr_hash);\n }\n return hashes;\n}", "calculateHash(){ \r\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\r\n }", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n\n for (var i = 0; i < 8; i++) {\n output[j++] = ihash[i] >>> 24 & 0xff;\n output[j++] = ihash[i] >>> 16 & 0xff;\n output[j++] = ihash[i] >>> 8 & 0xff;\n output[j++] = ihash[i] & 0xff;\n }\n\n return output;\n}", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n\n for (var i = 0; i < 8; i++) {\n output[j++] = ihash[i] >>> 24 & 0xff;\n output[j++] = ihash[i] >>> 16 & 0xff;\n output[j++] = ihash[i] >>> 8 & 0xff;\n output[j++] = ihash[i] & 0xff;\n }\n\n return output;\n}", "hash(input) {\n var hash = crypto.createHash('SHA256').update(input).digest('base64');\n return hash;\n }", "function computeHash(password) {\n\treturn new Promise((resolve, reject) => {\n\t\tvar len = 256;\n\t\tvar iterations = 10000;\n\n\t\tcrypto.randomBytes(len, (err, salt) => {\n\t\t\tif (err) { reject(err); }\n\t\t\tsalt = salt.toString('base64');\n\t\t\tcrypto.pbkdf2(password, salt, iterations, len, 'sha1', (err, derivedKey) => {\n\t\t\t\tif (err) { reject(err); }\n\t\t\t\tresolve([derivedKey.toString('base64'), salt]);\n\t\t\t});\n\t\t});\n\t});\n}", "function _sha256() {\n if ( typeof window.Sha256.hash === \"function\" ) {\n // The return value is the hashed fingerprint string.\n return md5( _raw() );\n }\n else {\n // If `window.Sha256.hash()` isn't available, an error is thrown.\n throw \"sha256 unavailable, please get it from https://github.com/chrisveness/crypto\";\n }\n }", "_hash(key) {\n let total = 0;\n const PRIME_NUM = 31;\n for (let i = 0; i < Math.min(key.length, 100); i += 1) {\n const char = key.charAt(i);\n const value = char.charCodeAt(0) - 96;\n total = (total * PRIME_NUM + value) % this.map.length;\n }\n\n return total;\n }", "function hashPassword(password, salt) {\n var hash = crypto.createHash('sha256');\n hash.update(password);\n hash.update(salt);\n return hash.digest('hex');\n}", "function hashPassword(password) {\n const salt = crypto.randomBytes(16).toString('hex');\n const hash = crypto.pbkdf2Sync(password, salt, 2048, 32, 'sha512').toString('hex');\n return [salt, hash].join('$');\n}", "function scrypt(a,b,c,d,e,f,g,h,i){\"use strict\";function k(a){function l(a){for(var l=0,m=a.length;m>=64;){var v,w,x,y,z,n=c,o=d,p=e,q=f,r=g,s=h,t=i,u=j;for(w=0;w<16;w++)x=l+4*w,k[w]=(255&a[x])<<24|(255&a[x+1])<<16|(255&a[x+2])<<8|255&a[x+3];for(w=16;w<64;w++)v=k[w-2],y=(v>>>17|v<<15)^(v>>>19|v<<13)^v>>>10,v=k[w-15],z=(v>>>7|v<<25)^(v>>>18|v<<14)^v>>>3,k[w]=(y+k[w-7]|0)+(z+k[w-16]|0)|0;for(w=0;w<64;w++)y=(((r>>>6|r<<26)^(r>>>11|r<<21)^(r>>>25|r<<7))+(r&s^~r&t)|0)+(u+(b[w]+k[w]|0)|0)|0,z=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&p^o&p)|0,u=t,t=s,s=r,r=q+y|0,q=p,p=o,o=n,n=y+z|0;c=c+n|0,d=d+o|0,e=e+p|0,f=f+q|0,g=g+r|0,h=h+s|0,i=i+t|0,j=j+u|0,l+=64,m-=64}}var b=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],c=1779033703,d=3144134277,e=1013904242,f=2773480762,g=1359893119,h=2600822924,i=528734635,j=1541459225,k=new Array(64);l(a);var m,n=a.length%64,o=a.length/536870912|0,p=a.length<<3,q=n<56?56:120,r=a.slice(a.length-n,a.length);for(r.push(128),m=n+1;m<q;m++)r.push(0);return r.push(o>>>24&255),r.push(o>>>16&255),r.push(o>>>8&255),r.push(o>>>0&255),r.push(p>>>24&255),r.push(p>>>16&255),r.push(p>>>8&255),r.push(p>>>0&255),l(r),[c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,d>>>24&255,d>>>16&255,d>>>8&255,d>>>0&255,e>>>24&255,e>>>16&255,e>>>8&255,e>>>0&255,f>>>24&255,f>>>16&255,f>>>8&255,f>>>0&255,g>>>24&255,g>>>16&255,g>>>8&255,g>>>0&255,h>>>24&255,h>>>16&255,h>>>8&255,h>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,j>>>24&255,j>>>16&255,j>>>8&255,j>>>0&255]}function l(a,b,c){function i(){for(var a=e-1;a>=e-4;a--){if(f[a]++,f[a]<=255)return;f[a]=0}}a=a.length<=64?a:k(a);var d,e=64+b.length+4,f=new Array(e),g=new Array(64),h=[];for(d=0;d<64;d++)f[d]=54;for(d=0;d<a.length;d++)f[d]^=a[d];for(d=0;d<b.length;d++)f[64+d]=b[d];for(d=e-4;d<e;d++)f[d]=0;for(d=0;d<64;d++)g[d]=92;for(d=0;d<a.length;d++)g[d]^=a[d];for(;c>=32;)i(),h=h.concat(k(g.concat(k(f)))),c-=32;return c>0&&(i(),h=h.concat(k(g.concat(k(f))).slice(0,c))),h}function m(a,b,c,d){var u,v,e=a[0]^b[c++],f=a[1]^b[c++],g=a[2]^b[c++],h=a[3]^b[c++],i=a[4]^b[c++],j=a[5]^b[c++],k=a[6]^b[c++],l=a[7]^b[c++],m=a[8]^b[c++],n=a[9]^b[c++],o=a[10]^b[c++],p=a[11]^b[c++],q=a[12]^b[c++],r=a[13]^b[c++],s=a[14]^b[c++],t=a[15]^b[c++],w=e,x=f,y=g,z=h,A=i,B=j,C=k,D=l,E=m,F=n,G=o,H=p,I=q,J=r,K=s,L=t;for(v=0;v<8;v+=2)u=w+I,A^=u<<7|u>>>25,u=A+w,E^=u<<9|u>>>23,u=E+A,I^=u<<13|u>>>19,u=I+E,w^=u<<18|u>>>14,u=B+x,F^=u<<7|u>>>25,u=F+B,J^=u<<9|u>>>23,u=J+F,x^=u<<13|u>>>19,u=x+J,B^=u<<18|u>>>14,u=G+C,K^=u<<7|u>>>25,u=K+G,y^=u<<9|u>>>23,u=y+K,C^=u<<13|u>>>19,u=C+y,G^=u<<18|u>>>14,u=L+H,z^=u<<7|u>>>25,u=z+L,D^=u<<9|u>>>23,u=D+z,H^=u<<13|u>>>19,u=H+D,L^=u<<18|u>>>14,u=w+z,x^=u<<7|u>>>25,u=x+w,y^=u<<9|u>>>23,u=y+x,z^=u<<13|u>>>19,u=z+y,w^=u<<18|u>>>14,u=B+A,C^=u<<7|u>>>25,u=C+B,D^=u<<9|u>>>23,u=D+C,A^=u<<13|u>>>19,u=A+D,B^=u<<18|u>>>14,u=G+F,H^=u<<7|u>>>25,u=H+G,E^=u<<9|u>>>23,u=E+H,F^=u<<13|u>>>19,u=F+E,G^=u<<18|u>>>14,u=L+K,I^=u<<7|u>>>25,u=I+L,J^=u<<9|u>>>23,u=J+I,K^=u<<13|u>>>19,u=K+J,L^=u<<18|u>>>14;b[d++]=a[0]=w+e|0,b[d++]=a[1]=x+f|0,b[d++]=a[2]=y+g|0,b[d++]=a[3]=z+h|0,b[d++]=a[4]=A+i|0,b[d++]=a[5]=B+j|0,b[d++]=a[6]=C+k|0,b[d++]=a[7]=D+l|0,b[d++]=a[8]=E+m|0,b[d++]=a[9]=F+n|0,b[d++]=a[10]=G+o|0,b[d++]=a[11]=H+p|0,b[d++]=a[12]=I+q|0,b[d++]=a[13]=J+r|0,b[d++]=a[14]=K+s|0,b[d++]=a[15]=L+t|0}function n(a,b,c,d,e){for(;e--;)a[b++]=c[d++]}function o(a,b,c,d,e){for(;e--;)a[b++]^=c[d++]}function p(a,b,c,d,e){n(a,0,b,c+16*(2*e-1),16);for(var f=0;f<2*e;f+=2)m(a,b,c+16*f,d+8*f),m(a,b,c+16*f+16,d+8*f+16*e)}function q(a,b,c){return a[b+16*(2*c-1)]}function r(a){for(var b=[],c=0;c<a.length;c++){var d=a.charCodeAt(c);d<128?b.push(d):d>127&&d<2048?(b.push(d>>6|192),b.push(63&d|128)):(b.push(d>>12|224),b.push(d>>6&63|128),b.push(63&d|128))}return b}function s(a){for(var b=\"0123456789abcdef\".split(\"\"),c=a.length,d=[],e=0;e<c;e++)d.push(b[a[e]>>>4&15]),d.push(b[a[e]>>>0&15]);return d.join(\"\")}function t(a){for(var f,g,h,i,b=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".split(\"\"),c=a.length,d=[],e=0;e<c;)f=e<c?a[e++]:0,g=e<c?a[e++]:0,h=e<c?a[e++]:0,i=(f<<16)+(g<<8)+h,d.push(b[i>>>18&63]),d.push(b[i>>>12&63]),d.push(b[i>>>6&63]),d.push(b[i>>>0&63]);return c%3>0&&(d[d.length-1]=\"=\",c%3===1&&(d[d.length-2]=\"=\")),d.join(\"\")}function D(){for(var a=0;a<32*d;a++){var b=4*a;x[B+a]=(255&z[b+3])<<24|(255&z[b+2])<<16|(255&z[b+1])<<8|(255&z[b+0])<<0}}function E(a,b){for(var c=a;c<b;c+=2)n(y,c*(32*d),x,B,32*d),p(A,x,B,C,d),n(y,(c+1)*(32*d),x,C,32*d),p(A,x,C,B,d)}function F(a,b){for(var c=a;c<b;c+=2){var e=q(x,B,d)&w-1;o(x,B,y,e*(32*d),32*d),p(A,x,B,C,d),e=q(x,C,d)&w-1,o(x,C,y,e*(32*d),32*d),p(A,x,C,B,d)}}function G(){for(var a=0;a<32*d;a++){var b=x[B+a];z[4*a+0]=b>>>0&255,z[4*a+1]=b>>>8&255,z[4*a+2]=b>>>16&255,z[4*a+3]=b>>>24&255}}function H(a,b,c,d,e){!function h(){setTimeout(function(){g((j/Math.ceil(w/f)*100).toFixed(2)),d(a,a+c<b?a+c:b),a+=c,j++,a<b?h():e()},0)}()}function I(b){var c=l(a,z,e);return\"base64\"===b?t(c):\"hex\"===b?s(c):c}var j,u=1;if(c<1||c>31)throw new Error(\"scrypt: logN not be between 1 and 31\");var x,y,z,A,v=1<<31>>>0,w=1<<c>>>0;if(d*u>=1<<30||d>v/128/u||d>v/256||w>v/128/d)throw new Error(\"scrypt: parameters are too large\");\"string\"==typeof a&&(a=r(a)),\"string\"==typeof b&&(b=r(b)),\"undefined\"!=typeof Int32Array?(x=new Int32Array(64*d),y=new Int32Array(32*w*d),A=new Int32Array(16)):(x=[],y=[],A=new Array(16)),z=l(a,b,128*u*d);var B=0,C=32*d;f<=0?(D(),E(0,w),F(0,w),G(),h(I(i))):(j=0,D(),H(0,w,2*f,E,function(){H(0,w,2*f,F,function(){G(),h(I(i))})}))}", "_coreSHA1(_x, _len) {\n\n _x[_len >> 5] |= 0x80 << (24 - _len % 32);\n _x[((_len + 64 >> 9) << 4) + 15] = _len;\n\n const _this = this;\n let _a = 1732584193;\n let _b = -271733879;\n let _c = -1732584194;\n let _d = 271733878;\n let _e = -1009589776;\n const _w = new Array(80);\n let i;\n let _olda;\n let _oldb;\n let _oldc;\n let _oldd;\n let _olde;\n let j;\n let _t;\n\n for (i = 0; i < _x.length; i += 16) {\n _olda = _a;\n _oldb = _b;\n _oldc = _c;\n _oldd = _d;\n _olde = _e;\n\n for (j = 0; j < 80; j++) {\n if (j < 16) {\n _w[j] = _x[i + j];\n }\n else {\n _w[j] = _this._rol(_w[j-3] ^ _w[j-8] ^ _w[j-14] ^ _w[j-16], 1);\n }\n _t = _this._safeAdd(_this._safeAdd(_this._rol(_a, 5), _this._sha1FT(j, _b, _c, _d)),\n _this._safeAdd(_this._safeAdd(_e, _w[j]), _this._sha1KT(j)));\n _e = _d;\n _d = _c;\n _c = _this._rol(_b, 30);\n _b = _a;\n _a = _t;\n }\n\n _a = _this._safeAdd(_a, _olda);\n _b = _this._safeAdd(_b, _oldb);\n _c = _this._safeAdd(_c, _oldc);\n _d = _this._safeAdd(_d, _oldd);\n _e = _this._safeAdd(_e, _olde);\n }\n return [_a, _b, _c, _d, _e];\n }", "function HashText(text) {\n return CryptoJS.SHA256(text).toString();\n}", "function DoHash(lengths){\r\n\tvar listSize = 256;\r\n\tvar list = Array(listSize).fill(0).map((e, i) => i);\r\n\tvar curr = 0;\r\n\tvar skip = 0;\r\n\t\r\n\tif(typeof lengths == \"string\") lengths = lengths.split(\"\").map(e => e.charCodeAt(0));\r\n\tlengths = lengths.concat([17, 31, 73, 47, 23]);\r\n\t\r\n\tfunction DoRound(){\r\n\t\tvar lengs = lengths.slice();\r\n\t\twhile(lengs.length){\r\n\t\t\tvar l = lengs.shift();\r\n\t\t\t\r\n\t\t\tvar s = list.concat(list).splice(curr, l);\r\n\t\t\ts.reverse();\r\n\t\t\tlist = list.map((e, i) => ((s[listSize + i - curr] + 1) || (s[i - curr] + 1) || (e + 1)) - 1);\r\n\t\t\t\r\n\t\t\tcurr += l + skip;\r\n\t\t\tcurr = curr % listSize;\r\n\t\t\tskip++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(var i = 0; i < 64; i++) DoRound();\r\n\t\r\n\tvar sparse = [];\r\n\twhile(list.length) sparse.push(list.splice(0, 16));\r\n\treturn sparse.map(b => b.reduce((acc, e, i, a) => acc ^ e, 0));\r\n}", "function iterate_hash( input, key, count ) {\n /* Loop while iteration count isn't 0. */\n while ( count !== 0 ) {\n /* Update the input with the concatenated hash of the old input + key. */\n input = Buffer.from( _discordCrypt.__sha256( Buffer.concat( [ input, key ] ), true ), 'hex' );\n count -= 1;\n }\n\n /* Return the result as a buffer. */\n return input;\n }", "function scramble(password, salt) {\n var stage1 = sha1(password);\n var stage2 = sha1(stage1);\n var stage3 = sha1(salt + stage2);\n return xor(stage3, stage1);\n}", "calculateHash(){\n\t\treturn SHA256(this.index + this.previousHash + this.timestamp + this.data + this.nonce).toString();\n\n\t}", "function sha256(ascii) {\n function rightRotate(value, amount) {\n return (value >>> amount) | (value << (32 - amount));\n };\n\n var mathPow = Math.pow;\n var maxWord = mathPow(2, 32);\n var lengthProperty = 'length'\n var i, j; // Used as a counter across the whole file\n var result = ''\n\n var words = [];\n var asciiBitLength = ascii[lengthProperty] * 8;\n\n //* caching results is optional - remove/add slash from front of this line to toggle\n // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes\n // (we actually calculate the first 64, but extra values are just ignored)\n var hash = sha256.h = sha256.h || [];\n // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes\n var k = sha256.k = sha256.k || [];\n var primeCounter = k[lengthProperty];\n\t/*/\n\tvar hash = [], k = [];\n\tvar primeCounter = 0;\n\t//*/\n\n var isComposite = {};\n for (var candidate = 2; primeCounter < 64; candidate++) {\n if (!isComposite[candidate]) {\n for (i = 0; i < 313; i += candidate) {\n isComposite[i] = candidate;\n }\n hash[primeCounter] = (mathPow(candidate, .5) * maxWord) | 0;\n k[primeCounter++] = (mathPow(candidate, 1 / 3) * maxWord) | 0;\n }\n }\n\n ascii += '\\x80' // Append Ƈ' bit (plus zero padding)\n while (ascii[lengthProperty] % 64 - 56) ascii += '\\x00' // More zero padding\n for (i = 0; i < ascii[lengthProperty]; i++) {\n j = ascii.charCodeAt(i);\n if (j >> 8) return; // ASCII check: only accept characters in range 0-255\n words[i >> 2] |= j << ((3 - i) % 4) * 8;\n }\n words[words[lengthProperty]] = ((asciiBitLength / maxWord) | 0);\n words[words[lengthProperty]] = (asciiBitLength)\n\n // process each chunk\n for (j = 0; j < words[lengthProperty];) {\n var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration\n var oldHash = hash;\n // This is now the undefinedworking hash\", often labelled as variables a...g\n // (we have to truncate as well, otherwise extra entries at the end accumulate\n hash = hash.slice(0, 8);\n\n for (i = 0; i < 64; i++) {\n var i2 = i + j;\n // Expand the message into 64 words\n // Used below if \n var w15 = w[i - 15], w2 = w[i - 2];\n\n // Iterate\n var a = hash[0], e = hash[4];\n var temp1 = hash[7]\n + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1\n + ((e & hash[5]) ^ ((~e) & hash[6])) // ch\n + k[i]\n // Expand the message schedule if needed\n + (w[i] = (i < 16) ? w[i] : (\n w[i - 16]\n + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15 >>> 3)) // s0\n + w[i - 7]\n + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2 >>> 10)) // s1\n ) | 0\n );\n // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble\n var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0\n + ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2])); // maj\n\n hash = [(temp1 + temp2) | 0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()\n hash[4] = (hash[4] + temp1) | 0;\n }\n\n for (i = 0; i < 8; i++) {\n hash[i] = (hash[i] + oldHash[i]) | 0;\n }\n }\n\n for (i = 0; i < 8; i++) {\n for (j = 3; j + 1; j--) {\n var b = (hash[i] >> (j * 8)) & 255;\n result += ((b < 16) ? 0 : '') + b.toString(16);\n }\n }\n return result;\n}", "function hashpw(password, salt, callback, progress) {\n var real_salt;\n var passwordb = [];\n var saltb = [];\n var hashed = [];\n var minor = String.fromCharCode(0);\n var rounds = 0;\n var off = 0;\n\n if (!progress) {\n progress = function() {};\n }\n\n if (salt.charAt(0) != '$' || salt.charAt(1) != '2')\n throw \"Invalid salt version\";\n if (salt.charAt(2) == '$')\n off = 3;\n else {\n minor = salt.charAt(2);\n if ((minor != 'a' && minor != 'b') || salt.charAt(3) != '$')\n throw \"Invalid salt revision\";\n off = 4;\n }\n\n // Extract number of rounds\n if (salt.charAt(off + 2) > '$')\n throw \"Missing salt rounds\";\n var r1 = parseInt(salt.substring(off, off + 1)) * 10;\n var r2 = parseInt(salt.substring(off + 1, off + 2));\n rounds = r1 + r2;\n real_salt = salt.substring(off + 3, off + 25);\n password = password + (minor >= 'a' ? \"\\000\" : \"\");\n passwordb = password_to_bytes(password)\n saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);\n crypt_raw(\n passwordb,\n saltb,\n rounds,\n BF_CRYPT_CIPHERTEXT.slice(0),\n function(hashed) {\n var rs = [];\n rs.push(\"$2\");\n if (minor >= 'a')\n rs.push(minor);\n rs.push(\"$\");\n if (rounds < 10)\n rs.push(\"0\");\n rs.push(rounds.toString());\n rs.push(\"$\");\n rs.push(encode_base64(saltb, saltb.length));\n rs.push(encode_base64(hashed, BF_CRYPT_CIPHERTEXT.length * 4 - 1));\n callback(rs.join(''));\n },\n progress);\n}", "function SHA256Hashing(message) {\r\n var digest = CryptoJS.SHA256(message);\r\n var digestString = CryptoJS.enc.Base64.stringify(digest);\r\n return digestString;\r\n }", "function sha256hash(content) {\n return _crypto.default.createHash('sha256').update(content, 'utf-8').digest('hex');\n} // Returns a base64 encoding of a string or buffer.", "function sha256hash(content) {\n return _crypto.default.createHash('sha256').update(content, 'utf-8').digest('hex');\n} // Returns a base64 encoding of a string or buffer.", "function computeHash(data) {\n\tconst sha256 = crypto.createHash('sha256');\n\n\treturn sha256.update(data).digest();\n}", "calculateHash(){\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)+this.nonce).toString();\n }", "function hash (pwd, salt, fn) {\n log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){\n //log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n fn(err, hash.toString('base64'));\n });\n}", "function hash(s) {\n let h = 1;\n for (let i = 0; i < s.length; i ++)\n h = Math.imul(h + s.charCodeAt(i) | 0, 2654435761);\n return (h ^ h >>> 17) >>> 0;\n}", "function saltHashPassword(password)\n{\n var salt = \"aejjdgerjrxzcxzvbfahjaer\";\n var hash = crypto.createHmac('sha512', salt);\n hash.update(password);\n var value = hash.digest('hex');\n value=value.slice(0,40);\n return value;\n\n}", "static async toHash(password) {\n\t\tconst salt = randomBytes(8).toString(\"hex\");\n\t\tconst buf = await scryptAsync(password, salt, 64);\n\n\t\treturn `${buf.toString(\"hex\")}.${salt}`;\n\t}", "calculateHash(){\r\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\r\n }", "function betterHash(key, arrayLen) {\n let total = 0;\n let primeNum = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 96;\n total = (total * primeNum + value) % arrayLen;\n }\n return total;\n}", "function hash256(buf) {\n return utils.sha256(utils.sha256(buf));\n}", "calculateHash() {\n return Base64.stringify(HmacSHA256( this.previousHash + this.timesamp + this.data + this.nonce.toString(), this.index.toString()));\n }", "function hash(input, salt){\n //How do we create a hash??\n //explanation of pbkdf2Sync: \n //1. input will be hashed to input+salt ==> 'password-this-is-some-random-string'\n //2. This String will be hashed 10000times ==> hashvalue is unique\n var hashed = crypto.pbkdf2Sync(input, salt, 10000, 512, 'sha512'); // crypto Object has to be create as object on the top\n return ['pbkdf2', '100000', salt, hashed.toString('hex')].join('$');\n}", "async function generateHash(password) {\n if ((typeof password) !== \"string\") {\n throw new Error(\"The password when generating a hash is not a string\")\n }\n const salt = await crypto.randomBytes(16).toString('hex');\n let iterations = 65536;\n let hash;\n hash = crypto.pbkdf2Sync(password, salt, iterations, 64, \"sha512\").toString('hex');\n return [hash, salt, iterations].join(\":\");\n}", "_hashed (s) {\n return s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0); \n }", "function hash(key, arraylength){\n let total=0;\n let primeNumber=31\n\n for(let i=0;i<Math.min(arraylength, 100); i++){\n //pulling the individual character of the key\n //and converting each character to an alphabetic\n //ranking and adding the prime number and diving it by the array length to get a unique out\n //put of a fixed size\n\n let char=key[i];\n let value= char.charCodeAt(0) -96\n total= (total+value+primeNumber)%arraylength\n }\n return total\n}", "calculateHash(){\n\t\treturn SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\n\t}", "calculateHash(){\n return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data));\n }", "function hash1(key, arrayLen) {\n let total = 7;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 'a'.charCodeAt(0);\n total += (total * WEIRD_PRIME + value) % arrayLen\n } \n return total;\n}", "calculateHash(){\n \n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\n\n }", "calculateHash(){\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\n }", "calculateHash() {\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\n }", "calculateHash() {\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\n }", "calculateHash() {\n return SHA256(\n this.previousHash\n + this.previousDatabaseHash\n + this.blockNumber.toString()\n + this.refHiveBlockNumber.toString()\n + this.refHiveBlockId\n + this.prevRefHiveBlockId\n + this.timestamp\n + this.merkleRoot\n + JSON.stringify(this.transactions) // eslint-disable-line\n )\n .toString(enchex);\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 }", "key(username, password, iterations) {\n if (iterations < 2) throw new Error('Iterations < 2 not implemented, and probably not secure anyway');\n return Sha256.pbkdf2(ByteArray.fromString(password), ByteArray.fromString(username), iterations, 32);\n }", "function hashPassword(p) {\n return hash(\"sha1\", p);\n}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}" ]
[ "0.77472264", "0.74704796", "0.68856514", "0.6854732", "0.6828961", "0.6819471", "0.6819471", "0.68038625", "0.6789471", "0.67773455", "0.6776444", "0.67601156", "0.67274123", "0.67165977", "0.6711122", "0.6705384", "0.6704871", "0.66762346", "0.66523", "0.66523", "0.66430545", "0.66282415", "0.66177016", "0.6579854", "0.6528752", "0.6524321", "0.6480105", "0.6460234", "0.6459105", "0.64480656", "0.64349437", "0.6392811", "0.6376972", "0.63691646", "0.63658386", "0.6365799", "0.6345923", "0.6345923", "0.63399553", "0.63382244", "0.6334752", "0.63322645", "0.6296398", "0.6295701", "0.6295701", "0.6293294", "0.62866116", "0.625913", "0.6254032", "0.6249894", "0.6249894", "0.6242042", "0.62214696", "0.6211735", "0.6211735", "0.61985356", "0.6197456", "0.6195864", "0.6156579", "0.6155666", "0.61528176", "0.61524475", "0.6151702", "0.6145419", "0.6139675", "0.6119053", "0.6117432", "0.61161566", "0.61114466", "0.6109325", "0.6105559", "0.61053324", "0.61053324", "0.61014104", "0.60965216", "0.6095296", "0.6094303", "0.6069442", "0.60656637", "0.60646963", "0.60566837", "0.60524464", "0.6042932", "0.603793", "0.60361487", "0.6028885", "0.6024843", "0.6024585", "0.60232687", "0.60224867", "0.6017461", "0.6002735", "0.6001786", "0.6001786", "0.5999401", "0.59961116", "0.5988574", "0.5985332", "0.5983004", "0.5983004" ]
0.64346105
31
First gets a different salt from the last value. Then, Calculates the super short hashsum Only count last 12bits..so plenty of collisions for an attacker
function calculate_new_short_hash(pwd, prev_salt) { //First get a salt that is not equal to prev_salt var curr_salt = prev_salt; while (curr_salt == prev_salt) { var r = Math.floor((Math.random() * 1000)) % 1000; curr_salt = pii_vault.salt_table[r]; } //Now get the short hash using salt calculated var salted_pwd = curr_salt + ":" + pwd; var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd)); var hash_pwd = k.substring(k.length - 3, k.length); var rc = { 'salt' : curr_salt, 'short_hash' : hash_pwd, } return rc; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculate_short_hash(pwd, salt) {\n //Now get the short hash using salt calculated\n var salted_pwd = salt + \":\" + pwd;\n var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd));\n var hash_pwd = k.substring(k.length - 3, k.length);\n var rc = {\n\t'short_hash' : hash_pwd, \n }\n return rc;\n}", "function compose_salt ( )\n {\n // storage note, seems to result in length 344\n\n return crypto.randomBytes( 256 ).toString( 'base64' );\n }", "_generateSalt() {\n return crypto.randomBytes(Math.ceil(this._saltLength / 2))\n .toString('hex')\n .slice(0, this._saltLength);\n }", "function _stdHash(dd) {\n\t\t\tvar hash=0,salt=0;\n\t\t \tfor (var i=dd.length-1;i>=0;i--) {\n\t\t\t var charCode=parseInt(dd.charCodeAt(i));\n\t\t\t hash=((hash << 8) & 268435455) + charCode + (charCode << 12);\n\t\t\t if ((salt=hash & 161119850)!=0){hash=(hash ^ (salt >> 20))};\n\t\t\t}\n\t\t return hash.toString(16);\n\t\t}", "function createSalt() {\n\t//define the length of the salt\n\tvar len = 8;\n\t//create the hash\n\treturn crypto.randomBytes(Math.ceil(len/2)).toString('hex').substring(0,len);\n}", "function generateSalt() {\n var saltWord = bip39.generateMnemonic(8);\n var saltHashedBitArray = sjcl.hash.sha256.hash(saltWord);\n salt = sjcl.codec.base64.fromBits(saltHashedBitArray);\n}", "function generateSalt() {\n var set =\n \"0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ\";\n var salt = \"\";\n for (var i = 0; i < 10; i += 1) {\n var p = Math.floor(Math.random() * set.length);\n salt += set[p];\n }\n return salt;\n }", "_hash(key) {\n let total = 0;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let value = key[i].charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % this.keyMap.length;\n }\n return total;\n }", "function computeHash (source, salt) { \n\t//get hashing algorithm\n\tvar hmac = crypto.createHmac(\"sha1\", salt);\n\t//create the hash number\t\n\tvar hash = hmac.update(source);\n\t//get the hash as hex string\n\treturn hash.digest(\"hex\");\n}", "calculateHash(nonce) {\n // Your code here\n\n }", "function saltHashPassword(password)\n{\n var salt = \"aejjdgerjrxzcxzvbfahjaer\";\n var hash = crypto.createHmac('sha512', salt);\n hash.update(password);\n var value = hash.digest('hex');\n value=value.slice(0,40);\n return value;\n\n}", "function unique_salt() {\r\n return SHA1(mt_rand().toString());\r\n }", "generateDatabaseSalt() {\n return Math.floor(Math.random() * (999999999 - 100000000)) + 100000000;\n }", "function generateSalt() {\n return crypto.randomBytes(16).toString('base64');\n}", "_coreSHA1(_x, _len) {\n\n _x[_len >> 5] |= 0x80 << (24 - _len % 32);\n _x[((_len + 64 >> 9) << 4) + 15] = _len;\n\n const _this = this;\n let _a = 1732584193;\n let _b = -271733879;\n let _c = -1732584194;\n let _d = 271733878;\n let _e = -1009589776;\n const _w = new Array(80);\n let i;\n let _olda;\n let _oldb;\n let _oldc;\n let _oldd;\n let _olde;\n let j;\n let _t;\n\n for (i = 0; i < _x.length; i += 16) {\n _olda = _a;\n _oldb = _b;\n _oldc = _c;\n _oldd = _d;\n _olde = _e;\n\n for (j = 0; j < 80; j++) {\n if (j < 16) {\n _w[j] = _x[i + j];\n }\n else {\n _w[j] = _this._rol(_w[j-3] ^ _w[j-8] ^ _w[j-14] ^ _w[j-16], 1);\n }\n _t = _this._safeAdd(_this._safeAdd(_this._rol(_a, 5), _this._sha1FT(j, _b, _c, _d)),\n _this._safeAdd(_this._safeAdd(_e, _w[j]), _this._sha1KT(j)));\n _e = _d;\n _d = _c;\n _c = _this._rol(_b, 30);\n _b = _a;\n _a = _t;\n }\n\n _a = _this._safeAdd(_a, _olda);\n _b = _this._safeAdd(_b, _oldb);\n _c = _this._safeAdd(_c, _oldc);\n _d = _this._safeAdd(_d, _oldd);\n _e = _this._safeAdd(_e, _olde);\n }\n return [_a, _b, _c, _d, _e];\n }", "function passwordHash(password, salt) {\n var saltedPassword = password + salt;\n var hash = CryptoJS.MD5(saltedPassword);\n var hashedPassword = \"\";\n for (var i = 0; i < hash.words.length; i++) {\n hashedPassword += hash.words[i];\n }\n return hashedPassword;\n\n}", "function newHash(key, arrayLen){\n let total = 0;\n let WEIRD_PRIME = 31;\n for(let i = 0; i < Math.min(key.length, 100); i++){\n let char = key[i];\n let value = char.charCodeAt(0) - 96\n total = (total * WEIRD_PRIME + value) % arrayLen\n }\n console.log(total);\n}", "function getSalt(saltSize) {\n var bytes = crypto.randomBytes(Math.ceil(saltSize / 2));\n return bytes.toString('hex').slice(0, saltSize);\n }", "function genCalcHash() {\r\n\t\t//document.write(\"<br>random_seed \"+random_seed);\t\t\t//test random_seed value in this function.\r\n\t\t\r\n\t\tif(random_seed == false){//if random_seed not active\r\n\t\t\t//using original brainwallet function\r\n\t\t\tvar hash = Crypto.SHA256($('#pass').val());\r\n\t\t}else{\r\n\t\t\t//using brainwallet with specified random_seed\r\n\t\t\t//using xor at hash(random_seed). This was been defined.\r\n\t\t\t\r\n\t\t\tvar hash_of_passphase = Crypto.SHA256($('#pass').val());\t//this value is depending from entered passphrase.\r\n\t\t\tvar hash = XOR_hex(hash_of_random_seed, hash_of_passphase); //XOR this two hashes\r\n\r\n\t\t\t//document.write(\"<br>hash_of_random_seed \"+hash_of_random_seed); \t//print value of hash random_seed\r\n\t\t\t//0a743e5fcb375bcc6b9a044b6df5feaa309e939d9a29275265c3ecdb025bf905\r\n\t\t\t\r\n\t\t\t//you can see it in converter page\r\n\t\t\t//uncomment this two strings and press sha256-button in the section Converter\r\n\t\t\t//$('#src').val(random_seed);\r\n\t\t\t//$('#enc_to [id=\"to_sha256\"]').addClass('active');\r\n\t\t\t//result 0a743e5fcb375bcc6b9a044b6df5feaa309e939d9a29275265c3ecdb025bf905\t\t\t\r\n\t\t}\r\n\t\r\n\t\t//document.write(\"<br>hash is secret exponent: \"+hash); //echo value of new secret exponent\r\n\t\t$('#hash').val(hash);\t\t//set up hash_of_random_seed in the field of form.\r\n\t\t$('#hash_random_seed').val(hash_of_random_seed);\t\t//set up secret exponent in the field of form.\r\n\t\t$('#chhash_random_seed').val(hash_of_random_seed);\r\n\t\t$('#hash_passphrase').val(hash_of_passphase);\t\t//set up secret exponent in the field of form.\r\n\t\t\r\n\t\t//This value is a private key hex.\r\n\t\t//Generator -> press \"Togle Key\" button -> Private key WIF -> converter -> from Base58Check to hex -> is this value.\r\n\t\t//from Base58Check: 5KbEudEWZMr38UFxUrEww3ERKt3Pcc665cuQXBh3zoH6GZvkyBN\r\n\t\t//to hex: e9c4fa1d53cb47d8f161f083f49a478e1730d279feb2b41ec15675c07a094150\r\n\t\t//== Secret Exponent == hash value.\r\n\t\t\r\n\t\t//So when random_seed is defined and not false,\r\n\t\t//then private_key = Base58Check(hash(passphase) XOR hash(random_seed));\r\n }", "_hash(key) {\n let total = 0;\n const PRIME_NUM = 31;\n for (let i = 0; i < Math.min(key.length, 100); i += 1) {\n const char = key.charAt(i);\n const value = char.charCodeAt(0) - 96;\n total = (total * PRIME_NUM + value) % this.map.length;\n }\n\n return total;\n }", "static async slowHash(password, salt) {\n\n return new Promise(function (resolve, reject) {\n\n let pb = Security.str2ab(password);\n let sb = Security.str2ab(salt);\n\n scryptAsync(pb, sb, {\n N: Math.pow(2, 14),\n r: 8,\n p: 1,\n dkLen: 64,\n encoding: 'hex'\n }, function (derivedKey) {\n resolve(derivedKey);\n });\n\n });\n }", "function scramble(password, salt) {\n var stage1 = sha1(password);\n var stage2 = sha1(stage1);\n var stage3 = sha1(salt + stage2);\n return xor(stage3, stage1);\n}", "_hash(key) { //O(1)\n let hash = 0;\n for (let i = 0; i < key.length; i++) {//grab the length of 'grapes' (key)\n hash = (hash + key.charCodeAt(i) * i) % this.data.length;\n //charCodeAt(): returns an integer between 0 & 65535 \n //this.data.length: ensures the size stays between 0-50 (memory space for hash table)\n console.log(hash); // 0 14 8 44 48 23\n }\n return hash;\n }", "function generatePassword(conns){\n var salt = o.salt;\n if(o.dynamicSalt){\n salt = $( o.dynamicSalt).val();\n }\n var res = salt; //start our string to include the salt\n var off = o.shaOffset; //used to offset which bits we take\n var len = o.passLength; //length of password\n for(i in conns){\n res+=\"-\" + conns[i].startID;\n }\n res+=\"-\" + conns[i].endID; //make sure we get that last pin\n log(res);\n res = Sha1.hash(res, false);\n \n //make sure that we don't try to grab bits outside of our range\n if(off + len > res.length){\n off = 0; \n } \n res = res.substring(off, off + len);\n return res;\n }", "_hash(key) {\n let total = 0;\n let PRIME_NUMBER = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 96;\n total = (total * PRIME_NUMBER + value) % this.keyMap.length;\n }\n return total;\n }", "function decimal_finder(secret_key, hash_start){\n let decimal;\n for(i = 0; i < Infinity; i++){\n if(md5(secret_key.concat(i)).slice(0, hash_start.length) === hash_start){\n decimal = i;\n break;\n }\n }\n return decimal;\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function hashV2(key,arrayLen){\n var total = 0;\n var WEIRD_PRIME = 31;\n for(var i = 0; i < Math.min(key.length, 100); i++){\n var char = key[i];\n var value = char.charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % arrayLen;\n }\n return total;\n}", "function unblindEncrypt(N, e, s, b1){\r\n unblind = (s.multiply(b1)).mod(N);\r\n hash = unblind.modPow(e,N);\r\n return hash; \r\n }", "calculateHash(){\n\t\treturn SHA256(this.index + this.previousHash + this.timestamp + this.data + this.nonce).toString();\n\n\t}", "function DoHash(lengths){\r\n\tvar listSize = 256;\r\n\tvar list = Array(listSize).fill(0).map((e, i) => i);\r\n\tvar curr = 0;\r\n\tvar skip = 0;\r\n\t\r\n\tif(typeof lengths == \"string\") lengths = lengths.split(\"\").map(e => e.charCodeAt(0));\r\n\tlengths = lengths.concat([17, 31, 73, 47, 23]);\r\n\t\r\n\tfunction DoRound(){\r\n\t\tvar lengs = lengths.slice();\r\n\t\twhile(lengs.length){\r\n\t\t\tvar l = lengs.shift();\r\n\t\t\t\r\n\t\t\tvar s = list.concat(list).splice(curr, l);\r\n\t\t\ts.reverse();\r\n\t\t\tlist = list.map((e, i) => ((s[listSize + i - curr] + 1) || (s[i - curr] + 1) || (e + 1)) - 1);\r\n\t\t\t\r\n\t\t\tcurr += l + skip;\r\n\t\t\tcurr = curr % listSize;\r\n\t\t\tskip++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(var i = 0; i < 64; i++) DoRound();\r\n\t\r\n\tvar sparse = [];\r\n\twhile(list.length) sparse.push(list.splice(0, 16));\r\n\treturn sparse.map(b => b.reduce((acc, e, i, a) => acc ^ e, 0));\r\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[4] ^= R(x[0] + x[12], 7)\n x[8] ^= R(x[4] + x[0], 9)\n x[12] ^= R(x[8] + x[4], 13)\n x[0] ^= R(x[12] + x[8], 18)\n x[9] ^= R(x[5] + x[1], 7)\n x[13] ^= R(x[9] + x[5], 9)\n x[1] ^= R(x[13] + x[9], 13)\n x[5] ^= R(x[1] + x[13], 18)\n x[14] ^= R(x[10] + x[6], 7)\n x[2] ^= R(x[14] + x[10], 9)\n x[6] ^= R(x[2] + x[14], 13)\n x[10] ^= R(x[6] + x[2], 18)\n x[3] ^= R(x[15] + x[11], 7)\n x[7] ^= R(x[3] + x[15], 9)\n x[11] ^= R(x[7] + x[3], 13)\n x[15] ^= R(x[11] + x[7], 18)\n x[1] ^= R(x[0] + x[3], 7)\n x[2] ^= R(x[1] + x[0], 9)\n x[3] ^= R(x[2] + x[1], 13)\n x[0] ^= R(x[3] + x[2], 18)\n x[6] ^= R(x[5] + x[4], 7)\n x[7] ^= R(x[6] + x[5], 9)\n x[4] ^= R(x[7] + x[6], 13)\n x[5] ^= R(x[4] + x[7], 18)\n x[11] ^= R(x[10] + x[9], 7)\n x[8] ^= R(x[11] + x[10], 9)\n x[9] ^= R(x[8] + x[11], 13)\n x[10] ^= R(x[9] + x[8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "async generateSalt(){\n var saltValue = crypto.randomBytes(32).toString('base64');\n return saltValue;\n }", "function saltHashPassword (user) {\n if(user.changed('password')){\n user.password = sha256(user.password, '123445678910');\n }\n}", "hash(key){\n let hashedSum = 0;\n for(let i=0; i<key.length; i++){\n let hashedChar = i*(key[i].charCodeAt());\n hashedSum = hashedSum + hashedChar;\n }\n let primeHash = hashedSum*599;\n\n return primeHash%(this.size);\n }", "function hash(s) {\n let h = 1;\n for (let i = 0; i < s.length; i ++)\n h = Math.imul(h + s.charCodeAt(i) | 0, 2654435761);\n return (h ^ h >>> 17) >>> 0;\n}", "function hash (pwd, salt, fn) {\n log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){\n //log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n fn(err, hash.toString('base64'));\n });\n}", "function hashpw(password, salt, callback, progress) {\n var real_salt;\n var passwordb = [];\n var saltb = [];\n var hashed = [];\n var minor = String.fromCharCode(0);\n var rounds = 0;\n var off = 0;\n\n if (!progress) {\n progress = function() {};\n }\n\n if (salt.charAt(0) != '$' || salt.charAt(1) != '2')\n throw \"Invalid salt version\";\n if (salt.charAt(2) == '$')\n off = 3;\n else {\n minor = salt.charAt(2);\n if ((minor != 'a' && minor != 'b') || salt.charAt(3) != '$')\n throw \"Invalid salt revision\";\n off = 4;\n }\n\n // Extract number of rounds\n if (salt.charAt(off + 2) > '$')\n throw \"Missing salt rounds\";\n var r1 = parseInt(salt.substring(off, off + 1)) * 10;\n var r2 = parseInt(salt.substring(off + 1, off + 2));\n rounds = r1 + r2;\n real_salt = salt.substring(off + 3, off + 25);\n password = password + (minor >= 'a' ? \"\\000\" : \"\");\n passwordb = password_to_bytes(password)\n saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);\n crypt_raw(\n passwordb,\n saltb,\n rounds,\n BF_CRYPT_CIPHERTEXT.slice(0),\n function(hashed) {\n var rs = [];\n rs.push(\"$2\");\n if (minor >= 'a')\n rs.push(minor);\n rs.push(\"$\");\n if (rounds < 10)\n rs.push(\"0\");\n rs.push(rounds.toString());\n rs.push(\"$\");\n rs.push(encode_base64(saltb, saltb.length));\n rs.push(encode_base64(hashed, BF_CRYPT_CIPHERTEXT.length * 4 - 1));\n callback(rs.join(''));\n },\n progress);\n}", "calculateHash(){\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)+this.nonce).toString();\n }", "function makeHash(salt, password) {\n return createHmac('sha512', salt).update(password).digest('base64')\n}", "calculateHash() {\n return SHA256(this.timestamp + this.vote + this.voter + this.previousHash).toString();\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}", "calculateHash(){\n return SHA256(this.id + this.prevHash + this.timestamp + JSON.stringify(this.transactionList)+this.nonce).toString();\n }", "calculateHash(){\n\t\treturn SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();\n\t}", "function saltHashPassword(userpassword) {\n var salt = genRandomString(16); /** Gives us salt of length 16 */\n var passwordData = sha512(userpassword, salt);\n return passwordData;\n}", "function saltHashPassword({password, salt = randomString()}){\n const hash = crypto.createHmac('sha512', salt).update(password);\n return {\n salt,\n hash: hash.digest('hex')\n }\n}", "fastHash(password) {\n return crypto.createHash('sha256').update(password.toString()).digest(\"hex\");\n }", "function hash(input, salt){\n //How do we create a hash??\n //explanation of pbkdf2Sync: \n //1. input will be hashed to input+salt ==> 'password-this-is-some-random-string'\n //2. This String will be hashed 10000times ==> hashvalue is unique\n var hashed = crypto.pbkdf2Sync(input, salt, 10000, 512, 'sha512'); // crypto Object has to be create as object on the top\n return ['pbkdf2', '100000', salt, hashed.toString('hex')].join('$');\n}", "calculateHash(){\n return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();\n }", "calculateHash(){\n return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions)+this.nonce).toString();\n \n }", "function calculate_full_hash(domain, username, pwd, pwd_strength) {\n var hw_key = domain + \"_\" + username;\n if (hw_key in hashing_workers) {\n\tconsole.log(\"APPU DEBUG: Cancelling previous active hash calculation worker for: \" + hw_key);\n\thashing_workers[hw_key].terminate();\n\tdelete hashing_workers[hw_key];\n }\n\n const { ChromeWorker } = require(\"chrome\");\n var hw = new ChromeWorker(data.url(\"hash.js\"));\n\n hashing_workers[hw_key] = hw;\n\n hw.onmessage = function(worker_key, my_domain, my_username, my_pwd, my_pwd_strength) {\n\treturn function(event) {\n\t var rc = event.data;\n\t var hk = my_username + ':' + my_domain;\n\n\t if (typeof rc == \"string\") {\n\t\tconsole.log(\"(\" + worker_key + \")Hashing worker: \" + rc);\n\t }\n\t else if (rc.status == \"success\") {\n\t\tconsole.log(\"(\" + worker_key + \")Hashing worker, count:\" + rc.count + \", passwd: \" \n\t\t\t + rc.hashed_pwd + \", time: \" + rc.time + \"s\");\n\t\tif (pii_vault.password_hashes[hk].pwd_full_hash != rc.hashed_pwd) {\n\t\t pii_vault.password_hashes[hk].pwd_full_hash = rc.hashed_pwd;\n\n\t\t //Now calculate the pwd_group\n\t\t var curr_pwd_group = get_pwd_group(my_domain, rc.hashed_pwd, [\n\t\t\t\t\t\t\t\t\t\t my_pwd_strength.entropy, \n\t\t\t\t\t\t\t\t\t\t my_pwd_strength.crack_time,\n\t\t\t\t\t\t\t\t\t\t my_pwd_strength.crack_time_display\n\t\t\t\t\t\t\t\t\t\t ]);\n\t\t \n\t\t if (curr_pwd_group != pii_vault.current_report.user_account_sites[domain].my_pwd_group) {\n\t\t\tpii_vault.current_report.user_account_sites[domain].my_pwd_group = curr_pwd_group;\n\t\t\tflush_selective_entries(\"current_report\", [\"user_account_sites\"]);\n\t\t }\n\t\t \n\t\t //Now verify that short hash is not colliding with other existing short hashes.\n\t\t //if so, then modify it by changing salt\n\t\t for (var hash_key in pii_vault.password_hashes) {\n\t\t\tif (hash_key != hk && \n\t\t\t (pii_vault.password_hashes[hk].pwd_short_hash == \n\t\t\t pii_vault.password_hashes[hash_key].pwd_short_hash) &&\n\t\t\t (pii_vault.password_hashes[hk].pwd_full_hash != \n\t\t\t pii_vault.password_hashes[hash_key].pwd_full_hash)) {\n\t\t\t //This means that there is a short_hash collision. In this case, just change it,\n\t\t\t //by changing salt\n\t\t\t var err_msg = \"Seems like short_hash collision for keys: \" + hk + \", \" + hash_key;\n\t\t\t console.log(\"APPU DEBUG: \" + err_msg);\n\t\t\t print_appu_error(\"Appu Error: \" + err_msg);\n\t\t\t rc = calculate_new_short_hash(my_pwd, pii_vault.password_hashes[hk].salt);\n\n\t\t\t pii_vault.password_hashes[hk].pwd_short_hash = rc.short_hash;\n\t\t\t pii_vault.password_hashes[hk].salt = rc.salt;\n\t\t\t}\n\t\t }\n\t\t //Done with everything? Now flush those damn hashed passwords to the disk\n\t\t vault_write(\"password_hashes\", pii_vault.password_hashes);\n\t\t send_user_account_site_row_to_reports(domain);\n\t\t}\n\t\t//Now delete the entry from web workers.\n\t\tdelete hashing_workers[worker_key];\n\t }\n\t else {\n\t\tconsole.log(\"(\" + worker_key + \")Hashing worker said : \" + rc.reason);\n\t }\n\t}\n } (hw_key, domain, username, pwd, pwd_strength);\n \n //First calculate the salt\n //This salt is only for the purpose of defeating rainbow attack\n //For each password, the salt value will always be the same as salt table is\n //precomputed and fixed\n var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(pwd));\n var r = k.substring(k.length - 10, k.length);\n var rsv = parseInt(r, 16) % 1000;\n var rand_salt = pii_vault.salt_table[rsv];\n var salted_pwd = rand_salt + \":\" + pwd;\n\n console.log(\"APPU DEBUG: (calculate_full_hash) Added salt: \" + rand_salt + \" to domain: \" + domain);\n\n hw.postMessage({\n\t 'limit' : 1000000,\n\t\t'cmd' : 'hash',\n\t\t'pwd' : salted_pwd,\n\t\t});\n}", "function betterHash(str, len) {\n let total = 0;\n let value;\n const somePrime = 11;\n console.log(str.length);\n // limits iterations for extremely long strings\n for (let i = 0; i < Math.min(str.length, 100); i++) {\n value = str.charCodeAt(i) - 96;\n console.log(value);\n total = (total * somePrime + value) % len;\n }\n return total;\n}", "function sha256_S (X,n){return (X >>> n ) | (X << (32-n));}", "function hash1(key, arrayLen) {\n let total = 7;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 'a'.charCodeAt(0);\n total += (total * WEIRD_PRIME + value) % arrayLen\n } \n return total;\n}", "_hashed (s) {\n return s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0); \n }", "calculateHash() {\r\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();\r\n }", "function scrypt(a,b,c,d,e,f,g,h,i){\"use strict\";function k(a){function l(a){for(var l=0,m=a.length;m>=64;){var v,w,x,y,z,n=c,o=d,p=e,q=f,r=g,s=h,t=i,u=j;for(w=0;w<16;w++)x=l+4*w,k[w]=(255&a[x])<<24|(255&a[x+1])<<16|(255&a[x+2])<<8|255&a[x+3];for(w=16;w<64;w++)v=k[w-2],y=(v>>>17|v<<15)^(v>>>19|v<<13)^v>>>10,v=k[w-15],z=(v>>>7|v<<25)^(v>>>18|v<<14)^v>>>3,k[w]=(y+k[w-7]|0)+(z+k[w-16]|0)|0;for(w=0;w<64;w++)y=(((r>>>6|r<<26)^(r>>>11|r<<21)^(r>>>25|r<<7))+(r&s^~r&t)|0)+(u+(b[w]+k[w]|0)|0)|0,z=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&p^o&p)|0,u=t,t=s,s=r,r=q+y|0,q=p,p=o,o=n,n=y+z|0;c=c+n|0,d=d+o|0,e=e+p|0,f=f+q|0,g=g+r|0,h=h+s|0,i=i+t|0,j=j+u|0,l+=64,m-=64}}var b=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],c=1779033703,d=3144134277,e=1013904242,f=2773480762,g=1359893119,h=2600822924,i=528734635,j=1541459225,k=new Array(64);l(a);var m,n=a.length%64,o=a.length/536870912|0,p=a.length<<3,q=n<56?56:120,r=a.slice(a.length-n,a.length);for(r.push(128),m=n+1;m<q;m++)r.push(0);return r.push(o>>>24&255),r.push(o>>>16&255),r.push(o>>>8&255),r.push(o>>>0&255),r.push(p>>>24&255),r.push(p>>>16&255),r.push(p>>>8&255),r.push(p>>>0&255),l(r),[c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,d>>>24&255,d>>>16&255,d>>>8&255,d>>>0&255,e>>>24&255,e>>>16&255,e>>>8&255,e>>>0&255,f>>>24&255,f>>>16&255,f>>>8&255,f>>>0&255,g>>>24&255,g>>>16&255,g>>>8&255,g>>>0&255,h>>>24&255,h>>>16&255,h>>>8&255,h>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,j>>>24&255,j>>>16&255,j>>>8&255,j>>>0&255]}function l(a,b,c){function i(){for(var a=e-1;a>=e-4;a--){if(f[a]++,f[a]<=255)return;f[a]=0}}a=a.length<=64?a:k(a);var d,e=64+b.length+4,f=new Array(e),g=new Array(64),h=[];for(d=0;d<64;d++)f[d]=54;for(d=0;d<a.length;d++)f[d]^=a[d];for(d=0;d<b.length;d++)f[64+d]=b[d];for(d=e-4;d<e;d++)f[d]=0;for(d=0;d<64;d++)g[d]=92;for(d=0;d<a.length;d++)g[d]^=a[d];for(;c>=32;)i(),h=h.concat(k(g.concat(k(f)))),c-=32;return c>0&&(i(),h=h.concat(k(g.concat(k(f))).slice(0,c))),h}function m(a,b,c,d){var u,v,e=a[0]^b[c++],f=a[1]^b[c++],g=a[2]^b[c++],h=a[3]^b[c++],i=a[4]^b[c++],j=a[5]^b[c++],k=a[6]^b[c++],l=a[7]^b[c++],m=a[8]^b[c++],n=a[9]^b[c++],o=a[10]^b[c++],p=a[11]^b[c++],q=a[12]^b[c++],r=a[13]^b[c++],s=a[14]^b[c++],t=a[15]^b[c++],w=e,x=f,y=g,z=h,A=i,B=j,C=k,D=l,E=m,F=n,G=o,H=p,I=q,J=r,K=s,L=t;for(v=0;v<8;v+=2)u=w+I,A^=u<<7|u>>>25,u=A+w,E^=u<<9|u>>>23,u=E+A,I^=u<<13|u>>>19,u=I+E,w^=u<<18|u>>>14,u=B+x,F^=u<<7|u>>>25,u=F+B,J^=u<<9|u>>>23,u=J+F,x^=u<<13|u>>>19,u=x+J,B^=u<<18|u>>>14,u=G+C,K^=u<<7|u>>>25,u=K+G,y^=u<<9|u>>>23,u=y+K,C^=u<<13|u>>>19,u=C+y,G^=u<<18|u>>>14,u=L+H,z^=u<<7|u>>>25,u=z+L,D^=u<<9|u>>>23,u=D+z,H^=u<<13|u>>>19,u=H+D,L^=u<<18|u>>>14,u=w+z,x^=u<<7|u>>>25,u=x+w,y^=u<<9|u>>>23,u=y+x,z^=u<<13|u>>>19,u=z+y,w^=u<<18|u>>>14,u=B+A,C^=u<<7|u>>>25,u=C+B,D^=u<<9|u>>>23,u=D+C,A^=u<<13|u>>>19,u=A+D,B^=u<<18|u>>>14,u=G+F,H^=u<<7|u>>>25,u=H+G,E^=u<<9|u>>>23,u=E+H,F^=u<<13|u>>>19,u=F+E,G^=u<<18|u>>>14,u=L+K,I^=u<<7|u>>>25,u=I+L,J^=u<<9|u>>>23,u=J+I,K^=u<<13|u>>>19,u=K+J,L^=u<<18|u>>>14;b[d++]=a[0]=w+e|0,b[d++]=a[1]=x+f|0,b[d++]=a[2]=y+g|0,b[d++]=a[3]=z+h|0,b[d++]=a[4]=A+i|0,b[d++]=a[5]=B+j|0,b[d++]=a[6]=C+k|0,b[d++]=a[7]=D+l|0,b[d++]=a[8]=E+m|0,b[d++]=a[9]=F+n|0,b[d++]=a[10]=G+o|0,b[d++]=a[11]=H+p|0,b[d++]=a[12]=I+q|0,b[d++]=a[13]=J+r|0,b[d++]=a[14]=K+s|0,b[d++]=a[15]=L+t|0}function n(a,b,c,d,e){for(;e--;)a[b++]=c[d++]}function o(a,b,c,d,e){for(;e--;)a[b++]^=c[d++]}function p(a,b,c,d,e){n(a,0,b,c+16*(2*e-1),16);for(var f=0;f<2*e;f+=2)m(a,b,c+16*f,d+8*f),m(a,b,c+16*f+16,d+8*f+16*e)}function q(a,b,c){return a[b+16*(2*c-1)]}function r(a){for(var b=[],c=0;c<a.length;c++){var d=a.charCodeAt(c);d<128?b.push(d):d>127&&d<2048?(b.push(d>>6|192),b.push(63&d|128)):(b.push(d>>12|224),b.push(d>>6&63|128),b.push(63&d|128))}return b}function s(a){for(var b=\"0123456789abcdef\".split(\"\"),c=a.length,d=[],e=0;e<c;e++)d.push(b[a[e]>>>4&15]),d.push(b[a[e]>>>0&15]);return d.join(\"\")}function t(a){for(var f,g,h,i,b=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".split(\"\"),c=a.length,d=[],e=0;e<c;)f=e<c?a[e++]:0,g=e<c?a[e++]:0,h=e<c?a[e++]:0,i=(f<<16)+(g<<8)+h,d.push(b[i>>>18&63]),d.push(b[i>>>12&63]),d.push(b[i>>>6&63]),d.push(b[i>>>0&63]);return c%3>0&&(d[d.length-1]=\"=\",c%3===1&&(d[d.length-2]=\"=\")),d.join(\"\")}function D(){for(var a=0;a<32*d;a++){var b=4*a;x[B+a]=(255&z[b+3])<<24|(255&z[b+2])<<16|(255&z[b+1])<<8|(255&z[b+0])<<0}}function E(a,b){for(var c=a;c<b;c+=2)n(y,c*(32*d),x,B,32*d),p(A,x,B,C,d),n(y,(c+1)*(32*d),x,C,32*d),p(A,x,C,B,d)}function F(a,b){for(var c=a;c<b;c+=2){var e=q(x,B,d)&w-1;o(x,B,y,e*(32*d),32*d),p(A,x,B,C,d),e=q(x,C,d)&w-1,o(x,C,y,e*(32*d),32*d),p(A,x,C,B,d)}}function G(){for(var a=0;a<32*d;a++){var b=x[B+a];z[4*a+0]=b>>>0&255,z[4*a+1]=b>>>8&255,z[4*a+2]=b>>>16&255,z[4*a+3]=b>>>24&255}}function H(a,b,c,d,e){!function h(){setTimeout(function(){g((j/Math.ceil(w/f)*100).toFixed(2)),d(a,a+c<b?a+c:b),a+=c,j++,a<b?h():e()},0)}()}function I(b){var c=l(a,z,e);return\"base64\"===b?t(c):\"hex\"===b?s(c):c}var j,u=1;if(c<1||c>31)throw new Error(\"scrypt: logN not be between 1 and 31\");var x,y,z,A,v=1<<31>>>0,w=1<<c>>>0;if(d*u>=1<<30||d>v/128/u||d>v/256||w>v/128/d)throw new Error(\"scrypt: parameters are too large\");\"string\"==typeof a&&(a=r(a)),\"string\"==typeof b&&(b=r(b)),\"undefined\"!=typeof Int32Array?(x=new Int32Array(64*d),y=new Int32Array(32*w*d),A=new Int32Array(16)):(x=[],y=[],A=new Array(16)),z=l(a,b,128*u*d);var B=0,C=32*d;f<=0?(D(),E(0,w),F(0,w),G(),h(I(i))):(j=0,D(),H(0,w,2*f,E,function(){H(0,w,2*f,F,function(){G(),h(I(i))})}))}", "calculateHash() {\n return SHA256(\n this.previousHash +\n this.timestamp +\n JSON.stringify(this.transactions) +\n this.nonce\n ).toString();\n }", "_hash(key){\n let hash = 1\n for(let i=0;i<key.length;i++){\n hash = (hash + key.charCodeAt(i) * i) % this.data.length\n }\n return hash\n }", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n const {\n XY,\n V,\n B32,\n x,\n _X,\n B,\n tickCallback\n } = checkAndInit(key, salt, N, r, p, dkLen, progressCallback)\n\n for (var i = 0; i < p; i++) {\n smixSync(B, i * 128 * r, r, N, V, XY, _X, B32, x, tickCallback)\n }\n\n return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n const {\n XY,\n V,\n B32,\n x,\n _X,\n B,\n tickCallback\n } = checkAndInit(key, salt, N, r, p, dkLen, progressCallback)\n\n for (var i = 0; i < p; i++) {\n smixSync(B, i * 128 * r, r, N, V, XY, _X, B32, x, tickCallback)\n }\n\n return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n}", "hashFunction(key){\n var hash = 0;\n for (var i = 0; i < key.length; i++){\n hash += key.charCodeAt(i);\n }\n // use modulo of prime # 37\n return hash % 37;\n }", "function digest() {\n // Pad\n write(0x80);\n if (offset > 14 || (offset === 14 && shift < 24)) {\n processBlock();\n }\n offset = 14;\n shift = 24;\n\n // 64-bit length big-endian\n write(0x00); // numbers this big aren't accurate in javascript anyway\n write(0x00); // ..So just hard-code to zero.\n write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);\n write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);\n for (var s = 24; s >= 0; s -= 8) {\n write(totalLength >> s);\n }\n\n // At this point one last processBlock() should trigger and we can pull out the result.\n return toHex(h0) +\n toHex(h1) +\n toHex(h2) +\n toHex(h3) +\n toHex(h4);\n }", "function digest() {\n // Pad\n write(0x80);\n if (offset > 14 || (offset === 14 && shift < 24)) {\n processBlock();\n }\n offset = 14;\n shift = 24;\n\n // 64-bit length big-endian\n write(0x00); // numbers this big aren't accurate in javascript anyway\n write(0x00); // ..So just hard-code to zero.\n write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);\n write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);\n for (var s = 24; s >= 0; s -= 8) {\n write(totalLength >> s);\n }\n\n // At this point one last processBlock() should trigger and we can pull out the result.\n return toHex(h0) +\n toHex(h1) +\n toHex(h2) +\n toHex(h3) +\n toHex(h4);\n }", "function digest() {\n // Pad\n write(0x80);\n if (offset > 14 || (offset === 14 && shift < 24)) {\n processBlock();\n }\n offset = 14;\n shift = 24;\n\n // 64-bit length big-endian\n write(0x00); // numbers this big aren't accurate in javascript anyway\n write(0x00); // ..So just hard-code to zero.\n write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);\n write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);\n for (var s = 24; s >= 0; s -= 8) {\n write(totalLength >> s);\n }\n\n // At this point one last processBlock() should trigger and we can pull out the result.\n return toHex(h0) +\n toHex(h1) +\n toHex(h2) +\n toHex(h3) +\n toHex(h4);\n }", "calculateHash() {\n return Base64.stringify(HmacSHA256( this.previousHash + this.timesamp + this.data + this.nonce.toString(), this.index.toString()));\n }", "calculateHash() {\n return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();\n }", "calculateHash() {\n return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();\n }", "function passwordHash(password, salt) {\n\tvar hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */\n hash.update(password);\n \n return hash.digest('hex');\n}", "calculateHash(key) {\r\n return key.toString().length % this.size;\r\n }", "function getHash(pwd, salt){\n\treturn md5(pwd + salt)\n}", "calculateHash(){ \r\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\r\n }", "function testHashing512() {\n // This test tends to time out on IE7.\n if (!goog.userAgent.IE || goog.userAgent.isVersionOrHigher('8')) {\n hashGoldenTester(new goog.crypt.Sha512(), '512');\n }\n}", "hash() {\n function s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n }\n return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;\n }", "function betterHash(key, arrayLen) {\n let total = 0;\n let primeNum = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 96;\n total = (total * primeNum + value) % arrayLen;\n }\n return total;\n}", "calculateHash() {\n return SHA256(\n this.previousHash\n + this.previousDatabaseHash\n + this.blockNumber.toString()\n + this.refHiveBlockNumber.toString()\n + this.refHiveBlockId\n + this.prevRefHiveBlockId\n + this.timestamp\n + this.merkleRoot\n + JSON.stringify(this.transactions) // eslint-disable-line\n )\n .toString(enchex);\n }", "function sha1_ft(t, b, c, d)\r\n{\r\n if(t < 20) return (b & c) | ((~b) & d);\r\n if(t < 40) return b ^ c ^ d;\r\n if(t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}", "function core_sha1(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j];\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n}", "function core_sha1(x, len) {\r\n /* append padding */\r\n x[len >> 5] |= 0x80 << (24 - len % 32);\r\n x[((len + 64 >> 9) << 4) + 15] = len;\r\n\r\n var w = Array(80);\r\n var a = 1732584193;\r\n var b = -271733879;\r\n var c = -1732584194;\r\n var d = 271733878;\r\n var e = -1009589776;\r\n\r\n for (var i = 0; i < x.length; i += 16) {\r\n var olda = a;\r\n var oldb = b;\r\n var oldc = c;\r\n var oldd = d;\r\n var olde = e;\r\n\r\n for (var j = 0; j < 80; j++) {\r\n if (j < 16) w[j] = x[i + j];\r\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\r\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\r\n e = d;\r\n d = c;\r\n c = rol(b, 30);\r\n b = a;\r\n a = t;\r\n }\r\n\r\n a = safe_add(a, olda);\r\n b = safe_add(b, oldb);\r\n c = safe_add(c, oldc);\r\n d = safe_add(d, oldd);\r\n e = safe_add(e, olde);\r\n }\r\n return Array(a, b, c, d, e);\r\n\r\n}", "async function scryptHash(string, salt) {\n // Выбираем соль. Если соль есть - используем ее(нужно для сопоставления уже имеющихся данных), если нет - генерируем сами и возвращаем\n const saltInUse = salt || crypto.randomBytes(16).toString('hex')\n // Создаем хеш. Первый параметр scrypt - данные, второй - соль, третий - выходная длина хеша\n const hashBuffer = await util.promisify(crypto.scrypt)(string, saltInUse, 32)\n // Хеш переделываем в строку\n return `${(hashBuffer).toString('hex')}:${saltInUse}`\n}", "_hash(r,c) {\n return (15485867 + r) * 15485867 + c;\n }", "gen_hash(hashString) {\n var hex = 7\n for (let i = 0; i < hashString.length; i++) {\n hex = hex * 37 + sipherString.indexOf(hashString[i])\n }\n return hex\n }", "calculateHash(){\r\n return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();\r\n }", "function saltKey(key, salt, rounds) {\n let klen = key.length;\n let slen = salt.length;\n if (!slen) return key;\n\n // make a copy to avoid altering the input salt\n salt = salt.slice();\n\n let k = klen > 1 ? key[klen - 1] : 0;\n let s = slen > 1 ? salt[slen - 1] : 0;\n\n if (rounds == undefined) rounds = 1;\n while (rounds-- > 0) {\n for (let i = Math.max(klen, slen); i--;) {\n let ki = i % klen;\n let si = i % slen;\n k = key[ki] + k;\n s = salt[si] + s;\n\n s ^= s << 13; // 19\n s ^= s >>> 7; // 25\n\n k ^= k << 11; // 21\n k ^= k >>> 8; // 24\n\n // s >>>= 0;\n k += s;\n // k >>>= 0;\n\n key[ki] = k;\n salt[si] = s;\n }\n }\n\n return key;\n}", "function testHashing256() {\n hashGoldenTester(new goog.crypt.Sha512_256(), '256');\n}", "function sha1_ft(t, b, c, d) {\n if (t < 20) return (b & c) | ((~b) & d);\n if (t < 40) return b ^ c ^ d;\n if (t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "calculateHash(){\n return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data));\n }" ]
[ "0.70807123", "0.69053096", "0.6689671", "0.64896554", "0.64372206", "0.64352554", "0.6383274", "0.638033", "0.63542473", "0.6334163", "0.6296724", "0.62763786", "0.62681717", "0.6258082", "0.62338126", "0.6208083", "0.62007177", "0.6192447", "0.6171485", "0.6152615", "0.61450404", "0.61153096", "0.6114855", "0.61032903", "0.60679495", "0.60281646", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6018288", "0.6009862", "0.60020137", "0.5988123", "0.59825593", "0.59819645", "0.5977149", "0.59766513", "0.59549814", "0.59535366", "0.5951395", "0.5934025", "0.59270924", "0.5924433", "0.5921555", "0.5917302", "0.59149873", "0.5903379", "0.59021366", "0.5893752", "0.5888874", "0.5883925", "0.5875967", "0.587512", "0.5864493", "0.5862973", "0.58625805", "0.5860797", "0.5858371", "0.5850419", "0.5826218", "0.5820216", "0.5818991", "0.58098876", "0.58098876", "0.5796944", "0.5795421", "0.5795421", "0.5795421", "0.57944536", "0.57920444", "0.57899445", "0.5782902", "0.57823014", "0.5774468", "0.57582706", "0.5757111", "0.57502455", "0.5748213", "0.5741782", "0.5737141", "0.5734274", "0.5734274", "0.57129693", "0.57048583", "0.5704238", "0.5703496", "0.5697947", "0.56957316", "0.56929547", "0.5690138", "0.56896967", "0.5682096" ]
0.73278916
0
Calculates the super short hashsum given a salt Only count last 12bits..so plenty of collisions for an attacker
function calculate_short_hash(pwd, salt) { //Now get the short hash using salt calculated var salted_pwd = salt + ":" + pwd; var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd)); var hash_pwd = k.substring(k.length - 3, k.length); var rc = { 'short_hash' : hash_pwd, } return rc; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculate_new_short_hash(pwd, prev_salt) {\n //First get a salt that is not equal to prev_salt\n var curr_salt = prev_salt;\n while (curr_salt == prev_salt) {\n\tvar r = Math.floor((Math.random() * 1000)) % 1000;\n\tcurr_salt = pii_vault.salt_table[r];\n }\n\n //Now get the short hash using salt calculated\n var salted_pwd = curr_salt + \":\" + pwd;\n var k = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(salted_pwd));\n var hash_pwd = k.substring(k.length - 3, k.length);\n var rc = {\n\t'salt' : curr_salt,\n\t'short_hash' : hash_pwd, \n }\n return rc;\n}", "function compose_salt ( )\n {\n // storage note, seems to result in length 344\n\n return crypto.randomBytes( 256 ).toString( 'base64' );\n }", "function saltHashPassword(password)\n{\n var salt = \"aejjdgerjrxzcxzvbfahjaer\";\n var hash = crypto.createHmac('sha512', salt);\n hash.update(password);\n var value = hash.digest('hex');\n value=value.slice(0,40);\n return value;\n\n}", "function _stdHash(dd) {\n\t\t\tvar hash=0,salt=0;\n\t\t \tfor (var i=dd.length-1;i>=0;i--) {\n\t\t\t var charCode=parseInt(dd.charCodeAt(i));\n\t\t\t hash=((hash << 8) & 268435455) + charCode + (charCode << 12);\n\t\t\t if ((salt=hash & 161119850)!=0){hash=(hash ^ (salt >> 20))};\n\t\t\t}\n\t\t return hash.toString(16);\n\t\t}", "function makeHash(salt, password) {\n return createHmac('sha512', salt).update(password).digest('base64')\n}", "static async slowHash(password, salt) {\n\n return new Promise(function (resolve, reject) {\n\n let pb = Security.str2ab(password);\n let sb = Security.str2ab(salt);\n\n scryptAsync(pb, sb, {\n N: Math.pow(2, 14),\n r: 8,\n p: 1,\n dkLen: 64,\n encoding: 'hex'\n }, function (derivedKey) {\n resolve(derivedKey);\n });\n\n });\n }", "function createSalt() {\n\t//define the length of the salt\n\tvar len = 8;\n\t//create the hash\n\treturn crypto.randomBytes(Math.ceil(len/2)).toString('hex').substring(0,len);\n}", "fastHash(password) {\n return crypto.createHash('sha256').update(password.toString()).digest(\"hex\");\n }", "function passwordHash(password, salt) {\n var saltedPassword = password + salt;\n var hash = CryptoJS.MD5(saltedPassword);\n var hashedPassword = \"\";\n for (var i = 0; i < hash.words.length; i++) {\n hashedPassword += hash.words[i];\n }\n return hashedPassword;\n\n}", "function computeHash (source, salt) { \n\t//get hashing algorithm\n\tvar hmac = crypto.createHmac(\"sha1\", salt);\n\t//create the hash number\t\n\tvar hash = hmac.update(source);\n\t//get the hash as hex string\n\treturn hash.digest(\"hex\");\n}", "function hash(s) {\n let h = 1;\n for (let i = 0; i < s.length; i ++)\n h = Math.imul(h + s.charCodeAt(i) | 0, 2654435761);\n return (h ^ h >>> 17) >>> 0;\n}", "_generateSalt() {\n return crypto.randomBytes(Math.ceil(this._saltLength / 2))\n .toString('hex')\n .slice(0, this._saltLength);\n }", "function sha256_S (X,n){return (X >>> n ) | (X << (32-n));}", "function saltHashPassword(userpassword) {\n var salt = genRandomString(16); /** Gives us salt of length 16 */\n var passwordData = sha512(userpassword, salt);\n return passwordData;\n}", "function passwordHash(password, salt) {\n\tvar hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */\n hash.update(password);\n \n return hash.digest('hex');\n}", "function scramble(password, salt) {\n var stage1 = sha1(password);\n var stage2 = sha1(stage1);\n var stage3 = sha1(salt + stage2);\n return xor(stage3, stage1);\n}", "function generateSalt() {\n var saltWord = bip39.generateMnemonic(8);\n var saltHashedBitArray = sjcl.hash.sha256.hash(saltWord);\n salt = sjcl.codec.base64.fromBits(saltHashedBitArray);\n}", "_hash(key) {\n let total = 0;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let value = key[i].charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % this.keyMap.length;\n }\n return total;\n }", "function generateSalt() {\n var set =\n \"0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ\";\n var salt = \"\";\n for (var i = 0; i < 10; i += 1) {\n var p = Math.floor(Math.random() * set.length);\n salt += set[p];\n }\n return salt;\n }", "function hashpw(password, salt, callback, progress) {\n var real_salt;\n var passwordb = [];\n var saltb = [];\n var hashed = [];\n var minor = String.fromCharCode(0);\n var rounds = 0;\n var off = 0;\n\n if (!progress) {\n progress = function() {};\n }\n\n if (salt.charAt(0) != '$' || salt.charAt(1) != '2')\n throw \"Invalid salt version\";\n if (salt.charAt(2) == '$')\n off = 3;\n else {\n minor = salt.charAt(2);\n if ((minor != 'a' && minor != 'b') || salt.charAt(3) != '$')\n throw \"Invalid salt revision\";\n off = 4;\n }\n\n // Extract number of rounds\n if (salt.charAt(off + 2) > '$')\n throw \"Missing salt rounds\";\n var r1 = parseInt(salt.substring(off, off + 1)) * 10;\n var r2 = parseInt(salt.substring(off + 1, off + 2));\n rounds = r1 + r2;\n real_salt = salt.substring(off + 3, off + 25);\n password = password + (minor >= 'a' ? \"\\000\" : \"\");\n passwordb = password_to_bytes(password)\n saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);\n crypt_raw(\n passwordb,\n saltb,\n rounds,\n BF_CRYPT_CIPHERTEXT.slice(0),\n function(hashed) {\n var rs = [];\n rs.push(\"$2\");\n if (minor >= 'a')\n rs.push(minor);\n rs.push(\"$\");\n if (rounds < 10)\n rs.push(\"0\");\n rs.push(rounds.toString());\n rs.push(\"$\");\n rs.push(encode_base64(saltb, saltb.length));\n rs.push(encode_base64(hashed, BF_CRYPT_CIPHERTEXT.length * 4 - 1));\n callback(rs.join(''));\n },\n progress);\n}", "function saltHashPassword({password, salt = randomString()}){\n const hash = crypto.createHmac('sha512', salt).update(password);\n return {\n salt,\n hash: hash.digest('hex')\n }\n}", "_coreSHA1(_x, _len) {\n\n _x[_len >> 5] |= 0x80 << (24 - _len % 32);\n _x[((_len + 64 >> 9) << 4) + 15] = _len;\n\n const _this = this;\n let _a = 1732584193;\n let _b = -271733879;\n let _c = -1732584194;\n let _d = 271733878;\n let _e = -1009589776;\n const _w = new Array(80);\n let i;\n let _olda;\n let _oldb;\n let _oldc;\n let _oldd;\n let _olde;\n let j;\n let _t;\n\n for (i = 0; i < _x.length; i += 16) {\n _olda = _a;\n _oldb = _b;\n _oldc = _c;\n _oldd = _d;\n _olde = _e;\n\n for (j = 0; j < 80; j++) {\n if (j < 16) {\n _w[j] = _x[i + j];\n }\n else {\n _w[j] = _this._rol(_w[j-3] ^ _w[j-8] ^ _w[j-14] ^ _w[j-16], 1);\n }\n _t = _this._safeAdd(_this._safeAdd(_this._rol(_a, 5), _this._sha1FT(j, _b, _c, _d)),\n _this._safeAdd(_this._safeAdd(_e, _w[j]), _this._sha1KT(j)));\n _e = _d;\n _d = _c;\n _c = _this._rol(_b, 30);\n _b = _a;\n _a = _t;\n }\n\n _a = _this._safeAdd(_a, _olda);\n _b = _this._safeAdd(_b, _oldb);\n _c = _this._safeAdd(_c, _oldc);\n _d = _this._safeAdd(_d, _oldd);\n _e = _this._safeAdd(_e, _olde);\n }\n return [_a, _b, _c, _d, _e];\n }", "function newHash(key, arrayLen){\n let total = 0;\n let WEIRD_PRIME = 31;\n for(let i = 0; i < Math.min(key.length, 100); i++){\n let char = key[i];\n let value = char.charCodeAt(0) - 96\n total = (total * WEIRD_PRIME + value) % arrayLen\n }\n console.log(total);\n}", "function DoHash(lengths){\r\n\tvar listSize = 256;\r\n\tvar list = Array(listSize).fill(0).map((e, i) => i);\r\n\tvar curr = 0;\r\n\tvar skip = 0;\r\n\t\r\n\tif(typeof lengths == \"string\") lengths = lengths.split(\"\").map(e => e.charCodeAt(0));\r\n\tlengths = lengths.concat([17, 31, 73, 47, 23]);\r\n\t\r\n\tfunction DoRound(){\r\n\t\tvar lengs = lengths.slice();\r\n\t\twhile(lengs.length){\r\n\t\t\tvar l = lengs.shift();\r\n\t\t\t\r\n\t\t\tvar s = list.concat(list).splice(curr, l);\r\n\t\t\ts.reverse();\r\n\t\t\tlist = list.map((e, i) => ((s[listSize + i - curr] + 1) || (s[i - curr] + 1) || (e + 1)) - 1);\r\n\t\t\t\r\n\t\t\tcurr += l + skip;\r\n\t\t\tcurr = curr % listSize;\r\n\t\t\tskip++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(var i = 0; i < 64; i++) DoRound();\r\n\t\r\n\tvar sparse = [];\r\n\twhile(list.length) sparse.push(list.splice(0, 16));\r\n\treturn sparse.map(b => b.reduce((acc, e, i, a) => acc ^ e, 0));\r\n}", "function sha256_S(X, n) {\n\t return (X >>> n) | (X << (32 - n));\n\t }", "function getSalt(saltSize) {\n var bytes = crypto.randomBytes(Math.ceil(saltSize / 2));\n return bytes.toString('hex').slice(0, saltSize);\n }", "function hash (pwd, salt, fn) {\n log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){\n //log(\"Calculating hash \" + pwd + \"\\n\" + salt)\n fn(err, hash.toString('base64'));\n });\n}", "hash(key){\n let hashedSum = 0;\n for(let i=0; i<key.length; i++){\n let hashedChar = i*(key[i].charCodeAt());\n hashedSum = hashedSum + hashedChar;\n }\n let primeHash = hashedSum*599;\n\n return primeHash%(this.size);\n }", "function generatePassword(conns){\n var salt = o.salt;\n if(o.dynamicSalt){\n salt = $( o.dynamicSalt).val();\n }\n var res = salt; //start our string to include the salt\n var off = o.shaOffset; //used to offset which bits we take\n var len = o.passLength; //length of password\n for(i in conns){\n res+=\"-\" + conns[i].startID;\n }\n res+=\"-\" + conns[i].endID; //make sure we get that last pin\n log(res);\n res = Sha1.hash(res, false);\n \n //make sure that we don't try to grab bits outside of our range\n if(off + len > res.length){\n off = 0; \n } \n res = res.substring(off, off + len);\n return res;\n }", "_hash(key) { //O(1)\n let hash = 0;\n for (let i = 0; i < key.length; i++) {//grab the length of 'grapes' (key)\n hash = (hash + key.charCodeAt(i) * i) % this.data.length;\n //charCodeAt(): returns an integer between 0 & 65535 \n //this.data.length: ensures the size stays between 0-50 (memory space for hash table)\n console.log(hash); // 0 14 8 44 48 23\n }\n return hash;\n }", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7)\n x[ 8] ^= R(x[ 4] + x[ 0], 9)\n x[12] ^= R(x[ 8] + x[ 4], 13)\n x[ 0] ^= R(x[12] + x[ 8], 18)\n x[ 9] ^= R(x[ 5] + x[ 1], 7)\n x[13] ^= R(x[ 9] + x[ 5], 9)\n x[ 1] ^= R(x[13] + x[ 9], 13)\n x[ 5] ^= R(x[ 1] + x[13], 18)\n x[14] ^= R(x[10] + x[ 6], 7)\n x[ 2] ^= R(x[14] + x[10], 9)\n x[ 6] ^= R(x[ 2] + x[14], 13)\n x[10] ^= R(x[ 6] + x[ 2], 18)\n x[ 3] ^= R(x[15] + x[11], 7)\n x[ 7] ^= R(x[ 3] + x[15], 9)\n x[11] ^= R(x[ 7] + x[ 3], 13)\n x[15] ^= R(x[11] + x[ 7], 18)\n x[ 1] ^= R(x[ 0] + x[ 3], 7)\n x[ 2] ^= R(x[ 1] + x[ 0], 9)\n x[ 3] ^= R(x[ 2] + x[ 1], 13)\n x[ 0] ^= R(x[ 3] + x[ 2], 18)\n x[ 6] ^= R(x[ 5] + x[ 4], 7)\n x[ 7] ^= R(x[ 6] + x[ 5], 9)\n x[ 4] ^= R(x[ 7] + x[ 6], 13)\n x[ 5] ^= R(x[ 4] + x[ 7], 18)\n x[11] ^= R(x[10] + x[ 9], 7)\n x[ 8] ^= R(x[11] + x[10], 9)\n x[ 9] ^= R(x[ 8] + x[11], 13)\n x[10] ^= R(x[ 9] + x[ 8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\n}", "_hash(key) {\n let total = 0;\n const PRIME_NUM = 31;\n for (let i = 0; i < Math.min(key.length, 100); i += 1) {\n const char = key.charAt(i);\n const value = char.charCodeAt(0) - 96;\n total = (total * PRIME_NUM + value) % this.map.length;\n }\n\n return total;\n }", "function sha1_ft(t, b, c, d)\r\n{\r\n if(t < 20) return (b & c) | ((~b) & d);\r\n if(t < 40) return b ^ c ^ d;\r\n if(t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n}", "calculateHash(nonce) {\n // Your code here\n\n }", "function betterHash(str, len) {\n let total = 0;\n let value;\n const somePrime = 11;\n console.log(str.length);\n // limits iterations for extremely long strings\n for (let i = 0; i < Math.min(str.length, 100); i++) {\n value = str.charCodeAt(i) - 96;\n console.log(value);\n total = (total * somePrime + value) % len;\n }\n return total;\n}", "function scrypt (key, salt, N, r, p, dkLen, progressCallback) {\n if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')\n\n if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')\n if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')\n\n var XY = new Buffer(256 * r)\n var V = new Buffer(128 * r * N)\n\n // pseudo global\n var B32 = new Int32Array(16) // salsa20_8\n var x = new Int32Array(16) // salsa20_8\n var _X = new Buffer(64) // blockmix_salsa8\n\n // pseudo global\n var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')\n\n var tickCallback\n if (progressCallback) {\n var totalOps = p * N * 2\n var currentOp = 0\n\n tickCallback = function () {\n ++currentOp\n\n // send progress notifications once every 1,000 ops\n if (currentOp % 1000 === 0) {\n progressCallback({\n current: currentOp,\n total: totalOps,\n percent: (currentOp / totalOps) * 100.0\n })\n }\n }\n }\n\n for (var i = 0; i < p; i++) {\n smix(B, i * 128 * r, r, N, V, XY)\n }\n\n return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')\n\n // all of these functions are actually moved to the top\n // due to function hoisting\n\n function smix (B, Bi, r, N, V, XY) {\n var Xi = 0\n var Yi = 128 * r\n var i\n\n B.copy(XY, Xi, Bi, Bi + Yi)\n\n for (i = 0; i < N; i++) {\n XY.copy(V, i * Yi, Xi, Xi + Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n for (i = 0; i < N; i++) {\n var offset = Xi + (2 * r - 1) * 64\n var j = XY.readUInt32LE(offset) & (N - 1)\n blockxor(V, j * Yi, XY, Xi, Yi)\n blockmix_salsa8(XY, Xi, Yi, r)\n\n if (tickCallback) tickCallback()\n }\n\n XY.copy(B, Bi, Xi, Xi + Yi)\n }\n\n function blockmix_salsa8 (BY, Bi, Yi, r) {\n var i\n\n arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)\n\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 64, _X, 0, 64)\n salsa20_8(_X)\n arraycopy(_X, 0, BY, Yi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)\n }\n }\n\n function R (a, b) {\n return (a << b) | (a >>> (32 - b))\n }\n\n function salsa20_8 (B) {\n var i\n\n for (i = 0; i < 16; i++) {\n B32[i] = (B[i * 4 + 0] & 0xff) << 0\n B32[i] |= (B[i * 4 + 1] & 0xff) << 8\n B32[i] |= (B[i * 4 + 2] & 0xff) << 16\n B32[i] |= (B[i * 4 + 3] & 0xff) << 24\n // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js\n }\n\n arraycopy(B32, 0, x, 0, 16)\n\n for (i = 8; i > 0; i -= 2) {\n x[4] ^= R(x[0] + x[12], 7)\n x[8] ^= R(x[4] + x[0], 9)\n x[12] ^= R(x[8] + x[4], 13)\n x[0] ^= R(x[12] + x[8], 18)\n x[9] ^= R(x[5] + x[1], 7)\n x[13] ^= R(x[9] + x[5], 9)\n x[1] ^= R(x[13] + x[9], 13)\n x[5] ^= R(x[1] + x[13], 18)\n x[14] ^= R(x[10] + x[6], 7)\n x[2] ^= R(x[14] + x[10], 9)\n x[6] ^= R(x[2] + x[14], 13)\n x[10] ^= R(x[6] + x[2], 18)\n x[3] ^= R(x[15] + x[11], 7)\n x[7] ^= R(x[3] + x[15], 9)\n x[11] ^= R(x[7] + x[3], 13)\n x[15] ^= R(x[11] + x[7], 18)\n x[1] ^= R(x[0] + x[3], 7)\n x[2] ^= R(x[1] + x[0], 9)\n x[3] ^= R(x[2] + x[1], 13)\n x[0] ^= R(x[3] + x[2], 18)\n x[6] ^= R(x[5] + x[4], 7)\n x[7] ^= R(x[6] + x[5], 9)\n x[4] ^= R(x[7] + x[6], 13)\n x[5] ^= R(x[4] + x[7], 18)\n x[11] ^= R(x[10] + x[9], 7)\n x[8] ^= R(x[11] + x[10], 9)\n x[9] ^= R(x[8] + x[11], 13)\n x[10] ^= R(x[9] + x[8], 18)\n x[12] ^= R(x[15] + x[14], 7)\n x[13] ^= R(x[12] + x[15], 9)\n x[14] ^= R(x[13] + x[12], 13)\n x[15] ^= R(x[14] + x[13], 18)\n }\n\n for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]\n\n for (i = 0; i < 16; i++) {\n var bi = i * 4\n B[bi + 0] = (B32[i] >> 0 & 0xff)\n B[bi + 1] = (B32[i] >> 8 & 0xff)\n B[bi + 2] = (B32[i] >> 16 & 0xff)\n B[bi + 3] = (B32[i] >> 24 & 0xff)\n // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor (S, Si, D, Di, len) {\n for (var i = 0; i < len; i++) {\n D[Di + i] ^= S[Si + i]\n }\n }\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 sha1_ft(t, b, c, d) {\n if (t < 20) return (b & c) | ((~b) & d);\n if (t < 40) return b ^ c ^ d;\n if (t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function generateSalt() {\n return crypto.randomBytes(16).toString('base64');\n}", "function hash1(key, arrayLen) {\n let total = 7;\n let WEIRD_PRIME = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 'a'.charCodeAt(0);\n total += (total * WEIRD_PRIME + value) % arrayLen\n } \n return total;\n}", "function hashV2(key,arrayLen){\n var total = 0;\n var WEIRD_PRIME = 31;\n for(var i = 0; i < Math.min(key.length, 100); i++){\n var char = key[i];\n var value = char.charCodeAt(0) - 96;\n total = (total * WEIRD_PRIME + value) % arrayLen;\n }\n return total;\n}", "function saltHashPassword (user) {\n if(user.changed('password')){\n user.password = sha256(user.password, '123445678910');\n }\n}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}", "function SHA1(s){function U(a,b,c){while(0<c--)a.push(b)}function L(a,b){return(a<<b)|(a>>>(32-b))}function P(a,b,c){return a^b^c}function A(a,b){var c=(b&0xFFFF)+(a&0xFFFF),d=(b>>>16)+(a>>>16)+(c>>>16);return((d&0xFFFF)<<16)|(c&0xFFFF)}var B=\"0123456789abcdef\";return(function(a){var c=[],d=a.length*4,e;for(var i=0;i<d;i++){e=a[i>>2]>>((3-(i%4))*8);c.push(B.charAt((e>>4)&0xF)+B.charAt(e&0xF))}return c.join('')}((function(a,b){var c,d,e,f,g,h=a.length,v=0x67452301,w=0xefcdab89,x=0x98badcfe,y=0x10325476,z=0xc3d2e1f0,M=[];U(M,0x5a827999,20);U(M,0x6ed9eba1,20);U(M,0x8f1bbcdc,20);U(M,0xca62c1d6,20);a[b>>5]|=0x80<<(24-(b%32));a[(((b+65)>>9)<<4)+15]=b;for(var i=0;i<h;i+=16){c=v;d=w;e=x;f=y;g=z;for(var j=0,O=[];j<80;j++){O[j]=j<16?a[j+i]:L(O[j-3]^O[j-8]^O[j-14]^O[j-16],1);var k=(function(a,b,c,d,e){var f=(e&0xFFFF)+(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF),g=(e>>>16)+(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)})(j<20?(function(t,a,b){return(t&a)^(~t&b)}(d,e,f)):j<40?P(d,e,f):j<60?(function(t,a,b){return(t&a)^(t&b)^(a&b)}(d,e,f)):P(d,e,f),g,M[j],O[j],L(c,5));g=f;f=e;e=L(d,30);d=c;c=k}v=A(v,c);w=A(w,d);x=A(x,e);y=A(y,f);z=A(z,g)}return[v,w,x,y,z]}((function(t){var a=[],b=255,c=t.length*8;for(var i=0;i<c;i+=8){a[i>>5]|=(t.charCodeAt(i/8)&b)<<(24-(i%32))}return a}(s)).slice(),s.length*8))))}", "function unblindEncrypt(N, e, s, b1){\r\n unblind = (s.multiply(b1)).mod(N);\r\n hash = unblind.modPow(e,N);\r\n return hash; \r\n }", "_hashed (s) {\n return s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0); \n }", "function unique_salt() {\r\n return SHA1(mt_rand().toString());\r\n }", "function hashPassword(password, salt) {\n var hash = crypto.createHash('sha256');\n hash.update(password);\n hash.update(salt);\n return hash.digest('hex');\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function sha1_ft(t, b, c, d)\n{\n if(t < 20) return (b & c) | ((~b) & d);\n if(t < 40) return b ^ c ^ d;\n if(t < 60) return (b & c) | (b & d) | (c & d);\n return b ^ c ^ d;\n}", "function testHashing512() {\n // This test tends to time out on IE7.\n if (!goog.userAgent.IE || goog.userAgent.isVersionOrHigher('8')) {\n hashGoldenTester(new goog.crypt.Sha512(), '512');\n }\n}", "async function scryptHash(string, salt) {\n // Выбираем соль. Если соль есть - используем ее(нужно для сопоставления уже имеющихся данных), если нет - генерируем сами и возвращаем\n const saltInUse = salt || crypto.randomBytes(16).toString('hex')\n // Создаем хеш. Первый параметр scrypt - данные, второй - соль, третий - выходная длина хеша\n const hashBuffer = await util.promisify(crypto.scrypt)(string, saltInUse, 32)\n // Хеш переделываем в строку\n return `${(hashBuffer).toString('hex')}:${saltInUse}`\n}", "_hash(key) {\n let total = 0;\n let PRIME_NUMBER = 31;\n for (let i = 0; i < Math.min(key.length, 100); i++) {\n let char = key[i];\n let value = char.charCodeAt(0) - 96;\n total = (total * PRIME_NUMBER + value) % this.keyMap.length;\n }\n return total;\n }", "function sha1_ft(t, b, c, d) {\n\t if (t < 20) {\n\t return (b & c) | ((~b) & d);\n\t }\n\t if (t < 40) {\n\t return b ^ c ^ d;\n\t }\n\t if (t < 60) {\n\t return (b & c) | (b & d) | (c & d);\n\t }\n\t return b ^ c ^ d;\n\t }", "function scrypt(a,b,c,d,e,f,g,h,i){\"use strict\";function k(a){function l(a){for(var l=0,m=a.length;m>=64;){var v,w,x,y,z,n=c,o=d,p=e,q=f,r=g,s=h,t=i,u=j;for(w=0;w<16;w++)x=l+4*w,k[w]=(255&a[x])<<24|(255&a[x+1])<<16|(255&a[x+2])<<8|255&a[x+3];for(w=16;w<64;w++)v=k[w-2],y=(v>>>17|v<<15)^(v>>>19|v<<13)^v>>>10,v=k[w-15],z=(v>>>7|v<<25)^(v>>>18|v<<14)^v>>>3,k[w]=(y+k[w-7]|0)+(z+k[w-16]|0)|0;for(w=0;w<64;w++)y=(((r>>>6|r<<26)^(r>>>11|r<<21)^(r>>>25|r<<7))+(r&s^~r&t)|0)+(u+(b[w]+k[w]|0)|0)|0,z=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&p^o&p)|0,u=t,t=s,s=r,r=q+y|0,q=p,p=o,o=n,n=y+z|0;c=c+n|0,d=d+o|0,e=e+p|0,f=f+q|0,g=g+r|0,h=h+s|0,i=i+t|0,j=j+u|0,l+=64,m-=64}}var b=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],c=1779033703,d=3144134277,e=1013904242,f=2773480762,g=1359893119,h=2600822924,i=528734635,j=1541459225,k=new Array(64);l(a);var m,n=a.length%64,o=a.length/536870912|0,p=a.length<<3,q=n<56?56:120,r=a.slice(a.length-n,a.length);for(r.push(128),m=n+1;m<q;m++)r.push(0);return r.push(o>>>24&255),r.push(o>>>16&255),r.push(o>>>8&255),r.push(o>>>0&255),r.push(p>>>24&255),r.push(p>>>16&255),r.push(p>>>8&255),r.push(p>>>0&255),l(r),[c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,d>>>24&255,d>>>16&255,d>>>8&255,d>>>0&255,e>>>24&255,e>>>16&255,e>>>8&255,e>>>0&255,f>>>24&255,f>>>16&255,f>>>8&255,f>>>0&255,g>>>24&255,g>>>16&255,g>>>8&255,g>>>0&255,h>>>24&255,h>>>16&255,h>>>8&255,h>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,j>>>24&255,j>>>16&255,j>>>8&255,j>>>0&255]}function l(a,b,c){function i(){for(var a=e-1;a>=e-4;a--){if(f[a]++,f[a]<=255)return;f[a]=0}}a=a.length<=64?a:k(a);var d,e=64+b.length+4,f=new Array(e),g=new Array(64),h=[];for(d=0;d<64;d++)f[d]=54;for(d=0;d<a.length;d++)f[d]^=a[d];for(d=0;d<b.length;d++)f[64+d]=b[d];for(d=e-4;d<e;d++)f[d]=0;for(d=0;d<64;d++)g[d]=92;for(d=0;d<a.length;d++)g[d]^=a[d];for(;c>=32;)i(),h=h.concat(k(g.concat(k(f)))),c-=32;return c>0&&(i(),h=h.concat(k(g.concat(k(f))).slice(0,c))),h}function m(a,b,c,d){var u,v,e=a[0]^b[c++],f=a[1]^b[c++],g=a[2]^b[c++],h=a[3]^b[c++],i=a[4]^b[c++],j=a[5]^b[c++],k=a[6]^b[c++],l=a[7]^b[c++],m=a[8]^b[c++],n=a[9]^b[c++],o=a[10]^b[c++],p=a[11]^b[c++],q=a[12]^b[c++],r=a[13]^b[c++],s=a[14]^b[c++],t=a[15]^b[c++],w=e,x=f,y=g,z=h,A=i,B=j,C=k,D=l,E=m,F=n,G=o,H=p,I=q,J=r,K=s,L=t;for(v=0;v<8;v+=2)u=w+I,A^=u<<7|u>>>25,u=A+w,E^=u<<9|u>>>23,u=E+A,I^=u<<13|u>>>19,u=I+E,w^=u<<18|u>>>14,u=B+x,F^=u<<7|u>>>25,u=F+B,J^=u<<9|u>>>23,u=J+F,x^=u<<13|u>>>19,u=x+J,B^=u<<18|u>>>14,u=G+C,K^=u<<7|u>>>25,u=K+G,y^=u<<9|u>>>23,u=y+K,C^=u<<13|u>>>19,u=C+y,G^=u<<18|u>>>14,u=L+H,z^=u<<7|u>>>25,u=z+L,D^=u<<9|u>>>23,u=D+z,H^=u<<13|u>>>19,u=H+D,L^=u<<18|u>>>14,u=w+z,x^=u<<7|u>>>25,u=x+w,y^=u<<9|u>>>23,u=y+x,z^=u<<13|u>>>19,u=z+y,w^=u<<18|u>>>14,u=B+A,C^=u<<7|u>>>25,u=C+B,D^=u<<9|u>>>23,u=D+C,A^=u<<13|u>>>19,u=A+D,B^=u<<18|u>>>14,u=G+F,H^=u<<7|u>>>25,u=H+G,E^=u<<9|u>>>23,u=E+H,F^=u<<13|u>>>19,u=F+E,G^=u<<18|u>>>14,u=L+K,I^=u<<7|u>>>25,u=I+L,J^=u<<9|u>>>23,u=J+I,K^=u<<13|u>>>19,u=K+J,L^=u<<18|u>>>14;b[d++]=a[0]=w+e|0,b[d++]=a[1]=x+f|0,b[d++]=a[2]=y+g|0,b[d++]=a[3]=z+h|0,b[d++]=a[4]=A+i|0,b[d++]=a[5]=B+j|0,b[d++]=a[6]=C+k|0,b[d++]=a[7]=D+l|0,b[d++]=a[8]=E+m|0,b[d++]=a[9]=F+n|0,b[d++]=a[10]=G+o|0,b[d++]=a[11]=H+p|0,b[d++]=a[12]=I+q|0,b[d++]=a[13]=J+r|0,b[d++]=a[14]=K+s|0,b[d++]=a[15]=L+t|0}function n(a,b,c,d,e){for(;e--;)a[b++]=c[d++]}function o(a,b,c,d,e){for(;e--;)a[b++]^=c[d++]}function p(a,b,c,d,e){n(a,0,b,c+16*(2*e-1),16);for(var f=0;f<2*e;f+=2)m(a,b,c+16*f,d+8*f),m(a,b,c+16*f+16,d+8*f+16*e)}function q(a,b,c){return a[b+16*(2*c-1)]}function r(a){for(var b=[],c=0;c<a.length;c++){var d=a.charCodeAt(c);d<128?b.push(d):d>127&&d<2048?(b.push(d>>6|192),b.push(63&d|128)):(b.push(d>>12|224),b.push(d>>6&63|128),b.push(63&d|128))}return b}function s(a){for(var b=\"0123456789abcdef\".split(\"\"),c=a.length,d=[],e=0;e<c;e++)d.push(b[a[e]>>>4&15]),d.push(b[a[e]>>>0&15]);return d.join(\"\")}function t(a){for(var f,g,h,i,b=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".split(\"\"),c=a.length,d=[],e=0;e<c;)f=e<c?a[e++]:0,g=e<c?a[e++]:0,h=e<c?a[e++]:0,i=(f<<16)+(g<<8)+h,d.push(b[i>>>18&63]),d.push(b[i>>>12&63]),d.push(b[i>>>6&63]),d.push(b[i>>>0&63]);return c%3>0&&(d[d.length-1]=\"=\",c%3===1&&(d[d.length-2]=\"=\")),d.join(\"\")}function D(){for(var a=0;a<32*d;a++){var b=4*a;x[B+a]=(255&z[b+3])<<24|(255&z[b+2])<<16|(255&z[b+1])<<8|(255&z[b+0])<<0}}function E(a,b){for(var c=a;c<b;c+=2)n(y,c*(32*d),x,B,32*d),p(A,x,B,C,d),n(y,(c+1)*(32*d),x,C,32*d),p(A,x,C,B,d)}function F(a,b){for(var c=a;c<b;c+=2){var e=q(x,B,d)&w-1;o(x,B,y,e*(32*d),32*d),p(A,x,B,C,d),e=q(x,C,d)&w-1,o(x,C,y,e*(32*d),32*d),p(A,x,C,B,d)}}function G(){for(var a=0;a<32*d;a++){var b=x[B+a];z[4*a+0]=b>>>0&255,z[4*a+1]=b>>>8&255,z[4*a+2]=b>>>16&255,z[4*a+3]=b>>>24&255}}function H(a,b,c,d,e){!function h(){setTimeout(function(){g((j/Math.ceil(w/f)*100).toFixed(2)),d(a,a+c<b?a+c:b),a+=c,j++,a<b?h():e()},0)}()}function I(b){var c=l(a,z,e);return\"base64\"===b?t(c):\"hex\"===b?s(c):c}var j,u=1;if(c<1||c>31)throw new Error(\"scrypt: logN not be between 1 and 31\");var x,y,z,A,v=1<<31>>>0,w=1<<c>>>0;if(d*u>=1<<30||d>v/128/u||d>v/256||w>v/128/d)throw new Error(\"scrypt: parameters are too large\");\"string\"==typeof a&&(a=r(a)),\"string\"==typeof b&&(b=r(b)),\"undefined\"!=typeof Int32Array?(x=new Int32Array(64*d),y=new Int32Array(32*w*d),A=new Int32Array(16)):(x=[],y=[],A=new Array(16)),z=l(a,b,128*u*d);var B=0,C=32*d;f<=0?(D(),E(0,w),F(0,w),G(),h(I(i))):(j=0,D(),H(0,w,2*f,E,function(){H(0,w,2*f,F,function(){G(),h(I(i))})}))}", "function sha1_ft(t, b, c, d) {\r\n if (t < 20) return (b & c) | ((~b) & d);\r\n if (t < 40) return b ^ c ^ d;\r\n if (t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n}", "function sha1_ft(t, b, c, d) {\r\n if (t < 20) return (b & c) | ((~b) & d);\r\n if (t < 40) return b ^ c ^ d;\r\n if (t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n}", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function sha1_ft(t, b, c, d) {\n\t if(t < 20) return (b & c) | ((~b) & d);\n\t if(t < 40) return b ^ c ^ d;\n\t if(t < 60) return (b & c) | (b & d) | (c & d);\n\t return b ^ c ^ d;\n\t }", "function core_sha1(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j];\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n}", "function sha1_ft(t, b, c, d) {\r\n if(t < 20) return (b & c) | ((~b) & d);\r\n if(t < 40) return b ^ c ^ d;\r\n if(t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n }", "function binb_sha1(x, len)\n{\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for(var i = 0; i < x.length; i += 16)\n {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for(var j = 0; j < 80; j++)\n {\n if(j < 16) w[j] = x[i + j];\n else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\n var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),\n safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = bit_rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n}" ]
[ "0.7265873", "0.6680175", "0.65515584", "0.64110565", "0.632748", "0.63217413", "0.6301112", "0.6293531", "0.62884015", "0.62826186", "0.627014", "0.62294567", "0.6227629", "0.6218043", "0.6198331", "0.6185951", "0.614623", "0.6134158", "0.610319", "0.60551685", "0.6049774", "0.6048157", "0.6039621", "0.60356915", "0.60123485", "0.6011728", "0.5991996", "0.5981749", "0.597468", "0.5971712", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5970394", "0.5960104", "0.595633", "0.5943271", "0.5939285", "0.59367913", "0.59178257", "0.5908791", "0.5907497", "0.59059113", "0.59029174", "0.5898841", "0.5880588", "0.5880588", "0.58797693", "0.5871377", "0.5867384", "0.5867175", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5851439", "0.5847675", "0.5842145", "0.5827209", "0.5800198", "0.5794992", "0.5785722", "0.5785722", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.57763356", "0.5767084", "0.5761338", "0.5756226" ]
0.74395984
0
END OF Password Code START OF Blacklist Code
function pii_add_blacklisted_sites(message) { var dnt_site = message.dnt_site; var r = {}; if (pii_vault.options.blacklist.indexOf(dnt_site) == -1) { pii_vault.options.blacklist.push(dnt_site); r.new_entry = dnt_site; } else { r.new_entry = null; } console.log("New blacklist: " + pii_vault.options.blacklist); vault_write("options:blacklist", pii_vault.options.blacklist); return r; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function confirmCode(txt) {\n\t\tvar fullHash = hash(\"Multi-Pass Salt - \"+txt);\n\t\treturn fullHash.substring(fullHash.length-4);\n\t}", "static process_password(passwd){\n return passwd.padEnd(32, passwd) //passwd must be 32 long\n }", "function generatePassword() {\n\n\n\n//prompting the user for a passwordlength\n\n var passwordLength = prompt('How many characters would you like your password to contain? choose a number between 8 and 128 ! '); \n\n \n// if not (passwordLength>=8 && passwordLength<=128) \nif (!(passwordLength >= 8 && passwordLength <= 128)){\n\n // then Alert to the user that they need to provide a corrent length\n alert('invalid choice! please select a number between 8 ~ 128.');\n\n\n // and exit function\n return; \n}\n\n\n// Declare a new list of charcterToUse\n\nvar charactersToUse = []; \n\n// declare a new 'password' string \nvar password = \"\"; \n\n\n// confirm if the password generator 'isUsingNumbers'\n\n// IF 'isUsingNumbers'\n// Then push 'numbers'inton 'charactersToUSe' List \n// and Append on random number from the 'numbers' list \nvar isUsingNumbers = confirm ('Use Numbers in your password?'); \nif (isUsingNumbers == true){\n charactersToUse = charactersToUse.concat(numberSet); \n}\n\n\n// confirm if the password generator 'isUsingSpecial'\n\n// IF 'isUsingSpecial'\n// Then push 'specialSet' into charactersToUSe' List \n// and Append on random number from the 'specialSet' list \n\nvar isUsingSpecial = confirm('Use Special Characters to you password'); \n\nif (isUsingSpecial == true){\n\n charactersToUse = charactersToUse.concat(specialSet); \n}\n\n\n\n// confirm if the password generator 'isUsingUpper'\n// IF 'isUsingUpper'\n// Then push 'uppercase'into 'charactersToUSe' List \n// and Append on random number from the 'numbers' list \n \nvar isUsingUpper = confirm ('Use UPPER-CASE in your password?'); \nif (isUsingUpper == true){\n charactersToUse = charactersToUse.concat(upperSet); \n}\n\n\n\n// confirm if the password generator 'isUsingLower'\n// IF 'isUsingLower'\n// Then push 'lowercase ' into 'charactersToUSe' List \n// and Append on random number from the 'numbers' list \n\nvar isUsingLower= confirm ('Use lower-case in your password?'); \nif (isUsingLower == true){\n charactersToUse = charactersToUse.concat(lowerSet); \n}\n\n //check if user selects nothing \n\n\n\nif ( !isUsingNumbers && !isUsingSpecial && !isUsingUpper && !isUsingLower ) { \n\n alert('Please select options'); \n \n\n return; \n }\n\n\n\n\n\n\n//while password.length , passwordLength\n\nwhile (password.length < passwordLength) { \n\n\n // Select 'randomCharacter' a character from 'charactersToUse'\n var randomCharacter = charactersToUse[Math.floor(Math.random() * charactersToUse.length)]; \n \n // Append 'randomCharacter' to 'password' string \n\n password += randomCharacter; \n\n\n\n}\nconsole.log(charactersToUse); \n// Select Random characters from newlist characterstoUsefor 'password'\n\n// return'password'\nreturn password; \n}", "function unlockCard(card, codeInput){\r\n\tif(codeInput.substring(codeInput.length-1) == 'V'){\r\n\t\tif(codeInput.startsWith(card.password)){\r\n\t\t\tdisplayScreen(3);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tremainingTries--;\r\n\t\t\tif(remainingTries==0){\r\n\t\t\t\tdisplayScreen(5);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tdisplayScreen(2);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tdocument.getElementById(\"code\").innerHTML = \"• \".repeat(codeInput.length) + \"_ \".repeat(4-codeInput.length)\r\n\t}\r\n}", "function passwordRandomizer() {;\n for (var i = 0; i < characterAmount; i++) {\n finalPullList = finalStringList.replace(/,/g, \"\"); \n console.log(finalPullList);\n finalPassword += finalPullList[Math.floor(Math.random() * finalStringList.length)];\n console.log(finalPassword);\n return finalPassword;\n};\n}", "function passwordOnChange() {\n const pattern = \"^[a-zA-Z0-9_-]{6,20}$\";\n validate(this, pattern);\n}", "function getBlacklistAscii() {\n\t\tvar blacklist = '!@#$%^&*()+=[]\\\\\\';,/{}|\":<>?~`.-_';\n\t\tblacklist += \" \"; // 'Space' is on the blacklist but can be enabled using the 'allowSpace' config entry\n\t\treturn blacklist;\n\t}", "function validatePassword() {\n\n // empty array for the final if statement to check\n var errors = [];\n\n if (confirmLowerCase === true) {\n if (finalPass.search(/[a-z]/) < 0) {\n errors.push(\"lower\");\n }\n }\n if (confirmUpperCase === true) {\n if (finalPass.search(/[A-Z]/) < 0) {\n errors.push(\"upper\");\n }\n }\n if (confirmNumeric === true) {\n if (finalPass.search(/[0-9]/i) < 0) {\n errors.push(\"numeric\");\n }\n }\n if (confirmSpecialChar === true) {\n if (finalPass.search(/[!?@#$%^&*]/i) < 0) {\n errors.push(\"specialchar\");\n }\n }\n // if error array has contents, clear password string and regenerate password\n if (errors.length > 0) {\n finalPass = \"\"\n return passwordGen();\n }\n }", "function buildPassword () {\n //No user input validation alert//\n if(passArray.length == 0) {\n alert(\"You did not enter Any input(s) for your password. Please Enter an input.\");\n ///------------------------------------------------------///\n \n //Randomly select password characters from user(s) input//\n } else {\n for(var i = 0; i < passLength; i++) {\n var selectPassArray =\n passArray[Math.floor(Math.random() * passArray.length)];\n passwordArray.push(selectPassArray);\n } \n joinPassword (); \n }\n }", "function pwEvent() {\r\n if (validPW()) {\r\n $password.next().hide(); //next searches through immediate following siblings\r\n } else {\r\n $password.next().show();\r\n }\r\n}", "function getPasswordRequirements() {\n var passwordLength = parseInt(prompt(\"How many characters do you want in your password?\"))\n if (isNaN(passwordLength) === true) {\n alert(\"The length of the password must be a number\");\n return\n }\n if (passwordLength < 8) {\n alert(\"Please make sure your password is at least 8 characters long\");\n return\n }\n if (passwordLength > 128) {\n alert(\"Please make sure your password is less than 128 characters\");\n return\n }\n var containsSpecialCharacters = confirm(\"Click the OK button to confirm you want to use the special characters\")\n var containsNumbers = confirm(\"Click OK button to confirm you want numbers\")\n var containsLowercase = confirm(\"Click OK if you want lowercase characters\")\n var containsUppercase = confirm(\"Click OK if you want Uppercase characters\")\n\n if (containsSpecialCharacters === false && containsNumbers === false && containsLowercase === false && containsUppercase === false) {\n alert(\"You must select one character type in order to form a password\");\n }\n var allCharacters = [];\n\n if (containsUppercase) allCharacters = allCharacters.concat(uppercase);\n if (containsLowercase) allCharacters = allCharacters.concat(lowercase);\n if (containsNumbers) allCharacters = allCharacters.concat(numbers);\n if (containsSpecialCharacters) allCharacters = allCharacters.concat(specialCharaters);\n console.log(allCharacters);\n \n var secretCode = [];\n\n for (var i = 0; i < passwordLength; i++) {\n var pickChoices = allCharacters[Math.floor(Math.random() * allCharacters.length)];\n secretCode.push(pickChoices);\n console.log(secretCode);\n\n\n // var getPasswordRequirements={\n // passwordLength: passwordLength, \n // containsSpecialCharacters: containsSpecialCharacters,\n // containsNumbers: containsNumbers,\n // containsLowercase: containsLowercase,\n // containsUppercase: containsUppercase\n // }\n \n }\n return secretCode.join(\"\");\n}", "function pwCriteria() {\n var length = parseInt(\n prompt(\"Choose a password length from 8 to 128 characters\")\n );\n // length validation\n if (length < 8 || length > 128 || Number.isNaN(length)) {\n alert(\"Password needs to be in beetwen 8 to 128\");\n return;\n }\n\n //I confirm whether or not to include lowercase, uppercase, numeric, and/or special characters\n var lwrChoice = confirm(\"Click ok if you want lower case letters\");\n\n var upprChoice = confirm(\"Click ok if you want upper case letters\");\n\n var numChoice = confirm(\"Click ok if you want numbers\");\n\n var spcChoice = confirm(\"Click ok if you want special characters\");\n // VALIDATE IF USER CHOSE CHARACTERS\n if (\n lwrChoice === false &&\n upprChoice === false &&\n numChoice === false &&\n spcChoice === false\n ) {\n alert(\"The password must contain one type of character!\");\n return;\n }\n if (lwrChoice) {\n allChar = allChar.concat(lowerChar)\n \n }\n if (upprChoice) {\n allChar = allChar.concat(upperChar)\n \n }\n if (numChoice) {\n allChar = allChar.concat(numChar)\n \n }\n if (spcChoice) {\n allChar = allChar.concat(specialChar)\n \n }\n for (var i = 0; i < length; i++) {\n var index = Math.floor(Math.random() * allChar.length);\n var rndChar = allChar[index];\n rndPass = rndPass.concat(rndChar)\n \n }\n return rndPass;\n}", "function generatePassword() {\n //this returns the value for passwordParameters\n var userAnswers = passwordOptions()\n // create variable to hold the concatonated values\n // create empty arrays -> var possibleOptions = []\n // gauranteed array to hold gauranteed values\n\n if (userAnswers.hasRandomUpper) {\n // var possibleOptions = possibleOptions.concat(upper)\n // gauranteed.push(getRandom(upper))\n }\n}", "function checkPassword() {\n\n\n\n}", "function generatePassword() {\n alert (\"Select which criteria to include in the password\");\n\n\n var passLength = parseInt(prompt(\"Choose a length of at least 8 characters and no more than 128 characters\"));\n\n //evaluate user input for password length\n while (isNaN(passLength) || passLength < 8 || passLength > 128)\n {\n \n if (passLength === null) {\n return;\n }\n\n passLength = prompt(\"choose a length of at least 8 characters and no more than 128 characters\");\n }\n\n\n var lowerCase = confirm(\"Do you want lowercase characters in your password\");\n var upperCase = confirm(\"Do you want uppercase characters in your password\");\n var numChar = confirm(\"Do you want numbers in your password?\");\n var specChar = confirm(\"Do you want special characters in your password?\");\n\n\n //evalute criteria for password generation\n if (lowerCase || upperCase || numChar || specChar)\n {\n var otherToGen = '';\n var intList = '0123456789';\n var uCharList ='ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var lCharList ='abcdefghijklmnopqrstuvwxyz'; \n var sCharList =\"!#$%&()*+,-./:;<=>?@[]^_`{|}~\";\n var remainlenght = 0;\n var criteriaMatch = 0;\n var value = '';\n\n if (numChar){\n value += genchar(1, intList);\n criteriaMatch++;\n otherToGen += intList;\n\n }\n\n if (lowerCase){\n value += genchar(1, lCharList);\n criteriaMatch++;\n otherToGen += lCharList;\n }\n\n if (upperCase) {\n value += genchar(1, uCharList);\n criteriaMatch++;\n otherToGen += uCharList;\n }\n\n\n if(specChar) {\n value += genchar(1, sCharList);\n criteriaMatch++;\n otherToGen += sCharList;\n\n }\n\n remainlenght = passLength-criteriaMatch;\n value += genchar(remainlenght, otherToGen);\n\n return value;\n}\n}", "function ChangePassword() {\n\t}", "function generatePassword() {\n //prompt for password length\n var passLength = prompt(\"Please enter password length between 8 and 128\", \"8\");\n if (passLength < 8 || passLength > 128) {\n alert(\"Please enter a number between 8 and 128\");\n return;\n }\n //prompt for password complexity options\n var passUpOpt = confirm(\"would you like to include uppercase characters?\");\n var passLowOpt = confirm(\"would you like to include lowercase characters?\");\n var passNumOpt = confirm(\"would you like to include numeric characters?\");\n var passSpecOpt = confirm(\"would you like to include special characters?\");\n //array for password characters\n //let passChar = ['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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')' '_' '+'];\n var passUpChar = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var passLowChar = \"abcdefghijklmopqrstuvwxyz\";\n var passNumChar = \"1234567890\";\n var passSpecChar = \"!@#$%^&*()_+\";\n var passChar = \"\";\n \n /* if (passUpOpt = true) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecOpt = true) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } else if (passUpOpt = false) {\n if (passLowOpt = true) {\n if (passNumOpt = true) {\n if (passSpecChar = true) {\n passChar = passLowChar + passNumChar + passSpecChar;\n }\n }\n }\n } */\n //combinations of strings\n if (passUpOpt && passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passLowChar + passNumChar + passSpecChar;\n } else if (!passUpOpt && !passLowOpt && !passNumOpt && !passSpecOpt) {\n alert(\"Please choose at least one type of character\")\n } else if (passLowOpt && passNumOpt && passSpecOpt) {\n passChar = passLowChar + passNumChar + passSpecChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passUpOpt && passNumOpt && passSpecOpt) {\n passChar = passUpChar + passNumChar + passSpecChar;\n } else if (passUpOpt && passSpecOpt) {\n passChar = passUpChar + passSpecChar;\n } else if (passUpOpt && passLowOpt && passNumOpt) {\n passChar = passUpChar + passLowChar + passNumChar;\n } else if (passUpOpt && passLowOpt && passSpecChar) {\n passChar = passUpChar + passLowChar + passSpecChar;\n } else if (passUpOpt && passNumOpt) {\n passChar = passUpChar + passNumChar;\n } else if (passUpOpt) {\n passChar = passUpChar;\n } else if (passLowOpt && passNumOpt) {\n passChar = passLowChar + passNumChar;\n } else if (passLowChar) {\n passChar = passLowChar;\n } else if (passNumOpt && passSpecOpt) {\n passChar = passNumChar + passSpecChar;\n } else if (passSpecOpt) {\n passChar = passSpecChar;\n } else if (passNumOpt) {\n passChar = passNumChar;\n } else if (passUpOpt && passLowOpt) {\n passChar = passUpChar + passLowChar;\n } else if (passLowOpt && passSpecOpt) {\n passChar = passLowChar && passSpecChar;\n }\n\n console.log(passChar);\n\n\n var pass = \"\";\n //for loop to pick the characters the password will contain\n for(var i = 0; i <= passLength; i++) {\n pass = pass + passChar.charAt(Math.floor(Math.random() * Math.floor(passChar.length - 1)));\n }\n alert(pass);\n //return pass;\n document.querySelector(\"#password\").value = pass;\n\n}", "function passwordGen() {\n if (confirmLowerCase === true) {\n characterPool.push(confirmOptions.lowercase)\n }\n if (confirmUpperCase === true) {\n characterPool.push(confirmOptions.uppercase)\n }\n if (confirmNumeric === true) {\n characterPool.push(confirmOptions.numeric)\n }\n if (confirmSpecialChar === true) {\n characterPool.push(confirmOptions.specialchar)\n }\n\n //for loop to generate password and input into finalPass\n for (let i = 0; i < passLength; i++) {\n var poolArray = characterPool[Math.floor(Math.random() * characterPool.length)]\n var categoryIndex = (Math.floor(Math.random() * (poolArray.length +1)));\n if (categoryIndex >= poolArray.length) {\n categoryIndex = poolArray.length -1\n }\n finalPass = finalPass + poolArray[categoryIndex]\n }\n }", "function writePassword() {\n // var password = generatePassword(); \n //use \"Number\" to convert the string out of the prompt into a number \n a=Number(prompt(\"How many characters do you need ?\", \"Type number between 8 & 128\"));\n if (a<8 || a>128){\n alert(\"Your password length must be between 8 and 128\");}\n else{\n // series of prompts to confirm password criteria \n b=confirm(\"Can your password include numbers? Use Cancel for NO\"); \n c=confirm(\"Can your password include Upper-case letters? Use Cancel for NO\");\n d=confirm(\"Can your password include Special Characters? Use Cancel for NO\");\n /// calling my function of characters \n // using concatenate \"concat\" to link different sets of special characters \n var isNumber=myascii(48,57);\n var isSpecial=myascii(33,47).concat(myascii(58,64)).concat(myascii(91,96));\n var isUpper=myascii(65,90);\n var isLower=myascii(97,122);\n var charlist=isLower; // i'm using a local variable and will initiate it assuming all passwords will have lower characters \n if(b) {charlist=charlist.concat(isNumber)}; \n if(c) {charlist=charlist.concat(isUpper)};\n if(d) {charlist=charlist.concat(isSpecial)};\n var passcode=[];\n for (i=0; i<a; i++) {\n // creating a variable to select random number from our arrays length a\n var char=charlist[Math.floor(Math.random()*charlist.length)];\n // pushing the random number to the array passcode including transforming decimal to ascii characters\n passcode.push(String.fromCharCode(char));\n }\n \n } ; \n // re writing on the text area and transforming the array into string \n document.querySelector(\"#password\").textContent=passcode.join('');\n }", "function generatePassword() {\n \n var charList = \"\";\n \n if (upCharacters) {\n charList = charList + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n }\n if (lowCharacters) {\n charList = charList + \"abcdefghijklmnopqrstuvwxyz\";\n }\n if (numbers) {\n charList = charList + \"0123456789\";\n }\n if (specCh) {\n charList = charList + \"~!@#$%^&*()\";\n }\n \n /* this is in place so that if user doesnt select from the options this will alert */\n \n if (charList == \"\") {\n alert(\"You didn't pick from any of the criteria.\");\n return;\n }\n var password = \"\";\n for (var i = 0; i < passCharLength; i++) {\n password += charList[Math.floor(Math.random() * charList.length)];\n }\n document.getElementById('passwordBox').value = password;\n }", "function isValidPassword(password) {\n\n\n}", "validate(value) {\r\n if (value.toLowerCase().includes('password'))\r\n throw new Error('Password cannot contain password, come on');\r\n }", "function update_blacklist() {\n //blocked websites stored locally in blacklist.txt\n blocked = fs.readFileSync('./blacklist.txt').toString().split('\\n')\n .filter(function(rx) { return rx.length })\n .map(function(rx) { return RegExp(rx) });\n}", "function checkPassword() {\r\n\r\nvar pw = document.getElementBy(\"pw\").value.toLowerCase();\r\n\r\n\r\nfor (i = 0; i < wordsList.length; i++){\r\n if(pw == wordsList[0])\r\n { var pw = document.getElementBy break; \r\n }\r\n text += \"\"\r\n\r\n }\r\n\r\n\r\n}", "function generatePassword() {\n var passwordCriteria = userPrompts();\n console.log(passwordCriteria)\nif (passwordCriteria ==null){\n return \"WARNING you must have at least one 'Y' click generate password again\"; \n}else {\n var asciiCodes = [];\n if (passwordCriteria.numbers == \"Y\") {\n asciiCodes = asciiCodes.concat(NUMBER_CHAR_CODES);\n }\n if (passwordCriteria.passwordUpper == \"Y\") {\n asciiCodes = asciiCodes.concat(UPPERCASE_CHAR_CODES);\n }\n if (passwordCriteria.passwordLower == \"Y\") {\n asciiCodes = asciiCodes.concat(LOWERCASE_CHAR_CODES);\n }\n if (passwordCriteria.specialChar == \"Y\") {\n asciiCodes = asciiCodes.concat(SYMBOL_CHAR_CODES);\n }\n\n const passwordCharacters = []\n for (let i = 0; i < passwordCriteria.passwordLength; i++) {\n const characterCode = asciiCodes[Math.floor(Math.random() * asciiCodes.length)];\n passwordCharacters.push(String.fromCharCode(characterCode));\n }\n return passwordCharacters.join('')\n}\n \n}", "function generatePassword(){\n var length = window.prompt(\"Choose a password length of at least 8 characters and no more than 128 characters.\");\n\n if (length == null) {\n return randomPassword = \"Your Secure Password\";\n\n } else if (length >= 8 && length <= 128) {\n // run next step\n upperMessage;\n\n } else {\n window.alert(\"Please input a number between 8 and 128.\")\n return randomPassword = \"Your Secure Password\";\n }\n\n var upperMessage = window.confirm(\"Would you like to use uppercase letters? If no, select cancel.\");\n var lowerMessage = window.confirm(\"Would you like to use lowercase letters? If no, select cancel.\");\n var numberMessage = window.confirm(\"Would you like to use numbers? If no, select cancel.\");\n var symbolMessage = window.confirm(\"Would you like to use special characters? If no, select cancel.\");\n\n //selection criteria for password variable conditions \n\n if (!upperMessage && !lowerMessage && !numberMessage && !symbolMessage) {\n window.alert(\"You must select at least one of the options.\")\n return randomPassword = \"Your Secure Password\";\n }\n\n var randomPassword = [];\n\n if (upperMessage && lowerMessage && numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(upper).concat(lower).concat(number).concat(symbol);\n\n } else if (upperMessage && !lowerMessage && !numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(upper);\n \n } else if (upperMessage && lowerMessage && !numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(upper).concat(lower);\n \n } else if (upperMessage && lowerMessage && !numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(upper).concat(lower).concat(symbol);\n \n } else if (upperMessage && !lowerMessage && numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(upper).concat(number);\n\n } else if (upperMessage && !lowerMessage && !numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(upper).concat(symbol);\n\n } else if (!upperMessage && lowerMessage && !numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(lower); \n \n } else if (!upperMessage && lowerMessage && numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(lower).concat(number);\n \n } else if (!upperMessage && lowerMessage && !numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(lower).concat(symbol);\n\n } else if (!upperMessage && !lowerMessage && numberMessage && !symbolMessage) {\n randomPassword = randomPassword.concat(number);\n\n } else if (!upperMessage && !lowerMessage && numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(number).concat(symbol);\n\n } else if (!upperMessage && !lowerMessage && !numberMessage && symbolMessage) {\n randomPassword = randomPassword.concat(symbol);\n \n } \n\n /* for loop to randomly select password based on concating variables into the\n randomPassword array and then creates a random password in the securePassword variable.*/ \n\n var securePassword = \" \";\n\n for (i=0; i < length; i++) {\n securePassword = securePassword + randomPassword [Math.floor(Math.random() * randomPassword.length)];\n }\n\n // retuen secure password so variable password can display the output on the screen.\n return securePassword;\n}", "function password(){\n\t\t\n\t\t\tvar a = document.getElementById(\"pwd1\").value;\n\t\t\tif(a.length <= 8 ){\n\t\t\t\tdocument.getElementById(\"pwd1Hint\").style.display ='block';\n\t\t\t\n\t\t\t}\n\t\t\tif(a.length >= 8){\n\t\t\t\tdocument.getElementById(\"pwd1Hint\").style.display ='none';\n\t\t\t}\n\t\t\n\t\t\t\n\t\t\t\n\t}", "function writePassword() {\n \n // Ask user how long they want their password to be.\n // Prompt is inside of a for Loop until the user enters a password length between 8 and 128.\n \n var howlongpw = prompt(\"How long would you like your password to be (between 8 and 128 characters)?\");\n if (isNaN(howlongpw) === true) {\n return alert (\"You must select a number between 8 and 128, please try again.\");\n }\n\n if (((howlongpw)<8) || ((howlongpw)>128)) {\n return alert (\"You must select a password length between 8 and 128, please try again.\");\n }\n\n // Ask user if they want to include lower case letters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionLowerCase = confirm(\"Hit OK if you would like to include lower case letters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionLowerCase ===true) {\n Array.prototype.push.apply(userPasswordCritera,lowerCaseLettersCriteria);\n }\n\n // Ask user if they want to include upper case letters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n \n var optionUpperCase = confirm(\"Hit OK if you would like to include upper case letters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionUpperCase ===true) {\n Array.prototype.push.apply(userPasswordCritera,upperCaseLettersCriteria);\n }\n\n // Ask user if they want to include numbers in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionNumbers = confirm(\"Hit OK if you would like to include numbers in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionNumbers ===true) {\n Array.prototype.push.apply(userPasswordCritera,numberCriteria);\n }\n\n // Ask user if they want to include special characters in their password.\n // Use a confirm, OK = yes include. Cancel = no exclude.\n\n var optionSpecialChars = confirm(\"Hit OK if you would like to include special characters in your password. Please hit Cancel if you would like to exclude them.\");\n if (optionSpecialChars ===true) {\n Array.prototype.push.apply(userPasswordCritera,specialCharsCriteria);\n }\n\n // Test to see if user's password criteria was in fact added to the userPasswordCritera array after hitting OK.\n for (var t=0; t < userPasswordCritera.length; t++) {\n console.log (\"Users password criteria to choose from \" + userPasswordCritera[i]);\n }\n\n// Now that we have the userPasswordCritera array which contains the available characters for the users password we can run \n// a loop (based on howlongpw variable) to add random characters to their empty password array. \n// Generate a random number (using math.floor and math.random) from 0 to userPasswordCritera.length to pick random index in userPasswordCritera array. \n// Then add it to the userSecurePassword array and display user's password in the text area when password is complete.\n\n// Generate random characters to append to userSecurePassword.\nfor (var i=0; i < howlongpw; i++) {\n var randomIndexGenerator = Math.floor(Math.random() * userPasswordCritera.length);\n var characterToAddToPassword = userPasswordCritera[randomIndexGenerator];\n userSecurePassword.push(characterToAddToPassword);\n }\n\n // Declared password as the userSecurePassword without the commas between each letter in the password. \n var password = userSecurePassword.join(\"\");\n var passwordText = document.querySelector(\"#password\");\n\n // Display randomly generated password in text area on password generater webpage.\n passwordText.value = password;\n}", "function getPasswordCap() {\n if (upperLetters) {\n finalPassword.push(capitalLetters[Math.floor(Math.random() * capitalLetters.length)]);\n } else {\n capitalLetters.splice(0, 26)\n }\n\n}", "function writePassword() {}", "function generatePassword() {\n\n let generatedPassword = \"\"; // RETURN THIS VALUE\n let categoriesChosen = [];\n const numbers = \"0123456789\"; // 10 fixed\n const letters = \"abcdefghijklmnopqrstuvwxyz\"; // 26 fixed\n const chars = \"!\\#\\$\\%\\'()+,-./:?@[\\\\]^_\\`{}~\"; // 24 fixed\n // chars checked against Oracle & Microsoft ActiveDirectory password requirements:\n // not allowed = ampersand, asterisk, semicolon, greaterthan, lessthan, equals, pipebar\n const dictionary = {\n numbers: Array.from(numbers),\n lowercases: Array.from(letters),\n uppercases: Array.from((letters).toUpperCase()),\n specials: Array.from(chars),\n };\n const userInput = {\n includeNums: confirm(\"Do you want to include numbers? (0 1 2 3...)\"),\n includeLowers: confirm(\"Do you want to include lowercase letters? (a b c d...)\"),\n includeUppers: confirm(\"Do you want to include uppercase letters? (A B C D...)\"),\n includeSpecials: confirm(\"Do you want to include special characters? (# $ % @...)\"),\n passwordLength: prompt(\"How many characters should the password contain? (8-128)\"),\n };\n\n // validate userInput\n while (!userInput.includeNums && !userInput.includeLowers && !userInput.includeUppers && !userInput.includeSpecials) {\n alert(\"You must select at least one category of characters for your password\");\n userInput.includeNums = confirm(\"Do you want to include numbers? (0 1 2 3...)\");\n userInput.includeLowers = confirm(\"Do you want to include lowercase letters? (a b c d...)\");\n userInput.includeUppers = confirm(\"Do you want to include uppercase letters? (A B C D...)\");\n userInput.includeSpecials = confirm(\"Do you want to include special characters? (# $ % @...)\");\n };\n while (isNaN(userInput.passwordLength) || (8 > userInput.passwordLength) || (userInput.passwordLength > 128)) {\n userInput.passwordLength = prompt(\"You did not enter a number between 8 and 128!\", \"Enter a number using digits between 8 and 128\");\n };\n\n // build array of chosen category names\n if (userInput.includeNums) {categoriesChosen.push(\"numbers\")};\n if (userInput.includeLowers) {categoriesChosen.push(\"lowercases\")};\n if (userInput.includeUppers) {categoriesChosen.push(\"uppercases\")};\n if (userInput.includeSpecials) {categoriesChosen.push(\"specials\")};\n\n // Cycle through the chosen categories and add a random character from each until generatedPassword.length >= passwordLength\n while (generatedPassword.length < userInput.passwordLength) {\n for (let i = 0; i < categoriesChosen.length; i++) {\n let loopCategory = dictionary[categoriesChosen[i]];\n generatedPassword += loopCategory[Math.floor(Math.random() * (loopCategory.length))];\n };\n };\n // truncate the final password to the exact request length if it's longer\n document.querySelector(\"#copy\").disabled = false;\n return generatedPassword.substring(0, userInput.passwordLength);\n}", "function generatePassword(conns){\n var salt = o.salt;\n if(o.dynamicSalt){\n salt = $( o.dynamicSalt).val();\n }\n var res = salt; //start our string to include the salt\n var off = o.shaOffset; //used to offset which bits we take\n var len = o.passLength; //length of password\n for(i in conns){\n res+=\"-\" + conns[i].startID;\n }\n res+=\"-\" + conns[i].endID; //make sure we get that last pin\n log(res);\n res = Sha1.hash(res, false);\n \n //make sure that we don't try to grab bits outside of our range\n if(off + len > res.length){\n off = 0; \n } \n res = res.substring(off, off + len);\n return res;\n }", "function secondPass() {\n var errors = document.querySelector(\"#errors\");\n var password = document.querySelector(\"#secondPass\");\n var pass = password.value.trim();\n var patt = /^(?=.*[a-z])(?=.*\\d){8,16}$/ig;\n if(!patt.test(pass)) {\n return false;\n } \n else {\n return true;\n }\n}", "function writePassword() {\n //function generatePassword (){\n //Establish variables. Arrays 1-4 are initial options that will be concatenated together based on prompts\n var passwordText = document.querySelector(\"#password\");\n var array1 = [\"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 //write quickly an uppercase array, from google. \n var array2 = array1.map(function(x) {return x.toUpperCase(); });\n var array3 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];\n var array4 = [\"!\", \"#\", \"$\", \"%\", \"&\", \"(\", \")\", \"*\", \"+\", \",\", \"-\", \".\", \":\", \";\", \"<\", \"=\", \">\", \"?\", \"@\", \"[\", \"]\", \"^\", \"_\", \"`\", \"{\", \"|\", \"}\", \"~\"]\n var passwordLength = window.prompt('Password length?');\n//Kicks back to top of function if length criteria is not met\n if (passwordLength <= 8 || passwordLength >=128 ) {\n alert(\"Please enter value between 8 and 128\");\n writePassword ();\n} else {\n\n \n//give user selection for lower case, upper case alpha, numbers, and special chars in the password\nvar alphaLowerConf = confirm(\"Include lower case letters?\");\nvar alphaUpperConf = confirm(\"Include upper case letters?\");\nvar numConf = confirm(\"Include numbers?\");\nvar specConf = confirm(\"Include special characters?\");\n\n//declare initial empty final array. Combine arrays based on prompts. Could remove ==true later to save space.\n//if all prompts were false, restart at the top of the function.\nvar finalArray = [];\nif (numConf){\n finalArray = finalArray.concat(array3);}\nif (alphaLowerConf) {\n finalArray = finalArray.concat(array1);}\nif (alphaUpperConf){\n finalArray = finalArray.concat(array2);} \nif (specConf){\n finalArray = finalArray.concat(array4);} \nif (numConf==false && alphaLowerConf==false && alphaUpperConf==false && specConf ==false){\n alert(\"Please select at least one character type.\")\n writePassword();\n} else {\n\n //check that an appropriate array was built\n console.log(`this is my final array${finalArray}`);\nvar pw = new Array(passwordLength);\n\nfor (i=0; i<=passwordLength; i++){\n var rand = Math.floor(Math.random() * finalArray.length);\npw[i] = finalArray[rand];\n}\n//reducing array down to a string without commas for printing to screen\nvar pwStringA=pw.join(\",\");\nvar pwStringB=pwStringA.replaceAll(\",\",\"\");\nvar finalPW = document.querySelector('#password');\nfinalPW.textContent = pwStringB;\n}\n}\n}", "function writePassword() {\n // sort all the various characters into arrays by type\n var specialCharacters = \"`~!@#$%^&*()-_=+[{]}\\\\|;:'\\\",<.>/?\".split(\"\");\n var numerics = \"1234567890\".split(\"\");\n var lowerCase = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n var upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\");\n // make sure password length is within limits\n var passwordLength = prompt(\"Your Password must be between 8 and 128 Characters. Please enter your desired password length:\");\n if (passwordLength < 8 || passwordLength > 128 || isNaN(passwordLength) === true) {\n alert(\"If you can't even do this right, you have no business protecting your information behind passwords. Sigh. Your password will now be 30 characters, okay?\");\n var passwordLength = 30;\n }\n // ask user what kind of password they want\n var wantsSpecialCharacters = confirm(\"Do you want Special Characters in your password? (OK: Yes / Cancel: No)\");\n var wantsNumerics = confirm(\"Do you want Numerics in your password? (OK: Yes / Cancel: No)\");\n var wantsLowerCase = confirm(\"Do you want Lowercase Letters in your password? (OK: Yes / Cancel: No)\");\n var wantsUpperCase = confirm(\"Do you want Uppercase Letters in your password? (OK: Yes / Cancel: No)\");\n // uses Booleans to place all selected character types into final character \"pool\"\n var characterPool = [];\n if (wantsSpecialCharacters === true) {\n var characterPool = characterPool.concat(specialCharacters);\n }\n if (wantsNumerics === true) {\n var characterPool = characterPool.concat(numerics);\n }\n if (wantsLowerCase === true) {\n var characterPool = characterPool.concat(lowerCase);\n }\n if (wantsUpperCase === true) {\n var characterPool = characterPool.concat(upperCase);\n }\n if (wantsSpecialCharacters === false && wantsNumerics === false && wantsLowerCase === false && wantsUpperCase === false) {\n alert(\"You have chosen NOTHING as your password? Are you serious? Look, just use all possible characters. Trust me, it will help you.\");\n var characterPool = characterPool.concat(specialCharacters).concat(numerics).concat(lowerCase).concat(upperCase);\n }\n // create the password of set length and with selected character types\n function generatePassword(pool, length) {\n var password = \"\";\n for (let i = 0; i < length; i++) {\n var randomSelector = Math.floor(Math.random() * pool.length);\n console.log(randomSelector);\n password += pool[randomSelector];\n }\n return password;\n }\n // display password in box\n var password = generatePassword(characterPool, passwordLength);\n var passwordText = document.querySelector(\"#password\");\n passwordText.textContent = password;\n}", "function checkPassword() {\n //get what the user input\n //in.html, the input box has id=pw\n var input = document.getElementById(\"pw\").value;\n\n //loop through all the words in the word list\n //earlier, words list was set to contain a list of english words\n for (var index = 0; index < wordsList.length; index++) {\n //warn them if password matches a word from the list\n\n if (wordsList[index] == input) {\n alert(\"Password is too weak! It's an English word.\");\n return; //stop this function as soon as I find this match\n }\n\n //warn them if that word from th elist, when I leetify it,\n //matches their input\n //ex:wordsList[index] is 'hello', leetify(wordsList[index]) is 'h3ll0'\n if (leetify(wordsList[index]) == input ) {\n alert(\"Weak password! It's too close to \" + wordsList[index]);\n return;\n }\n }\n\n for (var index = 0; index < commonList.length; index++) {\n //warn them if password matches a word from the list\n\n if (commonList[index] == input) {\n alert(\"Password is too weak! It's too common!\");\n return; //stop this function as soon as I find this match\n }\n }\n\n for (var index = 0; index < commonFem.length; index++) {\n //warn them if password matches a word from the list\n\n if (commonList[index] == input) {\n alert(\"Password is too weak! It's a name!\");\n return; //stop this function as soon as I find this match\n }\n }\n\n for (var index = 0; index < commonMale.length; index++) {\n //warn them if password matches a word from the list\n\n if (commonList[index] == input) {\n alert(\"Password is too weak! It's a name!\");\n return; //stop this function as soon as I find this match\n }\n }\n\n for (var index = 0; index < commonLast.length; index++) {\n //warn them if password matches a word from the list\n\n if (commonList[index] == input) {\n alert(\"Password is too weak! It's a name!\");\n return; //stop this function as soon as I find this match\n }\n }\n\n //after the for loop finishes, if it wasn't an English word\n //tell them their pass word is safe\n alert(\"Your password is just fine :)\")\n}", "function generatePassword () {\n \n//List of Arrays\nvar uppercaseLetters = [\"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\nvar lowercaseLetters = [\"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\nvar numbers = [0,1,2,3,4,5,6,7,8,9];\n\nvar symbols = ['!', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '[','{', ']', '}', '|', ';', ':', '<', ',', '>', '.', '?', '~', '`'];\n\n//all true conditions array\nvar characters = [];\n\n //Ask user how many characters they would like their passowrd to contain\n var numberOfCharacters = prompt(\"How many characters would you like your password to contain? (Password must be 8 - 128 characters long)\");\n\n\n //check to see if answer meets condition; if not it will repeat the question\n while (numberOfCharacters < 8 || numberOfCharacters > 128) { \n \n //alert the user the condition and ask the prompt again\n alert(\"PLEASE ENTER A NUMBER BETWEEN 8 & 128!\");\n \n numberOfCharacters = prompt(\"How many characters would you like your password to contain? (Password must be 8 - 128 characters long)\");\n\n \n\n }\n \n //if user hits OK, add symbols array to characters array\n if (confirm(\"Click OK to confirm including special characters\")) {\n characters.push(symbols);\n }\n\n //if user hits OK, add numbers to characters array\n if (confirm(\"Click OK to confirm including numeric characters\")) {\n characters.push(numbers);\n }\n\n //if user hits OK, add lowecaseLetters to character array\n if (confirm(\"Click OK to confirm including lowercase letters\")) {\n characters.push(lowercaseLetters);\n }\n\n //if user hits OK, add uppercaseLetters to character array\n if (confirm(\"Click OK to confirm including uppercase letters\")) {\n characters.push(uppercaseLetters);\n }\n\n let password = [];\n //for loop for generating password\nfor (var i = 0; i < numberOfCharacters; i++ ) {\n var randomArray = characters[Math.floor(Math.random() * characters.length)];\n password += randomArray[Math.floor(Math.random() * randomArray.length)];\n }\n\n console.log(password);\n return password;\n\n}", "function generatePassword() {\nvar options = getPasswordOptions();\n\n// variable that stores password while concatenating \nvar result = [];\n\n// variable that stores character types to include in password\nvar characterTypes = [];\n\n// variable that includes one of each type of character to make sure it's used\nvar charactersUsed = [];\n\n\n// Condition statements for array usage\n// ----------------------------------\n\n// adds numeric characters array to characterTypes\n// Use getRandom to add random numeric character to charactersUsed\n\nif (options.hasNumeric) {\ncharacterTypes = (numeric); charactersUsed.push(getRandom(numeric));\n}\n\n// repeated same pattern from above, just updated variable properties\nif (options.hasLowercase) {\n characterTypes = (lowercase); charactersUsed.push(getRandom(lowercase));\n}\n\n// repeated same pattern from above, just updated variable properties\nif (options.hasUppercase) {\n characterTypes = (uppercase); charactersUsed.push(getRandom(uppercase));\n}\n\n// repeated same pattern from above, just updated variable properties\nif (options.hasSymbols) {\n characterTypes = (symbols); charactersUsed.push(getRandom(symbols));\n}\n\n// for loop to select random values from the character types\nfor (var i = 0; i < options.length; i++) {\nvar characterTypes = getRandom\n(characterTypes);\nresult.push(characterTypes);\n}\n\n// for loops to include at least one of the charactersUsed\nfor (var i = 0; i < charactersUsed.length; i++) {\n result[i] = charactersUsed[i];\n }\n\n// return result as a string and send to the function writePassword to write the password\nreturn result.join('');\n}", "function QuickPassword() {\n console.log(\"Running Quick Gen\");\n alert(\"Time to choose a password\");\n var charlength = prompt(\"How many characters do you want the password to be (select number only between 8 and 128)\");\n \n if(charlength >7 && charlength< 129) {\n var charlength = Math.floor(charlength);\n alert(\"Your password will be \" + charlength + \" characters long\");\n }\n else {\n alert(\"You have input incorrectly- try again\");\n return;\n }\n\n //set variables and criteria loop so password won't be accepted until all parameters appear \n var criteria = 0;\n\n for (var ix = 0; criteria < 1; ix++) {\n\n var lettercount = 0;\n var numbercount = 0;\n var symbolcount = 0;\n var lowercasecount =0\n\n\n var passwordcomplete = \"\";\n var letters=[\"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 // (letters[(Math.floor(Math.random()*24))].charAt(0));\n // (passwordcomplete.charAt(0));\n var numbers= [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"];\n var symbols= [\"!\",\"@\",\"#\",\"%\",\"&\",\"(\",\"$\",\")\",\"{\",\"}\",\"?\",\"/\",\">\",\"]\"]\n var capitals= [\"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\n\n // generate lower case temp password\n for (var ia = 0; ia < charlength; ia++) {\n passwordcomplete += letters[(Math.floor(Math.random()*letters.length))].charAt(0);\n // (passwordcomplete);\n }\n alert(\"Initialising new password!\")\n\n \n //insert Capitals randomly \n for (var icap = 0; icap < charlength; icap++) {\n var numberstest = Math.floor((Math.random())*6);\n // (numberstest);\n if (numberstest > 2) {\n var passwordcomplete2 = passwordcomplete.replaceAt(icap, capitals[(Math.floor(Math.random()*capitals.length))]);\n // (passwordcomplete2);\n var passwordcomplete = passwordcomplete2;\n }\n }\n\n //insert numbers randomly \n for (var ib = 0; ib < charlength; ib++) {\n var numberstest = Math.floor((Math.random())*5);\n // (numberstest);\n if (numberstest > 2) {\n var passwordcomplete2 = passwordcomplete.replaceAt(ib, numbers[(Math.floor(Math.random()*numbers.length))]);\n // (passwordcomplete2);\n var passwordcomplete = passwordcomplete2;\n\n }\n \n }\n \n\n //insert symbols randomly \n for (var ic = 0; ic < charlength; ic++) {\n var numberstest2 = Math.floor((Math.random())*5);\n // (numberstest2);\n if (numberstest2 > 2) {\n var passwordcomplete2 = passwordcomplete.replaceAt(ic, symbols[(Math.floor(Math.random()*symbols.length))]);\n // (passwordcomplete2);\n var passwordcomplete = passwordcomplete2;\n\n }\n \n }\n \n //capital letter test\n for (t1=0; t1 < capitals.length; t1++) {\n var charcode = passwordcomplete.indexOf(capitals[t1]); \n if (charcode > -1){\n lettercount++;\n }\n }\n\n //number test\n for (t2=0; t2 < numbers.length; t2++) {\n var charcode = passwordcomplete.indexOf(numbers[t2]);\n // console.log(charcode) \n if (charcode > -1){\n numbercount++;\n }\n }\n\n //symbol test\n for (t3=0; t3 < symbols.length; t3++) {\n var charcode = passwordcomplete.indexOf(symbols[t3]); \n if (charcode > -1){\n symbolcount++;\n }\n }\n\n //lowercase check\n for (t4=0; t4 < letters.length; t4++) {\n var charcode = passwordcomplete.indexOf(letters[t4]); \n if (charcode > -1){\n lowercasecount++;\n }\n }\n\n //If all parameters AND lowercase letters appear in the password, loop will close, else the loop will rerun\n if (symbolcount > 0 && numbercount > 0 && lettercount > 0&& lowercasecount > 0){\n criteria = 1;\n }\n else {\n criteria = 0;\n }\n console.log(\"Temp Password \" + passwordcomplete);\n var loopcount = ix + 1;\n }\n console.log(\"loopcount: \" + loopcount);\n alert(\"Your quick password is \" + passwordcomplete);\n console.log(\"Final password\" + passwordcomplete);\n\n document.getElementById(\"result\").innerHTML = passwordcomplete;\n var xi2 = document.getElementById(\"textdisplay\");\n xi2.style.display = \"block\";\n\n }", "function bruteforce() {\n let crack = [];\n\n for (let j = 0; j <= password.length - 1; j++) {\n for (let i = 0; i <= allowedChars.length - 1; i++) {\n // console.log(i, allowedChars[i]);\n if (allowedChars[i] === password[j]) {\n crack.push(allowedChars[i]);\n console.log(crack.join(''));\n }\n };\n\n // console.log('From J:', j, password[j]);\n };\n}", "function hideIt(password) {\n return ''\n}", "function passwordChecker() {\n password_value = password.value;\n\n if (password_value.length < 8) {\n errorMessage.innerText = \"Password is too short\";\n register.setAttribute(\"disabled\", \"disabled\");\n } else {\n if (password_value.match(/\\d/) === null) {\n errorMessage.innerText = \"Password must contain at least one number.\";\n register.setAttribute(\"disabled\", \"disabled\");\n } else {\n if (password_value.match(/[#%\\-@_&*!]/)) {\n errorMessage.innerText = \"\";\n passwordCompare();\n } else {\n errorMessage.innerText = \"Password must contain at least one special character: #%-@_&*!\";\n register.setAttribute(\"disabled\", \"disabled\");\n }\n\n }\n }\n}", "function generatePassword(characterAmount, IncludeUpperLetters, \n IncludeNumbers, IncludeSymbols) {\n// this variable sets lower case letters as the default \n let CharCodes = LowerLetter_Char_Codes \n// The following three lines make it so that when the boxes are checked it'll append upon those character codes.\n if (IncludeUpperLetters) CharCodes = CharCodes.concat(UpperLetter_Char_Codes)\n if (IncludeNumbers) CharCodes = CharCodes.concat(Numbers_Char_Codes)\n if (IncludeSymbols) CharCodes = CharCodes.concat(Symbols_Char_Codes)\n\n // The following 'for' loop lets 'i' equal 0 when its less than our character amount and adds one each time. this will loop once for each character.\n var passwordCharacters = []\n for(let i = 0; i < characterAmount; i++) {\n // the math function gives me a random number between 0 and the character amount and gives us the character code \n var CharacterCode = CharCodes[Math.floor(Math.random() * \n CharCodes.length)]\n passwordCharacters.push(String.fromCharCode(CharacterCode))\n }\n// this returns the array into a string \n return passwordCharacters.join(\"\")\n}", "function generatePw() {\n var possible = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';\n var newPassword = '';\n \n for(var i=0; i < 16; i++) {\n newPassword += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n \n return newPassword;\n }", "function writePassword() {\n function generatePassword() {\n // promts user to choose pass length and parses into an integer\n var passLength = prompt(\"Password length (min:8 chars, max:128 chars): \");\n var length = parseInt(passLength);\n\n var passChars = prompt(\"What type of characters would you like to use: \\nlowercase, uppercase, numeric, special characters or all\");\n var charset;\n var charset1 = \"abcdefghijklmnopqrstuvwxyz\";\n var charset2 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var charset3 = \"0123456789\";\n var charset4 = \"!@#$%&*\";\n var charset5 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*\"\n\n if (length >= 8 && length <= 128) {\n length;\n // straight up just the character set to choose from\n // The retVal kinda sets it up as both a split and gets returned as a string for the password\n if (passChars === \"lowercase\") {\n charset = charset1;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"uppercase\") {\n charset = charset2;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"numeric\") {\n charset = charset3;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"special characters\" || passChars === \"special\") {\n charset = charset4;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else if (passChars === \"all\") {\n charset = charset5;\n retVal = \"\";\n for (var i = 0, n = charset.length; i < length; ++i) {\n //parses and prints like an array after choosing random whole numbers associated with the charlist\n retVal += charset.charAt(Math.floor(Math.random() * n));\n }\n return retVal;\n }\n else {\n alert(\"Please enter valid response\")\n }\n }\n\n // I honestly couldnt figure out how to do this part of connecting two inputs and thier character sets, lemme know if I was on the right track here\n // Didnt want to code every variation and couldnt figureout how to do more than one variable\n\n // else if (passChars === \"lowercase uppercase\") {\n // charset = charset1 + charset2;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase special characters\" || passChars === \"lowercase special\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"uppercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"uppercase special characters\" || passChars === \"uppercase special\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n // else if (passChars === \"lowercase numeric\") {\n // charset = charset1 + charset3;\n // retVal = \"\";\n // for (var i = 0, n = charset.length; i < length; ++i) {\n // //parses and prints like an array after choosing random whole numbers associated with the charlist\n // retVal += charset.charAt(Math.floor(Math.random() * n));\n // }\n // return retVal;\n // }\n\n // else {\n // alert(\"Please input a vaild length.\")\n // }\n }\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n}", "function passwordSpecifications() {\n var lowerCaseAlphabet = [\"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 upperCaseAlphabet = [\"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 numberChoice = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"];\n var specialCharacters = [\"~\", \"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"-\"];\n var charactersToInclude = [];\n //Asking if user wants to include lowercase characters\n if (confirm(\"Would you like your password to include lowercase characters?\")) {\n charactersToInclude = [...charactersToInclude,...lowerCaseAlphabet]\n } \n //Asking if user wants to include uppercase characters\n if (confirm(\"Would you like your password to include uppercase characters?\")) {\n charactersToInclude = [...charactersToInclude,...upperCaseAlphabet]\n }\n //Asking if user wants to include numbers\n if (confirm(\"Would you like your password to include numbers?\")) {\n charactersToInclude = [...charactersToInclude,...numberChoice]\n } \n //Asking if user wants to include special characters\n if (confirm(\"Would you like your password to include special characters?\")) {\n charactersToInclude = [...charactersToInclude,...specialCharacters]\n } \n howLongPassword();\n return charactersToInclude;\n}", "function generatePassword() {\n //debugger;\n // Prompt for password legnth\n //debugger;\n passLength = window.prompt(\n \"How long would you like your password? (Please Pick a number between 8 and 128)\"\n );\n\n var lengthOf = parseInt(passLength);\n\n if (Number.isNaN(passLength)) {\n alert(\"Password length must be a number\");\n return null;\n }\n\n if (lengthOf < 8 || lengthOf > 128) {\n alert(\"Password must be greater than 8 but less than 128\");\n return null;\n }\n\n var numbers = window.confirm(\n \"Click OK if you want to include numberical values?\"\n );\n\n var upCase = window.confirm(\n \"Click OK if you want to include uppercase letters?\"\n );\n\n var lowCase = window.confirm(\n \"Click OK if you want to include lowercase letters?\"\n );\n\n var special = window.confirm(\n \"Click OK if you want to include special characters?\"\n );\n\n if (\n numbers == false &&\n upCase == false &&\n lowCase == false &&\n special == false\n ) {\n alert(\"You must select at least one criteria.\");\n return null;\n }\n\n var userSelections = {\n numbers: numbers,\n lowCase: lowCase,\n upCase: upCase,\n special: special,\n lengthOf: lengthOf,\n };\n return combinesSelection(userSelections);\n}", "function generatePassword() {\n//Given the choice of 8-128 characters, this data will be the length of their password.\n//We are using promt to get and store their answer.\n//Using parse-int to get a numbered output.\nvar length = parseInt(prompt(\"How many characters do you want the password to be? (8 and up to 128 characters)\"));\n\n//The user will also be given an alert if they choose any number less than 8 or more than 128.\n//And if so, this promt will start at the beginning of the process then would ask the User to reenter their password length.\nif (length < 8 || length > 128){\nreturn alert (\"Invalid password length\")\n}\n//Given the choice of a Yes or No to confirm, the User can decide if they would like to include any uppercase letters.\nvar includeUpper = confirm(\"Do you want your password to have UPPERCASE characters?\");\n\n//Given the choice of a Yes or No to confirm, the User can decide if they would like to include any lowercase letters.\nvar includeLower = confirm(\"Do you want your password to have lowercase characters?\");\n\n//Given the choice of a Yes or No to confirm, the User can decide if they would like to include any numbers.\nvar includeNumber = confirm(\"do you want your password to include numbers?\");\n\n//Given the choice of a Yes or No to confirm, the User can decide if they would like to include any special characters.\nvar includeSpCase = confirm(\"do you want your password to include special characters?\");\n\n//If the user did not choose any characters, it will alert an invalid response.\n//This would then ask the User to restart and make new character selection(s).\nif (\n includeUpper === false && \n includeLower === false &&\n includeSpCase === false &&\n includeNumber === false\n){\n return alert (\"Must select one character type\")\n}\n\n//We then gather all of the data from the result above and put it in this password-pot of results.\nvar potPassword = [];\n\n//This variable is to store and generate the User's final password.\nvar finalPassword = \"\"\n\n\n\n//+++The set of data below are now gathered and retrived from the User's choices above.+++//\n\n\n//With an If statement, we can gather and combine the arrays to/from our \"password-pot\", and also our original arrays of the variables.\n//If the user chose Yes to include uppercase letters, it is then added to our password-pot.\nif(includeUpper === true){\n potPassword = potPassword.concat(upperCase);\n}\n\n//If the user chose Yes to include lowercase letters, it is then added to our password-pot.\n//Because we are using the concat method, we can also write it as =+\nif(includeLower === true){\n potPassword = potPassword.concat(lowerCase);\n}\n\n//If the user chose Yes to include special characters, it is then added to our password-pot.\nif(includeSpCase === true){\n potPassword = potPassword.concat(spCase);\n}\n\n//If the user chose Yes to include lowercase letters, it is then added to our password-pot.\nif(includeNumber === true){\n potPassword = potPassword.concat(numChoice);\n}\n\n//This step is now to mix all of the data from the User into the password-pot.\n console.log(potPassword)\n\n\n\n//Looping is used to generate the variables from the User's choice.\nfor (let i = 0 ; i < length ; i++){\n//To generate the random output, Random is used here based on the password-length specified by the User.\n//The loop above will generate a new password-string everytime it's being run.\n var index = Math.floor(Math.random()*(potPassword.length));\n var temp = potPassword[index];\n finalPassword += temp;\n}\n//Generating final password\nreturn finalPassword;\n}", "function getNukeCodes() {\n return \"someSuperSecretPassword\";\n}", "function passwordChanged(input, output) {\n\t\tif( input.value.length < 8 ) {\n\t\t\t// Master-password size smaller than minimum allowed size\n\t\t\t// Provide a masked partial confirm-code, to acknowledge the user input\n\t\t\tvar maskedCode='';\n\t\t\tswitch(Math.floor(input.value.length*4/8)) {\n\t\t\t\tcase 1: maskedCode='#'; break;\n\t\t\t\tcase 2: maskedCode='##'; break;\n\t\t\t\tcase 3: maskedCode='###'; break;\n\t\t\t}\n\t\t\toutput.value=maskedCode;\n\t\t} else {\n\t\t\toutput.value = confirmCode(input.value);\n\t\t}\n\t\tvaluesChanged();\n\t}", "function pushPassword() {\n // connect character randomly selected with the corresponding array of characters &\n // determine if character randomly chosen had been confirmed by user\n if (typeChar == 0 && charSelection[typeChar] == true) {\n char(specialChar);\n }\n else if (typeChar == 1 && charSelection[typeChar] == true) {\n char(numericChar);\n }\n else if (typeChar == 2 && charSelection[typeChar] == true) {\n char(lowecaseChar);\n }\n else if (typeChar == 3 && charSelection[typeChar] == true) {\n char(uppercaseChar);\n }\n // every time the type of character randomly selected had not been confirmed by the user,\n // add 1 to the falseChar count\n else if (charSelection[typeChar] == false) {\n falseChar++;\n }\n }", "function writePassword() { \n var charactersToInclude = passwordSpecifications();\n var finalPassword = [];\n for (let i = 0; i < passwordLength; i++) {\n var arrayLength = charactersToInclude.length;\n var randomNumber = Math.floor(Math.random() * arrayLength);\n finalPassword.push(charactersToInclude[randomNumber]);\n }\n passwordTextArea.innerHTML = finalPassword.join(\"\");\n}", "function password(length,special)\n{\n\tvar iteration = 0;\n \tvar password = \"\";\n \tvar randomNumber;\n \tif(special == undefined){\n \tvar special = false;\n \t}\n \twhile(iteration < length){\n \trandomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;\n \tif(!special){\n \t\tif ((randomNumber >=33) && (randomNumber <=47)) { continue; }\n \t\tif ((randomNumber >=58) && (randomNumber <=64)) { continue; }\n \t\tif ((randomNumber >=91) && (randomNumber <=96)) { continue; }\n \t\tif ((randomNumber >=123) && (randomNumber <=126)) { continue; }\n \t}\n \titeration++;\n \tpassword += String.fromCharCode(randomNumber);\n \t}\n \treturn password;\n}", "function generatePassword(){\n\n // Gather Selections from user\n \n // Password length:\n selections[0]=window.prompt(\"How many characters for the password? \\n (Note: minimum of 8 and maximum of 128)\");\n if (selections[0] < 8){\n window.alert(\"Password length must be at least 8 characters\");\n generatePassword();\n } else if (selections[0] > 128){\n window.alert(\"Password length must be at less than 128 characters\");\n generatePassword();};\n\n // Special characters:\n Special = window.confirm(\"Click OK to confirm including special characters\");\n if (Special){selections[1] = \"Y\";}\n else {selections[1] = \"N\"};\n\n // Numeric characters:\n Numeric = window.confirm(\"Click OK to confirm including numeric characters\");\n if (Numeric){selections[2] = \"Y\";}\n else {selections[2] = \"N\"};\n \n // Lower case letters:\n Lower = window.confirm(\"Click OK to confirm including lower case letters\");\n if (Special){selections[3] = \"Y\"}\n else {selections[3] = \"N\"};\n\n // Upper case letters:\n Upper = window.confirm(\"Click OK to confirm including upper case letters\");\n if (Special){selections[4] = \"Y\"}\n else {selections[4] = \"N\"};\n\n\n //Generate Password\n for (i=0;i<selections[0];i=i){\n \n if (selections[1]=\"Y\"){\n var choices = \"@%+\\/'!#$^?:,(){}[]`-_.\";\n spcl = choices[Math.floor(Math.random() * choices.length)];\n password=password + spcl;\n i++;} \n \n if (selections[2]=\"Y\"){\n var choices = \"0123456789\";\n num = choices[Math.floor(Math.random() * choices.length)];\n password=password + num;\n i++}\n\n if (selections[3]=\"Y\"){\n var choices = \"abcdefghijklmnopqrstuvwxyz\";\n low = choices[Math.floor(Math.random() * choices.length)];\n password=password + low;\n i++}\n\n if (selections[4]=\"Y\"){\n var choices = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n UP = choices[Math.floor(Math.random() * choices.length)];\n password=password + UP;\n i++}\n }\n\n return password;\n}", "function generatePassword(){\n // Checking the password length who must be betwen and also including 8 and 128\n var passwordLength = 0 \n while (passwordLength<8 || passwordLength>128){\n passwordLength= prompt(\"Choose a length of at least 8 character and no more thant 128\");\n \n }\n //Confirming what type of characters users want to include in his password \nvar confirmLowerCase = confirm(\"Do you want lowercase in your password\");\nvar confirmUpperCase = confirm(\"Do you want uppperCase in your password\");\nvar confirmNumber = confirm(\"Do you want any number in your character\");\nvar confirmSpecialCharacter = confirm(\"Do you want any specialcharacter in your password?\");\n// Controling they choice by making sure that they choose at least one character\n while(!confirmLowerCase && !confirmUpperCase && !confirmNumber && !confirmSpecialCharacter){\n alert(\n \"You must choose one of those character\"\n )\n generatePassword();\n }\n//Building the array of each type of characters\nvar lowerCase = [\"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\"];\nvar upperCase = [\"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\"];\nvar number = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\",\"9\"];\nvar specialCharacter = ['@', '%', '+', '\\\\', '/', \"'\", '!', '#', '$', '^', '?', ':', ', ', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.'];\nvar passwordChoices=[];\n\n//concatenating together whatever characters they confirm to chose from\nif (confirmLowerCase){\n passwordChoices=passwordChoices.concat(lowerCase);\n}\n\nif (confirmUpperCase){\n passwordChoices=passwordChoices.concat(upperCase);\n}\nif (confirmNumber){\n passwordChoices=passwordChoices.concat(number);\n}\nif (confirmSpecialCharacter){ \n passwordChoices=passwordChoices.concat(specialCharacter)\n}\nconsole.log(passwordChoices);\n\nvar randomPassword= \"\";\n//loop through the number of character they picked which constitute the password length;\nfor ( var i= 0; i<passwordLength; i++){\n // randomly picking a number of index out of passwordChoices\n var numberPicked = Math.floor(Math.random()*passwordChoices.length);\n //adding each character to randomPassword to build up the full password\n randomPassword += passwordChoices[numberPicked];\n \n console.log(randomPassword);\n}\nreturn randomPassword;\n}", "function _getPasswordLevel(password, email) {\n var commonPasswordArray = [\"111111\", \"11111111\", \"112233\", \"121212\", \"123123\", \"123456\", \"1234567\", \"12345678\", \"131313\", \"232323\", \"654321\", \"666666\", \"696969\",\n \"777777\", \"7777777\", \"8675309\", \"987654\", \"aaaaaa\", \"abc123\", \"abcdef\", \"abgrtyu\", \"access\", \"access14\", \"action\", \"albert\", \"alexis\", \"amanda\", \"amateur\", \"andrea\", \"andrew\", \"angela\", \"angels\",\n \"animal\", \"anthony\", \"apollo\", \"apples\", \"arsenal\", \"arthur\", \"asdfgh\", \"ashley\", \"august\", \"austin\", \"badboy\", \"bailey\", \"banana\", \"barney\", \"baseball\", \"batman\", \"beaver\", \"beavis\", \"bigdaddy\", \"bigdog\", \"birdie\",\n \"bitches\", \"biteme\", \"blazer\", \"blonde\", \"blondes\", \"bond007\", \"bonnie\", \"booboo\", \"booger\", \"boomer\", \"boston\", \"brandon\", \"brandy\", \"braves\", \"brazil\", \"bronco\", \"broncos\", \"bulldog\", \"buster\", \"butter\", \"butthead\",\n \"calvin\", \"camaro\", \"cameron\", \"canada\", \"captain\", \"carlos\", \"carter\", \"casper\", \"charles\", \"charlie\", \"cheese\", \"chelsea\", \"chester\", \"chicago\", \"chicken\", \"cocacola\", \"coffee\", \"college\", \"compaq\", \"computer\",\n \"cookie\", \"cooper\", \"corvette\", \"cowboy\", \"cowboys\", \"crystal\", \"dakota\", \"dallas\", \"daniel\", \"danielle\", \"debbie\", \"dennis\", \"diablo\", \"diamond\", \"doctor\", \"doggie\", \"dolphin\", \"dolphins\", \"donald\", \"dragon\", \"dreams\",\n \"driver\", \"eagle1\", \"eagles\", \"edward\", \"einstein\", \"erotic\", \"extreme\", \"falcon\", \"fender\", \"ferrari\", \"firebird\", \"fishing\", \"florida\", \"flower\", \"flyers\", \"football\", \"forever\", \"freddy\", \"freedom\", \"gandalf\",\n \"gateway\", \"gators\", \"gemini\", \"george\", \"giants\", \"ginger\", \"golden\", \"golfer\", \"gordon\", \"gregory\", \"guitar\", \"gunner\", \"hammer\", \"hannah\", \"hardcore\", \"harley\", \"heather\", \"helpme\", \"hockey\", \"hooters\", \"horney\",\n \"hotdog\", \"hunter\", \"hunting\", \"iceman\", \"iloveyou\", \"internet\", \"iwantu\", \"jackie\", \"jackson\", \"jaguar\", \"jasmine\", \"jasper\", \"jennifer\", \"jeremy\", \"jessica\", \"johnny\", \"johnson\", \"jordan\", \"joseph\", \"joshua\", \"junior\",\n \"justin\", \"killer\", \"knight\", \"ladies\", \"lakers\", \"lauren\", \"leather\", \"legend\", \"letmein\", \"little\", \"london\", \"lovers\", \"maddog\", \"madison\", \"maggie\", \"magnum\", \"marine\", \"marlboro\", \"martin\", \"marvin\", \"master\", \"matrix\",\n \"matthew\", \"maverick\", \"maxwell\", \"melissa\", \"member\", \"mercedes\", \"merlin\", \"michael\", \"michelle\", \"mickey\", \"midnight\", \"miller\", \"mistress\", \"monica\", \"monkey\", \"monster\", \"morgan\", \"mother\", \"mountain\", \"muffin\",\n \"murphy\", \"mustang\", \"naked\", \"nascar\", \"nathan\", \"naughty\", \"ncc1701\", \"newyork\", \"nicholas\", \"nicole\", \"nipple\", \"nipples\", \"oliver\", \"orange\", \"packers\", \"panther\", \"panties\", \"parker\", \"password\", \"password1\",\n \"password12\", \"password123\", \"patrick\", \"peaches\", \"peanut\", \"pepper\", \"phantom\", \"phoenix\", \"player\", \"please\", \"pookie\", \"porsche\", \"prince\", \"princess\", \"private\", \"purple\", \"pussies\", \"qazwsx\", \"qwerty\",\n \"qwertyui\", \"rabbit\", \"rachel\", \"racing\", \"raiders\", \"rainbow\", \"ranger\", \"rangers\", \"rebecca\", \"redskins\", \"redsox\", \"redwings\", \"richard\", \"robert\", \"rocket\", \"rosebud\", \"runner\", \"rush2112\", \"russia\", \"samantha\",\n \"sammy\", \"samson\", \"sandra\", \"saturn\", \"scooby\", \"scooter\", \"scorpio\", \"scorpion\", \"secret\", \"sexsex\", \"shadow\", \"shannon\", \"shaved\", \"sierra\", \"silver\", \"skippy\", \"slayer\", \"smokey\", \"snoopy\", \"soccer\", \"sophie\", \"spanky\",\n \"sparky\", \"spider\", \"squirt\", \"srinivas\", \"startrek\", \"starwars\", \"steelers\", \"steven\", \"sticky\", \"stupid\", \"success\", \"summer\", \"sunshine\", \"superman\", \"surfer\", \"swimming\", \"sydney\", \"taylor\", \"tennis\", \"teresa\",\n \"tester\", \"testing\", \"theman\", \"thomas\", \"thunder\", \"thx1138\", \"tiffany\", \"tigers\", \"tigger\", \"tomcat\", \"topgun\", \"toyota\", \"travis\", \"trouble\", \"trustno1\", \"tucker\", \"turtle\", \"twitter\", \"united\", \"vagina\", \"victor\",\n \"victoria\", \"viking\", \"voodoo\", \"voyager\", \"walter\", \"warrior\", \"welcome\", \"whatever\", \"william\", \"willie\", \"wilson\", \"winner\", \"winston\", \"winter\", \"wizard\", \"xavier\", \"xxxxxx\", \"xxxxxxxx\", \"yamaha\", \"yankee\", \"yankees\",\n \"yellow\", \"zxcvbn\", \"zxcvbnm\", \"zzzzzz\", \"football\",\"77777777\",\"11111111\",\"12345678\",\"123123123\",\"123456789\",\"987654321\",\"1234567890\",\"1q2w3e4r\",\"1qaz2wsx\",\"aaaaaaaa\",\"abcd1234\",\"alexander\",\"asdfasdf\",\"asdfghjkl\",\"baseball\",\"chocolate\",\"computer\",\"66666666\",\"homedepot\",\"homedepot123\",\"iloveyou\",\"internet\",\"jennifer\",\"liverpool\",\"michelle\",\"password\",\"password1\",\"princess\",\"qwertyuiop\",\"sunshine\",\"superman\",\"testpassword\",\"trustno1\",\"welcome1\",\"whatever\",\"abcdefghi\",\"abcdefgh\"];\n \n var commonPasswordArrayWCS = [\"12345678\", \"123123123\", \"123456789\", \"987654321\", \"1234567890\", \"1q2w3e4r\", \"1qaz2wsx\", \"abcd1234\", \"alexander\", \"asdfasdf\", \"asdfghjkl\", \"baseball\", \"chocolate\", \"computer\", \"football\", \"homedepot\", \"homedepot123\", \"iloveyou\", \"internet\", \"jennifer\", \"liverpool\", \"michelle\", \"password\", \"password1\", \"princess\", \"qwertyuiop\", \"sunshine\", \"superman\", \"testpassword\", \"trustno1\", \"welcome1\", \"whatever\", \"abcdefghi\", \"abcdefgh\", \"12345678\"];\n\n\n email = email !== undefined ? email : \"\";\n\n var regexPat = /(.)\\1{4,}/;\n if(authHelper.isIAMThrottled()) {\n\t if ((password.length < 8) || ($.inArray(password.toLowerCase(), commonPasswordArray) > -1) ||\n\t ((password.toLowerCase().split(password[0].toLowerCase()).length - 1) == password.length) || password.toLowerCase() === $.trim(email.toLowerCase()) || regexPat.test(password)) {\n\t return 0;\n\t }\n } else {\n \tif ((password.length < 8) || ($.inArray(password.toLowerCase(), commonPasswordArrayWCS) > -1) ||\n ((password.toLowerCase().split(password[0].toLowerCase()).length - 1) == password.length) || password.toLowerCase() === $.trim(email.toLowerCase())) {\n return 0;\n }\n }\n \n \n var score = 0;\n if (/[a-z]/.test(password)) { //Check lowercase\n score++;\n }\n if (/[A-Z]/.test(password)) { //Check uppercase\n score++;\n }\n if (/\\d/.test(password)) { //Check Numbers\n score++;\n }\n if (/^[a-zA-Z0-9- ]*$/.test(password) == false) { //Check Special Characters\n score++;\n }\n if ((score > 1 && (password.length > 12)) || (score > 2 && (password.length > 8))) {\n return 2; //Strong Password\n }\n return 1; // Good Password\n }", "function validate_blacklist_whitelist() {\n var form = get_form_data('#blacklist_whitelist_form');\n var command = $('#is_blacklisted').prop('checked')?\"blacklist\":\"whitelist\";\n if (check_field_empty(form.nick, 'nick'))\n return false;\n\n var dataObj = {\n \"content\" : [{\n \"session_id\" : get_cookie()\n }, {\n \"nick\" : form.nick\n }]\n };\n call_server(command, dataObj);\n}", "function generatePassword(promptPasswordLength, startPassword, charUsed, charTypeCount, password) {\n let remainingPassword = '';\n let finalPassword = '';\n \n let adjCharUsed = charUsed.split(',');\n \n // loop through the char list to pick the remaining characters randomly\n for (var i = 0; i < promptPasswordLength - charTypeCount; i++) {\n remainingPassword += adjCharUsed[Math.floor(Math.random() * adjCharUsed.length)];\n }\n \n // combine the password components\n finalPassword = startPassword + remainingPassword;\n \n // append the password to the textarea\n document.getElementById('password').append(finalPassword);\n}", "function two(){\n let x=first();\n if (!x) {\n return;\n }\n// help to extract the password\n let password1=[];\n console.log(password1)\n if (x.lowerCase){\n for (let i = 0; i < onlylowerCase.length; i++) {\n password1.push(onlylowerCase[i]);\n }\n }\n if (x.upperCase){\n for (let i = 0; i <onlyupperCase.length; i++) {\n password1.push(onlyupperCase[i]);\n }\n }\n if (x.numeric){\n for (let i = 0; i <onlynumbers.length; i++) {\n password1.push(onlynumbers[i]);\n }\n }\n if (x.specialcharacters){\n for (let i = 0; i < onlysymbols.length; i++) {\n password1.push(onlysymbols[i]);\n }\n}\n let lastpassword=[];\n for (let i = 0; i < x.length; i++) {\n let pickrandomly =Math.floor(Math.random()*Math.floor(password1.length));\n lastpassword.push(password1[pickrandomly]);\n }\n console.log(lastpassword)\n let finalpassword=lastpassword.join(\"\");\n console.log(finalpassword);\n document.getElementById(\"password\").value = finalpassword;\n }", "function generatePassword(charLen, upperCase, lowerCase, number, specialC)\n{\n let charCodes = LOWERCASE_CHAR_CODES\n\n if (upperCase) charCodes = charCodes.concat\n (UPPERCASE_CHAR_CODES)\n\n if (lowerCase) charCodes = charCodes.concat\n (LOWERCASE_CHAR_CODES)\n\n if(specialC) charCodes = charCodes.concat\n (SPECIAL_CHAR_CODES)\n\n if(number) charCodes = charCodes.concat\n (NUMBER_CHAR_CODES)\n\n // else window.alert('You did not make a selection! Please make a selection:');\n// I couldn't get the above line of code to work properly, would apprectiate feedback, Thank you\n\n const passwordCharacters = []\n for (let i = 0; i < charLen; i++)\n {\n const characterCode = charCodes[Math.floor(Math.random()* charCodes.length)]\n passwordCharacters.push(String.fromCharCode(characterCode))\n }\n\n return passwordCharacters.join('')\n\n}", "function secretPassword() {\n var password = 'xh38sk';\n return {\n \t//Code here\n }\n }", "function getPasswordCriteria () {\n\n //Add lower case letters to the passwordChar string\n if (isLowercase.checked) {\n var lowerChars = \"abcdefghijklmopqrstuvwxyz\";\n } else {\n //Remove lower case letters to the passwordChar string\n lowerChars = \"\";\n }\n \n //Add upper case letters to the passwordChar string\n if (isUppercase.checked) {\n var upperChars = \"ABCDEFGHIJKLMOPQRSTUVWXYZ\";\n } else {\n //Removes upper case letters to the passwordChar string\n upperChars = \"\";\n }\n\n //Add special characters to the passwordChar string\n if (isSpecial.checked) {\n var specialChars = \"!@#$%^&*()_+<>?\";\n } else {\n //Removes special characters to the passwordChar string\n specialChars = \"\";\n }\n\n //Add numbers to the passwordChar string\n if (isNumeric.checked) {\n var numericChars = \"1234567890\";\n } else {\n //Removes numbers to the passwordChar string\n numericChars = \"\";\n }\n //Generate the passwordCharlist and return it to the generatePassword function\n var passwordCharList = lowerChars + upperChars + specialChars + numericChars;\n\n //If users doesn't select any option, we have a default/fallback list of chars to choose from\n if (passwordCharList == \"\") {\n passwordCharList = \"abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ!@#$%^&*()_+<>?1234567890\";\n }\n \n return passwordCharList\n}", "function beginPassword(event) {\n \n // prompt for length of password\n var promptPasswordLength = prompt('How many characters do you want in your password?', 'Please enter a number between 8 and 128.');\n \n // if the pasword length is acceptable, then prompt for characters to be used\n if (promptPasswordLength >= 8 && promptPasswordLength <= 128) {\n \n // prompt to use lowercase characters\n var promptLowercase = prompt(\"Would you like to include lowercase letters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected lowercase, then add lowercase to the char list (charUsed)\n if(promptLowercase === 'yes') {\n charUsed += lowercase;\n charTypeCount += 1;\n \n for(var i=0; i < 1; i++ )\n { \n // pick a lowercase character by random index\n startPassword = startPassword + lowercase[(Math.floor(Math.random() * lowercase.length))];\n }\n }\n \n // prompt to use uppercase characters \n var promptUppercase = prompt(\"Would you like to use UPPERCASE letters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected uppercase, then add uppercase to the char list (charUsed)\n if(promptUppercase === 'yes') {\n charUsed += uppercase;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick an uppercase character by random index\n startPassword = startPassword + uppercase[(Math.floor(Math.random() * uppercase.length))];\n }\n }\n \n // prompt to use number characters\n var promptNumber = prompt(\"Would you like to use numbers in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected number, then add number to the char list (charUsed)\n if(promptNumber === 'yes') {\n charUsed += number;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick a number character by random index\n startPassword = startPassword + number[(Math.floor(Math.random() * number.length))];\n }\n }\n \n \n // prompt to use special characters\n var promptSpecialChar = prompt(\"Would you like to use special characters in the password? Enter 'yes' or 'no' to choose.\");\n \n // if the user selected special character, then add special char to the char list (charUsed)\n if(promptSpecialChar === 'yes') {\n charUsed += specialChar;\n charTypeCount += 1;\n\n for(var i=0; i < 1; i++ )\n { \n // pick a special character by random index\n startPassword = startPassword + specialChar[(Math.floor(Math.random() * specialChar.length))];\n }\n } \n } else {\n window.alert('Total characters must be between 8 and 128. Please try again!');\n return;\n }\n \n if (promptUppercase !== 'yes' && promptLowercase !== 'yes' && promptNumber !== 'yes' && promptSpecialChar !== 'yes') {\n window.alert('At least one character type must be chosen. Please try again!');\n \n return;\n \n } else {\n \n // inititate generatePassword() and pass the needed information\n generatePassword(promptPasswordLength, startPassword, charUsed, charTypeCount, password);\n }\n \n}", "function writePassword() {\n var len = window.prompt(\"Enter length of password between 8 and 128 characters: \")\n /* if (len === null) {\n return;\n } */\n while (len <= 7 || len >= 129){\n var len = window.prompt(\"Invalid Entry. Enter length of password between 8 and 128 characters: \")\n }\n var upper = window.prompt(\"Include uppercase letters? (Y/N): \").toLowerCase()\n while (upper != \"y\" && upper!= \"n\" ){\n var upper = window.prompt(\"Invalid Entry. Include uppercase letters? (Y/N): \")\n } \n \n var lower = window.prompt(\"Include lowercase letters? (Y/N): \").toLowerCase()\n while (lower != \"y\" && lower!= \"n\"){\n var lower = window.prompt(\"Invalid Entry. Include lowercase letters? (Y/N): \")\n }\n\n var num = window.prompt(\"Include numbers? (Y/N): \").toLowerCase()\n while (num != \"y\" && num != \"n\"){\n var num = window.prompt(\"Invalid Entry. numbers? (Y/N): \") \n } \n\n var special = window.prompt(\"Include special characters? (Y/N): \").toLowerCase()\n while (special != \"y\" && special != \"n\"){\n var special = window.prompt(\"Invalid Entry. special characters? (Y/N): \") \n } \n\n upper = (upper == 'y') ? true : false;\n lower = (lower =='y') ? true : false;\n num = (num == 'y') ? true : false;\n special = (special == 'y') ? true : false;\n\n var password = generatePassword(len, upper, lower, num, special);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function passwordStrength() { \n _v.form.password.addEventListener('keyup', (e) => {\n let isValid = {\n low: false,\n high: false\n },\n pwd = e.target.value;\n resetStrength();\n if(pwd.length >= 8) {\n _v.pwdStrengthColor[0].classList.add('active');\n if (regexCount(/[&?!%]/g, pwd) > 0) {\n _v.pwdStrengthColor[1].classList.add('active');\n } \n isValid.low = true;\n } \n if (pwd.length >= 10 && regexCount(/[&?!%]/g, pwd) > 1 && regexCount(/[A-Z]/g, pwd) > 0) {\n _v.pwdStrengthColor.forEach((item) => {\n item.classList.add('active');\n });\n isValid.high = true; \n }\n _v.isValidPassword = (isValid.low || isValid.high) ? true : false;\n });\n}", "function generatePassword() {\n var passParams = passwordParameters();\n var passString = \"\";\n var pChar =\"\";\n\n for (var i = 0; i < passParams[0]; i++) { \n if ( passParams.length > 2) { \n var typeIndex = (Math.floor((Math.random() * (passParams.length - 1))) + 1); \n } else {\n var typeIndex = 1;\n }\n \n if (passParams[typeIndex] == \"upper\") {\n pAlpha = genAlpha();\n pChar = pAlpha.toUpperCase();\n } else {\n if (passParams[typeIndex] == \"lower\") {\n pChar = genAlpha();\n } else {\n if (passParams[typeIndex] == \"numeric\") {\n pChar = genNumeric();\n } else {\n pChar = genSpecial();\n }\n }\n }\n passString += pChar;\n }\n return (passString); \n}", "function handleCleanUpBlacklist() {\n\tdb_readGeneric(function (localAccount) {\n\t\tsync_cleanBlacklist(function () { console.log(\"Blacklist should be clean now\", localAccount['blacklist']) }, localAccount);\n\t}, 1, \"account\");\n}", "function generatePassword(){\n pwLength();\n uppercase();\n determineNumbers();\n determineSpecial();\n\n var characters = lowerCs;\n var password = \"\";\n if (!uppercaseCheck && !numberCheck && !splCheck) {\n return;\n\n } \n if (uppercaseCheck) {\n characters += upperCs \n;\n\n } \n if (numberCheck) {\n characters += numbers;\n;\n\n } if (uppercaseCheck) {\n characters += upperCs;\n;\n }\n\n \n if (splCheck) {\n characters += splChars;\n\n } \n // for loop / code block run and will pull random character from string stored in variables using the charAt method, them randomize it with the math.random function\n for (var i = 0; i < passwordLgth; i++) {\n password += characters.charAt(Math.floor(Math.random() * characters.length));\n }\n return password;\n\n\n\n\n}", "function genPass(charAmount, upperCase, incNum, incSymbol){\n // this defines our default character group. in this code, the password will always include lowercase.\n let carCodes = lowerChar\n if (upperCase) carCodes = carCodes.concat(upperChar)\n if (incNum) carCodes = carCodes.concat(numberChar)\n if (incSymbol) carCodes = carCodes.concat(symbolChar)\n\n const passChar = []\n for (let i=0; i < charAmount ; i++){\n const character = carCodes[Math.floor(Math.random() * carCodes.length)]\n passChar.push(String.fromCharCode(character))\n }\n return passChar.join('')\n}", "function checkPassword() {\n //get what the user input as their password\n //in .html, the input box has id=pw\n var input = document.getElementById(\"pw\").value;\n\n //loop through alllllllll the words in the word list\n //earlier, wordsList was set to contain a list of English words\n for (var index = 0; index < wordsList.length; index++) {\n\n //warn them if their password matches a word from the list\n if (wordsList[index] == input) {\n alert(\"that is a weak password! it's an English word.\");\n return; //stop this function as soon as I find this match\n }\n\n //warn them if that word from the list, when I \"leetify\" it,\n //matches their input\n //EX: wordsList[index] is 'hello', leetify(wordsList[index]) is 'h3ll0'\n if (leetify(wordsList[index]) == input) {\n alert(input + \" is a weak password! it's too close to \" + wordsList[index]);\n return; //stop this function as soon as I find a leetified match\n }\n }\n\n //after the for loop finishes, if it wasn't an English word,\n //tell them their password is safe\n alert(\"Your password is just fine :D \");\n}", "function validatePassword(wachtwoord1, herwachtwoord){\r\n if(wachtwoord1.length < 8 && herwachtwoord < 8){\r\n errors.push(\"Het wachtwoord moet minstens 8 karakters bevatten.\");\r\n }\r\n else{\r\n if (wachtwoord1 != herwachtwoord){\r\n errors.push(\"Wachtwoord moet gelijk zijn!\");\r\n }\r\n }\r\n }", "function generatePassword() {\n alert(`INSTRUCTIONS: \\n1. You must indicate an amount of characters between 8 and 128 for your password. \\n2. You must select at least one of the following criteria for your password: \\n - Uppercase \\n - Lowercase \\n - Special Characters \\n - Numbers`);\n\n\n // First Criteria - Character Amount \n var charAmount = prompt(`How many characters would you like to have for your password? Please enter a numerical value between 8 and 128.`);\n \n \n // Parse integer so user's string-based entry becomes a number that can be used later in loop iterations\n charAmount = parseInt(charAmount);\n console.log(charAmount);\n \n\n // If else statement ensuring user input is valid\n if ((isNaN(charAmount) === false) || (charAmount >= 8) || (charAmount <= 128)) {\n \n \n // Second Criteria - Numbers\n var numbers = confirm(\"Would you like to include numbers in your password?\");\n \n \n // Add numbers array to password array if user confirms to have numbers in the password\n if (numbers === true) {\n passwordArray = passwordArray.concat(numbersArray);\n console.log(passwordArray);\n }\n else {\n numbers === false;\n }\n \n\n // Third Criteria - Special Characters\n var specialChar = confirm(\"Would you like to have special characters in your password?\");\n\n\n // Add special characters array to password array if user confirms to have numbers in the password\n if (specialChar === true) {\n passwordArray = passwordArray.concat(specialCharArray);\n console.log(passwordArray);\n }\n else {\n specialChar === false;\n }\n \n\n // Fourth Criteria - Uppercase Letters\n var uppercase = confirm(\"Would you like to have uppercase letters in your password?\");\n \n \n // Add uppercase array to password array if user confirms to have numbers in the password\n if (uppercase === true) {\n passwordArray = passwordArray.concat(uppercaseArray);\n console.log(passwordArray);\n }\n else {\n uppercase=== false;\n }\n \n\n // Fifth Criteria - Lowercase Letters\n var lowercase = confirm(\"Would you like to havelowercase letters in your password?\");\n\n\n // Add lowercase array to password array if user confirms to have numbers in the password\n if (lowercase === true) {\n passwordArray = passwordArray.concat(lowercaseArray);\n console.log(passwordArray);\n }\n else {\n lowercase === false;\n }\n \n\n // Console log the password array based on indicated criteria\n console.log(passwordArray);\n \n\n // If statement to check whether user confirmed at least one of either uppercase, lowercase, special characters, or numbers to include in the password. \n if (numbers === false && specialChar === false && uppercase === false && lowercase === false) {\n alert(`You did not pick at least one of the criteria (uppercase, lowercase, special characters, or numbers) to be included in your password. Please try again.`);\n return randomPassword;\n }\n \n\n // Else statement to proceed if user confirmed at least one of either uppercase, lowercase, special characters, or numbers to include in the password. \n else {\n var randomPassword = \"\";\n for (var i = 0; i < charAmount; i++) {\n var password = Math.floor(Math.random() * passwordArray.length);\n randomPassword += passwordArray[password];\n }\n \n\n // Display generated password \n console.log(randomPassword);\n return randomPassword;\n }\n }\n\n\n // If user did not indicate a number between 8 and 128 for characters amount\n else {\n alert(`You did not enter a numerical value between 8 and 128. Please try again.`);\n }\n }", "function resetPass() {\n howMany = (0);\n choices = [];\n newPass = (\"\");\n password = (\"\");\n}", "function randomizePassword() {\n for(var i = 0; i < charSelect; i++) {\n var randomIdx = Math.floor(Math.random() * passwordContainer.length);\n var randomChar = passwordContainer[randomIdx];\n finalPassword = randomChar + finalPassword;\n } \n }", "function getTeamPassword() {\n var password = \"\";\n for (var i = 0; i < 5; i++) {\n var random = Math.floor(Math.random() * 74 + 48)\n while (random > 57 && random < 65 || random > 90 && random < 97){\n var random = Math.floor(Math.random() * 75 + 47)\n }\n password += String.fromCharCode(random)\n }\n\n return password\n}", "function specPass(){\n var password = \"\";\n var i;\n for (i = 0; i <= len - 1; i++) {\n password += letSpec[getRandomInt(59)];\n }\n return password;\n }", "function generatePassword() {\n var passwordLength = parseInt(window.prompt ('How many characters? Enter between 8-128'));\n\n if (passwordLength < 8 || passwordLength > 128) {\n alert('Please select a number between 8-128');\n return \"\"\n }\n\n else if (passwordLength >= 8 && passwordLength <= 128) {\n var numeric = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];\n var lowercase = ['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 uppercase = ['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 specialCharacters = ['@', '&', '+', '/', '!', '#', '$', '^', '?', ';', ':', ',', '(', ')', '{', '}', '[', ']', '~', '-', '_'];\n var possibleChars = [];\n\n var numericIncluded = window.confirm (\"Do you want to include numbers?\");\n switch (numericIncluded) {\n case true:\n possibleChars = numeric;\n break;\n }\n var lowercaseIncluded = window.confirm(\"Do you want to include lowercase?\");\n switch (lowercaseIncluded) {\n case true:\n possibleChars = [].concat(possibleChars, lowercase);\n break;\n }\n var uppercaseIncluded = window.confirm(\"Do you want to include uppercase?\");\n switch (uppercaseIncluded) {\n case true:\n possibleChars = [].concat (possibleChars, uppercase);\n break;\n }\n var specialcharIncluded = window.confirm(\"Do you want to include special characters?\");\n switch (specialcharIncluded) {\n case true:\n possibleChars = [].concat (possibleChars, specialCharacters);\n break;\n }\n\n var newPassword = ''\n for (var i = 0; i < passwordLength; i++) {\n var randomPassword = possibleChars[Math.floor(Math.random() * possibleChars.length)];\n newPassword += randomPassword\n }\n\n return newPassword\n }\n\n else if (isNaN) {\n return \"\"\n }\n}", "function writePassword() {\n //var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n //string variables to hold each criteria type\n var userLowerCase = 'abcdefghijklmnopqrstuvwxyz';\n var userUpperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXY'\n var userNumeric = '0123456789';\n var userSpecial = '!@#$%&*';\n\n //string variables for user input\n var l = userLowerCase;\n var s = userSpecial;\n var n = userNumeric;\n var u = userUpperCase;\n\n //string variable to hold initial password criteria\n var pw = \"\";\n\n //array to hold randomly generated characters the user needs\n var criteriaArray = [];\n\n //array to hold generated password\n var password1 = [];\n\n //initial prompt to ask the length of the password\n var pwLength = prompt(\"How many characters long does your password need to be? Please choose between 8 and 128 characters.\")\n\n //conditional statement if input is out of range\n while (pwLength < 8 || pwLength > 128) {\n\n\n alert(\"Your password must be between 8 and 128 characters\");\n var pwLength = prompt(\"How many characters long does your password need to be? Please choose between 8 and 128 characters.\")\n\n }\n\n //series of prompts asking the user what character types they need\n var usChar = prompt(\"Please enter s if you need a special character for your password, press enter to continue.\");\n\n if (usChar === \"s\") {\n\n criteriaArray.push(s.charAt([Math.floor(Math.random() * s.length)]));\n pw += s;\n console.log(criteriaArray);\n }\n var usChar = prompt(\"Please enter l if you need a lowercase characters for your password, press enter to continue.\");\n if (usChar === \"l\") {\n\n criteriaArray.push(l.charAt([Math.floor(Math.random() * l.length)]));\n pw += l;\n console.log(criteriaArray);\n }\n var usChar = prompt(\"Please enter u if you need a uppercase characters for your password, press enter to continue.\");\n if (usChar === \"u\") {\n\n criteriaArray.push(u.charAt([Math.floor(Math.random() * u.length)]));\n pw += u;\n console.log(criteriaArray);\n }\n var usChar = prompt(\"Please enter n if you need a number for your password, press enter to continue.\");\n if (usChar === \"n\") {\n\n criteriaArray.push(n.charAt([Math.floor(Math.random() * n.length)]));\n pw += n;\n console.log(criteriaArray);\n }\n\n //for loop that generates a password into the array password1\n for (i = 0; i < pwLength; i++) {\n password1 += pw.charAt([Math.floor(Math.random() * pw.length)]);\n\n }\n\n //turning the password string into an array called finalPW\n var finalPW = password1.split(\"\");\n\n //places criteria from the criteriaArray into the final password array\n Array.prototype.splice.apply(finalPW, [0, criteriaArray.length].concat(criteriaArray));\n\n //the final password array is then put into a single string\n var genPW = finalPW.join(\"\");\n\n\n //displays the password in the textfield\n passwordText.value = genPW;\n\n console.log(password1);\n console.log(pw);\n console.log(finalPW);\n console.log(genPW);\n}", "function password() {\n var errors = document.querySelector(\"#errors\");\n var password = document.querySelectorAll(\"#pass\");\n var pass = password.value.trim();\n var patt = /^(?=.*[a-z])(?=.*\\d){8,16}$/ig;\n if(!patt.test(pass)) {\n return false;\n }\n else {\n return true;\n }\n}", "function writePassword(len, upper,lower,num, sym) {\n \n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n // var char = upperCase + lowerCase + Numbers + Symbols;\n // var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&‘()*+,-./:;<=>?@[\\]^_`{|}~';\n \n}", "function passwordCrit() \n{\n // prompt to determine the length of the password\n pwdLength = prompt(\"How many characters does the password need?\");\n // checks if the length is within the criteria then it asks for the rest of the criteria\n if (pwdLength >= 8 && pwdLength <= 128) \n {\n specChar = confirm(\"Would you like special characters?\");\n numChar = confirm(\"Would you like numbers?\");\n capChar = confirm(\"Would you like to use capital letters\");\n \n }\n // security for when someone tries to input a number too little or too high or any other character.\n else \n {\n alert(\"Pick a number of 8 characters and a max of 128 characters for your password length.\")\n passwordCrit();\n }\n}", "function generatePassword(){\n //ask for password length and assign length to lengthCriteria \n var lengthCriteria = prompt(\"Select Password length. Please enter a NUMBER between 8 and 128 characters.\");\n\n // print lengthCriteria to console \n console.log(lengthCriteria);\n\n //Verify length selection is allowable and if so procede to uppercase inclusion/exclusion\n if (isNaN(lengthCriteria) !== isNaN(\"1\") ){\n alert(\"You have entered an invalid value!\");\n return;\n }\n if (lengthCriteria < 8 || lengthCriteria > 128 ){\n alert(\"You have entered an invalid value!\");\n return;\n }\n if (lengthCriteria >= 8 && lengthCriteria <= 128 ){\n var upperCase = prompt(\"Would you like to use upperCase letters? Please enter y for yes or n for no.\");\n \n //insure input is as requested and uppercase. if so print to console and procede to lowercase inclusion/exclusion\n upperCase = upperCase.toUpperCase(); \n if(upperCase != \"N\" && upperCase != \"Y\"){\n alert(\"Sorry you did not submit a valid entry!\");\n return;\n }\n\n // Print uppercase to console\n console.log(upperCase);\n\n //insure input is as requested and uppercase. if so print to console and procede to numberical inclusion/exclusion\n var lowerCase = prompt(\"Would you like to use lowerCase letters? Please enter y for yes or n for no.\");\n lowerCase = lowerCase.toUpperCase(); \n if(lowerCase != \"N\" && lowerCase != \"Y\"){\n alert(\"Sorry you did not submit a valid entry!\");\n return;\n }\n\n // Print lowercase to console \n console.log(lowerCase);\n\n //Numerical inclusion?\n var numbers = prompt(\"Would you like to include numbers? Please enter y for yes or n for no.\");\n numbers = numbers.toUpperCase(); \n if(numbers != \"N\" && numbers != \"Y\"){\n alert(\"Sorry you did not submit a valid entry!\");\n return;\n }\n\n //print number to console\n console.log(numbers);\n\n var specialChars = prompt(\"Would you like to include special characters? Please enter y for yes or n for no\")\n specialChars = specialChars.toUpperCase(); \n if(specialChars != \"N\" && specialChars != \"Y\"){\n alert(\"Sorry you did not submit a valid entry!\");\n return;\n }\n\n //print specialchar to console\n console.log(specialChars);\n\n }\n //make all local values global\n genCriteria[0] = upperCase;\n genCriteria[1] = lowerCase;\n genCriteria[2] = numbers;\n genCriteria[3] = specialChars;\n console.log(genCriteria);\n LengthCriteria = lengthCriteria;\n uppercase = upperCase;\n lowercase = lowerCase;\n numerical = numbers;\n special = specialChars;\n //create an array to detect if no character type was selected\n var notAllowed = [\"N\", \"N\", \"N\", \"N\"];\n if (genCriteria.toString() === notAllowed.toString()){\n alert(\"Sorry you must select at least one character type to constitute your password.\");\n return;\n }\n //if at least one char type is selected the generate selected characterset\n else if (genCriteria !== notAllowed){\n if (genCriteria[0] == \"Y\"){\n selectChars = \"QWERTYUIOPLKJHGFDSAZXCVBNM\";\n }\n if (genCriteria[1] == \"Y\"){\n selectChars = selectChars.concat('qwertyuioplkjhgfdsazxcvbnm');\n }\n if (genCriteria[2] == \"Y\"){\n selectChars = selectChars.concat(\"0123456789\");\n }\n if (genCriteria[3] == \"Y\"){\n selectChars = selectChars.concat(\"!@#$%^&*()-_+=~/|[]{},.`<>?\");\n }\n }\n\n // print charset to the console for verification \n console.log(selectChars);\n\n //Generate Password from selected characterset and length and store it in pw\n var pw = \"\";\n for (var i = 0; i < LengthCriteria; i++){\n pw = pw.concat(selectChars.charAt(Math.floor(Math.random() * selectChars.length)));\n }\n\n //pass pw to \n return pw;\n\n }", "function generatePassword() {\n const lowerBox = document.querySelector('#lowerBox')\n const upperBox = document.querySelector('#upperBox')\n const numbersBox = document.querySelector('#numbersBox')\n const symbolsBox = document.querySelector('#symbolsBox')\n\n // Arrays that will be randomly shuffled\n const lowerCase = \"abcdefghijklmnopqrstuvwxyz\";\n const upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const numbers = \"1234567890\";\n const symbols = \"~`!@#$%^&*()_-+=[]';:?\";\n const validators = []\n let isValid = true\n\n // Buffer variables as a location for random passwords to be held\n let passwordOptions = \"\";\n let finalPassword = \"\";\n\n // Makes the user input password length turn into a number, versus a string\n const passLength = parseInt(document.getElementById(\"passLength\").value);\n if (passLength < 8 || passLength > 128) {\n alert(\"Password must be between 8 and 128 characters\")\n return\n }\n\n // Validate that each criterion user requested appear at least once in the final password\n if (lowerBox.checked) {\n passwordOptions += lowerCase\n validators.push(/[a-z]/)\n }\n if (upperBox.checked) {\n passwordOptions += upperCase\n validators.push(/[A-Z]/)\n }\n if (numbersBox.checked) {\n passwordOptions += numbers\n validators.push(/[0-9]/)\n }\n if (symbolsBox.checked) {\n passwordOptions += symbols\n validators.push(/[\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\-\\+\\=\\[\\]\\'\\;\\:\\?]/)\n }\n\n while (finalPassword.length < passLength) {\n finalPassword += passwordOptions[Math.floor(Math.random() * passwordOptions.length)]\n }\n\n validators.forEach((validator) => {\n if (!isValid) {\n return\n }\n if (!validator.exec(finalPassword)) {\n isValid = false\n }\n })\n\n // Final result of what running the function will produce\n return isValid ? finalPassword : generatePassword()\n\n// Closing tag for generatePassword function\n}", "function generatePassword() {\n \n// create confirm to ask user if they want uppercase letters and set to a variable\n\nvar uppercaseQ = confirm(\"Would you like your password to contain Uppercase letters?\")\n\n// create confirm to ask user if they want lowercase letters and set to a variable\n\nvar lowercaseQ = confirm(\"Would you like your password to contain Lowercase letters?\")\n\n// create confirm to ask user if they want number letters and set to a variable\n\nvar numbersQ = confirm(\"Would you like your password to contain Numbers?\")\n\n// create confirm to ask user if they want special character letters and set to a variable\n\nvar specialCharactersQ = confirm(\"Would you like your password to contain Special Characters?\")\n\n// create prompt to ask user how many char they want their pass to be and set to a variable (at least 8 characters, no more than 128)\n\nvar testPasswordLength = prompt(\"How long do you want your password to be? Please pick a number between 8 and 280.\")\n\nif ( testPasswordLength < 8)\n{\n alert(\"Too short, must be greater than 8!\")\n}\nelse if (testPasswordLength > 280)\n{\n alert(\"Too long, must be shorter than 280.\")\n}\nelse \n{\n passwordLength = testPasswordLength\n}\n\n// create a conditional to make sure that the user has chosen at least one type of character\n\nif (!uppercaseQ && !lowercaseQ && !numbersQ && !specialCharactersQ)\n{\n alert(\"Must select at least one password criteria!\")\n}\n\n// create an array of uppercase letters, lowercase letters, nums, and special char.\n\nvar uppercaseLetters = [\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"]\nvar lowercaseLetters = [\"abcdefghijklmnopqrstuvwxyz\"]\nvar numbers = [\"0123456789\"]\nvar specialCharacters = [\"!@#$%^&*()_\"]\n\n// Create an empty array to hold user requested characters\n\nvar finalArrayOfCharacters = []\n\n// Create multiple if statements that checks if the user said yes or no to different confirms that we asked them, and based on their response, push those special chars to our empty array\n\nif (uppercaseQ) {\n // push all the special chars in the empty array\n finalArrayOfCharacters = finalArrayOfCharacters + uppercaseLetters\n}\nif (lowercaseQ) {\n // push all the special chars in the empty array\n finalArrayOfCharacters = finalArrayOfCharacters + lowercaseLetters\n}\nif (numbersQ) {\n // push all the special chars in the empty array\n finalArrayOfCharacters = finalArrayOfCharacters + numbers\n}\nif (specialCharactersQ) {\n // push all the special chars in the empty array\n finalArrayOfCharacters = finalArrayOfCharacters + specialCharacters\n}\nconsole.log(finalArrayOfCharacters)\n// create a var to hold the final results\n\nvar finalPassword = \"\";\n\n// A for loop to loop over final array, it should run based on the results of the prompt when we asked user how many chars they like their pass to be, choose randomly from final array that holds all the characters that the user wanted and save them to our finalPassword variable\n\nfor (var i = 0; i < passwordLength; i++) {\n var randomNum = Math.floor(Math.random()*finalArrayOfCharacters.length) // length of final array)\n finalPassword = finalPassword + finalArrayOfCharacters[randomNum]\n console.log(i + \" \" + finalPassword)\n}\nconsole.log(finalPassword)\n\n// return the finalPassword from this function out side of the for loop at the end of this function\n\nreturn finalPassword\n\n}", "function generatePassword() {\n var howManyNumbers = prompt(\"How many characters would you like your password to be?\");\n\n if (howManyNumbers < 8) {\n alert(\"Must be at least 8 characters\");\n\n }\n else if (howManyNumbers > 128) {\n alert(\"Can't be more than 128 characters\");\n\n }\n \n// Confirm type of characters user would like in password, user must choose at least 1//\n\n var chooselowercase = confirm(\"Would you like lowercase letters in your password?\");\n var chooseuppercase = confirm(\"Would you like uppercase letters in your password?\");\n var chooseSpChar = confirm(\"Would you like special characters in your password?\");\n var chooseNumeric = confirm(\"Would you like numbers in your password?\");\n\n\n if (chooselowercase == false && chooseuppercase == false && chooseSpChar == false && chooseNumeric == false) {\n\n alert(\"Must choose at least 1 character type\")\n }\n//Concat arrays for possible password combinations//\n var userArray = []\n if (chooselowercase) {\n userArray = userArray.concat(lowerCase)\n console.log(userArray)\n }\n\n if (chooseuppercase) {\n userArray = userArray.concat(upperCase)\n console.log(userArray)\n }\n\n if (chooseSpChar) {\n userArray = userArray.concat(specialCharacter)\n console.log(userArray)\n }\n\n if (chooseNumeric) {\n userArray = userArray.concat(Numeric)\n console.log(userArray)\n }\n//Display password with all chosen criteria//\n var password = \"\";\n for (i = 0; i < howManyNumbers; i++) {\n password += userArray[Math.floor(Math.random() * userArray.length)];\n console.log(password)\n }\n return password;\n\n}", "function generatePassword(){\n\n //User Preference Alerts\n\n // Asks if you want to use numbers and produces a Boolean \n\n var usenum = confirm(\"Would you like to include numbers?\")\n\n // Asks if you want to use Symbols and produces a Boolean \n\n var usesym = confirm(\"Would you like to include special characters?\")\n\n // Asks if you want to use Uppercase and produces a Boolean \n\n var useupp = confirm(\"Would you like to include Uppercase Letters?\")\n\n // Asks if you want to use lowercase and produces a Boolean\n\n var uselow = confirm(\"Would you like to include lowercase letters?\")\n\n // Asks how long you want the password to be and produces a string of a number\n\n var long = prompt(\"How many characters would you like to include in your password? (8-128)\")\n\n \n\n\n //Length Loop\n // MUST BE BETWEEN 8 and 128 Characters\n\n if(long<129 &&long>7){\n\n for(i = 0; i < parseInt(long); i++){\n\n // Decides a random if/else to select this time\n\n var selector = Math.floor((Math.random() * 4) + 1)\n\n //User preference loops\n\n // If Numbers are wanted\n if(usenum === true && selector === 1){\n var randnum = Math.floor(Math.random() * (max - min + 1)) + min;\n possible.push(randnum);\n }\n // If Symbols are wanted\n else if(usesym === true && selector === 2){\n var randsymbol = character[Math.floor(Math.random() * character.length)];\n possible.push(randsymbol);\n }\n // If Uppercase letters are wanted\n else if(useupp === true && selector === 3){\n var randupper = upper[Math.floor(Math.random() * upper.length)];\n possible.push(randupper);\n }\n // If lowercase letters are wanted\n else if(uselow === true && selector === 4){\n var randlower = lower[Math.floor(Math.random() * lower.length)];\n possible.push(randlower);\n }\n\n random.push(possible[Math.floor(Math.random() * possible.length)])\n }\n\n // Joins the array of characters together\n random = random.join('');\n\n // Logs into the console for saved passwords (DEVELOPER ONLY)\n console.log(random)\n\n // Displays new password on screen \n var Display = document.querySelectorAll(\"p\")\n\n Display[0].textContent= random\n Display[0].setAttribute(\"value\", random)\n\n // Resets back to empty to facilitate rerolling passwords\n\n possible = []\n random = []\n }\n // Error message for improper length\n\n else{\n alert(\"Please try again, must be between 8 and 128 characters.\")\n }\n}", "function generatePassword() {\n clickit = parseInt(prompt(\"How long would you like your password? Please choose between 8 and 128\"));\n\n // Validation 1 - Incorrect Input made by the User\n if (!clickit) {\n alert(\"Ensure you type in the length (a number) you would like for your password\");\n }\n /// Validation 1a - User's choice went beyond the criteria\n else if (clickit < 8 || clickit > 128) {\n clickit = parseInt(prompt(\"Inorder to proceed, ensure you choose the length of your password. It must be between 8 and 128\"));\n\n }\n\n // Other Password criteria user can choose from \n else {\n\n validateUpperCase = confirm(\"Would you like your password to contain Uppercases?\");\n validateLowerCase = confirm(\"Would you like your password to contain Lowercase?\");\n validateNumber = confirm(\"Would you like your password to contain Numbers?\");\n validateCharacter = confirm(\"Would you like your password to contain Characters?\");\n };\n\n\n // Validation 2 - User did not make any criteria choice\n if (!validateUpperCase && !validateLowerCase && !validateNumber && !validateCharacter) {\n userinput = alert(\"You have to choose a Password Criteria\");\n }\n\n //Validation 3 - User did accept all 4 Criteria\n else if (validateUpperCase && validateLowerCase && validateNumber && validateCharacter) {\n userinput = largeletters.concat(smalletters, numbers, special);\n\n }\n\n /// Validation 4 - Only one choice made \n else if (validateUpperCase) {\n userinput = largeletters;\n }\n else if (validateLowerCase) {\n userinput = smalletters;\n }\n else if (validateNumber) {\n userinput = numbers;\n }\n else if (validateCharacter) {\n userinput = special;\n }\n\n\n // Validation 5 - Only two choices made by the User\n else if (validateUpperCase && validateLowerCase) {\n userinput = largeletters.concat(smalletters);\n }\n else if (validateCharacter && validateNumber) {\n userinput = special.concat(numbers);\n }\n else if (validateCharacter && validateLowerCase) {\n userinput = special.concat(smalletters);\n }\n else if (validateUpperCase && validateCharacter) {\n userinput = largeletters.concat(special);\n }\n else if (validateLowerCase && validateNumber) {\n userinput = smalletters.concat(numbers);\n }\n else if (validateUpperCase && validateNumber) {\n userinput = largeletters.concat(numbers);\n }\n\n\n // Validation 6 - Only three choices made by the User\n else if (validateNumber && validateUpperCase && validateLowerCase) {\n userinput = numbers.concat(largeletters, smalletters);\n }\n else if (validateNumber && validateUpperCase && validateCharacter) {\n userinput = numbers.concat(largeletters, special);\n }\n else if (validateNumber && validateLowerCase && validateCharacter) {\n userinput = numbers.concat(smalletters, special);\n }\n else if (validateCharacter && validateUpperCase && validateLowerCase) {\n userinput = special.concat(largeletters, smalletters);\n }\n\n\n\n //Random selection of password based on the criteria picked by the User\n var uniqueid = [];\n for (var i = 0; i < clickit; i++) {\n var userDecision = userinput[Math.floor(Math.random() * userinput.length)];\n uniqueid.push(userDecision);\n }\n var password = uniqueid.join(\"\");\n PasswordEntry(password);\n return uniqueid;\n}", "function validateBlurPasswordText() {\n\n if (passwordInput.value === \"\" || passwordInput.value === null) {\n infoDivPassword.style.display = \"block\"\n infoDivPassword.style.color = \"red\"\n infoDivPassword.innerText = \"Password field is empty\"\n return;\n }\n if (passwordInput.value.search(/[a-z]/) < 0) {\n infoDivPassword.style.display = \"block\"\n infoDivPassword.style.color = \"red\"\n infoDivPassword.innerText = \"Password must contain at least one lowercase letter\"\n return;\n }\n if (passwordInput.value.search(/[A-Z]/) < 0) {\n infoDivPassword.style.display = \"block\"\n infoDivPassword.style.color = \"red\"\n infoDivPassword.innerText = \"Password must contain at least one uppercase letter\"\n return;\n }\n if (passwordInput.value.search(/[0-9]/) < 0) {\n infoDivPassword.style.display = \"block\"\n infoDivPassword.style.color = \"red\"\n infoDivPassword.innerText = \"Password must contain at least one number \"\n return;\n }\n if (passwordInput.value.length < 8) {\n infoDivPassword.style.display = \"block\"\n infoDivPassword.style.color = \"red\"\n infoDivPassword.innerText = \"Password must have at least 8 characters\"\n return;\n }\n}", "function getPassowrd() {\n let eyeIconShow = document.getElementById('eye-icon-slash-1');\n eyeIconShow.style.display = 'block';\n eyeIconShow.classList = 'fas fa-eye';\n\n let changeType = document.getElementById('singup-pass');\n changeType.type = 'text';\n\n let chars = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+=-[]{}><:';\n let password = '';\n\n for (let i = 0; i < 12; i++) {\n let r = Math.floor(Math.random() * chars.length);\n password += chars[r];\n }\n document.getElementById('singup-pass').value = password;\n}", "function passwordValidation3(password) {\n return ((password.length >= 7) && (\"Strong\") && (\"Weak\"));\n}", "function hashUserList()\n{\n\t$(\"div.web-address-list li.selected\").removeClass('selected').children('input').removeAttr('checked');\n\t$(\"form\").each(function() { this.reset(); }); \n\t\n\t$(\"input[type=password\" , \"form#editRegister\").addClass(\"passwordField\");\n}", "function generatePassword() {\n var charCh = \"abcdefghijklmnopqrstuvwxyzABDCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*?\";\n\n var password = \"\"\n\n for (i = 0; i <= 8; i++) {\n password = password + charCh.charAt(Math.floor(Math.random() * Math.floor(charCh.length - 1)));\n }\n\n\n /****\n * WRITE YOUR CODE HERE\n */\n alert(\"Generate Password\");\n \n return password;\n }", "function writePassword() {\n var password = generatePassword();\n function generatePassword() {\n // created blank array to allow user to generate password multiple times without refreshing page\n finalPassword = []\n var chooseLength = prompt(\"Choose password length (between 8 and 128 characters\")\n // if user hits \"cancel\" instead of choosing a length\n if (!chooseLength) {\n alert(\"You must choose a length to create a password!\");\n }\n // if user chooses a length less than 8 or greater than 128\n else if (chooseLength < 8 || chooseLength > 128) {\n alert(\"Please choose a password length between 8 and 128\");\n }\n // user choices with confirmation boxes\n else { chooseUpper = confirm(\"Do you want uppercase letters?\");\n chooseLower = confirm(\"Do you want lowercase letters?\");\n chooseSymbols = confirm(\"Do you want symbols?\");\n chooseNumbers = confirm(\"Do you want numbers?\");\n }\n // all false \n if(!chooseUpper && !chooseLower && !chooseSymbols && !chooseNumbers){\n alert(\"Please make a choice you dummy!\");\n }\n // all true\n if(chooseUpper && chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(lowerCase, symbolChar, numbersChar);\n }\n // upper true else false\n if(chooseUpper && !chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = upperCase;\n }\n // lower true else false\n if(!chooseUpper && chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = lowerCase;\n }\n // Numbers true else false\n if(!chooseUpper && !chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = numbersChar;\n }\n // symnbol true else false\n if(!chooseUpper && !chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = symbolChar;\n }\n // upper and lower true else false\n if(chooseUpper && chooseLower && !chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(lowerCase);\n }\n // upper and Numbers true else false\n if(chooseUpper && !chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(numbersChar);\n }\n // upper and symbol true else false\n if(chooseUpper && !chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(symbolChar);\n }\n // upper, lower and Numbers true \n if(chooseUpper && chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(lowerCase,numbersChar);\n }\n // upper, lower and symbol true\n if(chooseUpper && chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = upperCase.concat(lowerCase,symbolChar);\n }\n // upper Number and symbol true\n if(chooseUpper && !chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = upperCase.concat(symbolChar,numbersChar);\n }\n // lower and Numbers are true else false\n if(!chooseUpper && chooseLower && !chooseSymbols && chooseNumbers){\n passwordArray = lowerCase.concat(numbersChar);\n }\n // lower and symbol are true else false\n if(!chooseUpper && chooseLower && chooseSymbols && !chooseNumbers){\n passwordArray = lowerCase.concat(symbolChar);\n }\n // lower Numbers and symbol are true\n if(!chooseUpper && chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = lowerCase.concat(numbersChar, symbolChar);\n }\n // Numbers and symbol are true else false\n if(!chooseUpper && !chooseLower && chooseSymbols && chooseNumbers){\n passwordArray = symbolChar.concat(numbersChar);\n }\n // random password generation from previous choices \n for(var i = 0; i < chooseLength; i++){\n var index = Math.floor(Math.random() * passwordArray.length);\n var password = passwordArray[index];\n finalPassword.push(password); \n } return finalPassword.join(\"\"); \n}\n\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function listOfPassword (input) {\r\n const arrOfPass = [];\r\n\r\n input.map(string => {\r\n // Get the splitted Min and Max elements from the array. ex. 1-6 or 1-4 ...\r\n const min = string[0].split('-')[0];\r\n const max = string[0].split('-')[1]\r\n // Get the char element from the array, in position [1][0]\r\n const char = string[1][0];\r\n if (isValid(min, max, char, string[2])) arrOfPass.push(string[2]);\r\n })\r\n\r\n return arrOfPass;\r\n}", "unlocked(){return hasChallenge(\"燃料\",11)}", "unlocked(){return hasChallenge(\"燃料\",11)}", "generateTemporaryStegPassword() {\r\n\r\n\t\t\t\t\tlet password = \"\";\r\n\t\t\t\t\tlet invisibleCharacters = [\"\\u200C\", \"\\u200D\", \"\\u2061\", \"\\u2062\", \"\\u2063\", \"\\u2064\"];\r\n\t\t\t\t\tfor (var i = 0; i < 4; i++) {\r\n\t\t\t\t\t\tpassword += invisibleCharacters[(Math.floor(Math.random() * 6))];\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn password;\r\n\t\t\t\t}", "function passwordCharacterRules(value, $tooltip) {\n // The password MUST contains letters and numbers, and it CAN contain the approved special characters\n if (value.search(/^(?=.*[0-9])(?=.*[a-zA-Z])([A-Za-z0-9~`!@#$%^&*_+-=\\?.,\\<\\>\\ ]+)$/) > -1) {\n $tooltip.find('li.val-chars').addClass('valid');\n } else {\n $tooltip.find('li.val-chars').removeClass('valid');\n return false;\n }\n\n return true;\n}", "function writePassword() {\r\n //review inputs before execution. Each function handles errors by exiting program execution with empty returns\r\n if(validateCharactersRequested() && validateLength()){\r\n password.generatePassword();\r\n passwordText.value = password.randomPassword;\r\n }\r\n\r\n}", "function testPassword(passwd, documentPlace)\n{\n\t\tvar intScore = 0\n\t\tvar strVerdict = \"weak\"\n\t\tvar\tstrFont=\"text-danger\";\n\t\t\n\t\t\n\t\tif (passwd.length>7)// get 1 point for each character after 8\n\t\t{\n\t\t\tintScore = passwd.length\n\t\t}\t\n\t\t\n\t\t// LETTERS \n\t\tif (passwd.match(/[a-z]/)) // at least one lower case letter\n\t\t{\n\t\t\tintScore = (intScore+1)\n\t\t}\n\t\t\n\t\tif (passwd.match(/[A-Z]/)) // at least one upper case letter\n\t\t{\n\t\t\tintScore = (intScore+1)\n\t\t}\n\t\t\n\t\t// NUMBERS\n\t\tif (passwd.match(/\\d+/)) // at least one number\n\t\t{\n\t\t\tintScore = (intScore+1)\n\t\t}\n\t\t\n\t\tif (passwd.match(/(.*[0-9].*[0-9].*[0-9])/)) // at least three numbers\n\t\t{\n\t\t\tintScore = (intScore+3)\n\t\t}\n\t\t\n\t\t\n\t\t// SPECIAL CHAR\n\t\tif (passwd.match(/[^a-zA-Z0-9]/)) // at least one special character\n\t\t{\n\t\t\tintScore = (intScore+2)\n\t\t}\n\t\t\n\t\t\t\t\t\t\t\t\t // [verified] at least two special characters\n\t\tif (passwd.match(/(.*[^a-zA-Z0-9].*[^a-zA-Z0-9])/))\n\t\t{\n\t\t\tintScore = (intScore+3)\n\t\t}\n\t // check for common passwords ignore case\n\t\tvar lowerCasePass = passwd.toLowerCase();\n\t\tif (lowerCasePass.match(/^(passw(o|0)rd1?|123456789?|trustno1|football|iloveyou|welcome|whatever|jordan23)$/)){\n\t\t\tintScore=0;\n\t\t}\n\t\t// check for common passwords\n\t\tif (lowerCasePass.match(/^(1qaz2wsx|12341234|corvette|computer|blahblah|matthew|mercedes)$/)){\n\t\t\tintScore=0;\n\t\t}\t\t\n\t\t// check for common passwords\n\t\tif (lowerCasePass.match(/^(admin1234?|michelle|sunshine|zaq1zaq1|jennifer|maverick|starwars)$/)){\n\t\t\tintScore=0;\n\t\t}\t\t\t\n\t\n\t\tif(intScore < 8)\n\t\t{\n\t\t strVerdict = \"Try a longer password or add a special character...\"\n\t\t strFont=\"text-danger\";\n\t\t}\n\t\telse if (intScore >= 8 && intScore < 14)\n\t\t{\n\t\t strVerdict = \"Pretty good choice if I do say so myself ...\"\n\t\t strFont = \"text-info\"\n\t\t}\n\t\telse if (intScore >= 14)\n\t\t{\n\t\t strVerdict = \"That's my favorite password!!! Yipee!!\"\n\t\t strFont=\"text-success\";\n\t\t}\n\t\tdocument.getElementById(documentPlace).innerHTML = \"<div class=\\\"text-center \" + strFont + \"\\\">\" + strVerdict + \"</div>\"\n}", "function writePassword() {\n \n // Array of possible characters for each character type\n \n var lower = [\"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 upper = [\"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 number = [0,1,2,3,4,5,6,7,8,9];\n var symbol = [\"!\",\"@\",\"#\",\"$\",\"%\",\"^\",\"&\",\"*\",\"(\",\")\",\"+\",\"?\",\"<\",\">\",\"|\",\"~\",\"{\",\"}\",\"=\",\"+\"];\n\n var charTypeSelected = [];\n var password = [];\n\n // A series of prompts user completes in order to select password criteria \n var passwordLength = prompt(\"Choose a password length. Enter a number between 8 - 128.\");\n if(passwordLength < 8 || passwordLength > 128) {\n alert(\"Please enter a valid number.\");\n return;\n } else {\n alert(\"Your password will consist of \" + passwordLength + \" characters.\");\n }\n\n var lowercaseChar = confirm(\"Do you want to include lowercase characters in your password?\");\n if(lowercaseChar) {\n alert(\"Your password will include lowercase letters.\");\n charTypeSelected = charTypeSelected.concat(lower);\n } else {\n alert(\"Your password will NOT inlcude lowercase letters.\");\n }\n\n var uppercaseChar = confirm(\"Do you want to include uppercase characters in your password?\");\n if(uppercaseChar) {\n alert(\"Your password will include uppercase letters.\");\n charTypeSelected = charTypeSelected.concat(upper);\n } else {\n alert(\"Your password will NOT inlcude uppercase letters.\");\n }\n\n var numericChar = confirm(\"Do you want to include numeric characters in your password?\");\n if(numericChar) {\n alert(\"Your password will include numeric characters.\");\n charTypeSelected = charTypeSelected.concat(number);\n } else {\n alert(\"Your password will NOT inlcude numeric characters.\");\n }\n\n var specialChar = confirm(\"Do you want to include special characters in your password?\");\n if(specialChar) {\n alert(\"Your password will include special characters.\");\n charTypeSelected = charTypeSelected.concat(symbol);\n } else {\n alert(\"Your password will NOT inlcude special characters.\");\n }\n\n // If no character types were selected, the user will be asked to select at least one character type and the function will return. The user must then click the button again and start over.\n if (!lowercaseChar && !uppercaseChar && !numericChar && !specialChar) {\n alert(\"Please select at least one character type.\") \n return;\n }\n\n // This for loop creates the random password to be generated to the password box\n for (var i = 0; i < passwordLength; i++) {\n password[i] = charTypeSelected[Math.floor(Math.random() * charTypeSelected.length)];\n \n }\n\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password.join(\"\"); \n\n\n}" ]
[ "0.6026811", "0.5992311", "0.5721471", "0.5712165", "0.57091814", "0.56848127", "0.5673862", "0.56640947", "0.56416243", "0.5571793", "0.55652976", "0.5557384", "0.5556953", "0.5555809", "0.5548888", "0.55458504", "0.5528871", "0.5519436", "0.55165875", "0.5509438", "0.55054367", "0.54951376", "0.5477824", "0.5476332", "0.54649967", "0.545937", "0.5458051", "0.54475206", "0.5447111", "0.5446561", "0.54430056", "0.54348695", "0.5421977", "0.54218036", "0.5403385", "0.54029363", "0.54022664", "0.53992885", "0.5397315", "0.53942764", "0.53939235", "0.5389531", "0.5380718", "0.53660685", "0.536391", "0.5359525", "0.5357765", "0.53459805", "0.53399104", "0.5337311", "0.5337201", "0.5336528", "0.53356767", "0.5334609", "0.53278875", "0.532353", "0.53193784", "0.5314948", "0.53146726", "0.5311475", "0.5311398", "0.53096676", "0.53065795", "0.5300569", "0.52906626", "0.52898407", "0.52890074", "0.5287709", "0.52876586", "0.5287602", "0.5287322", "0.52854955", "0.52845037", "0.5282041", "0.5281251", "0.5274387", "0.5271249", "0.5271091", "0.5267556", "0.52673125", "0.5263639", "0.526362", "0.5262619", "0.5261345", "0.52588516", "0.52577543", "0.52515", "0.524991", "0.52445227", "0.5243922", "0.5242706", "0.5242585", "0.52369505", "0.5236664", "0.52339685", "0.52339685", "0.52311563", "0.5230784", "0.5230713", "0.5229015", "0.52280635" ]
0.0
-1
END OF Blacklist Code START OF Misc Code Function to see if Appu server is up Also tells the server that this appu installation is still running
function pii_check_if_stats_server_up() { var stats_server_url = "http://woodland.gtnoise.net:5005/" try { var wr = {}; wr.guid = (sign_in_status == 'signed-in') ? pii_vault.guid : ''; wr.version = pii_vault.config.current_version; wr.deviceid = (sign_in_status == 'signed-in') ? pii_vault.config.deviceid : 'Not-reported'; var r = request({ url: stats_server_url, content: JSON.stringify(wr), onComplete: function(response) { if (response.status == 200) { var data = response.text; var is_up = false; var stats_message = /Hey ((?:[0-9]{1,3}\.){3}[0-9]{1,3}), Appu Stats Server is UP!/; is_up = (stats_message.exec(data) != null); my_log("Appu stats server, is_up? : "+ is_up, new Error); } else { //This means that HTTP response is other than 200 or OK my_log("Appu: Could not check if server is up: " + stats_server_url + ", status: " + response.status.toString(), new Error); print_appu_error("Appu Error: Seems like server was down. " + "Status: " + response.status.toString() + " " + (new Date())); } } }); r.post(); } catch (e) { my_log("Error while checking if stats server is up", new Error); } last_server_contact = new Date(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isRunning(req, res) {\n res.send(\"Its Alive!!!\");\n}", "function checkIfServerIsUp(server_ip_address)\n {\n \tvar is_server_up = false;\n \tconsole.log(\"Invoking a synchronous AJAX call to check for server's status ..\");\n \ttry {\n $.ajax({\n type: \"GET\",\n url: SESSION_MGR_API_URL,\n data: \"operation=getServerStatus&serverIP=\" + server_ip_address, \n \t async:false, \n success: function(response) {\n \tconsole.log(\"API Result : \" + response);\n \tapi_result = response;\n },\n error: function( req, status, err ) {\n console.log( 'something went wrong', status, err );\n } \n }); \t\t\n \t}\n \tcatch(e) {\n \t\tconsole.log(\"Failed to determine if server is up. Reason : \" + e.message);\n \t}\n\n \n console.log(\"API Result for normal client disconnect mode determination is \" + api_result);\n api_result = $.trim(api_result);\n if(api_result == \"reachable\") {\n \tis_server_up = true;\n } \t\n \n \treturn is_server_up;\n }", "function checkingHosting() {\n if (window.location.hostname === \"localhost\") {\n //checkingLocalHostURLS();\n console.log(\"User is on LOCALHOST\");\n }\n\n if (window.location.hostname === \"127.0.0.1\") {\n //checkingLocalHostURLS();\n console.log(\"User is on LOCALHOST\");\n }\n\n if (window.location.hostname !== \"localhost\") {\n checkingServerURLS();\n console.log(\"User is on HOSTING SERVER\");\n }\n\n if (window.location.hostname !== \"127.0.0.1\") {\n checkingServerURLS();\n console.log(\"User is on HOSTING SERVER\");\n }\n }", "function checkDaemonRunning() {\n // FIXME: need to handle USE_TCP_LOOPBACK\n return fs.existsSync(MDNS_UDS_SERVERPATH);\n}", "function online() {\n\t\t\treturn serverStatus === \"online\";\n\t\t}", "async function checkServerRunning() {\n let isServerRunning = await isReachable(`${host}:${port.toString()}`);\n return isServerRunning;\n}", "function checkServer() {\n\n // After the timer has passed, hide the initial window\n indexElements.servicePlaceholderInitial.hide();\n indexElements.serviceTableBody.hide();\n\n // Make a promise chain to get our registered services\n fetch(\"/registry/endpoints\", {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n }\n })\n .then( response => response.json())\n .then( services => {\n\n // Keep track of how many we have here\n let serviceCount = 0;\n\n // Clear our current table\n clearServiceTable();\n\n // If we have services registered, update the table\n for (var service in services) {\n if (services.hasOwnProperty(service)) {\n\n // Add this to the table\n addServiceToTable(services[service]);\n\n // Update the counter\n serviceCount++;\n }\n }\n\n // If we have services registered, update the table\n if (serviceCount > 0) {\n \n // Hide the placeholder\n indexElements.serviceTableBody.show();\n indexElements.servicePlaceholder.hide();\n\n } else {\n\n // Show the placeholder\n indexElements.servicePlaceholder.show();\n indexElements.serviceTableBody.hide();\n }\n });\n\n // Once all of that is handled, allow another check\n waitingForServer = false;\n}", "function checkNewApp (){\n\tif (lastUpdate == undefined){\n\t\tactivateScript(\"system_profiler SPApplicationsDataType\", (stdout)=>{\n\t\t\tvar softwareInfos = stdout.split(\"\\n\\n\");\n\t\t\tvar softwareName;\n\t\t\tvar softwareNames = [];\n\t\t\tvar localSoftwares_incomplete = [];\n\t\t\tsoftwareInfos.forEach((ASoftwareInfo)=>{\n\t\t\t\tvar lines = ASoftwareInfo.split(\"\\n\");\n\t\t\t\tif (lines.length === 1){\n\t\t\t\t\tvar nameLine = lines[0];\n\t\t\t\t\tvar nameLineSplit = nameLine.split(\":\");\n\t\t\t\t\tsoftwareName = nameLineSplit[0].replace(/ /g,'');\n\t\t\t\t}else {\n\t\t\t\t\tvar versionLine = lines[0];\n\t\t\t\t\tvar versionSplit = versionLine.split(\": \");\n\t\t\t\t\tsoftwareNames.push(softwareName);\n\t\t\t\t\tvar tempAppInfo = {\n\t\t\t\t\t\t\"name\": softwareName,\n\t\t\t\t\t\t\"old_version\": versionSplit[1],\n\t\t\t\t\t\t\"new_version\": 2,\n\t\t\t\t\t\t\"id\": \"0\",\n\t\t\t\t\t\t\"updatable\": \"false\"\n\t\t\t\t\t}\n\t\t\t\t\tlocalSoftwares_incomplete.push(tempAppInfo);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsetCompleteInfo(softwareNames, localSoftwares_incomplete);\n\t\t\tlastUpdate = new Date();\n\t\t});\n\t}\n}", "function checkHotLoader() {\n return new Promise((resolve, reject) => {\n var server = net.createServer();\n\n server.once(\"error\", (err) => {\n resolve(err.code === \"EADDRINUSE\");\n });\n\n server.once(\"listening\", () => server.close());\n server.once(\"close\", () => resolve(false));\n server.listen(5050);\n });\n}", "function whenServerReady(cb) {\n var serverReady = false;\n var appReadyInterval = setInterval(function () {\n checkAppReady(function (ready) {\n if (!ready || serverReady) {\n return;\n }\n clearInterval(appReadyInterval);\n serverReady = true;\n cb();\n });\n },\n 100);\n}", "function whenServerReady(cb) {\n\tlet serverReady = false;\n\tvar appReadyInterval = setInterval(() =>\n\t\t\t\tcheckAppReady(ready => {\n\t\t\t\t\tif (!ready || serverReady) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tclearInterval(appReadyInterval);\n\t\t\t\t\tserverReady = true;\n\t\t\t\t\tcb();\n\t\t\t\t}),\n\t\t\t\t100);\n}", "function checkUpdate() {\n\tsync.net.getVersion(function(serverVersion) {\n\t\tif (serverVersion != version) {\n\t\t\tconsole.log(\"New update is available\");\n\t\t}\n\t});\n}", "function get_server_status() {\n var target = 'cgi_request.php';\n var data = {\n action: 'is_online'\n };\n var callback = parse_server_status;\n send_ajax_request(target, data, callback, true);\n}", "function check_url(url, ratings_server_status) {\n\tif (ratings_server_status) {\n\t\t// Bring up ratings server \n\t\tcmd.get('forever start ratings.js', function(err, data, stderr) {\n\t\t\tsleep(3000);\n\t\t\tcheck(url);\n\t\t});\n\t} else {\n\t\t// Bring down ratings server \n\t\tcmd.get('forever stop ratings.js', function(err, data, stderr) {\n\t\t\tsleep(3000);\n\t\t\tcheck(url);\n\t\t});\n\t}\n}", "function pnAvailable() {\r\n var bAvailable = false;\r\n if (window.isSecureContext) {\r\n\t\t// running in secure context - check for available Push-API\r\n bAvailable = (('serviceWorker' in navigator) && \r\n\t\t ('PushManager' in window) && \r\n\t\t\t\t\t ('Notification' in window)); \r\n } else {\r\n console.log('site have to run in secure context!');\r\n }\r\n return bAvailable;\r\n}", "function whenServerReady(p, cb) {\n let serverReady = false\n const appReadyInterval = setInterval(() =>\n checkAppReady(p, (ready) => {\n if (!ready || serverReady) {\n return\n }\n clearInterval(appReadyInterval)\n serverReady = true\n cb()\n }), 500)\n}", "function cnc_check_if_loaded() {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (typeof qx != 'undefined') {\n\t\t\t\t\t\t\ta = qx.core.Init.getApplication(); // application\n\t\t\t\t\t\t\tif (a) {\n\t\t\t\t\t\t\t\tcnctaopt_create();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twindow.setTimeout(cnc_check_if_loaded, 1000);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twindow.setTimeout(cnc_check_if_loaded, 1000);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (typeof console != 'undefined') console.log(e);\n\t\t\t\t\t\telse if (window.opera) opera.postError(e);\n\t\t\t\t\t\telse GM_log(e);\n\t\t\t\t\t}\n\t\t\t\t}", "function cnc_check_if_loaded() {\n try {\n if (typeof qx != 'undefined') {\n a = qx.core.Init.getApplication(); // application\n if (a) {\n cncopt_create();\n } else {\n window.setTimeout(cnc_check_if_loaded, 1000);\n }\n } else {\n window.setTimeout(cnc_check_if_loaded, 1000);\n }\n } catch (e) {\n if (typeof console != 'undefined') console.log(e);\n else if (window.opera) opera.postError(e);\n else GM_log(e);\n }\n }", "function isOnline() {\n var xhr = new ( window.ActiveXObject || XMLHttpRequest )( \"Microsoft.XMLHTTP\" );\n var status;\n xhr.open( \"GET\", window.location.origin + window.location.pathname + \"/ping\",false);\n try {\n xhr.send();\n return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );\n } catch (error) {\n return false;\n }\n }", "function fnIsCodeStageProduction()\n{\n // if servername in (EuBigWb)\n var s = location.hostname;\n var nPos = s.search(\"EuBigWb1\");\n if nPos === 0 {nPos = s.search(\"EuBigWb2\");}\n var bOut = (nPos === 0) ? 0:1;\n \n return bOut;\n}", "function isOurs() {\n var deferred = Q.defer();\n var url = \"http://\" + state[\"pio\"].hostname + \":\" + state[\"pio.services\"].services[\"pio.server\"].descriptor.env.PORT + \"/.instance-id/\" + state[\"pio\"].instanceId;\n REQUEST({\n method: \"POST\",\n url: url,\n timeout: 1 * 1000\n }, function(err, res, body) {\n if (err) {\n var message = [\n \"Error while checking if instance is ours by calling '\" + url + \"'.\",\n \"Hostname '\" + state[\"pio\"].hostname + \"' is likely not resolving to the IP '\" + state[\"pio.vm\"].ip + \"' of our server!\",\n \"To see what the hostname resolves to use: http://cachecheck.opendns.com/\",\n \"You can use http://opendns.com/ (which refreshes fast) for your DNS servers:\",\n \" 208.67.222.222\",\n \" 208.67.220.220\",\n \"Then flush your local DNS cache:\",\n \" sudo killall -HUP mDNSResponder\",\n \" sudo dscacheutil -flushcache\",\n \"TODO: Why does running the above command not immediately flush the DNS cache even though the host resolves correctly on opendns?\",\n \"TODO: Insert a temporary entry into the /etc/hosts. We need a sudo/root daemon first.\"\n ].join(\"\\n\").red;\n if (\n err.code === \"ESOCKETTIMEDOUT\" ||\n err.code === \"ETIMEDOUT\"\n ) {\n console.error(\"Warning: TIMEOUT \" + message, err.stack);\n } else {\n console.error(\"Warning: \" + message, err.stack);\n }\n return deferred.resolve(false);\n }\n if (res.statusCode === 204) {\n return deferred.resolve(true);\n }\n return deferred.resolve(false);\n });\n return deferred.promise;\n }", "function serverStatus(test) {\r\n if (test === 'http://httpstat.us/200'){\r\n return ServerOnline\r\n }else {\r\n return ServerOffline\r\n }\r\n}", "function cnc_check_if_loaded() {\n\t\ttry {\n\t\t\tif (typeof qx != 'undefined') {\n\t\t\t\ta = qx.core.Init.getApplication(); // application\n\t\t\t\tif (a) {\n\t\t\t\t\tcncloot_create();\n\t\t\t\t} else {\n\t\t\t\t\twindow.setTimeout(cnc_check_if_loaded, 1000);\n }\n\t\t\t} else {\n\t\t\t\twindow.setTimeout(cnc_check_if_loaded, 1000);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (typeof console != 'undefined') console.log(e);\n\t\t\telse if (window.opera) opera.postError(e);\n\t\t\telse GM_log(e);\n\t\t}\n\t}", "function whenServerReady(p, cb) {\n let serverReady = false;\n const appReadyInterval = setInterval(() =>\n checkAppReady(p, (ready) => {\n if (!ready || serverReady) {\n return;\n }\n clearInterval(appReadyInterval);\n serverReady = true;\n cb();\n }),\n 100);\n}", "function check_if_deployed(e, attempt){\r\n\tif(e){\r\n\t\tcb_deployed(e);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//looks like an error pass it along\r\n\t}\r\n\telse if(attempt >= 15){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//tried many times, lets give up and pass an err msg\r\n\t\tconsole.log('[preflight check]', attempt, ': failed too many times, giving up');\r\n\t\tvar msg = 'chaincode is taking an unusually long time to start. this sounds like a network error, check peer logs';\r\n\t\tif(!process.error) process.error = {type: 'deploy', msg: msg};\r\n\t\tcb_deployed(msg);\r\n\t}\r\n\telse{\r\n\t\tconsole.log('[preflight check]', attempt, ': testing if chaincode is ready');\r\n\t\tchaincode.query.read(['_marbleindex'], function(err, resp){\r\n\t\t\tvar cc_deployed = false;\r\n\t\t\ttry{\r\n\t\t\t\tif(err == null){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//no errors is good, but can't trust that alone\r\n\t\t\t\t\tif(resp === 'null') cc_deployed = true;\t\t\t\t\t\t\t\t\t//looks alright, brand new, no marbles yet\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\tvar json = JSON.parse(resp);\r\n\t\t\t\t\t\tif(json.constructor === Array) cc_deployed = true;\t\t\t\t\t//looks alright, we have marbles\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch(e){}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//anything nasty goes here\r\n\r\n\t\t\t// ---- Are We Ready? ---- //\r\n\t\t\tif(!cc_deployed){\r\n\t\t\t\tconsole.log('[preflight check]', attempt, ': failed, trying again');\r\n\t\t\t\tsetTimeout(function(){\r\n\t\t\t\t\tcheck_if_deployed(null, ++attempt);\t\t\t\t\t\t\t\t\t\t//no, try again later\r\n\t\t\t\t}, 10000);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tconsole.log('[preflight check]', attempt, ': success');\r\n\t\t\t\tcb_deployed(null);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//yes, lets go!\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n}", "function appStart() {\n\t$status.innerHTML = \"App ready!\";\n}", "function check_iconnection() {\n\n\n\n\n function updateOfflineStatus() {\n toaster(\"Your Browser is offline\", 15000)\n return false;\n }\n\n window.addEventListener('offline', updateOfflineStatus);\n}", "function ArduinoUDPServerIsListening() {\r\n\tconsole.log('Arduino UDP Server is listening');\r\n}", "function checkFunction(callback) {\n console.log('Checking proxy app');\n functionsManager.init(function (err, _appServiceClient) {\n if (err) {\n status.funcError = err;\n return callback();\n }\n \n appServiceClient = _appServiceClient;\n appServiceClient.get(function (err, result) {\n if (err) {\n status.funcError = err;\n return callback();\n }\n\n status.funcActive = result && result.properties && result.properties.state == 'Running' || false;\n console.log('proxy app active: ' + status.funcActive);\n return callback();\n })\n });\n }", "checkConnectionStatus() {\n const connected = Meteor.status().connected;\n if (!connected) sAlert.error('Ingen tilkobling til server. Er du koblet til internett?');\n return connected;\n }", "function getStatusServer() {\r\n _doGet('/status');\r\n }", "function cnc_check_if_loaded() {\n try {\n if (typeof qx != 'undefined') {\n a = qx.core.Init.getApplication(); // application\n if (a) {\n cncopt_create();\n } else {\n window.setTimeout(cnc_check_if_loaded, 1000);\n }\n } else {\n window.setTimeout(cnc_check_if_loaded, 1000);\n }\n } catch (e) {\n if (typeof console != 'undefined') console.log(e);\n else if (window.opera) opera.postError(e);\n else console.log(e);\n }\n }", "function check_status() {\n YUI().use(\"io-base\", function(Y) {\n var url = M.cfg.wwwroot+'/local/rlsiteadmin/mass/addonstatus.php?addoncommand='+$response.file+'&hash='+$response.hash;\n var cfg = {\n method: 'GET',\n on: {\n success: function(id, o) {\n var $status = null;\n YUI().use('json-parse', function (Y) {\n try {\n $status = Y.JSON.parse(o.responseText);\n var status = \"waiting\";\n if ($status.running) {\n status = \"running\";\n } else if (!$status.running && $status.fileexists === false && $status.results) {\n status = \"completed\";\n }\n if (status != \"completed\") {\n update_modal(status);\n setTimeout(function() {\n check_status();\n }, 2000);\n } else {\n $response.results = $status.results;\n complete_feedback();\n }\n }\n catch (e) {\n Y.log(\"Parsing failed.\");\n }\n });\n },\n failure: function(c, o) {\n if (o.status == '503') {\n // Ignore failures caused by this site is upgrading messages.\n setTimeout(function() {\n check_status();\n }, 2000);\n return;\n }\n try {\n $status = Y.JSON.parse(o.responseText);\n complete_feedback();\n } catch (e) {\n // Some other error has occured. The progress bar will now stop moving.\n Y.log(\"Parsing failed.\");\n }\n }\n }\n };\n $addons = Y.io(url, cfg);\n });\n }", "function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n stop()\n }\n }", "function checkOnlineStatus(){\n status = navigator.onLine;\n return status;\n }", "function updateAppStatus(app){\n if (app.running){\n if (app.state == \"STOPPED\"){\n app.state = \"MONITORING\";\n app.status = \"RUNNING\";\n }\n else if (app.state == \"STOPPING\"){\n app.status = \"STOPPING\";\n }\n else if (app.state == \"STARTING\"){\n app.state = \"MONITORING\";\n app.status = \"RUNNING\";\n }\n else {\n app.state = \"RUNNING\";\n app.status = \"RUNNING\";\n }\n }\n else { //!app.running\n if (app.state == \"STARTING\"){\n app.status = \"STARTING\";\n }\n else if (app.state == \"MONITORING\" && app.restart == \"true\"){\n startApp(app);\n }\n else {\n app.state = \"STOPPED\";\n app.status = \"STOPPED\";\n }\n }\n updateAppLabelStatus(app);\n}", "function checkServer(serverIP, channelID) {\r\n\t sinusbot.http({\r\n\t \"method\": \"GET\",\r\n\t \"url\": \"https://mcapi.ca/query/\" + serverIP + \"/info/old\",\r\n\t \"timeout\": 60000,\r\n\t \"headers\": [\r\n\t {\"Content-Type\": \"application/json\"}\r\n\t ]\r\n\t }, function (error, response) {\r\n\t \tvar serverinfo = JSON.parse(response.data);\r\n\r\n\t \tif (serverinfo.status) {\r\n\t \t\tsinusbot.chatPrivate(channelID, \"Auf dem Minecraft Server mit der IP: [color=blue]\" + serverIP + \"[/color] und der Version: [color=purple]\" + serverinfo.version + \"[/color] sind [color=green]\" + serverinfo.players.online + \"[/color] Spieler von [color=red]\" + serverinfo.players.max + \"[/color] online\");\r\n\t \t} else if (!serverinfo.status) {\r\n\t \t\tsinusbot.chatPrivate(channelID, \"Der Minecraft Server mit der IP: [color=blue]\" + serverIP + \"[/color] ist [color=red]offline[/color] oder [color=red]nicht erreichbar[/color]\");\r\n\t \t}\r\n\t \r\n\t });\r\n }", "_is_localhost() {\n return ['127.0.0.1','localhost', os.hostname()].includes(this.settings.clamdscan.host);\n }", "function isXmbcAlive(callback) {\n // Send JSONRPC ping request.\n xbmcRpc('JSONRPC.Ping',\n function (result) {\n callback(true);\n },\n function (error) {\n callback(false);\n });\n }", "function checkIfNormalClientDisconnect()\n {\n \tvar is_server_up = checkIfServerIsUp(preferred_ip_address);\n \tconsole.log(\"Normal client disconnect : \" + is_server_up);\n \tif(is_server_up == true) {\n \t\treturn true;\n \t}\n \t\n \treturn false;\n }", "static get NOT_READY () {return 0}", "function ex_check_site(url,minion,testing_cb,down_cb,up_cb){\n testing_cb(minion)\n $.post(\"http://\"+minion+ '/isdown', {\n url: url\n }, function(res,status) {\n \tconsole.log(status)\n if (res == \"false\"){\n \tup_cb(minion)\n \t// console.log(minion,\"site up!\")\n }else{\n \tdown_cb(minion)\n \t// console.log(minion,\"down.\")\n }\n })\n}", "function check_status() {\n var open, ptotal, sample, pid, pname, line, match, tmp, i;\n\n // Handle operation disabled\n if (!controller.settings.en) {\n change_status(0,\"red\",\"<p class='running-text center'>\"+_(\"System Disabled\")+\"</p>\",function(){\n areYouSure(_(\"Do you want to re-enable system operation?\"),\"\",function(){\n showLoading(\"#footer-running\");\n send_to_os(\"/cv?pw=&en=1\").done(function(){\n update_controller(check_status);\n });\n });\n });\n return;\n }\n\n // Handle open stations\n open = {};\n for (i=0; i<controller.status.length; i++) {\n if (controller.status[i]) {\n open[i] = controller.status[i];\n }\n }\n\n if (controller.options.mas) {\n delete open[controller.options.mas-1];\n }\n\n // Handle more than 1 open station\n if (Object.keys(open).length >= 2) {\n ptotal = 0;\n\n for (i in open) {\n if (open.hasOwnProperty(i)) {\n tmp = controller.settings.ps[i][1];\n if (tmp > ptotal) {\n ptotal = tmp;\n }\n }\n }\n\n sample = Object.keys(open)[0];\n pid = controller.settings.ps[sample][0];\n pname = pidname(pid);\n line = \"<div><div class='running-icon'></div><div class='running-text'>\";\n\n line += pname+\" \"+_(\"is running on\")+\" \"+Object.keys(open).length+\" \"+_(\"stations\")+\" \";\n if (ptotal > 0) {\n line += \"<span id='countdown' class='nobr'>(\"+sec2hms(ptotal)+\" \"+_(\"remaining\")+\")</span>\";\n }\n line += \"</div></div>\";\n change_status(ptotal,\"green\",line,function(){\n changePage(\"#status\");\n });\n return;\n }\n\n // Handle a single station open\n match = false;\n for (i=0; i<controller.stations.snames.length; i++) {\n if (controller.settings.ps[i][0] && controller.status[i] && controller.options.mas !== i+1) {\n match = true;\n pid = controller.settings.ps[i][0];\n pname = pidname(pid);\n line = \"<div><div class='running-icon'></div><div class='running-text'>\";\n line += pname+\" \"+_(\"is running on station\")+\" <span class='nobr'>\"+controller.stations.snames[i]+\"</span> \";\n if (controller.settings.ps[i][1] > 0) {\n line += \"<span id='countdown' class='nobr'>(\"+sec2hms(controller.settings.ps[i][1])+\" \"+_(\"remaining\")+\")</span>\";\n }\n line += \"</div></div>\";\n break;\n }\n }\n\n if (match) {\n change_status(controller.settings.ps[i][1],\"green\",line,function(){\n changePage(\"#status\");\n });\n return;\n }\n\n // Handle rain delay enabled\n if (controller.settings.rd) {\n change_status(0,\"red\",\"<p class='running-text center'>\"+_(\"Rain delay until\")+\" \"+dateToString(new Date(controller.settings.rdst*1000))+\"</p>\",function(){\n areYouSure(_(\"Do you want to turn off rain delay?\"),\"\",function(){\n showLoading(\"#footer-running\");\n send_to_os(\"/cv?pw=&rd=0\").done(function(){\n update_controller(check_status);\n });\n });\n });\n return;\n }\n\n // Handle rain sensor triggered\n if (controller.options.urs === 1 && controller.settings.rs === 1) {\n change_status(0,\"red\",\"<p class='running-text center'>\"+_(\"Rain detected\")+\"</p>\");\n return;\n }\n\n // Handle manual mode enabled\n if (controller.settings.mm === 1) {\n change_status(0,\"red\",\"<p class='running-text center'>\"+_(\"Manual mode enabled\")+\"</p>\",function(){\n areYouSure(_(\"Do you want to turn off manual mode?\"),\"\",function(){\n showLoading(\"#footer-running\");\n send_to_os(\"/cv?pw=&mm=0\").done(function(){\n update_controller(check_status);\n });\n });\n });\n return;\n }\n\n $(\"#footer-running\").slideUp();\n}", "function checkOnline(){\n\t\tif(navigator.onLine == true){\n\t\t\tconsole.log(\"isOnline == true\");\n\t\t\t$rootScope.isOnline = true;\n\t\t} else {\n\t\t\tconsole.log(\"isOnline == false\");\n\t\t\t$rootScope.isOnline = false;\n\t\t}\n\t}", "function checkServerStatus(){\n\t\tif(xmlHttp.readyState===4){\n\t\t\tif(xmlHttp.status===200){\n\t\t\t\ttext = xmlHttp.responseText;\n\t\t\t\tloginMessage.innerHTML = text;\n\t\t\t}\n\t\t\telse\n\t\t\t\talert(xmlHttp.statusText);\n\t\t}\n\t}", "function checkConnection() {\n var status_div = document.querySelector('#connection_status');\n\n var loading = document.createElement('i'),\n url = '/dashboard/_load/ping.php';\n\n loading.className = 'fas fa-spinner fa-spin';\n status_div.appendChild(loading);\n\n fetch(url, {\n method: 'GET',\n credentials: 'same-origin',\n cache: 'default'\n })\n .then(response => {\n clearStatus(status_div);\n\n // status needed == 200\n if( response.status == 200 || response.status == 202 ) {\n serviceIsUp(status_div);\n } else {\n serviceIsDown(status_div);\n }\n\n status_div.innerHTML = `<small>${response.statusText}</small>`;\n })\n // connection errors\n .catch(err => {\n clearStatus(status_div);\n serviceIsDown(status_div);\n status_div.innerHTML = `<small>Unreachable</small>`;\n console.error(err);\n });\n}", "function checkConnection(){\n viewModel.notOnline(!navigator.onLine);\n // requests next check in 500 ms\n setTimeout(checkConnection, 500);\n}", "function hasStarted() {\n return window.location.href.indexOf(\"http://www3.nhk.or.jp/\") > -1; \n}", "function checkSetupRan () {\n fs.readFile(CONFIG_PATH, 'utf8', function (err, data) {\n if (err) console.error(err)\n if (data.indexOf(REPLACE_CORDOVA_NAME) >= 0) {\n getCordovaName()\n } else {\n console.log('Setup script was already run. Doing nothing.')\n }\n })\n}", "function noInstallStatus () { // Timeout, we will never get the install event, assume justInstalled = false\r\n console.log(\"No install event\");\r\n getInstallStatusTimerID = undefined;\r\n justInstalled = false;\r\n gis_resolve(justInstalled);\r\n}", "static async isRunning() {\n return await ForegroundServiceModule.isRunning();\n }", "function checkServerDelayed() {\n\n // Check that we're not already waiting for something\n if (waitingForServer)\n return;\n \n // Mark that we're checking the server\n waitingForServer = true;\n\n // Hide our elements and show the initial placeholder\n indexElements.serviceTableBody.hide();\n indexElements.servicePlaceholder.hide();\n indexElements.servicePlaceholderInitial.show();\n\n setTimeout(checkServer, 1000);\n}", "async function checkUpdate(){\r\n\r\n var fileContents = Fs.readFileSync(__dirname+'/package.json');\r\n var pkg = JSON.parse(fileContents);\r\n\tpkg['name'] = PACKAGE_TO_UPDATE;\r\n\tpkg['version'] = pkg['dependencies'][PACKAGE_TO_UPDATE];\r\n\tif(isNaN(pkg['version'].substr(0,1))){\r\n\t\t//exemple: ^0.3.1\r\n\t\tpkg['version'] = pkg['version'].substr(1);\r\n\t}\r\n\r\n\tconst update = new AutoUpdate(pkg);\r\n\tupdate.on('update', function(){\r\n\t\tconsole.log('started update')\r\n\t\tif(app){\r\n\t\t\tconsole.log('[lanSupervLauncher] stopApplication');\r\n\t\t\tapp.stopApplication();\r\n\t\t\tapp = null;\r\n\t\t}\r\n\t});\r\n\tupdate.on('ready', function(){\r\n\t\tconsole.log('[lanSupervLauncher] ready (updated or not !)');\r\n\t\t//3) (Re)launch application\r\n\t\tif(app===null){\r\n\t\t\tconsole.log('[lanSupervLauncher] startApplication');\r\n\t\t\tapp = new LanSuperv();\r\n\t\t\tvar ConfigFile = __dirname + '/config.js';\r\n\t\t\tapp.startApplication(ConfigFile);\r\n\t\t\t//(initial launch or relaunch after update)\r\n\t\t}\r\n\t});\r\n\r\n}", "function check_iconnection() {\n\n\n if (navigator.onLine) {\n\n\n } else {\n toaster(\"No Internet connection\");\n }\n}", "function check_iconnection() {\n\n\n if (navigator.onLine) {\n\n\n } else {\n toaster(\"No Internet connection\");\n }\n}", "function isOnline() {\n var online = true;\n\n if (typeof window !== 'undefined' && 'navigator' in window && window.navigator.onLine === false) {\n online = false;\n }\n\n return online;\n}", "function ArduinoUDPServerIsListening() {\n\tlet address = arduinoUDPServer.address();\n\tconsole.log('Arduino UDP Server is listening at: '+ address.address + \":\" + address.port);\n}", "check_admin_status() {}", "function checkStatus() {\n\n }", "function checkForUpdate() {\n superagent.get(packageJson).end((error, response) => {\n if (error) return;\n const actualVersion = JSON.parse(response.text).version; // TODO: case without internet connection\n console.log('Actual app version: ' + actualVersion + '. Current app version: ' + currentVersion);\n if (semver.gt(actualVersion, currentVersion)) {\n mb.window.webContents.send('update-available');\n console.log('New version is available!');\n }\n });\n}", "function isPlatformServer(platformId){return platformId===PLATFORM_SERVER_ID;}", "get is_idle() {\n\t\treturn this.req_queue.length == 0 && Object.keys(this.req_map).length == 0;\n\t}", "function checkIfMongos() {\n const res = db.serverStatus();\n assert(res, \"The serverStatus command failed\");\n assert(res.hasOwnProperty(\"ok\"), \"The ok field is not present\");\n assert.eq(1, res.ok, \"Failed to run serverStatus command\");\n assert(res.hasOwnProperty(\"process\"), \"The process field is not present\");\n assert.neq(\"mongos\", res.process, \"Mongos detected but this script is not meant to be run on a mongos\");\n }", "function checkAlive() {\n for(var i = 0; i < pingSet.length; i++) {\n var ip = pingSet[i];\n setTimeout(pingHost(ip), 1000);\n }\n}", "isAvailable () {\n const lessThanOneHourAgo = (date) => {\n const HOUR = 1000 * 60 * 60;\n const anHourAgo = Date.now() - HOUR;\n\n return date > anHourAgo;\n }\n\n return this.socket !== null || (this.lastSeen !== null && lessThanOneHourAgo(this.lastSeen))\n }", "function checkConnectionStatus() {\n if (!client.isConnected()) {\n connect();\n }\n}", "checkConnection() {\n var client = navigator;\n var container = this.component;\n\n if (!client.online) {\n\n container.show();\n\n container.html('<p>You are currently on any internet connection find a connection and try again</p>');\n\n } else{\n container.hide();\n }\n }", "function checkIfLiveCSRS() {\n const res = db.serverCmdLineOpts();\n assert(res, \"The serverCmdLineOpts command failed\");\n assert(res.hasOwnProperty(\"ok\"), \"The ok field is not present\");\n assert.eq(1, res.ok, \"Failed to obtain the startup configuration parameters\");\n assert(res.hasOwnProperty(\"parsed\"), \"The parsed field is not present\");\n assert(!res.parsed.hasOwnProperty(\"sharding\"), \"This server is running with sharding enabled. The CSRS should be running in standalone or non-configsvr replica set mode for the script to work\");\n }", "function check_app_jobs(username,app_id, app_status)\n{\n app_timer = setInterval(function() {\n if((app_timer !=\"stop\")&&(app_status != 'completed')) check_for_app_finished_job(username,app_id);\n },3000);\n}", "function reqTimeout () {\n\t\tapp.onStatus(\"Checking for update... Oups!\");\n\t\tapp.onOpen(appUrl);\n\t}", "function main()\n{\n\t//Gets the current address (location):\n\tCB_Elements.insertContentById(\"location_current\", CB_Client.getLocation());\n\tCB_Elements.insertContentById(\"location_current_no_file\", CB_Client.getLocationWithoutFile());\n\t\n\t//Tells whether it is running locally (using the \"file:\" protocol):\n\tCB_Elements.insertContentById(\"running_locally\", CB_Client.isRunningLocally() ? \"Yes\" : \"No\");\n}", "function checkWeb3(){\n // Set the connect status on the app\n if (web3 && web3.isConnected()) {\n console.info('Connected');\n $('#no_status').text(\"Conectado\");\n // Set version\n setWeb3Version();\n checkNodeStatus();\n } else {\n console.info('Not Connected');\n $('#no_status').text(\"Desconectado\");\n }\n}", "function isOnline() {\r\n return window.navigator.onLine;\r\n}", "async isConnected(req){\n if(await this.isMetamaskInstalled()){\n await this.injectWeb3();\n }else{\n await this.installMetamaskPrompt();\n }\n }", "function checkExitURLStatus() {\n\n }", "static isAvailable() {\n\n // Check if we have an install lock present.\n if (process.env.TALK_INSTALL_LOCK === 'TRUE') {\n return Promise.reject(errors.ErrInstallLock);\n }\n\n // Get the current settings, we are expecing an error here.\n return SettingsService\n .retrieve()\n .then(() => {\n\n // We should NOT have gotten a settings object, this means that the\n // application is already setup. Error out here.\n return Promise.reject(errors.ErrSettingsInit);\n\n })\n .catch((err) => {\n\n // If the error is `not init`, then we're good, otherwise, it's something\n // else.\n if (err !== errors.ErrSettingsNotInit) {\n return Promise.reject(err);\n }\n\n // Allow the request to keep going here.\n return;\n });\n }", "function _checkForAppController(req, res, params) {\n\tvar path = 'app/public/server-remote-web/scripts/apps/' + params.view + '/app.js';\n\tfs.exists(path, function(exists) {\n\t\tif (exists) {\n\t\t\tparams.app = 'scripts/apps/' + params.view + '/app';\n\t\t}\n\t\t_getUserDisplayName(req, res, params);\n\t});\t\n}", "function botIsAlone() {\r\n let currentChannel = backend.getCurrentChannel();\r\n let clients = currentChannel ? currentChannel.getClientCount() : 0;\r\n return (clients <= 1) \r\n }", "function isSomRunning() {\n return isRunning;\n}", "async function pnSubscribed() {\r\n var swReg;\r\n if (pnAvailable()) {\r\n swReg = await navigator.serviceWorker.getRegistration();\r\n }\r\n return (swReg !== undefined);\r\n}", "readyCheck(vcList) {\n const botUsers = vcList.filter(vcUser => vcUser.user.bot === true); \n const isEveryoneReady = (vcList.size <= this.readyCollection.size + this.skipCollection.size + botUsers.size);\n return isEveryoneReady;\n }", "function checkServerTimeout()\n{\n\t// Checking server performance\n\tvar receivedDataDelay = (Date.now() - lastPacketReceived) / 1000.0;\n\tif (receivedDataDelay > lagReloadDelay) \n\t{\n\t\tconsole.log(\"things might be a little slow: \" + receivedDataDelay);\n\t\tpostWarningMessage(\"red\", \"things might be a little slow: \" + receivedDataDelay);\n\t\tlastPacketReceived = Date.now() + (lagReloadRetry*1000); // add 10 sec before running this reconnect/reset again\n\t\t\n\t\t//reconnectToServerNode();\n\t\t\n\t\t//location.reload(false);\n\t\t//loadNewGameSessionData();\n\t\t//console.log(\"RELOADED PAGE\");\n\t\t\n\t\tif (reloadOnServerTimeout) {\n\t\t\twindow.location=\"http://sandbox-dane.rhcloud.com/games/voidpirates?autostart=1\";\n\t\t}\n\t}\n}", "'starting up server'(){\n console.log(this.name+' is starting up...');\n }", "async getServerStatus(req, res, next) {\r\n\t\ttry {\r\n\t\t\tres.locals.serverStatus = await helpers.getStatus();\r\n\t\t\tnext();\r\n\t\t} catch (error) {\r\n\t\t\thelpers.submitError('helper.getServerStatus', error);\r\n\t\t\tres.locals.serverStatus = false;\r\n\t\t\tnext();\r\n\t\t}\r\n\t}", "function checkIfDB() {\n\t\n\tsqlConnect.query(\n\t\t'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = \"bamazon\"',\n\n\t\tfunction (err, res) {\n\t\t\tif (err) throw err;\n\n\t\t\tif (!res[0]) {\n\t\t\t\tcreateDB();\n\t\t\t}\n\n\t\t\telse {\n\t\t\t\tdisplayInventory();\n\t\t\t}\n\t\t}\n\t);\n}", "function updateready_ques_(applicationCacheStatus) /* (applicationCacheStatus : applicationCacheStatus) -> bool */ {\n return (applicationCacheStatus === 5);\n}", "function updateServerStatus(status, info) {\n\n\t\tif (status) {\n\n\t\t\tdocument.querySelector('#ojd-server-status').classList.remove('ojd-status-bad');\n\t\t\tdocument.querySelector('#ojd-server-status').classList.add('ojd-status-good');\n\t\t\tdocument.querySelector('#ojd-server-status .ojd-indicator-text').innerHTML = `Server Started`;\n\n\t\t\tconst urls = [];\n\t\t\tconst ifaces = os.networkInterfaces();\n\t\t\tObject.keys(ifaces).forEach(function (ifname) {\n\t\t\t\tiface = ifaces[ifname];\n\t\t\t\tfor (const net of iface) {\n\t\t\t\t\tif (net.address !== '127.0.0.1' && net.address !== '::1') {\n\t\t\t\t\t\tif (net.family === 'IPv4') {\n\t\t\t\t\t\t\turls.push(`${net.address}:${info.port}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (urls.length === 0) {\n\t\t\t\turls.push(`127.0.0.1:${info.port}`);\n\t\t\t}\n\n\t\t\tconst elementList = document.querySelector('#ojd-server-address ul');\n\t\t\telementList.innerHTML = \"\";\n\n\t\t\tfor (const url of urls) {\n\t\t\t\tconst li = document.createElement('li');\n\t\t\t\tli.innerHTML = url;\n\t\t\t\telementList.appendChild(li);\n\t\t\t}\n\n\t\t\tdocument.querySelector('#ojd-server-address').style['display'] = 'block';\n\n\t\t} else {\n\t\t\tdocument.querySelector('#ojd-server-status').classList.remove('ojd-status-good');\n\t\t\tdocument.querySelector('.ojd-status-server').classList.add('ojd-status-bad');\n\t\t\tdocument.querySelector('#ojd-server-status .ojd-indicator-text').innerHTML = 'Server Not Started';\n\t\t}\n\t}", "function checkstatus()\n\t{\n\t\tif(disconnectwarned || !AjaxLife.Network.Connected) return;\n\t\tvar now = new Date();\n\t\tif(!now.getTime() - lastmessage.getTime() > 60000)\n\t\t{\n\t\t\tdisconnectwarned = true;\n\t\t\talert(\"No data has been received for over a minute. You may have been disconnected.\");\n\t\t}\n\t}", "function checkConnection() {\n\t if (!window.tronWeb) {\n\t $('#connection-status').html('Not Connected to Tron');\n\t return false;\n\t }\n\t if (!window.tronWeb.defaultAddress.base58) {\n\t $('#connection-status').html('Not Connected to Tron');\n\t return false;\n\t }\n\t $('#connection-status').html('Connected to Tron');\n\t return true;\n\t}", "function checkBridgeUserExistance(ip, username) {\n var userExists = false;\n $.ajax({\n url: \"http://\" + ip + \"/api/\" + username + \"/\",\n async: false\n }).done(function(data) {\n if (data.config !== undefined) {\n userExists = true;\n } \n });\n return userExists;\n}", "function checkForGlobalGame(callback) {\n delayedCheck(\"script[src*='socket']\", callback);\n}", "checkMachineReady(){\n\t\tvar machineReady = new Promise((resolve, reject) => {\n\t\t setTimeout(() => {\n\t\t\t if (this.apiReady) {\n\t\t\t\tresolve(true);\n\t\t\t }else if (!this.apiReady) {\n\t\t\t\t reject(false)\n\t\t\t }\n\t\t }, 3000);\n\t\t}); \n\t\t\n\t\treturn Promise.resolve(machineReady);\n\t}", "function checkFirstRun () {\r\n\tvar localVersion = us_getValue(\"us_local_version\", 0);\r\n\tif (localVersion == 0) {\r\n\t\tus_showBox();\r\n\t\tvar cont = '<div id=\"us_loginbox_form\">'+\r\n\t\t'<h4>Welcome to YouScrobbler!</h4><br/>'+\r\n\t\t'<span>Join the <a target=\"_blank\" href=\"http://www.last.fm/group/YouScrobbler\">Last.fm Group</a> to stay up to date.</span><br/><br/>'+\r\n\t\t'<span>Description and documentation can be found on the <a target=\"_blank\" href=\"http://www.lukash.de/youscrobbler\">Homepage</a>.</span><br/><br/>'+\r\n\t\t'</div><div class=\"us_submitbuttons\"><input id=\"us_submit\" value=\"Next\" type=\"submit\" /></div>';\r\n\t\tus_boxcontent('First Run',cont);\r\n\t\tdocument.getElementById('us_submit').addEventListener('click', us_showBox, false);\r\n\t\tus_saveValue(\"us_local_version\", VERSION);\r\n\t} else if (localVersion < VERSION) {\r\n\t\tus_showBox();\r\n\t\tvar cont = '<div id=\"us_loginbox_form\">'+\r\n\t\t'<div class=\"us_done\">YouScrobbler was updated succesfully to Version '+VERSION+'.</div><br/>'+\r\n\t\t'<span>Changelog can be found on the <a target=\"_blank\" href=\"http://www.lukash.de/youscrobbler\">Homepage</a>.</span><br/>'+\r\n\t\t'<br/>'+\r\n\t\t'<br/>'+\r\n\t\t'<h4>Join the <a target=\"_blank\" href=\"http://www.last.fm/group/YouScrobbler\" title=\"Last.fm Group\">Last.fm Group</a> to stay tuned</h4>'+\r\n\t\t'<br /></div><div class=\"us_submitbuttons\"><input id=\"us_submit\" value=\"Close\" type=\"submit\" /></div>';\r\n\t\tus_boxcontent('Succesfully Updated',cont);\r\n\t\tdocument.getElementById('us_submit').addEventListener('click', us_closebox, false);\r\n\t\tus_saveValue(\"us_local_version\", VERSION);\r\n\t}\r\n}", "function work_available(client, data) {\n if(client.type === \"worker\") {\n console.log(\"worker \"+client.worker+\" asked if work is available\");\n }\n}", "function checkServerTime () {\n $q.all([getEndBackendTime(),getServerTime()])\n .then(function (){\n var duration = self.endBackendTime - self.currentBackendTime;\n if ( duration <= 0 ){\n finishTest();\n }\n });\n }", "function checkEveryoneIsReady(players) {\n return (countReadyPlayers(players) > 5) ? true : false\n}", "get isSingleApp() {\n return !this.applications || this._appsLength < 2;\n }", "requestCrostiniInstallerStatus() {}", "function online() {\n\tif (!(isMobile.any()))\n\t\treturn true;\n\n if (typeof(navigator)!='object' || typeof(navigator.connection)!='object')\n\t return false;\n\t\t\n\tvar networkState = navigator.connection.type;\n\n\tvar states = {};\n\tstates[Connection.UNKNOWN] = 'Unknown connection';\n\tstates[Connection.ETHERNET] = 'Ethernet connection';\n\tstates[Connection.WIFI] = 'WiFi connection';\n\tstates[Connection.CELL_2G] = 'Cell 2G connection';\n\tstates[Connection.CELL_3G] = 'Cell 3G connection';\n\tstates[Connection.CELL_4G] = 'Cell 4G connection';\n\tstates[Connection.CELL] = 'Cell generic connection';\n\tstates[Connection.NONE] = 'No network connection';\n\n\tif (states[networkState] == 'No network connection') {\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}", "function checkIfOnlineUntilWeAre() {\n if (!navigator.onLine) {\n setTimeout(checkIfOnlineUntilWeAre.bind(this), 3000)\n } else {\n this.$apollo.skipAll = false\n }\n}" ]
[ "0.6616564", "0.65891254", "0.65401095", "0.6455398", "0.6387666", "0.62745297", "0.6234303", "0.6193202", "0.6179587", "0.6148485", "0.6120712", "0.6115703", "0.6038705", "0.60366625", "0.602341", "0.6019539", "0.5993458", "0.59888405", "0.5969588", "0.5947656", "0.5941883", "0.5901731", "0.5899415", "0.58852845", "0.5879787", "0.5865981", "0.5856243", "0.5832167", "0.5808407", "0.5806771", "0.57997155", "0.5785982", "0.57691747", "0.5768165", "0.5763078", "0.57553923", "0.5745486", "0.5745007", "0.5738385", "0.57323134", "0.5720035", "0.5705535", "0.56908286", "0.569002", "0.56844467", "0.56643254", "0.5663142", "0.56516194", "0.5628116", "0.56261075", "0.5619587", "0.56159407", "0.5604336", "0.56001955", "0.56001955", "0.5590553", "0.5583182", "0.55614185", "0.5558378", "0.5546053", "0.5541194", "0.553595", "0.55013084", "0.5491548", "0.5483088", "0.5481906", "0.54813945", "0.5478123", "0.54709727", "0.54703414", "0.54674846", "0.5466034", "0.5465627", "0.5454143", "0.54529965", "0.5450458", "0.5446126", "0.5445327", "0.5444685", "0.54425925", "0.5440333", "0.54403085", "0.5435822", "0.5433917", "0.542949", "0.5423943", "0.5422452", "0.5421944", "0.541922", "0.54185313", "0.5413739", "0.5410733", "0.5400831", "0.54000276", "0.53851295", "0.5371644", "0.53686494", "0.53670424", "0.53617704", "0.5360432" ]
0.7513655
0
END OF Misc Code START OF UpdateStats Code
function init_user_account_sites_entry() { var uas_entry = {}; uas_entry.num_logins = 0; uas_entry.pwd_unchanged_duration = 0; uas_entry.pwd_stored_in_browser = 'donno'; uas_entry.num_logouts = 0; uas_entry.latest_login = 0; //Specifically naming it with prefix "my_" because it was //creating confusion with current_report.pwd_groups (Notice 's' at the end) uas_entry.my_pwd_group = 'no group'; uas_entry.tts = 0; uas_entry.tts_login = 0; uas_entry.tts_logout = 0; uas_entry.site_category = 'unclassified'; return uas_entry; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateStats()\n{\n updateGoalAttempts();\n updateShotsOnGoal();\n updateShotsOffGoal();\n updateBlockedShots();\n updateCorners();\n updateOffsides();\n updateGKSaves();\n updateFoulsCommited();\n updateFoulsReceived();\n\n updateCompletePasses();\n updateIncompletePasses();\n updateTotalPasses();\n\n updateThrows();\n}", "updateStats() {\n if (this.status === 0 || !this.dealtIn) {\n this.nvpip = 0;\n this.npfr = 0;\n this.n3bet = 0;\n this.nhands = 0;\n }\n else if (this.status === 1) {\n this.nvpip += this._vpip;\n this.npfr += this._pfr;\n this.n3bet += this._3bet;\n this.nhands += 1;\n }\n \n this._vpip = 0;\n this._pfr = 0;\n this._3bet = 0;\n }", "function updateAllStats(){\n wantedLevelChange()\n updateMaxHeld()\n}", "function updateStats()\n{\n\tvar element;\n\telement = document.getElementById(\"score\");\n\telement.firstChild.nodeValue = \"Score: \" + score;\n\telement = document.getElementById(\"completion\");\n\telement.firstChild.nodeValue = \"Completion: \" + blocksDestroyed + \"/\" + numBlocks;\n}", "function statUpdateTick() {\n updateCurrentStats();\n }", "function update_stats() {\n\t\t\t// get time delta if not specified\n\t\t\tif (dtime === undefined) {\n\t\t\t\tvar old = medeactx.time;\n\t\t\t\tmedeactx.time = Date.now() * 0.001;\n\n\t\t\t\tdtime = medeactx.time - old;\n\t\t\t}\n\n\t\t\t// check if the canvas sized changed\n\t\t\tif(medeactx.cached_cw != medeactx.canvas.width) {\n\t\t\t\tmedeactx.cached_cw = medeactx.canvas.width;\n\t\t\t\tmedeactx.frame_flags |= medeactx.FRAME_CANVAS_SIZE_CHANGED;\n\t\t\t}\n\t\t\tif(medeactx.cached_ch != medeactx.canvas.height) {\n\t\t\t\tmedeactx.cached_ch = medeactx.canvas.height;\n\t\t\t\tmedeactx.frame_flags |= medeactx.FRAME_CANVAS_SIZE_CHANGED;\n\t\t\t}\n\n\t\t\tmedeactx._UpdateFrameStatistics(dtime);\n\t\t}", "updateStats() {\n if (this.visualize) {\n var ncount = document.getElementById(\"ncount\");\n ncount.innerHTML = \"Neutron count: \" + this.neutrons.length;\n\n var meanHeat = document.getElementById(\"meanHeat\");\n meanHeat.innerHTML = \"Mean heat: \" + this.getMeanHeat();\n }\n }", "function updateStats(mx,cd, jmx, jbd, jdx, jdd, cgx, cgd, rbx, rbd, adx, add){\n var csContent =\"<b>Most Dupe with \" + mx + \":</b><br>\";\n for(i in cd){\n csContent += cd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Jonny Most Dupe with \" + jmx + \":</b><br>\";\n for(i in jbd){\n csContent += jbd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>JD Most Dupe with \" + jdx + \":</b><br>\";\n for(i in jdd){\n csContent += jdd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Chris Most Dupe with \" + cgx + \":</b><br>\";\n for(i in cgd){\n csContent += cgd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Richard Most Dupe with \" + rbx + \":</b><br>\";\n for(i in rbd){\n csContent += rbd[i] + \"<br>\";\n }\n csContent +=\"<p><b>Andy Most Dupe with \" + adx + \":</b><br>\";\n for(i in add){\n csContent += add[i] + \"<br>\";\n }\n\n document.getElementById('theStatArea').innerHTML = csContent;\n\n\n\n\n }", "function updateStats(ui, stats) {\n ui.headMovements.text('Track Movement: ' + stats.trackMovement);\n ui.averageTime.text('Average Wait Time: ' + Math.round(stats.averageWait));\n}", "function updateStats() {\n\t\n\tFFXIV_HPPercent = document.querySelector(\"#hp_percent\").textContent;\n\tFFXIV_MPPercent = document.querySelector(\"#mp_percent\").textContent;\n\tFFXIV_TPPercent = document.querySelector(\"#tp_percent\").textContent;\n\tFFXIV_HPCurrent = document.querySelector(\"#hp_current\").textContent;\n\tFFXIV_MPCurrent = document.querySelector(\"#mp_current\").textContent;\n\tFFXIV_TPCurrent = document.querySelector(\"#tp_current\").textContent;\n\tFFXIV_HPMax = document.querySelector(\"#hp_max\").textContent;\n\tFFXIV_MPMax = document.querySelector(\"#mp_max\").textContent;\n\tFFXIV_TPMax = \"1000\";\n\tFFXIV_HudType = document.querySelector(\"#hud_type\").textContent;\n\tFFXIV_Location = document.querySelector(\"#current_location\").textContent;\n\tFFXIV_HudMode = document.querySelector(\"#hud_mode\").textContent;\n\tFFXIV_TargetHPPercent = document.querySelector(\"#target_hppercent\").textContent;\n\tFFXIV_TargetHPCurrent = document.querySelector(\"#target_hpcurrent\").textContent;\n\tFFXIV_TargetHPMax = document.querySelector(\"#target_hpmax\").textContent;\n\tFFXIV_TargetName = document.querySelector(\"#target_name\").textContent;\n\tFFXIV_TargetEngaged = document.querySelector(\"#target_engaged\").textContent;\n\tFFXIV_PlayerPosX = document.querySelector(\"#playerposX\").textContent;\n\tFFXIV_PlayerPosY = document.querySelector(\"#playerposY\").textContent;\n\tFFXIV_PlayerPosZ = document.querySelector(\"#playerposZ\").textContent;\n\tFFXIV_ActionStatus = document.querySelector(\"#actionstatus\").textContent;\n\tFFXIV_CastPercent = document.querySelector(\"#castperc\").textContent;\n\tFFXIV_CastProgress = document.querySelector(\"#castprogress\").textContent;\n\tFFXIV_CastTime = document.querySelector(\"#casttime\").textContent;\n\tFFXIV_CastingToggle = document.querySelector(\"#castingtoggle\").textContent;\n\tFFXIV_HitboxRadius = document.querySelector(\"#hitboxrad\").textContent;\n\tFFXIV_PlayerClaimed = document.querySelector(\"#playerclaimed\").textContent;\n\tFFXIV_PlayerJob = document.querySelector(\"#playerjob\").textContent;\n\tFFXIV_MapID = document.querySelector(\"#mapid\").textContent;\n\tFFXIV_MapIndex = document.querySelector(\"#mapindex\").textContent;\n\tFFXIV_MapTerritory = document.querySelector(\"#mapterritory\").textContent;\n\tFFXIV_PlayerName = $(\"#playername\").text();\n\tFFXIV_TargetType = document.querySelector(\"#targettype\").textContent;\n\t\n\t//document.querySelector(\"#debug1\").textContent = \"Increment: \" + i;\n\t//$(\"#debug1\").text(\"Increment: \" + i);\n\t//i++;\n\t/*\n\tvar FFXIV = {\n \tHPPercent:FFXIV_HPPercent,\n\t\tMPPercent:FFXIV_MPPercent,\n\t\tTPPercent:FFXIV_TPPercent,\n\t\tHPCurrent:FFXIV_HPCurrent,\n\t\tMPCurrent:FFXIV_MPCurrent,\n\t\tTPCurrent:FFXIV_TPCurrent,\n\t\tHPMax:FFXIV_HPMax,\n\t\tMPMax:FFXIV_MPMax,\n\t\tTPMax:FFXIV_TPMax,\n\t\tHudType:FFXIV_HudType,\n\t\tLocation:FFXIV_Location,\n\t\tHudMode:FFXIV_HudMode,\n\t\tTargetHPPercent:FFXIV_TargetHPPercent,\n\t\tTargetHPCurrent:FFXIV_TargetHPCurrent,\n\t\tTargetHPMax:FFXIV_TargetHPMax,\n\t\tTargetName:FFXIV_TargetName,\n\t\tTargetEngaged:FFXIV_TargetEngaged,\n\t\tPlayerPosX:FFXIV_PlayerPosX,\n\t\tPlayerPosY:FFXIV_PlayerPosY,\n\t\tPlayerPosZ:FFXIV_PlayerPosZ,\n\t\tActionStatus:FFXIV_ActionStatus,\n\t\tCastPercent:FFXIV_CastPercent,\n\t\tCastProgress:FFXIV_CastProgress,\n\t\tCastTime:FFXIV_CastTime,\n\t\tCastingToggle:FFXIV_CastingToggle,\n\t\tHitboxRadius:FFXIV_HitboxRadius,\n\t\tPlayerClaimed:FFXIV_PlayerClaimed,\n\t\tPlayerJob:FFXIV_PlayerJob,\n\t\tMapID:FFXIV_MapID,\n\t\tMapIndex:FFXIV_MapIndex,\n\t\tMapTerritory:FFXIV_MapTerritory,\n\t\tPlayerName:FFXIV_PlayerName,\n\t\tTargetType:FFXIV_TargetType\n\t};\n\t*/\n\t/*\n\tFFXIV_HPPercent = document.querySelector(\"#hp_percent\").textContent;\n\tFFXIV_MPPercent = document.querySelector(\"#mp_percent\").textContent;\n\tFFXIV_TPPercent = document.querySelector(\"#tp_percent\").textContent;\n\tFFXIV_HPCurrent = document.querySelector(\"#hp_current\").textContent;\n\tFFXIV_MPCurrent = document.querySelector(\"#mp_current\").textContent;\n\tFFXIV_TPCurrent = document.querySelector(\"#tp_current\").textContent;\n\tFFXIV_HPMax = document.querySelector(\"#hp_max\").textContent;\n\tFFXIV_MPMax = document.querySelector(\"#mp_max\").textContent;\n\tFFXIV_TPMax = \"1000\";\n\tFFXIV_HudType = document.querySelector(\"#hud_type\").textContent;\n\tFFXIV_Location = document.querySelector(\"#current_location\").textContent;\n\tFFXIV_HudMode = document.querySelector(\"#hud_mode\").textContent;\n\tFFXIV_TargetHPPercent = document.querySelector(\"#target_hppercent\").textContent;\n\tFFXIV_TargetHPCurrent = document.querySelector(\"#target_hpcurrent\").textContent;\n\tFFXIV_TargetHPMax = document.querySelector(\"#target_hpmax\").textContent;\n\tFFXIV_TargetName = document.querySelector(\"#target_name\").textContent;\n\tFFXIV_TargetEngaged = document.querySelector(\"#target_engaged\").textContent;\n\tFFXIV_PlayerPosX = document.querySelector(\"#playerposX\").textContent;\n\tFFXIV_PlayerPosY = document.querySelector(\"#playerposY\").textContent;\n\tFFXIV_PlayerPosZ = document.querySelector(\"#playerposZ\").textContent;\n\tFFXIV_ActionStatus = document.querySelector(\"#actionstatus\").textContent;\n\tFFXIV_CastPercent = document.querySelector(\"#castperc\").textContent;\n\tFFXIV_CastProgress = document.querySelector(\"#castprogress\").textContent;\n\tFFXIV_CastTime = document.querySelector(\"#casttime\").textContent;\n\tFFXIV_CastingToggle = document.querySelector(\"#castingtoggle\").textContent;\n\tFFXIV_HitboxRadius = document.querySelector(\"#hitboxrad\").textContent;\n\tFFXIV_PlayerClaimed = document.querySelector(\"#playerclaimed\").textContent;\n\tFFXIV_PlayerJob = document.querySelector(\"#playerjob\").textContent;\n\tFFXIV_MapID = document.querySelector(\"#mapid\").textContent;\n\tFFXIV_MapIndex = document.querySelector(\"#mapindex\").textContent;\n\tFFXIV_MapTerritory = document.querySelector(\"#mapterritory\").textContent;\n\tFFXIV_PlayerName = document.querySelector(\"#playername\").textContent;\n\tFFXIV_TargetType = document.querySelector(\"#targettype\").textContent;\n\t*/\n}", "function updateStats() {\n\t$(\"#stats\").text(JSON.stringify(ozpIwc.metrics.toJson(),null,2));\n}", "function updateStats() {\n\n\tvar queries = [\n\t\t{ k: \"world\", t: \"World\", q: \"\" },\n\t\t{ k: \"male\", t: \"Male\", q: \"gender=1\" },\n\t\t{ k: \"female\", t: \"Female\", q: \"gender=2\" },\n\t\t{ k: \"age1\", t: \"≤34\", q: \"age_ub=34\" },\n\t\t{ k: \"age2\", t: \"35-54\", q: \"age_lb=35&age_ub=54\" },\n\t\t{ k: \"age3\", t: \"≥55\", q: \"age_lb=55\" },\n\t\t{ k: \"hdi1\", t: \"Low\", q: \"hdi=1\" },\n\t\t{ k: \"hdi2\", t: \"Medium\", q: \"hdi=2\" },\n\t\t{ k: \"hdi3\", t: \"High\", q: \"hdi=3\" },\n\t\t{ k: \"hdi4\", t: \"Very High\", q: \"hdi=4\" }\n\t];\n\n\tfor(var i in queries) {\n\t\tvar query = queries[i];\n\t\tgetData(\"normal\", { \"table\": \"segment\", \"query\": query }, function(r, options) {\n\t\t\tdata.segments[options.query.k] = {\n\t\t\t\tid: options.query.k,\n\t\t\t\ttitle: options.query.t,\n\t\t\t\tvalues: r\n\t\t\t};\n\t\t});\n\t}\n\n}", "function updateStats() {\n let contents = \"Restarts: \" + restarts;\n $(\"#restarts\").text(contents);\n\n contents = \"Endings: \" + endings.length + \"/\" + TOTAL_ENDINGS;\n $(\"#totalEndings\").text(contents);\n}", "UpdateMetrics() {\n }", "setStats( stats ) {\n var now = performance.now();\n this.totalHashes += stats.hashes;\n if(this.prevStatTime) {\n var delta = now-this.prevStatTime;\n this.hashrate = 1000 * stats.hashes / delta;\n }\n this.prevStatTime = now;\n }", "increaseStat() {}", "function updateStats() {\n const total_cases = cases_list[cases_list.length - 1];\n const new_confirmed_cases = total_cases - cases_list[cases_list.length - 2];\n\n const total_recovered = recovered_list[recovered_list.length - 1];\n const new_recovered_cases = total_recovered - recovered_list[recovered_list.length - 2];\n\n const total_deaths = deaths_list[deaths_list.length - 1];\n const new_deaths_cases = total_deaths - deaths_list[deaths_list.length - 2];\n\n const active_cases = total_cases - total_recovered - total_deaths;\n\n total_cases_element.innerHTML = total_cases;\n new_cases_element.innerHTML = `+${new_confirmed_cases}`;\n recovered_element.innerHTML = total_recovered;\n new_recovered_element.innerHTML = `+${new_recovered_cases}`;\n deaths_element.innerHTML = total_deaths;\n new_deaths_element.innerHTML = `+${new_deaths_cases}`;\n\n active_element.innerHTML = active_cases;\n\n}", "function updateStats(){\r\n $(\" #correct-counter \").text(roundStats.correct);\r\n $(\" #incorrect-counter \").text(roundStats.incorrect);\r\n \r\n }", "function updateStats (stats, dim, name, value) {\r\n if (stats[dim][name] === undefined) {\r\n // if not yet seen, give it a fresh new stats object\r\n // NOTE an stdev field will be added to this object during final\r\n // calculations\r\n stats[dim][name] = {\r\n min: value, // helps to find most negative z-score\r\n max: value, // helps to find most positive z-score\r\n mean: 0, // used in calculating standard deviation/z-scores\r\n meanOfSquares: 0 // used in calculating standard deviation\r\n };\r\n }\r\n\r\n stats[dim][name].min = Math.min(stats[dim][name].min, value);\r\n stats[dim][name].max = Math.max(stats[dim][name].max, value);\r\n stats[dim][name].mean += value; // this will be averaged later\r\n stats[dim][name].meanOfSquares += value * value; // averaged later\r\n }", "function updateStats() {\n numOfCookiesElm.innerHTML = Math.floor(cookies) + \" cookies\";\n scoreElm.innerHTML = \"Score: \" + Math.floor(score);\n cookiesPerSecElm.innerHTML = cps + \" per second\";\n}", "function updateStats() {\n $(\"#number-to-guess\").text(targetNumber);\n $(\"#user-score\").text(userScore);\n $(\"#wins\").text(wins);\n $(\"#losses\").text(losses);\n }", "function sendStats() {\n push('stats', {\n hits: hits,\n totalHits: totalHits,\n bytes: bytes,\n totalBytes: totalBytes,\n cost: cost,\n totalCost: totalCost,\n period: STATS_PERIOD,\n uptime: +(new Date) - startTime\n });\n\n hits = 0;\n bytes = 0;\n cost = 0;\n}", "async function updateStats() {\n const stats = await (await fetch( './getStats', { method: 'POST'} )).json();\n\n // fill in static routes\n fillElements( stats );\n\n // progress bar\n document.querySelector( '.progress .tabresult' ).style.width = (100 * stats.tables.result / stats.tables.total) + '%';\n document.querySelector( '.progress .taberror' ).style.width = (100 * stats.tables.error / stats.tables.total) + '%';\n const progressTitle = `Results: ${(100 * stats.tables.result / stats.tables.total).toFixed(2)}% | Errors: ${(100 * stats.tables.error / stats.tables.total).toFixed(2)}%`;\n ['.progress', '.progress .tabresult', '.progress .taberror']\n .forEach( (sel) => document.querySelector( sel ).setAttribute( 'title', progressTitle ) );\n\n // update file availability\n for( const link of [ 'results', 'errors' ] ) {\n if( stats.files[ link ] ) {\n els[ link ].classList.remove( 'disabled');\n els[ link ].setAttribute( 'href', els[ link ].dataset.href );\n } else {\n els[ link ].classList.remove( 'disabled');\n els[ link ].removeAttribute( 'href' );\n }\n }\n\n // checkmark for finished\n if( stats.tables.unfinished < 1 ) {\n document.querySelector( '.finishedFlag' ).classList.add( 'finished' );\n } else {\n document.querySelector( '.finishedFlag' ).classList.remove( 'finished' );\n }\n\n // enable/disable evaluation section\n document.querySelector('#eval').style.display = stats.hasEvaluation ? 'block' : 'none';\n document.querySelector('#analysis').style.display = stats.hasEvaluation ? 'block' : 'none';\n\n }", "function updateStats() {\n $(\"#fighterhealth\").text(\"HP:\\xa0\" + fighterHP);\n $(\"#defenderhealth\").text(\"HP:\\xa0\" + defenderHP);\n }", "function updateStats(gfc) {\n var gr, ch;\n assert(0 <= gfc.bitrate_index && gfc.bitrate_index < 16);\n assert(0 <= gfc.mode_ext && gfc.mode_ext < 4);\n\n /* count bitrate indices */\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][4]++;\n gfc.bitrate_stereoMode_Hist[15][4]++;\n\n /* count 'em for every mode extension in case of 2 channel encoding */\n if (gfc.channels_out == 2) {\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][gfc.mode_ext]++;\n gfc.bitrate_stereoMode_Hist[15][gfc.mode_ext]++;\n }\n for (gr = 0; gr < gfc.mode_gr; ++gr) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n var bt = gfc.l3_side.tt[gr][ch].block_type | 0;\n if (gfc.l3_side.tt[gr][ch].mixed_block_flag != 0)\n bt = 4;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][bt]++;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][5]++;\n gfc.bitrate_blockType_Hist[15][bt]++;\n gfc.bitrate_blockType_Hist[15][5]++;\n }\n }\n }", "function updateStats(gfc) {\n var gr, ch;\n assert(0 <= gfc.bitrate_index && gfc.bitrate_index < 16);\n assert(0 <= gfc.mode_ext && gfc.mode_ext < 4);\n\n /* count bitrate indices */\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][4]++;\n gfc.bitrate_stereoMode_Hist[15][4]++;\n\n /* count 'em for every mode extension in case of 2 channel encoding */\n if (gfc.channels_out == 2) {\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][gfc.mode_ext]++;\n gfc.bitrate_stereoMode_Hist[15][gfc.mode_ext]++;\n }\n for (gr = 0; gr < gfc.mode_gr; ++gr) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n var bt = gfc.l3_side.tt[gr][ch].block_type | 0;\n if (gfc.l3_side.tt[gr][ch].mixed_block_flag != 0)\n bt = 4;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][bt]++;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][5]++;\n gfc.bitrate_blockType_Hist[15][bt]++;\n gfc.bitrate_blockType_Hist[15][5]++;\n }\n }\n }", "function renderStats(stats) {\n const f = stats.updateFrequency;\n let onTimeRate = (stats.updates-stats.misses) / stats.updates;\n onTimeRate = (onTimeRate*100).toFixed(1) + \"%\";\n $g(\"total-listen\").innerText = secondsToHuman(stats.totalListen);\n $g(\"count\").innerText = stats.updates;\n $g(\"update-freq\").innerText = `Updates about every ${f === 1 ? 'day' : `${f} days`}`;\n $g(\"ontime-rate-label\").innerText = onTimeRate;\n $g(\"ontime-rate\").style.width = onTimeRate;\n $g(\"ontime-rate-inverse\").style.width = `calc(100% - ${onTimeRate})`;\n}", "function updateStats() {\n playerStats.innerText = \"Name: \" + player.name + \"\\n\";\n playerStats.innerText += \"Hp: \" + player.hp;\n playerMoney.innerText = player.money;\n $(\"#playDate\").text(\"Day: \" + player.day);\n $(\"#playerLoan\").text(\" Loan: \" + player.loan);\n}", "function updateStats() {\n var htmlString = \"\";\n htmlString += (\"<h1>\" + character.name + \"</h1>\");\n htmlString += (\"<h2 id='level'>Level \" + character.lvl + \"</h2>\");\n htmlString += (\"<p id='hp'>HP: \" + character.hp + \"/\" + character.maxhp + \"</p>\");\n htmlString += (\"<p id='xp'>XP: \" + character.xp + \"/\" + (character.lvl*character.lvl*150) + \"</p>\");\n htmlString += (\"<p id='energy'>Energy: \" + character.energy + \"/\" + character.maxenergy + \"</p>\");\n $('#stats').css('overflow-y', 'hidden');\n $('#stats').html(htmlString);\n }", "function update_metrics() {\n metric_signups();\n past_events();\n photos_count();\n upcoming_events();\n past_events_photos();\n avg_event_photos();\n revenue();\n}", "update() {\n this.emit('fetch');\n if (this.guilds > 0 && this.users > 0) {\n if (!config.beta) {\n dogstatsd.gauge('musicbot.guilds', this.guilds);\n dogstatsd.gauge('musicbot.users', this.users);\n }\n let requestOptions = {\n headers: {\n Authorization: config.discord_bots_token\n },\n url: `https://bots.discord.pw/api/bots/${config.bot_id}/stats`,\n method: 'POST',\n json: {\n 'server_count': this.guilds\n }\n };\n request(requestOptions, (err, response, body) => {\n if (err) {\n return this.emit('error', err);\n }\n this.emit('info', 'Stats Updated!');\n this.emit('info', body);\n });\n if (!config.beta) {\n let requestOptionsCarbon = {\n url: 'https://www.carbonitex.net/discord/data/botdata.php',\n method: 'POST',\n json: {\n 'server_count': this.guilds,\n 'key': config.carbon_token\n }\n };\n request(requestOptionsCarbon, (err, response, body) => {\n if (err) {\n return this.emit('error', err)\n }\n this.emit('info', 'Stats Updated Carbon!');\n this.emit('info', body);\n });\n }\n }\n }", "setStats(updatedGameSessions) {\n\t\tthis.setTimePlayed(updatedGameSessions)\n\t\tthis.setGameModes(updatedGameSessions)\n this.setGamesPlayedByLoggedInUsers(updatedGameSessions)\n}", "updatePercentReady() {\n let stats_ready = 0,\n stats_count = this.stats_list.length\n\n this.percent_ready = this.stats_aggregated.percent_ready || 0\n this.compare_percent_ready = this.compare_stats_aggregated.percent_ready || 0\n\n if (stats_count == 0)\n return\n\n if (this.percent_ready === 0) {\n this.stats_list.map(s => {\n if (s.percent_ready === 1)\n stats_ready +=1\n })\n this.percent_ready = parseFloat(stats_ready / stats_count)\n }\n\n if (this.compare_percent_ready === 0) {\n this.stats_list.map(s => {\n if (s.percent_ready === 1)\n stats_ready +=1\n })\n this.percent_ready = parseFloat(stats_ready / stats_count)\n }\n }", "function recalculateStats() {\n\tvar totalVictims = victimStats.length;\n\tvar savedVictims = 0;\n\tvar missingVictims = 0;\n\t\n\tfor(var i = 0; i < totalVictims; i++)\n\t\tif(isVictimSafe(victimStats[i]))\n\t\t\tsavedVictims++;\n\t\n\tmissingVictims = totalVictims - savedVictims;\n\t\n\t$('#lblStatsVictims').html(totalVictims);\n\t$('#lblStatsSaved').html(savedVictims);\n\t$('#lblStatsMissings').html(missingVictims);\n}", "function updateEnemyStats() {\n\t\t$(\"#enemyHealth\").html(\"HP: \" + enemyPicked.health + \"<br />Attack: \" + enemyPicked.attack);\n\t\t$(\"#enemyName\").html(enemyPicked.display);\n\t}", "function updatePlayerStats() {\n\t\t$(\"#playerHealth\").html(\"HP: \" + characterPicked.health + \"<br />Attack: \" + characterPicked.attack);\n\t\t$(\"#playerName\").html(characterPicked.display);\n\t}", "function updateCalendarStats(){\n if(new Date().getFullYear() == currentCalendar.lastYearViewed){\n currentStreakDiv.innerHTML = \"Current Streak: <span>\" + getCurrentStreak() + \"</span>\";\n }else{\n currentStreakDiv.innerHTML = \"\";\n }\n longestStreakSpan.innerHTML = getLongestStreak();\n totalLitSpan.innerHTML = getNumberCellsLit();\n percentLitSpan.innerHTML = getPercentCellsLit();\n }", "function updateStats() {\n\tdocument.getElementById('wins').innerHTML = wins;\n\tdocument.getElementById('losses').innerHTML = losses;\n\tdocument.getElementById('gamesplayed').innerHTML = wins + losses;\n}", "function updateHitrate()\n{\n\tvar s1 = collect(makeProperJson(vdata[0]),['VBE'],undefined);\n\tvar tmp = [10, 100, 1000];\t\n\tfor (x in tmp ) {\n\t\ta = tmp[x];\n\t\tvar origa = a;\n\t\tif (vdatap.length-1 < a) {\n\t\t\ta = vdatap.length-1;\n\t\t}\n\t\tproper = makeProperJson(vdata[a]);\n\t\ts2 = collect(proper,['VBE'],undefined);\n\t\tstorage = collect(proper,['SMA','SMF'],'Transient');\n\t\thitrate[origa].d = a;\n\t\thitrate[origa].h = ((vdatap[0]['cache_hit'] - vdatap[a]['cache_hit']) / (vdatap[0]['client_req'] - vdatap[a]['client_req'])).toFixed(5);\n\t\thitrate[origa].b = (s1['beresp_hdrbytes'] + s1['beresp_bodybytes'] - \n\t\t\t\t s2['beresp_hdrbytes'] - s2['beresp_bodybytes']) / a;\n\t\thitrate[origa].f = (vdatap[0]['s_resp_hdrbytes'] + vdatap[0]['s_resp_bodybytes']\n\t\t\t\t- (vdatap[a]['s_resp_hdrbytes'] + vdatap[a]['s_resp_bodybytes']))/a;\n\t\tdocument.getElementById(\"hitrate\" + origa + \"d\").textContent = hitrate[origa].d;\n\t\tdocument.getElementById(\"hitrate\" + origa + \"v\").textContent = (hitrate[origa].h*100).toFixed(3) + \"%\";\n\t\tdocument.getElementById(\"bw\" + origa + \"v\").textContent = toHuman(hitrate[origa].b) + \"B/s\";\n\t\tdocument.getElementById(\"fbw\" + origa + \"v\").textContent = toHuman(hitrate[origa].f) + \"B/s\";\n\t\t\n\t\tdocument.getElementById(\"storage\" + origa + \"v\").textContent = toHuman(storage['g_bytes']);\n\n\t}\n\tdocument.getElementById(\"MAIN.uptime-1\").textContent = secToDiff(vdatap[0]['uptime']);\n\tdocument.getElementById(\"MGT.uptime-1\").textContent = secToDiff(vdatap[0]['MGT.uptime']);\n}", "function reWriteStats() {\n\n targetNumber = Math.floor(Math.random() * (120 - 19 + 1)) + 19;\n //console.log('Reset targetNumber: ' + targetNumber);\n $('#target-number').text(targetNumber);\n\n playerCounter = 0;\n //$('#player-score').empty();\n\n //$('#game-round-alert').empty();\n\n assignToImages();\n \n }", "function updateGameStats(score, size, speed) {\n document.getElementById('score').innerText = score;\n document.getElementById('size').innerText = size;\n document.getElementById('speed').innerText = speed.toFixed(2) + ' blocks/sec';\n}", "function update() {\n controls.update();\n stats.update();\n }", "function printStatistics() {\n var textP;\n var defxo = 0.1, //default x offset\n defwo = 1, //default width offset\n wo = 0.8 //another width offset\n deftp = 0.05; // default text percentage\n textP = \"Statistics\";\n printText(0, 0.25, defwo, textP, deftp, \"center\");\n\n //Longest Time Alive Statistic\n textP = \"Longest time alive:\";\n printText(defxo, 0.35, defwo, textP, deftp, \"left\");\n textP = calculateLongestPlayerAliveTime() + \"s\";\n printText(defxo, 0.35, wo, textP, deftp, \"right\");\n\n //Number of Deaths Statistic\n textP = \"Number of deaths:\";\n printText(defxo, 0.45, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"playerHit\");\n printText(defxo, 0.45, wo, textP, deftp, \"right\");\n\n //Enemies Destroyed Statistic\n textP = \"Enemies Destroyed:\";\n printText(defxo, 0.55, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"enemiesKilled\");\n printText(defxo, 0.55, wo, textP, deftp, \"right\");\n\n //Bonuses Collected Statistic\n textP = \"Bonuses collected:\";\n printText(defxo, 0.65, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"bonusCollected\");\n printText(defxo, 0.65, wo, textP, deftp, \"right\");\n\n //Final Score Statistic\n textP = \"Final Score:\";\n printText(defxo, 0.75, defwo, textP, deftp, \"left\");\n textP = Crafty(\"Score\")._score;\n printText(defxo, 0.75, wo, textP, deftp, \"right\");\n}", "function update() {}", "function actualiserStats(){\r\n\tvar fin=new Date();\r\n\tfor(var c in stats){// actualise tous les contextes : stats locales, du thème, et globales\r\n\t\tif(stats[c].rep!=stats[c].repJustes+stats[c].repFausses+stats[c].repNeutres)\r\n\t\t\tstats[c].rep=stats[c].repJustes+stats[c].repFausses+stats[c].repNeutres;\r\n\t\tstats[c].points=stats[c].repJustes-stats[c].repFausses; // pts gagnés\r\n\t\tstats[c].note=(20*stats[c].points/stats[c].rep); // calcul de la note locale avec signe\r\n\t\tstats[c].note=(stats[c].note<0?0:stats[c].note); // on ramène à zéro le cas échéant\r\n\t\tstats[c].note=Math.floor(2*stats[c].note+0.5)/2; // arrondi au demi-point le + proche\r\n\t\tstats[c].temps=Math.floor((fin-stats[c].debut)/1000); // temps écoulé\r\n\t\tstats[c].efficacite= 60*stats[c].points/stats[c].temps; // points gagnés par minute\r\n\t\tstats[c].efficacite=Math.floor(10*stats[c].efficacite)/10; //arrondi\r\n\t\t\r\n\t}\r\n}", "function updateStats() {\n\t// Set the date we're counting down to\n\tvar startDate = new Date(\"Jan 13 15:15:15 2017\");\n\n\t// Update the count down every 1 day\n\n\t// Get today's date and time\n\tvar now = new Date();\n\n\t// Find the distance between now an the count down date\n\tvar distanceSec = (now - startDate)/1000 ;\n\n\t// Time calculations for weeks, days, hours\n\tvar weeks = Math.floor(distanceSec / (60 * 60 * 24 * 7));\n\tvar days = Math.floor(distanceSec / (60 * 60 * 24) - weeks * 2);\n\tvar hours = Math.floor(days * 7);\n\n\t// Display the result in the element with id\n\tdocument.getElementById(\"weeks\").innerHTML = String(weeks);\n\tdocument.getElementById(\"coffee\").innerHTML = String(days);\n\tdocument.getElementById(\"hours\").innerHTML = String(hours);\n}", "function updateGameStats () {\n var gamesRef = dataBase.ref(`games/` + gameId.key)\n var winner = getAllPlayers()\n gamesRef.update({winner: winner[0].id, status: 'finished'})\n }", "function _updateStatsSurface(){\n Timer.setInterval(function(){\n placeID = getSelectedPlace();\n // update stats panel\n this.statsSurface.setContent(getRecord(this.options.placeStats, placeID))\n }.bind(this), 250)\n }", "function setStats(){\n console.log('Stats set')\n\n switch(Global.PLAYER_CLASS) {\n \n case 'Ninja':\n //this.ONE();\n break;\n \n case 'Warrior':\n Global.PLAYER_DEFENSE = 4;\n Global.PLAYER_SKILL1 = 20;\n mod = prob/10.0;\n Global.PLAYER_SKILL2 = Math.round((Global.PLAYER_SKILL1 + Global.PLAYER_SKILL1) * (mod))\n //player_skill2 = (int)Math.round((player_skill1 + player_skill1) * (mod));\n Global.PLAYER_HEALTH = 100;\n //gameClass = \"warrior\";\n break;\n\n case 'Knight':\n //this.THREE();\n break;\n\n case 'Preist':\n //this.FOUR();\n break;\n\n }\n\n\n}", "function stateStats(resultStats){\n started = true;\n var today = resultStats[\"today\"]\n var cmtoday = today[\"onecup\"];\n cmtoday += today[\"double\"];\n cmtoday += today[\"strong\"];\n cmtoday += today[\"xstrong\"];\n var week = resultStats[\"week\"]\n var cmweek = week[\"onecup\"];\n cmweek += week[\"double\"];\n cmweek += week[\"strong\"];\n cmweek += week[\"xstrong\"];\n var total = resultStats[\"total\"]\n var cmtotal = total[\"onecup\"];\n cmtotal += total[\"double\"];\n cmtotal += total[\"strong\"];\n cmtotal += total[\"xstrong\"];\n trester_progress = parseInt(resultStats[\"trester\"]) / 640 * 100;\n console.log(resultStats[\"trester\"]);\n\n\n // write list\n document.querySelector('.cm-update-stats-icon').innerHTML = \"<i class=\\\"icon ion-android-sync big-icon cm-update-stats\\\" query=\\\"update\\\"></i>\";\n document.querySelector('.cm-today').innerHTML = cmtoday;\n if (!today[\"onecup\"] == 0 ){\n document.querySelector('.cm-single-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + today[\"onecup\"].toString()+\"</span> </li> \";\n }\n if (!today[\"double\"] == 0 ){\n document.querySelector('.cm-double-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + today[\"double\"].toString()+\"</span> </li> \";\n }\n if (!today[\"strong\"] == 0 ){\n document.querySelector('.cm-strong-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + today[\"strong\"].toString()+\"</span> </li> \";\n }\n if (!today[\"xstrong\"] == 0 ){\n document.querySelector('.cm-xstrong-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + today[\"xstrong\"].toString()+\"</span> </li> \";\n }\n if (!today[\"flushs\"] == 0 ){\n document.querySelector('.cm-flush-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + today[\"flushs\"].toString()+\"</span> </li> \";\n }\n\n document.querySelector('.cm-week').innerHTML = cmweek;\n\n if (!week[\"onecup\"] == 0) {\n document.querySelector('.cm-single-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + week[\"onecup\"].toString()+\"</span> </li> \";\n }\n if (!week[\"double\"] == 0) {\n document.querySelector('.cm-double-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + week[\"double\"].toString()+\"</span> </li> \";\n }\n if (!week[\"strong\"] == 0) {\n document.querySelector('.cm-strong-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + week[\"strong\"].toString()+\"</span> </li> \";\n }\n if (!week[\"xstrong\"] == 0) {\n document.querySelector('.cm-xstrong-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + week[\"xstrong\"].toString()+\"</span> </li> \";\n }\n if (!week[\"flushs\"] == 0) {\n document.querySelector('.cm-flush-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + week[\"flushs\"].toString()+\"</span> </li> \";\n }\n document.querySelector('.cm-total').innerHTML = cmtotal;\n document.querySelector('.cm-single-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + total[\"onecup\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-double-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + total[\"double\"]+\"</span> </li> \";\n document.querySelector('.cm-strong-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + total[\"strong\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-xstrong-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + total[\"xstrong\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-flush-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + total[\"flushs\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-trester-progress').innerHTML = \"<div class=\\\"determinate\\\" style=\\\"width: \"+trester_progress +\"%;\\\"></div>\";\n }", "function gameLoop() {\n stats.begin(); // Begin measuring\n ///updating current state\n currentstate.update();\n stats.end(); // end measuring\n}", "function updateNeededStat() {\n //Find out which column this is in\n var colIdx = getColumnIndex(this.parentNode);\n //Find out which table this is in\n var table = whichTableIsInputIn(this);\n\n //If I just blurred out of the plus to all column, need to update all 3 stats\n if (colIdx === 4) {\n updateAllOutputs(this, table);\n } else {\n //Just blurred out of a regular column, only update that column\n //Get all inputs in the table 'table' with the column 'colIdx' using nth-child\n var inputs = document.querySelectorAll('.' + table + ' td:nth-child(' +\n (colIdx+1) + ') > input'); //add one because nth-child is 1-indexed\n\n //Get all inputs in the 'plus to all' column in the table\n var plusToAllInputs = document.querySelectorAll('.' + table + ' td:nth-child('\n + (4+1) + ') > input'); //'plus to all' column is column 4\n\n inputs = Array.prototype.slice.call(inputs);\n plusToAllInputs = Array.prototype.slice.call(plusToAllInputs);\n inputs = inputs.concat(plusToAllInputs); //Join the two arrays\n\n\n //Get the needed stat\n var output = calculateNeededStat(inputs);\n\n //Save the needed state to the webpage\n saveNeededStat(output, colIdx, table);\n }\n}", "function renderScoreUpdateLogic () {\n scoreUpdateDelta++;\n \n if (scoreUpdateDelta >= SI.res.ResourceLoader.getResources().game.properties.HUDScoreUpdateMaxDelta) {\n scoreUpdateDelta = 0;\n \n if (score != finalScore) {\n if (score < finalScore) {\n score += SI.res.ResourceLoader.getResources().game.properties.HUDScoreUpdateSpeed;\n \n if (score > finalScore) {\n score = finalScore;\n }\n } else {\n score -= SI.res.ResourceLoader.getResources().game.properties.HUDScoreUpdateSpeed;\n \n if (score < finalScore) {\n score = finalScore;\n }\n }\n }\n }\n }", "function refreshStats() {\n\t//use localStorage to load our game stats\n\tlet DS = DataStore;\n\t$(\"#win-spins\").text(DS.wins);\n\t$(\"#lose-spins\").text(DS.loses);\n\t$(\"#most-spins\").text(DS.most);\n\t$(\"#least-spins\").text(DS.least);\n}", "function getStatistics(statsPos) {\r\n var myStats = getStats(statsPos);\r\n return myStats;\r\n}", "function updateStats() {\n \n let specialNames = [\"Quake\", \"Chain_Lightning\", \"Curse\", \"Courage\", \"Wind_Prison\"];\n for (const sName of specialNames) {\n for (let i = 1; i < 6; i++) {\n let elem = document.getElementById(sName + \"-\" + i);\n let name = sName.replace(\"_\", \" \");\n if (elem.classList.contains(\"toggleOn\")) { //toggle the pressed button off\n elem.classList.remove(\"toggleOn\");\n let special = powderSpecialStats[specialNames.indexOf(sName)];\n console.log(special);\n if (special[\"weaponSpecialEffects\"].has(\"Damage Boost\")) { \n if (name === \"Courage\" || name === \"Curse\") { //courage is universal damage boost\n //player_build.damageMultiplier -= special.weaponSpecialEffects.get(\"Damage Boost\")[i-1]/100;\n player_build.externalStats.set(\"sdPct\", player_build.externalStats.get(\"sdPct\") - special.weaponSpecialEffects.get(\"Damage Boost\")[i-1]);\n player_build.externalStats.set(\"mdPct\", player_build.externalStats.get(\"mdPct\") - special.weaponSpecialEffects.get(\"Damage Boost\")[i-1]);\n player_build.externalStats.set(\"poisonPct\", player_build.externalStats.get(\"poisonPct\") - special.weaponSpecialEffects.get(\"Damage Boost\")[i-1]);\n } else if (name === \"Wind Prison\") {\n player_build.externalStats.set(\"aDamPct\", player_build.externalStats.get(\"aDamPct\") - special.weaponSpecialEffects.get(\"Damage Boost\")[i-1]);\n player_build.externalStats.get(\"damageBonus\")[4] -= special.weaponSpecialEffects.get(\"Damage Boost\")[i-1];\n }\n }\n }\n }\n }\n \n\n \n let skillpoints = player_build.total_skillpoints;\n let delta_total = 0;\n for (let i in skp_order) {\n let value = document.getElementById(skp_order[i] + \"-skp\").value;\n if (value === \"\"){value = 0; setValue(skp_order[i] + \"-skp\", value)}\n let manual_assigned = 0;\n if (value.includes(\"+\")) {\n let skp = value.split(\"+\");\n for (const s of skp) {\n manual_assigned += parseInt(s,10);\n }\n } else {\n manual_assigned = parseInt(value,10);\n }\n let delta = manual_assigned - skillpoints[i];\n skillpoints[i] = manual_assigned;\n player_build.base_skillpoints[i] += delta;\n delta_total += delta;\n }\n player_build.assigned_skillpoints += delta_total;\n if(player_build){\n updatePowderSpecials(\"skip\", false);\n updateBoosts(\"skip\", false);\n }\n for (let id of editable_item_fields) {\n player_build.statMap.set(id, parseInt(getValue(id)));\n }\n player_build.aggregateStats();\n console.log(player_build.statMap);\n calculateBuildStats();\n}", "componentDidUpdate() {\n this.updateStats();\n }", "updateStats(){\n document.getElementById(\"hp\").innerHTML = health;\n document.getElementById(\"wp\").innerHTML = weapon;\n document.getElementById(\"xp\").innerHTML = exp;\n document.getElementById(\"lvl\").innerHTML = level;\n document.getElementById(\"dng\").innerHTML = dungeon;\n }", "function updateStats() {\n $(\"#player-stats\").html(\"<h1>PLAYER</h1><h1 style=\\\"margin-top: 10px\\\">HP: \" + player.hitPoints + \"</h1>\");\n $(\"#enemy-stats\").html(\"<h1>Enemy</h1><h1 style=\\\"margin-top: 10px\\\">HP: \" + enemy.hitPoints + \"</h1>\");\n}", "addStats(currentStat) {\n let score = 0;\n let topItemsForSlots = this.props.topItemsForSlots;\n let slotTitles = [\"head\", \"cape\", \"neck\", \"weapon\", \"body\", \"shield\", \"legs\", \"hands\", \"feet\", \"ring\"];\n for (let i = 0; i < slotTitles.length; i++) {\n let currentItem = topItemsForSlots[slotTitles[i]][0];\n if (!currentItem) {\n continue;\n }\n score += currentItem.stats[currentStat.statCategory][currentStat.attackStyle];\n }\n return score.toString();\n }", "_update() {\n }", "function initStats() {\n stats = {};\n stats.acumTemp = 0.0;\n stats.contaTemp = 0;\n stats.acumUmid = 0.0;\n stats.contaUmid = 0;\n stats.acumQuali = 0.0;\n stats.contaQuali = 0;\n stats.data = new Date();\n}", "function getStats(){\n return stats;\n }", "function finalCalculations (stats, dim, name, numVals) {\r\n stats[dim][name].mean *= (1 / numVals);\r\n stats[dim][name].meanOfSquares *= (1 / numVals);\r\n stats[dim][name].stdev = Math.sqrt(stats[dim][name].meanOfSquares - Math.pow(stats[dim][name].mean, 2));\r\n }", "function onUpdateStatus(id, r)\r\n{\r\n\tif (r == null) return onUpdateFail(id,'Resp Error');\r\n\tif (r == false) return onUpdateFail(id,'No Response');\r\n\r\n\tvar utilization = (r.bytes / r.limit_maxbytes) * 100;\r\n\t$('utilization_'+id).update(utilization.toFixed(2) + '%');\r\n\t\r\n\tvar w = Math.round( utilization * ($('utilization_bar_'+id).getWidth()/100) );\r\n\t$('utilization_bar_b_'+id).setStyle({width: w+'px'});\r\n\t\r\n\t$('pid_'+id).update(r.pid);\r\n\t$('uptime_'+id).update(r.uptime);\r\n\t$('time_'+id).update(r.pidtime);\r\n\t$('version_'+id).update(r.version);\r\n\t$('pointer_size_'+id).update(r.pointer_size);\r\n\t$('curr_items_'+id).update(r.curr_items);\r\n\t$('total_items_'+id).update(r.total_items);\r\n\t$('bytes_'+id).update(r.bytes);\r\n\t$('curr_connections_'+id).update(r.curr_connections);\r\n\t$('total_connections_'+id).update(r.total_connections);\r\n\t$('connection_structures_'+id).update(r.connection_structures);\r\n\t$('cmd_get_'+id).update(r.cmd_get);\r\n\t$('cmd_set_'+id).update(r.cmd_set);\r\n\t$('get_hits_'+id).update(r.get_hits);\r\n\t$('get_misses_'+id).update(r.get_misses);\r\n\t$('bytes_read_'+id).update(r.bytes_read);\r\n\t$('bytes_written_'+id).update(r.bytes_written);\r\n\t$('limit_maxbytes_'+id).update(r.limit_maxbytes);\r\n\r\n\t$('result_'+id).update('OK');\r\n\t$('result_'+id).addClassName('ok')\r\n\r\n\tupdateNext(id);\r\n}", "function generateStats() {\n // e.preventDefault();\n if (statGeneration.chances === 0) return;\n\n // Generate values for strength, power, combat, intelligence, speed, and durability\n strength = generateVal();\n power = generateVal();\n combat = generateVal();\n intelligence = generateVal();\n speed = generateVal();\n durability = generateVal();\n // Calculate the attack and defense based on the above stats\n attack = parseInt(calcBattleStat(strength, power, combat));\n defense = parseInt(calcBattleStat(intelligence, speed, durability));\n setStatGeneration({\n chances: statGeneration.chances - 1,\n attack: attack,\n defense: defense,\n strength: strength,\n power: power,\n combat: combat,\n intelligence: intelligence,\n speed: speed,\n durability: durability\n });\n }", "function TotalStatValues(BaseStats, JobBonusStats) {\n for (var i = 0; i < 6; i++) {\n BaseStats[i] = parseInt(BaseStats[i]) + JobBonusStats[i];\n }\n return BaseStats;\n}", "updateBackgroundStats() {\n this.treeSpeed += 0.4;\n this.horizonSpeed *= 0.8;\n }", "function updateStats() {\r\n\tif(state.saved_player_wins + state.saved_pc_wins > 0){\r\n\t\t//User win percentage\r\n\t\tvar plWins = Math.round((state.saved_player_wins/(state.saved_player_wins + state.saved_pc_wins)) * 100);\r\n\t\t//AI win percentage\r\n\t\tvar pcWins = Math.round((state.saved_pc_wins/(state.saved_player_wins + state.saved_pc_wins)) * 100);\r\n\t\tvar winText = document.getElementById(\"svgTextP1V\");\r\n\t\twinText.textContent = plWins + \"%\";\r\n\t\tvar looseText = document.getElementById(\"svgTextP1L\");\r\n\t\tlooseText.textContent = 100 - plWins + \"%\";\r\n\t\tvar winTextPC = document.getElementById(\"svgTextP2V\");\r\n\t\twinTextPC.textContent = pcWins + \"%\";\r\n\t\tvar looseTextPC = document.getElementById(\"svgTextP2L\");\r\n\t\tlooseTextPC.textContent = 100 - pcWins + \"%\";\r\n\r\n\t\tvar circles = []\r\n\t\tsvgSCircles.forEach(element => {\r\n\t\t\tcircles.push(document.getElementById(element));\r\n\t\t});\r\n\r\n\t\t//Win feedback\r\n\t\tif(plWins > 70) { //Good win percentage\r\n\t\t\tcircles[0].setAttribute('stroke','#00DCA4');\r\n\t\t\tcircles[0].setAttribute('fill','#00DCA4');\r\n\t\t\tcircles[1].setAttribute('stroke','#00DCA4');\r\n\t\t\tcircles[1].setAttribute('fill','#00DCA4');\r\n\t\t\tcircles[2].setAttribute('stroke','red');\r\n\t\t\tcircles[2].setAttribute('fill','red');\r\n\t\t\tcircles[3].setAttribute('stroke','red');\r\n\t\t\tcircles[3].setAttribute('fill','red');\r\n\t\t}\r\n\t\telse if (plWins > 30 && plWins < 70) { //Mediocre win percentage\r\n\t\t\tcircles[0].setAttribute('stroke','#F1C40F');\r\n\t\t\tcircles[0].setAttribute('fill','#F1C40F');\r\n\t\t\tcircles[1].setAttribute('stroke','#F1C40F');\r\n\t\t\tcircles[1].setAttribute('fill','#F1C40F');\r\n\t\t\tcircles[2].setAttribute('stroke','#F1C40F');\r\n\t\t\tcircles[2].setAttribute('fill','#F1C40F');\r\n\t\t\tcircles[3].setAttribute('stroke','#F1C40F');\r\n\t\t\tcircles[3].setAttribute('fill','#F1C40F');\r\n\t\t}\r\n\t\telse { //Bad win percentage\r\n\t\t\tcircles[0].setAttribute('stroke','red');\r\n\t\t\tcircles[0].setAttribute('fill','red');\r\n\t\t\tcircles[1].setAttribute('stroke','red');\r\n\t\t\tcircles[1].setAttribute('fill','red');\r\n\t\t\tcircles[2].setAttribute('stroke','#00DCA4');\r\n\t\t\tcircles[2].setAttribute('fill','#00DCA4');\r\n\t\t\tcircles[3].setAttribute('stroke','#00DCA4');\r\n\t\t\tcircles[3].setAttribute('fill','#00DCA4');\r\n\t\t}\r\n\r\n\t\t//Setting the circles (games played) and squares (win records) states\r\n\t\tfor (let index = 0; index < svgTexts.length; index++) {\r\n\t\t\tvar text = document.getElementById(svgTexts[index]);\r\n\t\t\tif (!isMobile) text.style.fontSize= \"30px\";\r\n\t\t\tif (state.wins[index]!=null) {\r\n\t\t\t\tvar circ = document.getElementById(svgCircles[index]);\r\n\t\t\t\tcirc.setAttribute('fill',\"#d8d8d8\");\r\n\t\t\t\ttext.textContent = state.wins[index];\t\t\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\ttext.textContent = '';\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// updating the total timer\r\n\tvar time = document.getElementById(\"time\");\r\n\ttime.textContent = msToTime(state.accumulated_time);\r\n\r\n}", "function updateStats() {\n if (!g_original_title) {\n g_original_title = document.title;\n }\n var total_entries = getEntries().length;\n var new_entries = total_entries - g_n_collapsed;\n document.title = g_original_title + ' - ' + new_entries + ' new entries';\n var stats = document.getElementById('stats');\n if (stats) {\n stats.innerHTML = total_entries + ' entries, ' + new_entries + ' new.';\n }\n}", "function checkStats(){\n\t\tif(numberofbrains >= 13){\n\t\t\t///game won \n\t\t\t$(\"div.winner\").text(\"Winner: \" + currplayer);\n\t\t\t$(\"div.gameOver\").text(\"Game Over\");\n\n\t\t\t//runs twice \n\t\t\tsocket.emit(\"winner\", currentsid);\n\n\t\t\tconsole.log(\"Sending ID: \" + currentsid);\n\t\t\tconsole.log(\"Sending name: \" + currplayer);\n\n\t\t\t//socket.emit(\"stopScore\", currentsid);\n\t\t\t//add winner to game stats pass winner \n\t\t}\n\t\telse if(numberofshotguns >= 3){\n\t\t\t//game over reset numberofshotgun & number of brains\n\t\t\t$(\"div.gameOver\").text(\"Death by Shotgun: \" + currplayer);\n\t\t\t//clear emit\n\t\t\tsocket.emit(\"clearBoard\");\n\t\t\tnumberofbrains = 0;\n\t\t\tsocket.emit(\"TrackScore\", currentsid, numberofbrains); //reset back to zero\n\t\t\tsocket.emit(\"stopScore\", currentsid);\n\t\t}\n\t\telse{\n\t\t\t///nothing \n\t\t}\n\t}", "function createStats(job, level) {\r\n\tif(job == jobs.war) { \r\n\t\tstats.str = 2 + (level * 2);\r\n\t\tstats.dex = 1 + level;\r\n\t\tstats.con = 3 + level;\r\n\t\tstats.intel = 0 + level;\r\n\t\tstats.will = 0 + level;\r\n\t\tstats.chari = 0 + level;\r\n\t}\r\n\telse if(job == jobs.hnt) { \r\n\t\tstats.str = 1 + level;\r\n\t\tstats.dex = 1 + (level * 2);\r\n\t\tstats.con = 1 + level;\r\n\t\tstats.intel = 1 + level;\r\n\t\tstats.will = 2 + level;\r\n\t\tstats.chari = 0 + level;\r\n\t}\r\n\telse if(job == jobs.rog) { \r\n\t\tstats.str = 0 + level;\r\n\t\tstats.dex = 1 + (level * 2);\r\n\t\tstats.con = 1 + level; //<--- bug here. if this value changes, it fucks up mp for rogue.\r\n\t\tstats.intel = 3 + level;\r\n\t\tstats.will = 0 + level;\r\n\t\tstats.chari = 1 + level;\r\n\t}\r\n\telse if(job == jobs.wiz) { \r\n\t\tstats.str = 0 + level;\r\n\t\tstats.dex = 0 + level;\r\n\t\tstats.con = 1 + level;\r\n\t\tstats.intel = 2 + level;\r\n\t\tstats.will = 3 + (level * 2);\r\n\t\tstats.chari = 0 + level;\r\n\t}\r\n\t\r\n\tstatsArray = [ \"Strength \" + stats.str, \"Dexterity \" + stats.dex, \"Constitution \" + stats.con, \"Intelligence \" + stats.intel, \"Willpower \" + stats.will, \"Charisma \" + stats.chari];\r\n\tprintArray(statsArray);\r\n\tgenHp(stats.con);\r\n\tgenMp(stats.will);\r\n\tgenAtkBonus();\r\n\tgetSkills(playerDetails.job, playerDetails.level);\r\n}", "function updateStatsUI() {\n countItems();\n var progressBarWidth = percentBar.css('width');\n progressBarWidth = Number(progressBarWidth.slice(0, progressBarWidth.length - 2));\n if (count == 0) {\n percentBarFill.css('width', '0px');\n percentText.text('0%');\n } else {\n percentBarFill.css('width', '' + Math.round(completed / count * progressBarWidth) + 'px');\n percentText.text('' + Math.round(completed / count * 100) + '%');\n }\n}", "function mobStats(HP, STR, MGC, LVL, XPR, DVP, OFA, mobName) {\n this.HP = HP;\n this.STR = STR;\n this.MGC = MGC;\n this.LVL = LVL;\n this.XPR = XPR;\n this.DVP = DVP;\n this.OFA = OFA;\n this.mobName = mobName;\n this.HPchange = HPchange;\n\n function HPchange(newValue) {\n this.HP = newValue;\n }\n this.STRchange = STRchange;\n\n function STRchange(newValue) {\n this.STR = newValue;\n }\n this.MGCchange = MGCchange;\n\n function MGCchange(newValue) {\n this.MGC = newValue;\n }\n this.LVLchange = LVLchange;\n\n function LVLchange(newValue) {\n this.LVL = newValue;\n }\n this.XPRchange = XPRchange;\n\n function XPRchange(newValue) {\n this.XPR = newValue;\n }\n this.DVPchange = DVPchange;\n\n function DVPchange(newValue) {\n this.DVP = newValue;\n }\n this.OFAchange = OFAchange;\n\n function OFAchange(newValue) {\n this.OFA = newValue;\n }\n this.mobNamechange = mobNamechange;\n\n function mobNamechange(newValue) {\n this.mobName = newValue;\n }\n}", "function updateStatistics() {\n var MILLIS_IN_AN_HOUR = 60 * 60 * 1000;\n var now = Date.now();\n var from = new Date(now - MILLIS_IN_AN_HOUR).toISOString();\n var until = new Date(now).toISOString();\n var functionEventsProjectName = '{project=\"' + ctrl.project.metadata.name + '\"}';\n var projectName = '{project_name=\"' + ctrl.project.metadata.name + '\"}';\n var gpuUtilizationMetric = ' * on (pod) group_left(function_name)(nuclio_function_pod_labels{project_name=\"' +\n ctrl.project.metadata.name + '\"})';\n var args = {\n metric: ctrl.functionEventsMetric + functionEventsProjectName,\n from: from,\n until: until,\n interval: '5m'\n };\n\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionEventsMetric))\n .catch(handleError.bind(null, ctrl.functionEventsMetric));\n\n args.metric = ctrl.functionCPUMetric + projectName;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionCPUMetric))\n .catch(handleError.bind(null, ctrl.functionCPUMetric));\n\n args.metric = ctrl.functionGPUMetric + gpuUtilizationMetric;\n args.appendQueryParamsToUrlPath = true;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionGPUMetric))\n .catch(handleError.bind(null, ctrl.functionGPUMetric));\n delete args.appendQueryParamsToUrlPath;\n\n args.metric = ctrl.functionMemoryMetric + projectName;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionMemoryMetric))\n .catch(handleError.bind(null, ctrl.functionMemoryMetric));\n\n /**\n * Sets error message to the relevant function\n */\n function handleError(type, error) {\n lodash.forEach(ctrl.functions, function (aFunction) {\n lodash.set(aFunction, 'ui.error.' + type, error.msg);\n\n $timeout(function () {\n ElementLoadingStatusService.hideSpinner(type + '-' + aFunction.metadata.name);\n });\n });\n }\n\n /**\n * Parses data for charts\n * @param {string} type\n * @param {Object} data\n */\n function parseData(type, data) {\n var results = lodash.get(data, 'result', []);\n\n lodash.forEach(ctrl.functions, function (aFunction) {\n var funcStats = [];\n\n lodash.forEach(results, function (result) {\n var functionName = lodash.get(aFunction, 'metadata.name');\n var metric = lodash.get(result, 'metric', {});\n var resultName = lodash.defaultTo(metric.function, metric.function_name);\n\n if (resultName === functionName) {\n funcStats.push(result);\n }\n });\n\n if (lodash.isObject(funcStats)) {\n var latestValue = lodash.sum(lodash.map(funcStats, function (stat) {\n return Number(lodash.last(stat.values)[1]);\n }));\n\n // calculating of invocation per second regarding last timestamps\n var invocationPerSec = lodash.chain(funcStats)\n .map(function (stat) {\n var firstValue;\n var secondValue;\n\n if (stat.values.length < 2) {\n return 0;\n }\n\n // handle array of length 2\n firstValue = stat.values[0];\n secondValue = stat.values[1];\n\n // when querying up to current time prometheus\n // may duplicate the last value, so we calculate an earlier\n // interval [pre-last] to get a meaningful value\n if (stat.values.length > 2) {\n firstValue = stat.values[stat.values.length - 3];\n secondValue = stat.values[stat.values.length - 2];\n }\n\n var valuesDiff = Number(secondValue[1]) - Number(firstValue[1]);\n var timestampsDiff = secondValue[0] - firstValue[0];\n\n return valuesDiff / timestampsDiff;\n })\n .sum()\n .value();\n\n var funcValues = lodash.get(funcStats, '[0].values', []);\n\n if (funcStats.length > 1) {\n funcValues = lodash.fromPairs(funcValues);\n\n for (var i = 1; i < funcStats.length; i++) {\n var values = lodash.get(funcStats, '[' + i + '].values', []);\n\n lodash.forEach(values, function (value) { // eslint-disable-line no-loop-func\n var timestamp = value[0];\n\n lodash.set(funcValues, timestamp, lodash.has(funcValues, timestamp) ?\n Number(funcValues[timestamp]) + Number(value[1]) : Number(value[1]));\n });\n }\n\n funcValues = lodash.chain(funcValues)\n .toPairs()\n .sortBy(function (value) {\n return value[0];\n })\n .value();\n }\n\n if (type === ctrl.functionCPUMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n 'cpu.cores': latestValue,\n cpuCoresLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else if (type === ctrl.functionMemoryMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n size: Number(latestValue),\n sizeLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else if (type === ctrl.functionGPUMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n 'gpu.cores': latestValue,\n gpuCoresLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else { // type === METRICS.FUNCTION_COUNT\n lodash.merge(aFunction.ui, {\n metrics: {\n count: Number(latestValue),\n countLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n }),\n invocationPerSec:\n $filter('scale')(invocationPerSec, Number.isInteger(invocationPerSec) ? 0 : 2)\n }\n });\n }\n }\n });\n\n // if the column values have just been updated, and the table is sorted by this column - update sort\n if (type === ctrl.functionCPUMetric && ctrl.sortedColumnName === 'ui.metrics[\\'cpu.cores\\']' ||\n type === ctrl.functionGPUMetric && ctrl.sortedColumnName === 'ui.metrics[\\'gpu.cores\\']' ||\n type === ctrl.functionMemoryMetric && ctrl.sortedColumnName === 'ui.metrics.size' ||\n type === ctrl.functionEventsMetric &&\n lodash.includes(['ui.metrics.invocationPerSec', 'ui.metrics.count'], ctrl.sortedColumnName)) {\n sortTable();\n }\n\n $timeout(function () {\n hideSpinners(type);\n })\n }\n }", "CalcStats( log = null ) { \n\t\tlog = log || this.log;\n\t\tif ( !log ) { return; }\n\t\t// first time setup\n\t\tif ( !this.stats ) { \n\t\t\tlet blank = {\n\t\t\t\tlosses:0,\n\t\t\t\tkills:0,\n\t\t\t\ttotal_dmg_out:0,\n\t\t\t\ttotal_dmg_in:0,\n\t\t\t\thull_dmg_out:0,\n\t\t\t\thull_dmg_in:0,\n\t\t\t\tarmor_dmg_out:0,\n\t\t\t\tarmor_dmg_in:0,\n\t\t\t\tshield_dmg_out:0,\n\t\t\t\tshield_dmg_in:0,\n\t\t\t\tattacks_made:0,\n\t\t\t\tattacks_received:0,\n\t\t\t\tattacks_missed:0,\n\t\t\t\tattacks_dodged:0,\n\t\t\t\tmilval_killed:0,\n\t\t\t\tmilval_lost:0\n\t\t\t\t};\n\t\t\tthis.stats = {};\n\t\t\tthis.stats[this.teams[0].label] = Object.assign({}, blank);\n\t\t\tthis.stats[this.teams[1].label] = Object.assign({}, blank);\n\t\t\t}\n\t\tlog.forEach( x => {\n\t\t\t// tabulate\n\t\t\tlet teamdata = this.stats[x.team.label];\n\t\t\tif ( teamdata ) { \n\t\t\t\tteamdata.hull_dmg_out += x.hull;\n\t\t\t\tteamdata.armor_dmg_out += x.armor;\n\t\t\t\tteamdata.shield_dmg_out += x.shield;\n\t\t\t\tteamdata.total_dmg_out += x.hull + x.armor;\n\t\t\t\tteamdata.attacks_made++;\n\t\t\t\tif ( x.missed ) { teamdata.attacks_missed++; } \n\t\t\t\tif ( x.killed ) { \n\t\t\t\t\tteamdata.kills++; \n\t\t\t\t\tteamdata.milval_killed += x.target.bp.milval; \n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t});\n\t\t// swap records\n\t\tlet keys = Object.keys( this.stats );\n\t\tlet t0 = this.stats[keys[0]];\n\t\tlet t1 = this.stats[keys[1]];\n\t\tt0.losses = t1.kills;\n\t\tt1.losses = t0.kills;\n\t\tt0.total_dmg_in = t1.total_dmg_out;\n\t\tt1.total_dmg_in = t0.total_dmg_out;\n\t\tt0.hull_dmg_in = t1.hull_dmg_out;\n\t\tt1.hull_dmg_in = t0.hull_dmg_out;\n\t\tt0.armor_dmg_in = t1.armor_dmg_out;\n\t\tt1.armor_dmg_in = t0.armor_dmg_out;\n\t\tt0.shield_dmg_in = t1.shield_dmg_out;\n\t\tt1.shield_dmg_in = t0.shield_dmg_out;\n\t\tt0.attacks_received = t1.attacks_made;\n\t\tt1.attacks_received = t0.attacks_made;\n\t\tt0.attacks_dodged = t1.attacks_missed;\n\t\tt1.attacks_dodged = t0.attacks_missed;\n\t\tt0.milval_lost = t1.milval_killed;\n\t\tt1.milval_lost = t0.milval_killed;\n\t\t}", "function updateScores() {\n dealerScore = getScore(dealerCards);\n playerScore = getScore(playerCards);\n}", "function UpdateProgressMetrics(){\n // Calculate percentage of module progress\n perbaspro = baspro/20*100;\n perpospro = pospro/20*100;\n perfol1pro = fol1pro/20*100;\n perfol2pro = fol2pro/20*100;\n perbashrqpro = bashrqpro/6*100;\n perposhrqpro = poshrqpro/6*100;\n perfol1hrqpro = fol1hrqpro/6*100;\n perfol2hrqpro = fol2hrqpro/6*100;\n perbasmitakpro = basmitakpro/37*100;\n perposmitakpro = posmitakpro/37*100;\n perfol1mitakpro = fol1mitakpro/37*100;\n perfol2mitakpro = fol2mitakpro/37*100;\n permipro = mipro/6*100;\n peroarspro = oarspro/58*100;\n pertarpro = tarpro/33*100;\n perevokpro = evokpro/100*100;\n perplanpro = planpro/11*100;\n perfullmipro = fullmipro/1*100;\n \n // Calculate percentage of skill acquisition based on correct items\n affirmcount = UpdateProgressResponseCorrect(oarsanswercorrect5) + UpdateProgressResponseCorrect(oarsanswercorrect6);\n peraffirm = affirmcount/15*100;\n \n reflectcount = UpdateProgressResponseCorrect(oarsanswercorrect4) + UpdateProgressResponseCorrect(targetanswercorrect2);\n perreflect = reflectcount/11*100;\n \n openclosecount = UpdateProgressResponseCorrect(oarsanswercorrect1) + UpdateProgressResponseCorrect(oarsanswercorrect2) + UpdateProgressResponseCorrect(oarsanswercorrect3);\n peropenclose = openclosecount/39*100;\n \n targetcount = UpdateProgressResponseCorrect(targetanswercorrect1);\n pertarget = targetcount/13*100;\n \n changetalkcount = UpdateProgressResponseCorrect(evokanswercorrect1) + UpdateProgressResponseCorrect(evokanswercorrect2) + UpdateProgressResponseCorrect(evokanswercorrect3) + UpdateProgressResponseCorrect(evokanswercorrect4) + UpdateProgressResponseCorrect(evokanswercorrect5);\n perchangetalk = changetalkcount/88*100;\n \n}", "function update() {\n\t\t\n\t}", "update()\r\n\t{\r\n\t\tlet secondsToAdd = (Date.now() - this.lastUpdate) / 1000;\r\n\t\tthis.members.forEach( (member, duration) => duration += secondsToAdd );\r\n\t}", "function updateStats() {\n document.getElementById(\"bleiben\").innerHTML = \"Chance beim Bleiben: \" + prozentBleiben + \"%\";\n document.getElementById(\"wechseln\").innerHTML = \"Chance beim Wechseln: \" + prozentWechseln + \"%\";\n document.getElementById(\"autos\").innerHTML = \"Autos: \"+ (result[\"bleiben\"][\"won\"] + result[\"wechseln\"][\"won\"]);\n document.getElementById(\"ziegen\").innerHTML = \"Ziegen: \" + (result[\"bleiben\"][\"lost\"] + result[\"wechseln\"][\"lost\"]);\n}", "update() { }", "update() { }", "function _createStats() {\n this.statsSurface = new Surface({\n size: [undefined, undefined],\n content: \" \\\n <table id='stats_table'> \\\n <tr class='even'> \\\n <td class='left_cell'> \\\n Average \\\n </td> \\\n <td class='right_cell'> \\\n 0 \\\n <span class='small'>sec</span> \\\n </td> \\\n </tr> \\\n <tr class='odd'> \\\n <td class='left_cell'> \\\n Median \\\n </td> \\\n <td class='right_cell'> \\\n 0 \\\n <span class='small'>sec</span> \\\n </td> \\\n </tr> \\\n <tr class='even'> \\\n <td class='left_cell'> \\\n 90th Percentile \\\n </td> \\\n <td class='right_cell'> \\\n 0 \\\n <span class='small'>sec</span> \\\n </td> \\\n </tr> \\\n <tr class='odd'> \\\n <td class='left_cell'> \\\n Fastest \\\n </td> \\\n <td class='right_cell'> \\\n 0 \\\n <span class='small'>sec</span> \\\n </td> \\\n </tr> \\\n <tr class='even'> \\\n <td class='left_cell'> \\\n Slowest \\\n </td> \\\n <td class='right_cell'> \\\n 0 \\\n <span class='small'>sec</span> \\\n </td> \\\n </tr> \\\n </table> \\\n \\\n \",\n properties: {\n textAlignt: 'center',\n paddingTop: '5px',\n backgroundColor: '#E6E6F0',\n },\n });\n\n var statsModifier = new StateModifier({\n origin: [0.5, 0],\n align: [0.5, 0.5],\n });\n\n this.layout.content.add(statsModifier).add(this.statsSurface);\n }", "totalUpdates() {\n return 30;\n }", "function updateStatistics() {\n\n let queryString = \"./latest\";\n jQuery.getJSON(queryString, function(all_stats, status) {\n if (status == \"success\") {\n console.log(all_stats);\n if (all_stats.sensor1 !== undefined) {\n all_stats.sensor1.entries.forEach(function(entry) {\n fermentationTemperature.innerHTML=\"<p style='margin:0;'>\"\n + Math.round(entry.temperature).toString()\n + \"&#176;C&nbsp;\"\n + \"<span style='font-size:15px; color:blue;'>Fermentation</span>\"\n + \"</p>\";\n\n graphAddItem(entry.temperature, entry.timestamp, sensorEnum.FERMENTER_TEMP, entry.index);\n latest_fermentation_temp = entry.temperature;\n });\n }\n\n if (all_stats.sensor2 !== undefined) {\n all_stats.sensor2.entries.forEach(function(entry) {\n ambientTemperature.innerHTML=\"<p style='margin:0'>\"\n + Math.round(entry.temperature).toString()\n + \"&#176;C&nbsp;\"\n + \"<span style='font-size:15px; color:orange;'>Ambient</span>\"\n + \"</p>\";\n\n graphAddItem(entry.temperature, entry.timestamp, sensorEnum.AMBIENT_TEMP, entry.index);\n latest_ambient_temp = entry.temperature;\n });\n }\n\n let average_count = 0;\n let total_count = 0;\n let latest_time = 0; \n let earliest_time = 0; \n\n //The query returns the last 10 entries for bubbles, average them\n if (all_stats.bubbles !== undefined) {\n all_stats.bubbles.entries.forEach(function(entry) {\n total_count += entry.average;\n average_count +=1;\n if (average_count == 1) {\n earliest_time = entry.timestamp;\n }\n latest_time = entry.timestamp;\n });\n }\n\n if (average_count > 0) {\n let timeDiff = new Date(latest_time).getTime()/1000 - new Date(earliest_time).getTime()/1000;\n timeDiff = timeDiff / 60; //Seconds to minutes\n //console.log(\"bubble stat, retreived \" + average_count + \" entries totaling \" + total_count + \" over \" + timeDiff + \" minutes\"); \n let rate = Math.round(Math.round(total_count / timeDiff));\n bubbleRate.innerHTML=\"<p style='margin:0'>\"\n + rate.toString()\n + \"<span style='font-size:15px;'>bpm</span>\"\n + \"</p>\";\n\n // TODO - update graph/timeline with bubbles average\n\n latest_bubbles_avg = rate;\n }\n } else {\n console.log(\"Jquery failed to get sensor2 information\");\n }\n });\n\n /* Go through alert list and check for violations */\n let alert_messages = [];\n let alertsEnabledCount = 0;\n\n // https://theshravan.net/blog/storing-json-objects-in-html5-local-storage/\n let jsonString = localStorage.getItem('alertsList');\n if (jsonString != null) {\n\n let alertsCurrent = JSON.parse(jsonString);\n console.log(alertsCurrent);\n\n //Check for any alerts only if they are turned on\n alertsCurrent.forEach(function(item) {\n if (item.on == true) {\n alertsEnabledCount += 1;\n\n // Ambient temperature alerts\n if (item.id == \"maxAmbientTemperatureAlert\") {\n if (latest_ambient_temp !== undefined) {\n if (latest_ambient_temp >= item.constraint) {\n alert_messages.push( { 'message': \"Ambient temperature rose above\", 'constraint':item.constraint, 'value':latest_ambient_temp } );\n }\n }\n }\n\n if (item.id == \"minAmbientTemperatureAlert\") {\n if (latest_ambient_temp !== undefined) {\n if (latest_ambient_temp <= item.constraint) {\n alert_messages.push( { 'message': \"Ambient temperature fell below\", 'constraint':item.constraint, 'value':latest_ambient_temp } );\n }\n }\n }\n\n // Fermenter temperature alerts\n if (item.id == \"maxFermenterTemperatureAlert\") {\n if (latest_fermentation_temp !== undefined) {\n if (latest_fermentation_temp >= item.constraint) {\n alert_messages.push( { 'message': \"Fermenter temperature rose above\", 'constraint':item.constraint, 'value':latest_fermentation_temp } );\n }\n }\n }\n\n if (item.id == \"minFermenterTemperatureAlert\") {\n if (latest_fermentation_temp !== undefined) {\n if (latest_fermentation_temp <= item.constraint) {\n alert_messages.push( { 'message': \"Fermenter temperature fell below\", 'constraint':item.constraint, 'value':latest_fermentation_temp } );\n }\n }\n }\n\n // Bubble average alerts\n if (item.id == \"maxBubblesAlert\") {\n if (latest_bubbles_avg !== undefined) {\n if (latest_bubbles_avg >= item.constraint) {\n alert_messages.push( { 'message': \"Average bubble per minute (bmp) exceeded\", 'constraint':item.constraint, 'value':latest_bubbles_avg } );\n }\n }\n }\n }\n });\n }\n\n /* Update status bar with ok/alerts */\n let newHtml = \"\";\n let currentDate = formatDate(new Date());\n\n if (alert_messages.length == 0) {\n newHtml=\"<p style='color:green;'>No current alerts as of: \" + currentDate + \" (\" + alertsEnabledCount + \" alerts enabled)</p>\";\n }\n\n alert_messages.forEach(function(item) {\n newHtml += \"<li style='color:red;'>\" + item.message + \"{\" + item.constraint + \"} Value = {\" + item.value + \"} \" + currentDate + \"</li>\";\n });\n\n statusField.innerHTML = newHtml;\n}", "function update()\n{\n if (objects['bricks'].objects.length > 0)\n {\n // ATI: Has either player won yet?\n if (gPlayerScore1 < MAX_SCORE && gPlayerScore2 < MAX_SCORE)\n {\n // ATI: No. Analyze the state of the game.\n if (touchedFloor)\n {\n // ATI: Player # 2 scores a point because Player # 1 missed the ball.\n gPlayerScore2++;\n updatePlayer2Score(gPlayerScore2);\n\n // gameStates[currentGameState].running = false;\n // currentGameState = gameStates[currentGameState].transitions.reset;\n\n // AIT: Reset the touched ceiling variable.\n touchedFloor = false;\n\n //if (lives == 0)\n //{\n // $('#lose').fadeIn();\n // $('#overlay-small').fadeIn();\n //}\n }\n else if (touchedCeiling)\n {\n // ATI: Player # 1 scores a point because Player # 2 missed the ball.\n gPlayerScore1++;\n updatePlayer1Score(gPlayerScore1);\n\n // AIT: Reset the touched ceiling variable.\n touchedCeiling = false;\n }\n\n // ATI: If the game is still running keep the balls and paddle supdated.\n if (gameStates[currentGameState].running)\n {\n updateBalls();\n updatePaddles();\n }\n }\n else\n {\n gameStates[currentGameState].running = false;\n currentGameState = gameStates[currentGameState].transitions.lose;\n\n console.log(\"Game over.\");\n // console.log(lives);\n }\n } else\n {\n $('#win').fadeIn();\n }\n stats.update();\n}", "refreshCombatPoints(){\n this.updateProperty('hit_points', this.props.stats_current.health)\n this.updateProperty('mana_points', Math.round(this.props.stats_current.mana * .5))\n this.updateProperty('stamina_points', Math.round(this.props.stats_current.stamina * .5))\n }", "updateStats() {\n let users = {};\n const { orders } = this.props;\n\n if(orders.length === 0) {\n return {\n num_users: '...',\n num_buys: '...',\n num_sells: '...',\n buy_volume: '...',\n sell_volume: '...',\n last_price: '...',\n last_type: '...'\n };\n }\n\n let new_stats = {\n num_users: 0,\n num_buys: 0,\n num_sells: 0,\n buy_volume: 0.0,\n sell_volume: 0.0,\n last_price: 0,\n last_type: \"BUY\"\n };\n\n for(let i = 0; i < orders.length; i++) {\n const order = orders[i];\n\n // Check if maker is in user list\n if(!(order[\"maker\"] in users)) {\n users[order[\"maker\"]] = 1;\n new_stats[\"num_users\"] += 1;\n }\n\n // Check if taker is in user list\n if(!(order[\"taker\"] in users)) {\n users[order[\"taker\"]] = 1;\n new_stats[\"num_users\"] += 1;\n }\n\n // Check if order is buy or sell and add the necessary info\n const curr_1 = parseFloat(ethers.utils.formatUnits(order[\"curr_1\"].toString(), \"ether\"));\n if(order[\"type\"] === \"BUY\") {\n new_stats[\"num_buys\"] += 1;\n new_stats[\"buy_volume\"] += curr_1;\n } else if(order[\"type\"] === \"SELL\") {\n new_stats[\"num_sells\"] += 1;\n new_stats[\"sell_volume\"] += curr_1;\n }\n }\n\n if(orders.length > 0) {\n new_stats[\"last_price\"] = Math.round(orders[0][\"price\"] * 1000) / 1000;\n new_stats[\"last_type\"] = orders[0][\"type\"];\n new_stats[\"buy_volume\"] = Math.round(new_stats[\"buy_volume\"] * 100) / 100;\n new_stats[\"sell_volume\"] = Math.round(new_stats[\"sell_volume\"] * 100) / 100;\n }\n\n return new_stats;\n }", "update(data){\r\n /*Check if the infrastructure has been attacked */\r\n if(this.#hitpoints > data.hitpoints){\r\n console.log( (this.#hitpoints - data.hitpoints) + \" points of damage taken on \" + this.#name);\r\n window.ui.alert((this.#hitpoints - data.hitpoints) + \" points of damage taken on \" + this.#name);\r\n }\r\n }", "updateAllStats(card=null) {\n if (card) {\n card.document.find(`.pcm_hitStats`).css('cursor', 'default');\n card.document.find(`${this.accepted.class}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n card.document.find(`${this.fetched.class}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n } else {\n $(`${this.accepted.id}_${this.myId}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n $(`${this.fetched.id}_${this.myId}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n $(`${this.accepted.id2}_${this.myId}`).html(`${this.accepted.label}: ${this.accepted.value}`);\n $(`${this.fetched.id2}_${this.myId}`).html(`${this.fetched.label}: ${this.fetched.value}`);\n }\n }", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "update() {}", "function updateArray()\n{\n\t$.ajax({\n\t\ttype: \"GET\",\n\t\turl: \"/stats\",\n\t\tdataType: \"text\",\n\t\tsuccess: function (data, textStatus, jqXHR) {\n\t\t\tvar tmp = JSON.parse(data);\n\t\t\tvar tmpp = {};\n\t\t\tif (vdatap.length != 0) {\n\t\t\t\tif (vdatap[0]['timestamp'] == tmp['timestamp']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (v in tmp) {\n\t\t\t\tif (tmp[v]['value'] != undefined) {\n\t\t\t\t\ttmp[v]['value'] = parseInt(tmp[v]['value']);\n\t\t\t\t\ttmpp[v.replace(\"MAIN.\",\"\")] = parseInt(tmp[v]['value']);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvdata.unshift(tmp);\n\t\t\tvdatap.unshift(tmpp);\n\t\t\tcompressData();\n\t\t\tupdateHitrate();\n\t\t\tif (reconstructTable) {\n\t\t\t\tconstructTable();\n\t\t\t\treconstructTable = false;\n\t\t\t\tsparklineDataHistory = {};\n\t\t\t} else {\n\t\t\t\tupdateTable();\n\t\t\t}\n\t\t}\n\t})\t\n}" ]
[ "0.8194134", "0.7530241", "0.7400833", "0.7087256", "0.7046263", "0.7034952", "0.7024674", "0.70074767", "0.6870079", "0.6845485", "0.67913896", "0.674652", "0.67213464", "0.67183614", "0.6713343", "0.67113453", "0.66795605", "0.6669361", "0.66481775", "0.662707", "0.6601899", "0.657162", "0.65606403", "0.655638", "0.65217113", "0.65217113", "0.64750165", "0.646709", "0.64363295", "0.6434249", "0.6421451", "0.63998646", "0.6386287", "0.63661504", "0.63577247", "0.63539404", "0.6342586", "0.63416326", "0.63210106", "0.6320295", "0.63104826", "0.63102597", "0.6288887", "0.62734956", "0.62655324", "0.62629074", "0.62582743", "0.62556267", "0.6241188", "0.6241179", "0.62346214", "0.6217598", "0.6214623", "0.6205576", "0.619918", "0.6195583", "0.61944944", "0.618842", "0.6185902", "0.6170561", "0.61691034", "0.6164895", "0.616328", "0.61525106", "0.61410844", "0.6136109", "0.6130272", "0.6124018", "0.611208", "0.6108903", "0.6105133", "0.6102973", "0.6101381", "0.60980666", "0.6095698", "0.6087058", "0.60766584", "0.6071951", "0.60653466", "0.60581475", "0.6054556", "0.6053551", "0.6053551", "0.60497123", "0.60487515", "0.6048703", "0.6041329", "0.60321003", "0.6031647", "0.60292256", "0.6025345", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6021561", "0.6020192" ]
0.0
-1
Aggregate data is gathered over the time unlike daily reports. Also aggregate data will contain sensitive data such as per_site_pi that is not sent to the server. Only user can view it from "My Footprint"
function initialize_aggregate_data() { var aggregate_data = {}; //When was this created? aggregate_data.initialized_time = new Date(); //Is user aware? How many times is he reviewing his own data? //This could be used as a feedback to the system about user's awareness //(hence an indirect metric about users' savviness) and //also to warn user. aggregate_data.num_viewed = 0; aggregate_data.total_time_spent = 0; //Stats about general sites access aggregate_data.num_total_sites = 0; aggregate_data.all_sites_total_time_spent = 0; aggregate_data.all_sites_stats_start = new Date(); //Stats and data about sites with user accounts (i.e. where user logs in) //user_account_sites[] is an associative array with key: site_name //Value corresponding to that is an object with following dictionary: //Each site is a record such as // site_name --> Primary Key // tts = Total Time Spent // tts_login = Total Time Spent Logged In // tts_logout = Total Time Spent Logged out // num_logins = Number of times logged in to a site // num_logouts = Number of times logged out of a site explicitly // latest_login = Last login time in the account // pwd_group = To group by sites using same password // site_category = Type of the site aggregate_data.num_user_account_sites = 0; aggregate_data.user_account_sites = {}; //Stats and data about sites where user browses but never logs in //IMPORTANT: This detailed list of sites is only maintained in aggregate stats. // Its never reported to the server. //non_user_account_sites[] is an associative array with key: site_name //Value corresponding to that is an object with following dictionary: //site_name, last_access_time, total_time_spent, site_category aggregate_data.num_non_user_account_sites = 0; aggregate_data.non_user_account_sites = {}; //Passwords data //pwd_groups is an associative array. Key is group name and values are list of sites //sharing that password aggregate_data.num_pwds = 0; // Password group name, sites in each group and password strength // Key: "Grp A" etc // Value: { // 'sites' : Array of domains, // 'strength' : Array of pwd strength, // 'full_hash' : A million times rotated hash value of salted passwd, // } aggregate_data.pwd_groups = {}; aggregate_data.pwd_similarity = {}; //Per site PI downloaded //Key: site name //Values: time downloaded // field_name --> field value aggregate_data.per_site_pi = {}; //This is used to assign a unique identifier to //each possible value of PI. //For eg. an address like "122, 5th ST SE, ATLANTA 30318, GA, USA" will //get an identifier like "address1" //Or a name like "Appu Singh" will get an identifier like "name3" //This is useful to show in reports page (so that the real values are // shown in the tooltip). Also it helps to always assign a unique //identifier even if that thing is downloaded multiple times over the //time. aggregate_data.pi_field_value_identifiers = {}; return aggregate_data; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function GetSummary() {\n var YearQuery = '';\n if (FilterList.DashboardFilterYear === '') {\n YearQuery =\n ' business_year = ' +\n \"'\" +\n moment().utcOffset('+08:00').format('YYYY') +\n \"'\";\n } else {\n YearQuery =\n ' business_year = ' + \"'\" + FilterList.DashboardFilterYear + \"'\";\n }\n\n var MonthQuery = '';\n if (FilterList.DashboardFilterMonth === '') {\n MonthQuery =\n ' and business_month = ' +\n \"'\" +\n moment().utcOffset('+08:00').format('MMMM') +\n \"'\";\n } else {\n MonthQuery =\n ' and business_month = ' + \"'\" + FilterList.DashboardFilterMonth + \"'\";\n }\n\n var TeamQuery = '';\n if (\n FilterList.DashboardFilterTeam === '' ||\n FilterList.DashboardFilterTeam === 'ALL'\n ) {\n TeamQuery = ' and team IN ' + global.TeamAccessList;\n } else {\n TeamQuery = ' and team = ' + \"'\" + FilterList.DashboardFilterTeam + \"'\";\n }\n\n var VendorQuery = '';\n if (\n FilterList.DashboardFilterVendor === '' ||\n FilterList.DashboardFilterVendor === 'ALL'\n ) {\n VendorQuery = ' and principal_name like ' + \"'%%' \";\n } else {\n VendorQuery =\n ' and principal_name = ' + \"'\" + FilterList.DashboardFilterVendor + \"'\";\n }\n\n dbperymtsat.transaction((tx) => {\n tx.executeSql(\n 'SELECT SUM(amount) as amount , SUM(target) as target FROM perymtsat_tbl where ' +\n YearQuery +\n MonthQuery +\n TeamQuery +\n VendorQuery +\n ' order by invoice_date asc ',\n [],\n (tx, results) => {\n var len = results.rows.length;\n if (len > 0) {\n // console.log(results.rows.item(0).target);\n //console.log(results.rows.item(0).amount);\n //setTotalSales();\n setTotalTarget(parseInt(results.rows.item(0).target));\n setTotalSales(parseInt(results.rows.item(0).amount));\n settotalSalesAnimation(true);\n // numbro(parseInt(results.rows.item(0).amount)).format({\n // thousandSeparated: true,\n // mantissa: 2,\n // }),\n\n // console.log(\n // 'Successfully got summary of ' +\n // FilterList.DashboardFilterMonth +\n // numbro(parseInt(results.rows.item(0).amount)).format({\n // thousandSeparated: true,\n // mantissa: 2,\n // }),\n // );\n }\n },\n SQLerror,\n );\n });\n }", "function aggregateData(region_id) {\n let sales = 0\n let numAccounts = 0\n let salesAg = []\n let agSales = 0\n\n for (var key in region_lookup) {\n if (region_lookup[key] == region_id) {\n salesAg.push(key)\n }\n }\n if(salesAg.length > 0) {\n salesAg.forEach(zip => {\n sales = ((sales + postal4_lookup[zip]))\n agSales = (sales / 1000000).toFixed(2)\n numAccounts = parseInt(numAccounts + postal4_count[zip])\n })\n }\n document.getElementById('totalsales').innerHTML = `$${agSales} M`\n document.getElementById('totalaccounts').innerHTML = numAccounts.toLocaleString()\n }", "function _aggregateCurrentSession() {\n if (!_firstAggregationComplete) {\n _firstAggregationComplete = true;\n }\n for (var cdnLocationId in sessionBandwidthMeasurements) {\n sessionBandwidthMeasurements[cdnLocationId] = _aggregateBandwidthMeasurements(sessionBandwidthMeasurements[cdnLocationId], config.histAggregationTimeSpanInSeconds);\n }\n _saveHistoricalData();\n }", "function generateRawStatistics() {\n console.log(self.selectDatasource);\n if(self.selectDatasource !== \"Select\" || self.selectDatasource !== null){\n homeService.getRawDataStatistics(self.selectDatasource).then(function(response){\n if(!response.data.isError && response.status == 200){\n //angular.copy(response.data.data, self.rawStatistics);\n //prepend newly created task to the task history array\n self.taskHistory.data.push(response.data);\n }\n else{\n console.log(\"Error: \" + response.data);\n }\n });\n }\n }", "function aggregateData(query, data) {\r\n var aggregate = create2DArray(7);\r\n var max = 0;\r\n var colors = {};\r\n for (var usageIx = 0; usageIx < query.usageTypes.length; usageIx++) {\r\n var usageType = query.usageTypes[usageIx];\r\n colors[usageType.name] = usageType.color;\r\n var toInclude = [];\r\n if (usageType.usageType == \"All\") {\r\n var allUsageTypes = getUsageTypes(usageType.cdrType);\r\n for (var i = 0; i < allUsageTypes.length; i++) {\r\n if (data.usageData[allUsageTypes[i]] !== undefined) {\r\n toInclude.push(data.usageData[allUsageTypes[i]]);\r\n }\r\n }\r\n } else {\r\n if (data.usageData[usageType.usageType] !== undefined) {\r\n toInclude.push(data.usageData[usageType.usageType]);\r\n }\r\n }\r\n // sum up the relevant data\r\n\t\tif(toInclude.length == 0) {\r\n\t\t\tcontinue; // no data for this uT, don't put in aggregation\r\n\t\t}\r\n var tmpAggregate = toInclude.reduce(function (ut1, ut2) {\r\n var res = {};\r\n for (var prop in ut1) {\r\n res[prop] = sum2DArray(ut1[prop], ut2[prop]);\r\n }\r\n return res;\r\n });\r\n\r\n var measureData = tmpAggregate[query.measureType];\r\n for (var x = 0; x < measureData.length; x++) {\r\n for (var y = 0; y < measureData[x].length; y++) {\r\n if (aggregate[x][y] === undefined) {\r\n aggregate[x][y] = {};\r\n }\r\n aggregate[x][y][usageType.name] = measureData[x][y];\r\n if (measureData[x][y] > max) {\r\n max = measureData[x][y];\r\n }\r\n }\r\n }\r\n }\r\n\r\n\tif(max == 0) {\r\n\t\t// no data at all for this query\r\n\t\treturn null;\r\n\t}\r\n\r\n return {\r\n aggregate: aggregate,\r\n maxUsage: max,\r\n colors: colors\r\n };\r\n}", "getSessionAggregates() {\n const aggregates = Object.keys(this._pendingAggregates).map((key) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return utils.dropUndefinedKeys(sessionAggregates);\n }", "aggregate() {\n let allRecords = this.props.allRecords;\n let startDate = this.getDateFromMonth(this.state.selectedMonth, \"\")\n let endDate = this.getDateFromMonth(this.state.selectedMonth, \"end\")\n let table = {}\n let data = []\n let type = this.state.type === \"expense\" ? 0 : 1;\n\n if (allRecords.length !== 0) {\n allRecords.map(element => {\n if (element.date >= startDate && element.date < endDate && element.type === type) {\n table[element.category.name] = table[element.category.name] + element.amount ||\n element.amount \n }\n })\n Object.keys(table).map(element => data.push({ name: element, value: table[element]}));\n data.sort((a, b) => (b.value - a.value));\n data.forEach((obj, index) => obj.fill = COLORS[index % COLORS.length]);\n }\n return data;\n }", "getAggregatedData(variable, options, success, error) {\n const deployedURL = appManager.getDeployedURL();\n if (deployedURL) {\n return this.aggregateData(deployedURL, variable, options, success, error);\n }\n }", "function getDashboardData(){\n var _serviceURI = '';\n $.each(DATA_METRICS_ARR, function(_index, _dataset){\n if((DATA_METRICS_ARR[_index] !== 'NA')){\n objloadedArr.push(DATA_METRICS_ARR[_index]);\n _serviceURI = DATA_SERVICE_URI + \"?dataset=\" + _dataset + \"&session_id=\" + session_id + \"&from=\" + from_date + \"&to=\" + to_date + \"&aggreg_type=\" + aggreg_typ;\n $engine.makeAJAXRequest(\n _serviceURI,\n 'get',\n {},\n '',\n 'json',\n {itemIndex: _index, dataSet: _dataset},\n true,\n graphDataSuccessHandler,\n dataErrorHandler\n );\n }\n });\n }", "publishOverviewData(data) {\n\t for (const [key, value] of Object.entries(data)) {\n\t if (!globals.globals.overviewStore.has(key)) {\n\t globals.globals.overviewStore.set(key, []);\n\t }\n\t if (value instanceof Array) {\n\t globals.globals.overviewStore.get(key).push(...value);\n\t }\n\t else {\n\t globals.globals.overviewStore.get(key).push(value);\n\t }\n\t }\n\t globals.globals.rafScheduler.scheduleRedraw();\n\t }", "function perform5minAggregat(siteId, startEpoch, endEpoch) {\n // create temp collection as placeholder for aggreagation results\n const aggrResultsName = `aggr${moment().valueOf()}`;\n const AggrResults = new Meteor.Collection(aggrResultsName);\n\n // gather all data, group by 5min epoch\n const pipeline = [\n {\n $match: {\n $and: [\n {\n epoch: {\n $gt: parseInt(startEpoch, 10),\n $lt: parseInt(endEpoch, 10)\n }\n }, {\n site: siteId\n }\n ]\n }\n }, {\n $project: {\n epoch5min: 1,\n epoch: 1,\n site: 1,\n subTypes: 1\n }\n }, {\n $group: {\n _id: '$epoch5min',\n site: {\n $last: '$site'\n },\n subTypes: {\n $push: '$subTypes'\n }\n }\n }, {\n $out: aggrResultsName\n }\n ];\n\n Promise.await(LiveData.rawCollection().aggregate(pipeline, { allowDiskUse: true }).toArray());\n\n // create new structure for data series to be used for charts\n AggrResults.find({}).forEach((e) => {\n const subObj = {};\n subObj._id = `${e.site}_${e._id}`;\n subObj.site = e.site;\n subObj.epoch = e._id;\n const subTypes = e.subTypes;\n const aggrSubTypes = {}; // hold aggregated data\n\n for (let i = 0; i < subTypes.length; i++) {\n for (const subType in subTypes[i]) {\n if (subTypes[i].hasOwnProperty(subType)) {\n const data = subTypes[i][subType];\n let numValid = 1;\n var newkey;\n\n // if flag is not existing, put 9 as default, need to ask Jim?\n if (data[0].val === '') {\n data[0].val = 9;\n }\n if (data[0].val !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n\n if (subType.indexOf('RMY') >= 0) { // HNET special calculation for wind data\n // get windDir and windSpd\n let windDir;\n let windSpd;\n let windDirUnit;\n let windSpdUnit;\n for (let j = 1; j < data.length; j++) {\n if (data[j].val === '' || isNaN(data[j].val)) { // taking care of empty or NaN data values\n numValid = 0;\n }\n if (data[j].metric === 'WD') {\n windDir = data[j].val;\n windDirUnit = data[j].unit;\n }\n if (data[j].metric === 'WS') {\n windSpd = data[j].val;\n windSpdUnit = data[j].unit;\n }\n }\n\n // Convert wind speed and wind direction waves into wind north and east component vectors\n const windNord = Math.cos(windDir / 180 * Math.PI) * windSpd;\n const windEast = Math.sin(windDir / 180 * Math.PI) * windSpd;\n\n let flag = data[0].val;\n\n if (flag !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n\n // automatic flagging of high wind speed values/flag with 9(N)\n if (windSpd >= 35) {\n numValid = 0;\n flag = 9;\n }\n\n // Aggregate data points\n newkey = subType + '_' + 'RMY';\n if (!aggrSubTypes[newkey]) {\n aggrSubTypes[newkey] = {\n sumWindNord: windNord,\n sumWindEast: windEast,\n avgWindNord: windNord,\n avgWindEast: windEast,\n numValid: numValid,\n totalCounter: 1, // initial total counter\n flagstore: [flag], // store all incoming flags in case we need to evaluate\n WDunit: windDirUnit, // use units from last data point in the aggregation\n WSunit: windSpdUnit // use units from last data point in the aggregation\n };\n } else {\n if (numValid !== 0) { // taking care of empty data values\n aggrSubTypes[newkey].numValid += numValid;\n aggrSubTypes[newkey].sumWindNord += windNord; // holds sum until end\n aggrSubTypes[newkey].sumWindEast += windEast;\n aggrSubTypes[newkey].avgWindNord = aggrSubTypes[newkey].sumWindNord / aggrSubTypes[newkey].numValid;\n aggrSubTypes[newkey].avgWindEast = aggrSubTypes[newkey].sumWindEast / aggrSubTypes[newkey].numValid;\n }\n aggrSubTypes[newkey].totalCounter += 1; // increase counter\n aggrSubTypes[newkey].flagstore.push(flag); // store incoming flag\n }\n } else { // normal aggreagation for all other subTypes\n for (let j = 1; j < data.length; j++) {\n newkey = subType + '_' + data[j].metric;\n\n if (data[j].val === '' || isNaN(data[j].val)) { // taking care of empty or NaN data values\n numValid = 0;\n }\n\n const flag = data[0].val;\n\n if (flag !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n\n if (!aggrSubTypes[newkey]) {\n if (numValid === 0) {\n data[j].val = 0;\n }\n\n aggrSubTypes[newkey] = {\n sum: Number(data[j].val),\n 'avg': Number(data[j].val),\n 'numValid': numValid,\n 'totalCounter': 1, // initial total counter\n 'flagstore': [flag], // store all incoming flags in case we need to evaluate\n unit: data[j].unit // use unit from first data point in aggregation\n };\n } else {\n if (numValid !== 0) { // keep aggregating only if numValid\n aggrSubTypes[newkey].numValid += numValid;\n aggrSubTypes[newkey].sum += Number(data[j].val); // holds sum until end\n if (aggrSubTypes[newkey].numValid !== 0) {\n aggrSubTypes[newkey].avg = aggrSubTypes[newkey].sum / aggrSubTypes[newkey].numValid;\n }\n }\n aggrSubTypes[newkey].totalCounter += 1; // increase counter\n aggrSubTypes[newkey].flagstore.push(flag); // /store incoming flag\n }\n numValid = 1; // reset numvalid\n }\n }\n }\n }\n }\n\n // transform aggregated data to generic data format using subtypes etc.\n const newaggr = {};\n for (const aggr in aggrSubTypes) {\n if (aggrSubTypes.hasOwnProperty(aggr)) {\n const split = aggr.lastIndexOf('_');\n const instrument = aggr.substr(0, split);\n const measurement = aggr.substr(split + 1);\n if (!newaggr[instrument]) {\n newaggr[instrument] = {};\n }\n\n const obj = aggrSubTypes[aggr]; // makes it a little bit easier\n\n // dealing with flags\n if ((obj.numValid / obj.totalCounter) >= 0.75) {\n obj.Flag = 1; // valid\n } else {\n // find out which flag was majority\n const counts = {};\n for (let k = 0; k < obj.flagstore.length; k++) {\n counts[obj.flagstore[k]] = 1 + (counts[obj.flagstore[k]] || 0);\n }\n const maxObj = _.max(counts, function(obj) {\n return obj;\n });\n const majorityFlag = (_.invert(counts))[maxObj];\n obj.Flag = majorityFlag;\n }\n\n if (measurement === 'RMY') { // special treatment for wind measurements\n if (!newaggr[instrument].WD) {\n newaggr[instrument].WD = [];\n }\n if (!newaggr[instrument].WS) {\n newaggr[instrument].WS = [];\n }\n const windDirAvg = (Math.atan2(obj.avgWindEast, obj.avgWindNord) / Math.PI * 180 + 360) % 360;\n const windSpdAvg = Math.sqrt((obj.avgWindNord * obj.avgWindNord) + (obj.avgWindEast * obj.avgWindEast));\n\n newaggr[instrument].WD.push({ metric: 'sum', val: 'Nan' });\n newaggr[instrument].WD.push({ metric: 'avg', val: windDirAvg });\n newaggr[instrument].WD.push({ metric: 'numValid', val: obj.numValid });\n newaggr[instrument].WD.push({ metric: 'unit', val: obj.WDunit });\n newaggr[instrument].WD.push({ metric: 'Flag', val: obj.Flag });\n\n newaggr[instrument].WS.push({ metric: 'sum', val: 'Nan' });\n newaggr[instrument].WS.push({ metric: 'avg', val: windSpdAvg });\n newaggr[instrument].WS.push({ metric: 'numValid', val: obj.numValid });\n newaggr[instrument].WS.push({ metric: 'unit', val: obj.WSunit });\n newaggr[instrument].WS.push({ metric: 'Flag', val: obj.Flag });\n } else { // all other measurements\n if (!newaggr[instrument][measurement]) {\n newaggr[instrument][measurement] = [];\n }\n\n // automatic flagging of aggregated values that are out of range for NO2 to be flagged with 9(N)\n if (instrument === '42i') {\n if (obj.avg < -0.5) {\n obj.Flag = 9;\n }\n }\n\n newaggr[instrument][measurement].push({ metric: 'sum', val: obj.sum });\n newaggr[instrument][measurement].push({ metric: 'avg', val: obj.avg });\n newaggr[instrument][measurement].push({ metric: 'numValid', val: obj.numValid });\n newaggr[instrument][measurement].push({ metric: 'unit', val: obj.unit });\n newaggr[instrument][measurement].push({ metric: 'Flag', val: obj.Flag });\n }\n }\n }\n\n subObj.subTypes = newaggr;\n\n AggrData.insert(subObj, function(error, result) {\n // only update aggregated values if object already exists to avoid loosing edited data flags\n if (result === false) {\n Object.keys(newaggr).forEach(function(newInstrument) {\n Object.keys(newaggr[newInstrument]).forEach(function(newMeasurement) {\n // test whether aggregates for this instrument/measurement already exists\n const qry = {};\n qry._id = subObj._id;\n qry[`subTypes.${newInstrument}.${newMeasurement}`] = { $exists: true };\n\n if (AggrData.findOne(qry) === undefined) {\n const newQuery = {};\n newQuery.epoch = subObj.epoch;\n newQuery.site = subObj.site;\n const $set = {};\n const newSet = [];\n newSet[0] = newaggr[newInstrument][newMeasurement][0];\n newSet[1] = newaggr[newInstrument][newMeasurement][1];\n newSet[2] = newaggr[newInstrument][newMeasurement][2];\n newSet[3] = newaggr[newInstrument][newMeasurement][3];\n newSet[4] = newaggr[newInstrument][newMeasurement][4];\n $set['subTypes.' + newInstrument + '.' + newMeasurement] = newSet;\n\n // add aggregates for new instrument/mesaurements\n AggrData.findAndModify({\n query: newQuery,\n update: {\n $set: $set\n },\n upsert: false,\n new: true\n });\n } else {\n const query0 = {};\n query0._id = subObj._id;\n query0[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'sum';\n const $set0 = {};\n $set0[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][0].val;\n AggrData.update(query0, { $set: $set0 });\n const query1 = {};\n query1._id = subObj._id;\n query1[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'avg';\n const $set1 = {};\n $set1[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][1].val;\n AggrData.update(query1, { $set: $set1 });\n const query2 = {};\n query2._id = subObj._id;\n query2[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'numValid';\n const $set2 = {};\n $set2[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][2].val;\n AggrData.update(query2, { $set: $set2 });\n const query3 = {};\n query3._id = subObj._id;\n query3[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'unit';\n const $set3 = {};\n $set3[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][3].val;\n AggrData.update(query3, { $set: $set3 });\n const query4 = {};\n query4._id = subObj._id;\n query4[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'Flag';\n const $set4 = {};\n $set4[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][4].val;\n AggrData.update(query4, { $set: $set4 });\n }\n });\n });\n }\n });\n });\n // drop temp collection that was placeholder for aggreagation results\n AggrResults.rawCollection().drop();\n}", "async dealReport() {\n return await global.db\n .collection('pipedrive-deal')\n .aggregate([\n {\n $match: { status: 'won' }\n },\n {\n $addFields: {\n day: {\n $dateToString: { format: '%d-%m-%Y', date: '$date' }\n }\n }\n },\n {\n $group: {\n _id: '$day',\n vendas: { $sum: '$value' }\n }\n }\n ])\n .toArray();\n }", "function analyticData(allObjects, callback) {\n allObjects = allObjects.check_data_exist;\n var finalData = {};\n if (allObjects.data === 'DataFromDb') {\n finalData = {\n metricId: allObjects.metricId,\n data: 'DataFromDb',\n queryResults: results,\n channelId: results.metric.channelId\n };\n callback(null, finalData);\n }\n else {\n var apiQuery = {}\n if (allObjects.api === configAuth.googleApiTypes.mcfApi) {\n apiQuery = {\n 'key': configAuth.googleAuth.clientSecret,\n 'ids': 'ga:' + allObjects.object.channelObjectId,\n 'start-date': allObjects.startDate,\n 'end-date': allObjects.endDate,\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true,\n }\n var analytics = googleapis.analytics({\n version: 'v3',\n auth: allObjects.oauth2Client\n }).data.mcf.get;\n callGoogleApi(apiQuery);\n }\n else if (allObjects.api === configAuth.googleApiTypes.youtubeApi) {\n apiQuery = {\n 'access_token': allObjects.oauth2Client.credentials.access_token,\n 'ids': 'channel==' + allObjects.object.channelObjectId,\n 'start-date': allObjects.startDate,\n 'end-date': allObjects.endDate,\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true,\n }\n var analytics = googleapis.youtubeAnalytics({\n version: 'v1',\n auth: allObjects.oauth2Client\n }).reports.query;\n callGoogleApi(apiQuery);\n }\n else {\n apiQuery = {\n 'auth': allObjects.oauth2Client,\n 'ids': 'ga:' + allObjects.object.channelObjectId,\n 'start-date': allObjects.startDate,\n 'end-date': allObjects.endDate,\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true\n }\n var analytics = googleapis.analytics({version: 'v3', auth: oauth2Client}).data.ga.get;\n callGoogleApi(apiQuery);\n }\n /**Method to call the google api\n * @param oauth2Client - set credentials\n */\n var googleResult = [];\n\n function callGoogleApi(apiQuery) {\n analytics(apiQuery, function (err, result) {\n if (err)\n callback(err)\n else {\n if (result.rows != undefined) {\n for (var i = 0; i < result.rows.length; i++) {\n googleResult.push(result.rows[i]);\n }\n }\n else\n googleResult = 'No Data';\n if (result.nextLink != undefined) {\n var splitRequiredQueryData = result.nextLink.split('&');\n if (allObjects.api === configAuth.googleApiTypes.mcfApi) {\n apiQuery = {\n 'key': configAuth.googleAuth.clientSecret,\n 'ids': 'ga:' + allObjects.object.channelObjectId,\n 'start-date': splitRequiredQueryData[3].substr(splitRequiredQueryData[3].indexOf('=') + 1),\n 'end-date': splitRequiredQueryData[4].substr(splitRequiredQueryData[4].indexOf('=') + 1),\n 'start-index': splitRequiredQueryData[5].substr(splitRequiredQueryData[5].indexOf('=') + 1),\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true,\n }\n }\n else if (allObjects.api === configAuth.googleApiTypes.youtubeApi) {\n apiQuery = {\n 'key': configAuth.youTubeAuth.clientSecret,\n 'ids': 'channel==' + allObjects.object.channelObjectId,\n 'start-date': splitRequiredQueryData[3].substr(splitRequiredQueryData[3].indexOf('=') + 1),\n 'end-date': splitRequiredQueryData[4].substr(splitRequiredQueryData[4].indexOf('=') + 1),\n 'start-index': splitRequiredQueryData[5].substr(splitRequiredQueryData[5].indexOf('=') + 1),\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true,\n }\n }\n else {\n apiQuery = {\n 'auth': allObjects.oauth2Client,\n 'ids': 'ga:' + allObjects.object.channelObjectId,\n 'start-date': splitRequiredQueryData[3].substr(splitRequiredQueryData[3].indexOf('=') + 1),\n 'end-date': splitRequiredQueryData[4].substr(splitRequiredQueryData[4].indexOf('=') + 1),\n 'start-index': splitRequiredQueryData[5].substr(splitRequiredQueryData[5].indexOf('=') + 1),\n 'dimensions': allObjects.dimension,\n 'metrics': allObjects.metricName,\n prettyPrint: true\n }\n }\n callGoogleApi(apiQuery);\n }\n else {\n finalData = {\n metricId: allObjects.metricId,\n data: googleResult,\n queryResults: results,\n channelId: results.metric.channelId,\n startDate: allObjects.startDate,\n endDate: allObjects.endDate,\n metric: allObjects.metric\n };\n callback(null, finalData);\n }\n }\n });\n }\n }\n }", "function exportAggregate() {\n\t/*\n\tOnly data element in datasets included. Include config option for \"placeholder\"\n\tdatasets that is only used to get dependencies, but where the actual dataset is not \n\tincluded in the export file. This also includes other data elements used in \n\tindicators, like those for population.\n\t\n\tFavourites and indicator formulas should still be checked for data elements, \n\tcategory option groups, legend sets etc. For legend sets, category option groups etc\n\tthey should be included, but for data elements we should only show a warning that \n\tthey need to be added to a data set to be included.\n\t*/\n\n\tconsole.log(\"1. Downloading metadata\");\n\n\t//Do initial dependency export\n\tvar promises = [\n\t\tdependencyExport(\"dataSet\", currentExport.dataSetIds),\n\t\tdependencyExport(\"dashboard\", currentExport.dashboardIds),\n\t\tlimitedDependencyExport(currentExport.exportDataSetIds),\n\t\tcustomObjects()\n\t];\n\tQ.all(promises).then(function (results) {\n\n\n\t\t//Get indicators and categoryOptionGroupSets from favourites and groups\n\t\t//Get validation rules and groups from conf file\n\t\t//Get data element and indicator groups from conf files\n\t\tpromises = [\n\t\t\tindicators(),\n\t\t\tcategoryOptionGroupSetStructure(),\n\t\t\tvalidationRules(),\n\t\t\tsaveObject(\"dataElementGroups\", currentExport.dataElementGroupIds),\n\t\t\tsaveObject(\"indicatorGroups\", currentExport.indicatorGroupIds),\n\t\t\tuserGroups(),\n\t\t\tusers()\n\t\t];\n\t\tQ.all(promises).then(function (results) {\n\n\t\t\t//Get legends from data elements, indicators and favourites\n\t\t\t//Get indicator types from indicators\n\t\t\t//Get predictors based on data elements\n\t\t\tpromises = [\n\t\t\t\tindicatorTypes(),\n\t\t\t\tlegendSets(),\n\t\t\t\tpredictors()\n\t\t\t];\n\t\t\tQ.all(promises).then(function (results) {\n\n\t\t\t\tprocessAggregate();\n\n\t\t\t});\n\n\t\t});\n\n\t});\n\n}", "function aggregateData() {\n\n // Nest the data by year, counting the number of cases in every issue area\n // in each year\n NS.dataByYear = d3.nest()\n .key(function(d) { return +d.term; })\n .rollup(function(v) {\n // v is an array of all cases in a given year\n \n // set up aggregate information storage for both \"real\" issue areas and\n // \"aggregates\"\n var aggregates = [];\n for(var issueArea = 0; issueArea < NS.issueAreas.length; issueArea++) {\n aggregates[issueArea] = 0;\n }\n for(var i = 0; i < v.length; i++) {\n d = v[i]; // shorthand for the current data in the style of d3 functions\n //set the issue area to the issue area in the dataset if the issue area is\n // valid; otherwise, set to the \"other\" category.\n var issueArea = (d.issueArea != \"\" && d.issueArea != \"NA\") ? +d.issueArea - 1 : 14;\n aggregates[issueArea]++;\n }\n\n return aggregates;\n })\n .entries(NS.dataset);\n}", "onSumNoAggregate(data) {\n return new Promise((resolve, reject) => {\n console.log('Received:', JSON.stringify(data));\n resolve();\n });\n }", "function distill_analytics(table, filter) {\n\tswitch (filter) {\n\t\tcase \"all\":\n\t\t\t// Don't filter the checkins.\n\t\t\tvar grouped = google.visualization.data.group(table, [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"month\":\n\t\t\t// Filter the checkins by month.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - milliseconds_in_month)), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"quarter\":\n\t\t\t// Filter the checkins by quarter.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - (milliseconds_in_month * 3))), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"half\":\n\t\t\t// Filter the checkins by half.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - (milliseconds_in_month * 6))), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"year\":\n\t\t\t// Filter the checkins by year.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - milliseconds_in_year)), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t}\n}", "function Aggregate() {}", "function loadSummary(data) {\n console.log(\"Summary store\");\n if(data) _summary = data.data;\n console.log(_summary);\n}", "function runReport() {\n /**\n * TODO(developer): Uncomment this variable and replace with your\n * Google Analytics 4 property ID before running the sample.\n */\n const propertyId = 'YOUR-GA4-PROPERTY-ID';\n\n var metric = AnalyticsData.newMetric();\n metric.name = 'activeUsers';\n\n var dimension = AnalyticsData.newDimension();\n dimension.name = 'city';\n\n var dateRange = AnalyticsData.newDateRange();\n dateRange.startDate = '2020-03-31';\n dateRange.endDate = 'today';\n\n var request = AnalyticsData.newRunReportRequest();\n request.dimensions = [dimension];\n request.metrics = [metric];\n request.dateRanges = dateRange;\n\n var report = AnalyticsData.Properties.runReport(request,\n 'properties/' + propertyId);\n if (report.rows) {\n var spreadsheet = SpreadsheetApp.create('Google Analytics Report');\n var sheet = spreadsheet.getActiveSheet();\n\n // Append the headers.\n var dimensionHeaders = report.dimensionHeaders.map(\n function(dimensionHeader) {\n return dimensionHeader.name;\n });\n var metricHeaders = report.metricHeaders.map(\n function(metricHeader) {\n return metricHeader.name;\n });\n var headers = [...dimensionHeaders, ...metricHeaders];\n\n sheet.appendRow(headers);\n\n // Append the results.\n var rows = report.rows.map( function(row) {\n var dimensionValues = row.dimensionValues.map(\n function(dimensionValue) {\n return dimensionValue.value;\n });\n var metricValues = row.metricValues.map(\n function(metricValues) {\n return metricValues.value;\n });\n return [...dimensionValues, ...metricValues];\n });\n\n sheet.getRange(2, 1, report.rows.length, headers.length)\n .setValues(rows);\n\n Logger.log('Report spreadsheet created: %s',\n spreadsheet.getUrl());\n } else {\n Logger.log('No rows returned.');\n }\n}", "function aggregateUsage(data) {\n var chartData = [];\n\n for(var i = 0; i < 27; i++) {\n chartData[i] = 0;\n }\n\n for( var f in data ) {\n for( var j = 0; j < data[ f ].stack.length; j++ ) {\n chartData[j] += data[ f ].stack[ j ] + data[ f ].fugitive[ j ];\n }\n }\n\n return chartData;\n }", "function createReports() {\r\n var RawDataReport = AdWordsApp.report(\"SELECT Domain, Clicks \" + \"FROM AUTOMATIC_PLACEMENTS_PERFORMANCE_REPORT \" + \"WHERE Clicks > 0 \" + \"AND Conversions < 1 \" + \"DURING LAST_7_DAYS\");\r\n RawDataReport.exportToSheet(RawDataReportSheet);\r\n}", "function genReport(data){\n var byweek = {};\n function groupweek(value, index, array){\n if(value.Owner === window.myName){\n var d = new Date(value['Datetime']);\n d = Math.floor(d.getTime()/weekfactor);\n byweek[d] = byweek[d] || [];\n byweek[d].push(value);\n }\n\n }\n data.map(groupweek);\n return byweek;\n}", "function getAgg(form, data) {\n\talerts_on = true;\n\tgetAgg2(form, data);\n\talerts_on = false;\n\tgetAgg2(form, data);\n}", "async function getCaseStatistics(caseId) {\n const caseStatistics = {\n views: 0,\n opens: 0,\n canAfford: 0,\n totalViews: 0,\n totalOpens: 0,\n totalCanAfford: 0,\n firstViews: 0,\n firstOpens: 0,\n totalFirstOpens: 0,\n totalFirstViews: 0\n };\n\n // collect first opens/views\n const firstViewsOpens = await UserStatistics.aggregate([\n {\n $group: {\n _id: {\n views: { $eq: [\"$firstViewedCase\", mongoose.Types.ObjectId(caseId)] },\n opens: { $eq: [\"$firstOpenedCase\", mongoose.Types.ObjectId(caseId)] }\n },\n views: {\n $sum: {\n $cond: [{ $ne: [{ $type: \"$firstViewedCase\" }, \"missing\"] }, 1, 0]\n }\n },\n opens: {\n $sum: {\n $cond: [{ $ne: [{ $type: \"$firstOpenedCase\" }, \"missing\"] }, 1, 0]\n }\n }\n }\n }\n ]);\n\n for (const elem of firstViewsOpens) {\n if (elem._id.views === true) {\n caseStatistics.firstViews += elem.views;\n } else if (elem._id.opens === true) {\n caseStatistics.firstOpens += elem.opens;\n }\n\n caseStatistics.totalFirstViews += elem.views;\n caseStatistics.totalFirstOpens += elem.opens;\n }\n\n const totalViewsOpens = await CaseStatistics.aggregate([\n {\n $group : { \n _id : \"$case\",\n opensNum: { $sum: \"$opens.all\" },\n viewsNum: { $sum: \"$views.all\" },\n canAffordNum: { $sum: \"$views.canAfford\" },\n }\n },\n {\n $project: {\n _id: 0,\n opensNum: 1,\n viewsNum: 1,\n canAffordNum: 1,\n case: \"$_id\",\n }\n },\n {\n $group: {\n _id: { $eq: [\"$case\", mongoose.Types.ObjectId(caseId)] },\n opensNum: { $sum: \"$opensNum\" },\n viewsNum: { $sum: \"$viewsNum\" },\n canAffordNum: { $sum: \"$canAffordNum\" }\n }\n }\n ]);\n\n for (const elem of totalViewsOpens) {\n if (elem._id === true) {\n caseStatistics.views += elem.viewsNum;\n caseStatistics.opens += elem.opensNum;\n caseStatistics.canAfford += elem.canAffordNum;\n }\n\n caseStatistics.totalViews += elem.viewsNum;\n caseStatistics.totalOpens += elem.opensNum;\n caseStatistics.totalCanAfford += elem.canAffordNum;\n }\n\n return caseStatistics;\n}", "function getResourcesData(data) {\n var indexName = data.company;\n var startdate = data.strdate + ' 00:00:00';\n var enddate = data.enddate + ' 23:59:59';\n var from = 0;\n var size = 10;\n var filter = {};\n var regionfilter = {};\n var productfilter = {};\n var sorting_order = data.shortingorder;\n var sorting_field = data.sortingfield;\n\n if (data.size) {\n size = data.size;\n }\n\n if (data.currentpage) {\n from = ((data.currentpage - 1) * size);\n }\n\n if (data.filter != \"\") {\n filter = {\n \"multi_match\": {\n \"query\": data.filter,\n \"fields\": [\"ResourceId\", \"aws:*\", \"user:*\"],\n \"type\": \"phrase_prefix\"\n }\n };\n }\n\n if (data.region != \"\") {\n regionfilter = { \"match\": { \"__AvailabilityRegion\": data.region } };\n }\n\n if (data.product != \"\") {\n productfilter = { \"match\": { \"ProductName\": data.product } };\n }\n var sort = {};\n sort[sorting_field] = { \"order\": sorting_order };\n\n var query = {\n \"from\": from,\n \"size\": size,\n \"sort\": [sort],\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"UsageStartDate\": {\n \"gte\": startdate,\n \"format\": \"yyyy-MM-dd HH:mm:ss\"\n }\n }\n },\n {\n \"range\": {\n \"UsageEndDate\": {\n \"lte\": enddate,\n \"format\": \"yyyy-MM-dd HH:mm:ss\"\n }\n }\n },\n filter,\n productfilter,\n regionfilter\n\n ]\n\n }\n\n },\n \"aggs\": {\n \"total_cost\": {\n \"sum\": {\n \"field\": \"BlendedCost\"\n }\n },\n \"total_quantity\": {\n \"sum\": {\n \"field\": \"UsageQuantity\"\n }\n }\n },\n \"_source\": [\n \"ProductName\",\n \"UsageType\",\n \"__AvailabilityRegion\",\n \"ItemDescription\",\n \"UsageStartDate\",\n \"UsageEndDate\",\n \"UsageQuantity\",\n \"BlendedRate\",\n \"BlendedCost\",\n \"Operation\",\n \"aws:*\",\n \"user:*\",\n \"ResourceId\"\n ]\n };\n\n //debugQuery(query);\n\n return elasticClient.search({\n index: indexName,\n body: query\n })\n\n}", "finalData(hrData) {\r\n const scope = this;\r\n let totalOccupancy, counter;\r\n scope.tempData.occupancy = [];\r\n\r\n scope.tempData.forEach(v => {\r\n totalOccupancy = 0;\r\n counter = 0;\r\n hrData.forEach(d => {\r\n if((new Date(d.Time)).getHours() === v.time){\r\n v.occupancy.push(d.mean);\r\n totalOccupancy = totalOccupancy + d.mean;\r\n counter++;\r\n }\r\n });\r\n\r\n if(counter > 0)\r\n v.average = totalOccupancy / counter;\r\n else\r\n v.average = 0;\r\n });\r\n\r\n return scope.tempData;\r\n }", "function summarizedSalesByProduct() {\n // var dataSummarized = [];\n var data = get.mappedSalesData();\n\n return data.reduce(function(allSummary, week){\n var keeptrack = {};\n allSummary.push(week.reduce(function(weekSum, sale) {\n if (!keeptrack[sale.product]) {\n keeptrack[sale.product] = 1;\n weekSum.push({week: sale.week, category: sale.category, product: sale.product, quantity: sale.quantity, unitprice: sale.unitprice, revenue: sale.revenue, totalcost: sale.totalcost, profit: sale.profit });\n } else {\n var product = weekSum.find(function(item) {return item.product === sale.product;});\n product.quantity += sale.quantity;\n product.revenue += sale.revenue;\n product.totalcost += sale.totalcost;\n product.profit += sale.profit;\n\n if (typeof product.unitprice!== 'object' && product.unitprice!==sale.unitprice) {\n product.unitprice = [product.unitprice, sale.unitprice];\n } else if (typeof product.unitprice === 'object' && product.unitprice.indexOf(sale.unitprice)===-1) {\n product.unitprice.push(sale.unitprice);\n }\n }\n\n return weekSum;\n },[])\n );\n return allSummary;\n },[]);\n // return dataSummarized;\n }", "function megaCalculation() {\n // getting all the records by making api calls\n allUsers = getRecordsUserDetails();\n records = getRecordsTransactionHistory();\n\n adminID = document.getElementById(\"userGuid\").value;\n // calculating all the performance report ddda\n MegaData = createMegaData();\n\n BuyerUsers = MegaData[0];\n\n MerchantUsers = MegaData[1];\n Items = MegaData[2];\n Pays = MegaData[3];\n\n MerchantHistory = calculateHistoricalData(\"Merchant\");\n MerchantHistory = MerchantHistory[0];\n var Hist = calculateHistoricalData(\"User\")\n\n BuyerHistory = Hist[0];\n PaymentHistory = Hist[1];\n itemHistory = Hist[2];\n\n\n // TODO: fix the logins for new marketplaces\n temp = new Date();\n currDate = temp.getDate() + \"-\" + (Number(temp.getMonth()) + 1) + \"-\" + temp.getFullYear();\n // locationData = calculateLocation();\n loginData = retrieveCfValueJSON(\"loginCount\");\n var loginTemp;\n if (loginData) {\n loginData = loginData.Values[0];\n loginTemp = $.extend(true, {}, loginData);\n latestDate = loginData.latestData.date.split(\"-\");\n delete loginData.latestData.date;\n if (!loginData.historicalData[latestDate[2]]) {\n loginData.historicalData[latestDate[2]] = {};\n }\n if (!loginData.historicalData[latestDate[2]][latestDate[1] - 1]) {\n loginData.historicalData[latestDate[2]][latestDate[1] - 1] = {}\n };\n loginData.historicalData[latestDate[2]][latestDate[1] - 1][latestDate[0]] = loginData.latestData;\n } else {\n var loginc = { \"latestData\": { \"date\": currDate }, \"historicalData\": {} };\n createCfImplementationsJSON(\"loginCount\", loginc, false);\n loginData = loginc;\n loginTemp = loginc;\n }\n\n loginData = loginData.historicalData;\n loginData = getCumulative(loginData, null, merchStartDate, merchEndDate, {}, true);\n console.log(\"login data inside mega calculation\", loginData);\n\n\n currMerchData = getCumulative(MerchantHistory, keyName[\"Merchant\"], merchStartDate, merchEndDate, MerchantUsers);\n\n marketplaceStartDate -= 86400000\n\n\n // setting all the required variables\n userRecords = allUsers;\n transactionRecords = records;\n // calculating all different types of metrics\n userData = retUserData(userRecords);\n transacationData = retTransactionData(transactionRecords);\n perMerchantData = calculateRatio(userRecords, transactionRecords);\n allData = Object.assign(userData, transacationData, perMerchantData);\n trans = calculateTransactions(transactionRecords);\n msd = new Date(marketplaceStartDate);\n temp = calculateRatioRegisteredBuyers(transactionRecords);\n temp = temp[\"historicData\"];\n allData[metrics[10]] = fillInMonth(temp);\n\n // TODO: have to fix logins\n allData[metrics[11]] = displayLoginCount(loginTemp);\n console.log(\"display format of login data\", allData[metrics[11]])\n\n allData[metrics[12]] = calculateAveragePurchasesPerBuyer(trans, allData[metrics[0]]);\n allData[metrics[13]] = calculateAverageOrderValue(allData[metrics[2]], trans);\n}", "async function runReport() {\n // [START analyticsdata_run_report]\n const [response] = await analyticsDataClient.runReport({\n property: `properties/${propertyId}`,\n dateRanges: [\n {\n startDate: '2020-03-31',\n endDate: 'today',\n },\n ],\n dimensions: [\n {\n name: 'city',\n },\n ],\n metrics: [\n {\n name: 'activeUsers',\n },\n ],\n });\n // [END analyticsdata_run_report]\n\n // [START analyticsdata_run_report_response]\n console.log('Report result:');\n response.rows.forEach(row => {\n console.log(row.dimensionValues[0], row.metricValues[0]);\n });\n // [END analyticsdata_run_report_response]\n }", "function summarizeIncidentReport(report) {\n return summarizeIncident(report);\n}", "_parseDailySummary(body) {\n const sentences = this._extractPdfSentences(body);\n // console.log(sentences);\n\n // Regex the items we want from the sentences.\n const stateDataREs = {\n cases: /were (\\d+) cases/,\n deaths: /with (\\d+) deaths/,\n hospitalized: /been (\\d+) of .* cases that have been hospitalized/,\n testedNeg: /(\\d+) negative tests/\n };\n\n const rawStateData = Object.keys(stateDataREs).reduce((hsh, key) => {\n const re = stateDataREs[key];\n const text = sentences.filter(s => {\n return re.test(s);\n });\n if (text.length === 0) console.log(`No match for ${key} re ${re}`);\n if (text.length > 1) console.log(`Ambiguous match for ${key} re ${re} (${text.join(';')})`);\n const m = text[0].match(re);\n\n return {\n ...hsh,\n [key]: parse.number(m[1])\n };\n }, {});\n\n rawStateData.tested = rawStateData.cases + rawStateData.testedNeg;\n delete rawStateData.testedNeg;\n\n const data = [];\n\n const countyRE = /^(.*) County (\\d+)$/;\n const countyData = sentences.filter(s => {\n return countyRE.test(s);\n });\n countyData.forEach(lin => {\n const cm = lin.trim().match(countyRE);\n // console.log(cm);\n const rawName = `${cm[1]} County`;\n const countyName = geography.addCounty(rawName);\n const cases = cm[2];\n if (this._counties.includes(countyName)) {\n data.push({\n county: countyName,\n cases: parse.number(cases)\n });\n }\n });\n\n const summedData = transform.sumData(data);\n data.push(summedData);\n\n data.push({ ...rawStateData, aggregate: 'county' });\n\n const result = geography.addEmptyRegions(data, this._counties, 'county');\n // no sum because we explicitly add it above\n\n return result;\n }", "function getMyStats() {\n var user = getActiveUserEmail();\n var findQuery = {\n user : user\n };\n var q = JSON.stringify(findQuery);\n var fields = JSON.stringify({\n right : 1,\n wrong : 1,\n _id : 0\n });\n var url = properties.mongoStatsUrl + \"?apiKey=\" + properties.mongoLabApiKey + \"&q=\" + encodeURIComponent(q) + \"&f=\" + encodeURIComponent(fields)\n + \"&l=100000\";\n var response = fetchUrlWithLogging(url, \"Mongo q: \" + q, {});\n var responseText = response.getContentText();\n // vrati pole dokumentov obsahujucich right a wrong hodnoty\n var data = JSON.parse(responseText);\n return aggregateSumRightWrong(data);\n}", "timesheets() {\n var from = FlowRouter.getParam(\"from\");\n var to = FlowRouter.getParam(\"to\");\n var projectId = FlowRouter.getParam(\"projectId\");\n var timesheets = [];\n var result = null;\n\n //if it's date range, making sure query reflects the range\n if (from == null || to == null) {\n result = Timesheets.find();\n } else {\n result = Timesheets.find({\n $and:[\n {'date': {$gte: from}}, \n {'date': {$lte: to}}\n ]});\n }//end of date range if-else statement\n \n \n var fectchResult = result.fetch();\n var dateString = '';\n \n //consolidatedArray.push.apply(fectchResult);\n fectchResult.forEach(function (entry) {\n var timechunks = Timechunks.find({$and:[{'timesheet': entry._id}, {'project': projectId}]}).fetch();\n if(FlowRouter.getParam(\"reportType\") == \"daily\") {\n dateString = getStringDate(entry.date, 'dddd, MMMM Do YYYY');\n\n } else if (FlowRouter.getParam(\"reportType\") == \"weekly\" || FlowRouter.getParam(\"reportType\") == \"date_range\") {\n var curr = new Date(entry.date);\n var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week\n var last = first + 6; // last day is the first day + 6\n var dateString = getStringDate(new Date(curr.setDate(first)), 'MMMM Do YYYY') + \" - \" + getStringDate(new Date(curr.setDate(last)), 'MMMM Do YYYY');\n\n } else if(FlowRouter.getParam(\"reportType\") == \"monthly\") {//Check if monthly\n var dateString = getStringDate(entry.date, 'MMMM YYYY');\n }\n \n timechunks.forEach(function (timechunck) {\n var key = dateString;\n var userId = timechunck.userInfo[\"userId\"];\n console.log(\"Printng userId----*****\", userId);\n if(timeChunkObject[key] == null) {\n \n var timeChunkData = {};\n timeChunkData[\"name\"] = (timechunck.userInfo.firstName + \" \" + timechunck.userInfo.lastName);\n timeChunkData[\"totalHours\"] = getTotalHoursForTimeChunk(timechunck);\n timeChunkData[\"date\"] = dateString;\n\n var userObj = {};\n userObj[userId] = timeChunkData;\n\n /*\n monday: {\n userId: {}\n userId2: {}\n userId3 : {}\n }\n\n */\n timeChunkObject[key] = userObj;\n timeChunkKeyArray.push(key);\n //console.log(\"Adding to array key\", timeChunkObject);\n \n } else {\n /*\n we have a json that looks like this. \n {\n \"userId\": {\n \"name\": nameOfUserInTimeChunk,\n \"totalHours\": total hours for a user in time chunk\n }\n }\n */\n \n if(timeChunkObject[dateString][userId] == null) {\n \n console.log(\"printing else oj\",timeChunkObject[dateString]);\n \n\n console.log(\"tcObj before\", timeChunkObject);\n var timeChunkData = {};\n timeChunkData[\"name\"] = (timechunck.userInfo.firstName + \" \" + timechunck.userInfo.lastName);\n timeChunkData[\"totalHours\"] = getTotalHoursForTimeChunk(timechunck);\n timeChunkData[\"date\"] = dateString;\n\n var data = timeChunkObject[dateString];\n data[userId] = timeChunkData;\n timeChunkObject[dateString] = data;\n \n\n } else {\n console.log(\"tcObj\", timeChunkObject);\n\n //get the value from timeChunkObject\n var data = timeChunkObject[key][userId]; \n \n // if(data[\"userId\"] === userId) {\n\n // } else {\n\n // }\n //get the totalhour from the value(data)\n var totalHours = data[\"totalHours\"];\n \n //aggregate the existing hour with the new time chunk hour\n var concatHours = totalHours + getTotalHoursForTimeChunk(timechunck);\n \n // update the value object totalhours with aggreagated value\n data[\"totalHours\"] = concatHours;\n\n //Set the upated value object back to timechunkObject\n timeChunkObject[key][userId] = data;\n }\n\n console.log(\"PRINTING DATA\", timeChunkObject);\n \n }\n });\n\n });//end of fetchResult forEach loop\n \n var showNodataValue = timeChunkKeyArray.length === 0;\n Session.set(\"showNoData\", showNodataValue);\n\n\n return timeChunkKeyArray;\n\n }", "function aggregated(data) {\n if (!data) {\n return;\n }\n\n return data.reduce(function (previousValue, obj) {\n if (!obj.net_total) {\n return previousValue + 0;\n }\n return previousValue + obj.net_total.value;\n }, 0)\n\n }", "function perform5minAggregatBC2(siteId, startEpoch, endEpoch) {\n // create temp collection as placeholder for aggreagation results\n const aggrResultsName = `aggr${moment().valueOf()}`;\n const AggrResults = new Meteor.Collection(aggrResultsName);\n\n // gather all data, group by 5min epoch\n const pipeline = [\n {\n $match: {\n $and: [\n {\n epoch: {\n $gt: parseInt(startEpoch, 10),\n $lt: parseInt(endEpoch, 10)\n }\n }, {\n site: siteId\n }\n ]\n }\n }, {\n $sort: {\n epoch: 1\n }\n }, {\n $project: {\n epoch5min: 1,\n epoch: 1,\n site: 1,\n subTypes: 1\n }\n }, {\n $group: {\n _id: '$epoch5min',\n site: {\n $last: '$site'\n },\n subTypes: {\n $push: '$subTypes'\n }\n }\n }, {\n $out: aggrResultsName\n }\n ];\n\n Promise.await(LiveData.rawCollection().aggregate(pipeline, { allowDiskUse: true }).toArray());\n\n /*\n * Only aggregate data if a certain percentage (defined by thresholdPercent) of the required data is in the 5minepoch.\n * There is supposed to be 630 database documents per 5minepoch.\n *\n * 30 documents for DAQFactory, 300 documents for TAP01, and 300 documents for TAP02.\n * Eventually we'll just pull how many datapoints are expected from the database. This will work for now\n *\n * Take for example if thresholdPercent were .75.\n *\n * There would need to be:\n * 30 * .75 = 22.5 \n * round(22.5) = 23 documents for DAQFactory required\n *\n * 300 * .75 = 225\n * 225 documents for TAP01 and TAP02 are required\n *\n * ONE EXCEPTION:\n * aggregate regardless of missing data if it is 55 min from the startEpoch\n *\n * Also, left these outside the loop because unnecessary calculations slow the loop down. \n * Additionally, we will be querying for this data rather than relying on hardcoded numbers later on.\n * Querying a database is slow. The less of those we do, the better.\n */\n\n const thresholdPercent = .75;\n // Hard coded numbers. Should not be hardcoded but oh well. Should be changed in the future.\n const maxDAQFactoryCount = 30, maxTAPCount = 300;\n const minDAQFactoryCount = Math.round(thresholdPercent * maxDAQFactoryCount);\n const minTAPcount = Math.round(thresholdPercent * maxTAPCount);\n\n // tap switch variables ***MUST*** be viable over iterations of the foreach loop\n // 8 is offline. Assume offline unless specified otherwise in TAP switch implementation\n var TAP01Flag = 8, TAP02Flag = 8;\n var TAP01Epoch = 0, TAP02Epoch = 0;\n\n // For some god aweful reason, some sites don't have neph flags. Need to check for neph flag before assigning whatever\n let hasNephFlag = false;\n\n // Tap data filtration is required. These variables are simply placeholders for where the rgb abs coef indeces and sampleFlow index is at.\n // ***MUST*** be viable over for loop\n let hasCheckedTAPdataSchema = false;\n let tapDataSchemaIndex = {};\n tapDataSchemaIndex.RedAbsCoef = undefined, tapDataSchemaIndex.GreenAbsCoef = undefined, tapDataSchemaIndex.BlueAbsCoef = undefined, tapDataSchemaIndex.SampleFlow = undefined;\n let TAP01Name = undefined;\n let TAP02Name = undefined;\n const allElementsEqual = arr => arr.every(v => v === arr[0]);\n\n AggrResults.find({}).forEach((e) => {\n const subObj = {};\n subObj._id = `${e.site}_${e._id}`;\n subObj.site = e.site;\n subObj.epoch = e._id;\n const subTypes = e.subTypes;\n const aggrSubTypes = {}; // hold aggregated data\n let newData = (endEpoch - 3300 - subObj.epoch) < 0;\n\n let subTypesLength = subTypes.length\n for (let i = 0; i < subTypesLength; i++) {\n for (const subType in subTypes[i]) {\n if (subTypes[i].hasOwnProperty(subType)) {\n const data = subTypes[i][subType];\n let numValid = 1;\n var newkey;\n\n // if Neph flag is undefined, flag it 1, otherwise ignore\n if (subType.includes(\"Neph\")) {\n if (data[0].metric === 'Flag') {\n hasNephFlag = true;\n }\n if (!hasNephFlag) {\n data.unshift({ metric: 'Flag', val: 1, unit: 'NA' });\n }\n }\n\n\n /** Tap flag implementation **/\n // Get flag from DAQ data and save it\n if (subType.includes('TAP01')) {\n TAP01Flag = data[0].val === 10 ? 1 : data[0].val;\n TAP01Epoch = subObj.epoch;\n } else if (subType.includes('TAP02')) {\n TAP02Flag = data[0].val === 10 ? 8 : data[0].val\n TAP02Epoch = subObj.epoch;\n }\n\n // Get flag from TAP0(1|2)Flag and give it to the appropriate instrument\n if (subType.includes('tap_')) {\n\n // TAP01 = even\n // TAP02 = odd\n // confusing amirite!?\n // EXAMPLE:\n // tap_SN36 <- even goes to TAP01\n // tap_SN37 <- odd goes to TAP02\n // This is parsing tap_* string for integer id\n var subTypeName = subType;\n let epochDiff;\n do {\n subTypeName = subTypeName.slice(1);\n } while (isNaN(subTypeName));\n let subTypeNum = subTypeName;\n if (parseInt(subTypeNum) % 2 === 0) {\n // Even - Needs flag from TAP01\n // Make sure that tap data has a corresponding timestamp in DaqFactory file\n // If not, break and do not aggregate datapoint\n epochDiff = subObj.epoch - TAP01Epoch;\n\n if (epochDiff >= 0 && epochDiff < 10) {\n data[0].val = TAP01Flag;\n } else {\n data[0].val = 20;\n }\n } else {\n // Odd - Needs flag from TAP02\n // Make sure that tap data has a corresponding timestamp in DaqFactory file\n // If not, break and do not aggregate datapoint\n epochDiff = subObj.epoch - TAP02Epoch;\n if (epochDiff >= 0 && epochDiff < 10) {\n data[0].val = TAP02Flag;\n } else {\n data[0].val = 20;\n }\n }\n\n /** Data filtration start **/\n\n /* Reason for data filtration to be inside this subType.includes is for performance reasons. The less if statements ran, the faster.\n */\n\n /* Matlab code\n * Some data filtration is required. We will not aggregate datapoints (not records) that do not fit our standards.\n * To Note: Comments in matlab are my own comments\n\n % Do not aggregate data point if r, g, b is < 0 or > 100 \n r1=numa(:,7);\n g1=numa(:,8);\n b1=numa(:,9);\n r2(r2 < 0 | r2 > 100) = NaN;\n g2(g2 < 0 | g2 > 100) = NaN;\n b2(b2 < 0 | b2 > 100) = NaN;\n\n\n %TAP_02data defined here\n TAP_02data = [JD2 time2 A_spot2 R_spot2 flow2 r2 g2 b2 Tr2 Tg2 Tb2];\n\n % Don't aggregate data point if SampleFlow / Flow(L/min) is off 5% from 1.7 Min: 1.615, Max: 1.785\n idx = find(TAP_02data (:,5) <1.63 | TAP_02data (:,5) >1.05*1.7); %condition if flow is 5% off 1.7lpm\n TAP_02data(idx,5:8) = NaN; clear idx time2 A_spot2 R_spot2 flow2 r2 g2 b2 Tr2 Tg2 Tb2\n\n\n % This is for the TAP switching. It was a way to get the TAP switching working in the matlab script.\n % Don't aggregate the first 100s after a switch has occured. Let instrument recalibrate. \n R01 = strfind(isnan(TAP_02data(:,5)).', [1 0]); % Find Indices Of [0 1] Transitions\n for i=1:100\n TAP_02data(R01+i,6:8) = NaN; % Replace Appropriate Values With 'NaN '\n end\n\n\n 20 = potentially invalid data\n 1 = valid data\n */\n\n // Reason for if statement is to speed the code up alot. \n // Having to check for the schema every run is VERY significant.\n // Only having to do it once and assuming the rest will be the same is a very safe assumption.\n // If this isn't true, then lord help us all\n if (!hasCheckedTAPdataSchema) {\n let dataLength = data.length;\n for (let k = 0; k < dataLength; k++) {\n if (data[k].metric === 'RedAbsCoef') {\n tapDataSchemaIndex.RedAbsCoef = k;\n }\n if (data[k].metric === 'GreenAbsCoef') {\n tapDataSchemaIndex.GreenAbsCoef = k;\n }\n if (data[k].metric === 'BlueAbsCoef') {\n tapDataSchemaIndex.BlueAbsCoef = k;\n }\n if (data[k].metric === 'SampleFlow') {\n tapDataSchemaIndex.SampleFlow = k;\n }\n }\n hasCheckedTAPdataSchema = true;\n }\n\n // We flag the faulty data with flag 20.\n if (data[tapDataSchemaIndex.RedAbsCoef].val < 0 || data[tapDataSchemaIndex.RedAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.RedAbsCoef].val)) {\n data[tapDataSchemaIndex.RedAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.GreenAbsCoef].val < 0 || data[tapDataSchemaIndex.GreenAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.GreenAbsCoef].val)) {\n data[tapDataSchemaIndex.GreenAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.BlueAbsCoef].val < 0 || data[tapDataSchemaIndex.BlueAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.BlueAbsCoef].val)) {\n data[tapDataSchemaIndex.BlueAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.SampleFlow].val < 1.615 || data[tapDataSchemaIndex.SampleFlow].val > 1.785 || isNaN(data[tapDataSchemaIndex.SampleFlow].val)) {\n data[tapDataSchemaIndex.SampleFlow].Flag = 20;\n }\n\n\n /** Data filtration finished **/ \n }\n\n /** End of TAP switch implementation **/\n\n // Don't aggregate TAP01 and TAP02 subtype. They are only useful for giving TAP_SNXX flags\n if (subTypes.includes(\"TAP01\") || subTypes.includes(\"TAP02\")) {\n continue;\n }\n\n\n // if flag is not existing, put 9 as default, need to ask Jim?\n if (data[0].val === '') {\n data[0].val = 9;\n }\n if (data[0].val !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n for (let j = 1; j < data.length; j++) {\n newkey = subType + '_' + data[j].metric;\n\n // TAP data requires data filtration. Setting flag to 20 if such for specified values. \n // Otherwise, use suggested flag value from file\n const flag = data[j].Flag !== undefined ? data[j].Flag : data[0].val;\n\n if (flag !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n\n if (!aggrSubTypes[newkey]) {\n if (numValid === 0) {\n data[j].val = 0;\n }\n\n aggrSubTypes[newkey] = {\n sum: Number(data[j].val),\n 'avg': Number(data[j].val),\n 'numValid': numValid,\n 'totalCounter': 1, // initial total counter\n 'flagstore': [flag], // store all incoming flags in case we need to evaluate\n unit: data[j].unit // use unit from first data point in aggregation\n };\n } else {\n if (numValid !== 0) { // keep aggregating only if numValid\n aggrSubTypes[newkey].numValid += numValid;\n aggrSubTypes[newkey].sum += Number(data[j].val); // holds sum until end\n if (aggrSubTypes[newkey].numValid !== 0) {\n aggrSubTypes[newkey].avg = aggrSubTypes[newkey].sum / aggrSubTypes[newkey].numValid;\n }\n }\n aggrSubTypes[newkey].totalCounter += 1; // increase counter\n aggrSubTypes[newkey].flagstore.push(flag); // /store incoming flag\n }\n numValid = 1; // reset numvalid\n }\n }\n }\n }\n\n // This is prep for calculations. Need ensure that we are working with data that has the data necessary to do calculations.\n // The for loop for transforming aggregated data to a generic data format is more useful for calculations than raw aggrSubTypes.\n // All I'm doing here is collecting a little bit of information of what we are working with before I do calculations.\n let hasTap = false;\n let hasNeph = false;\n // Don't have to do this with neph. Neph will always have the same name. Tap will always have different numbers\n let tapNames = [];\n\n // transform aggregated data to generic data format using subtypes etc.\n const newaggr = {};\n for (const aggr in aggrSubTypes) {\n if (aggrSubTypes.hasOwnProperty(aggr)) {\n const split = aggr.lastIndexOf('_');\n const instrument = aggr.substr(0, split);\n const measurement = aggr.substr(split + 1);\n\n if (!newaggr[instrument]) {\n newaggr[instrument] = {};\n }\n\n const obj = aggrSubTypes[aggr]; // makes it a little bit easier\n\n // dealing with flags\n if ((obj.numValid / obj.totalCounter) >= 0.75) {\n obj.Flag = 1; // valid\n } else {\n // find out which flag was majority\n const counts = {};\n for (let k = 0; k < obj.flagstore.length; k++) {\n counts[obj.flagstore[k]] = 1 + (counts[obj.flagstore[k]] || 0);\n }\n const maxObj = _.max(counts, function(obj) {\n return obj;\n });\n const majorityFlag = (_.invert(counts))[maxObj];\n obj.Flag = majorityFlag;\n }\n\n // Some specific setting up for tap calculations and skipping\n if (instrument.includes(\"Neph\")) {\n hasNeph = true;\n\n // If obj.totalCounter (which is documentation for the amount of datapoints in our 5minepoch) is < minTAPcount\n // And what we are aggregating is greater than 55 minutes from endEpoch: \n // SKIP \n if (obj.totalCounter < minDAQFactoryCount && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return;\n }\n }\n\n if (instrument.includes(\"tap_\")) {\n hasTap = true;\n if (!tapNames.includes(instrument)) {\n tapNames.push(instrument);\n }\n\n if (obj.totalCounter < 300)\n // If obj.totalCounter (which is documentation for the amount of datapoints in our 5minepoch) is < minTAPcount\n // And what we are aggregating is greater than 55 minutes from endEpoch: \n // SKIP \n if (obj.totalCounter < minTAPcount && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return;\n }\n }\n\n if (!newaggr[instrument][measurement]) { newaggr[instrument][measurement] = [];\n }\n\n // automatic flagging of aggregated values that are out of range for NO2 to be flagged with 9(N)\n if (instrument === '42i') {\n if (obj.avg < -0.5) {\n obj.Flag = 9;\n }\n }\n\n newaggr[instrument][measurement].push({ metric: 'sum', val: obj.sum });\n newaggr[instrument][measurement].push({ metric: 'avg', val: obj.avg });\n newaggr[instrument][measurement].push({ metric: 'numValid', val: obj.numValid });\n newaggr[instrument][measurement].push({ metric: 'unit', val: obj.unit });\n newaggr[instrument][measurement].push({ metric: 'Flag', val: obj.Flag });\n }\n }\n\n // If TAP or NEPH is missing AND what we are aggregating is greater than 55 minutes from endEpoch:\n // SKIP\n if ((tapNames.length < 2 || !hasNeph) && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return; \n }\n\n /** Helpful functions for calculations **/\n\n // flips sign for all elements in array\n function flipSignForAll1D(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] *= -1;\n }\n }\n\n // flips sign for all elements in 2D array\n function flipSignForAll2D(M) {\n for (let i = 0; i < M.length; i++) {\n flipSignForAll1D(M[i]);\n }\n }\n\n // returns row reduced echelon form of given matrix\n // if vector, return rref vector\n // if invalid, do nothing\n function rref(M) {\n let rows = M.length;\n let columns = M[0].length;\n if (((rows === 1 || rows === undefined) && columns > 0) || ((columns === 1 || columns === undefined) && rows > 0)) {\n M = [];\n let vectorSize = Math.max(isNaN(columns) ? 0 : columns, isNaN(rows) ? 0 : rows);\n for (let i = 0; i < vectorSize; i++) {\n M.push(0);\n }\n M[0] = 1;\n return M;\n } else if (rows < 0 || columns < 0) {\n return;\n }\n\n let lead = 0;\n for (let k = 0; k < rows; k++) {\n if (columns <= lead) {\n return;\n }\n\n let i = k;\n while (M[i][lead] === 0) {\n i++;\n if (rows === i) {\n i = k;\n lead++;\n if (columns === lead) { \n return;\n }\n }\n }\n let p = M[i]\n let s = M[k];\n M[i] = s, M[k] = p;\n\n let scalar = M[k][lead];\n for (let j = 0; j < columns; j++) {\n M[k][j] /= scalar;\n }\n\n for (let i = 0; i < rows; i++) {\n if (i === k) continue;\n scalar = M[i][lead];\n for (let j = 0; j < columns; j++) {\n M[i][j] -= scalar * M[k][j];\n }\n }\n lead++;\n }\n return M;\n }\n /** END of Helpful functions for calculations **/\n\n // Calculations for Nepholometer is done here\n if (hasNeph) {\n newaggr['Neph']['SAE'] = [];\n\n if (newaggr['Neph']['RedScattering'] === undefined || newaggr['Neph']['GreenScattering'] === undefined || newaggr['Neph']['BlueScattering'] === undefined) {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20});\n } else {\n\n let RedScatteringFlagIndex = 0;\n let RedScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['RedScattering'].length; index++) {\n if (newaggr['Neph']['RedScattering'][index].metric === 'Flag') {\n RedScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['RedScattering'][index].metric === 'avg') {\n RedScatteringAvgIndex = index;\n }\n }\n\n let GreenScatteringFlagIndex = 0;\n let GreenScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['GreenScattering'].length; index++) {\n if (newaggr['Neph']['GreenScattering'][index].metric === 'Flag') {\n GreenScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['GreenScattering'][index].metric === 'avg') {\n GreenScatteringAvgIndex = index;\n }\n }\n\n let BlueScatteringFlagIndex = 0;\n let BlueScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['BlueScattering'].length; index++) {\n if (newaggr['Neph']['BlueScattering'][index].metric === 'Flag') {\n BlueScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['BlueScattering'][index].metric === 'avg') {\n BlueScatteringAvgIndex = index;\n }\n }\n\n\n // SAE calculations begin here \n // Need to make sure that Neph has valid data before calculations can begin\n if (newaggr['Neph']['RedScattering'][RedScatteringFlagIndex].val === 1 && newaggr['Neph']['GreenScattering'][GreenScatteringFlagIndex].val === 1 && newaggr['Neph']['BlueScattering'][BlueScatteringFlagIndex].val === 1) {\n let x = [635, 525, 450]; // Matlab code: x=[635,525,450]; %Wavelength values for Nephelometer \n let y_Neph = [\n newaggr['Neph']['RedScattering'][RedScatteringAvgIndex].val,\n newaggr['Neph']['GreenScattering'][GreenScatteringAvgIndex].val,\n newaggr['Neph']['BlueScattering'][BlueScatteringAvgIndex].val\n ]; // Matlab code: y_Neph = outdata_Neph(:,2:4); %Scattering coefficient values from Daqfactory for Neph\n\n let lx = mathjs.log(x); // Matlab code: lx = log(x); %Taking log of wavelength\n let ly_Neph = mathjs.log(y_Neph); // Matlab code: ly_Neph = log(y_Neph); %Taking log of scattering coefficient values\n\n // Matlab code: log_Neph = -[lx(:) ones(size(x(:)))] \\ ly_Neph(:,:)'; %Step 1- SAE calulation\n // going to have to break this down a little bit\n let log_Neph = [ // [lx(:) ones(size(x(:)))]\n lx, \n mathjs.ones(mathjs.size(x))\n ];\n log_Neph = mathjs.transpose(log_Neph); // Needed to make matrix 3 x 2\n\n // - operator just negates everything in the matrix\n flipSignForAll2D(log_Neph);\n /*\n * if A is a rectangular m-by-n matrix with m ~= n, and B is a matrix with m rows, then A\\B returns a least-squares solution to the system of equations A*x= B.\n * Least squares solution approximation is needed.\n * Links to calculating least squares solution:\n * https://textbooks.math.gatech.edu/ila/least-squares.html\n * https://www.youtube.com/watch?v=9UE8-6Jlezw\n */\n\n // A^T*A\n let ATA = mathjs.multiply(mathjs.transpose(log_Neph), log_Neph);\n // A^T*b\n let ATb = mathjs.multiply(mathjs.transpose(log_Neph), ly_Neph);\n\n // Create augmented matrix to solve for least squares solution\n ATA[0].push(ATb[0]);\n ATA[1].push(ATb[1]);\n\n log_Neph = rref(ATA);\n // Reason for index 0,2 is because I am skipping a step in the least squares approximation.\n // It is supposed to return a vector with 2 values, but I just shortcut it straight to the correct answer from the 3x2 rref matrix\n let SAE_Neph = log_Neph[0][2]; // SAE_Neph = log_Neph(1,:)'; %Step 2- SAE calulation\n\n // SAE ranges should be: -1 - 5\n // Matlab code: SAE_Neph(SAE_Neph > 5)= NaN;\n // Sujan said this ^^^\n // Unsure If I want to check for zero value\n if (SAE_Neph === undefined || SAE_Neph < -1 || SAE_Neph > 5) { \n newaggr['Neph']['SAE'].push({ metric: 'calc', val: ((SAE_Neph === undefined) ? 'NaN' : SAE_Neph) });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20 });\n } else {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: SAE_Neph });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n // Must be valid data if it it came this far\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 1 });\n }\n } else {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n // It's just easier to assign flag 20 when if fails\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20 });\n }\n }\n }\n\n // Unfortunately, Neph doesn't really have a flag. It's just trusted that if there is data, it is valid. \n // I'll ensure data exists before a calculation for safety reasons.\n // Calculations for tap instruments done here\n tapNames.forEach((instrument) => {\n newaggr[instrument]['SSA_Red'] = [];\n newaggr[instrument]['SSA_Green'] = [];\n newaggr[instrument]['SSA_Blue'] = [];\n newaggr[instrument]['AAE'] = [];\n if (newaggr['Neph'] !== undefined && newaggr['Neph']['RedScattering'] !== undefined && newaggr['Neph']['GreenScattering'] !== undefined && newaggr['Neph']['BlueScattering'] !== undefined) {\n let RedScatteringFlagIndex = 0;\n let RedScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['RedScattering'].length; index++) {\n if (newaggr['Neph']['RedScattering'][index].metric === 'Flag') {\n RedScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['RedScattering'][index].metric === 'avg') {\n RedScatteringAvgIndex = index;\n }\n }\n\n let GreenScatteringFlagIndex = 0;\n let GreenScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['GreenScattering'].length; index++) {\n if (newaggr['Neph']['GreenScattering'][index].metric === 'Flag') {\n GreenScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['GreenScattering'][index].metric === 'avg') {\n GreenScatteringAvgIndex = index;\n }\n }\n\n let BlueScatteringFlagIndex = 0;\n let BlueScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['BlueScattering'].length; index++) {\n if (newaggr['Neph']['BlueScattering'][index].metric === 'Flag') {\n BlueScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['BlueScattering'][index].metric === 'avg') {\n BlueScatteringAvgIndex = index;\n }\n }\n\n let RedAbsCoefFlagIndex = 0;\n let RedAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['RedAbsCoef'].length; index++) {\n if (newaggr[instrument]['RedAbsCoef'][index].metric === 'Flag') {\n RedAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['RedAbsCoef'][index].metric === 'avg') {\n RedAbsCoefAvgIndex = index;\n }\n }\n\n let GreenAbsCoefFlagIndex = 0;\n let GreenAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['GreenAbsCoef'].length; index++) {\n if (newaggr[instrument]['GreenAbsCoef'][index].metric === 'Flag') {\n GreenAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['GreenAbsCoef'][index].metric === 'avg') {\n GreenAbsCoefAvgIndex = index;\n }\n }\n\n let BlueAbsCoefFlagIndex = 0;\n let BlueAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['BlueAbsCoef'].length; index++) {\n if (newaggr[instrument]['BlueAbsCoef'][index].metric === 'Flag') {\n BlueAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['BlueAbsCoef'][index].metric === 'avg') {\n BlueAbsCoefAvgIndex = index;\n }\n }\n\n // If any of the SSA calculations fail, AAE calculations will fail.\n // Allows Different SSA colors to still do calculations whilst preventing AAE from failing\n let SSAFailed = false;\n\n //SSA calculations begin here:\n let obj = {\n Flag:newaggr[instrument]['RedAbsCoef'][RedAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['RedAbsCoef'][RedAbsCoefAvgIndex].val\n };\n if (parseInt(newaggr['Neph']['RedScattering'][RedScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let redScatteringAvg = parseFloat(newaggr['Neph']['RedScattering'][RedScatteringAvgIndex].val);\n let TotalExtinction_R = redScatteringAvg + obj.avg; // Matlab code: TotalExtinction_R = AC_R_Combined + outdata_Neph(:,2); %Total Extinction calculation for Red wavelength\n let SSA_R = redScatteringAvg / TotalExtinction_R; // Matlab code: SSA_R = outdata_Neph(:,2)./TotalExtinction_R; % SSA calculation for Red Wavelength\n\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: SSA_R });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_R (SSA_R < 0 | SSA_R ==1)=NaN;\n // decided > 1 because I have no idea why he used == and not >\n // I decided to make it SSA_R <= 0 to because javascript sends error values to zero by default\n if (SSA_R === undefined || SSA_R <= 0 || SSA_R > 1) {\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: ((SSA_R === undefined) ? 'NaN' : SSA_R) });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: 20});\n }\n } else {\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n\n obj = {\n Flag:newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefAvgIndex].val \n };\n if (parseInt(newaggr['Neph']['GreenScattering'][GreenScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let greenScatteringAvg = parseFloat(newaggr['Neph']['GreenScattering'][GreenScatteringAvgIndex].val);\n let TotalExtinction_G = greenScatteringAvg + obj.avg; // Matlab code: TotalExtinction_G = AC_G_Combined + outdata_Neph(:,3); %Total Extinction calculation for Green wavelength\n let SSA_G = greenScatteringAvg / TotalExtinction_G; // Matlab code: SSA_G = outdata_Neph(:,3)./TotalExtinction_G; % SSA calculation for Green Wavelength\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: SSA_G });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_G (SSA_G < 0 | SSA_G ==1)=NaN;\n // decided > 1 because I have no idea why he used == and not >\n // I decided to make it SSA_G <= 0 to because javascript sends error values to zero by default\n if (SSA_G === undefined || SSA_G <= 0 || SSA_G > 1) {\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: ((SSA_G === undefined) ? 'NaN' : SSA_G) });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: 20 });\n }\n } else {\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n\n obj = {\n Flag:newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefAvgIndex].val\n };\n if (parseInt(newaggr['Neph']['BlueScattering'][BlueScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let blueScatteringAvg = parseFloat(newaggr['Neph']['BlueScattering'][BlueScatteringAvgIndex].val);\n let TotalExtinction_B = blueScatteringAvg + obj.avg; // Matlab code: TotalExtinction_B = AC_B_Combined + outdata_Neph(:,4); %Total Extinction calculation for Blue wavelength\n let SSA_B = blueScatteringAvg / TotalExtinction_B; // Matlab code: SSA_B = outdata_Neph(:,4)./TotalExtinction_B; % SSA calculation for Blue Wavelength\n\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: SSA_B });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_B (SSA_B < 0 | SSA_B ==1)=NaN; \n // I decided to make it SSA_B <= 0 to because javascript sends error values to zero by default\n if (SSA_B === undefined || (SSA_B <= 0 || SSA_B == 1)) {\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: ((SSA_B === undefined) ? 'NaN' : SSA_B) });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: 20});\n }\n } else {\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n if (!SSAFailed) {\n // AAE calculations begin here:\n // Make sure tap instrument is valid\n let x = [640, 520, 365]; // Matlab code: x=[640,520,365]; % Wavelengths values\n let y_TAP = [ // Matlab code: y_TAP_01 = outdata1_TAP_01(:,6:8); %Absorption coefficients from TAP01\n parseFloat(newaggr[instrument]['RedAbsCoef'][RedAbsCoefAvgIndex].val), \n parseFloat(newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefAvgIndex].val), \n parseFloat(newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefAvgIndex].val)\n ];\n\n let lx = mathjs.log(x); // Matlab code: lx = log(x); %Taking log of the wavelengths\n let ly_TAP = mathjs.log(y_TAP);// Matlab code: ly_TAP_01 = log(y_TAP_01); %Taking log of the absorption coefficients for TAP01\n for (let i = 0; i < ly_TAP.length; i++) {\n if (isNaN(ly_TAP[i]) || ly_TAP[i] < 0) {\n ly_TAP[i] = 0;\n }\n }\n\n // Going to have to break this matlab code down a bit, again:\n // Matlab code: log_TAP_01 = -[lx(:) ones(size(x(:)))] \\ ly_TAP_01(:,:)'; %Step 1 -AAE from TAP 01 data\n let log_TAP = [ // Matlab code: [lx(:) ones(size(x(:)))] \n lx,\n mathjs.ones(mathjs.size(x))\n ];\n log_TAP = mathjs.transpose(log_TAP); // Needs to be transposed into 3x2 matrix\n // - operator just negates everything in the matrix\n flipSignForAll2D(log_TAP);\n\n\n /* More information on how I came to the lines below is in the SAE calculations. \n * Essentially, we are finding the least squares solution to the system of equations:\n * A*x=b\n */\n\n // A \\ b\n let ATA = mathjs.multiply(mathjs.transpose(log_TAP), log_TAP);\n let ATb = mathjs.multiply(mathjs.transpose(log_TAP), ly_TAP);\n\n // Create augmented matrix to solve for least squares solution\n ATA[0].push(ATb[0]);\n ATA[1].push(ATb[1]);\n\n log_TAP = rref(ATA);\n // Reason for index 0,2 is because I am skipping a step in the least squares approximation.\n // It is supposed to return a vector with 2 values, but I just shortcut it straight to the correct answer from the 3x2 rref matrix\n let AAE_TAP = log_TAP[0][2]; // Matlab code: SAE_Neph = log_Neph(1,:)'; %Step 2- SAE calulation\n\n // AAE normal ranges: .5 - 3.5\n // Sujan said this ^^^\n // matlab comment: % AAE__TAP_A(AAE__TAP_A < 0)= NaN;\n // I decided to make it AAE_TAP <= 0 to because javascript sends error values to zero by default\n if (AAE_TAP === undefined || AAE_TAP <= 0 || AAE_TAP > 3.5) {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: ((AAE_TAP === undefined) ? 'NaN' : AAE_TAP) });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\"});\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: 20 });\n } else {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: AAE_TAP });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\"});\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: obj.Flag});\n }\n } else {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: 20 });\n }\n }\n });\n\n subObj.subTypes = newaggr;\n AggrData.insert(subObj, function(error, result) {\n if (result === false) {\n Object.keys(newaggr).forEach(function(newInstrument) {\n Object.keys(newaggr[newInstrument]).forEach(function(newMeasurement) {\n // test whether aggregates for this instrument/measurement already exists\n const qry = {};\n qry._id = subObj._id;\n qry[`subTypes.${newInstrument}.${newMeasurement}`] = { $exists: true };\n\n if (AggrData.findOne(qry) === undefined) {\n const newQuery = {};\n newQuery.epoch = subObj.epoch;\n newQuery.site = subObj.site;\n const $set = {};\n const newSet = [];\n newSet[0] = newaggr[newInstrument][newMeasurement][0];\n newSet[1] = newaggr[newInstrument][newMeasurement][1];\n newSet[2] = newaggr[newInstrument][newMeasurement][2];\n newSet[3] = newaggr[newInstrument][newMeasurement][3];\n newSet[4] = newaggr[newInstrument][newMeasurement][4];\n $set['subTypes.' + newInstrument + '.' + newMeasurement] = newSet;\n\n // add aggregates for new instrument/mesaurements\n AggrData.findAndModify({\n query: newQuery,\n update: {\n $set: $set\n },\n upsert: false,\n new: true\n });\n } else {\n // Some aggregations will have less than 5 parts to it. \n // Need if statements to make sure it doesn't generate errors.\n // I really think that this whole thing should change, but I have no idea how it works.\n // So just leave this be and it will keep working.\n let newaggrLength = newaggr[newInstrument][newMeasurement].length;\n if (newaggrLength > 1) {\n const query0 = {};\n query0._id = subObj._id;\n query0[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'sum';\n const $set0 = {};\n $set0[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][0].val;\n AggrData.update(query0, { $set: $set0 });\n }\n if (newaggrLength > 1) {\n const query1 = {};\n query1._id = subObj._id;\n query1[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'avg';\n const $set1 = {};\n $set1[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][1].val;\n AggrData.update(query1, { $set: $set1 });\n }\n if (newaggrLength > 2) {\n const query2 = {};\n query2._id = subObj._id;\n query2[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'numValid';\n const $set2 = {};\n $set2[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][2].val;\n AggrData.update(query2, { $set: $set2 });\n }\n if (newaggrLength > 3) {\n const query3 = {};\n query3._id = subObj._id;\n query3[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'unit';\n const $set3 = {};\n $set3[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][3].val;\n AggrData.update(query3, { $set: $set3 });\n }\n if (newaggrLength > 4) {\n const query4 = {};\n query4._id = subObj._id;\n query4[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'Flag';\n const $set4 = {};\n $set4[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][4].val;\n AggrData.update(query4, { $set: $set4 });\n }\n }\n });\n });\n }\n });\n });\n // drop temp collection that was placeholder for aggreagation results\n AggrResults.rawCollection().drop();\n}", "prepareDataUsageGraphData() {\n this.prepareUsageGraphData(\n this.streamUsageGraphData,\n this.streamData,\n 'logs_home_data_stream',\n );\n this.prepareUsageGraphData(\n this.archiveUsageGraphData,\n this.archiveData,\n 'logs_home_data_archive',\n );\n this.prepareUsageGraphData(\n this.indiceUsageGraphData,\n this.indiceData,\n 'logs_home_data_index',\n );\n }", "collectResults() {\n // Collect groups\n let rows = Array.from(this.groups, ([_, group]) => {\n const { bindings: groupBindings, aggregators } = group;\n // Collect aggregator bindings\n // If the aggregate errorred, the result will be undefined\n const aggBindings = {};\n for (const variable in aggregators) {\n const value = aggregators[variable].result();\n if (value !== undefined) { // Filter undefined\n aggBindings[variable] = value;\n }\n }\n // Merge grouping bindings and aggregator bindings\n return groupBindings.merge(aggBindings);\n });\n // Case: No Input\n // Some aggregators still define an output on the empty input\n // Result is a single Bindings\n if (rows.length === 0) {\n const single = {};\n for (const i in this.pattern.aggregates) {\n const aggregate = this.pattern.aggregates[i];\n const key = rdf_string_1.termToString(aggregate.variable);\n const value = sparqlee_1.AggregateEvaluator.emptyValue(aggregate);\n if (value !== undefined) {\n single[key] = value;\n }\n }\n rows = [bus_query_operation_1.Bindings(single)];\n }\n return rows;\n }", "function summarize(data) {\n if (view.viewFunctions.summarize) {\n var result = [],\n values = $scope.values,\n object = {\n value: 0,\n type: '',\n format: ''\n }\n\n if ($scope.summarize.length > 0) {\n result = $scope.summarize;\n }\n\n for (var i = 0; i < values.length; i++) {\n if (result.length !== values.length) {\n result[i] = object;\n object = {\n value: 0,\n type: '',\n format: ''\n };\n\n result[i].type = values[i].type;\n result[i].format = values[i].format;\n }\n\n for (var j = 0; j < data.length; j++) {\n if (values[i].type === 'digits') {\n var value = findMatch(data[j], values[i].matchValue);\n\n if (value !== null) {\n result[i].value += value;\n }\n } else {\n result[i] = {};\n }\n }\n }\n\n $scope.summarize = result;\n }\n }", "getStoreTotals() {\n const reportDate = this.reportDate;\n const reportDateEnd = this.reportDateEnd;\n const begin = this.reportDate ? moment(reportDate, 'MM-DD-YYYY').format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');\n const end = this.reportDateEnd ? moment(reportDateEnd, 'MM-DD-YYYY').format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');\n Service.get(this).getStoreTotals({\n companyId: state.get(this).params.companyId,\n begin,\n end\n });\n }", "allDataHoursSummary(data) {\n let uniqueTypeNames = this.getUniqueNames(data)\n let allSummaryObject = []\n\n for (var j = 0; j < uniqueTypeNames.length; j++) {\n let hoursSubTotal = 0\n for (var i = 0; i < data.length; i++) {\n\n if (data[i].type === uniqueTypeNames[j]) {\n hoursSubTotal += parseInt(data[i].hours, 10)\n }\n if (i === data.length - 1) {\n let typeName = uniqueTypeNames[j]\n allSummaryObject.push({\n x: typeName, y: hoursSubTotal\n })\n }\n }\n }\n return allSummaryObject\n }", "function updatePageAnalyticsData(summaryData) {\n window.pageAnalyticsData = summaryData;\n lastRow = summaryData.rows.length-1;\n setPageStatInt(\"nodesLabel\", \"nodesValue\", \"Node Count\", \"\", summaryData.rows[lastRow][\"count_hostname\"]);\n setPageStatInt(\"cpuLabel\", \"cpuValue\", \"Avg Load\", \"%\", summaryData.rows[lastRow][\"avg_cpu\"]);\n}", "function aggregate(homeKey, value){\n if(value) homeKey += (\"-\"+value);\n if(localStorage.hasOwnProperty(homeKey)){\n var data = localStorage[homeKey].split(\"|\");\n var counts = {}\n var x = data.length-1; // subtract empty last array val.\n var val; \n \n // parse data to retrive players => action counts\n while(x--){\n val = data[x];\n if (counts[val]) counts[val] += 1;\n else counts[val] = 1;\n }\n \n // add action's counts to player object\n for(var player in counts){\n if(!analysis[player]) analysis[player] = {}\n analysis[player][value?action+\"-\"+value:action] = counts[player];\n }\n }\n }", "get _topLevelAggregations() {\n const aggs = this.groupedBy.split(',').map((term) => {\n return {\n by: {\n terms: {\n field: this._fieldFor(term.trim()),\n },\n },\n };\n });\n\n // set max number of buckets to return\n if (this.groupLimit !== -1 && aggs.length) {\n aggs[0].by.terms.size = this.groupLimit;\n }\n\n return aggs;\n }", "refresh() {\n const ctx = Authentication_1.getExtensionContext();\n if (ctx.globalState.get(Constants_1.GLOBAL_STATE_USER_ID) === undefined) {\n this.data = [\n new DailyMetricItem(Constants_1.DAILY_METRIC_KEYSTROKES_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_LINES_CHANGED_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_TIME_INTERVAL_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_POINTS_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n ];\n return;\n }\n else {\n Firestore_1.retrieveUserUpdateDailyMetric().then((userDocument) => {\n if (userDocument === undefined) {\n this.data = [\n new DailyMetricItem(Constants_1.DAILY_METRIC_KEYSTROKES_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_LINES_CHANGED_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_TIME_INTERVAL_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n new DailyMetricItem(Constants_1.DAILY_METRIC_POINTS_TREEVIEW, [\n new DailyMetricItem(\"🚀 Today: \" + \"0\" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),\n ]),\n ];\n }\n else {\n var today = new Date();\n var time = today.getHours() +\n \":\" +\n today.getMinutes() +\n \":\" +\n today.getSeconds();\n this.data = [];\n let tempList = [];\n for (let key in userDocument) {\n if (key === \"teamId\") {\n continue;\n }\n tempList.push(new DailyMetricItem(Constants_1.DAILY_METRIC_DISPLAY_HEADER_MAP_TREEVIEW[key], [\n new DailyMetricItem(\"🚀 Today: \" +\n +userDocument[key].toFixed(3) +\n \" (Updated: \" +\n time +\n \")\"),\n ]));\n }\n this.data = tempList;\n }\n });\n }\n this._onDidChangeTreeData.fire(null);\n }", "function zoomData() {\n\t\tconst getUserInfo = userArray\n\t\t\t.filter(userInfo => `#${userInfo.login}` === currentLocation.hash) // only get the data from the user who matches with #\n\t\t\t.map(userInfo => zoomDom(userInfo))\n\t\t\t.join('');\n\n\t\trenderToZoom(getUserInfo);\n\t}", "async function collectMetrics() {\n // Get all reviews within interval hours of now\n let firstReviewDate = new Date(\n Date.now() - settings.interval * 60 * 60 * 1000\n );\n let options = {\n last_update: firstReviewDate,\n };\n\n let reviewCollection = await wkof.Apiv2.fetch_endpoint(\"reviews\", options);\n let reviews = reviewCollection.data;\n\n // Save our first metric\n metrics.reviewed = reviews.length;\n\n // Calculate and save our second set of metrics\n // findSessions() returns an Array of Session objects\n // Also builds metrics.pareto\n metrics.sessions = findSessions(reviews);\n\n // Retrieve and save the apprentice metrics\n let config = {\n wk_items: {\n filters: {\n srs: \"appr1, appr2, appr3, appr4\",\n },\n },\n };\n\n let items = await wkof.ItemData.get_items(config);\n\n metrics.apprentice = items.length;\n\n // Finally, retrieve and save the number of kanji in stages 1 and 2\n config = {\n wk_items: {\n filters: {\n srs: \"appr1, appr2\",\n item_type: \"kan\",\n },\n },\n };\n items = await wkof.ItemData.get_items(config);\n metrics.newKanji = items.length;\n }", "function Aggregator() {\n }", "function aggregateWorstAlarmByHost(hostCountData) {\n $scope.inventory_cards[0].data.unknown.count += hostCountData.unknown.count;\n $scope.inventory_cards[0].data.ok.count += hostCountData.ok.count;\n $scope.inventory_cards[0].data.warning.count += hostCountData.warning.count;\n $scope.inventory_cards[0].data.critical.count += hostCountData.critical.count;\n $scope.inventory_cards[0].data.altTotal.count += hostCountData.altTotal.count;\n }", "AggregateReportByOrderData(filter = {}, group = {}) {\n return new Promise((resolve, reject) => {\n this.collection.aggregate([\n {\n $match: filter\n },\n {\n $group: group\n }\n ], (err, data) => {\n if (err) return reject({ message: err, status: 0 });\n\n return resolve(data);\n });\n });\n }", "aggregate( field = '' ) {\n\n // Execute the request without loading.\n return this.request('GET', `index/${field}`, true, {}, false);\n\n }", "aggregateHistoryDataSegment(processedTransactions) {\n // Separate transaactions to aggregate\n let aggregated = [];\n let toAggregate = [];\n for (const transaction of processedTransactions) {\n if (Blockchain.transactionsToAggregate.includes(transaction.type)) {\n toAggregate.push(transaction); // For aggregation\n } else {\n aggregated.push(transaction); // No aggregation - straight to processed\n }\n }\n\n // Aggregate\n for (const type of Blockchain.transactionsToAggregate) {\n let individualTransactions = toAggregate.filter(x => x.type === type);\n if (individualTransactions.length > 0) {\n aggregated = aggregated.concat(this.aggregateTransactionsByDate(individualTransactions));\n }\n }\n return aggregated;\n }", "function getInsightsDataMap() {\n return {\n organicEngagements: {\n metric: 'organicEngagements',\n getter: function(metric) {\n let channels = ['facebook', 'twitter'];\n return dataResolvers.getChannelValues(channels, metric, 'totalValue');\n }\n },\n\n organicFacebookSharesValue: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'totalValue');\n }\n },\n organicFacebookSharesChangeValue: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changeValue');\n }\n },\n organicFacebookSharesChangePercent: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n },\n organicTwitterSharesValue: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'totalValue');\n }\n },\n organicTwitterSharesChangeValue: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changeValue');\n }\n },\n organicTwitterSharesChangePercent: {\n metric: 'organicShares',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n },\n\n organicFacebookLikesValue: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'totalValue');\n }\n },\n organicFacebookLikesChangeValue: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changeValue');\n }\n },\n organicFacebookLikesChangePercent: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n },\n\n organicTwitterLikesValue: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'totalValue');\n }\n },\n organicTwitterLikesChangeValue: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changeValue');\n }\n },\n organicTwitterLikesChangePercent: {\n metric: 'organicLikes',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n },\n\n organicFacebookCommentsValue: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'totalValue');\n }\n },\n organicFacebookCommentsChangeValue: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changeValue');\n }\n },\n organicFacebookCommentsChangePercent: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('facebook', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n },\n\n organicTwitterCommentsValue: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'totalValue');\n }\n },\n organicTwitterCommentsChangeValue: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changeValue');\n }\n },\n organicTwitterCommentsChangePercent: {\n metric: 'organicComments',\n getter: function(metric) {\n return dataResolvers.getChannelValues('twitter', metric, 'changePercent');\n },\n formatters: [\n dataFormatters.decimalToPercent\n ]\n }\n };\n} // end getInsightsDataMap", "function getAndDisplayDataStoreSummary()\n{\n cmd = \"getUserDataStoreSummary\";\n callback = \"displayUserDataStoreSummary\";\n\n payload = {userID: userID,\n userGroups: [\"public\", \"test\"]};\n\n msg = {cmd: cmd, status:\"request\", callback:callback, payload:payload};\n\n hub.send(JSON.stringify(msg));\n\n} // getAndDisplayDataStoreSummary", "function daily_office() {\n _daily_report_(WORK_LIST,OFFICE);\n}", "render() {\n\n //---- Here this is determining which data is going to be passed to the chart depending on the timeperiod. ----\n // **map function to return an object containing every water entry in function of every hours**\n const databaseWaterEntries = this.state.water_entries.map(e => {\n return {\n label: (new Date(e.drunk_at)).getUTCHours(),\n value: e.volume\n }\n })\n console.log(databaseWaterEntries)\n\n const timePeriod = this.props.timePeriod;\n const sumvolumedaily = this.state.water_entries.map(e => e.volume).reduce((a, b) => a + b, 0)\n console.log(sumvolumedaily)\n\n // Here this is determining which data is going to be passed to the chart depending on the timeperiod.\n \n // let currentUser = false;\n // let currentUserId;\n // if (this.props.currentUser) {\n // currentUser = true;\n // currentUserId = this.props.currentUser.id;\n // }\n\n let averageWater;\n let waterEntries;\n\n \n\n if (timePeriod === 'day') {\n averageWater = sumvolumedaily / 1000;\n waterEntries = databaseWaterEntries\n } else if (timePeriod === 'week') {\n averageWater = U1averageWaterWeek; \n waterEntries = U1weekWaterEntries;\n } else if (timePeriod === 'month') {\n averageWater = U1averageWaterMonth;\n waterEntries = U1monthWaterEntries;\n }\n // } else {\n // if (timePeriod === 'day') {\n // averageWater = U2totalWaterDay;\n // waterEntries = U2dayWaterEntries; \n // } else if (timePeriod === 'week') {\n // averageWater = U2averageWaterWeek; \n // waterEntries = U2weekWaterEntries;\n // } else if (timePeriod === 'month') {\n // averageWater = U2averageWaterMonth;\n // waterEntries = U2monthWaterEntries;\n // }\n // }\n \n \n // This sets the data for the charts\n waterCylinder.dataSource.value = averageWater;\n waterCylinder.dataSource.chart.plottooltext = `Water consumption per day: <b>${averageWater}</b>`\n waterConfigs.dataSource.data = waterEntries;\n\n // This sets the charts to variables which can be passed to the generic chart\n const chart1 = <ReactFC {...waterCylinder} />\n const chart2 = <ReactFC {...waterConfigs} />\n\n // This is the popup where people can enter water\n const dialog = <Dialog onSubmit={this.handleWaterSubmit}/>\n\n // This compares the consumed with the recommended to create a messsage that can be passed to generic chart\n let message;\n let video;\n if ((2.3 - averageWater) === 0) {\n message = \"Wohoo you are meeting the recommendations. Here's a little treat to make you smile\";\n video = 'https://www.youtube.com/embed/SDkPi0N5CZg'\n } else if ((2.3 - averageWater) < 0) {\n message = 'You are exceeding expectations. Remember your bladder can only hold so much!' \n video = 'https://www.youtube.com/embed/SDkPi0N5CZg'\n } else {\n message = `Drinking enough water helps manage symptoms like heart burn. Try drinking an extra ${Math.round((2.3 - averageWater) * 1000/440)} bottle(s).`\n video = 'https://www.youtube.com/embed/F9sigNSpETc'\n }\n\n\n return (\n // This passes variables to the generic card component which renders the card\n <GenericCard \n type=\"water\" \n message={message} \n timePeriod={this.props.timePeriod} \n video={video}\n dialog={dialog} \n averageWater={averageWater} \n panel='waterPanel'\n chart1={chart1} \n chart2={chart2}\n />\n )\n }", "function groupAll() {\n\n // reducing does nothing because currently we can't choose how the database will aggregate data\n var groupAllObj = {\n reduce: function () { return groupAllObj; },\n reduceCount: function () { return groupAllObj; },\n reduceSum: function () { return groupAllObj; },\n dispose: function () {},\n value: function () { return getData(null, false)[0].value; }\n };\n\n return groupAllObj;\n }", "function populateData() {\n let counts = {};\n let chartPieData = {'possible': 0, 'probable': 0, 'certain': 0, 'gueri': 0, 'mort': 0};\n let chartDateData = {};\n let chartAgeData = {\n 'total': [0,0,0,0,0,0,0,0,0,0],\n 'possible': [0,0,0,0,0,0,0,0,0,0],\n 'probable': [0,0,0,0,0,0,0,0,0,0],\n 'certain': [0,0,0,0,0,0,0,0,0,0],\n 'gueri': [0,0,0,0,0,0,0,0,0,0],\n 'mort': [0,0,0,0,0,0,0,0,0,0]\n };\n let chartSexData = {\n 'total': {'F': 0, 'M': 0},\n 'possible': {'F': 0, 'M': 0},\n 'probable': {'F': 0, 'M': 0},\n 'certain': {'F': 0, 'M': 0},\n 'gueri': {'F': 0, 'M': 0},\n 'mort': {'F': 0, 'M': 0}\n };\n for (let cas of cases) {\n let loc = cas['Domicile'];\n if (!(loc in counts)) {\n counts[loc] = {'total': 0, 'possible': 0, 'probable': 0, 'certain': 0, 'gueri': 0, 'mort': 0};\n }\n let filtered = (viewConfig.filter ? viewConfig.filter(cas) : viewFilterDefault(cas));\n if (filtered) {\n counts[loc]['total'] += 1;\n counts[loc][filtered['Condition']] += 1;\n\n chartPieData[filtered['Condition']] += 1;\n\n let date = new Date(filtered['Date symptomes']);\n if (!isNaN(date)) {\n date = date.toISOString();\n chartDateData[date] = (chartDateData[date] || 0 ) + 1;\n }\n\n chartAgeData['total'][Math.floor(filtered['Age']/10)] += 1;\n chartAgeData[filtered['Condition']][Math.floor(filtered['Age']/10)] += 1;\n\n chartSexData['total'][filtered['Sexe']] += 1;\n chartSexData[filtered['Condition']][filtered['Sexe']] += 1;\n }\n }\n data = {\n 'map': counts,\n 'globalpie': chartPieData,\n 'date': chartDateData,\n 'age': chartAgeData,\n 'sex': chartSexData,\n };\n}", "get aggregatedByLink() {\n const df = this.filteredDataFrame;\n if (df === null || df.shape[0] === 0) {\n return null;\n }\n let dfAggregated = df.groupby(['source', 'sourceName', 'target', 'targetName']).col([COLUMN_WEIGHT]).sum();\n dfAggregated.rename({ [`${COLUMN_WEIGHT}_sum`]: COLUMN_WEIGHT }, { inplace: true });\n\n // Sort\n dfAggregated = dfAggregated.sortValues(COLUMN_WEIGHT, { ascending: false });\n dfAggregated.resetIndex({ inplace: true });\n\n runInAction(() => {\n // Min/max weights\n this.minLinkWeight = dfAggregated[COLUMN_WEIGHT].min();\n this.maxLinkWeight = dfAggregated[COLUMN_WEIGHT].max();\n \n this.dfLinkTotals = dfAggregated;\n });\n const links = dfd.toJSON(dfAggregated);\n return links.slice(0, this.topN);\n }", "async leaderBoardAllTime(req, res){\n\t\ttry {\n\t\t\tvar leaderBoard = await UserModel.aggregate([\n\t\t\t\t{$unwind: '$performance'},\n\t\t\t\t{$group: {\n\t\t\t\t\t\t_id: '$_id',\n\t\t\t\t\t\tamount: {$sum: '$performance.prizeMoney.amount'},\n\t\t\t\t\t\tcorrectCount: {$sum: '$performance.correctCount'},\n\t\t\t\t\t\tincorrectCount: {$sum: '$performance.incorrectCount'}\n\t\t\t\t}},\n\t\t\t\t{$sort: {amount: -1}}\n\t\t\t])\n\t\t} catch(err) {\n\t\t\tHelper.notifyError(err, `Error in fetching leaderBoard in user controller`)\n\t\t\treturn res.status(510).send({\n\t\t\t\tmessage: `Something went wrong. Please try again`,\n\t\t\t\terr: err.message\n\t\t\t})\n\t\t}\n\t\treturn res.status(200).send({\n\t\t\tleaderBoard: leaderBoard,\n\t\t\tmessage: 'Operation successful.'\n\t\t})\n\t}", "async postParsingAnalysis () {\n var mapped = Object.keys(this.results).map(addr => {return { addr: addr, count: this.results[addr] }})\n var sortedByCount = this.sortEntriesByCount(mapped)\n var topNentries = this.getTopN(sortedByCount, N)\n\n var fileName = `${this.baseOutPath}-${analysisName}.json`\n var fileContent = {\n // Signal and format to visualize as piechart\n piechart: {\n datasets: [{\n backgroundColor: ['#D33F49', '#77BA99', '#23FFD9', '#27B299', '#831A49'],\n data: this.formatData(topNentries)\n }],\n labels: await this.formatLabelsForPieChart(topNentries)\n },\n hint: 'The labels of this chart have been computed using temporally sensitive data'\n }\n var summary = {\n fileName: fileName,\n attackCategory: 'Network State',\n analysisName: `Top ${N} sources by traffic`,\n supportedDiagrams: ['PieChart']\n }\n return await this.storeAndReturnResult(fileName, fileContent, summary)\n }", "function getAllStats() {\n var fields = JSON.stringify({\n user : 1,\n right : 1,\n wrong : 1,\n _id : 0\n });\n var url = properties.mongoStatsUrl + \"?apiKey=\" + properties.mongoLabApiKey + \"&f=\" + encodeURIComponent(fields) + \"&l=100000\";\n var response = fetchUrlWithLogging(url, \"Mongo q: \" + q, {});\n var responseText = response.getContentText();\n // vrati pole dokumentov obsahujucich mena uzivatelov, right a wrong hodnoty\n var data = JSON.parse(responseText);\n return aggregateSumRightWrong(data);\n}", "async getView() {\n const findAll = _promisify((...args) => {\n this.collection.aggregate(...args);\n });\n const result = await findAll([\n { $sort: { _id: -1 } },\n { $group: { _id: `$${this.keyName}`, data: { $first: '$$ROOT' } } },\n { $project: { _id: 0, 'data.nodes': 0 } },\n ])\n .then((a) => a)\n .catch((e) => {\n throw ServerError('Failed to get View', e);\n });\n const all = await result.toArray();\n const flatAll = all.map((d) => {\n return { ...d.data };\n });\n return flatAll;\n }", "function generateComparisonChartData(){\n\n let all_comparison_chart_data = {};\n // we actually only need these keys to be in the dictionary \n // because for the comparison chart, these are the only metrics we use\n let keys_to_keep = [\"date\", \"spend\", \"trial_starts_all\", \"ltv_subs_all\", \"ltv_subs_revenue\"];\n\n // we want to run the following operations for both the regular chartdata AND the aggregate\n // that way we can pull either the single advertiser's information, or the aggregate data in the\n // comparisonChart() function where we actually generate the chart\n [chartdata, chartdata_aggregate].map( data_to_use => {\n // find all the advertisers selected that are not Organic\n let unique_paid_advertisers = data_to_use.advertiser.filter( onlyUnique ).filter( x => x !== \"Organic\");\n\n // in the case that Android is the only OS chosen, we want to only allow certain advertisers\n if(os_chosen.length === 1 && os_chosen.includes(\"ANDROID\")){\n unique_paid_advertisers = unique_paid_advertisers.filter(x => [\"Facebook Ads\", \"pinterest_int\", \"snapchat_int\", \"Aggregate Paid\"].includes(x));\n }\n\n // for all the advertisers selected, create a dictionary with each advertiser as a top level key\n // then the value of that key will be the information needed for the chart series for that advertiser\n unique_paid_advertisers.map((advertiser,i) => {\n // create a new dictionary to load data into\n let advertiser_comparison_data = {};\n\n // load the \"advertiser_comparison_data\" dictionary with only the date and metrics (keys) we care about for comparison charts\n for (key of keys_to_keep){\n advertiser_comparison_data[key] = data_to_use[key].filter((d,i) => {\n // return indexes_of_data_to_keep[i];\n // we could use this line of code and eliminate the need for creating the \"indexes_of_data_to_keep\" list.\n // but it would be slightly more confusing as to what we are doing and only save a little time.\n return (data_to_use.advertiser[i] === advertiser);\n });\n }\n\n all_comparison_chart_data[advertiser] = advertiser_comparison_data;\n\n });\n });\n\n // THE FINAL DICTIONARY WILL LOOK LIKE THIS\n //{\n // date: [\"2020-02-10\", \"2020-02-11\", etc.....]\n // advertiser: [\"Aggregate Paid\", \"Aggregate Paid\", etc.....]\n // spend: [1460.83, 1168.31, etc.....]\n // trial_starts_all: [101, 81, etc.....]\n // ltv_subs_all: [10, 2, etc.....]\n // ltv_subs_revenue: [475.2760479755903, 134.31296573571356, etc.....]\n //}\n\n return all_comparison_chart_data;\n}", "function _showAggregateAnalitycs(client){\r\n\r\n\t\t\twindow.location.hash = '';\r\n\r\n\t\t\tif(Page.mediaspots.length == 0){\r\n\t\t\t\t$div.hide();\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\t_mediaspot = null;\r\n\r\n \t\t$('[href=\"#tab-analytics\"]').tab('show')\r\n\t\t\t$div.find('.mediaspot-tabs').hide();\r\n\r\n\t\t\tvar title = '';\r\n\t\t\tif($('#select_content_provider option').length > 1){\r\n\t\t\t\ttitle = 'Aggregated analytics for <b>' + Page.contentProvider.displayName + '</b>';\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\ttitle = 'Aggregated analytics';\r\n\t\t\t}\r\n\t\t\t$div.find('h4').html(title);\r\n\t\t\t$div.show();\r\n\r\n\r\n\t\t\tDownloadsOverTime.show(client);\r\n\t\t\tTableTopFiles.show(client);\r\n\t\t}", "AggregateGetTotalEarning(filter) {\n return new Promise((resolve, reject) => {\n this.collection.aggregate([\n {\n $match: filter\n },\n {\n $unwind: '$restaurantInfo'\n },\n {\n $group: {\n _id: {\n resId: '$restaurantInfo.restaurantId',\n name: '$restaurantInfo.name'\n },\n price: {\n $sum: '$restaurantInfo.totalPrice'\n }\n }\n },\n {\n $project: {\n _id: 0,\n resId: '$_id.resId',\n name: '$_id.name',\n price: 1\n }\n }\n ], (err, data) => {\n if (err) return reject({ message: err, status: 0 });\n\n return resolve(data);\n })\n })\n }", "function shearMyData() {\r\n for (let index = 0; index < AllProducts.length; index++) {\r\n clicks.push(AllProducts[index].clicks);\r\n views.push(AllProducts[index].views);\r\n\r\n }\r\n}", "function analytics(req, res) {\n var operation = requestOperation(req);\n if (process.env.IS_MONITORING_ENABLED === 'true' && operation) {\n var apiVersion = requestApiVersion(req);\n var ip = requestIp(req);\n var userAgent = requestUserAgent(req);\n var modelName = requestModelName(req);\n res[ANALYTICS_KEY] = new AnalyticsEntry(apiVersion, operation, modelName, ip, userAgent);\n res[ANALYTICS_KEY].setApiCommunicationStart(new Date());\n }\n}", "function produceReport(){\n // this is were most functions are called\n\n userURL = getuserURL();\n\n // add this into the website\n vertifyHttps(userURL); // check if the url is http/s\n googleSafeBrowsingAPI(userURL);\n virusTotalAPI(userURL);\n apilityCheck(userURL);\n}", "function aggregation(req, res, Output, Aggretation, Functions) {\n\n\tthis.aggregate = aggregate;\t\n\n\tfunction aggregate(){\n\t var cur_uri='';\n\t\tvar cur_end = -1;\n\t var grp=-1;\n \tvar groups = new Array();\n\t\tvar group_names = new Array();\n\t\tvar group_ends = new Array();\n\t Output.find({},function (err, C) {\n \t if (err) return console.error(err);\n\n\t\t\t//Group\n \tfor(var i=0; i < C.length; i++){\n if( C[i].uri != cur_uri ){\n grp++;\n cur_uri = C[i].uri;\n cur_end = C[i].end;\n groups[grp] = new Array();\n\t\t\t\t\tgroup_names.push(cur_uri);\n\t\t\t\t\tgroup_ends.push(cur_end);\n }\n if(groups[grp]){\n\t\t\t\t\tvar marks = C[i].marks.split(',').map(Number);\n\t\t\t\t\tfor(var j=0; j < marks.length; j++){\n\t\t\t\t\t\tif(marks[j] > 0){\n\t\t\t\t\t\t\tgroups[grp].push(marks[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n \t}\n\n\t\t\tvar videos = new Array;\n\t\t\tfor(var i=0; i < groups.length; i++){\n\t\t\t\tvar group = groups[i];\n\t\t\t\tgroup.sort(function(a,b){return a - b;});\n\t\t\t\tconsole.log('#'+group_names[i]);\n\t\t\t\tvar ranges = new Array;\n\t\t\t\tvar cur_range = -1;\n\t\t\t\tvar cur_value = -1;\n\t\t\t\tvar cont = 0;\n\t\t\t\tvar total = 0;\n\t\t\t\tfor(var j=0; j < group.length; j++){\n\t\t\t\t\tif(parseFloat(group[j]) > (cur_value + 0)){\n\t\t\t\t\t\tif(cur_range >= 0 && cont > 0){\n\t\t\t\t\t\t\tranges.push(parseFloat(total/cont));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur_range++;\n\t\t\t\t\t\tcur_value = parseFloat(group[j]);\n\t\t\t\t\t\tcont = 0;\n\t\t\t\t\t\ttotal = 0;\n\t\t\t\t\t}\n\t\t\t\t\tcont++;\n\t\t\t\t\ttotal += parseFloat(group[j]);\n\t\t\t\t}\n\t\t\t\tvideos.push({'uri':group_names[i], 'starts':ranges, 'end':group_ends[i]});\n\t\t\t\tfor(var j=0; j < ranges.length; j++){\n\t\t\t\t\tconsole.log(ranges[j]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//Store\n\t\t\tfor(i=0; i < videos.length; i++){\n\t\t\t\t//console.log(videos[i]);\n\t\t\t\tvar starts = videos[i].starts;\n\t\t\t\tvar uri = videos[i].uri;\n\t\t\t\tvar end = videos[i].end;\n\t\t\t\tfor(var j=0; j < starts.length -1; j++){\n\t\t\t\t \tvar data ={'uri': uri,'start': starts[j],'end': starts[j+1]}\n \tvar a = new Aggregation(data);\n \ta.save(function (err, m0) {if (err) return console.error(err);});\t\n\t\t\t\t}\n \tvar data ={'uri': uri,'start': starts[starts.length-1],'end': end}\n var a = new Aggregation(data);\n a.save(function (err, m0) {if (err) return console.error(err);});\n\t\t\t}\n\n \t res.end();\n\t }).sort({'uri' : 1});\n\t}\n}", "function consumptionMapData() {\n /* eslint-disable no-undef */\n emit(this.id, { \n litresConsumed: this.litresConsumed, \n kilometersTravelled: this.kilometersTravellled,\n litrosTanque: this.litrosTanque, \n kilometraje: this.kilometraje,\n processed: this.processed \n });\n /* eslint-enable no-undef */\n}", "function excelReportFinal(){\n\t\t\t\t\t\texcelReportSummaryByBillingModes();\n\t\t\t\t\t}", "summarize() {\n return null;\n }", "summarize() {\n return null;\n }", "function getOverviewData(map, sumLevel, sourceID) {\n\tvar activePCs = getSelections(\"activePCs\");\n\tvar activeSources = getSelections(\"activeSources\");\n\n\tvar datasetNames = {}; // keyset of all datasets (not array to make\n\t// datasets uinique)\n\tvar sum = {};\n\tvar sumKey = \"\";\n\n\tif (sumLevel == 3) {\n\t\tvar datasetName = \"ReceivedSubIDs\";\n\t\tdatasetNames[datasetName] = 1;\n\t\tfor ( var host in map) {\n\t\t\tvar subDetectorData = map[host][sourceID]\n\t\t\tif (subDetectorData) {\n\t\t\t\tfor ( var subID in subDetectorData) {\n\t\t\t\t\tif (!sum[subID]) {\n\t\t\t\t\t\tsum[subID] = {};\n\t\t\t\t\t\tsum[subID][datasetName] = subDetectorData[subID];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsum[subID][datasetName] += subDetectorData[subID];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor ( var host in map) {\n\t\t\tif (!activePCs[host]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sumLevel == 1 && !sum[host]) {\n\t\t\t\tsum[host] = {};\n\t\t\t\tsumKey = host;\n\t\t\t}\n\t\t\tfor ( var source in map[host]) {\n\t\t\t\tif (!activeSources[source]) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ((sumLevel == 2)) {\n\t\t\t\t\tif(!sum[source]){\n\t\t\t\t\t\tsum[source] = {};\n\t\t\t\t\t}\n\t\t\t\t\tsumKey = source;\n\t\t\t\t}\n\t\t\t\tfor ( var key in map[host][source]) {\n\t\t\t\t\tif (!sum[sumKey][key]) {\n\t\t\t\t\t\tsum[sumKey][key] = map[host][source][key];\n\t\t\t\t\t\tdatasetNames[key] = 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsum[sumKey][key] += map[host][source][key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar chartData = {};\n\tchartData.labels = [];\n\tchartData.datasets = [];\n\n\t/*\n\t * Find maximum values\n\t */\n\tvar scaleFactors = {};\n\tfor ( var dataset in datasetNames) {\n\t\tscaleFactors[dataset] = 0;\n\t\tfor ( var label in sum) {\n\t\t\tif (sum[label][dataset] > scaleFactors[dataset]) {\n\t\t\t\tscaleFactors[dataset] = sum[label][dataset];\n\t\t\t}\n\t\t}\n\t}\n\t/*\n\t * Calculate scale factors for every dataset and store labels\n\t */\n\tfor ( var dataset in datasetNames) {\n\t\tscaleFactors[dataset] = scaleValue(scaleFactors[dataset]);\n\t}\n\n\tfor ( var label in sum) {\n\t\tchartData.labels.push(label);\n\t}\n\n\tvar datasetNum = 0;\n\tfor ( var dataset in datasetNames) {\n\t\tvar data = [];\n\t\tvar scale = scaleFactors[dataset];\n\t\tfor ( var label in sum) {\n\t\t\tdata.push(sum[label][dataset] / scale['factor']);\n\t\t}\n\n\t\tchartData.datasets.push({\n\t\t\t'label' : dataset\n\t\t\t\t\t+ (scale['prefix'] ? ' [' + scale['prefix'] + ']' : ''),\n\t\t\t'data' : data,\n\t\t\tfillColor : \"rgba(\" + barCollors[datasetNum] + \",0.5)\",\n\t\t\tstrokeColor : \"rgba(\" + barCollors[datasetNum] + \",1)\",\n\t\t\tpointColor : \"rgba(\" + barCollors[datasetNum] + \",1)\",\n\t\t\tpointStrokeColor : \"#fff\",\n\t\t\tpointHighlightFill : \"#fff\",\n\t\t\tpointHighlightStroke : \"rgba(\" + barCollors[datasetNum++] + \",1)\",\n\t\t});\n\t}\n\n//\tconsole.log(scaleFactors);\n//\tconsole.log(sum);\n//\tconsole.log(chartData);\n//\tconsole.log(\"########\");\n\treturn chartData;\n}", "async _getAllAggregateExpenses(req, res) {\n // log method\n logger.log(1, '_getAllAggregateExpenses', 'Attempting to get all aggregate expenses');\n\n // compute method\n try {\n if (\n this.isAdmin(req.employee) ||\n this.isUser(req.employee) ||\n this.isIntern(req.employee) ||\n this.isManager(req.employee)\n ) {\n // employee is an admin or user\n // get expense types\n let expenseTypes;\n\n let employeesData;\n let expensesData;\n if (this.isAdmin(req.employee) || this.isManager(req.employee)) {\n // get all employee and expense data if admin\n [expenseTypes, employeesData, expensesData] = await Promise.all([\n this.getAllExpenseTypes(),\n this.employeeDynamo.getAllEntriesInDB(),\n this.expenseDynamo.getAllEntriesInDB()\n ]);\n } else {\n // get the requesting employee and expenses\n [expenseTypes, employeesData, expensesData] = await Promise.all([\n this.getAllExpenseTypes(),\n this.employeeDynamo.getEntry(req.employee.id),\n this.expenseDynamo.querySecondaryIndexInDB('employeeId-index', 'employeeId', req.employee.id)\n ]);\n employeesData = [employeesData];\n }\n let employees = _.map(employeesData, (employeeData) => {\n return new Employee(employeeData);\n });\n\n let expenses = _.map(expensesData, (expenseData) => {\n return new Expense(expenseData);\n });\n\n let aggregateExpenses = this._aggregateExpenseData(expenses, employees, expenseTypes);\n\n // log success\n logger.log(1, '_getAllAggregateExpenses', 'Successfully got all aggregate expenses');\n\n // send successful 200 status\n res.status(200).send(aggregateExpenses);\n\n // return aggregate expenses\n return aggregateExpenses;\n } else {\n // insuffient employee permissions\n let err = {\n code: 403,\n message: 'Unable to get all aggregate expenses due to insufficient employee permissions.'\n };\n\n throw err; // handled by try-catch\n }\n } catch (err) {\n // log error\n logger.log(1, '_getAllAggregateExpenses', 'Failed to get all aggregate expenses');\n\n // send error status\n this._sendError(res, err);\n\n // return error\n return err;\n }\n }", "function doSummary() {\n if (userType == \"EXT\") {\n $(\"#merchAccts\").val($(\"#merchAccts\").val());\n }\n else {\n validateSummary4INT();\n $(\"#merchAccts\").val();\n }\n\n // cacheSearchValues();\n\n $.blockUI({\n message: PROCESSING,\n overlayCSS: {backgroundColor: '#E5F3FF'}\n });\n\n $(\"#reportForm\").attr(\"action\", \"summaryReport.htm\");\n $(\"#reportForm\").submit();\n}", "function getOverview() {\n db.collection(\"overview_visitor\")\n .get()\n .then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n // doc.data() is never undefined for query doc snapshots\n console.log(\"Your document data is: \", doc.data());\n overview = doc.data();\n displayRecentDonors();\n displayTopDonors();\n });\n })\n .catch(function(error) {\n console.log(\"Error getting documents: \", error);\n });\n}", "function queryReadings() {\n\t\t\tdashboard.queryReadings();\n\t\t}", "function getData() {\r\n\r\n //count each time a case is taught at HKS\r\n //In other words, number of sessions in which a case was used duirng a specified academic year\r\n //these numbers may reflect a sigle session thatused multiple cases,\r\n //or an individual case that is used multiple times in multiple places\r\n //vars reset each time function is called \r\n var pubCount5 = 0;\r\n var pubCount10 = 0;\r\n var pubCount15 = 0;\r\n var pubCount20 = 0;\r\n var pubCount25 = 0;\r\n var pubCount30 = 0;\r\n var pubCount35 = 0;\r\n var pubCount40 = 0;\r\n var pubCount40more = 0;\r\n var all = 0;\r\n var lessThanTen = 0;\r\n\r\n //unique cases\r\n var UpubCount5 = 0;\r\n var UpubCount10 = 0;\r\n var UpubCount15 = 0;\r\n var UpubCount20 = 0;\r\n var UpubCount25 = 0;\r\n var UpubCount30 = 0;\r\n var UpubCount35 = 0;\r\n var UpubCount40 = 0;\r\n var UpubCount40more = 0;\r\n\r\n var yearAll = 0;\r\n var noPubDate = 0;\r\n var UnoPubDate = 0;\r\n var UlessThanTen = 0;\r\n\r\n //unique cases used in EE\r\n var UpubCount5_EE = 0;\r\n var UpubCount10_EE = 0;\r\n var UpubCount15_EE = 0;\r\n var UpubCount20_EE = 0;\r\n var UpubCount25_EE = 0;\r\n var UpubCount30_EE = 0;\r\n var UpubCount35_EE = 0;\r\n var UpubCount40_EE = 0;\r\n var UpubCount40more_EE = 0;\r\n var UnoPubDate_EE = 0;\r\n\r\n //unique cases used in DP\r\n var UpubCount5_DP = 0;\r\n var UpubCount10_DP = 0;\r\n var UpubCount15_DP = 0;\r\n var UpubCount20_DP = 0;\r\n var UpubCount25_DP = 0;\r\n var UpubCount30_DP = 0;\r\n var UpubCount35_DP = 0;\r\n var UpubCount40_DP = 0;\r\n var UpubCount40more_DP = 0;\r\n var UnoPubDate_DP = 0;\r\n\r\n var yearlyCaseNames = [];\r\n\r\n //Initialize chart with data and settings\r\n //fill pubDate var with publication dates from case data list\r\n for (var i = 0; i < caseData.length; ++i) {\r\n\r\n //make the date string from the case data list a usable formatted date - see moment.js\r\n var pubDate = moment(new Date(caseData[i].PubDate));\r\n\r\n //fill pubDateYear var with just the years of the publication dates from pubDate\r\n var pubDateYear = pubDate._i.getFullYear();\r\n\r\n //iterate through the data, and if the AY matches the selected year, populate var based on time/ age\r\n //want to consolidate into a different more effecient function - feedback welcome\r\n if (caseData[i].AY == currentYear) {\r\n all++;\r\n yearCount++;\r\n if (pubDateYear >= pastTen) {\r\n lessThanTen ++;\r\n }\r\n if (pubDateYear <= todayYear && pubDateYear >= pastFive ) {\r\n pubCount5++;\r\n }\r\n else if (pubDateYear < pastFive && pubDateYear >= pastTen) {\r\n pubCount10++;\r\n }\r\n else if (pubDateYear < pastTen && pubDateYear >= pastFifteen) {\r\n pubCount15++;\r\n }\r\n else if (pubDateYear < pastFifteen && pubDateYear >= pastTwenty) {\r\n pubCount20++;\r\n }\r\n else if (pubDateYear < pastTwenty && pubDateYear >= pastTwentyFive) {\r\n pubCount25++;\r\n }\r\n else if (pubDateYear < pastTwentyFive && pubDateYear >= pastThirty) {\r\n pubCount30++;\r\n }\r\n else if(pubDateYear < pastThirty && pubDateYear >= pastThirtyFive) {\r\n pubCount35++;\r\n }\r\n else if (pubDateYear < pastThirtyFive && pubDateYear >= pastForty) {\r\n pubCount40++;\r\n }\r\n else if (caseData[i].PubDate == \"00-Jan-1900\") { \r\n noPubDate++;\r\n }\r\n else if (caseData[i].PubDate == \"0\") {\r\n noPubDate++;\r\n }\r\n else if (caseData[i].PubDate ==\"\") {\r\n noPubDate++;\r\n }\r\n else {\r\n pubCount40more++;\r\n }\r\n\r\n //array with records of ay, case title, and pub date in selected AY\r\n yearlyCaseNames.push({caseTitle: caseData[i].CaseTitle, pubDate: caseData[i].PubDate, ay: caseData[i].AY, dept: caseData[i].Department});\r\n \r\n }\r\n }\r\n \r\n //Remove duplicates from the yearlyCaseNames array. Resulting object should be list of unique\r\n //case titles from selected AY with pubdate if applicable \r\n var auxArr = {};\r\n\r\n for ( var i=0, len=yearlyCaseNames.length; i < len; i++ )\r\n auxArr[yearlyCaseNames[i]['caseTitle']] = yearlyCaseNames[i];\r\n\r\n yearlyCaseNames = new Array();\r\n for ( var key in auxArr )\r\n yearlyCaseNames.push(auxArr[key]);\r\n \r\n console.log(\"yearlyCaseNames\");\r\n console.log(yearlyCaseNames);\r\n console.log(\"auxArr\");\r\n console.log(auxArr);\r\n\r\n \r\n\r\n //age tally for full list of uniqe case titles taught in specified AY\r\n for (var i = 0; i < yearlyCaseNames.length; ++i) {\r\n //make the date string from the case data list a usable formatted date - see moment.js\r\n var UpubDate = moment(new Date(yearlyCaseNames[i].pubDate));\r\n\r\n //fill UpubDateYear var with just the years of the publication dates from UpubDate\r\n var UpubDateYear = UpubDate._i.getFullYear();\r\n \r\n yearAll++\r\n\r\n\r\n if (UpubDateYear >= pastTen) {\r\n UlessThanTen ++;\r\n }\r\n if (UpubDateYear <= todayYear && UpubDateYear >= pastFive ) {\r\n UpubCount5++;\r\n }\r\n else if (UpubDateYear < pastFive && UpubDateYear >= pastTen) {\r\n UpubCount10++;\r\n }\r\n else if (UpubDateYear < pastTen && UpubDateYear >= pastFifteen) {\r\n UpubCount15++;\r\n }\r\n else if (UpubDateYear < pastFifteen && UpubDateYear >= pastTwenty) {\r\n UpubCount20++;\r\n }\r\n else if (UpubDateYear < pastTwenty && UpubDateYear >= pastTwentyFive) {\r\n UpubCount25++;\r\n }\r\n else if (UpubDateYear < pastTwentyFive && UpubDateYear >= pastThirty) {\r\n UpubCount30++;\r\n }\r\n else if(UpubDateYear < pastThirty && UpubDateYear >= pastThirtyFive) {\r\n UpubCount35++;\r\n }\r\n else if (UpubDateYear < pastThirtyFive && UpubDateYear >= pastForty) {\r\n UpubCount40++;\r\n }\r\n else if (UpubDateYear == \"00-Jan-1900\") { \r\n UnoPubDate++;\r\n }\r\n else if (UpubDateYear == \"0\") {\r\n UnoPubDate++;\r\n }\r\n else if (UpubDateYear == \"\") {\r\n UnoPubDate++;\r\n }\r\n else if (isNaN(UpubDateYear) == true) {\r\n UnoPubDate++;\r\n }\r\n else {\r\n UpubCount40more++;\r\n }\r\n\r\n //age tally for uniqe case titles taught at Executive Education in specified AY \r\n if (yearlyCaseNames[i].dept == \"Executive Education\") {\r\n\r\n if (UpubDateYear <= todayYear && UpubDateYear >= pastFive ) {\r\n UpubCount5_EE++;\r\n }\r\n else if (UpubDateYear < pastFive && UpubDateYear >= pastTen) {\r\n UpubCount10_EE++;\r\n }\r\n else if (UpubDateYear < pastTen && UpubDateYear >= pastFifteen) {\r\n UpubCount15_EE++;\r\n }\r\n else if (UpubDateYear < pastFifteen && UpubDateYear >= pastTwenty) {\r\n UpubCount20_EE++;\r\n }\r\n else if (UpubDateYear < pastTwenty && UpubDateYear >= pastTwentyFive) {\r\n UpubCount25_EE++;\r\n }\r\n else if (UpubDateYear < pastTwentyFive && UpubDateYear >= pastThirty) {\r\n UpubCount30_EE++;\r\n }\r\n else if(UpubDateYear < pastThirty && UpubDateYear >= pastThirtyFive) {\r\n UpubCount35_EE++;\r\n }\r\n else if (UpubDateYear < pastThirtyFive && UpubDateYear >= pastForty) {\r\n UpubCount40_EE++;\r\n }\r\n else if (UpubDateYear == \"00-Jan-1900\") { \r\n UnoPubDate_EE++;\r\n }\r\n else if (UpubDateYear == \"0\") {\r\n UnoPubDate_EE++;\r\n }\r\n else if (UpubDateYear == \"\") {\r\n UnoPubDate_EE++;\r\n }\r\n else if (isNaN(UpubDateYear) == true) {\r\n UnoPubDate_EE++;\r\n }\r\n else {\r\n UpubCount40more_EE++;\r\n }\r\n } \r\n\r\n //age tally for uniqe case titles taught at Degree Programs in specified AY \r\n if (yearlyCaseNames[i].dept == \"Degree Program\" || yearlyCaseNames[i].dept == \"Degree Programs\") {\r\n\r\n if (UpubDateYear <= todayYear && UpubDateYear >= pastFive ) {\r\n UpubCount5_DP++;\r\n }\r\n else if (UpubDateYear < pastFive && UpubDateYear >= pastTen) {\r\n UpubCount10_DP++;\r\n }\r\n else if (UpubDateYear < pastTen && UpubDateYear >= pastFifteen) {\r\n UpubCount15_DP++;\r\n }\r\n else if (UpubDateYear < pastFifteen && UpubDateYear >= pastTwenty) {\r\n UpubCount20_DP++;\r\n }\r\n else if (UpubDateYear < pastTwenty && UpubDateYear >= pastTwentyFive) {\r\n UpubCount25_DP++;\r\n }\r\n else if (UpubDateYear < pastTwentyFive && UpubDateYear >= pastThirty) {\r\n UpubCount30_DP++;\r\n }\r\n else if(UpubDateYear < pastThirty && UpubDateYear >= pastThirtyFive) {\r\n UpubCount35_DP++;\r\n }\r\n else if (UpubDateYear < pastThirtyFive && UpubDateYear >= pastForty) {\r\n UpubCount40_DP++;\r\n }\r\n else if (UpubDateYear == \"00-Jan-1900\") { \r\n UnoPubDate_DP++;\r\n }\r\n else if (UpubDateYear == \"0\") {\r\n UnoPubDate_DP++;\r\n }\r\n else if (UpubDateYear == \"\") {\r\n UnoPubDate_DP++;\r\n }\r\n else if (isNaN(UpubDateYear) == true) {\r\n UnoPubDate_DP++;\r\n }\r\n else {\r\n UpubCount40more_DP++;\r\n }\r\n }\r\n\r\n\r\n\r\n }\r\n\r\n\r\n\r\n //testing for the counting vars\r\n console.log(\"Cases in 0-5 years: \" + pubCount5);\r\n console.log(\"Cases in 5-10 years: \" + pubCount10);\r\n console.log(\"Cases in 10-15 years: \" + pubCount15);\r\n console.log(\"Cases in 15-20 years: \" + pubCount20);\r\n console.log(\"Cases in 20-25 years: \" + pubCount25);\r\n console.log(\"Cases in 25-30 years: \" + pubCount30);\r\n console.log(\"Cases in 30-35 years: \" + pubCount35);\r\n console.log(\"Cases in 35-40 years: \" + pubCount40);\r\n console.log(\"Cases in 40+ years: \" + pubCount40more);\r\n console.log(\"No pub date: \" + noPubDate);\r\n console.log(\"PUBDATE: \" + pubDate);\r\n\r\n\r\n withData = (all - noPubDate);\r\n console.log(\"all: \" + all);\r\n console.log(\"no pub: \" + noPubDate);\r\n console.log(all);\r\n console.log(\"wiz with: \" + withData);\r\n console.log(\"No pub date: \" + noPubDate);\r\n console.log(\"PUBDATE: \" + pubDate);\r\n console.log(\"past 10:\" + pastTen);\r\n console.log(\"les than:\" + lessThanTen);\r\n\r\n\r\n\r\n\r\n console.log(\"Cases in 0-5 yearsUUUU: \" + UpubCount5);\r\n console.log(\"Cases in 5-10 yearsUUUU: \" + UpubCount10);\r\n console.log(\"Cases in 10-15 yearsUUUU: \" + UpubCount15);\r\n console.log(\"Cases in 15-20 yearsUUUU: \" + UpubCount20);\r\n console.log(\"Cases in 20-25 yearsUUUU: \" + UpubCount25);\r\n console.log(\"Cases in 25-30 yearsUUUU: \" + UpubCount30);\r\n console.log(\"Cases in 30-35 yearsUUUU: \" + UpubCount35);\r\n console.log(\"Cases in 35-40 yearsUUUU: \" + UpubCount40);\r\n console.log(\"Cases in 40+ years: \" + UpubCount40more);\r\n console.log(\"No pub date: \" + UnoPubDate);\r\n console.log(\"UPUBDATE: \" + UpubDate);\r\n\r\n\r\n\r\n console.log(\"Cases in 0-5 yearsUUUU_EE: \" + UpubCount5_EE);\r\n console.log(\"Cases in 5-10 yearsUUUU_EE: \" + UpubCount10_EE);\r\n console.log(\"Cases in 10-15 yearsUUUU_EE: \" + UpubCount15_EE);\r\n console.log(\"Cases in 15-20 yearsUUUU_EE: \" + UpubCount20_EE);\r\n console.log(\"Cases in 20-25 yearsUUUU_EE: \" + UpubCount25_EE);\r\n console.log(\"Cases in 25-30 yearsUUUU_EE: \" + UpubCount30_EE);\r\n console.log(\"Cases in 30-35 yearsUUUU_EE: \" + UpubCount35_EE);\r\n console.log(\"Cases in 35-40 yearsUUUU_EE: \" + UpubCount40_EE);\r\n\r\n console.log(\"Cases in 0-5 yearsUUUU_DP: \" + UpubCount5_DP);\r\n console.log(\"Cases in 5-10 yearsUUUU_DP: \" + UpubCount10_DP);\r\n console.log(\"Cases in 10-15 yearsUUUU_DP: \" + UpubCount15_DP);\r\n console.log(\"Cases in 15-20 yearsUUUU_DP: \" + UpubCount20_DP);\r\n console.log(\"Cases in 20-25 yearsUUUU_DP: \" + UpubCount25_DP);\r\n console.log(\"Cases in 25-30 yearsUUUU_DP: \" + UpubCount30_DP);\r\n console.log(\"Cases in 30-35 yearsUUUU_DP: \" + UpubCount35_DP);\r\n console.log(\"Cases in 35-40 yearsUUUU_DP: \" + UpubCount40_DP);\r\n//chartjs config\r\n\r\n\r\n\r\n\r\n/*****************\r\nBAR CHART - Unique values\r\n*****************/\r\nvar barChartData_Unique = {\r\n labels: [\"0-5 Years\", \"5-10 Years\", \"10-15 Years\", \"15-20 Years\", \"20-25 Years\", \"25-30 Years\", \"30-35 Years\", \"35-40 Years\", \"40 + years\"],\r\n datasets: [\r\n {\r\n fillColor: \"#D55C19\",\r\n data: [UpubCount5, UpubCount10, UpubCount15, UpubCount20, UpubCount25, UpubCount30, UpubCount35, UpubCount40, UpubCount40more]\r\n },\r\n ]\r\n\r\n };\r\n\r\nvar ctx = document.getElementById(\"barCanvasUnique\").getContext(\"2d\");\r\nconsole.log(\"ctxORING: \" + ctx);\r\nvar myLine = new Chart(ctx).Bar(barChartData_Unique, {\r\n showTooltips: false,\r\n scaleOverride : false,\r\n scaleSteps : 10,\r\n scaleStepWidth : 30,\r\n scaleStartValue : 0,\r\n //stacked: true,\r\n onAnimationComplete: function () {\r\n\r\n var ctx = this.chart.ctx;\r\n ctx.font = this.scale.font;\r\n //ctx.fillStyle = this.scale.textColor\r\n ctx.textAlign = \"center\";\r\n ctx.textBaseline = \"bottom\";\r\n\r\n this.datasets.forEach(function (dataset) {\r\n dataset.bars.forEach(function (bars) {\r\n ctx.fillText(bars.value, bars.x, bars.y - 10);\r\n });\r\n })\r\n }\r\n\r\n});\r\n\r\n// ======================================================\r\n// Doughnut Chart 2\r\n// ======================================================\r\n\r\n// Doughnut Chart Options\r\nvar doughnutOptions2 = {\r\n //Boolean - Whether we should show a stroke on each segment\r\n segmentShowStroke : true,\r\n \r\n //String - The colour of each segment stroke\r\n segmentStrokeColor : \"#fff\",\r\n \r\n //Number - The width of each segment stroke\r\n segmentStrokeWidth : 2,\r\n \r\n //The percentage of the chart that we cut out of the middle.\r\n percentageInnerCutout : 50,\r\n \r\n //Boolean - Whether we should animate the chart \r\n animation : true,\r\n \r\n //Number - Amount of animation steps\r\n animationSteps : 50,\r\n \r\n //String - Animation easing effect\r\n animationEasing : \"easeOutBounce\",\r\n \r\n //Boolean - Whether we animate the rotation of the Doughnut\r\n animateRotate : true,\r\n\r\n //Boolean - Whether we animate scaling the Doughnut from the centre\r\n animateScale : true,\r\n \r\n //Function - Will fire on animation completion.\r\n onAnimationComplete : null,\r\n\r\n tooltipTemplate: \"<%= label %> <%= value %>\",\r\n \r\n onAnimationComplete: function()\r\n {\r\n this.showTooltip(this.segments, true);\r\n },\r\n \r\n tooltipEvents: [],\r\n \r\n showTooltips: true\r\n }\r\nvar uAll = yearlyCaseNames.length;\r\nvar uWithPubDate = (uAll - UnoPubDate);\r\n// Doughnut Chart Data\r\nvar doughnutData2 = [\r\n {\r\n value : UnoPubDate,\r\n color : \"#E0E0EB\"\r\n },\r\n {\r\n label: \"w/ Publication Date: \",\r\n value: uWithPubDate,\r\n color:\"#D55C19\"\r\n },\r\n/*\r\nvar doughnutData2 = [\r\n {\r\n value : UmoreThanTen_NOay,\r\n color : \"#E0E0EB\"\r\n },\r\n {\r\n label: \"< 10 Years: \",\r\n value: UlessThanTen_NOay,\r\n color:\"#6A7F10\"\r\n },\r\n*/\r\n]\r\n\r\n//Get the context of the Doughnut Chart canvas element we want to select\r\nvar ctx = document.getElementById(\"pieCanvas2\").getContext(\"2d\");\r\n\r\n// Create the Doughnut Chart\r\nvar mydoughnutChart2 = new Chart(ctx).Doughnut(doughnutData2, doughnutOptions2);\r\n\r\n/*****************\r\n\r\nLINE CHART\r\n\r\n*****************/\r\n$( document ).ready(function() {\r\n\r\nvar lineChartData = {\r\n labels: [\"0-5 Years\", \"5-10 Years\", \"10-15 Years\", \"15-20 Years\", \"20-25 Years\", \"25-30 Years\", \"30-35 Years\", \"35-40 Years\", \"40 + years\"],\r\n \r\n datasets: [{\r\n fillColor: \"transparent\",\r\n pointColor: \"black\",\r\n strokeColor: \"#003946\",\r\n data: [UpubCount5_EE, UpubCount15_EE, UpubCount10_EE, UpubCount20_EE, UpubCount25_EE, UpubCount30_EE, UpubCount35_EE, UpubCount40_EE, UpubCount40more_EE]\r\n \r\n },\r\n {\r\n fillColor: \"transparent\",\r\n pointColor: \"black\",\r\n strokeColor: \"#A71930\",\r\n data: [UpubCount5_DP, UpubCount10_DP, UpubCount15_DP, UpubCount20_DP, UpubCount25_DP, UpubCount30_DP, UpubCount35_DP, UpubCount40_DP, UpubCount40more_DP]\r\n }]\r\n };\r\n\r\nvar ctx = document.getElementById(\"lineCanvas\").getContext(\"2d\");\r\nvar myLine = new Chart(ctx).Line(lineChartData, {\r\n showTooltips: false,\r\n bezierCurve: false,\r\n \r\n onAnimationComplete: function () {\r\n\r\n var ctx = this.chart.ctx;\r\n ctx.font = this.scale.font;\r\n //ctx.fillStyle = this.scale.textColor\r\n ctx.textAlign = \"center\";\r\n ctx.textBaseline = \"bottom\";\r\n\r\n this.datasets.forEach(function (dataset) {\r\n dataset.points.forEach(function (points) {\r\n ctx.fillText(points.value, points.x, points.y - 10);\r\n });\r\n })\r\n },\r\n\r\n\r\n});\r\n\r\n});\r\n\r\n/*****************\r\nBAR CHART - Unique values - DEPT=EE\r\n*****************/\r\nvar barChartData_Unique_EE = {\r\n labels: [\"0-5 Years\", \"5-10 Years\", \"10-15 Years\", \"15-20 Years\", \"20-25 Years\", \"25-30 Years\", \"30-35 Years\", \"35-40 Years\", \"40 + years\"],\r\n datasets: [\r\n {\r\n fillColor: \"red\",\r\n data: [UpubCount5_EE, UpubCount15_EE, UpubCount10_EE, UpubCount20_EE, UpubCount25_EE, UpubCount30_EE, UpubCount35_EE, UpubCount40_EE, UpubCount40more_EE]\r\n },\r\n ]\r\n\r\n };\r\n\r\nvar ctx = document.getElementById(\"barCanvasUniqueEE\").getContext(\"2d\");\r\nconsole.log(\"ctxORING: \" + ctx);\r\nvar myLine = new Chart(ctx).Bar(barChartData_Unique_EE, {\r\n showTooltips: false,\r\n scaleOverride : false,\r\n scaleSteps : 10,\r\n scaleStepWidth : 30,\r\n scaleStartValue : 0,\r\n //stacked: true,\r\n onAnimationComplete: function () {\r\n\r\n var ctx = this.chart.ctx;\r\n ctx.font = this.scale.font;\r\n //ctx.fillStyle = this.scale.textColor\r\n ctx.textAlign = \"center\";\r\n ctx.textBaseline = \"bottom\";\r\n\r\n this.datasets.forEach(function (dataset) {\r\n dataset.bars.forEach(function (bars) {\r\n ctx.fillText(bars.value, bars.x, bars.y - 10);\r\n });\r\n })\r\n }\r\n\r\n});\r\n\r\n\r\n/*****************\r\nBAR CHART - Unique values - DEPT=DP\r\n*****************/\r\nvar barChartData_Unique_DP = {\r\n labels: [\"0-5 Years\", \"5-10 Years\", \"10-15 Years\", \"15-20 Years\", \"20-25 Years\", \"25-30 Years\", \"30-35 Years\", \"35-40 Years\", \"40 + years\"],\r\n datasets: [\r\n {\r\n fillColor: \"green\",\r\n data: [UpubCount5_DP, UpubCount10_DP, UpubCount15_DP, UpubCount20_DP, UpubCount25_DP, UpubCount30_DP, UpubCount35_DP, UpubCount40_DP, UpubCount40more_DP]\r\n },\r\n ]\r\n\r\n };\r\n\r\nvar ctx = document.getElementById(\"barCanvasUniqueDP\").getContext(\"2d\");\r\nconsole.log(\"ctxORING: \" + ctx);\r\nvar myLine = new Chart(ctx).Bar(barChartData_Unique_DP, {\r\n showTooltips: false,\r\n scaleOverride : false,\r\n scaleSteps : 10,\r\n scaleStepWidth : 30,\r\n scaleStartValue : 0,\r\n //stacked: true,\r\n onAnimationComplete: function () {\r\n\r\n var ctx = this.chart.ctx;\r\n ctx.font = this.scale.font;\r\n //ctx.fillStyle = this.scale.textColor\r\n ctx.textAlign = \"center\";\r\n ctx.textBaseline = \"bottom\";\r\n\r\n this.datasets.forEach(function (dataset) {\r\n dataset.bars.forEach(function (bars) {\r\n ctx.fillText(bars.value, bars.x, bars.y - 10);\r\n });\r\n })\r\n }\r\n\r\n});\r\n\r\n\r\n//EMND BAR CHARTS\r\n\r\n\r\n\r\nconsole.log(\"%^%*@%*@%@&*%@*&@%&*@%@^&%@&*@%@&*^%@&*%\");\r\nconsole.log(\"yearAll\" + yearAll);\r\n document.getElementById(\"uCasesAll\").innerHTML = yearAll;\r\n \r\nconsole.log(UlessThanTen);\r\n document.getElementById(\"lessTenAll\").innerHTML = UlessThanTen;\r\n\r\nconsole.log(UnoPubDate);\r\n\r\n document.getElementById(\"noPubAll\").innerHTML = UnoPubDate;\r\n \r\n\r\n}", "function loadData()\n{\n\tdb.collection('all').find().toArray(function(err, data){\n\t\tfor(var j in data)\n\t\t{ \n\t\t\tif(data[j]['name']==undefined)\n\t\t\t\tcontinue;\n\t\t\tvarUsage.names.push(data[j]['name'])\n\t\t\tvarUsage.amounts.push(0);\n\t\t\tvarUsage.dataIn.push(false);\n\t\t\tvarUsage.dimensions.push({});\n\t\t\tvarUsage.sources.push(data[j].source)\n\t\t\tvarUsage.bounds.push([0,0]);\n\t\t}\n endLoad();\n\t})\n\t\n\tdb.collection('allsuper').find().toArray(function(err, data){\n\t\tfor(var j in data)\n\t\t{\n\t\t\tsuperUsage.names.push(data[j]['name'])\n\t\t\tsuperUsage.amounts.push(0);\n\t\t\tsuperUsage.dataIn.push(false);\n\t\t\tsuperUsage.dimensions.push({});\n\t\t\tsuperUsage.dependancies.push(data[j]['dependancies']);\n\t\t\tsuperUsage.sources.push(data[j].source);\n\t\t}\n endLoad();\n\t})\n\t\n\tdb.collection('var').find({name:'Population'}).toArray(function(err, d){\n\t\tvar data=d[0].data;\n\t\tfor(var j in data)\n\t\t{\n\t\t\tfor(var k=0;k<data[j]/1000;k++)\n\t\t\t{\n\t\t\t\tpeople.push({fip:j})\n\t\t\t}\n\t\t}\n endLoad();\n\t})\n}", "function groupAll() {\n\n // reducing does nothing because currently we can't choose how the database will aggregate data\n var groupAllObj = {\n reduce: function () { return groupAllObj; },\n reduceCount: function () { return groupAllObj; },\n reduceSum: function () { return groupAllObj; },\n dispose: function () {},\n value: function () { return getData(dimensionName, false)[0].value; }\n };\n\n return groupAllObj;\n }", "function getLatestReports(user_id) { \n const query = {\n text:'SELECT public_id as id, created_at FROM reports_v3 WHERE user_id = $1 AND folder_id IN ( SELECT portfolio_id FROM portfolio_access_controls WHERE user_id = $2) AND archived_at IS NULL ORDER BY created_at DESC LIMIT 5',\n values: [user_id,user_id],\n };\n client.query(query, (err, res) => {\n if(err){\n throw err;\n }\n else{\n setReportValue(res);\n }\n })\n}", "aggregate(aggregateSteps) {\n return new Promise((res, rej) => {\n this.model.aggregate(aggregateSteps, (err, result) => {\n if (err) {\n return rej(err);\n }\n else {\n return res(result);\n }\n });\n });\n }", "summarizeIssue(issue) {\n const summary = {};\n summary.number = issue.number;\n summary.title = issue.title;\n summary.html_url = issue.html_url;\n summary.labels = issue.labels;\n // TODO: get events, comments and rollup up other \"stage\" data\n return summary;\n }", "AggregateReportByItemData(filter = {}, project1 = {}, unwind, project2 = {}, group = {}, project3 = {}, lookup = {}, unwind2, project4 = {}) {\n return new Promise((resolve, reject) => {\n this.collection.aggregate([\n {\n $match: filter\n },\n {\n $project: project1\n },\n {\n $unwind: unwind\n },\n {\n $unwind: unwind\n },\n {\n $project: project2\n },\n {\n $group: group\n },\n {\n $project: project3\n },\n {\n $lookup: lookup\n },\n {\n $unwind: unwind2\n },\n {\n $project: project4\n }\n ], (err, data) => {\n if (err) return reject({ message: err, status: 0 });\n\n return resolve(data);\n });\n });\n }", "function auctionStats(callback) {\n\tLicense.aggregate([\n\t{$match: { 'bid.auction.id': { $gt: 0}}},\n\t{$project: { _id:0, 'bid.auction.id':1, channel:1, MHz:1, \n\t\t'channelBlock.lowerBand':1, 'channelBlock.upperBand':1, \n\t\t'bid.amount.gross': 1, population:1}},\n\t{$group: { _id: {auction: '$bid.auction.id', channel: '$channel', MHz: '$MHz',\n\t\tstart: '$channelBlock.lowerBand', end: '$channelBlock.upperBand'}, \n\t\ttotalPrice: {$sum: '$bid.amount.gross'}, \n\t\ttotalPops: {$sum: '$population'} }},\n\t{$sort: { _id: 1}}\n\t], function (err, result) {\n\t\tcallback(err, result)\n\t})\n}", "get data() {\n\n // verify valid source provided\n if (this.dataSource && Object.keys(this.dataSource).length > 0) {\n\n let activityTypesMerged = [];\n\n // loop through keys\n for (const key in this.dataSource) {\n\n // push all activity objects into single array\n activityTypesMerged = activityTypesMerged.concat(this.dataSource[key]);\n\n }\n\n // aggregate collab/push days\n this.dataAggregateDays = rollup(activityTypesMerged,\n v => v.length,\n d => moment(d.date).format(\"YYYY-MM-DD\"),\n d => d.type\n );\n\n let dateEnd = moment(this.dateEnd);\n let dateStart = moment(this.dateStart);\n\n let weeks = [];\n\n // get list of first date of months\n while (dateStart < dateEnd) {\n\n // capture actual date iso string since moment mutates values\n let dateWeek = dateStart.format(\"YYYY-W\");\n\n // update list\n weeks.push(dateWeek);\n\n // iterate the date value\n dateStart.add(1, \"week\");\n\n }\n\n // because the time range may/may not be an entire year\n // we need to map index to iso week so we can reference the position later\n this.weekIndicies = weeks;\n\n // extract years\n this.years = [...new Set(this.weekIndicies.map(d => d.split(\"-\")[0]))];\n\n // get weekday values\n let weekdays = moment.weekdays();\n\n // shift so monday is the first day of the week\n weekdays.push(weekdays.shift());\n\n // update self\n this.weekdays = weekdays;\n\n let months = [];\n\n dateEnd = moment(this.dateEnd);\n dateStart = moment(this.dateStart);\n\n // get list of first date of months\n while (dateStart < dateEnd) {\n months.push(dateStart.format(\"YYYY-MM-DD\"))\n dateStart.add(1, \"month\")\n }\n\n // update self\n this.months = months;\n this.dataCells = this.activityTypes.map(d => this.extractActivity(d)).flat();\n\n }\n\n }", "function drawSumOfDataThroughHoursSubscriberGraph(r, fragmentId, query, aggregateRes, startHeight) {\r\n var maxUsage = aggregateRes.maxUsage;\r\n var colors = aggregateRes.colors;\r\n var aggregate = aggregateRes.aggregate;\r\n\r\n // sum the aggregate\r\n var hourlySum = [];\r\n for (var y = 0; y < aggregate[0].length; y++) {\r\n hourlySum[y] = {};\r\n for (var x = 0; x < aggregate.length; x++) {\r\n for (var prop in aggregate[x][y]) {\r\n if (x == 0) {\r\n hourlySum[y][prop] = 0;\r\n }\r\n hourlySum[y][prop] += aggregate[x][y][prop];\r\n }\r\n }\r\n }\r\n\r\n var maxHourlySum = 0;\r\n for (var i = 0; i < 24; i++) {\r\n var hourTot = 0;\r\n for (var tu in hourlySum[i]) {\r\n hourTot += hourlySum[i][tu];\r\n }\r\n if (hourTot > maxHourlySum) {\r\n maxHourlySum = hourTot;\r\n }\r\n }\r\n\r\n var width = $(fragmentId).innerWidth();\r\n var height = ($(\"#top\").height() - $(\".ui-tabs-nav\").outerHeight()) * (0.95 - mainGraphHeight);\r\n height = Math.floor(height);\r\n var availHeight = height - 20;\r\n var barHeight = 20;\r\n var xSpace = (width * mainGraphWidth - leftGutter - 20) / axisX.length;\r\n var correctionFactor = 5;\r\n for (i = 0; i < 24; i++) {\r\n var hourData = hourlySum[i];\r\n var hourTotal = 0;\r\n var yMove = 0;\r\n\r\n if (i >= 1 && i <= 5) {\r\n correctionFactor += i * 0.6;\r\n } else if ((i >= 6 && i <= 10) || (i >= 17 && i <= 21)) {\r\n correctionFactor += i * 0.1;\r\n } else if (i == 12) {\r\n correctionFactor += i * 0.2;\r\n }\r\n\r\n for (tu in hourData) {\r\n r.rect(leftGutter + xSpace * i + 10 + correctionFactor,\r\n startHeight + yMove,\r\n barHeight,\r\n (hourData[tu] / maxHourlySum) * availHeight\r\n ).attr({\r\n stroke: \"none\",\r\n fill: \"#\" + colors[tu]\r\n });\r\n hourTotal += hourData[tu];\r\n yMove += (hourData[tu] / maxHourlySum) * availHeight;\r\n }\r\n\r\n hourTotal = toFixed(hourTotal, 2);\r\n r.text(leftGutter + xSpace * i + 10 + correctionFactor, startHeight + yMove + 10, hourTotal).attr(defaultFont);\r\n }\r\n}", "static async getData () {\n return await App.getPage('popular', 1);\n }", "function exportDataAsCSV(aqsid, startEpoch, endEpoch, fileFormat) {\n const dataObject = {};\n let aggregatData;\n\n if (endEpoch === null) {\n aggregatData = AggrData.find({\n $and: [\n {\n epoch: {\n $in: startEpoch\n }\n }, {\n site: `${aqsid}`\n }\n ]\n }, {\n sort: {\n epoch: 1\n }\n }).fetch();\n } else {\n aggregatData = AggrData.find({\n site: `${aqsid}`,\n $and: [\n {\n epoch: {\n $gte: parseInt(startEpoch, 10)\n }\n },\n {\n $and: [\n {\n epoch: {\n $lte: parseInt(endEpoch, 10)\n }\n }\n ]\n }\n ] }, {\n sort: {\n epoch: 1\n }\n }).fetch();\n }\n\n switch (fileFormat) {\n case 'raw':\n if (aggregatData.length !== 0) {\n dataObject.data = [];\n dataObject.fields = ['siteID', 'dateGMT', 'timeGMT']; // create fields for unparse\n }\n _.each(aggregatData, (e) => {\n const obj = {};\n const siteID = e.site.substring(e.site.length - 4, e.site.length);\n if (siteID.startsWith('0')) {\n obj.siteID = e.site.substring(e.site.length - 3, e.site.length);\n } else if (siteID.startsWith('9')) {\n obj.siteID = e.site;\n } else {\n obj.siteID = e.site.substring(e.site.length - 4, e.site.length);\n }\n obj.dateGMT = moment.utc(moment.unix(e.epoch)).format('YY/MM/DD');\n obj.timeGMT = moment.utc(moment.unix(e.epoch)).format('HH:mm:ss');\n\n Object.keys(e.subTypes).forEach((instrument) => {\n if (Object.prototype.hasOwnProperty.call(e.subTypes, instrument)) {\n const measurements = e.subTypes[instrument];\n Object.keys(measurements).forEach((measurement) => {\n if (Object.prototype.hasOwnProperty.call(measurements, measurement)) {\n const data = measurements[measurement];\n\n let label = `${instrument}_${measurement}_flag`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n obj[label] = flagsHash[_.last(data).val].label; // Flag\n label = `${instrument}_${measurement}_value`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n\n let outputValue;\n if (data.length < 5) {\n outputValue = data[0].val; // calc\n } else {\n outputValue = data[1].val; // avg\n }\n\n // HNET Unit conversion for Temp from C to F\n if (measurement === 'Temp' || measurement === 'AmbTemp') {\n outputValue = (outputValue * 9 / 5) + 32;\n } else if (measurement === 'WS') {\n outputValue = Math.round(outputValue * 3600 / 1610.3 * 1000) / 1000;\n }\n if (outputValue !== 'undefined' && !isNaN(outputValue)) {\n // if (!isNaN(outputValue)) {\n obj[label] = outputValue.toFixed(3);\n }\n }\n });\n }\n });\n dataObject.data.push(obj);\n });\n break;\n case 'tceq_allchannels':\n if (aggregatData.length !== 0) {\n dataObject.data = [];\n dataObject.fields = ['siteID', 'dateGMT', 'timeGMT', 'status']; // create fields for unparse\n }\n _.each(aggregatData, (e) => {\n const obj = {};\n const siteID = e.site.substring(e.site.length - 4, e.site.length);\n if (siteID.startsWith('0')) {\n obj.siteID = e.site.substring(e.site.length - 3, e.site.length);\n } else {\n obj.siteID = e.site.substring(e.site.length - 4, e.site.length);\n }\n obj.dateGMT = moment.utc(moment.unix(e.epoch)).format('YY/MM/DD');\n obj.timeGMT = moment.utc(moment.unix(e.epoch)).format('HH:mm:ss');\n obj.status = 0;\n\n Object.keys(e.subTypes).forEach((instrument) => {\n if (Object.prototype.hasOwnProperty.call(e.subTypes, instrument)) {\n const measurements = e.subTypes[instrument];\n Object.keys(measurements).forEach((measurement) => {\n if (Object.prototype.hasOwnProperty.call(measurements, measurement)) {\n let label = `${instrument}_${measurement}_channel`;\n obj[label] = channelHash[`${instrument}_${measurement}`]; // channel\n\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n const data = measurements[measurement];\n\n label = `${instrument}_${measurement}_flag`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n obj[label] = flagsHash[_.last(data).val].label; // Flag\n label = `${instrument}_${measurement}_value`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n // taking care of flag Q (span)\n if (flagsHash[_.last(data).val].label === 'Q') {\n obj[label] = 0; // set value to 0\n } else {\n let outputValue = data[1].val; // avg\n // HNET Unit conversion for Temp from C to F\n if (measurement === 'Temp' || measurement === 'AmbTemp') {\n outputValue = (outputValue * 9 / 5) + 32;\n } else if (measurement === 'WS') {\n outputValue = Math.round(outputValue * 3600 / 1610.3 * 1000) / 1000;\n }\n obj[label] = outputValue.toFixed(3);\n }\n }\n });\n }\n });\n\n obj.QCref_channel = 50;\n obj.QCref_flag = 'K';\n obj.QCref_value = 0;\n obj.QCstatus_channel = 51;\n obj.QCstatus_flag = 'K';\n obj.QCstatus_value = 99000;\n dataObject.data.push(obj);\n });\n if (dataObject.fields !== undefined) {\n dataObject.fields.push('QCref_channel', 'QCref_flag', 'QCref_value', 'QCstatus_channel', 'QCstatus_flag', 'QCstatus_value');\n }\n break;\n case 'tceq': {\n const site = LiveSites.findOne({ AQSID: `${aqsid}` });\n if (site === undefined) {\n throw new Error(`Could not find AQSID: ${aqsid} in LiveSites.`);\n }\n const channels = site.Channels;\n const activeChannels = [];\n _.each(channels, (channel) => {\n if (channel.Status === 'Active') {\n activeChannels.push(channel.Name);\n }\n });\n if (aggregatData.length !== 0) {\n dataObject.data = [];\n dataObject.fields = ['siteID', 'dateGMT', 'timeGMT', 'status']; // create fields for unparse\n }\n _.each(aggregatData, (e) => {\n const obj = {};\n const siteID = e.site.substring(e.site.length - 4, e.site.length);\n if (siteID.startsWith('0')) {\n obj.siteID = e.site.substring(e.site.length - 3, e.site.length);\n } else {\n obj.siteID = e.site.substring(e.site.length - 4, e.site.length);\n }\n obj.dateGMT = moment.utc(moment.unix(e.epoch)).format('YY/MM/DD');\n obj.timeGMT = moment.utc(moment.unix(e.epoch)).format('HH:mm:ss');\n obj.status = 0;\n\n Object.keys(e.subTypes).forEach((instrument) => {\n if (Object.prototype.hasOwnProperty.call(e.subTypes, instrument)) {\n const measurements = e.subTypes[instrument];\n Object.keys(measurements).forEach((measurement) => {\n if (Object.prototype.hasOwnProperty.call(measurements, measurement)) {\n if (activeChannels.includes(measurement)) { // check wheather measurement is an active channel\n let label = `${instrument}_${measurement}_channel`;\n obj[label] = channelHash[`${instrument}_${measurement}`]; // channel\n\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n const data = measurements[measurement];\n\n label = `${instrument}_${measurement}_flag`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n obj[label] = flagsHash[_.last(data).val].label; // Flag\n label = `${instrument}_${measurement}_value`;\n if (dataObject.fields.indexOf(label) === -1) { // add to fields?\n dataObject.fields.push(label);\n }\n // taking care of flag Q (span)\n if (flagsHash[_.last(data).val].label === 'Q') {\n obj[label] = 0; // set value to 0\n } else {\n let outputValue = data[1].val; // avg\n // HNET Unit conversion for Temp from C to F\n if (measurement === 'Temp' || measurement === 'AmbTemp') {\n outputValue = (outputValue * 9 / 5) + 32;\n } else if (measurement === 'WS') {\n outputValue = Math.round(outputValue * 3600 / 1610.3 * 1000) / 1000;\n }\n obj[label] = outputValue.toFixed(3);\n }\n }\n }\n });\n }\n });\n\n obj.QCref_channel = 50;\n obj.QCref_flag = 'K';\n obj.QCref_value = 0;\n obj.QCstatus_channel = 51;\n obj.QCstatus_flag = 'K';\n obj.QCstatus_value = 99000;\n dataObject.data.push(obj);\n });\n if (dataObject.fields !== undefined) {\n dataObject.fields.push('QCref_channel', 'QCref_flag', 'QCref_value', 'QCstatus_channel', 'QCstatus_flag', 'QCstatus_value');\n }\n break;\n }\n default:\n throw new Meteor.Error('Unexpected switch clause', 'exception in switch statement for export file format');\n }\n return dataObject;\n}", "function getGoing(aggrType){\n\tconsole.log(aggrType);\n\tif(aggrType == null) attrType = 'count';\n\t//var plotType = $(\"input:radio[name=plotType]:checked\").val();\n\t//var aggregate = $(\"input:radio[name=aggregate_by]:checked\").val();\n\t//console.log (plotType + \", \" + aggregate);\n\n\t//if(plotType == \"full_year\"){\t//time and resource consuming animation. make animation smooth\n\t\tvar jsonpipe = [];\n\t\t\t//console.log(tick + \": Size of jsonpipe \" + jsonpipe.length);\n\t $.ajax({\n\t\t\t type: 'GET',\n\t\t\t url: '/koding/mapapp/index.php/sale/query',\t// following the pattern of (controller/action)\n\t\t\t data: {aggr: aggrType},\n\t\t\t dataType: 'json',\n\t\t\t success: function (result) {\n\t\t\t\t for(var i=0; i<result.length; i++){\n\t\t\t\t\t if(jsonpipe.length > 100) jsonpipe.shift();\n\t\t\t\t\t jsonpipe.push(result[i]);\n\t\t\t\t }\n\t\t\t console.log(JSON.stringify(jsonpipe));\n\t\t\t },\n\t\t\t complete: function (result) {\n\t\t\t\t overlayCountOfSale();\n\t\t\t }\n\t });\n//\t} else if(plotType == \"one_month\"){\n//\t\tjsonpipe = [];\n//\t\tvar temp = $(\"#pmonth\").val();\n////\t\tvar month = parseInt(temp.substring(5, 7));\n////\t\tvar year = parseInt(temp.substring(0, 4));\n//\t\t$.ajax({\n//\t\t\ttype: 'GET',\n//\t\t\turl: 'duration.php',\n//\t\t\tdata: {\"pmonth\": temp, \"aggregate\": aggregate},\t//temp format - YYYY-DD; the webservice will suffix 01 and 30/31\n//\t\t\tdataType: 'json',\n//\t\t\tsuccess: function (result) {\n//\t\t\t\tfor(var i=0; i<result.length; i++){\n//\t\t\t\t//if(jsonpipe.length > 100) jsonpipe.shift();\n//\t\t\t\t\tconsole.log(result[i]);\n//\t\t\t\t\tjsonpipe.push(result[i]);\n//\t\t\t\t}\n//\t\t\t\t//console.log(\"reading data \"+tick);\n//\t\t\t},\n//\t\t\tcomplete: function (result) {\n//\t\t\t\tshowPlots(jsonpipe);\n//\t\t\t}\n//\t\t});\t\t\t\n//\t} else if(plotType == \"month_range\") {\n//\t\tjsonpipe = [];\n//\t\tvar temp1 = $(\"#pmonth1\").val();\n//\t\tvar temp2 = $(\"#pmonth2\").val();\n//\t\t$.ajax({\n//\t\t\ttype: 'GET',\n//\t\t\turl: 'duration.php',\n//\t\t\tdata: {pmonth1: temp1, pmonth2: temp2, aggregate: aggregate},\t//temp format - YYYY-DD; the webservice will suffix 01 and 30/31\n//\t\t\tdataType: 'json',\n//\t\t\tsuccess: function (result) {\n//\t\t\t\tfor(var i=0; i<result.length; i++){\n//\t\t\t\t//if(jsonpipe.length > 100) jsonpipe.shift();\n//\t\t\t\t\tjsonpipe.push(result[i]);\n//\t\t\t\t}\n//\t\t\t\t//console.log(\"reading data \"+tick);\n//\t\t\t},\n//\t\t\tcomplete: function (result) {\n//\t\t\t\t// overlayPostcodes();\n//\t\t\t\tdocument.write(JSON.stringify(result));\n//\t\t\t}\n//\t\t});\n//\t} else if(plotType == \"price_range\") {\n//\t} else {\t//area_codes\n//\t}\n}", "function getData(err, user) {\n //logger.debug(user);\n\n //get individual br asset report\n\n var _sql = \"SELECT a.machine as Machine,\\\n a.tacho as Tacho,\\\n a.site as Site,\\\n a.description as Description,\\\n a.order_number as OrderNumber,\\\n a.id_number as ID_Number,\\\n a.jlg_jobnumber as Job_Number,\\\n a.creation_date as Creation_Date,\\\n a.`mileage_e/w` as Mileage,\\\n a.job_status_idjob_status as Status_id,\\\n st.description as Status, \\\n a.finished as Finished,\\\n a.invoiced as Invoiced,\\\n a.idjob as DB_ID, \\\n a.priority as Priority, \\\n b.name as Customer,\\\n IF(c.stoptime IS NULL, 'Not Started', c.stoptime) as Last_Worked\\\n FROM job a \\\n JOIN job_status st \\\n ON st.idjob_status = a.job_status_idjob_status \\\n JOIN customer b \\\n ON b.idcustomer = a.customer_idcustomer\\\n LEFT JOIN (SELECT * FROM (SELECT stoptime, job_idjob FROM work_instance ORDER BY stoptime DESC) as temp GROUP BY job_idjob) as c\\\n ON c.job_idjob = a.idjob\";\n //logger.info(_sql);\n mysql.query(_sql, function(err2, rows) {\n if (!err2) {\n for (var i = 0; i < rows.length; i++) {\n\n if (rows[i]['Last_Worked'] != \"Not Started\") {\n var tempTime = new Date(rows[i]['Last_Worked']);\n //logger.debug(tempTime);\n var tempTime2 = tempTime.toUTCString();\n // logger.debug(tempTime2);\n rows[i]['Last_Worked'] = tempTime2;\n }\n //logger.debug(rows[i]['Last_Worked']);\n }\n res.json(rows);\n\n } else {\n logger.debug('error:', err2);\n res.status(500).send(err);\n }\n })\n\n }", "function sumHourlyTotals(){\n for (var i = 0; i < storesHours.length; i++){\n var hourlySum = 0;\n for (var j = 0; j < allStores.length; j++){\n hourlySum += allStores[j].hourlySales[i];\n }\n hourlyTotals[i] = hourlySum;\n grandTotal += hourlySum;\n }\n}", "function dashboardApps(data) {\n return logCollection.find(dataField).sort({ \"_id\": -1 }).skip(toSkip).limit(countLimit).toArray()\n .then(logAppList => {\n return logCollection.find(dataField).count()\n .then(logListCount => {\n var result = []\n if (logListCount) {\n for (var i = 0; i < logListCount; i++) {\n var getResult = {\n \"_id\": logAppList[i]._id,\n \"app_id\": logAppList[i].app_id,\n \"comp_id\": logAppList[i].comp_id,\n \"issues\": logAppList[i].issues,\n \"type\": logAppList[i].type,\n \"platform\": logAppList[i].platform,\n \"device\": logAppList[i].device,\n \"version\": logAppList[i].version,\n \"created_dateTime\": logAppList[i].created_dateTime\n }\n result.push(getResult)\n }\n var finalRes = {\n \"logList\": result,\n \"count\": logListCount\n }\n return finalRes; // Final Result for Loglist for Particular App \n\n } else {\n var err = { \"error\": \"log List not found\" };\n return err;\n }\n });\n\n }).catch(err => {\n return err;\n });\n }", "get_aggregate_attribute() {\n const aggs = JSON.parse(this.getAttribute(\"aggregates\")) || {};\n return Object.keys(aggs).map(col => ({column: col, op: aggs[col]}));\n }", "function getMainDataMap() {\n return {\n bestAdsSales: {\n metric: 'bestAds',\n getter: function(metric) {\n return dataResolvers.getOrderedCollection(metric, 'ads', 'sales', 'sortByConversion');\n }\n },\n bestAdsRoi: {\n metric: 'bestAds',\n getter: function(metric) {\n return dataResolvers.getOrderedCollection(metric, 'ads', 'roi', 'sortByConversion');\n }\n },\n bestAdsConversions: {\n metric: 'bestAds',\n getter: function(metric) {\n return dataResolvers.getOrderedCollection(metric, 'ads', 'conversions', 'sortByConversion');\n }\n },\n bestAdsCpc: {\n metric: 'bestAds',\n getter: function(metric) {\n return dataResolvers.getOrderedCollection(metric, 'ads', 'cpc', 'sortByConversion');\n }\n },\n bestAdsCpm: {\n metric: 'bestAds',\n getter: function(metric) {\n return dataResolvers.getOrderedCollection(metric, 'ads', 'cpm', 'sortByConversion');\n }\n }\n };\n} // end getMainDataMap", "function displayUserReport(data) {\n $('body').append(\n \t'<p>' + 'Report: ' + data.report + '</p>');\n}", "getAll(query, isDenials = true, customer = null) {\n const dateRange = this.getDateParams();\n return Resource.get(this).resource(`SupplierCompany:getAllActivityRevised`, {\n dateRange,\n query,\n companyId: auth.get(this).user.company._id,\n isDenials,\n customer\n })\n .then(res => {\n let inventories = res.inventories;\n const payments = Array.isArray(res.payments) ? res.payments : null;\n // Combine payment and denials, include running total\n if (customer && isDenials) {\n inventories = this.handleDenialView(inventories, payments);\n }\n const meta = res.meta;\n this.activity = inventories;\n this.displayData.activity = inventories;\n this.displayData.totals.grandTotal = meta.totals;\n this.displayData.totals.pageTotal = meta.pageTotals;\n this.displayData.totalPages = meta.pages;\n this.displayData.totalItems = meta.total;\n })\n .then(() => {\n if (!this.safeData.retailers.length) {\n // Get list of retailers\n this.getRetailerList();\n }\n })\n .then(() => {\n if (this.displayData.activity.length) {\n this.getParamsInRange();\n } else {\n this.displayData.batches = [];\n }\n });\n }", "static getData() {\r\n return getWeatherReports({\r\n startDate: new Date(new Date().setDate(new Date().getDate() - 7)),\r\n endDate: new Date()\r\n });\r\n }" ]
[ "0.5974392", "0.594095", "0.5920378", "0.58689076", "0.57769215", "0.57223976", "0.57133436", "0.5699888", "0.5674575", "0.56137127", "0.5535037", "0.5526437", "0.55062884", "0.5472775", "0.5439763", "0.5424515", "0.5401869", "0.5391098", "0.53871936", "0.5373135", "0.53729796", "0.53719765", "0.5370745", "0.5344289", "0.5331019", "0.53233784", "0.5309647", "0.53075963", "0.53074265", "0.5280854", "0.5271687", "0.52642757", "0.5261382", "0.525934", "0.52388126", "0.5231397", "0.52284575", "0.5227342", "0.52217394", "0.5214944", "0.5214578", "0.51733744", "0.5171288", "0.51692396", "0.5165776", "0.5148645", "0.51482964", "0.51443684", "0.5142948", "0.5142122", "0.5141653", "0.51256764", "0.5124994", "0.5100938", "0.5085141", "0.5084599", "0.5076641", "0.5076211", "0.5073525", "0.5061643", "0.5057049", "0.5055657", "0.5053577", "0.50502086", "0.5042404", "0.50375634", "0.5037331", "0.5035393", "0.5034884", "0.50232816", "0.5013817", "0.50116724", "0.5008812", "0.5008812", "0.50061697", "0.5000788", "0.499814", "0.4997081", "0.4997018", "0.49931577", "0.4987737", "0.4981416", "0.49810645", "0.49790424", "0.49773943", "0.49767023", "0.49682882", "0.49681315", "0.4968126", "0.4967579", "0.4964059", "0.4959585", "0.49517658", "0.49510285", "0.49461278", "0.4945776", "0.4941159", "0.49378014", "0.49222624", "0.4918908" ]
0.7445762
0
current_report.input_fields = [ [1, new Date(1354966002000), ' 'test', 'button', 0],
function pii_log_user_input_type(message) { var total_entries = pii_vault.current_report.input_fields.length; var last_index = total_entries ? pii_vault.current_report.input_fields[total_entries - 1][0] : 0; var domain_input_elements = [ last_index + 1, new Date(), tld.getDomain(message.domain), message.attr_list.name, message.attr_list.type, message.attr_list.length, ]; my_log("APPU INFO: Appending to input_fields list: " + JSON.stringify(domain_input_elements), new Error); pii_vault.current_report.input_fields.push(domain_input_elements); flush_selective_entries("current_report", ["input_fields"]); send_messages_to_report_tabs("report-table-change-row", { type: "report-table-change-row", table_name: "input_fields", mod_type: "add", changed_row: domain_input_elements, }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function CreateDefaultDetailsArray()\r\n{\r\n var current_date = new Date() ;\r\n var current_time = current_date.getTime() ;\r\n\r\n var default_form_no = current_date.getFullYear().toFixed( 0 ) ;\r\n Alloy.Globals.ShedModeDetails =\r\n {\r\n \"FORM_NO\": default_form_no , // ToString of the current datetime\r\n \"DATE\": current_time.toString() // Now\r\n } ;\r\n}", "function restTransactionInputFields() {\r\n document.getElementById('budgetToolInput').reset();\r\n // Set the date input to today's date\r\n document.getElementById('date').valueAsDate = new Date();\r\n}", "function setPerfData(formName) {\r\n thisForm = eval(\"document.\" + formName);\r\n\r\n var newField = document.createElement(\"input\");\r\n newField.type = \"hidden\";\r\n newField.name = \"requestTotalTime\";\r\n newField.value = hiddenFieldStateForm.requestTotalTime.value;\r\n thisForm.appendChild(newField);\r\n //alert('requestTotalTime:' + hiddenFieldStateForm.requestTotalTime.value);\r\n var newField2 = document.createElement(\"input\");\r\n newField2.type = \"hidden\";\r\n newField2.name = \"requestStartTime\";\r\n newField2.value = (new Date()).getTime();\r\n thisForm.appendChild(newField2);\r\n // alert( \"requestTotalTime:\" + newField.value );\r\n // alert( \"requestStartTime:\" + newField2.value );\r\n}", "function setReportValue(value) {\n for (var i = 0; i < value.rowCount; i++) {\n report_data.r_id.push(value.rows[i]['id']);\n report_data.r_created_at.push(value.rows[i]['created_at']);\n }\n}", "function SetStartTime(custid) {\n\n\n //TimeStamp - Capture Start Time\n var currentTime = new Date();\n var month = currentTime.getMonth() + 1;\n var day = currentTime.getDate();\n var year = currentTime.getFullYear();\n\n var hours = currentTime.getHours();\n var minutes = currentTime.getMinutes();\n\n if (minutes < 10) {\n minutes = '0' + minutes\n }\n\n var seconds = currentTime.getSeconds();\n if (seconds < 10) {\n seconds = '0' + seconds\n }\n\n var daTime = (month + \"/\" + day + \"/\" + year + \" \" + hours + \":\" + minutes + \":\" + seconds);\n\n //alert(\"Start Time \"+ daTime);\n document.forms[0].timestamp.value = daTime;\n\n\n //saveReport (custid, \"timestamp\", document.forms[0].timestamp.value);\n saveReport(custid, \"StartTime\", daTime);\n\n //\n\n}", "function saveJfjlMeterId(meterId) {\n //initform(\"\",\"\");\n $(\"#starttime\").val(\"\");\n $(\"#endtime\").val(\"\");\n $(\"#meterId\").val(meterId);\n getHistoryJfjl();\n\n}", "inputChange(e) {\n this.props.dates([e.target.id], new Date(e.target.value).getTime());\n }", "function setValueInFields(data){\n if(data)\n {\n var parsedArray = JSON.parse(data);\n tenantID = parsedArray[0];\n tenantdataset = parsedArray;\n var i = 1;\n $.each(everyField, function(key, val){\n if(key == 'tenantStatus')\n {\n $('#'+key).prop('checked', parsedArray[i] == 1 ? true : false);\n }\n else if(key == 'boardingDate')\n {\n var convertedDate = intToDate(parsedArray[i]);\n $('#boardingDate').datepicker('setDate', convertedDate);\n }\n else if(key == 'graceperiod')\n {\n $('#graceperiod').val(parsedArray[parsedArray.length - 1]); \n }\n else\n {\n $('#'+key).val(parsedArray[i]);\n }\n i++; \n });\n setFieldStatus(everyField, true);\n loadButtonStatuses(false);\n }\n}", "function showNewRevenueInputFields(_line) {\n\n $('#revenueDetail-' + _line).append('<tr><td>New</td>'\n + '<td><input type=\"text\" class=\"form-control mr-sm-2\" data-provide=\"datepicker\" aria-label=\"operation date\" id=\"inputNewRevenueDate-' + _line + '\" /></td>'\n + '<td><input type=\"text\" class=\"form-control\" id=\"inputNewRevenueAmount-' + _line + '\" /></td></tr>');\n\n $('.datepicker').datepicker({ format: 'dd/mm/yyyy' });\n\n $('#revenueDetailButtons-' + _line).empty();\n $('#revenueDetailButtons-' + _line).append('<button type=\"submit\" class=\"btn btn-outline-primary\" onclick=\"confirmNewRevenue( ' + _line + ' );\">Confirm</button> &nbsp;');\n $('#revenueDetailButtons-' + _line).append('<button type=\"button\" class=\"btn btn-outline-secondary\" onclick=\"showRevenueTableDetails( ' + _line + ' );\">Cancel</button>');\n}", "function ReportDate(obj) {\n this.obj = obj;\n if ( 'datepicker' in this.obj )\n this.obj.datepicker({maxDate:new Date()}); // enable datepicker\n else\n console.log('failed to load datepicker()');\n}", "function test_service_dialog_date_datetime_picker_dynamic_dialog() {}", "function saveAdate(indexDoc) {\n let first_name = document.getElementById(\"first_name\").value;\n let last_name = document.getElementById(\"last_name\").value;\n let telefonr = document.getElementById(\"telefonnumber\".value);\n myObjectContactFormular = {\n 'first_name': first_name,\n 'last_name': last_name,\n 'telefon_number': telefonr,\n }\n docsListFormulars.push(myObjectContactFormular);\n showTheFixedAppointment(indexDoc);\n}", "function logArrayElements(element, index, array) {\n dateFromPython = new Date(element['Date'])\n data.push([dateFromPython.getTime(), parseFloat(element[fieldName])])\n }", "function fields() {\n var d = new Date;\n\n function days() {\n return 32 - new Date(d.getYear(), d.getMonth(), 32).getDate();\n }\n\n var second = (d.getSeconds() + d.getMilliseconds() / 1000) / 60,\n minute = (d.getMinutes() + second) / 60,\n hour = (d.getHours() + minute) / 24,\n weekday = (d.getDay() + hour) / 7,\n date = (d.getDate() - 1 + hour) / days(),\n month = (d.getMonth() + date) / 12;\n\n return [{\n value: second,\n index: .7,\n text: fsec(d)\n }, {\n value: minute,\n index: .6,\n text: fmin(d)\n }, {\n value: hour,\n index: .5,\n text: fhou(d)\n }, {\n value: weekday,\n index: .3,\n text: fwee(d)\n }, {\n value: date,\n index: .2,\n text: fdat(d)\n }, {\n value: month,\n index: .1,\n text: fmon(d)\n }, ];\n }", "function m_aux_Update(obj_stock, fechaInicio, fechaFin) {\n document.getElementById(\"inicio\").value = formatDate(fechaInicio);\n document.getElementById(\"fin\").value = formatDate(fechaFin);\n obj_stock.e_update_click();\n}", "static generateValue(field) {\n\n function withDate(fmt, i, currDate) {\n\n\n let d = currDate.getDate();\n let date = \"\";\n if (d < 10) {\n date = \"0\" + d;\n } else {\n date = \"\" + d;\n }\n return fmt.substr(0, i) + date + fmt.substr(i + 2);\n\n\n }\n\n function withMonth(fmt, i, currDate) {\n\n let m = currDate.getMonth() + 1;\n let month = \"\";\n if (m < 10) {\n month = \"0\" + m;\n } else {\n month = \"\" + m;\n }\n fmt = fmt.substr(0, i) + month + fmt.substr(i + 2);\n return fmt;\n\n }\n\n function withHour(fmt, i, currDate) {\n\n let m = currDate.getHours();\n let hr = \"\";\n if (m < 10) {\n hr = \"0\" + m;\n } else {\n hr = \"\" + m;\n }\n fmt = fmt.substr(0, i) + hr + fmt.substr(i + 2);\n return fmt;\n\n }\n\n function withMins(fmt, i, currDate) {\n let m = currDate.getMinutes();\n let mins = \"\";\n if (m < 10) {\n mins = \"0\" + m;\n } else {\n mins = \"\" + m;\n }\n fmt = fmt.substr(0, i) + mins + fmt.substr(i + 2);\n return fmt;\n }\n\n function withSecs(fmt, i, currDate) {\n let m = currDate.getSeconds();\n let secs = \"\";\n if (m < 10) {\n secs = \"0\" + m;\n } else {\n secs = \"\" + m;\n }\n fmt = fmt.substr(0, i) + secs + fmt.substr(i + 2);\n return fmt;\n }\n\n if (field.Hint.Type == \"date_time\") {\n if (field.Hint.Format) {\n //we only support\n //MMdd HHmmss\n let currDate = new Date();\n let fmt = field.Hint.Format;\n let i = fmt.indexOf(\"MM\");\n if (i != -1) {\n fmt = withMonth(fmt, i, currDate)\n }\n\n i = fmt.indexOf(\"dd\");\n if (i != -1) {\n fmt = withDate(fmt, i, currDate)\n }\n\n i = fmt.indexOf(\"HH\");\n if (i != -1) {\n fmt = withHour(fmt, i, currDate)\n }\n\n i = fmt.indexOf(\"mm\");\n if (i != -1) {\n fmt = withMins(fmt, i, currDate)\n }\n\n i = fmt.indexOf(\"ss\");\n if (i != -1) {\n fmt = withSecs(fmt, i, currDate)\n }\n\n return fmt;\n\n }\n\n return \"\"\n }\n\n return \"\"\n }", "addNewReport() {\n \n }", "function updateCalendarFromField(date_field) {\n var dateRe = /(\\d\\d\\d\\d)-(\\d\\d?)-(\\d\\d?)/;\n var pieces = dateRe.exec(date_field.value);\n if (pieces) {\n var cal = YAHOO.bugzilla[\"calendar_\" + date_field.id];\n cal.select(new Date(pieces[1], pieces[2] - 1, pieces[3]));\n var selectedArray = cal.getSelectedDates();\n var selected = selectedArray[0];\n cal.cfg.setProperty(\"pagedate\", (selected.getMonth() + 1) + '/' \n + selected.getFullYear());\n cal.render();\n }\n}", "function updateDOM_inputDate() {\n\n const a = new Date();\n $('#date-leave').val(DateUtilities.toApiDateString(a));\n $('#date-return').val(DateUtilities.toApiDateString(a));\n\n}", "function attachDateValues(dates) {\n document.getElementById(\"time_off_start_date\").value = dates[0];\n document.getElementById(\"time_off_end_date\").value = dates[1];\n}", "function _dat_dateInitialize()\n{\n\tvar list=new Array;\n\tvar type,field,i;\n\n\tlist=mjs_formElementList();\n\tfor(i=list.length-1;i>=0;i--)\n\t{\n\t\tfield=list[i];\n\n\t\tif(!mjs_valued(type=mjs_attr(field,gMJS_typeAttrName)))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif(strcasecmp(type,\"date\"))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t_dat_expandDateField(field);\n\t}\n}", "function updateInputValue() {\n inputField.value = formatDate(currentDateTime, 'full');\n }", "function lpSetDateInput(sectionId) {\n // $(\":date\").dateinput({\n $(\"#section_due_date_\"+sectionId).dateinput({\n format: 'mmmm dd, yyyy', // the format displayed for the user\n selectors: true, // whether month/year dropdowns are shown\n offset: [10, 20], // tweak the position of the calendar\n speed: 'fast', // calendar reveal speed\n firstDay: 1 // which day starts a week. 0 = sunday, 1 = monday etc..\n });\n// $(\":date\").dateinput({format: 'mmmm dd, yyyy', selectors: true, offset: [10, 20], speed: 'fast', firstDay: 1});\n}", "backlogRecords(date){\n \n }", "function getDateAndTimeStarted(){\n var panel = View.panels.get('tool_form');\n var wrId = panel.getFieldValue(\"wrtl.wr_id\");\n\tvar result = {};\n\ttry {\n\t\t result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n\tcatch (e) {\n\t\tWorkflow.handleError(e);\n \t\t}\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"tool_form_wrtl.date_start\").value = date;\n $(\"tool_form_wrtl.time_start\").value = time;\n $(\"Storedtool_form_wrtl.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}", "function setCurrentDate () {\n\tvar console = View.panels.get('allocGroupConsole');\n\tvar record = console.getRecord();\n\n\tif (console.getFieldValue('gp.date_start') == '') {\n\t\trecord.setValue('gp.date_start', new Date());\n\t\tconsole.onModelUpdate();\n\t}\n}", "function addReportedFieldForReadReport(data) {\n\t\t//Create the new elements to attach\n\t\tfor (var i = 0; i < currentNbrOfReports; i++) {\n\t\t\tvar newTableRow = $(document.createElement('tr'));\n\t\t\tnewTableRow.attr('id', 'survey_list_reports');\n\n\t\t\tvar newTdSurveyName = $(document.createElement('td'));\n\t\t\tnewTdSurveyName = $(newTdSurveyName);\n\t\t\tnewTdSurveyName.text(data[i]);\n\t\t\tnewTdSurveyName.appendTo(newTableRow);\n\t\t\tnewTableRow.appendTo(fillableReportList);\n\t\t}\n\t}", "function setUpFields(fields){\n\n\t_.forEach(fields, function(value, key){\n\t\tif(value.type == 'date'){\n\t\t\t$scope.data.thisContent[value.field || value.key] = {\n\t\t\t\tstartDate: $scope.data.thisContent[value.field || value.key] || null,\n\t\t\t\tendDate: null //have to stub but don't use all the time\n\t\t\t}\n\t\t}\n\t})\n\n\treturn fields;\n\n}", "static setDate() {\n let dayFieldsArray = Array.from(dayFields);\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"];\n dayFieldsArray.forEach(item => item.innerText = days[(currentDate.getDay()+dayFieldsArray.indexOf(item))%7]);\n document.querySelector(\".date-0\").innerText = `${currentDate.getDate()} ${months[currentDate.getMonth()]}`;\t\n }", "function getFormDate() {\n var d = new Date();\n if (app.SHRFlag == 2) {\n app.esSHRData.date = d.getFullYear() + \"-\" + (d.getMonth() + 1) + \"-\" + d.getDate();\n } else if (app.SHRFlag == 1) {\n app.prevalingSHRData.date = d.getFullYear() + \"-\" + (d.getMonth() + 1) + \"-\" + d.getDate();\n } else {\n\n app.esIRData.date = d.getFullYear() + \"-\" + (d.getMonth() + 1) + \"-\" + d.getDate();\n console.log(\"setting date = \" + app.esIRData.date);\n }\n\n}", "static get fieldType() {\n return 'date';\n }", "static get fieldType() {\n return 'date';\n }", "function setFieldFromCalendar(type, args, date_field) {\n var dates = args[0];\n var setDate = dates[0];\n\n // We can't just write the date straight into the field, because there \n // might already be a time there.\n var timeRe = /\\b(\\d{1,2}):(\\d\\d)(?::(\\d\\d))?/;\n var currentTime = timeRe.exec(date_field.value);\n var d = new Date(setDate[0], setDate[1] - 1, setDate[2]);\n if (currentTime) {\n d.setHours(currentTime[1], currentTime[2]);\n if (currentTime[3]) {\n d.setSeconds(currentTime[3]);\n }\n }\n\n var year = d.getFullYear();\n // JavaScript's \"Date\" represents January as 0 and December as 11.\n var month = d.getMonth() + 1;\n if (month < 10) month = '0' + String(month);\n var day = d.getDate();\n if (day < 10) day = '0' + String(day);\n var dateStr = year + '-' + month + '-' + day;\n\n if (currentTime) {\n var minutes = d.getMinutes();\n if (minutes < 10) minutes = '0' + String(minutes);\n var seconds = d.getSeconds();\n if (seconds > 0 && seconds < 10) {\n seconds = '0' + String(seconds);\n }\n\n dateStr = dateStr + ' ' + d.getHours() + ':' + minutes;\n if (seconds) dateStr = dateStr + ':' + seconds;\n }\n\n date_field.value = dateStr;\n hideCalendar(date_field.id);\n}", "function frmt_date(a,field) {\n for(var i=0; i < a.length; i++){\n if( ! a[i][field] ) { continue }\n var d = new Date(a[i][field] * 1000)\n a[i][field] = d.toISOString().substr(0,16).replace('T',' ')\n }\n return(a)\n}", "function enterCurrentDateToHTML() {\n currentDate = Date.now();\n dateIn.value = date;\n}", "function myDatePicker_dateSelected(page){\n page.children.flexLayout1.children.textFlex.children.dateLabel.text = definedDate;\n}", "function addReportedField(data) {\n\t\t//Create the new elements to attach\n\t\tfor (var i = 0; i < nbrReportedSurveyInTotal; i++) {\n\t\t\tvar newTableRow = $(document.createElement('tr'));\n\t\t\tnewTableRow.attr('id', 'survey_reported_' + data[i].pk);\n\n\t\t\tvar newTdSurveyName = $(document.createElement('td'));\n\t\t\tnewTdSurveyName = $(newTdSurveyName);\n\t\t\tnewTdSurveyName.text(data[i].name);\n\t\t\tnewTdSurveyName.appendTo(newTableRow);\n\n\t\t\tvar newTdSurveyOwner = $(document.createElement('td'));\n\t\t\tnewTdSurveyOwner = $(newTdSurveyOwner);\n\t\t\tnewTdSurveyOwner.text(data[i].username.split('T')[0]);\n\t\t\tnewTdSurveyOwner.appendTo(newTableRow);\n\t\t\t\n\t\t\tvar newTdCreationDate = $(document.createElement('td'));\n\t\t\tnewTdCreationDate = $(newTdCreationDate);\n\t\t\tnewTdCreationDate.text(data[i].fields.creationDate.split('T')[0]);\n\t\t\tnewTdCreationDate.appendTo(newTableRow);\n\n\t\t\tvar newTdLastEditdate = $(document.createElement('td'));\n\t\t\tnewTdLastEditdate = $(newTdLastEditdate);\n\t\t\tnewTdLastEditdate.text(data[i].fields.last_editDate.split('T')[0]);\n\t\t\tnewTdLastEditdate.appendTo(newTableRow);\n\n\t\t\tvar newTdQuiz = $(document.createElement('td'));\n\t\t\tnewTdQuiz = $(newTdQuiz);\n\t\t\tif (data[i].fields.isQuizz == false) {\n\t\t\t\tnewTdQuiz.text('No');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnewTdQuiz.text('Yes');\n\t\t\t}\n\t\t\tnewTdQuiz.appendTo(newTableRow);\n\n\t\t\tvar newTdActions = $(document.createElement('td'));\n\t\t\tnewTdActions.addClass('center');\n\t\t\tnewTdActions = $(newTdActions);\n\t\t\tvar newReadReportButton = $(document.createElement('i'));\n\t\t\tvar newReadReportButtonHref = $(document.createElement('a'));\n\t\t\tnewReadReportButton.appendTo(newReadReportButtonHref).attr({\n\t\t\t\tid: 'readReportButton_reported_' + data[i].pk,\n\t\t\t\ttitle: 'Read Reports',\n\t\t\t\t'class': 'icon-file filledReadReportButton hasPointer'\n\t\t\t});\n\t\t\tnewReadReportButtonHref.appendTo(newTdActions).attr({\n\t\t\t\thref: '#readReportModal',\n\t\t\t\trole: 'button',\n\t\t\t\t'data-toggle': 'modal'\n\t\t\t});\n\t\t\tnewReadReportButton.tooltip();\n\n\t\t\t\n\t\t\tvar newPreviewButton = $(document.createElement('i'));\n\t\t\tvar newPreviewButtonHref = $(document.createElement('a'));\n\t\t\tnewPreviewButton.appendTo(newPreviewButtonHref).attr({\n\t\t\t\tid: 'previewButton_reported_' + data[i].pk,\n\t\t\t\ttitle: 'Preview Survey',\n\t\t\t\t'class': 'icon-info-sign filledPreviewButton'\n\t\t\t});\n\t\t\tnewPreviewButtonHref.appendTo(newTdActions).attr({\n\t\t\t\thref: '#previewSurveyModal',\n\t\t\t\trole: 'button',\n\t\t\t\t'data-toggle': 'modal'\n\t\t\t});\n\t\t\tnewPreviewButton.tooltip();\n\t\t\t\n\t\t\t\n\t\t\tvar newBlockButton = $(document.createElement('i'));\n\t\t\tvar newBlockButtonHref = $(document.createElement('a'));\n\t\t\tnewBlockButton.appendTo(newBlockButtonHref).attr({\n\t\t\t\tid: 'blockButton_published_' + data[i].pk,\n\t\t\t\ttitle: 'Block Survey',\n\t\t\t\t'class': 'icon-ban-circle filledBlockButton hasPointer'\n\t\t\t});\n\t\t\tnewBlockButtonHref.appendTo(newTdActions).attr({\n\t\t\t\thref: '#blockModal',\n\t\t\t\trole: 'button',\n\t\t\t\t'data-toggle': 'modal'\n\t\t\t});\n\t\t\tnewBlockButton.tooltip();\n\t\t\t\n\t\t\tvar newWarnButton = $(document.createElement('i'));\n\t\t\tvar newWarnButtonHref = $(document.createElement('a'));\n\t\t\tnewWarnButton.appendTo(newWarnButtonHref).attr({\n\t\t\t\t\tid: 'warnButton_' + data[i].pk,\n\t\t\t\t\ttitle: 'Warn Survey',\n\t\t\t\t\t'class': 'icon-warning-sign filledWarnButton hasPointer',\n\t\t\t});\n\t\t\tnewWarnButtonHref.appendTo(newTdActions).attr({\n\t\t\t\thref: '#warningModal',\n\t\t\t\trole: 'button',\n\t\t\t\t'data-toggle': 'modal'\n\t\t\t});\n\t\t\tnewWarnButton.tooltip();\n\n\t\t\tvar newIgnoreButton = $(document.createElement('i'));\n\t\t\tvar newIgnoreButtonHref = $(document.createElement('a'));\n\t\t\tnewIgnoreButton.appendTo(newIgnoreButtonHref).attr({\n\t\t\t\tid: 'ignoreButton_published_' + data[i].pk,\n\t\t\t\ttitle: 'Ignore Survey',\n\t\t\t\t'class': 'icon-trash filledIgnoreButton hasPointer'\n\t\t\t});\n\t\t\tnewIgnoreButtonHref.appendTo(newTdActions).attr({\n\t\t\t\thref: '#ignoreModal',\n\t\t\t\trole: 'button',\n\t\t\t\t'data-toggle': 'modal'\n\t\t\t});\n\t\t\tnewIgnoreButton.tooltip();\n\n\t\t\tnewTdActions.appendTo(newTableRow);\n\n\t\t\tnewTableRow.appendTo(fillableReportedTableAdmin);\n\t\t}\n\t}", "function initInputs() {\n setDateInput(\"startDate\", { dateFormat: \"yy-mm-dd\" });\n setDateInput(\"endDate\", { dateFormat: \"yy-mm-dd\" });\n}", "function showDate(input){\n document.getElementById(\"questiondate\").innerHTML = `This question aired on: ${formatDate(input[0].airdate)}`\n\n}", "function updatePostDate(type,args,obj)\n{\n var month = (args[0][0][1] < 10) ? '0' + args[0][0][1] : args[0][0][1];\n var day = (args[0][0][2] < 10) ? '0' + args[0][0][2] : args[0][0][2];\n var year = args[0][0][0];\n\n document.getElementById('post_date').value = month + '/' + day + '/' + year;\n window.cal1.hide();\n}", "setFields(event, exclude) {\n this.mode.current = this.$location.search().mode || 'latest';\n this.mode[this.mode.current] = true;\n this.$scope.reportHash = this.$location.search().report;\n this.$scope.dateFrom = this.$location.search().date_from || moment.utc().format('YYYY-MM-DD');\n this.$scope.dateTo = this.$location.search().date_to || moment.utc().format('YYYY-MM-DD');\n return this.reset(event, exclude);\n }", "function showDateInput(input)\r\n{\r\n\tshowDateInput(input,false);\r\n}", "function setDate() {\n // It will set the departure date to current date\n const departureDate = customDateFormat();\n document.getElementById('departure-date').value = departureDate;\n\n // It will set the return date to 7 days fast from current date\n const returnDate = customDateFormat(7);\n document.getElementById('return-date').value = returnDate;\n}", "function syncDisplayableDateToGrid() {\r\n\r\n try {\r\n var parentTrRow = findParentTrRow(window.event.srcElement);\r\n var myrow = parentTrRow.rowIndex - 1;\r\n var myname = window.event.srcElement.name;\r\n var displayedDate = document.all(myname)[myrow];\r\n\r\n var hiddenDate = document.all(normalizeFieldName(displayedDate))[myrow];\r\n updateHiddenFieldForDateField(displayedDate, hiddenDate);\r\n\r\n var dataSrc = hiddenDate.dataSrc.substring(1);\r\n var dataFld = hiddenDate.dataFld;\r\n var dataGrid = eval(dataSrc);\r\n dataGrid.recordset(dataFld).value = hiddenDate.value;\r\n\r\n }\r\n catch(ex) {\r\n logDebug(\"Exception: \" + ex.name + \" : \" + ex.message);\r\n }\r\n\r\n}", "function SP_GetnSetDateFields()\n{\n\ttry\n\t{\t\n\t\tif(arguments.length > 0)\n\t\t{\n\t\t\tfor (var n=0; n < arguments.length; n++ )\n\t\t\t{\n\t\t\t\tvar oDate = document.getElementById(arguments[n]);\n\t\t\t\tSP_SetDateFormat(oDate);\n\t\t\t}\n\t\t}\n\t}\n\tcatch (ex)\n\t{\n\t\t//alert(ex);\n\t}\n\t\n\ttry\n\t{\n\t\tvar FormDate = document.getElementById(\"mastercontrol.form.created\");\n\t\tif(SP_Trim(FormDate.value) != \"\")\n\t\t{\n\t\t\tSP_SetDateFormat(FormDate);\n\t\t\tvar inputFields = document.getElementsByTagName(\"input\");\n\t\t\tvar isDateField = false;\n\t\t\n\t\t\tfor (var x = 0; x < inputFields.length; x++)\n\t\t\t{\n\t\t\t\tisDateField = false;\n\t\t\t\tif(inputFields[x].type == \"text\")\n\t\t\t\t{\n\t\t\t\t\tif(inputFields[x].name.indexOf('_date') != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(SP_Trim(inputFields[x].value) != \"\")\t\n\t\t\t\t\t\t\tSP_SetDateFormat(inputFields[x]);\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcatch(excp)\n\t{\n\t\t//alert(excp);\t\n\t}\n}", "function test_datepicker_in_service_request() {}", "beforeInit() {\n const { ele } = this.props;\n this._value = [];\n if (!ele.fieldClass) {\n FieldUtiles.prepareFieldsRec(ele);\n }\n this.ele = ele.fieldClass\n ? ele\n : FieldUtiles.getFieldData({ ele }, ObjectField);\n }", "function register_actual_date()\n{\n RMPApplication.debug (\"begin register_actual_date\");\n var my_date = new Date(); \n var currentTime = Math.round(my_date.getTime()/1000); \n c_debug(debug.prepare_data, \"=> register_actual_date: currentTime = \", currentTime);\n RMPApplication.setVariable(\"date_intervention\", currentTime);\n // other_var.date_intervention = RMPApplication.get(\"date_intervention\");\n RMPApplication.debug (\"end register_actual_date\");\n}", "function init() {\n $(\"#startDate\").jqxDateTimeInput({ width: '270px', height: '25px' });\n $(\"#endDate\").jqxDateTimeInput({ width: '270px', height: '25px' });\n isInitialized=true\n \n}", "function dateForInputs(date){\r\n return date.getFullYear() + \"-\" + twoNum(date.getMonth()+1) + \"-\" + twoNum(date.getDate())\r\n }", "function continueButtonClicked() {\n console.log(\"woot got a click\");\n //eyr = {};\n //eyr[\"FLD\"] = \"DC\";\n //eyr[\"VAL\"] = 60;\n //DefaultInputs.push(eyr);\n // inputData[\"Inputs\"] = DefaultInputs;\n}", "function currentInput(id=\"\", date=\"\") {\r\n this.id = id; \r\n this.date = date; \r\n this.pulseEntries = [];\r\n}", "function _0001485874497586_117_DateTime_settlementScreen()\n{\n\nLog.AppendFolder(\"_0001485874497586_117_DateTime_settlementScreen\");\ntry\n{ InitializationEnviornment.initiliaze();\n AppLoginLogout.login();\n WrapperFunction.selectKeyword(\"Daily Admission\");\n selectPackage(\"3 site Combi\",\"Children (Ages 3-12)\");\n \n selectQuantityFromSubWindow(1);\n selectSubPackageFromSubWindow(\"Children (Ages 3-12)\");\n selectQuantityFromSubWindow(1);\n selectSubPackageFromSubWindow(\"Adult\");\n \n selectDateFromSubWindow(CommonCalender.getTodaysDate()); //mm-dd-yyyy\n selectAvailableTimeFromSubWindow(\"12:30 AM\");\n selectNextButtonFromSubWindow();\n selectFinalizeOrderbutton();\n \n var orderDateTimeValue=WrapperFunction.getTextValue(OrderDetailDateTime_Row1);\n Log.Message(\"orderDateTimeValue\"+orderDateTimeValue);\n\n AppLoginLogout.logout();\n}\n\ncatch(e)\n{\n merlinLogError(\"Exception in Test script\");\n //Runner.Stop();\n}\n}", "function setCurrentTime() {\n var creationDate = document.getElementById(\"entity_creationDate\");\n var dateStatusChange = document.getElementById(\"entity_dateStatusChange\");\n if (creationDate) {\n creationDate.value = new Date().toISOString();\n }\n if (dateStatusChange) {\n dateStatusChange.value = new Date().toISOString();\n }\n}", "static setEmbedField() {\n const rows = document.querySelector('#fields-table tbody').querySelectorAll('tr');\n let fields = [], name = \"\", value = \"\", i = 0;\n rows.forEach((row) => {\n name = row.querySelector('.field-names').textContent;\n value = row.querySelector('.field-values').textContent;\n if (name && value) {\n fields[i++] = {\n name: name,\n value: value,\n inline: row.querySelector('.field-inline input').checked,\n };\n }\n });\n document.querySelector('#embed-fields').value = JSON.stringify(fields);\n }", "function updateData(info) {\r\n try {\r\n nlapiSubmitField('workorder', info.id, info.field, info.value);\r\n } catch (e) {\r\n nlapiLogExecution('ERROR', 'Error during main updateDate', e.toString());\r\n }\r\n}", "static initialize(obj, report, _date, growthRate, growthRateType) { \n obj['report'] = report;\n obj['date'] = _date;\n obj['growth_rate'] = growthRate;\n obj['growth_rate_type'] = growthRateType;\n }", "function loadDataToForm(obj, _selectorForm) {\n var dataInput = $(_selectorForm).find(\"input\");\n $.each(dataInput, function(index, input) {\n var fieldName = $(input).attr('fieldName');\n if (fieldName.toLowerCase().includes(\"date\")) {\n console.log(fieldName);\n let d = new Date(obj[fieldName] + '');\n let month = '' + (d.getMonth() + 1);\n let day = '' + d.getDate();\n let year = d.getFullYear();\n\n if (month.length < 2)\n month = '0' + month;\n if (day.length < 2)\n day = '0' + day;\n // var local = obj[fieldName].toLocaleDateString() + \"\";\n // local.setMinutes(this.getMinutes() - this.getTimezoneOffset());\n let date = [year, month, day].join('-');\n $(input).val(date);\n } else if (fieldName.toLowerCase().includes(\"salary\")) {\n let salary = obj[fieldName].split(\".\");\n let s = \"\";\n for (let i = 0; i < salary.length; i++) {\n s += salary[i];\n }\n s = parseInt(s);\n $(input).val(s);\n } else {\n $(input).val(obj[fieldName]);\n }\n });\n}", "function addToFormDateValues(node, slangVariable, additionalSlangIndicator) {\n\t//console.log(\"addToFormDateValues .......................................\");\n\tvar formJsonData = null;\n\tif (dojo.byId(\"historyWritersJsonFormData\")) {\n\t\tformJsonData = dojo.byId(\"historyWritersJsonFormData\");\n\t} else if (dojo.byId(\"historyWritersJsonFormData\")) {\n\t\tformJsonData = dojo.byId(\"historyWritersJsonFormData\");\n\t}\n\tif (formJsonData != null) {\n\t\tJsonData = dojo.fromJson(formJsonData.value);\n\t}\n\tif (!node.value.length) {\n\t\tif (additionalSlangIndicator in JsonData) {\n\t\t\tdelete JsonData[additionalSlangIndicator];\n\t\t} \n\t} else {\n\t\tJsonData[additionalSlangIndicator] = \"1\"; \n\t}\n\taddToFormValues(node, slangVariable);\n\t\n\tvar revisedJson = dojo.toJson(JsonData);\n\tdojo.attr(formJsonData, \"value\", revisedJson);\n}", "function setDate(id, date) {\n $(\"#\" + id + \"_Year\").val(date.getFullYear());\n $(\"#\" + id + \"_Month\").val(date.getMonth() + 1);\n $(\"#\" + id + \"_Day\").val(date.getDate());\n $(\"#\" + id + \"_Hour\").val(date.getHours());\n $(\"#\" + id + \"_Minute\").val(date.getMinutes());\n\n var date_hidden = $(\"#\" + id);\n date_hidden.val(pad(date.getDate()) + \"-\" + pad(date.getMonth()) + \"-\" + date.getFullYear() + \" \"\n + pad(date.getHours()) + \":\" + pad(date.getMinutes()) + \":00\");\n}", "date(e){\n this.appDate = e.detail.value; \n \n }", "function fillReport(field, value, report) {\n\n //adds 1 to the step\n report[0].step += 1;\n\n switch (field) {\n case \"cause\":\n report[0].cause = value;\n break;\n case \"homeDamages\":\n report[0].homeDamages = value;\n break;\n case \"humansHarmed\":\n //parses the number in the string to int type\n report[0].humansHarmed = parseInt(value);\n break;\n case \"humansDeath\":\n //parses the number in the string to int type\n report[0].humansDeath = parseInt(value);\n break;\n case \"noHumansHarmed\":\n //fills with 0 and adds another step\n report[0].humansHarmed = 0;\n report[0].humansDeath = 0;\n report[0].step += 1;\n break;\n case \"img\":\n //saves the img url and the img buffer\n report[0].img.data = value[0];\n report[0].img.contentType = 'image/png';\n report[0].imgUrl = value[1];\n break;\n case \"video\":\n report[0].imgUrl = value;\n case \"location\":\n report[0].X = value[0];\n report[0].Y = value[1];\n break;\n case \"address\":\n report[0].address = value[2];\n report[0].X = value[0];\n report[0].Y = value[1];\n break;\n case \"observation\":\n //adds the recived observation value\n report[0].observation += value + \"--\";\n\n //if the control is not taken send the report to arcgis\n if (!report[0].tomarControl) {\n sendReportToArcGis(report[0]);\n } else {\n report[0].response = {};\n }\n break;\n case \"tomarControl\":\n report[0].tomarControl = value;\n break;\n case \"step\":\n report[0].step = value;\n break;\n case \"closeAsistance\":\n report[0].step = value[0];\n report[0].tomarControl = value[1];\n report[0].observation += value[2];\n //sends thereport toarcgis\n sendReportToArcGis(report[0]);\n break;\n case \"fromApp\":\n report[0].fromApp = value;\n //set step to 13, step where the aux conversation starts\n report[0].step = 13;\n break;\n case \"homeOrComunitty\":\n report[0].homeOrComunitty = value;\n break;\n default:\n //In case it where wrongsomehow the step would just remain\n report[0].step = report[0].step - 1;\n return;\n }\n //Updates the date\n var date = new Date();\n report[0].date = date.getTime();\n\n //updates the object with the same object_id in the mongo database\n Report.findByIdAndUpdate(report[0]._id, report[0], function (err, upt) {\n console.log(\"field : \" + field + \"-------saved\")\n Report.find(function (err, doc) {\n if (err) {\n console.log(err);\n } else {\n console.log(\"guardadoooooooooooooooo\")\n }\n });\n })\n return report;\n}", "addReport(value, num) {\n //this._directReports.push(value);\n console.log(String(num));\n return \"Hello\";\n }", "function recordchange(type, name){\n\n\tif(name == 'datefield' && nlapiGetFieldValue('datefield') != \"\"){\n\t\t\n\t\t// replace URL with custom report URL\n\t\tvar reporturl = 'https://system.na1.netsuite.com/app/reporting/reportrunner.nl?cr=522&customized=T&whence='\n\t\t\n\t\tvar win = window.open(reporturl,\"_blank\",\"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=10, height=10, visible=none\");\n\t \twindow.focus(); // focuses the main window.\n\n\t\t// Change 'crit_1_from' to your custom field, and change 'datefield' to the report's field that needs to be modified\n\t\twin.onload = function(){\n\t\t\twin.document.getElementById('crit_1_from').value=nlapiGetFieldValue('datefield');\n\t\t\twin.document.getElementById(\"refresh\").click();\n\t\t\t\n\t\t\t//alert(\"Start Date critera modified.\");\n\t\t\tsetTimeout(function(){ \n\n\t\t\t\twin.close();\n\t\t\t}, 1000);\n\t\t}\n\t}\n\t\n\tif(name == 'datefield2' && nlapiGetFieldValue('datefield2') != \"\"){\n\t\n\t\t// replace URL with custom report URL\n\t\tvar reporturl = 'https://system.na1.netsuite.com/app/reporting/reportrunner.nl?cr=522&customized=T&whence='\n\t\t\n\t\tvar win = window.open(reporturl,\"_blank\",\"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=10, height=10, visible=none\");\n\t\twindow.focus(); // focuses the main window.\n\n\t\t// Change 'crit_1_to' to your custom field, and change 'datefield2' to the report's field that needs to be modified\n\t\twin.onload = function(){\n\t\t\twin.document.getElementById('crit_1_to').value=nlapiGetFieldValue('datefield2');\n\t\t\twin.document.getElementById(\"refresh\").click();\n\t\t\t\n\t\t\t//alert(\"End Date critera modified.\");\n\t\t\tsetTimeout(function(){ \n\n\t\t\t\twin.close();\n\t\t\t}, 1000);\n\t\t}\n\t}\n}", "writeValue(value) {\n this.date = new Date(value).toISOString();\n this.show_tooltip = false;\n }", "function CHMnetscapeDate(value)\r\n{\r\n dateObj.value=value;\r\n return;\r\n}", "function add_entry(action, item_value, date_value){\n //resets the input field\n document.getElementById('item').value=\"\";\n //transforms the html datetime format (yyyy-mm-ddThh:mm) type into SQL datetime format (yyyy-mm-dd hh:mm:ss)\n date_value=date_value.replace(\"T\", \" \")+\":00\";\n //resets the default value of the date and time\n var default_date=document.getElementById('date').defaultValue;\n document.getElementById('date').value=default_date;\n //submits the form with the entered input\n submitForm(action, ucfirst(item_value), date_value);\n }", "function $Date() {\n\t\treturn Field.apply(this, arguments);\n\t}", "function createReports() {\r\n var RawDataReport = AdWordsApp.report(\"SELECT Domain, Clicks \" + \"FROM AUTOMATIC_PLACEMENTS_PERFORMANCE_REPORT \" + \"WHERE Clicks > 0 \" + \"AND Conversions < 1 \" + \"DURING LAST_7_DAYS\");\r\n RawDataReport.exportToSheet(RawDataReportSheet);\r\n}", "function set_status_date(dateid) {\n $(dateid).clear();\n var date = new Date();\n var text = formatDate(date);\n $(dateid).value = text;\n}", "function getSelectedDate()\n{\nreturn curr_date;\n}", "function setUpSheet(sheet, fieldKeys) {\n sheet.getRange(1, fieldKeys.indexOf('starttime') + 1, 999).setNumberFormat(dateFormat);\n sheet.getRange(1, fieldKeys.indexOf('endtime') + 1, 999).setNumberFormat(dateFormat);\n sheet.getRange(1, fieldKeys.indexOf('duration') + 1, 999).setNumberFormat('0.0');\n sheet.hideColumns(fieldKeys.indexOf('id') + 1);\n sheet.hideColumns(fieldKeys.indexOf('description') + 1);\n}", "function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_cf_cf_form');\n var wrId = panel.getFieldValue(\"wrcf.wr_id\");\n\n //kb:3024805\n\tvar result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n try {\n result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n catch (e) {\n Workflow.handleError(e);\n }\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"sched_wr_cf_cf_form_wrcf.date_start\").value = date;\n $(\"sched_wr_cf_cf_form_wrcf.time_start\").value = time;\n \n $(\"Storedsched_wr_cf_cf_form_wrcf.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}", "function fnFormatDetails(nTr) {\n var aData = uoTable.fnGetData(nTr);\n\n var oFormObject = document.forms['drugregimenname'];\n\n oFormObject.elements[\"regimennamename\"].value = aData[3];\n oFormObject.elements[\"regimennameedit\"].value = 'true';\n oFormObject.elements[\"regimennameuuid\"].value = aData[2];\n\n\n}", "function onResponse_addFixum(fixumJSON){\n\n var fixum = $.parseJSON(fixumJSON);\n insertfixumAsTableRow(fixum.fixumID, fixum.startDate, fixum.lastUsedDate, fixum.name, fixum.frequency, fixum.categoryName, fixum.isPositive, fixum.value);\n}", "'click #due_date'(){\n var due_date_id = this._id;\n console.log();\n\n $(\"#due_date\").datepicker({dateFormat : \"mm/dd/yy\"});\n // showOn: \"button\",\n \n // buttonImageOnly: true,\n // buttonText: \"Select date\",\n // onSelect: function(){\n // var due_date = $(this).val();\n // task_list.update({_id : due_date_id},{$set:{'due_date' : due_date}});\n\n // }\n // });\n document.getElementById('due_date').value='';\n }", "function setCustomShipDate(record, shipDate){\r\n if(!!shipDate){\r\n nlapiLogExecution('DEBUG', 'f3_custbody_sortingshipdate', shipDate);\r\n record.setFieldValue('custbody_sortingshipdate', shipDate);\r\n }\r\n}", "function tglinput(par){ \n\t$(par).datepicker();\n}", "function onSelectV(strSerialized, strField, strTemp)\n{\n\tvar strXMLData = \"\";\n\tvar objForm = document.forms[afmInputsFormName];\n\tif(strField != \"\")\n\t{\n\t\tvar typeUpperCase = arrFieldsInformation[strField][\"type\"];\n\t\ttypeUpperCase = typeUpperCase.toUpperCase();\n\t\tvar formatUpperCase = arrFieldsInformation[strField][\"format\"];\n\t\tformatUpperCase = formatUpperCase.toUpperCase();\n\t\tvar strValue = objForm.elements[strField].value;\n\t\t//removing money sign and grouping separator and changing date into ISO format\n\t\tstrValue = convertFieldValueIntoValidFormat(typeUpperCase, formatUpperCase, strValue);\n\t\t//trim strValues\n\t\tstrValue = strValue.replace(/^\\s+/,'').replace(/\\s+$/,'');\n\t\tif(typeUpperCase != \"JAVA.SQL.TIME\")\n\t\t\tstrValue = convert2validXMLValue(strValue);\n\t\tvar strData = \"\";\n\t\tvar strXMLValue = \"\";\n\t\tif(strSerialized != \"\")\n\t\t{\n\t\t\t//calling setSerializedInsertingDataVariables() in\n\t\t\t//common.js to set up related js variables in common.js\n\t\t\t//strSerializedStartTag, strSerializedCloseTag,\n\t\t\t//strSerializedInsertingDataFirstPart,strSerializedInsertingDataRestPart\n\t\t\tsetSerializedInsertingDataVariables(strSerialized);\n\t\t\tvar temp_table = \"\";\n\t\t\tvar temp_field = \"\";\n\t\t\tvar temp_array = new Array();\n\t\t\ttemp_array = strField.split(\".\");\n\t\t\tif(temp_array[0] != null)\n\t\t\t\ttemp_table = temp_array[0];\n\t\t\tif(temp_array[1] != null)\n\t\t\t\ttemp_field = temp_array[1];\n\t\t\t<!-- adding role=\"self\" in field will disable Java to show the values in its referred table if it is a foreign key -->\n\t\t\t<!-- not adding role=\"\" or adding role=\"\" with any string rather than \"self\" will enable Java to show the values in its referred table-->\n\t\t\tstrData = '<fields><field role=\"self\" table=\"'+temp_table+'\" name=\"'+temp_field+'\"/></fields>';\n\t\t\t//getting all records\n\t\t\t//strData = strData +gettingRecordsData();\n\t\t\t//strData = strData +strStartTag+ 'prefix ';\n\t\t\t//strData = strData + 'value=\"'+strValue+'\"';\n\t\t\t//strData = strData + '/'+strCloseTag;\n\t\t\tstrXMLValue = strSerializedInsertingDataFirstPart + strData + strSerializedInsertingDataRestPart;\n\t\t\t//calling OpenSelectVWindow() to open a new window for server\n\t\t\t//to show available values for specified field\n\t\t\tOpenSelectVWindow(strXMLValue);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(Debug)\n\t\t\t{\n\t\t\t\talert(\"The attribute serialized of afmAction is empty.\");\n\t\t\t}\n\t\t}\n\t}\n}", "function setData() {\n let today = new Date().toJSON().substr(0,10);\n let day = dayjs().add(8, 'days').toDate().toJSON().substr(0, 10);\n console.log(day);\n $(\"#date\").attr(\"min\", today);\n $(\"#date\").attr(\"max\", day);\n}", "function initDateInput() {\n\tlet dateInput = document.getElementById(\"dateInput\");\n\tlet d = new Date();\n\tdateInput.value = d.getFullYear() + \"-\" +\n\t\tlz(Number(d.getMonth()+1)) + \"-\" +\n\t\tlz(d.getDate());\n}", "function dateFilter(column){\n var operator = column.parent('div').next();\n var value = operator.next();\n \n value.empty().append($('<input />').attr('type', 'text').addClass('textfield_value form-control no_radius') \n .attr('name','textfield_value[]')\n .attr('id', 'textfield_value'+(idDateField++))\n .datepicker({\n dateFormat: \"dd-mm-yy\"\n })\n ); \n \n operator.children().empty().html($(\"#Operadores\").html());\n}", "function populateDataFields() {}", "'click #start_date'(){\n \n\n $(\"#start_date\").datepicker({dateFormat : \"mm/dd/yy\"});\n\n // showOn: \"button\",\n \n // buttonImageOnly: true,\n // buttonText: \"Select date\",\n // onSelect: function(){\n // var due_date = $(this).val();\n // task_list.update({_id : due_date_id},{$set:{'due_date' : due_date}});\n\n // }\n // });\n document.getElementById('start_date').value='';\n }", "function purchaseExcelReport(data_record_po) {\n\n}", "function stock_change_report() {\n //\n // clearing elements inside main-container div\n var childNodes = document.getElementById('main-container').childNodes;\n for (var i = 0; i < childNodes.length; i++) {\n if (childNodes[i].nodeType == 1) {childNodes[i].removeAll();}\n }\n //\n //\n var head_elements = Array(\n {'elm' : 'LEGEND','textNode' : 'Stock Report Parameters'},\n {'elm' : 'LABEL', 'className' : 'label-12em', 'textNode' : 'Show Deleted Records'},\n {'elm' : 'INPUT', 'id' : 'show-deleted', 'type' : 'checkbox', 'events' : [{'event' : 'click', 'function' : show_update_button.bind(null,'create-report','stock-change-report-table','Show Changes')}]},\n {'elm' : 'BR'},\n {'elm' : 'LABEL', 'className' : 'label-12em', 'textNode' : 'Narrow by Item Number:'},\n {'elm' : 'INPUT', 'id' : 'search-item-number', 'type' : 'text', 'events' : [{'event' : 'keyup', 'function' : show_update_button.bind(null,'create-report','stock-change-report-table','Show Changes')}]},\n {'elm' : 'BR'},\n {'elm' : 'BR'},\n {'elm' : 'DIV', 'id' : 'time-range-inputs'}\n );\n //\n var fieldset = document.createElementWithAttr('FIELDSET',{'class' : 'fieldset-default'});\n var button = document.createElementWithAttr('BUTTON',{'id' : 'create-report', 'type' : 'button'});\n button.addEventListener('click',create_change_report.bind(null));\n button.addTextNode('Create Report');\n document.getElementById('input-div').appendChild(fieldset);\n document.getElementById('input-div').appendChild(button);\n addChildren(fieldset,head_elements);\n //\n // creating time range inputs\n var input_args = {\n output_id : 'time-range-inputs',\n time_range_onchange : \"show_update_button('create-report','stock-change-report-table','Show Changes');\",\n day_onkeyup : \"show_update_button('create-report','stock-change-report-table','Show Changes');\",\n month_onchange : \"show_update_button('create-report','stock-change-report-table','Show Changes');\",\n year_onchange : \"show_update_button('create-report','stock-change-report-table','Show Changes');\",\n add_date_range_onclick : \"show_update_button('create-report','stock-change-report-table','Show Changes');\"\n };\n create_time_range_inputs(input_args);\n}", "constructor(data) {\n this.asset_report_id__c = data.asset_report_id;\n this.client_report_id__c = data.client_report_id;\n this.date_generated__c = data.date_generated;\n this.days_requested__c = data.days_requested;\n }", "function record_data(e) {\n try {\n var d = new Date();\n var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty(\"key\"));\n var sheet = doc.getSheetByName('record');\n var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];\n var nextRow = sheet.getLastRow() + 1;\n var row = [(d.getMonth() + 1) + \"/\" + d.getDate() + \"/\" + d.getFullYear()];\n row.push(formatAMPM(d));\n for (var i = 2; i < headers.length; i++) {\n if (headers[i].length > 0) {\n if (e.parameter[headers[i]]) {\n row.push(e.parameter[headers[i]]);\n }\n }\n }\n sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);\n } catch (error) {\n Logger.log(e);\n } finally {\n return;\n }\n}", "function initialize(){\ncurr_date=opener.selDate;\nsemimonthly=opener.isSemimonthly; \ncurr_date=(curr_date == null)?new Date():curr_date;\nreturn curr_date;\n}", "function createNew(intDate){\r\n\tvar dateObj = new Date;\r\n\tdocument.getElementById(\"reminderEdit\").style.display = 'block';\r\n\tclearForm();\r\n\tdocument.getElementById(\"reminderDate\").value = intDate;\r\n\tdocument.getElementById(\"reminderMonth\").value = myShortMonths[dateObj.getMonth()];\r\n\tdocument.getElementById(\"reminderYear\").value = dateObj.getFullYear();\r\n\tdocument.getElementById(\"reminderMode\").value = \"new\";\r\n}", "onChangeDate(value){\n let newPayment = this.state.dispPayment;\n newPayment.date = value.slice(0, 10);\n this.setState({dispPayment: newPayment});\n }", "constructor({id = -1,\r\n dateCreated = \"\",\r\n dateUpdated = \"\",\r\n completed = 0,\r\n title = \"\",\r\n description = \"\",\r\n tags = [],\r\n weight = 0,\r\n prerequisites = [],\r\n time_estimate = \"\",\r\n due_date = \"\"} = {}) {\r\n // CONVERT FIELDS HERE\r\n this.#id = id;\r\n this.#dateCreated = dateCreated;\r\n this.#dateUpdated = dateUpdated;\r\n this.title = title;\r\n this.completed = parseInt(completed);\r\n this.description = description;\r\n this.#tags = tags;\r\n this.weight = parseInt(weight) ? parseInt(weight) : 0;\r\n this.#prerequisites = prerequisites;\r\n this.time_estimate = time_estimate;\r\n this.due_date = due_date;\r\n }", "function dateTimePopulate (event) {\n const currentDateTime = new Date();\n let currentDate, currentTime = '';\n let month = currentDateTime.getMonth() + 1;\n let day = currentDateTime.getDay() + 1;\n let hour = currentDateTime.getHours();\n let year = currentDateTime.getFullYear();\n let minutes = currentDateTime.getMinutes();\n\n if (month < 10) month = \"0\" + month;\n if (day < 10) day = \"0\" + day;\n if (hour < 10) hour = \"0\" + hour;\n if (minutes < 10) minutes = \"0\" + minutes;\n\n currentDate = `${year}-${month}-${day}`;\n currentTime = `${hour}:${minutes}`;\n\n $(event.currentTarget).next('form').find('.date-dash').val(currentDate);\n\n if ($(event.currentTarget).next('form').find('.time-dash')) {\n $(event.currentTarget).next('form').find('.time-dash').val(currentTime);\n }\n\n}", "function applyDate(inputFieldNames, inputFieldValues, isInlineCalendar, event){\r\n\t\r\n\t\r\n\tif (event){\r\n\t\tvar target = (isIE) ? event.srcElement : event.target;\r\n\t\tfor (var p=target.parentNode;p!=null;p=p.parentNode){\r\n\t\t\tif ((p.id) && ((p.id.indexOf(\"HATSFR\")) == 0)){\r\n\t\t\t\tvar parentName=p.id.substring(6);\r\n\t\t\t\tsetHatsFocus(parentName);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (var i=0,iL=inputFieldNames.length,iName,iVal; i<iL; ++i){\r\n\t\tiName=inputFieldNames[i];\r\n\t\tiVal=inputFieldValues[i];\r\n\t\tvar e = eval(\"hatsForm.\" + iName);\r\n\r\n\t\tif (typeof e.value == 'undefined'){\r\n\t\t\tif (typeof e[0].value != 'undefined'){\r\n\t\t\t\te = e[0];\r\n\t\t\t\tif ((isInlineCalendar) && (i == (iL - 1))){\r\n\t\t\t\t\te.focus();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (e && isInlineCalendar && (i == (iL - 1))){\r\n\t\t\te.focus();\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\te.setAttribute(\"MDT\",\"1\");\r\n\t\t}\r\n\t\tcatch(ex){\r\n\t\t\tvar errNum = (ex.number) ? (ex.number & 0xFFFF) : \"\";\r\n\t\t\talert(\"applyDate Exception \" + errNum + \": \" + ex.name + \" \" + ex.toString());\r\n\t\t}\r\n\r\n\t\tif (enableBIDI){\r\n\t\t\tif(e.length > 0){\r\n\t\t\t\tfor (var k=0,kL=e.length; k<kL; ++k){\r\n\t\t\t\t\tiVal = reverseData(e[k], iVal);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tiVal = reverseData(e, iVal);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcheckInput2(iName, iVal, e.type);\r\n\r\n\t\tif (i == (iL - 1)){// only set the cursor position on the last field (works for single and multiple)\r\n\t\t\tvar inputField = iName.split(\"_\");\r\n\t\t\tvar fstart = parseInt(inputField[1]);\r\n\t\t\tvar flength = parseInt(inputField[2]);\r\n\t\t\tvar d = fstart + flength;\r\n\r\n\t\t\tif (flength <= iVal.length){\r\n\t\t\t\td = d - 1; //adjust for last in field\r\n\t\t\t}\r\n\r\n\t\t\tsetCursorPosition(d, hatsForm.name);\r\n\t\t\thatsForm.CARETPOS.value = d + 1;\r\n\t\t}\r\n\t}\r\n}", "function addScheduledInterviewId() {\n document.feedbackForm.interviewId.value = getScheduledInterviewId();\n}", "function paintGridDate(){\r\n $('.futureDate').text(gridSimulatorVar.future_date.format(gridSimulatorCons.moment_format))\r\n}", "function fixDates() {\n //console.log(\"done\");\n const today = new Date();\n const daysToAdd = dateDiff(params.reportdate, today.toISOString().slice(0, 10));\n params[\"daysToAdd\"] = daysToAdd;\n if (daysToAdd == 0) return;\n //note to self: cannot use JSON.stringify as it doesnt cov er the functions\n traverse(params);\n}", "function OnExportEventClicked(o)\n{\n var s = GatherFilterSelections(o.getAttribute('filter_div'), o.getAttribute('is_calgroup').toLowerCase()); \n document.getElementById(o.getAttribute('hid_filter_info')).value = s;\n}", "function SetMaxDateInput(inputID) {\n document.getElementById(inputID).max = new Date().toISOString().split(\"T\")[0];\n}", "fieldsInfo () {\n return [\n {\n text: this.$t('fields.id'),\n name: 'id',\n details: false,\n table: false,\n },\n\n {\n type: 'input',\n column: 'order_nr',\n text: 'order No.',\n name: 'order_nr',\n multiedit: false,\n required: true,\n disabled: true,\n create: false,\n },\n {\n type: 'input',\n column: 'name',\n text: 'person name',\n name: 'name',\n multiedit: false,\n required: false,\n edit: false,\n create: false,\n },\n\n {\n type: 'input',\n column: 'email',\n text: 'email',\n name: 'email',\n multiedit: false,\n required: false,\n edit: false,\n create: false,\n },\n\n {\n type: 'select',\n url: 'crm/people',\n list: {\n value: 'id',\n text: 'fullname',\n data: [],\n },\n column: 'user_id',\n text: this.$t('fields.person'),\n name: 'person',\n apiObject: {\n name: 'person.name',\n },\n table: false,\n },\n {\n type: 'input',\n column: 'package_points',\n text: 'package points',\n name: 'package_points',\n required: false,\n edit: false,\n create: false,\n },\n\n // package_points\n {\n type: 'select',\n url: 'crm/package',\n list: {\n value: 'id',\n text: 'full_name',\n data: [],\n },\n column: 'package_id',\n text: 'package name',\n name: 'package',\n apiObject: {\n name: 'package.package_name',\n },\n table: false,\n },\n {\n type: 'input',\n column: 'package_name',\n text: 'package name',\n name: 'package_name',\n multiedit: false,\n required: false,\n edit: false,\n create: false,\n },\n\n {\n type: 'input',\n column: 'package_price',\n text: 'package price',\n name: 'package_price',\n multiedit: false,\n required: false,\n edit: false,\n create: false,\n },\n\n {\n type: 'input',\n column: 'pur_date',\n text: 'purche date',\n name: 'pur_date',\n multiedit: false,\n required: false,\n edit: false,\n create: false,\n },\n ]\n }" ]
[ "0.5637057", "0.5588363", "0.5576377", "0.55255324", "0.55194706", "0.551584", "0.54450744", "0.5440085", "0.5382059", "0.5361598", "0.5327738", "0.52900213", "0.5272739", "0.5270403", "0.52629256", "0.5251821", "0.5246729", "0.5245311", "0.5244439", "0.52371335", "0.52336746", "0.5215413", "0.5215241", "0.52112293", "0.5205193", "0.5185114", "0.51737577", "0.51671076", "0.5155306", "0.51524025", "0.5145519", "0.5145519", "0.51383984", "0.51240104", "0.51225877", "0.5121228", "0.5112987", "0.5103762", "0.51000327", "0.509193", "0.50918096", "0.5085675", "0.5085408", "0.5085127", "0.50732315", "0.50675124", "0.5052304", "0.5038522", "0.50342715", "0.5029142", "0.50283396", "0.50201017", "0.5017451", "0.5010313", "0.50083023", "0.5002332", "0.49910468", "0.4990578", "0.49806032", "0.49746078", "0.49695706", "0.49660134", "0.49653015", "0.4962899", "0.4954486", "0.4953414", "0.49473146", "0.4943291", "0.49395683", "0.49355945", "0.49329194", "0.49323368", "0.49308044", "0.49283147", "0.49235496", "0.49175712", "0.4898884", "0.48886314", "0.48856142", "0.48841286", "0.4882928", "0.48806983", "0.48710313", "0.48704827", "0.48683575", "0.48603427", "0.48554772", "0.4847746", "0.4834805", "0.48332363", "0.48289904", "0.48255736", "0.4823313", "0.48178965", "0.48149693", "0.48131627", "0.48100612", "0.4809933", "0.48080692", "0.47963518" ]
0.5310902
11
END OF UpdateStats Code START OF Reporting Code
function pii_next_report_time() { var curr_time = new Date(); curr_time.setSeconds(0); // Set next send time after 3 days curr_time.setMinutes( curr_time.getMinutes() + 4320); curr_time.setMinutes(0); curr_time.setHours(0); curr_time.setMinutes( curr_time.getMinutes() + pii_vault.config.reporting_hour); return new Date(curr_time.toString()); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateStats()\n{\n updateGoalAttempts();\n updateShotsOnGoal();\n updateShotsOffGoal();\n updateBlockedShots();\n updateCorners();\n updateOffsides();\n updateGKSaves();\n updateFoulsCommited();\n updateFoulsReceived();\n\n updateCompletePasses();\n updateIncompletePasses();\n updateTotalPasses();\n\n updateThrows();\n}", "UpdateMetrics() {\n }", "function update_metrics() {\n metric_signups();\n past_events();\n photos_count();\n upcoming_events();\n past_events_photos();\n avg_event_photos();\n revenue();\n}", "function updateAllStats(){\n wantedLevelChange()\n updateMaxHeld()\n}", "function updateStats() {\n\t$(\"#stats\").text(JSON.stringify(ozpIwc.metrics.toJson(),null,2));\n}", "function update_stats() {\n\t\t\t// get time delta if not specified\n\t\t\tif (dtime === undefined) {\n\t\t\t\tvar old = medeactx.time;\n\t\t\t\tmedeactx.time = Date.now() * 0.001;\n\n\t\t\t\tdtime = medeactx.time - old;\n\t\t\t}\n\n\t\t\t// check if the canvas sized changed\n\t\t\tif(medeactx.cached_cw != medeactx.canvas.width) {\n\t\t\t\tmedeactx.cached_cw = medeactx.canvas.width;\n\t\t\t\tmedeactx.frame_flags |= medeactx.FRAME_CANVAS_SIZE_CHANGED;\n\t\t\t}\n\t\t\tif(medeactx.cached_ch != medeactx.canvas.height) {\n\t\t\t\tmedeactx.cached_ch = medeactx.canvas.height;\n\t\t\t\tmedeactx.frame_flags |= medeactx.FRAME_CANVAS_SIZE_CHANGED;\n\t\t\t}\n\n\t\t\tmedeactx._UpdateFrameStatistics(dtime);\n\t\t}", "updateStats() {\n if (this.status === 0 || !this.dealtIn) {\n this.nvpip = 0;\n this.npfr = 0;\n this.n3bet = 0;\n this.nhands = 0;\n }\n else if (this.status === 1) {\n this.nvpip += this._vpip;\n this.npfr += this._pfr;\n this.n3bet += this._3bet;\n this.nhands += 1;\n }\n \n this._vpip = 0;\n this._pfr = 0;\n this._3bet = 0;\n }", "function statUpdateTick() {\n updateCurrentStats();\n }", "function sendStats() {\n push('stats', {\n hits: hits,\n totalHits: totalHits,\n bytes: bytes,\n totalBytes: totalBytes,\n cost: cost,\n totalCost: totalCost,\n period: STATS_PERIOD,\n uptime: +(new Date) - startTime\n });\n\n hits = 0;\n bytes = 0;\n cost = 0;\n}", "function updateStats() {\n let contents = \"Restarts: \" + restarts;\n $(\"#restarts\").text(contents);\n\n contents = \"Endings: \" + endings.length + \"/\" + TOTAL_ENDINGS;\n $(\"#totalEndings\").text(contents);\n}", "updateStats() {\n if (this.visualize) {\n var ncount = document.getElementById(\"ncount\");\n ncount.innerHTML = \"Neutron count: \" + this.neutrons.length;\n\n var meanHeat = document.getElementById(\"meanHeat\");\n meanHeat.innerHTML = \"Mean heat: \" + this.getMeanHeat();\n }\n }", "function main()\n{\n\t// Fetch all stats that exist already\n\tvar fetchAllUrl = baseUrl + \"/apps/fetchstats/\" + appId;\n\tconsole.log(\"Fetching all stats...\");\n\tAppsAjaxRequest(fetchAllUrl, {}, function(results){\n\t\tconsole.log(\"Retrieved results!\");\n\t\texistingStats = results;\n\t\tParseExistingStats();\n\t});\n}", "function process_Pdh_Frame_Link_History_Data_Stats(record)\n{\n\tvar myId;\t\t\n\tvar subelement = LOOKUP.get(record.monitoredObjectPointer); \n\t\n\tif(subelement == null)\n\t{\n\t\tlogP5Msg(\"process_Pdh_Frame_Link_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Link_History_Data_Stats\", \"Skipping 0 rid for --> \"+ record.monitoredObjectPointer);\n\t\treturn;\n\t}\n\tmyId = subelement.id;\n logP4Msg(\"process_Pdh_Frame_Link_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Link_History_Data_Stats\", \"ENTERING for --> \"+ record.monitoredObjectPointer + \" with id == \" + myId);\n \n\tfor(var i in PdhFrameLinkHistoryDataStats15MinMetrics)\n\t{\n\t var value = parseInt(record[PdhFrameLinkHistoryDataStats15MinMetrics[i]]);\t\n\t if (!(value == null || isNaN(value))) {\n\t\t CreateSimpleMetricObject(myId, record, \"AP~Specific~Alcatel~5620 SAM~Bulk~radioequipment~PdhFrameLinkHistoryDataStats15Min~\", PdhFrameLinkHistoryDataStats15MinMetrics[i]);\n }\n\t}\n\tlogP4Msg(\"process_Pdh_Frame_Link_History_Data_Stats\", \"SAMUBA_Pdh_Frame_Link_History_Data_Stats\", \"LEAVING\");\n}", "async function updateStats() {\n const stats = await (await fetch( './getStats', { method: 'POST'} )).json();\n\n // fill in static routes\n fillElements( stats );\n\n // progress bar\n document.querySelector( '.progress .tabresult' ).style.width = (100 * stats.tables.result / stats.tables.total) + '%';\n document.querySelector( '.progress .taberror' ).style.width = (100 * stats.tables.error / stats.tables.total) + '%';\n const progressTitle = `Results: ${(100 * stats.tables.result / stats.tables.total).toFixed(2)}% | Errors: ${(100 * stats.tables.error / stats.tables.total).toFixed(2)}%`;\n ['.progress', '.progress .tabresult', '.progress .taberror']\n .forEach( (sel) => document.querySelector( sel ).setAttribute( 'title', progressTitle ) );\n\n // update file availability\n for( const link of [ 'results', 'errors' ] ) {\n if( stats.files[ link ] ) {\n els[ link ].classList.remove( 'disabled');\n els[ link ].setAttribute( 'href', els[ link ].dataset.href );\n } else {\n els[ link ].classList.remove( 'disabled');\n els[ link ].removeAttribute( 'href' );\n }\n }\n\n // checkmark for finished\n if( stats.tables.unfinished < 1 ) {\n document.querySelector( '.finishedFlag' ).classList.add( 'finished' );\n } else {\n document.querySelector( '.finishedFlag' ).classList.remove( 'finished' );\n }\n\n // enable/disable evaluation section\n document.querySelector('#eval').style.display = stats.hasEvaluation ? 'block' : 'none';\n document.querySelector('#analysis').style.display = stats.hasEvaluation ? 'block' : 'none';\n\n }", "function updateStats(ui, stats) {\n ui.headMovements.text('Track Movement: ' + stats.trackMovement);\n ui.averageTime.text('Average Wait Time: ' + Math.round(stats.averageWait));\n}", "function reWriteStats() {\n console.log(car.make, car.model, car.color, car.mileage, car.isWorking);\n }", "function RainbowProfileReport() {\r\n}", "increaseStat() {}", "function updateStats()\n{\n\tvar element;\n\telement = document.getElementById(\"score\");\n\telement.firstChild.nodeValue = \"Score: \" + score;\n\telement = document.getElementById(\"completion\");\n\telement.firstChild.nodeValue = \"Completion: \" + blocksDestroyed + \"/\" + numBlocks;\n}", "function reWriteStats() {\nconsole.log('-----------')\nconsole.log('Make: ' + car.make)\nconsole.log('Model: ' + car.model)\nconsole.log('Color: ' + car.color)\nconsole.log('Mileage: ' + car.mileage)\nconsole.log('Is working: ' + car.isWorking)\nconsole.log('-----------')\n}", "function getSummonerStatsSummary(){\n\n}", "function process_lte_S1uAgwPeer_stats(record)\n{\n\tvar myId;\t\t\n\tvar subelement = LOOKUP.get(record.monitoredObjectPointer); \n\t\n\tif(subelement == null)\n\t{\n\t\tlogP5Msg(\"process_lte_S1uAgwPeer_stats\", \"SAMUBA_lte_S1uAgwPeerStats\", \"Skipping 0 rid for --> \"+ record.monitoredObjectPointer);\n\t\treturn;\n\t}\n\tmyId = subelement.id;\n logP4Msg(\"process_lte_S1uAgwPeer_stats\", \"SAMUBA_lte_S1uAgwPeerStats\", \"ENTERING for --> \"+ record.monitoredObjectPointer + \" with id == \" + myId);\n \n\tfor(var i in S1uAgwPeerStatsMetrics)\n\t{\n\t var value = parseInt(record[S1uAgwPeerStatsMetrics[i]]);\t\n\t if (!(value == null || isNaN(value))) {\n\t\t CreateSimpleMetricObject(myId, record, \"AP~Specific~Alcatel~5620 SAM~Bulk~lteepc~AGW~S1UPeerStats~\", S1uAgwPeerStatsMetrics[i]); \n }\n\t}\n\tlogP4Msg(\"process_lte_S1uAgwPeer_stats\", \"SAMUBA_lte_S1uAgwPeerStats\", \"LEAVING\");\n}", "function updateStats(mx,cd, jmx, jbd, jdx, jdd, cgx, cgd, rbx, rbd, adx, add){\n var csContent =\"<b>Most Dupe with \" + mx + \":</b><br>\";\n for(i in cd){\n csContent += cd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Jonny Most Dupe with \" + jmx + \":</b><br>\";\n for(i in jbd){\n csContent += jbd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>JD Most Dupe with \" + jdx + \":</b><br>\";\n for(i in jdd){\n csContent += jdd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Chris Most Dupe with \" + cgx + \":</b><br>\";\n for(i in cgd){\n csContent += cgd[i] + \"<br>\";\n }\n\n csContent +=\"<p><b>Richard Most Dupe with \" + rbx + \":</b><br>\";\n for(i in rbd){\n csContent += rbd[i] + \"<br>\";\n }\n csContent +=\"<p><b>Andy Most Dupe with \" + adx + \":</b><br>\";\n for(i in add){\n csContent += add[i] + \"<br>\";\n }\n\n document.getElementById('theStatArea').innerHTML = csContent;\n\n\n\n\n }", "function updateCalendarStats(){\n if(new Date().getFullYear() == currentCalendar.lastYearViewed){\n currentStreakDiv.innerHTML = \"Current Streak: <span>\" + getCurrentStreak() + \"</span>\";\n }else{\n currentStreakDiv.innerHTML = \"\";\n }\n longestStreakSpan.innerHTML = getLongestStreak();\n totalLitSpan.innerHTML = getNumberCellsLit();\n percentLitSpan.innerHTML = getPercentCellsLit();\n }", "function UpdateProgressMetrics(){\n // Calculate percentage of module progress\n perbaspro = baspro/20*100;\n perpospro = pospro/20*100;\n perfol1pro = fol1pro/20*100;\n perfol2pro = fol2pro/20*100;\n perbashrqpro = bashrqpro/6*100;\n perposhrqpro = poshrqpro/6*100;\n perfol1hrqpro = fol1hrqpro/6*100;\n perfol2hrqpro = fol2hrqpro/6*100;\n perbasmitakpro = basmitakpro/37*100;\n perposmitakpro = posmitakpro/37*100;\n perfol1mitakpro = fol1mitakpro/37*100;\n perfol2mitakpro = fol2mitakpro/37*100;\n permipro = mipro/6*100;\n peroarspro = oarspro/58*100;\n pertarpro = tarpro/33*100;\n perevokpro = evokpro/100*100;\n perplanpro = planpro/11*100;\n perfullmipro = fullmipro/1*100;\n \n // Calculate percentage of skill acquisition based on correct items\n affirmcount = UpdateProgressResponseCorrect(oarsanswercorrect5) + UpdateProgressResponseCorrect(oarsanswercorrect6);\n peraffirm = affirmcount/15*100;\n \n reflectcount = UpdateProgressResponseCorrect(oarsanswercorrect4) + UpdateProgressResponseCorrect(targetanswercorrect2);\n perreflect = reflectcount/11*100;\n \n openclosecount = UpdateProgressResponseCorrect(oarsanswercorrect1) + UpdateProgressResponseCorrect(oarsanswercorrect2) + UpdateProgressResponseCorrect(oarsanswercorrect3);\n peropenclose = openclosecount/39*100;\n \n targetcount = UpdateProgressResponseCorrect(targetanswercorrect1);\n pertarget = targetcount/13*100;\n \n changetalkcount = UpdateProgressResponseCorrect(evokanswercorrect1) + UpdateProgressResponseCorrect(evokanswercorrect2) + UpdateProgressResponseCorrect(evokanswercorrect3) + UpdateProgressResponseCorrect(evokanswercorrect4) + UpdateProgressResponseCorrect(evokanswercorrect5);\n perchangetalk = changetalkcount/88*100;\n \n}", "getStatistics() {\n return {\n averageRTTms: this.rpcProxy.getAverageRttMs(),\n sentMessages: this.id - INITIAL_ID,\n failedMessages: this.rpcProxy.errorCounter,\n };\n }", "function reportStats() {\n\t\t\t//\n\t\t\t// Memory\n\t\t\t//\n\t\t\tvar mem = p &&\n\t\t\t p.memory &&\n\t\t\t p.memory.usedJSHeapSize;\n\n\t\t\tif (mem) {\n\t\t\t\tt.set(\"mem\", mem);\n\t\t\t}\n\n\t\t\t//\n\t\t\t// DOM sizes (bytes) and length (node count)\n\t\t\t//\n\t\t\tdomLength = domAllNodes.length;\n\n\t\t\tt.set(\"domsz\", d.documentElement.innerHTML.length);\n\t\t\tt.set(\"domln\", domLength);\n\n\t\t\t//\n\t\t\t// DOM mutations\n\t\t\t//\n\t\t\tif (mutationCount > 0) {\n\t\t\t\t// report as % of DOM size\n\t\t\t\tvar deltaPct = Math.min(Math.round(mutationCount / domLength * 100), 100);\n\n\t\t\t\tt.set(\"mut\", deltaPct);\n\n\t\t\t\tmutationCount = 0;\n\t\t\t}\n\t\t}", "function updateStats() {\n if (!g_original_title) {\n g_original_title = document.title;\n }\n var total_entries = getEntries().length;\n var new_entries = total_entries - g_n_collapsed;\n document.title = g_original_title + ' - ' + new_entries + ' new entries';\n var stats = document.getElementById('stats');\n if (stats) {\n stats.innerHTML = total_entries + ' entries, ' + new_entries + ' new.';\n }\n}", "function updateStatistics() {\n var MILLIS_IN_AN_HOUR = 60 * 60 * 1000;\n var now = Date.now();\n var from = new Date(now - MILLIS_IN_AN_HOUR).toISOString();\n var until = new Date(now).toISOString();\n var functionEventsProjectName = '{project=\"' + ctrl.project.metadata.name + '\"}';\n var projectName = '{project_name=\"' + ctrl.project.metadata.name + '\"}';\n var gpuUtilizationMetric = ' * on (pod) group_left(function_name)(nuclio_function_pod_labels{project_name=\"' +\n ctrl.project.metadata.name + '\"})';\n var args = {\n metric: ctrl.functionEventsMetric + functionEventsProjectName,\n from: from,\n until: until,\n interval: '5m'\n };\n\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionEventsMetric))\n .catch(handleError.bind(null, ctrl.functionEventsMetric));\n\n args.metric = ctrl.functionCPUMetric + projectName;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionCPUMetric))\n .catch(handleError.bind(null, ctrl.functionCPUMetric));\n\n args.metric = ctrl.functionGPUMetric + gpuUtilizationMetric;\n args.appendQueryParamsToUrlPath = true;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionGPUMetric))\n .catch(handleError.bind(null, ctrl.functionGPUMetric));\n delete args.appendQueryParamsToUrlPath;\n\n args.metric = ctrl.functionMemoryMetric + projectName;\n ctrl.getStatistics(args)\n .then(parseData.bind(null, ctrl.functionMemoryMetric))\n .catch(handleError.bind(null, ctrl.functionMemoryMetric));\n\n /**\n * Sets error message to the relevant function\n */\n function handleError(type, error) {\n lodash.forEach(ctrl.functions, function (aFunction) {\n lodash.set(aFunction, 'ui.error.' + type, error.msg);\n\n $timeout(function () {\n ElementLoadingStatusService.hideSpinner(type + '-' + aFunction.metadata.name);\n });\n });\n }\n\n /**\n * Parses data for charts\n * @param {string} type\n * @param {Object} data\n */\n function parseData(type, data) {\n var results = lodash.get(data, 'result', []);\n\n lodash.forEach(ctrl.functions, function (aFunction) {\n var funcStats = [];\n\n lodash.forEach(results, function (result) {\n var functionName = lodash.get(aFunction, 'metadata.name');\n var metric = lodash.get(result, 'metric', {});\n var resultName = lodash.defaultTo(metric.function, metric.function_name);\n\n if (resultName === functionName) {\n funcStats.push(result);\n }\n });\n\n if (lodash.isObject(funcStats)) {\n var latestValue = lodash.sum(lodash.map(funcStats, function (stat) {\n return Number(lodash.last(stat.values)[1]);\n }));\n\n // calculating of invocation per second regarding last timestamps\n var invocationPerSec = lodash.chain(funcStats)\n .map(function (stat) {\n var firstValue;\n var secondValue;\n\n if (stat.values.length < 2) {\n return 0;\n }\n\n // handle array of length 2\n firstValue = stat.values[0];\n secondValue = stat.values[1];\n\n // when querying up to current time prometheus\n // may duplicate the last value, so we calculate an earlier\n // interval [pre-last] to get a meaningful value\n if (stat.values.length > 2) {\n firstValue = stat.values[stat.values.length - 3];\n secondValue = stat.values[stat.values.length - 2];\n }\n\n var valuesDiff = Number(secondValue[1]) - Number(firstValue[1]);\n var timestampsDiff = secondValue[0] - firstValue[0];\n\n return valuesDiff / timestampsDiff;\n })\n .sum()\n .value();\n\n var funcValues = lodash.get(funcStats, '[0].values', []);\n\n if (funcStats.length > 1) {\n funcValues = lodash.fromPairs(funcValues);\n\n for (var i = 1; i < funcStats.length; i++) {\n var values = lodash.get(funcStats, '[' + i + '].values', []);\n\n lodash.forEach(values, function (value) { // eslint-disable-line no-loop-func\n var timestamp = value[0];\n\n lodash.set(funcValues, timestamp, lodash.has(funcValues, timestamp) ?\n Number(funcValues[timestamp]) + Number(value[1]) : Number(value[1]));\n });\n }\n\n funcValues = lodash.chain(funcValues)\n .toPairs()\n .sortBy(function (value) {\n return value[0];\n })\n .value();\n }\n\n if (type === ctrl.functionCPUMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n 'cpu.cores': latestValue,\n cpuCoresLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else if (type === ctrl.functionMemoryMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n size: Number(latestValue),\n sizeLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else if (type === ctrl.functionGPUMetric) {\n lodash.merge(aFunction.ui, {\n metrics: {\n 'gpu.cores': latestValue,\n gpuCoresLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n })\n }\n });\n } else { // type === METRICS.FUNCTION_COUNT\n lodash.merge(aFunction.ui, {\n metrics: {\n count: Number(latestValue),\n countLineChartData: lodash.map(funcValues, function (dataPoint) {\n return [dataPoint[0] * 1000, Number(dataPoint[1])]; // [time, value]\n }),\n invocationPerSec:\n $filter('scale')(invocationPerSec, Number.isInteger(invocationPerSec) ? 0 : 2)\n }\n });\n }\n }\n });\n\n // if the column values have just been updated, and the table is sorted by this column - update sort\n if (type === ctrl.functionCPUMetric && ctrl.sortedColumnName === 'ui.metrics[\\'cpu.cores\\']' ||\n type === ctrl.functionGPUMetric && ctrl.sortedColumnName === 'ui.metrics[\\'gpu.cores\\']' ||\n type === ctrl.functionMemoryMetric && ctrl.sortedColumnName === 'ui.metrics.size' ||\n type === ctrl.functionEventsMetric &&\n lodash.includes(['ui.metrics.invocationPerSec', 'ui.metrics.count'], ctrl.sortedColumnName)) {\n sortTable();\n }\n\n $timeout(function () {\n hideSpinners(type);\n })\n }\n }", "function statistics() {\n\t/*var time = Date.now() - startTime - pauseTime;\n\t\tvar seconds = (time / 1000 % 60).toFixed(2);\n\t\tvar minutes = ~~(time / 60000);\n\t\tstatsTime.innerHTML = (minutes < 10 ? '0' : '') + minutes +\n\t(seconds < 10 ? ':0' : ':') + seconds;*/\n}", "function printStatistics() {\n var textP;\n var defxo = 0.1, //default x offset\n defwo = 1, //default width offset\n wo = 0.8 //another width offset\n deftp = 0.05; // default text percentage\n textP = \"Statistics\";\n printText(0, 0.25, defwo, textP, deftp, \"center\");\n\n //Longest Time Alive Statistic\n textP = \"Longest time alive:\";\n printText(defxo, 0.35, defwo, textP, deftp, \"left\");\n textP = calculateLongestPlayerAliveTime() + \"s\";\n printText(defxo, 0.35, wo, textP, deftp, \"right\");\n\n //Number of Deaths Statistic\n textP = \"Number of deaths:\";\n printText(defxo, 0.45, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"playerHit\");\n printText(defxo, 0.45, wo, textP, deftp, \"right\");\n\n //Enemies Destroyed Statistic\n textP = \"Enemies Destroyed:\";\n printText(defxo, 0.55, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"enemiesKilled\");\n printText(defxo, 0.55, wo, textP, deftp, \"right\");\n\n //Bonuses Collected Statistic\n textP = \"Bonuses collected:\";\n printText(defxo, 0.65, defwo, textP, deftp, \"left\");\n textP = metrics.get(\"bonusCollected\");\n printText(defxo, 0.65, wo, textP, deftp, \"right\");\n\n //Final Score Statistic\n textP = \"Final Score:\";\n printText(defxo, 0.75, defwo, textP, deftp, \"left\");\n textP = Crafty(\"Score\")._score;\n printText(defxo, 0.75, wo, textP, deftp, \"right\");\n}", "refreshUpdateStatus() {}", "updateReport(query, update) {\n\n }", "function updateStats() {\n\t\n\tFFXIV_HPPercent = document.querySelector(\"#hp_percent\").textContent;\n\tFFXIV_MPPercent = document.querySelector(\"#mp_percent\").textContent;\n\tFFXIV_TPPercent = document.querySelector(\"#tp_percent\").textContent;\n\tFFXIV_HPCurrent = document.querySelector(\"#hp_current\").textContent;\n\tFFXIV_MPCurrent = document.querySelector(\"#mp_current\").textContent;\n\tFFXIV_TPCurrent = document.querySelector(\"#tp_current\").textContent;\n\tFFXIV_HPMax = document.querySelector(\"#hp_max\").textContent;\n\tFFXIV_MPMax = document.querySelector(\"#mp_max\").textContent;\n\tFFXIV_TPMax = \"1000\";\n\tFFXIV_HudType = document.querySelector(\"#hud_type\").textContent;\n\tFFXIV_Location = document.querySelector(\"#current_location\").textContent;\n\tFFXIV_HudMode = document.querySelector(\"#hud_mode\").textContent;\n\tFFXIV_TargetHPPercent = document.querySelector(\"#target_hppercent\").textContent;\n\tFFXIV_TargetHPCurrent = document.querySelector(\"#target_hpcurrent\").textContent;\n\tFFXIV_TargetHPMax = document.querySelector(\"#target_hpmax\").textContent;\n\tFFXIV_TargetName = document.querySelector(\"#target_name\").textContent;\n\tFFXIV_TargetEngaged = document.querySelector(\"#target_engaged\").textContent;\n\tFFXIV_PlayerPosX = document.querySelector(\"#playerposX\").textContent;\n\tFFXIV_PlayerPosY = document.querySelector(\"#playerposY\").textContent;\n\tFFXIV_PlayerPosZ = document.querySelector(\"#playerposZ\").textContent;\n\tFFXIV_ActionStatus = document.querySelector(\"#actionstatus\").textContent;\n\tFFXIV_CastPercent = document.querySelector(\"#castperc\").textContent;\n\tFFXIV_CastProgress = document.querySelector(\"#castprogress\").textContent;\n\tFFXIV_CastTime = document.querySelector(\"#casttime\").textContent;\n\tFFXIV_CastingToggle = document.querySelector(\"#castingtoggle\").textContent;\n\tFFXIV_HitboxRadius = document.querySelector(\"#hitboxrad\").textContent;\n\tFFXIV_PlayerClaimed = document.querySelector(\"#playerclaimed\").textContent;\n\tFFXIV_PlayerJob = document.querySelector(\"#playerjob\").textContent;\n\tFFXIV_MapID = document.querySelector(\"#mapid\").textContent;\n\tFFXIV_MapIndex = document.querySelector(\"#mapindex\").textContent;\n\tFFXIV_MapTerritory = document.querySelector(\"#mapterritory\").textContent;\n\tFFXIV_PlayerName = $(\"#playername\").text();\n\tFFXIV_TargetType = document.querySelector(\"#targettype\").textContent;\n\t\n\t//document.querySelector(\"#debug1\").textContent = \"Increment: \" + i;\n\t//$(\"#debug1\").text(\"Increment: \" + i);\n\t//i++;\n\t/*\n\tvar FFXIV = {\n \tHPPercent:FFXIV_HPPercent,\n\t\tMPPercent:FFXIV_MPPercent,\n\t\tTPPercent:FFXIV_TPPercent,\n\t\tHPCurrent:FFXIV_HPCurrent,\n\t\tMPCurrent:FFXIV_MPCurrent,\n\t\tTPCurrent:FFXIV_TPCurrent,\n\t\tHPMax:FFXIV_HPMax,\n\t\tMPMax:FFXIV_MPMax,\n\t\tTPMax:FFXIV_TPMax,\n\t\tHudType:FFXIV_HudType,\n\t\tLocation:FFXIV_Location,\n\t\tHudMode:FFXIV_HudMode,\n\t\tTargetHPPercent:FFXIV_TargetHPPercent,\n\t\tTargetHPCurrent:FFXIV_TargetHPCurrent,\n\t\tTargetHPMax:FFXIV_TargetHPMax,\n\t\tTargetName:FFXIV_TargetName,\n\t\tTargetEngaged:FFXIV_TargetEngaged,\n\t\tPlayerPosX:FFXIV_PlayerPosX,\n\t\tPlayerPosY:FFXIV_PlayerPosY,\n\t\tPlayerPosZ:FFXIV_PlayerPosZ,\n\t\tActionStatus:FFXIV_ActionStatus,\n\t\tCastPercent:FFXIV_CastPercent,\n\t\tCastProgress:FFXIV_CastProgress,\n\t\tCastTime:FFXIV_CastTime,\n\t\tCastingToggle:FFXIV_CastingToggle,\n\t\tHitboxRadius:FFXIV_HitboxRadius,\n\t\tPlayerClaimed:FFXIV_PlayerClaimed,\n\t\tPlayerJob:FFXIV_PlayerJob,\n\t\tMapID:FFXIV_MapID,\n\t\tMapIndex:FFXIV_MapIndex,\n\t\tMapTerritory:FFXIV_MapTerritory,\n\t\tPlayerName:FFXIV_PlayerName,\n\t\tTargetType:FFXIV_TargetType\n\t};\n\t*/\n\t/*\n\tFFXIV_HPPercent = document.querySelector(\"#hp_percent\").textContent;\n\tFFXIV_MPPercent = document.querySelector(\"#mp_percent\").textContent;\n\tFFXIV_TPPercent = document.querySelector(\"#tp_percent\").textContent;\n\tFFXIV_HPCurrent = document.querySelector(\"#hp_current\").textContent;\n\tFFXIV_MPCurrent = document.querySelector(\"#mp_current\").textContent;\n\tFFXIV_TPCurrent = document.querySelector(\"#tp_current\").textContent;\n\tFFXIV_HPMax = document.querySelector(\"#hp_max\").textContent;\n\tFFXIV_MPMax = document.querySelector(\"#mp_max\").textContent;\n\tFFXIV_TPMax = \"1000\";\n\tFFXIV_HudType = document.querySelector(\"#hud_type\").textContent;\n\tFFXIV_Location = document.querySelector(\"#current_location\").textContent;\n\tFFXIV_HudMode = document.querySelector(\"#hud_mode\").textContent;\n\tFFXIV_TargetHPPercent = document.querySelector(\"#target_hppercent\").textContent;\n\tFFXIV_TargetHPCurrent = document.querySelector(\"#target_hpcurrent\").textContent;\n\tFFXIV_TargetHPMax = document.querySelector(\"#target_hpmax\").textContent;\n\tFFXIV_TargetName = document.querySelector(\"#target_name\").textContent;\n\tFFXIV_TargetEngaged = document.querySelector(\"#target_engaged\").textContent;\n\tFFXIV_PlayerPosX = document.querySelector(\"#playerposX\").textContent;\n\tFFXIV_PlayerPosY = document.querySelector(\"#playerposY\").textContent;\n\tFFXIV_PlayerPosZ = document.querySelector(\"#playerposZ\").textContent;\n\tFFXIV_ActionStatus = document.querySelector(\"#actionstatus\").textContent;\n\tFFXIV_CastPercent = document.querySelector(\"#castperc\").textContent;\n\tFFXIV_CastProgress = document.querySelector(\"#castprogress\").textContent;\n\tFFXIV_CastTime = document.querySelector(\"#casttime\").textContent;\n\tFFXIV_CastingToggle = document.querySelector(\"#castingtoggle\").textContent;\n\tFFXIV_HitboxRadius = document.querySelector(\"#hitboxrad\").textContent;\n\tFFXIV_PlayerClaimed = document.querySelector(\"#playerclaimed\").textContent;\n\tFFXIV_PlayerJob = document.querySelector(\"#playerjob\").textContent;\n\tFFXIV_MapID = document.querySelector(\"#mapid\").textContent;\n\tFFXIV_MapIndex = document.querySelector(\"#mapindex\").textContent;\n\tFFXIV_MapTerritory = document.querySelector(\"#mapterritory\").textContent;\n\tFFXIV_PlayerName = document.querySelector(\"#playername\").textContent;\n\tFFXIV_TargetType = document.querySelector(\"#targettype\").textContent;\n\t*/\n}", "totalUpdates() {\n return 30;\n }", "function sendStats() {\n client.publish(\"/internal/meta/statistics\", {\n source: sourceId,\n stats: {\n connections: connections,\n wsConnections: wsConnections\n }\n });\n }", "function updateStats(){\r\n $(\" #correct-counter \").text(roundStats.correct);\r\n $(\" #incorrect-counter \").text(roundStats.incorrect);\r\n \r\n }", "function updateReport() {\n $(\"#currentTotal\").text(Math.floor(data.totalCurrent));\n $(\"#cps\").text((data.totalCPS).toFixed(1));\n}", "function logStats() {\n const tbl = table(config.statTableName, stats.get(), config.units);\n config.logFunction(tbl);\n}", "function updateStats() {\n\n\tvar queries = [\n\t\t{ k: \"world\", t: \"World\", q: \"\" },\n\t\t{ k: \"male\", t: \"Male\", q: \"gender=1\" },\n\t\t{ k: \"female\", t: \"Female\", q: \"gender=2\" },\n\t\t{ k: \"age1\", t: \"≤34\", q: \"age_ub=34\" },\n\t\t{ k: \"age2\", t: \"35-54\", q: \"age_lb=35&age_ub=54\" },\n\t\t{ k: \"age3\", t: \"≥55\", q: \"age_lb=55\" },\n\t\t{ k: \"hdi1\", t: \"Low\", q: \"hdi=1\" },\n\t\t{ k: \"hdi2\", t: \"Medium\", q: \"hdi=2\" },\n\t\t{ k: \"hdi3\", t: \"High\", q: \"hdi=3\" },\n\t\t{ k: \"hdi4\", t: \"Very High\", q: \"hdi=4\" }\n\t];\n\n\tfor(var i in queries) {\n\t\tvar query = queries[i];\n\t\tgetData(\"normal\", { \"table\": \"segment\", \"query\": query }, function(r, options) {\n\t\t\tdata.segments[options.query.k] = {\n\t\t\t\tid: options.query.k,\n\t\t\t\ttitle: options.query.t,\n\t\t\t\tvalues: r\n\t\t\t};\n\t\t});\n\t}\n\n}", "function updateStats() {\n\t// Set the date we're counting down to\n\tvar startDate = new Date(\"Jan 13 15:15:15 2017\");\n\n\t// Update the count down every 1 day\n\n\t// Get today's date and time\n\tvar now = new Date();\n\n\t// Find the distance between now an the count down date\n\tvar distanceSec = (now - startDate)/1000 ;\n\n\t// Time calculations for weeks, days, hours\n\tvar weeks = Math.floor(distanceSec / (60 * 60 * 24 * 7));\n\tvar days = Math.floor(distanceSec / (60 * 60 * 24) - weeks * 2);\n\tvar hours = Math.floor(days * 7);\n\n\t// Display the result in the element with id\n\tdocument.getElementById(\"weeks\").innerHTML = String(weeks);\n\tdocument.getElementById(\"coffee\").innerHTML = String(days);\n\tdocument.getElementById(\"hours\").innerHTML = String(hours);\n}", "function updateStats(gfc) {\n var gr, ch;\n assert(0 <= gfc.bitrate_index && gfc.bitrate_index < 16);\n assert(0 <= gfc.mode_ext && gfc.mode_ext < 4);\n\n /* count bitrate indices */\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][4]++;\n gfc.bitrate_stereoMode_Hist[15][4]++;\n\n /* count 'em for every mode extension in case of 2 channel encoding */\n if (gfc.channels_out == 2) {\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][gfc.mode_ext]++;\n gfc.bitrate_stereoMode_Hist[15][gfc.mode_ext]++;\n }\n for (gr = 0; gr < gfc.mode_gr; ++gr) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n var bt = gfc.l3_side.tt[gr][ch].block_type | 0;\n if (gfc.l3_side.tt[gr][ch].mixed_block_flag != 0)\n bt = 4;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][bt]++;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][5]++;\n gfc.bitrate_blockType_Hist[15][bt]++;\n gfc.bitrate_blockType_Hist[15][5]++;\n }\n }\n }", "function updateStats(gfc) {\n var gr, ch;\n assert(0 <= gfc.bitrate_index && gfc.bitrate_index < 16);\n assert(0 <= gfc.mode_ext && gfc.mode_ext < 4);\n\n /* count bitrate indices */\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][4]++;\n gfc.bitrate_stereoMode_Hist[15][4]++;\n\n /* count 'em for every mode extension in case of 2 channel encoding */\n if (gfc.channels_out == 2) {\n gfc.bitrate_stereoMode_Hist[gfc.bitrate_index][gfc.mode_ext]++;\n gfc.bitrate_stereoMode_Hist[15][gfc.mode_ext]++;\n }\n for (gr = 0; gr < gfc.mode_gr; ++gr) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n var bt = gfc.l3_side.tt[gr][ch].block_type | 0;\n if (gfc.l3_side.tt[gr][ch].mixed_block_flag != 0)\n bt = 4;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][bt]++;\n gfc.bitrate_blockType_Hist[gfc.bitrate_index][5]++;\n gfc.bitrate_blockType_Hist[15][bt]++;\n gfc.bitrate_blockType_Hist[15][5]++;\n }\n }\n }", "getStats()\n {\n var objMetaMaskList = this.getListStructure();\n var objEslTools = new EslTools();\n\n if(document.getElementById(\"ext-ethersecuritylookup-domain_verification_checkbox\")) {\n document.getElementById(\"ext-ethersecuritylookup-domain_verification_checkbox\").checked = objMetaMaskList.status;\n document.getElementById(\"ext-ethersecuritylookup-domain_verification_last_updated\").innerText = objEslTools.timeDifference(Math.floor(Date.now() / 1000), objMetaMaskList.timestamp);\n document.getElementById(\"ext-ethersecuritylookup-domain_verification_count\").innerText = Object.keys(objMetaMaskList.list.blacklist).length;\n }\n }", "function stateStats(resultStats){\n started = true;\n var today = resultStats[\"today\"]\n var cmtoday = today[\"onecup\"];\n cmtoday += today[\"double\"];\n cmtoday += today[\"strong\"];\n cmtoday += today[\"xstrong\"];\n var week = resultStats[\"week\"]\n var cmweek = week[\"onecup\"];\n cmweek += week[\"double\"];\n cmweek += week[\"strong\"];\n cmweek += week[\"xstrong\"];\n var total = resultStats[\"total\"]\n var cmtotal = total[\"onecup\"];\n cmtotal += total[\"double\"];\n cmtotal += total[\"strong\"];\n cmtotal += total[\"xstrong\"];\n trester_progress = parseInt(resultStats[\"trester\"]) / 640 * 100;\n console.log(resultStats[\"trester\"]);\n\n\n // write list\n document.querySelector('.cm-update-stats-icon').innerHTML = \"<i class=\\\"icon ion-android-sync big-icon cm-update-stats\\\" query=\\\"update\\\"></i>\";\n document.querySelector('.cm-today').innerHTML = cmtoday;\n if (!today[\"onecup\"] == 0 ){\n document.querySelector('.cm-single-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + today[\"onecup\"].toString()+\"</span> </li> \";\n }\n if (!today[\"double\"] == 0 ){\n document.querySelector('.cm-double-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + today[\"double\"].toString()+\"</span> </li> \";\n }\n if (!today[\"strong\"] == 0 ){\n document.querySelector('.cm-strong-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + today[\"strong\"].toString()+\"</span> </li> \";\n }\n if (!today[\"xstrong\"] == 0 ){\n document.querySelector('.cm-xstrong-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + today[\"xstrong\"].toString()+\"</span> </li> \";\n }\n if (!today[\"flushs\"] == 0 ){\n document.querySelector('.cm-flush-today').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + today[\"flushs\"].toString()+\"</span> </li> \";\n }\n\n document.querySelector('.cm-week').innerHTML = cmweek;\n\n if (!week[\"onecup\"] == 0) {\n document.querySelector('.cm-single-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + week[\"onecup\"].toString()+\"</span> </li> \";\n }\n if (!week[\"double\"] == 0) {\n document.querySelector('.cm-double-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + week[\"double\"].toString()+\"</span> </li> \";\n }\n if (!week[\"strong\"] == 0) {\n document.querySelector('.cm-strong-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + week[\"strong\"].toString()+\"</span> </li> \";\n }\n if (!week[\"xstrong\"] == 0) {\n document.querySelector('.cm-xstrong-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + week[\"xstrong\"].toString()+\"</span> </li> \";\n }\n if (!week[\"flushs\"] == 0) {\n document.querySelector('.cm-flush-week').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + week[\"flushs\"].toString()+\"</span> </li> \";\n }\n document.querySelector('.cm-total').innerHTML = cmtotal;\n document.querySelector('.cm-single-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Normal</span> <span class=\\\"pull-right\\\">\" + total[\"onecup\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-double-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Double</span> <span class=\\\"pull-right\\\">\" + total[\"double\"]+\"</span> </li> \";\n document.querySelector('.cm-strong-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Strong</span> <span class=\\\"pull-right\\\">\" + total[\"strong\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-xstrong-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Xtra strong</span> <span class=\\\"pull-right\\\">\" + total[\"xstrong\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-flush-total').innerHTML = \"<li class=\\\"padded-list\\\"> <span class=\\\"pull-left\\\">Flushs</span> <span class=\\\"pull-right\\\">\" + total[\"flushs\"].toString()+\"</span> </li> \";\n document.querySelector('.cm-trester-progress').innerHTML = \"<div class=\\\"determinate\\\" style=\\\"width: \"+trester_progress +\"%;\\\"></div>\";\n }", "function addStats() {\r\n\r\n // Get the peak usage html element\r\n const peakUsageElem = document.evaluate(\"//span[@data-byte-format='telemeterCtrl.selectedPeriod.usage.peakUsage']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);\r\n // Get the exact amount used\r\n const peakUsage = parseFloat(peakUsageElem.singleNodeValue.textContent.substr(0, 6).replace(',', '.'));\r\n\r\n // Get current number of days usage\r\n const daysUsage = document.evaluate(\"count(//*[contains(@class, 'TelenetUsageDetails') and contains(@class, 'NoMobile')]//*[local-name()='g' and contains(@class, 'nv-group') and contains(@class, 'nv-series-0')]/*)\", document, null, XPathResult.NUMBER_TYPE, null).numberValue;\r\n\r\n // Get reset date\r\n const resetDateElem = document.evaluate(\"//span[@data-translate='telemeter.reset-volume']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent.split(\" \");\r\n const resetDateString = resetDateElem[resetDateElem.length - 1];\r\n const dateParts = resetDateString.split(\"/\");\r\n const resetDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]); // dd/mm/yyyy\r\n\r\n // Calculate remaining days in current period\r\n const diffTime = Math.abs(resetDate - new Date());\r\n const remainingDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));\r\n\r\n\r\n // Display new stats\r\n const currentPeriod = document.evaluate(\"//*[@class='currentPeriod']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\r\n \r\n var totalUsage = document.evaluate(\"//*[@class='currentusage']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\r\n totalUsage.setAttribute(\"style\", \"margin:12px\"); // extra styling :)\r\n const span = document.evaluate(\"//*[@class='currentusage']/span\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\r\n\r\n // Get language preference\r\n const language = document.evaluate(\"//*[@class='lang-selected']/span\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;\r\n \r\n const totalDays = daysUsage + remainingDays - 1;\r\n const peakHoursLimit = daysUsage * (750 / totalDays);\r\n displayStat(totalUsage, span, (language == \"nl\" ? \"Dag\" : \"Jour\"), daysUsage + \" / \" + totalDays);\r\n displayStat(totalUsage, span, (language == \"nl\" ? \"Piekuren\" : \"Heures pleines\"), Math.round(peakUsage) + \" GB / \" + Math.round(peakHoursLimit) + \" GB\");\r\n\r\n}", "function onUpdateStatus(id, r)\r\n{\r\n\tif (r == null) return onUpdateFail(id,'Resp Error');\r\n\tif (r == false) return onUpdateFail(id,'No Response');\r\n\r\n\tvar utilization = (r.bytes / r.limit_maxbytes) * 100;\r\n\t$('utilization_'+id).update(utilization.toFixed(2) + '%');\r\n\t\r\n\tvar w = Math.round( utilization * ($('utilization_bar_'+id).getWidth()/100) );\r\n\t$('utilization_bar_b_'+id).setStyle({width: w+'px'});\r\n\t\r\n\t$('pid_'+id).update(r.pid);\r\n\t$('uptime_'+id).update(r.uptime);\r\n\t$('time_'+id).update(r.pidtime);\r\n\t$('version_'+id).update(r.version);\r\n\t$('pointer_size_'+id).update(r.pointer_size);\r\n\t$('curr_items_'+id).update(r.curr_items);\r\n\t$('total_items_'+id).update(r.total_items);\r\n\t$('bytes_'+id).update(r.bytes);\r\n\t$('curr_connections_'+id).update(r.curr_connections);\r\n\t$('total_connections_'+id).update(r.total_connections);\r\n\t$('connection_structures_'+id).update(r.connection_structures);\r\n\t$('cmd_get_'+id).update(r.cmd_get);\r\n\t$('cmd_set_'+id).update(r.cmd_set);\r\n\t$('get_hits_'+id).update(r.get_hits);\r\n\t$('get_misses_'+id).update(r.get_misses);\r\n\t$('bytes_read_'+id).update(r.bytes_read);\r\n\t$('bytes_written_'+id).update(r.bytes_written);\r\n\t$('limit_maxbytes_'+id).update(r.limit_maxbytes);\r\n\r\n\t$('result_'+id).update('OK');\r\n\t$('result_'+id).addClassName('ok')\r\n\r\n\tupdateNext(id);\r\n}", "function updateStats() {\n const total_cases = cases_list[cases_list.length - 1];\n const new_confirmed_cases = total_cases - cases_list[cases_list.length - 2];\n\n const total_recovered = recovered_list[recovered_list.length - 1];\n const new_recovered_cases = total_recovered - recovered_list[recovered_list.length - 2];\n\n const total_deaths = deaths_list[deaths_list.length - 1];\n const new_deaths_cases = total_deaths - deaths_list[deaths_list.length - 2];\n\n const active_cases = total_cases - total_recovered - total_deaths;\n\n total_cases_element.innerHTML = total_cases;\n new_cases_element.innerHTML = `+${new_confirmed_cases}`;\n recovered_element.innerHTML = total_recovered;\n new_recovered_element.innerHTML = `+${new_recovered_cases}`;\n deaths_element.innerHTML = total_deaths;\n new_deaths_element.innerHTML = `+${new_deaths_cases}`;\n\n active_element.innerHTML = active_cases;\n\n}", "setStats( stats ) {\n var now = performance.now();\n this.totalHashes += stats.hashes;\n if(this.prevStatTime) {\n var delta = now-this.prevStatTime;\n this.hashrate = 1000 * stats.hashes / delta;\n }\n this.prevStatTime = now;\n }", "function reportStats(period, label) {\n var today = new Date();\n if (today.getHours() > 14) today.setHours(24); // sets day +1 for timezone -9 h from Ljubljana\n if (period === \"THIS_MONTH\") { // variables for reporting current stats\n var year = today.getFullYear();\n var month = today.getMonth() + 1;\n var day = today.getDate();\n var string = \"GAdW Statistics for current month, retrieved on: \" + today.toUTCString() + \"\\n\\n\";\n var csv = \"\";\n } else if (period === \"LAST_MONTH\") { // variables for reporting last montht stats\n \tvar previous = getPrevMonth();\n var year = previous.getFullYear();\n var month = previous.getMonth() + 1;\n var day = previous.getDate();\n var string = \"GAdW Statistics for \" + year + \"-\" + ((month >= 10) ? month : \"0\" + month) + \", retrieved on: \" + today.toUTCString() + \"\\n\\n\";\n var csv = \"\";\n }\n var json = {\"date\": [year, month, day], \"stats\": {}}\n var accountIterator = MccApp.accounts().withCondition('LabelNames CONTAINS \"' + label + '\"').get();\n while (accountIterator.hasNext()) {\n var account = accountIterator.next();\n var accName = account.getName();\n MccApp.select(account);\n var OP = getOP(AdWordsApp.campaigns().get());\n var stats = getImpressionsClicksCTRCostCPC(account, period);\n var paused = true;\n var campaignIterator = AdWordsApp.campaigns().get();\n while (campaignIterator.hasNext()) {\n if (campaignIterator.next().isEnabled()) {\n paused = false;\n break;\n }\n }\n // building string\n string = string +\n \t\t (paused ? accName + \" [PAUSED]\" : accName) + \"\\n\" +\n \t\t \"impressions: \" + stats[0] + \"\\n\" +\n \"clicks: \" + stats[1] + \"\\n\" +\n \"CTR: \" + Math.round(stats[2] * 10000) / 100 + \" %\" + \"\\n\" +\n \"cost: \" + stats[3] + \" €\" + \"\\n\" +\n \"CPC: \" + stats[4] + \" €\" + \"\\n\" +\n \"\\n\";\n\t// building CSV\n csv = csv + OP + \";\" + accName + \";\" + stats[0] + \";\" + stats[1] + \"\\n\";\n // building JSON\n if (period === \"THIS_MONTH\") {\n if (paused) json[\"stats\"][OP] = [\"paused\"];\n else json[\"stats\"][OP] = [stats[1], stats[2], stats[3], stats[0], stats[4]];\n } else if (period === \"LAST_MONTH\") {\n json[\"stats\"][OP] = [stats[1], stats[2], stats[3], stats[0], stats[4]];\n }\n }\n return [string, csv, JSON.stringify(json)];\n}", "function generateRawStatistics() {\n console.log(self.selectDatasource);\n if(self.selectDatasource !== \"Select\" || self.selectDatasource !== null){\n homeService.getRawDataStatistics(self.selectDatasource).then(function(response){\n if(!response.data.isError && response.status == 200){\n //angular.copy(response.data.data, self.rawStatistics);\n //prepend newly created task to the task history array\n self.taskHistory.data.push(response.data);\n }\n else{\n console.log(\"Error: \" + response.data);\n }\n });\n }\n }", "function updateStats() {\n $(\"#fighterhealth\").text(\"HP:\\xa0\" + fighterHP);\n $(\"#defenderhealth\").text(\"HP:\\xa0\" + defenderHP);\n }", "function startStatusUpdates(){\n if(!pound.userOptions.printStatusUpdateEveryNseconds){return;}\n var intervalCount = 1;\n pound.statusUpdateIntervalId = setInterval(function(){\n console.log('============= status update %s ==================', intervalCount++);\n printTotals();\n }, pound.userOptions.printStatusUpdateEveryNseconds * 1000);\n\n }", "function reWriteStats() {\n\n targetNumber = Math.floor(Math.random() * (120 - 19 + 1)) + 19;\n //console.log('Reset targetNumber: ' + targetNumber);\n $('#target-number').text(targetNumber);\n\n playerCounter = 0;\n //$('#player-score').empty();\n\n //$('#game-round-alert').empty();\n\n assignToImages();\n \n }", "CalcStats( log = null ) { \n\t\tlog = log || this.log;\n\t\tif ( !log ) { return; }\n\t\t// first time setup\n\t\tif ( !this.stats ) { \n\t\t\tlet blank = {\n\t\t\t\tlosses:0,\n\t\t\t\tkills:0,\n\t\t\t\ttotal_dmg_out:0,\n\t\t\t\ttotal_dmg_in:0,\n\t\t\t\thull_dmg_out:0,\n\t\t\t\thull_dmg_in:0,\n\t\t\t\tarmor_dmg_out:0,\n\t\t\t\tarmor_dmg_in:0,\n\t\t\t\tshield_dmg_out:0,\n\t\t\t\tshield_dmg_in:0,\n\t\t\t\tattacks_made:0,\n\t\t\t\tattacks_received:0,\n\t\t\t\tattacks_missed:0,\n\t\t\t\tattacks_dodged:0,\n\t\t\t\tmilval_killed:0,\n\t\t\t\tmilval_lost:0\n\t\t\t\t};\n\t\t\tthis.stats = {};\n\t\t\tthis.stats[this.teams[0].label] = Object.assign({}, blank);\n\t\t\tthis.stats[this.teams[1].label] = Object.assign({}, blank);\n\t\t\t}\n\t\tlog.forEach( x => {\n\t\t\t// tabulate\n\t\t\tlet teamdata = this.stats[x.team.label];\n\t\t\tif ( teamdata ) { \n\t\t\t\tteamdata.hull_dmg_out += x.hull;\n\t\t\t\tteamdata.armor_dmg_out += x.armor;\n\t\t\t\tteamdata.shield_dmg_out += x.shield;\n\t\t\t\tteamdata.total_dmg_out += x.hull + x.armor;\n\t\t\t\tteamdata.attacks_made++;\n\t\t\t\tif ( x.missed ) { teamdata.attacks_missed++; } \n\t\t\t\tif ( x.killed ) { \n\t\t\t\t\tteamdata.kills++; \n\t\t\t\t\tteamdata.milval_killed += x.target.bp.milval; \n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t});\n\t\t// swap records\n\t\tlet keys = Object.keys( this.stats );\n\t\tlet t0 = this.stats[keys[0]];\n\t\tlet t1 = this.stats[keys[1]];\n\t\tt0.losses = t1.kills;\n\t\tt1.losses = t0.kills;\n\t\tt0.total_dmg_in = t1.total_dmg_out;\n\t\tt1.total_dmg_in = t0.total_dmg_out;\n\t\tt0.hull_dmg_in = t1.hull_dmg_out;\n\t\tt1.hull_dmg_in = t0.hull_dmg_out;\n\t\tt0.armor_dmg_in = t1.armor_dmg_out;\n\t\tt1.armor_dmg_in = t0.armor_dmg_out;\n\t\tt0.shield_dmg_in = t1.shield_dmg_out;\n\t\tt1.shield_dmg_in = t0.shield_dmg_out;\n\t\tt0.attacks_received = t1.attacks_made;\n\t\tt1.attacks_received = t0.attacks_made;\n\t\tt0.attacks_dodged = t1.attacks_missed;\n\t\tt1.attacks_dodged = t0.attacks_missed;\n\t\tt0.milval_lost = t1.milval_killed;\n\t\tt1.milval_lost = t0.milval_killed;\n\t\t}", "function updateInfoMsg(){\n console.log(`updateInfoMsg: called`);\n\n var sMsg = \"Cache max age for matching items is set to \";\n \n let hour = 60 * 60;\n let day = 24 * hour;\n let week = 7 * day;\n let month = 30 * day;\n let year = 365 * day;\n if (gnCacheMaxSecs < hour)\n sMsg += (gnCacheMaxSecs + \" seconds.\");\n else if (gnCacheMaxSecs < day)\n sMsg += ((gnCacheMaxSecs/hour).toFixed(1) + \" hours.\");\n else if (gnCacheMaxSecs < week)\n sMsg += ((gnCacheMaxSecs/day).toFixed(1) + \" days.\");\n else if (gnCacheMaxSecs < month)\n sMsg += ((gnCacheMaxSecs/week).toFixed(1) + \" weeks.\");\n else if (gnCacheMaxSecs < year)\n sMsg += ((gnCacheMaxSecs/month).toFixed(1) + \" months.\");\n else\n sMsg += ((gnCacheMaxSecs/year).toFixed(1) + \" years.\");\n \n sMsg += \"<br /><br />\"\n sMsg += `${garrsURLPatterns.length} URL patterns defined.`;\n sMsg += \"<br /><br />\"\n sMsg += `${garrsExcludeURLPrefixes.length} exclusions defined.`;\n sMsg += \"<br /><br />\"\n sMsg += \"Modify matching items of types: \";\n sMsg += garrsResourceTypes;\n \n document.querySelector('#infodiv').innerHTML = sMsg;\n console.log(`updateInfoMsg: return`);\n}", "getStats()\n {\n var objTwitterWhitelist = this.getWhitelistStructure();\n var objEslTools = new EslTools();\n\n if(document.getElementById(\"ext-ethersecuritylookup-twitter_whitelist_checkbox\")) {\n document.getElementById(\"ext-ethersecuritylookup-twitter_whitelist_checkbox\").checked = objTwitterWhitelist.status;\n document.getElementById(\"ext-ethersecuritylookup-twitter_whitelist_last_updated\").innerText = objEslTools.timeDifference(Math.floor(Date.now() / 1000), objTwitterWhitelist.timestamp);\n document.getElementById(\"ext-ethersecuritylookup-twitter_whitelist_count\").innerText = Object.keys(objTwitterWhitelist.users).length;\n }\n }", "function renderStats(stats) {\n const f = stats.updateFrequency;\n let onTimeRate = (stats.updates-stats.misses) / stats.updates;\n onTimeRate = (onTimeRate*100).toFixed(1) + \"%\";\n $g(\"total-listen\").innerText = secondsToHuman(stats.totalListen);\n $g(\"count\").innerText = stats.updates;\n $g(\"update-freq\").innerText = `Updates about every ${f === 1 ? 'day' : `${f} days`}`;\n $g(\"ontime-rate-label\").innerText = onTimeRate;\n $g(\"ontime-rate\").style.width = onTimeRate;\n $g(\"ontime-rate-inverse\").style.width = `calc(100% - ${onTimeRate})`;\n}", "runStatistics() {\r\n console.clear();\r\n HangmanUtils.displayStatsOptions();\r\n let statsOption = input.questionInt(\">> \");\r\n let stats = new Statistics(this.recordsFileName);\r\n if (statsOption >= 1 && statsOption <= 6) {\r\n console.clear();\r\n }\r\n switch (statsOption) {\r\n case 1:\r\n stats.displayLeaderBoard();\r\n break;\r\n case 2:\r\n stats.displayAllRecords();\r\n break;\r\n case 3:\r\n stats.displayStatistics();\r\n break;\r\n case 4:\r\n stats.displayPlayerHighscores();\r\n break;\r\n case 5:\r\n stats.displayPlayerRecords();\r\n break;\r\n case 6:\r\n stats.displayPlayerStatistics();\r\n break;\r\n case 7:\r\n break;\r\n default:\r\n console.log(\"Please only enter 1, 2, 3, 4, 5, 6 or 7!\");\r\n }\r\n input.question(\"\\nPress \\\"Enter\\\" to proceed...\");\r\n }", "update(dt) {\n logID(1007);\n }", "function updateInfo() {\n\tconsole.log(\"Running update\");\n\t// Make sure current tab exists\n\tif (curTabId == null) {\n\t\treturn;\n\t} else {\n\t\t// Get data from the current tab\n\t\tconsole.debug(\"Update - \" + curTabId);\n\t\tchrome.tabs.get(curTabId, \n\t\tfunction(tab) { \n\t\t\tconsole.debug(tab);\n\t\t\t// Get base URL\n\t\t\tvar theSite = getSite(tab.url);\n\t\t\tvar curURL = tab.url;\n\t\t\t//Stop Social Band if returned to assignment page -->\n\t\t\t\tvar urlParts = curURL.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/);\n\t\t\t\tvar urlParts1 = urlParts[0].split(\".\");\n\t\t\t\tvar siteDomain = urlParts1[0];\n\t\t\t\tvar trackingSitesList = 'facebook,yahoo,youtube,twitter,instagram,tumblr,dailymotion,pinterest,vine';\n\t\t\t\t\n\t\t\t\tParse.initialize(\"LcQYRvseB9ExXGIherTt1v2pw2MVzPFwVXfigo11\", \"F5enB5XfOfqo4ReAItZCkJVxOY76hoveZrOMwih9\"); \n\t\t\t\tchrome.cookies.get({\"url\": 'http://timem.github.io/', \"name\": 'username'}, function(cookie) { //Cookie access starts A1\n\t\t\t\t\tusname = cookie.value;\n\t\t\t\t\tif(usname.indexOf(\"@\") > 0 && usname.indexOf(\".\")){\n\t\t\t\t\t\tvar query = new Parse.Query(\"LoginDetails\");\n\t\t\t\t\t\tquery.equalTo(\"UserName\", usname);\n\t\t\t\t\t\tquery.descending(\"SessionStartedOn\");\n\t\t\t\t\t\tquery.first({ //Parse Instance Starts A1\n\t\t\t\t\t\t success: function(result){\n\t\t\t\t\t\t\t\tvar currentSessionObjId = result.id;\n\t\t\t\t\t\t\t\tvar socialSitesTimeParse = result.get(\"SocialSitesTime\");\n\t\t\t\t\t\t\t\tvar lastActiveLap = $.parseJSON(result.get(\"LastLapDetails\"));\n\t\t\t\t\t\t\t\tvar lastButtonActiveMode = lastActiveLap.buttonMode;\n\t\t\t\t\t\t\t\tconsole.log(\"6th November\");\n\t\t\t\t\t\t\t\tconsole.log(curURL.indexOf(\"assignments.html\"));\n\t\t\t\t\t\t\t\tconsole.log(trackingSitesList.indexOf(siteDomain));\n\t\t\t\t\t\t\t\tconsole.log(lastActiveLap.lapStatus);\n\t\t\t\t\t\t\t\tif(curURL.indexOf(\"assignments.html\") != -1 && lastActiveLap.lapStatus == \"SocialInProgress\"){\n\t\t\t\t\t\t\t\t\tvar newBandTitle = \"SocialSites\";\n\t\t\t\t\t\t\t\t\tvar newlapStatus = \"InProcess\";\n\t\t\t\t\t\t\t\t\ts = new Date().getTime();\n\t\t\t\t\t\t\t\t\t//Update Lap details in parse starts -->\n\t\t\t\t\t\t\t\t\tvar e = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar newbandDetails = {};\n\t\t\t\t\t\t\t\t\tnewbandDetails.title = newBandTitle;\n\t\t\t\t\t\t\t\t\tvar stTime = lastActiveLap.startTime;\n\t\t\t\t\t\t\t\t\tnewbandDetails.timeSpent = e - parseInt(stTime);\n\t\t\t\t\t\t\t\t\tnewbandDetails.lapStartTime = parseInt(stTime);\n\t\t\t\t\t\t\t\t\tif(result.get(\"LapData\")){\n\t\t\t\t\t\t\t\t\t\tvar objLapData = $.parseJSON(result.get(\"LapData\"));\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\tvar objLapData = [];\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\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\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LapData\",objLapDataString);\n\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\tvar lastActiveLap = {};\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"06th Nov 2015-\"+newlapStatus);\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.buttonMode = lastButtonActiveMode;\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.lapStatus = newlapStatus;\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.startTime = s;\n\t\t\t\t\t\t\t\t\t\tvar tmpStringifyStr = JSON.stringify(lastActiveLap);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LastLapDetails\",tmpStringifyStr);\n\t\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Updated Successfully\");\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Update failed\");\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\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\t\tconsole.log(\"LapData Updated Successfully\");\t\n\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"LapData Update failed\");\n\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\t//Update Lap details in parse ends <--\n\t\t\t\t\t\t\t\t}else if(trackingSitesList.indexOf(siteDomain) != -1 && lastActiveLap.lapStatus == \"InProcess\"){\n\t\t\t\t\t\t\t\t\tvar newBandTitle = \"Study\";\n\t\t\t\t\t\t\t\t\tvar newlapStatus = \"SocialInProgress\";\n\t\t\t\t\t\t\t\t\ts = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar e = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar newbandDetails = {};\n\t\t\t\t\t\t\t\t\tnewbandDetails.title = newBandTitle;\n\t\t\t\t\t\t\t\t\tvar stTime = lastActiveLap.startTime;\n\t\t\t\t\t\t\t\t\tnewbandDetails.timeSpent = e - parseInt(stTime);\n\t\t\t\t\t\t\t\t\tnewbandDetails.lapStartTime = parseInt(stTime);\n\t\t\t\t\t\t\t\t\tif(result.get(\"LapData\")){\n\t\t\t\t\t\t\t\t\t\tvar objLapData = $.parseJSON(result.get(\"LapData\"));\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\tvar objLapData = [];\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\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\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LapData\",objLapDataString);\n\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\tvar lastActiveLap = {};\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"06th Nov 2015-\"+newlapStatus);\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.buttonMode = lastButtonActiveMode;\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.lapStatus = newlapStatus;\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.startTime = s;\n\t\t\t\t\t\t\t\t\t\tvar tmpStringifyStr = JSON.stringify(lastActiveLap);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LastLapDetails\",tmpStringifyStr);\n\t\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Updated Successfully\");\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Update failed\");\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\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\t\tconsole.log(\"LapData Updated Successfully\");\t\n\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"LapData Update failed\");\n\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\t//Update Lap details in parse ends <--\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t },\n\t\t\t\t\t\t error: function(){\n\t\t\t\t\t\t\t console.log('Parse Error');\n\t\t\t\t\t\t },\n\t\t\t\t\t\t\n\t\t\t\t\t\t}) //Parse Instance Ends A1\t\t\t\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\tconsole.log(\"Username does not exists.\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t})//Cookie access ends A1\t\t\t\n\t\t\t//Stop Social Band if returned to assignment page ends <--\n\t\t\t\n\t\t\t// Check if its valid\n\t\t\tif (theSite == null) {\n\t\t\t\tconsole.log(\"URL issue\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Set site if doesnt exist yet\n\t\t\tif (curSite == null) {\n\t\t\t\tconsole.log(\"Setting new site - \" + curSite);\n\t\t\t\tstartTime = new Date();\n\t\t\t\tcurSite = theSite;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// If new site, update time spent\n\t\t\tif (curSite != theSite) {\n\t\t\t\tvar diffTimeSec = ((new Date()).getTime() - startTime.getTime()) / 1000;\n\t\t\t\tupdateTime(curSite, diffTimeSec);\n\t\t\t\tcurSite = theSite;\n\t\t\t\tstartTime = new Date();\n\t\t\t}\n\t\t});\n\t}\n}", "function initStats() {\n stats = {};\n stats.acumTemp = 0.0;\n stats.contaTemp = 0;\n stats.acumUmid = 0.0;\n stats.contaUmid = 0;\n stats.acumQuali = 0.0;\n stats.contaQuali = 0;\n stats.data = new Date();\n}", "setStats(updatedGameSessions) {\n\t\tthis.setTimePlayed(updatedGameSessions)\n\t\tthis.setGameModes(updatedGameSessions)\n this.setGamesPlayedByLoggedInUsers(updatedGameSessions)\n}", "function dashboardUpdateAll() {\n\t\tdashboardSet('stars', whiteStar + whiteStar + whiteStar);\n\t\tdashboardSet('tally', 0);\n\t\tdashboardSet('reset', semicircleArrow);\n\t\tdocument.getElementsByClassName('current-timer')[0].innerHTML = \"00:00\";\n}", "function updateEnemyStats() {\n\t\t$(\"#enemyHealth\").html(\"HP: \" + enemyPicked.health + \"<br />Attack: \" + enemyPicked.attack);\n\t\t$(\"#enemyName\").html(enemyPicked.display);\n\t}", "function updateHitrate()\n{\n\tvar s1 = collect(makeProperJson(vdata[0]),['VBE'],undefined);\n\tvar tmp = [10, 100, 1000];\t\n\tfor (x in tmp ) {\n\t\ta = tmp[x];\n\t\tvar origa = a;\n\t\tif (vdatap.length-1 < a) {\n\t\t\ta = vdatap.length-1;\n\t\t}\n\t\tproper = makeProperJson(vdata[a]);\n\t\ts2 = collect(proper,['VBE'],undefined);\n\t\tstorage = collect(proper,['SMA','SMF'],'Transient');\n\t\thitrate[origa].d = a;\n\t\thitrate[origa].h = ((vdatap[0]['cache_hit'] - vdatap[a]['cache_hit']) / (vdatap[0]['client_req'] - vdatap[a]['client_req'])).toFixed(5);\n\t\thitrate[origa].b = (s1['beresp_hdrbytes'] + s1['beresp_bodybytes'] - \n\t\t\t\t s2['beresp_hdrbytes'] - s2['beresp_bodybytes']) / a;\n\t\thitrate[origa].f = (vdatap[0]['s_resp_hdrbytes'] + vdatap[0]['s_resp_bodybytes']\n\t\t\t\t- (vdatap[a]['s_resp_hdrbytes'] + vdatap[a]['s_resp_bodybytes']))/a;\n\t\tdocument.getElementById(\"hitrate\" + origa + \"d\").textContent = hitrate[origa].d;\n\t\tdocument.getElementById(\"hitrate\" + origa + \"v\").textContent = (hitrate[origa].h*100).toFixed(3) + \"%\";\n\t\tdocument.getElementById(\"bw\" + origa + \"v\").textContent = toHuman(hitrate[origa].b) + \"B/s\";\n\t\tdocument.getElementById(\"fbw\" + origa + \"v\").textContent = toHuman(hitrate[origa].f) + \"B/s\";\n\t\t\n\t\tdocument.getElementById(\"storage\" + origa + \"v\").textContent = toHuman(storage['g_bytes']);\n\n\t}\n\tdocument.getElementById(\"MAIN.uptime-1\").textContent = secToDiff(vdatap[0]['uptime']);\n\tdocument.getElementById(\"MGT.uptime-1\").textContent = secToDiff(vdatap[0]['MGT.uptime']);\n}", "function recalculateStats() {\n\tvar totalVictims = victimStats.length;\n\tvar savedVictims = 0;\n\tvar missingVictims = 0;\n\t\n\tfor(var i = 0; i < totalVictims; i++)\n\t\tif(isVictimSafe(victimStats[i]))\n\t\t\tsavedVictims++;\n\t\n\tmissingVictims = totalVictims - savedVictims;\n\t\n\t$('#lblStatsVictims').html(totalVictims);\n\t$('#lblStatsSaved').html(savedVictims);\n\t$('#lblStatsMissings').html(missingVictims);\n}", "function getStats (numberToBegin) {\n/*\n\t var Statistics = Parse.Object.extend(\"Statistics\");\n\t var queryCheckInStatistics = new Parse.Query(Statistics);\n\t \n\t queryCheckInStatistics.limit(1000);\n\t queryCheckInStatistics.skip(numberToBegin);\n\t \n\t queryCheckInStatistics.find({\n\t\t success: function(results) {\n\t\t\t for (var i = 0; i < results.length; i++) { \n\t\t\t \t\t\n\t\t\t \t if (results[i].attributes.invitedEventCount >0){\n\t\t\t\t \t totalFriendsWithEvent++;\n\t\t\t \t }\n\t\t\t \t if (results[i].attributes.createdEventCount >0){\n\t\t\t\t \t totalFriendsWithEventCreate++;\n\t\t\t \t }\n\t\t\t \t \n\t\t\t \t totalStatsScroll++;\n\t\t\t \t totalNumber += results[i].attributes.invitedEventCount;\n\t\t\t \t \n\t\t\t \t if (results[i].attributes.createdEventCount){\n\t\t\t \ttotalEventCreated += results[i].attributes.createdEventCount;\n\t\t\t }\n\t\t\t \n\t\t\t \t $(\".stats\").empty();\n\t\t\t \t $(\".stats\").append(numberWithCommas(totalStatsScroll));\n\t\t\t \t $(\".number\").empty();\n\t\t\t \t $(\".number\").append(numberWithCommas(totalNumber));\n\t\t\t \t $(\".event\").empty();\n\t\t\t \t $(\".event\").append(numberWithCommas(totalEventCreated));\n\t\t\t \t $(\".userAttend\").empty();\n\t\t\t \t $(\".userAttend\").append(numberWithCommas(totalFriendsWithEvent));\n\t\t\t \t $(\".userCreate\").empty();\n\t\t\t \t $(\".userCreate\").append(numberWithCommas(totalFriendsWithEventCreate));\n\t\t\t \n\t\t\t \n\t\t\t }\n\t\t if (results.length == 1000) {\n\t\t\t numberToBegin += 1000;\n\t\t\t getStats(numberToBegin);\n\t\t }\n\t\t else {\n\t\t \t\t $(\".ratioAttend\").empty();\n\t\t\t \t var temp = totalNumber / totalFriendsWithEvent;\n\t\t\t \t $(\".ratioAttend\").append(temp);\n\t\t\t \t \n\t\t\t \t $(\".ratioCreate\").empty();\n\t\t\t \t var temp = totalEventCreated / totalFriendsWithEventCreate;\n\t\t\t \t $(\".ratioCreate\").append(temp);\n\t\t }\n\t\t \n\t\t },\n\t\t error: function() {\n\t\t\t //console.log(\" \\n !!!!! !!!!! \\n\" );\n\t\t\t }\n\t\t}); \n\t\t\n*/\t \n}", "function PerformanceReporter() {\n }", "function updateLogs() {\r\n updatePositionLogs();\r\n updateContactLogs();\r\n}", "update() {\n this.emit('fetch');\n if (this.guilds > 0 && this.users > 0) {\n if (!config.beta) {\n dogstatsd.gauge('musicbot.guilds', this.guilds);\n dogstatsd.gauge('musicbot.users', this.users);\n }\n let requestOptions = {\n headers: {\n Authorization: config.discord_bots_token\n },\n url: `https://bots.discord.pw/api/bots/${config.bot_id}/stats`,\n method: 'POST',\n json: {\n 'server_count': this.guilds\n }\n };\n request(requestOptions, (err, response, body) => {\n if (err) {\n return this.emit('error', err);\n }\n this.emit('info', 'Stats Updated!');\n this.emit('info', body);\n });\n if (!config.beta) {\n let requestOptionsCarbon = {\n url: 'https://www.carbonitex.net/discord/data/botdata.php',\n method: 'POST',\n json: {\n 'server_count': this.guilds,\n 'key': config.carbon_token\n }\n };\n request(requestOptionsCarbon, (err, response, body) => {\n if (err) {\n return this.emit('error', err)\n }\n this.emit('info', 'Stats Updated Carbon!');\n this.emit('info', body);\n });\n }\n }\n }", "function updateDashboard() {\n request\n .get(\"https://dsrealtimefeed.herokuapp.com/\")\n .end(function(res) {\n console.log(\"Pinged Dashboard, \" + res.status)\n if(res.status != 200) {\n stathat.trackEZCount(config.STATHAT, 'dsrealtime-feed-cant_ping', 1, function(status, response){});\n }\n });\n}", "function packageStats() {\n var idx,\n res;\n\n for (idx = 0; idx < stats.results.length; idx++) {\n res = stats.results[idx];\n\n // seems like inactive timestamps are init with unix epoch\n if (new Date(res.timestamp).getTime() != 0 && stats.timestamp == 0) {\n stats.timestamp = res.timestamp;\n }\n\n // Channels - Chrome\n if (res.type == 'googCandidatePair' && res.googActiveConnection == 'true') {\n stats.channels.push({\n id: res.googChannelId,\n local: {\n candidateType: res.googLocalCandidateType,\n ipAddress: res.googLocalAddress\n },\n remote: {\n candidateType: res.googRemoteCandidateType,\n ipAddress: res.googRemoteAddress\n },\n transport: res.googTransportType\n });\n }\n\n // Channels - Firefox\n if (res.type == 'candidatepair' &&\n res.state == 'succeeded'){\n // not really helpful?\n }\n\n // Audio - Chrome\n if (res.googCodecName == 'opus' && res.bytesSent) {\n stats.audio = merge(stats.audio, {\n inputLevel: res.audioInputLevel,\n packetsLost: res.packetsLost,\n rtt: res.googRtt,\n packetsSent: res.packetsSent,\n bytesSent: res.bytesSent\n });\n }\n\n // Audio - Firefox\n if (res.mediaType == 'audio' && res.bytesSent) {\n if (res.isRemote) {\n stats.audio = merge(stats.audio, {\n inputLevel: '?',\n rtt: res.mozRtt,\n packetsLost: res.packetsLost\n });\n } else {\n stats.audio = merge(stats.audio, {\n packetsSent: res.packetsSent,\n bytesSent: res.bytesSent\n });\n }\n }\n\n // Video - Chrome\n if (res.googCodecName == 'VP8' && res.bytesSent) {\n stats.video = merge(stats.video, {\n frameHeightInput: res.googFrameHeightInput,\n frameWidthInput: res.googFrameWidthInput,\n rtt: res.googRtt,\n packetsLost: res.packetsLost,\n packetsSent: res.packetsSent,\n frameRateInput: res.googFrameRateInput,\n frameRateSent: res.googFrameRateSent,\n frameHeightSent: res.googFrameHeightSent,\n frameWidthSent: res.googFrameWidthSent,\n bytesSent: res.bytesSent\n });\n }\n\n // Video - Firefox\n if (res.mediaType == 'video' && res.bytesSent) {\n if (res.isRemote) {\n stats.video = merge(stats.video, {\n rtt: res.mozRtt,\n packetsLost: res.packetsLost\n });\n } else {\n var localVideo = document.getElementById('localVideo');\n\n stats.video = merge(stats.video, {\n frameHeightInput: localVideo.videoHeight,\n frameWidthInput: localVideo.videoWidth,\n packetsSent: res.packetsSent,\n frameRateInput: Math.round(res.framerateMean),\n frameRateSent: '?',\n frameHeightSent: '?',\n frameWidthSent: '?',\n bytesSent: res.bytesSent\n });\n }\n }\n }\n\n // Because Firefox gets stats per mediaTrack we need to 'wait'\n // for both audio and video stats before invoking the callback.\n // There might be a better way to do this though.\n if (stats.audio.bytesSent && stats.video.bytesSent) {\n callback(stats);\n }\n }", "function updateStats() {\n $(\"#number-to-guess\").text(targetNumber);\n $(\"#user-score\").text(userScore);\n $(\"#wins\").text(wins);\n $(\"#losses\").text(losses);\n }", "function statusUpdate() {\n console.log(\"Session Seconds: \" + sessionSeconds);\n console.log(\"Short Break Seconds: \" + shortBreakSeconds);\n console.log(\"Long Break Seconds: \" + longBreakSeconds);\n console.log(\"Paused: \" + paused);\n console.log(\"Seconds Left: \" + seconds_left);\n console.log(\"Current Timer: \" + currentTimer);\n console.log(\"Temp Session Seconds: \" + tempoarySessionSeconds);\n console.log(\"Temp Short Break Seconds: \" + tempoaryShortBreakSeconds);\n console.log(\"Temp Long Break Seconds: \" + tempoaryLongBreakSeconds);\n}", "function getStats(){\n return stats;\n }", "function updateInformation() {\n\t\tupdateBattery();\n\n\t}", "function updatePageAnalyticsData(summaryData) {\n window.pageAnalyticsData = summaryData;\n lastRow = summaryData.rows.length-1;\n setPageStatInt(\"nodesLabel\", \"nodesValue\", \"Node Count\", \"\", summaryData.rows[lastRow][\"count_hostname\"]);\n setPageStatInt(\"cpuLabel\", \"cpuValue\", \"Avg Load\", \"%\", summaryData.rows[lastRow][\"avg_cpu\"]);\n}", "function onReport() {\n\t\t\tvar reportTime = t.getTimeBucket();\n\t\t\tvar curTime = reportTime;\n\t\t\tvar missedReports = 0;\n\n\t\t\tif (total === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// if we had more polls than we expect in each\n\t\t\t// collection period (we allow one extra for wiggle room), we\n\t\t\t// must not have been able to report, so assume those periods were 100%\n\t\t\twhile (total > (POLLS_PER_REPORT + 1) &&\n\t\t\t missedReports <= MAX_MISSED_REPORTS) {\n\t\t\t\tt.set(\"busy\", 100, --curTime);\n\n\t\t\t\t// reset the period by one\n\t\t\t\ttotal -= POLLS_PER_REPORT;\n\t\t\t\tlate = Math.max(late - POLLS_PER_REPORT, 0);\n\n\t\t\t\t// this was a busy period\n\t\t\t\toverallTotal += POLLS_PER_REPORT;\n\t\t\t\toverallLate += POLLS_PER_REPORT;\n\n\t\t\t\tmissedReports++;\n\t\t\t}\n\n\t\t\t// update the total stats\n\t\t\toverallTotal += total;\n\t\t\toverallLate += late;\n\n\t\t\tt.set(\"busy\", Math.round(late / total * 100), reportTime);\n\n\t\t\t// reset stats\n\t\t\ttotal = 0;\n\t\t\tlate = 0;\n\t\t}", "function updateReport(event) {\n \n cleanReport();\n \n // If the arrows where clicked, than update the arrows' timestamp\n updateTimeSpan(event);\n \n // extract report query from the DOM\n var reportQ = getReportQueryFromControlPanel();\n \n // write time span in human readable way\n var titleFrom = moment.unix(reportQ.start).format('YY MM DD HH:mm');\n var titleTo = moment.unix(reportQ.end).format('YY MM DD HH:mm');\n var verbalTimeSpanFormat = $(\"[name='radio-span']:checked\").data('verbal-format');\n var humanReadableTimespan = moment.unix(reportQ.end).format(verbalTimeSpanFormat);\n $('#report-title').html( /*titleFrom + '</br>' +*/ humanReadableTimespan /*+ '</br>' + titleTo*/ );\n\n // query data and update report\n getDataAndPopulateReport(reportQ);\n}", "function initStats(){\n stats = [];\n statsinfo = { /* will hold today, weekstart, total */\n total : 0,\n todayTotal : 0,\n weekTotal : 0,\n num : 1\n };\n /* create object for todays date */\n createToday();\n /* create object for start of week date */\n createWeekStart();\n}", "update(data){\r\n /*Check if the infrastructure has been attacked */\r\n if(this.#hitpoints > data.hitpoints){\r\n console.log( (this.#hitpoints - data.hitpoints) + \" points of damage taken on \" + this.#name);\r\n window.ui.alert((this.#hitpoints - data.hitpoints) + \" points of damage taken on \" + this.#name);\r\n }\r\n }", "updatePercentReady() {\n let stats_ready = 0,\n stats_count = this.stats_list.length\n\n this.percent_ready = this.stats_aggregated.percent_ready || 0\n this.compare_percent_ready = this.compare_stats_aggregated.percent_ready || 0\n\n if (stats_count == 0)\n return\n\n if (this.percent_ready === 0) {\n this.stats_list.map(s => {\n if (s.percent_ready === 1)\n stats_ready +=1\n })\n this.percent_ready = parseFloat(stats_ready / stats_count)\n }\n\n if (this.compare_percent_ready === 0) {\n this.stats_list.map(s => {\n if (s.percent_ready === 1)\n stats_ready +=1\n })\n this.percent_ready = parseFloat(stats_ready / stats_count)\n }\n }", "async function vesselFinalProcess(){\n let finalStats = await vessel.getVesselStats(vesselID)\n vesselStats.fill_level = finalStats.fill_percent\n vesselValidation = vessel.validate(finalStats)\n vessel.batchRecord(vesselStats, vesselValidation, {'start_time': startTime, 'end_time': endTime})\n}", "function statistics() {\n var time = Date.now() - startTime - pauseTime;\n var seconds = (time / 1000 % 60).toFixed(2);\n var minutes = ~~(time / 60000);\n statsTime.innerHTML = (minutes < 10 ? '0' : '') + minutes +\n (seconds < 10 ? ':0' : ':') + seconds;\n}", "function refreshPage() {\n vm.overallStats = timelineCalculationService.overallCostTRIEconomie(vm.actions.getByBuildingId( vm.currentBuilding ));\n vm.actionsFiltered = vm.actions.getByIsPlanified( vm.showPlanifiedActions );\n }", "function getUserStatistics() {\n var getUserStatUrl = config.serverURL + config.getUserStatistics; \n getRequest(getUserStatUrl, function(response) {\n $(\".recent-list-wrap .loading-icon\").hide();\n if(response.error) { \n $(\".recent-list-wrap .error-msg\").text(response.error);\n } else {\n $(\".reviewer-stat h1\").text(response.data.reviewerCount);\n $(\".designer-stat h1\").text(response.data.designerCount);\n }\n }, function() {\n $(\".recent-list-wrap .loading-icon\").hide();\n $(\".recent-list-wrap .error-msg\").text(config.serverError);\n });\n }", "function updateWorkoutInfo(workoutState) {\n $('#timeLeft').val(deadlineToTimeRemaining(workoutState['deadline'], workoutState['server_time']));\n var hits = sortHits(workoutState['correct_hits']);\n var misses = sortHits(workoutState['incorrect_hits']);\n $(\"#rhit\").text(hits['r'].length);\n $(\"#chit\").text(hits['c'].length);\n $(\"#lhit\").text(hits['l'].length);\n $(\"#rtime\").text(getAverage(hits['r']));\n $(\"#ctime\").text(getAverage(hits['c']));\n $(\"#ltime\").text(getAverage(hits['l']));\n $(\"#rmiss\").text(misses['r'].length);\n $(\"#cmiss\").text(misses['c'].length);\n $(\"#lmiss\").text(misses['l'].length);\n }", "function statusUpdate() {\n\t\tvar webAPI3 = new globals.xml.gameStatus(gameID);\n\t}", "getUsageStats() {\n return `Buffer: ${bytes(this.recentBuffer.length)}, lrErrors: ${this.lrErrors}`;\n }", "function RunAfterLoad() {\n\n lab = document.getElementById(labNameClientID).value;\n dataSource = document.getElementById(dataSourceClientID).value;\n\n \n\n updateStats();\n}", "function updateStats() {\n playerStats.innerText = \"Name: \" + player.name + \"\\n\";\n playerStats.innerText += \"Hp: \" + player.hp;\n playerMoney.innerText = player.money;\n $(\"#playDate\").text(\"Day: \" + player.day);\n $(\"#playerLoan\").text(\" Loan: \" + player.loan);\n}", "function getBatStats() {\n log('[getBatStats]');\n xedx_TornUserQuery(null, 'attacks,battlestats,basic', statsQueryCB);\n }", "function getBatStats() {\n log('[getBatStats]');\n xedx_TornUserQuery(null, 'attacks,battlestats,basic', statsQueryCB);\n }", "function updateCounter(data) {\n // ui.grid.updateLastChanged( getCurrentTime() );\n console.log(\"data last updated at: \" + getCurrentTime() + \" with \" + data);\n}", "function report(){\n\n\tconsole.log(\"Summary of Current Session: \")\n\tfor(var url in urlDict){\n\t\tconsole.log(\"\\tURL: \" + url + \"\\tElapsed Time: \" + urlDict[url] + \"s\");\n\t}\n}", "function updateVisualsTimeChange(start, end) {\n minDate = new Date(Date.parse(start));\n maxDate = new Date(Date.parse(end));\n updatePieChart(pieDataAllApps.report.data, currMetric);\n totals = {};\n totals['visits'] = pieData['totalVisits'];\n totals['views'] = pieData['totalViews'];\n updateTables(barGroup, pieDataAllApps.report.data, ['App', 'Raw', 'Perc'], ['Total Views', 'Total Visits'], currMetric, totals);\n updateBarChart(barGroup, currColor, browserType, browserData, currMetric);\n updateBarChart(barGroup, currColor, osType, osData, currMetric);\n updateHourlyBarChart(barGroup, currColor, currMetric);\n}", "function checkStats(){\n\t\tif(numberofbrains >= 13){\n\t\t\t///game won \n\t\t\t$(\"div.winner\").text(\"Winner: \" + currplayer);\n\t\t\t$(\"div.gameOver\").text(\"Game Over\");\n\n\t\t\t//runs twice \n\t\t\tsocket.emit(\"winner\", currentsid);\n\n\t\t\tconsole.log(\"Sending ID: \" + currentsid);\n\t\t\tconsole.log(\"Sending name: \" + currplayer);\n\n\t\t\t//socket.emit(\"stopScore\", currentsid);\n\t\t\t//add winner to game stats pass winner \n\t\t}\n\t\telse if(numberofshotguns >= 3){\n\t\t\t//game over reset numberofshotgun & number of brains\n\t\t\t$(\"div.gameOver\").text(\"Death by Shotgun: \" + currplayer);\n\t\t\t//clear emit\n\t\t\tsocket.emit(\"clearBoard\");\n\t\t\tnumberofbrains = 0;\n\t\t\tsocket.emit(\"TrackScore\", currentsid, numberofbrains); //reset back to zero\n\t\t\tsocket.emit(\"stopScore\", currentsid);\n\t\t}\n\t\telse{\n\t\t\t///nothing \n\t\t}\n\t}", "function updateStats() {\n numOfCookiesElm.innerHTML = Math.floor(cookies) + \" cookies\";\n scoreElm.innerHTML = \"Score: \" + Math.floor(score);\n cookiesPerSecElm.innerHTML = cps + \" per second\";\n}", "function check_and_report() {\n \n }", "function gameLoop() {\n stats.begin(); // Begin measuring\n ///updating current state\n currentstate.update();\n stats.end(); // end measuring\n}" ]
[ "0.7145684", "0.66246194", "0.64329547", "0.64114493", "0.6381396", "0.6369314", "0.63612884", "0.6293869", "0.62871665", "0.6271742", "0.62272316", "0.6190304", "0.61630094", "0.6144154", "0.6106665", "0.6104366", "0.61037374", "0.60841095", "0.60564554", "0.6044697", "0.6043883", "0.604095", "0.6021241", "0.60119385", "0.5957075", "0.5946338", "0.59389454", "0.5928055", "0.5927837", "0.59243715", "0.5917773", "0.5913694", "0.59010226", "0.58826494", "0.5882062", "0.58730525", "0.5869578", "0.58410317", "0.5834985", "0.5816231", "0.58105874", "0.5801115", "0.5801115", "0.57907957", "0.57803845", "0.5780345", "0.5766964", "0.575592", "0.5747364", "0.5736827", "0.5729889", "0.572786", "0.5714117", "0.57081944", "0.57028353", "0.56937015", "0.569303", "0.56757575", "0.56722397", "0.56646395", "0.5650056", "0.5646918", "0.5642446", "0.56386346", "0.5637001", "0.5636334", "0.563383", "0.5626725", "0.561708", "0.5613931", "0.5613839", "0.5603715", "0.56026024", "0.56002957", "0.5598169", "0.5597682", "0.5593078", "0.5592882", "0.55924475", "0.55905485", "0.55817664", "0.55806345", "0.5579217", "0.55781585", "0.55763197", "0.5568906", "0.5568579", "0.556667", "0.5566105", "0.555965", "0.5551302", "0.55501056", "0.5546799", "0.5546799", "0.5544964", "0.5541255", "0.55352825", "0.5530826", "0.55266804", "0.55186504", "0.5515019" ]
0.0
-1
Probably deprecated..also f'king big names..what was I thinking?
function pii_check_if_entry_exists_in_past_profile_list(curr_entry) { for(var i=0; i < pii_vault.past_reports.length; i++) { var past_master_profile_list = pii_vault.past_reports[i].master_profile_list; for(var j = 0; j < past_master_profile_list.length; j++) { if (past_master_profile_list[j] == curr_entry) { return true; } } } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "transient protected internal function m189() {}", "static final private internal function m106() {}", "transient final protected internal function m174() {}", "transient private internal function m185() {}", "protected internal function m252() {}", "transient private protected internal function m182() {}", "function StupidBug() {}", "_mapDeprecatedFunctionality(){\n\t\t//all previously deprecated functionality removed in the 5.0 release\n\t}", "static transient final private internal function m43() {}", "static transient private protected internal function m55() {}", "static transient final protected public internal function m46() {}", "static private internal function m121() {}", "static transient final protected internal function m47() {}", "transient private protected public internal function m181() {}", "static transient private protected public internal function m54() {}", "static transient final private protected internal function m40() {}", "static private protected internal function m118() {}", "transient final private protected internal function m167() {}", "static private protected public internal function m117() {}", "transient final private internal function m170() {}", "transient private public function m183() {}", "static transient private public function m56() {}", "get deprecated() {\n return false;\n }", "function _____SHARED_functions_____(){}", "function __func(){}", "transient final private protected public internal function m166() {}", "function positionMapTools(){\r\n\t//deprecated...\t\r\n}", "static transient final protected function m44() {}", "static final private protected public internal function m102() {}", "static transient final private protected public internal function m39() {}", "static protected internal function m125() {}", "static final private protected internal function m103() {}", "static transient final private protected public function m38() {}", "static final private public function m104() {}", "__previnit(){}", "static final protected internal function m110() {}", "function depd(namespace){if(!namespace){throw new TypeError('argument namespace is required');}function deprecate(message){// no-op in browser\n}deprecate._file=undefined;deprecate._ignored=true;deprecate._namespace=namespace;deprecate._traced=false;deprecate._warned=(0,_create2.default)(null);deprecate.function=wrapfunction;deprecate.property=wrapproperty;return deprecate;}", "function _G() {}", "function _G() {}", "static transient private internal function m58() {}", "function reserved(){}", "function Utils() {}", "function Utils() {}", "function DWRUtil() { }", "static transient final private public function m41() {}", "function StackFunctionSupport() {\r\n}", "function fm(){}", "function dummy(){}", "function dummy(){}", "function dummy(){}", "static private public function m119() {}", "function _() { undefined; }", "bfs() {\n throw new Error(\"This method hasn't been implemented yet!\");\n }", "bfs() {\n throw new Error(\"This method hasn't been implemented yet!\");\n }", "transient final private public function m168() {}", "function ExtraMethods() {}", "function FunctionUtils() {}", "function ea(){}", "function Sref() {\r\n}", "static transient final private public internal function m42() {}", "function Util() {}", "function VeryBadError() {}", "function miFuncion (){}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function dummy() {}", "function dummy() {}", "function dummy() {}", "function Xuice() {\r\n}", "function Scdr() {\r\n}", "function TMP(){return;}", "function TMP(){return;}", "sinceFunction() {}", "function oi(){}", "function Adapter() {}", "function fos6_c() {\n ;\n }", "function AeUtil() {}", "function _0x329edd(_0x38ef9f){return function(){return _0x38ef9f;};}", "hacky(){\n return\n }", "static transient protected internal function m62() {}", "function Utils(){}", "function Helper() {}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "function ie(a){this.ra=a}", "function no_overlib() { return ver3fix; }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }" ]
[ "0.72012395", "0.70153606", "0.68228614", "0.68015224", "0.6735375", "0.67181647", "0.67007357", "0.66948444", "0.6635623", "0.6424343", "0.6408598", "0.640222", "0.6401879", "0.63362134", "0.6288824", "0.6287156", "0.62778556", "0.62334293", "0.6211442", "0.6134688", "0.6127921", "0.6099121", "0.6046563", "0.60289216", "0.596901", "0.59527147", "0.5921672", "0.5921599", "0.5865109", "0.5856949", "0.5815523", "0.58096135", "0.57927036", "0.5760036", "0.5737157", "0.5717849", "0.5650553", "0.5641487", "0.56391925", "0.56324995", "0.56324995", "0.55983496", "0.55914336", "0.5565778", "0.5565778", "0.55559504", "0.55403984", "0.5508855", "0.5505821", "0.54897183", "0.54897183", "0.54897183", "0.54876256", "0.5469268", "0.5458564", "0.5458564", "0.54471856", "0.54335207", "0.54264057", "0.5422533", "0.54207313", "0.5413529", "0.54095364", "0.54057884", "0.5405034", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.5394369", "0.539096", "0.539096", "0.539096", "0.53882223", "0.5384074", "0.538365", "0.538365", "0.53748333", "0.53644323", "0.5357631", "0.5349396", "0.5344582", "0.53388554", "0.532608", "0.5322872", "0.5305479", "0.5305349", "0.5291852", "0.5291852", "0.5291852", "0.5278292", "0.52627206", "0.5259423", "0.5259423" ]
0.0
-1
Probably deprecated..also f'king big names..what was I thinking?
function pii_check_if_entry_exists_in_past_pwd_reports(curr_entry) { var ce = {}; var ce_str = ""; ce.site = curr_entry.site; ce.other_sites = curr_entry.other_sites; ce.other_sites.sort(); ce_str = JSON.stringify(ce); for(var i=0; i < pii_vault.past_reports.length; i++) { var past_report = pii_vault.past_reports[i].pwd_reuse_report; for(var j = 0; j < past_report.length; j++) { var past_report_entry = {}; var pre_str = ""; past_report_entry.site = past_report[j].site; past_report_entry.other_sites = past_report[j].other_sites; past_report_entry.other_sites.sort(); pre_str = JSON.stringify(past_report_entry); if (pre_str == ce_str) { return true; } } } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "transient protected internal function m189() {}", "static final private internal function m106() {}", "transient final protected internal function m174() {}", "transient private internal function m185() {}", "protected internal function m252() {}", "transient private protected internal function m182() {}", "function StupidBug() {}", "_mapDeprecatedFunctionality(){\n\t\t//all previously deprecated functionality removed in the 5.0 release\n\t}", "static transient final private internal function m43() {}", "static transient final protected public internal function m46() {}", "static transient private protected internal function m55() {}", "static private internal function m121() {}", "static transient final protected internal function m47() {}", "transient private protected public internal function m181() {}", "static transient private protected public internal function m54() {}", "static transient final private protected internal function m40() {}", "static private protected internal function m118() {}", "transient final private protected internal function m167() {}", "static private protected public internal function m117() {}", "transient final private internal function m170() {}", "transient private public function m183() {}", "static transient private public function m56() {}", "get deprecated() {\n return false;\n }", "function _____SHARED_functions_____(){}", "function __func(){}", "transient final private protected public internal function m166() {}", "function positionMapTools(){\r\n\t//deprecated...\t\r\n}", "static transient final protected function m44() {}", "static final private protected public internal function m102() {}", "static transient final private protected public internal function m39() {}", "static protected internal function m125() {}", "static final private protected internal function m103() {}", "static transient final private protected public function m38() {}", "static final private public function m104() {}", "__previnit(){}", "static final protected internal function m110() {}", "function depd(namespace){if(!namespace){throw new TypeError('argument namespace is required');}function deprecate(message){// no-op in browser\n}deprecate._file=undefined;deprecate._ignored=true;deprecate._namespace=namespace;deprecate._traced=false;deprecate._warned=(0,_create2.default)(null);deprecate.function=wrapfunction;deprecate.property=wrapproperty;return deprecate;}", "function _G() {}", "function _G() {}", "static transient private internal function m58() {}", "function reserved(){}", "function Utils() {}", "function Utils() {}", "function DWRUtil() { }", "static transient final private public function m41() {}", "function StackFunctionSupport() {\r\n}", "function fm(){}", "function dummy(){}", "function dummy(){}", "function dummy(){}", "static private public function m119() {}", "function _() { undefined; }", "bfs() {\n throw new Error(\"This method hasn't been implemented yet!\");\n }", "bfs() {\n throw new Error(\"This method hasn't been implemented yet!\");\n }", "transient final private public function m168() {}", "function ExtraMethods() {}", "function FunctionUtils() {}", "function ea(){}", "function Sref() {\r\n}", "static transient final private public internal function m42() {}", "function Util() {}", "function VeryBadError() {}", "function miFuncion (){}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function kd(a){return void 0===a?of:\"function\"==typeof a&&(of=a,!0)}", "function dummy() {}", "function dummy() {}", "function dummy() {}", "function Xuice() {\r\n}", "function TMP(){return;}", "function TMP(){return;}", "function Scdr() {\r\n}", "sinceFunction() {}", "function oi(){}", "function Adapter() {}", "function fos6_c() {\n ;\n }", "function AeUtil() {}", "function _0x329edd(_0x38ef9f){return function(){return _0x38ef9f;};}", "hacky(){\n return\n }", "static transient protected internal function m62() {}", "function Utils(){}", "function Helper() {}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "function ie(a){this.ra=a}", "function no_overlib() { return ver3fix; }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }" ]
[ "0.7200169", "0.70144904", "0.68214345", "0.6801084", "0.6734167", "0.6717289", "0.66999686", "0.66941327", "0.6635343", "0.64238596", "0.6407567", "0.64009297", "0.64007574", "0.6334515", "0.6287966", "0.6286348", "0.62765515", "0.62321544", "0.6210333", "0.6133756", "0.6126511", "0.6097794", "0.6045418", "0.60274696", "0.5968271", "0.59520245", "0.5920543", "0.5920111", "0.5864306", "0.58557564", "0.5813997", "0.5808264", "0.5790872", "0.57588106", "0.5735636", "0.5716475", "0.5649463", "0.564028", "0.5639223", "0.56317997", "0.56317997", "0.55967516", "0.5589683", "0.5565406", "0.5565406", "0.55558294", "0.55390525", "0.55093205", "0.5504699", "0.54891413", "0.54891413", "0.54891413", "0.5485768", "0.54685366", "0.545814", "0.545814", "0.5445718", "0.5433277", "0.5426509", "0.5421819", "0.5419462", "0.54127747", "0.54094553", "0.5406047", "0.5403943", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5393815", "0.5390829", "0.5390829", "0.5390829", "0.5386517", "0.538347", "0.538347", "0.53831756", "0.5375223", "0.53640264", "0.53578454", "0.53493667", "0.5344265", "0.5338524", "0.5326765", "0.53215504", "0.5304893", "0.5304652", "0.5290881", "0.5290881", "0.5290881", "0.52779865", "0.526283", "0.52589023", "0.52589023" ]
0.0
-1
Following functions are not really managing current report. Rather they update the displayed current_report on any tab if user is viewing it.
function send_pwd_group_row_to_reports(type, grp_name, sites, strength) { for (var i = 0; i < report_tab_ids.length; i++) { chrome.tabs.sendMessage(report_tab_ids[i], { type: "report-table-change-row", table_name: "pwd_groups", mod_type: type, changed_row: [ grp_name, sites.sort().join(", "), strength.join(", "), strength.join(", "), ], }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "storeCurrentlyViewedReport() {\n const reportID = this.getReportID();\n updateCurrentlyViewedReportID(reportID);\n }", "function refreshCurrentTab() {\r\n chartAnimationReady = true;\r\n showTab(currentPage, true);\r\n}", "function stock_reports() {\n //\n reset_meat_page();\n //\n document.getElementById('tab-clicked').value = 'stock-reports';\n //\n remove_class('hidden-elm','inventory-report');\n remove_class('hidden-elm','stock-change-report');\n}", "function currentTabs(tabs) {\n var loc = tbr.localSession_;\n consoleDebugLog('Latest local tabs:\\n' + tabsToString(tabs));\n // Accept the new set of tabs\n loc.tabs = tabs;\n // Proceed with updated tabs in place.\n contFunc();\n }", "selectReport(report) {\n this.$scope.reportHash = report;\n this.setMode('report');\n }", "function refresh(current) {\n $scope.info = pageInfo();\n if (current) {\n $scope.current = viewPage($scope.options.index, $scope.options.pageSize);\n }\n $scope.style.first = $scope.options.index === 0;\n $scope.style.last = $scope.options.index === Math.ceil(count / $scope.options.pageSize) - 1;\n\n //Refresh the count\n pager.count().then(onGotCount);\n }", "function showReports() {\n var reportsTab = document.getElementsByClassName(\"reports-tab\");\n reportsTab[0].className = \"tab reports-tab selected\";\n\n var reports = document.getElementsByClassName(\"reports\");\n reports[0].style.display = \"flex\";\n\n var firmwareUpdaterTab = document.getElementsByClassName(\"firmware-updater-tab\");\n firmwareUpdaterTab[0].className = \"tab firmware-updater-tab\";\n\n var firmwareUpdater = document.getElementsByClassName(\"firmware-updater\");\n firmwareUpdater[0].style.display = \"none\";\n\n var alertRulesTab = document.getElementsByClassName(\"alert-rules-tab\");\n alertRulesTab[0].className = \"tab alert-rules-tab\";\n\n var alertRules = document.getElementsByClassName(\"alert-rules\");\n alertRules[0].style.display = \"none\";\n\n cameraReport();\n}", "function updateCurrentTab(data) {\n return {\n type: _constants.UPDATE_CURRENT_TAB,\n data: data\n };\n}", "updateReport() {\n location.reload();\n }", "static set lastReport(value) {}", "function allCurrent()\n{\n mode = \"allCurrent\";\n refresh();\n}", "function updateReport(event) {\n \n cleanReport();\n \n // If the arrows where clicked, than update the arrows' timestamp\n updateTimeSpan(event);\n \n // extract report query from the DOM\n var reportQ = getReportQueryFromControlPanel();\n \n // write time span in human readable way\n var titleFrom = moment.unix(reportQ.start).format('YY MM DD HH:mm');\n var titleTo = moment.unix(reportQ.end).format('YY MM DD HH:mm');\n var verbalTimeSpanFormat = $(\"[name='radio-span']:checked\").data('verbal-format');\n var humanReadableTimespan = moment.unix(reportQ.end).format(verbalTimeSpanFormat);\n $('#report-title').html( /*titleFrom + '</br>' +*/ humanReadableTimespan /*+ '</br>' + titleTo*/ );\n\n // query data and update report\n getDataAndPopulateReport(reportQ);\n}", "function updateReport() {\n $(\"#currentTotal\").text(Math.floor(data.totalCurrent));\n $(\"#cps\").text((data.totalCPS).toFixed(1));\n}", "function watchByCurrentPage(){\n scope.$watch(function () {\n return tableCtrl.currentPage;\n }, function (newVal) {\n\n scope.currentPage = newVal;\n });\n }", "getReport() {\n // Inspect the UID to determine the report to render. As a special case,\n // we will display a fake report for development purposes.\n const uid = this.props.match.params.uid;\n if (uid === \"_dev\") {\n const [r] = propagateIndices([fakeReportAssertions]);\n setTimeout(() => {this.setState({report: r, loading: false});}, 1500);\n } else {\n axios.get(`/api/v1/reports/${uid}`)\n .then(response => propagateIndices([response.data]))\n .then(reportEntries => this.setState({\n report: reportEntries[0],\n loading: false\n }))\n .catch(error => this.setState({\n error,\n loading: false\n }));\n }\n }", "function loadMenuReportDirect(cate,idReport){\r\n if (checkFormChangeInProgress()) {\r\n return false;\r\n }\r\n item=\"Reports\";\r\n cleanContent(\"detailDiv\");\r\n hideResultDivs();\r\n formChangeInProgress=false;\r\n var currentScreen=item;\r\n var objectExist='false';\r\n loadContent(\"reportsMain.php?idCategory=\"+cate, \"centerDiv\");\r\n loadDiv(\"menuUserScreenOrganization.php?currentScreen=\"+currentScreen+'&objectExist='+objectExist,\"mainDivMenu\");\r\n stockHistory(item,null,currentScreen);\r\n if(defaultMenu == 'menuBarRecent'){\r\n menuNewGuiFilter(defaultMenu, item);\r\n }\r\n editFavoriteRow(true);\r\n selectIconMenuBar(item);\r\n setTimeout('reportSelectReport('+idReport+')',500);\r\n return true;\r\n}", "@action update_current_view(data) {\n this.page_state.update_current_view(data);\n }", "function excelReportFinal(){\n\t\t\t\t\t\texcelReportSummaryByBillingModes();\n\t\t\t\t\t}", "updateReport(report) {\n this.setReports(_reports.forEach((r) => {\n r = r.id == report.id ? report : r;\n }));\n }", "function updateCurrentActiveIndex() {\n\tchrome.tabs.query({\n\t\thighlighted: true\n\t}, function (tabs) {\n\t\tfor (var index = 0; index < tabs.length; index++) {\n\t\t\tvar tab = tabs[index];\n\t\t\tvar allTabs = user.tabsSortedByWindow[tab.windowId];\n\t\t\tvar previousActiveIndex = user.activeTabIndex[tab.windowId];\n\t\t\tvar timeStamp = getTimeStamp();\n\t\t\tconsole.log(tab)\n\t\t\tif (previousActiveIndex !== tab.index && previousActiveIndex !== null && allTabs[previousActiveIndex]) {\n\t\t\t\tif (user.loggedIn) {\n\t\t\t\t\tdeactivateTimeTab(allTabs[previousActiveIndex].databaseTabID);\n\t\t\t\t}\n\t\t\t\tallTabs[previousActiveIndex].highlighted = false;\n\t\t\t\tallTabs[previousActiveIndex].timeOfDeactivation = timeStamp;\n\t\t\t}\n\t\t\tuser.activeTabIndex[tab.windowId] = tab.index;\n\t\t\tallTabs[tab.index].highlighted = true;\n\t\t}\n\t})\n}", "function refreshCurrentTab()\n{\n jsobj.swap_tabs(XPCNativeWrapper.unwrap($(\"tabs\")).down(\".tabon\").getAttribute(\"val\"));\n}", "function updateInfo() {\n\tconsole.log(\"Running update\");\n\t// Make sure current tab exists\n\tif (curTabId == null) {\n\t\treturn;\n\t} else {\n\t\t// Get data from the current tab\n\t\tconsole.debug(\"Update - \" + curTabId);\n\t\tchrome.tabs.get(curTabId, \n\t\tfunction(tab) { \n\t\t\tconsole.debug(tab);\n\t\t\t// Get base URL\n\t\t\tvar theSite = getSite(tab.url);\n\t\t\tvar curURL = tab.url;\n\t\t\t//Stop Social Band if returned to assignment page -->\n\t\t\t\tvar urlParts = curURL.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/);\n\t\t\t\tvar urlParts1 = urlParts[0].split(\".\");\n\t\t\t\tvar siteDomain = urlParts1[0];\n\t\t\t\tvar trackingSitesList = 'facebook,yahoo,youtube,twitter,instagram,tumblr,dailymotion,pinterest,vine';\n\t\t\t\t\n\t\t\t\tParse.initialize(\"LcQYRvseB9ExXGIherTt1v2pw2MVzPFwVXfigo11\", \"F5enB5XfOfqo4ReAItZCkJVxOY76hoveZrOMwih9\"); \n\t\t\t\tchrome.cookies.get({\"url\": 'http://timem.github.io/', \"name\": 'username'}, function(cookie) { //Cookie access starts A1\n\t\t\t\t\tusname = cookie.value;\n\t\t\t\t\tif(usname.indexOf(\"@\") > 0 && usname.indexOf(\".\")){\n\t\t\t\t\t\tvar query = new Parse.Query(\"LoginDetails\");\n\t\t\t\t\t\tquery.equalTo(\"UserName\", usname);\n\t\t\t\t\t\tquery.descending(\"SessionStartedOn\");\n\t\t\t\t\t\tquery.first({ //Parse Instance Starts A1\n\t\t\t\t\t\t success: function(result){\n\t\t\t\t\t\t\t\tvar currentSessionObjId = result.id;\n\t\t\t\t\t\t\t\tvar socialSitesTimeParse = result.get(\"SocialSitesTime\");\n\t\t\t\t\t\t\t\tvar lastActiveLap = $.parseJSON(result.get(\"LastLapDetails\"));\n\t\t\t\t\t\t\t\tvar lastButtonActiveMode = lastActiveLap.buttonMode;\n\t\t\t\t\t\t\t\tconsole.log(\"6th November\");\n\t\t\t\t\t\t\t\tconsole.log(curURL.indexOf(\"assignments.html\"));\n\t\t\t\t\t\t\t\tconsole.log(trackingSitesList.indexOf(siteDomain));\n\t\t\t\t\t\t\t\tconsole.log(lastActiveLap.lapStatus);\n\t\t\t\t\t\t\t\tif(curURL.indexOf(\"assignments.html\") != -1 && lastActiveLap.lapStatus == \"SocialInProgress\"){\n\t\t\t\t\t\t\t\t\tvar newBandTitle = \"SocialSites\";\n\t\t\t\t\t\t\t\t\tvar newlapStatus = \"InProcess\";\n\t\t\t\t\t\t\t\t\ts = new Date().getTime();\n\t\t\t\t\t\t\t\t\t//Update Lap details in parse starts -->\n\t\t\t\t\t\t\t\t\tvar e = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar newbandDetails = {};\n\t\t\t\t\t\t\t\t\tnewbandDetails.title = newBandTitle;\n\t\t\t\t\t\t\t\t\tvar stTime = lastActiveLap.startTime;\n\t\t\t\t\t\t\t\t\tnewbandDetails.timeSpent = e - parseInt(stTime);\n\t\t\t\t\t\t\t\t\tnewbandDetails.lapStartTime = parseInt(stTime);\n\t\t\t\t\t\t\t\t\tif(result.get(\"LapData\")){\n\t\t\t\t\t\t\t\t\t\tvar objLapData = $.parseJSON(result.get(\"LapData\"));\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\tvar objLapData = [];\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\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\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LapData\",objLapDataString);\n\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\tvar lastActiveLap = {};\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"06th Nov 2015-\"+newlapStatus);\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.buttonMode = lastButtonActiveMode;\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.lapStatus = newlapStatus;\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.startTime = s;\n\t\t\t\t\t\t\t\t\t\tvar tmpStringifyStr = JSON.stringify(lastActiveLap);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LastLapDetails\",tmpStringifyStr);\n\t\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Updated Successfully\");\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Update failed\");\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\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\t\tconsole.log(\"LapData Updated Successfully\");\t\n\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"LapData Update failed\");\n\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\t//Update Lap details in parse ends <--\n\t\t\t\t\t\t\t\t}else if(trackingSitesList.indexOf(siteDomain) != -1 && lastActiveLap.lapStatus == \"InProcess\"){\n\t\t\t\t\t\t\t\t\tvar newBandTitle = \"Study\";\n\t\t\t\t\t\t\t\t\tvar newlapStatus = \"SocialInProgress\";\n\t\t\t\t\t\t\t\t\ts = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar e = new Date().getTime();\n\t\t\t\t\t\t\t\t\tvar newbandDetails = {};\n\t\t\t\t\t\t\t\t\tnewbandDetails.title = newBandTitle;\n\t\t\t\t\t\t\t\t\tvar stTime = lastActiveLap.startTime;\n\t\t\t\t\t\t\t\t\tnewbandDetails.timeSpent = e - parseInt(stTime);\n\t\t\t\t\t\t\t\t\tnewbandDetails.lapStartTime = parseInt(stTime);\n\t\t\t\t\t\t\t\t\tif(result.get(\"LapData\")){\n\t\t\t\t\t\t\t\t\t\tvar objLapData = $.parseJSON(result.get(\"LapData\"));\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\t\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t\tvar objLapData = [];\n\t\t\t\t\t\t\t\t\t\tobjLapData.push(newbandDetails);\n\t\t\t\t\t\t\t\t\t\tvar objLapDataString = JSON.stringify(objLapData);\n\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\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LapData\",objLapDataString);\n\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\tvar lastActiveLap = {};\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"06th Nov 2015-\"+newlapStatus);\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.buttonMode = lastButtonActiveMode;\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.lapStatus = newlapStatus;\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlastActiveLap.startTime = s;\n\t\t\t\t\t\t\t\t\t\tvar tmpStringifyStr = JSON.stringify(lastActiveLap);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tvar lapUpdateClass = Parse.Object.extend(\"LoginDetails\");\n\t\t\t\t\t\t\t\t\t\tvar lapUpdate = new lapUpdateClass();\n\t\t\t\t\t\t\t\t\t\tlapUpdate.id = currentSessionObjId;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tlapUpdate.set(\"LastLapDetails\",tmpStringifyStr);\n\t\t\t\t\t\t\t\t\t\t// Save\n\t\t\t\t\t\t\t\t\t\tlapUpdate.save(null, {\n\t\t\t\t\t\t\t\t\t\t success: function(lapUpdate) {\n\t\t\t\t\t\t\t\t\t\t\t// Saved successfully.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Updated Successfully\");\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(\"LastLapDetails Update failed\");\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\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\t\tconsole.log(\"LapData Updated Successfully\");\t\n\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t error: function(point, error) {\n\t\t\t\t\t\t\t\t\t\t// The save failed.\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"LapData Update failed\");\n\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\t//Update Lap details in parse ends <--\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t },\n\t\t\t\t\t\t error: function(){\n\t\t\t\t\t\t\t console.log('Parse Error');\n\t\t\t\t\t\t },\n\t\t\t\t\t\t\n\t\t\t\t\t\t}) //Parse Instance Ends A1\t\t\t\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\tconsole.log(\"Username does not exists.\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t})//Cookie access ends A1\t\t\t\n\t\t\t//Stop Social Band if returned to assignment page ends <--\n\t\t\t\n\t\t\t// Check if its valid\n\t\t\tif (theSite == null) {\n\t\t\t\tconsole.log(\"URL issue\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Set site if doesnt exist yet\n\t\t\tif (curSite == null) {\n\t\t\t\tconsole.log(\"Setting new site - \" + curSite);\n\t\t\t\tstartTime = new Date();\n\t\t\t\tcurSite = theSite;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// If new site, update time spent\n\t\t\tif (curSite != theSite) {\n\t\t\t\tvar diffTimeSec = ((new Date()).getTime() - startTime.getTime()) / 1000;\n\t\t\t\tupdateTime(curSite, diffTimeSec);\n\t\t\t\tcurSite = theSite;\n\t\t\t\tstartTime = new Date();\n\t\t\t}\n\t\t});\n\t}\n}", "componentDidUpdate(pastProps){\n const { pagedjs = null } = this.props;\n if (!pastProps.pagedjs && pagedjs) {\n this.renderReportIntoRef();\n }\n }", "function getReports(page = 1){\n if(window.datasLoaderLocked)\n return false;\n\n window.datasLoaderLocked = true;\n $('#documentslist .reportsList .content').html('');\n $(\"#documentslist .reportsList h3\").text(\"... lot(s)\");\n\n var filter = ''\n if(window.currentTargetFilter == 'all')\n {\n filter = window.getParamsFromFilter();\n window.setParamsFilterText();\n }\n\n var view = $(\"select[name=document_owner_list]\").val();\n var per_page = $(\"select[name=per_page]\").val();\n\n $(\"#panel1 .header h3\").text('Pieces');\n $(\"#panel1 > .content\").html(\"\");\n\n $(\"#presPanel1 .header h3\").text('Ecritures comptables');\n $(\"#presPanel1 > .content\").html(\"\")\n\n var Url = \"/account/documents/reports?page=\"+page+\"&view=\"+view+\"&per_page=\"+per_page+'&'+filter;\n window.currentLink = null;\n\n $.ajax({\n url: encodeURI(Url),\n data: \"\",\n dataType: \"html\",\n type: \"GET\",\n beforeSend: function() {\n logBeforeAction(\"Traitement en cours\");\n },\n success: function(data) {\n logAfterAction();\n var list = $(\"#documentslist .reportsList .content\");\n list.children(\"*\").remove();\n list.append(data);\n\n reports_count = $(\"input[name=reports_count]\").val();\n \n $(\"#documentslist .reportsList h3\").text(reports_count + \" lot(s)\");\n\n $(\"#pageslist #panel1\").attr(\"style\",\"min-height:\"+$(\"#documentslist\").height()+\"px\");\n $(\"#preseizuresList #presPanel1\").attr(\"style\",\"min-height:\"+$(\"#documentslist\").height()+\"px\");\n\n initEventOnPackOrReportRefresh();\n window.initEventOnHoverOnInformation();\n\n setTimeout(function(){ window.datasLoaderLocked = false; }, 1000);\n },\n error: function(data){\n logAfterAction();\n $(\".alerts\").html(\"<div class='row-fluid'><div class='span12 alert alert-danger'><a class='close' data-dismiss='alert'> × </a><span> Une erreur est survenue et l'administrateur a été prévenu.</span></div></div>\");\n setTimeout(function(){ window.datasLoaderLocked = false; }, 1000);\n }\n });\n }", "function monitorCurrentPage() {\n $('#monitor_page').addClass('inprogress');\n chrome.tabs.getSelected(null, function(tab) {\n initializePageModePickerPopup(tab);\n _gaq.push(['_trackEvent', tab.url, 'add']);\n\n chrome.tabs.getAllInWindow(null, function(tabs){\n var found = false;\n for (var i = 0; i < tabs.length; i++) {\n if(tabs[i].url == chrome.extension.getURL(\"options.htm\")) \n {\n found = true;\n break;\n }\n }\n \n if (found == false)\n {\n chrome.tabs.create({url: \"options.htm\", active: false});\n }\n addPage({url: tab.url, name: tab.title}, function() {\n BG.takeSnapshot(tab.url);\n });\n});\n \n });\n}", "function getAndDisplayUserReport() {\n getUserInfo(displayUserReport);\n}", "function processGenerateReportButton() \n{ \n\t//console.log(\"Entereed generateReport\");\n\t//console.log(currentPage);\n\t\n\tif (currentPage == \"Campus\")\n\t{\n\t\tinitCampusReportGeneration();\n\t}\n\telse\n\t{ \n\t\tinitBuildingReportGeneration(currentPage);\n\t}\n\t\n}", "function onReport() {\n\t\t\tvar reportTime = t.getTimeBucket();\n\t\t\tvar curTime = reportTime;\n\t\t\tvar missedReports = 0;\n\n\t\t\tif (total === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// if we had more polls than we expect in each\n\t\t\t// collection period (we allow one extra for wiggle room), we\n\t\t\t// must not have been able to report, so assume those periods were 100%\n\t\t\twhile (total > (POLLS_PER_REPORT + 1) &&\n\t\t\t missedReports <= MAX_MISSED_REPORTS) {\n\t\t\t\tt.set(\"busy\", 100, --curTime);\n\n\t\t\t\t// reset the period by one\n\t\t\t\ttotal -= POLLS_PER_REPORT;\n\t\t\t\tlate = Math.max(late - POLLS_PER_REPORT, 0);\n\n\t\t\t\t// this was a busy period\n\t\t\t\toverallTotal += POLLS_PER_REPORT;\n\t\t\t\toverallLate += POLLS_PER_REPORT;\n\n\t\t\t\tmissedReports++;\n\t\t\t}\n\n\t\t\t// update the total stats\n\t\t\toverallTotal += total;\n\t\t\toverallLate += late;\n\n\t\t\tt.set(\"busy\", Math.round(late / total * 100), reportTime);\n\n\t\t\t// reset stats\n\t\t\ttotal = 0;\n\t\t\tlate = 0;\n\t\t}", "navigateToReportPage() {\n return this._navigate(this.buttons.report, 'reportPage.js');\n }", "function processRestoreCumulativeView() \n{ \n\n\tif (currentPage == \"Campus\"){generateSummaryfromEntireDateSelection();}\n\telse{generateZoneSummaryfromEntireDateSelection();}\n\t\n}", "function getStockRequestOnLoanReport(){\n if(!WtfGlobal.EnableDisable(Wtf.UPerm.consignmentsales, Wtf.Perm.consignmentsales.viewconsignmentloan)) {\n var mainTabId = Wtf.getCmp(\"as\");\n var stockloanReportTab = Wtf.getCmp(\"stockReqOnLoanReportTab\");\n if(stockloanReportTab == null){\n stockloanReportTab = new Wtf.StockRequestOnLoanReport({\n layout:\"fit\",\n title: Wtf.util.Format.ellipsis(WtfGlobal.getLocaleText(\"acc.field.requestOnLoanReport\"), Wtf.TAB_TITLE_LENGTH), \n tabTip: WtfGlobal.getLocaleText(\"acc.field.requestOnLoanReport\"),\n closable:true,\n border:false,\n// iconCls:getButtonIconCls(Wtf.etype.inventoryqa),\n id:\"stockReqOnLoanReportTab\"\n });\n mainTabId.add(stockloanReportTab);\n }\n mainTabId.setActiveTab(stockloanReportTab);\n mainTabId.doLayout();\n }else{\n WtfComMsgBox(46,0,false,WtfGlobal.getLocaleText(\"acc.common.viewing\")+\" \"+\"this feature\");\n }\n}", "function onDocX(){\n\tvar controller = View.controllers.get('abRepmLsadminPropProfileCtrl');\n\t/*\n\t * KB 3029212 Ioan don't export if there is no data available\n\t */\n\tvar objOverviewPanel = View.panels.get(overviewPanelId);\n\tif (objOverviewPanel.gridRows.length == 0) {\n\t\tView.showMessage(getMessage('msg_docx_nodata'));\n\t\treturn;\n\t}\n\tvar reportConfig = {\n\t\ttitle: getMessage('msg_report_title'),\n\t\tfileName: 'ab-repm-lsadmin-prop-profile-rpt',\n\t\tcallerView: 'ab-repm-lsadmin-prop-profile.axvw',\n\t\tdataSource: 'abRepmLsadminPropProfile_ds_grid',\n\t\tprintableRestriction: controller.printableRestriction,\n\t\tfiles:[]\n\t};\n\tvar consoleRestr = \tcontroller.restriction;\n\tvar parameters = controller.parameters;\n\tvar restriction = new Ab.view.Restriction();\n\trestriction.addClause('property.pr_id', '', 'IS NOT NULL', ')AND(', false);\n\tvar rptFileCfg = new RptFileConfig(\n\t\t'ab-repm-lsadmin-prop-profile-details-rpt.axvw',\n\t\t{permanent: consoleRestr, temporary: restriction, parameters: parameters},\n\t\t'property.pr_id',\n\t\t{parameters :[\n\t\t\t\t{name: 'prId', type: 'value', value: 'property.pr_id'},\n\t\t\t\t{name: 'owned', type: 'text', value: getMessage(\"owned\")},\n\t\t\t\t{name: 'leased', type: 'text', value: getMessage(\"leased\")},\n\t\t\t\t{name: 'neither', type: 'text', value: getMessage(\"neither\")}]},\n\t\tnull\n\t);\n\treportConfig.files.push(rptFileCfg);\n\t\n\tonPaginatedReport(reportConfig);\n}", "function updateLocalInfo() {\n\t\t$scope.localInfo = localAccount.selected;\n\t\tif (localAccount.selected) {\n\t\t\tupdateList(localAccount.selected.path);\n\t\t}\n\t}", "function displaySelectedCPCompTab(){\n var url = parent.location.href;\n s=url.indexOf(\"summary\");\n if (s!=-1){\n obj= document.getElementById('summary-li');\n if(obj){\n document.getElementById('summary').style.display=\"\";\n }\n }\n if (url.indexOf(\"basiccontrol\")!=-1){\n obj= document.getElementById('basiccontrol-li');\n if(obj){\n document.getElementById('basiccontrol').style.display=\"\";\n }\n }\n if (url.indexOf(\"auditreadyasmt\")!=-1){\n obj= document.getElementById('auditreadyasmt-li');\n if(obj){\n document.getElementById('auditreadyasmt').style.display=\"\";\n }\n }\n if (url.indexOf(\"riskmsdcommit\")!=-1){\n obj= document.getElementById('riskmsdcommit-li');\n if(obj){\n document.getElementById('riskmsdcommit').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"auditreview\")!=-1){\n obj= document.getElementById('auditreview-li');\n if(obj){\n document.getElementById('auditreview').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"kctest\")!=-1){\n obj= document.getElementById('kctest-li');\n if(obj){\n document.getElementById('kctest').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"opmetric\")!=-1){\n obj= document.getElementById('opmetric-li');\n if(obj){\n document.getElementById('opmetric').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"other\")!=-1){\n obj= document.getElementById('other-li');\n if(obj){\n document.getElementById('other').style.display=\"\";\n }\n }\n}", "function initLocalDashboardPage(){\r\n\treportsSection = \"dashboard\";\r\n\treportsObject = getDashboardReports(sid);\r\n\tvar list = $(\"#dashboard\");\r\n\tlist.empty();\r\n\tvar predefinedReports = reportsObject.predefined;\r\n\tif(predefinedReports.length > 0){\r\n\t\t\r\n\t\t$.each(predefinedReports, function(k, vObj){\r\n\t\t\tvar raport = prepareDashboardReport(vObj.code);\r\n\t\t\treportObjectToExecute = loadDashboardReport(raport);\r\n\t\t\tlist.append(\r\n\t\t\t\t\t$(\"<div>\",{class:\"dashboard-item-\"+reportObjectToExecute.class+\" uss\",id:reportObjectToExecute.id})\r\n\t\t\t\t\t\t.append($(\"<div>\",{class:\"title\"}))\r\n\t\t\t\t\t\t.append($(\"<div>\",{class:\"form\"}))\r\n\t\t\t\t\t\t.append($(\"<div>\",{class:\"graph\",id:\"graph-\"+reportObjectToExecute.id}).append($(\"<div>\",{class:\"loading-span\"}).text(\"Loading ...\")))\r\n\t\t\t);\r\n\t\t\trenderDashboardReport(reportObjectToExecute);\r\n\t\t});\r\n\t}\r\n}", "function View() {\n var self = this;\n this.currentDate = new Date();\n this.currentReport = {\n needToPickupList: [],\n absenceList: [],\n pickedUpList: []\n };\n }", "showReport() {\n this.props.showReport();\n }", "function currentTab(){\r\n\tif (byId(\"tUnassigned\").style.display == \"block\") return 1;\r\n\telse return 2;\r\n}", "viewCurrentRecord(currentRow) {\n console.log('currentRow-->'+JSON.stringify(currentRow));\n this.bShowModal = true;\n this.isEditForm = false;\n this.selectedRecord = currentRow.sId;\n this.selectedEnrollmentType = currentRow.sEnrollmentType;\n }", "function load_report_page() {\n page = 'user_help';\n load_page();\n}", "function showReportDialog() {\n return;\n}", "function OpenReportOption()\n{\n var currentVisibleFields = \"\";\n var currentVisibleFieldsWithWidth = \"\";\n \n if(OBSettings.SQL_GROUP_BY == \"NONE\" ) {\n currentVisibleFields = GetCurrentVisibleFieldNames();\n currentVisibleFieldsWithWidth = GetCurrentVisibleFieldNamesWithWidth();\n }\n else {\n currentVisibleFields = OBSettings.SQL_SELECT;\n\n //currentVisibleFields = GetCurrentVisibleFieldNamesWithWidth();\n if (OBSettings.ACTIVE_GRID == 'DETAIL_GRID') {\n currentVisibleFields = GetCurrentVisibleFieldNames();\n currentVisibleFieldsWithWidth = GetCurrentVisibleFieldNamesWithWidth();\n }\n\n \n }\n \n if(OBSettings.COLOR_MODE == 1)\n {\n OpenChild('./Report/common_template.html?isGroupColoredID=1&fields='+currentVisibleFields+'&fieldswidth='+currentVisibleFieldsWithWidth, 'PDFReportOptions', true, 330, 150, 'no', 'no');\n }\n else\n {\n OpenChild('./Report/common_template.html?isGroupColoredID=null&fields='+currentVisibleFields+'&fieldswidth='+currentVisibleFieldsWithWidth, 'PDFReportOptions', true, 330, 150, 'no', 'no');\n }\n}", "function calculateCurrent() {\n if (!currentCalculator) { return; }\n\n const result = Calculations.calculate(currentCalculator);\n renderOutput(result);\n }", "function getJobWorkInAgedReport() {\n if (!isProdBuild) {\n jobWorkInAgedReport();\n } else {\n if (Wtf.ReportScriptLoadedFlag.jobWorkInAgedReport) {\n jobWorkInAgedReport();\n } else {\n ScriptMgr.load({\n scripts: ['../../scripts/Reports/JobWorkInAgedReport.js'],\n callback: function () {\n jobWorkInAgedReport();\n Wtf.ReportScriptLoadedFlag.jobWorkInAgedReport = true\n },\n scope: this\n });\n }\n }\n}", "function refreshCurrentDate() {\n\t\t\t\tdateCurrent = getDateInRange(dateCurrent, dateShadow, before, after);\n\t\t\t}", "onTabChange(evt) {\n const win = evt.target.ownerGlobal;\n const currentURI = win.gBrowser.currentURI;\n // Don't show the page action if page is not http or https\n if (currentURI.scheme !== \"http\" && currentURI.scheme !== \"https\") {\n this.hidePageAction(win.document);\n return;\n }\n\n const currentWin = Services.wm.getMostRecentWindow(\"navigator:browser\");\n\n // If user changes tabs but stays within current window we want to update\n // the status of the pageAction, then reshow it if the new page has had any\n // resources blocked.\n if (win === currentWin) {\n this.hidePageAction(win.document);\n // depending on the treatment branch, we want the count of timeSaved\n // (\"fast\") or blockedResources (\"private\")\n const counter = this.treatment === \"private\" ?\n this.state.blockedResources.get(win.gBrowser.selectedBrowser) :\n this.state.timeSaved.get(win.gBrowser.selectedBrowser);\n if (counter) {\n this.showPageAction(win.document, counter);\n this.setPageActionCounter(win.document, counter);\n }\n }\n }", "function edit_notes_show_report_exit()\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"edit_notes_div\").innerHTML=\"\";\n\t\t\t}", "currentPeriodClicked() {\n this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';\n }", "currentPeriodClicked() {\n this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';\n }", "receiveReport(report) {\n //this.removeReport(report);\n this.setReports(_reports.concat(report));\n }", "function reportClicked() {\n chrome.runtime.sendMessage({ \"button\": \"report\", \"id\": data[currentIndex]._id });\n}", "reportProgress(text, current, total) {\n if (this.current.by.connected) {\n this.current.by.emit('progressReport', text, current, total);\n }\n }", "function getCurrentTab() {\n return $currentTab;\n}", "function initTabs() {\n\t$(\"#report-content .tabs\").each(function(){\n\t\t$(this).tabs({\n\t\t\t\"show\": function(event, ui) {\n\t\t\t var table = $.fn.dataTable.fnTables(true);\n\t\t\t if ( table.length > 0 ) {\n\t\t\t $(table).dataTable().fnAdjustColumnSizing();\n\t\t\t }\n\t\t\t},\n\t\t\t\"activate\": function(event, ui) {\n\t\t\t\tvar table = ui.newPanel.find(\"table.dataTable\");\n\t\t\t\t//console.log(table);\n\t\t\t\tupdateFooter(table);\n\t\t\t}\n\t\t});\n\t});\n}", "function toggleCurrent() {\n toggleAndShow(getCurEntry());\n}", "_renderCurrentPage() {\n this._clearRenderedCards();\n\n this._displayedCards.forEach(card => this._renderCard(card));\n this._evaluateControllers();\n }", "function reportSetSelectedStaffMemberName(reportName) {\n\t$(\".reportCurrentStaffMemberName\").each(function () {\n\t\tif (reportName == \"FUNDINGHISTORY\") {\n\t\t\t$(this).text(\"ALL\");\n\t\t} else {\n\t\t\t$(this).text($(\"#AssignedStaffList option:selected\").text());\n\t\t}\n\t});\n}", "afterModel(report) {\n return this.replaceWith('reports.report.view', get(report, 'tempId'));\n }", "function getCurrentTab() {\n return currentTab;\n}", "function getCurrentTab() {\n return currentTab;\n}", "function getCurrentTab() {\n return currentTab;\n}", "setReports(reports) {\n _reports = reports;\n this.setState({\n reports: reports,\n }, this.setReportsDataSource(reports, this.state.location));\n }", "function afterReload () {\n //based on today date valid our html field(date field)\n valid.dateValidHtml();\n //see last time wich page was active \n let wichPage = localStorage.getItem('page');\n //show actived page with info that has have before\n switch(wichPage) {\n case '1':\n ui.showfirst();\n break;\n case null:\n ui.showfirst();\n break;\n case '2':\n ui.showMid();\n ui.cul();\n ui.addTitle();\n break;\n case '3':\n ui.showLast();\n ui.done();\n break;\n }\n}", "function modifyReports(validReportIDS, invalidReportIDS) {\n console.log(\"VALID: \" + validReportIDS); // Call function to change expiretS of valid reports.\n setExpireDate(validReportIDS);\n console.log(\"INVALID: \" + invalidReportIDS); // Call function to remove information of invalid reports.\n // TODO: currently not doing anything to invalid reports.\n}", "function cumulativeToggled(report) {\n var cumulative = (report.tab.find('input.segment-enabled:radio:checked').val() === 'no');\n\n // Toggle display of segmentation options\n report.tab.find('.segment-options').toggle(! cumulative);\n\n // if user wants cumulative display, segmentation is null\n report.segmentation = cumulative ? null : report.segmentation;\n\n if(cumulative) { // Load data and update graph\n loadData(report, function() {\n updateGraph(report);\n });\n } else {\n segmentationChanged(report);\n }\n}", "function refreshSelected() {\n if (MessageCountHistory.length > 1) {\n var message_time_delta = MessageCountHistory[MessageCountHistory.length-1].time - MessageCountHistory[0].time;\n var message_count_delta = MessageCountHistory[MessageCountHistory.length-1].messages - MessageCountHistory[0].messages;\n if (message_time_delta > 0)\n MessageRate = message_count_delta / message_time_delta;\n } else {\n MessageRate = null;\n }\n\n\trefreshPageTitle();\n \n var selected = false;\n\tif (typeof SelectedPlane !== 'undefined' && SelectedPlane != \"ICAO\" && SelectedPlane != null) {\n \t selected = Planes[SelectedPlane];\n }\n \n $('#dump1090_infoblock').css('display','block');\n $('#skyaware_version').text('SkyAware ' + SkyAwareVersion);\n $('#dump1090_total_ac').text(TrackedAircraft);\n $('#dump1090_total_ac_positions').text(TrackedAircraftPositions);\n $('#dump1090_total_history').text(TrackedHistorySize);\n $('#active_filter_count').text(ActiveFilterCount);\n\n if (MessageRate !== null) {\n $('#dump1090_message_rate').text(MessageRate.toFixed(1));\n } else {\n $('#dump1090_message_rate').text(\"n/a\");\n }\n\n setSelectedInfoBlockVisibility();\n\n if (!selected) {\n return;\n }\n \n if (selected.flight !== null && selected.flight !== \"\") {\n $('#selected_callsign').text(selected.flight);\n } else {\n $('#selected_callsign').text('n/a');\n }\n $('#selected_flightaware_link').html(getFlightAwareModeSLink(selected.icao, selected.flight, \"Visit Flight Page\"));\n\n if (selected.registration !== null) {\n $('#selected_registration').text(selected.registration);\n } else {\n $('#selected_registration').text(\"n/a\");\n }\n\n if (selected.icaotype !== null) {\n $('#selected_icaotype').text(selected.icaotype);\n } else {\n $('#selected_icaotype').text(\"n/a\");\n }\n\n // Not using this logic for the redesigned info panel at the time, but leaving it in if/when adding it back\n // var emerg = document.getElementById('selected_emergency');\n // if (selected.squawk in SpecialSquawks) {\n // emerg.className = SpecialSquawks[selected.squawk].cssClass;\n // emerg.textContent = NBSP + 'Squawking: ' + SpecialSquawks[selected.squawk].text + NBSP ;\n // } else {\n // emerg.className = 'hidden';\n // }\n\n\t\t$(\"#selected_altitude\").text(format_altitude_long(selected.altitude, selected.vert_rate, DisplayUnits));\n\n\t\t$('#selected_onground').text(format_onground(selected.altitude));\n\n if (selected.squawk === null || selected.squawk === '0000') {\n $('#selected_squawk').text('n/a');\n } else {\n $('#selected_squawk').text(selected.squawk);\n }\n\t\n\t\t$('#selected_speed').text(format_speed_long(selected.gs, DisplayUnits));\n\t\t$('#selected_ias').text(format_speed_long(selected.ias, DisplayUnits));\n\t\t$('#selected_tas').text(format_speed_long(selected.tas, DisplayUnits));\n\t\t$('#selected_vertical_rate').text(format_vert_rate_long(selected.baro_rate, DisplayUnits));\n\t\t$('#selected_vertical_rate_geo').text(format_vert_rate_long(selected.geom_rate, DisplayUnits));\n $('#selected_icao').text(selected.icao.toUpperCase());\n $('#airframes_post_icao').attr('value',selected.icao);\n\t\t$('#selected_track').text(format_track_long(selected.track));\n\n if (selected.seen <= 1) {\n $('#selected_seen').text('now');\n } else {\n $('#selected_seen').text(selected.seen.toFixed(1) + 's');\n }\n\n if (selected.seen_pos <= 1) {\n $('#selected_seen_pos').text('now');\n } else {\n $('#selected_seen_pos').text(selected.seen_pos.toFixed(1) + 's');\n }\n\n $('#selected_country').text(selected.icaorange.country);\n if (ShowFlags && selected.icaorange.flag_image !== null) {\n $('#selected_flag').removeClass('hidden');\n $('#selected_flag img').attr('src', FlagPath + selected.icaorange.flag_image);\n $('#selected_flag img').attr('title', selected.icaorange.country);\n } else {\n $('#selected_flag').addClass('hidden');\n }\n\n\tif (selected.position === null) {\n $('#selected_position').text('n/a');\n $('#selected_follow').addClass('hidden');\n } else {\n $('#selected_position').text(format_latlng(selected.position));\n $('#position_age').text(selected.seen_pos.toFixed(1) + 's');\n $('#selected_follow').removeClass('hidden');\n if (FollowSelected) {\n $('#selected_follow').css('font-weight', 'bold');\n OLMap.getView().setCenter(ol.proj.fromLonLat(selected.position));\n } else {\n $('#selected_follow').css('font-weight', 'normal');\n }\n\t}\n\t\tif (selected.getDataSource() === \"adsb_icao\") {\n\t\t\t$('#selected_source').text(\"ADS-B\");\n\t\t} else if (selected.getDataSource() === \"tisb_trackfile\" || selected.getDataSource() === \"tisb_icao\" || selected.getDataSource() === \"tisb_other\") {\n\t\t\t$('#selected_source').text(\"TIS-B\");\n\t\t} else if (selected.getDataSource() === \"mlat\") {\n\t\t\t$('#selected_source').text(\"MLAT\");\n\t\t} else {\n\t\t\t$('#selected_source').text(\"Other\");\n\t\t}\n\t\t$('#selected_category').text(selected.category ? selected.category : \"n/a\");\n $('#selected_sitedist').text(format_distance_long(selected.sitedist, DisplayUnits));\n $('#selected_rssi').text(selected.rssi.toFixed(1) + ' dBFS');\n $('#selected_message_count').text(selected.messages);\n\t\t$('#selected_photo_link').html(getFlightAwarePhotoLink(selected.registration));\n\t\t\n\t\t$('#selected_altitude_geom').text(format_altitude_long(selected.alt_geom, selected.geom_rate, DisplayUnits));\n $('#selected_mag_heading').text(format_track_long(selected.mag_heading));\n $('#selected_true_heading').text(format_track_long(selected.true_heading));\n $('#selected_ias').text(format_speed_long(selected.ias, DisplayUnits));\n $('#selected_tas').text(format_speed_long(selected.tas, DisplayUnits));\n if (selected.mach == null) {\n $('#selected_mach').text('n/a');\n } else {\n $('#selected_mach').text(selected.mach.toFixed(3));\n }\n if (selected.roll == null) {\n $('#selected_roll').text('n/a');\n } else {\n $('#selected_roll').text(selected.roll.toFixed(1));\n }\n if (selected.track_rate == null) {\n $('#selected_trackrate').text('n/a');\n } else {\n $('#selected_trackrate').text(selected.track_rate.toFixed(2));\n }\n $('#selected_geom_rate').text(format_vert_rate_long(selected.geom_rate, DisplayUnits));\n if (selected.nav_qnh == null) {\n $('#selected_nav_qnh').text(\"n/a\");\n } else {\n $('#selected_nav_qnh').text(selected.nav_qnh.toFixed(1) + \" hPa\");\n }\n $('#selected_nav_altitude').text(format_altitude_long(selected.nav_altitude, 0, DisplayUnits));\n $('#selected_nav_heading').text(format_track_long(selected.nav_heading));\n if (selected.nav_modes == null) {\n $('#selected_nav_modes').text(\"n/a\");\n } else {\n $('#selected_nav_modes').text(selected.nav_modes.join());\n\t\t}\n\t\tif (selected.nic_baro == null) {\n\t\t\t$('#selected_nic_baro').text(\"n/a\");\n\t\t} else {\n\t\t\tif (selected.nic_baro == 1) {\n\t\t\t\t$('#selected_nic_baro').text(\"cross-checked\");\n\t\t\t} else {\n\t\t\t\t$('#selected_nic_baro').text(\"not cross-checked\");\n\t\t\t}\n\t\t}\n\n\t\t$('#selected_nac_p').text(format_nac_p(selected.nac_p));\n\t\t$('#selected_nac_v').text(format_nac_v(selected.nac_v));\n\t\tif (selected.rc == null) {\n\t\t\t$('#selected_rc').text(\"n/a\");\n\t\t} else if (selected.rc == 0) {\n\t\t\t$('#selected_rc').text(\"unknown\");\n\t\t} else {\n\t\t\t$('#selected_rc').text(format_distance_short(selected.rc, DisplayUnits));\n\t\t}\n\n\t\tif (selected.sil == null || selected.sil_type == null) {\n\t\t\t$('#selected_sil').text(\"n/a\");\n\t\t} else {\n\t\t\tvar sampleRate = \"\";\n\t\t\tvar silDesc = \"\";\n\t\t\tif (selected.sil_type == \"perhour\") {\n\t\t\t\tsampleRate = \" per flight hour\";\n\t\t\t} else if (selected.sil_type == \"persample\") {\n\t\t\t\tsampleRate = \" per sample\";\n\t\t\t}\n\t\t\t\n\t\t\tswitch (selected.sil) {\n\t\t\t\tcase 0:\n\t\t\t\t\tsilDesc = \"&gt; 1×10<sup>-3</sup>\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tsilDesc = \"≤ 1×10<sup>-3</sup>\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsilDesc = \"≤ 1×10<sup>-5</sup>\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tsilDesc = \"≤ 1×10<sup>-7</sup>\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsilDesc = \"n/a\";\n\t\t\t\t\tsampleRate = \"\";\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$('#selected_sil').html(silDesc + sampleRate);\n\t\t}\n\n if (selected.uat_version == null) {\n $('#selected_version').text('none');\n } else if (selected.uat_version == 0) {\n $('#selected_version').text('v0 (DO-282)');\n } else if (selected.uat_version == 1) {\n $('#selected_version').text('v1 (DO-282A)');\n } else if (selected.uat_version == 2) {\n $('#selected_version').text('v2 (DO-282B)');\n } else {\n $('#selected_version').text('v' + selected.version);\n }\n\n }", "static get lastReport() {}", "function updateUI() {\n\tchrome.storage.local.get(\n\t\tfunction (storage) {\n\t\t\tvar progressState = storage.printQueueList.length;\n\t\t\tif (progressState != lastProgressState) {\n\t\t\t\tdisplayPrintTable();\n\t\t\t\tlastProgressState = progressState;\n\t\t\t}\n\t\t}\n\t);\n\treturn true;\n}", "handleShowPetitionReport() {\n this.setState({ showReport: !this.state.showReport });\n }", "function update() {\n updateMonthly(calculateMonthlyPayment(getCurrentUIValues()));\n}", "function currentTabs(tabs) {\n var loc = tbr.localSession_;\n consoleDebugLog('HAD local tabs:\\n' + tabsToString(loc.tabs));\n consoleDebugLog('GOT local tabs:\\n' + tabsToString(tabs));\n // Accept the new set of tabs\n loc.tabs = tabs;\n // if this is local session initialization, make generation = 0\n if (loc.generation < 0) {\n loc.generation = 0;\n }\n // Touch the session to update timestamp and generation.\n loc.touch();\n // For first-time init, we go init remote session now.\n if (!tbr.initialized_) {\n // Continue initialization by fetching remote storage.\n chrome.storage.sync.get(null, tbr.onStorageGet);\n } else { // after normal update go sync\n // Update status and session states. Note that this path can happen during\n // post-init syncing\n tbr.doSync_();\n }\n }", "function displaySelectedCUPortfolioCompTab(){\n var url = parent.location.href;\n s=url.indexOf(\"summary\");\n if (s!=-1){\n obj= document.getElementById('summary-li');\n if(obj){\n document.getElementById('summary').style.display=\"\";\n }\n }\n if (url.indexOf(\"basiccontrol\")!=-1){\n obj= document.getElementById('basiccontrol-li');\n if(obj){\n document.getElementById('basiccontrol').style.display=\"\";\n }\n }\n if (url.indexOf(\"auditreadyasmt\")!=-1){\n obj= document.getElementById('auditreadyasmt-li');\n if(obj){\n document.getElementById('auditreadyasmt').style.display=\"\";\n }\n }\n if (url.indexOf(\"riskmsdcommit\")!=-1){\n obj= document.getElementById('riskmsdcommit-li');\n if(obj){\n document.getElementById('riskmsdcommit').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"auditreview\")!=-1){\n obj= document.getElementById('auditreview-li');\n if(obj){\n document.getElementById('auditreview').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"kctest\")!=-1){\n obj= document.getElementById('kctest-li');\n if(obj){\n document.getElementById('kctest').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"opmetric\")!=-1){\n obj= document.getElementById('opmetric-li');\n if(obj){\n document.getElementById('opmetric').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"accountrating\")!=-1){\n obj= document.getElementById('accountrating-li');\n if(obj){\n document.getElementById('accountrating').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"other\")!=-1){\n obj= document.getElementById('other-li');\n if(obj){\n document.getElementById('other').style.display=\"\";\n }\n }\n}", "function updatePageData(){\n // Update current step number\n $(\".kf-current-step\").each(function(index) {\n $(this).text(currentStep);\n });\n }", "viewCurrentRecord(currentRow) {\r\n const awsAccountId = currentRow[AWS_ACCOUNT_FIELD.fieldApiName];\r\n this.selectedAwsAccountLabel = this.currentOceanRequest.applicationDetails.awsAccounts.filter(a => a.value === awsAccountId)[0].label;\r\n this.bShowModal = true;\r\n this.isEditForm = false;\r\n this.record = currentRow;\r\n }", "function displaySelectedCUHybridCompTab(){\n var url = parent.location.href;\n s=url.indexOf(\"summary\");\n if (s!=-1){\n obj= document.getElementById('summary-li');\n if(obj){\n document.getElementById('summary').style.display=\"\";\n }\n }\n if (url.indexOf(\"basiccontrol\")!=-1){\n obj= document.getElementById('basiccontrol-li');\n if(obj){\n document.getElementById('basiccontrol').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"cprating\")!=-1){\n obj= document.getElementById('cprating-li');\n if(obj){\n document.getElementById('cprating').style.display=\"\";\n }\n }\n if (url.indexOf(\"auditreadyasmt\")!=-1){\n obj= document.getElementById('auditreadyasmt-li');\n if(obj){\n document.getElementById('auditreadyasmt').style.display=\"\";\n }\n }\n if (url.indexOf(\"riskmsdcommit\")!=-1){\n obj= document.getElementById('riskmsdcommit-li');\n if(obj){\n document.getElementById('riskmsdcommit').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"auditreview\")!=-1){\n obj= document.getElementById('auditreview-li');\n if(obj){\n document.getElementById('auditreview').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"kctest\")!=-1){\n obj= document.getElementById('kctest-li');\n if(obj){\n document.getElementById('kctest').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"opmetric\")!=-1){\n obj= document.getElementById('opmetric-li');\n if(obj){\n document.getElementById('opmetric').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"other\")!=-1){\n obj= document.getElementById('other-li');\n if(obj){\n document.getElementById('other').style.display=\"\";\n }\n }\n}", "function showChangeTrackingTabCount()\r\n{\r\n $(document).ready(function()\r\n {\r\n \t//Change tracking tab button id\r\n \t//Tracker#: 19238 F2J. CHANGE TRACKING ON COMPETENCIES DOCUMENT\r\n \t//Tracker#: 18917 F4L - CHANGE TRACKING ON CAPACITY DOCUMENT\r\n \tif ($(\"#1237CenterCell\").length > 0 || $(\"#16377CenterCell\").length > 0\r\n \t || $(\"#16352CenterCell\").length > 0 || $(\"#16388CenterCell\").length > 0\r\n \t || $(\"#16389CenterCell\").length > 0 || $(\"#16390CenterCell\").length > 0\r\n \t || $(\"#1441CenterCell\").length > 0 || $(\"#16391CenterCell\").length > 0\r\n \t || $(\"#1304CenterCell\").length > 0 || $(\"#1497CenterCell\").length > 0\r\n\t\t\t || $(\"#16394CenterCell\").length > 0 || $(\"#16395CenterCell\").length > 0\r\n \t || $(\"#16401CenterCell\").length > 0 || $(\"#16404CenterCell\").length > 0\r\n || $(\"#16454CenterCell\").length > 0 || $(\"#2110CenterCell\").length > 0\r\n || $(\"#16555CenterCell\").length > 0 )\r\n \t{\r\n \t\tvar changeAjax = new htmlAjax();\r\n \t\tchangeAjax.setActionURL(\"changetrackviewerplm.do\");\r\n \t\tchangeAjax.setActionMethod(\"numberOfChanges\");\r\n \t\tchangeAjax.setProcessHandler(\"showNumCTChanges\");\r\n \t\tchangeAjax.showProcessingBar(false);\t//Tracker#: 20234 CHANGE TRACKING COUNT PERFORMANCE ON OVERVIEW SCREENS\r\n\r\n \t\tvar parentDocViewId = null;\r\n \t\tif ($(\"#1237CenterCell\").length > 0)\r\n \t\t{\r\n \t\t //TechSpec\r\n parentDocViewId = \"132\";\r\n \t\t}\r\n \t\telse if ($(\"#16377CenterCell\").length > 0)\r\n \t\t{\r\n \t\t //Material Projections\r\n \t\t\tparentDocViewId = \"5800\";\r\n \t\t}\r\n else if ($(\"#16352CenterCell\").length > 0)\r\n {\r\n //Material Quote Overview\r\n parentDocViewId = \"155\";\r\n }\r\n else if ($(\"#16388CenterCell\").length > 0)\r\n {\r\n //Material Library Overview\r\n parentDocViewId = \"3303\";\r\n }\r\n else if ($(\"#16389CenterCell\").length > 0)\r\n {\r\n //Artwork Library Overview\r\n parentDocViewId = \"4200\";\r\n }\r\n else if ($(\"#16390CenterCell\").length > 0)\r\n {\r\n //Color Library Overview\r\n parentDocViewId = \"2900\";\r\n }\r\n else if ($(\"#1441CenterCell\").length > 0)\r\n {\r\n //Color Palette Overview\r\n parentDocViewId = \"3500\";\r\n }\r\n else if ($(\"#16391CenterCell\").length > 0)\r\n {\r\n //Material Palette Overview\r\n parentDocViewId = \"6000\";\r\n }\r\n else if ($(\"#1304CenterCell\").length > 0)\r\n {\r\n //Submits\r\n parentDocViewId = \"3400\";\r\n }\r\n else if ($(\"#1497CenterCell\").length > 0)\r\n {\r\n //Fit Evaluation\r\n parentDocViewId = \"2406\";\r\n }\r\n \t\telse if ($(\"#16394CenterCell\").length > 0)\r\n \t\t{\r\n parentDocViewId = \"6800\";\r\n \t\t}\r\n\r\n \t\telse if ($(\"#16395CenterCell\").length > 0)\r\n \t\t{\r\n parentDocViewId = \"6801\";\r\n \t\t}\r\n \t\t//Tracker#: 19238 F2J. CHANGE TRACKING ON COMPETENCIES DOCUMENT\r\n \t\telse if ($(\"#16401CenterCell\").length > 0)\r\n \t\t{\r\n parentDocViewId = \"7000\";\r\n \t\t}\r\n \t\t//Tracker#: 18917 F4L - CHANGE TRACKING ON CAPACITY DOCUMENT\r\n \t\telse if ($(\"#16404CenterCell\").length > 0)\r\n \t\t{\r\n parentDocViewId = \"7300\";\r\n \t\t}\r\n else if ($(\"#16454CenterCell\").length > 0)\r\n {\r\n parentDocViewId = \"212\";\r\n }\r\n else if ($(\"#2110CenterCell\").length > 0)\r\n {\r\n parentDocViewId = \"321\";\r\n }\r\n else if ($(\"#16555CenterCell\").length > 0)\r\n {\r\n parentDocViewId = \"6304\";\r\n }\r\n changeAjax.parameter().add(\"parentDocViewId\", parentDocViewId);\r\n \t\tchangeAjax.sendRequest();\r\n \t}\r\n });\r\n}", "function setProgressMeterToQAPanel($currentPanel) {\n updateProgressMeter($('.js-profileQA-container form').index($currentPanel));\n }", "function saveAndPreview(){ \n\t\tvar view = tabsFrame.newView;\n\t\t//if (pattern.match(/highlight-thematic/gi) && prefix != 'drill' && view.tableGroups.tables[0].table_name != 'zone'){\n\t\tif (pattern.match(/highlight-thematic/gi)){\n\t\t\tvar drill2 = $('drill2Std').innerHTML;\n\t\t\tvar data = $('dataStd').innerHTML;\n\t\t\tvar requiredMsg = getMessage('required');\n\t\t\tif((drill2 == requiredMsg || data == requiredMsg) && view.tableGroups[0].tables[0].table_name != 'zone'){\n\t\t\t\talert(getMessage('noStandards'));\n\t\t\t} \n\t\t}\n\t\t\t\t\n if ((pattern.match(/paginated-parent/gi) && validateParameterRestrictions(view) == false) || !removeVirtualFields(view)){\n } else if(hasMeasuresInSummarizeBySortOrder() == false){\n \talert(getMessage('noStatistics')); \n } else {\n \ttabsFrame.selectTab('page5');\n \t}\n}", "_onCurrentChanged(sender, args) {\n const oldWidget = args.previousTitle\n ? this._findWidgetByTitle(args.previousTitle)\n : null;\n const newWidget = args.currentTitle\n ? this._findWidgetByTitle(args.currentTitle)\n : null;\n if (oldWidget) {\n oldWidget.hide();\n }\n if (newWidget) {\n newWidget.show();\n }\n this._lastCurrent = newWidget || oldWidget;\n this._refreshVisibility();\n }", "function displaySelectedCUHybridPortfolioCompTab(){\n var url = parent.location.href;\n s=url.indexOf(\"summary\");\n if (s!=-1){\n obj= document.getElementById('summary-li');\n if(obj){\n document.getElementById('summary').style.display=\"\";\n }\n }\n if (url.indexOf(\"basiccontrol\")!=-1){\n obj= document.getElementById('basiccontrol-li');\n if(obj){\n document.getElementById('basiccontrol').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"cprating\")!=-1){\n obj= document.getElementById('cprating-li');\n if(obj){\n document.getElementById('cprating').style.display=\"\";\n }\n }\n if (url.indexOf(\"auditreadyasmt\")!=-1){\n obj= document.getElementById('auditreadyasmt-li');\n if(obj){\n document.getElementById('auditreadyasmt').style.display=\"\";\n }\n }\n if (url.indexOf(\"riskmsdcommit\")!=-1){\n obj= document.getElementById('riskmsdcommit-li');\n if(obj){\n document.getElementById('riskmsdcommit').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"auditreview\")!=-1){\n obj= document.getElementById('auditreview-li');\n if(obj){\n document.getElementById('auditreview').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"kctest\")!=-1){\n obj= document.getElementById('kctest-li');\n if(obj){\n document.getElementById('kctest').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"opmetric\")!=-1){\n obj= document.getElementById('opmetric-li');\n if(obj){\n document.getElementById('opmetric').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"accountrating\")!=-1){\n obj= document.getElementById('accountrating-li');\n if(obj){\n document.getElementById('accountrating').style.display=\"\";\n }\n }\n\tif (url.indexOf(\"other\")!=-1){\n obj= document.getElementById('other-li');\n if(obj){\n document.getElementById('other').style.display=\"\";\n }\n }\n}", "function _makeReport() {\n document.getElementById(\"reportTable\").hidden = false;\n document.getElementById(\"chartContainer\").hidden = false;\n updateReportFromDB();\n}", "function setCurrent(){\n\t\t//set ls items\n\t\tlocalStorage.setItem('currentMiles', $(this).data('miles'));\n\t\tlocalStorage.setItem('currentDate', $(this).data('date'));\n\n\t\t//insert into the edit form\n\t\t$('#editMiles').val(localStorage.getItem('currentMiles'));\n\t\t$('#editDate').val(localStorage.getItem('currentDate'));\n\t}", "function updatePages() {\n $('#borrow-content .curr').html(currPage);\n $('#borrow-content .total').html(allPages);\n}", "function updateDisplay() {\n if (view == 'assignments') {\n $('#graded-items').hide();\n\n $('#assignments').show();\n $('.assignment-progress-bar').show();\n updateAssignments((a) => {\n assignments = a;\n displayAssignments(assignments);\n });\n } else if (view == 'gradedItems') {\n $('#assignments').hide();\n $('.assignment-progress-bar').hide();\n\n $('#graded-items').show();\n updateGradedItems((g) => {\n gradedItems = g;\n displayGradedItems(gradedItems);\n });\n }\n }", "function reloadActiveTabs() {\n\t\n\tvar formJsonData = null;\n\tif (dojo.byId(\"historyWritersJsonFormData\")) {\n\t\tformJsonData = \"historyWritersJsonFormData\";\n\t} else if (dojo.byId(\"historyWritersJsonFormData\")) {\n\t\tformJsonData = \"historyWritersJsonFormData\";\n\t}\n\n\ttry {\n\tdojo.parser.parse(\"referralHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"referralHistInfo\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"RefRel\"), false, 'strRefRel_Other', 'strRefRelOthLblWrp');\n\tinitializeReferralReasonsOtherFlds();\n\ttry {\n\tdojo.parser.parse(\"personalHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"personalHistInfo\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"rel_stat\"), false, \"rel_statOther\", \"mrtOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"LivingArrangeType\"), false, \"strLivingArrangeType_Other\", \"curLivArngOthLblWrp\");\n\n\ttry {\n\tdojo.parser.parse(\"languageSocialHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"languageSocialHistInfo\");\n\tinitializeDefaultRadioSelectionValues('LengthEnglishExposure');\n\tinitializeDefaultRadioSelectionValues('LengthEnglishSpoken');\n\tinitializeDefaultRadioSelectionValues('ObservedEnglish');\n\tinitializeDefaultRadioSelectionValues('Milestones_');\n\tinitializeLoopRadioSelections(dojo.byId(\"LengthEnglishExposure\"), \"strLengthEnglishExposure\", \"strLengthEnglishExposure_OtherWrp\");\n\tinitializeLoopRadioSelections(dojo.byId(\"LengthEnglishSpoken\"), \"strLengthEnglishSpoken_Other\", \"strLengthEnglishSpoken_OtherWrp\");\n\tinitializeLoopRadioSelections(dojo.byId(\"Milestones_Other\"), \"strMilestones_Other\", \"strMilestones_Other_Wrp\", 0, false);\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"DevelopmentAccord\"), false, 'strDevelopmentAccord_Other', 'strDevelopmentAccord_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"Birth_Other\"), false, 'strPregBirth_Other', 'Birth_Other', 'strPregBirth_OtherWrp');\n\n\ttry {\n\tdojo.parser.parse(\"educationHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"educationHistInfo\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"ed_level\"), false, \"ed_levelOther\", \"exmEduOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"EducMother\"), false, \"EducMother_Other\", \"mthEduOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"EducFather\"), false, \"EducFather_Other\", \"fthEduOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolPlacement\"), false, \"SchoolPlacement_Other\", \"schPlaceOthLblWrp\");\n\tcheckIfEducationCompletionRequired(dojo.byId(\"ed_level\"), 'EducProgComp');\n\tcheckIfEducationCompletionRequired(dojo.byId(\"EducMother\"), 'EducProgCompMother');\n\tcheckIfEducationCompletionRequired(dojo.byId(\"EducFather\"), 'EducProgCompFather');\n\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolAttendCurrent\"), false, \"SchoolAttendCurrent_Other\", \"schCurAtndOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolDiffCurrent\"), false, \"SchoolDiffCurrent_Other\", \"schDifOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolAttendPast\"), false, \"SchoolAttendPast_Other\", \"schPrvAtndOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolDiffPast\"), false, \"SchoolDiffPast_Other\", \"schPrvDifOthLblWrp\");\n\t\n\tinitializeDefaultRadioSelectionValues('AchieveTestRecent');\n\tinitializeDefaultRadioSelectionValues('AchieveTestPast');\n\tinitializeLoopRadioSelections(dojo.byId(\"AchieveTestRecent_Other\"), \"strAchieveTestRecent_Other\", \"strAchieveTestRecent_Other_Wrp\", 0, false);\n\tinitializeLoopRadioSelections(dojo.byId(\"AchieveTestPast_Other\"), \"strAchieveTestPast_Other\", \"strAchieveTestPast_Other_Wrp\", 0, false);\n\t\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"FreqSchoolChange\"), false, \"FreqSchoolChange_Other\", \"schChngOthLblWrp\");\n\tmanageChkBoxRelatedAcrdToOtherField(dojo.byId(\"EducAccord\"), false, \"EducAccord_Other\", \"schAcrdToOthLbl\", \"EducAccord_Other_Wrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"EducPreKindergarten\"), false, \"EducPreKindergarten_Other\", \"schPreKndrOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"EducPreFirstGrade\"), false, \"EducPreFirstGrade_Other\", \"schPre1stOthLblWrp\");\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"StrengthPersonal_Other\"), false, 'strStrengthPersonal_Other', 'StrengthPersonal_Other', 'strStrengthPersonal_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"WeaknessPersonal_Other\"), false, 'strWeaknessPersonal_Other', 'WeaknessPersonal_Other', 'strWeaknessPersonal_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"WeaknessCompPeers_Other\"), false, 'strWeaknessCompPeers_Other', 'WeaknessCompPeers_Other', 'strWeaknessCompPeers_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"StrengthCompPeers_Other\"), false, 'strStrengthCompPeers_Other', 'StrengthCompPeers_Other', 'strStrengthCompPeers_OtherWrp');\n\tmanageChkBoxMultiRelatedOtherField(dojo.byId(\"LearningDis_Other1\"), false);\n\tmanageChkBoxMultiRelatedOtherField(dojo.byId(\"LearningDis_Other2\"), false);\n\tmanageChkBoxMultiRelatedOtherField(dojo.byId(\"LearningDis_Other3\"), false);\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolAcadPerformCurrent\"), false, \"SchoolAcadPerformCurrent_Other\", \"schCurPerfOthLblWrp\"); \n\tmanageChkBoxRelatedOtherField(dojo.byId(\"SchoolAcadPerformPast\"), false, \"SchoolAcadPerformPast_Other\", \"schPastPerfOthLblWrp\"); \n\n\ttry {\n\tdojo.parser.parse(\"healthHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"healthHistInfo\");\n\tmanageChkBoxRelatedAcrdToOtherField(dojo.byId(\"HealthRef\"), false, \"HealthRef_Other\", \"hthAcrdToOthLbl\", \"HealthRef_Other_Wrp\");\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"VisionScreenResult_Other\"), false, 'strVisionScreenResult_Other', 'VisionScreenResult_Other', 'strVisionScreenResult_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"HearingScreenResult_Other\"), false, 'strHearingScreenResult_Other', 'HearingScreenResult_Other', 'strHearingScreenResult_OtherWrp');\n\tmanageLoopedChkBoxRelatedOtherField(dojo.byId(\"Sensory_Other\"), false, 'strSensory_Other', 'Sensory_Other', 'strSensory_OtherWrp');\n\tmanageChkBoxMultiRelatedOtherField(dojo.byId(\"Motor_OtherFM\"), false);\n\tmanageChkBoxMultiRelatedOtherField(dojo.byId(\"Motor_OtherGM\"), false);\n\tinitializeMedicalConditions(dojo.byId(\"MedCondition_None\"), dojo.byId(\"MedCondition_Unknown\"));\n\tinitSensoryConditions(dojo.byId('Sensory_None'), 'Sensory_', 'strSensory_Other', 'strSensory_OtherWrp');\n\tinitMotorConditions(dojo.byId('Motor_None'), 'Motor_', 'strMotor_OtherGM', 'strMotor_OtherGMWrp', 'strMotor_OtherFM', 'strMotor_OtherFMWrp');\n\tif(dojo.byId('CurrentMedication') != null){\n\t\tsetCount('CurrentMedication','medCount',255);\n\t}\n\t\n\ttry {\n\tdojo.parser.parse(\"employmentHistInfo\");\n\t} catch (e) {}\n\tfnConvertHistoryJsonToTab(formJsonData, \"employmentHistInfo\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"CurrentEmployStatus\"), false, \"CurrentEmployStatus_Other\", \"empCurStsOthLblWrp\");\n\tmanageChkBoxRelatedOtherField(dojo.byId(\"PreviousEmployStatus\"), false, \"PreviousEmployStatus_Other\", \"empPrvStsOthLblWrp\");\n\tcheckIfPositionTitleRequired(dojo.byId(\"CurrentEmployStatus\"), 'CurrentJobTitle', 'CurrentJobTitleWrp');\n\tcheckIfPositionTitleRequired(dojo.byId(\"PreviousEmployStatus\"), 'PreviousJobTitle', 'PreviousJobTitleWrp');\n}", "function toggle_report_block(path, element, id, newTitle, defaultTitle) {\n \n\t//toggle the image\n if(element.src.indexOf(\"plus\") != '-1') {\n \telement.src = element.src.replace(\"plus\", \"minus\");\n \telement.title = newTitle;\n \telement.alt = newTitle;\n } else {\n \telement.src = element.src.replace(\"minus\", \"plus\");\n \telement.title = defaultTitle;\n \telement.alt = defaultTitle;\n }\n \n //on success, find the report body and set its contents\n var php_report_success = function(o) {\n \tvar container = element.parentNode.parentNode.parentNode;\n \tset_content_in_class_tree(container, new Array('content', 'php_report_block', 'php_report_body'), 0, o.responseText);\n \t// Check for container's name, if it is undefined, it causes errors with my_handler\n \tif(container.name) {\n \tmy_handler = new associate_link_handler(path + 'dynamicreport.php', 'php_report_body_' + id);\n \tmy_handler.make_links_internal();\n \t}\n }\n \n var php_report_failure = function(o) {\n \talert(\"failure: \" + o.responseText);\n }\n \n //similar to profile_value.js\n var callback = {\n success: php_report_success,\n failure: php_report_failure\n }\n \n var requestURL = path + \"dynamicreport.php?id=\" + id;\n \n YAHOO.util.Connect.asyncRequest('GET', requestURL, callback, null);\n}", "function update() {\n getCurrentUIValues();\n calculateMonthlyPayment(UIValues);\n updateMonthly();\n}", "function Interpreter_UpdateDisplay()\n{\n\t//helpers\n\tvar uidObject, theObject;\n\t//loop through all of our iframes\n\tfor (uidObject in this.LoadedIFrames)\n\t{\n\t\t//get the object\n\t\ttheObject = this.LoadedIFrames[uidObject];\n\t\t//valid?\n\t\tif (theObject && theObject.HTML)\n\t\t{\n\t\t\t//purge all css data\n\t\t\tBrowser_RemoveCSSData_Purge(theObject.HTML.contentDocument);\n\t\t}\n\t}\n\t//purge all css data from main doc too\n\tBrowser_RemoveCSSData_Purge(document);\n\t//loop through all toplevel objects\n\tfor (uidObject in this.TopLevelObjects)\n\t{\n\t\t//get the object\n\t\ttheObject = this.TopLevelObjects[uidObject];\n\t\t//valid?\n\t\tif (theObject)\n\t\t{\n\t\t\t//update it with full recursion\n\t\t\ttheObject.UpdateDisplay(true);\n\t\t}\n\t}\n\t//rearrange the forms\n\tForm_RearrangeForms(this.FocusedFormId);\n\t//and reset this\n\tthis.FocusedFormId = [];\n\t//have we got a focused object id? (AND NOT IN DESIGNER)\n\tif (this.State && this.State.FocusedObjectId > 0)\n\t{\n\t\t//memorise it\n\t\tthis.FocusedObjectId = this.State.FocusedObjectId;\n\t}\n\t//we need to handle the tabs here\n\tthis.PreUpdatePostDisplay();\n}", "function openAppSpecificReportDialog() {\n var dialogHeight = 870;\n var dialogWidth = 1150;\n var frameSource = PageNavUserInfo.webAppContextPath + PageNavUserInfo.homeTabHtmlFragment.replace('.html', '-rpt.html');\n\n var dialogElement = $('#reportingDialog');\n dialogElement.attr('title','Graphics Sectors Report');\n dialogElement.attr('style','padding: 0');\n dialogElement.html('<iframe id=\"asb-report-frame\" src=\"' + frameSource + '\" width=\"99%\" height=\"99%\"></iframe>');\n\n dialogElement.dialog({ modal: true, autoOpen: false, draggable: false, width: 500 });\n var uiDialogTitle = $('.ui-dialog-title');\n $(uiDialogTitle).css('width', '75%');\n // TODO localize buttonlabel\n $(uiDialogTitle).after('<button class=\"ui-widget\" id=\"reportButton\" type=\"button\" onClick=\"onReportButtonClick(event);\" ' +\n 'style=\"float:right;margin-right:30px;\">' + 'Run Report' + '</button>' );\n dialogElement.dialog( 'option', \"position\", {my:\"right top\", at:\"right-10 top\"} );\n dialogElement.dialog( 'option', \"height\", dialogHeight );\n dialogElement.dialog( 'option', \"width\", dialogWidth );\n dialogElement.dialog('open');\n}", "updateCurrent() {\n let currentPage = page.getBasePath() + page.getCurrentFile();\n let current = this.navEl_.querySelector('a.current');\n if (current) {\n let href = current.getAttribute('href');\n if (href === currentPage) {\n return;\n }\n current.classList.remove('current');\n }\n\n let link = this.navEl_.querySelector(`a[href=\"${currentPage}\"]`);\n if (link) {\n link.classList.add('current');\n }\n }", "function setRecordInfo(selectButton) {\n var parent = selectButton.parent().parent();\n\n jQuery('#userFlag').html(parent.find('.ip img').clone());\n jQuery('#resolutionInfo').text(options.resolution.replace(' ', 'x') + ' ');\n jQuery('#resolutionInfo').append(parent.find('.browser').html());\n jQuery('#urlInfo').text(options.url);\n jQuery('#dateInfo').text(parent.find('.date').text());\n\n // Add the pages history to the session\n userTrackAjax.getRecordList(parent.attr('data-id'));\n }", "function handleChange(event, newValue) {\r\n setCurrentView(newValue); // newValue is the index of the tab that is selected\r\n }", "function updateReportDate(){\n\t\t//empty table if necessary\n\t\tif($(\"table.dataGrid tr\").length > 1){\n\t\t\t$(\"table.dataGrid tbody\").empty();\n\t\t}\n\t\t$('.container').hide();\n\t\t$.blockUI({ message: '<img src=\"images/busy.gif\" /> Saving New Report Date...' });\n\t\tvar reportDate = $(\"#reportDate\").val();\n\t\tvar ajaxParams = \"reportDate=\"+reportDate;\n\t\t$.ajax({\n\t\t\turl: \"/billing-circ/servlets/UpdateReportDate\",\n\t\t\tdataType: \"text\",\n\t\t\tdata: ajaxParams,\n\t\t\terror: function (xhr, desc, exceptionobj) {\n\t\t\t\t$.unblockUI();\n\t\t\t\t//add error message\n\t\t\t\t$.blockUI({ message: 'There was an error saving the report date. Please try again.' });\n\t\t\t\t setTimeout($.unblockUI, 2000);\n\t\t\t},\n\t\t\tsuccess: function(data){\n\t\t\t\t$.unblockUI();\n\t\t\t\t//add error message\n\t\t\t\t$.blockUI({ message: 'The report date was successfully saved.' });\n\t\t\t\t setTimeout($.unblockUI, 2000);\n\t\t\t}\n\t\t});\n\t}", "function changeTab (activeTab, activeComp, activeChart) {\n /* allows you to leave opening info page */\n $('#opening-info').click(function() {\n changePage('#opening-code');\n $('.navbar').hide();\n });\n\n $('#home-tab').click(function() {\n $(activeTab).removeClass('nav-item-active');\n activeTab = '#home-tab';\n $(activeTab).addClass('nav-item-active');\n changePage('#main');\n });\n\n /* this deals with clicking the save money button on home page */\n $('#save-button').click(function() {\n changePage('#save-money');\n });\n\n $('#comparisons-tab').click(function() {\n $(activeTab).removeClass('nav-item-active');\n activeTab = '#comparisons-tab';\n $(activeTab).addClass('nav-item-active');\n if (activeComp == '.to-fb') {\n changePage('#comp-fb');\n } else if (activeComp == '.to-reg') {\n changePage('#comp-reg');\n } else {\n changePage('#comp-you');\n }\n });\n\n $('#statistics-tab').click(function() {\n $(activeTab).removeClass('nav-item-active');\n activeTab = '#statistics-tab';\n $(activeTab).addClass('nav-item-active');\n if (activeChart == '.to-cost') {\n changePage('#charts-cost');\n } else if (activeChart == '.to-energy') {\n changePage('#charts-energy');\n } else if (activeChart == '.to-temp') {\n changePage('#charts-temp');\n } else {\n changePage('#charts-goals');\n }\n });\n\n /* this deals with the different settings pages */\n $('#settings-tab').click(function() {\n $(activeTab).removeClass('nav-item-active');\n activeTab = '#settings-tab';\n $(activeTab).addClass('nav-item-active');\n changePage('#settings');\n });\n\n $('#settings-to-thermo').click(function() {\n changePage('#settings-thermo');\n $('.change-code-info').hide();\n $('#change-code-general').show();\n });\n\n $('#settings-to-house').click(function() {\n changePage('#settings-house');\n });\n\n $('#settings-to-fb').click(function() {\n changePage('#settings-fb');\n });\n\n $('#settings-to-custom').click(function() {\n changePage('#settings-custom');\n });\n\n $('#settings-to-support').click(function() {\n changePage('#settings-support');\n });\n\n $('.settings-return').click(function() {\n changePage('#settings');\n });\n\n /* deals with the toggle on fb settings page */\n $('#settings-fb-share').click(function() {\n if ($('#settings-fb-toggle').hasClass('fa-toggle-on')) {\n $('#settings-fb-toggle').removeClass('fa-toggle-on');\n $('#settings-fb-toggle').addClass('fa-toggle-off');\n $('#settings-fb-toggle').css('color', '#000');\n } else {\n $('#settings-fb-toggle').removeClass('fa-toggle-off');\n $('#settings-fb-toggle').addClass('fa-toggle-on');\n $('#settings-fb-toggle').css('color', '#1b9af7');\n }\n });\n\n /* this is for the circle nav in the competitions page */\n $('.to-fb').click(function() {\n $(activeComp).removeClass('nav-item-active');\n activeComp = '.to-fb';\n $(activeComp).addClass('nav-item-active');\n changePage('#comp-fb');\n });\n\n $('.to-reg').click(function() {\n $(activeComp).removeClass('nav-item-active');\n activeComp = '.to-reg';\n $(activeComp).addClass('nav-item-active');\n changePage('#comp-reg');\n });\n\n $('.to-you').click(function() {\n $(activeComp).removeClass('nav-item-active');\n activeComp = '.to-you';\n $(activeComp).addClass('nav-item-active');\n changePage('#comp-you');\n });\n\n /* this is for the circle nav in the charts page */\n $('.to-cost').click(function() {\n $(activeChart).removeClass('nav-item-active');\n activeChart = '.to-cost';\n $(activeChart).addClass('nav-item-active');\n changePage('#charts-cost');\n });\n\n $('.to-energy').click(function() {\n $(activeChart).removeClass('nav-item-active');\n activeChart = '.to-energy';\n $(activeChart).addClass('nav-item-active');\n changePage('#charts-energy');\n });\n\n $('.to-temp').click(function() {\n $(activeChart).removeClass('nav-item-active');\n activeChart = '.to-temp';\n $(activeChart).addClass('nav-item-active');\n changePage('#charts-temp');\n });\n\n $('.to-goals').click(function() {\n $(activeChart).removeClass('nav-item-active');\n activeChart = '.to-goals';\n $(activeChart).addClass('nav-item-active');\n changePage('#charts-goals');\n });\n}", "function recall() {\n tabs.open({\n \"url\" : self.data.url(\"dashboard.html\"),\n });\n}", "function afterTabChange(tabPanel, currentTabName){\n\n\tvar currentTab = tabPanel.findTab(currentTabName);\n\tvar controller = abCompViolationController;\n\n\t//when content of tab is loaded\n\tif(currentTab.isContentLoaded){\t\n\n\t\t//if currently select first tab\n\t\tif(currentTabName==controller.selectTabName){\n\t\t\t //if sign needRefreshSelectList is true\n\t\t\tif(controller.needRefreshSelectList){\n\t\t\t\t //refresh the select list in first tab\n\t\t\t\tvar selectControl = currentTab.getContentFrame().View.controllers.get(controller.tabCtrl[currentTabName] );\n\t\t\t\tif(selectControl){\n\t\t\t\t\tselectControl.refreshGrid();\n\t\t\t\t\tcontroller.needRefreshSelectList = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "watchReport () {\n this.unwatchReport = this.$watch('report', () => {\n this.$root.bus.$emit('setReportUrl', null)\n }, { deep: true })\n }", "function reflectCurrent() {\n document.getElementById('current-'+ activePlayer).textContent = current;\n }", "function report (result){\n displayActions();\n displayInventory();\n displayScene();\n}", "function enableCurrent() {\n const parentNode = document.querySelectorAll('section')[0];\n loadData(parentNode, '.current-position', () => {\n const params = report2Params(document.querySelector('.weather-report'));\n params.temp = document.querySelector('p');\n params.icon = document.querySelector('.wi');\n params.city = document.querySelector('.place-current');\n\n navigator.geolocation.getCurrentPosition(async (position) => {\n const query = `${position.coords.latitude},${position.coords.longitude}`;\n await fillReport(query, params);\n }, async () => { await fillReport(defaultCity, params); });\n }, 500);\n}", "function dashboardUpdateAll() {\n\t\tdashboardSet('stars', whiteStar + whiteStar + whiteStar);\n\t\tdashboardSet('tally', 0);\n\t\tdashboardSet('reset', semicircleArrow);\n\t\tdocument.getElementsByClassName('current-timer')[0].innerHTML = \"00:00\";\n}" ]
[ "0.67155343", "0.6127847", "0.5851364", "0.57509166", "0.57420653", "0.57214427", "0.56491613", "0.5638274", "0.5601469", "0.557395", "0.5543187", "0.54939914", "0.5481291", "0.54346865", "0.5394556", "0.53553957", "0.5354937", "0.53443617", "0.53352153", "0.53268355", "0.53210527", "0.5294531", "0.52564436", "0.5242492", "0.52286977", "0.5206174", "0.5202418", "0.5192517", "0.51828337", "0.51733077", "0.51706946", "0.5154772", "0.5148478", "0.5143022", "0.5134285", "0.51291585", "0.5119517", "0.5116786", "0.5103493", "0.5100501", "0.5098074", "0.5093633", "0.5093558", "0.5087997", "0.5071591", "0.5070669", "0.5055336", "0.50552523", "0.50552523", "0.5054952", "0.5046253", "0.50381994", "0.5037943", "0.5034846", "0.50280625", "0.5025274", "0.5021653", "0.50156975", "0.50049305", "0.50049305", "0.50049305", "0.50002766", "0.49954465", "0.4982911", "0.49815333", "0.4981234", "0.4977581", "0.49724382", "0.49630544", "0.4958824", "0.4955166", "0.49537528", "0.49522474", "0.49489364", "0.49415803", "0.4938616", "0.4936339", "0.4933238", "0.49300024", "0.4929492", "0.49171916", "0.4914571", "0.48867652", "0.48822176", "0.48796234", "0.48794", "0.487935", "0.48659056", "0.48640528", "0.48638242", "0.48624963", "0.4848058", "0.48468947", "0.48438734", "0.4842658", "0.48356682", "0.4832236", "0.48304704", "0.48211595", "0.48182154", "0.48157775" ]
0.0
-1
END OF Reporting Code START OF Util Code
function my_log(msg, error) { var ln = error.lineNumber; var fn = error.fileName.split('->').slice(-1)[0].split('/').splice(-1)[0]; console.log(fn + "," + ln + ": " + msg); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private internal function m248() {}", "private public function m246() {}", "protected internal function m252() {}", "static private internal function m121() {}", "function DWRUtil() { }", "transient private protected internal function m182() {}", "static final private internal function m106() {}", "transient protected internal function m189() {}", "transient private internal function m185() {}", "function Util() {}", "static private protected internal function m118() {}", "function AeUtil() {}", "static transient private protected internal function m55() {}", "static transient final private internal function m43() {}", "transient final protected internal function m174() {}", "static transient final protected internal function m47() {}", "function Utils(){}", "static transient final private protected internal function m40() {}", "transient private protected public internal function m181() {}", "function Utils() {}", "function Utils() {}", "transient final private protected internal function m167() {}", "static transient final protected public internal function m46() {}", "static private protected public internal function m117() {}", "static final private protected internal function m103() {}", "static protected internal function m125() {}", "function _____SHARED_functions_____(){}", "static final private protected public internal function m102() {}", "static transient private internal function m58() {}", "static transient private protected public internal function m54() {}", "static final protected internal function m110() {}", "static final private public function m104() {}", "transient final private internal function m170() {}", "transient final private protected public internal function m166() {}", "static transient private public function m56() {}", "function Utils() {\n}", "static transient final protected function m44() {}", "static transient final private protected public internal function m39() {}", "transient private public function m183() {}", "static transient final private protected public function m38() {}", "static private public function m119() {}", "function TMP() {\n return;\n }", "function FAADataHelper() {\n}", "static transient final private public function m41() {}", "function Helper() {}", "static transient protected internal function m62() {}", "function CCUtility() {}", "expected( _utils ) {\n\t\t\treturn 'nothing';\n\t\t}", "function SBRecordsetPHP_analyzePlatformSpecific()\r\n{\r\n\r\n\r\n}", "function StupidBug() {}", "function __it() {}", "function SigV4Utils() { }", "static get END() { return 6; }", "function FunctionUtils() {}", "function AppUtils() {}", "function TMP(){return;}", "function TMP(){return;}", "transient final private public function m168() {}", "function eUtil() {\n\n //Get URL Parameters by name\n function getUrlParam(name){\n if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))\n return decodeURIComponent(name[1]);\n }\n\n}", "obtain(){}", "function kp() {\n $log.debug(\"TODO\");\n }", "function Scdr() {\r\n}", "function jessica() {\n $log.debug(\"TODO\");\n }", "function accessesingData2() {\n\n}", "function accessesingData2() {\n\n}", "function Util() {\n\t\"use strict\";\n\tvar ii;\n\n\tthis.golfStatements = JSON.parse(JSON.stringify(golfStatements)); // \"clone\"\n\tfor (ii = 0; ii < this.golfStatements.length; ii++) {\n\t\tif (this.golfStatements[ii].actor) {\n\t\t\tthis.golfStatements[ii].actor.mbox = this.actor.mbox;\n\t\t\tthis.golfStatements[ii].actor.name = this.actor.name;\n\t\t}\n\t\tthis.golfStatements[ii].id = this.ruuid();\n\t}\n}", "function o0(o1)\n{\n var o2 = -1;\n try {\nfor (var o259 = 0; o3 < o1.length; function (o502, name, o38, o781, o782, o837, o585, o838, o549) {\n try {\no839.o468();\n}catch(e){}\n // TODO we should allow people to just pass in a complete filename instead\n // of parent and name being that we just join them anyways\n var o840 = name ? o591.resolve(o591.o592(o502, name)) : o502;\n\n function o841(o842) {\n function o843(o842) {\n try {\nif (!o838) {\n try {\no474.o800(o502, name, o842, o781, o782, o549);\n}catch(e){}\n }\n}catch(e){}\n try {\nif (o837) try {\no837();\n}catch(e){}\n}catch(e){}\n try {\no334('cp ' + o840);\n}catch(e){}\n }\n var o844 = false;\n try {\nModule['preloadPlugins'].forEach(function (o845) {\n try {\nif (o844) try {\nreturn;\n}catch(e){}\n}catch(e){}\n try {\nif (o845['canHandle'](o840)) {\n try {\no845['handle'](o842, o840, o843, function () {\n try {\nif (o585) try {\no585();\n}catch(e){}\n}catch(e){}\n try {\no334('cp ' + o840);\n}catch(e){}\n });\n}catch(e){}\n try {\no844 = true;\n}catch(e){}\n }\n}catch(e){}\n });\n}catch(e){}\n try {\nif (!o844) try {\no843(o842);\n}catch(e){}\n}catch(e){}\n }\n try {\no332('cp ' + o840);\n}catch(e){}\n try {\nif (typeof o38 == 'string') {\n try {\no839.o846(o38, function (o842) {\n try {\no841(o842);\n}catch(e){}\n }, o585);\n}catch(e){}\n } else {\n try {\no841(o38);\n}catch(e){}\n }\n}catch(e){}\n })\n {\n try {\nif (o1[o3] == undefined)\n {\n try {\nif (o2 == -1)\n {\n try {\no2 = o3;\n}catch(e){}\n }\n}catch(e){}\n }\n else\n {\n try {\nif (o2 != -1)\n {\n try {\no4.o5(o2 + \"-\" + (o3-1) + \" = undefined\");\n}catch(e){}\n try {\no2 = -1;\n}catch(e){}\n }\n}catch(e){}\n try {\no4.o5(o3 + \" = \" + o1[o3]);\n}catch(e){}\n }\n}catch(e){}\n }\n}catch(e){}\n}", "lastUsed() { }", "function main() {\n // Variables\n var\n // the user agent object before adding\n uaInfo = {},\n\n // cashing the navigator.userArgent String\n uaString = navigator.userAgent;\n\n\n for ( var k in PREFIXES ) {\n // add to userAgentInfo the positive resulte item\n uaInfo[k] = testUserAgentAgaintsChecklist( PREFIXES[k], uaString );\n\n // add to userAgentInfo an array of negative resault\n uaInfo[ PREFIX_NOT + k ] = filterChecklist( PREFIXES[k], uaInfo[k] );\n }\n\n // check for mobile\n uaInfo[ PREFIX_MOBILE ] = testUserAgentIfMobile( MOBILE, uaString );\n\n // adding to the root element classes of useragent result\n addCSSClassesToElement( document.documentElement, uaInfo );\n\n // add languages\n // the languages is done after the css is being added\n // so won't be language classes\n addLanguageToUserAgent( uaInfo );\n\n // check & backup if there is object in the globalscope and add to the global scope\n if ( 'userAgentInfo' in window ) oldUserAgentInfo = window.userAgentInfo;\n\n // add the userAgentInfo to the global scope\n window.userAgentInfo = uaInfo;\n }", "function Kutility() {\n\n}", "function Kutility() {\n\n}", "static get SUCCESS() { return 0; }", "__previnit(){}", "function TMP(){}", "function TMP(){}", "function WebIdUtils () {\n}", "function check_and_report() {\n \n }", "function GraFlicUtil(paramz){\n\t\n}", "static fromCASFile(casfile) {\n//-----------\nlggr.warn(\"fromCASFile: Not implemented\");\nreturn void 0;\n}", "function fos6_c() {\n ;\n }", "function Common(){}", "function _____INTERNAL_log_functions_____(){}\t\t//{", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "function o700() {\n try {\nif (o947()) {\n try {\no90.o361.o109 = o90.o361.o989;\n}catch(e){}\n try {\no90.o361.o110 = o90.o361.o990;\n}catch(e){}\n }\n}catch(e){}\n}", "analyze(){ return null }", "static get elvl_info() {return 0;}", "function Utils() {\n // All of the normal singleton code goes here.\n }", "_validate() {\n\t}", "function DCKBVCommonUtils() {\n // purely static object at the moment, nothing in the instances.\n }", "static get ERROR () { return 0 }", "function HTTPUtil() {\n}", "prepare() {}", "function fm(){}", "static ready() { }", "function miFuncion (){}", "static get INVALID()\n\t{\n\t\treturn 2;\n\t}", "function MainScript() {\n debug('');\n audit('MainScript', '======START======');\n // processFile( // UNIQUE INSTITUTION\n // './ABAI_RAW/UNIQUE.csv',\n // 'A Spicy Boy', parseUniqueInstitution, UNIQUE_INSTITUTIONS\n // );\n processFile( // INSTITUTION\n './ABAI_RAW/unique.csv',//abaiBatchRecord[ 'custrecord_institue_fileid' ),\n ABAI_TABLES.INSTITUTION, parseInstitution, ABAI_INSTITUTION,\n );\n // debug(JSON.stringify(ABAI_INSTITUTION));\n file.writeFileSync('./RC_RAW/' + 'fuckthisgarbage' + '.json', JSON.stringify(ABAI_INSTITUTION) );\n processFile( // DEPARTMENT ID\n './ABAI_RAW/NetSuiteInstitution-Department.csv',//abaiBatchRecord[ 'custrecord_institue_fileid' ),\n 'depo', parseDepo, ABAI_DEPARTMENT,\n );\n // debug(JSON.stringify(ABAI_INSTITUTION));\n file.writeFileSync('./RC_RAW/' + 'fuckthisgarbageDepartment' + '.json', JSON.stringify(ABAI_DEPARTMENT) );\n // debug('Matched: ' + matchedInstitutions + ' : ' + unMatchedInstitutions)\n processFile( // INSTITUTION ADDRESS\n './ABAI_RAW/institution_address.csv',//abaiBatchRecord['custrecord_institueaddr_fileid'),\n ABAI_TABLES.INSTITUTION_ADDRESS, parseInstitutionAddress, ABAI_INSTITUTION_ADDRESS\n );\n file.writeFileSync('./RC_RAW/' + 'garbageIA' + '.json', JSON.stringify(ABAI_INSTITUTION_ADDRESS) );\n processFile( // COORDINATOR\n './ABAI_RAW/coordinator.csv',//abaiBatchRecord['custrecord_coordinaor_fileid'),\n ABAI_TABLES.COORDINATOR, parseCoordinator, ABAI_COORDINATOR\n );\n file.writeFileSync('./RC_RAW/' + 'garbagecoord' + '.json', JSON.stringify(ABAI_COORDINATOR) );\n processFile( // COURSE SEQUENCE\n './ABAI_RAW/course_sequence.csv',//abaiBatchRecord['custrecord_coursesseq_fileid'),\n ABAI_TABLES.COURSE_SEQUENCE, parseCourseSequence, ABAI_COURSE_SEQUENCE\n );\n file.writeFileSync('./RC_RAW/' + 'garbageCS' + '.json', JSON.stringify(ABAI_COURSE_SEQUENCE) );\n processFile( // COURSE\n './ABAI_RAW/course.csv',//abaiBatchRecord['custrecord_course_fileid'),\n ABAI_TABLES.COURSE, parseCourse, ABAI_COURSE\n );\n file.writeFileSync('./RC_RAW/' + 'garbageCourse' + '.json', JSON.stringify(ABAI_COURSE) );\n processFile( // AP WAIVER\n './ABAI_RAW/ap_waiver.csv', //abaiBatchRecord['custrecord_apwaiver_fileid'),\n ABAI_TABLES.APWAIVER, parseApWaiver, ABAI_AP_WAIVER\n );\n file.writeFileSync('./RC_RAW/' + 'garbageWaiver' + '.json', JSON.stringify(ABAI_AP_WAIVER) );\n processFile( // INSTRUCTOR GROUP\n './ABAI_RAW/instructor_group.csv',//abaiBatchRecord['custrecord_instructorgrp_fileid'),\n ABAI_TABLES.INSTRUCTOR_GROUP, parseInstructor, ABAI_INSTRUCTOR\n );\n processFile( // COURSE SEQUENCE ASSIGNMENT\n './ABAI_RAW/course_sequence_course_assignment.csv',//abaiBatchRecord['custrecord_courseseq_crsass_fileid'),\n ABAI_TABLES.COURSE_ASSIGNEMNT, parseAssignment, ABAI_ASSIGNMENT\n );\n file.writeFileSync('./RC_RAW/' + 'garbageCSA' + '.json', JSON.stringify(ABAI_ASSIGNMENT) );\n file.writeFileSync('./RC_RAW/' + 'garbageCSA2' + '.json', JSON.stringify(ABAI_XREF.CourseToCourseSequence) );\n processFile( // ALT COURSE ID\n './ABAI_RAW/alternative_courseID.csv', //abaiBatchRecord['custrecord_alt_courseid_fileid'),\n ABAI_TABLES.ALT_COURSE_ID, parseAltCourseId, ABAI_ALT_ID\n );\n file.writeFileSync('./RC_RAW/' + 'altCourse' + '.json', JSON.stringify(ABAI_ALT_ID) );\n processFile( // CONTENT HOURS\n './ABAI_RAW/content_hours.csv',//abaiBatchRecord['custrecord_cont_hours_fileid'),\n ABAI_TABLES.CONTENT_HOURS, parseContentHours, ABAI_CONTENT_HOURS\n );\n file.writeFileSync('./RC_RAW/' + 'CHGarbage' + '.json', JSON.stringify(ABAI_CONTENT_HOURS) );\n processFile( // ALLOCATION HOURS\n './ABAI_RAW/content_area_hours_allocation.csv', //abaiBatchRecord['custrecord_cont_hsallocat_fileid'),\n ABAI_TABLES.ALLOCATION, parseAllocation, ABAI_ALLOCATION_HOURS\n );\n file.writeFileSync('./RC_RAW/' + 'garbageAllocation' + '.json', JSON.stringify(ABAI_ALLOCATION_HOURS) );\n audit('MainScript', 'FILE LOAD COMPLETE');\n file.writeFileSync('./RC_RAW/' + 'xref_sequence' + '.json', JSON.stringify(ABAI_XREF.CourseToCourseSequence));\n\n\n audit('MainScript', '=======END=======');\n}", "function _main() {\n try {\n // the modules own main routine\n //_logCalls();\n\n // enable a global accessability from window\n window.tools = {} || window.tools;\n window.tools._log = _log;\n window.tools._addNavigation = _addNavigation;\n } catch (error) {\n console.log(error);\n }\n\n }", "function MapDataUtils(){\n\t\t\n\t\t/**\n\t\t * Extracts path-coord. from polyline.\n\t\t * @param polyline : PolylineHolder\n\t\t * @return [google.maps.LatLng]\n\t\t */\n\t\tthis.extractPath = function(polyline){\t\t\t\n\t\t\tthrow new Error('This is abstract');\n\t\t};\n\t\t\n\t\t/**\n\t\t * Request for geocoding of the given address.\n\t\t * @param args : {address : string} or string\n\t\t * @param callback : function(err, {latitude: integer, longitude: integer, noResult: boolean})\n\t\t */\n\t\tthis.findCoordFromAddress = function(args, callback){\n\t\t\tthrow new Error('This is abstract');\n\t\t};\n\t}" ]
[ "0.7060762", "0.6922038", "0.67473304", "0.67428106", "0.6553565", "0.6511141", "0.6493171", "0.6472616", "0.6391483", "0.6388277", "0.6318973", "0.62596005", "0.62387264", "0.62007105", "0.61873996", "0.6160373", "0.6055391", "0.605386", "0.604838", "0.60331804", "0.60331804", "0.6005903", "0.5980503", "0.59056985", "0.5866265", "0.5860877", "0.58474827", "0.58409005", "0.58206826", "0.5795387", "0.57260317", "0.5605203", "0.5605074", "0.55881566", "0.5587779", "0.5519763", "0.5509276", "0.5490589", "0.54817826", "0.5467568", "0.5459832", "0.5414564", "0.54035324", "0.53932786", "0.53582925", "0.53387505", "0.528351", "0.52773887", "0.5244107", "0.5223724", "0.518594", "0.5183996", "0.5173319", "0.5165769", "0.5163184", "0.51522523", "0.51522523", "0.5092412", "0.50911444", "0.505414", "0.50364476", "0.5033233", "0.5009864", "0.5005146", "0.5005146", "0.49981847", "0.4997253", "0.4993567", "0.49844578", "0.49752724", "0.49752724", "0.49748898", "0.4967308", "0.49624327", "0.49624327", "0.4960696", "0.49544126", "0.49444255", "0.4935628", "0.49330652", "0.4919892", "0.48945612", "0.4894514", "0.4894514", "0.4894514", "0.48943436", "0.48833433", "0.48821393", "0.48805472", "0.4873074", "0.48712483", "0.4869264", "0.4859813", "0.48477927", "0.48425964", "0.4830685", "0.48280466", "0.48257968", "0.48037764", "0.48014134", "0.48013696" ]
0.0
-1
Only useful for reading extension specific files
function read_file(filename) { var file_data = data.load(filename); return file_data; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fileExtension(str){\n\n // code goes here\n\n}", "getFileExtension1(filename) {\r\n return /[.]/.exec(filename) ? /[^.]+$/.exec(filename)[0] : undefined;\r\n }", "function getExtension(_filename){\n let extension =_filename.split('.');\n extension=extension[extension.length-1];\n return extension.toLowerCase();\n\n}", "function tryExtensions (p, exts) {\n for (let i = 0, EL = exts.length; i < EL; i++) {\n let filename = tryFile(p + exts[i])\n\n if (filename) {\n return filename\n }\n }\n return false\n}", "supportedExtExtract(filename) {\n let extensions = [\"csv\", \"doc\", \"docx\", \"eml\", \"epub\", \"gif\", \"htm\", \"html\",\n \"jpeg\", \"jpg\", \"json\", \"log\", \"mp3\", \"msg\", \"odt\", \"ogg\",\n \"pdf\", \"png\", \"pptx\", \"ps\", \"psv\", \"rtf\", \"tff\", \"tif\",\n \"tiff\", \"tsv\", \"txt\", \"wav\", \"xls\", \"xlsx\"];\n return extensions.some(ext => filename.endsWith(ext));\n }", "function tryExtensions(p, exts, isMain) {\n\t for (var i = 0; i < exts.length; i++) {\n\t const filename = tryFile(p + exts[i]);\n\n\t if (filename) {\n\t return filename;\n\t }\n\t }\n\t return false;\n\t }", "readBuiltinFiles(filename) {\n if (Sk.builtinFiles === undefined ||\n Sk.builtinFiles[\"files\"][filename] === undefined) {\n throw \"File not found: '\" + filename + \"'\";\n }\n\n return Sk.builtinFiles[\"files\"][filename];\n }", "supportedExt(filename) {\n let extensions = [\"doc\", \"docx\", \"odt\", \"pdf\", \"rtf\", \"txt\"];\n return extensions.some(ext => filename.endsWith(ext));\n }", "function getExtention(file) {\n // surasti prievardi\n // jei yra . tai yra prievardis\n let dot = file.lastIndexOf(\".\");\n console.log(\"dot\", dot);\n if (dot !== -1) {\n let prievardis = file.slice(dot);\n console.log(prievardis);\n } else {\n console.warn(\"prievardzio nera\");\n }\n}", "function tryExtensions(p, exts) {\n for (var i = 0, EL = exts.length; i < EL; i++) {\n var filename = tryFile(p + exts[i]);\n\n if (filename) {\n return filename;\n }\n }\n return false;\n}", "getFileExtension(filename) {\n return filename.slice((filename.lastIndexOf(\".\") - 1 >>> 0) + 2);\n }", "function tryExtensions(p, exts, isMain) {\r\n for (var i = 0; i < exts.length; i++) {\r\n\r\n var filename = tryFile(p + exts[i], isMain);\r\n\r\n if (filename) {\r\n return filename;\r\n }\r\n }\r\n return false;\r\n}", "function printFiles(files,fileExt){\nfor (var i=0;i<files.length;i++){\n\tif(fileExt==files[i][1])\n\t\tconsole.log(files[i][0]+\".\"+files[i][1])\n\n}\n\n}", "function getExt(files) {\n return files.map(function(file) {\n return path.extname(file);\n }).filter(function(item, index, arr) {\n return index === arr.indexOf(item);\n });\n}", "function getExtension(file){\n file = file.split(\".\");\n return file[1];\n}", "getExtForIcon(filePath /*:string*/) /*:string*/ {\n const customExtensions = {\n '.deps.js': '.apib',\n '.bemhtml.js': '.bemjson.js',\n '.priv.js': '.node'\n };\n\n for (const ext in customExtensions) {\n if (customExtensions.hasOwnProperty(ext) && filePath.endsWith(ext)) {\n return customExtensions[ext];\n }\n }\n\n return filePath;\n }", "function findByExt(base,exts,files,result) \n{\n files = files || fs.readdirSync(base) \n result = result || [] \n\n files.forEach( \n function (file) {\n var newbase = path.join(base,file)\n if (!fs.statSync(newbase).isDirectory())\n {\n for (let i = 0; i < exts.length; i++) {\n const ext = exts[i];\n if ( file.substr(-1*(ext.length+1)) == '.' + ext )\n {\n result.push(newbase);\n break;\n } \n }\n }\n }\n )\n return result\n}", "function getExtensionFile(filename) {\n return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;\n}", "function getFileExtension(filename){\t\n\treturn filename.substr(filename.lastIndexOf('.')+1);\n}", "function fileChecker(directory, ext, callback){\n \n fs.readdir(directory, (err, fileData) => {\n if(err) return callback(err);\n // if (err) {console.log(\"Error Received in readdir\");}\n\n let items = []\n fileData.forEach(file => {\n if (path.extname(file) === \".\" + ext) {\n items.push(file);\n }\n\n });\n callback(null, items);\n });\n}", "function getFileList(extension){\n $scope[extension+'_list'] = \"\";\n File.getFiles({ filter: extension, location: ProjectObject.original_location }).then(function (resp) {\n $scope[extension+'_list'] = resp;\n $scope[extension+'_file'] = resp[0];\n getFileContent(extension);\n },function(error){\n });\n }", "function file_ext(file) {\n return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';\n }", "function getExtension(){\n\tvar files = fs.readdirSync(\"tests\");\n\t// check for main in the files list\n\t// could get more fancy like finding the most frequent extension\n\tvar first = files[0].split(\".\");\n\tvar ext = first[1];\n\treturn ext;\n}", "getFileExtension(docName) {\n let fileExtension;\n let documentArray = docName.split('.');\n if(documentArray.length > 2)\n {\n let fileExtensionArray = documentArray[2].split('/');\n fileExtension = fileExtensionArray[fileExtensionArray.length - 1];\n } \n else\n fileExtension = documentArray[1];\n \n return fileExtension;\n\n }", "function getFileIcon(ext) {\n return ( ext && extensionsMap[ext.toLowerCase()]) || 'fa-file-o';\n}", "function findFileExtention(filename){\nalert(filename.split('.').pop());\n}", "getExtension() {\n return this.rawFilename.substr(8).trim();\n }", "function _get_extention(filename)\n\t\t{\n\t\t\treturn filename.split('.').pop();\n\t\t}", "_parseFilename(filePath) {\n const parts = filePath.split(\".\");\n this.extension = parts[parts.length - 1];\n this._log(\"File extension:\", this.extension);\n }", "function getExtension(filename) {\n return filename.split('.').pop();\n }", "hasExtension(fileName) {\n return (new RegExp(`(${this.props.imgExtension.join('|').replace(/\\./g, '\\\\.')})$`)).test(fileName);\n }", "function getFileExtension(filename) {\n return filename.split('.').pop();\n }", "function extractFiles(data, options){\n return data.entries.filter(entry => entry[`.tag`] === `file` && options.extensions.includes(path.extname(entry.name)))\n}", "function getExtension(fpath) {\n var sp = fpath.split(\".\");\n return sp[1];\n}", "function getExtension(fpath) {\n var sp = fpath.split(\".\");\n return sp[1];\n}", "function extension(filename){\n return filename.split('.').pop();\n}", "function readExtFile(path) {\n // const id = \"{65b3130e-8513-41b6-8ea8-43dbd9cc0bf5}\";\n // try {\n var file = Components.classes[\"@mozilla.org/extensions/manager;1\"]\n .getService(Components.interfaces.nsIExtensionManager)\n .getInstallLocation(id)\n .getItemFile(id, \"chrome/content/data/\" + path);\n var data = \"\";\n var fstream = Components.classes[\"@mozilla.org/network/file-input-stream;1\"]\n .createInstance(Components.interfaces.nsIFileInputStream);\n var sstream = Components.classes[\"@mozilla.org/scriptableinputstream;1\"]\n .createInstance(Components.interfaces.nsIScriptableInputStream);\n fstream.init(file, -1, 0, 0);\n sstream.init(fstream); \n \n var str = sstream.read(16384);\n while (str.length > 0) {\n data += str;\n str = sstream.read(128000);\n }\n sstream.close();\n fstream.close();\n // }\n // catch(e) { alert(e); }\n return data;\n}", "function getFileExtension(filename) {\n var pos = filename.lastIndexOf('.');\n if (pos != -1)\n return filename.substring(pos+1);\n else // if '.'' never occurs\n return '';\n }", "function getFileExtension(filename) {\n return filename ? filename.split('.').pop() : '';\n}", "isSupportedExtension(filename) {\n const ext = path.extname(filename);\n let result = false;\n this.supportedExtensions.forEach((item) => {\n if (item === ext) {\n result = true;\n }\n });\n return result;\n }", "function getExtension(filename) {\n return filename.substr(filename.lastIndexOf('.') + 1).toLowerCase();\n}", "filesWithExtensionSync(params) {\n if (!objects().isDefined(params))\n throw new TypeError(\n `We expected params to be defined, but it was ${params}.`\n );\n\n const { dir, ext } = params;\n\n if (!objects().isDefined(dir))\n throw new TypeError(\n `We expected params.dir to be defined, but it was ${dir}.`\n );\n if (!objects().isDefined(ext))\n throw new TypeError(\n `We expected params.ext to be defined, but it was ${ext}.`\n );\n\n const files = this.readdirSync(dir);\n const filesWithExt = [];\n const divider = strings().endsWith(dir, \"/\") ? \"\" : \"/\";\n files.forEach((file) => {\n if (strings().endsWith(file.toLowerCase(), \".\" + ext)) {\n filesWithExt.push(dir + divider + file);\n }\n });\n return filesWithExt;\n }", "function filterFilesByExt(files, exts) {\n 'use strict';\n //console.log(\"%s: filterFilesByExt: exts = %j\", MODNAME, exts)\n return files.filter(function(fn) {\n for (let ext of exts) {\n // test the file's extension name (minus the leading '.')\n if (path.extname(fn).substr(1) == ext) {\n return true\n }\n }\n return false\n })\n}", "function getfileextension(filename) { \r\n\tif (!filename || filename == null || filename.length == 0) return \"\";\r\n\tvar dot = filename.lastIndexOf(\".\"); \r\n\tif (dot == -1) return \"\"; \r\n\tvar extension = filename.substr(dot+1,filename.length); \r\n\treturn extension; \r\n}", "getFiles() { throw new Error('Should be overridden in subclass.') }", "getFileExtension() {\n throw new TypeError(\"Stub.\");\n }", "function getExtension(filename){\n\treturn splitFromBack(filename, '.')[1];\n}", "static matchFilename(descs, filename) {\n for (let d of descs)\n if (d.filename && d.filename.test(filename))\n return d;\n let ext = /\\.([^.]+)$/.exec(filename);\n if (ext)\n for (let d of descs)\n if (d.extensions.indexOf(ext[1]) > -1)\n return d;\n return null;\n }", "function isAllowedFileExtensionWhiteList(ext) {\n\tif (!window.acceptedFileExtensions) {\n\t\twindow.acceptedFileExtensions =\n\t\t{\n\t\t\t'.123':1,'.3g2':1,'.3gp':1,'.3gp2':1,'.7z':1,'.aac':1,'.abw':1,'.abx':1,'.accdb':1,'.accde':1,\n\t\t\t'.accdr':1,'.accdt':1,'.accfl':1,'.ace':1,'.ade':1,'.adp':1,'.aeh':1,'.ai':1,'.aif':1,'.aiff':1,\n\t\t\t'.amr':1,'.apng':1,'.arc':1,'.art':1,'.asc':1,'.asf':1,'.asx':1,'.atom':1,'.au':1,'.avi':1,\n\t\t\t'.awt':1,'.azw':1,'.azw1':1,'.b64':1,'.backup':1,'.bin':1,'.bmp':1,'.bz':1,'.bz2':1,'.bzip':1,\n\t\t\t'.bzip2':1,'.cab':1,'.caf':1,'.cgm':1,'.crtx':1,'.css':1,'.csv':1,'.cwk':1,'.dap':1,'.db':1,\n\t\t\t'.dbf':1,'.dcr':1,'.dds':1,'.dex':1,'.dib':1,'.dif':1,'.diz':1,'.dmg':1,'.doc':1,'.docm':1,\n\t\t\t'.docx':1,'.dot':1,'.dotm':1,'.dotx':1,'.drw':1,'.ds_store':1,'.dv':1,'.dvr-ms':1,'.dwf':1,'.dwg':1,\n\t\t\t'.dxf':1,'.emf':1,'.eml':1,'.emlx':1,'.emz':1,'.eot':1,'.eps':1,'.fbp':1,'.fdp':1,'.fhtml':1,\n\t\t\t'.file':1,'.flac':1,'.flc':1,'.fli':1,'.flp':1,'.flv':1,'.fm':1,'.fm2':1,'.fm3':1,'.fm5':1,\n\t\t\t'.fmp':1,'.fnt':1,'.fon':1,'.fp':1,'.fp3':1,'.fp5':1,'.fp7':1,'.fphtml':1,'.fpt':1,'.fpweb':1,\n\t\t\t'.fpx':1,'.gg':1,'.gif':1,'.gnumeric':1,'.gra':1,'.gsm':1,'.gz':1,'.hdmov':1,'.hdp':1,'.hqx':1,\n\t\t\t'.htm':1,'.html':1,'.ical':1,'.icns':1,'.ico':1,'.ics':1,'.ifo':1,'.indd':1,'.isf':1,'.isu':1,\n\t\t\t'.ivs':1,'.jbf':1,'.jpe':1,'.jpeg':1,'.jpf':1,'.jpg':1,'.jxr':1,'.key':1,'.kml':1,'.kmz':1,\n\t\t\t'.knt':1,'.kth':1,'.lhz':1,'.lit':1,'.log':1,'.lrc':1,'.lrf':1,'.lrx':1,'.lst':1,'.lyr':1,\n\t\t\t'.m4a':1,'.m4b':1,'.m4p':1,'.m4r':1,'.mdb':1,'.mde':1,'.mht':1,'.mhtml':1,'.mid':1,'.midi':1,\n\t\t\t'.mim':1,'.mix':1,'.mng':1,'.mobi':1,'.mod':1,'.moi':1,'.mov':1,'.movie':1,'.mp3':1,'.mp4':1,\n\t\t\t'.mpa':1,'.mpc':1,'.mpe':1,'.mpeg':1,'.mpg':1,'.mpv2':1,'.msg':1,'.mswmm':1,'.mxd':1,'.numbers':1,\n\t\t\t'.odb':1,'.odf':1,'.odg':1,'.ods':1,'.odx':1,'.ofm':1,'.oft':1,'.ogg':1,'.ogm':1,'.ogv':1,\n\t\t\t'.one':1,'.onepkg':1,'.opx':1,'.osis':1,'.ost':1,'.otf':1,'.oth':1,'.p65':1,'.p7b':1,'.pages':1,\n\t\t\t'.pbm':1,'.pcast':1,'.pcf':1,'.pcm':1,'.pct':1,'.pcx':1,'.pdc':1,'.pdd':1,'.pdf':1,'.pdp':1,\n\t\t\t'.pfx':1,'.pgf':1,'.pic':1,'.pict':1,'.pkg':1,'.pmd':1,'.pmf':1,'.png':1,'.pot':1,'.pothtml':1,\n\t\t\t'.potm':1,'.potx':1,'.ppam':1,'.pps':1,'.ppsm':1,'.ppsx':1,'.ppt':1,'.ppthtml':1,'.pptm':1,'.pptx':1,\n\t\t\t'.prc':1,'.ps':1,'.psd':1,'.psp':1,'.pspimage':1,'.pst':1,'.pub':1,'.pubhtml':1,'.pubmhtml':1,'.qbb':1,\n\t\t\t'.qcp':1,'.qt':1,'.qxd':1,'.qxp':1,'.ra':1,'.ram':1,'.ramm':1,'.rar':1,'.raw':1,'.rax':1,\n\t\t\t'.rm':1,'.rmh':1,'.rmi':1,'.rmm':1,'.rmvb':1,'.rmx':1,'.rp':1,'.rss':1,'.rt':1,'.rtf':1,\n\t\t\t'.rts':1,'.rv':1,'.sbx':1,'.sdf':1,'.sea':1,'.shs':1,'.sit':1,'.sitx':1,'.smil':1,'.snapfireshow':1,\n\t\t\t'.snp':1,'.stc':1,'.svg':1,'.svgz':1,'.swf':1,'.sxc':1,'.sxi':1,'.tab':1,'.tar':1,'.tex':1,\n\t\t\t'.tga':1,'.thmx':1,'.tif':1,'.tiff':1,'.tpz':1,'.tr':1,'.trm':1,'.tsv':1,'.ttf':1,'.txt':1,\n\t\t\t'.uue':1,'.vcf':1,'.vob':1,'.vrml':1,'.vsc':1,'.vsd':1,'.wab':1,'.wav':1,'.wax':1,'.wbk':1,\n\t\t\t'.wbmp':1,'.wdp':1,'.webarchive':1,'.webloc':1,'.wk1':1,'.wk3':1,'.wm':1,'.wma':1,'.wmf':1,'.wmmp':1,\n\t\t\t'.wmv':1,'.wmx':1,'.wpd':1,'.wps':1,'.wri':1,'.wvx':1,'.xbm':1,'.xcf':1,'.xg0':1,'.xg1':1,\n\t\t\t'.xg2':1,'.xg3':1,'.xg4':1,'.xht':1,'.xhtm':1,'.xhtml':1,'.xif':1,'.xlam':1,'.xlb':1,'.xlc':1,\n\t\t\t'.xld':1,'.xlk':1,'.xlm':1,'.xls':1,'.xlsb':1,'.xlshtml':1,'.xlsm':1,'.xlsmhtml':1,'.xlsx':1,'.xlt':1,\n\t\t\t'.xlthtml':1,'.xltm':1,'.xltx':1,'.xlv':1,'.xlw':1,'.xml':1,'.xpi':1,'.xps':1,'.xsf':1,'.xsn':1,\n\t\t\t'.xtp':1,'.zabw':1,'.zip':1,'.zipx':1\n\t\t};\n\t}\n\t\n\treturn (window.acceptedFileExtensions[(ext + '').toLowerCase()] === 1);\n}", "function getExt(fileName) {\n return {\n /** base extension (e.g. `.js`) */\n baseExt: path_1.default.extname(fileName).toLocaleLowerCase(),\n /** full extension, if applicable (e.g. `.proxy.js`) */\n expandedExt: path_1.default.basename(fileName).replace(/[^.]+/, '').toLocaleLowerCase(),\n };\n}", "static readFiles(){\n\t\treturn (context, arr) => {\n\t\t\tvar fs = context.createProvider(\"default:fs\");\n\t\t\tvar res = arr.map((file) => {\n\t\t\t\treturn Lib.readFile(fs, file);\n\t\t\t});\n\t\t\treturn res;\n\t\t}\n\t}", "function getFileExtension(filename){\n let arr = [];\n arr = filename.split(\".\");\n return arr[arr.length - 1];\n}", "function getExtension(filename) {\n var i = filename.lastIndexOf('.');\n return (i < 0) ? '' : filename.substr(i);\n}", "function getExtension(filename)\r\n{\r\n var idx = filename.lastIndexOf('.');\r\n return 0 <= idx ? filename.substr(idx) : \".\";\r\n}", "function containsDotFile(parts){for(var i=0;i<parts.length;i++){if(parts[i][0]==='.'){return true;}}return false;}", "function getExt(fileName) {\n return {\n /** base extension (e.g. `.js`) */\n baseExt: path.extname(fileName).toLocaleLowerCase(),\n\n /** full extension, if applicable (e.g. `.proxy.js`) */\n expandedExt: path.basename(fileName).replace(/[^.]+/, '').toLocaleLowerCase()\n };\n}", "function getExtension(filename) {\n const dot = filename.lastIndexOf('.');\n if (dot === -1) return '';\n return filename.substring(dot + 1, filename.length);\n }", "function filePrepare(name, type, extension){\n var newProps = {};\n newProps.name = name + \".\" + extension;\n newProps.type = type + \".\" + extension;\n return newProps;\n }", "function getExt(key) {\n switch (key) {\n case 'photo':\n return 'jpg';\n case 'voice':\n return 'ogg';\n case 'audio':\n return 'mp3';\n case 'animation':\n case 'video':\n case 'video_note':\n return 'mp4';\n case 'sticker':\n return 'webp';\n default:\n return 'dat';\n }\n}", "function getExtension(filename) {\n // Strip pathname, in case the filename has no dot but a path component does.\n // Not sure if we need to support backslash here.\n const slash = filename.lastIndexOf(\"/\");\n if (slash >= 0) {\n filename = filename.substr(slash + 1);\n }\n // Look for extension.\n const dot = filename.lastIndexOf(\".\");\n // If the dot is at position 0, then it's just a hidden file, not an extension.\n return dot > 0 ? filename.substr(dot).toUpperCase() : \"\";\n}", "function getExtension(fn) {\n return fn.split('.').pop();\n}", "function myModule(dirPath, ext, callback) {\n const aRay = []\n fs.readdir(dirPath, (err, files) => {\n if (err) return callback(err)\n\n files.forEach(file => {\n if (path.extname(file) === '.' + ext)\n aRay.push(file)\n // console.log(file)\n \n \n })\n callback(err, aRay)\n \n })\n}", "function getExtensionFromName(fileName) {\n\n try {\n\n var fileExt = \"\";\n var lastDotIndex = -1;\n\n if (typeof fileName != 'undefined' && fileName.length > 0) {\n lastDotIndex = fileName.lastIndexOf(\".\");\n }\n if (lastDotIndex > -1) {\n fileExt = fileName.substr(lastDotIndex + 1, fileName.length - lastDotIndex - 1);\n }\n\n return fileExt.toLowerCase();\n } catch (e) { alertExceptionDetails(e); }\n}", "function readFileInfo(x){\n\tconsole.log(\"Cur \" + x + \" Tot \" + nrOfFiles);\n\tif (x >= nrOfFiles) {\n\t\tofferShare();\n\t\treturn;\n\t}\n\tvar f = files[x];\n\tvar reader = new FileReader();\n\t\treader.onloadend = function (e) {\n\t\t\tif(reader.readyState == FileReader.DONE){\n\t\t\t\tconsole.log(f.name);\n\t\t\t\tfmArray[x].stageLocalFile(f.name, f.type, reader.result);\n\t\t\t\treadFileInfo(x+1);\n\t\t\t}\n\t\t}; \n\t\treader.readAsArrayBuffer(f);\n}", "function readIndexJS() {\n\t\tconst core = fs.readFileSync('core.js', {encoding: 'utf8'});\n\t\tconst extArray = core.match(/(?<=ext:\\s')(.*)(?=',)/g);\n\t\tconst mimeArray = core.match(/(?<=mime:\\s')(.*)(?=')/g);\n\t\tconst exts = new Set(extArray);\n\t\tconst mimes = new Set(mimeArray);\n\n\t\treturn {\n\t\t\texts,\n\t\t\tmimes,\n\t\t};\n\t}", "function getExtension(filename){\n var parts = filename.split('.');\n\n return parts[parts.length - 1];\n }", "function getCustomFiles(featureXmlDir) {\n return getFiles_1.getFiles(featureXmlDir, path.join('**', '*.*'), 'Found custom file: ');\n}", "function displayFiles() {\n\n console.log(__dirname);\n\n const testFolder = __dirname + '/engine-samples';\n const fs = require('fs');\n files = [];\n let i = 0;\n fs.readdirSync(testFolder).forEach(file => {\n if (path.extname(file) == '.js') {\n console.log(\"\" + (++i) + \" \" + file);\n files.push(file);\n }\n });\n}", "function checkFileType() {\n var validFileType = false;\n var regexFileType = /(?:\\.([^.]+))?$/; //whats my extention?\n var checkValidFileType = regexFileType.exec(fileName)[1];\n var validFileTypes = [\"jpeg\", \"png\", \"gif\", \"jpg\"]; //which file types are valid?\n\n for(var i = 0; i < validFileTypes.length; i++){\n if(validFileTypes[i] === checkValidFileType){\n validFileType = true;\n }\n }\n\n if(validFileType){\n return true;\n }else{\n return false;\n }\n\n }", "function get_mime(filename)\n{\n let ext, type\n for (let ext in MIME_TYPES) {\n type = MIME_TYPES[ext]\n if (filename.indexOf(ext, filename.length - ext.length) !== -1) {\n return type\n }\n }\n return MIME_TYPES[\"txt\"]\n}", "function importfiles() {\n getlabelfiles(filesdone);\n}", "function getFileExtension(curFileName) {\n return curFileName.substr(curFileName.lastIndexOf('.'), curFileName.length);\n}", "function getIncludeFileExtensions() {\n return Object.keys( options.includeFiles );\n }", "hasExtension(fileName) {\n return (new RegExp('(' + appConstants.actionPicture.extensions.join('|').replace(/\\./ig, '\\\\.') + ')$')).test(fileName) ||\n (new RegExp('(' + appConstants.actionPicture.extensions.join('|').replace(/\\./ig, '\\\\.') + ')$')).test(fileName.toLowerCase());\n }", "function extensionContentsFor(path) {\n\n // Need to combine user element metadata with the internal metadata.\n if (path.endsWith(`/${constants.userElementMetadata}`)) {\n\n return spliceElementMetadata(path)\n } else {\n\n // Just read the file and pass back the contents.\n return readFile(path)\n }\n}", "filterForExtension(ext) {\n if (ext == null) {\n for (item of this.files) {\n item.show();\n }\n } else {\n for (item of this.files) {\n if (item.hasExtension(ext)) {\n item.show();\n } else {\n item.hide();\n }\n }\n }\n }", "function main(folderObj, ext) {\n\t// If a valid folder is selected\n\tif (folderObj != null) {\n var fileList = new Array();\n \tfileList = folderObj.getFiles();\n if (fileList.length > 0) {\n getFolder(folderObj);\n }\n else {\n alert('No matching files found');\n }\n\t}\n function getFolder(folderObj) {\n \tvar fileList = folderObj.getFiles();\n \tfor (var i=0; i<fileList.length; i++){\n \t\tif (fileList[i].getFiles) {\n \t\t\tgetFolder(fileList[i]); // サブフォルダがある限り繰り返す\n \t\t} else {\n \t\t\tvar f = fileList[i].name.toLowerCase();\n \t\t\tfor(var j=0; j<ext.length; j++){\n \t\t\t\tif (f.indexOf(ext[j]) > -1) { createPNG(fileList[i]); }\n \t\t\t}\n \t\t}\n \t}\n }\n}", "function listAllowedExt() {\n var\n fileTypes = Y.doccirrus.media.types.fileTypes,\n allowedExt = [],\n i;\n\n for ( i = 0; i < fileTypes.length; i++ ) {\n if ( -1 !== allowCategories.indexOf( fileTypes[i].group ) ) {\n allowedExt.push( fileTypes[i].ext );\n }\n }\n\n return allowedExt;\n }", "function readFiles(filepath, processFiles) {\n // split the full path (/home/roland/...) and get the string after views. EG: about, notes/blog\n let relFilePath = filepath.split(\"/SSG_webpack_boilerplate/src/views/\")[1]\n processFiles({\n // return the filepath without an extension\n filepath: relFilePath.split('.')[0],\n // return the file of the filepath without an extension\n title: path.parse(filepath).name\n })\n}", "function getFileExtension(path)\n{\n return path.lastIndexOf(\".\") > 0 ? path.split(\".\").pop() : \"\";\n}", "function getFileType(fileName){\n var type = \"\";\n for(var i = fileName.length; i > 0; i--) {\n var letter = fileName.charAt(i);\n if(letter === '.'){\n return type\n } else {\n type = letter + type;\n }\n }\n //default to plain file if no extension found\n return \"file\";\n}", "function _calcExtension(filename, currentExt) {\n\t// simply return the rightmost extension\n\tvar ext = filename.split('.').slice(-1);\n\tif (ext=='tem' || ext=='html')\n\t\t// revert to html if no better option.\n\t\t// The html check is here to rename 'tem.html' to '.hubla' if 'hubla' has been set as the new default extension\n\t\treturn _config.DEF_EXTENSION;\n\treturn ext;\n}", "function getExtension(filename) {\n var parts = filename.split('.');\n return parts[parts.length - 1];\n}", "function checkExtension()\n{\n // for mac/linux, else assume windows\n var fileTypes = new Array('.ppt','.pptx','.jnt','.rtf','.pps','.pdf','.swf','.doc','.xls','.xlsx','.docx','.ppsx','.flv','.mp3','.wmv','.wav','.wma','.mov','.avi','.mpeg'); // valid filetypes\n var fileName = document.getElementById('fileupload').value; // current value\n var extension = fileName.substr(fileName.lastIndexOf('.'), fileName.length);\n var valid = 0;\n for(var i in fileTypes)\n {\n if(fileTypes[i].toUpperCase() == extension.toUpperCase())\n {\n valid = 1;\n break;\n }\n }\n return valid;\n}", "function getExt(nombre){\n return nombre.split('.').pop();\n}", "function extReg(ext) {\n var parse_ext = /[a-zA-Z0-9\\/]/,\n res;\n if (ext && typeof ext === 'string' && parse_ext.test(ext)) {\n res = new RegExp(\"[\\\\w\\\\-\\\\/]+\\\\.\" + ext, \"g\");\n return res;\n }\n else {\n throw new Error('ERROR : \"' + ext + '\" is not a file extension');\n }\n}", "function parseImgExt() {\n\text = imgext;\n\tnewext = ext.split(\" \");\n}", "function checkType(file) {\n for (let type in types) {\n for (let ext of types[type]) {\n if (path.extname(file).split(\".\")[1] == ext) {\n return type;\n }\n }\n }\n return 'others';\n}", "function filterByFileType (extension) {\n return function (name) {\n return (-1 !== name.indexOf(extension)); \n };\n}", "static getFileExtension(path) {\n return path.substring(path.lastIndexOf('.'), path.length);\n }", "function extname(filename) {\n\treturn path.extname(filename).slice(1).toLowerCase();\n}", "get extname() {\n return typeof this.path === 'string' ? path.extname(this.path) : undefined\n }", "function getExtension(filename) {\n let parts = filename.split('.');\n return parts[parts.length - 1];\n}", "onExtensionSelected(ext) {\n this.fileView.filterForExtension(ext);\n this.contentView.filterForExtension(ext);\n }", "function getFileContent(extension){\n if( $scope[extension+'_file'] )\n {\n File.index({ mode: 'editfile', 'path': $scope[extension+'_file'] }).then(function (resp) {\n if( extension == \"html\" ) {\n $scope.editHtml = filterHtml(ProjectObject, resp.result, $config, user_id, organization_id);\n setTimeout(function(){\n generatePreview();\n },100);\n }\n else\n $scope['edit'+capitalizeFirstLetter(extension)] = resp.result;\n },function(){\n toastr.error(\"Unable to load file\");\n });\n }\n else{\n $scope['edit'+ capitalizeFirstLetter(extension)] = \"\";\n }\n }", "parseFlsFile(baseFile) {\r\n this.extension.logger.addLogMessage('Parse fls file.');\r\n const rootDir = path.dirname(baseFile);\r\n const outDir = this.getOutDir(baseFile);\r\n const flsFile = path.resolve(rootDir, path.join(outDir, path.basename(baseFile, '.tex') + '.fls'));\r\n if (!fs.existsSync(flsFile)) {\r\n this.extension.logger.addLogMessage(`Cannot find fls file: ${flsFile}`);\r\n return;\r\n }\r\n this.extension.logger.addLogMessage(`Fls file found: ${flsFile}`);\r\n const ioFiles = this.parseFlsContent(fs.readFileSync(flsFile).toString(), rootDir);\r\n ioFiles.input.forEach((inputFile) => {\r\n // Drop files that are also listed as OUTPUT or should be ignored\r\n if (ioFiles.output.includes(inputFile) ||\r\n this.isExcluded(inputFile) ||\r\n !fs.existsSync(inputFile)) {\r\n return;\r\n }\r\n // Drop the current rootFile often listed as INPUT and drop any file that is already in the texFileTree\r\n if (baseFile === inputFile || inputFile in this.cachedContent) {\r\n return;\r\n }\r\n if (path.extname(inputFile) === '.tex') {\r\n // Parse tex files as imported subfiles.\r\n this.cachedContent[baseFile].children.push({\r\n index: Number.MAX_VALUE,\r\n file: inputFile\r\n });\r\n this.parseFileAndSubs(inputFile);\r\n }\r\n else if (this.fileWatcher && !this.filesWatched.includes(inputFile)) {\r\n // Watch non-tex files.\r\n this.fileWatcher.add(inputFile);\r\n this.filesWatched.push(inputFile);\r\n }\r\n });\r\n ioFiles.output.forEach((outputFile) => {\r\n if (path.extname(outputFile) === '.aux' && fs.existsSync(outputFile)) {\r\n this.parseAuxFile(fs.readFileSync(outputFile).toString(), path.dirname(outputFile).replace(outDir, rootDir));\r\n }\r\n });\r\n }", "function realFile(f) {\n\treturn f && f.charAt(0)!=='.';\n}", "handleFiles(files) {\n [...files].forEach(this.__readAndHandleFile, this);\n }", "function enumerateFilename(fileName) {\n const fileArr = fileName.split('.');\n const extension = fileArr.pop();\n let fileStem = fileArr.join('.');\n const suffix = fileStem.split('--').pop();\n \n if (isNaN(suffix)) {\n return [fileStem, '--', 1, '.', extension].join('');\n } else {\n fileStem = fileStem.split('--');\n fileStem.pop();\n fileStem = fileStem.join('--');\n return [fileStem, '--', parseInt(suffix) + 1, '.', extension].join('');\n }\n}", "function getFileNameExtension(filename) {\n var parts = filename.split(\".\");\n return parts[parts.length - 1];\n }", "function checkFormat(filename, extensions) {\n if (extensions)\n return extensions.reduce((prevExt, currExt) => (checkNewExt(filename, prevExt.length, currExt) ? currExt : prevExt), '');\n else\n return '';\n}" ]
[ "0.6619774", "0.6478976", "0.6438233", "0.6434032", "0.639619", "0.637693", "0.63752055", "0.63665426", "0.636399", "0.6337162", "0.63250667", "0.6296181", "0.6258504", "0.6244185", "0.6235741", "0.6210412", "0.6177049", "0.6175436", "0.6162403", "0.6150251", "0.61375976", "0.6136245", "0.61298615", "0.6120049", "0.61073357", "0.6106222", "0.61025214", "0.61009145", "0.60991865", "0.60784525", "0.6059112", "0.60192317", "0.6013728", "0.5993932", "0.5993932", "0.5991753", "0.59783334", "0.59613687", "0.5958212", "0.59510547", "0.59499526", "0.59425235", "0.5937755", "0.59355175", "0.59318656", "0.59158283", "0.5911091", "0.5910633", "0.5896648", "0.5869944", "0.5849484", "0.5845344", "0.5844346", "0.58279645", "0.58255595", "0.58190674", "0.58054316", "0.57889", "0.57804465", "0.57699126", "0.5761441", "0.5756821", "0.575121", "0.5745685", "0.5741699", "0.5736384", "0.5721671", "0.57163954", "0.5715393", "0.57131046", "0.57124686", "0.5709062", "0.5695581", "0.5690761", "0.5686978", "0.5685691", "0.5681355", "0.56718564", "0.5671085", "0.56681466", "0.5649992", "0.5647166", "0.56458026", "0.56457514", "0.5643483", "0.56382924", "0.56356657", "0.56275684", "0.5618934", "0.5615929", "0.5609912", "0.5594963", "0.5594661", "0.5584207", "0.5583241", "0.5579947", "0.55588984", "0.55538154", "0.5549662", "0.55492944", "0.5547961" ]
0.0
-1
END OF Util Code START OF Signin Code
function create_account(sender_worker, username, password) { var new_guid = generate_random_id(); var wr = { 'guid': new_guid, 'username': CryptoJS.SHA1(username).toString(), 'password' : CryptoJS.SHA1(password).toString(), 'version' : pii_vault.config.current_version } var r = request({ url: "http://woodland.gtnoise.net:5005/create_new_account", content: JSON.stringify(wr), onComplete: function(response) { my_log("Here here: Comepleted create-account response", new Error); my_log("Here here: Response status: " + response.status, new Error); my_log("Here here: Response status txt: " + response.statusText, new Error); my_log("Here here: Response text: " + response.text, new Error); my_log("Here here: Response json: " + response.json, new Error); my_log("Here here: Response headers: " + response.headers, new Error); if (response.status == 200) { var data = response.text; if (data == 'Success') { sender_worker.port.emit("account-success", { type: "account-success", desc: "Account was created successfully. You are now logged-in" }); //Reset pii_vault. pii_vault = { "options" : {}, "config": {}}; pii_vault.guid = new_guid; my_log("create_account(): Updated GUID in vault: " + pii_vault.guid, new Error); vault_write("guid", pii_vault.guid); current_user = username; pii_vault.current_user = username; vault_write("current_user", pii_vault.current_user); sign_in_status = 'signed-in'; pii_vault.sign_in_status = 'signed-in'; vault_write("sign_in_status", pii_vault.sign_in_status); //GUID has changed, call init() to create new fields. Otherwise it //will not do anything. vault_init(); my_log("APPU DEBUG: Account creation was success", new Error); //Just to report our status pii_check_if_stats_server_up(); } else if (data.split(' ')[0] == 'Failed') { var temp = data.split(' '); temp.shift(); var reason = temp.join(' '); sender_worker.port.emit("account-failure", { type: "account-failure", desc: reason }); my_log("APPU DEBUG: Account creation was failure: " + reason, new Error); } else { sender_worker.port.emit("account-failure", { type: "account-failure", desc: "Account creation failed for unknown reasons" }); my_log("APPU DEBUG: Account creation was failure: Unknown Reason", new Error); } } else { //This means that HTTP response is other than 200 or OK print_appu_error("Appu Error: Account creation failed at the server: " + response.toString() + " @ " + (new Date())); sender_worker.port.emit("account-failure", { type: "account-failure", desc: "Account creation failed, service possibly down" }); my_log("APPU DEBUG: Account creation was failure: Unknown Reason", new Error); } } }); r.post(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "signIn() {}", "function sign_in() {\n start();\n}", "function interactiveSignIn() {\r\n }", "function signIn(req, res, data) {\n //extract form data\n var dataObj = querystring.parse(data),\n login = dataObj.login, pw = dataObj.pw\n //attempt to sign in registered user\n dbLogin(req, res, login, pw)\n}", "function signin(username) {\n\n\t}", "handleSignIn() {\n const loginRequest = {};\n loginRequest[USERNAME_ID] = this.state.formFields[USERNAME_ID];\n loginRequest[PASSWORD_ID] = this.state.formFields[PASSWORD_ID];\n sendLoginRequest(loginRequest, true, this.state.formFields[USERNAME_ID], null);\n }", "function signIn(){\n var dataEntered = getLoginData();\n loginUser(dataEntered);\n}", "function signIn(name) {\n gw.signIn(name, function(err, res) {\n if (err) log.error(\"sign in error: \" + err);\n else log.info(\"sign in succeeded: \\n\" + JSON.stringify(res));\n });\n}", "signIn(email, password) {\n /* Sign in the user */\n\n }", "function signIn() {\n\tconsole.log(\"Sign In Button Pressed.\");\n\tvar name = $(\"input:text[name=signInName]\").val().trim();\n\tvar pass = $(\"input:password[name=signInPassword]\").val().trim();\n\n\tvar userInfo = {\n\t\tsignInName: name,\n\t\tsignInPassword: pass\n\t}\n\n\t//=-=-=-=-=-=-=-=\n\t$.post(\"/api/user/login\", userInfo)\n .then(function(data){\n \tconsole.log(\"Sent user info: \" + userInfo);\n \tif (data.error)\n \t\t$(\"input:text[name=signInName]\").val(data.error);\n\n \tif (data.success)\n \t\twindow.location = data.redirectTo;\n });\n\t//=-=-=-=-=-=-=-=\n}", "function signinFunction() {\n var username = document.getElementById('username-input').value;\n var password = document.getElementById('password-input').value;\n signIn(username, password)\n}", "function signIn (info) {\n\t\t\tParse.User.logIn(info.email, info.password, {\n\t\t\t\tsuccess: success,\n\t\t\t\terror: error\n\t\t\t});\n\t\t\treturn defer.promise;\n\t\t}", "async function signIn(formData) {\n const response = await Api.serverApi.users.auth.signin(formData)\n console.log('signIn resp', response.data)\n return response.data\n }", "static singIn({ username, password }) {\r\n return new Promise(async resolve =>{\r\n try {\r\n let checkExit = await USER_COLL.findOne({ username });\r\n\r\n if( !checkExit ) return resolve({ error : true, message : 'UserName not exist'});\r\n\r\n let passWord = checkExit.password;\r\n\r\n let checkpass = await compare( password, passWord);\r\n if( !checkpass ) \r\n {\r\n return resolve({ error: true , message: 'wrong pass'});\r\n }\r\n \r\n //tao token \r\n await delete checkExit.password;\r\n \r\n let token = await sign( { data:checkExit } );\r\n \r\n return resolve( { error : false , data:{checkExit, token} } );\r\n } catch ( error ) {\r\n return resolve({ error: true, message: error.message} )\r\n }\r\n })\r\n }", "function signedIn(){\r\n document.cookie = \"signedin=true\" + ';';\r\n changeSignIn();\r\n}", "handleSignIn() {\n // Sign in the user -- this will trigger the onAuthStateChanged() method\n\n }", "function signIn() {\n myMSALObj.loginPopup(loginRequest)\n .then(loginResponse => {\n // get the accesstoken for the user\n getTokenPopup(loginRequest);\n\n }).catch(error => {\n console.log(error);\n });\n}", "function signInSuper() {\n\tsocket.emit('SignInSuperRequest',\"\");\n}", "signIn () {\n return this.mgr.signinRedirect().catch(function (err) {\n console.log(err)\n })\n }", "function signInFunc () {\n if (vm.user.email !== null && vm.user.password !== null) {\n LoadingService.showLoadingState();\n AuthService\n .firebaseAuthObj\n .$signInWithEmailAndPassword(vm.user.email, vm.user.password)\n .then(function (user) {\n $log.log('Logged In as ' + user );\n $state.go('main.dashboard');\n LoadingService.hideLoadingState();\n })\n .catch(function (error) {\n switch (error.code) {\n case 'auth/user-not-found':\n vm.errorMessage = 'User does not exist';\n break;\n case 'auth/wrong-password':\n vm.errorMessage = 'Wrong Password';\n break;\n }\n LoadingService.hideLoadingState();\n });\n }\n }", "function signinCallback(authResult) {\n\n if (authResult['status']['signed_in']) {\n\n // Successfully authorized\n// document.getElementById('customBtn').setAttribute('style', 'display: none');\n apiClientLoad();\n\n } else if (authResult['error']) {\n\n // There was an error.\n // Possible error codes:\n // \"access_denied\" - User denied access to your app\n // \"immediate_failed\" - Could not automatially log in the user\n //console.log('There was an error: ' + authResult['error']);\n gpLoggedInFailure(authResult['error']);\n }\n}", "function signIn() {\n auth.signInWithEmailAndPassword(email, password)\n .then(() => {\n navigation.navigate(\"Main\")\n }).catch(error=> {\n alert(error.message)\n })\n }", "function login() {}", "siginHandler(data) {\n\t\t\tif (data.username) {\n\t\t\t\tthis.showSpinner().then(() => {\n\t\t\t\t\tdata.password = this.generatePassword();\n\t\t\t\t\tdata.address = this.$web3.personal.newAccount(data.password);\n\t\t\t\t\tthis.$web3.eth.defaultAccount = data.address;\n\n\t\t\t\t\tthis.$storage.set(\"user\", data);\n\n\t\t\t\t\tthis.tokensRequest(data.address)\n\t\t\t\t\t\t.then(() => {\n\t\t\t\t\t\t\tthis.$eventbus.$emit(\"hideSpinner\");\n\t\t\t\t\t\t\tRouter.push({ name: \"waiting\" });\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch(err => {\n\t\t\t\t\t\t\tconsole.error(err);\n\t\t\t\t\t\t\tthis.$eventbus.$emit(\"hideSpinner\");\n\t\t\t\t\t\t\tthis.$eventbus.$emit(\"alert\", {\n\t\t\t\t\t\t\t\ttype: \"danger\",\n\t\t\t\t\t\t\t\tmessage: \"Error creating account for this user.\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}", "function checkSignIn(){\r\n if (getCookie(\"signedin\") == \"true\"){\r\n changeSignIn();\r\n return true;\r\n }\r\n return false;\r\n}", "signInUser(data) {\n return this.post('signin', data);\n }", "signIn() {\n this.props.signInCallback(this.state.email, this.state.password);\n }", "function success(data){\n\t\tsignFactoryService.sign(data).then(successLogin, error);\n\t}", "function signIn(){\n console.log(\"click en sign in\");\n\n var nombre = loginctrl.name;\n var pass = loginctrl.pass;\n var isNoEmty = (nombre !== \"\" && pass !== \"\");\n console.log(nombre,pass,isNoEmty);\n if(isNoEmty){\n console.log(\"dentro del id\",isNoEmty);\n // TODO mostrar un mensaje de cargando\n Authentification.login(nombre,pass)\n .then(function (result) {\n loginctrl.userInfo = result.usuario;\n console.info(\"loginctrl.userInfo\",loginctrl.userInfo);\n //console.log($state.get('app'));\n $scope.$emit(events.ON_LOGIN_CHANGE,{usuario:result.usuario});\n\n $state.go('user',{}).then(function (argument) {\n console.log(argument);\n },function (a,b,c) {\n console.log(a,b,c);\n })\n\n }, function (error) {\n //$window.alert(\"Invalid credentials\");\n console.log(\"Invalid credentials\",error);\n });\n }//TODO poner como validacion en la lista que los 2 campos sean obligatorios, no lo hace el formulario?\n\n\n }", "function signIn(inputEmail = varEmail, inputPassword = varPassword) {\n\n\t\tinputs.get(0).sendKeys(inputEmail);\n\t\tinputs.get(1).sendKeys(inputPassword);\n\n\t\tsignInButton.click();\n\t}", "function handleLoginOnStartUp() {\n //if user is signed in, show their profile info\n if (blockstack.isUserSignedIn()) {\n var user = blockstack.loadUserData().profile\n //blockstack.loadUserData(function(userData) {\n // showProfile(userData.profile)\n //})\n }\n //signin pending, \n else if (blockstack.isSignInPending()) {\n blockstack.handlePendingSignIn.then((userData) => {window.location = window.location.origin})\n }\n\n}", "function signIn() {\r\n\tgapi.client.setApiKey(apiKey);\r\n\twindow.setTimeout(signInAuto,1);\r\n}", "function signedIn(){\n document.body.classList.add('auth');\n document.body.classList.remove('no-auth');\n fs.get('/platform/users/current', function(error, response){\n if(error){\n output(error.message);\n } else {\n output(JSON.stringify(response.data, null, 2));\n }\n });\n}", "static async ensureSignedIn(context) {\n const suite = new UITestSuite();\n suite.mochaContext = context;\n const signedIn = await suite.checkForStatusBarTitle(suite.hostWindow, suite.testAccount.email);\n if (!signedIn) {\n const userCode = await web.signIn(suite.serviceUri, 'microsoft', suite.testAccount.email, suite.testAccount.password, false);\n assert(userCode, 'Should have gotten a user code from browser sign-in.');\n await suite.runLiveShareCommand(suite.hostWorkbench, 'liveshare.signin.token');\n await suite.hostWorkbench.quickinput.waitForQuickInputOpened();\n await suite.hostWindow.waitForSetValue(quickinput_1.QuickInput.QUICK_INPUT_INPUT, userCode);\n await suite.hostWindow.dispatchKeybinding('enter');\n await suite.waitForStatusBarTitle(suite.hostWindow, suite.testAccount.email);\n }\n }", "async signIn(data: SignInForm): Promise<APIResponse> {\n const response = await this.jsonRequest('api/auth/sign-in', data);\n\n return response.json();\n }", "function login() {\n\nAuth.signInWithRedirect (provider);\n\nAuth.getRedirectResult()\n .then(function (result) {});\n .catch(function (error) {});\n\n}", "function handleFastSignIn() {\n\n const paramdict = getAuthorisation();\n const config = {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(paramdict)\n }\n\n //print(\"Signin.js: fetching from \" + `${process.env.REACT_APP_API_SERVICE_URL}/fastlogin`)\n // verify user/pwd, get encoded userid as access and refresh tokens in return\n //fetch(\"http://localhost:5000/fastlogin\", config)\n //fetch(`${process.env.REACT_APP_BE_NETWORK}:${process.env.REACT_APP_BE_PORT}/fastlogin`, config)\n //fetch(`${process.env.REACT_APP_API_SERVICE_URL}/fastlogin`, config)\n fetch(\"http://aa1f1319b43a64c5388b2505b86edfe8-1002164639.us-east-1.elb.amazonaws.com:5000/fastlogin\", config)\n //fetch(\"http://localhost:5000/fastlogin\", config)\n // fetch(`${process.env.REACT_APP_API_SERVICE_URL}/fastlogin`, config)\n .then(response => response.json())\n .then(data => {\n\n // save to local storage\n console.log(\"received these keys in return:\")\n console.log(data);\n saveAuthorisation({\n access: data[0][0],\n refresh: data[0][1],\n });\n\n // back to landing page!\n history.push(\"/\");\n })\n .catch( (err) => {\n alert(err);\n console.log(err);\n });\n }", "handleSignIn(e) {\n e.preventDefault();\n //generates an auth request and redirects the user to the blockstack Browser\n //to approve the sign in request\n userSession.redirectToSignIn();\n }", "async _onSignInButtonPressed(){\n\t\tlet {userEmail, userPwd} = this.state;\n\t\t//we first get the user info by the username\n\t\tthis.setState({isLoading: true});\n\t\ttry {\n\t\t\tlet status = await Network.verifyUser(userEmail, userPwd);\n\t\t\t//Alert.alert(JSON.stringify(status));\n\t\t\tswitch (status) {\n\t\t\t\t//correct user_email and user_pwd\n\t\t\t\t//we save the user info to async storage and jump to main pages\n\t\t\t\tcase 200: {\n\t\t\t\t\tthis.setState({isLoading: false});\n\t\t\t\t\tStorage.setSignInByGoogle('false');\n\t\t\t\t\tthis.password.focus();\n\t\t\t\t\t//jump to main page\n\t\t\t\t\tthis.props.navigation.navigate('Main');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase 400:\n\t\t\t\tcase 404: this.setState(\n\t\t\t\t\t\t{errors: {\n\t\t\t\t\t\t\temail: 'incorrect email or password',\n\t\t\t\t\t\t\tpassword: 'incorrect email or password',\n\t\t\t\t\t\t}});\n\t\t\t\tbreak;\n\t\t\t\tdefault: Alert.alert('Internet Error', JSON.stringify(res.error));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tAlert.alert(error.toString());\n\t\t}\n\t\tthis.setState({isLoading: false});\n\t}", "function signInOrSignUp(successCallback) {\n\tvar emailElement = d3.select(\"input[name=email]\");\n\tvar email = emailElement.property(\"value\");\n\tvar passwordElement = d3.select(\"input[name=password]\");\n\tvar password = passwordElement.property(\"value\");\n\tvar signIn = d3.select(\"input[name=operation]\").property(\"value\") === \"sign-in\";\n\n\t// Check for presence of email\n\tif(tp.util.isEmpty(email) || !validEmail(email)) {\n\t\ttp.dialogs.showDialog(\"errorDialog\", tp.util.isEmpty(email) ? \"#email-empty\" : \"#email-invalid\")\n\t\t\t.on(\"ok\", function() {\n\t\t\t\temailElement.node().select();\n\t\t\t})\n\t\t;\n\t\treturn;\n\t}\n\n\t// Handle sign in or sign up\n\tif(signIn) {\n\n\t\t// Check password\n\t\tif(tp.util.isEmpty(password)) {\n\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#no-credentials\")\n\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\tpasswordElement.node().select();\n\t\t\t\t})\n\t\t\t;\n\t\t\treturn;\n\t\t}\n\t\tif(password.length < 6) {\n\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#password-too-short\")\n\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\tpasswordElement.node().select();\n\t\t\t\t})\n\t\t\t;\n\t\t\treturn;\n\t\t}\n\n\t\t// Sign in\n\t\tvar rememberMe = d3.select(\"input[name=persist-sign-in]\").property(\"value\") === \"remember-me\";\n\t\tvar expires = rememberMe ? \"false\" : \"true\";\n\t\tvar currentLanguage = tp.lang.default;\n\t\ttp.session.signIn(email, password, expires, function(error, data) {\n\t\t\tif(error) {\n\t\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#wrong-credentials\")\n\t\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\t\tpasswordElement.node().select();\n\t\t\t\t\t})\n\t\t\t\t;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle successful sign in\n\t\t\ttp.session.setHasAccount();\n\t\t\ttp.session.loadSettings('user.settings', function(error, settings) {\n\t\t\t\tif(!error) {\n\t\t\t\t\ttp.lang.setDefault(settings.lang);\n\t\t\t\t}\n\t\t\t\tif(applicationRequested) {\n\t\t\t\t\tdoNavigate(applicationRequested);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(successCallback) {\n\t\t\t\tsuccessCallback();\n\t\t\t}\n\t\t});\n\t} else {\n\n\t\t// Check for same passwords\n\t\tvar password = d3.select(\"input[name=password]\").property(\"value\");\n\t\tvar verifyPassword = d3.select(\"input[name=password-verify]\").property(\"value\");\n\t\tif(tp.util.isEmpty(password) || password.length < 6) {\n\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#password-too-short\")\n\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\tpasswordElement.node().select();\n\t\t\t\t})\n\t\t\t;\n\t\t\treturn;\n\t\t}\n\t\tif(password !== verifyPassword) {\n\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#passwords-different\")\n\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\tpasswordElement.node().select();\n\t\t\t\t})\n\t\t\t;\n\t\t\treturn;\n\t\t}\n\n\t\t// Sign up\n\t\ttp.session.createAccount(email, password, function(error, data) {\n\t\t\tif(error) {\n\t\t\t\tconsole.error(error, data);\n\t\t\t\ttp.dialogs.showDialog(\"errorDialog\", \"#account-add-failed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle successful sign up\n\t\t\ttp.dialogs.showDialog(\"messageDialog\", \"#activation-mail-sent\")\n\t\t\t\t.on(\"ok\", function() {\n\t\t\t\t\tif(successCallback) {\n\t\t\t\t\t\tsuccessCallback();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t;\n\t\t});\n\t}\n}", "function _signInHandler(data, statusText, xhr) {\n print2Console(\"Sign in RESPONSE\", xhr.status);\n\n //Ensure success.\n\tif (xhr.status === 202) {\n //Hide signin forms and show actions.\n $(\"#div-signin\").hide();\n $(\"#actions\").show();\n $(\"#div-signout\").show();\n $(\"#span-agent-info\").html(\"Logged in as <b>\" + _username + \"</b> with extension <b>\" + _extension + \"</b>\");\n }\n}", "function signIN() {\n\tvar database = firebase.database();\n\tvar form = document.getElementsByClassName(\"short\");\n\tconsole.log(form[0].value);\n\tfirebase.auth().createUserWithEmailAndPassword(form[1].value, form[3].value).then(function () {\n\t\tconsole.log(\"OK\");\n\t\tvar user = firebase.auth().currentUser;\n\t\thideAndShow(\"tenth\");\n\t\t/*\tuser \t\n\t\t\t\t\tname:form[0].value,\n\t\t\t\t\tteam: form[2].value,\n\t\t\t\t\temail: form[1].value*/\n\t\tuser.updateProfile({\n\t\t\tdisplayName: form[0].value\n\n\t\t}).then(function () {\n\t\t\t// Update successful.\n\t\t}).catch(function (error) {\n\t\t\t// An error happened.\n\t\t});\n\n\t}).catch(function (error) {\n\t\t// Handle Errors here.\n\t\tvar errorCode = error.code;\n\t\tvar errorMessage = error.message;\n\t\tconsole.log(\"BAD\");\n\t\t// ...\n\t});\n}", "function initSignin() {\n const signinForm = document.querySelector('.signup-signin-form form');\n signinForm.addEventListener('submit', signin);\n}", "function signIn(e){\r\n\tCloud.Users.login({\r\n\t\tlogin:$.login.value,\r\n\t\tpassword:$.password.value\r\n\t}, function(e){\r\n\t\tif(e.success){\r\n\t\t\tvar tochange=Alloy.createController(\"index\");\r\n\t\t\ttochange.signInButton.title=\"Sign Out\";\r\n\t\t\t$.signWin.close();\r\n\t\t}\r\n\t\telse{\r\n\t\t\t$.signWin.close();\r\n\t\t\talert(\"Sign in Failed\");\r\n\t\t}\r\n\t});\r\n\t\r\n\t\r\n}", "async login() {}", "async signin ({ auth,request , response}) {\n \n try {\n await auth.attempt(request.input('email'), request.input('password'))\n return response.redirect('/admin')\n } catch (error) {\n console.log(error)\n return response.redirect('/login')\n }\n \n \n }", "signIn(signInData, additionalData) {\n this.userType.next((signInData.userType == null) ? null : this.getUserTypeByName(signInData.userType));\n const body = {\n [this.options.loginField]: signInData.login,\n password: signInData.password\n };\n if (additionalData !== undefined) {\n body.additionalData = additionalData;\n }\n const observ = this.http.post(this.getServerPath() + this.options.signInPath, body).pipe(share());\n observ.subscribe(res => this.userData.next(res.data));\n return observ;\n }", "function signIn(){\n var userSIEmail = document.getElementById(\"userSIEmail\").value;\n var userSIPassword = document.getElementById(\"userSIPassword\").value;\n var userSIEmailFormate = /^(([^<>()\\[\\]\\\\.,;:\\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,}))$/;\n var userSIPasswordFormate = /(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{10,}/; \n\n var checkUserEmailValid = userSIEmail.match(userSIEmailFormate);\n var checkUserPasswordValid = userSIPassword.match(userSIPasswordFormate);\n\n if(checkUserEmailValid == null){\n return checkUserSIEmail();\n }else if(checkUserPasswordValid == null){\n return checkUserSIPassword();\n }else{\n firebase.auth().signInWithEmailAndPassword(userSIEmail, userSIPassword).then((success) => {\n swal({\n type: 'successfull',\n title: 'Welcome to foodmate', \n }).then((value) => {\n setTimeout(function(){\n window.location.replace(\"menu.html\");\n }, 1000)\n });\n }).catch((error) => {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n swal({\n type: 'error',\n title: 'Error',\n text: \"Error\",\n })\n });\n }\n}", "function signIn(){\n var userSIEmail = document.getElementById(\"email\").value;\n var userSIPassword = document.getElementById(\"password\").value;\n \n \n if(userSIEmail == null){\n return checkUserSIEmail();\n }else if(userSIPassword == null){\n return checkUserSIPassword();\n }else{\n firebase.auth().signInWithEmailAndPassword(userSIEmail, userSIPassword)\n .then((userCredential) => {\n // Signed in\n var user = userCredential.user;\n window.location.replace(\"admin.html\");\n\n // ...\n })\n .catch((error) => {\n var errorCode = error.code;\n var errorMessage = error.message;\n window.alert(errorMessage)\n });\n\n }\n}", "async signIn(email, password) {\n\t\tlet path = '/user/sign_in.php';\n\t\tlet options = {\n\t\t\t// data to be sent to the server\n\t\t\tbody: {\n\t\t\t\temail: email,\n\t\t\t\tpassword: password,\n\t\t\t\t// asynchronous function for fetching the network interface MAC address\n\t\t\t\tmac: await DeviceInfo.getMacAddress().then((mac) => {return mac}),\n\t\t\t\tos: DeviceInfo.getSystemName(),\n\t\t\t\tversion: DeviceInfo.getSystemVersion()\n\t\t\t}\n\t\t};\n\t\t// both path and options are mandatory\n\t\t// options can be an empty object\n\t\treturn this.post(path, options).then((response) => {\n\t\t\t// server response\n\t\t\tif(response.status == 'ok') {\n\t\t\t\tSettings.setSession(response.session);\n\t\t\t\tSettings.setData(response.data);\n\t\t\t\tresponse.status = true;\n\t\t\t} else {\n\t\t\t\t// error\n\t\t\t\tresponse.status = false;\n\t\t\t}\n\t\t\treturn response;\n\t\t});\n\t}", "getSignedIn () {\n let self = this\n return new Promise((resolve, reject) => {\n this.mgr.getUser().then(function (user) {\n if (user == null) {\n return self.signIn()\n } else{\n return resolve(true)\n }\n }).catch(function (err) {\n console.log(err)\n return reject(err)\n });\n })\n }", "handleSignin(login, password) {\n if(login.length == 0 || password.length < 8){\n //checking for the user length\n if(login.length == 0){\n this.setState({statusLog:\"danger\", captionLog: \"You need to enter your username\"})\n }\n //checking for the password length\n if(password.length < 8){\n this.setState({statusPass:\"danger\", captionPass: \"Password should at least contain 8 symbols\"})\n }}\n //checking the login\n else{\n authentification(login, password)\n .then(response => {\n \n if (response[\"success\"] === 0) {\n this.setState({statuspass:\"danger\", statusLog:\"danger\", captionPass: response[\"explanation\"] })\n\n }\n else {\n let token = response[\"data\"][\"access_tokens\"][0];\n this.setState({ token: token});\n \n this.context.handleToken(token)\n storeData({authToken: token, signIn: \"drawer\"},\"@storage_Key\")\n this.props.navigation.navigate(\"drawer\")\n }\n \n });\n }}", "function handleSignIn(event) {\n GoogleAuth.signIn();\n loginHandler();\n }", "function login(callback) {\n var CLIENT_ID = '933790dc3b564fa6b2ed3d8f09ed440f';\n var REDIRECT_URI = 'https://1undrgrnd.s3.amazonaws.com/frontend/trial.html';\n function getLoginURL(scopes) {\n return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +\n '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +\n '&scope=' + encodeURIComponent(scopes.join(' ')) +\n '&response_type=token';\n }\n \n // SCOPES (PERMISSIONS) USED TO GENERATE KEY\n var url = getLoginURL([\n 'user-read-email user-follow-modify user-top-read user-library-modify user-follow-modify'\n ]);\n \n // DISPLAY SETTINGS FOR POPUP AUTH BOX\n var width = 450,\n height = 730,\n left = (screen.width / 2) - (width / 2),\n top = (screen.height / 2) - (height / 2);\n // PARSES DATA AND CALLS BACK TOKEN HASH\n window.addEventListener(\"message\", function(event) {\n var hash = JSON.parse(event.data);\n if (hash.type == 'access_token') {\n callback(hash.access_token);\n }\n }, false);\n \n var w = window.open(url,\n 'Spotify',\n 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left\n );\n \n }", "function signIn() {\n var user = document.getElementById('username').value;\n var pass = document.getElementById('password').value;\n var auth_token = 'a_random_string';\n \n // Record that we've started an authentication request\n var URL = \"https://quotedserver.herokuapp.com/lookup/auth/\";\n xhttprequest(URL, user + \":\" + pass + \":\" + auth_token, function(xhr) {\n if (xhr.responseText === auth_token) {\n // SUCCESSFUL AUTHENTICATION\n document.getElementById(\"password\").value = \"\";\n \n chrome.storage.sync.set({USER: {username:user, token:auth_token, authenticated:'y'}}, function() {\n sendMessageToContentJS({'task':'signin', user:user});\n updateUIForSignedIn(user);\n });\n } else {\n // BAD AUTHENTICATION\n $('#signedoutmessage').text(BAD_AUTH_MESSAGE);\n }\n });\n}", "function signIn() {\r\n\t// Clear any previous server errors\r\n\tclear(\"sign-in-errors\");\r\n\r\n\t// Get the values from the form fields\r\n\tvar username = $(\"#username\").val();\r\n\tvar password = $(\"#password\").val();\r\n\r\n\t// Validate the business rules\r\n\tvalidateRequired(\"username\", \"error.username\");\r\n\tvalidateRequired(\"password\", \"error.password\");\r\n\r\n\tvalidateEmailFormat(\"username\", \"error.username.format\");\r\n\r\n\t// Create the data model to be sent\r\n\tvar user = {\r\n\t\tusername : username,\r\n\t\tpassword : password\r\n\t};\r\n\r\n\t// Post the request to the server\r\n\tpost(signInUrl, user, signInSuccess, signInError);\r\n}", "function signIn(){\n var userSIEmail = document.getElementById(\"userSIEmail\").value;\n var userSIPassword = document.getElementById(\"userSIPassword\").value;\n var userSIEmailFormate = /^(([^<>()\\[\\]\\\\.,;:\\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,}))$/;\n var userSIPasswordFormate = /(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{10,}/; \n\n var checkUserEmailValid = userSIEmail.match(userSIEmailFormate);\n var checkUserPasswordValid = userSIPassword.match(userSIPasswordFormate);\n\n if(checkUserEmailValid == null){\n return checkUserSIEmail();\n }else if(checkUserPasswordValid == null){\n return checkUserSIPassword();\n }else{\n firebase.auth().signInWithEmailAndPassword(userSIEmail, userSIPassword).then((success) => {\n swal({\n type: 'successfull',\n title: 'Succesfully signed in', \n }).then((value) => {\n setTimeout(function(){\n window.location.replace(\"control-panel.html\");\n }, 1000)\n });\n }).catch((error) => {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n swal({\n type: 'error',\n title: 'Error',\n text: \"Error\",\n })\n });\n }\n}", "function sign_out() {}", "function handleSignIn() {\n if (!firebase.auth().currentUser) {\n var email = document.getElementById('email').value;\n var password = document.getElementById('password').value;\n if (email.length < 4) {\n alert('Please enter an email address.');\n return;\n }\n if (password.length < 4) {\n alert('Please enter a password.');\n return;\n }\n // Sign in with email and pass.\n // [START authwithemail]\n firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n // [START_EXCLUDE]\n if (errorCode === 'auth/wrong-password') {\n alert('Wrong password.');\n } else {\n alert(errorMessage);\n }\n console.log(error);\n // [END_EXCLUDE]\n });\n // [END authwithemail]\n }\n}", "async userSignIn(ctx, payload) {\n await fb\n .auth()\n .signInWithEmailAndPassword(payload[0], payload[1])\n .then(response => {\n ctx.dispatch(\"fetchUserCollection\", response.user.uid);\n ctx.userCollection = ctx.getters.getUserCollection;\n ctx.commit(\"setUser\", response.user.uid);\n ctx.commit('setSignedIn', true);\n ctx.commit('setSignInBox', false);\n if(payload[2] == true) {\n ctx.commit('setKeepSignedIn', true);\n localStorage.setItem(\"loggedIn\", response.user.uid);\n } else {\n ctx.commit('setKeepSignedIn', false);\n sessionStorage.setItem('loggedIn', response.user.uid);\n }\n ctx.dispatch(\"fetchCustomShelfs\");\n ctx.dispatch('fetchMovieNightLists', response.user.uid);\n })\n .catch(error => {\n ctx.commit('setLoginFailure', true);\n ctx.commit('setFailureMessage', error.message);\n console.log(error);\n });\n }", "function signinUser(email, password) {\n\t\t\t$.post(\"/api/signin\", {\n\t\t\t\temail: email,\n\t\t\t\tpassword: password\n\t\t\t})\n\t\t\t\t.then(function () {\n\t\t\t\t\twindow.location.replace(\"/gallery\");\n\t\t\t\t})\n\t\t\t\t// .catch(function (err) {\n\t\t\t\t// \tconsole.log(err);\n\t\t\t\t// });\n\t\t\t\t.fail(function() {\n\t\t\t\t\tconsole.log(\"------------------invalid login---------------------\")\n\t\t\t\t\tlet emailContain = $(\"#emailErrorContainer\");\n \t\t\tlet passContain = $(\"#passErrorContainer\");\n\t\t\t\t\tlet emailErr= $(\"<small>\");\n\t\t\t\t\temailErr.attr(\"id\", \"passwordHelp\");\n\t\t\t\t\temailErr.addClass(\"text-danger\");\n\t\t\t\t\temailErr.text(\"Please ensure your email is valid.\");\n\t\t\t\t\temailContain.append(emailErr);\n\t\t\t\t\tlet passErr= $(\"<small>\");\n\t\t\t\t\tpassErr.attr(\"id\", \"passwordHelp\");\n\t\t\t\t\tpassErr.addClass(\"text-danger\");\n\t\t\t\t\tpassErr.text(\"Please enter a correct password\");\n\t\t\t\t\tpassContain.append(passErr);\n\t\t\t\t})\n\t\t}", "function handleAuthClick() {\n auth2.signIn();\n}", "signIn (data) {\n return new Promise((resolve, reject) => {\n axios.post(IP + '/signIn', data).then(response => {\n resolve(response.body.data)\n }).catch(e => {\n reject(e)\n })\n })\n }", "function initApp() {\n // Listening for auth state changes.\n // [START authstatelistener]\n firebase.auth().onAuthStateChanged(function(user) {\n // [START_EXCLUDE silent]\n // document.getElementById('quickstart-verify-email').disabled = true;\n console.log(user);\n // [END_EXCLUDE]\n if (user) {\n if(window.location.pathname.split(\"/\").pop() !== 'index.html'){\n location.assign('index.html');\n }\n console.log(user);\n // if (user) {\n // // sessionStorage.setItem(\"useremail2\", user.uid);\n // console.log(user.uid);\n // location.assign('index.html');\n // User is signed in.\n let displayName = user.displayName;\n let email = user.email;\n let emailVerified = user.emailVerified;\n let photoURL = user.photoURL;\n let isAnonymous = user.isAnonymous;\n let uid = user.uid;\n let providerData = user.providerData;\n // [START_EXCLUDE]\n // document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';\n // document.getElementById('quickstart-sign-in').textContent = 'Sign out';\n // document.getElementById('quickstart-account-details').textContent = JSON.stringify(user, null, ' ');\n // if (!emailVerified) {\n // // document.getElementById('quickstart-verify-email').disabled = false;\n // }\n // [END_EXCLUDE]\n } else {\n // User is signed out.\n console.log(\"no hay sesion\");\n // if (window.location.pathname.split(\"/\").pop() !== \"registration.html\"){\n // location.assign('registration.html');\n // }\n // console.log(window.location.pathname.split(\"/\").pop());\n // if (location)\n // location.assign('registration.html');\n // [START_EXCLUDE]\n // document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';\n // document.getElementById('quickstart-sign-in').textContent = 'Sign in';\n // document.getElementById('quickstart-account-details').textContent = 'null';\n // [END_EXCLUDE]\n }\n // [START_EXCLUDE silent]\n document.getElementById('loginbtn').disabled = false;\n // [END_EXCLUDE]\n });\n // [END authstatelistener]\n \n document.getElementById('loginbtn').addEventListener('click', toggleSignIn, false);\n document.getElementById('signupbtn').addEventListener('click', handleSignUp, false);\n // document.getElementById('quickstart-verify-email').addEventListener('click', sendEmailVerification, false);\n document.getElementById('buttonforgot').addEventListener('click', sendPasswordReset, false);\n }", "function signinCallback(authResult) {\n if (authResult['access_token']) {\n // Successfully authorized\n // Hide the sign-in button now that the user is authorized:\n document.getElementById('signinButton')\n .setAttribute('style', 'display: none');\n // One of the async actions have happened\n unitsReady++;\n checkAllUnitsLoaded();\n } else if (authResult['error']) {\n // There was an error.\n // Possible error codes:\n // \"access_denied\" - User denied access to your app\n // \"immediate_failed\" - Could not automatically log in the user\n console.log('There was an error: ' + authResult['error']);\n\n document.getElementById('signinButton')\n .setAttribute('style', 'display: visible');\n document.getElementById('loggedInUI')\n .setAttribute('style', 'display: none');\n }\n}", "function signInWithFb() {\n return {\n type: SIGN_IN_WITH_FB\n };\n}", "function makeSignInLink(){\n var msrtSpotifyClientId = \"f0bec57f45dd42bead54f9a76d931a9c\";\n\n // Log In and Link to MSRT App\n var queryURLforSpotifyToken = \"https://accounts.spotify.com/authorize/?client_id=\" + msrtSpotifyClientId + \"&response_type=token&redirect_uri=http%3A%2F%2Fmsrt-spotify.herokuapp.com%2F&scope=user-read-private%20user-read-email%20playlist-modify-public%20playlist-modify-private%20playlist-read-private%20playlist-read-collaborative\";\n // console.log(\"Log In URL...\")\n // console.log(queryURLforSpotifyToken);\n\n $('#sign-in').attr('href', queryURLforSpotifyToken);\n\n // Log Out (if needed in future)\n // console.log(\"Log Out URL (if needed in future)...\")\n // console.log(\"https://accounts.spotify.com/en/status\")\n }", "function signInCallback(authResult) {\n if (authResult['code']) {\n var auth_info = {};\n auth_info['code'] = authResult['code'];\n $.ajax({\n type: 'POST',\n url: '/authenticate/',\n data: auth_info,\n success: function(result) {\n var result_obj = JSON.parse(result);\n id_token_var = result_obj.id_token;\n document.cookie = \"id_token=\" + id_token_var;\n if (id_token_var) {\n // fill in account that was used to log in\n // and store info to a cookie\n getLoginInfo(id_token_var);\n switchToSearch(false);\n }\n else {\n switchToWarning();\n }\n },\n error: function(error) {\n console.log(\"An error occurred: \" + error.responseText);\n }\n });\n }\n else {\n console.log(\"Sorry, there was an error generating your id token.\");\n }\n}", "function signInStorage() {\n var createUsername = localStorage.getItem('createUsername');\n var createPw = localStorage.getItem('createPw');\n \n var username = document.getElementById('username');\n var pw = document.getElementById('pw');\n \n if (username.value == createUsername && pw.value == createPw) {\n alert('You are logged in.');\n \n // Hides and shows pages if signInSubmitBtn is pressed\n document.getElementById('registerAreaBtn').style.display = 'none'; \n document.getElementById('registerAreaBtn').style.display = 'none'; \n document.getElementById('signInAreaBtn').style.display = 'none'; \n document.getElementById('registerDiv').style.display = 'none'; \n document.getElementById('signInDiv').style.display = 'none'; \n document.getElementById('welcomeDiv').style.display = 'unset'; \n } else {\n alert('Error on login');\n }\n \n // Retrieves\n document.getElementById(\"welcomePhrase\").innerHTML = localStorage.getItem(\"createUsername\");\n}", "function enterSession(data) {\n firebase.auth().signInWithEmailAndPassword(data.email, data.pass)\n .catch(function(error) {\n console.log(error);\n }); \n}", "signIn() {\n\n if (this.$.form.validate()) {\n let phone = this.phone;\n let password = this.password;\n this.details = { mobile: phone, password: password }\n this.$.form.reset();\n this._makeAjax(`http://10.117.189.55:9090/admanagement/users/login`, \"post\", this.details);\n\n } else {\n this.$.blankForm.open();\n\n }\n }", "_requestSignIn() {\n const event = new CustomEvent('sign-in', {\n detail: {\n 'sign-in': true,\n },\n });\n this.dispatchEvent(event);\n }", "function initApp() {\n // Listening for auth state changes.\n // [START authstatelistener]\n firebase.auth().onAuthStateChanged(function(user) {\n // [START_EXCLUDE silent]\n document.getElementById('quickstart-verify-email').disabled = true;\n\t\t\t\t\tsignInEmail.innerHTML = \"Not Signed In\";\n\t\t\t\t\tloggedInView.style.display = 'none';\n $(\"#loggedInContent\").fadeOut();\n\t\t\t\t\tloginPage.style.display = 'block';\n\t\t\t\t\t\n // [END_EXCLUDE]\n if (user) {\n // User is signed in.\n var displayName = user.displayName;\n var email = user.email;\n var emailVerified = user.emailVerified;\n var photoURL = user.photoURL;\n var isAnonymous = user.isAnonymous;\n var uid = user.uid;\n var providerData = user.providerData;\n\t\t\t\t\t\t\n\n // [START_EXCLUDE]\n \n signInEmail.innerHTML = user.email;\n loggedInView.style.display = 'block';\n // loggedInContent.style.display = 'block';\n $(\"#loggedInContent\").fadeIn();\n $('#wrapper').fadeOut();\n loginPage.style.display = 'none';\n \n document.getElementById('quickstart-sign-in').textContent = 'Sign out';\n //document.getElementById('quickstart-account-details').textContent = JSON.stringify(user, null, ' ');\n\t\t\t\t\t\t\n if (!emailVerified) {\n document.getElementById('quickstart-verify-email').disabled = false;\n }\n // [END_EXCLUDE]\n } else {\n // User is signed out.\n // [START_EXCLUDE]\n $('#wrapper').fadeIn();\n document.getElementById('quickstart-sign-in').textContent = 'Sign in';\n //document.getElementById('quickstart-account-details').textContent = 'null';\n // [END_EXCLUDE]\n }\n // [START_EXCLUDE silent]\n document.getElementById('quickstart-sign-in').disabled = false;\n // [END_EXCLUDE]\n });\n // [END authstatelistener]\n\n document.getElementById('quickstart-sign-in').addEventListener('click', toggleSignIn, false);\n document.getElementById('quickstart-sign-up').addEventListener('click', handleSignUp, false);\n document.getElementById('quickstart-verify-email').addEventListener('click', sendEmailVerification, false);\n document.getElementById('quickstart-password-reset').addEventListener('click', sendPasswordReset, false);\n\n }", "signIn() {\n\n if (this.$.form.validate()) {\n let phone = this.phone;\n let password = this.password;\n this.details = { mobile: phone, password: password }\n this.$.form.reset();\n this._makeAjax(`${baseUrl1}/akshayapathra/admins`, 'post', this.details);\n } else {\n\n }\n }", "function gpSignInCallback() {\n\tvar profile = googleUser.getBasicProfile();\n\tvar id_token = googleUser.getAuthResponse().id_token;\n\t$('#fg_token').val(id_token);\n\t$('#fg_id').val(profile.getId());\n\t$('#fgl_id').val(profile.getId());\n\t$('#fgl_token').val(id_token);\n\t$('#fgl_type').val('Google');\n\t$('#fg_type').val('Google');\n\tif(!is_social_signin) {\n\t\tisAlreadySignedUP(function() {\n\t\t\t$('#fgl_form').submit();\n\t\t}, function() {\n\t\t\t$('#fg_name').val(profile.getName());\n\t\t\t$('#fg_email').val(profile.getEmail());\n\t\t\tsecondStageSocialSignUp();\n\t\t}, null);\n\t\t$('#otp_container').hide('slow');\n\t} else {\n\t\tisAlreadySignedUP(function() {\n\t\t\t$('#fgl_form').submit();\n\t\t}, function() {\n\t\t\t$('#s_login_error').show('slow');\n\t\t\t$('#s_login_error').html('You have to SignUp using Google');\n\t\t}, null);\n\t}\n}", "function loginToR(cookie, publicKey) {\n\talert(\"loginToR\");\n\tvar username = 'ruser';\n var password = '875test123BH';\n var payload = username + \"\\n\" + password;\n var chunks = publicKey.split(':', 2);\n var exp = chunks[0];\n var mod = chunks[1];\n var encrypted = encrypt(payload, exp, mod);\n\tvar encryption = encodeURIComponent(encrypted);\n var pck = \"persist=1&appUri=&clientPath=%2Fauth-sign-in&v=\" + encryption;\n\t$.ajax({\n \t\ttype: \"POST\",\n \t\turl: \"http://221.199.209.249:8787/auth-do-sign-in/\",\n \t\tdata: pck,\n\t\tcontentType: \"application/x-www-form-urlencoded\",\n\t\tcomplete: function(xhr, textStatus) {alert(xhr.status + \" \" + xhr.getAllResponseHeaders());}\n\t\t//cookie: cookie,\n\t\t//xhrFields: { withCredentials:true }\n\t\t})\n \t\t.done(function(msg) {\n\t\talert(\"done\");\n\t\t//alert(\"loginToR: \" + msg);\n\t\t//alert (msg.getAllResponseHeaders());\n \t\t//restartRequest(msg);\n \t\t}).fail(function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText + \" \" + jqXHR.responseXML + \" \" + jqXHR.responseHeader);})\n \t\t.always(function() { alert(\"complete\"); });\n\talert(\"after ajax\");\n}", "function initApp() {\n // Result from Redirect auth flow.\n // [START getidptoken]\n firebase.auth().getRedirectResult().then(function(result) {\n if (result.credential) {\n // This gives you a GitHub Access Token. You can use it to access the GitHub API.\n var token = result.credential.accessToken;\n // [START_EXCLUDE]\n // document.getElementById('quickstart-oauthtoken').textContent = token;\n } else {\n // document.getElementById('quickstart-oauthtoken').textContent = 'null';\n // [END_EXCLUDE]\n }\n // The signed-in user info.\n var user = result.user;\n }).catch(function(error) {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n // The email of the user's account used.\n var email = error.email;\n // The firebase.auth.AuthCredential type that was used.\n var credential = error.credential;\n // [START_EXCLUDE]\n if (errorCode === 'auth/account-exists-with-different-credential') {\n alert('You have already signed up with a different auth provider for that email.');\n // If you are using multiple auth providers on your app you should handle linking\n // the user's accounts here.\n } else {\n console.error(error);\n }\n // [END_EXCLUDE]\n });\n // [END getidptoken]\n // Listening for auth state changes.\n // [START authstatelistener]\n firebase.auth().onAuthStateChanged(function(user) {\n if (user) {\n //document.getElementById('user-info').css(\"display\", \"block\");\n // User is signed in.\n var displayName = user.displayName;\n var email = user.email;\n var emailVerified = user.emailVerified;\n var photoURL = user.photoURL;\n var isAnonymous = user.isAnonymous;\n var uid = user.uid;\n var providerData = user.providerData;\n var currentUser = JSON.stringify(user, null, ' ');\n // user.getToken().then(function(idToken) {\n // getUser(idToken);\n // });\n // [START_EXCLUDE]\n // document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';\n document.getElementById('quickstart-sign-in').textContent = 'Sign out';\n // document.getElementById('quickstart-account-details').textContent = currentUser;\n // document.getElementById('user-photo').attr('src', photoURL);\n // document.getElementById('user-name').textContent = displayName;\n // [END_EXCLUDE]\n } else {\n // User is signed out.\n // [START_EXCLUDE]\n //document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';\n document.getElementById('quickstart-sign-in').textContent = 'Sign in with GitHub';\n //document.getElementById('quickstart-account-details').textContent = 'null';\n //document.getElementById('quickstart-oauthtoken').textContent = 'null';\n // [END_EXCLUDE]\n }\n // [START_EXCLUDE]\n document.getElementById('quickstart-sign-in').disabled = false;\n // [END_EXCLUDE]\n });\n // [END authstatelistener]\n document.getElementById('quickstart-sign-in').addEventListener('click', toggleSignIn, false);\n}", "function anonymousSignIn(e) {\n e.preventDefault();\n errorReset();\n window.Babble.register({ name: '', email: '' });\n}", "function onSigninClicked(){\n var username = document.getElementById(\"txtUsername\").value;\n var password = document.getElementById(\"txtPassword\").value;\n localStorage.setItem(\"username\", username);\n data = {'username':username, 'password':password};\n $.getJSON(\"/login_verify_credentials\", data, onSigninSuccess, onSigninFailed);\n}", "function registerSignIn() {\n\t/* Set up the request by specifying the correct API endpoint,\n\tgrabbing the unique csrf token and collecting the data we\n\twould like to send to the API */\n\tconst productActionURL = ('/signIn/');\n\tconst securityToken = getCSRFToken('csrftoken');\n\tconst productData = {employeeID: getEmployeeID(), employeePassword: getEmployeePassword()};\n\n\t// As per the comment in apiRequest.js, we need to use the POST verb to create a new database record\n\tajaxPost(productActionURL, productData, securityToken, (callbackResponse) => {\n\n\t// Use the status code stored in our callbackResponse to see if the request was successful\n\tif (isSuccessResponse(callbackResponse)) {\n\t\tdisplayMessage('The product was successfully added.', 'success');\n\t\tdocument.getElementById('employeeID').value = '';\n\t\tdocument.getElementById('employeePassword').value = ''\n\t}\n\n\t// Use the status code stored in our callbackResponse to see if the request failed\n\tif (isErrorResponse(callbackResponse)){\n\t\tdisplayMessage('The request to add a product was denied.', 'failed');\n\t}\n});\n\n}", "function singInWithFacebook() {\n var provider = new firebase.auth.FacebookAuthProvider();\n var d = new Date();\n firebase.auth().signInWithPopup(provider).then(({user}) => {\n //create database of user\n if (user.metadata.creationTime === user.metadata.lastSignInTime) {\n createData('/users/' + user.uid, {\n \"displayName\": user.displayName,\n \"email\": user.email,\n \"joinedOn\": d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear(),\n \"username\": user.uid,\n });\n }\n\n //final step creat local login\n return user.getIdToken().then((idToken) => {\n return fetch(\"/sessionLogin\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"CSRF-Token\": Cookies.get(\"XSRF-TOKEN\"),\n },\n body: JSON.stringify({\n idToken\n }),\n });\n });\n })\n .then(() => {\n window.location.assign(\"/dashboard\");\n });\n}", "function signIn(userNamePrompt, passwordPrompt) {\n for (var i=0; i < database.length; i++) {\n if (userNamePrompt === database[i].username &&\n passwordPrompt === database[i].password) {\n return true;\n }\n }\n return false;\n}", "function pressEnterLogin(e) {\n if (e.keyCode == 13) {\n signIn();;\n }\n}", "function handleSignIn(event){\n\n event.preventDefault();\n let credentials = { email: email, password: md5(password)};\n\n axios.post(DATABASE_URL + CLIENTS+ '/signin', credentials).then( res => {\n\n //Validates the credentials\n if(res.data === 'Email wrong'){\n alert(labels.noEmailLabel)\n } else if(res.data === 'Password wrong'){\n alert(labels.wrongPasswordLabel)\n } else {\n localStorage.setItem('client', JSON.stringify(res.data));\n localStorage.setItem('isLogged', 'true');\n context.client = res.data;\n context.login();\n context.updateContext(context);\n router.push(router.locale+'/dashboard');\n }\n })\n\n }", "function singInWithGithub() {\n var provider = new firebase.auth.GithubAuthProvider();\n var d = new Date();\n firebase.auth().signInWithPopup(provider).then(({user}) => {\n //create database of user\n if (user.metadata.creationTime === user.metadata.lastSignInTime) {\n createData('/users/' + user.uid, {\n \"displayName\": user.displayName,\n \"email\": user.email,\n \"joinedOn\": d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear(),\n \"username\": user.uid,\n });\n }\n //final step creat local login\n return user.getIdToken().then((idToken) => {\n return fetch(\"/sessionLogin\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"CSRF-Token\": Cookies.get(\"XSRF-TOKEN\"),\n },\n body: JSON.stringify({\n idToken\n }),\n });\n });\n })\n .then(() => {\n window.location.assign(\"/dashboard\");\n });\n}", "function verifySignedIn(){\n fs.readFile('login-credentials.json', function read(err, data) {\n if (err) {\n throw err;\n }\n content = data;\n if(content.toString() === ''){\n location.href = \"signup.html\";\n }else{\n refreshCredentials(JSON.parse(content));\n }\n \n });\n}", "function signIn() {\n// Sign into Firebase using popup auth & Google as the identity provider.\n var provider = new firebase.auth.GoogleAuthProvider();\n firebase.auth().signInWithPopup(provider);\n}", "signin(req, res) {\n // first, find user by the email/username in the request body.\n const loginData = req.body.email ? {email: req.body.email} : {username: req.body.username};\n // When retrieving the user from database, include the password for authentication:\n User.findOne(loginData, '+password', (err, user) => {\n // Error check\n if(err) return res.status(500).send(err);\n // Not being able to find a user is not an error, handles null\n if(user === null) {\n response = {success: false, message: 'Could not find registered user with the email/username'};\n return res.status(500).send(response);\n }\n // if there's no user found, or they put a wrong password:\n if(!user || (user && !user.validPassword(req.body.password))) {\n response = {success: false, message: 'Incorrect email/username or password.'};\n return res.status(500).send(response);\n }\n\n const userData = user.toObject();\n // remove the password from this object before creating the token:\n delete userData.password\n\n userData['iat'] = new Date().getTime() / 1000;\n userData['exp'] = (new Date().getTime() + 10000000) / 1000; // 1000 = 1 second\n\n const token = jwt.sign(userData, process.env.SECRET_TOKEN);\n // send the token back to the client in our response:\n response = {success: true, message: 'Logged in successfully.', token};\n return res.status(200).json(response);\n });\n }", "checkAuth() { }", "function updateSigninStatus(isSignedIn) {\n if (isSignedIn && !window.sessionStorage.getItem('wasLoggedIn')\n && !window.sessionStorage.getItem('EventsInserted')) {\n window.sessionStorage.setItem('wasLoggedIn', true);\n authorizeButton.style.display = 'none';\n // getScheduleFromServer();\n insertEvent();\n }\n else if (window.sessionStorage.getItem('wasLoggedIn')){\n if ( window.sessionStorage.getItem('EventsInserted')) { // case of was logged in in current session and events inserted\n successModal(\"Calendar Updated Successfuly\");\n }\n else { // case of insertion fail but login success\n failureModal({message: 'Insertion of events failed'});\n }\n }\n}", "function defSignIn(){\n\tvar provider = new firebase.auth.GoogleAuthProvider();\n\tfirebase.auth()\n\t\t.signInWithPopup(provider)\n\t\t.then((result) => {\n\t\t\t/**@type {firebase.auth.OAuthCredential} */\n\t\t\tvar credential = result.credential;\n\n\t\t\t// This gives you a Google Access Token. You can use it to access the Google API.\n\t\t\tvar token = credential.accessToken;\n\t\t\t// The signed-in user info.\n\t\t\tvar user = result.user;\n\t\t\t// ...\n\t\t\treturn user;\n\t\t}).catch((error) => {\n\t\t\t// Handle Errors here.\n\t\t\tvar errorCode = error.code;\n\t\t\tvar errorMessage = error.message;\n\t\t\t// The email of the user's account used.\n\t\t\tvar email = error.email;\n\t\t\t// The firebase.auth.AuthCredential type that was used.\n\t\t\tvar credential = error.credential;\n\t\t\t// ...\n\t\t\t//body.innerHTML = '<button onclick=\"createAccount();\">Sign up</button><script src = \"sketch.js\" defer></script>';\n\t\t}).then((user) => {\n\t\t\t//console.log(user.uid, user.displayName, user.email);\n\t\t\tvar userId = user.uid;\n\t\t\tfirebase.database().ref('users').orderByChild('specialId').equalTo(userId).once('value',function(snapshot){\n\t\t\t\tif(!snapshot.exists()){\n\t\t\t\t\tfirebase.auth().signOut().then(() => {\n\t\t\t\t\t\t// Sign-out successful.\n\t\t\t\t\t\t//console.log('signed out.');\n\t\t\t\t\t}).catch((error2) => {\n\t\t\t\t\t\t// An error happened.\n\t\t\t\t\t\t//console.log(error2);\n\t\t\t\t\t});\n\t\t\t\t\talert('No account found. Click \"sign up\" to ... well, sign up.');\n\n\t\t\t\t}else{\n\t\t\t\t\t//console.log(snapshot.val());\n\t\t\t\t\tvar snapshotData = snapshot.val();\n\n\n\t\t\t\t\tdocument.getElementById('signedOut').hidden = true;\n\t\t\t\t\tdocument.getElementById('signedIn').hidden = false;\t\t\t\t\t\n\n\t\t\t\t\tvar key = Object.keys(snapshotData)[0];\n\n\t\t\t\t\tclientData.username = snapshotData[key].username;\n\t\t\t\t\tclientData.email = snapshotData[key].email;\t\t\t\t\t\n\t\t\t\t\tclientData.image = snapshotData[key].image;\n\n\t\t\t\t\tdocument.getElementById('user-image').src= snapshotData[key].image;\n\n\t\t\t\t\tclientData.iron = snapshotData[key].gameData.iron;\n\t\t\t\t\tclientData.oil = snapshotData[key].gameData.oil;\t\t\t\t\n\n\t\t\t\t\tclientData = snapshotData[key];\n\n\t\t\t\t\tfetch(`/user-signed-in/${snapshotData[key].username}/${snapshotData[key].email}`)\n\t\t\t\t\t\t.then(response => response.json())\n\t\t\t\t\t\t.then((data)=>{\n\t\t\t\t\t\t\tconsole.log(data);\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}).catch((err) => {\n\t\t\t//console.log(err);\n\t\t});\n}", "async handleSignIn(){\n console.log('sign in')\n\n if(this.handleFieldsCheck()){\n let [ username , password ] = [this.form.username.value, this.form.password.value]\n this.form.reset()\n\n // use to get user location login record\n const publicIp = require(\"react-public-ip\");\n const ipv6 = await publicIp.v6() || \"\";\n\n loginUser({\n username : username,\n password : password,\n ipv6 : ipv6\n }).then(({data}) => {\n if(data)\n {\n this.errorMessage.style.display = 'none'\n document.querySelector('.models').classList.remove('authorized')\n setTimeout(() => {\n localStorage.setItem('user', data)\n this.props.isAuthorized({ isAuthorized : true }) \n }, 1000); \n }else {\n this.errorMessage.innerHTML = 'Invalid username/password, please try again !'\n this.errorMessage.style.display = 'block'\n }\n \n })\n .catch(err => {console.error(err)})\n }else {\n this.errorMessage.innerHTML = 'Please fill in all the following red field(s)'\n this.errorMessage.style.display = 'block'\n }\n }", "signIn() {\n const paramsUser = {\n username: this.username,\n password: this.password,\n };\n let formData = [];\n for (let index in paramsUser) {\n let encodedKey = encodeURIComponent(index);\n let encodedValue = encodeURIComponent(paramsUser[index]);\n formData.push(encodedKey + '=' + encodedValue);\n }\n formData = formData.join('&');\n const params = {\n method: 'POST',\n body: formData,\n headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}\n };\n fetch(CONTEXT_URL + '/login', params)\n .then(response => response.json())\n .then(action(user => {\n sessionStorage.setItem('user', JSON.stringify(user));\n this.user = user;\n }))\n .catch(action(error => this.error = 'Invalid username or password'));\n }", "function signInFunction() {\n if ($(\"login-username\").val()==\"\"){\n $(\"login-wrong\").val(\"Fill in all of the fields\");\n console.log($(\"login-wrong\").val());\n\n }\n if ($(\"login-password\").val()==\"\"){\n $(\"login-wrong\").val(\"Fill in all of the fields\");\n }\n else\n {\n var login_email = $('#login-username').val();\n var login_password = $('#login-password').val();\n ref.authWithPassword({\n email : login_email,\n password : login_password//this inputs the varibles that we saved above in order to check it on the server\n }, function(error, authData) \n {\n if (error) {\n //reload the page withew$\n $('login-wrong').val(\"Wrong password or username\");\n console.log(\"Login Failed!\", error);\n } else {\n console.log(\"Authenticated successfully with payload:\", authData);\n //make it load into home.html\n }\n });\n }\n }", "function doLogin(email, key) {\n const crypto = new OpenCrypto();\n var message = crypto.stringToArrayBuffer(email);\n return window.crypto.subtle.sign(\n {\n name: \"RSASSA-PKCS1-v1_5\",\n hash: { name: \"SHA-512\" },\n },\n key,\n message,\n )\n .catch(error => {\n output(\"Couldn't create the signed message\");\n })\n .then(signed => {\n const crypto = new OpenCrypto();\n const base64 = crypto.arrayBufferToBase64(signed);\n return $.post('', {'email':email, 'signed':base64})\n }) // Login errors are handled in the parent function\n}", "emailLogin() {\n window.AccountKit.login(\n 'EMAIL',\n {emailAddress: '[email protected]'},\n this.loginCallback\n );\n }", "function signIn() {\n // Calculating the redirect URI for current window\n let redirectURI = window.location.origin + '/auth';\n \n // Google's OAuth 2.0 endpoint for requesting an access token\n let oauthEndpoint = PROD_ENDPOINT + projectId + \"/auth\";\n\n // Create <form> element to submit parameters to OAuth 2.0 endpoint.\n let form = document.createElement('form');\n form.setAttribute('method', 'GET');\n form.setAttribute('action', oauthEndpoint);\n\n // Parameters to pass to OAuth 2.0 endpoint.\n let params = {\n 'access_type': 'offline',\n 'client_id': clientId,\n 'include_granted_scopes': 'true',\n 'prompt' : 'consent',\n 'redirect_uri': redirectURI,\n 'response_type': 'code',\n 'scope': OAUTH_SCOPE,\n 'state': 'pass-through value'\n };\n\n // Add form parameters as hidden input values.\n for (let p in params) {\n let input = document.createElement('input');\n input.setAttribute('type', 'hidden');\n input.setAttribute('name', p);\n input.setAttribute('value', params[p]);\n form.appendChild(input);\n }\n\n // Add form to page and submit it to open the OAuth 2.0 endpoint.\n document.body.appendChild(form);\n pushLog(LogType.HTTP, \"GET Request\", JSON.stringify(form, null, 4));\n form.submit();\n}", "static async logIn(formData) {\n const { username, password } = formData;\n const data = {\n username: username,\n password: password\n };\n \n let res = await this.request(\n 'auth/token', \n data,\n 'post'\n );\n \n this.setToken(res.token);\n return res.token;\n }", "async function signIn(userForm) {\n const headers = {};\n attach_headers([HEADERS.CSRF], headers);\n const body = { user: userForm };\n\n cleanupAuthState();\n dispatch({ type: LOADING_STARTED });\n const resp = await supervise_rq(() =>\n axios.post(API_PATHS.AUTH_SIGN_IN, body, { headers })\n );\n\n if (resp.status === STATUS.SUCCESS) {\n const user = await getUserData();\n dispatch({\n type: AUTH_ACTIONS.AUTH_SUCCESS,\n payload: `Hi, ${user.first_name}. Sign-in is successful!`,\n });\n } else {\n dispatch({\n type: AUTH_ACTIONS.AUTH_ERROR,\n payload:\n \"The provided login details did not work. Please verify your credentials, and try again.\",\n });\n }\n }", "function emailLogin() {\n var emailAddress = document.getElementById(\"email\").value;\n AccountKit.login('EMAIL', {emailAddress: emailAddress}, loginCallback);\n}", "function signin(form, email, password) {\n\tvar emailValue = document.getElementById(email).value;\n\tvar passwordValue = document.getElementById(password).value;\n\t\n\tfirebase.auth().signInWithEmailAndPassword(emailValue, passwordValue)\n\t\t.then(function() { \n\t\t\tsendTokenToForm(form.unbind());\n\t\t})\n\t\t.catch(function(error) {\n\t\t addHidden(form, 'error', error.code);\n form.unbind().submit();\n\t\t});\n}" ]
[ "0.7495852", "0.7359", "0.7138019", "0.7068842", "0.70171005", "0.69556946", "0.6917877", "0.69121355", "0.68189925", "0.68115073", "0.67090774", "0.66729325", "0.66713935", "0.6623656", "0.6615702", "0.6602737", "0.6553545", "0.654584", "0.65361077", "0.6498028", "0.6497812", "0.6474888", "0.6473005", "0.64724296", "0.6415522", "0.6414191", "0.639284", "0.63920724", "0.6383927", "0.6380389", "0.6374869", "0.6370169", "0.6359967", "0.6341487", "0.63330317", "0.63325053", "0.6332325", "0.6330692", "0.63303816", "0.63237774", "0.63224995", "0.6300784", "0.62878925", "0.6275181", "0.62690574", "0.62536764", "0.62444454", "0.623912", "0.6235846", "0.62279725", "0.6221296", "0.62144727", "0.6193414", "0.6180465", "0.6178202", "0.61741835", "0.6165422", "0.61631227", "0.61631036", "0.61488", "0.6148004", "0.61461097", "0.61375713", "0.6135476", "0.6134402", "0.6133112", "0.6124273", "0.61242497", "0.61162585", "0.61040634", "0.60965914", "0.6095357", "0.60889167", "0.60882324", "0.60831034", "0.60663337", "0.60634804", "0.60543966", "0.6044457", "0.6044242", "0.60365766", "0.6032891", "0.603252", "0.6031407", "0.6017221", "0.6015305", "0.6011487", "0.60038686", "0.60036695", "0.59984803", "0.59965795", "0.5992107", "0.59893334", "0.5987535", "0.59830236", "0.5980009", "0.5979016", "0.5977126", "0.5967274", "0.5966493", "0.59625804" ]
0.0
-1
Initializing each property. TODO: Perhaps a better way is to write a generic function that accepts property_name and property initializer for that property. It will test if property exists. If not, then call the initializer function on that property. It will shorten the code and make it decent.
function vault_init() { var vault_modified = false; my_log("vault_init(): Initializing missing properties from last release", new Error); // All top level values if (!pii_vault.guid) { //Verifying that no such user-id exists is taken care by //Create Account or Sign-in. //However, if there is a duplicate GUID then we are in trouble. //Need to take care of that somehow. pii_vault.guid = generate_random_id(); my_log("vault_init(): Updated GUID in vault: " + pii_vault.guid, new Error); vault_write("guid", pii_vault.guid); pii_vault.current_user = current_user; vault_write("current_user", pii_vault.current_user); pii_vault.sign_in_status = sign_in_status; vault_write("sign_in_status", pii_vault.sign_in_status); } if (!pii_vault.salt_table) { var salt_table = {}; //current_ip for current input, not ip address var current_ip = pii_vault.guid; for(var i = 0; i < 1000; i++) { salt_table[i] = CryptoJS.SHA1(current_ip).toString(); current_ip = salt_table[i]; } pii_vault.salt_table = salt_table; my_log("vault_init(): Updated SALT TABLE in vault", new Error); vault_write("salt_table", pii_vault.salt_table); } if (!pii_vault.initialized) { pii_vault.initialized = true; my_log("vault_init(): Updated INITIALIZED in vault", new Error); vault_write("initialized", pii_vault.initialized); } if (!pii_vault.total_site_list) { // This is maintained only to calculate total number of DIFFERENT sites visited // from time to time. Its reset after every new current_report is created. pii_vault.total_site_list = []; my_log("vault_init(): Updated TOTAL_SITE_LIST in vault", new Error); vault_write("total_site_list", pii_vault.total_site_list); } if (!pii_vault.password_hashes) { // This is maintained separarely from current_report as it should not // be sent to the server. // Structure is: Key: 'username:etld' // Value: { // 'pwd_full_hash':'xyz', // 'pwd_short_hash':'a', // 'salt' : 'zz', // 'pwd_group' : '', // 'initialized': Date } pii_vault.password_hashes = {}; my_log("vault_init(): Updated PASSWORD_HASHES in vault", new Error); vault_write("password_hashes", pii_vault.password_hashes); } if (!pii_vault.past_reports) { pii_vault.past_reports = []; my_log("vault_init(): Updated PAST_REPORTS in vault", new Error); vault_write("past_reports", pii_vault.past_reports); } // All config values if (!pii_vault.config.deviceid) { //A device id is only used to identify all reports originating from a //specific Appu install point. It serves no other purpose. pii_vault.config.deviceid = generate_random_id(); my_log("vault_init(): Updated DEVICEID in vault: " + pii_vault.config.deviceid, new Error); flush_selective_entries("config", ["deviceid"]); } if (!pii_vault.config.current_version) { var response_text = read_file('manifest.json'); var manifest = JSON.parse(response_text); pii_vault.config.current_version = manifest.version; my_log("vault_init(): Updated CURRENT_VERSION in vault: " + pii_vault.config.current_version, new Error); flush_selective_entries("config", ["current_version"]); } if (!pii_vault.config.status) { pii_vault.config.status = "active"; my_log("vault_init(): Updated STATUS in vault", new Error); vault_write("config:status", pii_vault.config.status); } if (!pii_vault.config.disable_period) { pii_vault.config.disable_period = -1; my_log("vault_init(): Updated DISABLE_PERIOD in vault", new Error); vault_write("config:disable_period", pii_vault.config.disable_period); } if (!pii_vault.config.reporting_hour) { pii_vault.config.reporting_hour = 0; //Random time between 5 pm to 8 pm. Do we need to adjust according to local time? var rand_minutes = 1020 + Math.floor(Math.random() * 1000)%180; pii_vault.config.reporting_hour = rand_minutes; my_log("vault_init(): Updated REPORTING_HOUR in vault", new Error); vault_write("config:reporting_hour", pii_vault.config.reporting_hour); } if (!pii_vault.config.next_reporting_time) { var curr_time = new Date(); //Advance by 3 days. curr_time.setMinutes( curr_time.getMinutes() + 4320); //Third day's 0:0:0 am curr_time.setSeconds(0); curr_time.setMinutes(0); curr_time.setHours(0); curr_time.setMinutes( curr_time.getMinutes() + pii_vault.config.reporting_hour); //Start reporting next day pii_vault.config.next_reporting_time = curr_time.toString(); my_log("Report will be sent everyday at "+ Math.floor(rand_minutes/60) + ":" + (rand_minutes%60), new Error); my_log("Next scheduled reporting is: " + curr_time, new Error); my_log("vault_init(): Updated NEXT_REPORTING_TIME in vault", new Error); vault_write("config:next_reporting_time", pii_vault.config.next_reporting_time); } if (!pii_vault.config.report_reminder_time) { pii_vault.config.report_reminder_time = -1; my_log("vault_init(): Updated REPORT_REMINDER_TIME in vault", new Error); vault_write("config:report_reminder_time", pii_vault.config.report_reminder_time); } if (!pii_vault.config.reportid) { pii_vault.config.reportid = 1; my_log("vault_init(): Updated REPORTID in vault", new Error); vault_write("config:reportid", pii_vault.config.reportid); } // All options values if (!pii_vault.options.blacklist) { pii_vault.options.blacklist = []; my_log("vault_init(): Updated BLACKLIST in vault", new Error); vault_write("options:blacklist", pii_vault.options.blacklist); } if (!pii_vault.options.dontbuglist) { pii_vault.options.dontbuglist = []; my_log("vault_init(): Updated DONTBUGLIST in vault", new Error); vault_write("options:dontbuglist", pii_vault.options.dontbuglist); } //Three different types of reporting. //Manual: If reporting time of the day and if report ready, interrupt user and ask // him to review, modify and then send report. //Auto: Send report automatically when ready. //Differential: Interrupt user to manually review report only if current report // entries are different from what he reviewed in the past. // (How many past reports should be stored? lets settle on 10 for now?). // Highlight the different entries with different color background. if (!pii_vault.options.report_setting) { pii_vault.options.report_setting = "manual"; my_log("vault_init(): Updated REPORT_SETTING in vault", new Error); vault_write("options:report_setting", pii_vault.options.report_setting); } // All current report values if (!pii_vault.current_report) { pii_vault.current_report = initialize_report(); my_log("vault_init(): Updated CURRENT_REPORT in vault", new Error); flush_current_report(); } // All aggregate data values if (!pii_vault.aggregate_data) { pii_vault.aggregate_data = initialize_aggregate_data(); my_log("vault_init(): Updated AGGREGATE_DATA in vault", new Error); flush_aggregate_data(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_initializeProperties() {}", "function init() {\n for (var k in PROPERTY) {\n var p = PROPERTY[k];\n PROPERTY_DECODE[p[0]] = [ k, p[1], p[2] ];\n }\n}", "function fv_helper_addProperties(props) {\n var key;\n\n if (this !== window) {\n for (key in props) {\n if (props.hasOwnProperty(key)) {\n Object.defineProperty(this, key, { value: props[key] });\n }\n }\n }\n}", "function createInitProps (Ctor) {\n const propDescriptors = createNativePropertyDescriptors(Ctor);\n\n return (elem) => {\n getPropNamesAndSymbols(propDescriptors).forEach((nameOrSymbol) => {\n const propDescriptor = propDescriptors[nameOrSymbol];\n propDescriptor.beforeDefineProperty(elem);\n\n // We check here before defining to see if the prop was specified prior\n // to upgrading.\n const hasPropBeforeUpgrading = nameOrSymbol in elem;\n\n // This is saved prior to defining so that we can set it after it it was\n // defined prior to upgrading. We don't want to invoke the getter if we\n // don't need to, so we only get the value if we need to re-sync.\n const valueBeforeUpgrading = hasPropBeforeUpgrading && elem[nameOrSymbol];\n\n // https://bugs.webkit.org/show_bug.cgi?id=49739\n //\n // When Webkit fixes that bug so that native property accessors can be\n // retrieved, we can move defining the property to the prototype and away\n // from having to do if for every instance as all other browsers support\n // this.\n Object.defineProperty(elem, nameOrSymbol, propDescriptor);\n\n // DEPRECATED\n //\n // We'll be removing get / set callbacks on properties. Use the\n // updatedCallback() instead.\n //\n // We re-set the prop if it was specified prior to upgrading because we\n // need to ensure set() is triggered both in polyfilled environments and\n // in native where the definition may be registerd after elements it\n // represents have already been created.\n if (hasPropBeforeUpgrading) {\n elem[nameOrSymbol] = valueBeforeUpgrading;\n }\n });\n };\n}", "function createInitProps (Ctor) {\n const propDescriptors = createNativePropertyDescriptors(Ctor);\n\n return (elem) => {\n getPropNamesAndSymbols(propDescriptors).forEach((nameOrSymbol) => {\n const propDescriptor = propDescriptors[nameOrSymbol];\n propDescriptor.beforeDefineProperty(elem);\n\n // We check here before defining to see if the prop was specified prior\n // to upgrading.\n const hasPropBeforeUpgrading = nameOrSymbol in elem;\n\n // This is saved prior to defining so that we can set it after it it was\n // defined prior to upgrading. We don't want to invoke the getter if we\n // don't need to, so we only get the value if we need to re-sync.\n const valueBeforeUpgrading = hasPropBeforeUpgrading && elem[nameOrSymbol];\n\n // https://bugs.webkit.org/show_bug.cgi?id=49739\n //\n // When Webkit fixes that bug so that native property accessors can be\n // retrieved, we can move defining the property to the prototype and away\n // from having to do if for every instance as all other browsers support\n // this.\n Object.defineProperty(elem, nameOrSymbol, propDescriptor);\n\n // DEPRECATED\n //\n // We'll be removing get / set callbacks on properties. Use the\n // updatedCallback() instead.\n //\n // We re-set the prop if it was specified prior to upgrading because we\n // need to ensure set() is triggered both in polyfilled environments and\n // in native where the definition may be registerd after elements it\n // represents have already been created.\n if (hasPropBeforeUpgrading) {\n elem[nameOrSymbol] = valueBeforeUpgrading;\n }\n });\n };\n}", "function initProps(o) {\n\tif (!o._props) {\n\t\to._props = {};\n\t}\n}", "function loadProperties(input) {\n return loadAnything('property', input);\n}", "static initialize(obj, propertyId, contractAddress) { \n obj['propertyId'] = propertyId;\n obj['contractAddress'] = contractAddress;\n }", "function defineProperties(obj, properties) {\n for (const i in properties) {\n const value = properties[i];\n Object.defineProperty(\n obj,\n i,\n typeof value === 'function' ? { value } : value\n );\n }\n}", "function initProps(el, props, animatableModel, dataIndex, cb, during) {\n\t animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);\n\t }", "function initProps(el, props, animatableModel, dataIndex, cb, during) {\n animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);\n}", "function _initFields(scope, obj, isFromDB) {\n\t\tvar i,\n\t\t\tfield,\n\t\t\tinitValue;\n\n\t\tfor (i = 0; i < _configData.length; i = i + 1) {\n\t\t\tfield = _configData[i];\n\t\t\tinitValue = undefined;\n\t\t\tif (obj) {\n\t\t\t\tif (typeof obj !== \"object\") {\n\t\t\t\t\tAssert.require(_isPrimitiveType, \"PropertyBase - Sanity check failed: argument passed is not an object and there is more than one field: \" +\n\t\t\t\t\t\t\"field name: \" + field.dbFieldName +\n\t\t\t\t\t\t\" OBJ: \" + JSON.stringify(obj) +\n\t\t\t\t\t\t\" isPrimitiveType: \" + _isPrimitiveType +\n\t\t\t\t\t\t\" config length: \" + _configData.length);\n\n\t\t\t\t\tinitValue = obj;\n\t\t\t\t} else if (undefined !== obj[field.dbFieldName]) {\n\t\t\t\t\tinitValue = obj[field.dbFieldName];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// only setting the default when no raw object has been passed\n\t\t\t// We should only do this on new objects. We don't want to start setting defaults\n\t\t\t// on an object that came down from a sync source because we will send that change back up\n\t\t\t//\n\t\t\t// Do not set a default value if this object is being constructed from a DB object\n\t\t\t//\n\t\t\t// The caller needs to have an undefined check\n\t\t\tif (!isFromDB && undefined === initValue && undefined !== field.defaultValue) {\n\t\t\t\tinitValue = field.defaultValue;\n\t\t\t}\n\n\t\t\tif (field.classObject) {\n\t\t\t\tinitValue = new field.classObject(initValue);\n\t\t\t}\n\n\t\t\tif (undefined !== initValue) {\n\t\t\t\tscope[field.setterName].apply(scope, [initValue, true]);\n\t\t\t}\n\t\t}\n\t}", "fill(data, fields, fieldCheck) {\n const props = {};\n const doFieldCheck = typeof fieldCheck === 'function';\n\n fields = Array.isArray(fields) ? fields : Object.keys(data);\n\n fields.forEach((propKey) => {\n if (\n !Object.prototype.hasOwnProperty.call(this.getDefinitions(), propKey)\n ) {\n return;\n }\n\n if (doFieldCheck) {\n const fieldCheckResult = fieldCheck(propKey, data[propKey]);\n if (fieldCheckResult === false) {\n return;\n } else if (fieldCheckResult) {\n props[propKey] = fieldCheckResult;\n return;\n }\n }\n\n props[propKey] = data[propKey];\n });\n console.log('properties now ', props);\n this.property(props);\n return props;\n }", "function fillProperties(target,source){for(var key in source){if(source.hasOwnProperty(key)&&!target.hasOwnProperty(key)){target[key]=source[key]}}}", "function fillProperties(target,source){for(var key in source){if(source.hasOwnProperty(key)&&!target.hasOwnProperty(key)){target[key]=source[key];}}}", "function initPropertyValues() {\n var propertyNames = Object.keys(model.values);\n propertyNames.forEach(function (propertyName) {\n properties[propertyName] = 'unknown';\n });\n myself.addValue(properties);\n sendCommand(initialCommands);\n}", "setupStaticProperties() {\n var _a, _b;\n let updateBaseColor = false;\n for (const propName in this.styledProperties) {\n if (!this.styledProperties.hasOwnProperty(propName)) {\n continue;\n }\n const currentValue = this.currentStyledProperties[propName];\n if (currentValue === undefined || currentValue === null) {\n continue;\n }\n if (propName === \"color\" || propName === \"opacity\") {\n updateBaseColor = true;\n }\n else {\n this.applyMaterialGenericProp(propName, currentValue);\n }\n }\n if (updateBaseColor) {\n const color = (_a = this.currentStyledProperties.color) !== null && _a !== void 0 ? _a : 0xff0000;\n const opacity = (_b = this.currentStyledProperties.opacity) !== null && _b !== void 0 ? _b : 1;\n this.applyMaterialBaseColor(color, opacity);\n }\n }", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropNames && defineProp) {\n var props = getOwnPropNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProp(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "setProperties(properties) {\n for (const [key, value] of properties.entries()) {\n switch(key) {\n case \"type\": this.type = value;\n break;\n case \"startArrowHead\": this.startArrowHead = value;\n break;\n case \"endArrowHead\": this.endArrowHead = value;\n }\n }\n }", "load(properties) {\n let p = Object.create(null);\n\n Object.keys(properties).forEach(function(v) {\n p[v] = properties[v];\n });\n\n this.properties = p;\n\n return this;\n }", "function configureProperties(obj) {\n if (getOwnPropertyNames && defineProperty) {\n var props = getOwnPropertyNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProperty(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function configureProperties(obj) {\n if (getOwnPropertyNames && defineProperty) {\n var props = getOwnPropertyNames(obj), i;\n for (i = 0; i < props.length; i += 1) {\n defineProperty(obj, props[i], {\n value: obj[props[i]],\n writable: false,\n enumerable: false,\n configurable: false\n });\n }\n }\n}", "function parseObj() {\n var node = startNode(), first = true, sawGetSet = false;\n node.properties = [];\n next();\n while (!eat(_braceR)) {\n if (!first) {\n expect(_comma);\n if (options.allowTrailingCommas && eat(_braceR)) break;\n } else first = false;\n\n var prop = {type: \"Property\", key: parsePropertyName()}, isGetSet = false, kind;\n if (eat(_colon)) {\n prop.value = parseExpression(true);\n kind = prop.kind = \"init\";\n } else if (options.ecmaVersion >= 5 && prop.key.type === \"Identifier\" &&\n (prop.key.name === \"get\" || prop.key.name === \"set\")) {\n isGetSet = sawGetSet = true;\n kind = prop.kind = prop.key.name;\n prop.key = parsePropertyName();\n if (tokType !== _parenL) unexpected();\n prop.value = parseFunction(startNode(), false);\n } else unexpected();\n\n // getters and setters are not allowed to clash — either with\n // each other or with an init property — and in strict mode,\n // init properties are also not allowed to be repeated.\n\n if (prop.key.type === \"Identifier\" && (strict || sawGetSet)) {\n for (var i = 0; i < node.properties.length; ++i) {\n var other = node.properties[i];\n if (other.key.name === prop.key.name) {\n var conflict = kind == other.kind || isGetSet && other.kind === \"init\" ||\n kind === \"init\" && (other.kind === \"get\" || other.kind === \"set\");\n if (conflict && !strict && kind === \"init\" && other.kind === \"init\") conflict = false;\n if (conflict) raise(prop.key.start, \"Redefinition of property\");\n }\n }\n }\n node.properties.push(prop);\n }\n return finishNode(node, \"ObjectExpression\");\n }", "properties(properties) {\n if (arguments.length === 0) {\n // Return the existing properties.\n const properties = {};\n for (const key of internal(this).properties.keys())\n properties[key] = this.property(key);\n return properties;\n } else {\n // Set new property values.\n for (const key in properties) {\n const value = properties[key];\n this.property(key, value);\n }\n return this;\n }\n }", "function $__jsx_lazy_init(obj, prop, func) {\n\tfunction reset(obj, prop, value) {\n\t\tdelete obj[prop];\n\t\tobj[prop] = value;\n\t\treturn value;\n\t}\n\n\tObject.defineProperty(obj, prop, {\n\t\tget: function () {\n\t\t\treturn reset(obj, prop, func());\n\t\t},\n\t\tset: function (v) {\n\t\t\treset(obj, prop, v);\n\t\t},\n\t\tenumerable: true,\n\t\tconfigurable: true\n\t});\n}", "function ensureInitializerDefineProp(path, state) {\n if (!state.initializerDefineProp) {\n state.initializerDefineProp = path.scope.generateUidIdentifier('initDefineProp');\n var helper = buildInitializerDefineProperty({\n NAME: state.initializerDefineProp\n });\n path.scope.getProgramParent().path.unshiftContainer('body', helper);\n }\n\n return state.initializerDefineProp;\n }", "function buildPropertyStates() {\n // create an object to eventually return (it starts out empty)\n // iterate over all of the KEYS of whatever's exported from 'game/utils/name.js'\n // given a key from name.js, figure out if it is state-worthy (i.e., property, utility)\n // if it is --> '3': new PropertyState(stuff)\n // otherwise do nothing and just move on to the next one\n\n // return the object you've assembled iteratively\n\n let propertyPositions = Object.keys(propertyData);\n let data = {};\n\n propertyPositions.forEach(function(position){\n let propertyConfig = propertyData[position];\n\n if (propertyConfig.price && !propertyConfig.isTax){\n const name = propertyConfig.streetName || propertyConfig.name\n const prop = new Property(name, position);\n data[position] = prop;\n }\n })\n\n return data;\n}", "function ensureInitializerDefineProp(path, state) {\n\t if (!state.initializerDefineProp) {\n\t state.initializerDefineProp = path.scope.generateUidIdentifier('initDefineProp');\n\t var helper = buildInitializerDefineProperty({\n\t NAME: state.initializerDefineProp\n\t });\n\t path.scope.getProgramParent().path.unshiftContainer('body', helper);\n\t }\n\n\t return state.initializerDefineProp;\n\t }", "function ensureInitializerDefineProp(path, state) {\n\t if (!state.initializerDefineProp) {\n\t state.initializerDefineProp = path.scope.generateUidIdentifier('initDefineProp');\n\t var helper = buildInitializerDefineProperty({\n\t NAME: state.initializerDefineProp\n\t });\n\t path.scope.getProgramParent().path.unshiftContainer('body', helper);\n\t }\n\n\t return state.initializerDefineProp;\n\t }", "function setupInitialProperties() {\n var scriptProperties = PropertiesService.getScriptProperties();\n scriptProperties.setProperty(\"TWITTER_CONSUMER_KEY\", TWITTER_CONSUMER_KEY);\n scriptProperties.setProperty(\"TWITTER_CONSUMER_SECRET\", TWITTER_CONSUMER_SECRET);\n scriptProperties.setProperty(\"TWITTER_ACCESS_TOKEN\", TWITTER_ACCESS_TOKEN);\n scriptProperties.setProperty(\"TWITTER_ACCESS_SECRET\", TWITTER_ACCESS_SECRET);\n scriptProperties.setProperty(\"MAX_TWITTER_ID\", 0);\n}", "function initializeDimensions(properties) {\n var minX = properties.minX,\n minY = properties.minY,\n maxX = properties.maxX,\n maxY = properties.maxY;\n\n properties.minX = minX != null ? minX : 0;\n properties.maxX = maxX != null ? maxX : properties.width;\n properties.minY = minY != null ? minY : 0;\n properties.maxY = maxY != null ? maxY : properties.height;\n }", "properties(properties) {\n if (arguments.length === 0) {\n // Return existing component properties.\n const properties = {};\n for (const component of this.components())\n properties[component.type()] = component.properties();\n return properties;\n } else {\n // Set component properties.\n for (const type in properties) {\n const component = this.component(type).create();\n component.properties(properties[type]);\n }\n return this;\n }\n }", "addProperties(assigns) {\r\n\t\t\t\t\tvar assign, base, name, prototype, result, value, variable;\r\n\t\t\t\t\tresult = (function() {\r\n\t\t\t\t\t\tvar j, len1, results1;\r\n\t\t\t\t\t\tresults1 = [];\r\n\t\t\t\t\t\tfor (j = 0, len1 = assigns.length; j < len1; j++) {\r\n\t\t\t\t\t\t\tassign = assigns[j];\r\n\t\t\t\t\t\t\tvariable = assign.variable;\r\n\t\t\t\t\t\t\tbase = variable != null ? variable.base : void 0;\r\n\t\t\t\t\t\t\tvalue = assign.value;\r\n\t\t\t\t\t\t\tdelete assign.context;\r\n\t\t\t\t\t\t\tif (base.value === 'constructor') {\r\n\t\t\t\t\t\t\t\tif (value instanceof Code) {\r\n\t\t\t\t\t\t\t\t\tbase.error('constructors must be defined at the top level of a class body');\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t// The class scope is not available yet, so return the assignment to update later\r\n\t\t\t\t\t\t\t\tassign = this.externalCtor = new Assign(new Value(), value);\r\n\t\t\t\t\t\t\t} else if (!assign.variable.this) {\r\n\t\t\t\t\t\t\t\tname = base instanceof ComputedPropertyName ? new Index(base.value) : new (base.shouldCache() ? Index : Access)(base);\r\n\t\t\t\t\t\t\t\tprototype = new Access(new PropertyName('prototype'));\r\n\t\t\t\t\t\t\t\tvariable = new Value(new ThisLiteral(), [prototype, name]);\r\n\t\t\t\t\t\t\t\tassign.variable = variable;\r\n\t\t\t\t\t\t\t} else if (assign.value instanceof Code) {\r\n\t\t\t\t\t\t\t\tassign.value.isStatic = true;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tresults1.push(assign);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn results1;\r\n\t\t\t\t\t}).call(this);\r\n\t\t\t\t\treturn compact(result);\r\n\t\t\t\t}", "function initializeModuleProperties () {\n\t\t\t\t\tvar moduleConf;\n\t\t\t\t\t// Create the config properties if they don't exist yet\n\t\t\t\t\t$scope.module[$scope.configPropertyName] = $scope.module[$scope.configPropertyName] || {};\n\t\t\t\t\t// Create a shorthand\n\t\t\t\t\tmoduleConf = $scope.module[$scope.configPropertyName];\n\t\t\t\t\t// Check all properties and give a default value if undefined\n\t\t\t\t\tmoduleConf.xPos = moduleConf.xPos || 1;\n\t\t\t\t\tmoduleConf.yPos = moduleConf.yPos || 1;\n\t\t\t\t\tmoduleConf.xUnits = moduleConf.xUnits || 1;\n\t\t\t\t\tmoduleConf.yUnits = moduleConf.yUnits || 1;\n\t\t\t\t\tmoduleConf.xMinSize = moduleConf.xMinSize || 1;\n\t\t\t\t\tmoduleConf.yMinSize = moduleConf.yMinSize || 1;\n\t\t\t\t\tmoduleConf.dragging = moduleConf.dragging || false;\n\t\t\t\t\tmoduleConf.resizing = moduleConf.resizing || false;\n\t\t\t\t}", "_applyInstanceProperties() {\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n // tslint:disable-next-line:no-any\n this._instanceProperties.forEach((v, p) => this[p] = v);\n this._instanceProperties = undefined;\n }", "_applyInstanceProperties() {\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n // tslint:disable-next-line:no-any\n this._instanceProperties.forEach((v, p) => this[p] = v);\n this._instanceProperties = undefined;\n }", "_applyInstanceProperties() {\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n // tslint:disable-next-line:no-any\n this._instanceProperties.forEach((v, p) => this[p] = v);\n this._instanceProperties = undefined;\n }", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n }", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n }", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n }", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n }", "setProperties(properties) {\n Object.assign(this, properties);\n }", "setProperties(properties) {\n Object.assign(this, properties);\n }", "function createProperties(el) {\n\tvar properties = {};\n\n\tif (!el.hasAttributes()) {\n\t\treturn properties;\n\t}\n\n\tvar ns;\n\tif (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) {\n\t\tns = el.namespaceURI;\n\t}\n\n\tvar attr;\n\tfor (var i = 0; i < el.attributes.length; i++) {\n\t\t// use built in css style parsing\n\t\tif(el.attributes[i].name == 'style'){\n\t\t\tattr = createStyleProperty(el);\n\t\t}\n\t\telse if (ns) {\n\t\t\tattr = createPropertyNS(el.attributes[i]);\n\t\t} else {\n\t\t\tattr = createProperty(el.attributes[i]);\n\t\t}\n\n\t\t// special case, namespaced attribute, use properties.foobar\n\t\tif (attr.ns) {\n\t\t\tproperties[attr.name] = {\n\t\t\t\tnamespace: attr.ns\n\t\t\t\t, value: attr.value\n\t\t\t};\n\n\t\t// special case, use properties.attributes.foobar\n\t\t} else if (attr.isAttr) {\n\t\t\t// init attributes object only when necessary\n\t\t\tif (!properties.attributes) {\n\t\t\t\tproperties.attributes = {}\n\t\t\t}\n\t\t\tproperties.attributes[attr.name] = attr.value;\n\n\t\t// default case, use properties.foobar\n\t\t} else {\n\t\t\tproperties[attr.name] = attr.value;\n\t\t}\n\t};\n\n\treturn properties;\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function _default(properties) {\n // Normalize\n for (var i = 0; i < properties.length; i++) {\n if (!properties[i][1]) {\n properties[i][1] = properties[i][0];\n }\n }\n\n return function (model, excludes, includes) {\n var style = {};\n\n for (var i = 0; i < properties.length; i++) {\n var propName = properties[i][1];\n\n if (excludes && zrUtil.indexOf(excludes, propName) >= 0 || includes && zrUtil.indexOf(includes, propName) < 0) {\n continue;\n }\n\n var val = model.getShallow(propName);\n\n if (val != null) {\n style[properties[i][0]] = val;\n }\n }\n\n return style;\n };\n}", "function Properties (prop) {\n this.prop = prop;\n this.addProp = function (name, value) {\n this[name] = value;\n }\n}", "constructor() {\n\t this.properties = [];\n\t }", "function addProperties() {\n function addProps(o1,o2) {\n o1 = typeof o1 === 'object' ? o1 : {};\n o2 = typeof o2 === 'object' ? o2 : {};\n Object.keys(o2).forEach(function(k) {\n o1[k] = o2[k];\n });\n return o1;\n }\n var args = Array.prototype.slice.call(arguments);\n var newObject = {};\n args.forEach(function(a) {\n addProps(newObject, a);\n });\n return newObject;\n }", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillControlProperties(oControl) {\n\t\tvar mProperties = oControl.getMetadata().getAllProperties(),\n\t\t\tsControlName = oControl.getMetadata().getName();\n\n\t\tfor (var sPropertyName in mProperties) {\n\t\t\tvar oProperty = mProperties[sPropertyName];\n\t\t\ttry {\n\t\t\t\tif (!shouldIgnoreProperty(sControlName, sPropertyName)) {\n\t\t\t\t\tvar vValueToSet = \"text\"; // just try a string as default, with some frequently happening exceptions\n\n\t\t\t\t\t/*\n\t\t\t\t\t * This block increases the successfully set properties from 27% to 78%, but leads to no new memory leak detection\n\t\t\t\t\t * and leads to issues in several controls. So don't do it.\n\n\t\t\t\t\tif (oProperty.type === \"boolean\") {\n\t\t\t\t\t\tvValueToSet = true;\n\t\t\t\t\t} else if (oProperty.type === \"int\") {\n\t\t\t\t\t\tvValueToSet = 100;\n\t\t\t\t\t}\n\t\t\t\t\t */\n\n\t\t\t\t\toControl[oProperty._sMutator](vValueToSet);\n\t\t\t\t\tiSuccessfullyFilledProperties++;\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// type check error, ignore\n\t\t\t\taFailuresWhenFillingProperties.push(oProperty.type + \" (\" + sControlName + \".\" + sPropertyName + \")\");\n\t\t\t}\n\t\t}\n\t\toControl.setTooltip(\"test\"); // seems not to be a property...\n\t}", "function initializeState(property) {\n var result;\n // Look through all selections for this property;\n // values should all match by the time we perform\n // this lookup anyway.\n self.selection.forEach(function (selected) {\n result = (selected[property] !== undefined) ?\n self.lookupState(property, selected) :\n result;\n });\n return result;\n }", "static getNewProperties() {\n return {};\n }", "function define_property(obj, propertyname, func){\n\t\tif( Object.defineProperty ){\n\t\t\tObject.defineProperty( obj, propertyname, { get: func });\n\t\t} else {\n\t\t\tobj.__defineGetter__(propertyname, func);\n\t\t}\n\t}", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function spec(node, body, objId, initProps, file) {\n // add a simple assignment for all Symbol member expressions due to symbol polyfill limitations\n // otherwise use Object.defineProperty\n\n var _arr2 = node.properties;\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var prop = _arr2[_i2];\n // this wont work with Object.defineProperty\n if (t.isLiteral(t.toComputedKey(prop), { value: \"__proto__\" })) {\n initProps.push(prop);\n continue;\n }\n\n var key = prop.key;\n if (t.isIdentifier(key) && !prop.computed) {\n key = t.literal(key.name);\n }\n\n var bodyNode = t.callExpression(file.addHelper(\"define-property\"), [objId, key, prop.value]);\n\n body.push(t.expressionStatement(bodyNode));\n }\n\n // only one node and it's a Object.defineProperty that returns the object\n\n if (body.length === 1) {\n var first = body[0].expression;\n\n if (t.isCallExpression(first)) {\n first.arguments[0] = t.objectExpression(initProps);\n return first;\n }\n }\n}", "function setup_property(obj, prop, opts, failsafe) {\n\ttry {\n\t\t_setup_property(obj, prop, opts);\n\t} catch (err) {\n\t\tobj[prop] = failsafe;\n\t}\n}", "function _init (parametri) {\n\n for (let parametro in parametri) {\n if (parametri.hasOwnProperty(parametro)) {\n keystone.set(parametro, parametri[parametro]);\n }\n }\n\n}", "init(properties) {\n // basic properties\n this.setOrigin(0.5, 1); // center bottom\n this.setDepth(10);\n\n // physics properties\n this.setCollideWorldBounds(true);\n\n // import custom properties from Tiled\n this.preIngestData();\n this.ingestData(properties);\n this.postIngestData();\n }", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "function fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}", "loadOwnProperties(){\r\n \t\t\r\n\t}", "function setInitValues(facet, obj) {\n\tif (hierarchylevelnameFacet == facet) hierarchyInits = obj;\n\telse if (scenarioFacet == facet) scenarioInits = obj;\n\telse if (datatypeFacet == facet) datatypeInits = obj;\n\telse if (organizationFacet == facet) organizationInits = obj;\n\telse if (topicFacet == facet) topicInits = obj;\n}", "function evaluatePropertyAssignment({ environment, node, evaluate, statementTraversalStack }, parent) {\n const initializer = evaluate.expression(node.initializer, environment, statementTraversalStack);\n // Compute the property name\n const propertyNameResult = evaluate.nodeWithValue(node.name, environment, statementTraversalStack);\n parent[propertyNameResult] = initializer;\n}", "static initialize(obj, name, expression) { \n obj['name'] = name;\n obj['expression'] = expression;\n }", "function makePropertyValidator(props) {\n return function (object) {\n var _hasProperty = function(o, prop, type) { return o != null && (prop in o) && typeof (o[prop]) === type; };\n return !props.some(function (prop) { return !_hasProperty(object, prop.name, prop.type); });\n };\n}", "_applyInstanceProperties(){// Use forEach so this works even if for/of loops are compiled to for loops\n// expecting arrays\n// tslint:disable-next-line:no-any\nthis._instanceProperties.forEach((v,p)=>this[p]=v);this._instanceProperties=void 0}", "propertiesToObject(props) {\n const obj = {}\n props.forEach((elem) => {\n const key = elem.name;\n\n let value;\n if (elem.value) {\n // Some properties (e.g. with getters/setters) don't have a value.\n switch (elem.value.type) {\n case \"undefined\": value = undefined; break;\n default: value = elem.value.value; break;\n }\n }\n\n obj[key] = value;\n })\n\n return obj;\n }", "extendDefaults(source, properties) {\n var property;\n for (property in properties) {\n if (properties.hasOwnProperty(property)) {\n source[property] = properties[property];\n }\n }\n return source;\n }", "applyRuntimeInitializers() {\n const { mapValues } = this.lodash\n const matches = this.runtimeInitializers\n\n Helper.attachAll(this, this.helperOptions)\n\n mapValues(matches, (fn, id) => {\n try {\n this.use(fn.bind(this), INITIALIZING)\n } catch (error) {\n this.error(`Error while applying initializer ${id}`, { error })\n }\n })\n\n Helper.attachAll(this, this.helperOptions)\n\n return this\n }" ]
[ "0.64612824", "0.5962213", "0.5862964", "0.57617545", "0.57617545", "0.562477", "0.561436", "0.5610648", "0.5585682", "0.5566819", "0.55169815", "0.5485854", "0.5429811", "0.5415591", "0.54136515", "0.5411232", "0.5405818", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5343281", "0.5334395", "0.5307331", "0.52873886", "0.52873886", "0.5285147", "0.5276823", "0.52122384", "0.518239", "0.5164807", "0.51243776", "0.51243776", "0.5120246", "0.5102166", "0.5099728", "0.5066777", "0.5047375", "0.5040904", "0.5040904", "0.5040904", "0.5036401", "0.5033351", "0.5033351", "0.5033351", "0.5022414", "0.5022414", "0.50049984", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.49979597", "0.4985727", "0.4981492", "0.49730283", "0.4965014", "0.49494243", "0.4947786", "0.49439767", "0.4931771", "0.49316022", "0.49316022", "0.49316022", "0.49316022", "0.49255678", "0.49166927", "0.49128312", "0.4907626", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49070922", "0.49021998", "0.48938212", "0.48541012", "0.48537493", "0.48447987", "0.48441267", "0.48398992", "0.48337683", "0.4828026" ]
0.0
-1
Since this function is getting called async from many different points, ideally it should have a lock to avoid race conditions (and possibly corruption). However, apparently JS is threadless and JS engine takes care of this issue under the hood. So we are safe.
function vault_write(key, value) { if (value !== undefined) { if (key && key == "guid") { //my_log("APPU DEBUG: vault_write(), key: " + key + ", " + value); localStorage[key] = JSON.stringify(value); } else if (key !== undefined) { var write_key = pii_vault.guid + ":" + key; //my_log("APPU DEBUG: vault_write(), key: " + write_key + ", " + value); localStorage[write_key] = JSON.stringify(value); if (key.split(':').length == 2 && key.split(':')[0] === 'current_report') { //This is so that if the reports tab queries for current_report, //we can send it an updated one. There is no need to flush this to disk. pii_vault.current_report.report_updated = true; } } } else { my_log("Appu Error: vault_write(), Value is empty for key: " + key, new Error); print_appu_error("Appu Error: vault_write(), Value is empty for key: " + key); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Synchronized () {}", "function Synchronized () {}", "function Synchronized () {}", "static async method(){}", "async update_() {\n if (this.lockingUpdate_) {\n if (this.pendingUpdate_) {\n return;\n }\n this.pendingUpdate_ = (async () => {\n while (this.lockingUpdate_) {\n try {\n await this.lockingUpdate_;\n } catch (e) {\n // Ignore exception from waiting for existing update.\n }\n }\n this.lockingUpdate_ = this.pendingUpdate_;\n this.pendingUpdate_ = null;\n await this.doUpdate_();\n this.lockingUpdate_ = null;\n })();\n } else {\n this.lockingUpdate_ = (async () => {\n await this.doUpdate_();\n this.lockingUpdate_ = null;\n })();\n }\n }", "async function asyncFn() {\n return value;\n }", "async function asyncFn() {\n return value;\n }", "async function asyncFn(){\n\n return 1;\n}", "async function foo() {\n return 1\n}", "async function func() {\n return 1;\n}", "function AtomicInvoke() {\r\n}", "async method(){}", "async function asyncFunction(arg) {\r\n return arg;\r\n}", "function doWorkAsyncFirst(){\n setTimeout(()=>{\n let sum=0;\n for (let index = 0; index < 1000000000; index++) {\n sum+=index;\n }\n console.log('Sum: ',sum);\n return sum;\n },10);\n}", "function callSyncFunction() {\n var deferred = Q.defer();\n notDeferred();\n return deferred.promise;\n}", "async run() {\n }", "async function f() {\n return 1;\n }", "async function f() {\n return 1;\n }", "if (/*ret DOES NOT contain any hint on the result (lock is cracked)*/) {\n break; //Break loop (since further attempts are not neccessary)\n }", "async function f(){\n return something\n}", "async function asyncAwait() {\n var aVal = null;\n try {\n const first = await promiseFunc(aVal);\n console.log(first);\n\n const second = await promiseFunc(first);\n console.log(second);\n\n const third = await promiseFunc(second);\n console.log(third);\n\n aVal = third;\n console.log(aVal);\n\n } catch (e) {\n console(\"Error\");\n }\n}", "async function concurrent() {\n const firstPromise = firstAsyncThing();\n const secondPromise = secondAsyncThing();\n console.log(await firstPromise, await secondPromise);\n }", "async function StoredDataGetter(){\n\n return await updated_data;\n\n}", "async function refreshCache() {\n chrome.storage.sync.get(['syncCache'], function (x) {\n if (x.syncCache) {\n console.log('inside if statement in sync.get', x.syncCache);\n siteCache = x.syncCache;\n }\n });\n}", "function sync() {\n \n}", "function asyncInIE (f) {\n f();\n }", "function setAsync1(x) {\n return setAsync(x, 1);\n}", "async function test() {}", "function ARandomAsyncFunction(toIncrease) {\n setTimeout(() => {\n toIncrease.value++\n /*\n (3)\n When we see this value it should be the value of result,\n which is defined on line 10, but moduified. This is to prove\n that line 27 did actually do something.\n */\n console.log(`INSIDE: ARandomAsyncFunction and result at this point is: ${result.value}`)\n }, 500)\n\n}", "async function f() {\n return 1;\n}", "async function updateContentID() {\n // const start = performance.now();\n try {\n const newContentID = await getContentIDImpl();\n // console.log('updateContentID triggered', newContentID, currentContentID);\n if (!currentContentID || (newContentID.domain != currentContentID.domain || newContentID.userName != currentContentID.userName || newContentID.userID != currentContentID.userID || newContentID.platform != currentContentID.platform)) {\n currentContentID = newContentID;\n setTimeout(callContentIDCallbacks, 0); // Call after this function chain returns, hopefully.\n // console.log('updateContentID:', currentContentID);\n }\n } catch (err) {\n console.warn('updateContentID Error:', err);\n }\n\n // const took = performance.now() - start;\n // console.log('updateContentID took', took);\n}", "function wrap_sync (fn) {\n return function (params) {\n var val = fn(params)\n if (val && !isPromise(val)) throw val\n return val\n }\n}", "async function asyncTest() {\n await document.documentElement.requestFullscreen();\n const preType = screen.orientation.type;\n const isPortrait = preType.includes(\"portrait\");\n const newType = `${isPortrait ? \"landscape\" : \"portrait\"}-primary`;\n const p = screen.orientation.lock(newType);\n console.log(`${p}: what is p`);\n console.log(\n `${\n screen.orientation.type\n } + ${preType}: should be same and must not change orientation until next spin of event loop`\n );\n await p;\n console.log(\n `${\n screen.orientation.type\n } + ${newType} lock should be async, both should be the same and different to previous`\n );\n}", "lock() {\n this._locked = true;\n }", "function thunk2() {\n let now = Date.now();\n // This should be the current time in ms\n\n let value = 0;\n\n // Something will take 2 seconds to complete\n // This structure is technically blocking\n // This would be refactored to be asynchronous\n while(Date.now() <= now + 2000) {\n value = Date.now(); // Making up some random data\n }\n // Let's pretend we got some data back in response\n\n return subtract(Date.now(), value);\n}", "function js(t, e) {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_3__[\"__awaiter\"])(this, void 0, void 0, (function() {\n var n, r, i, o, s;\n return Object(tslib__WEBPACK_IMPORTED_MODULE_3__[\"__generator\"])(this, (function(u) {\n switch (u.label) {\n case 0:\n Wo((n = C(t)).remoteStore) || _(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\"), \n u.label = 1;\n\n case 1:\n return u.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , function(t) {\n var e = C(t);\n return e.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (function(t) {\n return e.Tn.getHighestUnacknowledgedBatchId(t);\n }));\n }(n.localStore) ];\n\n case 2:\n return -1 === (r = u.sent()) ? [ 2 /*return*/ , void e.resolve() ] : ((i = n.Bo.get(r) || []).push(e), \n n.Bo.set(r, i), [ 3 /*break*/ , 4 ]);\n\n case 3:\n return o = u.sent(), s = fs(o, \"Initialization of waitForPendingWrites() operation failed\"), \n e.reject(s), [ 3 /*break*/ , 4 ];\n\n case 4:\n return [ 2 /*return*/ ];\n }\n }));\n }));\n}", "async function asyncWrapperFunction() {\r\n await htmlRouting();\r\n await videoRouting();\r\n const data = await dataProcessing();\r\n const nodes = await nodesGetting();\r\n dynamic(data,nodes);\r\n display(data,nodes);\r\n}", "function doStuffSync() {\n return Promise.resolve('foo')\n // return Promise.reject('nok')\n}", "function someSyncApiCall(callback) {\n process.nextTick(callback);\n}", "function SYNC() {}", "function SYNC() {}", "function SYNC() {}", "function SYNC() {}", "async function foo(a) {\n assert.sameValue(this, a)\n}", "if (/*ret DOES NOT contain any hint on any of the arguments (lock is cracked)*/) {\n break; //Break loop (since further attempts are not neccessary)\n }", "async function MyAsyncFn () {}", "async function claimLock() { // () => Promise of /*release*/ () => ()\n const vid_DEBUG = vidGen_DEBUG();\n\n const t0 = performance.now();\n\n await (queue.length ? ( // Lock is already held by this env, or being waited upon; append to the pending queue.\n new Promise(resolve => {\n queue.push(resolve);\n\n }).then( _ => { // awakened; things to do before the operation\n assert(!imInside_DEBUG); imInside_DEBUG = true;\n })\n ) : ( // Queue is empty; claim the global lock\n queue.push(true), // marker that we are already claiming the lock (must be set before first 'await')\n\n assert(!imInside_DEBUG), imInside_DEBUG = true,\n\n // Profile the number of local locks, and the durations they waited + operations executed.\n waits_PROF = [],\n opsTook_PROF = [],\n\n claimGlobalLock() // IDE note: \"missing await\" is false warning; ignore\n .then( _ => { // DEBUG\n assert(imInside_DEBUG);\n })\n ));\n\n const dt = trunc( performance.now() - t0 );\n waits_PROF.push(dt);\n\n //console.log(now00_DEBUG(vid_DEBUG) + `Lock received after ${dt}ms`); // 246\n\n currentOpStart_PROF = performance.now();\n return release;\n\n // Proceed the queue; release the global lock if no more entries.\n //\n // Called by the locked operation, when it's done.\n //\n function release() {\n assert(queue.length);\n queue.shift();\n\n assert(imInside_DEBUG); imInside_DEBUG = false;\n\n assert(currentOpStart_PROF);\n opsTook_PROF.push( trunc(performance.now() - currentOpStart_PROF) );\n currentOpStart_PROF = undefined;\n\n if (queue.length) { // more to go\n const resolveNext = queue[0]; // keep in the queue to show we have the global lock\n resolveNext();\n } else {\n /*await*/ releaseGlobalLock(); // free-running tail\n\n // Report the profiling about this larger locking\n //\n const [waitMedian, waitMax] = getMedMax(waits_PROF);\n const [opMedian, opMax] = getMedMax(opsTook_PROF);\n\n // PROFILING analysis:\n //\n // - The FIRST global lock takes ~250ms; subsequent within the same run 25..40ms.\n // - Local locks are fast (<10ms); their waits happen in parallel with the global locking and thus that time does\n // not count.\n // - Operations are 1..25ms, each\n //\n if (false) console.info(\"Locking profiles:\", {\n waits: waits_PROF, // 246, 253, 254 (getting global lock is the decisive one; others wait alongside it)\n waitMedian, // 253\n waitMax, // 254\n opsTook: opsTook_PROF, // 1, 2, 24 ms\n opMedian, // 2\n opMax // 24\n })\n }\n }\n}", "sync(...args) {\n return sync.call(this, ...args);\n }", "async begin() {\n return;\n }", "async function simpleReturn() {\n return 1;\n}", "async function bar(){\r\n\tconsole.log(\"bar\")\r\n}", "async getApiLock() {\n let max_retry = 5;\n while (this.alreadyServing && max_retry > 0) {\n await this.pause(500);\n max_retry--;\n }\n console.log(\"Given lock\");\n this.alreadyServing = true;\n return true;\n }", "async function notAsync(){\n console.time('timer')\n\n console.log(\"Im not async\");\n\n var someInfo=asyncFn()\n someInfo.then(response => {\n console.log(response);\n \n if(response == 1){\n console.log (\"IT WORKS 😛\");\n console.timeEnd('timer');\n }\n });\n \n /*\n var someInfo = await asyncFn();\n if(someInfo == 1)\n console.log (\"IT ALSO WORKS! 😛 😛 😛 😛\");\n */\n \n \n return 0;\n}", "async function getDataAsync() {\n try {\n let data = getSomeData();\n return data;\n } catch (e) {\n throw e;\n }\n}", "function writeLock(fun) {\n\t return argsarray(function (args) {\n\t db._queue.push({\n\t fun: fun,\n\t args: args,\n\t type: 'write'\n\t });\n\n\t if (db._queue.length === 1) {\n\t nextTick$1(executeNext);\n\t }\n\t });\n\t }", "async onLoad() {}", "_map(func) {\n let ret = new AsyncRef(func(this._value));\n let thiz = this;\n (async function() {\n for await (let x of thiz.observeFuture()) {\n ret.value = func(x);\n }\n })();\n return ret;\n }", "function asyncExecute(fn) {\n if ((typeof document !== \"undefined\" && document !== null) && (document.hidden || document.msHidden) && nonAsyncCount++ < 10000) {\n fn();\n }\n else {\n nonAsyncCount = 0;\n setImmediate(fn);\n }\n }", "setAsyncContextIdPromise(contextId, promise) {\n const promiseId = getPromiseId(promise);\n\n // if (!promiseId) {\n\n // }\n\n const context = executionContextCollection.getById(contextId);\n if (context) {\n this.setAsyncContextPromise(context, promiseId);\n }\n\n // old version\n // TODO: remove the following part → this does not work if async function has no await!\n const lastAwaitData = this.lastAwaitByRealContext.get(contextId);\n\n // eslint-disable-next-line max-len\n // this.logger.warn(`[traceCallPromiseResult] trace=${traceCollection.makeTraceInfo(trace.traceId)}, lastContextId=${executionContextCollection.getLastRealContext(this._runtime.getLastPoppedContextId())?.contextId}`, calledContext?.contextId,\n // lastAwaitData);\n\n if (lastAwaitData) {\n lastAwaitData.asyncFunctionPromiseId = promiseId;\n\n // NOTE: the function has already returned -> the first `preAwait` was already executed (but not sent yet)\n // [edit-after-send]\n const lastUpdate = asyncEventUpdateCollection.getById(lastAwaitData.updateId);\n lastUpdate.promiseId = promiseId;\n }\n return lastAwaitData;\n }", "setSync(){\n this.async = false;\n }", "function readLock(fun) {\n\t return argsarray(function (args) {\n\t db._queue.push({\n\t fun: fun,\n\t args: args,\n\t type: 'read'\n\t });\n\n\t if (db._queue.length === 1) {\n\t nextTick$1(executeNext);\n\t }\n\t });\n\t }", "function h$runSync(a, cont) {\n h$runInitStatic();\n var c = h$return;\n var t = new h$Thread();\n\n\n\n t.isSynchronous = true;\n t.continueAsync = cont;\n var ct = h$currentThread;\n var csp = h$sp;\n var cr1 = h$r1; // do we need to save more than this?\n t.stack[4] = h$ap_1_0;\n t.stack[5] = a;\n t.stack[6] = h$return;\n t.sp = 6;\n t.status = h$threadRunning;\n var excep = null;\n var blockedOn = null;\n h$currentThread = t;\n h$stack = t.stack;\n h$sp = t.sp;\n\n\n\n try {\n while(true) {\n ;\n while(c !== h$reschedule) {\n\n\n\n\n\n\n c = c();\n\n c = c();\n c = c();\n c = c();\n c = c();\n c = c();\n c = c();\n c = c();\n c = c();\n c = c();\n\n }\n ;\n if(t.status === h$threadFinished) {\n ;\n break;\n } else {\n ;\n }\n var b = t.blockedOn;\n if(typeof b === 'object' && b && b.f && b.f.t === h$BLACKHOLE_CLOSURE) {\n var bhThread = b.d1;\n if(bhThread === ct || bhThread === t) { // hit a blackhole from running thread or ourselves\n ;\n c = h$throw(h$baseZCControlziExceptionziBasezinonTermination, false);\n } else { // blackhole from other thread, steal it if thread is running\n // switch to that thread\n if(h$runBlackholeThreadSync(b)) {\n ;\n c = h$stack[h$sp];\n } else {\n ;\n blockedOn = b;\n throw false;\n }\n }\n } else {\n ;\n blockedOn = b;\n throw false;\n }\n }\n } catch(e) { excep = e; }\n if(ct !== null) {\n h$currentThread = ct;\n h$stack = ct.stack;\n h$sp = csp;\n h$r1 = cr1;\n } else {\n h$currentThread = null;\n h$stack = null;\n }\n\n\n\n if(t.status !== h$threadFinished && !cont) {\n h$removeThreadBlock(t);\n h$finishThread(t);\n }\n if(excep) {\n throw excep;\n }\n return blockedOn;\n ;\n}", "async function fn(){ //This is the newer way of doing an async function\n return 'hello';\n}", "function handleAddTime() {\n console.log('async returnnnn');\n currentTime = 0;\n }", "get locked()\n\t{\n\t\treturn true;\n\t}", "evalCode() {\n throw new errors_1.QuickJSNotImplemented(\"QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead\");\n }", "async function getDataAndDoSomethingAsync() {\n try {\n let data = await getDataAsync();\n doSomethingHere(data);\n } catch (error) {\n throw error;\n }\n}", "function syncIt() {\n return getIndexedDB()\n .then(sendToServer)\n .catch(function(err) {\n return err;\n })\n}", "async function myFn() {\n // wait\n}", "async function WrapperForAsyncFunc() {\n const result = await AsyncFunction();\n console.log(result);\n}", "do(func) {\n return async && data instanceof Promise\n ? using(data.then(func), async)\n : using(func(data), async)\n }", "limitConcurrency() {\n return true;\n }", "static race(iterable) {\n return CustomPromise.handleArray(iterable, { resolveAny:1, rejectAny:1 });\n }", "async function noAwait() {\n let value = myPromise();\n console.log(value);\n}", "async function scenario1() { // eslint-disable-line no-unused-vars\n const nums = [1, 2, 3, 4, 5];\n \n \n async function processArray(array) {\n const results = [];\n array.forEach(async item => {\n const processedItem = await asyncOperation(item); // this does not block\n results.push(processedItem);\n });\n return results;\n }\n \n async function asyncOperation(item) {\n return new Promise(resolve => {\n setTimeout(() => {\n console.log(`Asynchronously processing item ${ item }`);\n resolve(item + 1);\n }, 1000);\n });\n }\n \n console.log(`before processing = ${ nums }`);\n const processedNums = await processArray(nums); // This does not block\n console.log(`after processing = ${ processedNums }`);\n console.log(`===========================\\n`);\n}", "async function executeHardAsync() {\n const r1 = await fetchUrlData(apis[0]);\n const r2 = await fetchUrlData(apis[1]);\n}", "async onTick() {}", "function onetime(){if(called)return value;called=1;value=fn.apply(this,arguments);fn=null;return value}//", "function fetchSync() {\n return { hello: \"world\" };\n }", "async function claimGlobalLock() { // () => Promise of ()\n assert(!weAreLocked_ASSERT);\n\n let retries=0;\n while(true) {\n const gotIt = await tryCreate(lockDoc,{});\n if (gotIt) {\n weAreLocked_ASSERT = true;\n return;\n\n } else {\n if (retries && retries %10 === 0) {\n console.debug(now00_DEBUG() + `Still waiting after ${retries} retries...`);\n }\n\n retries = retries + 1;\n\n // Wait until the document is seen to have been removed. Then, try again.\n //\n await waitUntilDeleted(lockDoc);\n }\n }\n}", "adoptedCallback() { }", "async function asyncCall() {\n try {\n const result = await getListActivity();\n console.log(result);\n return result;\n // the next line will fail\n //const result2 = await apiFunctionWrapper(\"bad query\");\n //console.log(result2);\n } catch(error) {\n console.error(\"ERROR:\" + error);\n }\n }", "async function executeAsyncTask() {\n const valueA = await functionA()\n const valueB = await functionB(valueA)\n return function3(valueA, valueB)\n}", "async function myFunc() {\n return 'Hello';\n}", "async function callback(name, fn) {\n const cachePath = files.joinPath(files.documentsDirectory(), name + \"-cache\")\n const cacheExists = files.fileExists(cachePath)\n\n if (cacheExists) {\n // async write data\n fn().then(data => {\n files.writeString(cachePath, JSON.stringify(data))\n })\n const cache = files.readString(cachePath)\n const resultRaw = JSON.parse(cache)\n return resultRaw\n }\n\n // sync read data\n const result = await fn()\n files.writeString(cachePath, JSON.stringify(result))\n return result\n}", "lock() {\n const that = this;\n\n that.locked = true;\n }", "static LoadFromMemoryAsync() {}", "async function callForTroubleDontCatchIt() {\n return await callForTrouble()\n}", "function _handleAsyncCall (cacheContent, cacheName, argsArray) {\n var _callback = argsArray.pop();\n\n if(cacheContent !== undefined) {\n _callback.apply(client, cacheContent);\n } else {\n //inserting our own callback\n argsArray.push(function() {\n var returnValue = [].slice.apply(arguments);\n\n cachingStrategy.set(cacheName, returnValue);\n\n _callback.apply(client, returnValue);\n });\n\n innerFunction.apply(client, argsArray);\n }\n }", "function async(f) {\n throw Error(\"Not implemented.\");\n Packages.net.appjet.ajstdlib.execution.runAsync(appjet.context, f);\n}", "cacheNatives() {\n return this.evaluateScriptOnLoad(`window.__nativePromise = Promise;\n window.__nativeError = Error;`);\n }", "function syncData() {}", "sendAsync(payload, cb) {\n log.info('ASYNC REQUEST', payload)\n const self = this\n // fixes bug with web3 1.0 where send was being routed to sendAsync\n // with an empty callback\n if (cb === undefined) {\n self.rpcEngine.handle(payload, noop)\n return self._sendSync(payload)\n } else {\n self.rpcEngine.handle(payload, cb)\n }\n }", "_get(callback, data, id) {\n let err = null; //placeholder for real calls\n //call API - for this example fake an async call with setTimeout\n setTimeout( () => {\n //set the response in the cache - cache exists across\n //multiple calls and this solves a problem with having\n //to make a state existence check in componentWillMount\n let dataToCache = data;\n if (err) {\n dataToCache = err;\n }\n cache.add(id, dataToCache);\n return callback(err, {result: dataToCache, id: id});\n }, 200);\n }", "_asyncWrapper(result) {\r\n if (typeof result === 'object' && 'then' in result) {\r\n return result;\r\n } else {\r\n return new Promise(function(resolve) {\r\n resolve(result);\r\n });\r\n }\r\n }", "lock (lockTimeMs = 10000) {\r\n this._lockedToMs = Date.now() + lockTimeMs;\r\n }", "async function waiting() {\n const firstValue = await firstAsyncThing();\n const secondValue = await secondAsyncThing();\n console.log(firstValue, secondValue);\n }", "adoptedCallback() {}", "adoptedCallback() {}", "function someAsyncApiCall(callback) {\n // callback()\n process.nextTick(callback)\n}", "dispatchAsync() {\r\n this._dispatchAsPromise(true, this, arguments);\r\n }" ]
[ "0.6491419", "0.6491419", "0.6491419", "0.5852969", "0.5718579", "0.5672407", "0.5672407", "0.55690384", "0.555606", "0.55317163", "0.5497414", "0.54947996", "0.5466264", "0.54195654", "0.5410075", "0.53771144", "0.5367348", "0.5367348", "0.53202033", "0.5318497", "0.5297434", "0.5290042", "0.5287292", "0.5284358", "0.5271768", "0.52605146", "0.52298003", "0.5225918", "0.5216559", "0.52034247", "0.51946825", "0.5191858", "0.5185058", "0.5183147", "0.5177899", "0.5158537", "0.5151107", "0.5126054", "0.51253575", "0.5120664", "0.5120664", "0.5120664", "0.5120664", "0.51135695", "0.51006275", "0.50982827", "0.50975007", "0.50779974", "0.5074772", "0.5071173", "0.50566155", "0.5054625", "0.5044235", "0.5042745", "0.50417393", "0.5016251", "0.5001536", "0.49996945", "0.49969378", "0.49947238", "0.4985301", "0.4983097", "0.49682295", "0.4967531", "0.4967258", "0.49599028", "0.49476257", "0.49416676", "0.49408102", "0.49403206", "0.49366066", "0.49360493", "0.49354583", "0.49341378", "0.49244303", "0.49145943", "0.49107474", "0.49098194", "0.48957446", "0.48945796", "0.48942336", "0.48874646", "0.48805967", "0.48785385", "0.4866775", "0.48636612", "0.4863014", "0.4855075", "0.48398745", "0.48397294", "0.48364857", "0.481974", "0.48131454", "0.48103178", "0.47847968", "0.47717685", "0.47716242", "0.47687674", "0.47687674", "0.47663355", "0.4762067" ]
0.0
-1
my_log("Here here: version: " + manifest['version']); my_log("Here here: vault_read is : " + toType(vault.vault_read)); my_log("Here here: site is : " + tld.getDomain('a.b.google.com'));
function init_environ() { //my_log("Here here: initing environ"); var pw = page_worker.Page({ contentScriptFile: [ data.url("thirdparty/voodoo1/voodoo.js"), data.url("get_environ.js") ] }); pw.port.on("got_environ", function(rc) { environ = object.extend(environ, rc); my_log("Here here: callback for pg worker, voodoo: " + JSON.stringify(environ), new Error); pw.destroy(); // BIG EXECUTION START vault_read(); vault_init(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function logSiteInfo() {\n\t\tvar siteName = $(document.body).data('site-name');\n\t\tvar siteNameStyles = 'font-family: sans-serif; font-size: 42px; font-weight: 700; color: #16b5f1; text-transform: uppercase;';\n\n\t\tvar siteDescription = $(document.body).data('site-description');\n\n\t\tconsole.log('%c%s', siteNameStyles, siteName);\n\t\tlog(siteDescription);\n log('Designed by: Nat Cheng http://natcheng.com/');\n log('Coded by: Den Isahac https://www.denisahac.xyz/');\n\t}", "function b(){var a,b=\"axe\",c=\"\";return\"undefined\"!=typeof axe&&axe._audit&&!axe._audit.application&&(b=axe._audit.application),\"undefined\"!=typeof axe&&(c=axe.version),a=b+\".\"+c}", "getLog() {\n const { runtime, message, assert, expected } = this.opts;\n\n if (\n runtime === 'inabox' ||\n message.includes('Signing service error for google')\n ) {\n return logs.ads;\n }\n\n if (assert) {\n return logs.users;\n }\n\n if (expected) {\n return logs.expected;\n }\n\n return logs.errors;\n }", "function logVBCS(){\r\n console.log(\" ------> RUNNING FROM EXTERNAL LIB <------\");\r\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 }", "function l(pvScriptName,pvFunctionName,pvMessage,pvLevel){\n\n // This function can be passed a pre-formatted log string, usually passed back from the balu-parse-server.\n // In this case, just console.log it, without the preceeding or trailing carriage returns\n if(typeof pvFunctionName === 'undefined' &&\n typeof pvMessage === 'undefined' &&\n typeof pvLevel === 'undefined') {\n console.log(pvScriptName.substring(1,pvScriptName.length));\n return '\\n' + pvScriptName.substring(1,pvScriptName.length);\n }\n\n var lvMaxAppNameLength = 22;\n var lvPadding = ' '.substring(0,lvMaxAppNameLength - gvAppName.length + 1);\n var lvLogText = '';\n\n switch(pvLevel) {\n\n case 'ERROR':\n if (gvLogErrors) {\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case 'PROCS':\n // Short for \"process\", these are the ubiquitous logs that\n // track (at the least) the start of every function, as well\n // as other key points\n // On by default\n if (gvLogProcs) {\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case 'ROUTE':\n // Similar to PROCS, but for the web server routes\n // On by default\n if (gvLogRoutes) {\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case ' INFO':\n // Additional to PROCS, these don't just track process, they\n // record information as well. Similar to DEBUG.\n // Off by default\n if (gvLogInfos){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case 'DEBUG':\n // Useful log points for debugging\n // Off by default\n if (gvLogDebugs){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case 'INITS':\n // Rather than putting PROCS in init functions (which always fire\n // and, once the app is working reliably, aren't particularly interesting)\n // Off by default\n if (gvLogInits){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case ' AJAX':\n if (gvLogAJAX){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case 'LSTNR':\n // Rather than putting PROCS in listeners (which can fire\n // continually in some scenarios), use LSTNR and keep them ...\n // Off by default\n if (gvLogLstnrs){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n case ' TEMP':\n // What it says on the tin. These should not stay in the code for long\n // On by default\n if (gvLogTemps){\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + pvLevel + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n break;\n\n default:\n lvLogText = gvAppName.substring(0,lvMaxAppNameLength) + lvPadding + '| ' + 'UNKWN' + ': ' + pvScriptName + '.' + pvFunctionName + ': ' + pvMessage;\n console.log(lvLogText);\n lvLogText = '\\n' + lvLogText;\n }\n return lvLogText; // Set to '' if logging is off for the given level.\n}", "static print() {\n console.log(\"snapClinical JS SDK Version: \" + \"1.2.15\" );\n }", "function log() {\n chrome.storage.sync.get(null, function (data) { console.log(data); });\n chrome.alarms.getAll(function (alarms) {\n var print = [];\n for (alarm in alarms) {\n date = new Date(alarms[alarm].scheduledTime);\n print.push([alarms[alarm].name, date.toLocaleDateString() + \" \" + date.toLocaleTimeString()]);\n }\n console.log(print);\n });\n}", "log_network (_url) {\n\n return this.log('network', `Fetching ${_url}`);\n }", "function a(t){\"use strict\";var n=this,i=e;n.s=t,n._c=\"s_m\",i.s_c_in||(i.s_c_il=[],i.s_c_in=0),n._il=i.s_c_il,n._in=i.s_c_in,n._il[n._in]=n,i.s_c_in++,n.version=\"1.0\";var a,r,o,s=\"pending\",c=\"resolved\",u=\"rejected\",l=\"timeout\",d=!1,f={},p=[],g=[],h=0,m=!1,v=function(){var e={};e.requiredVarList=[\"supplementalDataID\",\"timestamp\",\"dynamicVariablePrefix\",\"visitorID\",\"marketingCloudVisitorID\",\"analyticsVisitorID\",\"audienceManagerLocationHint\",\"authState\",\"fid\",\"vmk\",\"visitorMigrationKey\",\"visitorMigrationServer\",\"visitorMigrationServerSecure\",\"charSet\",\"visitorNamespace\",\"cookieDomainPeriods\",\"fpCookieDomainPeriods\",\"cookieLifetime\",\"pageName\",\"pageURL\",\"referrer\",\"contextData\",\"currencyCode\",\"lightProfileID\",\"lightStoreForSeconds\",\"lightIncrementBy\",\"retrieveLightProfiles\",\"deleteLightProfiles\",\"retrieveLightData\"],e.accountVarList=e.requiredVarList.concat([\"purchaseID\",\"variableProvider\",\"channel\",\"server\",\"pageType\",\"transactionID\",\"campaign\",\"state\",\"zip\",\"events\",\"events2\",\"products\",\"audienceManagerBlob\",\"tnt\"]),e.lightRequiredVarList=[\"timestamp\",\"charSet\",\"visitorNamespace\",\"cookieDomainPeriods\",\"cookieLifetime\",\"contextData\",\"lightProfileID\",\"lightStoreForSeconds\",\"lightIncrementBy\"],e.lightVarList=e.lightRequiredVarList.slice(0),e.accountConfigList=[\"account\",\"allAccounts\",\"debugTracking\",\"visitor\",\"visitorOptedOut\",\"trackOffline\",\"offlineLimit\",\"offlineThrottleDelay\",\"offlineFilename\",\"usePlugins\",\"doPlugins\",\"configURL\",\"visitorSampling\",\"visitorSamplingGroup\",\"linkObject\",\"clickObject\",\"linkURL\",\"linkName\",\"linkType\",\"trackDownloadLinks\",\"trackExternalLinks\",\"trackClickMap\",\"trackInlineStats\",\"linkLeaveQueryString\",\"linkTrackVars\",\"linkTrackEvents\",\"linkDownloadFileTypes\",\"linkExternalFilters\",\"linkInternalFilters\",\"useForcedLinkTracking\",\"forcedLinkTrackingTimeout\",\"trackingServer\",\"trackingServerSecure\",\"ssl\",\"abort\",\"mobile\",\"dc\",\"lightTrackVars\",\"maxDelay\",\"expectSupplementalData\",\"usePostbacks\",\"AudienceManagement\"];for(var t=0;250>=t;t++)76>t&&(e.accountVarList.push(\"prop\"+t),e.lightVarList.push(\"prop\"+t)),e.accountVarList.push(\"eVar\"+t),e.lightVarList.push(\"eVar\"+t),6>t&&e.accountVarList.push(\"hier\"+t),4>t&&e.accountVarList.push(\"list\"+t);var n=[\"pe\",\"pev1\",\"pev2\",\"pev3\",\"latitude\",\"longitude\",\"resolution\",\"colorDepth\",\"javascriptVersion\",\"javaEnabled\",\"cookiesEnabled\",\"browserWidth\",\"browserHeight\",\"connectionType\",\"homepage\",\"pageURLRest\"];return e.accountVarList=e.accountVarList.concat(n),e.requiredVarList=e.requiredVarList.concat(n),e}(),b=!1;n.newHit=!1,n.newHitVariableOverrides=null,n.hitCount=0,n.timeout=1e3,n.currentHit=null,n.backup=function(e,t,n){var i,a,r,o;for(t=t||{},i=0;2>i;i++)for(a=i>0?v.accountConfigList:v.accountVarList,r=0;r<a.length;r++)o=a[r],t[o]=e[o],n||t[o]||(t[\"!\"+o]=1);return t},n.restore=function(e,t,n){var i,a,r,o,s,c,u=!0;for(i=0;2>i;i++)for(a=i>0?v.accountConfigList:v.accountVarList,r=0;r<a.length;r++)if(o=a[r],s=e[o],s||e[\"!\"+o]){if(!n&&(\"contextData\"==o||\"retrieveLightData\"==o)&&t[o])for(c in t[o])s[c]||(s[c]=t[o][c]);t[o]=s}return u},n.createHitMeta=function(e,t){var i,a=n.s,r=[],o=[];return b&&console.log(a.account+\" - createHitMeta\"),t=t||{},i={id:e,delay:!1,restorePoint:h,status:c,promise:Promise.resolve(),backup:{s:{},sSet:{},variableOverrides:{}},values:{s:{},variableOverrides:{}},timeout:!1},r=n.replacePromises(a,i.values.s),o=n.replacePromises(t,i.values.variableOverrides),i.backup.s=n.backup(a),i.backup.sSet=n.backup(a,null,!0),i.backup.variableOverrides=t,(r&&r.length>0||o&&o.length>0)&&(i.delay=!0,i.status=s,i.promise=Promise.all([Promise.all(r),Promise.all(o)]).then(function(){i.delay=!1,i.status=c,i.timeout&&clearTimeout(i.timeout)}),n.timeout&&(i.timeout=setTimeout(function(){i.delay=!1,i.status=l,i.timeout&&clearTimeout(i.timeout),n.sendPendingHits()},n.timeout))),i},n.replacePromises=function(e,t){var n,i,a,r,o,l,d=[];t=t||{},r=function(e,t){return function(n){t[e].value=n,t[e].status=c}},o=function(e,t){return function(n){t[e].status=u,t[e].exception=n}},l=function(e,t,n){var i=e[t];i instanceof Promise?(n[t]=n[t]||{},e[t]=\"contextData\"===t||\"retrieveLightData\"===t?{}:\"\",n[t].status=s,d.push(i.then(r(t,n))[\"catch\"](o(t,n)))):\"object\"==typeof i&&null!==i&&i.promise instanceof Promise&&(n[t]=n[t]||{},e[t]=\"contextData\"===t||\"retrieveLightData\"===t?{}:\"\",i.hasOwnProperty(\"unresolved\")&&(n[t].value=i.unresolved),n[t].status=s,d.push(i.promise.then(r(t,n))[\"catch\"](o(t,n))))};for(n in e)if(e.hasOwnProperty(n))if(a=e[n],\"contextData\"===n||\"retrieveLightData\"===n)if(a instanceof Promise||\"object\"==typeof a&&null!==a&&a.promise instanceof Promise)l(e,n,t);else{t[n]={isGroup:!0};for(i in a)a.hasOwnProperty(i)&&l(a,i,t[n])}else l(e,n,t);return d},n.metaToObject=function(e){var t,i,a,r,o=(n.s,{});if(e)for(t in e)if(e.hasOwnProperty(t))if(a=e[t],\"contextData\"!==t&&\"retrieveLightData\"!==t||!a.isGroup)a.value&&a.status===c&&(o[t]=a.value);else{o[t]={};for(i in a)a.hasOwnProperty(i)&&(r=a[i],r.value&&r.status===c&&(o[t][i]=r.value))}return o},n.getMeta=function(e){return e&&p[e]?p[e]:p},n.forceReady=function(){d=!0,n.sendPendingHits()},a=t.isReadyToTrack,t.isReadyToTrack=function(){if(!n.newHit&&a()&&g&&g.length>0&&(d||p[g[0]]&&!p[g[0]].delay))return b&&console.log(t.account+\" - isReadyToTrack - true\"),!0;if(b&&(console.log(t.account+\" - isReadyToTrack - false\"),console.log(t.account+\" - isReadyToTrack - isReadyToTrack(original) - \"+a()),!a()))try{throw Error(\"Debugging Call stack\")}catch(e){console.log(t.account+\" - isReadyToTrack - \"+e.stack)}return!1},r=t.callbackWhenReadyToTrack,t.callbackWhenReadyToTrack=function(e,i,a){var o,s;return b&&console.log(t.account+\" - callbackWhenReadyToTrack\"),i!==t.track?r(e,i,a):void(n.newHit&&(o=n.hitCount++,g.push(o),s=n.createHitMeta(o,n.newHitVariableOverrides),p[o]=s,m||(m=setInterval(n.sendPendingHits,100)),s.promise.then(function(){n.sendPendingHits()})))},o=t.t,t.t=t.track=function(e,i,a){b&&console.log(t.account+\" - track\"),a||(n.newHit=!0,n.newHitVariableOverrides=e),o(e,i),a||(n.newHit=!1,n.newHitVariableOverrides=null,n.sendPendingHits())},n.sendPendingHits=function(){var e,t,i,a,r,o=n.s;for(b&&console.log(o.account+\" - sendPendingHits\");o.isReadyToTrack();){for(e=p[g[0]],n.currentHit=e,a={},r={},n.trigger(\"hitBeforeSend\",e),r.marketingCloudVisitorID=o.marketingCloudVisitorID,r.visitorOptedOut=o.visitorOptedOut,r.analyticsVisitorID=o.analyticsVisitorID,r.audienceManagerLocationHint=o.audienceManagerLocationHint,r.audienceManagerBlob=o.audienceManagerBlob,b&&console.log(o.account+\" - sendPendingHits - s.audienceManagerBlob => \"+o.audienceManagerBlob),n.restore(e.backup.s,o),t=e.restorePoint;t<g[0];t++)i=n.metaToObject(p[t].values.s),delete i.referrer,delete i.resolution,delete i.colorDepth,delete i.javascriptVersion,delete i.javaEnabled,delete i.cookiesEnabled,delete i.browserWidth,delete i.browserHeight,delete i.connectionType,delete i.homepage,n.restore(i,r);b&&console.log(o.account+\" - sendPendingHits - s.audienceManagerBlob => \"+o.audienceManagerBlob),n.restore(e.backup.sSet,r),b&&console.log(o.account+\" - sendPendingHits - s.audienceManagerBlob => \"+o.audienceManagerBlob),n.restore(n.metaToObject(e.values.s),r),b&&console.log(o.account+\" - sendPendingHits - s.audienceManagerBlob => \"+o.audienceManagerBlob),n.restore(e.backup.variableOverrides,a),n.restore(n.metaToObject(e.values.variableOverrides),a),o.track(a,r,!0),b&&console.log(o.account+\" - sendPendingHits - s.audienceManagerBlob => \"+o.audienceManagerBlob),h=g.shift(),n.trigger(\"hitAfterSend\",e),n.currentHit=null}m&&g.length<1&&(clearInterval(m),m=!1)},b&&console.log(t.account+\" - INITIAL isReadyToTrack - \"+a()),a()||r(n,function(){if(b)try{throw Error(\"Debugging Call stack\")}catch(e){console.log(t.account+\" - callbackWhenReadyToTrack - \"+e.stack)}n.sendPendingHits()},[]),n.on=function(e,t){f[e]||(f[e]=[]),f[e].push(t)},n.trigger=function(e,t){var n,i,a,r=!1;if(f[e])for(n=0,i=f[e].length;i>n;n++){a=f[e][n];try{a(t),r=!0}catch(o){}}else r=!0;return r},n._s=function(){n.trigger(\"_s\")},n._d=function(){return n.trigger(\"_d\"),0},n._g=function(){n.trigger(\"_g\")},n._t=function(){n.trigger(\"_t\")}}", "function printAuditLog() {\n console.log(\"Audit Log:\");\n for (var i = 0; i < localStorage.length; i++) {\n if (localStorage.key(i) === 'auditLog') {\n console.log(localStorage.getItem(localStorage.key(i)));\n }\n }\n }", "function logCurentCallToLocaLStorage() {\n\n}", "function log(aktlvl, msg) {\r\n\t\tlogArr[logArr.length] = msg;\r\n\t\t\r\n\t\tif (logLevels.indexOf(aktlvl) <= efConfig.log) { \r\n\t\t\tdisplayMessage(msg);\r\n\t\t}\r\n\t\tif (aktlvl == \"tiddler\"){ \r\n\t\t\tcreateTiddler(logName, {responseText:logArr.join(\"\\n\")})\r\n\t\t}\r\n\t} // function log()", "function i(t){\"use strict\";var a=this,n=e;a.s=t,a._c=\"s_m\",n.s_c_in||(n.s_c_il=[],n.s_c_in=0),a._il=n.s_c_il,a._in=n.s_c_in,a._il[a._in]=a,n.s_c_in++,a.version=\"1.0\";var i,o,r,s=\"pending\",c=\"resolved\",d=\"rejected\",l=\"timeout\",u=!1,p={},m=[],g=[],f=0,b=!1,h=function(){var e={};e.requiredVarList=[\"supplementalDataID\",\"timestamp\",\"dynamicVariablePrefix\",\"visitorID\",\"marketingCloudVisitorID\",\"analyticsVisitorID\",\"audienceManagerLocationHint\",\"authState\",\"fid\",\"vmk\",\"visitorMigrationKey\",\"visitorMigrationServer\",\"visitorMigrationServerSecure\",\"charSet\",\"visitorNamespace\",\"cookieDomainPeriods\",\"fpCookieDomainPeriods\",\"cookieLifetime\",\"pageName\",\"pageURL\",\"referrer\",\"contextData\",\"currencyCode\",\"lightProfileID\",\"lightStoreForSeconds\",\"lightIncrementBy\",\"retrieveLightProfiles\",\"deleteLightProfiles\",\"retrieveLightData\"],e.accountVarList=e.requiredVarList.concat([\"purchaseID\",\"variableProvider\",\"channel\",\"server\",\"pageType\",\"transactionID\",\"campaign\",\"state\",\"zip\",\"events\",\"events2\",\"products\",\"audienceManagerBlob\",\"tnt\"]),e.lightRequiredVarList=[\"timestamp\",\"charSet\",\"visitorNamespace\",\"cookieDomainPeriods\",\"cookieLifetime\",\"contextData\",\"lightProfileID\",\"lightStoreForSeconds\",\"lightIncrementBy\"],e.lightVarList=e.lightRequiredVarList.slice(0),e.accountConfigList=[\"account\",\"allAccounts\",\"debugTracking\",\"visitor\",\"visitorOptedOut\",\"trackOffline\",\"offlineLimit\",\"offlineThrottleDelay\",\"offlineFilename\",\"usePlugins\",\"doPlugins\",\"configURL\",\"visitorSampling\",\"visitorSamplingGroup\",\"linkObject\",\"clickObject\",\"linkURL\",\"linkName\",\"linkType\",\"trackDownloadLinks\",\"trackExternalLinks\",\"trackClickMap\",\"trackInlineStats\",\"linkLeaveQueryString\",\"linkTrackVars\",\"linkTrackEvents\",\"linkDownloadFileTypes\",\"linkExternalFilters\",\"linkInternalFilters\",\"useForcedLinkTracking\",\"forcedLinkTrackingTimeout\",\"trackingServer\",\"trackingServerSecure\",\"ssl\",\"abort\",\"mobile\",\"dc\",\"lightTrackVars\",\"maxDelay\",\"expectSupplementalData\",\"usePostbacks\",\"AudienceManagement\"];for(var t=0;250>=t;t++)76>t&&(e.accountVarList.push(\"prop\"+t),e.lightVarList.push(\"prop\"+t)),e.accountVarList.push(\"eVar\"+t),e.lightVarList.push(\"eVar\"+t),6>t&&e.accountVarList.push(\"hier\"+t),4>t&&e.accountVarList.push(\"list\"+t);var a=[\"pe\",\"pev1\",\"pev2\",\"pev3\",\"latitude\",\"longitude\",\"resolution\",\"colorDepth\",\"javascriptVersion\",\"javaEnabled\",\"cookiesEnabled\",\"browserWidth\",\"browserHeight\",\"connectionType\",\"homepage\",\"pageURLRest\"];return e.accountVarList=e.accountVarList.concat(a),e.requiredVarList=e.requiredVarList.concat(a),e}();a.newCall=!1,a.newCallVariableOverrides=null,a.hitCount=0,a.timeout=1e3,a.currentHit=null,a.backup=function(e,t,a){var n,i,o,r;for(t=t||{},n=0;2>n;n++)for(i=n>0?h.accountConfigList:h.accountVarList,o=0;o<i.length;o++)r=i[o],t[r]=e[r],a||t[r]||(t[\"!\"+r]=1);return t},a.restore=function(e,t,a){var n,i,o,r,s,c,d=!0;for(n=0;2>n;n++)for(i=n>0?h.accountConfigList:h.accountVarList,o=0;o<i.length;o++)if(r=i[o],s=e[r],s||e[\"!\"+r]){if(!a&&(\"contextData\"==r||\"retrieveLightData\"==r)&&t[r])for(c in t[r])s[c]||(s[c]=t[r][c]);t[r]=s}return d},a.createHitMeta=function(e,t){var n,i=a.s,o=[],r=[];return t=t||{},n={id:e,delay:!1,restorePoint:f,status:c,promise:Promise.resolve(),backup:{s:{},sSet:{},variableOverrides:{}},values:{s:{},variableOverrides:{}},timeout:!1},o=a.replacePromises(i,n.values.s),r=a.replacePromises(t,n.values.variableOverrides),n.backup.s=a.backup(i),n.backup.sSet=a.backup(i,null,!0),n.backup.variableOverrides=t,(o&&o.length>0||r&&r.length>0)&&(n.delay=!0,n.status=s,n.promise=Promise.all([Promise.all(o),Promise.all(r)]).then(function(){n.delay=!1,n.status=c,n.timeout&&clearTimeout(n.timeout)}),a.timeout&&(n.timeout=setTimeout(function(){n.delay=!1,n.status=l,n.timeout&&clearTimeout(n.timeout),a.sendPendingHits()},a.timeout))),n},a.replacePromises=function(e,t){var a,n,i,o,r,l,u=[];t=t||{},o=function(e,t){return function(a){t[e].value=a,t[e].status=c}},r=function(e,t){return function(a){t[e].status=d,t[e].exception=a}},l=function(e,t,a){var n=e[t];n instanceof Promise?(a[t]=a[t]||{},\"contextData\"===t||\"retrieveLightData\"===t?e[t]={}:e[t]=\"\",a[t].status=s,u.push(n.then(o(t,a))[\"catch\"](r(t,a)))):\"object\"==typeof n&&null!==n&&n.promise instanceof Promise&&(a[t]=a[t]||{},\"contextData\"===t||\"retrieveLightData\"===t?e[t]={}:e[t]=\"\",n.hasOwnProperty(\"unresolved\")&&(a[t].value=n.unresolved),a[t].status=s,u.push(n.promise.then(o(t,a))[\"catch\"](r(t,a))))};for(a in e)if(e.hasOwnProperty(a))if(i=e[a],\"contextData\"===a||\"retrieveLightData\"===a)if(i instanceof Promise||\"object\"==typeof i&&null!==i&&i.promise instanceof Promise)l(e,a,t);else{t[a]={isGroup:!0};for(n in i)i.hasOwnProperty(n)&&l(i,n,t[a])}else l(e,a,t);return u},a.metaToObject=function(e){var t,n,i,o,r=(a.s,{});if(e)for(t in e)if(e.hasOwnProperty(t))if(i=e[t],\"contextData\"!==t&&\"retrieveLightData\"!==t||!i.isGroup)i.value&&i.status===c&&(r[t]=i.value);else{r[t]={};for(n in i)i.hasOwnProperty(n)&&(o=i[n],o.value&&o.status===c&&(r[t][n]=o.value))}return r},a.getMeta=function(e){return e&&m[e]?m[e]:m},a.forceReady=function(){u=!0,a.sendPendingHits()},i=t.isReadyToTrack,t.isReadyToTrack=function(){return!!(!a.newCall&&i()&&g&&g.length>0&&(u||m[g[0]]&&!m[g[0]].delay))},o=t.callbackWhenReadyToTrack,t.callbackWhenReadyToTrack=function(e,n,i){var r,s;return n!==t.track?o(e,n,i):void(a.newCall&&(r=a.hitCount++,g.push(r),s=a.createHitMeta(r,a.newCallVariableOverrides),m[r]=s,b||(b=setInterval(a.sendPendingHits,100)),s.promise.then(function(){a.sendPendingHits()})))},r=t.t,t.t=t.track=function(e,t,n){n||(a.newCall=!0,a.newCallVariableOverrides=e),r(e,t),n||(a.newCall=!1,a.newCallVariableOverrides=null,a.sendPendingHits())},a.sendPendingHits=function(){for(var e,t,n,i,o,r=a.s;r.isReadyToTrack();){for(e=m[g[0]],a.currentHit=e,i={},o={},a.trigger(\"hitBeforeSend\",e),o.marketingCloudVisitorID=r.marketingCloudVisitorID,o.visitorOptedOut=r.visitorOptedOut,o.analyticsVisitorID=r.analyticsVisitorID,o.audienceManagerLocationHint=r.audienceManagerLocationHint,o.audienceManagerBlob=r.audienceManagerBlob,a.restore(e.backup.s,r),t=e.restorePoint;t<g[0];t++)n=a.metaToObject(m[t].values.s),delete n.referrer,delete n.resolution,delete n.colorDepth,delete n.javascriptVersion,delete n.javaEnabled,delete n.cookiesEnabled,delete n.browserWidth,delete n.browserHeight,delete n.connectionType,delete n.homepage,a.restore(n,o);a.restore(e.backup.sSet,o),a.restore(a.metaToObject(e.values.s),o),a.restore(e.backup.variableOverrides,i),a.restore(a.metaToObject(e.values.variableOverrides),i),r.track(i,o,!0),f=g.shift(),a.trigger(\"hitAfterSend\",e),a.currentHit=null}b&&g.length<1&&(clearInterval(b),b=!1)},i()||o(a,function(){a.sendPendingHits()},[]),a.on=function(e,t){p[e]||(p[e]=[]),p[e].push(t)},a.trigger=function(e,t){var a,n,i,o=!1;if(p[e])for(a=0,n=p[e].length;n>a;a++){i=p[e][a];try{i(t),o=!0}catch(e){}}else o=!0;return o},a._s=function(){a.trigger(\"_s\")},a._d=function(){return a.trigger(\"_d\"),0},a._g=function(){a.trigger(\"_g\")},a._t=function(){a.trigger(\"_t\")}}", "function log(file, resource, version, contentType, result) {\n console.log(\"OK \" + file + \" -> \" + resource + \":\" + version + \" (\" + contentType + \") \" + result.join(\" \"));\n }", "function checkLogs(){\n\n}", "function foo(){\n lib.log( \"hello world!\" );\n}", "debugLog() {\n\t\t\tthis.get().then((data) => {\n\t\t\t\tlet text = JSON.stringify(data, null, 2);\n\t\t\t\t// Hide 'token' and 'sessionID' values if available\n\t\t\t\ttext = Util.hideStringInText(data.token, text);\n\t\t\t\ttext = Util.hideStringInText(data.sessionID, text);\n\n\t\t\t\tconsole.info(`chrome.storage.${this.namespace} = ${text}`);\n\t\t\t});\n\t\t}", "checkManifest(e){return e.icons&&e.icons[0]?e.name?e.description?void 0:void console.error(\"Your web manifest must have a description listed\"):void console.error(\"Your web manifest must have a name listed\"):void console.error(\"Your web manifest must have atleast one icon listed\")}", "function foo() {\n lib.log(\"hello world!\");\n }", "function foo() {\n lib.log(\"hello world!\");\n}", "function logPlanets() \n{\n console.log('Here is the list of planets:');\n console.log(planets);\n}", "function vault_init() {\n var vault_modified = false;\n \n my_log(\"vault_init(): Initializing missing properties from last release\", new Error);\n // All top level values\n if (!pii_vault.guid) {\n\t//Verifying that no such user-id exists is taken care by\n\t//Create Account or Sign-in.\n\t//However, if there is a duplicate GUID then we are in trouble.\n\t//Need to take care of that somehow.\n\tpii_vault.guid = generate_random_id();\n\t\n\tmy_log(\"vault_init(): Updated GUID in vault: \" + pii_vault.guid, new Error);\n\tvault_write(\"guid\", pii_vault.guid);\n\t\n\tpii_vault.current_user = current_user;\n\tvault_write(\"current_user\", pii_vault.current_user);\n\t\n\tpii_vault.sign_in_status = sign_in_status;\n\tvault_write(\"sign_in_status\", pii_vault.sign_in_status);\n }\n \n if (!pii_vault.salt_table) {\n\tvar salt_table = {};\n\t//current_ip for current input, not ip address\n\tvar current_ip = pii_vault.guid;\n\tfor(var i = 0; i < 1000; i++) {\n\t salt_table[i] = CryptoJS.SHA1(current_ip).toString();\n\t current_ip = salt_table[i];\n\t}\n\tpii_vault.salt_table = salt_table;\n\t\n\tmy_log(\"vault_init(): Updated SALT TABLE in vault\", new Error);\n\tvault_write(\"salt_table\", pii_vault.salt_table);\n }\n \n if (!pii_vault.initialized) {\n\tpii_vault.initialized = true;\n\tmy_log(\"vault_init(): Updated INITIALIZED in vault\", new Error);\n\tvault_write(\"initialized\", pii_vault.initialized);\n\t}\n \n if (!pii_vault.total_site_list) {\n\t// This is maintained only to calculate total number of DIFFERENT sites visited\n\t// from time to time. Its reset after every new current_report is created.\n\tpii_vault.total_site_list = [];\n\tmy_log(\"vault_init(): Updated TOTAL_SITE_LIST in vault\", new Error);\n\tvault_write(\"total_site_list\", pii_vault.total_site_list);\n }\n \n if (!pii_vault.password_hashes) {\n\t// This is maintained separarely from current_report as it should not\n\t// be sent to the server. \n\t// Structure is: Key: 'username:etld'\n\t// Value: { \n\t// 'pwd_full_hash':'xyz', \n\t// 'pwd_short_hash':'a', \n\t// 'salt' : 'zz',\n\t// 'pwd_group' : '',\n\t// 'initialized': Date } \n\tpii_vault.password_hashes = {};\n\tmy_log(\"vault_init(): Updated PASSWORD_HASHES in vault\", new Error);\n\tvault_write(\"password_hashes\", pii_vault.password_hashes);\n }\n\n if (!pii_vault.past_reports) {\n\tpii_vault.past_reports = [];\n\tmy_log(\"vault_init(): Updated PAST_REPORTS in vault\", new Error);\n\tvault_write(\"past_reports\", pii_vault.past_reports);\n }\n \n // All config values\n if (!pii_vault.config.deviceid) {\n\t//A device id is only used to identify all reports originating from a \n\t//specific Appu install point. It serves no other purpose.\n\tpii_vault.config.deviceid = generate_random_id();\n\t\n\tmy_log(\"vault_init(): Updated DEVICEID in vault: \" + pii_vault.config.deviceid, new Error);\n\tflush_selective_entries(\"config\", [\"deviceid\"]);\n }\n \n if (!pii_vault.config.current_version) {\n\tvar response_text = read_file('manifest.json');\n\tvar manifest = JSON.parse(response_text);\n\tpii_vault.config.current_version = manifest.version;\n\tmy_log(\"vault_init(): Updated CURRENT_VERSION in vault: \" + pii_vault.config.current_version, new Error);\n\tflush_selective_entries(\"config\", [\"current_version\"]);\n }\n \n if (!pii_vault.config.status) {\n\tpii_vault.config.status = \"active\";\n\t my_log(\"vault_init(): Updated STATUS in vault\", new Error);\n\t vault_write(\"config:status\", pii_vault.config.status);\n }\n \n if (!pii_vault.config.disable_period) {\n\tpii_vault.config.disable_period = -1;\n\t my_log(\"vault_init(): Updated DISABLE_PERIOD in vault\", new Error);\n\t vault_write(\"config:disable_period\", pii_vault.config.disable_period);\n }\n \n if (!pii_vault.config.reporting_hour) {\n\tpii_vault.config.reporting_hour = 0;\n\t//Random time between 5 pm to 8 pm. Do we need to adjust according to local time?\n\tvar rand_minutes = 1020 + Math.floor(Math.random() * 1000)%180;\n\tpii_vault.config.reporting_hour = rand_minutes;\n\tmy_log(\"vault_init(): Updated REPORTING_HOUR in vault\", new Error);\n\tvault_write(\"config:reporting_hour\", pii_vault.config.reporting_hour);\n } \n \n if (!pii_vault.config.next_reporting_time) {\n\tvar curr_time = new Date();\n\t//Advance by 3 days. \n\tcurr_time.setMinutes( curr_time.getMinutes() + 4320);\n\t//Third day's 0:0:0 am\n\tcurr_time.setSeconds(0);\n\tcurr_time.setMinutes(0);\n\tcurr_time.setHours(0);\n\tcurr_time.setMinutes( curr_time.getMinutes() + pii_vault.config.reporting_hour);\n\t//Start reporting next day\n\tpii_vault.config.next_reporting_time = curr_time.toString();\n\t\n\tmy_log(\"Report will be sent everyday at \"+ Math.floor(rand_minutes/60) + \":\" + (rand_minutes%60), new Error);\n\tmy_log(\"Next scheduled reporting is: \" + curr_time, new Error);\n\tmy_log(\"vault_init(): Updated NEXT_REPORTING_TIME in vault\", new Error);\n\tvault_write(\"config:next_reporting_time\", pii_vault.config.next_reporting_time);\n }\n \n if (!pii_vault.config.report_reminder_time) {\n\tpii_vault.config.report_reminder_time = -1;\n\tmy_log(\"vault_init(): Updated REPORT_REMINDER_TIME in vault\", new Error);\n\tvault_write(\"config:report_reminder_time\", pii_vault.config.report_reminder_time);\n }\n \n if (!pii_vault.config.reportid) {\n\tpii_vault.config.reportid = 1;\n\tmy_log(\"vault_init(): Updated REPORTID in vault\", new Error);\n\tvault_write(\"config:reportid\", pii_vault.config.reportid);\n }\n \n // All options values\n if (!pii_vault.options.blacklist) {\n\tpii_vault.options.blacklist = [];\n\tmy_log(\"vault_init(): Updated BLACKLIST in vault\", new Error);\n\tvault_write(\"options:blacklist\", pii_vault.options.blacklist);\n }\n \n if (!pii_vault.options.dontbuglist) {\n\tpii_vault.options.dontbuglist = [];\n\tmy_log(\"vault_init(): Updated DONTBUGLIST in vault\", new Error);\n\tvault_write(\"options:dontbuglist\", pii_vault.options.dontbuglist);\n }\n \n //Three different types of reporting.\n //Manual: If reporting time of the day and if report ready, interrupt user and ask \n // him to review, modify and then send report.\n //Auto: Send report automatically when ready.\n //Differential: Interrupt user to manually review report only if current report\n // entries are different from what he reviewed in the past.\n // (How many past reports should be stored? lets settle on 10 for now?).\n // Highlight the different entries with different color background.\n if (!pii_vault.options.report_setting) {\n\tpii_vault.options.report_setting = \"manual\";\n\tmy_log(\"vault_init(): Updated REPORT_SETTING in vault\", new Error);\n\tvault_write(\"options:report_setting\", pii_vault.options.report_setting);\n } \n\n // All current report values\n if (!pii_vault.current_report) {\n\tpii_vault.current_report = initialize_report();\n\tmy_log(\"vault_init(): Updated CURRENT_REPORT in vault\", new Error);\n\t\n\tflush_current_report();\n }\n \n // All aggregate data values\n if (!pii_vault.aggregate_data) {\n\tpii_vault.aggregate_data = initialize_aggregate_data();\n\tmy_log(\"vault_init(): Updated AGGREGATE_DATA in vault\", new Error);\n\t\n\tflush_aggregate_data();\n }\n}", "function version(){\n console.log(\"Version:\" , _cfg.version );\n}", "_diagnostic(){\r\n\r\nlet diagvers=\"Version :\\t\" + \"1.1\" + \"\\n\"\r\nLog.info('@@@Dtag: DeviceInfo.systeminfo diagvers: ', diagvers)\r\nthis.tag('DiagnosticVersionLabel').patch({text: {text: diagvers}})\r\n\r\nthis.tag('ThunderDiagnosticService')._diagnostic().then(data => {\r\nconsole.log(\"@@@inside diag screen\",data);\r\nthis.tag('DiagnosticInfoLabel').patch({text: {text: data}})\r\n})\r\nthis.tag('ThunderDiagnosticService')._diagnosticVersion().then(data => {\r\nconsole.log(\"@@@inside diag screen\",data);\r\nthis.tag('DiagnosticIPLabel').patch({text: {text: data}})\r\n})\r\nthis.tag('ThunderDiagnosticService')._diagnosticResolution().then(data => {\r\nconsole.log(\"@@@inside diag screen\",data);\r\nthis.tag('DiagnosticResolutionLabel').patch({text: {text: data}})\r\n})\r\n\r\n}", "function logEvent(e) {\n var online, status, message;\n online = (navigator.onLine) ? 'yes' : 'no';\n var eventType = e.type;\n\n message = 'App {online: ' + online + '} ';\n message += 'Appcache {event: ' + eventType;\n message += ', status: ' + cacheStatusValues[appCache.status] + '} ';\n\n if (eventType == 'error' && navigator.onLine) {\n message += '(possible syntax errors in the manifest)';\n }\n\n console.log(message);\n}", "function readAmtAuditLog() {\r\n // See if MicroLMS needs to be started\r\n if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) {\r\n settings.noconsole = true; startLms(readAmtAuditLogEx);\r\n } else {\r\n readAmtAuditLogEx(9999);\r\n }\r\n}", "function LogwranglerModule(){}", "function _w18sub() {\n\tvar _w18userinfo_out = {};\n\tif( typeof localStorage !== \"undefined\" ) {\n\t\tif( localStorage.getItem( \"_w18userinfo\" ) !== null ) {\n\t\t\t_w18userinfo_out = localStorage.getItem( \"_w18userinfo\" );\n\t\t\t_w18userinfo_out = unescape( _w18userinfo_out );\n\t\t\tvar contact = JSON.parse( _w18userinfo_out );\n\t\t\t//console.log('_w18userinfo_out = ', contact);\n\t\t\tfor(var contactItem in contact){\n\t\t\t //console.log(\"Key=\"+contactItem);\n\t\t\t //console.log(contact[contactItem]);\n\t\t\t if(contactItem == 'interest_channel' || contactItem == 'interest_bucket' || contactItem == 'logged_in' || contactItem == 'extra'){\n\t\t\t\t//console.log(contact[contactItem]);\n\t\t\t\tfor(var contactItemVal in contact[contactItem]){\n\t\t\t\t //console.log(contact[contactItem][contactItemVal]+\"<<<<<<<<<<<>>>>>>>>>>>\"+contactItemVal);\n\t\t\t\t googletag.pubads().setTargeting( contactItemVal,contact[contactItem][contactItemVal] );\n\t\t\t\t}\n\t\t\t }\n\t\t\t else if(contactItem == 'vernacular' )\n\t\t\t {\n\t\t\t\t//console.log(contact[contactItem]);\n\t\t\t\tgoogletag.pubads().setTargeting( contactItem,contact[contactItem] );\n\t\t\t }\n\t\t\t else if(contactItem == 'interest_platform' )\n\t\t\t {\n\t\t\t\t//console.log(\"interest_platform\");\n\t\t\t\t//console.log(contact[contactItem]);\n\t\t\t\tfor(var contactItemVal in contact[contactItem])\n\t\t\t\t{\n\t\t\t\t //console.log(\"interest_platform\");\n\t\t\t\t //console.log(contactItemVal);\n\t\t\t\t //console.log(contact[contactItem][contactItemVal]);\n\t\t\t\t googletag.pubads().setTargeting( contactItemVal,contact[contactItem][contactItemVal]);\n\t\t\t\t for(var platform_name in contact[contactItem][contactItemVal] )\n\t\t\t\t {\n\t\t\t\t\t//console.log(contact[contactItem][contactItemVal][platform_name]);\n\t\t\t\t\t//googletag.pubads().setTargeting( contactItemVal,contact[contactItem][contactItemVal][platform_name] );\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t }\n\t\t\t};\n\t\t}\n\t}\n\treturn false;\n}", "function getWebhookInfo() {\r\n let hasil = tg.getWebhookInfo()\r\n return Logger.log(hasil)\r\n}", "function listify(words: Array<string>): string {\n if (words.length === 1) { return words[0]; }\n return words.slice(0, words.length - 1).join(\", \") + \" and \" + words[words.length - 1];\n}\n\n\nlet cli = new CLI();\n\nabstract class EnsPlugin extends Plugin {\n _ethAddressCache: { [ addressOrInterfaceId: string ]: string };\n\n constructor() {\n super();\n ethers.utils.defineReadOnly(this, \"_ethAddressCache\", { });\n }\n\n getEns(): ethers.Contract {\n return new ethers.Contract(this.network.ensAddress, ensAbi, this.accounts[0] || this.provider);\n }", "logHealthcheck() {\n (async () => {\n await module.exports.checkPg();\n module.exports.calcUptime();\n lumServer.logger.info('healthcheck', lumServer.healthcheck);\n })();\n }", "function logSomething(log) { log.info('something'); }", "function dumpSlotInfo(s) {\r\n\r\n\tprint(\"Slot #\" + s.getId());\r\n\tprint(\" Description : \" + s.getDescription());\r\n\tprint(\" Manufacturer : \" + s.getManufacturer());\r\n\tprint(\" Hardware Version : \" + s.getHardwareVersion());\r\n\tprint(\" Firmware Version : \" + s.getFirmwareVersion());\r\n\tprint(\" isTokenPresent : \" + s.isTokenPresent());\r\n\tprint(\" isHardwareDevice : \" + s.isHardwareDevice());\r\n\tprint(\" isRemovableDevice : \" + s.isRemovableDevice());\r\n\t\r\n\tif (s.isTokenPresent()) {\r\n\t\tvar label = s.getTokenLabel();\r\n\r\n\t\tprint(\" Token :\");\r\n\t\tprint(\" Label : \" + label);\r\n\t\tprint(\" Manufacturer : \" + s.getTokenManufacturer());\r\n\t\tprint(\" Model : \" + s.getTokenModel());\r\n\t\tprint(\" Serial Number : \" + s.getTokenSerialNumber());\r\n\t\tprint(\" Max PIN Length : \" + s.getTokenMaxPinLen());\r\n\t\tprint(\" Min PIN Length : \" + s.getTokenMinPinLen());\r\n\t\tprint(\" hasTokenProtectedAuthPath : \" + s.hasTokenProtectedAuthPath());\r\n\t\t\r\n\t\tvar mechs = s.getMechanisms();\r\n\t\tfor (var j = 0; j < mechs.length; j++) {\r\n\t\t\tprint(\" Mechanisms #\" + j);\r\n\t\t\tvar m = mechs[j];\r\n\t\t\tprint(\" Type : \" + m.getType() + \" (\" + m.getTypeName() + \")\");\r\n\t\t\tprint(\" Min Key Size : \" + m.getMinKeySize());\r\n\t\t\tprint(\" Max Key Size : \" + m.getMaxKeySize());\r\n\t\t\tprint(\" Flags : \" + m.getFlags());\r\n\t\t}\r\n\t}\r\n}", "function logbs(data) {\n chrome.storage.sync.get('debugMode', function(response) {\n if (response.debugMode) {\n console.log(data);\n }\n });\n}", "function manifest(ignored) {}", "function _____INTERNAL_log_functions_____(){}\t\t//{", "tokenBuiltEvent(web3){\n const contract = require('truffle-contract');\n const Betting = contract(CoreLayer);\n Betting.setProvider(web3.currentProvider);\n var BettingInstance;\n var logTokenBuiltEvent;\n web3.eth.getAccounts((error, accounts) => {\n Betting.deployed().then((instance) => {\n //Instantiate the contract in a promise\n BettingInstance = instance\n })\n .then((result) => {\n logTokenBuiltEvent = BettingInstance.LogTokenBuilt();\n logTokenBuiltEvent.watch(function(error, result){\n if (!error)\n {\n $(\"#loader\").hide();\n $(\"#instructor\").html(result.args.creatorAddress + ' built a token! Token: Stage ' + result.args.stage + ', First Place: '+ result.args.Winner + ', Second Place: '+ result.args.Runnerup + ', TimeStamp: '+ result.args.timeStamp);\n } else {\n $(\"#loader\").hide();\n console.log(error);\n }\n });\n })\n })\n }", "function logDetails(uid, item) {\n console.log(\"A product with \" + uid + \" has a title as \" + item);\n}", "static info(){\r\n\t\t\tconsole.log('A dog is a mammal');\r\n\t\t}", "function earthLogger(){\n console.log('Earth');\n\n}", "function logAlerts() {\n //log an alert if there is a NEW threshold on Harddrive OR Firewall, log \"No Alert\" otherwise\n\n if(hostName === undefined){\n context.succeed(null, \"hostname undefined for \" + srcKey + \"!!!\");\n } else if(alerted){\n context.succeed(null, \"alerted published alerts for \" + srcKey + \" !!!\");\n }\n else {\n alerted = true;\n var logOutput = \"Alerts: \";\n\n //harddiskStatus Alerts\n var harddiskString = \"Harddisk Alert! Current Harddisk Status: \" + newDiskStatus + \"%. \";\n if ((!oldDiskAlert && newDiskAlert) && alertHarddisk) {\n logOutput += harddiskString;\n console.log(harddiskString);\n publish(\"hostname: \" + hostName + \": \" + harddiskString);\n } else if (alertHarddisk == false) {\n //do not include Harddisk information in output.\n } else {\n var noAlert = \"No Harddisk Alert. \"\n logOutput += noAlert;\n console.log(noAlert);\n publish(\"hostname: \" + hostName + \": \" + noAlert + \" old: \" + oldDiskStatus + \" new: \" + newDiskStatus);\n }\n\n //FirewallStatus Alerts\n var firewallString = \"Firewall Alert! Current Firewall Status: \" + newFirewallStatus + \". \";\n //ensure firewall alert only if it matches config.json value\n if ((oldFirewallStatus != newFirewallStatus) && alertFirewall && (newFirewallStatus == firewallVal)) {\n logOutput += firewallString;\n console.log(firewallString);\n publish(\"hostname: \" + hostName + \": \" + firewallString);\n } else if (alertFirewall == false) {\n //do not include Firewall information in output.\n } else if (alertFirewall && oldFirewallStatus === undefined && (newFirewallStatus === firewallVal)) {\n logOutput += firewallString;\n console.log(firewallString);\n publish(\"hostname: \" + hostName + \": \" + firewallString);\n } else {\n var noAlert = \"No Firewall Alert. \";\n logOutput += noAlert;\n console.log(noAlert);\n publish(\"hostname: \" + hostName + \": \" + noAlert + \" old: \" + oldFirewallStatus + \" new: \" + newFirewallStatus);\n }\n\n //BatteryHealth alerts\n var batteryHealthString = \"Battery Health Alert! Battery Health: \" + srcBatteryHealth + \". Number of charge cycles: \" + srcBatteryCycles + \". \";\n if (alertBatteryHealth && alertBattery) {\n logOutput += batteryHealthString;\n console.log(batteryHealthString);\n publish(\"hostname: \" + hostName + \": \" + batteryHealthString);\n } else if(alertBattery) {\n var healthGood = \"Battery Health Good. \";\n logOutput += healthGood;\n console.log(healthGood);\n publish(\"hostname: \" + hostName + \": \" + healthGood);\n }\n\n //BatteryStatus alerts\n srcBatteryStatus = srcBatteryStatus.toString();\n srcBatteryStatus = srcBatteryStatus.substring(0, 4);\n if(oldBatteryStatus != undefined) {\n oldBatteryStatus = oldBatteryStatus.toString();\n oldBatteryStatus = oldBatteryStatus.substring(0, 4);\n }\n var batteryString = \"Battery Level Alert! Current Battery Level: \" + srcBatteryStatus + \"%. \";\n if ((!oldBatteryAlert && newBatteryAlert) && alertBattery) {\n logOutput += batteryString;\n console.log(batteryString);\n publish(\"hostname: \" + hostName + \": \" + batteryString);\n } else if (alertBattery == false) {\n //do not include Battery information in output.\n } else {\n if (alertBattery && oldBatteryStatus === undefined && (newBatteryAlert)) {\n logOutput += batteryString;\n console.log(batteryString);\n publish(\"hostname: \" + hostName + \": \" + batteryString);\n } else {\n var noAlert = \"No Battery Level Alert. \";\n logOutput += noAlert;\n console.log(noAlert);\n publish(\"hostname: \" + hostName + \": \" + noAlert + \" old: \" + oldBatteryStatus + \" new: \" + srcBatteryStatus);\n }\n }\n loggedAlerts = true;\n }\n }", "function getWebhookInfo() {\n let hasil = tg.getWebhookInfo()\n return Logger.log(hasil)\n}", "function PrintLog(a)\n{\nlogger.info(a);\n}", "function logger() {\n\tprint('[' + this['zap.script.name'] + '] ' + arguments[0]);\n}", "function custom_log(string)\n{\n log(\"SKETCH2CODE | \" + string)\n}", "function log(thing, tag) {\n\n var acceptedTags = [\n //\"server\",\n //\"stockfish\",\n //\"server_tick\",\n //\"server_all\",\n //\"ui\",\n ];\n\n var accepted = false;\n for (var i in acceptedTags)\n if (acceptedTags[i] == tag) {\n accepted = true;\n break;\n }\n\n if (accepted)\n console.log(thing);\n }", "function debug(entry) {\n console.log(entry)\n}", "function debug(entry) {\n console.log(entry)\n}", "function getPublicLedger(blockchainDomain){\n\n}", "function contractFrom(address) {\n \n \n // Reference to the deployed contract\n const DeployedContractRef = AccessTokenContract.at(address);\n // function registerAsset(bytes32 _assetkey, bool _flag) public isAdmin(_assetkey) returns (bool){\n var data = DeployedContractRef.registerAsset(web3.fromAscii(_assetkey),flag,{ from: web3.eth.accounts[0], gas: 400000 });\n console.log(data);\n // console.log(data[2]);\n\n DeployedContractRef.RegisteredAsset().watch(function(error, result) {\n\n console.log(result.args.result);\n //console.log(web3.toAscii(result.args.result[1]));\n //console.log(result.args.result[2]);\n//});\n })\n}", "function _logData(data)\n {\n if (data.version < \"3.0\") {\n console.warn(\"你的服务器端 NextPHPChromeDebug 库版本为\" + data.version + \" 。最新版本的扩展需要3.0或更高版本。\");\n return;\n }\n\n return _logCleanData(data, _complete);\n }", "function logger() {\n print('[' + this['zap.script.name'] + '] ' + arguments[0]);\n}", "logVersions() {\n /** Get framework version. */\n cy.get('#shop_version').then($frameworkVersion => {\n var frameworkVersion = ($frameworkVersion.text()).replace(/.*[^0-9.]/g, '');\n cy.wrap(frameworkVersion).as('frameworkVersion');\n });\n\n this.goToPageAndIgnoreWarning(this.ModulesAdminUrl);\n\n /** Get Paylike version. */\n cy.get(`div[data-tech-name*=${this.PaylikeName}]`).invoke('attr', 'data-version').then($pluginVersion => {\n cy.wrap($pluginVersion).as('pluginVersion');\n });\n\n /** Get global variables and make log data request to remote url. */\n cy.get('@frameworkVersion').then(frameworkVersion => {\n cy.get('@pluginVersion').then(pluginVersion => {\n\n cy.request('GET', this.RemoteVersionLogUrl, {\n key: frameworkVersion,\n tag: this.ShopName,\n view: 'html',\n ecommerce: frameworkVersion,\n plugin: pluginVersion\n }).then((resp) => {\n expect(resp.status).to.eq(200);\n });\n });\n });\n }", "info() { }", "function mylogging(logg)\r\n{\r\n\t let r = logg.requests[0].response.headers ;\r\n\t r = JSON.stringify(r) ;\r\n\t console.log(r) ;\r\n\t fs.writeFileSync(filePath,r);\r\n}", "help(){\n console.log(`Module :\n NativeObserver\n Reflect\n RootBypass`);\n }", "function PrintVars(stream)\r\n{\r\n stream.WriteLine(\"Variables:\");\r\n stream.WriteLine(\" VERSION=\" + VERSION);\r\n stream.WriteLine(\" DEVENV=\" + DEVENV);\r\n stream.WriteLine(\" DEVENVFLAGS=\" + DEVENVFLAGS);\r\n stream.WriteLine(\" CPPFLAGS=\" + CPPFLAGS);\r\n stream.WriteLine(\" LDFLAGS=\" + LDFLAGS);\r\n stream.WriteLine(\" LIBS=\" + LIBS);\r\n stream.WriteLine(\" CONVERT=\" + CONVERT);\r\n stream.WriteLine(\" CXX=\" + CXX);\r\n stream.WriteLine(\" LD=\" + LD);\r\n stream.WriteLine(\" AR=\" + AR);\r\n stream.WriteLine(\" AS=\" + AS);\r\n stream.WriteLine(\" SLNVER=\" + SLNVER);\r\n stream.WriteLine(\" SLNCOMMENT=\" + SLNCOMMENT);\r\n stream.WriteLine(\" UNICODELOG=\" + UNICODELOG);\r\n stream.WriteLine(\" NOSTCRT=\" + NOSTCRT);\r\n stream.WriteLine(\" WINDIFF=\" + WINDIFF);\r\n stream.WriteLine(\" ICCCONVERT=\" + ICCCONVERT);\r\n stream.WriteLine(\" PLATFORM=\" + PLATFORM);\r\n stream.WriteLine(\" CLVARSBAT=\" + CLVARSBAT);\r\n stream.WriteLine(\" ICCVER=\" + ICCVER);\r\n stream.WriteLine(\"\");\r\n}", "function $25db97ff793e71a3$var$accesslog(hljs) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\n const HTTP_VERBS = [\n \"GET\",\n \"POST\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"CONNECT\",\n \"OPTIONS\",\n \"PATCH\",\n \"TRACE\"\n ];\n return {\n name: \"Apache Access Log\",\n contains: [\n // IP\n {\n className: \"number\",\n begin: \"^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}(:\\\\d{1,5})?\\\\b\",\n relevance: 5\n },\n // Other numbers\n {\n className: \"number\",\n begin: \"\\\\b\\\\d+\\\\b\",\n relevance: 0\n },\n // Requests\n {\n className: \"string\",\n begin: '\"(' + HTTP_VERBS.join(\"|\") + \")\",\n end: '\"',\n keywords: HTTP_VERBS.join(\" \"),\n illegal: \"\\\\n\",\n relevance: 5,\n contains: [\n {\n begin: \"HTTP/[12]\\\\.\\\\d\",\n relevance: 5\n }\n ]\n },\n // Dates\n {\n className: \"string\",\n // dates must have a certain length, this prevents matching\n // simple array accesses a[123] and [] and other common patterns\n // found in other languages\n begin: /\\[\\d[^\\]\\n]{8,}\\]/,\n illegal: \"\\\\n\",\n relevance: 1\n },\n {\n className: \"string\",\n begin: /\\[/,\n end: /\\]/,\n illegal: \"\\\\n\",\n relevance: 0\n },\n // User agent / relevance boost\n {\n className: \"string\",\n begin: '\"Mozilla/\\\\d\\\\.\\\\d \\\\(',\n end: '\"',\n illegal: \"\\\\n\",\n relevance: 3\n },\n // Strings\n {\n className: \"string\",\n begin: '\"',\n end: '\"',\n illegal: \"\\\\n\",\n relevance: 0\n }\n ]\n };\n}", "static get tag(){return\"hal-9000\"}", "function asd(thing,outf) \n{\nlet log =\"\";\n for(var propname in thing)\n {\n if (true)//(thing.hasOwnProperty(propname))\n {log += propname + \":\" + thing[propname] + \"<br>\" ;}\n }\n\nif (!outf){loginhtml(log);}else{outf(log);}\nlog=\"\";\n}", "function debugme(arg) {\n if (DEBUGME[myType]) {\n\tconsole.log(arg);\n }\n}", "function LogOmnitureEvent(eventName)\n{\n try\n {\n s=s_gi(s_account);\n s.linkTrackVars=\"events\";\n s.linkTrackEvents=eventName;\n s.events=eventName;\n s.tl(this,'o','My Link Name');\n }\n catch(e){}\n}", "applyAudit() {\n super.applyAudit();\n this.log.debug('This is only another custom messagem from your custom server :)');\n }", "getClientLog() {\n\n }", "log(_args) {\n\n }", "baseUrl(){\n return `https://www.warcraftlogs.com:443/${this.version}`\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 }", "enterProgram(ctx) { console.log(\" %s: %s\", __function, ctx.getText()); }", "info() {}", "info() {}", "function accesslog(hljs) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\n var HTTP_VERBS = [\n \"GET\", \"POST\", \"HEAD\", \"PUT\", \"DELETE\", \"CONNECT\", \"OPTIONS\", \"PATCH\", \"TRACE\"\n ];\n return {\n name: 'Apache Access Log',\n contains: [\n // IP\n {\n className: 'number',\n begin: '^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}(:\\\\d{1,5})?\\\\b',\n relevance:5\n },\n // Other numbers\n {\n className: 'number',\n begin: '\\\\b\\\\d+\\\\b',\n relevance: 0\n },\n // Requests\n {\n className: 'string',\n begin: '\"(' + HTTP_VERBS.join(\"|\") + ')', end: '\"',\n keywords: HTTP_VERBS.join(\" \"),\n illegal: '\\\\n',\n relevance: 5,\n contains: [{\n begin: 'HTTP/[12]\\\\.\\\\d',\n relevance:5\n }]\n },\n // Dates\n {\n className: 'string',\n // dates must have a certain length, this prevents matching\n // simple array accesses a[123] and [] and other common patterns\n // found in other languages\n begin: /\\[\\d[^\\]\\n]{8,}\\]/,\n illegal: '\\\\n',\n relevance: 1\n },\n {\n className: 'string',\n begin: /\\[/, end: /\\]/,\n illegal: '\\\\n',\n relevance: 0\n },\n // User agent / relevance boost\n {\n className: 'string',\n begin: '\"Mozilla/\\\\d\\\\.\\\\d \\\\\\(', end: '\"',\n illegal: '\\\\n',\n relevance: 3\n },\n // Strings\n {\n className: 'string',\n begin: '\"', end: '\"',\n illegal: '\\\\n',\n relevance: 0\n }\n ]\n };\n}", "function accesslog(hljs) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\n var HTTP_VERBS = [\n \"GET\", \"POST\", \"HEAD\", \"PUT\", \"DELETE\", \"CONNECT\", \"OPTIONS\", \"PATCH\", \"TRACE\"\n ];\n return {\n name: 'Apache Access Log',\n contains: [\n // IP\n {\n className: 'number',\n begin: '^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}(:\\\\d{1,5})?\\\\b',\n relevance:5\n },\n // Other numbers\n {\n className: 'number',\n begin: '\\\\b\\\\d+\\\\b',\n relevance: 0\n },\n // Requests\n {\n className: 'string',\n begin: '\"(' + HTTP_VERBS.join(\"|\") + ')', end: '\"',\n keywords: HTTP_VERBS.join(\" \"),\n illegal: '\\\\n',\n relevance: 5,\n contains: [{\n begin: 'HTTP/[12]\\\\.\\\\d',\n relevance:5\n }]\n },\n // Dates\n {\n className: 'string',\n // dates must have a certain length, this prevents matching\n // simple array accesses a[123] and [] and other common patterns\n // found in other languages\n begin: /\\[\\d[^\\]\\n]{8,}\\]/,\n illegal: '\\\\n',\n relevance: 1\n },\n {\n className: 'string',\n begin: /\\[/, end: /\\]/,\n illegal: '\\\\n',\n relevance: 0\n },\n // User agent / relevance boost\n {\n className: 'string',\n begin: '\"Mozilla/\\\\d\\\\.\\\\d \\\\\\(', end: '\"',\n illegal: '\\\\n',\n relevance: 3\n },\n // Strings\n {\n className: 'string',\n begin: '\"', end: '\"',\n illegal: '\\\\n',\n relevance: 0\n }\n ]\n };\n}", "function console_log(stringa){\n if (global_verbosity_argo > 0){\n console.log(stringa);\n }\n}", "function myDetails(){\r\nconsole.log(\"Name :\" + details.name); // prints Name on Console\r\nconsole.log(\"Age :\" + details.age); // prints Age on Console\r\nconsole.log(\"Date Of Birth :\" + details.dateOfBirth); // prints date of birth on Console\r\nconsole.log(\"Place Of Birth :\" + details[\"placeOfBirth\"]); // prints place of birth on Console\r\n \r\n /* Console.log functions for printing name, \r\n age, date of birth and place of birth*/\r\n }", "function logAllNestedVideos(){\n logAncestorsOfType(\"your-folder-here\", \"your-type-here\");\n}", "function log() {\n //log here\n }", "function getAriaEventInfo(event) {\r\n var e_1, _a;\r\n var values = {\r\n 'CorrelationVector': event.vector.toString(),\r\n 'ValidationErrors': event.validationErrors,\r\n 'WebLog_FullName': event.eventName,\r\n 'WebLog_EventType': EventBase_1.ClonedEventType[event.eventType]\r\n };\r\n if (event.eventType === EventBase_1.ClonedEventType.End) {\r\n values.Duration = event.endTime - event.startTime;\r\n }\r\n var names = event.eventName.split(',');\r\n try {\r\n for (var names_1 = tslib_1.__values(names), names_1_1 = names_1.next(); !names_1_1.done; names_1_1 = names_1.next()) {\r\n var name_1 = names_1_1.value;\r\n if (name_1) {\r\n values[\"WebLog_Type_\" + name_1] = 1;\r\n }\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (names_1_1 && !names_1_1.done && (_a = names_1.return)) _a.call(names_1);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n var data = event.data, context = event.context;\r\n if (context) {\r\n for (var key in context) {\r\n if (Object.prototype.hasOwnProperty.call(context, key)) {\r\n var value = context[key];\r\n if (value === undefined || value === null) {\r\n continue;\r\n }\r\n var loggingName = index_1.capitalize(key);\r\n values[loggingName] = value;\r\n }\r\n }\r\n }\r\n if (data) {\r\n for (var field in data) {\r\n if (Object.prototype.hasOwnProperty.call(data, field)) {\r\n var value = data[field];\r\n if (value === undefined || value === null) {\r\n continue;\r\n }\r\n var propertyMetadata = event.metadata[field];\r\n if (propertyMetadata) {\r\n var loggingName = propertyMetadata.isPrefixingDisabled ?\r\n index_1.capitalize(field) :\r\n index_1.capitalize(propertyMetadata.definedInName) + \"_\" + field;\r\n var type = propertyMetadata.type;\r\n if (type === 4 /* Object */) {\r\n for (var subField in value) {\r\n if (value[subField] !== undefined) {\r\n values[loggingName + \"_\" + subField.replace('.', '_')] = value[subField];\r\n }\r\n }\r\n }\r\n else {\r\n values[loggingName] = type === 6 /* Enum */ ? propertyMetadata.typeRef[value] : value;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return {\r\n name: event.isEventTypePrefixingDisabled ? names[names.length - 2] : \"ev_\" + names[names.length - 2],\r\n values: values\r\n };\r\n}", "displayAspects() { console.log(this.logtags); }", "static get(lgr = \"anon\", maxLog = \"default\", force = \"default\") {\nvar i, len, lg, ref, ref1, ref2, ref3, stat, theLogger;\ntheLogger = null;\nref = Logger._loggers;\nfor (i = 0, len = ref.length; i < len; i++) {\nlg = ref[i];\nif (lg.modName === lgr) {\nif (theLogger == null) {\ntheLogger = lg;\n}\n}\n}\nstat = theLogger != null ? \"Updated\" : \"Created\";\nif (theLogger != null) {\nif (maxLog === \"default\") {\nmaxLog = theLogger.maxLog;\n}\nif (force === \"default\") {\nforce = theLogger.force;\n}\nif ((ref1 = Logger._modLogger) != null) {\nif (typeof ref1.trace === \"function\") {\nref1.trace(`get: Updating ${theLogger.modName} Logger. MaxLog ${theLogger.maxLog} -> ${maxLog}`);\n}\n}\ntheLogger._setLoggers(maxLog, force);\n} else {\nif (maxLog === \"default\") {\nmaxLog = Logger._defaultMaxLog;\n}\nif (force === \"default\") {\nforce = \"noforce\";\n}\nif ((ref2 = Logger._modLogger) != null) {\nif (typeof ref2.trace === \"function\") {\nref2.trace(`get: Create ${lgr} logger`);\n}\n}\ntheLogger = new Logger(lgr, maxLog, force);\n}\nif ((ref3 = Logger._modLogger) != null) {\nif (typeof ref3.debug === \"function\") {\nref3.debug(`${theLogger.modName} ${stat}: ${theLogger.maxLog} (${theLogger.maxLogLev}) ${theLogger.force}`);\n}\n}\nreturn theLogger;\n}", "_logString () {\n return logItemHelper('ItemEmbed', this, `embed:${JSON.stringify(this.embed)}`)\n }", "function v(t) {\n if (\"string\" == typeof t) return t;\n try {\n return e = t, JSON.stringify(e);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */ var e;\n}", "function logPlanets() {\n console.log(\"Here is the list of planets:\");\n console.log(planets);\n console.log(\"---- ---- ---- ----\");\n }", "function logPlanets() {\n console.log(\"Here is the list of planets:\");\n console.log(planets);\n console.log(\"---- ---- ---- ----\");\n }", "function logPlanets() {\n console.log(\"Here is the list of planets:\");\n console.log(planets);\n console.log(\"---- ---- ---- ----\");\n }", "function logPlanets() {\n console.log(\"Here is the list of planets:\");\n console.log(planets);\n console.log(\"---- ---- ---- ----\");\n }", "function getLog(key){\n\tlet tmp = key.replace('log',''); //remove log prefix from the key to get the number\n\tlogNumber = Number(tmp); //parse the string into a number\n\tlocalforage.getItem('logs') //load the logs from memory\n\t.then((logs)=>{\n\t\tlet log = logs[key]; //get our log at the parameter key.\n\t\tconsole.log(log)\n\t\tfor(let field in log){ //itwerage over the fields of the log\n\t\t\tlet value = log[field];\n\t\t\tif(typeof value === \"string\") //if the field is a string, it goes to a text input\n\t\t\t\t$(`.${field}`).val(value);\n\t\t\telse if(value){ //or else it is a checkbox\n\t\t\t\t$(`input[val=${field}]`).prop('checked',true);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$(`input[val=${field}]`).prop('checked',false);\n\t\t\t}\n\t\t}\n\t})\n\n\treturn\n}", "versionsVersionGet(incomingOptions, cb) {\n const Rollbar = require('./dist');\n\n let apiInstance = new Rollbar.VersionsApi(); // String | Use a project access token with 'read' scop // String | The code version sent on the occurrence payloa // String | The environment where the code version is detected\n /*let xRollbarAccessToken = \"xRollbarAccessToken_example\";*/ /*let version = \"version_example\";*/ /*let environment = \"environment_example\";*/ apiInstance.versionsVersionGet(\n incomingOptions.xRollbarAccessToken,\n incomingOptions.version,\n incomingOptions.environment,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data.result, response);\n }\n }\n );\n }", "printInfo(){\n console.log(\"Blockchain length: \" + this.chain.length + \"\\n\");\n console.log(this.chain);\n }", "function getMe(){\n let me = tg.getMe()\n return Logger.log(me)\n}", "function consoleLogs(){\n // console.log(\"API temperature is \" + tempApi);\n // console.log(\"expected Rain is \" + rainApi);\n // console.log(tempClient + \" is temperature of Client\")\n // console.log(\"type is \" + typeof tempClient)\n toClients(tempApi, rainApi, tempClient);\n}", "function trackRealtidbits(type,url) {\n var s = s_gi(s_account);\n s.eVar1= type+\" :content article: \"+url;\n s.trackExternalLinks = false;\n s.linkTrackEvents = s.events = 'event11';\n s.linkTrackVars = 'eVar1,events';\n s.tl(this, 'o', s.eVar1);\n}", "log() {}", "async function main() {\n\n const [deployer] = await ethers.getSigners();\n\n console.log(\n \"Deploying contracts with the account:\",\n deployer.address\n );\n\n console.log(\"Account balance:\", (await deployer.getBalance()).toString());\n\n const Granola = await ethers.getContractFactory(\"Granola\");\n const granolaToken = await Granola.deploy();\n\n console.log(\"Token address:\", granolaToken.address);\n}", "function getAriaEventInfo(event) {\r\n var values = {\r\n 'CorrelationVector': event.vector.toString(),\r\n 'ValidationErrors': event.validationErrors,\r\n 'WebLog_FullName': event.eventName,\r\n 'WebLog_EventType': EventBase_1.ClonedEventType[event.eventType]\r\n };\r\n if (event.eventType === EventBase_1.ClonedEventType.End) {\r\n values.Duration = event.endTime - event.startTime;\r\n }\r\n var names = event.eventName.split(',');\r\n for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {\r\n var name_1 = names_1[_i];\r\n if (name_1) {\r\n values[\"WebLog_Type_\" + name_1] = 1;\r\n }\r\n }\r\n var data = event.data, context = event.context;\r\n if (context) {\r\n for (var key in context) {\r\n if (Object.prototype.hasOwnProperty.call(context, key)) {\r\n var value = context[key];\r\n if (value === undefined || value === null) {\r\n continue;\r\n }\r\n var loggingName = index_1.capitalize(key);\r\n values[loggingName] = value;\r\n }\r\n }\r\n }\r\n if (data) {\r\n for (var field in data) {\r\n if (Object.prototype.hasOwnProperty.call(data, field)) {\r\n var value = data[field];\r\n if (value === undefined || value === null) {\r\n continue;\r\n }\r\n var propertyMetadata = event.metadata[field];\r\n if (propertyMetadata) {\r\n var loggingName = propertyMetadata.isPrefixingDisabled ?\r\n index_1.capitalize(field) :\r\n index_1.capitalize(propertyMetadata.definedInName) + \"_\" + field;\r\n var type = propertyMetadata.type;\r\n if (type === 4 /* Object */) {\r\n for (var subField in value) {\r\n if (Object.prototype.hasOwnProperty.call(value, subField)) {\r\n var subValue = value[subField];\r\n if (subValue !== undefined && subValue !== null && subValue !== '') {\r\n // Do not write values which would serialize as empty since they do not provide meaningful\r\n // information in instrumentation back-ends.\r\n values[loggingName + \"_\" + subField.replace('.', '_')] = subValue;\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n values[loggingName] = type === 6 /* Enum */ ? propertyMetadata.typeRef[value] : value;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return {\r\n name: event.isEventTypePrefixingDisabled ? names[names.length - 2] : \"ev_\" + names[names.length - 2],\r\n values: values\r\n };\r\n}", "function Log3(target, name, descriptor) {\n console.log(\"Method decorator\");\n console.log(target); // prototype\n console.log(name); // getPriceWithTax string\n console.log(descriptor); // { value: getPriceWithTax function }\n}", "function getlogs()\n{\n if (typeof (webphone_api.plhandler) !== 'undefined' && webphone_api.plhandler !== null)\n return webphone_api.plhandler.getlogs();\n else\n webphone_api.Log('ERROR, webphone_api: getlogs webphone_api.plhandler is not defined');\n}", "function printVariable() {\n console.log(\"____ + ____ + ____ + ____ +\\n\" +\n \"START\");\n var lang;\n var target;\n if (true) {\n lang = \"vi\";\n target = \"en-us\";\n console.log(\"INside block\");\n console.log(target);\n }\n console.log(\"OUTside block\");\n console.log(lang);\n}", "function alt_xapi()\n{\n\n\tconsole.log(\"????????????????????????????????????????\")\n\tconsole.log(\"Alt_image_id: \" + Alt_image_id)\n\tconsole.log(\"????????????????????????????????????????\")\n\n\nvar alttagStatement = {\n \"type\": \"alttag\",\n \"verb\": \"viewed\",\n \"module\": bCurrentMod + 1,\n \"lesson\": bCurrentLsn + 1,\n //\"page\": bCurrentPag + 1,\n\t\t\t\t\"page\": np_num,\n \"activity\": \"http://id.tincanapi.com/activitytype/resource\",\n \"objectID\":Alt_image_id, //some sort of generated id\n\n};\n\t\n\tif(typeof isXAPI !== \"undefined\"){\n\n\t\tLRSSend(alttagStatement);\n\n\t}\t\n\t\n}", "function log(a) {\n console.log(a);\n console.log(a.greeting);\n\n \n}", "function Rs(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}" ]
[ "0.5750213", "0.55510026", "0.5546298", "0.5474404", "0.5468204", "0.54242617", "0.5418602", "0.53442836", "0.52644193", "0.51618147", "0.5148425", "0.5123263", "0.5113483", "0.5106254", "0.50965", "0.50959975", "0.5086063", "0.50602496", "0.50314534", "0.50115806", "0.5009612", "0.49830267", "0.49654797", "0.49440336", "0.49364138", "0.49143732", "0.4905856", "0.48948646", "0.48940802", "0.48928237", "0.48908445", "0.48826748", "0.48618263", "0.48526916", "0.48514387", "0.4851057", "0.48474148", "0.48439655", "0.4827502", "0.48263544", "0.48223662", "0.48030588", "0.4799912", "0.47965991", "0.47909027", "0.4784728", "0.47844008", "0.47839037", "0.47839037", "0.47837588", "0.477141", "0.47703058", "0.47682667", "0.47621357", "0.4759944", "0.47567546", "0.4752117", "0.47515208", "0.47386178", "0.47365242", "0.47136387", "0.47132412", "0.4710501", "0.47096968", "0.47025317", "0.4695768", "0.4691168", "0.468685", "0.46857348", "0.46838686", "0.46838686", "0.46621174", "0.46621174", "0.4661682", "0.4659556", "0.46558434", "0.46526584", "0.46505535", "0.46490684", "0.46480858", "0.46477243", "0.46454704", "0.46454328", "0.46454328", "0.46454328", "0.46454328", "0.4639758", "0.46384963", "0.4637969", "0.46324345", "0.46318847", "0.4627856", "0.46248817", "0.462273", "0.46201736", "0.46189362", "0.46099147", "0.4604281", "0.4603731", "0.46026623", "0.46020317" ]
0.0
-1
Returns a protected route that redirects if not logged in
function ProtectedRoute({ redirectTo, path, component }) { if (!firebase.auth().currentUser) { return <Redirect to={redirectTo}></Redirect>; } else { return <Route exact path={path} component={component}></Route>; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function protectRoute(req, res, next) {\n let isLoggedIn = req.session.user ? true : false;\n if (isLoggedIn) {\n next();\n }\n else {\n res.redirect('/');\n }\n}", "function protectedRoute(req, res, next) {\n if (req.session && req.session.userId) {\n next();\n } else {\n // TODO: redirect user to /login through react router on the UI\n console.log('User is not authenticated.');\n res.redirect('/');\n }\n}", "function checknotau(req,res, next){\n if(req.isAuthenticated()){\n return res.redirect('/')\n }\n next()\n}", "function checkNotAuth(req, res, next) {\n // If authenticated, redirect to Home page\n if (req.isAuthenticated()) {\n return res.redirect('/');\n }\n // If not authenticated, proceed to requested route\n next();\n}", "function checkNotAuthenticated(req, res, next) {\n if (req.isAuthenticated()) {\n return res.redirect('/ratings/admin')\n }\n next()\n}", "function guest(req, res, next){\n if(!req.isAuthenticated()){ // this isAuthenticate is provided from passport\n return next()\n\n }\n return res.redirect('/')\n}", "function checkNotAuthenticated(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n return res.redirect('/')\r\n }\r\n next()\r\n}", "function ProtectedRoute(props) {\n return isLogin() ? <Route {...props} /> : <Redirect to=\"/\" />\n}", "function hasAccess(req, res, next) {\n if (req.isAuthenticated()) {\n return next();\n } \n else\n {\n return res.redirect('/'); \n }\n}", "doRedirectionFilter() {\n const config = {\n failureRedirect: {\n \t student: '/join',\t // if not logged in, go here (student)\n \t employer: '/join' // if not logged in, go here (employer)\n },\n restricted: {\n to: 'EMPLOYERS',\t\t // STUDENTS only on this route\n\t redirectTo: '/dashboard/st' // if not an EMPLOYER, redirect to the student equivalent\n\t\t \t\t\t // This might change to employer categories\n }\n }\n return authRedirectFilter(config, this.context.store, this.context.router)\n }", "function restrict(req, res, next) {\n if (req.session.user) {\n next();\n } else {\n res.redirect('/LoginGateway');\n }\n}", "beforeRouteEnter(to, from, next){\n const loggedIn = true;\n if(loggedIn) next();\n else next('*')\n }", "function authLanding(req, res, next) {\n\n // if user is authenticated, redirect to shipping page\n if (!req.isAuthenticated())\n res.redirect('/');\n\n return next();\n}", "function redirectIfUnauthenticated(req, res, next) {\n if (auth.isAuthenticated(req)) {\n next();\n }\n else if (req.query.play_as_guest) {\n res.redirect('/guest_login?next=' + req.originalUrl);\n }\n else {\n auth.ensureAuthenticated(req, res, next, 'You must log in before you can play!');\n }\n}", "function checkNotAuthenticated(req, res, next) {\n if (req.isAuthenticated()) {\n return res.redirect('/')\n }\n\n next()\n}", "function checkNotAuthenticated(req, res, next) {\n\tif (req.isAuthenticated()) {\n\t\treturn res.redirect('/');\n\t}\n\n\tnext();\n}", "function isLoggedIn(req,res,next){\n if(req.isAuthenticated()) return next()\n res.redirect('/')\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated()) \n return next();\n \n res.redirect('/');\n}", "function isNotLoggedIn(req, res, next) {\n\n // if user is authenticated in the session, carry on \n if (req.isAuthenticated()) {\n res.redirect('/');\n }\n else\n return next();\n // if they are logged in, redirect them to the home page\n}", "function isLoggedIn(req,res,next){\n if(req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function loggedIn(req, res, next) {\n if (req.isAuthenticated()) {\n return next();\n }\n res.redirect('/');\n}", "function checkNotAuthenticated(req, res, next) {\n // If user is logged in\n if (req.isAuthenticated()) {\n return res.redirect(\"/user\");\n }\n next();\n}", "function isLoggedIn(req, res, next) {\r\n if (req.isAuthenticated())\r\n return next();\r\n\r\n res.redirect('/');\r\n}", "function isLoggedIn(req, res, next) {\r\n if (req.isAuthenticated())\r\n return next();\r\n\r\n res.redirect('/');\r\n}", "function redirectIfLoggedIn (req, res, next) {\n if (req.user) return res.redirect('/Schedule');\n return next(); //this is only really useful if the if statement doesnt execute\n}", "function PrivateRoute({ component: RouteComponent, authed, ...rest }) {\n console.log(authed);\n return ( \n <Route\n {...rest}\n render={props =>\n authed === false ? (\n <RouteComponent {...props} /> \n ) : (\n <Redirect to={'/dash/main'} />\n \n )\n }\n />\n );\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n \n res.redirect('/');\n}", "function checkNotAuthenticated(req, res, next) {\n if (req.isAuthenticated()) {\n return res.redirect(\"/blogOpdemy\");\n }\n next();\n }", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/#/');\n }", "redirect() {\n if (get(this, 'session.isAuthenticated')) {\n this.transitionTo('index');\n }\n }", "function requireAut(req, res, next)\n{\n if(!req.isAuthenticated())\n {\n return res.redirect('/login')\n }\n next();\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated()) return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n \n res.redirect('/');\n}", "function PrivateRoute({ Component }) {\n\n return (\n <> {/* isAuthenticated() ? <Component /> : <Redirect to='/' /> */}<Component /> </>\n );\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function requireLogin(req, res, next)\n{\n if(!req.user) res.redirect('/');\n else next();\n}", "function isAuthenticated(){\n return function(req, res, next){\n if (req.isAuthenticated()){\n return next();\n }\n res.redirect('/signin');\n }\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated()) \n \n return next();\n\n res.redirect(\"/\");\n }", "function ProtectedRoute({isLoggedIn: loggedIn, isAuthorised, redirectPath : path, component: Component, ...rest }){\n\treturn (\n\t\t<Route {...rest} render={(props) => {\n\t\t\t// {rest.forEach(el => console.log(el))}\n\t\tconsole.log(isAuthorised)\n\t\t\tif(loggedIn && isAuthorised) {\n\t\t\t\treturn <Component />\n\t\t\t}else {\n\n\t\t\t\treturn <Redirect to={{ pathname :path , state: {from : props.location }}} />\n\t\t\t}\n\t\t}} />\n\n\t);\n}", "function PrivateRoute({ component: Component, ...rest }) {\n const { authenticatedUser } = useContext(Context);\n return (\n <Route\n {...rest}\n render={(props) =>\n authenticatedUser ? (\n <Component {...props} />\n ) : (\n <Redirect\n // code used to redirect user to the original protected URL he was requesting before being authenticated\n to={{\n pathname: \"/signin\",\n state: { from: props.location },\n }}\n />\n )\n }\n />\n );\n}", "function isLoggedIn(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n return next();\r\n }\r\n res.redirect('/');\r\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n }", "function PrivateRoute ({ component: Component, ...rest }) {\n return (\n <Route {...rest} render={props => (\n rest.authedUser\n ? <Component {...props} />\n : <Redirect to={{\n pathname: '/login',\n state: { from: props.location }\n }} />\n )}/>\n )\n}", "function PrivateRoute({ children, ...rest }) {\n return (\n <Route\n {...rest}\n render={({ location }) =>\n token ? ( // Why is token available but not isAuthenticated?\n children\n ) : (\n <Redirect\n to={{\n pathname: \"/\",\n state: { from: location },\n }}\n />\n )\n }\n />\n );\n}", "function isLoggedIn(req, res, next){ \r\n if(req.isAuthenticated()){\r\n return next(); //short circuit by return\r\n }\r\n res.redirect(\"/login\");\r\n\r\n}", "function isnotLoggedIn(req, res, next){\n if(!req.isAuthenticated()){\n return next();\n }else{\n //si está logueado y quiere visitar cierta ruta como la de iniciar sesion lo enviara al profile\n return res.redirect('/profile');\n }\n}", "function isLoggedIn(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n return next();\r\n }\r\n res.redirect('/');\r\n }", "function isLoggedIn(req, res, next) { //Pull this out into a function!!\n if (req.isAuthenticated()) return next();\n\n res.redirect('/');\n }", "function isLoggedIn(req, res, next) {\n\tif (req.isAuthenticated()) {\n res.redirect('/');\n } else {\n return next();\n }\n}", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) {\n return next();\n }\n res.redirect('/log');\n}", "function isLoggedIn(req,res,next)\r\n {\r\n if(req.isAuthenticated()){\r\n return next();\r\n }\r\n res.redirect('/');\r\n }", "function ensureAuthenticated(req, res, next) {\r\n if (req.isAuthenticated()) return next();\r\n if (req.method == 'GET') req.session.returnTo = req.originalUrl;\r\n res.redirect('/');\r\n }", "function isLoggedIn(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n return next();\r\n } else {\r\n res.redirect(\"/\");\r\n }\r\n}", "function forwardAuthenticated(req, res, next) {\n if (!req.isAuthenticated()) {\n return next()\n }\n res.redirect('/tournaments/myTournaments')\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n //res.redirect('/');\n return next();\n}", "function isLoggedIn (req, res, next) {\n if (req.isAuthenticated()) return next()\n res.redirect('/')\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function restrict(req, res, next) {\n // console.log(req.session.username)\n // if (!req.session.username) {\n // res.redirect('/');\n // }\n next()\n}", "function authenticatedUser(req, res, next){\n if(req.isAuthenticated()){\n return next();\n }\n res.redirect('/');\n}", "function PrivateRoute ({component: Component, authed, ...rest}) {\n\n return (\n <Route\n {...rest}\n render={(props) => authed === true\n ? <Component {...props} />\n : <Redirect to={{pathname: '/login'}} />}\n />\n )\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n }", "function authGuard(to, from, next) {\n if (auth.loggedIn()) {\n next();\n } else {\n next('/');\n }\n}", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/')\n }", "function isLoggedIn(req, res, next) {\n\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function PrivateRoute ({component: Component, authed, ...rest}) {\n\n var isAuthed = (localStorage.getItem('user-info') === null)? false : true\n\n console.log(isAuthed);\n\n return (\n \n <Route\n {...rest}\n render={(props) => isAuthed === true\n ? <Component {...props} />\n : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}\n />\n )\n }", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/') // changed from '/login' to '/index'\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function isLoggedIn(req, res, next) {\n if (req.isAuthenticated())\n return next();\n\n res.redirect('/');\n}", "function ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/');\n }", "function checkAuthenticated(req, res, next) {\r\n \r\n if (req.isAuthenticated()) {\r\n return next()\r\n }\r\n res.redirect(\"/\");\r\n \r\n}" ]
[ "0.71365124", "0.7024976", "0.69397354", "0.68692005", "0.68505937", "0.68274766", "0.6802913", "0.67945087", "0.678177", "0.6755551", "0.6747091", "0.67200154", "0.6689696", "0.66874695", "0.6668729", "0.6662668", "0.6598752", "0.6581527", "0.65792596", "0.6579218", "0.6560637", "0.65535444", "0.65495366", "0.65495366", "0.6546934", "0.65462184", "0.6541915", "0.6536239", "0.6529185", "0.65204597", "0.6518492", "0.65182555", "0.6511078", "0.6508442", "0.6503506", "0.65022653", "0.6501888", "0.65012795", "0.6500927", "0.64946645", "0.64944553", "0.6493914", "0.6492748", "0.64807045", "0.6480678", "0.64800745", "0.6479426", "0.64776826", "0.64684576", "0.6466281", "0.64662594", "0.64626276", "0.6462422", "0.64607805", "0.64572287", "0.64568764", "0.6454882", "0.6454882", "0.6454882", "0.6454882", "0.6447495", "0.6446503", "0.6445219", "0.6443952", "0.6443378", "0.6442868", "0.6440341", "0.6440341", "0.6433277", "0.64285004", "0.6425638", "0.6425638", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.64228415", "0.642135", "0.64169073" ]
0.65748066
20
var hero = gameBoard.append('circle').classed('player', true) .attr('cx', (240 gameSettings['heroWidth'])/2) .attr('cy', (125 gameSettings['heroHeight'])/2) .attr("r", 25) .attr('width', gameSettings['heroWidth']) .attr('height', gameSettings['heroHeight']) .attr('fill', heroColor) .call(drag);
function dragmove() { d3.select(this).attr('x', d3.event.x) .attr('y', d3.event.y); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function dragCircle()\n{\n d3.select(this).attr(\"cx\", d3.event.x)\n .attr(\"cy\", d3.event.y);\n}", "function createWorm() \n{\n\n //Create an SVG element for the worm\n var worm = svg.selectAll(\".worm\")\n .data(xyCoords)\n .enter()\n .append(\"circle\")\n .attr(\"class\", \"worm\")\n .attr(\"cx\", function(d) {\n return d.sourceX })\n .attr(\"cy\", function(d) { \n return d.sourceY})\n .attr(\"r\", 4)\n .style(\"fill\", \"black\")\n}", "function dragCircle(event,d){\n //get mouse coordinates\n var xCoordinates = event.x;\n var yCoordinates = event.y;\n //set mouse coordinates on object\n d3.select(this)\n .attr(\"cx\", xCoordinates)\n .attr(\"cy\", yCoordinates);\n // put object on top\n this.parentNode.appendChild(this); // https://stackoverflow.com/a/18362953\n }", "start() {\n this.preDragFill = this.attr(\"fill\");\n this.ox = this.attr(\"cx\");\n this.oy = this.attr(\"cy\");\n this.attr({ fill: config.draggingCircleColor });\n }", "function GO1() {\n var d3put = d3find.append('circle');\n d3put.attr('cx', 50).attr('cy', 50).attr('r', 40).attr('stroke', 'blue').attr('stroke-width', 3).attr('fill', 'white');\n }", "constructor(radius) {\n super(2 * radius, 2 * radius);\n this.shape = \"circle\"; //set shape property\n this.radius = radius; //set radius\n //sets size and position\n let circle = `<div class='shape circle' id='${counter}' style=\"height:${\n this.height\n }px; width:${this.width}px; left:${randomPosition(\n this.width\n )}px; top:${randomPosition(this.height)}px\"></div>`;\n $(\"#board\").append(circle);\n }", "function circle(diameter, fillStyle, strokeStyle, lineWidth, x, y) {\n \n //create the sprite\n let sprite = new Circle(diameter, fillStyle, strokeStyle, lineWidth, x, y)\n \n //Add sprite\n //stage.addChild(sprite)\n \n return sprite\n}", "function GO11() {\n var d3put = d3find.append('circle');\n d3put.attr('cx', 50).attr('cy', 50).attr('r', 40).attr('stroke', 'blue').attr('stroke-width', 3).attr('fill', 'white').attr('id', 'g01');\n}", "function drawPlayer() {\n fill(250,20,50,playerHealth);\n ellipse(playerX,playerY,playerRadius*2,playerRadius*2);\n}", "function createCircle(x,y,r,stroke,id){\n var circle = new createjs.Shape();\n circle.graphics.setStrokeStyle(4).beginStroke(stroke).drawCircle(0, 0, r);\n circle.x = x;\n circle.y = y;\n circle.name = \"circle\";\n circle.id = id;\n circle.on(\"pressmove\",drag);\n text = new createjs.Text(\"(\"+x+\",\"+y+\")\", \"13px Arial\", \"#000000\"); \n text.name = \"label\";\n text.textAlign = \"center\";\n text.textBaseline = \"middle\";\n text.x = x;\n text.y = y-25;\n text.id = id;\n circle.textObj = text;\n stage.addChild(circle, text); \n}", "function drawPlayer () {\r\n rect(player.x, player.y, player.w, player.h, player.col, \"fill\");\r\n}", "function drawCircle(radius, x, y) { svg.append(\"circle\").attr(\"fill\", \"red\").attr(\"r\", radius).attr(\"cx\", x).attr(\"cy\", y); }", "function appendCircle(layer, prefix, trainIndex, stopIndex, cx, cy, colorType) {\n var circle = d3.select(\"#\" + prefix + '_' + trainIndex + '_' + stopIndex);\n if (circle[0][0] == null)\n layer.append(\"circle\")\n .attr(\"train-index\", trainIndex)\n .attr(\"stop-index\", stopIndex)\n .attr(\"station-index\", trains[trainIndex].stops[stopIndex].stationIndex)\n .attr(\"color-type\", colorType)\n .attr(\"id\", prefix + '_' + trainIndex + '_' + stopIndex)\n .attr(\"cx\", cx)\n .attr(\"cy\", cy)\n .attr(\"r\", 2)\n .attr(\"cx-backup\", cx)\n .attr(\"fill\", \"white\")\n .attr(\"stroke-width\",2)\n .attr(\"vector-effect\", \"non-scaling-stroke\")\n .attr(\"stroke\", trainColor[colorType][trains[trainIndex].type])\n .style(\"opacity\", 1)\n .on(\"mouseover\", mouseoverTrainCircle)\n .on(\"mouseout\", mouseoutTrainCircle)\n .call(dragTrainCircleListener);\n else\n circle\n .attr(\"train-index\", trainIndex)\n .attr(\"stop-index\", stopIndex)\n .attr(\"station-index\", trains[trainIndex].stops[stopIndex].stationIndex)\n .attr(\"color-type\", colorType)\n .attr(\"id\", prefix + '_' + trainIndex + '_' + stopIndex)\n .attr(\"cx\", cx)\n .attr(\"cy\", cy)\n .attr(\"r\", 2)\n .attr(\"cx-backup\", cx)\n .attr(\"fill\", \"white\")\n .attr(\"stroke-width\", 1)\n .attr(\"vector-effect\", \"non-scaling-stroke\")\n .attr(\"stroke\", trainColor[colorType][trains[trainIndex].type])\n .style(\"opacity\", 1)\n .on(\"mouseover\", mouseoverTrainCircle)\n .on(\"mouseout\", mouseoutTrainCircle)\n .call(dragTrainCircleListener);\n}", "function createPos(turnData, selectName, fill, attackRange) {\n\n let svg = d3.select(\"#svgViz\");\n\n // /* Draw the position */\n svg.selectAll(selectName)\n .data(turnData[selectName])\n .enter()\n .append(\"circle\")\n .attr(\"cx\", function (d) {\n return x(d[\"posX\"]);\n })\n .attr(\"cy\", function (d) {\n return y(d[\"posY\"]);\n })\n .attr(\"id\", function (d) {\n return d[\"id\"];\n })\n .attr(\"fill\", fill)\n .attr(\"class\", selectName)\n .attr(\"r\", radius)\n\n if (selectName == \"zombies\" || selectName == \"Ash\") {\n svg.selectAll(selectName + \"Line\")\n .data(turnData[selectName])\n .enter()\n .append(\"line\")\n .attr(\"x1\", function (d) {\n return x(d[\"posX\"]);\n })\n .attr(\"x2\", function (d) {\n return x(d[\"targetX\"]);\n })\n .attr(\"y1\", function (d) {\n return y(d[\"posY\"]);\n })\n .attr(\"y2\", function (d) {\n return y(d[\"targetY\"]);\n })\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", fill)\n .attr(\"opacity\", \"0.5\")\n .attr(\"stroke-width\", lineStroke)\n .attr(\"class\", selectName + \"Line\")\n\n // /* Draw the range */\n svg.selectAll(selectName)\n .data(turnData[selectName])\n .enter()\n .append(\"ellipse\")\n .attr(\"cx\", function (d) {\n return x(d[\"posX\"]);\n })\n .attr(\"cy\", function (d) {\n return y(d[\"posY\"]);\n })\n .attr(\"fill\", fill)\n .attr(\"opacity\", 0.3)\n .attr(\"class\", selectName + \"Attack\")\n .attr(\"rx\", function (d) {\n if (selectName != \"Ash\") {\n return attackRange * ratioX;\n } else {\n return isDead(d[\"isDead\"], attackRange * ratioX);\n }\n })\n .attr(\"ry\", function (d) {\n if (selectName == \"Ash\") {\n return attackRange * ratioY;\n } else {\n return isDead(d[\"isDead\"], attackRange * ratioY);\n }\n })\n }\n\n if (selectName == \"zombies\" || selectName == \"humans\") {\n svg.selectAll(selectName + \"Text\")\n .data(turnData[selectName])\n .enter()\n .append(\"text\")\n .attr(\"x\", function (d) {\n return x(d[\"posX\"]) - radius / 2;\n })\n .attr(\"y\", function (d) {\n return y(d[\"posY\"]) + radius / 2;\n })\n .text(function (d) {\n return d[\"id\"];\n })\n .attr(\"class\", selectName + \"Text\")\n .attr(\"font-size\", fontSize)\n }\n\n printStatus(turnData)\n}", "function createMonster(x, y) {\r\n\r\n var monster = svgdoc.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\r\n svgdoc.getElementById(\"monsters\").appendChild(monster);\r\n monster.setAttribute(\"x\", x);\r\n monster.setAttribute(\"y\", y);\r\n var x_ = Math.floor(Math.random()*700);\r\n var y_ = Math.floor(Math.random()*500);\r\n// moveMonster(monster, x, y, x_, y_);\r\n monster.setAttributeNS(\"http://www.w3.org/1999/xlink\", \"xlink:href\", \"#monster\");\r\n // var monsterleft = svgdoc.getElementById(\"monsterleft\");\r\n // monsterleft.setAttribute(\"transform\", \"translate(\" +MONSTER_SIZE.w + \", 0) scale(-1,1)\");\r\n\r\n}", "function drawCircle(data,svg){\n // Makes the cirlce html, and runs the updates\n var circle = svg.selectAll(\"circle\").data(data.v, function(d){\n return d;\n });\n\n // Removes circles if there is only one (like in the python example)\n circle.exit().remove();\n\n // Adds a circle, using the data from data as the radius\n circle.enter().append(\"circle\").\n attr(\"cx\",function(d,i){return i * 100 + 100;})\n .attr(\"cy\",100)\n .attr(\"r\",function(d){return d * 2 + 20\n });\n \n}", "function Circle(position, move, color) {\nthis.position = createVector(position.x, position.y);\nthis.speed = createVector(move.x, move.y);\nthis.move2 = random(0);\nthis.life = 200;\n}", "function dropCircle() {\n let posX = random(80, window.innerWidth - 80);\n let size = random(sizes);\n let color = colorStrings[index % colorStrings.length];\n //circles.push(new Circle(posX, 10, size / 2, color));\n circles.push(new Circle(posX, 10, size / 2, color));\n //send the data to server\n var data = { index: index, mode: \"circle\" };\n socket.emit(\"trigger\", data);\n //socket.emit(\"playerIndex\",index);\n}", "function draw_circle() {\r\n\t$('#drag_resize').css({\"display\":\"block\" ,'top' : 0+'px', 'left' : 0+'px'});\t\r\n\t$('#drag_resize').draggable( \"enable\"); \r\n\t$('#choose_area').css({\"display\":\"table-cell\"});\r\n\t$('#delete_circle').css({\"display\":\"table-cell\"});\r\n}", "function dragon(x, y, d) {\n fill(color(0, 100, 100, 20))\n ellipse(x, y, 10 * d)\n\n fill(color(285, 55, 67, 20)) // dark purple\n ellipse(x, y, 5 * d)\n\n // ensure size s is more than zero\n if (d > 0) {\n var x1 = x + (8 * d * cos(35 * d * 1.5 * abs((frameCount/100) % 100 - 50)));\n var y1 = y + (8 * d * sin(35 * d * 1.5 * abs((frameCount/100) % 100 - 50)));\n var x2 = x - (8 * d * cos(35 * d * 1.5 * abs((frameCount/100) % 100 - 50)));\n var y2 = y - (8 * d * sin(35 * d * 1.5 * abs((frameCount/100) % 100 - 50)));\n\n dragon(x1, y1, d - 1);\n dragon(x2, y2, d - 1);\n }\n\n}", "function addCircle(){\n\t\t\tvar newCirc = new fabric.Circle({\n\t\t\ttop: 100, \n\t\t\tleft: 100, \n\t\t\tradius: 75,\t\t\t\n fill : 'rgb(200,200,200)'\n\t\t\t});\t\n\t\t\tcanvas.add(newCirc).setActiveObject(newCirc);\n\t\t\tselectObjParam();\n\t\t\tcanvas.renderAll();\t\t\n\n\t\t}", "function addArduino() {\n // Create a new div \n var maincanvas= document.getElementById(\"maincanvas\")\n var arduino = document.createElement('div')\n arduino.className = 'arduinos';\n arduino.innerHTML = '<img src=\"assets/images/arduino.png\" width=400px/>'\n // Add it to the main canvas\n maincanvas.appendChild(arduino);\n $(arduino).draggable({cursor: \"crosshair\"})\n\n}", "function newCircle() {\n x = random(windowWidth);\n y = random(windowHeight);\n r = random(255);\n g = random(255);\n b = random(255);\n}", "function drawPlayer() {\n fill(playerFill, playerHealth);\n ellipse(playerX, playerY, playerRadius * 2);\n}", "function drawRectangle (element, player) {\n element.append('svg')\n .attr('width', 15)\n .attr('height', 16)\n .append('rect')\n .attr('y', 1)\n .attr('width', 15)\n .attr('height', 15)\n .style('fill', color(player))\n .style('stroke', 'black')\n .style('stroke-width', 1)\n }", "function circleGrow(){\nxSize = xSize + 30;\nySize = ySize + 30;\n}", "function drag_player (ev) {\n\toffsetX = ev.offsetX - ev.offsetX * offset;\n\toffsetY = ev.offsetY - ev.offsetY * offset;\n\tev.dataTransfer.setData('rod_type', '1001');\n\tev.dataTransfer.setData('rod_player_id', 'rod_player_' + rod_num);\n\tvar clone_rod_player = ev.target.cloneNode(true);\n\tclone_rod_player.setAttribute('style', 'display:none');\n\tclone_rod_player.setAttribute('id', 'rod_player_' + rod_num);\n\trod_num++;\n\tdocument.getElementById('main_board').appendChild(clone_rod_player);\n}", "function walkingCircle() {\n addCircle(150, \"green\");\n addCircle(300, \"blue\");\n addCircle(600, \"purple\");\n addCircle(searchRadius, \"black\");\n}", "function modeMove()\n{\n d3.selectAll(\"circle\").call(d3.behavior.drag()\n .origin(circleOrigin)\n .on(\"drag\", dragCircle));\n d3.selectAll(\"path\").call(d3.behavior.drag()\n .on(\"drag\", dragPath));\n}", "constructor() {\n this.x = random(width);\n this.y = random(-2000, -10);\n this.dx = random(-10, 10);\n this.dy = random(5, 6);\n this.size = random(20, 40);\n this.color = color(random(200, 255));\n this.touchingGround = false;\n this.shape = \"*\";\n //Very similar to raindrop\n }", "function modeResize()\n{\n d3.selectAll(\"circle\").call(d3.behavior.drag().on(\"drag\", resize));\n}", "function drawPanel(){\n circleGroup = svg.append(\"g\");\n\n circleGroup.append(\"rect\")\n .attr(\"class\", \"panel\")\n .attr(\"id\", \"coverpanel\")\n .attr(\"x\",\"0\")\n .attr(\"y\",\"375\")\n .attr(\"width\",\"1100\")\n .attr(\"height\",\"300\")\n\n circleGroup.append(\"rect\")\n .attr(\"class\", \"panel panelButton\")\n .attr(\"x\",\"0\")\n .attr(\"y\",\"375\")\n .attr(\"rx\",\"5\")\n .attr(\"ry\",\"5\")\n .attr(\"width\",\"100\")\n .attr(\"height\",\"30\");\n\n circleGroup.append(\"text\")\n .attr(\"class\", \"panel panelButton panelButtonText\")\n .attr(\"id\", \"panel\")\n .attr(\"x\",\"8\")\n .attr(\"y\",\"395\")\n .text(\"Show data\");\n\n circleGroup.attr(\"id\",\"grouppanel\");\n}", "function drawPlayer() {\n // The red stroke mimics a glow\n // The stroke will determine the player's health\n stroke(255, 0, 0, playerHealth)\n strokeWeight(20);\n //the player will start red but becomes more and more\n // orange whenever it eats a firefly\n // Thanks to the firegreen variable\n fill(255, firegreen, 0);\n ellipse(playerX, playerY, playerRadius * 2);\n}", "circle() {\n const context = GameState.current;\n\n Helper.strewnSprite(\n Helper.getMember(GroupPool.circle().members),\n { y: context.game.stage.height },\n { y: 2 },\n (sprite) => {\n this._tweenOfCircle(context, sprite);\n }\n );\n }", "function appendPoint(x,y,name,radius,theclass) {\r\n\r\n svg.append(\"svg:circle\")\r\n .attr(\"class\",theclass)\r\n .attr(\"cx\", x)\r\n .attr(\"cy\", y)\r\n .attr(\"r\", radius)\r\n .attr(\"title\", name);\r\n\r\n }", "function drawPlayer(pt, radius = 15) {\n noStroke()\n fill(\"red\")\n circle(pt.x, pt.y, radius)\n}", "draw(){\n const panel = document.getElementById('graphpanel')\n const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle')\n circle.setAttribute('cx', this.x + this.size / 2)\n circle.setAttribute('cy', this.y + this.size / 2)\n circle.setAttribute('r', this.size / 2)\n circle.setAttribute('fill', this.color)\n panel.appendChild(circle)\n }", "function draw() {\n //Individual\n setupYears(startYear, endYear);\n playerCircles = individual.selectAll(\".playerCircle\")\n .data(csvData)\n .enter().append(\"circle\")\n .attr(\"r\", 0)\n .attr(\"cx\", function(d) { return d.xPosition; })\n .attr(\"cy\", height/2)\n .style(\"fill\", function(d) { return color(d.Rnd); })\n .attr(\"class\", \"playerCircle\")\n .attr(\"title\", tooltipText)\n .on(\"mouseover\", mouseOver)\n .on(\"mouseout\", mouseOut);\n attachTooltips();\n redraw(0);\n \n\n initSlider(startYear, endYear);\n initDecadeLinks(startYear, endYear);\n \n var counts = positions.map(function(d) { return d.count; });\n positionColor.domain(d3.extent(counts));\n positionCircles.each(function(d) {\n d3.select(this).style(\"fill\", function() { return positionColor(d.count); });\n });\n heatmapLegends.selectAll(\".label\").each(function(d) {\n d3.select(this).text(function() { return \"(\" + d.count + \")\"; });\n });\n \n}", "function move(d) {\n\t\tvar currentx = parseFloat(d3.select(this).attr(\"cx\")),\n\t\t \t//currenty = parseFloat(d3.select(this).attr(\"cy\")),\n\t\t\tradius = d.r;\n\n\t\t//Randomly define which quadrant to move next\n\t\tvar sideX = currentx > 0 ? -1 : 1,\n\t\t\tsideY = Math.random() > 0.5 ? 1 : -1,\n\t\t\trandSide = Math.random();\n\n\t\tvar newx,\n\t\t\tnewy;\n\n\t\t//Move new locations along the vertical sides in 33% of the cases\n\t\tif (randSide > 0.66) {\n\t\t\tnewx = sideX * 0.5 * SQRT3 * hexRadius - sideX*radius;\n\t\t\tnewy = sideY * Math.random() * 0.5 * hexRadius - sideY*radius;\n\t\t} else {\n\t\t\t//Choose a new x location randomly, \n\t\t\t//the y position will be calculated later to lie on the hexagon border\n\t\t\tnewx = sideX * Math.random() * 0.5 * SQRT3 * hexRadius;\n\t\t\t//Otherwise calculate the new Y position along the hexagon border \n\t\t\t//based on which quadrant the random x and y gave\n\t\t\tif (sideX > 0 && sideY > 0) {\n\t\t\t\tnewy = hexRadius - (1/SQRT3)*newx;\n\t\t\t} else if (sideX > 0 && sideY <= 0) {\n\t\t\t\tnewy = -hexRadius + (1/SQRT3)*newx;\n\t\t\t} else if (sideX <= 0 && sideY > 0) {\n\t\t\t\tnewy = hexRadius + (1/SQRT3)*newx;\n\t\t\t} else if (sideX <= 0 && sideY <= 0) {\n\t\t\t\tnewy = -hexRadius - (1/SQRT3)*newx;\n\t\t\t}//else\n\n\t\t\t//Take off a bit so it seems that the circles truly only touch the edge\n\t\t\tvar offSetX = radius * Math.cos( 60 * Math.PI/180),\n\t\t\t\toffSetY = radius * Math.sin( 60 * Math.PI/180);\n\t\t\tnewx = newx - sideX*offSetX;\n\t\t\tnewy = newy - sideY*offSetY;\n\t\t}//else\n\n\t\t//Transition the circle to its new location\n\t\td3.select(this)\n\t\t\t.transition(\"moveing\")\n\t\t\t.duration(3000 + 4000*Math.random())\n\t\t\t.ease(\"linear\")\n\t\t\t.attr(\"cy\", newy)\n\t\t\t.attr(\"cx\", newx)\n\t\t\t.each(\"end\", move);\n\n\t}", "function Circle(x, y) {\r\n this.position = createVector(x, y); // Position of the circles\r\n this.getColor = floor(random(360)); // Random color of the circles. floor() rounds the random number down to the closest int.\r\n this.speed = random(-1, -3); // Randomized speed that only goes up\r\n this.sway = random(-2, 2); // An experimental speed for the x position, wasn't used in the end\r\n this.d = random(25,100); // The size of the circles is random\r\n\r\n this.show = function() {\r\n if(startCol == 0) {\r\n fill(this.getColor, 100, 100); // Fills with a random color\r\n this.getColor+=colorSpeed; // The color will change over time\r\n\r\n\t\t\tif (this.getColor >= 360) {\r\n\t\t\t\tthis.getColor = 0;\r\n\t\t\t}\r\n }\r\n\r\n this.move = function() {\r\n this.position.y += this.speed; // The random speed for the Circle\r\n //this.position.x += this.sway; // If this is activated the circles will go in directions other than straight\r\n }\r\n\r\n ellipse(this.position.x, this.position.y, this.d, this.d); // The circles are drawn\r\n }\r\n}", "function gameSetup(data) {\n //console.log(subject);\n\n /*********************\n * Browser Settings *\n *********************/\n\n // Initializations to make the screen full size and black background\n $('html').css('height', '98%');\n $('html').css('width', '100%');\n $('html').css('background-color', 'black')\n $('body').css('background-color', 'black')\n $('body').css('height', '98%');\n $('body').css('width', '100%');\n\n // UNCOMMENT HERE IF YOU WANT TO SHOW POINTER TO MAKE AN ILLUSTRATIVE VIDEO\n //if (showPointer == 0) {\n // Hide the mouse from view \n $('html').css('cursor', 'url(images/transparentcursor.png), auto');\n $('body').css('cursor', 'url(images/transparentcursor.png), auto;');\n //} else {\n // show mouse as pointer (for recording example trials)\n // $('html').css('cursor', 'pointer');\n // $('body').css('cursor', 'pointer');\n //}\n\n // SVG container from D3.js to hold drawn items\n svgContainer = d3.select(\"body\").append(\"svg\")\n .attr(\"width\", \"100%\")\n .attr(\"height\", \"100%\").attr('fill', 'black')\n .attr('id', 'stage')\n .attr('background-color', 'black');\n\n // Getting the screen resolution\n screen_height = window.screen.availHeight;\n screen_width = window.screen.availWidth;\n\n // Calling update_cursor() everytime the user moves the mouse\n $(document).on(\"mousemove\", update_cursor);\n\n // Calling advance_block() everytime the user presses a key on the keyboard\n $(document).on(\"keydown\", advance_block);\n\n // Experiment parameters, subject_ID is no obsolete\n subject_ID = Math.floor(Math.random() * 10000000000);\n\n /***************************\n * Drawn Element Properties *\n ***************************/\n\n // Setting the radius from center to target location \n target_dist = screen_height/4;\n trial_type;\n\n\n // Setting parameters and drawing the center start circle\n start_x = screen_width/2;\n start_y = screen_height/2;\n start_radius = Math.round(target_dist * 4.5 / 80.0);\n start_color = 'lime';\n\n svgContainer.append('circle')\n .attr('cx', start_x)\n .attr('cy', start_y)\n .attr('r', start_radius)\n .attr('fill', 'none')\n .attr('stroke', start_color)\n .attr('stroke-width', 2)\n .attr('id', 'start')\n .attr('display', 'none');\n\n\n // Setting parameters and drawing the target \n target_x = screen_width/2;\n target_y = Math.round(screen_height/10 * 2);\n target_radius = Math.round(target_dist * 4.5/80.0);\n target_color = 'magenta';\n\n svgContainer.append('circle')\n .attr('cx', target_x)\n .attr('cy', target_y)\n .attr('r', target_radius)\n .attr('fill', target_color)\n .attr('id', 'target')\n .attr('display', 'none');\n\n /* Initializing variables for:\n - Coordinates of the mouse \n - Coordinates where the mouse crosses the target distance\n - Radius from center to hand coordinates\n - Coordinates of the displayed cursor (different from mouse if rotated)\n - Size of the displayed cursor\n */\n hand_x = 0;\n hand_y = 0;\n hand_fb_x = 0; \n hand_fb_y = 0;\n r = 0; \n cursor_x = 0;\n cursor_y = 0;\n cursor_radius = Math.round(target_dist * 1.75 * 1.5/80.0);\n cursor_color = 'lime';\n search_color = 'yellow';\n\n mousepos_x = new Array(200).fill(-1); // only take up to 1 s of data\n mousepos_y = new Array(200).fill(-1);\n mousepos_x[0] = [start_x];\n mousepos_y[0] = [start_y];\n mousetm = new Array(200).fill(-1);\n mousetm[0] = [0];\n positer = 1;\n elapsedTime = NaN; // initialize as NaN, but only update when checking the time in the \"MOVING\" phase\n curTime = NaN;\n\n instrucTimeLimit = 60000; // 1 min\n ititimelimit = 90000; // 1.5 mins\n //instrucTimeLimit = 30000; // 30 s for testing\n //ititimelimit = 30000; // 30 s for testing\n\n // Drawing the displayed cursor \n svgContainer.append('circle')\n .attr('cx', hand_x)\n .attr('cy', hand_y)\n .attr('r', cursor_radius)\n .attr('fill', cursor_color)\n .attr('id', 'cursor')\n .attr('display', 'block');\n\n searchRad = screen_width/2;\n // Drawing the search ring that expands and contracts as users search for the start circle (currently unemployed)\n svgContainer.append('circle')\n .attr('cx', start_x)\n .attr('cy', start_y)\n .attr('r', searchRad)\n .attr('fill', 'none')\n .attr('stroke', 'search_color')\n .attr('stroke-width', 2)\n .attr('id', 'search_ring')\n .attr('display', 'none');\n\n // The between block messages that will be displayed\n // **TODO** Update messages depending on your experiment\n messages = [[\"Dummy Message Test\"],\n [\"The green dot will now be visible while you move towards the target.\", // Message displayed when bb_mess == 1\n \"Quickly move your green dot to the target.\",\n \"Press 'b' when you are ready to proceed.\"],\n [\"This is an instruction understanding check, you may proceed ONLY if you choose the correct choice.\", // Message displayed when bb_mess == 2\n \"Choosing the wrong choice will result in early game termination and an incomplete HIT!\",\n \"Press 'a' if you should ignore the green dot and aim directly towards the target.\",\n \"Press 'b' if you should be aiming away from the target.\"],\n [\"The green dot will now be hidden.\", // bb_mess == 3\n \"Continue aiming DIRECTLY towards the target.\",\n \"Press SPACE BAR when you are ready to proceed.\"],\n [\"This is an attention check.\", // bb_mess == 4\n \"Press the key 'e' on your keyboard to CONTINUE.\",\n \"Pressing any other key will result in a premature game termination and an incomplete HIT!\"],\n [\"This is an attention check.\", // bb_mess == 5\n \"Press the key 'a' on your keyboard to CONTINUE.\",\n \"Pressing any other key will result in a premature game termination and an incomplete HIT!\"],\n [\"The green dot will no longer be under your control while you move towards the target.\", // bb_mess == 6\n \"IGNORE the green dot as best as you can and continue aiming DIRECTLY towards the target.\",\n \"This will be a practice trial.\",\n \"Press SPACE BAR when you are ready to proceed.\"]];\n\n // Setting size of the displayed letters and sentences\n line_size = Math.round(screen_height/30)\n message_size = String(line_size).concat(\"px\"); \n\n // initialize a timer for starting the experiment\n instrucTimeoutTimer = setTimeout(instrucTimedOut, instrucTimeLimit); // kick subject if they take too long to read the instructions\n\n // Setting up first initial display once the game is launched \n // **TODO** Update the '.text' sections to change initial displayed message\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/2 - line_size)\n .attr('fill', 'white')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'message-line-1')\n .attr('display', 'block')\n .text('Move the green dot to the center.');\n\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/2)\n .attr('fill', 'white')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'message-line-2')\n .attr('display', 'block')\n .text('The green dot will be visible during your reach.');\n\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/2 + line_size)\n .attr('fill', 'white')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'message-line-3')\n .attr('display', 'block')\n .text('Quickly move your green dot to the target.');\n\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/2 + line_size * 2)\n .attr('fill', 'white')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'message-line-4')\n .attr('display', 'block')\n .text('Press SPACE BAR when you are ready to proceed.');\n\n // Setting up parameters and display when reach is too slow\n too_slow_time = 300; // in milliseconds\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/2)\n .attr('fill', 'orange')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'too_slow_message')\n .attr('display', 'none')\n .text('Too Slow'); \n\n // Parameters and display for when users take too long to locate the center\n search_too_slow = 10000; // in milliseconds\n svgContainer.append('text')\n .attr('text-anchor', 'middle')\n .attr('x', screen_width/2)\n .attr('y', screen_height/3 * 2)\n .attr('fill', 'white')\n .attr('font-family', 'Verdana')\n .attr('font-size', message_size)\n .attr('id', 'search_too_slow')\n .attr('display', 'none')\n .text('The yellow circle gets smaller as your cursor approaches the starting circle (green).');\n\n // Parameters and display for the reach counter located at the bottom right corner\n counter = 1;\n totalTrials = target_file_data.numtrials;\n svgContainer.append('text')\n .attr('text-anchor', 'end')\n .attr('x', screen_width/20 * 19)\n .attr('y', screen_height/20 * 19)\n .attr('fill', 'white')\n .attr('font-size', message_size)\n .attr('id', 'trialcount')\n .attr('display', 'none')\n .text('Reach Number: ' + counter + ' / ' + totalTrials); \n \n /*****************\n * Task Variables *\n *****************/\n\n // Reading the json target file into the game\n target_file_data = data;\n rotation = target_file_data.rotation; // degrees\n target_angle = target_file_data.tgt_angle; //degrees\n online_fb = target_file_data.online_fb;\n endpt_fb = target_file_data.endpoint_feedback;\n clamped_fb = target_file_data.clamped_fb;\n between_blocks = target_file_data.between_blocks;\n target_jump = target_file_data.target_jump;\n num_trials = target_file_data.numtrials;\n target_size = target_file_data.tgt_size;\n\n // Initializing trial count\n trial = 0;\n\n // The distance from start at which they can see their cursor while searching in between trials\n search_tolerance = start_radius * 4 + cursor_radius * 4;\n\n // Calculated hand angles\n hand_angle = 0;\n hand_fb_angle = 0;\n\n // Timing Variables\n rt = 0; // reaction time\n mt = 0; // movement time\n search_time = 0; // time to reset trial (includes hold time)\n feedback_time = 50; // length of time feedback remains (ms)\n feedback_time_slow = 750; // length of \"too slow\" feedback\n hold_time = 500; // length of time users must hold in start before next trial (ms)\n \n // Initializing timer objects and variables\n hold_timer = null;\n fb_timer = null;\n\n // Variable to start clock for calculating time spent in states\n begin; \n /* Flag variables for\n - Whether or not hand is within start circle\n - Whether or not previous reach was too slow\n */\n timing = true; \n if_slow = false; \n\n // Game Phase Flags\n SEARCHING = 0; // Looking for the center after a reach\n HOLDING = 1; // Holding at start to begin the next target\n SHOW_TARGETS = 2; // Displaying the target\n MOVING = 3; // The reaching motion \n FEEDBACK = 4; // Displaying the feedback after reach\n BETWEEN_BLOCKS = 5; // Displaying break messages if necessary\n END_GAME = 1000; // I think this just needs to be defined\n game_phase = BETWEEN_BLOCKS;\n\n // Initializing between block parameters\n reach_feedback;\n bb_counter = 0;\n bb_mess = between_blocks[0];\n\n // Flags to determine whether we are showing the target and cursor (not mouse)\n target_invisible = true; // for clicking to see target\n cursor_show = false;\n\n //setTimeout(gameTimedOut, 30000); // 30s timeout for testing\n //gameTimer = setTimeout(gameTimedOut, 3600000); // one hour timeout\n\n // have the targets centered about random locations\n angleadd = Math.floor(Math.random()*360)+1;\n\n}", "function addCircle(chart) {\n if (this.circle) {\n $(this.circle.element).remove();\n }\n this.circle = chart.renderer.circle(10, 440, 430).attr({\n fill: 'transparent',\n stroke: 'black',\n 'stroke-width': 1\n });\n this.circle.add();\n}", "function drag_start(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n \n}", "function dragStart(d) {\n let draggedNode = d3.select(this).select('circle');\n if (!draggedNode.classed('fixed')) {\n draggedNode.classed('fixed', true);\n }\n\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n }", "constructor() {\n this.x = random(width);\n this.y = collectionHeight;\n this.dx = 0.01;\n this.dy = 5;\n this.radius = random(3, 8);\n this.color = color(180, 180, 190, 80);\n this.touchingGround = false;\n //I mean touchingTop, but to re-use functions, it had to be called touchingGround :(\n }", "show(){\n fill(0)\n stroke(255)\n circle(this.x,this.y,this.d)\n }", "function mouseoverCircle() {\n\n\t// Get circle\n\tvar circle = d3.select(this);\n\n\t// Display activated circle\n\tcircle.attr(\"r\", circle.attr(\"r\") * circleEnlargeConstant);\n\n}", "function drawCardFrame(position)\n{\n\tvar x, y;\n\t\n\t//Setting the positions of x, y based on the player's name.\n\t\n\tif (position == \"dealer\")\n\t{\n\t\t//\n\t\tx = 204;\n\t\ty = 40;\n\t}\n\telse if (position == \"player\")\n\t{\n\t\t//\n\t\tx = 204;\n\t\ty = 379;\n\t\t//-turn*cardHeight*0.25;\n\t}\n\telse if (position == \"bot\")\n\t{\n\t\tx = 204;\n\t\ty = 210;\n\t\t//-turn*cardHeight*0.25;\n\t}\n\t//Creating a new SVG element, which is a rectangle, in this case...\n\tvar newFrame = createSVGElement(\"rect\");\n\t//...setting its coordinates...\n\t\tnewFrame.setAttributeNS(null, \"x\", x - 5);\n\t\tnewFrame.setAttributeNS(null, \"y\", y - 5);\n\t//...making it a bit rounded...\t\n\t\tnewFrame.setAttributeNS(null, \"rx\", 5);\n\t\tnewFrame.setAttributeNS(null, \"ry\", 5);\n\t//...defining its height and width...\t\n\t\tnewFrame.setAttributeNS(null, \"width\", cardWidth + 10);\n\t\tnewFrame.setAttributeNS(null, \"height\", cardHeight + 10);\n\t//...colouring it...\n\t\tnewFrame.setAttributeNS(null, \"style\", \"stroke-width:1; stroke: yellow; fill: green\");\n\t//...and when it is all done, it is appended to the main SVG element.\n\t\t\n\tmySVG.appendChild(newFrame);\n}", "function circle(x, y, px, py) {\n //this is the speed part making the size be determined by speed of mouse\n var distance = abs(x-px) + abs(y-py);\n stroke(r, g, b);\n strokeWeight(2);\n //first set of variables for bigger circle\n r = random(255);\n g = random(255);\n b = random(255);\n\n//second set of colours so the inner circle is different colour or else it is the same\n r2 = random(255);\n g2 = random(255);\n b2 = random(255);\n //this is the big circle\n fill(r, g, b);\n ellipse(x, y, distance, distance);\n //this is the smaller inner circle\n fill(r2, g2, b2);\n ellipse(x, y, distance/2, distance/2);\n}", "function Circle(speed, width, xPos, yPos) {\n this.speed = speed\n this.width = width\n this.xPos = xPos\n this.yPos = yPos\n this.dx = Math.floor(Math.random() * 2) + 1\n this.dy = Math.floor(Math.random() * 2) + 1\n this.opacity = 0.05 + Math.random() * 0.5;\n this.isEaten = false\n this.color = colors[Math.floor(Math.random() * numColors - 1)]\n\n }", "function setup() { \n createCanvas(parseInt(prompt(\"Insert a number for the Width\")),parseInt(prompt(\"Insert a number for the Height\"))); //Creates the screen for the object to appear\n background(20,255,46); //Create the screen background color\n frameRate(50); //Determines how fast the object moves\n makeCircles();\n}", "function Fruit() {\n this.x = random(0, width);\n this.y = random(0, height);\n\n this.display = function() {\n stroke(255);\n fill(random(0,255),random(0,255),random(0,255)); //added random rgb colors \n ellipse(this.x, this.y, 24, 24);\n\n }\n//function to move objects\n this.move = function() {\n this.x = this.x + random(-1, 2); \n this.y = this.y + random(-1, 2);\n\n }\n}", "function letsDraw() {\n $(\"<div class = 'new-circles'\" + whereTo() + \"></div>\").appendTo('.back');\n }", "function draw() {\n background(0);\n\n move(); /// moves the circle\n wrap(); /// wraps the cicle (makes it start at the beginning of the screen)\n display(); //displays the circle\n\n}", "function playerMoving() {\n console.log('playerMoving')\n $squares.removeClass('drake-player1')\n $squares.eq(playerPosition).addClass('drake-player1')\n }", "move(x, y) {\n return this.attr('d', this.array().move(x, y));\n }", "draw() {\n this.xPos = Math.floor(Math.random() * 900 + 200);\n this.yPos = -5;\n this.el.style.position = 'absolute';\n this.el.style.left = this.xPos + 'px';\n this.el.style.top = this.yPos + 'px';\n\n container.appendChild(this.el);\n }", "function createCircles(number){\n //Generate number of circles told\n for (let i = 0; i < number; i++){\n let x = 0;\n let y = 0;\n \n switch(Math.floor(getRandom(0,4))){\n //left side of screen\n case 0:\n x = -10;\n y = Math.floor(getRandom(5,710));\n break;\n //right side of screen\n case 1:\n x = 1290;\n y = Math.floor(getRandom(5,710));\n break;\n //top of screen\n case 2:\n y = -10;\n x = Math.floor(getRandom(5,1270));\n break;\n //bottom of screen\n case 3:\n y = 730;\n x = Math.floor(getRandom(5,1270));\n break;\n }\n\n let circle = new Circle(Math.floor(getRandom(20,60)),0x0000FF,x,y,Math.floor(getRandom(20,80)),time);\n circles.push(circle);\n gameScene.addChild(circle);\n }\n}", "function moveCircle(x, y) {\n\t\n\t// select corresponding rover circle // see filter or direct selection https://d3indepth.com/selections/ && https://stackoverflow.com/questions/20414980/d3-select-by-attribute-value\n\tvar selectedCircle = d3.select( \"#vehicule\" + currentVehicule._id ); \n\tselectedCircle.transition()\n\t\t.duration(250)\n\t\t.attr(\"cx\", x * r)\n\t\t.attr(\"cy\", y * r)\n\t\t.ease(\"easebounce\");\n\n\t// move related text\n\tvar selectedText = d3.select( \"#label\" + currentVehicule._id ); \n\tselectedText.transition()\n\t\t.duration(250)\n\t\t.attr(\"x\", x * r - r) \n\t\t.attr(\"y\", y * r + r + 10)\n\t\t.ease(\"easebounce\");\n\t\t\n\t// check if rover position equals an obstacle on each move \n\t// TODO add zone area sensitivity to handle bigger obstacles\n\tobstacles.forEach(function (element) {\n\t\tif ((x == (element.x / r)) && (y == (element.y / r))) {\n\n\t\t\tvar destroyedCircle = d3.select( \"#vehicule\" + currentVehicule._id );\n\t\t\tvar destroyedText = d3.select( \"#label\" + currentVehicule._id );\n\n\t\t\t// remove and disable circle and vehicule\n\t\t\tdestroyedCircle.remove();\n\t\t\tdestroyedText.remove();\n\t\t\tdestroyVehicule();\n\n\t\t}\n\t});\n}", "function createActCircle(cx, cy)\n{\n var myCircle = document.createElementNS(svgNS,\"circle\"); //to create a circle. for rectangle use \"rectangle\"\n myCircle.setAttributeNS(null,\"id\",\"actCircle\");\n myCircle.setAttributeNS(null,\"cx\",cx);\n myCircle.setAttributeNS(null,\"cy\",cy);\n myCircle.setAttributeNS(null,\"r\",20);\n myCircle.setAttributeNS(null,\"fill\",\"white\");\n myCircle.setAttributeNS(null,\"stroke\",\"none\");\n myCircle.setAttributeNS(null,\"style\",\"opacity: 1;\");\n document.getElementById(\"henosisLayer\").appendChild(myCircle);\n}", "drop() {\n ctx.strokeStyle= '#ffffff';\n ctx.beginPath();\n ctx.setLineDash([2, 2])\n ctx.arc(this.x, this.y + 50, 5, Math.PI, Math.PI * 2, false);\n ctx.stroke(); \n }", "function drag_start(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n}", "function drag_start(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n}", "function Circle(x,y,dx,dy,radius){\n //independent x&y values\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n\n//creating a method within an object to create a circle every time this function is called anonymous function\n this.draw = function() {\n //console.log('hello there');\n //arc //circle\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);\n c.strokeStyle = 'pink';\n c.stroke();\n c.fill();\n}\n\nthis.update = function() {\n //moving circle by 1px --> x += 1;\n\n if(this.x + this.radius > innerWidth ||\n this.x - this.radius < 0){\n this. dx = -this.dx;\n }\n if(this.y + this.radius > innerHeight ||\n this.y - this.radius < 0){\n this.dy = -this.dy;\n }\n this.x += this.dx; \n this.y += this.dy;\n\n this.draw();\n }\n}", "constructor(diameter) {\n this.diameter = diameter\n if (mouseX <= 0 || mouseY <= 0) {\n this.x = random(this.diameter, 1426 - this.diameter)\n this.y = random(this.diameter, 732 - this.diameter)\n }\n else {\n this.x = random(width)\n this.y = random(height)\n }\n this.xVelocity = random(1 - 5)\n this.yVelocity = random(1 - 5)\n this.color = random(360)\n }", "function drawHealth() {\n ctx.lineWidth = 1\n // Draw empty health circles\n for (let i = hero.maxhealth; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'white', 'black', 0, 2 * Math.PI, [5, 5])\n }\n // Fill health circles\n for (let i = hero.health; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'hotpink', 'black', 0 - frame, 2 * Math.PI + frame, [5, 5])\n }\n}", "function drawAcircle(x, y, u, w, radius, cell) {\r\n\t\r\n\t// Si armure on met une bordure plus épaisse\r\n\tvar sw = 0;\r\n\tif(cell.isArmored) sw = 3;\r\n\t// On dessine le soldat\r\n\t$canvas.addLayer({\r\n\t\ttype: 'arc',\r\n\t\tgroups: [cell.legionId],\r\n\t\tbringToFront: true,\r\n\t\tfillStyle: tabCouleurs[cell.legionId],\r\n\t\tstrokeWidth : sw,\r\n\t\tstrokeStyle: '#000',\r\n\t\tx: x, y: y,\r\n\t\tradius: radius/100*60,\r\n\t\tname: 's'+u+','+w,\r\n\t\tlayer : true,\r\n\t\tclick : function(layer){\r\n\t\t\tif(!spectateur && moi.playerLegionId.indexOf(cell.legionId) != -1) clickAsolder(layer);\r\n\t\t},\r\n\t\ttouchend : function(layer){\r\n\t\t\tif(!spectateur && moi.playerLegionId.indexOf(cell.legionId) != -1) clickAsolder(layer);\r\n\t\t},\r\n\t}).addLayerToGroup('s'+u+','+w, 'plateau');\r\n}", "function setup() {\n \n createCanvas(400, 400);\n \n fakeGround = createSprite(30, 390, 400, 5);\n \n ground = createSprite(100, 200, 400, 10);\n ground. addImage(groundImage);\n ground. scale = 1;\n ground.velocityX = -2;\n \n monkey = createSprite(70, 330, 10, 10);\n monkey.addAnimation(\"Jumping\",monkeyImage);\n monkey.scale = 0.15;\n \n survivalTime = 0;\n stroke(\"white\");\n textSize(20);\n fill(\"black\");\n \n //create new groups\n bananaGroup = new Group();\n obstacleGroup = new Group();\n }", "function create_circle() {\n\t\t//Random Position\n\t\tthis.x = Math.random()*W;\n\t\tthis.y = Math.random()*H;\n\t\t\n\t\t//Random Velocities\n\t\tthis.vx = 0.1+Math.random()*1;\n\t\tthis.vy = -this.vx;\n\t\t\n\t\t//Random Radius\n\t\tthis.r = 10 + Math.random()*50;\n\t}", "function nodeDragStart(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n}", "function Target(){\n let gw = GWindow(GWINDOW_WIDTH,GWINDOW_HEIGHT);\n let x = GWINDOW_WIDTH / 2 ;\n let y = GWINDOW_HEIGHT / 2 ;\n gw.add(createFilledCircle(x,y,OUTER_RADIUS,\"Red\"));\n gw.add(createFilledCircle(x,y,OUTER_RADIUS * 2 / 3,\"White\"));\n gw.add(createFilledCircle(x,y,OUTER_RADIUS / 3,\"Red\"));\n}", "function dragstarted(d) {\n\t let index = d3.select(this).attr(\"index\") ;\n\t d.x = d3.event.x;\n\t d.y = d3.event.y;\n\t d3.select(this)\n\t .attr(\"r\", radius * 1.5)\n\t .raise();\n\t}", "function DrawCharacter()\n{\n\tvar color=0xFFFFFF;\n\tvar size=2;\n\te.lineStyle(size, color);\n\te.beginFill(color);\n\te.drawCircle(mapOrigin.x, mapOrigin.y, 2);\n\te.endFill();\n}", "function draw_circles(svg, data){\n /* Draw circles onto the specified svg canvas\n *\n * Parameters\n * ----------\n * svg (d3 selection) : SVG object\n * data (object) : Object with circle attributes\n *\n */\n svg.selectAll('circle')\n .data(data)\n .enter()\n .append('circle')\n .attr('cx', get_cx)\n .attr('cy', get_cy)\n .attr('fill', '#666')\n // .attr('stroke', get_stroke)\n .attr('stroke-width', 1)\n .transition()\n .duration(1000)\n .attr('r', get_r)\n ;\n\n }", "function mouseDragged() {\n var max_circles = 300;\n if (circles.length < max_circles) {\n circles.push(new Circle(mouseX, mouseY, random(10, 40) + size));\n // circles radius changes with global size variable\n }\n}", "_addCircle(x, y, r, text, maxWidth) {\n const group = this.get('group');\n const circleGroup = group.addGroup();\n const circleStyle = this.get('_unslidableCircleStyle');\n const textStyle = this.get('textStyle');\n const titleShape = this.get('titleShape');\n let titleGap = this.get('titleGap');\n\n if (titleShape) {\n titleGap += titleShape.getBBox().height;\n }\n\n circleGroup.addShape('circle', {\n attrs: Util.mix({\n x,\n y: y + titleGap,\n r: r === 0 ? 1 : r\n }, circleStyle)\n });\n if (this.get('layout') === 'vertical') {\n circleGroup.addShape('text', {\n attrs: Util.mix({\n x: maxWidth + 20 + this.get('textOffset'),\n y: y + titleGap,\n text: text === 0 ? '0' : text\n }, textStyle)\n });\n } else {\n circleGroup.addShape('text', {\n attrs: Util.mix({\n x,\n y: y + titleGap + maxWidth + 13 + this.get('textOffset'),\n text: text === 0 ? '0' : text\n }, textStyle)\n });\n }\n }", "function Character() {\n this.tileFrom = [1, 1];\n this.tileTo = [1, 1];\n this.timeMoved = 0;\n this.dimensions = [30, 30]\n this.position = [45, 45]\n this.delayMove = 700\n \n }", "function drag_start(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();//alpha will go up to 0.3, keeping the graph active!!\n d.fx = d.x;//a node with a defined node.fx has node.x reset to this value and node.vx set to zero\n d.fy = d.y;\n}", "setDraggable(blobDOM) {\n d3.select((blobDOM.node().parentNode)).classed('cg-draggable', true)\n }", "function setup() {\n createCanvas(1000,1000);\n \n //create the sprites\n ghost = createSprite(600, 200, 10, 10);\n ghost.addAnimation(\"floating\");\n \n ghost1 = createSprite(600, 200, 10, 10);\n ghost1.addAnimation(\"floating\");\n \n \n ghost2 = createSprite(600, 200, 10, 10);\n ghost2.addAnimation(\"floating\");\n \n ghost3 = createSprite(600, 200, 10, 10);\n ghost3.addAnimation(\"floating\");\n \n ghost4 = createSprite(600, 200, 10, 10);\n ghost4.addAnimation(\"floating\");\n \n ghost5 = createSprite(600, 200, 10, 10);\n ghost5.addAnimation(\"floating\");\n \n \n}", "function Circle(x,y,radius,color){\n this.x = x;\n this.y = y;\n // this.x = Math.floor(Math.random()*window.innerWidth);\n // this.y = Math.floor(Math.random()*window.innerWidth);\n // this.dx = dx;\n // this.dy = dy;\n this.radius = radius;\n this.color = color;\n this.blur = 30;\n\n this.reappear = function () {\n\n // //change x and y coordinates\n // this.x = Math.floor(Math.random()*window.innerWidth);\n // this.y = Math.floor(Math.random()*window.innerHeight);\n\n //change color\n this.color = pickColor();\n this.blur = blurArr[Math.floor(Math.random()*blurArr.length)];\n this.draw();\n }\n\n this.draw = function(){\n c.beginPath();\n //context.arc(x,y,r,sAngle,eAngle,counterclockwise)\n c.arc(this.x,this.y,this.radius,0, Math.PI * 2, false )\n c.fillStyle = this.color;\n c.shadowBlur = 30;\n c.shadowColor = \"white\";\n c.fill();\n }\n\n this.move = function() {\n while (this.x - this.radius < window.innerWidth){\n this.x += 0.5;\n this.draw();\n }\n }\n\n}", "createHandle(point, color) {\r\n\t\tlet graph = this;\r\n\t\tlet moving = false;\r\n\t\tif(color == undefined) {\r\n\t\t\tcolor = '#6ba2f9';\r\n\t\t}\r\n\t\tlet circle = this.handles.append(\"circle\")\r\n\t\t\t.attr('class', 'draggable')\r\n\t\t\t.attr('r', this.cell_size*.2)\r\n\t\t\t.attr('fill', color)\r\n\t\t\t.on('mouseenter', function() {\r\n\t\t\t\td3.select(this)\r\n\t\t\t\t\t.transition()\r\n\t\t\t\t\t.attr('r', graph.cell_size*.3);\r\n\t\t\t})\r\n\t\t\t.on('touchstart', function() {\r\n\t\t\t\td3.select(this)\r\n\t\t\t\t\t.transition()\r\n\t\t\t\t\t.attr('r', graph.cell_size*.35);\r\n\t\t\t})\r\n\t\t\t.on('mouseleave', function() {\r\n\t\t\t\tif(!moving) {\r\n\t\t\t\t\td3.select(this)\r\n\t\t\t\t\t.transition()\r\n\t\t\t\t\t.attr('r', graph.cell_size*.2);\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.on('touchend', function() {\r\n\t\t\t\td3.select(this)\r\n\t\t\t\t\t.transition()\r\n\t\t\t\t\t.attr('r', graph.cell_size*.2);\r\n\t\t\t})\r\n\t\t\t.on('touchmove', onDrag)\r\n\t\t\t.call(d3.drag().on('drag', onDrag).on('end', function() {\r\n\t\t\t\tmoving = false;\r\n\t\t\t\td3.select(this)\r\n\t\t\t\t.transition()\r\n\t\t\t\t.attr('r', graph.cell_size*.2);\r\n\t\t\t}));\r\n\r\n\t\t//This updates the circles attribute for where it's actually drawing on the screen\r\n\t\tfunction updatePosition() {\r\n\t\t\tcircle.attr('transform', `translate(${point.x * graph.cell_size + graph.offset.x} ${point.y * graph.cell_size + graph.offset.y})`);\r\n\t\t}\r\n\r\n\t\t//The function that gets called when dragging the circle on the screen\r\n\t\tfunction onDrag() {\r\n\t\t\t//Gets the top left corner of square that you're in (x, y)\r\n\t\t\tmoving = true;\r\n\t\t\tlet x_check = Math.floor((d3.event.x - graph.offset.x + graph.cell_size / 2) / graph.cell_size);\r\n\t\t\tlet y_check = Math.floor((d3.event.y - graph.offset.y + graph.cell_size / 2) / graph.cell_size);\r\n\t\t\tif(x_check <= 0) {\r\n\t\t\t\tpoint.x = 0;\r\n\t\t\t} else if(x_check >= graph.numCols) {\r\n\t\t\t\tpoint.x = graph.numCols;\r\n\t\t\t} else {\r\n\t\t\t\tpoint.x = x_check;\r\n\t\t\t}\r\n\t\t\tif(y_check <= 0) {\r\n\t\t\t\tpoint.y = 0;\r\n\t\t\t} else if(y_check >= graph.numRows) {\r\n\t\t\t\tpoint.y = graph.numRows;\r\n\t\t\t} else {\r\n\t\t\t\tpoint.y = y_check;\r\n\t\t\t}\r\n\t\t\tupdatePosition();\r\n\t\t\tgraph.update();\r\n\t\t}\r\n\r\n\t\tupdatePosition();\r\n\t}", "function createCircle(x,y)\n{\n\t//each segment of the circle is its own circle svg, placed in an array\n\tvar donuts = new Array(9)\n\t\n\t//loop through the array\n\tfor (var i=0;i<9;i++){\n\t\tdonuts[i]=document.createElementNS(\"http://www.w3.org/2000/svg\",\"circle\");\n\t\tdonuts[i].setAttributeNS(null,\"id\",\"d\".concat(i.toString()));\n\t\tdonuts[i].setAttributeNS(null,\"cx\",parseInt(x));\n donuts[i].setAttributeNS(null,\"cy\",parseInt(y));\n\t\tdonuts[i].setAttributeNS(null,\"fill\",\"transparent\");\n\t\tdonuts[i].setAttributeNS(null,\"stroke-width\",3);\n\t\t//each ring of circles has different radius values, and dash-array values\n\t\t//dash array defines what percentage of a full circle is being drawn\n\t\t//for example the inner circle has a radius of 15.91549, 2*pi*15.91549\n\t\t//gives a circumfrence of 100 pixels for the circle, so defining the dasharray as 31 69 means that 31% of 100 pixels is drawn, and 69% is transparent.\n\t\tif (i<3){\n\t\t\t\t\tdonuts[i].setAttributeNS(null,\"r\",15.91549);\n\t\t\t\t\tdonuts[i].setAttributeNS(null,\"stroke-dasharray\",\"31 69\");\n\t\t}\n\t\t//middle ring\n\t\telse if (i<6){\n\t\t\tdonuts[i].setAttributeNS(null,\"r\",19.853);\n\t\t\tdonuts[i].setAttributeNS(null,\"stroke-dasharray\",\"39.185019 85.555059\");\n\t\t}\n\t\t//outer ring\n\t\telse{\n\t\t\tdonuts[i].setAttributeNS(null,\"r\",23.76852);\n\t\t\tdonuts[i].setAttributeNS(null,\"stroke-dasharray\",\"47.335504 102.006512\");\n\t\t}\n\t\t//each point is added to the points SVGs, use insertBefore so that it is drawn below the points rather than above, which allows for click events to still occur\n\t\t document.getElementById(\"points\").insertBefore(donuts[i],document.getElementById(\"points\").childNodes.item(0));\n\t}\n\t//each point has its own colour, dash offset and class. Dash offset is how far from the starting point (top of the circle) to begin drawing the segment\n\t//each class relates to a different css animation because each animation has a different starting point. Animations are defined in component.css\ndonuts[0].setAttributeNS(null,\"stroke-dashoffset\",\"58.33333\" );\n\t\t\t\t\t\tdonuts[0].setAttributeNS(null,\"class\",\"spin1\");\ndonuts[1].setAttributeNS(null,\"stroke-dashoffset\",\"25\");\n\t\t\t\t\t\t\tdonuts[1].setAttributeNS(null,\"class\",\"spin2\");\ndonuts[2].setAttributeNS(null,\"stroke-dashoffset\",\"91.66667\" );\n\t\t\t\t\t\t\tdonuts[2].setAttributeNS(null,\"class\",\"spin3\");\ndonuts[3].setAttributeNS(null,\"stroke-dashoffset\",\"41.18502\" );\n\tdonuts[3].setAttributeNS(null,\"class\",\"spin4\");\ndonuts[4].setAttributeNS(null,\"stroke-dashoffset\",\"82.76505\" );\n\tdonuts[4].setAttributeNS(null,\"class\",\"spin5\");\ndonuts[5].setAttributeNS(null,\"stroke-dashoffset\",\"124.34508\");\n\tdonuts[5].setAttributeNS(null,\"class\",\"spin6\");\ndonuts[6].setAttributeNS(null,\"stroke-dashoffset\",\"56.3355\");\n\tdonuts[6].setAttributeNS(null,\"class\",\"spin7\");\ndonuts[7].setAttributeNS(null,\"stroke-dashoffset\",\"106.11618\");\n\tdonuts[7].setAttributeNS(null,\"class\",\"spin8\");\ndonuts[8].setAttributeNS(null,\"stroke-dashoffset\",\"155.89685\");\n\tdonuts[8].setAttributeNS(null,\"class\",\"spin9\");\ndonuts[0].setAttributeNS(null,\"stroke\",\"#115D6B\");\ndonuts[1].setAttributeNS(null,\"stroke\",\"#D90981\");\ndonuts[2].setAttributeNS(null,\"stroke\",\"#4A3485\");\ndonuts[3].setAttributeNS(null,\"stroke\",\"#F51424\");\ndonuts[4].setAttributeNS(null,\"stroke\",\"#0BA599\");\ndonuts[5].setAttributeNS(null,\"stroke\",\"#1077B5\");\ndonuts[6].setAttributeNS(null,\"stroke\",\"#FA893D\");\ndonuts[7].setAttributeNS(null,\"stroke\",\"#87C537\");\ndonuts[8].setAttributeNS(null,\"stroke\",\"#02B3EE\");\n}", "function draw_nodes(scenes, svg, chart_width, chart_height) {\n var node = svg.append(\"g\").selectAll(\".node\")\n .data(scenes)\n .enter().append(\"g\")\n .attr(\"class\", \"node\")\n .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; })\n .attr(\"scene_id\", function(d) { return d.id; })\n .call(d3.behavior.drag()\n .origin(function(d) { return d; })\n .on(\"dragstart\", function() { this.parentNode.appendChild(this); })\n .on(\"drag\", dragmove));\n\n\n node.append(\"rect\")\n .attr(\"width\", function(d) { return d.width; })\n .attr(\"height\", function(d) { return d.height; })\n .style(\"fill\", function(d) { return \"#1f77b4\"; })\n //.style(\"stroke\", function(d) { return \"#0f3a58\"; })\n .attr(\"rx\", 30)\n .attr(\"ry\", 30)\n .append(\"title\")\n .text(function(d) { return d.name; });\n\n node.append(\"text\")\n\t.attr(\"x\", -6)\n\t.attr(\"y\", function(d) { return d.width / 2; })\n\t.attr(\"dy\", \".35em\")\n\t.attr(\"text-anchor\", \"end\")\n\t.attr(\"transform\", null)\n\t.text(function(d) { return d.name; })\n .filter(function(d) { return d.x < chart_width / 2; })\n\t.attr(\"x\", function(d) { return 6 + d.width; })\n\t.attr(\"text-anchor\", \"start\");\n\n function dragmove(d) {\n\t//console.log('d.y = ' + d.y);\n\t//console.log('d3.event.y = ' + d3.event.y);\n\t//console.log('d.x = ' + d.x);\n\tvar newy = Math.max(0, Math.min(chart_height - d.height, d3.event.y));\n\tvar ydisp = d.y - newy;\n\td3.select(this).attr(\"transform\", \"translate(\" \n\t\t\t + (d.x = Math.max(0, Math.min(chart_width - d.width, d3.event.x))) + \",\" \n\t\t\t + (d.y = Math.max(0, Math.min(chart_height - d.height, d3.event.y))) + \")\");\n\treposition_node_links(d.id, d.x, d.y, d.width, d.height, svg, ydisp);\n\t//sankey.relayout();\n\t//link.attr(\"d\", path);\n }\n}", "function drag_start(d) {\n if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n}", "function Circle(x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n // Step 4\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n // Step 8 Add Color\n this.colors = [\"#16a085\", \"#e74c3c\", \"#34495e\"];\n\n // Step 3 Add Draw Function\n this.draw = function() {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n // Step 8 Add Color\n c.strokeStyle = \"blue\";\n // c.strokeStyle = this.colors[Math.floor(Math.random() * 3)];\n c.stroke();\n // c.fillStyle = this.colors[Math.floor(Math.random() * 3)];\n };\n\n // Step 4 Update / Create Animation\n // Add dx, dy, radius\n this.update = function() {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n\n this.x += this.dx;\n this.y += this.dy;\n\n // Step 5 add draw\n this.draw();\n };\n}", "function draw() {\n //background is pink\n //circle\n stroke(90,255,127); // an RGB color for the circle's border\n strokeWeight(10);\n fill(255,90,127,255); // an RGB color for the inside of the circle (the last number refers to transparency (min. 0, max. 255))\n ellipse(mouseX,height/2,100,seethru); // center of canvas, 20px dia\n fill(255,255,251,seethru);\n \n rect(50,200,400,100);\n}", "constructor(x, y, d, fallSpeed) {\n this.x = x; // x coordinate of raindrop\n this.y = y; // y coordinate of raindrop\n this.d = d; // diameter of the circle\n this.fallSpeed = fallSpeed;\n }", "function Circle(x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n\n this.draw = function() {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);\n c.fillStyle = randomHue;\n c.fill();\n c.strokeStyle = randomHue;\n c.stroke();\n }\n\n this.update = function() {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n this.draw();\n }\n}", "function drawCircle(x, y, num) {\n vis_nodes.append('circle')\n .attr('class', 'node-circle')\n .attr('id', num)\n .attr('fill','#1D2326')\n .attr('cx', x)\n .attr('cy', y)\n .attr('r', 8)\n .on('click', function(){\n if (states['#edges']) {\n c = d3.select(this);\n c.attr('fill','#5990D9');\n var n = endpoints.push(c);\n drawEdges(n); \n }\n else if (states['#select']) {\n c = d3.select(this);\n var n = startEnd.push(c);\n selectStartEnd(n);\n }\n });\n}", "function draw() {\n background(70);\n diffCircle.update();\n if (mouseIsPressed) {\n diffCircle = diffCircle - 300 ;\n } else {\n diffCircle = diffCircle + 300;\n }\n }", "function mousePressed() {\n circObjs.push(\nnew Circ(mouseX, mouseY, random(255)));\n}", "function createPoint(x,y,c,w,d){\n points.push({\n x: x,\n y: y,\n color: c,\n width: w,\n drag: d,\n })\n}", "function drawCircles() {\r\n placing = Placing.CIRCLE;\r\n}", "function startCharacter(){\n createRoundRectangle(player[0].color, 40, player[0].x, player[0].y);\n addNumbers(player[0].num, \"#ffffff\", player[0].x+20, player[0].y+20);\n\n createRoundRectangle(player[1].color, 40, player[1].x, player[1].y);\n addNumbers(player[1].num, \"#ffffff\", player[1].x+20, player[1].y+20);\n\n return stage.update();\n}", "function mouseDragged(){\n \n if(score < 5000){\n \n Matter.Body.setPosition(hexagon.body,{x:mouseX,y:mouseY});\n\n }\n}", "drawFiveDot(x,y,s,r,ang,circleFill){\n ctx.save();\n ctx.translate(x,y);\n ctx.rotate(ang*Math.PI/180);\n\n // draw the square\n ctx.beginPath();\n ctx.rect(-s/2, -s/2,s,s);\n ctx.fillStyle = this.dragFill;\n ctx.fill();\n\n // centre C\n this.drawCircle(0,0,r,circleFill);\n // top left\n this.drawCircle(-s/2,-s/2,r,circleFill);\n // top right\n this.drawCircle(s/2,-s/2,r,circleFill);\n // bottom left\n this.drawCircle(-s/2,+s/2,r,circleFill);\n // bottom right\n this.drawCircle(s/2,+s/2,r,circleFill);\n\n ctx.restore();\n }", "function addElement() {\n // zde vytvorim kruhovy prvek\n var newdiv = document.createElement(\"circle\");\n newdiv.setAttribute(\"cx\",\"50\");\n newdiv.setAttribute(\"cy\",\"50\");\n newdiv.setAttribute(\"r\",\"50\");\n //platno element\n \n // <circle id=\"redcircle\" cx=\"50\" cy=\"50\" r=\"50\" fill=\"red\" />\n\n}", "function dragmove (d){\n\t\t\t\t$scope.dragging_object = true;\n\n\t\t\t\tvar x = clamp(d3.event.x, 0, SVG_WIDTH); // temp\n\t\t\t\tvar y = clamp(d3.event.y, 0, SVG_HEIGHT); // temp\n\t\t\t\td3.select(this).attr(\"transform\", \"translate(\"+x+\",\"+y+\")\");\n\n\t\t\t\tthis._x = x;\n\t\t\t\tthis._y = y;\n\t\t\t}", "function setup() {\n\ncreateCanvas(600, 400);\n \nball1= new Ball(width/2, 0, 20, 2, 255, 140, 101, 175);// start ball at 100, with size of 20 pixels\nball2= new Ball (width/2, 0, 10, 3, 101, 255, 220, 170);\nball3= new Ball(width/2, random(height), 5, 5, 217, 25, 175);\nball4= new Ball(width/2, random(height), 12, 8, 174, 255, 170);\nball5= new Ball (width/2, random(height), random(5,20), 6, 255, 243, 31, 185);\nball6= new Ball(width/2, 0, 20, 2, 255, 140, 101, 200);\n\n\nfor (var d=0; d<20; d++){ //setting up for array of dots\n dots[d]= new Jiggle (d, 0, 20+d, 100);\n}\n\n//drop1= new Square (50, 25);//initialize drop 1 object\n//drop2= new Square (random(10, 30), 125);// initialize drop 2 object\n/*\nfor (var i=0; i< width; i++) { //initialize dot object at bottom of screen, radius 40 pixels, color white?\n dot= new Fallup (i, height, 40, 255);\n}\nball2=new Ball(random(0,width/2), random(100), random(10,15),6, 140);\ndot2= new Fallup(random(width), random(height), random(50,100), random(255));\ndrop3= new Square (random(100,200), random(255));\nball3= new Ball(random(width/2, width), height/2, 75, -2, 255);\nfor (var d=0; d<10; d++){ //setting up for array of dots\n dots[d]= new Fallup (d, width/2, 25, 100);\n}*/\n}" ]
[ "0.6684478", "0.6581289", "0.6517211", "0.64990413", "0.6228767", "0.6149783", "0.6146491", "0.6145719", "0.6125714", "0.61183983", "0.603671", "0.6024318", "0.60054815", "0.5986181", "0.597015", "0.59576213", "0.59518576", "0.59331656", "0.59262705", "0.5898942", "0.5869318", "0.5830076", "0.58198917", "0.5817367", "0.5815776", "0.5806644", "0.58015513", "0.57755625", "0.57675236", "0.5766123", "0.57554775", "0.57504046", "0.57344013", "0.5732619", "0.57307816", "0.56996584", "0.56928885", "0.56869787", "0.5682657", "0.56681263", "0.56622356", "0.5656832", "0.5635962", "0.5634267", "0.5632437", "0.56306595", "0.56289095", "0.56272286", "0.5626711", "0.56252164", "0.56112427", "0.5603699", "0.56025", "0.5600354", "0.55977184", "0.5597142", "0.5584785", "0.5581938", "0.5577639", "0.5577399", "0.55717236", "0.5570324", "0.5570324", "0.5568239", "0.55665797", "0.5566497", "0.55623394", "0.5559721", "0.55577564", "0.5557052", "0.55560136", "0.55497205", "0.554538", "0.5545293", "0.5544871", "0.5537158", "0.5533639", "0.55287707", "0.5523573", "0.55235386", "0.5518349", "0.55169845", "0.5516977", "0.5515166", "0.5514363", "0.5512796", "0.55109614", "0.55107427", "0.55058235", "0.550296", "0.54956484", "0.5495389", "0.5495122", "0.54932487", "0.5489535", "0.54854864", "0.5481961", "0.54817873", "0.5480348", "0.5475528" ]
0.57802695
27
Ticker API for Binance BTC Data
async index({request, response}) { }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function get30DayBTCData() {\r\n\tvar result;\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET',\r\n\t\t'https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=30&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false)\r\n\trequest.send(null);\r\n\tresult = JSON.parse(request.responseText);\r\n\treturn result;\r\n}", "async function getBitcoinData() {\n let histUrl = `${config.corsApiUrl}https://api.coindesk.com/v1/bpi/historical/close.json?start=${firstDay.format(\"YYYY-MM-DD\")}&end=${yesterday.format(\"YYYY-MM-DD\")}`,\n curUrl = `${config.corsApiUrl}https://api.coindesk.com/v1/bpi/currentprice/USD.json`;\n try {\n let bitcoinResp = await axios.all([axios.get(histUrl), axios.get(curUrl)]);\n const histData = bitcoinResp[0].data.bpi,\n curData = bitcoinResp[1].data.bpi.USD.rate_float;\n return { hist: histData, cur: curData };\n } catch (error) {\n console.log(error);\n }\n}", "ticker (symbol) {\n const url = `${baseUrl}/ticker/?symbol=${symbol}`\n return fetchJSON(url, this.token)\n }", "function getTrendingCurrency() {\n let apiURL = 'https://api.coingecko.com/api/v3/search/trending'\n fetch(apiURL)\n .then(response => response.json())\n .then(data => console.log(data));\n }", "function getLiveBTCRate() {\r\n\tvar result;\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET',\r\n\t\t'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false)\r\n\trequest.send(null);\r\n\tresult = JSON.parse(request.responseText);\r\n\treturn result;\r\n}", "function getRequest()\r\n{\r\nrequest.open('GET', 'https://www.blockchain.com/ticker', true)\r\n//Log progress\r\nconsole.log('Get Called')\r\n\r\nrequest.onload = function() {\r\n // Begin accessing JSON data here\r\n data = JSON.parse(this.response)\r\n\r\n // if we get a good response from server\r\n if (request.status >= 200 && request.status < 400) {\r\n\t //Log good news\r\n\t console.log('Api Good')\r\n console.log(data[currency])\r\n\t //Add to data points array for chart\r\n\t dataPoints.push({y: data[currency][\"15m\"]});\r\n\t //Update the chart\r\n\t window.updateChart();\r\n\t //Update the table with bitcoin info\r\n\t UpdateTable()\r\n\t//If API fail, output error!\r\n } else {\r\n console.log('error')\r\n }\r\n}\r\n//Send the request\r\nrequest.send()\r\n}", "function get24HBTCData() {\r\n\tvar result;\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET',\r\n\t\t'https://min-api.cryptocompare.com/data/v2/histohour?fsym=BTC&tsym=USD&limit=24&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false)\r\n\trequest.send(null);\r\n\tresult = JSON.parse(request.responseText);\r\n\treturn result;\r\n}", "function get_bitcoin_price() {\n var location = \"transaction\";\n var url = \"https://blockchain.info/ticker?cors=true\";\n\n $.ajax({\n url: url,\n type: 'GET',\n async: true,\n success: function(data, status) {\n USD_price = data.USD.last;\n console.log(USD_price);\n update_display();\n }\n });\n}", "function getPriceUSD(callback) {\n $.ajax({\n url: 'https://blockchain.info/ticker?&cors=true',\n type: 'GET',\n crossDomain: true,\n success: function(response) {\n callback(response['USD']['last']);\n },\n error: function(xhr, status) {\n callback('error!');\n }\n });\n }", "async function getBitcoin() {\n // obtain 1 months data of bitcoin\n try {\n const historicalBitcoinData = await axios.get(\n \"https://api.coincap.io/v2/assets/bitcoin/history?interval=d1&start=1577797200000&end=1623527003000\"\n );\n\n // extract the data out in a format data array format chart.js requires. Destructure the returned dataObject\n var { dataPoints, dataLabels } = massageData(\n historicalBitcoinData.data.data\n );\n\n // draw the actual chart\n bitcoinChart(dataLabels, dataPoints, \"myChart1\");\n\n // now plot the actual chart\n } catch (error) {\n console.log(\"The errors is: \", error);\n }\n}", "function ticker(market) {\r\n return new Promise(function (resolve, reject) {\r\n var options = {\r\n method: \"GET\",\r\n url: \"https://api.upbit.com/v1/ticker\",\r\n qs: { markets: market.toString() },\r\n };\r\n request(options, function (error, response, body) {\r\n if (error) reject(error);\r\n else {\r\n var data_1 = [];\r\n body = JSON.parse(body.toString());\r\n body.forEach(function (v) {\r\n var market = new Market_1.default(\r\n v[\"market\"].split(\"-\")[0],\r\n v[\"market\"].split(\"-\")[1]\r\n );\r\n setMarketData(market, v);\r\n data_1.push(market);\r\n });\r\n resolve(data_1);\r\n }\r\n });\r\n });\r\n}", "function BINTickFetch(){\n Logger.log(\"Function BINTickFetch is running : ........ \" )\n var rows=[],obj_array=null, msg=\"\";\n try {obj_array=JSON.parse(UrlFetchApp.fetch(\"https://api.binance.com/api/v3/ticker/price\").getContentText());} catch (e) { msg=e; obj_array=null;}\n if (obj_array!=null){\n for (r in obj_array) rows.push([obj_array[r].symbol, parseFloat(obj_array[r].price)]);\n var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Binance24h');ss.getRange(\"Binance24h!A1\").setValue(new Date());\n try {var range=sheet.getRange(2,1,sheet.getLastRow(),2).clearContent();} catch(e) {Logger.log(\"error\");}\n if (rows != \"\") range=sheet.getRange(2,1,rows.length,2); range.setValues(rows); \n }\n if (msg!=\"\") Browser.msgBox(\"Oops, Binance API did not provide any valid data and returned an error. \\\\n\\\\n\"+msg);\n}", "function loadRates() {\n return coinmarketcap.ticker(\"\", \"\").then((input) => {\n var result = {};\n input.forEach((item) => {\n result[item.symbol.replace(/[^\\w\\s]/gi, '_')] = item.percent_change_7d;\n });\n return result;\n }); \n}", "async fetchBinance(coin, element) {\n const URL = `https://api.binance.com/api/v3/ticker/price?symbol=${coin}USDT`;\n let price = await fetch(URL)\n .then((blob) => blob.json())\n .then((data) => {\n return data.price;\n })\n .catch((error) => {\n console.error(\"Error with the Binance fetch operation\", error);\n this.setPrice(\"\", element, \"Binance\");\n return \"\";\n });\n return parseFloat(price);\n }", "function checkBtcPrice () {\n const fromDate = document.querySelector('#fromDate').value\n const toDate = document.querySelector('#toDate').value\n const currency = document.querySelector('select#currencyCode').value\n let apiUrl = \"\";\n if (fromDate === \"\" || toDate === \"\"){\n apiUrl = `http://api.coindesk.com/v1/bpi/historical/close.json?currency=${currency}`\n } else {\n apiUrl = `http://api.coindesk.com/v1/bpi/historical/close.json?start=${fromDate}&end=${toDate}&currency=${currency}`\n }\n axios\n .get(apiUrl)\n .then(({ data: {bpi}}) => {\n printTheChart(bpi);\n const prices = Array.from(Object.values(bpi));\n showValues(prices);\n })\n .catch(err => console.log('Error while getting the data: ', err));\n}", "function getStocksFromApi(req, res) {\n // const options = {\n // method: 'GET',\n // url: 'https://www.alphavantage.co/query',\n // qs: {\n // function: 'TIME_SERIES_DAILY',\n // apikey: ALPHA_KEY1,\n // outputsize: 'full',\n // symbol: req.query.symbol\n // },\n // json: true\n // }\n const { symbol } = req.query;\n var fiveYearsAgo = new Date();\n fiveYearsAgo.setFullYear(fiveYearsAgo.getFullYear() - 5 );\n const options = {\n method: 'GET',\n url: `https://api.tiingo.com/tiingo/daily/${symbol}/prices`,\n qs: {\n token: ALPHA_KEY3,\n startDate: fiveYearsAgo,\n symbol: req.query.symbol\n },\n json: true\n }\n request(options)\n .then(function (apiResponse) {\n return apiResponse;\n })\n .then(function (data) {\n res.status(200).json(data)\n })\n .catch(function (err) {\n console.log(err)\n let errorMessage = 'Internal Server Error'\n res.status(500).send(errorMessage);\n });\n}", "function getData(type, cb) {\n\n var xhr = new XMLHttpRequest();\n\n xhr.open(\"GET\", \"https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=10&api_key={63ccb497d786ebd21bb4ac7e1f8842f8ae98d05aafcbe02f0aa3c51fe98b91ad}\")\n xhr.send();\n\n xhr.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n cb(JSON.parse(this.responseText))\n }\n };\n}", "async getCurrencyAPI() {\n const url = `https://min-api.cryptocompare.com/data/all/coinlist?api_key=${this.apikey}`\n\n // Fetch to api\n const getUrlCurruency = await fetch(url)\n\n // Response in JSON\n const currencies = await getUrlCurruency.json()\n return {\n currencies\n }\n }", "getBTCPrices (date) {\n return axios.get('https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD&ts=' + date);\n }", "function loadCoins() {\n return coinmarketcap.ticker(\"\", \"\", 100).then((input) => {\n var result = [];\n input.forEach((item) => {\n result.push({\"name\": item.name.toLowerCase().replace(/[^\\w\\s]/gi, '_'), \"symbol\":item.symbol.replace(/[^\\w\\s]/gi, '_')});\n });\n return result;\n });\n}", "async function getproductticker ( restapiserver, productid ) {\n\n async function restapirequest ( method, requestpath, body ) { // make rest api request.\n \n // create the prehash string by concatenating required parts of request.\n let timestamp = Date.now() / 1000;\n let prehash = timestamp + method + requestpath;\n if ( body !== undefined ) { prehash = prehash + body; }\n // created the prehash.\n \n // base64 decode the secret.\n let base64decodedsecret = Buffer(secret, 'base64');\n // secret decoded.\n \n // create sha256 hmac with the secret.\n let hmac = crypto.createHmac('sha256',base64decodedsecret);\n // created sha256 hmac.\n \n // sign the require message with the hmac and base64 encode the result.\n let signedmessage = hmac.update(prehash).digest('base64');\n // signed message.\n \n // define coinbase required headers.\n let headers = {\n 'ACCEPT': 'application/json',\n 'CONTENT-TYPE': 'application/json',\n 'CB-ACCESS-KEY': key,\n 'CB-ACCESS-SIGN': signedmessage,\n 'CB-ACCESS-TIMESTAMP': timestamp,\n 'CB-ACCESS-PASSPHRASE': passphrase,\n };\n // defined coinbase required headers. yes... content-type is required.\n // see https://docs.prime.coinbase.com/#requests for more information.\n \n // define request options for http request.\n let requestoptions = { 'method': method, headers };\n if ( body !== undefined ) { requestoptions['body'] = body; }\n // defined request options for http request.\n \n // define url and send request.\n let url = restapiserver + requestpath;\n let response = await fetch(url,requestoptions);\n let json = await response.json();\n // defined url and sent request.\n \n return json;\n \n } // made rest api request.\n\n\n // make request.\n let ticker = await restapirequest ( 'GET', '/products/' + productid + '/ticker' );\n // made request.\n\n // handle response.\n if ( Object.keys(ticker).length === 0 ) { console.log('unable to retrieve information'); }\n else if ( Object.keys(ticker).length === 1 ) { console.log('the Coinbase response is \"' + ticker.message + '\"'); }\n else {\n\n // report ticker.\n return ticker; \n // reported ticker.\n\n }\n // handled response.\n\n}", "getCoinRate(callback){\n const api_data = {\n api_name:'/get-coin-rate',\n coin:this.coin\n };\n api_call.apiGetCall(api_data,callback);\n }", "async function markets() {\n try {\n const client = new CoinMarketCap(process.env.COINMARKETCAP_API_KEY)\n const currency = 'CAD';\n const cryptoCount = 5;\n\n const prices = await client.getTickers({limit: cryptoCount, convert: currency});\n\n console.log('Market Monday\\n');\n console.log(`Top ${cryptoCount} cryptocurrencies by market cap:\\n`);\n prices.data.forEach(d => {\n const price = new Big(d.quote[currency].price);\n const change = new Big(d.quote[currency].percent_change_7d);\n const upDown = change.lt(0) ? 'down' : 'up';\n const chart = change.lt(0) ? emoji.get(':chart_with_downwards_trend:') : emoji.get(':chart_with_upwards_trend:');\n const decimals = price.lt(1) ? 4 : 0;\n\n console.log(`${chart} ${d.name} (${d.symbol}) $${price.toFormat(decimals)} CAD - ${upDown} ${change.abs().toString()}% this week ${chart}`);\n });\n } catch (err) {\n console.error(err);\n }\n}", "getCurrency(symbol) {\n return fetch(\n `https://min-api.cryptocompare.com/data/histominute?fsym=${symbol}&tsym=USD&limit=60`\n )\n .then(response => response.json())\n .then(json => json.Data);\n }", "function tickerCoins(){\n let tickerUrl = \"https://api.coinmarketcap.com/v2/ticker/?sort=rank\";\n \n request(tickerUrl, function(error, response, body) {\n // If the request is successful\n let tickerArray =[];\n let tickerArray2 =[];\n \n function CoinObject(name, symbol, max, price, chg1H, chg24H,chg7d) {\n \n this.name = name;\n this.symbol = symbol;\n this.max = max;\n this.price = price;\n this.chg1H = chg1H;\n this.chg24H = chg24H;\n this.chg7d = chg7d;\n };\n \n // try catch to parse through bad API data\n function canParseJson(str) {\n try {\n JSON.parse(body).data[str].name;\n success = true;\n } catch (e) {\n success = false;\n return false;\n }\n if (success){\n tickerArray[str] = new CoinObject(JSON.parse(body).data[str].name,JSON.parse(body).data[str].symbol,JSON.parse(body).data[str].max_supply,JSON.parse(body).data[str].quotes.USD.price,JSON.parse(body).data[str].quotes.USD.percent_change_1h,JSON.parse(body).data[str].quotes.USD.percent_change_24h,JSON.parse(body).data[str].quotes.USD.percent_change_7d)\n } \n // fills the array with a response from the API\n \n }\n \n // try catch for loop that looks through the api response and parses through the ids. need to do this because the api skips numbers.\n if (!error && response.statusCode === 200) {\n for (i=0; i< 800 ; i++){\n let success = false;\n canParseJson(i); \n };\n\n let coin1 = (req.params.id).toUpperCase();\n let coin2 = (req.params.id2).toUpperCase();\n console.log(coin1,coin2);\n search(coin1,tickerArray,tickerArray2);\n search2(coin2,tickerArray,tickerArray2);\n } else {\n console.log('cant find that crypto');\n };\n\n // search through the API return for the two coins we are going to compare\n function search(nameKey,tickerArray,tickerArray2){ \n for (var i=1; i < tickerArray.length; i++) {\n if ((tickerArray[i].symbol === nameKey)) {\n tickerArray2.push(tickerArray[i]);\n return tickerArray2;\n }; \n };\n };\n function search2(nameKey2,tickerArray,tickerArray2){ \n for (var i=1; i < 800; i++) {\n try {\n if (tickerArray[i].symbol === nameKey2) {\n console.log('this is ticker array');\n console.log(tickerArray);\n console.log(tickerArray[i].symbol);\n tickerArray2.push(tickerArray[i]);\n console.log(tickerArray2);\n return tickerArray2;\n }\n } catch(e) {\n console.log('this errored out ' + nameKey2)\n }\n \n }; \n };\n res.json(tickerArray2);\n });\n }", "async getStock() {\n const response = await fetch(\n `https://www.alphavantage.co/query?function=${this.timeFrame}&symbol=${\n this.symbol\n }&interval=${this.interval}&apikey=${this.apiKey}`\n );\n\n const responseData = await response.json();\n return responseData;\n }", "fetchChartData( symbol, cb ) {\n if ( !this._ajax || !symbol ) return;\n const endpoint = `${this._apiurl}/v3/klines?symbol=${symbol}&interval=1h&limit=168`;\n const prices = [];\n\n this._ajax.get( endpoint, {\n type: 'json',\n // cache: 600,\n success: ( xhr, status, res ) => {\n if ( res && Array.isArray( res ) ) {\n for ( let i = 0; i < res.length; ++i ) {\n prices.push( parseFloat( res[ i ][ 4 ] ) ); // close price\n }\n }\n if ( typeof cb === 'function' ) cb( prices );\n this.emit( 'chart_data', { symbol, prices } );\n },\n error: ( xhr, status, err ) => {\n if ( typeof cb === 'function' ) cb( prices );\n console.warn( err );\n }\n });\n }", "getCurrencyHistory (currency) {\n return axios.get(proxyUrl + currencyHistory + `${currency}`)\n .then(res => res.data.bpi)\n .catch(error => {\n console.log('error', error);\n })\n }", "function getLiveETHRate() {\r\n\tvar result;\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET',\r\n\t\t'https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false)\r\n\trequest.send(null);\r\n\tresult = JSON.parse(request.responseText);\r\n\treturn result;\r\n}", "getETHPrices (date) {\n return axios.get('https://min-api.cryptocompare.com/data/pricehistorical?fsym=ETH&tsyms=USD&ts=' + date);\n }", "function initCoinList() {\r\n binance.bookTickers((error, ticker) => {\r\n ticker.map((data) => {\r\n Object.keys(CURRENCIES).map((currency) => {\r\n if (data.symbol.includes(currency)) COINS[data.symbol] = { ...EMPTY }\r\n })\r\n })\r\n obtainHistoricData()\r\n })\r\n}", "function parseBinanceCandlestick(code:string, res: any[]) {\n const mappedData = res.map(itm => {\n const [openUtc, openPrice, highPrice, lowPrice, closePrice, volume, closeUTC] = itm\n return {\n openUtc: new Date(openUtc),\n closeUTC: new Date(closeUTC),\n openPrice: +openPrice,\n closePrice: +closePrice,\n volume: +volume,\n highPrice: +highPrice,\n lowPrice: +lowPrice,\n avgPrice: ((+openPrice) + (+closePrice)) / 2\n }\n })\n const highest = _.maxBy(mappedData, \"highPrice\")?.highPrice\n const lowest = _.minBy(mappedData, \"lowPrice\")?.lowPrice\n const mean = _.meanBy(mappedData, \"avgPrice\")\n const open = _.meanBy(mappedData, \"openPrice\")\n const close = _.meanBy(mappedData, \"closePrice\")\n\n const samples = mappedData.length\n return {\n stats: {code, max: highest, min: lowest, mean, open, close, samples},\n mappedData\n }\n}", "getTicker(symbol, callback) { // WORK DONE\n if (callback) {\n var symbolPair = symbol.toLowerCase()+this.convert.toLowerCase();\n this._getJSON('/ticker/'+symbolPair, (res) => {\n if (res) {callback(res);}\n });\n return this;\n } else {\n return false;\n }\n }", "function updateCoin(fsym) {\n axios.get('https://min-api.cryptocompare.com/data/histohour', {\n params: {\n api_key: \"2ccfbedbc83b1a45687c4e6eeaa6ab79299b4ade9398cee3878b6a42c1066f73\",\n fsym: fsym,\n tsym: \"SGD\",\n limit: 20,\n }\n })\n .then(function(response) {\n let readings1 = response.data.Data;\n let arrayinfoBitcoin = [];\n\n for (x in readings1) {\n // console.log(readings1[x])\n let time_raw = readings1[x].time;\n let time = convertTimestamp(time_raw);\n let close = readings1[x].close;\n let high = readings1[x].high;\n let low = readings1[x].low;\n let open = readings1[x].open;\n let volumefrom = readings1[x].volumefrom;\n let volumeto = readings1[x].volumeto;\n let infoBitcoin = { time, close, high, low, open, volumefrom, volumeto };\n arrayinfoBitcoin.push(infoBitcoin);\n }\n // console.log(arrayinfoBitcoin);\n printdata1(arrayinfoBitcoin);\n })\n .catch(function(error) {\n console.log(error);\n })\n .then(function() {\n // always executed\n });\n} //End of Function", "async function getTickerLastTrade() {\n await traderBot.api('Ticker', {pair: 'usdtzusd'})\n .then((res) => console.log(res.USDTZUSD.c[0]))\n .catch((rej) => console.log(rej));\n}", "static requestHistoricalDailyPriceForTicker(ticker) {\n return new Promise(resolve => {\n resolve(this.placeApiRequest(\"/api/v3/historical-price-full/\" + ticker\n + \"?from=\" + HISTORICAL_STOCK_START_DATE + \"&to=\" + TODAY));\n });\n }", "fetchBPI(){\n fetch('https://api.coindesk.com/v1/bpi/currentprice/usd.json')\n .then( (response) => {\n return response.json()\n })\n .then( (data) => {\n this.setState({\n bitcoin_prices: data\n })\n })\n .catch( (error) => {\n console.log(error)\n })\n }", "getUrl({ base, quote }) {\n return `https://www.bitstamp.net/api/v2/ticker/${base}${quote}`.toLowerCase();\n }", "getBTCPrices() {\n if (this.props.currency=\"BTC\"){\n return fetch(URL)\n .then(r => r.json())\n .then(data => {\n // console.log('data: ', data)\n this.setState({ Prices: data.bpi })\n //this.setState({ BTC_USD: data.bpi[\"2018-04-25\"]})\n this.showGraph()\n })\n .catch(err => {\n console.log(err)\n })\n }\n }", "function bitCoinAjaxCall() {\n var BTCprice;\n var USDprice;\n \n\n request(\"https://min-api.cryptocompare.com/data/price?fsym=USD&tsyms=BTC,ETH,EUR\", function(err, res, body) {\n var parsedBody = JSON.parse(body);\n // console.log(parsedBody.BTC);\n BTCprice = parsedBody.BTC;\n request(\"https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,ETH,EUR\", function(err, res, body) {\n // Subtract 7 hours on server. \n // var moment_tstamp = moment().subtract(7, \"Hours\").format(\"YYYY-MM-DD+HH:mm:ss\");\n var moment_tstamp = moment().format(\"YYYY-MM-DD+HH:mm:ss\");\n console.log(moment_tstamp)\n var parsedBody = JSON.parse(body);\n console.log(parsedBody.USD);\n USDprice = parsedBody.USD;\n\n // mongo.insertOne(logger, 'price', { BTCprice, USDprice }); //****************** */\n // dbManager.addToCurrencyTable(BTCprice, USDprice, moment_tstamp.toString());\n });\n });\n\n}", "async function fetchRates(base = 'DKK') {\n const response = await fetch(`${endpoint}?base=${base}`);\n const dataRates = await response.json();\n console.log('HERE THE FETCHED DATA', dataRates);\n /*\n you can call the fetchRates(); like this in the broswer and you can see that \n \"dataRates\" is a Promise, since it is an async function, and by clicking \"rates\"\n you get all the \"rates\" converted with the existing value of our base\n \n */\n return dataRates;\n}", "async function getTradeBalance() {\n await traderBot.api('TradeBalance', {asset: 'ETH'})\n .then((res) => console.log(res))\n .catch((rej) => console.log(rej));\n}", "function findStocksByAPI(companies, stocks=[], count=0, cb) {\n\t\n\tif(count == 0) {\n\t\tconsole.log('\\nSearching API for ' + companies.length + ' companies...\\n');\n\t}\n\tif(count < companies.length) {\n\t\t\n\t\tyahooFinance.quote({ symbol: companies[count].symbol, modules: ['summaryDetail', 'price' ]}, (err, quote) => {\n\t\t\tif(err) {\n\t\t\t\tconsole.log('Unable to find: ', companies[count].symbol);\n\t\t\t\tcount++;\n\t\t\t\tfindStocksByAPI(companies, stocks, count, cb)\n\t\t\t} else {\n\t\t\t\tvar sd = quote.summaryDetail ? quote.summaryDetail : {};\n\t\t\t\t\n\t\t\t\tif(sd.ask == 0 && sd.bid == 0) {\n\t\t\t\t\tvar price = parseFloat(sd.previousClose);\n\t\t\t\t} else if(sd.ask == 0) {\n\t\t\t\t\tvar price = parseFloat(sd.bid);\n\t\t\t\t} else {\n\t\t\t\t\tvar price = parseFloat(sd.ask);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar change = format(price - parseFloat(sd.previousClose));\n\t\t\t\tif(parseFloat(change) < 0) {\n\t\t\t\t\tvar gain = false;\n\t\t\t\t} else {\n\t\t\t\t\tvar gain = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar data = {\n\t\t\t\t\tprice: format(price),\n\t\t\t\t\tname: quote.price.shortName ? quote.price.shortName : '-',\n\t\t\t\t\tsymbol: quote.price.symbol ? quote.price.symbol : '-',\n\t\t\t\t\tchange: format(price - parseFloat(sd.previousClose)),\n\t\t\t\t\tunformattedChange: (((price / parseFloat(sd.previousClose)) - 1) * 100),\n\t\t\t\t\tpercentChange: (((price / parseFloat(sd.previousClose)) - 1) * 100).toFixed(2) + ' %',\n\t\t\t\t\tgain: (price - parseFloat(sd.previousClose) < 0) ? false : true,\n\t\t\t\t\tvolume: sd.volume ? sd.volume : 0\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tstocks.push(data);\n\t\t\t\tconsole.log(count + ' / ' + companies.length);\n\t\t\t\tcount++;\n\t\t\t\tfindStocksByAPI(companies, stocks, count, cb);\n\t\t\t}\n\t\t});\n\t} else {\n\t\tconsole.log(count + ' / ' + companies.length);\n\t\tconsole.log('\\nSearch Complete!\\n');\n\t\tcb(stocks);\n\t}\n}", "function loadFEETWD(){\n var array = [];\n var url = 'https://api.bitcoinaverage.com/ticker/global/TWD/';\n var json = loadJSON(url);\n array.push([\"BTC/TWD\",json['last']]);\n array.push([\"FEE/TWD\",json['last']/100000]);\n return array;\n}", "trades (symbol, start, limit) {\n if (this.dateToTimestamp) {\n start = dateToTimestamp(start)\n }\n let url = `${baseUrl}/trades/?symbol=${symbol}&start=${start}`\n if (limit && limit <= 300) {\n url += `&limit=${limit}`\n } else if (limit && limit > 300) {\n return 'Exceeds maximum number of trades to fetch (maximum 300).'\n }\n return fetchJSON(url, this.token)\n }", "static requestCurrentPriceForTicker(ticker) {\n return new Promise(resolve => {\n resolve(this.placeApiRequest(\"/api/v3/stock/real-time-price/\" + ticker));\n });\n }", "function requestAlphaVantageData(symbol) {\n var alpha = \"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=974UTD95QA2DV3Y5\";\n var http = new XMLHttpRequest();\n http.open(\"GET\", quandl, true);\n http.onreadystatechange = function () {\n if (http.readyState == 4 && http.status == 200) {\n var response = JSON.parse(http.responseText);\n console.log(response);\n }\n }\n http.send();\n }", "function financeAPI(stockSymbol) {\n\n\tvar stockSettings = {\n async: true,\n crossDomain: true,\n // \"url\": \"https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-summary?region=US&lang=en&\",\n url:\n \"https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes?region=US&lang=en&symbols=\" +\n stockSymbol +\n \"%252CKC%253DF%252C002210.KS%252CIWM%252CAMECX\",\n method: \"GET\",\n headers: {\n \"x-rapidapi-host\": \"apidojo-yahoo-finance-v1.p.rapidapi.com\",\n \"x-rapidapi-key\": \"d70d653601mshede7e7ed8e9af16p124362jsn3d74fdf16a19\"\n }\n };\n\n\t$.ajax(stockSettings).done(function (stockResponse) {\n\t\tconsole.log(stockResponse);\n\t\tvar cur = stockResponse.quoteResponse.result[0];\n\n\t\tsym1 = cur.symbol;\n\t\tmarketPrice = cur.regularMarketPrice;\n\t\tmarketPrice = parseFloat(marketPrice).toFixed(2);\n\t\t$(\"#defaultPrice\").text(marketPrice);\n\t\t\n\t\t\tlockPrice = marketPrice;\n\t\t\tbtn_press = false;\n\t\t\tcurrencyAPI(\"EUR\", lockPrice);\n\t\t\tcurrencyAPI(\"JPY\", lockPrice);\n\t\t\tcurrencyAPI(\"GBP\", lockPrice);\n\t\t\n\t\tvar newListItem = '<li id=\"searchHist\">' + stockSymbol + ' Selling For$' + marketPrice + '</li>';\n\t\t$('#searchResult').prepend(newListItem);\n\n\t});\n}", "function updateBitcoin(url)\n {\n // bitcoinData will hold all requested data(typically object or array) in JSON format\n $.getJSON(url, (bitcoinData) =>\n {\n\t const container = document.getElementById('bitcoin');\n\t\t\t container.innerHTML = bitcoinData.bpi.USD.rate;\n });\n }", "function getHistoricalData(symbolArray, ytd){\n let month = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n let a = new Date();\n let b;\n if (ytd){\n b = new Date(\"january 1 \"+a.getFullYear());\n } else {\n b = new Date(month[a.getMonth()]+\" \"+a.getDate()+\" \"+(parseInt(a.getFullYear()) - 2));\n }\n return new Promise((resolve, reject) => {\n if (symbolArray.length < 1 || symbolArray.constructor != Array){\n return reject({});\n }\n yahooFinance.historical({\n symbols: symbolArray,\n from: b,\n to: a\n }, (err, result) =>{\n if (err) return reject(err);\n resolve(result);\n })\n })\n}", "async function getStockPrice() {\n // const API_KEY = \"EFHRQZLWSBDE89TC\";\n // const stockPRICE = await axios.get(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${API_KEY}`);\n // DEMO API ===> IBM //\n const stockPRICE = await axios.get(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=demo`); \n setCompanyCurrentPrice(stockPRICE.data[\"Global Quote\"][\"05. price\"]);\n setCompanyDayChange(stockPRICE.data[\"Global Quote\"][\"09. change\"]);\n setCompanyDayChangePercent(stockPRICE.data[\"Global Quote\"][\"10. change percent\"]);\n \n }", "async function getTrend() {\n const trendURL = 'https://api.coingecko.com/api/v3/search/trending'\n try {\n const response = await axios.get(trendURL)\n const trend = response.data.coins\n showTrendInfo(trend)\n return response\n } catch (err) {\n console.error(err)\n }\n \n // Function that displays and appends current trending coins\n function showTrendInfo(trend) {\n const trendContainer = document.querySelector(\"#hot-coins\")\n \n const trendInfo = `\n <p class='trendName1'>${trend[0].item.name}</p>\n <p class='trendName2'>${trend[1].item.name}</p>\n <p class='trendName3'>${trend[2].item.name}</p>\n <p class='trendName4'>${trend[3].item.name}</p>\n <p class='trendName5'>${trend[4].item.name}</p>\n <p class='trendName6'>${trend[5].item.name}</p>\n `\n trendContainer.insertAdjacentHTML('beforeend', trendInfo)\n \n }\n \n }", "async getCryptocurrency (){\n const url = await fetch ('https://api.coinmarketcap.com/v1/ticker/');\n\n //Convert url values to JSON\n const cryptocurrency = await url.json();\n\n //return JSON values as object\n return {cryptocurrency}\n }", "async getQuote() {\n const response1 = await fetch(\n `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${\n this.symbol\n }&interval=${this.interval}&apikey=${this.apiKey}`\n );\n\n const response1Data = await response1.json();\n\n return response1Data;\n }", "function getQuotes(symbols, cb){\n //console.log(symbols.toString())\n fetch(\"https://www.freeforexapi.com/api/live?pairs=\" + symbols.toString(), {\n \"Accept\" : \"application/json\",\n \"Content-Type\" : \"application/json\",\n \"User-Agent\" : random_useragent.getRandom() // gets a random user agent string\n })\n .then(res => res.json())\n .then(json => {\n if(json.supportedPairs == undefined){\n if(json.code == 200){\n //console.log(json.rates);\n return cb(json.rates);\n } \n }\n return cb({\"error\":\"Pass correct pairs, check symbols first\"});\n })\n .catch(error => { \n console.log(error.message);\n })\n}", "async function fetch() {\n var price_feed = await retry(async bail => await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,chainlink,yearn-finance,ethlend,havven,compound-governance-token,ethereum&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true'))\n\n var contracts = [\n \"0x75c23271661d9d143dcb617222bc4bec783eff34\", //WETH-USDC\n \"0x562c0b218cc9ba06d9eb42f3aef54c54cc5a4650\", //LINK-USDC\n \"0xc226118fcd120634400ce228d61e1538fb21755f\", //LEND-USDC\n \"0xca7b0632bd0e646b0f823927d3d2e61b00fe4d80\", //SNX-USDC\n \"0x0d04146b2fe5d267629a7eb341fb4388dcdbd22f\", //COMP-USDC\n \"0x2109f78b46a789125598f5ad2b7f243751c2934d\", //WBTC-USDC\n \"0x1b7902a66f133d899130bf44d7d879da89913b2e\", //YFI-USDC\n ]\n var balanceCheck = '0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3';\n var tvl = 0;\n\n var contract = '0x75c23271661d9d143dcb617222bc4bec783eff34';\n var token = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';\n let balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data.ethereum.usd)\n\n var contract = '0x562c0b218cc9ba06d9eb42f3aef54c54cc5a4650';\n var token = '0x514910771af9ca656af840dff83e8264ecf986ca';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data.chainlink.usd)\n\n var contract = '0xc226118fcd120634400ce228d61e1538fb21755f';\n var token = '0x80fB784B7eD66730e8b1DBd9820aFD29931aab03';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data.ethlend.usd)\n\n var contract = '0xca7b0632bd0e646b0f823927d3d2e61b00fe4d80';\n var token = '0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data.havven.usd)\n\n\n var contract = '0x0d04146b2fe5d267629a7eb341fb4388dcdbd22f';\n var token = '0xc00e94cb662c3520282e6f5717214004a7f26888';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data['compound-governance-token'].usd)\n\n\n var contract = '0x2109f78b46a789125598f5ad2b7f243751c2934d';\n var token = '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data.bitcoin.usd)\n\n\n var contract = '0x1b7902a66f133d899130bf44d7d879da89913b2e';\n var token = '0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e';\n balance = await utils.returnBalance(token, contract);\n tvl += (parseFloat(balance) * price_feed.data['yearn-finance'].usd)\n\n await Promise.all(\n contracts.map(async contract => {\n var contract = contract;\n var token = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';\n let balance = await utils.returnBalance(token, contract);\n tvl += parseFloat(balance)\n\n })\n )\n\n return tvl;\n\n\n}", "getExchangeRates(cb) {\n $.get({\n url: 'http://api.fixer.io/latest?base=GBP',\n }, function(err, res, body) {\n if (err || !body) return cb(err || 'Something went wrong', null)\n return cb(null, body.rates)\n })\n }", "async getPriceHistory(symbol) {\n try {\n const stockPriceHistoryURL = `https://financialmodelingprep.com/api/v3/historical-price-full/${symbol}`;\n let rawData = await fetch(stockPriceHistoryURL);\n let data = await rawData.json();\n return data.historical;\n } catch (err) {\n return {}\n }\n }", "function currencyAPI(currencySymbols, amountUSD) {\n\n\tconsole.log(currencySymbols+\" \"+amountUSD);\n\tvar settings = {\n\t\t\"async\": true,\n\t\t\"crossDomain\": true,\n\t\t\"url\": \"https://currency-converter5.p.rapidapi.com/currency/convert?format=json&from=USD&to=\" + currencySymbols + \"&amount=\" + amountUSD,\n\t\t\"method\": \"GET\",\n\t\t\"headers\": {\n\t\t\t\"x-rapidapi-host\": \"currency-converter5.p.rapidapi.com\",\n\t\t\t\"x-rapidapi-key\": \"92cebe218cmshe8d74a9c1f090cep1da599jsn481891ebdf92\"\n\t\t}\n\t};\n\n\t$.ajax(settings).done(function (response) {\n\t\trate = \"response.rates\" + currencySymbols + \".rate\";\n\t\tconsole.log(response);\n\t\tcurrencyReturn = response.rates[currencySymbols].rate_for_amount;\n\t\tcurrencyReturn = parseFloat(currencyReturn).toFixed(2);\n\t\tif (currencySymbols === \"EUR\") {\n\t\t\tlockPrice = marketPrice;\n\t\t\t// currencyAPI(\"EUR\", marketPrice);\n\t\t\t$(\"#defaultCtry1\").html(\" = \" + currencyReturn);\n\t\t}\n\t\tif (currencySymbols === \"JPY\") {\n\t\t\tlockPrice = marketPrice;\n\t\t\t// currencyAPI(\"JPY\", marketPrice);\n\t\t\t$(\"#defaultCtry2\").html(\"= \" + currencyReturn);\n\t\t}\n\t\tif (currencySymbols === \"GBP\") {\n\t\t\tlockPrice = marketPrice;\n\t\t\t// currencyAPI(\"GBP\", marketPrice);\n\t\t\t$(\"#defaultCtry3\").html(\" = \" + currencyReturn);\n\t\t}\n\t\tif (CCflag) {\n\t\t\t$(\"#displayCurrencyValue\").html(newsym+\" = \" + currencyReturn);\n\t\t\tdisplayCurrencyValue\n\t\t\tconsole.log(CCflag+ \"currencyReturn=\" + currencyReturn + \" stockSymbol=\" + newsym);\n\t\t\tCCflag = false;\n\t\t}\n\t});\n}", "async updateRate() {\n let avgPriceSrv = await this.client.avgPrice({symbol: this.pair});\n avgPriceSrv = Number(avgPriceSrv.price);\n let res = await this.client.trades({symbol: this.pair});\n let totalPrice = 0;\n res.forEach(el => totalPrice += Number(el.price));\n\n let totalPriceForWeight = 0;\n let totalDividerForWeight = 0;\n let weightBase = Number(res[0].qty); \n//{\"id\":268893991,\"price\":\"4523.21000000\",\"qty\":\"0.01888200\",\"quoteQty\":\"85.40725122\",\"time\":1584356745682,\"isBuyerMaker\":true,\"isBestMatch\":true}\n res.forEach(el => {\n let k = Number(el.qty) / weightBase;\n totalPriceForWeight += Number(el.price) * k; \n totalDividerForWeight += k;\n });\n\n let avgPriceWeighted = (totalPriceForWeight / totalDividerForWeight);\n\n/*\n openTime: 1508328900000,\n open: '0.05655000',\n high: '0.05656500',\n low: '0.05613200',\n close: '0.05632400',\n volume: '68.88800000',\n closeTime: 1508329199999,\n quoteAssetVolume: '2.29500857',\n trades: 85,\n baseAssetVolume: '40.61900000',\n*/\n let candles = await this.client.candles({symbol: this.pair, interval: '1m', limit: 1});\n let sum = 0;\n let sum1 = 0;\n let lastPrice = 0;\n /*candles.forEach(el => {\n let delta = Number(el.close) - Number(el.open);\n sum += delta * Number(el.volume);\n \n sum1 = delta * Number(el.volume);\n\n // let deltaEx = Number(el.close) - Number(el.open);\n lastPrice = el.close;\n });*/\n\n let el = candles[0];\n\n let fut = await this.futuresCalc(avgPriceWeighted);\n // let fut = await this.futuresCalc(el.close);\n\n console.log('delta [' + (Number(el.close) - Number(el.open)) + '] deltaMax [' + (Number(el.high) - Number(el.low)) + '] volume [' + el.quoteAssetVolume + ', ' + el.baseAssetVolume + '] : price ' + el.close, \n '[ fut+', fut.sellMass + '/' + fut.sellMass2 + ']', '[ fut-', fut.buyMass + '/' + fut.buyMass2 + ']', ' | avg', avgPriceWeighted);\n // console.log('trend 3 [' + sum + '] trend 1 [' + sum1 + '] : price ' + lastPrice, ' | avg', avgPriceWeighted);\n\n // this.data.arr.push({time: Date.now(), avg: avgPriceSrv, price: avgPriceWeighted});\n\n // this.saveFile(this.data);\n }", "getAllRates() {\r\n axios.get(`https://api.exchangeratesapi.io/latest?base=${this.baseCurrency}`)\r\n .then((resp) => {\r\n this.dispatchBaseRates(resp.data.rates);\r\n })\r\n .catch((error) => console.error(error))\r\n }", "async queryAPI(currency, cryptocurrency){\n const url = await fetch(`https://api.coinmarketcap.com/v1/ticker/${cryptocurrency}/?convert=${currency}`);\n\n //covert result to JSSON\n const result = await url.json();\n\n return {result}\n }", "async getCurrencies() {\n let url = this.#endpoints.currencies;\n let payload = {\n accessToken: this.apiKey\n }\n let config = {\n method: \"post\",\n body: JSON.stringify(payload)\n };\n\n return this.#request(url, config)\n .then(response => {\n if (response.success) {\n return response\n } \n throw Error(response.message)\n })\n .catch(err => { throw Error(err.message) });\n }", "function getBTCPriceAsync() {\n return new Promise(function(resolve, reject) {\n $.ajax({\n type: \"GET\",\n beforeSend: function(xhttp) {\n xhttp.setRequestHeader(\"Content-type\", \"application/json\");\n xhttp.setRequestHeader(\"X-Parse-Application-Id\", chrome.runtime.id);\n },\n url: 'https://bittrex.com/api/v1.1/public/getticker?market=USDT-BTC',\n success: function(response) {\n resolve(response.result['Bid']);\n console.log(response.result['Bid']);\n\n },\n error: function(msg) {\n resolve(msg);\n }\n });\n });\n}", "async function example1 () {\n exchange['options']['defaultType'] = 'spot'; // very important set spot as default type\n\n await exchange.loadMarkets ();\n\n // fetch spot balance\n const balance = await exchange.fetchBalance ();\n console.log (balance)\n\n // create order\n const symbol = 'LTC/USDT';\n const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', 50, 0.1);\n console.log ('Created order id:', createOrder['id'])\n\n // cancel order\n const cancelOrder = await exchange.cancelOrder (createOrder['id'], symbol);\n\n // Check canceled orders (bybit does not have a single endpoint to check orders\n // we have to choose whether to check open or closed orders and call fetchOpenOrders\n // or fetchClosedOrders respectively\n const canceledOrders = await exchange.fetchClosedOrders (symbol);\n console.log (canceledOrders);\n}", "function updateData() {\n // Scrape TopX volume pairs from CoinMarketCap\n if(checkVolume) {\n request(cmcExchanges,(error,response,html)=>{\n var $ = cheerio.load(html)\n $('#markets > div.table-responsive > table > tbody > tr > td > a').each((i,element)=>{\n var omg = $(element).attr('href')\n if(Exchange == 'bittrex') {\n if(omg.match(/MarketName/i)) {\n var pair = omg.replace(\"https://bittrex.com/Market/Index?MarketName=\",\"\")\n if (pair.match(/^(BTC-)/i)) {\n pairs.push(pair)\n }\n }\n } else if(Exchange == 'poloniex') {\n if(omg.match(/exchange/i)) {\n var pair = omg.replace(\"https://poloniex.com/exchange/#\",\"\")\n if (pair.match(/^(btc_)/i)) {\n pairs.push(pair)\n }\n }\n }\n });\n setTimeout(buildPairs, 3000)\n });\n }\n if(checkTrend) {\n request('https://api.coinmarketcap.com/v1/ticker/?limit='+checkCoins, { json: true }, (err, res, body) => {\n if (err) { return console.log(err); }\n if (trendTime==\"1h\") var average = _.meanBy(body, (b) => parseInt(b.percent_change_1h))\n if (trendTime==\"24h\") var average = _.meanBy(body, (b) => parseInt(b.percent_change_24h))\n if (trendTime==\"7d\") var average = _.meanBy(body, (b) => parseInt(b.percent_change_7d))\n console.log(\"Top \"+checkCoins+\" Coins Trend (\"+trendTime+\"): \" + average + \"%\")\n });\n }\n}", "startTickerStream( reconnect ) {\n this.setReconnect( 'ticker', reconnect || false );\n this.emit( 'ticker_init', Date.now() );\n\n const ws = this.sockConnect( 'ticker', this._wssurl +'/ws/!ticker@arr' );\n if ( !ws ) return this.emit( 'ticker_fail', 'Could not connect to live ticker stream API endpoint.' );\n\n ws.addEventListener( 'open', e => {\n this.emit( 'ticker_open', e );\n this.startTickerTimer();\n });\n\n ws.addEventListener( 'error', e => {\n this.emit( 'ticker_error', e );\n this.stopTimer( 'ticker' );\n });\n\n ws.addEventListener( 'close', e => {\n this.emit( 'ticker_close', e );\n this.stopTimer( 'ticker' );\n this.checkReconnect( 'ticker', () => this.startTickerStream( reconnect ) );\n });\n\n ws.addEventListener( 'message', e => {\n this.emit( 'ticker_data', true );\n let list = JSON.parse( e.data || '[]' ) || [];\n let markets = Object.keys( this._markets );\n let count = list.length;\n\n // wait for markets data to be available before creating symbols\n if ( !markets.length || !count ) return;\n\n while ( count-- ) {\n let ticker = list[ count ];\n let pair = ticker.s; // trading pair symbol str\n let symbol = this._symbols[ pair ] || new Symbol( pair ); // cached\n\n symbol.splitSymbol( markets ); // split pair symbol into token / market\n symbol.setCoinData( this._coindata[ symbol.token ] ); // data from coincap.io\n symbol.setTickerData( ticker ); // update symbol ticker data\n symbol.resolveImage(); // find an icon for this token\n this._symbols[ pair ] = symbol; // update cache\n }\n });\n }", "function get24HETHData() {\r\n\tvar result;\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET',\r\n\t\t'https://min-api.cryptocompare.com/data/v2/histohour?fsym=ETH&tsym=USD&limit=24&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false);\r\n\trequest.send(null);\r\n\tresult = JSON.parse(request.responseText);\r\n\treturn result;\r\n}", "function getDataFromThirdParty(){\n return new Promise((resolve,reject)=>{\n var binance = binanceInstance(\"\",\"\");\n let accountFunds = binance.prices();\n accountFunds.then((sucess)=>{\n console.log(\"Going to updated in Koinfox DB\",sucess);\n // save here in DB\n })\n .catch((error)=>{\n console.log(\"Error occured while fetching funds\",error);\n });\n })\n}", "async function getAllPrices() {\n let tokensDetailedInfoRequest = await fetch(\n \"https://api.kyber.network/market\"\n );\n let tokensDetailedInfo = await tokensDetailedInfoRequest.json();\n return tokensDetailedInfo;\n }", "function getQuote(ticker) {\r\n const queryURL = `https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/v2/get-quotes?symbols=${ticker}&region=US`;\r\n console.log(queryURL);\r\n// this are the required headers to be passed in with the url to the fetch\r\n const options = {\r\n headers: new Headers({\r\n \"x-rapidapi-host\": \"apidojo-yahoo-finance-v1.p.rapidapi.com\",\r\n \"x-rapidapi-key\": apiKey\r\n })\r\n };\r\n\r\n fetch(queryURL, options)\r\n .then(response => response.json())\r\n .then(responseJson => displayQuote(responseJson))\r\n .catch(err => {\r\n console.log(err);\r\n $('#js-quote-error-message').text(`We don't recognize that ticker. Please try another`);\r\n $('#results-list').empty();\r\n })\r\n}", "async function getQuotes() {\n setShowErrorMessage(false);\n setShowCurrencyData(false);\n const apiurl = BASE_URL+`/latest?access_key=${api_key}&symbols=${targetCurrencies}&base=${cryptoCode}&amount=1`\n const fetchCurrencyValues = await fetch(apiurl);\n const currencyValues = await fetchCurrencyValues.json();\n processCurrencyValues(currencyValues);\n }", "function App() {\n\n const [marketData,setMarketData] = useState([])\n\n useEffect(() => {\n fetchData()\n }, [])\n\n function fetchData(){\n\n fetch('http://api.marketstack.com/v1/tickers?access_key=661b2b31730d1d045e13f3377036353e')\n .then(resp=>resp.json())\n .then(data=>{\n console.log(data.data)\n setMarketData(data.data)\n // let marketSymbols = data.data.map((ticker)=>(ticker.symbol)).toString()\n // fetch(`http://api.marketstack.com/v1/intraday?access_key=661b2b31730d1d045e13f3377036353e&symbols=${marketSymbols}`)\n // .then(resp=>resp.json())\n // .then(data=>{\n // console.log(data.data)\n // setMarketData(data.data)\n // })\n })\n .catch(err=>console.log(err))\n }\n\n\n return (\n <div className=\"App\">\n <div><h3>Penny Stocks API</h3></div>\n <Col xs={12} sm={12} lg={10} className=\"align-auto\">\n <Table striped bordered hover>\n <thead>\n <tr>\n <td>Rank</td>\n <td>Name</td>\n <td>Open</td>\n <td>Last</td>\n <td>Country</td>\n {/* <td>Market Cap</td>\n <td>Price</td>\n <td>Today</td>\n <td>Price (30 Days)</td> CHART JS IMPLEMENTATION PLUGIN\n <td>Country</td> */}\n </tr>\n </thead>\n <tbody>\n { marketData.length && marketData.map((ticker, i)=>{\n return(\n <TableRow \n index={i + 1}\n name={ticker.name}\n symbol={ticker.symbol}\n country={ticker.stock_exchange.country}\n />\n )\n })}\n {/* <TableRow\n stock={{rank: 3, name: 'Microsoft', marketCap: 1.848, price: 244.99, today: 0.20, country: 'USA'}}\n /> */}\n </tbody>\n </Table>\n </Col>\n </div>\n );\n}", "get(bet_param) {\n const _this = this;\n const t = this.t;\n bet_param = this.processBarrier(bet_param);\n const contract_map = {\n ASIANU: (param) => {\n return t.translate('[currency] [amount] payout if the last tick of [underlying] is strictly higher than the average of the [tick_count] ticks.', param);\n },\n ASIAND: (param) => {\n return t.translate('[currency] [amount] payout if the last tick of [underlying] is strictly lower than the average of the [tick_count] ticks.', param);\n },\n CALL: (param) => {\n if (param.tick_expiry === 1) { // Tick trade\n return t.translate('[currency] [amount] payout if [underlying] after [tick_count] ticks is strictly higher than [entry_spot].', param)\n }\n\n if (param.is_forward_starting === 1) {\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n param.date_start = _this.getDateTime(param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] is strictly higher than [entry_spot] at [duration] after [date_start].', param)\n }\n\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n // Daily normal constracts.\n param.date_expiry = 'close on ' + _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] is strictly higher than [entry_spot] at [date_expiry].', param)\n }\n\n if (param.fixed_expiry === 1) { //Fixed expiry\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] is strictly higher than [entry_spot] at [date_expiry].', param)\n }\n // Intraday normal contracts having duration in minutes, seconds, or hours.\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] is strictly higher than [entry_spot] at [duration] after contract start time.', param)\n },\n DIGITDIFF: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is not [barrier] after [tick_count] ticks.', param);\n },\n DIGITEVEN: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is even after [tick_count] ticks.', param);\n },\n DIGITMATCH: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is [barrier] after [tick_count] ticks.', param);\n },\n DIGITODD: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is odd after [tick_count] ticks.', param);\n },\n DIGITOVER: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is higher than [barrier] after [tick_count] ticks.', param);\n },\n DIGITUNDER: (param) => {\n return t.translate('[currency] [amount] payout if last digit of [underlying] is lower than [barrier] after [tick_count] ticks.', param);\n },\n EXPIRYMISS: (param) => {\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n param.date_expiry = _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] ends outside [low_barrier_str] to [high_barrier_str] at close on [date_expiry].', param);\n }\n\n if (param.fixed_expiry === 1) {\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] ends outside [low_barrier_str] to [high_barrier_str] at [date_expiry].', param);\n }\n\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] ends outside [low_barrier_str] to [high_barrier_str] at [duration] after contract start time.', param);\n },\n EXPIRYRANGE: (param) => {\n\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n param.date_expiry = _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] ends strictly between [low_barrier_str] to [high_barrier_str] at close on [date_expiry].', param);\n }\n\n if (param.fixed_expiry === 1) {\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] ends strictly between [low_barrier_str] to [high_barrier_str] at [date_expiry].', param);\n }\n\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] ends strictly between [low_barrier_str] to [high_barrier_str] at [duration] after contract start time.', param);\n },\n NOTOUCH: (param) => {\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n param.date_expiry = _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] does not touch [entry_spot] through close on [date_expiry].', param);\n }\n\n if (param.fixed_expiry === 1) {\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] does not touch [entry_spot] through [date_expiry].', param);\n }\n\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] does not touch [entry_spot] through [duration] after contract start time.', param);\n },\n ONETOUCH: (param) => {\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n param.date_expiry = _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] touches [entry_spot] through close on [date_expiry].', param);\n }\n\n if (param.fixed_expiry === 1) {\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] touches [entry_spot] through [date_expiry].', param);\n }\n\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] touches [entry_spot] through [duration] after contract start time.', param);\n },\n PUT: (param) => {\n if (param.tick_expiry === 1) { // Tick trade\n return t.translate('[currency] [amount] payout if [underlying] after [tick_count] ticks is strictly lower than [entry_spot].', param)\n }\n\n if (param.is_forward_starting === 1) {\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n param.date_start = _this.getDateTime(param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] is strictly lower than [entry_spot] at [duration] after [date_start].', param)\n }\n\n if (_this.isDaily(param.date_expiry - param.date_start)) {\n // Daily normal constracts.\n param.date_expiry = 'close on ' + _this.getDate(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] is strictly lower than [entry_spot] at [date_expiry].', param)\n }\n\n if (param.fixed_expiry === 1) { //Fixed expiry\n param.date_expiry = _this.getDateTime(param.date_expiry);\n return t.translate('[currency] [amount] payout if [underlying] is strictly lower than [entry_spot] at [date_expiry].', param)\n }\n // Intraday normal contracts having duration in minutes, seconds, or hours.\n param.duration = _this.getDuration(param.date_expiry - param.date_start);\n return t.translate('[currency] [amount] payout if [underlying] is strictly lower than [entry_spot] at [duration] after contract start time.', param)\n },\n SPREAD: () => {\n return t.translate('Legacy contract. No further information is available.');\n }\n };\n if(typeof contract_map[bet_param.bet_type] === 'undefined'){\n return 'Invalid short code.';\n }\n return contract_map[bet_param.bet_type](bet_param);\n }", "async function pushStockPrice(name){\n let url = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol='+name+'&apikey='+process.env.AV_API_KEY;\n return await axios.get(url)\n }", "async function syncHistoricalPriceData() {\n let market_chart;\n let daysAgo = 90;\n\n console.log('MARKETS: ', markets);\n for(let market of markets) {\n \n let query = 'https://api.coingecko.com/api/v3/coins/'+market.asset+'/market_chart?vs_currency='+market.base+'&days='+daysAgo;\n console.log(\"Market_Chart query: \", query);\n market_chart = await axios.get(query);\n market_chart = market_chart.data;\n // Now $market_chart contains hourly data. It is \"condensed\", meaning we've got a single price value for that hour -\n // there are no open/close or top/bottom values. Potentially we could have finer data in the database. We don't\n // want to blindly substitute data in the database with the data we just fetched from Coingecko.\n // On the other hand we can use $market_chart to expand our daily data (i.e. to have open/close, top/bottom price values),\n // if it's not already expanded\n\n // the result from CoinGecko is ordered such as the first element is the oldest price (as expected and the same way\n // we store price history)\n \n HourlyPrice.fetchLastHourData(market.id, (err, lastHourData) => {\n if(err != null) {\n console.error(\"ERROR: \", err);\n return;\n }\n // $market_chart dictates the timestamp\n // this means inside tick() we need to regularly call market_chart API in order to keep the database in sync\n // 1625226282960\n for(let priceAtHour of market_chart.prices) {\n let price = priceAtHour[1];\n let hour = priceAtHour[0];\n\n //let priceMomentFound = false;\n console.log(\"price entry: \", priceAtHour);\n if(lastHourData.timestamp < hour) {\n let priceEntry = new HourlyPrice({\n market: market.id,\n condensed: true,\n date: null,\n timestamp: hour,\n priceOpen: 0,\n priceClose: price,\n priceBottom: 0,\n priceTop: 0,\n });\n console.log(\"Saving\");\n priceEntry.save();\n }\n // for(let priceRow of dataInDatabase) {\n // if(priceRow.timestamp == hour) {\n // break;\n // }\n // }\n }\n });\n }\n}", "async function getCurrenciesList() {\n const apiUrl = 'https://api.coinmarketcap.com/v2/listings';\n\n const resp = await axios(apiUrl);\n const data = await resp.data;\n const list = data.data;\n\n return list;\n}", "function getData() {\n console.time(\"Peticion\");\n $.ajax({\n url: \"https://api.coinpaprika.com/v1/tickers\",\n type: 'GET',\n dataType: \"json\",\n success: function(response) {\n // array with 100 positions \n allData = response;\n // filter th array \n first100 = response.filter((elem) => elem.rank > 0 && elem.rank <= 100);\n // validation \n if (first100[0] == null) {\n return;\n }\n first100.sort((a, b) => a.rank - b.rank);\n // change display of loader \n document.getElementById(\"loader\").style.display = \"none\";\n // call functions to render tables \n renderView(first100, tab);\n // get filter data \n flMarketcap = marketCapFilter(allData);\n flVolumen = volume24hFilter(allData);\n flPrice = priceFilter(allData);\n\n dinamicValues();\n },\n error: function(error) {\n console.log(error);\n }\n });\n}", "getBalance(callback){\n \n const api_data = {\n api_name:'/get-balance',\n coin:this.coin,\n api_key: this.apikey,\n password : this.api_password,\n };\n api_call.apiPostCall(api_data,{},callback);\n }", "getPricesIntraday(ticker){\n\n\n const currTimestamp = getCurrentTimestamp();\n let prices = [];\n\n return fetch(baseURLext + intraDayQuery + ticker + intraDayParams60min + key2)\n .then(doc => doc.json())\n .then((doc) => {\n if(doc[\"Meta Data\"]){\n const latestTimestamp = doc[\"Meta Data\"][\"3. Last Refreshed\"];\n const latestDay = latestTimestamp.slice(8,10)\n const latestHour = latestTimestamp.slice(11,13)\n\n const sharesData = Object.values(doc[\"Time Series (60min)\"])\n\n const closingTime = \"15:30:00\"\n\n if(currTimestamp.day > latestDay){ //if market has not opened today\n for(let i = 0; i < 7; i++){\n prices.push(parseFloat(sharesData[i][\"4. close\"])) //Get yesterdays prices\n }\n }else if(currTimestamp.time >= closingTime){ //if market has closed for the day\n for(let i = 0; i < 7; i++){\n prices.push(parseFloat(sharesData[i][\"4. close\"])) //get todays prices\n }\n }else if(currTimestamp.time < closingTime){ //if market is open\n const priceIntervals = latestHour - 8; //Calculate how many prices intervals there are\n for(let i = 0; i < priceIntervals; i++){\n prices.push(parseFloat(sharesData[i][\"4. close\"])); //get prices\n }\n }\n return prices;\n }\n return null;\n })\n }", "candles (symbol, step, end, start) {\n if (this.dateToTimestamp) {\n start = dateToTimestamp(start)\n end = dateToTimestamp(end)\n }\n let url = `${baseUrl}/candles/?symbol=${symbol}&step=${step}&end=${end}&start=${start}`\n return fetchJSON(url, this.token)\n }", "async function getLatestPrice_PTA_BTC() {\n //curl --data \"market=PTA/BTC\" \"https://api.hotbit.io/v2/p1/market.last\"\n try {\n let resp = await execFile('curl', ['--data', 'market=PTA/BTC', constant.BaseUrl_P1 + \"market.last\"]);\n //let resp = await fetch(constant.BaseUrl_P1 + \"market.last\", {method: 'POST', body: 'market=PTA/BTC'});\n //let data = await resp.json();\n let data = JSON.parse(resp.stdout);\n if(!data.err) { \n return parseFloat(data.result);\n }\n return null; \n\n } catch(err) {\n console.error(\"Error message\" + err);\n }\n\n}", "function fetchSeriesData() {\n return new Promise((resolve, reject) => {\n fetch(\"https://www.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m\")\n .then(async (res) => {\n const data = await res.json();\n const result = data.map(([time, open, high, low, close]) => ({\n time,\n open,\n high,\n low,\n close,\n }));\n resolve(result);\n })\n .catch((e) => reject(e));\n });\n }", "function callAPIUsingFetch(){\n fetch(URL).then(res=> res.json()).then(parsedData=>{\n const value = parsedData.bpi.USD.rate_float;\n priceText.innerText = value;\n })\n}", "getPrevStockPrice(ticker, amount = 15, unit = 'minutes', limit = 100) {\n let nycTime = moment_timezone_1.default.tz(new Date().getTime(), 'America/New_York').subtract(amount, unit);\n let timestamp = nycTime.valueOf();\n return axios_1.default.get(`https://api.polygon.io/v2/ticks/stocks/trades/${ticker}/${nycTime.format('YYYY-MM-DD')}`, {\n params: {\n timestamp: timestamp,\n limit,\n apiKey: process.env['ALPACAS_API_KEY'] || \"\",\n reverse: false\n }\n })\n .then((data) => {\n //TODO: We should create a type for the data returned here\n if (data.data.results_count > 0) {\n let priceAsNumber = Number(data.data.results[data.data.results_count - 1].p);\n return Number(priceAsNumber.toFixed(2));\n }\n else {\n this.logger.log(base_1.LogLevel.ERROR, `Failed to get previous price for ${ticker}`);\n throw new exception.UnprocessableTicker(ticker);\n }\n });\n }", "async function getBitcoinRSI() {\n try {\n const historicalBitcoinData = await axios.get(\n \"https://api.coincap.io/v2/assets/bitcoin/history?interval=d1&start=1577797200000&end=1623527003000\"\n );\n\n // extract the data out in a format data array format chart.js requires. Destructure the returned dataObject\n var { dataPoints, dataLabels } = massageData(\n historicalBitcoinData.data.data\n );\n\n // now do the RSI component\n var rsiData = RSI(dataPoints);\n\n // draw the actual chart. Also need to supply the RSI data\n // bitcoinChart(dataLabels, dataPoints, \"myChart3\");\n bitcoinChart(dataLabels, rsiData, \"myChart3\");\n\n // now plot the actual chart\n } catch (error) {\n console.log(\"The errors is: \", error);\n }\n}", "async getCurrencies() {\n const promises = this.currencies.map(currency =>\n this.getCurrency(currency.symbol)\n );\n\n const responses = await Promise.all(promises);\n return responses.map((response, index) => {\n return response.map(entry => {\n return {\n price: entry.open.toFixed(2),\n timestamp: entry.time * 1000\n };\n });\n });\n }", "function fetchExchangeRateFromAPI(currencyCode, dbo, db, amount) {\n // Perform API Call to get new conversion rate\n var currentExchangeRate = 0;\n fetch(constants.CURRENCYURL)\n .then((response) => response.json())\n .then(function(data) {\n let currencyQuoteData = data.quotes;\n let exchangeTimeStamp = data.timestamp;\n //Frame JSON Object\n var quotes = [];\n var inputData = currencyQuoteData;\n for (var key in inputData) {\n if (inputData.hasOwnProperty(key)) {\n quotes.push({\n \"keypair\": key,\n \"value\": inputData[key],\n \"timestamp\": exchangeTimeStamp\n });\n if (key == currencyCode) {\n currentExchangeRate = inputData[key];\n }\n }\n }\n //Save the data to db\n dbo.collection(constants.COLLECTIONNAME).remove({}, function(err, result) {\n if (err) {\n throw err;\n } else {\n dbo.collection(constants.COLLECTIONNAME).insertMany(quotes, function(err, res) {\n if (err) {\n throw err;\n } else {\n //Do Nothing\n huobiCall(amount / currentExchangeRate, dbo, db);\n }\n });\n }\n });\n })\n .catch(function(error) {\n console.log(\"Error in file elaprice.js\" + error);\n });\n}", "function getAllTrades(tradingPair, timestamp) {\n //Setup query parameters\n const queryParams = {\n limit_trades: 500,\n }\n if (timestamp) {\n queryParams.since = timestamp\n }\n axios\n .get(\n `${process.env.GEMINI_REST}/trades/${tradingPair}${objectToQuery(\n queryParams,\n )}`,\n )\n .then(({ data }) => {\n //Add exchange and trading pair data to each object in array of objects\n const parsedTrades = data.map((tradeData) => {\n return {\n time: new Date(tradeData.timestampms).toISOString(),\n trade_id: tradeData.tid,\n price: tradeData.price,\n amount: tradeData.amount,\n exchange: 'gemini',\n trading_pair: tradingPair,\n }\n })\n console.log(\n `[GEMINI] REST +${parsedTrades.length} Trades FROM ${tradingPair} - ${parsedTrades[0].time}`,\n )\n insertionBatcher.add(...parsedTrades)\n //If the response consisted of 500 trades\n if (parsedTrades.length === 500) {\n const timestamp = data[data.length - 1].timestampms\n //Then recursively get the next 500 trades\n //Requests are rate limited by 1 second in SmartAxios\n getAllTrades(tradingPair, timestamp)\n }\n })\n .catch((err) => {\n if (!err.response.data.reason === 'HistoricalDataNotAvailable') {\n console.log(err)\n console.log(err.message, '\\n^^ GEMINI REST (TRADES)')\n }\n })\n // Example response:\n // [\n // {\n // timestamp: 1563852474,\n // timestampms: 1563852474042,\n // tid: 7544782407,\n // price: '10261.99',\n // amount: '0.00006',\n // exchange: 'gemini',\n // type: 'buy'\n // },\n // ...\n // ]\n}", "function fetchSeriesData() {\n return new Promise((resolve, reject) => {\n fetch('https://www.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m')\n .then(async res => {\n const data = await res.json()\n const result = data.map(([time, open, high, low, close]) => [time, open, high, low, close])\n resolve(result)\n })\n .catch(e => reject(e))\n })\n }", "function convertCurrencies(cr1, cr2) {\n let url = `https://api.exchangeratesapi.io/latest?base=${cr1}&symbols=${cr2}`;\n let xhr = new XMLHttpRequest();\n xhr.open(\n \"GET\",\n url,\n true\n );\n xhr.onload = function() {\n if(this.status == 200) {\n let result = JSON.parse(this.responseText);\n console.log(result.rates[cr2]);\n outputExchangeRate(cr1, cr2, result.rates[cr2]);\n }\n }\n xhr.send();\n}", "async getQuoteEndpointRequest(name) {\r\n const stock = await this.getResourse(\r\n `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${name}&apikey=${this._APIkey}`\r\n );\r\n return this._transformStock(stock);\r\n }", "function getStockPrice (companyName, priceType, date, CloudFnResponse) {\n\n\tconsole.log('In Function Get Stock Price');\n\n\tconsole.log(\"company name: \" + companyName);\n\tconsole.log(\"price type: \" + priceType);\n\tconsole.log(\"Date: \" + date);\n\n\t// \n\t// Step 1: Get the stock ticker for the company \n\t// Step 2: Get the stock details\n\t//\n\tvar stockTicker = \"\";\n\tvar tickerPathString = \"http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=\"\n\t+ companyName \n\t+\"&region=US&lang=en-US&row=ALL&callback=YAHOO.Finance.SymbolSuggest.ssCallback\";\n\n\thttp.get(tickerPathString, (res) => {\n\t\t//console.log('statusCode:', res.statusCode);\n\t\t//console.log('headers:', res.headers);\n\t\n\t\tres.on('data', (d) => {\n\t\t\toutput = d.toString();\n\t\t\t//process.stdout.write(output);\n\t\t\tjsonVal = output.split(\"(\")[1].split(\")\")[0];\n\t\t\tconsole.log(jsonVal);//.split(\")\")[0]).ResultSet.Result[0].symbol;\n\t\t\tconsole.log(JSON.parse(jsonVal).ResultSet.Result[0].symbol);\n\t\t\t\n\t\t\tstockTicker = JSON.parse(jsonVal).ResultSet.Result[0].symbol;\n\t\t\tstockTicker = stockTicker.split('-')[0];\n\t\t\t\n\t\t\tvar seconds = 1;\n\t\t\twhile(stockTicker === '') {\n\t\t\t\tvar waitTill = new Date(new Date().getTime() + seconds * 1000);\n\t\t\t\twhile(waitTill > new Date()){}\n\t\t\t}\n\t\t\tvar msg = \"\";\n\t\t\tif(stockTicker !== '') {\n\t\t\t console.log(\"Stock Ticker = \" + stockTicker);\n\t\t\t\tgetStockDetails(companyName, stockTicker, priceType, date, CloudFnResponse);\n\t\t\t}\n\t\t});\n\t\t\n\t\n\t}).on('error', (e) => {\n\t\tconsole.error(e);\n\t\t});\n\t\n}", "function getbbdata(){\n var bbsurl = bbapiurl\n \n var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象\n httpRequest.open('GET', bbsurl, true);//第二步:打开连接 将请求参数写在url中 ps:\"./Ptest.php?name=test&nameone=testone\"\n httpRequest.send();//第三步:发送请求 将请求参数写在URL中\n /**\n * 获取数据后的处理程序\n */\n httpRequest.onreadystatechange = function () {\n if (httpRequest.readyState == 4 && httpRequest.status == 200) {\n var json = httpRequest.responseText;//获取到json字符串,还需解析\n var obj = eval('(' + json + ')');\n // console.log(obj.data)\n const bbArray = obj.data.map(e => {\n return {\n 'date': e.date,\n 'content': e.content,\n 'from': e.from\n }\n })\n // console.log(fundsArray)\n saveToLocal.set('mj-essay', JSON.stringify(bbArray), 5 / (60 * 24))\n const data = saveToLocal.get('mj-essay');\n generateBBHtml(JSON.parse(data))\n }\n };\n}", "constructor(key, secret) {\n // Keep hold of the API key and secret\n this.key = key;\n this.secret = secret;\n\n this.bfx = new BFX({\n apiKey: key,\n apiSecret: secret,\n transform: true,\n ws: {\n autoReconnect: true,\n seqAudit: false,\n manageOrderBooks: true,\n },\n });\n\n this.ws = this.bfx.ws();\n\n // cache of some data\n this.state = {\n ticker: [],\n wallet: [],\n walletTimer: null,\n offers: [],\n loans: [],\n lastRates: {},\n };\n\n this.calcs = [];\n this.fundingRateChanged = () => {};\n }", "function getBlockAPI(arr){ \n var parameter = arr[0];\n console.log(parameter)\n var id = arr[1];\n var symbol = arr[2];\n var datatype = arr[3];\n var interval = arr[4]; \n fetch(parameter)\n .then(\n function(response) {\n if (response.status !== 200) {\n console.log('Looks like there was a problem. Status Code: ' +\n response.status);\n Table.displayError();\n return;\n }\n response.json().then(function(data) {\n Table.hideError();\n let interval_i = data.interval/1000;\n let plottype = data.plottype;\n if(plottype == \"scatter\"){\n var x = data.x.map(function(x){return x = x/1000 }).sort();\n var y = data.y;\n\n }else{\n var x = processDates(data,interval_i);\n var y = processData(data);\n }\n let coin_data = data.coin;\n let datatype_data = data.datatype;\n let first_date = x[0];\n let last_date = x[x.length-1];\n let last_datatype = data.y[y.length-1];\n\n //Here you will pass data to whatever Graphing library asynchronosly\n if(plottype == \"scatter\"){\n High.addScatterPlot(id,coin_data,datatype_data,x,y);\n Table.addBlockTable(id,coin_data,datatype_data,last_datatype,first_date, last_date, interval, exchange);\n }else{\n High.addBlockGraph(id,coin_data,datatype_data,x,y);\n Table.addBlockTable(id,coin_data,datatype_data,last_datatype,first_date, last_date, interval, exchange);\n }\n });\n }\n )\n .catch(function(err) {\n Table.displayError();\n console.log('Fetch Error :-S', err);\n\n });\n }", "getTickers(symbols, callback) {\n if (symbols && callback) {\n var allSymbolPairs = [];\n symbols.split(',').forEach(symbol => {\n\n var symbolPair = symbol.toLowerCase()+this.convert.toLowerCase();\n allSymbolPairs.push(symbolPair);\n });\n this._getJSON('/v2/tickers?symbols='+allSymbolPairs.join(','), (res) => {\n if (res) { callback(res); }\n });\n return this;\n } else {\n return false;\n }\n }", "function getDataApi(crypt)\n{\n var urlApi = \"https://min-api.cryptocompare.com/data/price?fsym=\"+crypt+\"&tsyms=USD,EUR,RUB,GBP\"\n $.ajax(\n {\n type: \"GET\",\n cache: false,\n url: urlApi,\n dataType:'json',\n error: function(request, error)\n\t{\n\t console.log(error)\n\t alert(\"Can't take request\")\n\t},\n success: function(data)\n\t{\n\t CURRENCY_DATA[crypt] = data\n\t newPrize(CURRENCY_DATA[crypt])\n\t perevod(1000, \"USD\", \"BTC\")\n\t $(\"#\"+crypt).children(\".crypt_prize\").text(\"$\"+CURRENCY_DATA[crypt].USD)\n\t}\n })\n }", "function send() {\n // decide to params for sending by GET methods\n var params = {\n \"status\": config.candlestick.status,\n \"stockcode\": config.candlestick.stockcode,\n \"duration\": config.candlestick.duration\n }\n\n if (config.sma.enable == true) {\n params[\"sma\"] = true;\n params[\"smaPeriod1\"] = config.sma.periods[0];\n params[\"smaPeriod2\"] = config.sma.periods[1];\n params[\"smaPeriod3\"] = config.sma.periods[2];\n }\n\n if (config.ema.enable == true) {\n params[\"ema\"] = true;\n params[\"emaPeriod1\"] = config.ema.periods[0];\n params[\"emaPeriod2\"] = config.ema.periods[1];\n params[\"emaPeriod3\"] = config.ema.periods[2];\n }\n\n if (config.bbands.enable == true) {\n params[\"bbands\"] = true;\n params[\"bbandsN\"] = config.bbands.n;\n params[\"bbandsK\"] = config.bbands.k;\n }\n\n if (config.ichimoku.enable == true) {\n params[\"ichimoku\"] = true;\n }\n\n if (config.rsi.enable == true) {\n params[\"rsi\"] = true;\n params[\"rsiPeriod\"] = config.rsi.period;\n }\n\n if (config.macd.enable == true) {\n params[\"macd\"] = true;\n params[\"macdPeriod1\"] = config.macd.periods[0];\n params[\"macdPeriod2\"] = config.macd.periods[1];\n params[\"macdPeriod3\"] = config.macd.periods[2];\n }\n\n if (config.willr.enable == true) {\n params[\"willr\"] = true;\n params[\"willrPeriod\"] = config.willr.period;\n }\n\n if (config.stochf.enable == true) {\n params[\"stochf\"] = true;\n params[\"stochfPeriod1\"] = config.stochf.periods[0];\n params[\"stochfPeriod2\"] = config.stochf.periods[1];\n }\n\n if (config.stoch.enable == true) {\n params[\"stoch\"] = true;\n params[\"stochPeriod1\"] = config.stoch.periods[0];\n params[\"stochPeriod2\"] = config.stoch.periods[1];\n params[\"stochPeriod3\"] = config.stoch.periods[2];\n }\n\n if (config.events.enable == true) {\n params[\"events\"] = true;\n params[\"EmaEventsEnable\"] = config.events.ema.enable;\n params[\"BBandsEventsEnable\"] = config.events.bbands.enable;\n params[\"IchimokuEventsEnable\"] = config.events.ichimoku.enable;\n params[\"RsiEventsEnable\"] = config.events.rsi.enable;\n params[\"MacdEventsEnable\"] = config.events.macd.enable;\n params[\"WillrEventsEnable\"] = config.events.willr.enable;\n params[\"StochfEventsEnable\"] = config.events.stochf.enable;\n params[\"StochEventsEnable\"] = config.events.stoch.enable;\n }\n\n // ajax(methods is GET)\n $.get(\"/candle\", params).done(function (data) {\n initConfigValues();\n var dataTable = new google.visualization.DataTable();\n // add columns of candles\n dataTable.addColumn('date', 'Date');\n dataTable.addColumn('number', 'Low');\n dataTable.addColumn('number', 'Open');\n dataTable.addColumn('number', 'Close');\n dataTable.addColumn('number', 'High');\n dataTable.addColumn('number', 'Volume');\n var googleChartData = [];\n var candles = data['candles'];\n\n // add columns of indicators\n if (data[\"smas\"] != undefined) {\n sma.addColumns(data, dataTable);\n }\n\n if (data[\"emas\"] != undefined) {\n ema.addColumns(data, dataTable);\n }\n\n if (data['bbands'] != undefined) {\n bbands.addColumns(data, dataTable);\n }\n\n if (data['ichimoku'] != undefined) {\n ichimoku.addColumns(data, dataTable)\n }\n\n if (data['events'] != undefined) {\n if (data['events']['ema_event'] != undefined) {\n ema.addEventColums(data, dataTable)\n }\n if (data['events']['bb_event'] != undefined) {\n bbands.addEventColums(data, dataTable)\n }\n if (data['events']['ichimoku_event'] != undefined) {\n ichimoku.addEventColums(data, dataTable)\n }\n if (data['events']['rsi_event'] != undefined) {\n rsi.addEventColums(data, dataTable)\n }\n if (data['events']['macd_event'] != undefined) {\n macd.addEventColums(data, dataTable)\n }\n if (data['events']['willr_event'] != undefined) {\n willr.addEventColums(data, dataTable)\n }\n if (data['events']['stochf_event'] != undefined) {\n stochf.addEventColums(data, dataTable)\n }\n if (data['events']['stoch_event'] != undefined) {\n stoch.addEventColums(data, dataTable)\n }\n }\n\n if (data['rsi'] != undefined) {\n rsi.addColumns(data, dataTable)\n }\n\n if (data['macd'] != undefined) {\n macd.addColumns(data, dataTable)\n }\n\n if (data['willr'] != undefined) {\n willr.addColumns(data, dataTable)\n }\n\n if (data['stochf'] != undefined) {\n stochf.addColumns(data, dataTable)\n }\n\n if (data['stoch'] != undefined) {\n stoch.addColumns(data, dataTable)\n }\n\n // add datas of candles and indicators\n for (var i = 0; i < candles.length; i++) {\n var candle = candles[i];\n var date = new Date(candle.date);\n // add candles data\n var datas = [date, candle.low, candle.open, candle.close, candle.high, candle.volume];\n\n // add indicators\n if (data[\"smas\"] != undefined) {\n sma.addData(datas, i)\n }\n\n if (data[\"emas\"] != undefined) {\n ema.addData(datas, i)\n }\n\n if (data[\"bbands\"] != undefined) {\n bbands.addData(datas, i)\n }\n\n if (data[\"ichimoku\"] != undefined) {\n ichimoku.addData(datas, i)\n }\n\n if (data[\"events\"] != undefined) {\n if (data['events']['ema_event'] != undefined) {\n ema.addEventData(datas, candle)\n }\n if (data['events']['bb_event'] != undefined) {\n bbands.addEventData(datas, candle)\n }\n if (data['events']['ichimoku_event'] != undefined) {\n ichimoku.addEventData(datas, candle)\n }\n if (data['events']['rsi_event'] != undefined) {\n rsi.addEventData(datas, candle)\n }\n if (data['events']['macd_event'] != undefined) {\n macd.addEventData(datas, candle)\n }\n if (data['events']['willr_event'] != undefined) {\n willr.addEventData(datas, candle)\n }\n if (data['events']['stochf_event'] != undefined) {\n stochf.addEventData(datas, candle)\n }\n if (data['events']['stoch_event'] != undefined) {\n stoch.addEventData(datas, candle)\n }\n }\n\n if (data[\"rsi\"] != undefined) {\n rsi.addData(datas, i)\n }\n\n if (data[\"macd\"] != undefined) {\n macd.addData(datas, i)\n }\n\n if (data[\"willr\"] != undefined) {\n willr.addData(datas, i)\n }\n\n if (data[\"stochf\"] != undefined) {\n stochf.addData(datas, i)\n }\n\n if (data[\"stoch\"] != undefined) {\n stoch.addData(datas, i)\n }\n\n googleChartData.push(datas);\n }\n\n dataTable.addRows(googleChartData);\n drawChart(dataTable);\n })\n}", "function standardAPITicker(APIURL, bidPath = '', askPath = '', lastPath = '', callback) {\n axios.get(APIURL)\n .then((APIres) => {\n var status = parseInt(APIres.status);\n\n if (status == 200) {\n\n //store different prices from response\n var prices = {};\n\n //loop through function arguments for paths to price types\n for (var arg in arguments) {\n if (arg > 0 && arg < 4) { // if we are one of the path arguments\n //set price type\n var priceType = 'bid';\n if (arg == 2) priceType = 'ask';\n else if (arg == 3) priceType = 'last';\n\n //set right path, fetch price from response and store in prices object\n var typePath = arguments[arg];\n if (typePath.length > 0) {\n //non-standard path\n prices[priceType] = APIres.data;\n var pathArr = typePath.split('.');\n for (var pathNode in pathArr) { //pathNode = index of JSON node in pathArr\n prices[priceType] = prices[priceType][pathArr[pathNode]];\n }\n prices[priceType] = parseFloat(prices[priceType]);\n } else prices[priceType] = parseFloat(APIres.data[priceType]); //standard path in JSON response\n\n }\n }\n //return success status code and prices object\n return callback({\n APIStatusCode: status,\n prices: prices\n });\n }\n //if res statuscode was not 200, return code and an error message\n return callback({\n APIStatusCode: status,\n message: 'API returned bad status code'\n });\n })\n .catch((err) => {\n //alert user there was a server error\n return callback({\n APIStatusCode: 404,\n message: String(err)\n });\n });\n}", "function stockPriceProcessing(symbol, Cname) {\n\n var apiKey = \"OITK8BXMQAB96E81\";\n\n var companySymbol = symbol;\n\n var apiUrl2 = \"https://www.alphavantage.co/query?function=GLOBAL_QUOTE\"\n\n var queryURL3 = apiUrl2 + \"&symbol=\" + companySymbol + \"&apikey=\" + apiKey;\n\n $.ajax({\n url: queryURL3,\n method: \"GET\",\n }).then(function (response) {\n console.log(response);\n $(\"#stockData\").empty();\n $(\"#stockData\").append(\"<li><b>\" + Cname + \"</b></li><br>\");\n $(\"#stockData\").append(\"<li><b>Open Price:</b> $\" + response[\"Global Quote\"][\"02. open\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>High Price:</b> $\" + response[\"Global Quote\"][\"03. high\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Low Price:</b> $\" + response[\"Global Quote\"][\"04. low\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Current Price:</b> $\" + response[\"Global Quote\"][\"05. price\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Latest Trading Day:</b> \" + response[\"Global Quote\"][\"07. latest trading day\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Previous Close:</b> $\" + response[\"Global Quote\"][\"08. previous close\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Change:</b> \" + response[\"Global Quote\"][\"09. change\"] + \"</li>\");\n $(\"#stockData\").append(\"<li><b>Change Percent:</b> \" + response[\"Global Quote\"][\"10. change percent\"] + \"</li>\");\n\n percentChange = parseFloat(response[\"Global Quote\"][\"10. change percent\"]);\n percentCheck(percentChange);\n\n });\n}" ]
[ "0.6797348", "0.67624694", "0.6644127", "0.658165", "0.6539851", "0.65306956", "0.64923173", "0.64742863", "0.6467732", "0.6405589", "0.6372627", "0.63693434", "0.6344111", "0.63280475", "0.6306575", "0.62882763", "0.62803525", "0.62518656", "0.6233387", "0.6203707", "0.61963826", "0.6185099", "0.615575", "0.61535317", "0.6136135", "0.6132937", "0.60876656", "0.60780454", "0.6075212", "0.60428053", "0.6027235", "0.60155517", "0.59974444", "0.5959217", "0.59586394", "0.5906571", "0.588624", "0.58802557", "0.5879794", "0.58565706", "0.58491296", "0.5842432", "0.58203524", "0.5819534", "0.5811635", "0.5811627", "0.58073986", "0.58064926", "0.57884073", "0.5782536", "0.5770419", "0.5769471", "0.5766662", "0.5762991", "0.5761621", "0.575933", "0.5744535", "0.57420146", "0.5734518", "0.57241684", "0.57233936", "0.5723297", "0.5716202", "0.57073694", "0.5701974", "0.56981915", "0.5698051", "0.56915", "0.5689462", "0.56850076", "0.56785613", "0.567215", "0.5670484", "0.56701773", "0.56515515", "0.56476235", "0.562943", "0.56045544", "0.5602419", "0.5599968", "0.5597582", "0.5591302", "0.5583001", "0.55770904", "0.55718505", "0.55549616", "0.5553592", "0.55376583", "0.5532687", "0.5522196", "0.55218065", "0.5521609", "0.5512027", "0.5509814", "0.5507606", "0.55039555", "0.5501215", "0.549659", "0.549401", "0.54930466", "0.5491702" ]
0.0
-1
Default value for teamsite
receiveContentProps({ path }) { this.rootUrl = `/${path}`; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_defaults() {\n return {\n name: \"\",\n teams: []\n };\n }", "function defaultValue(v) { }", "function defaultCurrentSit() {\n \n if(typeof currentSituation == \"undefined\" && availableSituations.length > 0) {\n \n currentSituation = availableSituations[0];\n \n }\n \n else if(availableSituations.length == 0) {\n currentSituation = undefined;\n }\n \n\n \n}", "function default_robot_name(){\n if(default_robot_name_id){\n return default_robot_name_id.value\n }\n else { return \"Dexter.dexter0\" }\n}", "function defaultValue(value, theDefault)\n {\n return (value !== undefined) ? value : theDefault;\n }", "function LiveAnnouncerDefaultOptions() { }", "function getTeam() {\n if (team.includes(\"Retired\") === true) {\n return \"Retired\";\n }\n if (team.includes(\"Free Agent\") === true) {\n return \"Free Agent\";\n } else {\n return team;\n }\n }", "function defaulted(value,defaultValue){return value!==undefined?value:defaultValue;}", "defaults () {\n return {\n id: null,\n title: 'Pelada',\n info: 'Pelada da semana',\n seats: 28,\n location: 'R9 Bate Bola',\n status: 'scheduled'\n }\n }", "function initTeam(t) {\n const team = {\n name: `TestCafé-${Date.now().toString(36)}`,\n };\n console.info('\\tteam:', team.name, `(${t.testRun.browserConnection.browserInfo.alias})`);\n return team;\n}", "get defaultValue() {\n return this.getStringAttribute('default_value');\n }", "function LiveAnnouncerDefaultOptions() {}", "function estudioDefault(estudiante='Anonimo', carrera='una carrera desconocida') {\n console.log('El estudiante', estudiante, 'esta estudiando', carrera)\n }", "defaultComputerPlayer(gameID) {\n return {\n 'name': 'cpu' + gameID,\n 'gameID': gameID,\n 'deck': COMPUTER_DECKS[this.computerLevel], //the bot deck\n }\n }", "function currently_selected_team()\n\t{\n\t\treturn $('#__rankingslash_leagueId99_team_select').val();\n\t}", "getDefault() {\n return JSON.parse(JSON.stringify(this.default))\n }", "function setDefault( value, defaultValue ) {\n\tif( value==''){\n\t\treturn defaultValue;\n\t} else {\n\t\treturn value;\n\t}\n}", "get defaults() {\n return {\n bag: {\n rock: 0,\n },\n }\n }", "function defaultVal(actual, defaultValue) {\n\t return actual == null ? defaultValue : actual;\n\t}", "setDefault() {\n\n if ( this.options.default ) {\n\n this.$field.val(this.options.default).change();\n }\n }", "function defaultValue(test,defaultValue) {\r\n\treturn (typeof test !== 'undefined' ? test : defaultValue);\r\n}", "optionTeamFiller(nhlTeam) {\n\t\treturn (\n\t\t\t<option value={nhlTeam}>{nhlTeam}</option>\n\t\t)\n\t}", "setDefault() { }", "getDefaultOption(boardId) {\n const ret = {\n 'boardId' : \"\",\n 'swimlaneId' : \"\",\n 'listId' : \"\",\n }\n return ret;\n }", "function getDefaultSettings() {\n var defaultSettings = {\n maxClocks: 8,\n theme: \"\"\n }\n return defaultSettings;\n}", "static getDefaultObject() {\n return {\n name : `name_${Math.round(Math.random() * 999999)}`,\n creation_date : `2019-10`,\n location : `location_${Math.round(Math.random() * 999999)}`,\n pvp_type : `pvp_type_${Math.round(Math.random() * 999999)}`,\n world_quest_titles : `world_quest_titles_${Math.round(Math.random() * 999999)}`,\n battleye_status : `battleye_status_${Math.round(Math.random() * 999999)}`,\n transfer_type : 'transfer_type',\n game_world_type : 'game_world_type',\n online_record : {\n players : Math.round(Math.random() * 999999),\n date : {\n date : '2017-12-03 19:10:30.000000',\n timezone_type : 2,\n timezone : 'CET'\n }\n },\n }\n }", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n }", "set default(defaultValue) {\n\t\tthis._hasDefault = true;\n\t\tthis._defaultValue = defaultValue;\n\t}", "getDefaultProps() {\n return {\n selectedArtist : {\n name: \"Default Props\",\n info: \"Here is the default props info\"\n }\n }\n }", "get defaultValueHumanName() {\n\t\treturn this.__defaultValueHumanName;\n\t}", "function setDefaultValues()\n{\n return [54, undefined, -127, \"sunshine\"];\n}", "defaults() {\n return {\n title: '',\n content: '',\n img: '',\n author: '',\n published: '',\n vertical: '',\n tags: '',\n country: ''\n };\n }", "setDefault (name, value) { this.agentProto[name] = value }", "function defaulted(value, defaultValue) {\r\n return value !== undefined ? value : defaultValue;\r\n}", "function defaulted(value, defaultValue) {\r\n return value !== undefined ? value : defaultValue;\r\n}", "function defaulted(value, defaultValue) {\r\n return value !== undefined ? value : defaultValue;\r\n}", "get defaultContext() {\n return 'n3/contexts#default';\n }", "static getDefaults() {\n return {};\n }", "function changeDefaultValues(parameters) {\n\tif (parameters[\"id\"] != undefined) {\n\t\tID = parameters[\"id\"];\n\t};\n\n\tif (parameters[\"amt\"] != undefined) {\n\t\tinitialValue = parameters[\"amt\"];\n\t\tuserCurrentValue = initialValue;\n\t\tmarketCurrentValue = initialValue;\n\t};\n\n\tif (parameters[\"years\"] != undefined) {\n\t\tyears = parameters[\"years\"];\n\t};\n\n\tif (parameters[\"speed\"] != undefined) {\n\t\tspeed = parameters[\"speed\"];\n\t};\n\n\tif (parameters[\"inv\"] != undefined) {\n\t\tinMarketDefault = Boolean(Number(parameters[\"inv\"]));\n\t\tinMarketCurrent = inMarketDefault;\n\t};\n}", "defaults () {\n }", "get typeDefault()\n {\n return null;\n }", "static favouritePlace() {\n return 'Switzerland';\n }", "function getOpponentTeamId(myTeamId) {\n if(myTeamId == 100) {\n return 200;\n }\n else {\n return 100;\n }\n}", "function getDefault(value, optional) {\n return value || optional;\n}", "static get defaultProps() {\n return {\n };\n }", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "defaults() {\n return {\n address: String,\n ssl_grade: String,\n country: String,\n owner: String,\n }\n }", "defaultLanguage() {\n // Kirby 3.6 Fiber\n if (this.hasFiber) {\n return window.panel.$languages.find(l => l.default == true) ?? window.panel.$languages[0];\n }\n // Pre 3.6\n return this.$store.state.languages.default;\n }", "function play(name = \"FootBall\") {\n console.log(name);\n }", "function option(value, defaultValue) {\n\tif (value === null || value === undefined)\n\t\treturn defaultValue;\n\treturn value;\n}", "function welcome( yourName ){\n if( typeof yourName === 'undefined'){\n yourName = \"defaultName - John Doe\";\n }\n return yourName;\n}", "function updateTeam(team) {\n console.log(\"update team: \", team);\n if (team === \"Trail Blazers\") {\n teamSelected = \"blazers\";\n } else {\n teamSelected = team.toLowerCase();\n }\n updateShotChart();\n}", "function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}", "function setupDefault() {\n}", "function getOrInitPref(name,default_value) {\r\n\t\tvalue = GM_getValue(name);\r\n\t\tif (value == undefined) {\r\n\t\t\tGM_setValue(name,default_value);\r\n\t\t\treturn default_value;\r\n\t\t}\r\n\t\telse { return value; }\r\n\t}", "function setDefaultsForStand(data_point, file_name) {\n /////////////////////////////////////////////////////////////////////////////////////\n // REMOVE THIS PART ONCE WE ACTUALLY COLLECT NEW DATA\n // It adds match, role, and team to stand app files, which the new stand app automatically does\n /////////////////////////////////////////////////////////////////////////////////////\n let parts = file_name.split(\"-\");\n parts[2] = parts[2].split(\".\")[0] // removing the .json\n if (data_point[\"info\"] === undefined) {\n data_point[\"info\"] = {}\n data_point[\"info\"][\"match\"] = parts[0].substr(1);\n data_point[\"info\"][\"role\"] = parts[1];\n data_point[\"info\"][\"team\"] = parts[2];\n }\n // sets default values to unfilled JSON requirements\n traverseScoutKitJSON(defaultStandJSON, function(json, page, page_index, question, question_index) {\n // if the question is not in the JSON\n if (data_point[page][question] === undefined) {\n // it adds the default response\n data_point[page][question] = defaultStandJSON[page][question];\n }\n });\n}", "function default_robot(){\n return value_of_path(default_robot_name())\n}", "getDefaultOption () {\n\t\tconst { blankOptionLabel, showDefaultOption, defaultOptionLabel, country } = this.props;\n\t\tif (!country) {\n\t\t\treturn <option value=\"\">{blankOptionLabel}</option>;\n\t\t}\n\t\tif (showDefaultOption) {\n\t\t\treturn <option value=\"\">{defaultOptionLabel}</option>;\n\t\t}\n\t\treturn null;\n\t}", "function chooseTeam() {\n inquirer.prompt(prompts.promptChooseTeam).then((choice) => {\n choice.chooseTeam === \"Engineer\"\n ? addEngineer()\n : choice.chooseTeam === \"Intern\"\n ? addIntern()\n : compileTeam();\n });\n}", "setDefault(newDefault) {\n this.defaultExt = newDefault\n }", "function defaultFalse( value ) { return optionalDefault( value, false ); }", "function welcome( yourName = \"John Doe\"){\n return yourName;\n}", "function defaultValues(){\n\tbluValue=0;\n\thueRValue=0;\n\tinvtValue=0;\n\tbrightnValue=1;\n\tsepiValue=0;\n\tgraysaValue=0;\n\topaciValue=1;\n\tsatuvalue=1;\n\tcontrstValue=1;\n}", "get notoriety() {\n return this._notoriety || User.defaults.notoriety;\n }", "async getFirstTeam () {\n\t\tif ((this.user.get('teamIds') || []).length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst teamId = this.user.get('teamIds')[0];\n\t\tthis.firstTeam = await this.request.data.teams.getById(teamId);\n\t}", "function optionalParameter( value, defaultValue ) {\n\n\t\treturn value !== undefined ? value : defaultValue;\n\n\t}", "function notifyNoTeam() {\n // TODO @querdos Manage translation for the non team message\n new PNotify({\n title: 'You have no team !',\n text: 'You must be in a team to participate in challenges',\n type: 'info',\n styling: 'bootstrap3'\n });\n}", "makeGameSettings(){\n const settings = {\n players: 1\n }\n }", "static instanceDefaults() {\n return {\n name: '',\n owner: '',\n members: []\n }\n }", "defaultValue(props) {\n // check if there is a value in the model, if there is, display it. Otherwise, check if\n // there is a default value, display it.\n //console.log('Text.defaultValue key', this.props.form.key);\n //console.log('Text.defaultValue model', this.props.model);\n let value = utils.selectOrSet(props.form.key, props.model); //console.log('Text defaultValue value = ', value);\n // check if there is a default value\n\n if (!value && props.form['default']) {\n value = props.form['default'];\n }\n\n if (!value && props.form.schema && props.form.schema['default']) {\n value = props.form.schema['default'];\n } // Support for Select\n // The first value in the option will be the default.\n\n\n if (!value && props.form.titleMap && props.form.titleMap[0].value) {\n value = props.form.titleMap[0].value;\n } //console.log('value', value);\n\n\n return value;\n }", "function setDefaultData() {\n train = { x: DEFAULT.train, y: DEFAULT.train, size: DEFAULT.size, trail: [], speed: DEFAULT.speed }\n passenger = { x: DEFAULT.passenger, y: DEFAULT.passenger, count: 0 }\n station = { x: undefined, y: undefined, count: 0, timers: {} }\n next = { dir: DOWN, x: 0, y: 0 }\n highScore = gameStarted = false\n timer = {count: 0}\n\n updateScore()\n updateTime()\n\n moveTrain()\n\n $(`[data-x=\"${passenger.x}\"][data-y=\"${passenger.y}\"]>i`).addClass('fas fa-male')\n\n}", "function $$getDefaultValue() {\n\t\t\t\tif (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n\t\t\t\tvar defaultValue = injector.invoke(config.$$fn);\n\t\t\t\tif (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))\n\t\t\t\t\tthrow new Error(\"Default value (\" + defaultValue + \") for parameter '\" + self.id + \"' is not an instance of Type (\" + self.type.name + \")\");\n\t\t\t\treturn defaultValue;\n\t\t\t}", "get defaultOptions() {\n return defaults(\n {},\n get(this, 'projectConfig'),\n result(this.constructor, 'defaultOptions'),\n // Find some way to be able to inject ARGV in projects which consume skypager via webpack\n global.SKYPAGER_ARGV,\n global.ARGV\n )\n }", "function defaultValue(defaultVal, data) {\n if (data === undefined) {\n return defaultVal;\n } else {\n return data;\n }\n}", "function optionalDefault( value, defaultValue ) {\n \tif ( value === undefined ) return defaultValue;\n \telse if ( value == null ) return defaultValue;\n \telse return value;\n }", "function i(t){return t&&\"object\"===typeof t&&\"default\"in t?t[\"default\"]:t}", "function i(t){return t&&\"object\"===typeof t&&\"default\"in t?t[\"default\"]:t}", "static instanceDefaults() {\n return {\n img: 'https://picsum.photos/seed/picsum/768/1024',\n name: ''\n };\n }", "get team() {\r\n return new Team(this);\r\n }", "function defaultTo(x, y) {\n return y == null ? x : y;\n }", "getDefaultValueSelected() {\n const {data} = this.props;\n // Bitcoin Network\n if (data.length > 2) {\n if (data[0].disabled) {\n return data[1];\n }\n return data[0];\n }\n // Public Factom Network\n return data[0];\n }", "function default_val(arg, val) {\n\treturn typeof arg === \"undefined\" ? val : arg;\n} // default_val()", "function defaultStage (stage) {\n let staging = 'staging'\n let production = 'production'\n if (stage !== staging && stage !== production)\n stage = staging\n return stage\n}", "constructor(defaultValue) {\n\t\tsuper(); \n\t\tthis.defaultValue = defaultValue;\n\t}", "function setDefaults(){\n\n $(\"#311MessageDBsummary\\\\.fmw span.db_connection.fmes-form-component select\").prop(\"disabled\", true);\n\n $(\"#UpdateDepartmentDB\\\\.fmw span.db_connection.fmes-form-component select\").change(function() {\n var val = $(this).val();\n $('#311MessageDBsummary\\\\.fmw span.db_connection.fmes-form-component select option').each(function(){\n var val2 = $(this).html();\n if (val2 == val) {\n $(this).prop('selected', true);\n } else {\n $(this).prop('selected', false);\n }\n });\n });\n $(\"#311MessageDBsummary\\\\.fmw span.RequestType.fmes-form-component select\").prop(\"value\", \"ALL\");\n $(\"#311MessageDBsummary\\\\.fmw span.Status.fmes-form-component select\").prop(\"value\", \"ALL\");\n $(\"#311PublicMessageLoader\\\\.fmw span.RequestType.fmes-form-component select\").prop(\"value\", \"Safety\");\n}", "function insertDefaultConfigValues() {\n insertConfigParamValue('city', 'Villaviciosa');\n insertConfigParamValue('temperatureUnit', 'Celsius');\n}", "function getDefaultRole()\n{\n return \"harvester\";\n}", "function printCity(homeCity = { city: \"Mohali\" }) {\n console.log(homeCity.city);\n}", "function setEntityTypeDefault() {\n entityTypeDefault = $(this).attr('label');\n return false;\n }", "constructor(name, teams=[], config={}){ //Constructor con sus parametros;\n this.name = name;\n this.matchDaySchedule = [];\n this.setupTeams(teams);\n this.setup(config);\n this.summaries = []\n \n }", "function defaultTrue( value ) { return optionalDefault( value, true ); }", "cfgValue(variable, defaultVal) {\n let val = defaultVal ? this.cfg.get(variable) : this.cfg.require(variable);\n if (typeof val === 'string') {\n let v = val.toLowerCase();\n if (v === 'no' || v === 'false' || v === 'none') {\n val = undefined;\n }\n }\n return val || defaultVal;\n }", "function $$getDefaultValue() {\n\t if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n\t var defaultValue = injector.invoke(config.$$fn);\n\t if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))\n\t throw new Error(\"Default value (\" + defaultValue + \") for parameter '\" + self.id + \"' is not an instance of Type (\" + self.type.name + \")\");\n\t return defaultValue;\n\t }", "function greetSomeone(name = \"Guest\") {\n console.log(\"Good morning, \" + name)\n}", "get name() {\n return this._data.team_name;\n }", "static GetMuscleDefaultMax() {}" ]
[ "0.74505764", "0.5916384", "0.5887596", "0.58614117", "0.58301574", "0.575466", "0.5727864", "0.5708126", "0.567636", "0.5662723", "0.5660674", "0.5653411", "0.56449294", "0.56347644", "0.56005186", "0.5586645", "0.5571506", "0.5551669", "0.55125725", "0.5482384", "0.54822385", "0.5470875", "0.5463707", "0.5460111", "0.54403627", "0.5438331", "0.54232645", "0.5398143", "0.5390381", "0.53755146", "0.53686285", "0.536401", "0.53637207", "0.53530616", "0.53530616", "0.53530616", "0.534604", "0.53421575", "0.5319946", "0.53144896", "0.53052783", "0.52781224", "0.52767074", "0.5261654", "0.52554536", "0.5253731", "0.5253731", "0.5253731", "0.5253731", "0.5253731", "0.5253731", "0.52435845", "0.524056", "0.52341104", "0.52312285", "0.522845", "0.522499", "0.52238023", "0.5221338", "0.52120054", "0.5203231", "0.5196273", "0.5181768", "0.51813984", "0.518134", "0.51795614", "0.5177424", "0.5172476", "0.5171099", "0.51663816", "0.51631737", "0.5161453", "0.51556945", "0.5146129", "0.5145108", "0.5140644", "0.51402646", "0.5139101", "0.5134579", "0.5130731", "0.5127103", "0.5127103", "0.51260775", "0.5120691", "0.51178455", "0.51178026", "0.51120645", "0.51085883", "0.5107455", "0.51064193", "0.5099818", "0.50951463", "0.5080868", "0.50778097", "0.50739974", "0.5072168", "0.5070099", "0.50673556", "0.50610685", "0.5060264", "0.50598514" ]
0.0
-1
TIME COMPLEXITY: O(log N), N = number of nodes in heap SPACE COMPLEXITY: O(N), 2N > O(N) (2N bec recursive call stack?)
insert(val) { this.array.push(val); // push value to end of array (add node to farthest bottom left of tree) this.siftUp(this.array.length - 1); // continuously swap value toward front of array to maintain maxHeap property }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function buildHeap(A) {\n var n = A.length;\n for (var i = n/2 - 1; i >= 0; i--) {\n heapify(A, i, n);\n }\n}", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "function heapreheapify() {\n\n var node = this.size; // set the size to heap\n var pn = Math.floor(node/2); // use math floor to set last parent node to pn = parent node\n\n var i = pn; // set new varibale and get value pn.\n while(i >= 1)\n {\n var key = i;\n var v = this.h[key];\n var v2 = this.h_item[key];\n var heap = false; // here intitalize heap with boolean value false\n\n for (var j = 2 * key; !heap && 2 * key <= node;)\n {\n if (j < node)\n {\n if (this.h[j] < this.h[j + 1]) {\n j += 1;\n } // end the inner if\n } // end the outer if\n\n\n if (v >= this.h[j])\n {\n heap = true;\n } // end if\n else\n {\n this.h_item[key] = this.h_item[j];\n this.h[key] = this.h[j];\n key = j;\n } // end wlse\n\n this.h[key] = v;\n this.h_item[key] = v2;\n }\n i = i-1; // here decreese the number in each iteration\n } // end while\n}", "buildHeap(array) {\n const firstParentIdx = Math.floor((array.length - 2) / 2);\n for (let currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {\n this.siftDown(currentIdx, array.length - 1, array);\n }\n return array;\n }", "function heapify(arr,comp){\r\n // arr[n/2-1:n-1] already satisfies the heap property because they are the leaves.\r\n for(let i = Math.floor((arr.length-2)/2); i >= 0; i--){\r\n // Restore the heap property for i\r\n siftDown(arr, comp, i);\r\n }\r\n // Now that the heap property is satisfied for all i from 0 to n-1, the array is a heap\r\n}", "function heapPerms(n, arr,set){\n\tif(n==1){\n\t\tset.push(Array.from(arr));\n\t}else{\n\t\tfor(var i=1;i<=n;i++){\n\t\t\theapPerms(n-1,arr,set);\n\t\t\tif(n%2){\n\t\t\t\tswap(arr,0,n-1);\n\t\t\t}else{\n\t\t\t\tswap(arr,i-1,n-1);\n\t\t\t}\n\t\t}\n\t}\n\treturn set;\n}", "function MinHeap() {\n\n /**\n * Insert an item into the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} x\n */\n this.insert = function(x) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:)\n *\n * @return{number}\n */\n this.peek = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Remove and return the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.pop = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the size of the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.size = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Convert the heap data into a string\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{string}\n */\n MinHeap.prototype.toString = function() {\n // INSERT YOUR CODE HERE\n }\n\n /*\n * The following are some optional helper methods. These are not required\n * but may make your life easier\n */\n\n /**\n * Get the index of the parent node of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var parent = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the index of the left child of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var leftChild = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Swap the values at 2 indices in our heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @param{number} j\n */\n var swap = function(i, j) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble up the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleUp = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble down the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleDown = function(i) {\n // INSERT YOUR CODE HERE\n }\n}", "heapify() {\n\t\t// last index is one less than the size\n\t\tlet index = this.size() - 1;\n\n\t\t/*\n Property of ith element in binary heap - \n left child is at = (2*i)th position\n right child is at = (2*i+1)th position\n parent is at = floor(i/2)th position\n */\n\n\t\t// converting entire array into heap from behind to front\n\t\t// just like heapify function to create it MAX HEAP\n\t\twhile (index > 0) {\n\t\t\t// pull out element from the array and find parent element\n\t\t\tlet element = this.heap[index],\n\t\t\t\tparentIndex = Math.floor((index - 1) / 2),\n\t\t\t\tparent = this.heap[parentIndex];\n\n\t\t\t// if parent is greater or equal, its already a heap hence break\n\t\t\tif (parent[0] >= element[0]) break;\n\t\t\t// else swap the values as we're creating a max heap\n\t\t\tthis.heap[index] = parent;\n\t\t\tthis.heap[parentIndex] = element;\n\t\t\tindex = parentIndex;\n\t\t}\n\t}", "function heapify(currentIndex, arr){\n\n if (isHavingChildrenLeft(currentIndex, arr)) {\n let parent = arr[currentIndex]\n\n if (isHavingChildrenRight(currentIndex, arr)){\n let maxChildren = Math.max(arr[currentIndex * 2 + 1], arr[currentIndex * 2 + 2])\n if (parent < maxChildren){\n let maxChilrenIndex = maxChildren == arr[currentIndex * 2 + 1] ? currentIndex * 2 + 1 : currentIndex * 2 + 2 \n swapArrayElement(currentIndex, maxChilrenIndex, arr)\n heapify(maxChilrenIndex, arr)\n }\n }else {\n if (parent < arr[currentIndex * 2 + 1]){\n swapArrayElement(currentIndex, currentIndex * 2 + 1, arr)\n heapify(currentIndex * 2 + 1, arr)\n }\n }\n }else {\n console.log(\"skipping index %d\", currentIndex)\n }\n}", "function heapSort(arr,n){\n for(var i=Math.floor(n/2);i>=0;i--){\n heapify(arr,n,i);\n }\n for(var i=n-1;i>=0;i--){\n swap(arr,0,i);\n heapify(arr,i,0);\n }\n}", "function heapDown(i) {\n var w = heapWeight(i)\n while(true) {\n var tw = w\n var left = 2*i + 1\n var right = 2*(i + 1)\n var next = i\n if(left < heapCount) {\n var lw = heapWeight(left)\n if(lw < tw) {\n next = left\n tw = lw\n }\n }\n if(right < heapCount) {\n var rw = heapWeight(right)\n if(rw < tw) {\n next = right\n }\n }\n if(next === i) {\n return i\n }\n heapSwap(i, next)\n i = next \n }\n }", "function heapify(array, n, i) {\n let leftIdx = 2 * i + 1; // 1) grab left/right indices/values of current val/node\n let rightIdx = 2 * i + 2; // root index is now 0 instead of 1 (no null placeholder)\n let leftVal = array[leftIdx];\n let rightVal = array[rightIdx];\n\n if (leftIdx >= n) leftVal = -Infinity; // 2) set left/right val to -infinity if we're out of array bounds (determined by n)\n if (rightIdx >= n) rightVal = -Infinity;\n\n if (array[i] > leftVal && array[i] > rightVal) return; // 3) exit if current val > both children\n\n let swapIdx;\n if (leftVal < rightVal) { // 4) determine index to swap current value with\n swapIdx = rightIdx;\n } else {\n swapIdx = leftIdx;\n }\n\n [array[i], array[swapIdx]] = [array[swapIdx], array[i]]; // 5) swap current val w/ larger of two children\n\n heapify(array, n, swapIdx); // 6) recursively siftDown/heapify until maxHeap property met\n}", "function heapify (heap) {\n // Get the parent idx of the last node\n var start = iparent(heap.arr.length - 1)\n while (start >= 0) {\n siftDown(start, heap)\n start -= 1\n }\n return heap\n}", "function minHeap(arr){\r\n\tfor(var i=Math.floor(arr.length/2); i >= 0; i--){\r\n\t\tminHeapafiy(arr, i)\r\n\t}\r\n\treturn arr\r\n}", "sink(k) {\n while (2*k < this.n) {\n /*\n * While the comparison node (k) still has children (2k or 2k+1), check\n * the parent against both its children. If greater than either, swap\n * it with the larger of its children. Continue sinking down the heap\n * until a parent is smaller than its two children.\n */\n let parent = this.heap[k].priority;\n let child1 = this.heap[2*k].priority;\n let child2 = this.heap[2*k + 1].priority;\n\n if (parent > child1 || parent > child2) {\n /*\n * If the parent node is smaller than either of its child nodes, swap\n * with the larger of its two children.\n */\n if (child1 <= child2 || child2 === undefined) {\n [this.heap[k], this.heap[2*k]] = [this.heap[2*k], this.heap[k]];\n k = 2*k;\n } else {\n [this.heap[k], this.heap[2*k+1]] = [this.heap[2*k+1], this.heap[k]];\n k = 2*k + 1;\n }\n } else {\n // Return because the parent node is smaller than its two children\n return;\n }\n }\n }", "heapifyDown(){\n let idx = 0,\n element = this.values[idx],\n swap,\n leftChildIdx,\n rightChildIdx,\n leftChild,\n rightChild;\n while (true){\n swap = null;\n leftChildIdx = (2 * idx) + 1;\n rightChildIdx = (2 * idx) + 2;\n leftChild = leftChildIdx < this.values.length ? this.values[leftChildIdx] : null;\n rightChild = rightChildIdx < this.values.length ? this.values[rightChildIdx] : null;\n if (leftChild <= rightChild && leftChild < element && leftChild !== null){\n swap = leftChildIdx\n }\n if (leftChild >= rightChild && rightChild < element && rightChild !== null){\n swap = rightChildIdx;\n }\n if (swap === null) break;\n this.values[idx] = this.values[swap];\n this.values[swap] = element;\n idx = swap; \n } \n }", "function heapUp(i) {\n var w = heapWeight(i)\n while(i > 0) {\n var parent = heapParent(i)\n if(parent >= 0) {\n var pw = heapWeight(parent)\n if(w < pw) {\n heapSwap(i, parent)\n i = parent\n continue\n }\n }\n return i\n }\n }", "function maxHeapify(arr){\n\n}", "traverse(node) {\n const stack = [];\n for (let i = 0; i < 8; i++) {\n const child = node.children[i];\n if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {\n stack.push(child);\n }\n }\n\n while (stack.length > 0) {\n const node = stack.pop();\n const weight = node.boundingSphere.radius;\n\n this.priorityQueue.push({ node, weight });\n\n // add children that intersect the cutting plane\n if (node.level < this.maxDepth) {\n for (let i = 0; i < 8; i++) {\n const child = node.children[i];\n if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {\n stack.push(child);\n }\n }\n }\n }\n }", "function heapify(arr) {\n if (arr.length < 1) return arr\n for (let i = arr.length - 1; i >= 0; i--) {\n minHeapify(arr, i)\n }\n return arr\n}", "_rebalance() {\n const head = this._heap[0];\n let ind = 0;\n let children = this._getChildren(ind);\n while(children[0] && this._heap[children[0]] < head || children[1] && this._heap[children[1]] < head) {\n if (this._heap[children[0]] < head) {\n ind = this._switch(ind, children[0]);\n }\n if (this._heap[children[1]] < head) {\n ind = this._switch(ind, children[1]);\n }\n children = this._getChildren(ind);\n }\n // last check for last switch for root\n const immediates = this._getChildren(0);\n if (this._heap[immediates[0]] < this._heap[0]) {\n this._switch(0, immediates[0]);\n }\n if (this._heap[immediates[1]] < this._heap[0]) {\n this._switch(0, immediates[1]);\n }\n }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function heapUp(i) {\n\t var w = heapWeight(i)\n\t while(i > 0) {\n\t var parent = heapParent(i)\n\t if(parent >= 0) {\n\t var pw = heapWeight(parent)\n\t if(w < pw) {\n\t heapSwap(i, parent)\n\t i = parent\n\t continue\n\t }\n\t }\n\t return i\n\t }\n\t }", "function heapUp(i) {\n\t var w = heapWeight(i)\n\t while(i > 0) {\n\t var parent = heapParent(i)\n\t if(parent >= 0) {\n\t var pw = heapWeight(parent)\n\t if(w < pw) {\n\t heapSwap(i, parent)\n\t i = parent\n\t continue\n\t }\n\t }\n\t return i\n\t }\n\t }", "breadthFirst() {\n let queue = new LinkedQueue();\n let visited = new LinkedList();\n queue.enqueue(new Point(WORLD_WIDTH - 2, WORLD_HEIGHT - 2, 0));\n let current = null;\n while (queue.length > 0) {\n current = queue.dequeue();\n let j = current.y;\n let i = current.x;\n if (this.tiles[j - 1][i] === 'F' &&\n !visited.contains(new Point(i, j - 1))) {\n queue.enqueue(new Point(i, j - 1, current.depth + 1));\n visited.add(new Point(i, j - 1));\n }\n if (this.tiles[j + 1][i] === 'F' &&\n !visited.contains(new Point(i, j + 1))) {\n queue.enqueue(new Point(i, j + 1, current.depth + 1));\n visited.add(new Point(i, j + 1));\n }\n if (this.tiles[j][i - 1] === 'F' &&\n !visited.contains(new Point(i - 1, j))) {\n queue.enqueue(new Point(i - 1, j, current.depth + 1));\n visited.add(new Point(i - 1, j));\n }\n if (this.tiles[j][i + 1] === 'F' &&\n !visited.contains(new Point(i + 1, j))) {\n queue.enqueue(new Point(i + 1, j, current.depth + 1));\n visited.add(new Point(i + 1, j));\n }\n }\n return current;\n }", "async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }", "function heapify(array, size, i, animations)\n{\n let root = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if(left < size && array[left] > array[root])\n {\n animations.push([root, left, false]);\n animations.push([root, left, false]);\n root = left;\n }\n if(right < size && array[right] > array[root])\n {\n animations.push([root, right, false]);\n animations.push([root, right, false]);\n root = right;\n }\n //Root has changed because i was not the root\n if(root != i)\n {\n animations.push([root, array[i], true]);\n animations.push([i, array[root], true]);\n //If root is not i, then swap the values, call heapify recursively\n swap(array, root, i);\n heapify(array, size, root, animations);\n }\n}", "remove() {\n if (this.heap.length < 2) {\n return this.heap.pop(); //easy\n }\n\n const removed = this.heap[0]; // save to return later\n this.heap[0] = this.heap.pop(); // replace with last el\n\n let currentIdx = 0;\n let [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n let currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n // right if heap[right].priority >= heap[left].priority, else left\n // index of max(left.priority, right.priority)\n\n while (\n this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority\n ) {\n let currentNode = this.heap[currentIdx];\n let currentChildNode = this.heap[currentChildIdx];\n\n // swap parent & max child\n\n this.heap[currentChildIdx] = currentNode;\n this.heap[currentIdx] = currentChildNode;\n\n\n // update pointers\n currentIdx = currentChildIdx;\n [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n }\n\n return removed;\n }", "traverse (node) {\n\t\t\tlet stack = [];\n\t\t\tfor (let i = 0; i < 8; i++) {\n\t\t\t\tlet child = node.children[i];\n\t\t\t\tif (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {\n\t\t\t\t\tstack.push(child);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (stack.length > 0) {\n\t\t\t\tlet node = stack.pop();\n\t\t\t\tlet weight = node.boundingSphere.radius;\n\n\t\t\t\tthis.priorityQueue.push({node: node, weight: weight});\n\n\t\t\t\t// add children that intersect the cutting plane\n\t\t\t\tif (node.level < this.maxDepth) {\n\t\t\t\t\tfor (let i = 0; i < 8; i++) {\n\t\t\t\t\t\tlet child = node.children[i];\n\t\t\t\t\t\tif (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {\n\t\t\t\t\t\t\tstack.push(child);\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}", "function _adjustHeap (arr) {\n var i = parseInt(arr.length / 2) - 1;\n\n while (i >= 0) {\n if (arr[i] < arr[2 * i + 1] || arr[i] < arr[2 * i + 2]) {\n if (arr[2 * i + 1] < arr[2 * i + 2]) {\n arr[2 * i + 2] = [arr[i], arr[i] = arr[2 * i + 2]][0];\n } else {\n arr[2 * i + 1] = [arr[i], arr[i] = arr[2 * i + 1]][0];\n }\n _adjustHeap(arr);\n }\n i--;\n };\n }", "buildHeap(left, right) {\r\n var x = this.values[left];\r\n var i = left;\r\n\r\n while(true) {\r\n let j = 2 * i;\r\n if (j > right) break;\r\n if ((j < right) && (Item.compare(this.values[j + 1], this.values[j]) >= 0)) {\r\n j++;\r\n }\r\n\r\n if (Item.compare(x, this.values[j]) >= 0) break;\r\n let temp = this.values[i];\r\n this.values[i] = this.values[j];\r\n this.values[j] = temp;\r\n\r\n this.values[i].selected = true;\r\n this.printStorage.pushTimedPrint(this.values);\r\n this.values[i].selected = false;\r\n i = j;\r\n }\r\n\r\n this.values[i] = x;\r\n\r\n this.values[i].selected = true;\r\n this.printStorage.pushTimedPrint(this.values);\r\n this.values[i].selected = false;\r\n }", "function heapify(array, size, i) {\n let max = i // initialize max as root\n let left = 2 * i + 1\n let right = 2 * i + 2\n \n // if left child is larger than root\n if (left < size && array[left] > array[max])\n max = left\n \n // if right child is larger than max\n if (right < size && array[right] > array[max])\n max = right\n \n // if max is not root\n if (max != i) {\n // swap\n let temp = array[i]\n array[i] = array[max]\n array[max] = temp\n \n // recursively heapify the affected sub-tree\n heapify(array, size, max)\n }\n }", "_heapifyUp(startIndex) {\n let childIndex = startIndex;\n let parentIndex = Math.floor((childIndex - 1) / 2);\n\n while (this._shouldSwap(parentIndex, childIndex)) {\n this._swap(parentIndex, childIndex);\n childIndex = parentIndex;\n parentIndex = Math.floor((childIndex - 1) / 2);\n }\n }", "function Heap(type) {\n var heapBuf = utils.expandoBuffer(Int32Array),\n indexBuf = utils.expandoBuffer(Int32Array),\n heavierThan = type == 'max' ? lessThan : greaterThan,\n itemsInHeap = 0,\n dataArr,\n heapArr,\n indexArr;\n\n this.init = function(values) {\n var i;\n dataArr = values;\n itemsInHeap = values.length;\n heapArr = heapBuf(itemsInHeap);\n indexArr = indexBuf(itemsInHeap);\n for (i=0; i<itemsInHeap; i++) {\n insertValue(i, i);\n }\n // place non-leaf items\n for (i=(itemsInHeap-2) >> 1; i >= 0; i--) {\n downHeap(i);\n }\n };\n\n this.size = function() {\n return itemsInHeap;\n };\n\n // Update a single value and re-heap\n this.updateValue = function(valIdx, val) {\n var heapIdx = indexArr[valIdx];\n dataArr[valIdx] = val;\n if (!(heapIdx >= 0 && heapIdx < itemsInHeap)) {\n error(\"Out-of-range heap index.\");\n }\n downHeap(upHeap(heapIdx));\n };\n\n this.popValue = function() {\n return dataArr[this.pop()];\n };\n\n this.getValue = function(idx) {\n return dataArr[idx];\n };\n\n this.peek = function() {\n return heapArr[0];\n };\n\n this.peekValue = function() {\n return dataArr[heapArr[0]];\n };\n\n // Return the idx of the lowest-value item in the heap\n this.pop = function() {\n var popIdx;\n if (itemsInHeap <= 0) {\n error(\"Tried to pop from an empty heap.\");\n }\n popIdx = heapArr[0];\n insertValue(0, heapArr[--itemsInHeap]); // move last item in heap into root position\n downHeap(0);\n return popIdx;\n };\n\n function upHeap(idx) {\n var parentIdx;\n // Move item up in the heap until it's at the top or is not lighter than its parent\n while (idx > 0) {\n parentIdx = (idx - 1) >> 1;\n if (heavierThan(idx, parentIdx)) {\n break;\n }\n swapItems(idx, parentIdx);\n idx = parentIdx;\n }\n return idx;\n }\n\n // Swap item at @idx with any lighter children\n function downHeap(idx) {\n var minIdx = compareDown(idx);\n\n while (minIdx > idx) {\n swapItems(idx, minIdx);\n idx = minIdx; // descend in the heap\n minIdx = compareDown(idx);\n }\n }\n\n function swapItems(a, b) {\n var i = heapArr[a];\n insertValue(a, heapArr[b]);\n insertValue(b, i);\n }\n\n // Associate a heap idx with the index of a value in data arr\n function insertValue(heapIdx, valId) {\n indexArr[valId] = heapIdx;\n heapArr[heapIdx] = valId;\n }\n\n // comparator for Visvalingam min heap\n // @a, @b: Indexes in @heapArr\n function greaterThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b],\n val1 = dataArr[idx1],\n val2 = dataArr[idx2];\n // If values are equal, compare array indexes.\n // This is not a requirement of the Visvalingam algorithm,\n // but it generates output that matches Mahes Visvalingam's\n // reference implementation.\n // See https://hydra.hull.ac.uk/assets/hull:10874/content\n return (val1 > val2 || val1 === val2 && idx1 > idx2);\n }\n\n // comparator for max heap\n function lessThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b];\n return dataArr[idx1] < dataArr[idx2];\n }\n\n function compareDown(idx) {\n var a = 2 * idx + 1,\n b = a + 1,\n n = itemsInHeap;\n if (a < n && heavierThan(idx, a)) {\n idx = a;\n }\n if (b < n && heavierThan(idx, b)) {\n idx = b;\n }\n return idx;\n }\n }", "function heapify(arr,n,i){\n var largest,l,r;\n largest = i;\n l = 2*i+1;\n r = 2*i+2;\n\n if(l<n && arr[l]>arr[largest]){\n largest = l;\n }\n if(r<n && arr[r]>arr[largest]){\n largest = r;\n }\n if(largest!=i){\n swap(arr,i,largest);\n heapify(arr,n,largest);\n }\n\n}", "function push_(item,a){// Handle resursion stop at leaf level.\nif(a.height===0){if(a.table.length<M){var newA={ctor:'_Array',height:0,table:a.table.slice()};newA.table.push(item);return newA;}else{return null;}}// Recursively push\nvar pushed=push_(item,botRight(a));// There was space in the bottom right tree, so the slot will\n// be updated.\nif(pushed!==null){var newA=nodeCopy(a);newA.table[newA.table.length-1]=pushed;newA.lengths[newA.lengths.length-1]++;return newA;}// When there was no space left, check if there is space left\n// for a new slot with a tree which contains only the item\n// at the bottom.\nif(a.table.length<M){var newSlot=create(item,a.height-1);var newA=nodeCopy(a);newA.table.push(newSlot);newA.lengths.push(newA.lengths[newA.lengths.length-1]+length(newSlot));return newA;}else{return null;}}// Converts an array into a list of elements.", "swim(k) {\n while (k > 1 && this.heap[Math.floor(k/2)].priority > this.heap[k].priority) {\n /*\n * While not at root node, swap k (parent) with k/2 (child) if\n * parent > child. Continue swimming upwards until the invariant holds.\n */\n [this.heap[k], this.heap[Math.floor(k/2)]]\n = [this.heap[Math.floor(k/2)], this.heap[k]];\n k = Math.floor(k / 2);\n }\n }", "function maxHeapify(arr , n , i)\n\t{\n\t\n\t\t// Find largest of node and its children\n\t\tif (i >= n) {\n\t\t\treturn;\n\t\t}\n\t\tvar l = i * 2 + 1;\n\t\tvar r = i * 2 + 2;\n\t\tvar max;\n\t\tif (l < n && arr[l] > arr[i]) {\n\t\t\tmax = l;\n\t\t} else\n\t\t\tmax = i;\n\t\tif (r < n && arr[r] > arr[max]) {\n\t\t\tmax = r;\n\t\t}\n\n\t\t// Put maximum value at root and\n\t\t// recur for the child with the\n\t\t// maximum value\n\t\tif (max != i) {\n\t\t\tvar temp = arr[max];\n\t\t\tarr[max] = arr[i];\n\t\t\tarr[i] = temp;\n\t\t\tmaxHeapify(arr, n, max);\n\t\t}\n\t}", "function heapSortV2(array) {\n\n for (let i = array.length - 1; i >= 0; i--) { // 1) loop through array, and convert it to maxHeap using heapify helper\n heapify(array, array.length, i); // array length not really used for this part\n }\n\n for (let endOfHeap = array.length - 1; endOfHeap >= 0; endOfHeap--) { // 2) loop from end of maxHeap to begin/left, and \"delete\" max val until heap region is \"empty\"\n [array[endOfHeap], array[0]] = [array[0], array[endOfHeap]]; // 3) swap the root of the heap with the last element of the heap, this shrinks the heap by 1 and grows the sorted array by 1\n\n console.log(array);\n\n heapify(array, endOfHeap, 0); // 4) sift down the new root, but not past the end of the heap\n }\n\n return array;\n}", "extractMax(){\n // bubble down\n // swap first and last element.\n // then pop\n [this.values[0],this.values[this.values.length-1]] = [this.values[this.values.length-1], this.values[0]]\n // console.log(element + ' removed from the heap');\n this.values.pop();\n let index = 0;\n while(true){\n // compare with both the children and swap with the larger one.\n let leftParent = 2 * index + 1;\n let rightParent = 2 * index + 2;\n if(this.values[index] < this.values[leftParent] || this.values[index] < this.values[rightParent]){\n if(this.values[leftParent] > this.values[rightParent]){\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent;\n\n }\n else if(this.values[rightParent] > this.values[leftParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent;\n }\n else {\n if(this.values[rightParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent\n }\n else {\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent\n }\n \n };\n }\n else return;\n }\n }", "function heapify(n, i) {\n let largest = i; // Initialize largest as root\n // Index of left and right child of root\n const left = 2*i + 1;\n const right = 2*i + 2;\n \n // See if left child of root exists and is greater than root\n if (left < n && arr[left] > arr[largest]) {\n largest = left;\n }\n \n // See if right child of root exists and is greater than current largest\n if (right < n && arr[right] > arr[largest]) {\n largest = right;\n }\n \n // Change root if needed\n if (largest !== i) {\n swap(i, largest);\n // Heapify down this subtree\n heapify(n, largest);\n }\n }", "function buildHeap(arr, type) {\n // gets the last index\n var lastIndex = arr.length - 1;\n // While the last index is greater than 0\n while (lastIndex > 0) {\n // get the parent index\n var parentIndex = Math.floor((lastIndex - 1) / 2);\n // get the items inside the parent\n // and the last index \n var lastItem = arr[lastIndex];\n var parentItem = arr[parentIndex];\n\n if (type === 'maxHeap') {\n // checks to see if the lastItem is greater\n // than the parentItem if so then do a swap\n if (lastItem > parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n else if (type === 'minHeap') {\n // checks to see if the lastItem is less\n // than the parentItem if so then do a swap\n if (lastItem < parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n\n }\n }", "function makeHeap(){\n\n //add a node to a heap and set it to current\n if(makeHeapStep == 1){\n heapAddNode();\n return;\n }else if(makeHeapStep == 2){ //Swim the node up if needed\n\n //We are at the start of the heap. No more swimming possible\n if(currentHeapPosition == 0){\n setNodeOneHeap();\n heapSwimStep = 1;\n \n \n return;\n }\n\n if(heapSwimStep == 1){ //set the parent Node\n heapSetParent();\n }else if(heapSwimStep == 2){ //compare to the parent Node\n if(orderArray[currentHeapPosition] > orderArray[heapParentIndex]){ //we must swap\n heapSwapWithParent();\n }else{ //do not swap. Node is now in the heap proper\n setToHeap();\n }\n \n heapSwimStep = 1;\n }\n }\n\n //sorting is now done\n if(heapSize == numNodes){\n doneMakingHeap = true;\n heapOldPosition = -1;\n addStep(\"The heap is now complete.\");\n }\n}", "function BinaryHeap() {\n this.nodes = [];\n}", "aStar(startCell, endCell) {\n\t\t// Check if startCell and endCell are the same\n\t\tif (startCell.x == endCell.x && startCell.y == endCell.y) {\n\t\t\treturn [startCell];\n\t\t}\n\n\t\t// Keep track of neighboring cells\n\t\tvar open = new Heap(function(lhs, rhs) { return lhs.fCost < rhs.fCost;});\n\t\topen.add(startCell);\n\n\t\t// Keep track of visited cells\n\t\tvar openSet = new Set();\n\t\topenSet.add(startCell);\n\t\tvar closedSet = new Set();\n\n\t\twhile (open.peek() && (open.peek().x != endCell.x || open.peek().y != endCell.y)) {\n\t\t\tvar curCell = open.remove();\n\t\t\tclosedSet.add(curCell);\n\n\t\t\tvar neighbors = this.grid.getNeighbors(curCell);\n\t\t\tfor (var neighbor of neighbors.contents) {\n\t\t\t\t// If neighbor is not traversable, skip it\n\t\t\t\tif (!neighbor.traversable) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Compute cost of current cell\n\t\t\t\tvar gCost = curCell.gCost + this.moveCost(neighbor, curCell);\n\t\t\t\tvar fCost = gCost + this.heuristic(neighbor, endCell);\n\t\t\t\tif (openSet.has(neighbor) && gCost < neighbor.gCost) {\n\t\t\t\t\t// Update the parent and gCost\n\t\t\t\t\tneighbor.gCost = gCost;\n\t\t\t\t\tneighbor.parent = curCell;\n\n\t\t\t\t\t// Decrease the key in the heap\n\t\t\t\t\topen.decreaseKey(neighbor, fCost, function(item, val) {\n\t\t\t\t\t\titem.fCost = val;\n\t\t\t\t\t});\n\t\t\t\t} else if (!openSet.has(neighbor) && !closedSet.has(neighbor)) {\n\t\t\t\t\t// Set the cost for the cell and add it to the heap\n\t\t\t\t\tneighbor.gCost = gCost;\n\t\t\t\t\tneighbor.parent = curCell;\n\t\t\t\t\tneighbor.fCost = fCost;\n\t\t\t\t\topen.add(neighbor);\n\t\t\t\t\topenSet.add(neighbor);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Follow the parent pointers to get the path\n\t\tvar path = []\n\t\tvar curCell = endCell;\n\t\twhile (curCell && curCell != startCell) {\n\t\t\tpath.push(curCell);\n\t\t\tcurCell = curCell.parent;\n\t\t}\n\t\tpath.push(startCell);\n\n\t\t// Revese the path to go from start to end\n\t\tpath.reverse();\n\n\t\treturn path;\n\t}", "siftUp(currentIdx, heap) {\n // Get parentNode index of node at currentIdx\n let parentIdx = Math.floor((currentIdx - 1) / 2);\n\n // While not at root index\n // Compare value at parentIdx and currentIdx\n // If currentNode < parentNode\n // Peform swap\n // re-calculate currentIdx and parentIdx \n while (currentIdx > 0 && heap[currentIdx] < heap[parentIdx]) {\n this.swap(currentIdx, parentIdx, heap);\n currentIdx = parentIdx;\n parentIdx = Math.floor((currentIdx - 1) / 2);\n }\n }", "function getAllNodes(grid) {\n for (const row of grid) {\n for (const node of row) {\n heap.push(node);\n }\n }\n}", "function heap(a, lo, hi) {\n\t var n = hi - lo,\n\t i = (n >>> 1) + 1;\n\t while (--i > 0) sift(a, i, n, lo);\n\t return a;\n\t }", "constructor(){\n this.heap = [];\n this.count = 0;\n }", "constructor(){\n this.heap = [];\n this.count = 0;\n }", "buildMaxHeap() {}", "async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }", "function expandChildren(index, chi){\n setTimeout(function () {\n //buildHeap([ 4, 3, 2, 9, 14, 29] );\n // console.log('hooho', nodes)\n if(nodes[index].children === null){\n nodes[0].children = [nodes[0]._children[chi]]\n }\n else{\n // console.log( typeof nodes[0]. children)\n nodes[index].children.push(nodes[index]._children[1])\n }\n// .h(nodes[0]._children[0]);\n //nodes[0]._children ;\n\n// console.log(nodes[index])\n update(nodes[index])\n if(chi < 1){\n expandChildren(0, 1)\n }\n }, 3000);\n\n}", "function insert_max_heap(A, no, value) {\n A[no] = value //Insert , a new element will be added always at last \n const n = no\n let i = n\n\n //apply hepify method till we reach root (i=1)\n while (i >= 1) {\n const parent = Math.floor((i - 1) / 2)\n if (A[parent] < A[i]) {\n swap(A, parent, i)\n i = parent\n } else {\n i = parent\n //return ;\n }\n }\n}", "function astarAlgo(graph, startNode, endNode){ // note: g(n) is the same as n.distanceFromSource\n\n\tlet numOfNodes = graph.nodes.heap.length;\n\tlet sNode = null;\n\tlet gNode = null;\n\tlet startIndx = -1;\n \n\tfor (let i=1; i<numOfNodes; i++){\n \n\t\tgraph.nodes.heap[i].priority = null;\n\t\tgraph.nodes.heap[i].previousNode = null;\n\t\tgraph.nodes.heap[i].fForAStar = null;\n\t\t\n\t\tif(graph.nodes.heap[i].name === startNode){\n\t\t\tgraph.nodes.heap[i].distanceFromSource = 0;\n\t\t\tstartIndx = i;\n\t\t\tsNode = graph.nodes.heap[i];\n\t\t}\n\t\t\n\t\tif(graph.nodes.heap[i].name === endNode){\n\t\t\tgNode = graph.nodes.heap[i];\n \n\t\t}\n \n\t}\n\t\n\tlet temp = graph.nodes.heap[1];\n\tgraph.nodes.heap[1] = sNode;\n\tsNode = graph.nodes.getMin();\n\tgraph.nodes.heap[startIndx] = temp;\n\t\n\tlet openList = new MinHeapVertex();\n\topenList.insert(sNode);\n\t\n\tlet openListNames = new Set(); \n\topenListNames.add(startNode);\n \n\tlet closedList = new Set();\n\tgraph.nodes.heap[startIndx].fForAStar = sNode.distanceFromSource + graph.heuristic(sNode, gNode);\n\tgraph.nodes.heap[startIndx].priority = graph.nodes.heap[startIndx].fForAStar;\n\tgraph.nodes.updateHeap(graph.nodes.heap.length -1);\n \n\tlet current = null;\n\tlet neighbours = [];\n\tlet numOfNeighbours = 0;\n \n\twhile (openList.heap.length!==1){\n \n\t\topenList.updateHeap(openList.heap.length -1);\n \n\t\tcurrent = openList.getMin();\n \n\t\tif (current) {\n \n\t\t\tif (current.name === endNode){\n \n\t\t\t\tfor (let h=1; h<numOfNodes; h++){\n \n\t\t\t\t\tif (graph.nodes.heap[h].name === endNode){\n \n\t\t\t\t\t\tgNode = graph.nodes.heap[h];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n \n\t\t\t\t}\n \n\t\t\t\treturn [getPath(gNode), graph];\n \n\t\t\t}\n \n\t\t\topenList.remove();\n\t\t\tclosedList.add(current.name);\n \n\t\t\tneighbours = getNeighbours(graph, current, closedList);\n\t\t\tnumOfNeighbours = neighbours.length;\n \n\t\t\tfor (let i = 0; i < numOfNeighbours; i++){\n \n\t\t\t\tlet singleNeighbour = neighbours[i];\n \n\t\t\t\tif(!(closedList.has(singleNeighbour.name))){\n \n\t\t\t\t\tsingleNeighbour.fForAStar = singleNeighbour.distanceFromSource + graph.heuristic(singleNeighbour, gNode);\n\t\t\t\t\tsingleNeighbour.priority = singleNeighbour.fForAStar;\n\t\t\t\t\tgraph.nodes.updateHeap(graph.nodes.heap.length-1);\n \n\t\t\t\t\tlet neighName = singleNeighbour.name;\n\t\t\t\t\tlet neighIndx = -1;\n \n\t\t\t\t\tif(!(openListNames.has(neighName))){\n \n\t\t\t\t\t\topenListNames.add(neighName);\n\t\t\t\t\t\topenList.insert(singleNeighbour);\n \n\t\t\t\t\t\tfor (let h=1; h<numOfNodes; h++){\n \n\t\t\t\t\t\t\tif (graph.nodes.heap[h].name === neighName){\n \n\t\t\t\t\t\t\t\tgraph.nodes.heap[h] = singleNeighbour;\n\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}\n \n\t\t\t\t\t\t}\n \n\t\t\t\t\t\topenList.updateHeap(openList.heap.length-1);\n \n\t\t\t\t\t} else {\n \n\t\t\t\t\t\tlet openNeighbour = null; \n \n\t\t\t\t\t\tlet maxP = openList.heap.length;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (let p=1; p<maxP; p++){\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(openList.heap[p].name === neighName){\n \n\t\t\t\t\t\t\t\topenNeighbour = openList.heap[p];\n\t\t\t\t\t\t\t\tneighIndx = p;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n \n\t\t\t\t\t\t}\n \n\t\t\t\t\t\tif (singleNeighbour.distanceFromSource < openList.heap[neighIndx].distanceFromSource) {\n \n\t\t\t\t\t\t\topenList.heap[neighIndx] = singleNeighbour;\n \n\t\t\t\t\t\t}\n \n\t\t\t\t\t\tfor (let h=1; h<numOfNodes; h++){\n \n\t\t\t\t\t\t\tif (graph.nodes.heap[h].name === openList.heap[neighIndx].name){\n \n\t\t\t\t\t\t\t\tgraph.nodes.heap[h] = openList.heap[neighIndx];\n\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}\n \n\t\t\t\t\t\t}\n \n \n\t\t\t\t\t\tgraph.nodes.updateHeap(numOfNodes-1);\n \n\t\t\t\t\t}\n\t\t\t\t\t\n\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}\n\t\n\treturn [false, graph];\n\t\n }", "function minheap_extract(heap) \n{\n var PrintE;\n PrintE = heap[0];\n heap[0] = heap[heap.length - 1];\n\n var a,large;\n var temp = heap.pop();\n for (a=0;a<heap.length;a=large)\n {\n if (2*a+2>heap.length)\n {break;}\n if (heap[2*a+1] > heap[2*a+2]) // use to swap those two numbers\n {\n if (heap[a]>heap[2*a+2])\n {\n temp = heap [a];\n heap[a] = heap[2*a+2];\n heap[2*a+2] = temp; \n large = 2*a+2; \n }\n else\n {break;}\n }\n else\n {\n if (heap[a]>heap[2*a+1])\n {\n temp = heap [2*a+1];\n heap[2*a+1] = heap[a];\n heap[a] = temp; \n large = 2*a+1;\n }\n else\n {break;}\n }\n }\n return PrintE;\n}", "heapDown(index) {\n const [leftIndex, rightIndex] = this.children(index);\n \n if (!leftIndex && !rightIndex) return;\n\n let min;\n rightIndex ? min = rightIndex : min = leftIndex;\n if ((leftIndex && rightIndex) &&\n this.store[leftIndex].key < this.store[rightIndex].key) {\n min = leftIndex;\n }\n\n if (this.store[index].key > this.store[min].key) {\n this.swap(index, min);\n this.heapDown(min);\n }\n }", "heapifyUp(customStartIndex) {\n // Take the last element (last in array or the bottom left in a tree)\n // in the heap container and lift it up until it is in the correct\n // order with respect to its parent element.\n let currentIndex = customStartIndex || this.heapContainer.length - 1;\n\n while (\n this.hasParent(currentIndex) &&\n !(this.parent(currentIndex) <= this.heapContainer[currentIndex])\n ) {\n this.swap(currentIndex, this.getParentIndex(currentIndex));\n currentIndex = this.getParentIndex(currentIndex);\n }\n }", "function heap(a, lo, hi) {\n var n = hi - lo,\n i = (n >>> 1) + 1;\n while (--i > 0) sift(a, i, n, lo);\n return a;\n }", "function Heap(){\n this.heap = [];\n}", "function heapPermutation(a, size, n, output)\n{\n if (size == 1){\n output.push(a.slice());\n return;\n }\n \n var temp, swap;\n for (var i=0; i<size; i++)\n {\n heapPermutation(a, size-1, n, output);\n \n // if size is odd, swap first and last\n // If size is even, swap ith and last\n swap = (size & 1) ? 0 : i;\n\n temp = a[swap];\n a[swap] = a[size-1];\n a[size-1] = temp;\n }\n}", "siftDown(currentIdx, endIdx, heap) {\n // Get childOne index\n\t\t// While not at the end of heap tree or leaf of heap tree\n\t\t// \t\tGet childTwo index\n\t\t// \t\tif there is a childTwo and childTwoValue < childOneValue\n\t\t// \t\t\tvalue to swap is childTwoValue\n\t\t// \t\telse\n\t\t/// \t\tvalue to swap is childOneValue\n\t\t// \t\tif valueToSwap < value at currentIdx\n\t\t// \t\t\tswap two value\n\t\t// \t\t\tupdate currentIdx to be index of valueToSwap\n\t\t// \t\t\tre-calculate childOne index\n\t\t// \t\telse \n\t\t// \t\t\tno swap needed\n let childOneIdx = currentIdx * 2 + 1;\n while (childOneIdx <= endIdx) {\n const childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1;\n let idxToSwap; \n if (childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]) {\n idxToSwap = childTwoIdx;\n } else {\n idxToSwap = childOneIdx;\n }\n\n if (heap[idxToSwap] < heap[currentIdx]) {\n this.swap(idxToSwap, currentIdx, heap);\n currentIdx = idxToSwap;\n childOneIdx = currentIdx * 2 + 1;\n } else {\n return;\n }\n }\n }", "function heapifyStandart(currentIndex, heapSize ,arr){\n\n var largestElement = currentIndex\n var leftIndex = 2 * currentIndex + 1\n var rightIndex = 2 * currentIndex + 2\n\n if (leftIndex < heapSize && arr[currentIndex] < arr[leftIndex]){\n largestElement = leftIndex\n }\n \n if (rightIndex < heapSize && arr[largestElement] < arr[rightIndex]){\n largestElement = rightIndex\n }\n\n if (largestElement != currentIndex){\n swapArrayElement(currentIndex, largestElement, arr)\n heapifyStandart(largestElement, heapSize, arr)\n }\n}", "static buildMaxHeap(a) {\n a.heap_size = a.length;\n\n // Max-heapify the first n/2 elements as\n // they are tree nodes, and the remaining are\n // usually tree leaves\n let mid = parseInt(a.length / 2);\n for (let i = mid; i >= 0; i -= 1) {\n Heap.maxHeapify(a, i);\n }\n }", "grow() {\n this.capacity *= 2;\n this.capacity = this.closestLargestPrime(this.capacity);\n for (let i = 0; i < this.table.length; i++) {\n let currentBucket = this.table[i];\n this.table[i] = [];\n if (currentBucket) {\n if (currentBucket.length > 0) {\n this.elements--;\n currentBucket.forEach(item => {\n this.add(item);\n });\n }\n }\n }\n }", "heapSort(start, length) {\n this.heapify(start, length);\n\n for (let i = length - start; i > 1; i--) {\n this.Writes.swap(start, start + i - 1);\n this.siftDown(1, i - 1, start);\n }\n\n // if(!isMax) {\n // this.Writes.reversal(arr, start, start + length - 1, 1, true, false);\n // }\n}", "_heapifyDownUntil(index) {\n let parentIndex = 0;\n let leftChildIndex = 1;\n let rightChildIndex = 2;\n let childIndex;\n\n while (leftChildIndex < index) {\n childIndex = this._compareChildrenBefore(\n index,\n leftChildIndex,\n rightChildIndex\n );\n\n if (this._shouldSwap(parentIndex, childIndex)) {\n this._swap(parentIndex, childIndex);\n }\n\n parentIndex = childIndex;\n leftChildIndex = (parentIndex * 2) + 1;\n rightChildIndex = (parentIndex * 2) + 2;\n }\n }", "async function heapSort() {\n // To heapify subtree rooted at index i. \n // n is size of heap \n async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }\n\n // main function to do heap sort \n async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }\n\n if (delay && typeof delay !== \"number\") {\n alert(\"sort: First argument must be a typeof Number\");\n return;\n }\n \n blocks = htmlElementToArray(\".block\");\n \n await heapSortAux(blocks);\n\n blocks.forEach((item, index) => {\n blocks[index].style.transition = \"background-color 0.7s\";\n blocks[index].style.backgroundColor = bar_colours.doneColour;\n })\n}", "function displayHeap() {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i].father == arr[i]) {\n arr[i].x = width / 2;\n arr[i].y = 100;\n }\n else {\n if (arr[i] == arr[i].father.leftson)\n arr[i].x = arr[i].father.x - arr[i].father.gap;\n else if (arr[i] == arr[i].father.rightson)\n arr[i].x = arr[i].father.x + arr[i].father.gap;\n\n arr[i].y = arr[i].father.y + 50;\n }\n }\n\n for (var ii = 0; ii < arr.length; ii++)\n arr[ii].edge = new edge(arr[ii]);\n}", "function setupHeap(lists) {\n var heap = new MinHeap();\n for (var i = 0; i < lists.length; i++) {\n var node = new ListNode(lists[i][0], lists[i][1]);\n heap.insert(node);\n }\n return heap;\n}", "heapify(/*index*/ i) {\n // this is a stub\n }", "function heapAddNode(){\n setClass(nodes[heapSize], 2, \"Current\"); //set the first Node to the heap\n currentHeapPosition = heapSize;\n addStep(\"Add Node \" + (heapSize + 1) + \" to the heap and set it to \\\"current\\\".\");\n makeHeapStep = 2;\n}", "path(start, end)\n {\n // Check if the end is reachable\n let endInfo = this.positionInfo(end);\n if (endInfo.passable === false)\n return undefined;\n\n // For node n, parent[n] is the node immediately preceding it on the cheapest path from start to n currently known\n let parent = new Map();\n\n // For node n, gScore[n] is the cost of the cheapest path from start to n currently known\n let gScore = new Map([[start.toString(), 0]]);\n\n // For node n, fScore[n] = gScore[n] + h(n)\n let fScore = new Map([[start.toString(), 0]]);\n\n // The heap of discovered nodes that need to be (re-)expanded\n let openHeap = new BinaryHeap(node => fScore.get(node.toString()) || 0);\n openHeap.push(start);\n\n // The set of closed nodes\n let closedSet = new Set();\n\n // Iterate while the heap is not empty\n while (openHeap.size > 0)\n {\n // Grab the lowest f(x) to process next\n let node = openHeap.pop();\n\n // End case -- result has been found, return the traced path\n if (node.x === end.x && node.y === end.y)\n {\n let path = [node];\n while (parent.has(node.toString()))\n {\n node = parent.get(node.toString());\n path.unshift(node);\n }\n return path.map(position => this.positionInfo(position));\n }\n\n // Normal case -- move node from open to closed, process each of its neighbors\n closedSet.add(node.toString());\n\n // Find all neighbors for the current node\n for (let neighbor of this.getNeighbors(node))\n {\n let neighborInfo = this.positionInfo(neighbor);\n\n // If the neighbor is already closed or is not passable, then continue\n if (closedSet.has(neighbor.toString()) || neighborInfo.passable === false)\n continue;\n\n // The g score is the shortest distance from start to current node\n // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet\n let gScoreTentative = gScore.get(node.toString()) + neighborInfo.cost;\n if (!gScore.has(neighbor.toString()) || gScoreTentative < gScore.get(neighbor.toString()))\n {\n parent.set(neighbor.toString(), node);\n gScore.set(neighbor.toString(), gScoreTentative);\n fScore.set(neighbor.toString(), gScoreTentative + Vector.manhattanDistance(neighbor, end));\n\n if (!openHeap.has(neighbor))\n openHeap.push(neighbor);\n else\n openHeap.rescoreElement(neighbor);\n }\n }\n }\n\n // No path found, so return undefined\n return undefined;\n }", "insert(data) {\r\n\t\tconst size = this.heap.length;\r\n\r\n\t\tif (size === 0) {\r\n\t\t\tthis.heap.push(data);\r\n\t\t} else {\r\n\t\t\tthis.heap.push(data);\r\n\r\n\t\t\tfor (let i = parseInt(this.heap.length / 2 - 1); i >= 0; i--) {\r\n\t\t\t\tthis.maxHeapify(this.heap, this.heap.length, i);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "grow() {\n this.capacity *= 2;\n this.capacity = this.closestLargestPrime(this.capacity);\n for (let i = 0; i < this.table.length; i++) {\n let currentBucket = this.table[i];\n this.table[i] = [];\n if (currentBucket) {\n if (currentBucket.length > 0) {\n this.elements--;\n currentBucket.forEach(item => {\n this.add(item.key, item.value);\n });\n }\n }\n }\n }", "bfs() {\n // need to use a queue when we are doing breadth first searching \n let currentNode = this.root;\n let queue = [];\n let visitedNodes = [];\n // push our current value into our queue array \n queue.push(currentNode);\n // while there are still elements in our queue array\n while (queue.length) {\n // first in is the first out so we work with the oldest item\n currentNode = queue.shift();\n // push the current value into our visited Nodes array\n visitedNodes.push(currentNode.val);\n // if there is a left side that exists \n if (currentNode.left) {\n // push that into our queue to work on \n queue.push(currentNode.left);\n }\n // after the left side if a right side exists then we can push that into the queue\n if (currentNode.right) {\n // push that right value into the queue\n queue.push(currentNode.right);\n }\n }\n // return the array of nodes we have visited \n return visitedNodes;\n }", "Dequeue() {\r\n if (this.heap.length == 0) return;\r\n const highestPriority = this.heap[0];\r\n const leastPriority = this.heap[this.heap.length - 1];\r\n //swap first and last priority\r\n this.heap[this.heap.length - 1] = highestPriority;\r\n this.heap[0] = leastPriority;\r\n this.heap.pop();\r\n let nodeIndex = 0; //sink down\r\n while (true) {\r\n const left = this.heap[2 * nodeIndex + 1];\r\n const right = this.heap[2 * nodeIndex + 2];\r\n const leastElement = this.heap[nodeIndex];\r\n if (\r\n right &&\r\n right.priority < left.priority &&\r\n right.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 2] = leastElement;\r\n this.heap[nodeIndex] = right;\r\n nodeIndex = 2 * nodeIndex + 2;\r\n } else if (\r\n left &&\r\n left.priority < right.priority &&\r\n left.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 1] = leastElement;\r\n this.heap[nodeIndex] = left;\r\n nodeIndex = 2 * nodeIndex + 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n return highestPriority;\r\n }", "function minheap_extract(heap) {\n swap(heap,0,heap.length - 1);\n var to_pop = heap.pop();\n var parent = 0;\n var child = parent * 2 + 1;\n while(child < heap.length){\n if(child + 1 < heap.length && heap[child] > heap[child + 1]){\n child = child + 1;\n }\n if(heap[child] < heap[parent]){\n swap(heap,child,parent);\n parent = child;\n child = parent * 2 + 1; \n }\n else{\n break;\n }\n }\n return to_pop;\n // STENCIL: implement your min binary heap extract operation\n}", "async function heapify(arr,length,i){\n chosen.style.color=\"black\";\n chosen.innerHTML=`Turning the remaining array into max heap...`;\n let largest=i;\n let left=i*2+1;\n let right=left+1;\n let rightBar=document.querySelector(`.bar${right}`);\n let leftBar=document.querySelector(`.bar${left}`);\n let iBar=document.querySelector(`.bar${i}`);\n await sleep(speed);\n iBar.style.backgroundColor=\"#3500d3\";//selected\n if (left<length)\n leftBar.style.backgroundColor=\"#f64c72\";//checking\n if (right<length)\n rightBar.style.backgroundColor=\"#f64c72\";//checking\n if (left<length && arr[left]>arr[largest])\n largest=left;\n if (right<length && arr[right]>arr[largest])\n largest=right;\n if(largest!=i){\n let largestBar=document.querySelector(`.bar${largest}`);\n iBar=document.querySelector(`.bar${i}`);\n [arr[largest],arr[i]]=[arr[i],arr[largest]];\n [largestBar.style.height,iBar.style.height]=[iBar.style.height,largestBar.style.height];\n [largestBar.innerHTML,iBar.innerHTML]=[iBar.innerHTML,largestBar.innerHTML];\n await sleep(speed);\n iBar.style.backgroundColor=\"#17a2b8\";//original\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n\n await heapify(arr,length,largest);\n }\n iBar.style.backgroundColor=\"#17a2b8\";//original\n if (left<length)\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n if (right<length)\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n}", "function heap_root(input, i) { \n var left = 2 * i + 1; \n var right = 2 * i + 2; \n var max = i; \n \n if (left < array_length && input[left] > input[max]) { \n max = left; \n } \n \n if (right < array_length && input[right] > input[max]) { \n max = right; \n } \n \n if (max != i) { \n swap(input, i, max); \n heap_root(input, max); \n } \n}", "heapify(/*index*/ i) {\n let l = this.left(i);\n let r = this.right(i);\n let biggest = i;\n if (l < this.heap_size && this.harr[i].element.compareByMulKeys(this.harr[l].element, this.compareValues) == -1)\n biggest = l;\n if (r < this.heap_size && this.harr[biggest].element.compareByMulKeys(this.harr[r].element, this.compareValues) == -1)\n biggest = r;\n if (biggest != i) {\n this.swap(this.harr, i, biggest);\n this.heapify(biggest);\n }\n }", "function buildMaxHeap() {\n for (let i = Math.floor(array.length / 2) - 1; i >= 0; i--) {\n maxHeapify(i, array.length);\n }\n}", "function heapSort(inputArr){\n var heap = new Heap;\n for(i=0; i<inputArr.length; i++){\n heap.add(inputArr[i])\n }\n var outputArr = []\n for(i=0; i<inputArr.length; i++){\n outputArr.push(heap.remove())\n }\n console.log(outputArr)\n return outputArr\n}", "function O(e,t){var a=t-e.height;if(a)for(var n=e;n;n=n.parent)n.height+=a}", "function pq_insert(heap, new_element) {\n var eIntIdx = heap.length;\n var prntIdx = Math.floor((eIntIdx - 1 ) / 2);\n heap.push(new_element);\n var heaped = (eIntIdx <= 0) || (heap[prntIdx].priority <= heap[eIntIdx]).priority;\n\n while(!heaped){\n var tmp = heap[prntIdx];\n heap[prntIdx] = heap[eIntIdx];\n heap[eIntIdx] = tmp;\n\n eIntIdx = prntIdx;\n prntIdx = Math.floor((eIntIdx - 1)/2);\n heaped = (eIntIdx <= 0) ||(heap[prntIdx].priority <= heap[eIntIdx].priority);\n }\n // STENCIL: implement your min binary heap insert operation\n}", "heapUp(index) {\n if (index <= 0) return;\n \n const parentIndex = this.parentIndex(index);\n if (this.store[index].key < this.store[parentIndex].key) {\n this.swap(index, parentIndex);\n this.heapUp(parentIndex);\n }\n }", "function maxHeapBuild(arr) {\n if (arr.length <= 1) return;\n createHeap(arr, arr.length);\n return arr;\n}", "heapify(currentParent) {\n let left = this.left(currentParent);\n let right = this.right(currentParent);\n let bestParent = currentParent;\n\n // looking for the best parent that fulfills the heap property for this node and it's children\n if (left < this.size && !this.validParent(left, bestParent)) {\n bestParent = left;\n }\n if (right < this.size && !this.validParent(right, bestParent)) {\n bestParent = right;\n }\n\n // if the current parent is not the best parent, we have some work to do\n if (currentParent != bestParent) {\n // swapping new parent with old parent\n let currentParentValue = this.heap[currentParent];\n this.heap[currentParent] = this.heap[bestParent];\n this.heap[bestParent] = currentParentValue;\n\n // set locations on the swap\n this.locations.set(this.hash(this.heap[bestParent]), bestParent);\n this.locations.set(this.hash(this.heap[currentParent]), currentParent);\n\n // recurse from the best parent's old position\n this.heapify(bestParent);\n }\n }", "function sinkNodeDone(){\n heapSize--;\n sortHeapStep = 1;\n}", "function Heap(key) {\n this._array = [];\n this._key = key || function (x) { return x; };\n}", "heapifyDown(customStartIndex = 0) {\n // Compare the parent element to its children and swap parent with the appropriate\n // child (smallest child for MinHeap, largest child for MaxHeap).\n // Do the same for next children after swap.\n let currentIndex = customStartIndex;\n let nextIndex = null;\n\n while (this.hasLeftChild(currentIndex)) {\n if (\n this.hasRightChild(currentIndex) &&\n this.rightChild(currentIndex) <= this.leftChild(currentIndex)\n ) {\n nextIndex = this.getRightChildIndex(currentIndex);\n } else {\n nextIndex = this.getLeftChildIndex(currentIndex);\n }\n\n if (this.heapContainer[currentIndex] <= this.heapContainer[nextIndex]) {\n break;\n }\n\n this.swap(currentIndex, nextIndex);\n currentIndex = nextIndex;\n }\n }", "function heapSort(array){\n // 1: Construction\n let heap = new MaxHeap()\n array.forEach(ele => {\n heap.insert(ele)\n });\n\n// 2: sortdown \n let sorted = []\n while (heap.array.length > 1){\n sorted.push(heap.deleteMax())\n }\n return sorted\n}", "constructor(initial) {\n this.Solution = null;\n let pq = new PQ();\n pq.push(new Node(initial, null, 0));\n while (pq.size > 0) {\n let node = pq.pop();\n if (node.moves > 50) {\n console.log(\"huge\");\n break;\n }\n if (node.board.isGoal() == true) {\n this.Solution = node;\n let copy = node;\n while (copy != null) {\n this.stk.push(copy.board.board);\n copy = copy.previos;\n }\n break;\n }\n node.board.neighbors().forEach(n => {\n if (node.previos != null && node.previos.board.equals(n.board) == false) {\n pq.push(new Node(n, node, node.moves + 1));\n } else if (node.previos == null) {\n pq.push(new Node(n, node, node.moves + 1));\n }\n })\n }\n }", "function addNeighborsLin(curNode, heap, grid, finishNode, visitedNodesInOrder) {\n let { row, col } = curNode;\n let untouchedNeighbors = newNeighborsLin(row, col, grid, visitedNodesInOrder);\n // console.log(untouchedNeighbors,'untouchedN')\n // for(let neighbor in untouchedNeighbors){\n // neighbor.distance = curNode.distance + 1;\n // neighbor.predecessor = curNode;\n // heap.push(neighbor);\n // }\n untouchedNeighbors.forEach((neighbor) => {\n let gCost = curNode.distance.gCost + calcCostLin(curNode, neighbor);\n let hCost = calcCostLin(neighbor, finishNode);\n let fCost = gCost + hCost;\n\n if (neighbor.distance === Infinity) {\n //if node havent been touched put it into the heap\n neighbor.predecessor = curNode;\n neighbor.distance = {\n gCost: gCost,\n hCost: hCost,\n fCost: fCost,\n };\n heap.push(neighbor);\n } else if (neighbor.distance.fCost > fCost) {\n //if it was touched but the new path is faster update the node\n neighbor.predecessor = curNode;\n neighbor.distance = {\n gCost: gCost,\n hCost: hCost,\n fCost: fCost,\n };\n }\n });\n}", "function bfs(i,j,visited){\n var queue = [];\n var curr_node = [i,j];\n //store visited node in this bfs\n var local_visited = [[i,j]];\n var edge = [];\n var territory = 1;\n //var count = 0;\n\n while(curr_node){\n var x = curr_node[0];\n var y = curr_node[1];\n if(x != 0){\n if(contains(local_visited, [x-1,y]) == false){\n if(state.board[x-1][y] == 0){\n local_visited.push([x-1,y]);\n visited.push([x-1,y]);\n queue.push([x-1,y]);\n territory++;\n //alert(\"territory: \" +territory + \" \" +[x-1,y]);\n }\n else{\n //alert(\"edge + \" + [x-1, y]);\n edge.push(state.board[x-1][y]);\n\n }\n }\n }\n\n if(x != state.size - 1){\n if(contains(local_visited, [x+1,y]) == false){\n if(state.board[x+1][y] == 0){\n local_visited.push([x+1,y]);\n visited.push([x+1,y]);\n queue.push([x+1,y]);\n territory++;\n //alert(\"territory: \" +territory + \" \" +[x+1,y]);\n }\n else{ \n //alert(\"edge is \" + [x+1,y]);\n edge.push(state.board[x+1][y]);\n }\n }\n }\n\n if(y != 0){\n if(contains(local_visited, [x,y-1]) == false){\n if(state.board[x][y-1] == 0){\n local_visited.push([x,y-1]);\n visited.push([x,y-1]);\n queue.push([x,y-1]);\n territory++;\n //alert(\"territory: \" +territory + \" \" +[x,y-1]);\n \n }\n else{\n //alert(\"edge is \" + [x, y-1]);\n edge.push(state.board[x][y-1]);\n }\n }\n\n }\n\n if(y != state.size -1){\n if(contains(local_visited, [x,y+1]) == false){\n if(state.board[x][y+1] == 0){\n local_visited.push([x,y+1]);\n visited.push([x,y+1]);\n queue.push([x,y+1]);\n territory++;\n //alert(\"territory: \" +territory + \" \" +[x,y+1]);\n \n }\n else{\n //alert(\"edge is \" + [x, y+1]);\n edge.push(state.board[x][y+1]);\n }\n }\n }\n //count++;\n\n curr_node = queue.shift();\n }\n\n\n var i = edge.length;\n\n //check if this area is surrounded by same color tokens\n //if it is not, it is not a valid territory\n while(i--){\n if(edge[i] != edge[0]){\n territory = 0;\n break;\n }\n }\n if (territory != 0)\n\n return [territory, edge[0]];\n else{\n //alert(curr_node);\n return [territory, 0];\n }\n}", "function popLargest(){\n console.log('done heaping now need to start sorting, should show swapping first and last elements of the array')\n \n //console.log('need to update nodes = ', nodes)\n // swap first with last node\n var topper = d3.select('#nodey' + nodes[0].id)\n \n var highval = nodes[0].data.name\n \n var lower = d3.select('#nodey' + nodes[nodes.length-1].id)\n var lowval = nodes[nodes.length-1].data.name\n \n // console.log('lowval is', lowval)\n var toptransX = nodes[0].x - nodes[nodes.length-1].x\n var toptransY = nodes[nodes.length-1].y -nodes[0].y\n \n // console.log(toptransX, 'and y= ', toptransY)\n topper.select('.valtext')\n .transition()\n .attr('transform', \"translate(\" + toptransX + \", \" + toptransY +')')\n .on('end', function(){\n //nodes[0].data.name = lowval;\n //nodes[nodes.length-1].data.name = highval;\n // console.log('and this is', this)\n d3.select(this).attr('transform', 'translate(0,0)')\n \n // upDateNodeVals()\n })\n \n nodes[0].data.name = lowval;\n nodes[nodes.length-1].data.name = highval;\n \n swapArrayGs(0, nodes.length-1)\n \n MakeRectDone(nodes.length-1, 'blue')\n \n lower.select('circle')\n .transition()\n .delay(1000)\n .duration(colorduration)\n .style('fill', 'blue')\n .on('end', function(d){\n var lastpar = nodes[nodes.length-1].parent;\n lastpar._children = nodes[nodes.length-1];\n // console.log(lastpar, \"last parent is\")\n var removableindex = lastpar.children.indexOf(nodes[nodes.length-1]);\n lastpar.children = lastpar.children.filter(function(d){\n return d !== nodes[nodes.length-1]\n })\n if(lastpar.children.length === 0){\n lastpar.children = null;\n }\n update(lastpar)\n // console.log('nodes after all that,', nodes)\n setTimeout(function(){\n if(nodes.length === 1){\n console.log('All done just need to make this rectangle blue and maybe make the root go to the array.')\n MakeRectDone(0, 'blue')\n }\n else{\n max_heapify(0, {})\n }\n \n }, 2000)\n \n })\n \n // console.log('want to make this blue')\n \n lower.select('.valtext')\n .transition()\n .attr('transform', \"translate(\" + -toptransX + \", \" + -toptransY +')')\n .on('end', function(){\n //nodes[0].data.name = lowval;\n // console.log('and this is', this)\n d3.select(this).attr('transform', 'translate(0,0)')\n \n upDateNodeVals()\n })\n \n }", "function SegmentTreeRMQ(n) {\n let h = Math.ceil(Math.log2(n)), len = 2 * 2 ** h, a = Array(len).fill(Number.MAX_SAFE_INTEGER);\n h = 2 ** h;\n return { update, minx, indexOf, tree }\n function update(pos, v) {\n a[h + pos] = v;\n for (let i = parent(h + pos); i >= 1; i = parent(i)) propagate(i);\n }\n function propagate(i) {\n a[i] = Math.min(a[left(i)], a[right(i)]);\n }\n function minx(l, r) {\n let min = Number.MAX_SAFE_INTEGER;\n if (l >= r) return min;\n l += h;\n r += h;\n for (; l < r; l = parent(l), r = parent(r)) {\n if (l & 1) min = Math.min(min, a[l++]);\n if (r & 1) min = Math.min(min, a[--r]);\n }\n return min;\n }\n function indexOf(l, v) {\n if (l >= h) return -1;\n let cur = h + l;\n while (1) {\n if (a[cur] <= v) {\n if (cur >= h) return cur - h;\n cur = left(cur);\n } else {\n cur++;\n if ((cur & cur - 1) == 0) return -1;\n if (cur % 2 == 0) cur = parent(cur);\n }\n }\n }\n function parent(i) {\n return i >> 1;\n }\n function left(i) {\n return 2 * i;\n }\n function right(i) {\n return 2 * i + 1;\n }\n function tree() {\n return a;\n }\n}" ]
[ "0.68850803", "0.6470579", "0.6470579", "0.63819873", "0.63819873", "0.6373285", "0.63520163", "0.6300878", "0.6250009", "0.6194016", "0.6163549", "0.61485755", "0.6144514", "0.6124655", "0.6123824", "0.6100817", "0.6075846", "0.6018477", "0.6002931", "0.60028577", "0.59801185", "0.59792453", "0.59727985", "0.59696424", "0.596243", "0.596243", "0.59419686", "0.59419686", "0.5930486", "0.5928923", "0.592217", "0.5910002", "0.58951765", "0.58787215", "0.5872478", "0.58431375", "0.58188033", "0.5807831", "0.58012533", "0.5788509", "0.5770253", "0.57639503", "0.5747724", "0.5744968", "0.5743931", "0.57348096", "0.5733844", "0.5731931", "0.5708831", "0.57009965", "0.57000744", "0.5695003", "0.5693904", "0.5693904", "0.5691759", "0.5686249", "0.5654969", "0.5654013", "0.56516755", "0.56441605", "0.5627436", "0.56272584", "0.5626597", "0.5618971", "0.56182206", "0.5596741", "0.55928963", "0.55775726", "0.5575036", "0.5566218", "0.5563867", "0.55606174", "0.5538898", "0.55302846", "0.55245596", "0.55225545", "0.5517691", "0.55142623", "0.5501998", "0.55003434", "0.5493674", "0.54865944", "0.5483453", "0.54768133", "0.54750896", "0.54722846", "0.5471325", "0.54662746", "0.546165", "0.5458975", "0.5453436", "0.54471785", "0.5446845", "0.5443635", "0.54379123", "0.5437726", "0.5436541", "0.542635", "0.5425141", "0.5416413", "0.5405734" ]
0.0
-1
helper No return value (undefined)
siftUp(idx) { if (idx === 1) return; // no need to siftUp if node is at root let parentIdx = this.getParent(idx); // grab parent node idx if (this.array[idx] > this.array[parentIdx]) { // if node is bigger than parent, we're breaking heap proprty, so siftUp [this.array[idx], this.array[parentIdx]] = // swap node w/ parent [this.array[parentIdx], this.array[idx]]; this.siftUp(parentIdx); // recursively siftUp node } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function returnUndefined() {}", "function nothing(){// parameters are optional within functions\n return undefined // will return undefined as a single value of the function\n}", "function emptyReturn() {return;}", "get None() {}", "get None() {}", "get None() {}", "get None() {}", "value() { return undefined; }", "function Helper() {}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "private public function m246() {}", "expected( _utils ) {\n\t\t\treturn 'nothing';\n\t\t}", "function miFuncion (){}", "function dummyReturn(){\n}", "_get(key) { return undefined; }", "function TMP(){return;}", "function TMP(){return;}", "function value() { }", "function nullAndUndefined()\n{\n\n}", "function DefaultReturnValue() {}", "function dummy(){}", "function dummy(){}", "function dummy(){}", "function __func(){}", "function func1(){ // Em funções normais, não se pode omitir seus blocos, denotados por chaves. Apenas em arrow-functions.\r\n \r\n // O retorno de valor é facultativo. Caso você não ponha, ele retornará 'undefined'.\r\n }", "function fnDirect(value) { return value; }", "function fn() {\n\t\t }", "async getNoParam() {\n\t\treturn \"\";\n\t}", "function get_Something(x) {\n return x;\n}", "static private internal function m121() {}", "function noOp(param) {\n return param;\n}", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function f () {\n return undefined;\n }", "function test() {\n return 1;\n }", "private internal function m248() {}", "function wa(){}", "function hai(){\n\treturn \"haiiii\"\n}", "function noReturn() {}", "function fun1(){} //toda a função de js retorna alguma coisa", "function TMP() {\n return;\n }", "function no_op () {}", "function _() { undefined; }", "function _noop(){}", "function def(arg, val) { return (typeof arg !== 'undefined') ? arg : val; }", "function _undefined() {\n return exports.PREFIX.undefined;\n}", "function _null_function() {}", "protected internal function m252() {}", "function identity(val){\n\t return val;\n\t }", "function ba(){}", "function ba(){}", "function ba(){}", "function ba(){}", "expected(_utils) {\n return 'nothing';\n }", "function dummy() {}", "function dummy() {}", "function dummy() {}", "function noop(){\r\n\r\n }", "static aHoax(){\n return false;\n }", "function none(value) {\n\treturn value\n}", "function fuction() {\n\n}", "function FunctionUtils() {}", "no_op() {}", "function Noop(data) {\r\n\r\n}", "value() {return 0}", "function getFunc() { return \"gate\"; }", "hacky(){\n return\n }", "function s(){}", "function _(e){return null===e||void 0===e}", "function reallyCoolFunction(val){\n\tval = val.toString();\n\tif(val.length == 1){ \n\t\t\t// do nothing\n\t} else {\n\t\t//console.log(val);\n\t\tval = val.slice(1); // .slice() function extracts parts of a string. Removes first character.\n\t}\n\tvalue = val;\n\t return val;\n}", "function a(){\n return param\n}", "analyze(){ return null }", "function returnArg(arg) {\n return arg;\n}", "function a(){return s}", "function fuctionPanier(){\n\n}", "function Utils(){}", "_isSet(value) {\n if (value) {\n return value;\n } else {\n return 'no data :('\n }\n }", "static private protected internal function m118() {}", "static get EMPTY()\n\t{\n\t\treturn 0;\n\t}", "function functionName(a){\nconsole.log(a);\nreturn(a);\n}", "function Utils() {}", "function Utils() {}", "function NULL() {\n}", "function isUndefined(value) {\n\n}", "function _undefinedCoerce() {\n return '';\n}", "function Blank() {}", "function Blank() {}", "function Blank() {}", "function Blank() {}", "function Blank() {}", "static get INVALID()\n\t{\n\t\treturn 2;\n\t}", "function getNumber(){\n\treturn;\n}", "function SoloValue() {}", "function miFuncion(){\n\n}" ]
[ "0.70224154", "0.6653878", "0.64629", "0.64429504", "0.64429504", "0.64429504", "0.64429504", "0.64039785", "0.633543", "0.6266707", "0.6266707", "0.6266707", "0.62559164", "0.6229695", "0.6223667", "0.6223067", "0.6166459", "0.61376786", "0.61376786", "0.6111398", "0.6020592", "0.60205454", "0.59693825", "0.59693825", "0.59693825", "0.594637", "0.5900228", "0.58983034", "0.5878757", "0.5872554", "0.58695644", "0.58565503", "0.58532584", "0.5846865", "0.5846865", "0.5846865", "0.5846865", "0.5846865", "0.5846865", "0.5846865", "0.5846703", "0.58422387", "0.5841857", "0.58218443", "0.579339", "0.57683706", "0.57662994", "0.5761707", "0.57440615", "0.57437146", "0.5739209", "0.5736069", "0.57357347", "0.57310206", "0.5726981", "0.57125837", "0.56934047", "0.56934047", "0.56934047", "0.56934047", "0.5690508", "0.5688701", "0.5688701", "0.5688701", "0.5679274", "0.5678551", "0.56580645", "0.5642944", "0.56418145", "0.5635294", "0.5625382", "0.5624272", "0.56228477", "0.5616343", "0.561589", "0.56124055", "0.5600957", "0.5600847", "0.5600053", "0.55990595", "0.5597988", "0.5581512", "0.55806446", "0.55801654", "0.55648", "0.55631083", "0.55623424", "0.5560222", "0.5560222", "0.5558287", "0.55544025", "0.55527925", "0.5550915", "0.5550915", "0.5550915", "0.5550915", "0.5550915", "0.55472106", "0.5546891", "0.5543316", "0.5539766" ]
0.0
-1
returns deleted max value (root) in heap TIME COMPLEXITY: O(log N), N = number of nodes in heap SPACE COMPLEXITY: O(N), 2N > O(N) (2N bec recursive call stack?)
deleteMax() { // recall that we have an empty position at the very front of the array, // so an array length of 2 means there is only 1 item in the heap if (this.array.length === 1) return null; // edge case- if no nodes in tree, exit if (this.array.length === 2) return this.array.pop(); // edge case- if only 1 node in heap, just remove it (2 bec. null doesnt count) let max = this.array[1]; // save reference to root value (max) this.array[1] = this.array.pop(); // remove last val in array (farthest right node in tree), and update root value with it this.siftDown(1); // continuoully swap the new root toward the back of the array to maintain maxHeap property return max; // return max value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "remove() {\n if (this.heap.length < 2) {\n return this.heap.pop(); //easy\n }\n\n const removed = this.heap[0]; // save to return later\n this.heap[0] = this.heap.pop(); // replace with last el\n\n let currentIdx = 0;\n let [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n let currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n // right if heap[right].priority >= heap[left].priority, else left\n // index of max(left.priority, right.priority)\n\n while (\n this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority\n ) {\n let currentNode = this.heap[currentIdx];\n let currentChildNode = this.heap[currentChildIdx];\n\n // swap parent & max child\n\n this.heap[currentChildIdx] = currentNode;\n this.heap[currentIdx] = currentChildNode;\n\n\n // update pointers\n currentIdx = currentChildIdx;\n [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n }\n\n return removed;\n }", "extractMax(){\n // bubble down\n // swap first and last element.\n // then pop\n [this.values[0],this.values[this.values.length-1]] = [this.values[this.values.length-1], this.values[0]]\n // console.log(element + ' removed from the heap');\n this.values.pop();\n let index = 0;\n while(true){\n // compare with both the children and swap with the larger one.\n let leftParent = 2 * index + 1;\n let rightParent = 2 * index + 2;\n if(this.values[index] < this.values[leftParent] || this.values[index] < this.values[rightParent]){\n if(this.values[leftParent] > this.values[rightParent]){\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent;\n\n }\n else if(this.values[rightParent] > this.values[leftParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent;\n }\n else {\n if(this.values[rightParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent\n }\n else {\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent\n }\n \n };\n }\n else return;\n }\n }", "findMaxValue() {\n\n let current = this.root;\n\n const findMax = (node) => {\n if (node === null) {\n return;\n }\n\n let actualMax = node.value;\n let leftSideMax = findMax(node.left);\n let rightSideMax = findMax(node.right);\n\n if (leftSideMax > actualMax) {\n actualMax = leftSideMax;\n }\n\n if (rightSideMax > actualMax) {\n actualMax = rightSideMax;\n }\n\n return actualMax;\n };\n\n return findMax(current);\n }", "extractMax() {\n let values = this.values;\n if (values.length === 0) return;\n let max = values[0];\n // For time complexity reasons, I swap first then remove the old root node\n values[0] = values[values.length - 1];\n values.pop();\n console.log(values);\n // instatiate child nodes\n let child1, child2, indexToSwap;\n let currentIndex = 0;\n while (true) {\n child1 = currentIndex * 2 + 1;\n child2 = currentIndex * 2 + 2;\n if (values[currentIndex] >= Math.max(values[child1], values[child2])) {\n break;\n }\n indexToSwap = values[child1] > values[child2] ? child1 : child2;\n if (!values[indexToSwap]) break;\n let oldNode = values[currentIndex];\n values[currentIndex] = values[indexToSwap];\n values[indexToSwap] = oldNode;\n currentIndex = indexToSwap;\n }\n this.values = values;\n return max;\n }", "function maxHeap(val, parentVal) {\n return val > parentVal;\n}", "extractMax(){\r\n if(this.values.length === 1) return this.values.pop();\r\n const oldRoot = this.values[0];\r\n this.values[0] = this.values[this.values.length-1];\r\n this.values.pop();\r\n let idx = 0;\r\n let child1 = (2*idx) + 1;\r\n let child2 = (2*idx) + 2;\r\n\r\n while(this.values[idx] < this.values[child1] || \r\n this.values[idx] < this.values[child2]){\r\n child1 = (2*idx) + 1;\r\n child2 = (2*idx) + 2;\r\n if(this.values[child1] >= this.values[child2]){\r\n let temp = this.values[child1];\r\n this.values[child1] = this.values[idx];\r\n this.values[idx] = temp;\r\n idx = child1;\r\n } else {\r\n let temp = this.values[child2];\r\n this.values[child2] = this.values[idx];\r\n this.values[idx] = temp;\r\n idx = child2;\r\n }\r\n }\r\n return oldRoot;\r\n }", "extractMax() {\r\n\t\tconst max = this.heap[0];\r\n\t\tthis.remove(max);\r\n\t\treturn max;\r\n\t}", "remove() {\n // Swap root value with last element in the heap\n // Pop the last element from heap array\n // Perform siftDown to correct position of swapped value\n // Return popped value\n this.swap(0, this.heap.length - 1, this.heap);\n const valueToRemove = this.heap.pop();\n this.siftDown(0, this.heap.length - 1, this.heap);\n \n return valueToRemove;\n }", "removeMax() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "extractMax() {\n\t\tconst max = this.heap[0];\n\t\tconst tmp = this.heap.pop();\n\t\tif (!this.empty()) {\n\t\t\tthis.heap[0] = tmp;\n\t\t\tthis.sinkDown(0);\n\t\t}\n\t\treturn max;\n\t}", "function insert_max_heap(A, no, value) {\n A[no] = value //Insert , a new element will be added always at last \n const n = no\n let i = n\n\n //apply hepify method till we reach root (i=1)\n while (i >= 1) {\n const parent = Math.floor((i - 1) / 2)\n if (A[parent] < A[i]) {\n swap(A, parent, i)\n i = parent\n } else {\n i = parent\n //return ;\n }\n }\n}", "function getMaxTree(node) {}", "findMax() {\r\n\t\treturn this.heap[0];\r\n\t}", "function maxHeapify(arr){\n\n}", "function heapDeleteRoot()\n{\n\tif (!this.isEmpty()) { \n\t\t// save root key and item pair\n\t\tvar root = [ this.h[1], this.h_item[1] ]; \n }\n\telse { //if heap is empty\n\t\treturn \"The heap is empty\";\n\t}\n\t// ... complete\n\tthis.h_item[1] = this.h_item[this.size];\n\n this.h[1] = this.h[this.size];\n this.heapify(1);\n\t\n //decrease the heap size by 1 since we delete from it\n this.size = this.size-1;\n\n\treturn root;\n}", "function max() {\n // set node to the root value\n var node = this.root;\n // loop until there is no more values to the right\n while( node.right != null ) {\n node = node.right; // move to the right value\n } // end while\n return node.data;\n} // end max", "max() {\n let currentNode = this.root;\n // continue traversing right until no more children\n while(currentNode.right) {\n currentNode = currentNode.right;\n }\n return currentNode.value;\n }", "max(){\r\n if(this.isEmpty()){\r\n console.log(\"Tree is empty!\");\r\n return null;\r\n }\r\n let runner = this.root;\r\n while(runner.right != null){\r\n runner = runner.right;\r\n }\r\n return runner.value;\r\n }", "function thirdLargestNode(tree) {\n tree.remove(tree._findMax().key);\n tree.remove(tree._findMax().key);\n return tree._findMax().key;\n}", "function _findLargest(root) {\n let nodeSum = _sum(root);\n const product = nodeSum * (totalVal - nodeSum);\n if (product > max) {\n max = product;\n }\n if (root.left && root.right) {\n _findLargest(root.left);\n _findLargest(root.right);\n } else if (root.left || root.right) {\n let child = root.left || root.right;\n let childProduct;\n while (child) {\n nodeSum = nodeSum - root.val;\n childProduct = nodeSum * (totalVal - nodeSum);\n if (childProduct > max) {\n max = childProduct;\n }\n if (child.left && child.right) {\n _findLargest(child.left);\n _findLargest(child.right);\n child = null;\n } else {\n root = child;\n child = child.left || child.right;\n }\n }\n }\n }", "function BSTMax(){\n var walker = this.root;\n while (walker.right != null){\n walker = walker.right;\n }\n return walker.val;\n }", "function maxHeapify(arr , n , i)\n\t{\n\t\n\t\t// Find largest of node and its children\n\t\tif (i >= n) {\n\t\t\treturn;\n\t\t}\n\t\tvar l = i * 2 + 1;\n\t\tvar r = i * 2 + 2;\n\t\tvar max;\n\t\tif (l < n && arr[l] > arr[i]) {\n\t\t\tmax = l;\n\t\t} else\n\t\t\tmax = i;\n\t\tif (r < n && arr[r] > arr[max]) {\n\t\t\tmax = r;\n\t\t}\n\n\t\t// Put maximum value at root and\n\t\t// recur for the child with the\n\t\t// maximum value\n\t\tif (max != i) {\n\t\t\tvar temp = arr[max];\n\t\t\tarr[max] = arr[i];\n\t\t\tarr[i] = temp;\n\t\t\tmaxHeapify(arr, n, max);\n\t\t}\n\t}", "function MaxHeap(array){\r\n Heap.call(this, array);\r\n \r\n // Build-max-heap method: produces a max-heap from an unordered input array\r\n // The elements in the subarray A[(floor(n/2)+1) .. n] are all leaves of the tree, and so\r\n // start doing Float-down from the top non-leave element ( floor(A.length/2) ) to the bottom ( A[i] )\r\n for (var i = Math.floor( this.heapSize / 2 ); i>0; i--){\r\n this.floatDownElementOfIndex(i)\r\n }\r\n}", "function heap_root(input, i) { \n var left = 2 * i + 1; \n var right = 2 * i + 2; \n var max = i; \n \n if (left < array_length && input[left] > input[max]) { \n max = left; \n } \n \n if (right < array_length && input[right] > input[max]) { \n max = right; \n } \n \n if (max != i) { \n swap(input, i, max); \n heap_root(input, max); \n } \n}", "max() {\n let currentNode = this.root;\n // Case for no root\n if(!currentNode) {\n throw new Error('This tree does not yet contain any values');\n return;\n }\n while(currentNode.right) {\n currentNode = currentNode.right;\n }\n return currentNode.value;\n }", "function maxHeap(array, n, i) {\n let largest = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if (left < n && array[left] > array[largest]) {\n largest = left;\n }\n\n // If right child is larger than largest so far\n if (right < n && array[right] > array[largest]) {\n largest = right;\n }\n\n // If largest is not root\n if (largest != i) {\n let swap = array[i];\n array[i] = array[largest];\n array[largest] = swap;\n\n // Recursively heapify the affected sub-tree\n maxHeap(array, n, largest);\n }\n}", "delete() {\n // implement delete\n // only delete if the heap has elements\n if (this.heap.length > 0) {\n // save the smallest element\n let smallest = this.heap[0];\n // swap the last element in the heap whatever it is \n this.heap[0] = this.heap[this.heap.length -1];\n this.heap.pop();\n this.minHeapifyDown(0, this.heap);\n return smallest;\n }\n }", "heapDown(index) {\n const [leftIndex, rightIndex] = this.children(index);\n \n if (!leftIndex && !rightIndex) return;\n\n let min;\n rightIndex ? min = rightIndex : min = leftIndex;\n if ((leftIndex && rightIndex) &&\n this.store[leftIndex].key < this.store[rightIndex].key) {\n min = leftIndex;\n }\n\n if (this.store[index].key > this.store[min].key) {\n this.swap(index, min);\n this.heapDown(min);\n }\n }", "findMax() {\n\n // It will keep the last data until current right is null\n let current = this.root;\n while (current.right !== null) {\n current = current.right;\n }\n\n return current.data;\n }", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "delMin() {\n /*\n * Save reference to the min key.\n * Swap the min key with the last key in the heap.\n * Decrement n so that the key does not swim back up the heap.\n * Sink down the heap to fix any violations that have arisen.\n * Delete the min key to prevent loitering, and return its reference.\n */\n let min = this.heap[1];\n\n [this.heap[1], this.heap[this.n]] = [this.heap[this.n], this.heap[1]];\n this.n--;\n this.sink(1);\n this.heap[this.n+1] = null;\n\n return min;\n }", "findMaxNode() {\n if (this.head == null && this.tail == null) {\n return undefined;\n }\n\n var runner = this.head\n var temp = runner\n while (runner != null) {\n if ( temp.value < runner.value ){\n temp = runner\n }\n runner = runner.next;\n \n }\n return temp;\n }", "maxSum() {\n if (this.root === null) return 0;\n let sum = this.root.val;\n let nodesToVisit = [this.root];\n\n while (nodesToVisit.length){\n\n let current = nodesToVisit.pop();\n\n if ((current.left === null) && (current.right === null)){\n sum = sum;\n }\n\n else if ((current.left !== null) && (current.right === null)){\n sum = sum + current.left.val;\n nodesToVisit.push(current.left)\n }\n\n else if ((current.left === null) && (current.right !== null)){\n sum = sum + current.right.val;\n nodesToVisit.push(current.right) \n }\n\n else if (current.left.val > current.right.val){\n sum = sum + current.left.val;\n nodesToVisit.push(current.left)\n }\n\n else {\n sum = sum + current.right.val;\n nodesToVisit.push(current.right)\n }\n }\n return sum;\n }", "buildMaxHeap() {}", "static buildMaxHeap(a) {\n a.heap_size = a.length;\n\n // Max-heapify the first n/2 elements as\n // they are tree nodes, and the remaining are\n // usually tree leaves\n let mid = parseInt(a.length / 2);\n for (let i = mid; i >= 0; i -= 1) {\n Heap.maxHeapify(a, i);\n }\n }", "findMax() {\n let current = this.root;\n // Loop until the rightmost node (no right subtree).\n while (current.right !== null) {\n current = current.right;\n }\n return current.data;\n }", "extractMax() {\n if (this.values.length===1) {\n return this.values.pop()\n }\n let max = this.values[0]\n let tail = this.values.pop()\n this.values[0] = tail\n let index = 0\n let element = this.values[index]\n // repeat until neither child is greater than the element\n while(true) {\n let swapped = null\n let leftIndex = 2 * index + 1\n let rightIndex = 2 * index + 2\n if (leftIndex < this.values.length) {\n if(this.values[leftIndex] > element) {\n swapped = leftIndex\n }\n }\n if (rightIndex < this.values.length) {\n if( (!swapped && this.values[rightIndex] > element || !!swapped && this.values[rightIndex] > this.values[leftIndex])) {\n swapped = rightIndex\n }\n }\n if (swapped===null) break\n this.values[index] = this.values[swapped]\n this.values[swapped] = element\n index = swapped\n }\n return max\n }", "maximum() {\n if (this.isEmpty()) {\n return null;\n }\n\n return this.doMaximum(this.root).key;\n }", "maxValue() {\n let currNode = this.top;\n let maxValue = this.top.value;\n \n while (currNode.next) {\n if (currNode.next.value > maxValue) maxValue = currNode.next.value;\n currNode = currNode.next;\n }\n \n return maxValue;\n }", "function maxHeapify(arr, length, parent) {\n var largest = parent;\n var leftChild = 2 * parent + 1;\n var rightChild = 2 * parent + 2;\n\n if (leftChild < length && arr[leftChild] > arr[largest]) {\n largest = leftChild;\n }\n\n if (rightChild < length && arr[rightChild] > arr[largest]) {\n largest = rightChild;\n }\n\n if (largest != parent) {\n var temp = arr[largest];\n arr[largest] = arr[parent];\n arr[parent] = temp;\n\n maxHeapify(arr, length, largest);\n }\n}", "maxHeap(index) {\n var left = this.left(index);\n var right = this.right(index);\n var largest = index;\n if (left < this.heapSize && this.array[left] > this.array[index]) {\n largest = left;\n }\n if (right < this.heapSize && this.array[right] > this.array[largest]) {\n largest = right;\n }\n if (largest != index) {\n this.swap(this.array, index, largest);\n this.maxHeap(largest);\n }\n }", "findMaximumValue(root = this.root) {\n // what does it mean to find the max?\n // traverse, and check against \"last max\"\n\n // base case: root is null\n if (!root) return;\n\n // base case: root has no children\n let rootMax = root.val;\n let leftMax, rightMax;\n\n if (root.left) leftMax = this.findMaximumValue(root.left);\n\n if (root.right) rightMax = this.findMaximumValue(root.right);\n\n // rootMax, leftMax and rightMax\n // compare them all and just return the\n // \"true max\"\n let max = rootMax;\n\n if (leftMax > max) max = leftMax;\n if (rightMax > max) max = rightMax;\n\n return max;\n }", "Dequeue() {\r\n if (this.heap.length == 0) return;\r\n const highestPriority = this.heap[0];\r\n const leastPriority = this.heap[this.heap.length - 1];\r\n //swap first and last priority\r\n this.heap[this.heap.length - 1] = highestPriority;\r\n this.heap[0] = leastPriority;\r\n this.heap.pop();\r\n let nodeIndex = 0; //sink down\r\n while (true) {\r\n const left = this.heap[2 * nodeIndex + 1];\r\n const right = this.heap[2 * nodeIndex + 2];\r\n const leastElement = this.heap[nodeIndex];\r\n if (\r\n right &&\r\n right.priority < left.priority &&\r\n right.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 2] = leastElement;\r\n this.heap[nodeIndex] = right;\r\n nodeIndex = 2 * nodeIndex + 2;\r\n } else if (\r\n left &&\r\n left.priority < right.priority &&\r\n left.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 1] = leastElement;\r\n this.heap[nodeIndex] = left;\r\n nodeIndex = 2 * nodeIndex + 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n return highestPriority;\r\n }", "function heapify(array, size, i) {\n let max = i // initialize max as root\n let left = 2 * i + 1\n let right = 2 * i + 2\n \n // if left child is larger than root\n if (left < size && array[left] > array[max])\n max = left\n \n // if right child is larger than max\n if (right < size && array[right] > array[max])\n max = right\n \n // if max is not root\n if (max != i) {\n // swap\n let temp = array[i]\n array[i] = array[max]\n array[max] = temp\n \n // recursively heapify the affected sub-tree\n heapify(array, size, max)\n }\n }", "function buildMaxHeap() {\n for (let i = Math.floor(array.length / 2) - 1; i >= 0; i--) {\n maxHeapify(i, array.length);\n }\n}", "function insert(maxHeap, value) {\n let currentIndex = maxHeap.length;\n let parent = Math.floor((currentIndex - 1) / 2);\n maxHeap.push(value);\n while (maxHeap[currentIndex] > maxHeap[parent]) {\n let temp = maxHeap[parent];\n maxHeap[parent] = maxHeap[currentIndex];\n maxHeap[currentIndex] = temp;\n currentIndex = parent;\n parent = Math.floor((currentIndex - 1) / 2);\n }\n return maxHeap;\n}", "function minheap_extract(heap) {\n swap(heap,0,heap.length - 1);\n var to_pop = heap.pop();\n var parent = 0;\n var child = parent * 2 + 1;\n while(child < heap.length){\n if(child + 1 < heap.length && heap[child] > heap[child + 1]){\n child = child + 1;\n }\n if(heap[child] < heap[parent]){\n swap(heap,child,parent);\n parent = child;\n child = parent * 2 + 1; \n }\n else{\n break;\n }\n }\n return to_pop;\n // STENCIL: implement your min binary heap extract operation\n}", "max() { \n /*\n Receberá a raiz e caso seja nula não terá valor máximo.\n Se for diferente de null, procurará o elemento a extrema direita, que será consequentemente o maior/máximo valor.\n */\n let node = this.root;\n if(node == null) return null\n while(node.right!=null){\n node = node.right;\n }\n return node.content;\n}", "heapify() {\n\t\t// last index is one less than the size\n\t\tlet index = this.size() - 1;\n\n\t\t/*\n Property of ith element in binary heap - \n left child is at = (2*i)th position\n right child is at = (2*i+1)th position\n parent is at = floor(i/2)th position\n */\n\n\t\t// converting entire array into heap from behind to front\n\t\t// just like heapify function to create it MAX HEAP\n\t\twhile (index > 0) {\n\t\t\t// pull out element from the array and find parent element\n\t\t\tlet element = this.heap[index],\n\t\t\t\tparentIndex = Math.floor((index - 1) / 2),\n\t\t\t\tparent = this.heap[parentIndex];\n\n\t\t\t// if parent is greater or equal, its already a heap hence break\n\t\t\tif (parent[0] >= element[0]) break;\n\t\t\t// else swap the values as we're creating a max heap\n\t\t\tthis.heap[index] = parent;\n\t\t\tthis.heap[parentIndex] = element;\n\t\t\tindex = parentIndex;\n\t\t}\n\t}", "function max(node) { \n var keyToReturn = node.key;\n if (node != null && node.key != 'null'){\n if (node.right.key != 'null') {\n keyToReturn = max(node.right);\n } else {\n keyToReturn = node.key;\n //deleteMin(node);\n }\n }\n return keyToReturn;\n }", "function Heap(type) {\n var heapBuf = utils.expandoBuffer(Int32Array),\n indexBuf = utils.expandoBuffer(Int32Array),\n heavierThan = type == 'max' ? lessThan : greaterThan,\n itemsInHeap = 0,\n dataArr,\n heapArr,\n indexArr;\n\n this.init = function(values) {\n var i;\n dataArr = values;\n itemsInHeap = values.length;\n heapArr = heapBuf(itemsInHeap);\n indexArr = indexBuf(itemsInHeap);\n for (i=0; i<itemsInHeap; i++) {\n insertValue(i, i);\n }\n // place non-leaf items\n for (i=(itemsInHeap-2) >> 1; i >= 0; i--) {\n downHeap(i);\n }\n };\n\n this.size = function() {\n return itemsInHeap;\n };\n\n // Update a single value and re-heap\n this.updateValue = function(valIdx, val) {\n var heapIdx = indexArr[valIdx];\n dataArr[valIdx] = val;\n if (!(heapIdx >= 0 && heapIdx < itemsInHeap)) {\n error(\"Out-of-range heap index.\");\n }\n downHeap(upHeap(heapIdx));\n };\n\n this.popValue = function() {\n return dataArr[this.pop()];\n };\n\n this.getValue = function(idx) {\n return dataArr[idx];\n };\n\n this.peek = function() {\n return heapArr[0];\n };\n\n this.peekValue = function() {\n return dataArr[heapArr[0]];\n };\n\n // Return the idx of the lowest-value item in the heap\n this.pop = function() {\n var popIdx;\n if (itemsInHeap <= 0) {\n error(\"Tried to pop from an empty heap.\");\n }\n popIdx = heapArr[0];\n insertValue(0, heapArr[--itemsInHeap]); // move last item in heap into root position\n downHeap(0);\n return popIdx;\n };\n\n function upHeap(idx) {\n var parentIdx;\n // Move item up in the heap until it's at the top or is not lighter than its parent\n while (idx > 0) {\n parentIdx = (idx - 1) >> 1;\n if (heavierThan(idx, parentIdx)) {\n break;\n }\n swapItems(idx, parentIdx);\n idx = parentIdx;\n }\n return idx;\n }\n\n // Swap item at @idx with any lighter children\n function downHeap(idx) {\n var minIdx = compareDown(idx);\n\n while (minIdx > idx) {\n swapItems(idx, minIdx);\n idx = minIdx; // descend in the heap\n minIdx = compareDown(idx);\n }\n }\n\n function swapItems(a, b) {\n var i = heapArr[a];\n insertValue(a, heapArr[b]);\n insertValue(b, i);\n }\n\n // Associate a heap idx with the index of a value in data arr\n function insertValue(heapIdx, valId) {\n indexArr[valId] = heapIdx;\n heapArr[heapIdx] = valId;\n }\n\n // comparator for Visvalingam min heap\n // @a, @b: Indexes in @heapArr\n function greaterThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b],\n val1 = dataArr[idx1],\n val2 = dataArr[idx2];\n // If values are equal, compare array indexes.\n // This is not a requirement of the Visvalingam algorithm,\n // but it generates output that matches Mahes Visvalingam's\n // reference implementation.\n // See https://hydra.hull.ac.uk/assets/hull:10874/content\n return (val1 > val2 || val1 === val2 && idx1 > idx2);\n }\n\n // comparator for max heap\n function lessThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b];\n return dataArr[idx1] < dataArr[idx2];\n }\n\n function compareDown(idx) {\n var a = 2 * idx + 1,\n b = a + 1,\n n = itemsInHeap;\n if (a < n && heavierThan(idx, a)) {\n idx = a;\n }\n if (b < n && heavierThan(idx, b)) {\n idx = b;\n }\n return idx;\n }\n }", "function heapreheapify() {\n\n var node = this.size; // set the size to heap\n var pn = Math.floor(node/2); // use math floor to set last parent node to pn = parent node\n\n var i = pn; // set new varibale and get value pn.\n while(i >= 1)\n {\n var key = i;\n var v = this.h[key];\n var v2 = this.h_item[key];\n var heap = false; // here intitalize heap with boolean value false\n\n for (var j = 2 * key; !heap && 2 * key <= node;)\n {\n if (j < node)\n {\n if (this.h[j] < this.h[j + 1]) {\n j += 1;\n } // end the inner if\n } // end the outer if\n\n\n if (v >= this.h[j])\n {\n heap = true;\n } // end if\n else\n {\n this.h_item[key] = this.h_item[j];\n this.h[key] = this.h[j];\n key = j;\n } // end wlse\n\n this.h[key] = v;\n this.h_item[key] = v2;\n }\n i = i-1; // here decreese the number in each iteration\n } // end while\n}", "function findKthBiggest(root, k) {}", "poll() {\r\n let rootElement = null;\r\n if (this.isEmpty()) {\r\n rootElement = null;\r\n } else if (this.hasSingleElement()) {\r\n rootElement = this.heapContainer.pop();\r\n } else { \r\n rootElement = this.heapContainer[0];\r\n this.heapContainer[0] = this.heapContainer.pop();\r\n this.heapifyDown();\r\n }\r\n \r\n return rootElement;\r\n }", "max() {\r\n return this.maxHelper(this.root);\r\n }", "function maxHeapBuild(arr) {\n if (arr.length <= 1) return;\n createHeap(arr, arr.length);\n return arr;\n}", "function heapify (heap) {\n // Get the parent idx of the last node\n var start = iparent(heap.arr.length - 1)\n while (start >= 0) {\n siftDown(start, heap)\n start -= 1\n }\n return heap\n}", "function deleteMax(h) { \n if (isRed(h.left))\n h = rotateRight(h);\n\n if (h.right == null || h.right == undefined)\n return null;\n\n if (!isRed(h.right) && !isRed(h.right.left))\n h = moveRedRight(h);\n\n h.right = deleteMax(h.right);\n\n return balance(h);\n }", "function secondLargestElement(tree) {\n var current = tree;\n var previous = tree.value;\n\n while (current) {\n if (current.left && !current.right) {\n previous = Math.max(current.value, previous);\n current = current.left;\n } else if (current.right) {\n previous = Math.max(current.value, previous);\n current = current.right;\n } else if (!current.right && !current.left) {\n return Math.min(previous, current.value);\n }\n\n }\n}", "remove(value) {\n let currentNode = this.root\n let prevNode = this.root\n\n while(currentNode) { \n if( value === currentNode.value ) { \n let LR = (currentNode.value > prevNode.value)? 'right' : 'left'\n let nodeToUse\n\n //When the node is a leaf\n if( !currentNode.left && !currentNode.right )\n prevNode[LR] = null\n\n //Get lowest number from right direction\n if( currentNode.right ) {\n nodeToUse = currentNode.right\n let prevNodeToUSe\n\n if( nodeToUse.left ) {\n while( nodeToUse.left ) { \n prevNodeToUSe = nodeToUse\n nodeToUse = nodeToUse.left\n }\n currentNode.value = nodeToUse.value\n prevNodeToUSe.left = nodeToUse.right\n } else {\n currentNode.value = nodeToUse.value\n currentNode.right = nodeToUse.right\n }\n }\n \n //Get greatest number from left direction if there's not right direction\n if( currentNode.left && !currentNode.right ) {\n nodeToUse = currentNode.left\n let prevNodeToUSe\n\n if( nodeToUse.right ) {\n while( nodeToUse.right ) { \n prevNodeToUSe = nodeToUse\n nodeToUse = nodeToUse.right\n }\n currentNode.value = nodeToUse.value\n prevNodeToUSe.left = nodeToUse.right\n } else {\n currentNode.value = nodeToUse.value\n currentNode.right = nodeToUse.left\n }\n }\n\n return this\n }\n\n prevNode = currentNode\n\n if(value < currentNode.value) \n currentNode = currentNode.left\n else\n currentNode = currentNode.right\n }\n }", "getMaxPossibleNode(time) {\n let current = this.start;\n //there is always a highest timeline less than\n while(true) {\n let value = current.right.time.compareTo(time);\n if (value === 0) {\n return current.right;\n } else if (value < 0) {\n current = current.right;\n } else {\n return current;\n }\n }\n }", "maxNode(node) {\n if (node) {\n while (node && node.right !== null) {\n node = node.right;\n }\n return node.key;\n }\n }", "bubble_down (p) {\n // var max_index = max_by(\n // [p, this.right_child(p), this.left_child(p)], // indices\n // index => this.queue[index] || -1 // scoring function\n // )\n\n // var max_index = p\n // var left_child_index = this.left_child(p)\n // var right_child_index = this.right_child(p)\n // if (this.queue[left_child_index] > this.queue[max_index]) {\n // max_index = left_child_index\n // }\n // if (this.queue[right_child_index] > this.queue[max_index]) {\n // max_index = right_child_index\n // }\n //\n // if (max_index !== p) {\n // this.swap(p, max_index)\n // this.bubble_down(max_index)\n // }\n\n\n // // latest and greatest\n var length = this.queue.length;\n var element = this.queue[p]\n\n while(true) {\n var child1N = this.left_child(p)\n var child2N = this.right_child(p)\n\n var swap = null\n if(child1N < length) {\n var child1 = this.queue[child1N]\n\n if (child1 > element)\n swap = child1N\n }\n\n if (child2N < length) {\n var child2 = this.queue[child2N]\n if(child2 > (swap === null ? element : this.queue[child1N]))\n swap = child2N\n }\n\n if (swap == null) {\n break;\n }\n\n this.queue[p] = this.queue[swap]\n this.queue[swap] = element\n p = swap\n }\n }", "function findMax(node) {\n if (node == null) return 0;\n\n let res = node.value;\n let lres = findMax(node.left);\n let rres = findMax(node.right);\n\n if (lres > res) res = lres;\n if (rres > res) res = rres;\n return res;\n}", "function heapDown(i) {\n var w = heapWeight(i)\n while(true) {\n var tw = w\n var left = 2*i + 1\n var right = 2*(i + 1)\n var next = i\n if(left < heapCount) {\n var lw = heapWeight(left)\n if(lw < tw) {\n next = left\n tw = lw\n }\n }\n if(right < heapCount) {\n var rw = heapWeight(right)\n if(rw < tw) {\n next = right\n }\n }\n if(next === i) {\n return i\n }\n heapSwap(i, next)\n i = next \n }\n }", "function heapify(currentIndex, arr){\n\n if (isHavingChildrenLeft(currentIndex, arr)) {\n let parent = arr[currentIndex]\n\n if (isHavingChildrenRight(currentIndex, arr)){\n let maxChildren = Math.max(arr[currentIndex * 2 + 1], arr[currentIndex * 2 + 2])\n if (parent < maxChildren){\n let maxChilrenIndex = maxChildren == arr[currentIndex * 2 + 1] ? currentIndex * 2 + 1 : currentIndex * 2 + 2 \n swapArrayElement(currentIndex, maxChilrenIndex, arr)\n heapify(maxChilrenIndex, arr)\n }\n }else {\n if (parent < arr[currentIndex * 2 + 1]){\n swapArrayElement(currentIndex, currentIndex * 2 + 1, arr)\n heapify(currentIndex * 2 + 1, arr)\n }\n }\n }else {\n console.log(\"skipping index %d\", currentIndex)\n }\n}", "extractMin() {\n if (this.size <= 0) return;\n if (this.size === 1) {\n this.size--;\n return this.data[0];\n }\n let root = this.data[0];\n this.data[0] = this.data[this.size - 1];\n this.size--;\n this.MinHeapify(0);\n return root;\n }", "function heapSortV2(array) {\n\n for (let i = array.length - 1; i >= 0; i--) { // 1) loop through array, and convert it to maxHeap using heapify helper\n heapify(array, array.length, i); // array length not really used for this part\n }\n\n for (let endOfHeap = array.length - 1; endOfHeap >= 0; endOfHeap--) { // 2) loop from end of maxHeap to begin/left, and \"delete\" max val until heap region is \"empty\"\n [array[endOfHeap], array[0]] = [array[0], array[endOfHeap]]; // 3) swap the root of the heap with the last element of the heap, this shrinks the heap by 1 and grows the sorted array by 1\n\n console.log(array);\n\n heapify(array, endOfHeap, 0); // 4) sift down the new root, but not past the end of the heap\n }\n\n return array;\n}", "function minheap_extract(heap) \n{\n var PrintE;\n PrintE = heap[0];\n heap[0] = heap[heap.length - 1];\n\n var a,large;\n var temp = heap.pop();\n for (a=0;a<heap.length;a=large)\n {\n if (2*a+2>heap.length)\n {break;}\n if (heap[2*a+1] > heap[2*a+2]) // use to swap those two numbers\n {\n if (heap[a]>heap[2*a+2])\n {\n temp = heap [a];\n heap[a] = heap[2*a+2];\n heap[2*a+2] = temp; \n large = 2*a+2; \n }\n else\n {break;}\n }\n else\n {\n if (heap[a]>heap[2*a+1])\n {\n temp = heap [2*a+1];\n heap[2*a+1] = heap[a];\n heap[a] = temp; \n large = 2*a+1;\n }\n else\n {break;}\n }\n }\n return PrintE;\n}", "max() {\n let current = this.root\n if (current == null)\n return null\n while (current.right != null)\n current = current.right\n return current.content\n }", "function heapify(array, n, i) {\n let leftIdx = 2 * i + 1; // 1) grab left/right indices/values of current val/node\n let rightIdx = 2 * i + 2; // root index is now 0 instead of 1 (no null placeholder)\n let leftVal = array[leftIdx];\n let rightVal = array[rightIdx];\n\n if (leftIdx >= n) leftVal = -Infinity; // 2) set left/right val to -infinity if we're out of array bounds (determined by n)\n if (rightIdx >= n) rightVal = -Infinity;\n\n if (array[i] > leftVal && array[i] > rightVal) return; // 3) exit if current val > both children\n\n let swapIdx;\n if (leftVal < rightVal) { // 4) determine index to swap current value with\n swapIdx = rightIdx;\n } else {\n swapIdx = leftIdx;\n }\n\n [array[i], array[swapIdx]] = [array[swapIdx], array[i]]; // 5) swap current val w/ larger of two children\n\n heapify(array, n, swapIdx); // 6) recursively siftDown/heapify until maxHeap property met\n}", "function maxProduct(root) {\n const totalVal = _sum(root);\n const modder = Math.pow(10, 9) + 7;\n let max = 0;\n\n // this works, but repeatedly calling _sum makes it inefficient \n function _findLargest(root) {\n let nodeSum = _sum(root);\n const product = nodeSum * (totalVal - nodeSum);\n if (product > max) {\n max = product;\n }\n if (root.left && root.right) {\n _findLargest(root.left);\n _findLargest(root.right);\n } else if (root.left || root.right) {\n let child = root.left || root.right;\n let childProduct;\n while (child) {\n nodeSum = nodeSum - root.val;\n childProduct = nodeSum * (totalVal - nodeSum);\n if (childProduct > max) {\n max = childProduct;\n }\n if (child.left && child.right) {\n _findLargest(child.left);\n _findLargest(child.right);\n child = null;\n } else {\n root = child;\n child = child.left || child.right;\n }\n }\n }\n }\n\n function _sum(root) {\n let sum = 0;\n function _recurAdd(root) {\n if (!root) {\n return;\n }\n sum += root.val;\n _recurAdd(root.left);\n _recurAdd(root.right);\n }\n _recurAdd(root);\n return sum;\n }\n\n _findLargest(root);\n return max % modder;\n}", "function findMax(stack) {\n var maxSize = 0;\n var max = null;\n for (var i = 0; i < stack.length; i++) {\n var peasant = stack[i];\n if (peasant.size > maxSize) {\n maxSize = peasant.size;\n max = peasant;\n }\n }\n\n return max;\n}", "findMax(node) {\n if (node.right === null) {\n return node;\n }\n return this.findMax(node.right);\n }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function maxDepth3(root) {\n if (!root) return 0\n\n const queue = [root]\n let maxDepth = 0\n\n while (queue.length) {\n let size = queue.length\n maxDepth++\n\n while (size) {\n // Remove first element of the queue\n const item = queue.shift()\n\n if (item.left) queue.push(item.left)\n if (item.right) queue.push(item.right)\n\n size--\n }\n }\n\n return maxDepth\n}", "dequeue (){\n // let removedRoot = this.values[0];\n //replace with last added value\n //TEACHERS SOLUTION\n const min = this.values[0];\n const end = this.values.pop();\n //EDGE CASE IF NOTHING LEFT IN\n if(this.values.length > 0){\n //LINE 97 CAUSES A FOREVER LOOP WITH THE LAST ELEMENT IF WE DON'T ADD THE CONDITIONAL, BECAUSE WE REASSIGN THE ROOT TO BE END (WHICH WAS THE ORIGINAL ROOT IF THERE'S ONLY ONE ELEMENT)\n this.values[0] = end;\n //START TRICKLE DOWN\n this.sinkDown();\n }\n \n \n return min;\n }", "function heapSort(array){\n // 1: Construction\n let heap = new MaxHeap()\n array.forEach(ele => {\n heap.insert(ele)\n });\n\n// 2: sortdown \n let sorted = []\n while (heap.array.length > 1){\n sorted.push(heap.deleteMax())\n }\n return sorted\n}", "heapifyDown(){\n let idx = 0,\n element = this.values[idx],\n swap,\n leftChildIdx,\n rightChildIdx,\n leftChild,\n rightChild;\n while (true){\n swap = null;\n leftChildIdx = (2 * idx) + 1;\n rightChildIdx = (2 * idx) + 2;\n leftChild = leftChildIdx < this.values.length ? this.values[leftChildIdx] : null;\n rightChild = rightChildIdx < this.values.length ? this.values[rightChildIdx] : null;\n if (leftChild <= rightChild && leftChild < element && leftChild !== null){\n swap = leftChildIdx\n }\n if (leftChild >= rightChild && rightChild < element && rightChild !== null){\n swap = rightChildIdx;\n }\n if (swap === null) break;\n this.values[idx] = this.values[swap];\n this.values[swap] = element;\n idx = swap; \n } \n }", "function MinHeap() {\n\n /**\n * Insert an item into the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} x\n */\n this.insert = function(x) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:)\n *\n * @return{number}\n */\n this.peek = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Remove and return the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.pop = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the size of the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.size = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Convert the heap data into a string\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{string}\n */\n MinHeap.prototype.toString = function() {\n // INSERT YOUR CODE HERE\n }\n\n /*\n * The following are some optional helper methods. These are not required\n * but may make your life easier\n */\n\n /**\n * Get the index of the parent node of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var parent = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the index of the left child of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var leftChild = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Swap the values at 2 indices in our heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @param{number} j\n */\n var swap = function(i, j) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble up the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleUp = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble down the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleDown = function(i) {\n // INSERT YOUR CODE HERE\n }\n}", "function nMax(){\n var arr=[-3,3,5,7];\n var max= arr[0];\n for(var i = 0; i< arr.length; i++){\n if(arr[i]>max){\n max=arr[i];\n arr.splice(max);\n }\n }\n for(var i=0; i<arr.length;i++){\n if(arr[i]>max){\n max=arr[i];\n \n }\n }\n console.log(max);\n return max;\n }", "dequeue() {\n if (!this.root) return undefined;\n\n let root = this.root,\n returnValue = this.root.value;\n\n if (this.root && !this.root.left && !this.root.right) {\n this.root = null;\n return root.value;\n } // check if there is only one thing in the queue\n\n this.root.value = this.lowestPriority.value;\n this.root.priority = this.lowestPriority.priority;\n if (this.lowestPriority.parent.left == this.lowestPriority) {\n this.lowestPriority.parent.left = null;\n } else if (this.lowestPriority.parent.right == this.lowestPriority) {\n this.lowestPriority.parent.right = null;\n }\n this.lowestPriority = null; // must be redefined!\n this._sinkDown(); // makes sure that everthing is in their correct position\n\n return returnValue;\n }", "function extractMin(heap) {\n if (heap.length < 1) return null\n // swap first and last element\n let temp = heap[0]\n heap[0] = heap[heap.length-1]\n heap[heap.length-1] = temp\n\n const result = heap.pop()\n minHeapify(heap, 0)\n return result\n}", "maxToBack(){\n var runner = this.head;\n var max = this.head\n var prevnode = this.head\n var maxprev = null\n while (runner != null) {\n if (runner.val > max.val) {\n max = runner;\n maxprev = prevnode\n }\n prevnode = runner\n runner = runner.next\n }\n prevnode.next = max\n maxprev.next = max.next\n max.next = null;\n }", "function heightOfABinaryTree(tree) {\n const stack = [];\n const recursive = (tree, count) => {\n if(!tree) return null;\n if(!tree.left && !tree.right) {\n stack.push(count);\n }\n !!tree.left && recursive(tree.left, count+1);\n !!tree.right && recursive(tree.right, count+1);\n }\n recursive(tree, 0);\n return Math.max.apply(null, stack);\n}", "function maxHeapify(idx, hSize) {\n let largest;\n const left = (2 * idx) + 1;\n const right = (2 * idx) + 2;\n if (left < hSize && array[left] > array[idx]) {\n largest = left;\n } else {\n largest = idx;\n }\n if (right < hSize && array[right] > array[largest]) {\n largest = right;\n }\n if (largest !== idx) {\n const temp = array[idx];\n array[idx] = array[largest];\n array[largest] = temp;\n maxHeapify(largest, hSize);\n }\n}", "getRoot() {\n if(this.heap_size <= 0) {\n console.log(\"Heap underflow\");\n return null;\n }\n return this.harr[0];\n }", "function heapify(n, i) {\n let largest = i; // Initialize largest as root\n // Index of left and right child of root\n const left = 2*i + 1;\n const right = 2*i + 2;\n \n // See if left child of root exists and is greater than root\n if (left < n && arr[left] > arr[largest]) {\n largest = left;\n }\n \n // See if right child of root exists and is greater than current largest\n if (right < n && arr[right] > arr[largest]) {\n largest = right;\n }\n \n // Change root if needed\n if (largest !== i) {\n swap(i, largest);\n // Heapify down this subtree\n heapify(n, largest);\n }\n }", "function largestNum(arr, k) {\n\tif (!arr && !arr.length && !k) return false;\n\n\tlet shunk = arr.slice(0, k); //first shunk\n\tlet heap = [];\n\tshunk.forEach(n => insertHeap(heap, n));\n\n\tfor (let i = k; i < arr.length; i++) {\n\t\tif (arr[i] >= heap[0]) {\n\t\t\tupdateHeap(heap, arr[i]);\n\t\t}\n\t}\n\n\treturn heap;\n}", "function maxTreeSum(high, n) {\n var result = 0;\n for (var i = 0; i < n; i++) {\n high += high;\n result += high;\n }\n return result;\n}", "getHeight(){\n let maxHeight = 0;\n const stack = [{node: this, height: 0}];\n while(stack.length){\n const next = stack.pop();\n if(next.height > maxHeight){\n maxHeight = next.height;\n }\n if(next.node.left){\n stack.push({node: next.node.left, height: next.height + 1});\n }\n if(next.node.right){\n stack.push({node: next.node.right, height: next.height + 1});\n }\n }\n return maxHeight;\n }", "find_max(node) {\n if (node.right) {\n return this.find_max(node.right)\n } else {\n return node;\n }\n }", "function remove(root, value) {\n //Exits and link updating/traversal is similar to \"put\"\n if (root == null) return null;\n\n if (value < root.value) root.left = remove(root.left, value);\n else if (value > root.value) root.right = remove(root.right, value);\n else {\n\n //Cases: 0, 1 or multiple children\n //0: Drop parent link\n //1: Linked list style, replace parent\n //2: Find successor of t, delete minimum in t's right subtree, x in t's original spot\n\n if (root.right == null) return root.left;\n if (root.left == null) return root.right;\n var t = _.cloneDeep(root);\n root = min(t.right);\n root.right = deleteMin(t.right);\n root.left = t.left;\n }\n root.size = size(root.left) + size(root.right) + 1;\n return root;\n}", "poll(){\n if(this.length()==1)return this.heap.pop()\n\n let result=this.heap[0]\n this.heap[0]=this.heap.pop()\n this.bubbleDown(0)\n return result\n }", "poll(){\n if(this.length()==1)return this.heap.pop()\n\n let result=this.heap[0]\n this.heap[0]=this.heap.pop()\n this.bubbleDown(0)\n return result\n }", "poll(){\n if(this.length()==1)return this.heap.pop()\n\n let result=this.heap[0]\n this.heap[0]=this.heap.pop()\n this.bubbleDown(0)\n return result\n }", "poll(){\n if(this.length()==1)return this.heap.pop()\n\n let result=this.heap[0]\n this.heap[0]=this.heap.pop()\n this.bubbleDown(0)\n return result\n }", "poll(){\n if(this.length()==1)return this.heap.pop()\n\n let result=this.heap[0]\n this.heap[0]=this.heap.pop()\n this.bubbleDown(0)\n return result\n }" ]
[ "0.72349405", "0.71611047", "0.7118273", "0.7075563", "0.7045658", "0.70281285", "0.69180804", "0.6905783", "0.68910396", "0.6877944", "0.6812218", "0.6794426", "0.67901075", "0.6739307", "0.6712732", "0.6690238", "0.6684173", "0.6665397", "0.66553473", "0.66267765", "0.6597829", "0.6589579", "0.65893865", "0.65690994", "0.65439445", "0.65405995", "0.65342885", "0.6528406", "0.64922047", "0.6476573", "0.6476573", "0.64585733", "0.645088", "0.64256406", "0.63981444", "0.6394105", "0.63904285", "0.6388585", "0.6378107", "0.63716644", "0.6363117", "0.6333058", "0.6314898", "0.6307581", "0.6279285", "0.6264672", "0.6261594", "0.6245015", "0.6236225", "0.6230694", "0.62290376", "0.62171227", "0.61911213", "0.6188439", "0.61756504", "0.6170861", "0.61562824", "0.615091", "0.61497056", "0.61419827", "0.6138678", "0.6134373", "0.6126885", "0.6118336", "0.611765", "0.6102203", "0.6093183", "0.6089237", "0.6041278", "0.6035705", "0.60289353", "0.6023313", "0.60227907", "0.5999255", "0.59989476", "0.5996108", "0.5996108", "0.599508", "0.5949802", "0.59475017", "0.59474146", "0.5943949", "0.592934", "0.59274566", "0.59224665", "0.5914106", "0.5912728", "0.590933", "0.58874166", "0.5880306", "0.5875994", "0.58742124", "0.5861759", "0.5861688", "0.58610797", "0.58437055", "0.58437055", "0.58437055", "0.58437055", "0.58437055" ]
0.828122
0
helper no return value
siftDown(idx) { let ary = this.array; // optional- reference to this.array w/ shorter variable name let leftIdx = this.getLeftChild(idx); // optional- grab left and right child indexes/values (easier to work w/ variable names) let rightIdx = this.getRightChild(idx); let leftVal = ary[leftIdx] || -Infinity; // short circuit if node missing child/undefined, use -Infinity (any val is > -Inifinity) let rightVal = ary[rightIdx] || -Infinity; if (ary[idx] > leftVal && ary[idx] > rightVal) return; // if node is bigger than both children, we have restored heap property, so exit if (leftVal < rightVal) { // node bigger than one of it's children, so swap this node with the larger of the two children var swapIdx = rightIdx; } else { var swapIdx = leftIdx; } [ary[idx], ary[swapIdx]] = [ary[swapIdx], ary[idx]]; this.siftDown(swapIdx); // continue to sift node down recursively }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "function Helper() {}", "private internal function m248() {}", "protected internal function m252() {}", "function miFuncion (){}", "static private internal function m121() {}", "function TMP(){return;}", "function TMP(){return;}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "transient protected internal function m189() {}", "function emptyReturn() {return;}", "function dummy(){}", "function dummy(){}", "function dummy(){}", "transient private protected internal function m182() {}", "obtain(){}", "function TMP() {\n return;\n }", "function __func(){}", "no_op() {}", "function _____SHARED_functions_____(){}", "static private protected internal function m118() {}", "function __it() {}", "expected( _utils ) {\n\t\t\treturn 'nothing';\n\t\t}", "transient private internal function m185() {}", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function noop(){}// No operation performed.", "function fn() {\n\t\t }", "function no_op () {}", "function dummyReturn(){\n}", "function Utils() {}", "function Utils() {}", "function returnUndefined() {}", "static transient private protected internal function m55() {}", "hacky(){\n return\n }", "get None() {}", "get None() {}", "get None() {}", "get None() {}", "function Utils(){}", "function dummy() {}", "function dummy() {}", "function dummy() {}", "static final private internal function m106() {}", "function ba(){}", "function ba(){}", "function ba(){}", "function ba(){}", "function wa(){}", "function noOp(param) {\n return param;\n}", "function noReturn() {}", "function Util() {}", "function DWRUtil() { }", "static transient final private internal function m43() {}", "function _noop(){}", "function ea(){}", "function oi(){}", "function FunctionUtils() {}", "static transient final protected internal function m47() {}", "function normal() {}", "static transient private protected public internal function m54() {}", "function s(){}", "transient final protected internal function m174() {}", "static protected internal function m125() {}", "static method(){}", "function TMP(){}", "function TMP(){}", "static transient private public function m56() {}", "static private protected public internal function m117() {}", "function nothing(){// parameters are optional within functions\n return undefined // will return undefined as a single value of the function\n}", "function AeUtil() {}", "transient private protected public internal function m181() {}", "function DefaultReturnValue() {}", "_get(key) { return undefined; }", "function i(e,t){return t}", "function _noop() {}", "function _noop() {}", "function _noop() {}", "function _noop() {}", "function _noop() {}", "function _noop() {}", "function _noop() {}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}" ]
[ "0.66283953", "0.636572", "0.6310107", "0.6245793", "0.6200203", "0.6197235", "0.61281204", "0.61281204", "0.60964346", "0.60964346", "0.60964346", "0.5978248", "0.59720474", "0.5928135", "0.5928135", "0.5928135", "0.5901462", "0.58703816", "0.58673716", "0.5866943", "0.58105135", "0.58046836", "0.5787599", "0.57740974", "0.57723385", "0.5762871", "0.5760876", "0.5760876", "0.5760876", "0.5760876", "0.5760876", "0.5760876", "0.5760876", "0.5755153", "0.5740148", "0.5739783", "0.5711986", "0.5711986", "0.56923", "0.5677177", "0.56682736", "0.5667749", "0.5667749", "0.5667749", "0.5667749", "0.5662551", "0.565622", "0.565622", "0.565622", "0.5644726", "0.56402165", "0.56402165", "0.56402165", "0.56402165", "0.5624515", "0.562222", "0.561743", "0.5612695", "0.5607131", "0.55921006", "0.5591087", "0.5582791", "0.5580915", "0.5565257", "0.556321", "0.5540479", "0.5532745", "0.5529378", "0.5528712", "0.5504099", "0.55011684", "0.5500779", "0.5500779", "0.54904836", "0.5475315", "0.5466757", "0.54651624", "0.546467", "0.54346365", "0.5432399", "0.5423745", "0.5411301", "0.5411301", "0.5411301", "0.5411301", "0.5411301", "0.5411301", "0.5411301", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246", "0.5405246" ]
0.0
-1
42 / \ 32 24 / \ / \ 30 31 20 18 / \ / 2 7 9 console.log(niceHeap.array); //=> [ null, 42, 32, 24, 30, 9, 20, 18, 2, 7 ] niceHeap.insert(31); console.log(niceHeap.array); //=> [ null, 42, 32, 24, 30, 31, 20, 18, 2, 7, 9 ] console.log(niceHeap.deleteMax()); //=> 42 console.log(niceHeap.array); //=> [ null, 32, 31, 24, 30, 9, 20, 18, 2, 7 ] 32 / \ 31 24 / \ / \ 30 9 20 18 / \ 2 7 3) HEAP SORT V1 (decreasing order, O(N) space) 1 build the heap: insert all elements of the array into MaxHeap 2 construct sorted list: continue to deleteMax until heap is empty every deletion will return the next element in decreasing order DOES NOT MUTATE INPUT ARRAY TIME COMPLEXITY: O(N log(N)), N = array size N + Nlog(N) => N log(N) First N comes from = step 1 (building heap) Nlog(N) comes from = step 2 SPACE COMPLEXITY: O(N), because heap is maintained separately from input array [ 0, 5, 1, 3, 2 ] => [ 5, 3, 2, 1, 0 ]
function heapSort(array) { let heap = new MaxHeap(); array.forEach(num => heap.insert(num)); // 1) build heap O(N) Amortized Time let sorted = []; while (heap.array.length > 1) { // 2) continously delete max and push deleted to sorted arr until heap empty sorted.push(heap.deleteMax()); // deletion takes log(N) } return sorted; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function heapSortV2(array) {\n\n for (let i = array.length - 1; i >= 0; i--) { // 1) loop through array, and convert it to maxHeap using heapify helper\n heapify(array, array.length, i); // array length not really used for this part\n }\n\n for (let endOfHeap = array.length - 1; endOfHeap >= 0; endOfHeap--) { // 2) loop from end of maxHeap to begin/left, and \"delete\" max val until heap region is \"empty\"\n [array[endOfHeap], array[0]] = [array[0], array[endOfHeap]]; // 3) swap the root of the heap with the last element of the heap, this shrinks the heap by 1 and grows the sorted array by 1\n\n console.log(array);\n\n heapify(array, endOfHeap, 0); // 4) sift down the new root, but not past the end of the heap\n }\n\n return array;\n}", "function heapSort(array){\n // 1: Construction\n let heap = new MaxHeap()\n array.forEach(ele => {\n heap.insert(ele)\n });\n\n// 2: sortdown \n let sorted = []\n while (heap.array.length > 1){\n sorted.push(heap.deleteMax())\n }\n return sorted\n}", "function heapSort(arr){\n var sorted = [];\n var heap1 = new MaxHeap();\n \n for(let i=0; i<arr.length; i++){\n heap1.insert(arr[i]);\n }\n \n for(let i=0; i<arr.length; i++){\n sorted.push(heap1.delete());\n }\n return sorted;\n}", "function heapSort(array){\n let heapify = new MinHeap;\n let sortedArray = [];\n let length = array.length;\n\n for(let i = 0; i < length; i++){\n heapify.add(array.pop());\n }\n\n for(let j = 0; j < length; j++){\n sortedArray.push(heapify.extract());\n }\n\n return sortedArray;\n}", "function heapSort(inputArr){\n var heap = new Heap;\n for(i=0; i<inputArr.length; i++){\n heap.add(inputArr[i])\n }\n var outputArr = []\n for(i=0; i<inputArr.length; i++){\n outputArr.push(heap.remove())\n }\n console.log(outputArr)\n return outputArr\n}", "function heapify(arr) {\n if (arr.length < 1) return arr\n for (let i = arr.length - 1; i >= 0; i--) {\n minHeapify(arr, i)\n }\n return arr\n}", "function heapSortInPlace(array){\n for(let i = 1; i < array.length; i++){\n MaxHeap.heapifyUp(array, i);\n }\n\n let temp;\n for(let j = array.length - 1; 0 < j; j--){\n temp = array[0];\n array[0] = array[j];\n array[j] = temp;\n\n // j is the length of array\n MaxHeap.heapifyDown(array, 0, j);\n }\n\n return array;\n}", "function heapSort(arr,comp){\r\n // Turn arr into a heap\r\n heapify(arr,comp);\r\n for(let i = arr.length-1; i > 0; i--){\r\n // The 0th element of a heap is the largest so move it to the top.\r\n [arr[0],arr[i]] = [arr[i],arr[0]];\r\n // The 0th element is no longer the largest; restore the heap property\r\n siftDown(arr,comp,0);\r\n }\r\n}", "heapify() {\n\t\t// last index is one less than the size\n\t\tlet index = this.size() - 1;\n\n\t\t/*\n Property of ith element in binary heap - \n left child is at = (2*i)th position\n right child is at = (2*i+1)th position\n parent is at = floor(i/2)th position\n */\n\n\t\t// converting entire array into heap from behind to front\n\t\t// just like heapify function to create it MAX HEAP\n\t\twhile (index > 0) {\n\t\t\t// pull out element from the array and find parent element\n\t\t\tlet element = this.heap[index],\n\t\t\t\tparentIndex = Math.floor((index - 1) / 2),\n\t\t\t\tparent = this.heap[parentIndex];\n\n\t\t\t// if parent is greater or equal, its already a heap hence break\n\t\t\tif (parent[0] >= element[0]) break;\n\t\t\t// else swap the values as we're creating a max heap\n\t\t\tthis.heap[index] = parent;\n\t\t\tthis.heap[parentIndex] = element;\n\t\t\tindex = parentIndex;\n\t\t}\n\t}", "function maxHeapify(arr){\n\n}", "deleteMax() {\n // recall that we have an empty position at the very front of the array, \n // so an array length of 2 means there is only 1 item in the heap\n\n if (this.array.length === 1) return null;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// edge case- if no nodes in tree, exit\n\n if (this.array.length === 2) return this.array.pop();\t\t\t\t\t\t\t\t\t\t\t\t// edge case- if only 1 node in heap, just remove it (2 bec. null doesnt count)\n\n let max = this.array[1];\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// save reference to root value (max)\n\n this.array[1] = this.array.pop();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // remove last val in array (farthest right node in tree), and update root value with it\n\n this.siftDown(1);\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// continuoully swap the new root toward the back of the array to maintain maxHeap property\n\n return max;\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// return max value\n }", "function heapify(arr,comp){\r\n // arr[n/2-1:n-1] already satisfies the heap property because they are the leaves.\r\n for(let i = Math.floor((arr.length-2)/2); i >= 0; i--){\r\n // Restore the heap property for i\r\n siftDown(arr, comp, i);\r\n }\r\n // Now that the heap property is satisfied for all i from 0 to n-1, the array is a heap\r\n}", "function heapSort(input) {\n // inplace sorting algorithm\n // iterate from the middle and go to the first element and heapify at each position\n let middleElement = Math.ceil(input.length / 2);\n\n for (let i = middleElement; i >= 0; i--) {\n heapify(i, input.length - 1, input);\n }\n\n let lastElement = input.length - 1;\n for (let i = 0; i <= lastElement; i++) {\n let temp = input[lastElement - i];\n input[lastElement - i] = input[0];\n input[0] = temp;\n heapify(0, lastElement - i - 1, input);\n }\n // console.log(\"sorted\");\n // console.log(input);\n}", "extractMax(){\n // bubble down\n // swap first and last element.\n // then pop\n [this.values[0],this.values[this.values.length-1]] = [this.values[this.values.length-1], this.values[0]]\n // console.log(element + ' removed from the heap');\n this.values.pop();\n let index = 0;\n while(true){\n // compare with both the children and swap with the larger one.\n let leftParent = 2 * index + 1;\n let rightParent = 2 * index + 2;\n if(this.values[index] < this.values[leftParent] || this.values[index] < this.values[rightParent]){\n if(this.values[leftParent] > this.values[rightParent]){\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent;\n\n }\n else if(this.values[rightParent] > this.values[leftParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent;\n }\n else {\n if(this.values[rightParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent\n }\n else {\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent\n }\n \n };\n }\n else return;\n }\n }", "remove() {\n if (this.heap.length < 2) {\n return this.heap.pop(); //easy\n }\n\n const removed = this.heap[0]; // save to return later\n this.heap[0] = this.heap.pop(); // replace with last el\n\n let currentIdx = 0;\n let [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n let currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n // right if heap[right].priority >= heap[left].priority, else left\n // index of max(left.priority, right.priority)\n\n while (\n this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority\n ) {\n let currentNode = this.heap[currentIdx];\n let currentChildNode = this.heap[currentChildIdx];\n\n // swap parent & max child\n\n this.heap[currentChildIdx] = currentNode;\n this.heap[currentIdx] = currentChildNode;\n\n\n // update pointers\n currentIdx = currentChildIdx;\n [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n }\n\n return removed;\n }", "function MaxHeap(array){\r\n Heap.call(this, array);\r\n \r\n // Build-max-heap method: produces a max-heap from an unordered input array\r\n // The elements in the subarray A[(floor(n/2)+1) .. n] are all leaves of the tree, and so\r\n // start doing Float-down from the top non-leave element ( floor(A.length/2) ) to the bottom ( A[i] )\r\n for (var i = Math.floor( this.heapSize / 2 ); i>0; i--){\r\n this.floatDownElementOfIndex(i)\r\n }\r\n}", "buildHeap(array) {\n const firstParentIdx = Math.floor((array.length - 2) / 2);\n for (let currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {\n this.siftDown(currentIdx, array.length - 1, array);\n }\n return array;\n }", "function _adjustHeap (arr) {\n var i = parseInt(arr.length / 2) - 1;\n\n while (i >= 0) {\n if (arr[i] < arr[2 * i + 1] || arr[i] < arr[2 * i + 2]) {\n if (arr[2 * i + 1] < arr[2 * i + 2]) {\n arr[2 * i + 2] = [arr[i], arr[i] = arr[2 * i + 2]][0];\n } else {\n arr[2 * i + 1] = [arr[i], arr[i] = arr[2 * i + 1]][0];\n }\n _adjustHeap(arr);\n }\n i--;\n };\n }", "function heapSort(arr,n){\n for(var i=Math.floor(n/2);i>=0;i--){\n heapify(arr,n,i);\n }\n for(var i=n-1;i>=0;i--){\n swap(arr,0,i);\n heapify(arr,i,0);\n }\n}", "heapSort(start, length) {\n this.heapify(start, length);\n\n for (let i = length - start; i > 1; i--) {\n this.Writes.swap(start, start + i - 1);\n this.siftDown(1, i - 1, start);\n }\n\n // if(!isMax) {\n // this.Writes.reversal(arr, start, start + length - 1, 1, true, false);\n // }\n}", "function insert(maxHeap, value) {\n let currentIndex = maxHeap.length;\n let parent = Math.floor((currentIndex - 1) / 2);\n maxHeap.push(value);\n while (maxHeap[currentIndex] > maxHeap[parent]) {\n let temp = maxHeap[parent];\n maxHeap[parent] = maxHeap[currentIndex];\n maxHeap[currentIndex] = temp;\n currentIndex = parent;\n parent = Math.floor((currentIndex - 1) / 2);\n }\n return maxHeap;\n}", "function heapifyStandart(currentIndex, heapSize ,arr){\n\n var largestElement = currentIndex\n var leftIndex = 2 * currentIndex + 1\n var rightIndex = 2 * currentIndex + 2\n\n if (leftIndex < heapSize && arr[currentIndex] < arr[leftIndex]){\n largestElement = leftIndex\n }\n \n if (rightIndex < heapSize && arr[largestElement] < arr[rightIndex]){\n largestElement = rightIndex\n }\n\n if (largestElement != currentIndex){\n swapArrayElement(currentIndex, largestElement, arr)\n heapifyStandart(largestElement, heapSize, arr)\n }\n}", "function buildMaxHeap() {\n for (let i = Math.floor(array.length / 2) - 1; i >= 0; i--) {\n maxHeapify(i, array.length);\n }\n}", "function insert_max_heap(A, no, value) {\n A[no] = value //Insert , a new element will be added always at last \n const n = no\n let i = n\n\n //apply hepify method till we reach root (i=1)\n while (i >= 1) {\n const parent = Math.floor((i - 1) / 2)\n if (A[parent] < A[i]) {\n swap(A, parent, i)\n i = parent\n } else {\n i = parent\n //return ;\n }\n }\n}", "async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }", "function buildHeap(arr, type) {\n // gets the last index\n var lastIndex = arr.length - 1;\n // While the last index is greater than 0\n while (lastIndex > 0) {\n // get the parent index\n var parentIndex = Math.floor((lastIndex - 1) / 2);\n // get the items inside the parent\n // and the last index \n var lastItem = arr[lastIndex];\n var parentItem = arr[parentIndex];\n\n if (type === 'maxHeap') {\n // checks to see if the lastItem is greater\n // than the parentItem if so then do a swap\n if (lastItem > parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n else if (type === 'minHeap') {\n // checks to see if the lastItem is less\n // than the parentItem if so then do a swap\n if (lastItem < parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n\n }\n }", "function heapify(arr,n,i){\n var largest,l,r;\n largest = i;\n l = 2*i+1;\n r = 2*i+2;\n\n if(l<n && arr[l]>arr[largest]){\n largest = l;\n }\n if(r<n && arr[r]>arr[largest]){\n largest = r;\n }\n if(largest!=i){\n swap(arr,i,largest);\n heapify(arr,n,largest);\n }\n\n}", "function minHeap(arr){\r\n\tfor(var i=Math.floor(arr.length/2); i >= 0; i--){\r\n\t\tminHeapafiy(arr, i)\r\n\t}\r\n\treturn arr\r\n}", "function Heap(type) {\n var heapBuf = utils.expandoBuffer(Int32Array),\n indexBuf = utils.expandoBuffer(Int32Array),\n heavierThan = type == 'max' ? lessThan : greaterThan,\n itemsInHeap = 0,\n dataArr,\n heapArr,\n indexArr;\n\n this.init = function(values) {\n var i;\n dataArr = values;\n itemsInHeap = values.length;\n heapArr = heapBuf(itemsInHeap);\n indexArr = indexBuf(itemsInHeap);\n for (i=0; i<itemsInHeap; i++) {\n insertValue(i, i);\n }\n // place non-leaf items\n for (i=(itemsInHeap-2) >> 1; i >= 0; i--) {\n downHeap(i);\n }\n };\n\n this.size = function() {\n return itemsInHeap;\n };\n\n // Update a single value and re-heap\n this.updateValue = function(valIdx, val) {\n var heapIdx = indexArr[valIdx];\n dataArr[valIdx] = val;\n if (!(heapIdx >= 0 && heapIdx < itemsInHeap)) {\n error(\"Out-of-range heap index.\");\n }\n downHeap(upHeap(heapIdx));\n };\n\n this.popValue = function() {\n return dataArr[this.pop()];\n };\n\n this.getValue = function(idx) {\n return dataArr[idx];\n };\n\n this.peek = function() {\n return heapArr[0];\n };\n\n this.peekValue = function() {\n return dataArr[heapArr[0]];\n };\n\n // Return the idx of the lowest-value item in the heap\n this.pop = function() {\n var popIdx;\n if (itemsInHeap <= 0) {\n error(\"Tried to pop from an empty heap.\");\n }\n popIdx = heapArr[0];\n insertValue(0, heapArr[--itemsInHeap]); // move last item in heap into root position\n downHeap(0);\n return popIdx;\n };\n\n function upHeap(idx) {\n var parentIdx;\n // Move item up in the heap until it's at the top or is not lighter than its parent\n while (idx > 0) {\n parentIdx = (idx - 1) >> 1;\n if (heavierThan(idx, parentIdx)) {\n break;\n }\n swapItems(idx, parentIdx);\n idx = parentIdx;\n }\n return idx;\n }\n\n // Swap item at @idx with any lighter children\n function downHeap(idx) {\n var minIdx = compareDown(idx);\n\n while (minIdx > idx) {\n swapItems(idx, minIdx);\n idx = minIdx; // descend in the heap\n minIdx = compareDown(idx);\n }\n }\n\n function swapItems(a, b) {\n var i = heapArr[a];\n insertValue(a, heapArr[b]);\n insertValue(b, i);\n }\n\n // Associate a heap idx with the index of a value in data arr\n function insertValue(heapIdx, valId) {\n indexArr[valId] = heapIdx;\n heapArr[heapIdx] = valId;\n }\n\n // comparator for Visvalingam min heap\n // @a, @b: Indexes in @heapArr\n function greaterThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b],\n val1 = dataArr[idx1],\n val2 = dataArr[idx2];\n // If values are equal, compare array indexes.\n // This is not a requirement of the Visvalingam algorithm,\n // but it generates output that matches Mahes Visvalingam's\n // reference implementation.\n // See https://hydra.hull.ac.uk/assets/hull:10874/content\n return (val1 > val2 || val1 === val2 && idx1 > idx2);\n }\n\n // comparator for max heap\n function lessThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b];\n return dataArr[idx1] < dataArr[idx2];\n }\n\n function compareDown(idx) {\n var a = 2 * idx + 1,\n b = a + 1,\n n = itemsInHeap;\n if (a < n && heavierThan(idx, a)) {\n idx = a;\n }\n if (b < n && heavierThan(idx, b)) {\n idx = b;\n }\n return idx;\n }\n }", "function heapify(array, size, i) {\n let max = i // initialize max as root\n let left = 2 * i + 1\n let right = 2 * i + 2\n \n // if left child is larger than root\n if (left < size && array[left] > array[max])\n max = left\n \n // if right child is larger than max\n if (right < size && array[right] > array[max])\n max = right\n \n // if max is not root\n if (max != i) {\n // swap\n let temp = array[i]\n array[i] = array[max]\n array[max] = temp\n \n // recursively heapify the affected sub-tree\n heapify(array, size, max)\n }\n }", "function buildHeap(A) {\n var n = A.length;\n for (var i = n/2 - 1; i >= 0; i--) {\n heapify(A, i, n);\n }\n}", "function MinHeap() {\n\n /**\n * Insert an item into the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} x\n */\n this.insert = function(x) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:)\n *\n * @return{number}\n */\n this.peek = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Remove and return the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.pop = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the size of the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.size = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Convert the heap data into a string\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{string}\n */\n MinHeap.prototype.toString = function() {\n // INSERT YOUR CODE HERE\n }\n\n /*\n * The following are some optional helper methods. These are not required\n * but may make your life easier\n */\n\n /**\n * Get the index of the parent node of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var parent = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the index of the left child of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var leftChild = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Swap the values at 2 indices in our heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @param{number} j\n */\n var swap = function(i, j) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble up the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleUp = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble down the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleDown = function(i) {\n // INSERT YOUR CODE HERE\n }\n}", "function maxHeapify(idx, hSize) {\n let largest;\n const left = (2 * idx) + 1;\n const right = (2 * idx) + 2;\n if (left < hSize && array[left] > array[idx]) {\n largest = left;\n } else {\n largest = idx;\n }\n if (right < hSize && array[right] > array[largest]) {\n largest = right;\n }\n if (largest !== idx) {\n const temp = array[idx];\n array[idx] = array[largest];\n array[largest] = temp;\n maxHeapify(largest, hSize);\n }\n}", "Dequeue() {\r\n if (this.heap.length == 0) return;\r\n const highestPriority = this.heap[0];\r\n const leastPriority = this.heap[this.heap.length - 1];\r\n //swap first and last priority\r\n this.heap[this.heap.length - 1] = highestPriority;\r\n this.heap[0] = leastPriority;\r\n this.heap.pop();\r\n let nodeIndex = 0; //sink down\r\n while (true) {\r\n const left = this.heap[2 * nodeIndex + 1];\r\n const right = this.heap[2 * nodeIndex + 2];\r\n const leastElement = this.heap[nodeIndex];\r\n if (\r\n right &&\r\n right.priority < left.priority &&\r\n right.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 2] = leastElement;\r\n this.heap[nodeIndex] = right;\r\n nodeIndex = 2 * nodeIndex + 2;\r\n } else if (\r\n left &&\r\n left.priority < right.priority &&\r\n left.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 1] = leastElement;\r\n this.heap[nodeIndex] = left;\r\n nodeIndex = 2 * nodeIndex + 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n return highestPriority;\r\n }", "function MinHeap(){\n\tthis.maxIndex = -1;\n\tthis.arr = {};\n}", "function heapify(array, n, i) {\n let leftIdx = 2 * i + 1; // 1) grab left/right indices/values of current val/node\n let rightIdx = 2 * i + 2; // root index is now 0 instead of 1 (no null placeholder)\n let leftVal = array[leftIdx];\n let rightVal = array[rightIdx];\n\n if (leftIdx >= n) leftVal = -Infinity; // 2) set left/right val to -infinity if we're out of array bounds (determined by n)\n if (rightIdx >= n) rightVal = -Infinity;\n\n if (array[i] > leftVal && array[i] > rightVal) return; // 3) exit if current val > both children\n\n let swapIdx;\n if (leftVal < rightVal) { // 4) determine index to swap current value with\n swapIdx = rightIdx;\n } else {\n swapIdx = leftIdx;\n }\n\n [array[i], array[swapIdx]] = [array[swapIdx], array[i]]; // 5) swap current val w/ larger of two children\n\n heapify(array, n, swapIdx); // 6) recursively siftDown/heapify until maxHeap property met\n}", "function maxHeapify(arr, length, parent) {\n var largest = parent;\n var leftChild = 2 * parent + 1;\n var rightChild = 2 * parent + 2;\n\n if (leftChild < length && arr[leftChild] > arr[largest]) {\n largest = leftChild;\n }\n\n if (rightChild < length && arr[rightChild] > arr[largest]) {\n largest = rightChild;\n }\n\n if (largest != parent) {\n var temp = arr[largest];\n arr[largest] = arr[parent];\n arr[parent] = temp;\n\n maxHeapify(arr, length, largest);\n }\n}", "remove(data) {\r\n\t\tconst size = this.heap.length;\r\n\r\n\t\tlet i;\r\n\t\tfor (i = 0; i < size; i++) {\r\n\t\t\tif (data === this.heap[i]) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t[this.heap[i], this.heap[size - 1]] = [this.heap[size - 1], this.heap[i]];\r\n\t\tthis.heap.splice(size - 1);\r\n\r\n\t\tfor (let i = parseInt(this.heap.length / 2 - 1); i >= 0; i--) {\r\n\t\t\tthis.maxHeapify(this.heap, this.heap.length, i);\r\n\t\t}\r\n\t}", "function heap(compareFunction, array = []) {\n const data = array;\n const heapSort = ()=>{data.sort(compareFunction)};\n const add = function (node) {\n data.push(node);\n heapSort();\n };\n\n const remove = function () {\n const node = data.shift();\n return node;\n };\n\n const empty = function () {\n return data.length === 0;\n };\n const updateItems = function () {\n heapSort();\n };\n return {\n data: data,\n add: add,\n remove: remove,\n empty: empty,\n update: updateItems,\n };\n}", "function maxHeapBuild(arr) {\n if (arr.length <= 1) return;\n createHeap(arr, arr.length);\n return arr;\n}", "function heapify(arr, length, i) {\n let largest = i;\n let left = i * 2 + 1;\n let right = left + 1;\n\n if (left < length && arr[left] > arr[largest]) {\n largest = left;\n }\n if (right < length && arr[right] > arr[largest]) {\n largest = right;\n }\n if (largest != i) {\n [arr[i], arr[largest]] = [arr[largest], arr[i]];\n heapify(arr, length, largest);\n }\n\n return arr;\n}", "function insert(arr, num) {\n console.log('Heap')\n console.log(arr)\n console.log('inserting: '+num)\n arr.push(num)\n console.log(arr)\n\n var childPos = arr.length-1\n var parentPos = Math.floor((arr.length-1)/2)\n var child = arr[childPos]\n var parent = arr[parentPos]\n\n console.log('child: '+child)\n console.log('child position: '+childPos)\n console.log('parent: '+parent)\n console.log('parent position: '+parentPos)\n\n recurse()\n\n function recurse() {\n if (parent === undefined){return}\n if(child >= parent){\n return arr\n }\n console.log('Child is less than parent, swapping...')\n arr[childPos] = parent\n arr[parentPos] = child\n console.log('new array')\n console.log(arr)\n\n childPos = parentPos\n console.log('new child: '+child)\n console.log('new child position: '+childPos)\n\n parentPos = Math.floor((parentPos-1)/2)\n parent = arr[parentPos]\n console.log('new parent: '+parent)\n console.log('new parent position: '+parentPos)\n\n\n return recurse(child, parent)\n }\n}", "function sort(A) {\n buildHeap(A);\n for (var i = A.length -1; i > 0; i--) {\n swap(A, 0, i);\n heapify(A, 0, i);\n }\n}", "heapifyDown(){\n let idx = 0,\n element = this.values[idx],\n swap,\n leftChildIdx,\n rightChildIdx,\n leftChild,\n rightChild;\n while (true){\n swap = null;\n leftChildIdx = (2 * idx) + 1;\n rightChildIdx = (2 * idx) + 2;\n leftChild = leftChildIdx < this.values.length ? this.values[leftChildIdx] : null;\n rightChild = rightChildIdx < this.values.length ? this.values[rightChildIdx] : null;\n if (leftChild <= rightChild && leftChild < element && leftChild !== null){\n swap = leftChildIdx\n }\n if (leftChild >= rightChild && rightChild < element && rightChild !== null){\n swap = rightChildIdx;\n }\n if (swap === null) break;\n this.values[idx] = this.values[swap];\n this.values[swap] = element;\n idx = swap; \n } \n }", "delMin() {\n /*\n * Save reference to the min key.\n * Swap the min key with the last key in the heap.\n * Decrement n so that the key does not swim back up the heap.\n * Sink down the heap to fix any violations that have arisen.\n * Delete the min key to prevent loitering, and return its reference.\n */\n let min = this.heap[1];\n\n [this.heap[1], this.heap[this.n]] = [this.heap[this.n], this.heap[1]];\n this.n--;\n this.sink(1);\n this.heap[this.n+1] = null;\n\n return min;\n }", "function heapify(currentIndex, arr){\n\n if (isHavingChildrenLeft(currentIndex, arr)) {\n let parent = arr[currentIndex]\n\n if (isHavingChildrenRight(currentIndex, arr)){\n let maxChildren = Math.max(arr[currentIndex * 2 + 1], arr[currentIndex * 2 + 2])\n if (parent < maxChildren){\n let maxChilrenIndex = maxChildren == arr[currentIndex * 2 + 1] ? currentIndex * 2 + 1 : currentIndex * 2 + 2 \n swapArrayElement(currentIndex, maxChilrenIndex, arr)\n heapify(maxChilrenIndex, arr)\n }\n }else {\n if (parent < arr[currentIndex * 2 + 1]){\n swapArrayElement(currentIndex, currentIndex * 2 + 1, arr)\n heapify(currentIndex * 2 + 1, arr)\n }\n }\n }else {\n console.log(\"skipping index %d\", currentIndex)\n }\n}", "function heapreheapify() {\n\n var node = this.size; // set the size to heap\n var pn = Math.floor(node/2); // use math floor to set last parent node to pn = parent node\n\n var i = pn; // set new varibale and get value pn.\n while(i >= 1)\n {\n var key = i;\n var v = this.h[key];\n var v2 = this.h_item[key];\n var heap = false; // here intitalize heap with boolean value false\n\n for (var j = 2 * key; !heap && 2 * key <= node;)\n {\n if (j < node)\n {\n if (this.h[j] < this.h[j + 1]) {\n j += 1;\n } // end the inner if\n } // end the outer if\n\n\n if (v >= this.h[j])\n {\n heap = true;\n } // end if\n else\n {\n this.h_item[key] = this.h_item[j];\n this.h[key] = this.h[j];\n key = j;\n } // end wlse\n\n this.h[key] = v;\n this.h_item[key] = v2;\n }\n i = i-1; // here decreese the number in each iteration\n } // end while\n}", "function minheap_extract(heap) \n{\n var PrintE;\n PrintE = heap[0];\n heap[0] = heap[heap.length - 1];\n\n var a,large;\n var temp = heap.pop();\n for (a=0;a<heap.length;a=large)\n {\n if (2*a+2>heap.length)\n {break;}\n if (heap[2*a+1] > heap[2*a+2]) // use to swap those two numbers\n {\n if (heap[a]>heap[2*a+2])\n {\n temp = heap [a];\n heap[a] = heap[2*a+2];\n heap[2*a+2] = temp; \n large = 2*a+2; \n }\n else\n {break;}\n }\n else\n {\n if (heap[a]>heap[2*a+1])\n {\n temp = heap [2*a+1];\n heap[2*a+1] = heap[a];\n heap[a] = temp; \n large = 2*a+1;\n }\n else\n {break;}\n }\n }\n return PrintE;\n}", "maxHeapify(arr, n, i) {\r\n\t\tlet largest = i;\r\n\t\tlet leftIndex = 2 * i + 1;\r\n\t\tlet rightIndex = 2 * i + 2;\r\n\r\n\t\tif (leftIndex < n && arr[leftIndex] > arr[largest]) {\r\n\t\t\tlargest = leftIndex;\r\n\t\t}\r\n\t\tif (rightIndex < n && arr[rightIndex] > arr[largest]) {\r\n\t\t\tlargest = rightIndex;\r\n\t\t}\r\n\t\tif (largest != i) {\r\n\t\t\tlet temp = arr[i];\r\n\t\t\tarr[i] = arr[largest];\r\n\t\t\tarr[largest] = temp;\r\n\t\t\tthis.maxHeapify(arr, n, largest);\r\n\t\t}\r\n\t}", "function MinHeap(array, comparator) {\n\n /**\n * Storage for heap. \n * @private\n */\n this.heap = array || new Array();\n\n /**\n * Default comparator used if an override is not provided.\n * @private\n */\n this.compare = comparator || function(item1, item2) {\n return item1 == item2 ? 0 : item1 < item2 ? -1 : 1;\n };\n\n /**\n * Retrieve the index of the left child of the node at index i.\n * @private\n */\n this.left = function(i) {\n return 2 * i + 1;\n };\n /**\n * Retrieve the index of the right child of the node at index i.\n * @private\n */\n this.right = function(i) {\n return 2 * i + 2;\n };\n /**\n * Retrieve the index of the parent of the node at index i.\n * @private\n */\n this.parent = function(i) {\n return Math.ceil(i / 2) - 1;\n };\n\n /**\n * Ensure that the contents of the heap don't violate the \n * constraint. \n * @private\n */\n this.heapify = function(i) {\n var lIdx = this.left(i);\n var rIdx = this.right(i);\n var smallest;\n if (lIdx < this.heap.length\n && this.compare(this.heap[lIdx], this.heap[i]) < 0) {\n smallest = lIdx;\n } else {\n smallest = i;\n }\n if (rIdx < this.heap.length\n && this.compare(this.heap[rIdx], this.heap[smallest]) < 0) {\n smallest = rIdx;\n }\n if (i != smallest) {\n var temp = this.heap[smallest];\n this.heap[smallest] = this.heap[i];\n this.heap[i] = temp;\n this.heapify(smallest);\n }\n };\n\n /**\n * Starting with the node at index i, move up the heap until parent value\n * is less than the node.\n * @private\n */\n this.siftUp = function(i) {\n var p = this.parent(i);\n if (p >= 0 && this.compare(this.heap[p], this.heap[i]) > 0) {\n var temp = this.heap[p];\n this.heap[p] = this.heap[i];\n this.heap[i] = temp;\n this.siftUp(p);\n }\n };\n\n /**\n * Heapify the contents of an array.\n * This function is called when an array is provided.\n * @private\n */\n this.heapifyArray = function() {\n // for loop starting from floor size/2 going up and heapify each.\n var i = Math.floor(this.heap.length / 2) - 1;\n for (; i >= 0; i--) {\n // jstestdriver.console.log(\"i: \", i);\n this.heapify(i);\n }\n };\n\n // If an initial array was provided, then heapify the array.\n if (array != null) {\n this.heapifyArray();\n }\n ;\n}", "delete() {\n // implement delete\n // only delete if the heap has elements\n if (this.heap.length > 0) {\n // save the smallest element\n let smallest = this.heap[0];\n // swap the last element in the heap whatever it is \n this.heap[0] = this.heap[this.heap.length -1];\n this.heap.pop();\n this.minHeapifyDown(0, this.heap);\n return smallest;\n }\n }", "function maxHeap(array, n, i) {\n let largest = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if (left < n && array[left] > array[largest]) {\n largest = left;\n }\n\n // If right child is larger than largest so far\n if (right < n && array[right] > array[largest]) {\n largest = right;\n }\n\n // If largest is not root\n if (largest != i) {\n let swap = array[i];\n array[i] = array[largest];\n array[largest] = swap;\n\n // Recursively heapify the affected sub-tree\n maxHeap(array, n, largest);\n }\n}", "function MaxPriorityQueue(array){\r\n MaxHeap.call(this, array)\r\n}", "function heapify(A, idx, max) {\n var largest = idx,\n left = 2 * idx + 1,\n right = 2 * idx + 2;\n\n if (left < max && A[left] > A[idx]) {\n largest = left;\n }\n if (right < max && A[right] > A[largest]) {\n largest = right;\n }\n if (largest !== idx) {\n swap(A, idx, largest);\n heapify(A, largest, max);\n }\n}", "function heap_root(input, i) { \n var left = 2 * i + 1; \n var right = 2 * i + 2; \n var max = i; \n \n if (left < array_length && input[left] > input[max]) { \n max = left; \n } \n \n if (right < array_length && input[right] > input[max]) { \n max = right; \n } \n \n if (max != i) { \n swap(input, i, max); \n heap_root(input, max); \n } \n}", "async function heapSort() {\n // To heapify subtree rooted at index i. \n // n is size of heap \n async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }\n\n // main function to do heap sort \n async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }\n\n if (delay && typeof delay !== \"number\") {\n alert(\"sort: First argument must be a typeof Number\");\n return;\n }\n \n blocks = htmlElementToArray(\".block\");\n \n await heapSortAux(blocks);\n\n blocks.forEach((item, index) => {\n blocks[index].style.transition = \"background-color 0.7s\";\n blocks[index].style.backgroundColor = bar_colours.doneColour;\n })\n}", "heapify(/*index*/ i) {\n let l = this.left(i);\n let r = this.right(i);\n let biggest = i;\n if (l < this.heap_size && this.harr[i].element.compareByMulKeys(this.harr[l].element, this.compareValues) == -1)\n biggest = l;\n if (r < this.heap_size && this.harr[biggest].element.compareByMulKeys(this.harr[r].element, this.compareValues) == -1)\n biggest = r;\n if (biggest != i) {\n this.swap(this.harr, i, biggest);\n this.heapify(biggest);\n }\n }", "function heapify (heap) {\n // Get the parent idx of the last node\n var start = iparent(heap.arr.length - 1)\n while (start >= 0) {\n siftDown(start, heap)\n start -= 1\n }\n return heap\n}", "function fun(){\n alert(\"Answer is \" + heapSort([3,0,10,8,1,5,4],7));\n}", "static maxHeapify(a, i) {\n let left = Heap.left(i);\n let right = Heap.right(i);\n\n // Find largest node between current, left and right\n let largest;\n if (left < a.heap_size && a[left] > a[i])\n largest = left;\n else\n largest = i;\n\n if (right < a.heap_size && a[right] > a[largest])\n largest = right;\n\n // Move current element to 'largest' position, and\n // continue until the element is positioned correctly\n if (largest != i) {\n let temp = a[i];\n a[i] = a[largest];\n a[largest] = temp;\n\n Heap.maxHeapify(a, largest);\n }\n }", "removeMax() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "maxHeap(index) {\n var left = this.left(index);\n var right = this.right(index);\n var largest = index;\n if (left < this.heapSize && this.array[left] > this.array[index]) {\n largest = left;\n }\n if (right < this.heapSize && this.array[right] > this.array[largest]) {\n largest = right;\n }\n if (largest != index) {\n this.swap(this.array, index, largest);\n this.maxHeap(largest);\n }\n }", "function minheap_insert(heap, new_element) \n{\n \n var adj,temp;\n heap.push(new_element);\n for (adj=heap.length-1;adj>0;adj=Math.floor((adj-1)/2))\n {\n if (new_element < heap[Math.floor((adj-1)/2)]) // use to swap those two numbers\n {\n temp = new_element;\n heap[adj] = heap[Math.floor((adj-1)/2)];\n heap[Math.floor((adj-1)/2)] = temp; \n }\n }\n return;\n}", "function maxHeapify(arr , n , i)\n\t{\n\t\n\t\t// Find largest of node and its children\n\t\tif (i >= n) {\n\t\t\treturn;\n\t\t}\n\t\tvar l = i * 2 + 1;\n\t\tvar r = i * 2 + 2;\n\t\tvar max;\n\t\tif (l < n && arr[l] > arr[i]) {\n\t\t\tmax = l;\n\t\t} else\n\t\t\tmax = i;\n\t\tif (r < n && arr[r] > arr[max]) {\n\t\t\tmax = r;\n\t\t}\n\n\t\t// Put maximum value at root and\n\t\t// recur for the child with the\n\t\t// maximum value\n\t\tif (max != i) {\n\t\t\tvar temp = arr[max];\n\t\t\tarr[max] = arr[i];\n\t\t\tarr[i] = temp;\n\t\t\tmaxHeapify(arr, n, max);\n\t\t}\n\t}", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "insert(data) {\r\n\t\tconst size = this.heap.length;\r\n\r\n\t\tif (size === 0) {\r\n\t\t\tthis.heap.push(data);\r\n\t\t} else {\r\n\t\t\tthis.heap.push(data);\r\n\r\n\t\t\tfor (let i = parseInt(this.heap.length / 2 - 1); i >= 0; i--) {\r\n\t\t\t\tthis.maxHeapify(this.heap, this.heap.length, i);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "remove(data) {\r\n\t\tconst size = this.heap.length;\r\n\r\n\t\tlet i;\r\n\t\tfor (i = 0; i < size; i++) {\r\n\t\t\tif (data === this.heap[i]) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t[this.heap[i], this.heap[size - 1]] = [this.heap[size - 1], this.heap[i]];\r\n\t\tthis.heap.splice(size - 1);\r\n\r\n\t\tfor (let i = parseInt(this.heap.length / 2 - 1); i >= 0; i--) {\r\n\t\t\tthis.minHeapify(this.heap, this.heap.length, i);\r\n\t\t}\r\n\t}", "function Heap(){\n this.heap = [];\n}", "function Heap()\n{\n\t// h[0] not used, heap initially empty\n\n\tthis.h = [null]; // heap of integer keys\n\tthis.h_item = [null]; // corresponding heap of data-items (any object)\n\tthis.size = 0; // 1 smaller than array (also index of last child)\n\n\n\t// --------------------\n\t// PQ-required only; more could be added later when needed\n\t// the 2 basic shape maintaining operations heapify and reheapify simplify\n\t// processing functions\n\n\tthis.isEmpty = heapisEmpty; // return true if heap empty\n\tthis.deleteRoot = heapDeleteRoot; // return data-item in root\n\tthis.insert = heapInsert; // insert data-item with key\n\n\tthis.heapify = heapheapify; // make subtree heap; top-down heapify (\"sink\") used by .deleteRoot()\n\tthis.reheapify = heapreheapify; // bottom-up reheapify (\"swim\") used by .insert()\n\tthis.show = heapShow; \t // utility: return pretty formatted heap as string\n\t \t // ... etc\n\n\t// --------------------\n}", "heapDown(index) {\n const [leftIndex, rightIndex] = this.children(index);\n \n if (!leftIndex && !rightIndex) return;\n\n let min;\n rightIndex ? min = rightIndex : min = leftIndex;\n if ((leftIndex && rightIndex) &&\n this.store[leftIndex].key < this.store[rightIndex].key) {\n min = leftIndex;\n }\n\n if (this.store[index].key > this.store[min].key) {\n this.swap(index, min);\n this.heapDown(min);\n }\n }", "function heapify(array, size, i, animations)\n{\n let root = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if(left < size && array[left] > array[root])\n {\n animations.push([root, left, false]);\n animations.push([root, left, false]);\n root = left;\n }\n if(right < size && array[right] > array[root])\n {\n animations.push([root, right, false]);\n animations.push([root, right, false]);\n root = right;\n }\n //Root has changed because i was not the root\n if(root != i)\n {\n animations.push([root, array[i], true]);\n animations.push([i, array[root], true]);\n //If root is not i, then swap the values, call heapify recursively\n swap(array, root, i);\n heapify(array, size, root, animations);\n }\n}", "function BinaryHeap() {\n this.array = [];\n }", "async function heapify(arr,length,i){\n chosen.style.color=\"black\";\n chosen.innerHTML=`Turning the remaining array into max heap...`;\n let largest=i;\n let left=i*2+1;\n let right=left+1;\n let rightBar=document.querySelector(`.bar${right}`);\n let leftBar=document.querySelector(`.bar${left}`);\n let iBar=document.querySelector(`.bar${i}`);\n await sleep(speed);\n iBar.style.backgroundColor=\"#3500d3\";//selected\n if (left<length)\n leftBar.style.backgroundColor=\"#f64c72\";//checking\n if (right<length)\n rightBar.style.backgroundColor=\"#f64c72\";//checking\n if (left<length && arr[left]>arr[largest])\n largest=left;\n if (right<length && arr[right]>arr[largest])\n largest=right;\n if(largest!=i){\n let largestBar=document.querySelector(`.bar${largest}`);\n iBar=document.querySelector(`.bar${i}`);\n [arr[largest],arr[i]]=[arr[i],arr[largest]];\n [largestBar.style.height,iBar.style.height]=[iBar.style.height,largestBar.style.height];\n [largestBar.innerHTML,iBar.innerHTML]=[iBar.innerHTML,largestBar.innerHTML];\n await sleep(speed);\n iBar.style.backgroundColor=\"#17a2b8\";//original\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n\n await heapify(arr,length,largest);\n }\n iBar.style.backgroundColor=\"#17a2b8\";//original\n if (left<length)\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n if (right<length)\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n}", "static buildMaxHeap(a) {\n a.heap_size = a.length;\n\n // Max-heapify the first n/2 elements as\n // they are tree nodes, and the remaining are\n // usually tree leaves\n let mid = parseInt(a.length / 2);\n for (let i = mid; i >= 0; i -= 1) {\n Heap.maxHeapify(a, i);\n }\n }", "function heap(a, lo, hi) {\n\t var n = hi - lo,\n\t i = (n >>> 1) + 1;\n\t while (--i > 0) sift(a, i, n, lo);\n\t return a;\n\t }", "function heap(a, lo, hi) {\n var n = hi - lo,\n i = (n >>> 1) + 1;\n while (--i > 0) sift(a, i, n, lo);\n return a;\n }", "async function MaxHeapify( i, heapSize)\n{\n\n let hasLeft = (2 * i + 1 < heapSize) ? true : false;\n let hasRight = (2 * i + 2 < heapSize) ? true : false;\n let l, r;\n let largest = i;\n if (hasLeft)\n l = arr[2 * i + 1].offsetHeight;\n if (hasRight)\n r = arr[2 * i + 2].offsetHeight;\n if (hasLeft && arr[i].offsetHeight < l)\n {\n largest = 2 * i + 1;\n }\n if (hasRight && arr[largest].offsetHeight < r)\n {\n largest = 2 * i + 2;\n }\n if (largest != i)\n {\n arr[i].style.backgroundColor='white';\n arr[largest].style.backgroundColor='green';\n await timer(delay);\n await swap(i, largest);\n arr[i].style.backgroundColor='red';\n arr[largest].style.backgroundColor='red';\n await MaxHeapify(largest, heapSize);\n }\n}", "function minheap_extract(heap) {\n swap(heap,0,heap.length - 1);\n var to_pop = heap.pop();\n var parent = 0;\n var child = parent * 2 + 1;\n while(child < heap.length){\n if(child + 1 < heap.length && heap[child] > heap[child + 1]){\n child = child + 1;\n }\n if(heap[child] < heap[parent]){\n swap(heap,child,parent);\n parent = child;\n child = parent * 2 + 1; \n }\n else{\n break;\n }\n }\n return to_pop;\n // STENCIL: implement your min binary heap extract operation\n}", "function pq_insert(heap, new_element) {\n var eIntIdx = heap.length;\n var prntIdx = Math.floor((eIntIdx - 1 ) / 2);\n heap.push(new_element);\n var heaped = (eIntIdx <= 0) || (heap[prntIdx].priority <= heap[eIntIdx]).priority;\n\n while(!heaped){\n var tmp = heap[prntIdx];\n heap[prntIdx] = heap[eIntIdx];\n heap[eIntIdx] = tmp;\n\n eIntIdx = prntIdx;\n prntIdx = Math.floor((eIntIdx - 1)/2);\n heaped = (eIntIdx <= 0) ||(heap[prntIdx].priority <= heap[eIntIdx].priority);\n }\n // STENCIL: implement your min binary heap insert operation\n}", "function Heap(key) {\n this._array = [];\n this._key = key || function (x) { return x; };\n}", "function SimpleHeap(f) {\n var data = [];\n\n // By default just use standard comparison\n var compareFunc = f;\n if (!compareFunc) {\n compareFunc = function(a,b) {\n if (a < b) return -1;\n return 1;\n }\n }\n\n this.insert = function(x) {\n data.push(x);\n data.sort(compareFunc);\n }\n\n this.pop = function() {\n return data.pop();\n }\n\n this.peek = function() {\n return data[data.length - 1];\n }\n\n this.size = function() {\n return data.length;\n }\n\n SimpleHeap.prototype.toString = function() {\n return data.toString();\n }\n}", "function makeHeap(){\n\n //add a node to a heap and set it to current\n if(makeHeapStep == 1){\n heapAddNode();\n return;\n }else if(makeHeapStep == 2){ //Swim the node up if needed\n\n //We are at the start of the heap. No more swimming possible\n if(currentHeapPosition == 0){\n setNodeOneHeap();\n heapSwimStep = 1;\n \n \n return;\n }\n\n if(heapSwimStep == 1){ //set the parent Node\n heapSetParent();\n }else if(heapSwimStep == 2){ //compare to the parent Node\n if(orderArray[currentHeapPosition] > orderArray[heapParentIndex]){ //we must swap\n heapSwapWithParent();\n }else{ //do not swap. Node is now in the heap proper\n setToHeap();\n }\n \n heapSwimStep = 1;\n }\n }\n\n //sorting is now done\n if(heapSize == numNodes){\n doneMakingHeap = true;\n heapOldPosition = -1;\n addStep(\"The heap is now complete.\");\n }\n}", "async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }", "buildMaxHeap() {}", "function minheap_insert(heap, new_element) {\n heap.push(new_element);\n var index = heap.length - 1;\n while(index > 0){\n var parent = Math.floor((index+1)/2)-1;\n if(heap[parent] > new_element){\n var temp = heap[parent];\n heap[parent] = new_element;\n heap[index] = temp;\n }\n index = parent;\n }\n // STENCIL: implement your min binary heap insert operation\n}", "function heapify(n, i) {\n let largest = i; // Initialize largest as root\n // Index of left and right child of root\n const left = 2*i + 1;\n const right = 2*i + 2;\n \n // See if left child of root exists and is greater than root\n if (left < n && arr[left] > arr[largest]) {\n largest = left;\n }\n \n // See if right child of root exists and is greater than current largest\n if (right < n && arr[right] > arr[largest]) {\n largest = right;\n }\n \n // Change root if needed\n if (largest !== i) {\n swap(i, largest);\n // Heapify down this subtree\n heapify(n, largest);\n }\n }", "function largestNum(arr, k) {\n\tif (!arr && !arr.length && !k) return false;\n\n\tlet shunk = arr.slice(0, k); //first shunk\n\tlet heap = [];\n\tshunk.forEach(n => insertHeap(heap, n));\n\n\tfor (let i = k; i < arr.length; i++) {\n\t\tif (arr[i] >= heap[0]) {\n\t\t\tupdateHeap(heap, arr[i]);\n\t\t}\n\t}\n\n\treturn heap;\n}", "function extractMin(heap) {\n if (heap.length < 1) return null\n // swap first and last element\n let temp = heap[0]\n heap[0] = heap[heap.length-1]\n heap[heap.length-1] = temp\n\n const result = heap.pop()\n minHeapify(heap, 0)\n return result\n}", "function heapDown(i) {\n var w = heapWeight(i)\n while(true) {\n var tw = w\n var left = 2*i + 1\n var right = 2*(i + 1)\n var next = i\n if(left < heapCount) {\n var lw = heapWeight(left)\n if(lw < tw) {\n next = left\n tw = lw\n }\n }\n if(right < heapCount) {\n var rw = heapWeight(right)\n if(rw < tw) {\n next = right\n }\n }\n if(next === i) {\n return i\n }\n heapSwap(i, next)\n i = next \n }\n }", "function minheap_insert(heap, new_element) {\n var length = heap.push(new_element);\n var child = length - 1;\n var parent = (child + child%2)/2 - 1;\n while(parent >= 0 && heap[child] < heap[parent]){\n swap(heap,parent,child);\n child = parent;\n parent = (child + child%2)/2 - 1;\n }\n // STENCIL: implement your min binary heap insert operation\n}", "async function heapSort(){\n bars.innerHTML=\"\";\n let a_copy=[...a];\n for (let i=0;i<a_copy.length;i++){\n let bar=document.createElement(\"div\");\n bar.style=`height: ${(a_copy[i]/35)*100}%;width:${33/40}em;background:#17a2b8;margin:0em 0.285em;float:left;`;\n bar.classList.add(`bar${i}`);\n bar.innerHTML=`<span style=\"font-size:0.7em;color:black;\"><b>${(a_copy[i])}</b></span>`;\n bars.appendChild(bar);\n }\n let length=a_copy.length;\n let i=Math.floor((length/2)-1);\n let j=length-1;\n while (i>=0){\n await heapify(a_copy,length,i);\n i--;\n }\n\n while (j>=0){\n let rootBar=document.querySelector(`.bar${0}`);\n let jBar=document.querySelector(`.bar${j}`);\n chosen.style.color=\"black\";\n chosen.innerHTML=`Deleting the first element...`;\n await sleep(speed+200);\n chosen.innerHTML=`And replacing it with element at index ${j}...`;\n rootBar.style.backgroundColor=\"#f64c72\";//checking\n jBar.style.backgroundColor=\"#f64c72\";//checking\n [a_copy[0],a_copy[j]]=[a_copy[j],a_copy[0]];\n [rootBar.style.height,jBar.style.height]=[jBar.style.height,rootBar.style.height];\n [rootBar.innerHTML,jBar.innerHTML]=[jBar.innerHTML,rootBar.innerHTML];\n await sleep(speed+200);\n rootBar.style.backgroundColor=\"#17a2b8\";//original\n jBar.style.backgroundColor=\"#5cdb95\";//sorted\n await heapify(a_copy,j,0);\n j--;\n }\n for (let i=0;i<a_copy.length;i++){\n let bar=document.querySelector(`.bar${i}`);\n bar.style.backgroundColor=\"#5cdb95\";//sorted\n }\n chosen.style.color=\"black\";\n chosen.innerHTML=`SORTED!!`;\n}", "MinHeapify(index) {\n let left = this.left(index);\n let right = this.right(index);\n let smallest = index;\n if (left < this.size && this.data[left] < this.data[index]) smallest = left;\n if (right < this.size && this.data[right] < this.data[smallest])\n smallest = right;\n if (smallest != index) {\n let temp = this.data[index];\n this.data[index] = this.data[smallest];\n this.data[smallest] = temp;\n this.MinHeapify(smallest);\n }\n }", "insert(data) {\r\n\t\tconst size = this.heap.length;\r\n\r\n\t\tif (size === 0) {\r\n\t\t\tthis.heap.push(data);\r\n\t\t} else {\r\n\t\t\tthis.heap.push(data);\r\n\r\n\t\t\tfor (let i = parseInt(this.heap.length / 2 - 1); i >= 0; i--) {\r\n\t\t\t\tthis.minHeapify(this.heap, this.heap.length, i);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "remove(element,comparator=this.compare){\r\n let totalOccurenceOfElement=this.find(element,comparator).length;\r\n for(let i=0;i<totalOccurenceOfElement;i++){\r\n let removeIndex=this.heapContainer.findIndex((x)=> comparator.equal(x,element)); // findIndex is used for finding first found element's index\r\n let heapSize=this.heapContainer.length;\r\n // if the element is at last index simply remove it as we\r\n // don't need to haepify\r\n if(removeIndex===heapSize-1){\r\n this.heapContainer.pop();\r\n }\r\n else{\r\n this.heapContainer[removeIndex]=this.heapContainer[heapSize-1]; \r\n this.heapContainer.pop();\r\n let parentElement=this.getParent(removeIndex);\r\n let elementAtRemovedIndex=this.heapContainer[removeIndex];\r\n // if at index where the element is removed does not have a parent element that means it was on root and we cannot go up to heapify and alternately if the parent element\r\n // is in right order as compare to the new element that is moved to removed index that means we dont' have to take care of upper part of heap as if it is i right position to parent than it will also be in correct position to it's\r\n // parent's parent and we have used hasLeftChild because we only need to heapify down if there exists element in \r\n // down side\r\n if(!parentElement || this.isPairInRightOrder(parentElement,elementAtRemovedIndex) && this.hasLeftChild(removeIndex)){\r\n this.heapifyDown(removeIndex);\r\n }\r\n else{\r\n this.heapifyUp(removeIndex);\r\n }\r\n }\r\n \r\n }\r\n return this;\r\n }", "insert_num(num) {\n // Insert a number if the num is less than the top ele in maxHeap, or maxHeap top is null\n if (!this.maxHeap.values.length || this.maxHeap.peek() >= num) {\n this.maxHeap.insert(num);\n } else {\n this.minHeap.insert(num);\n }\n\n // Rebalance the heaps. Max heap should have 1 extra element if total num of elements is odd\n if (this.maxHeap.values.length > this.minHeap.heap.length + 1) {\n this.minHeap.insert(this.maxHeap.extractMax());\n } else if (this.maxHeap.values.length < this.minHeap.heap.length) {\n this.maxHeap.insert(this.minHeap.remove());\n }\n }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "removeMin() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "function maxHeap(val, parentVal) {\n return val > parentVal;\n}" ]
[ "0.8441638", "0.8383409", "0.83790016", "0.80350906", "0.79281044", "0.77813506", "0.77546066", "0.76377046", "0.7431767", "0.7415624", "0.7386157", "0.73556167", "0.73465705", "0.7266286", "0.7224221", "0.72144055", "0.7195736", "0.71639025", "0.7154635", "0.711052", "0.7098958", "0.70764285", "0.7027095", "0.70260656", "0.69819987", "0.69805264", "0.697319", "0.6971001", "0.6906917", "0.6880307", "0.68798727", "0.6868676", "0.68574893", "0.6834817", "0.6834303", "0.6833369", "0.6831484", "0.6809788", "0.67999965", "0.6792946", "0.6792492", "0.67833716", "0.6772011", "0.67544585", "0.6739841", "0.67355496", "0.67210674", "0.6713245", "0.67108047", "0.66844076", "0.6682721", "0.6669153", "0.6662805", "0.6652501", "0.6650995", "0.6637229", "0.66207683", "0.6602797", "0.65897495", "0.6576094", "0.65713614", "0.65709907", "0.65576506", "0.65209395", "0.6507728", "0.6507728", "0.6496221", "0.6483976", "0.64435726", "0.64385456", "0.6423464", "0.6379406", "0.63649964", "0.63125026", "0.627993", "0.62735516", "0.62681925", "0.6259849", "0.6259001", "0.62101376", "0.62036514", "0.6200071", "0.6194977", "0.61889267", "0.61543995", "0.61382604", "0.61226755", "0.6120729", "0.6114047", "0.6113221", "0.611246", "0.6108449", "0.60744864", "0.6072603", "0.6071685", "0.6042672", "0.6034088", "0.6034088", "0.6030605", "0.6021239" ]
0.8260483
3
let arr = [ 0, 5, 1, 3, 2 ]; console.log(heapSort(arr)); //=> [ 5, 3, 2, 1, 0 ] 4) HEAP SORT V2 (Increasing order, O(1) space) 1 convert input array into maxHeap (in place), using heapify helper (similar to MaxHeapsiftDown method). This involves looping from left of array to front/right 2 diff btwn heapify and siftDown: root idx at 0 not one (no null placeholder) input arg, n determines out of bounds of array, not array length this is needed for part 2 below 2 loop from end of maxHeap to begin, continually swap root val w/ end of heap, and call heapify helper dont forget to define n as end of heap when calling heapify helper see heapsortdiagram.png for visualization of step 2 DOES MUTATE INPUT ARRAY TIME COMPLEXITY: O(N log(N)), N = array size N + Nlog(N) => Nlog(N) First N comes from = step 1 (building heap) Nlog(N) comes from = step 2 SPACE COMPLEXITY: O(1) (unless you count recursive stack?) HELPER FUNCTION similar logic to MaxHeapSiftDown n = number of nodes in heap, denotes where heap ends, and sorted region begins ([ 0, 5, 1, 3, 2 ]) => [ 5, 3, 1, 0, 2 ]
function heapify(array, n, i) { let leftIdx = 2 * i + 1; // 1) grab left/right indices/values of current val/node let rightIdx = 2 * i + 2; // root index is now 0 instead of 1 (no null placeholder) let leftVal = array[leftIdx]; let rightVal = array[rightIdx]; if (leftIdx >= n) leftVal = -Infinity; // 2) set left/right val to -infinity if we're out of array bounds (determined by n) if (rightIdx >= n) rightVal = -Infinity; if (array[i] > leftVal && array[i] > rightVal) return; // 3) exit if current val > both children let swapIdx; if (leftVal < rightVal) { // 4) determine index to swap current value with swapIdx = rightIdx; } else { swapIdx = leftIdx; } [array[i], array[swapIdx]] = [array[swapIdx], array[i]]; // 5) swap current val w/ larger of two children heapify(array, n, swapIdx); // 6) recursively siftDown/heapify until maxHeap property met }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function heapSortV2(array) {\n\n for (let i = array.length - 1; i >= 0; i--) { // 1) loop through array, and convert it to maxHeap using heapify helper\n heapify(array, array.length, i); // array length not really used for this part\n }\n\n for (let endOfHeap = array.length - 1; endOfHeap >= 0; endOfHeap--) { // 2) loop from end of maxHeap to begin/left, and \"delete\" max val until heap region is \"empty\"\n [array[endOfHeap], array[0]] = [array[0], array[endOfHeap]]; // 3) swap the root of the heap with the last element of the heap, this shrinks the heap by 1 and grows the sorted array by 1\n\n console.log(array);\n\n heapify(array, endOfHeap, 0); // 4) sift down the new root, but not past the end of the heap\n }\n\n return array;\n}", "function heapSort(array){\n // 1: Construction\n let heap = new MaxHeap()\n array.forEach(ele => {\n heap.insert(ele)\n });\n\n// 2: sortdown \n let sorted = []\n while (heap.array.length > 1){\n sorted.push(heap.deleteMax())\n }\n return sorted\n}", "function heapSort(input) {\n // inplace sorting algorithm\n // iterate from the middle and go to the first element and heapify at each position\n let middleElement = Math.ceil(input.length / 2);\n\n for (let i = middleElement; i >= 0; i--) {\n heapify(i, input.length - 1, input);\n }\n\n let lastElement = input.length - 1;\n for (let i = 0; i <= lastElement; i++) {\n let temp = input[lastElement - i];\n input[lastElement - i] = input[0];\n input[0] = temp;\n heapify(0, lastElement - i - 1, input);\n }\n // console.log(\"sorted\");\n // console.log(input);\n}", "function heapSort(arr){\n var sorted = [];\n var heap1 = new MaxHeap();\n \n for(let i=0; i<arr.length; i++){\n heap1.insert(arr[i]);\n }\n \n for(let i=0; i<arr.length; i++){\n sorted.push(heap1.delete());\n }\n return sorted;\n}", "function heapSortInPlace(array){\n for(let i = 1; i < array.length; i++){\n MaxHeap.heapifyUp(array, i);\n }\n\n let temp;\n for(let j = array.length - 1; 0 < j; j--){\n temp = array[0];\n array[0] = array[j];\n array[j] = temp;\n\n // j is the length of array\n MaxHeap.heapifyDown(array, 0, j);\n }\n\n return array;\n}", "function heapify(arr) {\n if (arr.length < 1) return arr\n for (let i = arr.length - 1; i >= 0; i--) {\n minHeapify(arr, i)\n }\n return arr\n}", "function heapSort(arr,comp){\r\n // Turn arr into a heap\r\n heapify(arr,comp);\r\n for(let i = arr.length-1; i > 0; i--){\r\n // The 0th element of a heap is the largest so move it to the top.\r\n [arr[0],arr[i]] = [arr[i],arr[0]];\r\n // The 0th element is no longer the largest; restore the heap property\r\n siftDown(arr,comp,0);\r\n }\r\n}", "function heapSort(arr,n){\n for(var i=Math.floor(n/2);i>=0;i--){\n heapify(arr,n,i);\n }\n for(var i=n-1;i>=0;i--){\n swap(arr,0,i);\n heapify(arr,i,0);\n }\n}", "function heapSort(array) {\n \n let heap = new MaxHeap();\n array.forEach(num => heap.insert(num)); // 1) build heap O(N) Amortized Time\n\n let sorted = [];\n while (heap.array.length > 1) { // 2) continously delete max and push deleted to sorted arr until heap empty\n sorted.push(heap.deleteMax()); // deletion takes log(N)\n }\n \n return sorted;\n}", "function heapifyStandart(currentIndex, heapSize ,arr){\n\n var largestElement = currentIndex\n var leftIndex = 2 * currentIndex + 1\n var rightIndex = 2 * currentIndex + 2\n\n if (leftIndex < heapSize && arr[currentIndex] < arr[leftIndex]){\n largestElement = leftIndex\n }\n \n if (rightIndex < heapSize && arr[largestElement] < arr[rightIndex]){\n largestElement = rightIndex\n }\n\n if (largestElement != currentIndex){\n swapArrayElement(currentIndex, largestElement, arr)\n heapifyStandart(largestElement, heapSize, arr)\n }\n}", "function heapSort(array){\n let heapify = new MinHeap;\n let sortedArray = [];\n let length = array.length;\n\n for(let i = 0; i < length; i++){\n heapify.add(array.pop());\n }\n\n for(let j = 0; j < length; j++){\n sortedArray.push(heapify.extract());\n }\n\n return sortedArray;\n}", "function _adjustHeap (arr) {\n var i = parseInt(arr.length / 2) - 1;\n\n while (i >= 0) {\n if (arr[i] < arr[2 * i + 1] || arr[i] < arr[2 * i + 2]) {\n if (arr[2 * i + 1] < arr[2 * i + 2]) {\n arr[2 * i + 2] = [arr[i], arr[i] = arr[2 * i + 2]][0];\n } else {\n arr[2 * i + 1] = [arr[i], arr[i] = arr[2 * i + 1]][0];\n }\n _adjustHeap(arr);\n }\n i--;\n };\n }", "function heapSort(inputArr){\n var heap = new Heap;\n for(i=0; i<inputArr.length; i++){\n heap.add(inputArr[i])\n }\n var outputArr = []\n for(i=0; i<inputArr.length; i++){\n outputArr.push(heap.remove())\n }\n console.log(outputArr)\n return outputArr\n}", "heapSort(start, length) {\n this.heapify(start, length);\n\n for (let i = length - start; i > 1; i--) {\n this.Writes.swap(start, start + i - 1);\n this.siftDown(1, i - 1, start);\n }\n\n // if(!isMax) {\n // this.Writes.reversal(arr, start, start + length - 1, 1, true, false);\n // }\n}", "function heapify(arr,comp){\r\n // arr[n/2-1:n-1] already satisfies the heap property because they are the leaves.\r\n for(let i = Math.floor((arr.length-2)/2); i >= 0; i--){\r\n // Restore the heap property for i\r\n siftDown(arr, comp, i);\r\n }\r\n // Now that the heap property is satisfied for all i from 0 to n-1, the array is a heap\r\n}", "function heapify(arr,n,i){\n var largest,l,r;\n largest = i;\n l = 2*i+1;\n r = 2*i+2;\n\n if(l<n && arr[l]>arr[largest]){\n largest = l;\n }\n if(r<n && arr[r]>arr[largest]){\n largest = r;\n }\n if(largest!=i){\n swap(arr,i,largest);\n heapify(arr,n,largest);\n }\n\n}", "function heapify(currentIndex, arr){\n\n if (isHavingChildrenLeft(currentIndex, arr)) {\n let parent = arr[currentIndex]\n\n if (isHavingChildrenRight(currentIndex, arr)){\n let maxChildren = Math.max(arr[currentIndex * 2 + 1], arr[currentIndex * 2 + 2])\n if (parent < maxChildren){\n let maxChilrenIndex = maxChildren == arr[currentIndex * 2 + 1] ? currentIndex * 2 + 1 : currentIndex * 2 + 2 \n swapArrayElement(currentIndex, maxChilrenIndex, arr)\n heapify(maxChilrenIndex, arr)\n }\n }else {\n if (parent < arr[currentIndex * 2 + 1]){\n swapArrayElement(currentIndex, currentIndex * 2 + 1, arr)\n heapify(currentIndex * 2 + 1, arr)\n }\n }\n }else {\n console.log(\"skipping index %d\", currentIndex)\n }\n}", "heapify() {\n\t\t// last index is one less than the size\n\t\tlet index = this.size() - 1;\n\n\t\t/*\n Property of ith element in binary heap - \n left child is at = (2*i)th position\n right child is at = (2*i+1)th position\n parent is at = floor(i/2)th position\n */\n\n\t\t// converting entire array into heap from behind to front\n\t\t// just like heapify function to create it MAX HEAP\n\t\twhile (index > 0) {\n\t\t\t// pull out element from the array and find parent element\n\t\t\tlet element = this.heap[index],\n\t\t\t\tparentIndex = Math.floor((index - 1) / 2),\n\t\t\t\tparent = this.heap[parentIndex];\n\n\t\t\t// if parent is greater or equal, its already a heap hence break\n\t\t\tif (parent[0] >= element[0]) break;\n\t\t\t// else swap the values as we're creating a max heap\n\t\t\tthis.heap[index] = parent;\n\t\t\tthis.heap[parentIndex] = element;\n\t\t\tindex = parentIndex;\n\t\t}\n\t}", "function heapify(array, size, i) {\n let max = i // initialize max as root\n let left = 2 * i + 1\n let right = 2 * i + 2\n \n // if left child is larger than root\n if (left < size && array[left] > array[max])\n max = left\n \n // if right child is larger than max\n if (right < size && array[right] > array[max])\n max = right\n \n // if max is not root\n if (max != i) {\n // swap\n let temp = array[i]\n array[i] = array[max]\n array[max] = temp\n \n // recursively heapify the affected sub-tree\n heapify(array, size, max)\n }\n }", "heapifyDown(){\n let idx = 0,\n element = this.values[idx],\n swap,\n leftChildIdx,\n rightChildIdx,\n leftChild,\n rightChild;\n while (true){\n swap = null;\n leftChildIdx = (2 * idx) + 1;\n rightChildIdx = (2 * idx) + 2;\n leftChild = leftChildIdx < this.values.length ? this.values[leftChildIdx] : null;\n rightChild = rightChildIdx < this.values.length ? this.values[rightChildIdx] : null;\n if (leftChild <= rightChild && leftChild < element && leftChild !== null){\n swap = leftChildIdx\n }\n if (leftChild >= rightChild && rightChild < element && rightChild !== null){\n swap = rightChildIdx;\n }\n if (swap === null) break;\n this.values[idx] = this.values[swap];\n this.values[swap] = element;\n idx = swap; \n } \n }", "function maxHeapify(arr){\n\n}", "function minHeap(arr){\r\n\tfor(var i=Math.floor(arr.length/2); i >= 0; i--){\r\n\t\tminHeapafiy(arr, i)\r\n\t}\r\n\treturn arr\r\n}", "function heap_root(input, i) { \n var left = 2 * i + 1; \n var right = 2 * i + 2; \n var max = i; \n \n if (left < array_length && input[left] > input[max]) { \n max = left; \n } \n \n if (right < array_length && input[right] > input[max]) { \n max = right; \n } \n \n if (max != i) { \n swap(input, i, max); \n heap_root(input, max); \n } \n}", "function heapify (heap) {\n // Get the parent idx of the last node\n var start = iparent(heap.arr.length - 1)\n while (start >= 0) {\n siftDown(start, heap)\n start -= 1\n }\n return heap\n}", "function buildHeap(arr, type) {\n // gets the last index\n var lastIndex = arr.length - 1;\n // While the last index is greater than 0\n while (lastIndex > 0) {\n // get the parent index\n var parentIndex = Math.floor((lastIndex - 1) / 2);\n // get the items inside the parent\n // and the last index \n var lastItem = arr[lastIndex];\n var parentItem = arr[parentIndex];\n\n if (type === 'maxHeap') {\n // checks to see if the lastItem is greater\n // than the parentItem if so then do a swap\n if (lastItem > parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n else if (type === 'minHeap') {\n // checks to see if the lastItem is less\n // than the parentItem if so then do a swap\n if (lastItem < parentItem) {\n // replaces item at parentIndex with\n // last item and do the same for the\n // lastIndex\n arr[parentIndex] = lastItem;\n arr[lastIndex] = parentItem;\n\n // Keeps track of the lastItem that was\n // inserted by changing the lastIndex \n // to be the parentIndex which is \n // currently where the lastItem is located\n lastIndex = parentIndex;\n }\n else {\n break;\n }\n }\n\n }\n }", "buildHeap(array) {\n const firstParentIdx = Math.floor((array.length - 2) / 2);\n for (let currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {\n this.siftDown(currentIdx, array.length - 1, array);\n }\n return array;\n }", "function maxHeapify(idx, hSize) {\n let largest;\n const left = (2 * idx) + 1;\n const right = (2 * idx) + 2;\n if (left < hSize && array[left] > array[idx]) {\n largest = left;\n } else {\n largest = idx;\n }\n if (right < hSize && array[right] > array[largest]) {\n largest = right;\n }\n if (largest !== idx) {\n const temp = array[idx];\n array[idx] = array[largest];\n array[largest] = temp;\n maxHeapify(largest, hSize);\n }\n}", "async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }", "siftDown(currentIdx, endIdx, heap) {\n // Get childOne index\n\t\t// While not at the end of heap tree or leaf of heap tree\n\t\t// \t\tGet childTwo index\n\t\t// \t\tif there is a childTwo and childTwoValue < childOneValue\n\t\t// \t\t\tvalue to swap is childTwoValue\n\t\t// \t\telse\n\t\t/// \t\tvalue to swap is childOneValue\n\t\t// \t\tif valueToSwap < value at currentIdx\n\t\t// \t\t\tswap two value\n\t\t// \t\t\tupdate currentIdx to be index of valueToSwap\n\t\t// \t\t\tre-calculate childOne index\n\t\t// \t\telse \n\t\t// \t\t\tno swap needed\n let childOneIdx = currentIdx * 2 + 1;\n while (childOneIdx <= endIdx) {\n const childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1;\n let idxToSwap; \n if (childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]) {\n idxToSwap = childTwoIdx;\n } else {\n idxToSwap = childOneIdx;\n }\n\n if (heap[idxToSwap] < heap[currentIdx]) {\n this.swap(idxToSwap, currentIdx, heap);\n currentIdx = idxToSwap;\n childOneIdx = currentIdx * 2 + 1;\n } else {\n return;\n }\n }\n }", "function insert_max_heap(A, no, value) {\n A[no] = value //Insert , a new element will be added always at last \n const n = no\n let i = n\n\n //apply hepify method till we reach root (i=1)\n while (i >= 1) {\n const parent = Math.floor((i - 1) / 2)\n if (A[parent] < A[i]) {\n swap(A, parent, i)\n i = parent\n } else {\n i = parent\n //return ;\n }\n }\n}", "function heapify(A, idx, max) {\n var largest = idx,\n left = 2 * idx + 1,\n right = 2 * idx + 2;\n\n if (left < max && A[left] > A[idx]) {\n largest = left;\n }\n if (right < max && A[right] > A[largest]) {\n largest = right;\n }\n if (largest !== idx) {\n swap(A, idx, largest);\n heapify(A, largest, max);\n }\n}", "async function heapSort() {\n // To heapify subtree rooted at index i. \n // n is size of heap \n async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }\n\n // main function to do heap sort \n async function heapSortAux(array) { \n const len = array.length;\n // Build heap (rearrange array) \n for (let i = Math.floor(len / 2) - 1; i >= 0; i--) { \n await heapify(array, len, i); \n }\n \n // One by one extract an element from heap \n for (let i = len-1; i > 0; i--) { \n array[0].style.backgroundColor = bar_colours.selectedColour2;\n array[i].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n // Move current root to end \n await swap(array, 0, i); \n array[i].style.backgroundColor = bar_colours.doneColour;\n array[0].style.backgroundColor = bar_colours.initColour;\n\n \n \n // call max heapify on the reduced heap \n await heapify(array, i, 0); \n } \n }\n\n if (delay && typeof delay !== \"number\") {\n alert(\"sort: First argument must be a typeof Number\");\n return;\n }\n \n blocks = htmlElementToArray(\".block\");\n \n await heapSortAux(blocks);\n\n blocks.forEach((item, index) => {\n blocks[index].style.transition = \"background-color 0.7s\";\n blocks[index].style.backgroundColor = bar_colours.doneColour;\n })\n}", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "function heap_root(input, i) {\n var left = 2 * i + 1;\n var right = 2 * i + 2;\n var max = i;\n\n if (left < array_length && input[left] > input[max]) {\n max = left;\n }\n\n if (right < array_length && input[right] > input[max]) {\n max = right;\n }\n\n if (max != i) {\n swap(input, i, max);\n heap_root(input, max);\n }\n}", "function heapreheapify() {\n\n var node = this.size; // set the size to heap\n var pn = Math.floor(node/2); // use math floor to set last parent node to pn = parent node\n\n var i = pn; // set new varibale and get value pn.\n while(i >= 1)\n {\n var key = i;\n var v = this.h[key];\n var v2 = this.h_item[key];\n var heap = false; // here intitalize heap with boolean value false\n\n for (var j = 2 * key; !heap && 2 * key <= node;)\n {\n if (j < node)\n {\n if (this.h[j] < this.h[j + 1]) {\n j += 1;\n } // end the inner if\n } // end the outer if\n\n\n if (v >= this.h[j])\n {\n heap = true;\n } // end if\n else\n {\n this.h_item[key] = this.h_item[j];\n this.h[key] = this.h[j];\n key = j;\n } // end wlse\n\n this.h[key] = v;\n this.h_item[key] = v2;\n }\n i = i-1; // here decreese the number in each iteration\n } // end while\n}", "function heapify(arr, length, i) {\n let largest = i;\n let left = i * 2 + 1;\n let right = left + 1;\n\n if (left < length && arr[left] > arr[largest]) {\n largest = left;\n }\n if (right < length && arr[right] > arr[largest]) {\n largest = right;\n }\n if (largest != i) {\n [arr[i], arr[largest]] = [arr[largest], arr[i]];\n heapify(arr, length, largest);\n }\n\n return arr;\n}", "function insert(maxHeap, value) {\n let currentIndex = maxHeap.length;\n let parent = Math.floor((currentIndex - 1) / 2);\n maxHeap.push(value);\n while (maxHeap[currentIndex] > maxHeap[parent]) {\n let temp = maxHeap[parent];\n maxHeap[parent] = maxHeap[currentIndex];\n maxHeap[currentIndex] = temp;\n currentIndex = parent;\n parent = Math.floor((currentIndex - 1) / 2);\n }\n return maxHeap;\n}", "function maxHeap(array, n, i) {\n let largest = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if (left < n && array[left] > array[largest]) {\n largest = left;\n }\n\n // If right child is larger than largest so far\n if (right < n && array[right] > array[largest]) {\n largest = right;\n }\n\n // If largest is not root\n if (largest != i) {\n let swap = array[i];\n array[i] = array[largest];\n array[largest] = swap;\n\n // Recursively heapify the affected sub-tree\n maxHeap(array, n, largest);\n }\n}", "function fun(){\n alert(\"Answer is \" + heapSort([3,0,10,8,1,5,4],7));\n}", "extractMax(){\n // bubble down\n // swap first and last element.\n // then pop\n [this.values[0],this.values[this.values.length-1]] = [this.values[this.values.length-1], this.values[0]]\n // console.log(element + ' removed from the heap');\n this.values.pop();\n let index = 0;\n while(true){\n // compare with both the children and swap with the larger one.\n let leftParent = 2 * index + 1;\n let rightParent = 2 * index + 2;\n if(this.values[index] < this.values[leftParent] || this.values[index] < this.values[rightParent]){\n if(this.values[leftParent] > this.values[rightParent]){\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent;\n\n }\n else if(this.values[rightParent] > this.values[leftParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent;\n }\n else {\n if(this.values[rightParent]){\n [this.values[index], this.values[rightParent]] = [this.values[rightParent], this.values[index]]\n index = rightParent\n }\n else {\n [this.values[index], this.values[leftParent]] = [this.values[leftParent], this.values[index]]\n index = leftParent\n }\n \n };\n }\n else return;\n }\n }", "function minheap_extract(heap) \n{\n var PrintE;\n PrintE = heap[0];\n heap[0] = heap[heap.length - 1];\n\n var a,large;\n var temp = heap.pop();\n for (a=0;a<heap.length;a=large)\n {\n if (2*a+2>heap.length)\n {break;}\n if (heap[2*a+1] > heap[2*a+2]) // use to swap those two numbers\n {\n if (heap[a]>heap[2*a+2])\n {\n temp = heap [a];\n heap[a] = heap[2*a+2];\n heap[2*a+2] = temp; \n large = 2*a+2; \n }\n else\n {break;}\n }\n else\n {\n if (heap[a]>heap[2*a+1])\n {\n temp = heap [2*a+1];\n heap[2*a+1] = heap[a];\n heap[a] = temp; \n large = 2*a+1;\n }\n else\n {break;}\n }\n }\n return PrintE;\n}", "maxHeapify(arr, n, i) {\r\n\t\tlet largest = i;\r\n\t\tlet leftIndex = 2 * i + 1;\r\n\t\tlet rightIndex = 2 * i + 2;\r\n\r\n\t\tif (leftIndex < n && arr[leftIndex] > arr[largest]) {\r\n\t\t\tlargest = leftIndex;\r\n\t\t}\r\n\t\tif (rightIndex < n && arr[rightIndex] > arr[largest]) {\r\n\t\t\tlargest = rightIndex;\r\n\t\t}\r\n\t\tif (largest != i) {\r\n\t\t\tlet temp = arr[i];\r\n\t\t\tarr[i] = arr[largest];\r\n\t\t\tarr[largest] = temp;\r\n\t\t\tthis.maxHeapify(arr, n, largest);\r\n\t\t}\r\n\t}", "function maxHeapify(arr , n , i)\n\t{\n\t\n\t\t// Find largest of node and its children\n\t\tif (i >= n) {\n\t\t\treturn;\n\t\t}\n\t\tvar l = i * 2 + 1;\n\t\tvar r = i * 2 + 2;\n\t\tvar max;\n\t\tif (l < n && arr[l] > arr[i]) {\n\t\t\tmax = l;\n\t\t} else\n\t\t\tmax = i;\n\t\tif (r < n && arr[r] > arr[max]) {\n\t\t\tmax = r;\n\t\t}\n\n\t\t// Put maximum value at root and\n\t\t// recur for the child with the\n\t\t// maximum value\n\t\tif (max != i) {\n\t\t\tvar temp = arr[max];\n\t\t\tarr[max] = arr[i];\n\t\t\tarr[i] = temp;\n\t\t\tmaxHeapify(arr, n, max);\n\t\t}\n\t}", "remove() {\n if (this.heap.length < 2) {\n return this.heap.pop(); //easy\n }\n\n const removed = this.heap[0]; // save to return later\n this.heap[0] = this.heap.pop(); // replace with last el\n\n let currentIdx = 0;\n let [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n let currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n // right if heap[right].priority >= heap[left].priority, else left\n // index of max(left.priority, right.priority)\n\n while (\n this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority\n ) {\n let currentNode = this.heap[currentIdx];\n let currentChildNode = this.heap[currentChildIdx];\n\n // swap parent & max child\n\n this.heap[currentChildIdx] = currentNode;\n this.heap[currentIdx] = currentChildNode;\n\n\n // update pointers\n currentIdx = currentChildIdx;\n [left, right] = [currentIdx * 2 + 1, currentIdx * 2 + 2];\n currentChildIdx = (\n this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left\n );\n }\n\n return removed;\n }", "function buildMaxHeap() {\n for (let i = Math.floor(array.length / 2) - 1; i >= 0; i--) {\n maxHeapify(i, array.length);\n }\n}", "function MaxHeap(array){\r\n Heap.call(this, array);\r\n \r\n // Build-max-heap method: produces a max-heap from an unordered input array\r\n // The elements in the subarray A[(floor(n/2)+1) .. n] are all leaves of the tree, and so\r\n // start doing Float-down from the top non-leave element ( floor(A.length/2) ) to the bottom ( A[i] )\r\n for (var i = Math.floor( this.heapSize / 2 ); i>0; i--){\r\n this.floatDownElementOfIndex(i)\r\n }\r\n}", "function minheap_insert(heap, new_element) \n{\n \n var adj,temp;\n heap.push(new_element);\n for (adj=heap.length-1;adj>0;adj=Math.floor((adj-1)/2))\n {\n if (new_element < heap[Math.floor((adj-1)/2)]) // use to swap those two numbers\n {\n temp = new_element;\n heap[adj] = heap[Math.floor((adj-1)/2)];\n heap[Math.floor((adj-1)/2)] = temp; \n }\n }\n return;\n}", "function buildHeap(A) {\n var n = A.length;\n for (var i = n/2 - 1; i >= 0; i--) {\n heapify(A, i, n);\n }\n}", "heapify(/*index*/ i) {\n let l = this.left(i);\n let r = this.right(i);\n let biggest = i;\n if (l < this.heap_size && this.harr[i].element.compareByMulKeys(this.harr[l].element, this.compareValues) == -1)\n biggest = l;\n if (r < this.heap_size && this.harr[biggest].element.compareByMulKeys(this.harr[r].element, this.compareValues) == -1)\n biggest = r;\n if (biggest != i) {\n this.swap(this.harr, i, biggest);\n this.heapify(biggest);\n }\n }", "heapifyDown(customStartIndex = 0) {\n // Compare the parent element to its children and swap parent with the appropriate\n // child (smallest child for MinHeap, largest child for MaxHeap).\n // Do the same for next children after swap.\n let currentIndex = customStartIndex;\n let nextIndex = null;\n\n while (this.hasLeftChild(currentIndex)) {\n if (\n this.hasRightChild(currentIndex) &&\n this.rightChild(currentIndex) <= this.leftChild(currentIndex)\n ) {\n nextIndex = this.getRightChildIndex(currentIndex);\n } else {\n nextIndex = this.getLeftChildIndex(currentIndex);\n }\n\n if (this.heapContainer[currentIndex] <= this.heapContainer[nextIndex]) {\n break;\n }\n\n this.swap(currentIndex, nextIndex);\n currentIndex = nextIndex;\n }\n }", "function Heap(type) {\n var heapBuf = utils.expandoBuffer(Int32Array),\n indexBuf = utils.expandoBuffer(Int32Array),\n heavierThan = type == 'max' ? lessThan : greaterThan,\n itemsInHeap = 0,\n dataArr,\n heapArr,\n indexArr;\n\n this.init = function(values) {\n var i;\n dataArr = values;\n itemsInHeap = values.length;\n heapArr = heapBuf(itemsInHeap);\n indexArr = indexBuf(itemsInHeap);\n for (i=0; i<itemsInHeap; i++) {\n insertValue(i, i);\n }\n // place non-leaf items\n for (i=(itemsInHeap-2) >> 1; i >= 0; i--) {\n downHeap(i);\n }\n };\n\n this.size = function() {\n return itemsInHeap;\n };\n\n // Update a single value and re-heap\n this.updateValue = function(valIdx, val) {\n var heapIdx = indexArr[valIdx];\n dataArr[valIdx] = val;\n if (!(heapIdx >= 0 && heapIdx < itemsInHeap)) {\n error(\"Out-of-range heap index.\");\n }\n downHeap(upHeap(heapIdx));\n };\n\n this.popValue = function() {\n return dataArr[this.pop()];\n };\n\n this.getValue = function(idx) {\n return dataArr[idx];\n };\n\n this.peek = function() {\n return heapArr[0];\n };\n\n this.peekValue = function() {\n return dataArr[heapArr[0]];\n };\n\n // Return the idx of the lowest-value item in the heap\n this.pop = function() {\n var popIdx;\n if (itemsInHeap <= 0) {\n error(\"Tried to pop from an empty heap.\");\n }\n popIdx = heapArr[0];\n insertValue(0, heapArr[--itemsInHeap]); // move last item in heap into root position\n downHeap(0);\n return popIdx;\n };\n\n function upHeap(idx) {\n var parentIdx;\n // Move item up in the heap until it's at the top or is not lighter than its parent\n while (idx > 0) {\n parentIdx = (idx - 1) >> 1;\n if (heavierThan(idx, parentIdx)) {\n break;\n }\n swapItems(idx, parentIdx);\n idx = parentIdx;\n }\n return idx;\n }\n\n // Swap item at @idx with any lighter children\n function downHeap(idx) {\n var minIdx = compareDown(idx);\n\n while (minIdx > idx) {\n swapItems(idx, minIdx);\n idx = minIdx; // descend in the heap\n minIdx = compareDown(idx);\n }\n }\n\n function swapItems(a, b) {\n var i = heapArr[a];\n insertValue(a, heapArr[b]);\n insertValue(b, i);\n }\n\n // Associate a heap idx with the index of a value in data arr\n function insertValue(heapIdx, valId) {\n indexArr[valId] = heapIdx;\n heapArr[heapIdx] = valId;\n }\n\n // comparator for Visvalingam min heap\n // @a, @b: Indexes in @heapArr\n function greaterThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b],\n val1 = dataArr[idx1],\n val2 = dataArr[idx2];\n // If values are equal, compare array indexes.\n // This is not a requirement of the Visvalingam algorithm,\n // but it generates output that matches Mahes Visvalingam's\n // reference implementation.\n // See https://hydra.hull.ac.uk/assets/hull:10874/content\n return (val1 > val2 || val1 === val2 && idx1 > idx2);\n }\n\n // comparator for max heap\n function lessThan(a, b) {\n var idx1 = heapArr[a],\n idx2 = heapArr[b];\n return dataArr[idx1] < dataArr[idx2];\n }\n\n function compareDown(idx) {\n var a = 2 * idx + 1,\n b = a + 1,\n n = itemsInHeap;\n if (a < n && heavierThan(idx, a)) {\n idx = a;\n }\n if (b < n && heavierThan(idx, b)) {\n idx = b;\n }\n return idx;\n }\n }", "function sort(A) {\n buildHeap(A);\n for (var i = A.length -1; i > 0; i--) {\n swap(A, 0, i);\n heapify(A, 0, i);\n }\n}", "function maxHeapBuild(arr) {\n if (arr.length <= 1) return;\n createHeap(arr, arr.length);\n return arr;\n}", "function MinHeap() {\n\n /**\n * Insert an item into the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} x\n */\n this.insert = function(x) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:)\n *\n * @return{number}\n */\n this.peek = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Remove and return the smallest value in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.pop = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the size of the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{number}\n */\n this.size = function() {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Convert the heap data into a string\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @return{string}\n */\n MinHeap.prototype.toString = function() {\n // INSERT YOUR CODE HERE\n }\n\n /*\n * The following are some optional helper methods. These are not required\n * but may make your life easier\n */\n\n /**\n * Get the index of the parent node of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var parent = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Get the index of the left child of a given index\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @return{number}\n */\n var leftChild = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Swap the values at 2 indices in our heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n * @param{number} j\n */\n var swap = function(i, j) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble up the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleUp = function(i) {\n // INSERT YOUR CODE HERE\n }\n\n /**\n * Starting at index i, bubble down the value until it is at the correct\n * position in the heap\n *\n * Time Complexity:\n * Space Complexity:\n *\n * @param{number} i\n */\n var bubbleDown = function(i) {\n // INSERT YOUR CODE HERE\n }\n}", "function heapDown(i) {\n var w = heapWeight(i)\n while(true) {\n var tw = w\n var left = 2*i + 1\n var right = 2*(i + 1)\n var next = i\n if(left < heapCount) {\n var lw = heapWeight(left)\n if(lw < tw) {\n next = left\n tw = lw\n }\n }\n if(right < heapCount) {\n var rw = heapWeight(right)\n if(rw < tw) {\n next = right\n }\n }\n if(next === i) {\n return i\n }\n heapSwap(i, next)\n i = next \n }\n }", "function maxHeapify(arr, length, parent) {\n var largest = parent;\n var leftChild = 2 * parent + 1;\n var rightChild = 2 * parent + 2;\n\n if (leftChild < length && arr[leftChild] > arr[largest]) {\n largest = leftChild;\n }\n\n if (rightChild < length && arr[rightChild] > arr[largest]) {\n largest = rightChild;\n }\n\n if (largest != parent) {\n var temp = arr[largest];\n arr[largest] = arr[parent];\n arr[parent] = temp;\n\n maxHeapify(arr, length, largest);\n }\n}", "function heapify(array, size, i, animations)\n{\n let root = i;\n let left = 2 * i + 1;\n let right = 2 * i + 2;\n if(left < size && array[left] > array[root])\n {\n animations.push([root, left, false]);\n animations.push([root, left, false]);\n root = left;\n }\n if(right < size && array[right] > array[root])\n {\n animations.push([root, right, false]);\n animations.push([root, right, false]);\n root = right;\n }\n //Root has changed because i was not the root\n if(root != i)\n {\n animations.push([root, array[i], true]);\n animations.push([i, array[root], true]);\n //If root is not i, then swap the values, call heapify recursively\n swap(array, root, i);\n heapify(array, size, root, animations);\n }\n}", "heapDown(index) {\n const [leftIndex, rightIndex] = this.children(index);\n \n if (!leftIndex && !rightIndex) return;\n\n let min;\n rightIndex ? min = rightIndex : min = leftIndex;\n if ((leftIndex && rightIndex) &&\n this.store[leftIndex].key < this.store[rightIndex].key) {\n min = leftIndex;\n }\n\n if (this.store[index].key > this.store[min].key) {\n this.swap(index, min);\n this.heapDown(min);\n }\n }", "function heapify(n, i) {\n let largest = i; // Initialize largest as root\n // Index of left and right child of root\n const left = 2*i + 1;\n const right = 2*i + 2;\n \n // See if left child of root exists and is greater than root\n if (left < n && arr[left] > arr[largest]) {\n largest = left;\n }\n \n // See if right child of root exists and is greater than current largest\n if (right < n && arr[right] > arr[largest]) {\n largest = right;\n }\n \n // Change root if needed\n if (largest !== i) {\n swap(i, largest);\n // Heapify down this subtree\n heapify(n, largest);\n }\n }", "function minheap_extract(heap) {\n swap(heap,0,heap.length - 1);\n var to_pop = heap.pop();\n var parent = 0;\n var child = parent * 2 + 1;\n while(child < heap.length){\n if(child + 1 < heap.length && heap[child] > heap[child + 1]){\n child = child + 1;\n }\n if(heap[child] < heap[parent]){\n swap(heap,child,parent);\n parent = child;\n child = parent * 2 + 1; \n }\n else{\n break;\n }\n }\n return to_pop;\n // STENCIL: implement your min binary heap extract operation\n}", "maxHeap(index) {\n var left = this.left(index);\n var right = this.right(index);\n var largest = index;\n if (left < this.heapSize && this.array[left] > this.array[index]) {\n largest = left;\n }\n if (right < this.heapSize && this.array[right] > this.array[largest]) {\n largest = right;\n }\n if (largest != index) {\n this.swap(this.array, index, largest);\n this.maxHeap(largest);\n }\n }", "static maxHeapify(a, i) {\n let left = Heap.left(i);\n let right = Heap.right(i);\n\n // Find largest node between current, left and right\n let largest;\n if (left < a.heap_size && a[left] > a[i])\n largest = left;\n else\n largest = i;\n\n if (right < a.heap_size && a[right] > a[largest])\n largest = right;\n\n // Move current element to 'largest' position, and\n // continue until the element is positioned correctly\n if (largest != i) {\n let temp = a[i];\n a[i] = a[largest];\n a[largest] = temp;\n\n Heap.maxHeapify(a, largest);\n }\n }", "async function MaxHeapify( i, heapSize)\n{\n\n let hasLeft = (2 * i + 1 < heapSize) ? true : false;\n let hasRight = (2 * i + 2 < heapSize) ? true : false;\n let l, r;\n let largest = i;\n if (hasLeft)\n l = arr[2 * i + 1].offsetHeight;\n if (hasRight)\n r = arr[2 * i + 2].offsetHeight;\n if (hasLeft && arr[i].offsetHeight < l)\n {\n largest = 2 * i + 1;\n }\n if (hasRight && arr[largest].offsetHeight < r)\n {\n largest = 2 * i + 2;\n }\n if (largest != i)\n {\n arr[i].style.backgroundColor='white';\n arr[largest].style.backgroundColor='green';\n await timer(delay);\n await swap(i, largest);\n arr[i].style.backgroundColor='red';\n arr[largest].style.backgroundColor='red';\n await MaxHeapify(largest, heapSize);\n }\n}", "deleteMax() {\n // recall that we have an empty position at the very front of the array, \n // so an array length of 2 means there is only 1 item in the heap\n\n if (this.array.length === 1) return null;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// edge case- if no nodes in tree, exit\n\n if (this.array.length === 2) return this.array.pop();\t\t\t\t\t\t\t\t\t\t\t\t// edge case- if only 1 node in heap, just remove it (2 bec. null doesnt count)\n\n let max = this.array[1];\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// save reference to root value (max)\n\n this.array[1] = this.array.pop();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // remove last val in array (farthest right node in tree), and update root value with it\n\n this.siftDown(1);\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// continuoully swap the new root toward the back of the array to maintain maxHeap property\n\n return max;\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// return max value\n }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function heapDown(i) {\n\t var w = heapWeight(i)\n\t while(true) {\n\t var tw = w\n\t var left = 2*i + 1\n\t var right = 2*(i + 1)\n\t var next = i\n\t if(left < heapCount) {\n\t var lw = heapWeight(left)\n\t if(lw < tw) {\n\t next = left\n\t tw = lw\n\t }\n\t }\n\t if(right < heapCount) {\n\t var rw = heapWeight(right)\n\t if(rw < tw) {\n\t next = right\n\t }\n\t }\n\t if(next === i) {\n\t return i\n\t }\n\t heapSwap(i, next)\n\t i = next \n\t }\n\t }", "function makeHeap(){\n\n //add a node to a heap and set it to current\n if(makeHeapStep == 1){\n heapAddNode();\n return;\n }else if(makeHeapStep == 2){ //Swim the node up if needed\n\n //We are at the start of the heap. No more swimming possible\n if(currentHeapPosition == 0){\n setNodeOneHeap();\n heapSwimStep = 1;\n \n \n return;\n }\n\n if(heapSwimStep == 1){ //set the parent Node\n heapSetParent();\n }else if(heapSwimStep == 2){ //compare to the parent Node\n if(orderArray[currentHeapPosition] > orderArray[heapParentIndex]){ //we must swap\n heapSwapWithParent();\n }else{ //do not swap. Node is now in the heap proper\n setToHeap();\n }\n \n heapSwimStep = 1;\n }\n }\n\n //sorting is now done\n if(heapSize == numNodes){\n doneMakingHeap = true;\n heapOldPosition = -1;\n addStep(\"The heap is now complete.\");\n }\n}", "siftUp(currentIdx, heap) {\n // Get parentNode index of node at currentIdx\n let parentIdx = Math.floor((currentIdx - 1) / 2);\n\n // While not at root index\n // Compare value at parentIdx and currentIdx\n // If currentNode < parentNode\n // Peform swap\n // re-calculate currentIdx and parentIdx \n while (currentIdx > 0 && heap[currentIdx] < heap[parentIdx]) {\n this.swap(currentIdx, parentIdx, heap);\n currentIdx = parentIdx;\n parentIdx = Math.floor((currentIdx - 1) / 2);\n }\n }", "async function heapify(array, n, i) {\n let largest = i; // Initialize largest as root \n const l = 2 * i + 1; // left = 2*i + 1 \n const r = 2 * i + 2; // right = 2*i + 2 \n \n // See if left child of root exists and is \n // greater than root \n if (l < n && getValue(array[l]) > getValue(array[largest])) { \n largest = l;\n }\n \n // See if right child of root exists and is \n // greater than root \n if (r < n && getValue(array[r]) > getValue(array[largest])) { \n largest = r;\n }\n \n // Change root, if needed \n if (largest != i) {\n array[i].style.backgroundColor = bar_colours.selectedColour2;\n array[largest].style.backgroundColor = bar_colours.selectedColour;\n await new Promise(resolve =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n await swap(array, i, largest); // swap\n array[i].style.backgroundColor = bar_colours.initColour;\n array[largest].style.backgroundColor = bar_colours.initColour;\n \n // Heapify the root. \n await heapify(array, n, largest);\n }\n }", "Dequeue() {\r\n if (this.heap.length == 0) return;\r\n const highestPriority = this.heap[0];\r\n const leastPriority = this.heap[this.heap.length - 1];\r\n //swap first and last priority\r\n this.heap[this.heap.length - 1] = highestPriority;\r\n this.heap[0] = leastPriority;\r\n this.heap.pop();\r\n let nodeIndex = 0; //sink down\r\n while (true) {\r\n const left = this.heap[2 * nodeIndex + 1];\r\n const right = this.heap[2 * nodeIndex + 2];\r\n const leastElement = this.heap[nodeIndex];\r\n if (\r\n right &&\r\n right.priority < left.priority &&\r\n right.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 2] = leastElement;\r\n this.heap[nodeIndex] = right;\r\n nodeIndex = 2 * nodeIndex + 2;\r\n } else if (\r\n left &&\r\n left.priority < right.priority &&\r\n left.priority < leastElement.priority\r\n ) {\r\n this.heap[2 * nodeIndex + 1] = leastElement;\r\n this.heap[nodeIndex] = left;\r\n nodeIndex = 2 * nodeIndex + 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n return highestPriority;\r\n }", "function minHeapify(heap, i) {\n if (heap.length < 1) return\n let left = 2 * i + 1\n let right = 2 * i + 2\n let smallest = i\n if (left < heap.length && heap[left] < heap[smallest]) {\n smallest = left\n }\n if (right < heap.length && heap[right] < heap[smallest]) {\n smallest = right\n }\n if (smallest !== i) {\n [heap[smallest], heap[i]] = swap(heap[smallest], heap[i])\n minHeapify(heap, smallest)\n }\n}", "function heap(a, lo, hi) {\n var n = hi - lo,\n i = (n >>> 1) + 1;\n while (--i > 0) sift(a, i, n, lo);\n return a;\n }", "function heap(a, lo, hi) {\n\t var n = hi - lo,\n\t i = (n >>> 1) + 1;\n\t while (--i > 0) sift(a, i, n, lo);\n\t return a;\n\t }", "function heapPerms(n, arr,set){\n\tif(n==1){\n\t\tset.push(Array.from(arr));\n\t}else{\n\t\tfor(var i=1;i<=n;i++){\n\t\t\theapPerms(n-1,arr,set);\n\t\t\tif(n%2){\n\t\t\t\tswap(arr,0,n-1);\n\t\t\t}else{\n\t\t\t\tswap(arr,i-1,n-1);\n\t\t\t}\n\t\t}\n\t}\n\treturn set;\n}", "function minheap_extract(heap) {\n var min = heap[0];\n heap[0] = heap.pop();\n var index = 0;\n while(true){\n var child1 = (index+1)*2;\n var child2 = child1 -1;\n var toSwap = null;\n if(heap[index] > heap[child1]){\n toSwap = child1;\n }\n if(heap[index] > heap[child2] &&\n (heap[child1] == null || (heap[child1] !== null && heap[child2] < heap[child1]))){\n toSwap = child2;\n }\n if(toSwap == null){\n break;\n }\n var temp = heap[toSwap];\n heap[toSwap] = heap[index];\n heap[index] = temp;\n index = toSwap;\n }\n return min;\n // STENCIL: implement your min binary heap extract operation\n}", "function insert(arr, num) {\n console.log('Heap')\n console.log(arr)\n console.log('inserting: '+num)\n arr.push(num)\n console.log(arr)\n\n var childPos = arr.length-1\n var parentPos = Math.floor((arr.length-1)/2)\n var child = arr[childPos]\n var parent = arr[parentPos]\n\n console.log('child: '+child)\n console.log('child position: '+childPos)\n console.log('parent: '+parent)\n console.log('parent position: '+parentPos)\n\n recurse()\n\n function recurse() {\n if (parent === undefined){return}\n if(child >= parent){\n return arr\n }\n console.log('Child is less than parent, swapping...')\n arr[childPos] = parent\n arr[parentPos] = child\n console.log('new array')\n console.log(arr)\n\n childPos = parentPos\n console.log('new child: '+child)\n console.log('new child position: '+childPos)\n\n parentPos = Math.floor((parentPos-1)/2)\n parent = arr[parentPos]\n console.log('new parent: '+parent)\n console.log('new parent position: '+parentPos)\n\n\n return recurse(child, parent)\n }\n}", "function heapPermutation(a, size, n, output)\n{\n if (size == 1){\n output.push(a.slice());\n return;\n }\n \n var temp, swap;\n for (var i=0; i<size; i++)\n {\n heapPermutation(a, size-1, n, output);\n \n // if size is odd, swap first and last\n // If size is even, swap ith and last\n swap = (size & 1) ? 0 : i;\n\n temp = a[swap];\n a[swap] = a[size-1];\n a[size-1] = temp;\n }\n}", "function bubbleSort(arr) {\n //shorten length of array by one index after one inner for loop is done.\n //by this process, can make sure new array is in ascending order. \n for (let j = arr.length; j > 0; j--) {\n //go through array from index 0\n //swap two elements if the first element is larger than second element.\n //after one loop, can make sure the maxium number will be the last index of array.\n for (let i = 0; i < j; i++) {\n let tmp;\n if (arr[i] > arr[i + 1]) {\n tmp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = tmp;\n }\n };\n }\n return arr;\n}", "function bubbleSort(arr) {\n //iterate through arr, usiing i to keep count of\n //how many values have been sorted\n for(var i = 0; i < arr.length; i++) {\n //iterate through arr finding the largest value\n //placing it at the end of non sorted portion of\n //the array\n for(var j = 0; j < (arr.length - 1 - i); j++) {\n //compare values and switch them if the greater index is a\n //smaller value\n if(arr[j] > arr[j + 1]) {\n //create temporary variable\n var temp = arr[j];\n //overwrite smaller index\n arr[j] = arr[j + 1];\n //overwrite previously moved index with temp variable\n arr[j + 1] = temp;\n }\n }\n }\n //return sorted array\n return arr;\n}", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "function minheap_insert(heap, new_element) {\n var length = heap.push(new_element);\n var child = length - 1;\n var parent = (child + child%2)/2 - 1;\n while(parent >= 0 && heap[child] < heap[parent]){\n swap(heap,parent,child);\n child = parent;\n parent = (child + child%2)/2 - 1;\n }\n // STENCIL: implement your min binary heap insert operation\n}", "heapifyToBottom(index) {\n let smallest = index;\n const child1 = index * 2 + 1;\n const child2 = index * 2 + 2;\n if (this.compare(child1, smallest) < 0) {\n smallest = child1;\n }\n if (this.compare(child2, smallest) < 0) {\n smallest = child2;\n }\n //swap with smaller child if either child is smaller than parent\n if (index !== smallest) {\n utility_1.default.swap(this._nodes, index, smallest);\n this.heapifyToBottom(smallest);\n }\n }", "bubble_down (p) {\n // var max_index = max_by(\n // [p, this.right_child(p), this.left_child(p)], // indices\n // index => this.queue[index] || -1 // scoring function\n // )\n\n // var max_index = p\n // var left_child_index = this.left_child(p)\n // var right_child_index = this.right_child(p)\n // if (this.queue[left_child_index] > this.queue[max_index]) {\n // max_index = left_child_index\n // }\n // if (this.queue[right_child_index] > this.queue[max_index]) {\n // max_index = right_child_index\n // }\n //\n // if (max_index !== p) {\n // this.swap(p, max_index)\n // this.bubble_down(max_index)\n // }\n\n\n // // latest and greatest\n var length = this.queue.length;\n var element = this.queue[p]\n\n while(true) {\n var child1N = this.left_child(p)\n var child2N = this.right_child(p)\n\n var swap = null\n if(child1N < length) {\n var child1 = this.queue[child1N]\n\n if (child1 > element)\n swap = child1N\n }\n\n if (child2N < length) {\n var child2 = this.queue[child2N]\n if(child2 > (swap === null ? element : this.queue[child1N]))\n swap = child2N\n }\n\n if (swap == null) {\n break;\n }\n\n this.queue[p] = this.queue[swap]\n this.queue[swap] = element\n p = swap\n }\n }", "async function heapify(arr,length,i){\n chosen.style.color=\"black\";\n chosen.innerHTML=`Turning the remaining array into max heap...`;\n let largest=i;\n let left=i*2+1;\n let right=left+1;\n let rightBar=document.querySelector(`.bar${right}`);\n let leftBar=document.querySelector(`.bar${left}`);\n let iBar=document.querySelector(`.bar${i}`);\n await sleep(speed);\n iBar.style.backgroundColor=\"#3500d3\";//selected\n if (left<length)\n leftBar.style.backgroundColor=\"#f64c72\";//checking\n if (right<length)\n rightBar.style.backgroundColor=\"#f64c72\";//checking\n if (left<length && arr[left]>arr[largest])\n largest=left;\n if (right<length && arr[right]>arr[largest])\n largest=right;\n if(largest!=i){\n let largestBar=document.querySelector(`.bar${largest}`);\n iBar=document.querySelector(`.bar${i}`);\n [arr[largest],arr[i]]=[arr[i],arr[largest]];\n [largestBar.style.height,iBar.style.height]=[iBar.style.height,largestBar.style.height];\n [largestBar.innerHTML,iBar.innerHTML]=[iBar.innerHTML,largestBar.innerHTML];\n await sleep(speed);\n iBar.style.backgroundColor=\"#17a2b8\";//original\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n\n await heapify(arr,length,largest);\n }\n iBar.style.backgroundColor=\"#17a2b8\";//original\n if (left<length)\n leftBar.style.backgroundColor=\"#17a2b8\";//original\n if (right<length)\n rightBar.style.backgroundColor=\"#17a2b8\";//original\n}", "function extractMin(heap) {\n if (heap.length < 1) return null\n // swap first and last element\n let temp = heap[0]\n heap[0] = heap[heap.length-1]\n heap[heap.length-1] = temp\n\n const result = heap.pop()\n minHeapify(heap, 0)\n return result\n}", "static buildMaxHeap(a) {\n a.heap_size = a.length;\n\n // Max-heapify the first n/2 elements as\n // they are tree nodes, and the remaining are\n // usually tree leaves\n let mid = parseInt(a.length / 2);\n for (let i = mid; i >= 0; i -= 1) {\n Heap.maxHeapify(a, i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapify() {\n if (this.size() < 2) return;\n for (let i = 1; i < this.size(); i++) {\n this.bubbleUp(i);\n }\n }", "heapifyUp(customStartIndex) {\n // Take the last element (last in array or the bottom left in a tree)\n // in the heap container and lift it up until it is in the correct\n // order with respect to its parent element.\n let currentIndex = customStartIndex || this.heapContainer.length - 1;\n\n while (\n this.hasParent(currentIndex) &&\n !(this.parent(currentIndex) <= this.heapContainer[currentIndex])\n ) {\n this.swap(currentIndex, this.getParentIndex(currentIndex));\n currentIndex = this.getParentIndex(currentIndex);\n }\n }", "function heapSwap(i,j) {\n var a = heap[i]\n var b = heap[j]\n heap[i] = b\n heap[j] = a\n index[a] = j\n index[b] = i\n }", "function minheap_insert(heap, new_element) {\n heap.push(new_element);\n var index = heap.length - 1;\n while(index > 0){\n var parent = Math.floor((index+1)/2)-1;\n if(heap[parent] > new_element){\n var temp = heap[parent];\n heap[parent] = new_element;\n heap[index] = temp;\n }\n index = parent;\n }\n // STENCIL: implement your min binary heap insert operation\n}", "function pq_insert(heap, new_element) {\n var eIntIdx = heap.length;\n var prntIdx = Math.floor((eIntIdx - 1 ) / 2);\n heap.push(new_element);\n var heaped = (eIntIdx <= 0) || (heap[prntIdx].priority <= heap[eIntIdx]).priority;\n\n while(!heaped){\n var tmp = heap[prntIdx];\n heap[prntIdx] = heap[eIntIdx];\n heap[eIntIdx] = tmp;\n\n eIntIdx = prntIdx;\n prntIdx = Math.floor((eIntIdx - 1)/2);\n heaped = (eIntIdx <= 0) ||(heap[prntIdx].priority <= heap[eIntIdx].priority);\n }\n // STENCIL: implement your min binary heap insert operation\n}", "minHeapify(arr, n, i) {\r\n\t\tlet smallest = i;\r\n\t\tlet leftIndex = 2 * i + 1;\r\n\t\tlet rightIndex = 2 * i + 2;\r\n\r\n\t\tif (leftIndex < n && arr[leftIndex] < arr[smallest]) {\r\n\t\t\tsmallest = leftIndex;\r\n\t\t}\r\n\t\tif (rightIndex < n && arr[rightIndex] < arr[smallest]) {\r\n\t\t\tsmallest = rightIndex;\r\n\t\t}\r\n\t\tif (smallest != i) {\r\n\t\t\tlet temp = arr[i];\r\n\t\t\tarr[i] = arr[smallest];\r\n\t\t\tarr[smallest] = temp;\r\n\t\t\tthis.minHeapify(arr, n, smallest);\r\n\t\t}\r\n\t}", "function MinHeap(array, comparator) {\n\n /**\n * Storage for heap. \n * @private\n */\n this.heap = array || new Array();\n\n /**\n * Default comparator used if an override is not provided.\n * @private\n */\n this.compare = comparator || function(item1, item2) {\n return item1 == item2 ? 0 : item1 < item2 ? -1 : 1;\n };\n\n /**\n * Retrieve the index of the left child of the node at index i.\n * @private\n */\n this.left = function(i) {\n return 2 * i + 1;\n };\n /**\n * Retrieve the index of the right child of the node at index i.\n * @private\n */\n this.right = function(i) {\n return 2 * i + 2;\n };\n /**\n * Retrieve the index of the parent of the node at index i.\n * @private\n */\n this.parent = function(i) {\n return Math.ceil(i / 2) - 1;\n };\n\n /**\n * Ensure that the contents of the heap don't violate the \n * constraint. \n * @private\n */\n this.heapify = function(i) {\n var lIdx = this.left(i);\n var rIdx = this.right(i);\n var smallest;\n if (lIdx < this.heap.length\n && this.compare(this.heap[lIdx], this.heap[i]) < 0) {\n smallest = lIdx;\n } else {\n smallest = i;\n }\n if (rIdx < this.heap.length\n && this.compare(this.heap[rIdx], this.heap[smallest]) < 0) {\n smallest = rIdx;\n }\n if (i != smallest) {\n var temp = this.heap[smallest];\n this.heap[smallest] = this.heap[i];\n this.heap[i] = temp;\n this.heapify(smallest);\n }\n };\n\n /**\n * Starting with the node at index i, move up the heap until parent value\n * is less than the node.\n * @private\n */\n this.siftUp = function(i) {\n var p = this.parent(i);\n if (p >= 0 && this.compare(this.heap[p], this.heap[i]) > 0) {\n var temp = this.heap[p];\n this.heap[p] = this.heap[i];\n this.heap[i] = temp;\n this.siftUp(p);\n }\n };\n\n /**\n * Heapify the contents of an array.\n * This function is called when an array is provided.\n * @private\n */\n this.heapifyArray = function() {\n // for loop starting from floor size/2 going up and heapify each.\n var i = Math.floor(this.heap.length / 2) - 1;\n for (; i >= 0; i--) {\n // jstestdriver.console.log(\"i: \", i);\n this.heapify(i);\n }\n };\n\n // If an initial array was provided, then heapify the array.\n if (array != null) {\n this.heapifyArray();\n }\n ;\n}", "function largestNum(arr, k) {\n\tif (!arr && !arr.length && !k) return false;\n\n\tlet shunk = arr.slice(0, k); //first shunk\n\tlet heap = [];\n\tshunk.forEach(n => insertHeap(heap, n));\n\n\tfor (let i = k; i < arr.length; i++) {\n\t\tif (arr[i] >= heap[0]) {\n\t\t\tupdateHeap(heap, arr[i]);\n\t\t}\n\t}\n\n\treturn heap;\n}", "function heap(compareFunction, array = []) {\n const data = array;\n const heapSort = ()=>{data.sort(compareFunction)};\n const add = function (node) {\n data.push(node);\n heapSort();\n };\n\n const remove = function () {\n const node = data.shift();\n return node;\n };\n\n const empty = function () {\n return data.length === 0;\n };\n const updateItems = function () {\n heapSort();\n };\n return {\n data: data,\n add: add,\n remove: remove,\n empty: empty,\n update: updateItems,\n };\n}", "MinHeapify(index) {\n let left = this.left(index);\n let right = this.right(index);\n let smallest = index;\n if (left < this.size && this.data[left] < this.data[index]) smallest = left;\n if (right < this.size && this.data[right] < this.data[smallest])\n smallest = right;\n if (smallest != index) {\n let temp = this.data[index];\n this.data[index] = this.data[smallest];\n this.data[smallest] = temp;\n this.MinHeapify(smallest);\n }\n }", "function bubbleSort(arr){\n \n for(let i = arr.length; i>0; i--){\n //i-1 means that we want to shrink the i everytime when swapping j's\n for(let j =0; j< i-1; j ++){\n if(arr[j]> arr[j+1]){\n let temp = arr[j];\n arr[j]=arr[j+1];\n arr[j+1]=temp;\n }\n }\n }\n\n return arr;\n\n\n \n}", "heapifyToTop(index) {\n while (index > 0) {\n const parent = Math.floor((index - 1) / 2);\n if (this.compare(index, parent) >= 0) {\n break;\n }\n //swap with parent node while current node is smaller\n utility_1.default.swap(this._nodes, index, parent);\n index = parent;\n }\n }" ]
[ "0.87359804", "0.81219524", "0.80146706", "0.799659", "0.79832715", "0.795762", "0.794475", "0.7920434", "0.78950447", "0.7670186", "0.76403815", "0.7600905", "0.7582311", "0.7546947", "0.75359094", "0.74537456", "0.7446912", "0.7415225", "0.7366461", "0.7340616", "0.7324018", "0.73037857", "0.72422874", "0.723968", "0.7214504", "0.7172321", "0.71101797", "0.7098439", "0.70760566", "0.7074344", "0.70503265", "0.7047836", "0.7039445", "0.7039445", "0.703412", "0.7009479", "0.70091873", "0.7000445", "0.6997529", "0.6996262", "0.6993983", "0.69448113", "0.6911416", "0.6898319", "0.6878038", "0.6832696", "0.6825596", "0.6822449", "0.68124056", "0.6782924", "0.67772436", "0.6748188", "0.67457813", "0.67452025", "0.67421716", "0.67374414", "0.6730685", "0.67042136", "0.6702048", "0.66522205", "0.6641985", "0.65865105", "0.657703", "0.6548845", "0.6544563", "0.6544563", "0.65185964", "0.6464998", "0.64621663", "0.6461746", "0.6459889", "0.64556694", "0.6420782", "0.64169097", "0.6412096", "0.6402871", "0.6379131", "0.6363339", "0.6352588", "0.6345381", "0.6345381", "0.63341314", "0.6327951", "0.6326733", "0.6326289", "0.63222694", "0.63117725", "0.6309572", "0.6309572", "0.63044316", "0.62961733", "0.62959903", "0.6295982", "0.6269914", "0.6240106", "0.6237149", "0.6231322", "0.6219262", "0.61864614", "0.616873" ]
0.7308083
21
0 1 2 3 4 [ 0, 5, 1, 3, 2 ] => [ 0, 1, 2, 3, 5 ]
function heapSortV2(array) { for (let i = array.length - 1; i >= 0; i--) { // 1) loop through array, and convert it to maxHeap using heapify helper heapify(array, array.length, i); // array length not really used for this part } for (let endOfHeap = array.length - 1; endOfHeap >= 0; endOfHeap--) { // 2) loop from end of maxHeap to begin/left, and "delete" max val until heap region is "empty" [array[endOfHeap], array[0]] = [array[0], array[endOfHeap]]; // 3) swap the root of the heap with the last element of the heap, this shrinks the heap by 1 and grows the sorted array by 1 console.log(array); heapify(array, endOfHeap, 0); // 4) sift down the new root, but not past the end of the heap } return array; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function four(arr){\n for(var i = 0; i < arr.length; i+1){\n var temp = arr[i];\n arr[i] = arr[i+1];\n }\n return arr;\n}", "function number4(array){\n var newElements= array.pop()\n var newArr= array.splice(0,0,newElements)\n return array\n}", "function A(n,t){for(;t+1<n.length;t++)n[t]=n[t+1];n.pop()}", "function e(){return [0,0,0,1]}", "function a(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function e(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function x(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}", "function r(e,t){var n=i.length?i.pop():[],r=s.length?s.pop():[],a=o(e,t,n,r);return n.length=0,r.length=0,i.push(n),s.push(r),a}", "function i(n=D){return[n[0],n[1],n[2],n[3],n[4],n[5]]}", "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 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 a(e,t){var n=i.length?i.pop():[],a=o.length?o.pop():[],s=r(e,t,n,a);return n.length=0,a.length=0,i.push(n),o.push(a),s}", "function contiguousSeq(arr) {\n\n}", "function n(e,t){var n=o.length?o.pop():[],a=i.length?i.pop():[],u=r(e,t,n,a);return n.length=0,a.length=0,o.push(n),i.push(a),u}", "function e(t,n){for(;n+1<t.length;n++)t[n]=t[n+1];t.pop()}", "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 unite(arr1, arr2, arr3) {\n newArray = [];\n \n for (var i = 0; i < arguments.length; i++) {\n var arrLength = arguments[i];\n \n for (var j = 0; j < arrLength.length; j++) {\n var indexValue = arrLength[j];\n\n while (newArray.indexOf(indexValue) < 0) {\n newArray.push(indexValue);\n }\n }\n }\n \n return newArray;\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 swipePairs(arr) {\n return [arr[0], arr[1], arr[2], arr[3]] = [arr[1], arr[0], arr[3], arr[2]];\n}", "function test() {\n var arr = [];\n arr[0] = [1, 2, 3, 4, 5];\n arr[1] = [1, 2, 3, 4, 5];\n arr[2] = [1, 2, 3, 4, 5];\n arr[3] = [1, 2, 3, 4, 5];\n arr[4] = [1, 2, 3, 4, 5];\n arr[5] = [1, 2, 3, 4, 5];\n arr[6] = [1, 2, 3, 4, 5];\n arr[7] = [1, 2, 3, 4, 5];\n arr[8] = [1, 2, 3, 4, 5];\n arr[9] = [1, 2, 3, 4, 5];\n arr[10] = [1, 2, 3, 4, 5];\n arr[11] = [1, 2, 3, 4, 5];\n arr[12] = [1, 2, 3, 4, 5];\n arr[13] = [1, 2, 3, 4, 5];\n arr[14] = [1, 2, 3, 4, 5];\n arr[15] = [1, 2, 3, 4, 5];\n arr[16] = [1, 2, 3, 4, 5];\n arr[17] = [1, 2, 3, 4, 5];\n arr[18] = [1, 2, 3, 4, 5];\n arr[19] = [1, 2, 3, 4, 5];\n arr[20] = [1, 2, 3, 4, 5];\n arr[21] = [1, 2, 3, 4, 5];\n arr[22] = [1, 2, 3, 4, 5];\n arr[23] = [1, 2, 3, 4, 5];\n arr[24] = [1, 2, 3, 4, 5];\n arr[25] = [1, 2, 3, 4, 5];\n arr[26] = [1, 2, 3, 4, 5];\n arr[27] = [1, 2, 3, 4, 5];\n arr[28] = [1, 2, 3, 4, 5];\n arr[29] = [1, 2, 3, 4, 5];\n arr[30] = [1, 2, 3, 4, 5];\n arr[31] = [1, 2, 3, 4, 5];\n arr[32] = [1, 2, 3, 4, 5];\n arr[33] = [1, 2, 3, 4, 5];\n\n for (var i = 0; i < 32; i++) {\n arr[i][0] = 0; // Conversion of copy-on-access array should be transparent\n }\n}", "function Arr_estados(Matriz1, Matriz2,Indice,A){ //\n for (let i=0;i<Indice-1;i++){\n Matriz1[i]=A[i]\n }\n\n for (let j=1;j<Indice;j++){\n Matriz2[j-1]=A[j]\n }\n}", "function n(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function n(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function fixTheMeerkat(arr) {\n let out = [];\n arr.forEach((x,y) => out[arr.length - 1 - y] = x);\n return out;\n}", "function r(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function r(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function r(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function r(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function ex_9_I(x)\n{\n var rt = [];\n var j = 0;\n for(var i = x.length -1; i >= 0; i--)\n {\n rt[j] = x[i];\n j++;\n }\n return rt;\n}", "function s(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function n(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function r(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function r(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function r(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function r(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function r(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function i(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function lis (arr) {\n\tvar d = []\n\tlet len = 1;\n\tlet target = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\td[i] = [arr[i]];\n\t\tfor (let j = i - 1; j >= 0; j--) {\n\t\t\tif (d[j][0] <= d[i] && j < i) {\n\t\t\t\td[j].forEach(item => {\n\t\t\t\t\td[i].push(item)\n\t\t\t\t})\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (d[i].length > len) {\n\t\t\tlen = d[i].length;\n\t\t\ttarget = d[i]\n\t\t}\n\t}\n\treturn target.reverse();\n}", "function newArray(array) {\n\t\tvar list = [];\n\t\tvar newList = [];\n\t\tvar newArray = [];\n\t\tfor (row = 0; row < Rows; row++) {\n\t\t\tnewArray[row] = 0;\n\t\t}\n\t\tfor (row = 0; row < Rows; row++) {\n\t\t\tif (array[row] !== 0) {\n\t\t\t\tlist.push(array[row]);\n\t\t\t}\n\t\t}\n\n\t\tif (list.length === 0) {\n\t\t\treturn newArray;\n\t\t}\n\t\telse if (list.length === 1) {\n\t\t\tnewArray[0] = list[0];\n\t\t\treturn newArray;\n\t\t}\n\t\telse {\n\t\t\tvar index = 0;\n\t\t\twhile (index < list.length - 1) {\n\t\t\t\tif (list[index] === list[index + 1]) {\n\t\t\t\t\tnewList.push(2 * list[index]);\n\t\t\t\t\tscore += 2 * list[index];\n\t\t\t\t\tindex += 2;\n\t\t\t\t}\n\t\t\t\telse if (list[index] !== list[index + 1]) {\n\t\t\t\t\tnewList.push(list[index]);\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t\tif (index === list.length - 1) {\n\t\t\t\t\tnewList.push(list[list.length - 1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var i = 0; i < newList.length; i++) {\n\t\t\t\tnewArray[i] = newList[i];\n\t\t\t}\n\t\t}\n\t\treturn newArray;\n\t}", "function multiEveryPositiv(array) {\n newArr = [];\n for (var i = 0; i < array.length; i++) {\n if (array[i] > 0) {\n newArr[i] = array[i] * 2;\n } else {\n newArr[i] = array[i];\n }\n }\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 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 createFourByFourArray(){\n\n let newShuffleArray = []\n\n let shuffledArray= shuffleArray()\n\n for(let i=0; i< shuffledArray.length; i+=4){\n\n newShuffleArray.push(shuffledArray.slice(i, i+4))\n \n } \n\n return newShuffleArray\n}", "function stc(arr){\n var x = 0;\n for(var e=0; e<arr.length/2; e+=2){\n x = arr[e];\n arr[e] = arr[arr.length-1-e];\n arr[arr.length-1-e] = x;\n }\n}", "function multiFour (arr)\n{\nvar four = arr.filter ( x => x%4===0 )\n\nreturn four;\n}", "function inShuffle(arr) {\n\t\tvar temp = [],\n\t\t\tlength = arr.length;\n\t\tfor (var i = 1; i < length; i += 2) {\n\t\t\ttemp.push(arr[i]);\n\t\t}\n\t\tfor (var i = 0; i < length; i += 2) {\n\t\t\ttemp.push(arr[i]);\n\t\t}\n\t\tarr.splice.apply(arr, [0, length].concat(temp));\n\t\treturn arr;\n\t}", "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 i(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}", "function n(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function n(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function n(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function n(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function mirror(ary) {\r\n \r\n var len = ary.length\r\n var revAry = [];\r\n var mirror = [];\r\n\r\n\r\n for (var i = len - 1; i >= 0; i--) {\r\n revAry.push(ary[i]);\r\n }\r\n \r\n console.log(ary.concat(revAry)); \r\n\r\n}", "function choose2(inputArr) {\n var len = inputArr.length;\n \n function combine(arr) {\n var cur = [];\n var result = [];\n\n for (var i = 0; i < len; i++) {\n for (var j = i + 1; j < len; j++) {\n cur = [arr[i], arr[j]];\n result.push(cur);\n }\n }\n return result;\n }\n\n return combine(inputArr);\n}", "function zeroestoback(a,b,c,d){ // Given 4 numbers, moves all the zeroes to end (0,2,4,0==>0,0,2,4)\n array=[0,a,b,c,d];\n for(var i=1; i<=4; i++){\n if(array[i]===0){\n for(var j=0; j<i; j++){\n array[i-j]=array[i-j-1];\n }\n }\n }\n return array;\n}", "function p12(){\n var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]\n var n1 = arr[0]\n var n2 = arr[arr.length-1]\n arr[0] = n2\n arr[arr.length-1] = n1\n console.log(arr)\n}", "function shift(array) {\n return [array[0], array.splice(0, 1)][0];\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 mirrorArray(array) {\n let newArray = array.slice(0, array.length);\n\n for (let i = array.length - 1; i >= 0; i -= 1) {\n let el = array[i];\n newArray.push(el);\n }\n\n return newArray;\n}", "function r(e){for(var t=-1,i=e?e.length:0,n=[];++t<i;){var r=e[t];r&&n.push(r)}return n}", "function ShiftArrayValsLeft(arr){\n}", "function initial(array) {\n return array.slice(0, array.length - 1);\n}", "function swapVals(arr){\n var first = arr[0];\n arr[0] = arr[arr.length-1];\n arr[arr.length-1] = first;\n return arr;\n}", "function mirrow(anArray) {\n var mirrowing = anArray.slice(0, anArray.length);\n mirrowing.reverse();\n return mirrowing;\n}", "function r(e,t){if(!Array.isArray(t))return e.slice();for(var n=t.length,r=e.length,o=-1,i=[];++o<r;){for(var a=e[o],s=!1,c=0;c<n;c++){if(a===t[c]){s=!0;break}}!1===s&&i.push(a)}return i}", "function slasher(arr, howMany) {\n // it doesn't always pay to be first\n return arr;\n}", "function mirrorMe() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tnewArray.push(oldArray[(oldArray.length - 1) - i]);\n\t}\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 mov(ori, des) { \n des.push(ori.pop()); \n}", "function s(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function leftRotationAhmedV(arr, d) {\n const index = d % arr.length\n const firstHalf = arr.slice(0, index)\n const secondHalf = arr.slice(index, arr.length)\n\n const result = secondHalf.concat(firstHalf)\n\n console.log(result)\n\n}", "function arrayConsoladation(arr) {\n let intArr = [];\n let counter = 0;\n while (arr[counter] !== undefined) {\n let integer = arr[counter];\n if (arr[counter] !== 0) {\n let index = arr.indexOf(integer);\n intArr.push(...arr.splice(index, 1));\n counter = 0;\n }\n counter++;\n }\n\n let consolidatedArray = [...intArr, ...arr];\n console.log(consolidatedArray);\n}", "function moveToBack (inArr, outArr, numOfElements) {\n for (var i = 0; i < numOfElements; i++) {\n var temp = inArr.shift();\n outArr.push(temp);\n }\n}", "function ranger (x,y){\n let array = [];\n for (i=x+1; i<y; i++) {\n array.push(i);\n }\n return array;\n}", "function f6(arr) {\n return arr.concat(arr.splice(0, 2));\n}", "function arrayManipulation(n, queries) {\n\n\n}", "function func1(){\n var result=[];\n for(var i=1; i<=255; i++){\n result[i-1]=i;\n }\n return result;\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 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 test1(arr) {\n\tarr.push(arr.splice(arr.indexOf(0), 1)[0]);\n\n\treturn arr;\n}", "function looper(arr){\n arr.map(function(val, i, arr){\n arr[i] = val + 5;\n })\n return arr;\n}", "function ex_8_I(a){\n n=Math.sqrt(a.length);\n b=[];\n for(var i=0; i<n; i++){\n b[i]=[];\n for(var j=0;j<n;j++){\n \tb[i][j]=a[n*i+j];\n }\n \n }\n return b;\n\n}", "function mirroredArray(arr) {\n return arr.concat([].concat(arr).reverse());\n}", "function Ui(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}", "function o(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function o(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function range(array){\n return [...array.keys()];\n}", "function _l(array, idx) {\n if (array.layout) {\n let n_array = [];\n for (let i = idx.length - 1; i >= 0; --i) {\n n_array.push(idx[i] + 1);\n }\n return n_array;\n }\n return idx;\n}", "function changeIndexValues(array) {\n var newArray = [];\n for(var i = 0; i < array.length; i++) {\n newArray.push([i, Number(array[i])]);\n }\n return newArray;\n}", "function three(arr){\n return arr.reverse(); \n}", "function main(arr) {\n let sums = [];\n\n for (let i = 0; i < arr.length; i++) {\n let temp = arr.shift(); //since array is always 5 elements, pop/store 1st element in var\n let sum = arr.reduce((pre, curr) => pre + curr, 0); //calculate the sums of 4\n sums.push(sum); // store sum\n arr.push(temp); // put stored elem at end of array\n }\n\n console.log(Math.min(...sums), Math.max(...sums));\n}", "getVaidMoves(spacesArray, currentPlayer){\n //why\n const valids = Array(this.getActionSize()).fill(0);\n const b = Array(this.rows).fill(Array(this.cols).fill(0));\n b = spacesArray.tolist(); //2D to 1D?\n }", "function getNeibord(index,n){\n var low=Math.max(0,index-4);\n var high=Math.min(n-1,index+4);\n return [low,high];\n}", "function swapIndex(arr) {\n var newArr = arr.slice();\n var temp = newArr[0];\n newArr[0] = newArr[newArr.length-1];\n newArr[newArr.length-1] = temp;\n return newArr; \n}", "function Add5ToAllArrayItems(arr) {\n var newArr = [];\n var newArr2 = [];\n for (let i = 0; i < arr.length; i++) {// 500\n for (let j = 0; j < arr.length; j++) {// 500\n newArr.push(arr[i] + 5);// 500 * 500 = 500^2\n newArr2.push(arr[i] + 5);\n }\n }\n return newArr;\n}" ]
[ "0.63081104", "0.61326754", "0.60628486", "0.5938526", "0.592679", "0.5871714", "0.58418727", "0.5832985", "0.5824122", "0.5813666", "0.5762824", "0.5747658", "0.5744858", "0.573617", "0.5725309", "0.5681897", "0.5673432", "0.5673305", "0.5651774", "0.56306416", "0.5604596", "0.5589747", "0.5589747", "0.55774945", "0.557735", "0.557735", "0.557735", "0.557735", "0.5570011", "0.5552152", "0.5545975", "0.55125743", "0.55125743", "0.55125743", "0.55125743", "0.55125743", "0.5507843", "0.5507843", "0.5507843", "0.5507843", "0.5507843", "0.5507843", "0.5507843", "0.55075735", "0.55027264", "0.55013806", "0.54983425", "0.5492917", "0.5476384", "0.5467164", "0.54630035", "0.5462925", "0.54529876", "0.5452671", "0.5449016", "0.5449016", "0.5449016", "0.5449016", "0.5432314", "0.5422196", "0.5410771", "0.5396565", "0.5394856", "0.53898394", "0.538923", "0.5388783", "0.5379697", "0.5371079", "0.5369621", "0.5368489", "0.53674024", "0.5351437", "0.5347568", "0.53448755", "0.5341074", "0.5337496", "0.533552", "0.53206915", "0.5320225", "0.5319718", "0.53147334", "0.53004", "0.5298845", "0.52879006", "0.5281446", "0.52813196", "0.5278063", "0.5271765", "0.52643245", "0.52635115", "0.52620864", "0.52620864", "0.52565455", "0.52562743", "0.52498907", "0.52481747", "0.5237473", "0.5234869", "0.5233695", "0.52320516", "0.5230911" ]
0.0
-1
sortByProcName: This function will sort Secondary Procedures by ascending only.
function sortByProcName(a, b) {//sort by name(display_as) ascending only if (a.DISPLAY_AS.toUpperCase() > b.DISPLAY_AS.toUpperCase()) { return 1; } if (a.DISPLAY_AS.toUpperCase() < b.DISPLAY_AS.toUpperCase()) { return -1; } return 0; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0)\n continue;\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0) continue;\n\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0)\n continue;\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0)\n continue;\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0)\n continue;\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n var procs = arr.map(getProcedure);\n for (var i = 1; i < arr.length; i++) {\n var procNew = procs[i];\n if (procNew < 0)\n continue;\n for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n var token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function sortByProcedure(arr) {\n const procs = arr.map(getProcedure);\n for (let i = 1; i < arr.length; i++) {\n const procNew = procs[i];\n if (procNew < 0)\n continue;\n for (let j = i - 1; j >= 0 && procNew < procs[j]; j--) {\n const token = arr[j + 1];\n arr[j + 1] = arr[j];\n arr[j] = token;\n procs[j + 1] = procs[j];\n procs[j] = procNew;\n }\n }\n}", "function twpro_sortJobs(){\r\n\t\tif (TWPro.twpro_failure) return;\r\n\t\tvar sortby = TWPro.twpro_jobsort, twpro_jobValues = TWPro.twpro_jobValues;\r\n\t\tvar sortfunc = function(twpro_a, twpro_b){\r\n\t\t\tvar twpro_a_str = twpro_a.name,\r\n\t\t\t\ttwpro_b_str = twpro_b.name;\r\n\t\t\tif(sortby == 'name'){\r\n\t\t\t\treturn twpro_a_str.localeCompare(twpro_b_str);\r\n\t\t\t}\r\n\t\t\tif(sortby == 'comb'){\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName].jobrank == twpro_jobValues[twpro_b.shortName].jobrank) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_b.shortName].jobrank - twpro_jobValues[twpro_a.shortName].jobrank);\r\n\t\t\t}\r\n\t\t\tif(sortby == 'erfahrung'){\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName].experience == twpro_jobValues[twpro_b.shortName].experience) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_b.shortName].experience - twpro_jobValues[twpro_a.shortName].experience);\r\n\t\t\t} if(sortby == 'lohn'){\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName].wages == twpro_jobValues[twpro_b.shortName].wages) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_b.shortName].wages - twpro_jobValues[twpro_a.shortName].wages);\r\n\t\t\t} if(sortby == 'glueck'){\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName].luckvaluemax == twpro_jobValues[twpro_b.shortName].luckvaluemax) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_b.shortName].luckvaluemax - twpro_jobValues[twpro_a.shortName].luckvaluemax);\r\n\t\t\t} if(sortby == 'gefahr'){\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName].danger == twpro_jobValues[twpro_b.shortName].danger) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_a.shortName].danger - twpro_jobValues[twpro_b.shortName].danger);\r\n\t\t\t} else {\r\n\t\t\t\treturn (twpro_jobValues[twpro_a.shortName][sortby] == twpro_jobValues[twpro_b.shortName][sortby]) ? twpro_a_str.localeCompare(twpro_b_str) : (twpro_jobValues[twpro_b.shortName][sortby] - twpro_jobValues[twpro_a.shortName][sortby]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tTWPro.twpro_jobs.sort(sortfunc);\r\n\t\t//if(sortby == 'danger') TWPro.twpro_jobs.reverse();\r\n\t}", "function sortMethod(a, b) {\n var x = a.name.toLowerCase();\n var y = b.name.toLowerCase();\n return ((x < y) ? -1 : ((x > y) ? 1 : 0));\n }", "function compSort(p1, p2) {\n if (p1[0] > p2[0]) {\n return -1;\n } else if (p1[0] < p2[0]) {\n return 1;\n } else if (p1[1] > p2[1]) {\n return -1;\n } else if (p1[1] < p2[1]) {\n return 1;\n } else {\n return 0;\n }\n }", "function compSort(p1, p2) {\n if (p1[0] > p2[0]) {\n return -1;\n } else if (p1[0] < p2[0]) {\n return 1;\n } else if (p1[1] > p2[1]) {\n return -1;\n } else if (p1[1] < p2[1]) {\n return 1;\n } else {\n return 0;\n }\n }", "function compSort(p1, p2) {\n if (p1[0] > p2[0]) {\n return -1;\n } else if (p1[0] < p2[0]) {\n return 1;\n } else if (p1[1] > p2[1]) {\n return -1;\n } else if (p1[1] < p2[1]) {\n return 1;\n } else {\n return 0;\n }\n }", "function sortFnByAppraisalNo(a, b) {\n\t if (a.appraisalNo < b.appraisalNo)\n\t return -1;\n\t if (a.appraisalNo > b.appraisalNo)\n\t return 1;\n\t if (a.appraisalNo == b.appraisalNo)\n\t return 0;\n\t}", "function sortBynameAsc(a, b) {\n if (a.name > b.name) return 1;\n if (a.name < b.name) return -1;\n return 0;\n}", "function SortByName(a, b){\n var aName = a.name.toLowerCase();\n var bName = b.name.toLowerCase(); \n return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));\n }", "function sortAlphabetically(a,b) {\n\treturn a.toLowerCase().localeCompare(b.toLowerCase());\n}", "function sortTitle(a,b){\n if (typeof a.props.field === 'string' && typeof b.props.field === 'string'){\n if(a.props.field.toLowerCase() < b.props.field.toLowerCase()) return -1;\n if(a.props.field.toLowerCase() > b.props.field.toLowerCase()) return 1;\n }\n return 0;\n }", "function sortBy(field, reverse, primer) {\r\n reverse = (reverse) ? -1 : 1;\r\n return function(a,b) {\r\n a = a[field];\r\n b = b[field];\r\n if (typeof(primer) != 'undefined'){\r\n a = primer(a);\r\n b = primer(b);\r\n }\r\n if (a<b) return reverse * -1;\r\n if (a>b) return reverse * 1;\r\n return 0;\r\n }\r\n}", "function getSortMethod(){\n var _args = Array.prototype.slice.call(arguments);\n return function(a, b){\n for(var x in _args){\n var ax = a[_args[x].substring(1)];\n var bx = b[_args[x].substring(1)];\n var cx;\n\n ax = typeof ax == \"string\" ? ax.toLowerCase() : ax / 1;\n bx = typeof bx == \"string\" ? bx.toLowerCase() : bx / 1;\n\n if(_args[x].substring(0,1) == \"-\"){cx = ax; ax = bx; bx = cx;}\n if(ax != bx){return ax < bx ? -1 : 1;}\n }\n }\n}", "function funSortByName(a, b) {\n return (a.employee_name.toLowerCase() > b.employee_name.toLowerCase()) ? 1 : -1;\n}", "function sortByFunc() {\n switch (sortBy.field) {\n case 'name':\n case 'ticker':\n if (sortBy.desc === 0) {\n return (a, b) => a[sortBy.field].localeCompare(b[sortBy.field])\n }\n return (a, b) => b[sortBy.field].localeCompare(a[sortBy.field])\n case 'price':\n case 'changes':\n case 'marketCapitalization':\n default:\n if (sortBy.desc === 0) {\n return (a, b) => (a[sortBy.field] - b[sortBy.field])\n }\n return (a, b) => (b[sortBy.field] - a[sortBy.field])\n }\n }", "function ResourceSort(first, second) {\n\tvar result = 0;\n\tif (second.mResName < first.mResName) {\n\t\tresult = 1;\n\t}\n\telse if (first.mResName < second.mResName) {\n\t\tresult = -1;\n\t}\n\t\n\treturn result;\n}", "function pr_asc(){\n console.log('Sort by Price Asc');\n myLibrary.sortByPriceAsc();\n}", "function GetSortOrder(prop) { \n return function(a, b) { \n if (a[prop] > b[prop]) { \n return 1; \n } else if (a[prop] < b[prop]) { \n return -1; \n } \n return 0; \n } \n }", "function sortBy(prop){\r\n return function(a,b){\r\n if( a[prop] > b[prop]){\r\n return 1;\r\n }else if( a[prop] < b[prop] ){\r\n return -1;\r\n }\r\n return 0;\r\n }\r\n}", "sort() {\r\n\t\treturn this.data.sort((a,b) => {\r\n\t\t\tfor(var i=0; i < this.definition.length; i++) {\r\n\t\t\t\tconst [code, key] = this.definition[i];\r\n\t\t\t\tswitch(code) {\r\n\t\t\t\t\tcase 'asc':\r\n\t\t\t\t\tcase 'desc':\r\n\t\t\t\t\t\tif (a[key] > b[key])\r\n\t\t\t\t\t\t\treturn code == 'asc' ? 1 : -1;\r\n\t\t\t\t\t\tif (a[key] < b[key])\r\n\t\t\t\t\t\t\treturn code == 'asc' ? -1 : 1;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'fn':\r\n\t\t\t\t\t\tlet result = key(a, b);\r\n\t\t\t\t\t\tif (result != 0) // If it's zero the sort wasn't decided.\r\n\t\t\t\t\t\t\treturn result;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn 0;\r\n\t\t});\r\n\t}", "function sortAsc(a, b) {\n return a - b;\n }", "function sortAsc(a, b) {\n return a[1] - b[1];\n }", "genSortAscendingByField(field) {\n return (a, b) => {\n const valA = a[field].toUpperCase()\n const valB = b[field].toUpperCase()\n let order = 0\n if (valA < valB) order = -1\n if (valA > valB) order = 1\n return order\n }\n }", "function GetSortOrder(prop) {\n return function (a, b) {\n if (a[prop] > b[prop]) {\n return direction ? 1 : -1;\n } else if (a[prop] < b[prop]) {\n return direction ? -1 : 1;\n }\n return 0;\n };\n }", "function GetSortOrder(prop) {\n return function (a, b) {\n if (a[prop] > b[prop]) {\n return direction ? 1 : -1;\n } else if (a[prop] < b[prop]) {\n return direction ? -1 : 1;\n }\n return 0;\n };\n }", "function userSortFn(a, b) {\n var nameA = a.name.toUpperCase(); // ignore upper and lowercase\n var nameB = b.name.toUpperCase(); // ignore upper and lowercase\n if (nameA < nameB) {\n return -1;\n }\n if (nameA > nameB) {\n return 1;\n }\n // names must be equal\n return 0;\n}", "function _providerSort(a, b) {\n return b.priority - a.priority;\n }", "function sortAlphabetical(pages) {\n return pages.sort((a, b) => {\n const aTitle = a.sidebarTitle || a.name;\n const bTitle = b.sidebarTitle || b.name;\n return aTitle.localeCompare(bTitle);\n });\n}", "function sortTrackName()\n{\n\ttracks.sort( function(a,b) { if (a.name < b.name) \nreturn -1; else return 1; } );\n\tclearTable();\n\tfillTracksTable();\n}", "function sortNameUp(arr) {\n return arr.sort()\n }", "function sortByName (a,b) {\n if (a.name > b.name){\n return 1\n } else {\n return -1\n }\n}", "genSortDescendingByField(field) {\n return (a, b) => {\n const valA = a[field].toUpperCase()\n const valB = b[field].toUpperCase()\n let order = 0\n if (valA < valB) order = 1\n if (valA > valB) order = -1\n return order\n }\n }", "function sortByName() {\n addressBook.sort(function (contact1,contact2){\n let a = contact1.firstName.toUpperCase()\n let b = contact2.firstName.toUpperCase()\n return a == b ? 0 : a > b ? 1: -1;\n })\n console.log(addressBook.toString());\n}", "function userSortFn(a, b) {\n var nameA = a.name.toUpperCase(); // ignore upper and lowercase\n var nameB = b.name.toUpperCase(); // ignore upper and lowercase\n if (nameA < nameB) {\n return -1;\n }\n if (nameA > nameB) {\n return 1;\n }\n \n // names must be equal\n return 0; \n}", "function stringSortFunction(a, b) {\n if (a < b) {\n return -1\n } else if (a === b) {\n return 0\n } else {\n return 1\n }\n}", "function unixCmp(a, b) {\n var aLower = a.toLowerCase();\n var bLower = b.toLowerCase();\n return (aLower === bLower ?\n -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does\n aLower.localeCompare(bLower));\n}", "function unixCmp(a, b) {\n var aLower = a.toLowerCase();\n var bLower = b.toLowerCase();\n return (aLower === bLower ?\n -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does\n aLower.localeCompare(bLower));\n}", "function unixCmp(a, b) {\n var aLower = a.toLowerCase();\n var bLower = b.toLowerCase();\n return (aLower === bLower ?\n -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does\n aLower.localeCompare(bLower));\n}", "function SortByPersonName()\n{\n let sortedArray = contactsArray;\n sortedArray.sort((a,b) => a.firstName.toLowerCase().localeCompare(b.firstName.toLowerCase()));\n console.log(\"\\n\\nPrinting sorted array by person name : \");\n sortedArray.forEach(p => console.log(\"\\n\"+p.toString()));\n}", "function sortByName(a, b)\n{\n return (b.properties.name.toLowerCase() > a.properties.name.toLowerCase() ? -1 : 1);\n}", "function sortResults(array, prop, asc) {\n array = array.sort(function (a, b) {\n\n // if sorting by department, then we want to check to see if we need to reorder by number for multiple courses in a dept.\n if ((prop === 'deptAbbrev') && (a['deptAbbrev'] === b['deptAbbrev'])) {\n // some courses have letters in their numbers, so we need to take those out first.\n var aNumber = a['number'].match(/\\d+/),\n bNumber = b['number'].match(/\\d+/);\n return (aNumber >= bNumber) ? 1 : ((aNumber < bNumber) ? -1 : 0);\n }\n\n // otherwise sort as usual\n if (asc) {\n return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);\n } else {\n return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);\n }\n });\n return array;\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 }", "sortFunctionAsc(field) {\n const compare = (a, b) => {\n var aField = a[field]\n var bField = b[field]\n if (typeof a[field] === 'string') {\n aField = a[field].toLowerCase()\n }\n if (typeof b[field] === 'string') {\n bField = b[field].toLowerCase()\n }\n\n if (aField < bField) { return -1 }\n if (aField > bField) { return 1 }\n return 0\n }\n return compare\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 }", "function ascSort(a,b){\n return a - b;\n }", "function nameSort(obj1, obj2)\n{\n\treturn LocaleSort.compareString(obj1.name.toUpperCase(), obj2.name.toUpperCase());\n}", "sortBy(field, reverse, primer) \n {\n const key = primer\n ? function(x) {\n return primer(x[field]);\n }\n : function(x) {\n return x[field];\n };\n\n return function(a, b) {\n a = key(a);\n b = key(b);\n return reverse * ((a > b) - (b > a));\n };\n }", "function sortByName(repos) {\n\t\trepos.sort( function(a, b) {\n\t\t\t\tif (a.full_name.toLowerCase() < b.full_name.toLowerCase())\n\t\t\t\t\treturn -1;\n\t\t\t\tif (a.full_name.toLowerCase() > b.full_name.toLowerCase())\n\t\t\t\t\treturn 1;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t);\n\t}", "function sort_by_price_asc (a, b) { // as a user I want to see cheapest holidays\n return (a.paxPrice < b.paxPrice)\n ? 1 : ((b.paxPrice < a.paxPrice) ? -1 : 0);\n}", "function compareByName(prod1, prod2)\n{\n if (prod1.name.toLowerCase() < prod2.name.toLowerCase())\n return -1;\n else if (prod1.name.toLowerCase() > prod2.name.toLowerCase())\n return 1;\n else\n return 0;\n}", "function sortByProp(prop) {\n return (a, b) => {\n if (a[prop] > b[prop]) {\n return 1;\n }\n if (a[prop] < b[prop]) {\n return -1;\n }\n return 0;\n };\n}", "function topicSort(a, b) {\n var nameA = a.name.toLowerCase();\n var nameB = b.name.toLowerCase();\n if (nameA < nameB) // sort string ascending\n return -1\n if (nameA > nameB)\n return 1\n return 0 //default return value (no sorting)\n }", "function getSortMethod(stpGuid, stpName, cbfn) {\r\n log(\r\n \"getSortMethod(\" +\r\n stpGuid +\r\n \",\" +\r\n stpName +\r\n \",\" +\r\n (cbfn ? \"defined function\" : \"null\") +\r\n \")\"\r\n );\r\n //sortQuery = _spPageContextInfo.siteAbsoluteUrl + \"/_api/web/lists/GetByTitle('Subtopic%20Sort')/items?$select=Subtopic,Sort_x0020_Method&$filter=TaxCatchAll/IdForTerm eq '\" + stpGuid + \"'\";\r\n sortQuery =\r\n _spPageContextInfo.siteAbsoluteUrl +\r\n \"/_api/web/lists/GetByTitle('Accordion%20Sort')/items?$select=TopicOrSubtopic,SortMethod&$filter=TaxCatchAll/IdForTerm eq '\" +\r\n stpGuid +\r\n \"'\";\r\n var subtopicSortMethod = \"\";\r\n var nullVal = \"Title asc\";\r\n var newSubtopicTermLabel = \"\";\r\n var ret = \"\";\r\n //if(cbfn == null) {\r\n //$.ajaxSetup({async: false});\r\n //}\r\n $.ajax({\r\n url: sortQuery,\r\n type: \"GET\",\r\n headers: {\r\n accept: \"application/json;odata=verbose\"\r\n },\r\n success: function(data) {\r\n log(data);\r\n if (data.d.results.length == 0) {\r\n if (cbfn != null) {\r\n cbfn(nullVal);\r\n } else {\r\n log(\r\n \"getSortMethod(\" +\r\n stpGuid +\r\n \",\" +\r\n stpName +\r\n \",\" +\r\n (cbfn ? \"defined function\" : \"null\") +\r\n \") returning \" +\r\n nullVal\r\n );\r\n ret = nullVal;\r\n }\r\n } else {\r\n $.each(data.d.results, function(index, item) {\r\n //Assign sort method to variable and send back to callback\r\n if (stpGuid) {\r\n //subtopicSortMethod = item.Sort_x0020_Method;\r\n subtopicSortMethod = item.SortMethod;\r\n //return sort method to callback func\r\n if (cbfn != null) {\r\n if (subtopicSortMethod) {\r\n cbfn(subtopicSortMethod);\r\n }\r\n } else {\r\n if (subtopicSortMethod) {\r\n log(\r\n \"getSortMethod(\" +\r\n stpGuid +\r\n \",\" +\r\n stpName +\r\n \",\" +\r\n (cbfn ? \"defined function\" : \"null\") +\r\n \") returning \" +\r\n subtopicSortMethod\r\n );\r\n ret = subtopicSortMethod;\r\n }\r\n }\r\n }\r\n });\r\n }\r\n }\r\n });\r\n //if(cbfn == null) {\r\n //$.ajaxSetup({async: true});\r\n //return ret;\r\n //}\r\n }", "function Sort() {}", "function sortByName(AddressBook) {\n let first, second;\n const display = AddressBook.sort((a, b) => {\n first = a.firstName.toLowerCase();\n second = b.firstName.toLowerCase();\n if (first < second) {\n return -1;\n }\n if (first > second) {\n return 1;\n }\n });\n console.log(display);\n}", "function userSortFn(a, b) {\n let nameA = a.name.toUpperCase(); // ignore upper and lowercase\n let nameB = b.name.toUpperCase(); // ignore upper and lowercase\n if (nameA < nameB) {\n return -1;\n }\n if (nameA > nameB) {\n return 1;\n }\n\n // names must be equal\n return 0;\n}", "function sortBy(colName, recordsetId)\n{\n\tif (recordsetId == null)\n\t\trecordsetId = \"query.sql\";\n\t\t\n\t//llamada Ajax...\n\tajaxCall(httpMethod=\"GET\", \n\t\t\t\t\turi=\"/action/sort?rs=\" + recordsetId + \"&colname=\" + colName, \n\t\t\t\t\tdivResponse=\"response\", \n\t\t\t\t\tdivProgress=\"grid-progress\", \n\t\t\t\t\tformName=null, \n\t\t\t\t\tafterResponseFn=showCurrentPage, \n\t\t\t\t\tonErrorFn=null); \t\n}", "sort(){\n\n }", "_sortGenresByName(a, b) {\n if (a.slug < b.slug) {\n return -1;\n }\n if (a.slug > b.slug) {\n return 1;\n }\n return 0;\n }", "function SortQuestionTitle() {\n\tif (sortTitleReverse === false) {\n\t\tSortQuestionArray();\n\t\tsortTitleReverse = true;\n\t} else {\n\t\tSortQuestionArray();\n\t\tsortTitleReverse = false;\n\t}\n}", "function sort_ascending (a, b) \n {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }", "function dynamicSort(property) {\n\t var sortOrder = 1;\n\t if(property[0] === \"-\") {\n\t sortOrder = -1;\n\t property = property.substr(1);\n\t }\n\t return function (a,b) {\n\t var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;\n\t return result * sortOrder;\n\t }\n\t}", "function sort (cmpts) {\n return _.sortBy(_.map(cmpts, cmpt => _.sortBy(cmpt)), cmpts => cmpts[0])\n}", "function sortByPriority(arr) {\n clock = 0;\n arr.sort((a, b) =>{\n return b.priority - a.priority\n })\n}", "function compareAsc( a, b ) {\n if ( a.name.first < b.name.first ){\n return -1;\n }\n if ( a.name.first > b.name.first ){\n return 1;\n }\n return 0;\n }", "function dynamicSort(property) {\r\n var sortOrder = 1;\r\n if (property[0] === \"-\") {\r\n sortOrder = -1;\r\n property = property.substr(1);\r\n }\r\n\r\n return function(a, b) {\r\n if (sortOrder == -1) {\r\n return b[property].localeCompare(a[property]);\r\n } else {\r\n return a[property].localeCompare(b[property]);\r\n }\r\n }\r\n}", "function sortServices(arr) {\n return arr.sort( function(prev, next) {\n\n if ( next.costs == prev.costs) {\n return prev.name.localeCompare(next.name);\n }\n\n return next.costs - prev.costs;\n });\n }", "function sortBy(srtValue, srtOrder){\n pageData = sortObjectBy(pageData,srtValue,srtOrder);\n checkSelected();\n pagination(max);\n}", "sortBy(field, reverse, primer) {\n\t\tconst key = primer\n\t\t\t? function (x) {\n\t\t\t\treturn primer(x[field]);\n\t\t\t}\n\t\t\t: function (x) {\n\t\t\t\treturn x[field];\n\t\t\t};\n\t\n\t\treturn function (a, b) {\n\t\t\ta = key(a);\n\t\t\tb = key(b);\n\t\t\treturn reverse * ((a > b) - (b > a));\n\t\t};\n\t}", "function sortTableAlphabeticallyAscending(){\n sortAlphabeticallyAscending();\n}", "function sort (cmpts) {\n return _.sortBy(_.map(cmpts, function (cmpt) {\n return _.sortBy(cmpt)\n }), function (cmpts) { return cmpts[0] })\n}", "function dynamicSort(property) {\n var sortOrder = 1;\n if (property[0] === \"-\") {\n sortOrder = -1;\n property = property.substr(1);\n }\n\n return function(a, b) {\n if (sortOrder == -1) {\n return b[property].localeCompare(a[property]);\n } else {\n return a[property].localeCompare(b[property]);\n }\n }\n}", "function dynamicSort(property) {\n var sortOrder = 1;\n if (property[0] === \"-\") {\n sortOrder = -1;\n property = property.substr(1);\n }\n return function (a, b) {\n var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;\n return result * sortOrder;\n }\n }", "async function TopologicalSort(){}", "function sortByProperty(property){ \n return function(a,b){ \n if(a[property] < b[property]) \n return 1; \n else if(a[property] > b[property]) \n return -1; \n \n return 0; \n } \n }", "function sortByProperty(property){ \n return function(a,b){ \n if(a[property] < b[property]) \n return 1; \n else if(a[property] > b[property]) \n return -1; \n \n return 0; \n } \n }", "function dynamicSort(property) {\n var sortOrder = 1;\n if (property[0] === \"-\") {\n sortOrder = -1;\n property = property.substr(1);\n }\n return function(a, b) {\n var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;\n return result * sortOrder;\n }\n }", "function Sort(a,b){\n\tif (a.ChoosedBy < b.ChoosedBy)\n\t\treturn 1;\n\telse\n\t\treturn -1;\n}", "function sortContactsByFirstName()\n{\n\tcontactArray.sort(sortContactsFName);\n\tfunction sortContactsFName(a, b)\n\t{\n\t\tvar contactFirstNameA = a.firstName.toLowerCase();\n\t\tvar contactFirstNameB = b.firstName.toLowerCase();\n\n\t\tif(contactFirstNameA > contactFirstNameB)\n\t\t{\n\t\t\treturn 1\n\t\t}\n\t\telse if(contactFirstNameA < contactFirstNameB)\n\t\t{\n\t\t\treturn -1\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 0\n\t\t}\n\t}\n}", "sortBy() {\n // YOUR CODE HERE\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 dynamicSort( property ) {\n var sortOrder = 1;\n if ( property[ 0 ] === \"-\" ) {\n sortOrder = -1;\n property = property.substr( 1 );\n }\n return function ( a, b ) {\n var result = ( a[ property ] < b[ property ] ) ? -1 : ( a[ property ] > b[ property ] ) ? 1 : 0;\n return result * sortOrder;\n };\n }", "function pr_desc(){\n console.log('Sort by Price Desc: ');\n myLibrary.sortByPriceDesc();\n}", "function sortInns(prop, asc) {\n $scope.inns = $scope.inns.sort(function(a, b) {\n if (asc) {\n return (a[prop] > b[prop]) ? -1 : ((a[prop] < b[prop]) ? 1 : 0);\n } else {\n return (b[prop] > a[prop]) ? -1 : ((b[prop] < a[prop]) ? 1 : 0);\n }\n });\n }", "function asc_sort(a, b) {\n return ($(b).text().toLowerCase()) < ($(a).text().toLowerCase()) ? 1 : -1;\n}", "function sortPatients(patientA, patientB) {\n // sort by patient name and then by person id if there are two patients with same name\n var patientAInfo = patientA.HRCColumns[0];\n var patientBInfo = patientB.HRCColumns[0];\n var compareResult = patientAInfo.PATNAME.localeCompare(patientBInfo.PATNAME);\n if (compareResult === 0) {\n compareResult = parseFloat(patientAInfo.PERSONID) - parseFloat(patientBInfo.PERSONID);\n }\n\n return compareResult;\n }", "function sortBy(sortField1, sortField2) {\n vm.sortField1 = sortField1;\n vm.sortField2 = sortField2;\n vm.sortAsc = !vm.sortAsc;\n vm.parametersList.applyValsForFilters();\n $timeout(vm.validateNamesUnique);\n }", "sortFunctionDesc(field) {\n const compare = (a, b) => {\n var aField = a[field]\n var bField = b[field]\n if (typeof a[field] === 'string') {\n aField = a[field].toLowerCase()\n }\n if (typeof b[field] === 'string') {\n bField = b[field].toLowerCase()\n }\n if (aField < bField) { return 1 }\n if (aField > bField) { return -1 }\n return 0\n }\n return compare\n }", "function sortByProperty(property){ \n return function(a,b){ \n if(a[property] < b[property]) \n return 1; \n else if(a[property] > b[property]) \n return -1; \n \n return 0; \n } \n }", "function sortBooksAlphabeticallyByTitle(books) {\n return books.sort(sortBy(\"title\"))\n}", "sort() {\n\t}", "sort() {\n\t}", "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 }", "sortBy(collection, functionOrKey) {\n return collection.sort((a, b) => {\n if (typeof functionOrKey === \"function\") {\n return functionOrKey(a) < functionOrKey(b) ? -1 : 1;\n }\n return a[functionOrKey] < b[functionOrKey] ? -1 : 1;\n });\n }" ]
[ "0.7111214", "0.7082964", "0.7069585", "0.7069585", "0.7069585", "0.7069585", "0.68992424", "0.60835826", "0.60537666", "0.5901711", "0.5901711", "0.5901711", "0.5762989", "0.57432014", "0.56889117", "0.56843835", "0.56165767", "0.558956", "0.5584798", "0.55671173", "0.5564948", "0.55622673", "0.55510473", "0.5547996", "0.5534299", "0.5525104", "0.55231637", "0.5520987", "0.5518759", "0.5499419", "0.5499419", "0.548643", "0.5477676", "0.547588", "0.54674184", "0.5462041", "0.5428824", "0.5428338", "0.5425476", "0.5424774", "0.5421331", "0.5416463", "0.5416463", "0.5416463", "0.54123586", "0.5406865", "0.53988147", "0.53887653", "0.5381542", "0.53762823", "0.53639203", "0.53535825", "0.5341077", "0.5328563", "0.5315238", "0.5312919", "0.5308929", "0.53072834", "0.53063494", "0.5306336", "0.53008986", "0.5294943", "0.5289014", "0.5280092", "0.5278915", "0.52704227", "0.5268001", "0.5258902", "0.525529", "0.52541953", "0.525416", "0.5253021", "0.5251084", "0.5250433", "0.52484524", "0.52468574", "0.5246041", "0.52374005", "0.52287817", "0.52258515", "0.5220509", "0.5220509", "0.52204394", "0.5219373", "0.5218582", "0.5215797", "0.5214562", "0.52124155", "0.5210321", "0.52045053", "0.5201116", "0.5190503", "0.5189571", "0.5185549", "0.5182268", "0.5181651", "0.5179621", "0.5179621", "0.5173305", "0.5173164" ]
0.7576404
0
ProcedureRequest function will initialize a JSON object needed for sending parameters for mp_exec_std_request script
function ProcedureRequest() { this.procedure_id = 0; this.encounter_id = 0; this.active_ind = 0; this.nomenclature_id = 0; this.procedure_date = ""; this.procedure_date_precision = 0; this.procedure_date_precision_cd = 0; this.free_text = ""; this.update_cnt = 0; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "makeRequest() {\r\n // Get Parameter Values\r\n let requestString = [];\r\n\r\n // Make Request\r\n this.getPrologRequest(requestString, this.handleReply);\r\n }", "function _getParams(funcParamObj, onExecuteComplete) {\r\n\r\n /** default object content of an operation */\r\n var httpRequest = funcParamObj.request;\r\n var httpResponse = funcParamObj.response;\r\n var data = funcParamObj.payload;\r\n\r\n // init data\r\n if (!data) {\r\n data = {}\r\n }\r\n\r\n // skip operation if coming from socket - no httprequest\r\n if (!funcParamObj.io) {\r\n\r\n // req body\r\n var keys = Object.keys(httpRequest.body);\r\n for (var iterator in keys) {\r\n _getValue(data, keys[iterator], httpRequest.body, httpResponse);\r\n }\r\n\r\n // req params\r\n keys = Object.keys(httpRequest.params);\r\n for (var iterator in keys) {\r\n _getValue(data, keys[iterator], httpRequest.params, httpResponse);\r\n }\r\n\r\n // req query\r\n keys = Object.keys(httpRequest.query);\r\n for (var iterator in keys) {\r\n _getValue(data, keys[iterator], httpRequest.query, httpResponse);\r\n }\r\n\r\n //replace \"[xx,yy]\" string with array\r\n keys = Object.keys(data);\r\n for (var iterator in keys) {\r\n var key = keys[iterator];\r\n var value = data[key];\r\n if (value && value.indexOf && value.indexOf('[') == 0 && value.indexOf(']') == (value.length - 1)) {\r\n value = value.substring(1, (value.length - 1));\r\n value = value.split(',');\r\n data[key] = value;\r\n }\r\n }\r\n\r\n //debug purpose\r\n if (process.env.PRINT_REQUEST_PARAM) {\r\n console.log(MODULE_NAME + ': PRINT_REQUEST_PARAM [' + JSON.stringify(data) + ']');\r\n }\r\n\r\n //get rawbody\r\n if (httpRequest.rawBody) {\r\n //data.rawBody = httpRequest.rawBody.toString('binary');\r\n data.rawBody = httpRequest.rawBody;\r\n }\r\n }\r\n\r\n\r\n /** callback with funcParamObj updated - maybe */\r\n funcParamObj.payload = data;\r\n onExecuteComplete(null, funcParamObj);\r\n}", "getPrologRequest(requestString, onSuccess, onError, port) {\n let requestPort = port || SERVER_PORT;\n let request = new XMLHttpRequest();\n request.open('GET', 'http://localhost:' + requestPort + '/' + requestString, false); //( reqType,address, asyncProc) \n request.onload = onSuccess.bind(this) || function(data) { console.log(\"Request successful. Reply: \" + data.target.response); };\n request.onerror = onError || this.prologRequestError;\n request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\n request.send();\n }", "static initialize(obj, baseReq, stock, money, initPrice, maxSupply, maxPrice, maxMoney, earliestCancelTime) { \n obj['base_req'] = baseReq;\n obj['stock'] = stock;\n obj['money'] = money;\n obj['init_price'] = initPrice;\n obj['max_supply'] = maxSupply;\n obj['max_price'] = maxPrice;\n obj['max_money'] = maxMoney;\n obj['earliest_cancel_time'] = earliestCancelTime;\n }", "insert(id, cardTypeName, cardNumber, expMonth, expYear, cardCVV, firstName, lastName) {\n return new Promise((resolve) => {\n this.sql.acquire(function (err, connection) {\n let procedureName = \"uspcAddNewPaymentMethod\";\n var request = new Request(`${procedureName}`, (err, rowCount, rows) => {\n if (err) {\n console.log(err)\n }\n connection.release();\n });\n request.addParameter('UserId', TYPES.Int, id);\n request.addParameter('CardTypeName', TYPES.NVarChar, cardTypeName);\n request.addParameter('CardNumber', TYPES.NVarChar, cardNumber);\n request.addParameter('ExpMonth', TYPES.TinyInt, expMonth);\n request.addParameter('ExpYear', TYPES.SmallInt, expYear);\n request.addParameter('CardCVV', TYPES.SmallInt, cardCVV);\n request.addParameter('FirstName', TYPES.NVarChar, firstName);\n request.addParameter('LastName', TYPES.NVarChar, lastName);\n let jsonArray = []\n request.on('row', function (columns) {\n var rowObject = {};\n columns.forEach(function (column) {\n if (column.value === null) {\n console.log('NULL');\n } else {\n if (column.metadata.colName == 'ProfileImage' || column.metadata.colName == 'SenderProfileImage') {\n column.value = Buffer.from(column.value).toString('base64');\n }\n rowObject[column.metadata.colName] = column.value;\n }\n });\n jsonArray.push(rowObject)\n });\n\n request.on('doneProc', function (rowCount, more) {\n resolve(\"Card has been inserted\")\n });\n\n connection.callProcedure(request)\n });\n })\n .then((message) => {\n return message\n })\n .catch((err) => {\n console.log(err);\n });\n }", "function profpara(req, res) {\n var jerr = {\"status\" : \"err\", \"msg\": \"No prof param info available. \"};\n //var p = req.query;\n var qname = qvs.req2prof(req, jerr);\n var qn = qpset.getq(qname);\n if (!qn) { jerr.msg += \"No profile found\"; return res.json(jerr); }\n console.log(\"look up params for profid: \"+qname+\" \", qn);\n // Need to eval default values ?\n var defpara = {};\n if (qn.defpara) {\n //defpara = qvs.dclone(qn.defpara);\n Object.keys(qn.defpara).forEach(function (k) {\n var v = qn.defpara[k];\n defpara[k] = isfunc(v) ? v() : v;\n });\n }\n else { jerr.msg += \"No default params\"; return res.json(jerr); }\n var pi = { params: qn.params, defpara: defpara };\n res.json({status: \"ok\", data: pi});\n \n function isfunc(v) {\n return (typeof v == 'function') ? 1 : 0;\n }\n}", "function sendJSONRequest(request){\n gTrans.pTypeTrans = document.getElementById('id.pay-type').value;\n gTrans.pStatusTrans = document.getElementById('id.pay-type-dtl').value;\n var jsonData = new Object();\n jsonData.sequence_id = \"2\";\n jsonData.idtxn = gTrans.idtxn;\n jsonData.userId = gCustomerNo;\n if(request.transType == 1){\n jsonData.TRAN_TYPE = \"P\";\n }else if(request.transType == 2){\n jsonData.TRAN_TYPE = \"T\";\n }else{\n jsonData.TRAN_TYPE = \"\";\n }\n jsonData.status = request.transStatus;\n jsonData.FROM_DATE = request.dateBegin;\n jsonData.TO_DATE = request.dateEnd;\n jsonData.pageId = gTrans.pageId;\n jsonData.pageSize = gTrans.pageSize;\n\n var args = new Array();\n args.push(\"2\");\n args.push(jsonData);\n var gprsCmd = new GprsCmdObj(CONSTANTS.get(\"CMD_MANAGER_LC\"), \"\", \"\", gUserInfo.lang, gUserInfo.sessionID, args);\n var data = getDataFromGprsCmd(gprsCmd);\n requestMBServiceCorp.post(data,true, requestMBServiceSuccess, function() {\n showAlertText(CONST_STR.get(\"CORP_MSG_INTERNAL_TRANS_ERROR_GET_DATA\"));\n });\n }", "requestInitialData(sp) {\n this.isConnect = true;\n if (!this.sp) {\n this.sp = sp;\n }\n return this.makeData('REQ');\n }", "function executeRequest(requestConfig) {\n\t var operationType = requestConfig['operation'];\n\t var timestamp = Math.floor(new Date().getTime() / 1000);\n\t var requestData = requestConfig['data'] || {};\n\n\t if (SECRET_KEY) {\n\t // delete the auth key if it comes up empty.\n\t if (!requestData['auth']) {\n\t delete requestData['auth'];\n\t }\n\n\t requestData['timestamp'] = timestamp;\n\t var signInput = SUBSCRIBE_KEY + '\\n' + PUBLISH_KEY + '\\n';\n\n\t if (operationType === 'PNAccessManagerGrant') {\n\t signInput += 'grant' + '\\n';\n\t } else if (operationType === 'PNAccessManagerAudit') {\n\t signInput += 'audit' + '\\n';\n\t } else {\n\t var newPath = requestConfig['url'].slice();\n\t newPath.shift();\n\t signInput += '/' + newPath.join('/') + '\\n';\n\t }\n\n\t signInput += _get_pam_sign_input_from_params(requestData);\n\t var signature = hmac_SHA256(signInput, SECRET_KEY);\n\n\t signature = signature.replace(/\\+/g, '-');\n\t signature = signature.replace(/\\//g, '_');\n\n\t requestData['signature'] = signature;\n\t requestConfig['data'] = requestData;\n\t }\n\n\t return xdr(requestConfig);\n\t }", "function generateInitJSON(){\n\n var requestJSON = {\n USER: \"admin\",\n POSTTYPE: \"getAll\"\n }\n console.log(\"Json request:\\n\");\n console.log(requestJSON);\n\n // Sends request\n $.ajax({\n type: 'POST',\n url: \"https://web.njit.edu/~mjk29/cap/oracleDBConn.php\",\n data: requestJSON,\n success: function(data) {\n responseJSON = JSON.parse(data);\n console.log(responseJSON);\n populate2(responseJSON); \n },\n });\n}", "function createEvalReq(p) {\n let payload = [];\n //If there is no (useful) user input, use empty patient data\n if (p.length) {\n //Loop through all elements of p\n for (let i = 0; i < p.length; i++) {\n //This is a new payload object\n let json = {code: p[i].code, values: [{time: p[i].timestamp, value: p[i].value}]}\n let flag = 0;\n //Loop through all elements that are already in 'payload'\n for (let j = 0; j < payload.length; j++) {\n //Check if a code already exists\n if (p[i].code === payload[j].code) {\n //Add timestamp and value to value list of existing code\n payload[j].values.push({time: p[i].timestamp, value: p[i].value})\n //'flag' is 1 if acode already exists\n flag = 1;\n break;\n }\n }\n //only add the new payload object if code is new\n if (flag === 0) {\n payload.push(json);\n }\n }\n //Sort the value array of each code according to the timestamp\n for (let i = 0; i < payload.length; i++) {\n payload[i].values.sort(function (a, b) {\n let dateA = new Date(a.time), dateB = new Date(b.time);\n return dateA - dateB;\n });\n }\n }\n //Convert JSON to a string\n return JSON.stringify({guidelineId: currentGuidelineId, patientPayload: payload});\n}", "function getRuntimeParams() {\n return new Promise((resolve, reject) => {\n var response;\n multichain.getRuntimeParams({},\n (err, res) => {\n console.log(res)\n if (err == null) {\n return resolve({\n message: \"Blockchain runtime parameters\",\n response: res,\n\n });\n } else {\n console.log(err)\n return reject({\n status: 500,\n message: 'Internal Server Error !'\n });\n }\n }\n )\n })\n}", "function bcInitCprnPrintRequest() {\r\n\tpromFetchAll(vWork.db.work.handle, 'tapr').then(function (taprAry) {\r\n\t\tvWork.al.tapr = taprAry;\r\n\r\n\t\tpromFetchAllIdx(vWork.db.work.handle, 'tcdt', 'print_order').then(function (tcdtAry) {\r\n\t\t\tvWork.al.tcdt = tcdtAry.filter(function (o) { return o.sell_qty > 0});\r\n\r\n\t\t\tpromFetchRec(vWork.db.dnld.handle, 'rhdr', vDynm.re.rhdr.route_id).then(function (rhdrAry) {\r\n\t\t\t\tvDynm.re.rhdr = rhdrAry;\r\n\r\n\t\t\t\tpromFetchAll(vWork.db.work.handle, 'tchd').then(function (tchdAry) {\r\n\t\t\t\t\tvWork.al.tchd = tchdAry;\r\n\r\n\t\t\t\t\tif (vWork.al.tcdt.length > 0) {\r\n\t\t\t\t\t\tcprnPrePrintInit();\r\n\t\t\t\t\t\tprntXactHdrsScan();\r\n\t\t\t\t\t\tprntXactHdrsDisp(204900);\r\n\t\t\t\t\t\tprntXactSetVals();\r\n\t\t\t\t\t\tcprnDispPickList();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tboxChange(4902);\r\n\t\t\t\t\t}\r\n\t\t\t }).catch(function (error) {\r\n\t\t\t\t\tconsole.log(error);\r\n\t\t\t });\r\n\t\t }).catch(function (error) {\r\n\t\t\t\tconsole.log(error);\r\n\t\t });\r\n\t }).catch(function (error) {\r\n\t\t\tconsole.log(error);\r\n\t });\r\n }).catch(function (error) {\r\n\t\tconsole.log(error);\r\n });\r\n\r\n\tcprnBuildMethSel('i_csdnPayMethSel');\r\n\tcprnPrntReqScrInit();\r\n}", "_m_exec_http_request(ph_args, pf_process_next_in_queue) {\n const lo_this = this;\n\n const ph_query_opts = ph_args.ph_query_opts;\n\n const pf_json_callback = lo_this.m_pick_option(ph_args, \"pf_json_callback\");\n const pi_timeout_ms = lo_this.m_pick_option(ph_args, \"pi_timeout_ms\");\n const ps_call_context = lo_this.m_pick_option(ph_args, \"ps_call_context\");\n const ps_method = lo_this.m_pick_option(ph_args, \"ps_method\");\n const ps_url_end_point = lo_this.m_pick_option(ph_args, \"ps_url_end_point\");\n const ps_url_path = lo_this.m_pick_option(ph_args, \"ps_url_path\");\n\n const ls_url_full = f_join_non_blank_vals('', f_string_remove_trailing_slash(ps_url_end_point), ps_url_path);\n\n\n // credentials to call our own services\n const ps_http_pass = lo_this.m_pick_option(ph_args, \"ps_http_pass\", true);\n const ps_http_user = lo_this.m_pick_option(ph_args, \"ps_http_user\", true);\n\n /* eslint multiline-ternary:0, no-ternary:0 */\n const lh_auth = (f_string_is_blank(ps_http_pass) ? null : {\n user: ps_http_user,\n pass: ps_http_pass,\n sendImmediately: true\n });\n\n\n // one more call\n lo_this._ai_call_count_exec_total ++;\n f_chrono_start(lo_this._as_queue_chrono_name);\n\n // at first call\n if (lo_this._ab_first_call) {\n lo_this._ab_first_call = false;\n f_console_OUTGOING_CNX(`target=[${ls_url_full}] login=[${ps_http_user}] way=[push] comment=[connection ${lo_this.m_get_context(ps_call_context)}]`);\n }\n\n const ls_full_call_context = lo_this.m_get_context(`[#${lo_this._ai_call_count_exec_total}]`, ps_call_context);\n\n f_console_verbose(1, `${ls_full_call_context} - init`);\n\n // https://github.com/request/request#requestoptions-callback\n const lh_query_opts = f_object_extend({\n method: ps_method,\n url: ls_url_full,\n\n agent: false,\n auth: lh_auth,\n encoding: \"utf8\",\n json: true,\n rejectUnauthorized: false,\n requestCert: false,\n timeout: pi_timeout_ms,\n }, ph_query_opts);\n\n const ls_call_chrono_name = f_digest_md5_hex(f_join_non_blank_vals('~', lo_this._as_queue_chrono_name, lo_this._ai_call_count_exec_total, f_date_format_iso()));\n f_chrono_start(ls_call_chrono_name);\n\n\n // one more pending request in parallel...\n lo_this._ai_parallel_current ++;\n lo_this._ai_parallel_max = f_number_max(lo_this._ai_parallel_max, lo_this._ai_parallel_current);\n\n cm_request(lh_query_opts, function(ps_error, po_response, po_json_response) {\n\n // one less pending request in parallel...\n lo_this._ai_parallel_current --;\n\n const li_call_duration_ms = f_chrono_elapsed_ms(ls_call_chrono_name);\n f_console_verbose(2, `${ls_full_call_context} - call took [${f_human_duration(li_call_duration_ms, true)}]`);\n\n // collect stats\n lo_this._ai_call_duration_total_ms += li_call_duration_ms;\n lo_this._ai_call_duration_max_ms = f_number_max(lo_this._ai_call_duration_max_ms, li_call_duration_ms);\n lo_this._ai_call_duration_min_ms = f_number_min(lo_this._ai_call_duration_min_ms, li_call_duration_ms);\n\n try {\n\n // error ?\n if (f_string_is_not_blank(ps_error)) {\n throw f_console_error(`${ls_full_call_context} - ${ps_error}`);\n }\n\n const li_statusCode = po_response.statusCode;\n if (li_statusCode !== 200) {\n throw f_console_error(`${ls_full_call_context} - call returned statusCode=[${li_statusCode} / ${po_response.statusMessage}] on URL=[${ls_url_full}] - reponse=[${f_console_stringify(po_json_response)}]`);\n }\n\n if (f_is_not_defined(po_json_response)) {\n throw f_console_error(`${ls_full_call_context} - returned an empty body`);\n }\n\n f_console_verbose(3, `${ls_full_call_context} - returned statusCode=[${li_statusCode}] with raw response:`, {\n po_json_response: po_json_response\n });\n\n if (f_is_defined(po_json_response.errors)) {\n throw f_console_error(`${ls_full_call_context} - errors=[${f_console_stringify(po_json_response.errors)}]`);\n }\n\n if (f_is_defined(po_json_response.error)) {\n throw f_console_error(`${ls_full_call_context} - error=[${f_console_stringify(po_json_response.error)}]`);\n }\n\n // give a context to the reply\n po_json_response.as_call_context = ls_full_call_context;\n\n // positive feed-back through the call-back\n pf_json_callback(null, po_json_response);\n }\n\n catch (po_err) {\n f_console_catch(po_err);\n }\n\n // handle the next pending element in the queue\n f_console_verbose(2, `${lo_this.m_get_context()} - next in queue...`);\n pf_process_next_in_queue();\n });\n }", "function prepare_CONTROL2_SHEM_ISHUV_0_lov_request() {\n var inputParams = {};\n\n return inputParams;\n }", "function makeRequestWithExtraParams(verb, url, data, inDataJson, parse, resFunc, type, id){\n\tconsole.log(url);\n\t\n\t//Create and send request\n\tvar req = new XMLHttpRequest();\n\treq.open(verb, url, true);\n\treq.addEventListener('load', function(){\n\t\t//Check for error message\n\t\tif (req.status >= 200 && req.status < 400)\n\t\t{\n\t\t\tif (parse){\n\t\t\t\tconsole.log(\"Parsing data\");\n\t\t\t\tvar response = JSON.parse(req.responseText);\n\t\t\t\tconsole.log(response);\n\t\t\t\tresFunc(response, type, id);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tvar response = req.responseText;\n\t\t\t\tconsole.log(response);\n\t\t\t\tresFunc(response, type, id);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tconsole.log(\"Error in network request: \" + req.StatusText);\n\t});\n\tif (data != null && !inDataJson){\n\t\treq.send(data);\n\t}\n\telse if (data != null && inDataJson){\n\t\treq.send(JSON.stringify(data));\n\t}\n\telse{\n\t\treq.send();\n\t}\n}", "function scheduleRequest(){\n // create appointment object\n console.log(\"Schedule event requested:\")\n var appt = {};\n appt.name = \"Mayeline Pena\" //document.getElementById(\"name\").value; \n appt.eventEmail = \"[email protected]\" //document.getElementById(\"eventemail\").value;\n appt.eventName = \"90 Day Watch Party\" //document.getElementById(\"eventname\").value;\n appt.guestCount = \"10\" //document.getElementById(\"guest\").value;\n appt.eventDate = \"2019-01-02\" //document.getElementById(\"eventdate\").value;\n appt.eventPlace = \"Capen 2019\" //document.getElementById(\"eventplace\").value;\n appt.eventTime = \"20:00\" //document.getElementById(\"eventtime\").value;\n appt.request = \"schedule\";\n \n // set up ajax request and send appt obj to server\n var AJAXObj = new XMLHttpRequest();\n AJAXObj.onload = onloadScheduleRequest;\n AJAXObj.onerror = function(){\n alert(\"AJAX response error\");\n }\n msg = objectToString(appt);\n console.log(msg);\n AJAXObj.open(\"GET\",\"http://localhost:8080/?\"+msg);\n AJAXObj.setRequestHeader(\"Content-type\", \"application/json\"); \n AJAXObj.send();\n}", "function loadParamsFromServer() {\n\t\t\t\tvar paramArea = this;\n\t\t\t\tvar $this = $(this);\n\t\t\t\tvar componentId = $this.attr('componentId');\n\t\t\t\tvar entryId = $(this).attr('entryId');\n\n\t\t\t\tCREEDO.core.requestData(componentId, entryId, function(result) {\n\t\t\t\t\tPARAMETERS.renderParameters($this, result);\n\t\t\t\t});\n\t\t\t}", "function vardata_request() {\n\t$('body').css('cursor', 'wait');\n\tvar var1 = $('select[name=\"var1\"]').val();\n\tvar var2 = $('select[name=\"var2\"]').val();\n\tvar var1_min = $('input[name=\"var1_min\"]').val();\n\tvar var1_max = $('input[name=\"var1_max\"]').val();\n\tvar var2_min = $('input[name=\"var2_min\"]').val();\n\tvar var2_max = $('input[name=\"var2_max\"]').val();\n var url = \"/vardata?var1=\"+var1+\"&var2=\"+var2+\"&var1_min=\"+var1_min+\"&var1_max=\"+var1_max+\"&var2_min=\"+var2_min+\"&var2_max=\"+var2_max;\n $('#vardata-link').html(\"<p>Click here to launch a <a href=\\\"\"+url+\"\\\">direct REST Api call.</a></p>\");\n vardata_req.open(\"GET\", url, true);\n vardata_req.onreadystatechange = vardata_reply;\n vardata_req.send(null);\n}", "IN_Start() {\n return new Promise((resolve, reject) => {\n this.CurrentStepResolve = null;\n this.CurrentStepReject = null;\n this.CurrentStepProcess = null;\n\n this.Prov_Start.algorithm = 0; //FIPS P-256 Elliptic Curve\n\n //OOB Public Key is used if exist\n if(this.IN_Conf_Caps.pub_type == 0x01){\n this.Prov_Start.pub_key = 1;\n }else{\n this.Prov_Start.pub_key = 0; //No\n }\n\n //Select OOB Action\n if (this.IN_Conf_Caps.static_type) {\n console.log('Select PROV_STATIC_OOB');\n this.Prov_Start.auth_method = PROV_STATIC_OOB; //Static OOB authentication is used\n } else if (this.IN_Conf_Caps.output_size > this.IN_Conf_Caps.input_size) {\n console.log('Select PROV_OUTPUT_OOB');\n this.Prov_Start.auth_method = PROV_OUTPUT_OOB; //Output OOB authentication is used\n this.Prov_Start.auth_action = this.Select_Ouput_OOB();\n this.Prov_Start.auth_size = this.IN_Conf_Caps.output_size;\n } else if (this.IN_Conf_Caps.input_size > 0) {\n console.log('Select PROV_INPUT_OOB');\n this.Prov_Start.auth_method = PROV_INPUT_OOB; //Input OOB authentication is used\n this.Prov_Start.auth_action = this.Select_Input_OOB();\n this.Prov_Start.auth_size = this.IN_Conf_Caps.input_size;\n } else {\n console.log('Select PROV_NO_OOB');\n this.Prov_Start.auth_method = PROV_NO_OOB; //Input OOB authentication is used\n }\n\n //Check\n if (this.Prov_Start.auth_size > 8) {\n this.CurrentStepReject(\"error : auth_size > 8\")\n return;\n }\n\n console.log(Object.keys(this.Prov_Start));\n console.log(Object.values(this.Prov_Start));\n\n var index = 0\n var PDU = new Uint8Array(1 + 1 + 5);\n\n //Fill PDU_Start\n PDU[index++] = PROXY_PROVISIONING_PDU;\n PDU[index++] = PROV_START;\n //PDU Start Data\n PDU[index++] = this.Prov_Start.algorithm;\n PDU[index++] = this.Prov_Start.pub_key;\n PDU[index++] = this.Prov_Start.auth_method;\n PDU[index++] = this.Prov_Start.auth_action;\n PDU[index++] = this.Prov_Start.auth_size;\n\n console.log('Start PDU ' + PDU);\n console.log('Start PDU ' + PDU.length);\n this.PDU_Start = PDU;\n\n this.ProxyPDU_IN.Send(PDU)\n .then(() => {\n resolve();\n })\n .catch(error => {\n reject(error);\n });\n });\n }", "async prepareRequest(httpRequest) {\n const requestInit = {};\n // Set the http(s) agent\n requestInit.agent = this.getOrCreateAgent(httpRequest);\n requestInit.compress = httpRequest.decompressResponse;\n return requestInit;\n }", "function JSONscriptRequest(fullUrl) {\n // REST request path\n this.fullUrl = fullUrl; \n // Keep IE from caching requests\n this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();\n // Get the DOM location to put the script tag\n this.headLoc = document.getElementsByTagName(\"head\").item(0);\n // Generate a unique script tag id\n this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;\n }", "function readParameters(req){\n var request_parameters = {};\n\n var page_formats = [\"Letter\", \"Legal\", \"Tabloid\",\"Ledger\",\"A0\",\"A1\",\"A2\",\"A3\",\"A4\",\"A5\",\"A6\"];\n\n if (req.query.url && \"\" != req.query.url) {\n request_parameters.url = req.query.url;\n }\n\n if (req.query.username && null != req.query.username) {\n request_parameters.username = req.query.username;\n }\n\n if (req.query.password && null != req.query.password) {\n request_parameters.password = req.query.password;\n }\n\n if (req.query.scale && !isNaN(parseFloat(req.query.scale))) {\n request_parameters.scale = parseFloat(req.query.scale);\n }\n\n if (req.query.printBackground && 1 === parseInt(req.query.printBackground)) {\n request_parameters.printBackground = true;\n }\n\n if (req.query.landscape && 1 == parseInt(req.query.landscape)) {\n request_parameters.landscape = true;\n }\n\n if (req.query.format && page_formats.indexOf(req.query.format) > -1) {\n request_parameters.format = req.query.format;\n }\n\n if (req.query.delay && parseInt(req.query.delay) > 0) {\n request_parameters.delay = parseInt(req.query.delay);\n }\n\n if (req.query.pageRanges && \"\" != req.query.pageRanges) {\n request_parameters.pageRanges = req.query.pageRanges;\n }\n\n if (req.query.headerTemplate && \"\" != req.query.headerTemplate) {\n request_parameters.headerTemplate = req.query.headerTemplate;\n }\n\n if (req.query.footerTemplate && \"\" != req.query.footerTemplate) {\n request_parameters.footerTemplate = req.query.footerTemplate;\n }\n\n if (request_parameters.headerTemplate || request_parameters.footerTemplate) {\n request_parameters.displayHeaderFooter = true;\n }\n\n if (req.query.margin) {\n request_parameters.margin = {}\n\n if (req.query.margin[\"top\"]) {\n request_parameters.margin.top = req.query.margin[\"top\"]\n }\n\n if (req.query.margin[\"bottom\"]) {\n request_parameters.margin.bottom = req.query.margin[\"bottom\"]\n }\n\n if (req.query.margin[\"left\"]) {\n request_parameters.margin.left = req.query.margin[\"left\"]\n }\n\n if (req.query.margin[\"right\"]) {\n request_parameters.margin.right = req.query.margin[\"right\"]\n }\n }\n\n return Object.assign({}, default_parameters, request_parameters);\n}", "requestObject(request) {\n return request; \n }", "function VAEencoderRequest(input){\n input = JSON.stringify(input);\n $.ajax({\n type : 'POST',\n url : \"/VAEencoder\",\n dataType : \"json\",\n contentType: 'application/json;charset=UTF-8',\n data : JSON.stringify({\"input\":input}),\n success:callbackFuncVAE\n });\n}", "function transferAsparameter(reqbody) {\n\tvar temp = {'path':{},'sql':{},'data_process':{},'correlation_algorithm':{},\n\t 'association_rules':{},'root_analysis':{}};\n\tvar count = 0 ;\n\tfor(var i in reqbody) {\n if(count < 2 && count >= 0)\n\t\t\ttemp['path'][i] = reqbody[i];\n\t\telse if(count >= 2 && count < 20)\n\t\t\ttemp['sql'][i] = reqbody[i];\n\t\telse if(count >= 20 && count < 25)\n\t\t\ttemp['data_process'][i] = reqbody[i];\n\t\telse if(count >= 25 && count < 27)\n\t\t{\n\t\t\tif(count == 25)\n\t\t\t\ttemp['correlation_algorithm']['corr_support'] = reqbody[i];\n\t\t\telse\n\t\t\t\ttemp['correlation_algorithm'][i] = reqbody[i];\n\t\t}\n\t\telse if(count >= 27 && count < 32)\n\t\t\ttemp['association_rules'][i] = reqbody[i];\n\t\telse\n\t\t\ttemp['root_analysis'][i] = reqbody[i];\n\t\tcount++;\n\t}\n\treturn temp ;\n\t//console.log('reqpath:' + JSON.stringify(temp));\n\n}", "function loadInitData() {\n var jsonData = new Object();\n jsonData.sequence_id = \"1\";\n jsonData.idtxn = gTrans.idtxn;\n var args = new Array();\n args.push(null);\n args.push(jsonData);\n var gprsCmd = new GprsCmdObj(CONSTANTS.get(\"CMD_BATCH_SALARY_MANAGER\"), \"\", \"\", gUserInfo.lang, gUserInfo.sessionID, args);\n var data = getDataFromGprsCmd(gprsCmd);\n requestMBServiceCorp(data, false, 0, function (data) {\n var resp = JSON.parse(data);\n if (resp.respCode == 0 && resp.respJsonObj.listMakers.length > 0) {\n //Danh sach nguoi duyet\n gTrans.listMakers = resp.respJsonObj.listMakers;\n } else\n gotoHomePage();\n }, function () {\n gotoHomePage();\n });\n}", "function nlobjRequest() {\n}", "send(request, callback) {\n if (!request)\n callback('Undefined request');\n this.request(request)\n .then((result) => callback(null, { jsonrpc: '2.0', id: request.id, result }))\n .catch((error) => callback(error, null));\n }", "call(query, languageCode, context, sessionId) {\n // call(query:string, latitude:string, longitude:string, sessionId:string, iana_timezone:string, contexts: string[]): Promise<any> {\n let data = {\n \"query\": query,\n \"lang\": \"en\",\n \"sessionId\": sessionId,\n \"location\": {\n \"latitude\": Number('42.361145'),\n \"longitude\": Number('-71.057083'),\n },\n \"timezone\": 'America/New_York'\n };\n if (context) {\n data.contexts = [context];\n }\n let raw_url = \"\";\n return new Promise((resolve, reject) => {\n request.post({\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Authorization\": `${this.apiAuthorization}`\n },\n url: 'https://api.api.ai/v1/query?v=20150910',\n body: JSON.stringify(data)\n }, (error, response, body) => {\n if (error) {\n //console.log(error);\n reject(error);\n }\n else {\n let body_obj = JSON.parse(body);\n resolve(body_obj);\n }\n });\n });\n }", "function make_proc(op_name, ok_cb) {\n\n return function(req) { \n \n try {\n // init progress\n document.body.style.cursor = 'progress';\n \n if (req.readyState != COMPLETE) {\n return;\n }\n \n // if (alert_response) { alert(req.responseText); }\n \n if( req.status != OK ) {\n throw new procException( op_name + \" request status was '\" + req.status + \"'\", req )\n }\n\n ok_cb(req);\n \n } catch(e) {\n \n // clean up progress\n document.body.style.cursor = 'default';\n \n if (e instanceof procException) {\n alert( e.msg );\n if (DEBUG) {\n alert(e.req.responseText);\n }\n } else {\n throw(e);\n }\n }\n\n // clean up progress\n\n document.body.style.cursor = 'default';\n }\n }", "setDefault(id, existingCardId) {\n return new Promise((resolve) => {\n this.sql.acquire(function (err, connection) {\n let procedureName = \"uspcUpdateUserDefaultPaymentCard\";\n var request = new Request(`${procedureName}`, (err, rowCount, rows) => {\n if (err) {\n console.log(err)\n }\n connection.release();\n });\n request.addParameter('UserId', TYPES.Int, id);\n request.addParameter('ExistingCardId', TYPES.Int, existingCardId);\n let jsonArray = []\n request.on('row', function (columns) {\n var rowObject = {};\n columns.forEach(function (column) {\n if (column.value === null) {\n console.log('NULL');\n } else {\n if (column.metadata.colName == 'ProfileImage' || column.metadata.colName == 'SenderProfileImage') {\n column.value = Buffer.from(column.value).toString('base64');\n }\n rowObject[column.metadata.colName] = column.value;\n }\n });\n jsonArray.push(rowObject)\n });\n\n request.on('doneProc', function (rowCount, more) {\n resolve(\"Card has been set to default\")\n });\n\n connection.callProcedure(request)\n });\n })\n .then((message) => {\n return message\n })\n .catch((err) => {\n console.log(err);\n });\n }", "function getLaunchResponse(callback) {\n // If we wanted to initialize the session to have some attributes we could add those here.\n var sessionAttributes = {};\n var cardTitle = \"Launch\";\n var speechOutput = \"Recon is about to launch. \" +\n \"Give directions\";\n // If the user either does not reply to the welcome message or says something that is not\n // understood, they will be prompted again with this text.\n var repromptText = \"Please give directions\";\n var shouldEndSession = false;\n\n var postData = JSON.stringify({\n 'command' : 'launch'\n });\n\n\n var options = {\n hostname: FIREBASE_API,\n port: 443,\n path: '/.json',\n method: 'PATCH',\n /*headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': postData.length\n }*/\n };\n\n body = '';\n var req = https.request(options, function(res) {\n res.on('data', function (chunk) {\n body += chunk;\n callback(sessionAttributes,\n buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));\n\n });\n// context.succeed('Blah');\n });\n\n req.on('error', function(e) {\n console.log('problem with request:' + e.message);\n });\n\n // write data to request body*/\n req.write(postData);\n req.end();\n console.log(\"sdf: \" + body);\n\n}", "function processInit(res) {\r\n var answer = {};\r\n // add an empty array in messages to messages to be sent to the client when it polls\r\n messages[currentId] = [];\r\n // send back clientID to the client for future communications\r\n // increment client - in preperation to init request from the next client \r\n answer.id = currentId++; \r\n utils.sendJSONObj(res,200,answer);\r\n}", "async function getAPATCHParams(achieved, num) {\n return ({\n \"method\": \"PATCH\",\n \"headers\": await getHeader(),\n \"body\": JSON.stringify({\n \"patch\": achieved,\n \"completion\": num\n })\n })\n}", "function getPostObject(state)\n{\n\nlet measurement_description = { \n type:state.type,\n key:getKey(),\n start_time:formatDate(state.start_time),\n end_time:formatDate(state.end_time),\n count:state.count,\n interval_sec:1,\n priority:state.priority,\n parameters:{\n target:state.target.substring(8),\n server:\"null\",\n direction:state.tcp_speed_test, \n }\n };\nlet job_description = {\n measurement_description,\n node_count:state.node_count,\n job_interval:state.job_interval\n}\n\nlet result={job_description, request_type:\"SCHEDULE_MEASUREMENT\" ,user_id:getKey(), };\n\nreturn result;\n}", "function Param () {\n var obj = {\n display: \"\",\n conditions: [\n {\n display: \"\",\n min: \"\",\n max: \"\",\n linstep: \"\",\n unit: \"\",\n condition: \"\",\n pin: \"\"\n }\n ],\n typ: {\n target: \"\",\n penalty: \"100\"\n },\n min: {\n target: \"\",\n penalty: \"fail\"\n },\n max: {\n target: \"\",\n penalty: \"fail\"\n },\n pin: \"\",\n unit: \"\",\n method: \"\"\n };\n return obj;\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 }", "function GetRequest() {\n // checkLoginStatus();\n const url = location.search;\n let theRequest = new Object();\n if (url.indexOf(\"?\") != -1) {\n let str = url.substr(1);\n strs = str.split(\"&\");\n for (let i = 0; i < strs.length; i++) {\n theRequest[strs[i].split(\"=\")[0]] = unescape(strs[i].split(\"=\")[1]);\n }\n }\n console.log(theRequest);\n\n let sid = Number(theRequest.sid);\n let pid = Number(theRequest.pid);\n if (sid && pid) {\n GetStoreInfo({ storeid: sid }).then(data => {\n console.log(data);\n current_store = data;\n GetProductInfo({ productid: pid }).then(data => {\n productinfo = data;\n initMyproduct(data);\n console.log(data);\n createProductInfo(current_store, data)\n }).catch(err => {\n console.log(err);\n showToast(err);\n });\n }).catch(err => {\n console.log(err);\n showToast(err);\n });\n } else {\n showToast(\"Illegal connection\");\n window.open(`${window.location.origin}/view/home/Home.html`, '_self');\n }\n\n\n}", "function getCommonParams(event) {\n let body = event;\n try {\n if (event.body) {\n body = JSON.parse(event.body);\n }\n } catch (err) {\n throw new Error('request body is not a json string');\n }\n let {\n TENCENTCLOUD_SECRETID: secretId,\n TENCENTCLOUD_SECRETKEY: secretKey,\n TENCENTCLOUD_SESSIONTOKEN: token,\n Records: records,\n ObjectInfo: objectInfo,\n Upstream: upstream,\n sourceFrom = ['cosWorkflowObjectInfo'],\n sourceList = [],\n sourceConfigList = [],\n avoidLoopRisk,\n extraData = {},\n callbackUrl,\n parentRequestId,\n ...args\n } = {\n ...process.env,\n ...event,\n ...body,\n };\n\n try {\n if (typeof extraData === 'string') {\n extraData = JSON.parse(extraData);\n }\n } catch (err) {\n throw new Error('extraData must be JSON Object');\n }\n\n try {\n if (typeof sourceFrom === 'string') {\n sourceFrom = JSON.parse(sourceFrom);\n }\n } catch (err) {}\n\n try {\n if (typeof sourceFrom === 'string') {\n sourceFrom = [sourceFrom];\n }\n } catch (err) {}\n\n let triggerType = '';\n\n const missingParams = [\n { key: 'TENCENTCLOUD_SECRETID', value: secretId },\n { key: 'TENCENTCLOUD_SECRETKEY', value: secretKey },\n // { key: 'TENCENTCLOUD_SESSIONTOKEN', value: token },\n ]\n .filter(item => !item.value)\n .map(item => item.key);\n\n if (missingParams.length) {\n throw new Error(`params parsed error, missing params: ${missingParams.join(', ')}`);\n }\n\n if (parentRequestId) {\n logger({\n title: `this function is trigger by parent function, parent request id is ${parentRequestId}`,\n });\n }\n\n if (records) {\n logger({ title: 'this function is trigger by cos' });\n triggerType = 'cosTrigger';\n records\n .map(item => parseUrl(item.cos.cosObject.url))\n .forEach(item => sourceList.push(item));\n avoidLoopRisk = getFinalValue(avoidLoopRisk, 'true');\n } else if (objectInfo) {\n logger({ title: 'this function is trigger by cos workflow' });\n triggerType = 'cosWorkflow';\n const { BucketId: bucket, Region: region, Object: key } = objectInfo;\n const {\n BucketId: cosWorkflowUpstreamBucket,\n Region: cosWorkflowUpstreamRegion,\n Object: cosWorkflowUpstreamKey,\n } = upstream;\n if (sourceFrom.includes('cosWorkflowUpstream')) {\n sourceList.push({\n bucket: cosWorkflowUpstreamBucket,\n region: cosWorkflowUpstreamRegion,\n key: cosWorkflowUpstreamKey,\n });\n }\n if (sourceFrom.includes('cosWorkflowObjectInfo')) {\n sourceList.push({\n bucket,\n region,\n key,\n });\n }\n avoidLoopRisk = getFinalValue(avoidLoopRisk, 'true');\n } else {\n if (event.body) {\n logger({\n title: 'this function is trigger by apigateway',\n });\n } else {\n logger({\n title: 'this function is trigger by scf invoke',\n });\n }\n avoidLoopRisk = getFinalValue(avoidLoopRisk, 'false');\n }\n\n if (!sourceList.length && !sourceConfigList.length) {\n throw new Error('sourceList or sourceConfigList should be set');\n }\n\n return {\n secretId,\n secretKey,\n token,\n sourceList,\n sourceConfigList,\n triggerType,\n avoidLoopRisk: ['true', true].includes(avoidLoopRisk),\n extraData,\n callbackUrl,\n parentRequestId,\n ...args,\n };\n}", "function sendrequestparametervalues ()\n \n {\n \n request = {WPUSHG:{WPUSHGID:\"J1939_Data\",Maxrate:50,Minrate:5000}};\n send(ws, request, var_callbackgotresponse);\n console.log(\"group parameter push request sent\");/* TODO, turn off for development only*/\n \n }", "function get_pps_params(callback)\n{\n var ppsParams = null;\n chrome.storage.local.get(['ppsParams'], function(result) {\n if ($.isEmptyObject(result))\n {\n var oReq = new XMLHttpRequest();\n oReq.open(\"GET\", CLOUD_SERVER + 'get_pps_params', true);\n oReq.responseType = \"arraybuffer\";\n\n oReq.onload = function (oEvent) {\n ppsParams = oReq.response; // Note: not oReq.responseText\n chrome.storage.local.set({ppsParams: _arrayBufferToBase64(ppsParams)});\n callback(ppsParams);\n };\n\n oReq.send();\n }\n else\n {\n ppsParams = _base64ToArrayBuffer(result.ppsParams);\n callback(ppsParams);\n }\n });\n}", "makeRequest(method, resource, params, callback) { console.log(params)\n if (typeof(method) === 'undefined') { \n method = \"GET\";\n resource += '/?' + params;\n }\n const ascendant = this;\n let requestID = uuid()\n var req = https.request({ \n host: this.host,\n\t\t\tport: this.port,\n\t\t\tpath: resource, \n\t\t\tmethod: method,\n\t\t\theaders: this.request_headers\n }, (response) => { \n var data = '';\n response.on('data', (chunk) => data += chunk); // re-assemble fragmented response data\n response.on('end', () => {\n ascendant.callback(response.statusCode, requestID, data);\n });\n }).on('error', (err) => { \n ascendant.callback(0, requestID, err); // this is called when network request fails\n });\n\n // non-GET HTTP(S) reuqests pass arguments as data\n if (method !== \"GET\" && typeof(params) !== 'undefined') {\n req.write(params);\n }\n req.end();\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 }", "function CNCCommandSubmit()\n{\n var command_name = document.forms[\"CommandForm\"][\"command_name\"].value;\n var command_object = new Object();\n\n var params = document.forms[\"CommandForm\"][\"parameters\"].value.split(\",\");\n\n for (var idx = 0; idx < params.length; idx++)\n { \n pname = idx.toString();\n command_object[pname] = params[idx].trim();\n } \n\n command_object.command = \"put\";\n command_object.name = command_name;\n command_object.id = \"COMMAND\";\n\n var cmd_msg = JSON.stringify( command_object );\n\n ws.send( cmd_msg ); \n}", "getParams() {\n const self = this;\n const functionSignature = 'getParams()';\n return {\n callAsync(callData = {}, defaultBlock) {\n return __awaiter(this, void 0, void 0, function* () {\n base_contract_1.BaseContract._assertCallParams(callData, defaultBlock);\n const rawCallResult = yield self._performCallAsync(Object.assign({ data: this.getABIEncodedTransactionData() }, callData), defaultBlock);\n const abiEncoder = self._lookupAbiEncoder(functionSignature);\n base_contract_1.BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder);\n return abiEncoder.strictDecodeReturnValue(rawCallResult);\n });\n },\n getABIEncodedTransactionData() {\n return self._strictEncodeArguments(functionSignature, []);\n },\n };\n }", "getParamsForOrder(paramsFromForm, email, geoAttribute, maxArea) {\n let params = \"opt_servicemode=async&opt_responseformat=json\";\n let errMsg = \"\";\n\n // TODO: Check email format\n params = params + \"&opt_requesteremail=\" + email;\n\n let area = this.getPolygonArea();\n if (area <= 0) {\n errMsg = errMsg + \"Inget område ritat i kartan. \";\n } else if (area > maxArea) {\n errMsg =\n errMsg + \"Områdets storlek får inte överskrida \" + maxArea + \" m2. \";\n } else {\n let geoJSON = this.getPolygonAsGeoJSON();\n params = params + \"&\" + geoAttribute + \"=\" + geoJSON;\n }\n\n paramsFromForm.forEach((param) => {\n let paramName = \"\";\n let paramVal = \"\";\n if (param.type === \"TEXT\") {\n paramName = param.name;\n paramVal = param.value === undefined ? \"\" : param.value;\n } else if (param.type === \"LOOKUP_LISTBOX\") {\n paramName = param.name;\n let val = \"\";\n param.listOptions.forEach((option) => {\n if (param.value[this.prefixOptionValue(option.value)] === true) {\n val = val === \"\" ? option.value : val + \" \" + option.value;\n }\n });\n paramVal = val;\n } else if (param.type === \"LOOKUP_CHOICE\") {\n paramName = param.name;\n paramVal = param.value === undefined ? \"\" : param.value;\n }\n if (paramVal.length === 0 && param.optional === true) {\n paramName = \"\";\n } else if (paramVal.length === 0 && param.optional === false) {\n errMsg =\n errMsg +\n \"Inget värde valt för parameter '\" +\n param.description +\n \"'. \";\n }\n if (paramName.length > 0) {\n params = params + \"&\" + paramName + \"=\" + paramVal;\n }\n });\n\n return {\n success: errMsg.length === 0,\n params: params,\n errMsg: errMsg,\n };\n }", "function buildRequestParams(meta, range, calendar) {\n var dateEnv = calendar.dateEnv;\n var startParam;\n var endParam;\n var timeZoneParam;\n var customRequestParams;\n var params = {};\n if (range) {\n // startParam = meta.startParam\n // if (startParam == null) {\n startParam = calendar.opt('startParam');\n // }\n // endParam = meta.endParam\n // if (endParam == null) {\n endParam = calendar.opt('endParam');\n // }\n // timeZoneParam = meta.timeZoneParam\n // if (timeZoneParam == null) {\n timeZoneParam = calendar.opt('timeZoneParam');\n // }\n params[startParam] = dateEnv.formatIso(range.start);\n params[endParam] = dateEnv.formatIso(range.end);\n if (dateEnv.timeZone !== 'local') {\n params[timeZoneParam] = dateEnv.timeZone;\n }\n }\n // retrieve any outbound GET/POST data from the options\n if (typeof meta.extraParams === 'function') {\n // supplied as a function that returns a key/value object\n customRequestParams = meta.extraParams();\n }\n else {\n // probably supplied as a straight key/value object\n customRequestParams = meta.extraParams || {};\n }\n __assign(params, customRequestParams);\n return params;\n}", "function createParam() {\n var singledovParams = {};\n var mattId = self.isGlobal ? self.docModel.matterid : self.matterId;\n mattId = parseInt(mattId);\n singledovParams.documentname = self.docModel.documentname;\n singledovParams.categoryid = self.docModel.category.doc_category_id;\n singledovParams.needs_review = self.docModel.needs_review ? 1 : 0;\n singledovParams.review_user = utils.isNotEmptyVal(self.reviewUser) ? self.reviewUser.toString() : ''; // assign reviewer user\n singledovParams.uploadtype = 'fresh';\n singledovParams.intake_id = mattId;\n singledovParams.associated_party_id = angular.isUndefined(self.docModel.associated_party_id) ? 0 : self.docModel.associated_party_id;\n singledovParams.party_role = self.docModel.party_role ? self.docModel.party_role : 0;\n singledovParams.tags = _.pluck(self.docAddTags, 'name');\n angular.isDefined(self.memo) ? singledovParams.memo = self.memo : singledovParams.memo = '';\n singledovParams.date_filed_date = utils.isNotEmptyVal(self.docModel.date_filed_date) ? moment.utc(self.docModel.date_filed_date).unix() : '';\n return singledovParams;\n }", "static initialize(obj, baseReq, delegatorAddress, validatorSrcAddress, validatorDstAddress, amount) { \n obj['base_req'] = baseReq;\n obj['delegator_address'] = delegatorAddress;\n obj['validator_src_address'] = validatorSrcAddress;\n obj['validator_dst_address'] = validatorDstAddress;\n obj['amount'] = amount;\n }", "getPayments(id) {\n return new Promise((resolve) => {\n this.sql.acquire(function (err, connection) {\n let procedureName = \"uspcGetAllPaymentCards\";\n var request = new Request(`${procedureName}`, (err, rowCount, rows) => {\n if (err) {\n console.log(err)\n }\n connection.release();\n });\n request.addParameter('UserId', TYPES.Int, id);\n let jsonArray = []\n request.on('row', function (columns) {\n var rowObject = {};\n columns.forEach(function (column) {\n if (column.value === null) {\n console.log('NULL');\n } else {\n if (column.metadata.colName == 'ProfileImage' || column.metadata.colName == 'SenderProfileImage') {\n column.value = Buffer.from(column.value).toString('base64');\n }\n rowObject[column.metadata.colName] = column.value;\n }\n });\n jsonArray.push(rowObject)\n });\n\n request.on('doneProc', function (rowCount, more) {\n resolve(jsonArray);\n });\n\n connection.callProcedure(request)\n });\n })\n .then((jsonArray) => {\n return jsonArray\n })\n .catch((err) => {\n console.log(err);\n });\n }", "function requestGetNum(query, callback) {\n\n\t// var url = hostNum + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date, slotValue_solution); \n\n\t// var url = hostNum + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date); \n\n\tvar url = hostNum + query; \n\n request(url, function(error, response, body) { \n\n \tconsole.log(url); \n console.log('error: ', error); \n console.log('statusCode: ', response && response.statusCode); \n console.log('body: ', body); \n callback(JSON.parse(body)); \n\n }); \n\n\n}", "_request(request) {\n return request\n .set('X-Parse-Application-Id', this.applicationId)\n .set('X-Parse-Master-Key', this.masterKey)\n .set('Accept', 'application/json');\n }", "function requestJobData(event, callback) {\n\t\n var options = { \n\t method: 'GET',\n url: 'https://api.servicem8.com/api_1.0/job/' + event.eventArgs.jobUUID + '.json',\n auth: {\n bearer: event.auth.accessToken\n }\n };\n\n //Make Request to ServiceM8 API\n request(options, function (error, response, body) {\n \n\t if (error) {\n\t\t//Handle Error\n\t\treturn callback(\"Unable to retrieve job [\" + event.eventArgs.jobUUID + \"] [\" + error + \"]\");\n\t }\n\t\n\t//Parse Job Data\n\t var jobData = JSON.parse(body);\n\t\n\t //Success - Return Job JSON as the Response\n callback(null, { \n\t\teventResponse: JSON.stringify(jobData, null, 2)\n\t });\n\t\n });\n\t\n}", "setRequestObjects() {\n const requestScopes = ['openid', 'profile', 'User.Read'];\n const redirectUri = 'msal://redirect';\n\n this.authCodeUrlParams = {\n scopes: requestScopes,\n redirectUri: redirectUri\n };\n\n this.authCodeRequest = {\n scopes: requestScopes,\n redirectUri: redirectUri,\n code: null\n }\n\n this.pkceCodes = {\n challengeMethod: \"S256\", // Use SHA256 Algorithm\n verifier: \"\", // Generate a code verifier for the Auth Code Request first\n challenge: \"\" // Generate a code challenge from the previously generated code verifier\n };\n }", "promiseParams() {\n return {};\n }", "function start() {\n\n gw_job_process.UI();\n gw_job_process.procedure();\n //----------\n gw_com_module.startPage();\n //----------\n gw_com_api.setValue(\"frmOption\", 1, \"rns_fg\", \"SOP\");\n //gw_com_api.filterSelect(\"frmOption\", 1, \"rns_tp\", { memory: \"분류\", unshift: [{ title: \"전체\", value: \"\" }], key: [\"rns_fg\"] }, false, true);\n //----------\n var rns_id = gw_com_api.getPageParameter(\"rns_id\");\n if (rns_id != \"\") {\n try {\n gw_com_api.setValue(\"frmOption\", 1, \"rns_id\", rns_id);\n gw_com_api.setValue(\"frmOption\", 1, \"dept_area\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"rns_tp\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"rns_no\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"rns_nm\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"dept_nm\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"user_nm\", \"\");\n gw_com_api.setValue(\"frmOption\", 1, \"astat\", \"\");\n processRetrieve({});\n } catch (error) {\n\n } finally {\n gw_com_api.setValue(\"frmOption\", 1, \"rns_id\", \"0\");\n }\n }\n\n }", "function buildPdpJson(pdpInputJson, jsonPermitData, appOwner, testappName, userId, partyId, altinnTask) {\n var action = jsonPermitData['Action'];\n var accessSubject = jsonPermitData['AccessSubject'];\n var resource = jsonPermitData['Resource'];\n pdpInputJson = JSON.parse(pdpInputJson);\n\n //Loop through action and add to the json input template under Action\n for (var i = 0; i < action.length; i++) {\n var emptyObject = {};\n pdpInputJson.Request.Action[0].Attribute.push(emptyObject);\n pdpInputJson.Request.Action[0].Attribute[i].AttributeId = 'urn:oasis:names:tc:xacml:1.0:action:action-id';\n pdpInputJson.Request.Action[0].Attribute[i].Value = action[i];\n pdpInputJson.Request.Action[0].Attribute[i].DataType = 'http://www.w3.org/2001/XMLSchema#string';\n }\n\n //Loop through access Subject and add to the json input template under AccessSubject\n for (var i = 0; i < accessSubject.length; i++) {\n var value = '';\n var emptyObject = {};\n pdpInputJson.Request.AccessSubject[0].Attribute.push(emptyObject);\n switch (accessSubject[i]) {\n case 'urn:altinn:org':\n value = appOwner;\n break;\n case 'urn:altinn:userid':\n value = userId;\n break;\n }\n pdpInputJson.Request.AccessSubject[0].Attribute[i].AttributeId = accessSubject[i];\n pdpInputJson.Request.AccessSubject[0].Attribute[i].Value = value;\n }\n\n //Loop through Resource array and add to the json input template under resources\n for (var i = 0; i < resource.length; i++) {\n var value = '';\n var emptyObject = {};\n pdpInputJson.Request.Resource[0].Attribute.push(emptyObject);\n switch (resource[i]) {\n case 'urn:altinn:org':\n value = appOwner;\n break;\n case 'urn:altinn:app':\n value = testappName;\n break;\n case 'urn:altinn:partyid':\n value = partyId;\n break;\n case 'urn:altinn:task':\n value = altinnTask;\n break;\n case 'urn:altinn:appresource':\n value = 'events';\n break;\n }\n pdpInputJson.Request.Resource[0].Attribute[i].AttributeId = resource[i];\n pdpInputJson.Request.Resource[0].Attribute[i].Value = value;\n }\n return pdpInputJson;\n}", "function req2qpara(req, opts) { // Qv (old: (qp, req))\n var qp = this;\n var extype = {\"arr\": function () {}, \"obj\": function () {}};\n var parr = [];\n var q = req.query;\n if (!q) { return parr; }\n var p = qp.params;\n if (!p) { return parr; }\n function isfunc(v) {\n return (typeof v == 'function') ? 1 : 0;\n }\n //if (Array.isArray(p)) {type = \"arr\"; }\n p.forEach(function (k) {\n var v = q[k]; // By default grab from query\n if (!v && qp.defpara) {\n v = qp.defpara[k];\n if (Array.isArray(v)) {\n \n //parr = parr.concat(v);\n\tv.forEach((val) => {\n\t //if (typeof val == 'function') { parr.push(val()); }\n\t //else { parr.push(val); }\n\t parr.push(isfunc(val) ? val() : val);\n\t});\n\treturn;\n }\n }\n if (!v) { console.log(\"req2qpara: Warning: No value from query or defaults: \"+k); }\n parr.push(isfunc(v) ? v() : v);\n });\n return parr;\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 }", "function processApprRejRequestjavaERPInt (reqType, docType, userdetails, notID, ApprovalComments, reqBuffer, callback)\n{\n var actionType, deviceID, responderid ; //, docType = \"PR\" ;\n\n\tif (userdetails)\n\t{\n\t\tdeviceID = userdetails.DUID ;\n\t\tresponderid = userdetails.userID ;\n\t}\n\t\n getCurrentDateERPFormat (function (cTime)\n {\n if (reqType == 1) actionType = \"APPROVE\" ;\n else if (reqType == 2) actionType = \"REJECT\" ;\n\n if (!deviceID) deviceID = \"UNKN-123\" ;\n\n\t\t//Approve request packet\n\t\tvar req = new Object () ;\n\t\treq.ApproveRejectReq = Object () ;\n\t\treq.ApproveRejectReq.TID = Math.floor(Math.random()*9000) + 1000 ;\n\t\treq.ApproveRejectReq.RESPONDERID = responderid ;\n\t\treq.ApproveRejectReq.ACTIONDATE = cTime;\n\t\treq.ApproveRejectReq.ACTION = actionType;\n\t\treq.ApproveRejectReq.DOCUMENTTYPE = docType ;\n\t\treq.ApproveRejectReq.NID = notID ;\n\t\treq.ApproveRejectReq.DEVICEID = deviceID ;\n\t\treq.ApproveRejectReq.NOTE = ApprovalComments ;\n\t\treq.ApproveRejectReq.FWDTOUSER = \"\" ;\n\t\tJSONdata = JSON.stringify(req);\n\t\twinston.log (\"debug\", \"JSON data to send is [\" + JSONdata + \"]\\n\") ;\n\n try\n {\n\t\t\tvar options = {\n\t\t\t\thost: define.javaERPIntHost,\n\t\t\t\tport: define.javaERPIntPort,\n\t\t\t\tpath: define.javaERPIntPath,\n\t\t\t\t//auth: 'shepard:eatest77',\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Accept': 'application/json',\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'Content-Length': Buffer.byteLength(JSONdata),\n\t\t\t\t}\t\t\t\n\t\t\t};\n\t\t\t\t\n\t\t\t//Creating the request with the Server by posting the host, post method, function to be called and port no.\n\t\t\tvar reqClient = http.request(options, function(res)\t\n\t\t\t{\n\t\t\t\tvar str = '';\n\t\t\t\tres.on('data', function (chunk) {\n\t\t\t\t\tstr += chunk;\n\t\t\t\t});\n\t\t\t\tres.on('end', function () {\n\t\t\t\t\twinston.log(\"debug\", res.statusCode + \"\\n\");\n\t\t\t\t\twinston.log(\"debug\", res.headers);\n\t\t\t\t\t\twinston.log(\"debug\", \"str is ... [\" + str + \"]\\n\");\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tvar jsonrequest = JSON.parse(str);\n\t\t\t\t\t\tif (jsonrequest[\"ApproveRejectRes\"])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twinston.log (\"debug\", \"ApproveRejectRes response recieved...\\n\") ;\n\t\t\t\t\t\t\tif (jsonrequest[\"ApproveRejectRes\"].Status.Code == \"200\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\twinston.log (\"debug\", \"Succesfully processed the Approve / Reject request...\\n\") ;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\twinston.log (\"debug\", \"Error while processing the Approve / Reject request...\\n\") ;\n\t\t\t\t\t\t\t\twinston.log (\"debug\", \"Error is ... [\" + jsonrequest[\"ApproveRejectRes\"].Status.Description + \"]...\\n\") ;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twinston.log (\"debug\", \"ApproveRejectRes not recvd..\\n\") ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e)\n\t\t\t\t\t{\n\t\t\t\t\t\twinston.log (\"debug\", \"Error while processing the Approve / Reject request...\\n\") ;\n\t\t\t\t\t\t// winston.log (\"debug\", \"Error is ... [\" + jsonrequest[\"ApproveRejectRes\"].Status.Description + \"]...\\n\") ;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}).on('error', function(e)\n {\n winston.error(\"debug\", e);\n });\n\n callback (0, \"SUCCESS\") ; // For always success and send request after sending response\n\n\t\t\t//Posts the data to the Server\n\t\t\treqClient.write(JSONdata);\n\t\t\treqClient.end();\n\t\t}\n catch (e)\n { // Error\n winston.log (\"debug\", \"Unable to get the response from the java ERP interface server ...\\n\") ;\n //callback (1, \"ERROR\") ; // For always success and send request after sending response\n callback (0, \"SUCCESS\") ; // For always success and send request after sending response\n }\n }) ;\n}", "function getAssociatedParkingGroupsRequestHandle() {\n var getAssociatedParkingGroupsRequestHandle = {\n \"messageid\": \"da4067d5-7532-40d1-8763-9f19f02d4f9e\",\n \"responsetopic\": \"api.reply.interface\",\n \"request\": {\n \"instanceid\": \"75b3e303-ec4f-4643-b483-f98d975a5d24\",\n \"requestid\": \"291ef868-2bd0-4350-ac87-3591039bb397\",\n \"timestamp\": \"2017-07-12T02:33:25.504Z\",\n \"type\": \"associatedParkingGroups\",\n \"model\": \"getSensorHistoryFromTo\",\n \"action\": \"CAN_READ\",\n \"user\": \"0be386cc-2cca-4a1c-9a07-0e5a9bc2306c\",\n \"orgprops\": {\n \"orgid\": \"d8547b37-95ba-410d-9382-0b190d951332\"\n },\n \"siteprops\": {\n \"siteid\": \"d8547b37-95ba-410d-9382-0b190d951332\"\n },\n \"configprops\": {\n \"policyid\": \"d8547b37-95ba-410d-9382-0b190d951332\",\n\n }\n }\n };\n return getAssociatedParkingGroupsRequestHandle;\n}", "function GetInitObject()\n{\n var in_file = system.args[1];\n var out_file = system.args[2];\n\n var fs = require('fs');\n var in_string = fs.read(in_file);\n var in_object = JSON.parse(in_string);\n\n in_object.phantomjs_output_tunnel_file = out_file;\n return in_object;\n}", "function committify(proc) {\n return {\n step: \"Nomination\"\n , Process: proc.key\n , Type: proc.value.Type\n }\n ;\n }", "function sageRequest(res, input) {\n console.log(\"request sent\");\n var answer = null;\n var calc = \"print latex(\" + input + \")\";\n request({\n \turl: \"http://aleph.sagemath.org/service\",\n \tmethod: \"POST\",\n form: { \"code\": calc }\n }, function (error, response, body) {\n \t if (!error && response.statusCode === 200) {\n \t var calculation = JSON.parse(body);\n \t answer = \"$$\" + calculation.stdout + \"$$\";\n console.log(answer);\n \t } else {\n \t console.log(body);\n \t console.log(error);\n \t console.log(response.statusCode);\n \t console.log(response.statusText);\n \t }\n });\n}", "_onBrokerRequest(req, res) {\n const json = req.body;\n // Find the rending location. Default to csr if not specified\n const renderingLocation = json.class && (json.class === \"ssr_session\") ?\n SpawnerTypes_1.RenderingLocation.Server : SpawnerTypes_1.RenderingLocation.Client;\n const sessionToken = json.params ? json.params.sessionToken : null;\n const modelSearchDirectories = json.params ? json.params.modelSearchDirectories : null;\n const modelFile = json.params ? json.params.model : null;\n const spawnConfig = SpawnerTypes_1.SpawnConfig.createBrokerConfig(res, renderingLocation, sessionToken, modelSearchDirectories, modelFile);\n this._spawnScServer(spawnConfig);\n }", "start(pid,command,json) {\n\t\tlet self=this;\n\t\tif(self[command]&&typeof self[command] === 'function') {\n\n\t\t\t/*\n\t\t\t * Pass the json through the var processor\n\t\t\t */\n\n\t\t\tjson=JSON.parse(self.queue.templateVars(JSON.stringify(json)));\n\t\t\t/*\n\t\t\t * Execute\n\t\t\t */\n\t\t\tself[command](pid, json);\n\t\t} else {\n\t\t\tself.queue.finished(pid,self.queue.DEFINE.FIN_ERROR,'No such command ['+command+']');\n\t\t}\n\t}", "async function makerequest() {\r\n \r\n}", "constructor(input, init = {}) {\n // TODO support `input` being a Request\n this[urlSym] = input;\n\n if (!(init.headers instanceof Headers)) {\n this[rawHeadersSym] = init.headers;\n } else {\n this[headersSym] = init.headers;\n }\n this[methodSym] = init.method || 'GET';\n\n if (init.body instanceof ReadableStream || init.body instanceof FormData) {\n this[bodySym] = init.body;\n } else if (typeof init.body === 'string') {\n this[_bodyStringSym] = init.body;\n } else if (isBufferish(init.body)) {\n this[bodySym] = new StringReadable(init.body);\n }\n }", "function request(verb, route, jsonInput){\n const url = localURL.concat(route);\n const param={\n headers:{\n \"content-type\":\"application/json; charset=UTF-8\"\n },\n body:JSON.stringify(jsonInput),\n method:verb\n };\n return fetch(url,param)\n .then(data=>{return data.json()})\n //.then(res=>{console.log(res)})\n //.catch(error=>console.log(error))\n}", "function makeParticleRequest( functionName, postData, postType, callback ){\n\tif ( typeof callback == 'undefined' ){\n\t\tvar callback = function( data ){ return; }\n\t}\n\n\tlet fetchData = {\n\t\t\tmethod: 'POST',\n\t\t\t// credentials: 'same-origin',\n\t\t\t// mode: 'same-origin',\n\t\t\tbody: \"\",\n\t\t\theaders: {\n\t\t\t 'Accept': 'application/json',\n\t\t\t\t// 'Content-Type': 'application/json',\n\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t\t'Authorization': 'Bearer ' + particleLightKey\n\t\t\t}\n\t\t};\n\n\tif ( postType == 'variable' ){\n\t\tfetchData.method = 'GET';\n\t}else if ( postType == 'function' ){\n\t\tfetchData.method = 'POST';\n\t}\n\n\t//\n\t// Prepare to send the data to Particle for processing\n\tif ( typeof postData === 'object' && postData !== null && Object.keys( postData ).length > 0 ){\n\t\tfetchData.body = [];\n\t\tfor (var k in postData) {\n\t\t\tfetchData.body.push(encodeURIComponent(k) + \"=\" + encodeURIComponent( postData[k] ));\n\t\t}\n\t\tfetchData.body = fetchData.body.join(\"&\");\n\t}\n\n\treturn fetch('https://api.particle.io/v1/devices/' + particleDeviceID + '/' + encodeURIComponent( functionName ), fetchData )\n\t\t.then((response) => response.json())\n\t\t.then((responseJson) => {\n\t\t\t// console.log( responseJson );\n\t\t\tif ( postType == 'variable' ){\n\t\t\t\tcallback( responseJson.result );\n\t\t\t\treturn;\n\t\t\t}else if ( postType == 'function' ){\n\t\t\t\tcallback( responseJson.return_value );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// callback( responseJson.result );\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.error(error);\n\t\t\treturn;\n\t\t});\n}", "function formRequest(pointArr) {\n var startDate = document.getElementById('fromDate').value;\n var endDate = document.getElementById('toDate').value;\n var dataType = document.getElementById('dataType').value;\n var operation = document.getElementById('operation').value;\n var interval = document.getElementById('interval').value;\n\n request = \n {\n \"TimeInterval\": {\n \"From\": startDate,\n \"To\": endDate\n },\n \"Region\": {\n \"Type\": \"PointRegion\",\n \"Points\": [\n ]\n },\n \"Dataset\": dataType,\n \"Statistics\": {\n \"Operation\": \"cNone\",\n \"Interval\": interval,\n \"GetAccuracies\": false\n }\n }\n\n for (var i = 0; i < pointArr.length; i++) {\n request['Region']['Points'].push({\"Longitude\": parseFloat(pointArr[i][1]),\"Latitude\": parseFloat(pointArr[i][0])});\n }\n\n console.log(request);\n getPointReg(request);\n}", "static initialize(obj, name, programId, subLedgerId, value, recipientIntegrationId, transactionUUID) { \n obj['name'] = name;\n obj['programId'] = programId;\n obj['subLedgerId'] = subLedgerId;\n obj['value'] = value;\n obj['recipientIntegrationId'] = recipientIntegrationId;\n obj['transactionUUID'] = transactionUUID;\n }", "function symptoms(agent) {\n var body=JSON.stringify(request.body);\n console.log(body);\n var obj = JSON.parse(body);\n let symptoms=obj.queryResult.queryText;\n // use outputContext[2] when testing in dialogflow console\n //let insuranceNumber=obj.queryResult.outputContexts[2].parameters.Insurance_Number; \n let insuranceNumber=obj.queryResult.outputContexts[6].parameters.Insurance_Number;\n console.log(insuranceNumber);\n console.log(symptoms);\n let data = '';\n let url = encodeURI(`https://hook.integromat.com/avnuxe3kkygvng5g6c2f8f4eq2sjilss?Symptoms=` + symptoms);\n\treturn new Promise((resolve, reject) => { \n const request = https.get(url, (res) => {\n res.on('data', (d) => {\n data += d;\n console.log(JSON.stringify(data));\n var answer=JSON.stringify(data);\n if (answer.includes('no diagnosis')){\n \t agent.add(`Sorry I could determine a diagnosis.`);\n agent.add(`Please propose a date when you have time to see a doctor. The date has to be in the following format: DD/MM/YYYY HH:mm`);\n }else{\n \treturn new Promise((resolve, reject) => {\n \tconsole.log(`Start process`);\n \tlet url = encodeURI(`https://hook.integromat.com/38joojtm894r9ag9mlpc623y1ouu13y4?InsuranceNumber=`+ insuranceNumber + `&Symptoms=` + symptoms + `&dateTime=nodate`);\n \t\tagent.add(`Thank you, please check your e-mail to see which further actions are required`);\n \t\t\tagent.add(`I hope I could help. Get well soon and until next time.`);\n console.log(`Request sent`);\n \tconst request = https.get(url, (res) => {\n \t\t\tres.on('data', (d) => {\n \t\tdata += d;\n \t\t\t});\n \t\t\tres.on('end', resolve);\n \t\t\t});\n \t\t\trequest.on('error', reject);\n \t\t\t\t});\n }\n });\n res.on('end', resolve);\n });\n request.on('error', reject);\n });\n }", "function getParams(request, parsed) {\n return new Promise(function(resolve, reject) {\n if (request.method == 'POST') {\n var body = '';\n \n request.on('data', function (chunk) {\n body += chunk;\n\n // Too much POST data, kill the connection!\n // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB\n if (body.length > 1e6) {\n request.connection.destroy();\n reject('Too much data');\n }\n });\n\n request.on('end', function () {\n resolve(JSON.parse(body || \"{}\"));\n });\n } else if (request.method == 'GET') {\n resolve(parsed.query);\n }\n });\n}", "function AppsAjaxRequest( requestUrl, hashParms, successClosure, requestMethod )\n{\n\tif ( requestMethod == null ) requestMethod = 'post';\n\n\t// ensure session ID is present if we're posting\n\tif ( requestMethod.toLowerCase() == 'post' ) {\n\t\tif ( !( 'sessionid' in hashParms ) ) {\n\t\t\thashParms[ 'sessionid' ] = g_sessionID;\n\t\t}\n\t}\n\n\tnew Ajax.Request( requestUrl,\n\t\t{\n\t\t\trequestHeaders: { 'Accept': 'application/json' },\n\t\t\tmethod: requestMethod,\n\t\t\tparameters: hashParms,\n\t\t\tonSuccess: function( transport )\n\t\t\t{\n\t\t\t\tvar results = transport.responseJSON;\n\t\t\t\tif ( results )\n\t\t\t\t{\n\t\t\t\t\tsuccessClosure( results );\n\t\t\t\t}\n\t\t\t}\n\t\t} );\n}", "function xmlRequestNoProcessing(serviceString,paraString) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.responseType = 'json';\n\n xmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState==4 && xmlhttp.status==200)\t{\n console.log(xmlhttp.response);\n }\n };\n\n console.log(serviceString + paraString);\n xmlhttp.open(\"POST\",serviceString + paraString,true);\n xmlhttp.send();\n}", "enterCallParameters(ctx) {\n\t}", "systemManagementRequest(req, params) {\n return new Promise(async (resolve, reject) => {\n let s = new soapGen();\n let request = s.generateSoapRequest(req, params);\n let netReq = new httpRequest(this.url, this.SystemManagement);\n\n // make call\n netReq.POST(request)\n .then(response => {resolve(response)})\n .catch(response => {reject(response)});\n });\n }", "function processApprRejRequest (reqType, userdetails, notID, ApprovalComments, reqBuffer, callback)\n{\n\tvar querystr, url;\n\tvar actionType ;\n\tvar deviceID = userdetails.DUID ;\n\tvar docType = \"PR\" ;\n\n\tgetCurrentDateERPFormat (function (cTime)\n\t{\n\t\tif (reqType == 1) actionType = \"APPROVE\" ;\n\t\telse if (reqType == 2) actionType = \"REJECT\" ;\n\n\t\tif (!deviceID) deviceID = \"UNKN-123\" ;\n\t\n\t\tquerystr = \"P_RESPONDER_ID=\" + userdetails.userID + \"&P_ACTION_DATE=\" + cTime + \"&P_ACTION=\" + actionType \n\t\t\t+ \"&P_DOCUMENT_TYPE=\" + docType + \"&P_NID=\" + notID + \"&P_DEVICE_ID=\" + deviceID + \"&P_NOTE=\" + ApprovalComments + \"&sn.content_type=text/tab-separated-values\" ;\n\t\twinston.log (\"debug\", \"username is \" + userdetails.username) ;\n\t\twinston.log (\"debug\", \"userid is \" + userdetails.userID) ;\n\t\n\t\turl = \"https://\" + username + \":\" + password + \"@\" + hostname + path + \"?\" + querystr ;\n\t\twinston.log (\"debug\", \"The final url is \" + url) ;\n\n\t\ttry \n\t\t{\n\t\t\thttps.get(url, function(res) \n\t\t\t{\n\t\t\t\twinston.log(\"debug\", \"statusCode: \", res.statusCode);\n\t\t\t\twinston.log(\"debug\", \"headers: \", res.headers);\n\n\t\t\t\tres.on('data', function(d) \n\t\t\t\t{\n\t\t\t\t\tprocess.stdout.write(d);\n\t\t\t\t\tvar jsonrequest = JSON.parse(d);\n\t\t\t\t\twinston.log (\"debug\", \"Parse SUCCESS\") ;\n\t\t\t\t\twinston.log (\"debug\", \"Request for json X_RET_CODE\" + jsonrequest[0].X_RET_CODE) ;\n\t\t\t\t\twinston.log (\"debug\", \"Request for json X_RET_MSG\" + jsonrequest[0].X_RET_MSG) ;\n\t\t\t\t\tif (jsonrequest[0].X_RET_CODE == 'S')\n\t\t\t\t\t{\n\t\t\t\t\t\twinston.log (\"debug\", \"Success status from Snap Logic...\\n\") ;\n\t\t\t\t\t\t//callback (0, \"SUCCESS\") ; // For always success and send request after sending response\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\twinston.log (\"debug\", \"Error status from Snap Logic...\\n\") ;\n\t\t\t\t\t\t//callback (1, \"ERROR\") ; // For always success and send request after sending response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t}).on('error', function(e) \n\t\t\t{\n\t\t\t\twinston.error(\"debug\", e);\n\t\t\t\t//callback (1, \"ERROR\") ; // For always success and send request after sending response\n\t\t\t});\n\t\t\tcallback (0, \"SUCCESS\") ; // For always success and send request after sending response\n\t\t}\n\t\tcatch (e)\n\t\t{\t// Error\n\t\t\twinston.log (\"debug\", \"Unable to get the response from the Snap Logic server ...\\n\") ;\n\t\t\t//callback (1, \"ERROR\") ; // For always success and send request after sending response\n\t\t\tcallback (0, \"SUCCESS\") ; // For always success and send request after sending response\n\t\t}\n\t}) ;\n}", "function _request(request, successCallback, errorCallback) {\n var lmSuccess = function (info) {\n var url = _getConnectionURL(info);// + (request.path ? (\"/\" + request.path) : \"\");\n var operation = request.method;\n if (operation == 'undefined' || operation == null) {\n operation = \"GET\";\n }\n if (cordova.require(\"cordova/platform\").id.indexOf(\"windows\") === 0) {\n sap.AuthProxy.sendRequest(operation,\n url,\n { \"Accept\": \"application/json\", \"Content-Type\": \"application/json\", \"X-SMP-APPCID\": info.applicationConnectionId },\n request.data,\n function (response) {\n successCallback(response);\n },\n function (response) {\n errorCallback(response);\n },\n info.registrationContext.mobileUser,\n info.registrationContext.password,\n 0,\n null\n );\n } else {\n sap.Logon.getConfiguration( function(jsonconfig){\n \n var authConfig = JSON.parse(jsonconfig);\n \n sap.AuthProxy.sendRequest2(operation,\n url,\n { \"Accept\": \"application/json\", \"Content-Type\": \"application/json\" },\n request.data,\n function (response) {\n successCallback(response);\n },\n function (response) {\n errorCallback(response);\n },\n 0,\n authConfig\n );\n }, function(){}, \"authentication\");\n\n }\n\n }\n\n var lmError = function () {\n errorCallback({\n statusCode: 0,\n statusText: \"Logon failed\"\n });\n }\n\n sap.Logon.unlock(lmSuccess, lmError);\n \n }", "fetchdata(method, params) {\n return _.extend(this.fetchInit, {\n body: JSON.stringify({\n id: uniqueId(),\n jsonrpc: '2.0',\n method,\n params,\n }),\n });\n }", "function get_engine_data(input, callback){\n\tconst options = {\n\t url: \"http://ec2-35-163-184-27.us-west-2.compute.amazonaws.com:8080/Engine/new\",\n\t method: 'POST',\n\t headers: {\n\t\t 'Accept': 'application/json',\n\t\t 'Accept-Charset': 'utf-8',\n\t\t 'User-Agent': 'SJA-Engine'\n\t\t },\n\t body: JSON.stringify(input)\n\t};\n setting = request(options, (error, res, body) =>{\n \t//Wait for the respond from j-easy engine\n\t\tif(error){\n\t\t\tconsole.error(error);\n\t\t\treturn;\n\t\t}\n\t\t//setting = body;\n\t \tcallback(body);\n\t\t//console.log(\"==Repond content:\\n\" + setting);\n \t});\n\n}", "function appRequest(port, dataUrl, genomeID, mergeFlag, locusString, trackName) {\n\n // be good and remove the previous cytoscape script element\n // although, based on debugging, i'm not sure this really does anything\n var oldScript = document.getElementById(SCRIPT_ELEMENT_ID);\n if (oldScript) {\n oldScript.parentNode.removeChild(oldScript);\n }\n\n var localURL;\n sessionURL = dataUrl;\n genome = genomeID;\n locus = locusString;\n merge = mergeFlag;\n name = trackName;\n\n if(dataUrl) {\n localURL = \"http://127.0.0.1:\" + port + \"/load?callback=callBack();\";\n localURL += \"&file=\" + dataUrl;\n if (genomeID) {\n localURL += \"&genome=\" + genomeID;\n }\n if (locusString) {\n localURL += \"&locus=\" + locusString;\n }\n if (mergeFlag) {\n localURL += \"&merge=\" + mergeFlag;\n }\n if (trackName) {\n localURL += \"&name=\" + trackName;\n }\n }\n else {\n localURL = \"http://127.0.0.1:\" + port + \"/goto?callback=callBack();&locus=\" + locusString;\n }\n // create new script\n var newScript = document.createElement(\"script\");\n newScript.id = SCRIPT_ELEMENT_ID;\n newScript.setAttribute(\"type\", \"text/javascript\");\n newScript.setAttribute(\"src\", localURL);\n\n // add new script to document (head section)\n var head = document.getElementsByTagName(\"head\")[0];\n head.appendChild(newScript);\n\n // disable link\n // we do this because some browsers\n // will not fetch data if the url has been fetched in the past\n //disableLink(\"1\");\n\n // set timeout - handler for when IGV is not running\n timeoutVar = setTimeout(\"timeoutHandler()\", 2000);\n\n}", "requestValidation(){\r\n this.server.route({\r\n method: 'POST',\r\n path: '/requestValidation',\r\n handler: async (request, h) => {\r\n //Validates payload\r\n if(!request.payload){\r\n throw Boom.badRequest(\"You should provide a valid JSON request\");\r\n }\r\n\r\n //Address is required\r\n let address = request.payload.address;\r\n if(!address || address.length==0){\r\n throw Boom.badRequest(\"You should provide a valid address property in the JSON request\");\r\n }\r\n\r\n //returns a request object\r\n let requestObj = new RequestObject.RequestObject();\r\n requestObj.walletAddress = address;\r\n requestObj.requestTimeStamp = (new Date().getTime().toString().slice(0,-3));\r\n requestObj.message = requestObj.walletAddress+ \":\"+ requestObj.requestTimeStamp+ \":\"+ \"starRegistry\";\r\n\r\n requestObj = this.mempoolService.addARequestToMempool(requestObj);\r\n\r\n return requestObj;\r\n }\r\n });\r\n }", "function SIMPL__SendRequest_JSON( eString_URI, eJSON_Request, fCallback_Success, fCallback_Error )\n{\n\tvar eXHR = new XMLHttpRequest();\n\tvar eString_JSON = JSON.stringify( eJSON_Request );\n\n\teXHR.open( \"GET\", ( eString_URI + \"?JSON=\" + encodeURIComponent( eString_JSON ) ), true );\n\teXHR.onload = function ( eProgressEvent )\n\t\t{\n\t\t\tif (eXHR.readyState === 4)\n\t\t\t{\n\t\t\t\tif (eXHR.status === 200)\n\t\t\t\t{\n\t\t\t\t\tconsole.log( eXHR.responseText );\n\t\t\t\t\tvar eJSON_Response = JSON.parse( eXHR.responseText );\n\n\t\t\t\t\tif ( fCallback_Success != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tfCallback_Success( eJSON_Response, eProgressEvent, eXHR );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlocal_SIMPL__JSON__UpdateDebugView( eString_JSON, eXHR.responseText );\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\tif ( fCallback_Error != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tfCallback_Error( eString_URI, eJSON_Request, eProgressEvent, eXHR );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.error( \"SendRequest - not 200 : \" );\n\t\t\t\t\t\tconsole.error( eXHR.statusText );\n\t\t\t\t\t\tconsole.error( eString_URI );\n\t\t\t\t\t\tconsole.error( eJSON_Request );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconsole.log( eProgressEvent );\n\t\t\t}\n\t\t};\n\teXHR.onerror = function ( eProgressEvent )\n\t\t{\n\t\t\tif ( fCallback_Error != null )\n\t\t\t{\n\t\t\t\tfCallback_Error( eString_URI, eJSON_Request, eProgressEvent, eXHR );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconsole.error( \"SendRequest - onerror : \" );\n\t\t\t\tconsole.error( eXHR.statusText );\n\t\t\t\tconsole.error( eString_URI );\n\t\t\t\tconsole.error( eJSON_Request );\n\t\t\t}\n\t\t};\n\teXHR.onabort = eXHR.onerror;\n\teXHR.ontimeout = eXHR.onerror;\n\teXHR.send( null );\n}", "createBlockRequestResponse(data){\n\n\n\n\t\t}", "function makeAppropriateJSON() {\n var langFrom = $(langFromInput).val();\n var langTo = $(langToInput).val();\n var startTime = formDatetimeDataModule.getStartTime();\n var finishTime = formDatetimeDataModule.getFinishTime();\n var sex = $(genderInput).val();\n var qualification = $(qualificationInput).val();\n var subject = $(jobSubject).val();\n var type = $(jobType).val();\n var address = $(meetingAddress).val();\n var personName = $(meetingPersonName).val();\n var phoneNumber = $(meetingPhoneNumber).val();\n var extraInfo = $(meetingEtraInfo).val();\n var contactId = $(meetingId).val();\n var accessibilityValue = accessibility;\n var resObject;\n\n resObject = {\n job: {\n lang_from_id: langFrom,\n lang_to_id: langTo,\n start_time: startTime,\n finish_time: finishTime,\n sex: sex,\n qualification_id: qualification,\n subject: subject,\n assignment_type: type,\n accessibility: accessibilityValue\n }\n };\n\n if ($(attendersList).length) {\n resObject.job.attenders_array = makeAttendersAjax();\n }\n\n if (type === \"2\") {\n resObject.job.contact_attributes = {\n id: contactId,\n address: address,\n extra: extraInfo,\n name: personName,\n phone: phoneNumber\n };\n }\n\n return JSON.stringify(resObject);\n }", "function QueryExec(param)\r\n{\r\n \r\n if (is_r() && $v('service') == '')\r\n {\r\n alert('You must specify \"Query Service Endpoint\"!');\r\n return;\r\n }\r\n // if it is compile, clear the etalon\r\n if (param == 'c')\r\n $('etalon').innerHTML = '';\r\n $('res_area').innerHTML = 'Sending query...';\r\n\r\n // Determine format, if it is table the we need json results\r\n var format = $v('format');\r\n if (!format) format = 'text/html';\r\n if (format == 'application/isparql+table')\r\n format = 'application/sparql-results+json'; \r\n var content_type = 'application/x-www-form-urlencoded';\r\n \r\n var ReqHeaders = {'Accept':format,'Content-Type':content_type};\r\n\r\n // generate the request body\r\n var body = function()\r\n {\r\n var body = '';\r\n \r\n // parameters we will send\r\n var params = ['default-graph-uri','query','format','maxrows'];\r\n // if it is remote add service endpoint\r\n if (is_r())\r\n params.push('service');\r\n else\r\n params.push('should-sponge');\r\n \r\n for(var i = 0; i < params.length; i++)\r\n {\r\n if (!(params[i] == 'default-graph-uri' && $v('default-graph-uri') == '') && // Patch ot skip default graph if it is empty;\r\n !($(params[i]).type == 'checkbox' && !$(params[i]).checked)) // Skip unchecked checkboxes\r\n {\r\n if (body != '') \r\n body += '&'; \r\n body += params[i] + '=';\r\n if (params[i] == 'format') // If it is format get the overwritten value\r\n {\r\n body += encodeURIComponent(format); \r\n }\r\n else if ($(params[i]).type == 'radio')\r\n {\r\n for(var n = 0; n < $(params[i]).form.elements[$(params[i]).name].length;n++)\r\n if ($(params[i]).form.elements[$(params[i]).name][n].checked)\r\n body += encodeURIComponent($(params[i]).form.elements[$(params[i]).name][n].value); \r\n }\r\n else\r\n body += encodeURIComponent($v(params[i])); \r\n }\r\n }\r\n \r\n // get all checked named_graphs from named graphs tab\r\n named_graphs = document.getElementsByName('named_graph_cbk');\r\n \r\n if(named_graphs && named_graphs.length > 0)\r\n {\r\n for(var n = 0; n < named_graphs.length; n++)\r\n {\r\n // if it is checked, add to params too\r\n if (named_graphs[n].checked)\r\n {\r\n var named_graph_value = $v('named_graph_'+named_graphs[n].value);\r\n if (named_graph_value != '')\r\n {\r\n if (body != '') \r\n body += '&'; \r\n body += 'named-graph-uri=';\r\n body += encodeURIComponent(named_graph_value); \r\n }\r\n }\r\n }\r\n }\r\n \r\n return body;\r\n };\r\n\r\n //RESULT PROCESSING\r\n var callback = function(data,headers) \r\n { \r\n // Clear the tabls\r\n OAT.Dom.unlink($('res_container'));\r\n OAT.Dom.unlink($('result'));\r\n OAT.Dom.unlink($('request'));\r\n OAT.Dom.unlink($('response'));\r\n\r\n $('res_area').innerHTML = '';\r\n var tabres_html = '';\r\n \r\n // Make the tabs \r\n tabres_html += '<ul id=\"tabres\">';\r\n tabres_html += '<li id=\"tabres_result\">Result</li><li id=\"tabres_request\">Raw Request/Permalinks</li><li id=\"tabres_response\">Raw Response</li>';\r\n tabres_html += '</ul>';\r\n tabres_html += '<div id=\"res_container\"></div>';\r\n tabres_html += '<div id=\"result\">' + data + '</div>';\r\n $('res_area').innerHTML += tabres_html;\r\n \r\n var body_str = body();\r\n var request = '';\r\n request += '<div id=\"request\"><pre>';\r\n request += 'POST ' + endpoint + ' HTTP 1.1\\r\\n';\r\n request += 'Host: ' + window.location.host + '\\r\\n';\r\n if (ReqHeaders) {\r\n\t\t for (var p in ReqHeaders) {\r\n\t\t request += p + ': ' + ReqHeaders[p] + '\\r\\n';\r\n\t\t }\r\n\t\t}\r\n request += 'Content-Length: ' + body_str.length + '\\r\\n';\r\n request += '\\r\\n';\r\n request += body_str.replace(/&/g,'&amp;').replace(/</g,'&lt;');\r\n request += '<br/><br/><a href=\"'+endpoint+body_str+'\">direct link to result</a>&nbsp;-&nbsp;<a href=\"http://tinyurl.com/create.php?url=http://'+window.location.host+endpoint+body_str+'\"><i>create tinyurl</i></a>'; \r\n if (!body_str.match(/format=application%2Fsparql-results%2Bxml/))\r\n { request += '<br/><a href=\"'+endpoint+body_str.replace(/format=.*(&|$)/,'format=application%2Fsparql-results%2Bxml').replace(/\\?maxrows=.*/,'')+'\">direct link to query results as sparql/xml (no max rows)</a>';\r\n request += '&nbsp;-&nbsp;<a href=\"http://tinyurl.com/create.php?url=http://'+window.location.host+endpoint+body_str.replace(/format=.*(&|$)/,'format=application%2Fsparql-results%2Bxml').replace(/\\?maxrows=.*/,'')+'\"><i>create tinyurl</i></a>'}\r\n request += '<br/><a href=\"'+body_str.replace(/query/,'?query')+'\">direct link to query form filled with this query</a>'; \r\n request += '&nbsp;-&nbsp;<a href=\"http://tinyurl.com/create.php?url=http://'+window.location.host+endpoint+body_str+'\"><i>create tinyurl</i></a>'; \r\n request += '<br/><a href=\"'+body_str.replace(/query/,'?query')+'&go=1\">direct link to query form filled with this query and immediately run query</a>'; \r\n request += '&nbsp;-&nbsp;<a href=\"http://tinyurl.com/create.php?url=http://'+window.location.host+endpoint+body_str+'&go=1\"><i>create tinyurl</i></a>'; \r\n request += '</div>';\r\n// request += '</pre></div>'; \r\n $('res_area').innerHTML += request; \r\n\r\n var response = '';\r\n response += '<div id=\"response\"><pre>';\r\n response += headers;\r\n response += '\\r\\n';\r\n response += data.replace(/&/g,'&amp;').replace(/</g,'&lt;');\r\n response += '</pre></div>'; \r\n $('res_area').innerHTML += response; \r\n\r\n var tabres = new OAT.Tab (\"res_container\");\r\n tabres.add (\"tabres_result\",\"result\");\r\n tabres.add (\"tabres_request\",\"request\");\r\n tabres.add (\"tabres_response\",\"response\");\r\n tabres.go(0);\r\n\r\n //if it is a special format and param is empty then we postprocess json to draw a table\r\n if ($v('format') == '' && !param)\r\n {\r\n $('result').innerHTML += '<div id=\"grid\"></div>'; \r\n table = find_child_element($('result'),'table');\r\n var grid = new OAT.Grid(\"grid\",0);\r\n load_grid(grid,table);\r\n table.parentNode.removeChild(table);\r\n grid.ieFix();\r\n\t if (typeof grid2 != 'undefined')\r\n grid2.ieFix();\r\n }\r\n else\r\n {\r\n // it is either and error or compile\r\n if (param)\r\n {\r\n $('result').innerHTML = data;\r\n // result too big to post process, just show it\r\n } else if (data.length > 10 * 1024) {\r\n \r\n $('result').innerHTML = '<pre>' + data.replace(/</g,'&lt;') + '</pre>';\r\n // ry to postprocess it \r\n } else {\r\n var shtype = 'xml';\r\n if ($v('format') == 'application/sparql-results+json' || \r\n $v('format') == 'application/javascript' )\r\n shtype = 'javascript';\r\n else if ($v('format') == 'text/html')\r\n shtype = 'html';\r\n $('result').innerHTML = '<textarea name=\"code\" class=\"' + shtype + '\">' + data + '</textarea>';\r\n dp.SyntaxHighlighter.HighlightAll('code',0,0);\r\n }\r\n }\r\n\r\n };\r\n \r\n var endpoint = '';\r\n // it it is not remote or compile send to local sparql endpoint\r\n if (!is_r() && !param)\r\n endpoint = '/sparql/?'\r\n // if it is compile \r\n else if (param == 'c')\r\n endpoint = 'explain.vsp?';\r\n // it must be remote then\r\n else \r\n endpoint = '/library/php/remote.php?';\r\n \r\n\toptObj = {\r\n\t\theaders:ReqHeaders,\r\n\t\ttype:OAT.AJAX.TYPE_TEXT,\r\n\t\t//in case of an error exec the callback also, but give a parameter er\r\n\t\tonerror:function(xhr)\r\n {\r\n var status = xhr.getStatus();\r\n var response = xhr.getResponseText();\r\n\t\t\tvar headers = xhr.getAllResponseHeaders();\r\n\t\t\tvar data = '';\r\n param = 'er';\r\n if (!response)\r\n {\r\n response = 'There was a problem with your request! The server returned status code: ' + status + '<br/>\\n';\r\n response += 'Unfortunately your browser does not allow us to show the error. ';\r\n response += 'This is a known bug in the Opera Browser.<br/>\\n';\r\n response += 'However you can click this link which will open a new window with the error: <br/>\\n';\r\n response += '<a target=\"_blank\" href=\"/sparql/?' + body() + '\">/sparql/?' + body() + '</a>';\r\n }\r\n else \r\n {\r\n data = response.replace(/&/g,'&amp;').replace(/</g,'&lt;');\r\n }\r\n callback('<pre>' + data + '</pre>',headers);\r\n }\r\n\t}\r\n \r\n OAT.AJAX.POST(endpoint, body(), callback, optObj);\r\n}", "function request_inventory(){\n\tvar form = document.getElementById('req_inv');\n var jsonData = formToJson( form );\n\n //alert('in: req');\n\n $.ajax({\n type : \"POST\",\n url : \"/inv_mgt/inventory/create\",\n data : jsonData,\n contentType: \"application/json\",\n success:function(msg){\n \talert('success');\n }\n });\n\n //alert('out: req');\n}", "_dummyRequest(request) {\n console.log(\"\\n--------------------------- request ---------------------------\\n\");\n console.log(JSON.stringify(request, null, 2));\n console.log(\"\\n--------------------------- response ---------------------------\\n\");\n return \"dummy\";\n }", "function makeDataRequest(){ \n\tDatahttpRequest = new XMLHttpRequest(); \n\tDatahttpRequest.onreadystatechange = Datacallback; \n\tDatahttpRequest.open('GET', 'http://192.168.1.1/cgi-bin/TrackerV1Codes/GPSAltData.py');\n\tDatahttpRequest.send(); \n}", "callback(statusCode, requestID, data) { \n if (statusCode === 200) {\n\t\ttry {\n\t\t\tvar jsonData = JSON.parse(data);\n\t\t} catch (e) {\n\t\t\tconsole.log('request #', requestID, ' JSON parse error:', e);\n\t\t\treturn;\n\t\t}\n console.log('request #', requestID, ' has been executed:', JSON.stringify(jsonData, null, 2));\n } else {\n console.log('#', requestID, ': [status: ', statusCode, ', message: ', data, ']');\n } \n }", "function processRequestBody(inputData, params) {\n var requestBody = {},\n missingParams = [],\n paramValue;\n _.forEach(params, function (param) {\n paramValue = _.get(inputData, param.name);\n if (WM.isDefined(paramValue) && (paramValue !== '')) {\n paramValue = Utils.isDateTimeType(param.type) ? Utils.formatDate(paramValue, param.type) : paramValue;\n //Construct ',' separated string if param is not array type but value is an array\n if (WM.isArray(paramValue) && _.toLower(Utils.extractType(param.type)) === 'string') {\n paramValue = _.join(paramValue, ',');\n }\n requestBody[param.name] = paramValue;\n } else if (param.required) {\n missingParams.push(param.name || param.id);\n }\n });\n return {\n 'requestBody' : requestBody,\n 'missingParams' : missingParams\n };\n }", "parseParams() {\n\n let parms = this.omniJsonDef.propSetMap.customAttributes;\n\n // Find the values in the list (don't want to be fussy about the order)\n parms.forEach((val) => {\n if (val.name === \"headers\") {\n this.parms_headers = val.source;\n console.log('Headers = ' + this.parms_headers);\n }\n\n if (val.name === 'values') {\n this.parms_values = val.source;\n console.log('Values = ' + this.parms_values);\n }\n\n if (val.name === 'input') {\n this.parms_input = val.source;\n console.log('Input @ ' + this.parms_input);\n }\n\n if (val.name === 'select') {\n // Note that select defaults to true\n let s = val.source.toUpperCase();\n if (s === 'F' || s === 'FALSE' || s === 'N' || s === \"NO\") {\n this.parms_showSelect = false;\n }\n console.log('Select = ' + String(this.parms_showSelect));\n }\n\n });\n\n }", "function useRequest() {\nvar request = Module['memoryInitializerRequest'];\nvar response = request.response;\nif (request.status !== 200 && request.status !== 0) {\nvar data = tryParseAsDataURI(Module['memoryInitializerRequestURL']);\nif (data) {\nresponse = data.buffer;\n} else {\n// If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That\n// means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place.\n// Look in your browser's devtools network console to see what's going on.\nconsole.warn('a problem seems to have happened with Module.memoryInitializerRequest, status: ' + request.status + ', retrying ' + memoryInitializer);\ndoBrowserLoad();\nreturn;\n}\n}\napplyMemoryInitializer(response);\n}", "function postAssociateRequestHandle() {\n var postAssociateRequestHandle = {\n \"messageid\": \"da4067d5-7532-40d1-8763-9f19f02d4f9e\",\n \"responsetopic\": \"api.reply.interface\",\n \"request\": {\n \"instanceid\": \"75b3e303-ec4f-4643-b483-f98d975a5d24\",\n \"requestid\": \"291ef868-2bd0-4350-ac87-3591039bb397\",\n \"timestamp\": \"2017-07-12T02:33:25.504Z\",\n \"type\": \"policyAssociation\",\n \"model\": \"getSensorHistoryFromTo\",\n \"action\": \"CAN_READ\",\n \"user\": \"0be386cc-2cca-4a1c-9a07-0e5a9bc2306c\",\n \"orgprops\": {\n \"orgid\": \"d8547b37-95ba-410d-9382-0b190d951332\"\n },\n \"siteprops\": {\n \"siteid\": \"d8547b37-95ba-410d-9382-0b190d951332\"\n },\n \"configprops\": {\n \"policyid\": \"string\",\n \"ParkingGroupPolicyLink\": {\n \"parkinggroupid\": \"string\"\n }\n }\n }\n };\n return postAssociateRequestHandle;\n}", "static initialize(obj, created, programID, customerProfileID, type, amount, name, subLedgerID) { \n obj['created'] = created;\n obj['programID'] = programID;\n obj['customerProfileID'] = customerProfileID;\n obj['type'] = type;\n obj['amount'] = amount;\n obj['name'] = name;\n obj['subLedgerID'] = subLedgerID;\n }", "setupRequest(request_body) {\n throw new Error('setupRequest - not implemented');\n }", "function restockRequest() {\n\n\tinquirer.prompt([\n\t\t{\n\t\t\ttype: \"input\",\n\t\t\tname: \"inputId\",\n\t\t\tmessage: \"Please enter the item_id you would like to add.\",\n\t\t},\n\t\t{\n\t\t\ttype: \"input\",\n\t\t\tname: \"inputNumber\",\n\t\t\tmessage: \"How many units of this item would you like to add?\",\n\n\t\t}\n\t]).then(function (addQuantity) {\n\n\t\t//connect to database to and add the quantity to the table.........\n\t\tconnection.query(\"SELECT * FROM products WHERE item_id=?\", addQuantity.inputId, function (err, res) {\n\t\t\tfor (var i = 0; i < res.length; i++) {\n\n\n\n\n\t\t\t\tconsole.log((res[i].stock_quantity, addQuantity.inputNumber));\n\t\t\t\tvar newStock = (res[i].stock_quantity + parseInt(addQuantity.inputNumber));\n\t\t\t\tvar updateId = (addQuantity.inputId);\n\n\n\t\t\t\tconfirmPrompt(newStock, updateId);\n\t\t\t}\n\t\t});\n\t});\n}" ]
[ "0.58154833", "0.5806335", "0.54913676", "0.54202896", "0.52524227", "0.5242344", "0.5211276", "0.51933783", "0.5171736", "0.50880027", "0.5070031", "0.5050982", "0.50502527", "0.5007911", "0.49855408", "0.49679124", "0.4946332", "0.4934465", "0.4902039", "0.4890071", "0.48767397", "0.48708376", "0.48274392", "0.47863668", "0.47756046", "0.47443187", "0.4719737", "0.47119412", "0.4710522", "0.4708604", "0.4693565", "0.46851256", "0.4676859", "0.46678016", "0.46578738", "0.46572602", "0.46545568", "0.46501654", "0.46475902", "0.46463075", "0.46428573", "0.46403328", "0.46381256", "0.46231624", "0.46123108", "0.46096337", "0.46076143", "0.46069136", "0.46040422", "0.460305", "0.46006522", "0.45957538", "0.45929778", "0.45841655", "0.4583835", "0.45816183", "0.4576824", "0.4575971", "0.45745027", "0.45739073", "0.45738357", "0.4572696", "0.45690757", "0.45675087", "0.45568806", "0.45568463", "0.45567486", "0.4556641", "0.45453802", "0.45451695", "0.45443243", "0.45363203", "0.4534988", "0.45269862", "0.45231962", "0.4522769", "0.4521067", "0.4520068", "0.45176506", "0.45127282", "0.45080218", "0.4505105", "0.45043266", "0.45022124", "0.4499652", "0.44981524", "0.4497248", "0.44946718", "0.44900945", "0.4488517", "0.44858852", "0.4485069", "0.44838163", "0.4472151", "0.44716427", "0.44697535", "0.4464806", "0.44637978", "0.446247", "0.4458076" ]
0.6765716
0
The retrieveContributorSystemCds function will retrieve the codes from code set 89 and store them in the shared resource for future use Since the script call is asynchronous a call back function provided will be executed once the data is retrieved
function retrieveContributorSystemCds(component, callBackFunction) { // Get contributor system codes from shared resource var contributorSystemCdResource = MP_Resources.getSharedResource("contributorSystemCodes"); if (contributorSystemCdResource && contributorSystemCdResource.isResourceAvailable()) { //At this point, the codes are already available, so get the data component.contributorSystemCodes = contributorSystemCdResource.getResourceData(); // Call the call back function if defined if (callBackFunction) { callBackFunction(); } } else { // Retrieve code values from code set 89 // This code set contains the code values for contributor system code, used to sent as a request in mp_exec_std_request var contributorSysCdReq = new ScriptRequest(); contributorSysCdReq.setProgramName("MP_GET_CODESET"); contributorSysCdReq.setParameterArray(["^MINE^", "89.0"]); contributorSysCdReq.setAsyncIndicator(true); contributorSysCdReq.setResponseHandler(function(scriptReply) { if (scriptReply.getResponse().STATUS_DATA.STATUS === "S") { component.contributorSystemCodes = scriptReply.getResponse().CODES; // Load the sytem codes in a list so that the code value can be looked up component.contributorSystemCodes = MP_Util.LoadCodeListJSON(component.contributorSystemCodes); // Add it to the shared resource contributorSystemCdResource = new SharedResource("contributorSystemCodes"); if (contributorSystemCdResource) { contributorSystemCdResource.setResourceData(component.contributorSystemCodes); contributorSystemCdResource.setIsAvailable(true); MP_Resources.addSharedResource("contributorSystemCodes", contributorSystemCdResource); } // Call the call back function if defined if (callBackFunction) { callBackFunction(); } } }); contributorSysCdReq.performRequest(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function pollSystemCodes() {\n\t\t// Note we need to return here to allow tests\n\t\t// to hook into the promise\n\t\treturn fetchSystemCodes(options.cmdbApiKey)\n\t\t\t.then(codes => {\n\t\t\t\tvalidSystemCodes = codes.concat(options.validationExceptions);\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\t// If the poll errors then we don't throw,\n\t\t\t\t// we just start letting any valid source\n\t\t\t\t// parameter through\n\t\t\t\tvalidSystemCodes = undefined;\n\t\t\t\toptions.log.error(`CMDB error: ${error.message}`);\n\t\t\t});\n\t}", "async function getCMCData() {\n //WARNING! This will pull ALL cmc coins and cost you about 11 credits on your api account!\n let cmcJSON = await clientcmc.getTickers({ limit: 4200 }).then().catch(console.error);\n cmcArray = cmcJSON['data'];\n cmcArrayDictParsed = cmcArray;\n cmcArrayDict = {};\n try {\n cmcArray.forEach(function (v) {\n if (!cmcArrayDict[v.symbol])\n cmcArrayDict[v.symbol] = v;\n });\n } catch (err) {\n console.error(chalk.red.bold(\"failed to get cmc dictionary for metadata caching!\"));\n }\n //console.log(chalk.green(chalk.cyan(cmcArray.length) + \" CMC tickers updated!\"));\n}", "fetchContributors() {\n return Util.fetchJSON(this.data.contributors_url);\n }", "function lookupLicenseFromFCC(callSign, callback) {\n // Make the HTTP request\n var url = \"http://data.fcc.gov/api/license-view/basicSearch/getLicenses?format=json&searchValue=\" + callSign;\n\n // create the JSON response\n var handleResponse = function (err, result) {\n console.log(\"Lookup complete: \" + JSON.stringify(result));\n if (err) {\n console.log(err);\n callback(\"unexpected error looking up license information\");\n } else if (result.Errors && result.Errors.Err) {\n var errors = result.Errors.Err;\n console.log(\"error length \" + errors.length);\n if ((errors.length === 1) && errors[0].msg) {\n if (errors[0].code === \"110\") {\n callback(null, null);\n } else {\n callback(errors[0].msg);\n }\n } else if (errors.length > 1) {\n callback(\"multiple errors were encountered with the request\");\n } else {\n callback(\"unknown error was encountered with the request\");\n }\n } else if (result.Licenses && result.Licenses.License) {\n var licenses = result.Licenses.License;\n var license;\n if (licenses.length >= 1) {\n for (var i=0; i<licenses.length; i++) {\n if (licenses[i].callsign == callSign) {\n license = licenses[i];\n break;\n }\n }\n } \n \n if (license) {\n callback(null, license);\n } else {\n callback(null, null);\n }\n } else {\n callback(\"Invalid response received\");\n }\n };\n\n // Handle the HTTP request\n request(url, function (err, httpresp, body) {\n if (!err && httpresp.statusCode === 200) {\n var result = JSON.parse(body);\n handleResponse(null, result);\n } else {\n callback(err);\n }\n });\n}", "async function getTerm(storeId) {\n //https://svc.bkstr.com/courseMaterial/info?storeId=166904\n const str = await fetch(`https://svc.bkstr.com/courseMaterial/info?storeId=${storeId}`, {\n method: 'GET',\n mode: 'cors',\n headers: getHeaderString(),\n });\n const ret = await str.json(); \n var termData = [];\n console.log('term id and program id');\n let camp = ret.finalData?.campus;\n if(!camp || typeof camp == \"undefined\"){\n console.log(\"no campus or you are blocked\");\n process.exit(0);\n }else{\n camp.forEach(function(val,index){\n let campusId = val.campusId; \n val.program.forEach(function(val2,index2){\n val.program[index2].term.forEach(function(val3,index3){\n let termId = val3.termId;\n let programId = val.program[index2].programId;\n termData.push({campusId,termId,programId});\n })\n })\n })\n // console.log(termData);\n return termData; \n }\n}", "function getTGCData(callback, wantDists) {\r\n\t$.getJSON('tgcsystems.json', function(data) {\r\n\t\tlastFetch = data.date+'Z';\r\n\t\tsystemsMap = {};\r\n\t\taddSystems(data.systems);\r\n\t\tlogAppend('Loaded tgcsystems.json: data up to '+data.date+'. Total number of systems: '+Object.keys(systemsMap).length+'\\n');\r\n\t}).fail(function() {\r\n\t\tlogAppend('Failed to read from tgcsystems.json\\n');\r\n\t}).always(function() {\r\n\t\t// update with any additional data from the server\r\n\t\tupdateTGCData(function() {\r\n\t\t\t$.getJSON('tgcdistances.json', function(data) {\r\n\t\t\t\tlastDistFetch = data.date+'Z';\r\n\t\t\t\tvar dists = addDistances(data.distances);\r\n\t\t\t\tlogAppend('Loaded tgcdistances.json: data up to '+data.date+'. Added '+dists+'\\n');\r\n\t\t\t}).fail(function() {\r\n\t\t\t\tlogAppend('Failed to read from tgcdistances.json\\n');\r\n\t\t\t}).always(function() {\r\n\t\t\t\tfetchTGCDistances(callback);\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n}", "getDatasets (callback, isPublic, isSignedOut) {\n scitran.getProjects({authenticate: !isPublic, snapshot: false, metadata: true}, (projects) => {\n scitran.getProjects({authenticate: !isPublic, snapshot: true, metadata: true}, (pubProjects) => {\n projects = projects.concat(pubProjects);\n scitran.getUsers((err, res) => {\n let users = !err && res && res.body ? res.body : null;\n let resultDict = {};\n // hide other user's projects from admins & filter snapshots to display newest of each dataset\n if (projects) {\n for (let project of projects) {\n let dataset = this.formatDataset(project, null, users);\n let datasetId = dataset.hasOwnProperty('original') ? dataset.original : dataset._id;\n let existing = resultDict[datasetId];\n if (\n !existing ||\n existing.hasOwnProperty('original') && !dataset.hasOwnProperty('original') ||\n existing.hasOwnProperty('original') && existing.snapshot_version < project.snapshot_version\n ) {\n if (isPublic || this.userAccess(project)){\n resultDict[datasetId] = dataset;\n }\n }\n }\n }\n\n let results = [];\n for (let key in resultDict) {\n results.push(resultDict[key]);\n }\n callback(results);\n }, isSignedOut);\n });\n });\n }", "function getAllModuleLicenses(callback)\n {\n getModuleLicenses(\"all\", callback);\n }", "function getContributions(callback){\n db.collection(\"pollination\").find().toArray(callback);\n }", "function getLicences() {\n\n //these are the licenses provided from the spec that the user can select in a dropdown format\n const licenses = [\"CC BY\", \"CC BY-NC\", \"CC BY-NC-ND\", \"CC BY-NC-SA\", \"CC BY-SA\", \"EMUCL\", \"GFDL\", \"GGPL\", \"OPL\", \"PD\"]\n const licenseList = document.getElementById('license-select');\n\n for(let i = 0; i < licenses.length; i++) {\n const licenseListItem = document.createElement(\"option\");\n licenseListItem.textContent = licenses[i];\n licenseListItem.value = licenses[i];\n licenseList.appendChild(licenseListItem);\n }\n\n $('#license-select').multiselect({\n includeSelectAllOption: true,\n buttonText: function(options, select) {\n return 'Select one or more';\n },\n onChange: function(option, checked, select) {\n $(option).each(function(index, id) {\n let i = licenseArr.indexOf(id.value);\n if (i === -1) {\n licenseArr.push(id.value); \n } else {\n licenseArr.splice(i, 1);\n if (licenseArr.length === 0) {\n licenseArr.push(0);\n }\n }\n });\n searchBooksObj.licenseCodes = licenseArr;\n },\n onSelectAll: function() {\n searchBooksObj.licenseCodes = $('#license-select').val();\n }\n });\n}", "static getLicensePlateRecognitionServers(callback) {\n let apiPath = \"api/1.0/system/license-plate-recognition-servers/get\";\n try {\n let params = {};\n Api.get(apiPath, params, results => {\n callback(super.returnValue(apiPath, results));\n });\n } catch (error) {\n callback(super.catchError(error));\n }\n }", "getApplications(metamaskAddress) {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(this, void 0, void 0, function* () {\n console.log(metamaskAddress);\n const deployedRiceCertificate = yield this.RiceCertificate.deployed();\n return new Promise((res, rej) => {\n console.log(deployedRiceCertificate);\n deployedRiceCertificate.retApp.call().then(function (data) {\n console.log(data);\n // console.log(JSON.parse(data));\n });\n deployedRiceCertificate.getApplicationCount.call()\n .then(function (v) {\n console.log('GOT FROM BC');\n console.log(v);\n console.log(v.c);\n var appCount = v;\n // var candidatesResults = $(\"#candidatesResults\");\n // candidatesResults.empty();\n for (var i = 0; i < appCount; i++) {\n deployedRiceCertificate.myStructs(i).then(function (rice) {\n console.log(rice);\n console.log(web3__WEBPACK_IMPORTED_MODULE_8___default.a);\n var farm_id = rice[0].c;\n var farm_owner = rice[1];\n var address = web3__WEBPACK_IMPORTED_MODULE_8___default.a.prototype.toAscii(rice[2]).replace(/[^ -~]+/g, '');\n console.log(address);\n // //LOCATION DECODED\n var farmloc = web3__WEBPACK_IMPORTED_MODULE_8___default.a.prototype.toAscii(rice[3]).replace(/[^ -~]+/g, '');\n // var location = Geohash.decode(farmloc);\n // var latitude = location.lat;\n // var longitude = location.lon;\n // console.log('Latitude : ' + latitude + ',Longitude:' + longitude)\n // var requirement = Web3.prototype.toAscii(rice[4]).replace(/[^ -~]+/g, '');\n var requirement = web3__WEBPACK_IMPORTED_MODULE_8___default.a.prototype.toAscii(rice[4]).replace(/[^ -~]+/g, '');\n var standard = web3__WEBPACK_IMPORTED_MODULE_8___default.a.prototype.toAscii(rice[5]).replace(/[^ -~]+/g, '');\n var account = rice[6];\n var stat = web3__WEBPACK_IMPORTED_MODULE_8___default.a.prototype.toAscii(rice[7]).replace(/[^ -~]+/g, '');\n console.log(stat);\n console.log('ID : ' + farm_id + ' , FARMER : ' + farm_owner + ' ,ADDRESS : ' + address + ',REQUIREMENT : ' + requirement + ',STANDARD:' + standard + ',ACCOUNT' + account);\n sessionarray.push({\n 'farm_id': farm_id,\n 'farm_owner': farm_owner,\n 'address': address,\n 'farmloc': farmloc,\n 'requirement': requirement,\n 'standard': standard,\n 'stat': stat,\n });\n // if(stat == 'Pending'){\n // this.visibility = true;\n // }\n // else{\n // this.visibility = false;\n // }\n console.log('sessionarray');\n console.log(sessionarray);\n res(sessionarray);\n // Render candidate Result\n // var candidateTemplate = \"<tr><th>\" + farm_id + \"</th><td>\" + farm_owner + \"</td><td>\" + address + \"</td><td>\" + latitude + \"</td><td>\" + longitude + \"</td><td>\" + requirement + \"</td><td>\" + standard + \"</td><td>\" + account + \"</td><td>\" + stat + \"</td></tr>\"\n // candidatesResults.append(candidateTemplate);\n // // Render candidate ballot option\n /* var candidateOption = \"<option value='\" + farm_id + \"' >\" + farm_owner + \"</ option>\"\n candidatesSelect.append(candidateOption);\n */\n });\n }\n });\n });\n });\n }", "function getAllLMSData() {\n try {\n // create web service param objectst\n var serviceScormInfo = {\n \"UserID\": launchData.UserID,\n \"CourseLocation\": launchData.CourseLocation,\n \"ScormVersion\": launchData.ScormVersion\n }\n\n var oDataCurrent = null;\n oData = {}; oData.Data = [];\n // get previosly recorderd state data from non-SCORM webservice\n azureCDS && azureCDS.ajax({\n type: \"GET\",\n contentType: \"application/json; charset=utf-8\",\n url: azureCDS.LdServiceBaseUrl + \"consumptions/nonscorm/\" + launchData.UserID + \"/\" + azureCDS.CourseID + \"/\" + this.parent.course.settings.AttemptId,\n processData: false,\n data: \"{}\",\n async: false,\n crossDomain: true,\n dataType: \"json\",\n beforeSend: function (xhr) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + parent.parent.GetTokenToClient())\n }, success: function (data) {\n if (data && data.Data && data.Data.$values && data.Data.$values.length) {\n for (i = 0; i < data.Data.$values.length; i++) {\n var current = data.Data.$values[i];\n oData.Data.push({ Key: current.Key, Value: current.Value });\n if (current.Key == launchData.CurrentPage.id) {\n oDataCurrent = current.Value;\n }\n }\n }\n }, error: function () {\n }, complete: function () {\n }\n });\n\n if (oDataCurrent) {\n // parse local scorm data\n var aScormData = JSON.parse(oDataCurrent);\n // restore scorm data\n restoreBuff(aScormData);\n } else {\n oData.Data.push({ Key: launchData.CurrentPage.id, Value: null });\n }\n } catch (e) { }\n}", "async fetchContributors() {\n const response = await fetch(this.repository.contributors_url);\n return response.json();\n }", "function initScorm2004Data(userID, firstName, LastName, minProgressMeasure, timeLimitAction, dataFromLMS) {\n var sdNew;\n\n /* init the SCORM data list */\n sdList = new ScormData('ro', '0', 'cmi._version', 'CMIIdentifier', '', '1.0', null);\n sdNew = new ScormData('ro', '0', 'cmi.comments_from_learner._children', 'CMIString255', '\"comment\",\"location\",\"timestamp\"', 'comment,location,timestamp', sdList);\n sdNew = new ScormData('ro', '0', 'cmi.comments_from_learner._count', 'CMIInteger', '', 0, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.comments_from_lms._children', 'CMIString255', '\"comment\",\"location\",\"timestamp\"', 'comment,location,timestamp', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.comments_from_lms._count', 'CMIInteger', '', 0, sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.completion_status', 'CMIVocabulary', '\"completed\":\"incomplete\":\"not attempted\":\"unknown\"', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.completion_threshold', 'CMIInteger', '', minProgressMeasure, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.credit', 'CMIVocabulary', '\"credit\":\"no-credit\"', 'credit', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.entry', 'CMIVocabulary', '\"\":\"ab-initio\":\"resume\"', 'ab-initio', sdNew);\n sdNew = new ScormData('wo', '0', 'cmi.exit', 'CMIVocabulary', '\"\":\"normal\":\"logout\":\"suspend\":\"time-out\"', '', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.interactions._children', 'CMIString255', '\"id\",\"objectives\",\"timestamp\",\"type\",\"correct_responses\",\"weighting\",\"learner_response\",\"result\",\"latency\",\"description\"', 'id,objectives,timestamp,type,correct_responses,weighting,learner_response,result,latency,description', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.interactions._count', 'CMIInteger', '', 0, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.launch_data', 'CMIString4096', '', dataFromLMS, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.learner_id', 'CMIIdentifier', '', userID, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.learner_name', 'CMIString255', '', LastName + \", \" + firstName, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.learner_preference._children', 'CMIString255', '\"audio_level\",\"language\",\"delivery_speed\",\"audio_captioning\"', 'audio_level,language,delivery_speed,audio_captioning', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.learner_preference.audio_level', 'CMIInteger', '0,100', '0', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.learner_preference.language', 'CMIString255', '', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.learner_preference.delivery_speed', 'CMIInteger', '-0,100', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.learner_preference.audio_captioning', 'CMIInteger', '-1,1', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.location', 'CMIString255', '', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.max_time_allowed', 'CMIInteger', '', '', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.mode', 'CMIVocabulary', '\"normal\":\"review\":\"browse\"', 'normal', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.objectives._children', 'CMIString255', '\"id\",\"score\",\"success_status\",\"completions_status\",\"progress_measure\",description', 'id,score,success_status,progress_measure,description', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.objectives._count', 'CMIInteger', '', 0, sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.progress_measure', 'CMIInteger', '0,1', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.scaled_passing_scoree', 'CMIInteger', '-1,1', '', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.score._children', 'CMIString255', '\"scaled\",\"max\",\"min\",\"raw\"', 'scaled,max,min,raw', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.score.scaled', 'CMIDecimal', '0,1', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.score.max', 'CMIDecimal', '0,100', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.score.min', 'CMIDecimal', '0,100', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.score.raw', 'CMIDecimal', '0,100', '', sdNew);\n sdNew = new ScormData('wo', '0', 'cmi.session_time', 'CMITimespan', '', '', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.success_status', 'CMIVocabulary', '\"passed\":\"failed\":\"unknown\"', 'unknown', sdNew);\n sdNew = new ScormData('rw', '0', 'cmi.suspend_data', 'CMIString64000', '', '', sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.time_limit_action', 'CMIVocabulary', '\"exit,messaged\":\"continue,message\":\"exit,no message\":\"continue,no message\"', timeLimitAction, sdNew);\n sdNew = new ScormData('ro', '0', 'cmi.total_time', 'CMITimespan', '', 'PT0S', sdNew);\n}", "getDataset (projectId, callback, options) {\n scitran.getUsers((err, res) => {\n let users = !err && res && res.body ? res.body : null;\n scitran.getProject(projectId, (res) => {\n let tempFiles = this._formatFiles(res.body.files);\n if (res.status !== 200) {return callback(res);}\n let project = res.body;\n this.getMetadata(project, (metadata) => {\n let dataset = this.formatDataset(project, metadata['dataset_description.json'], users);\n dataset.README = metadata.README;\n crn.getDatasetJobs(projectId, (err, res) => {\n dataset.jobs = res.body;\n dataset.children = tempFiles;\n dataset.showChildren = true;\n this.usage(projectId, options, (usage) => {\n if (usage) {\n dataset.views = usage.views;\n dataset.downloads = usage.downloads;\n }\n callback(dataset);\n });\n }, options);\n }, options);\n }, options);\n }, options && options.isPublic);\n }", "async function getDataset() {\n const [dataset, perfTimes] = await fetchMorpheusJson(\n studyAccession,\n genes,\n cluster,\n annotation.name,\n annotation.type,\n annotation.scope,\n subsample\n )\n logFetchMorpheusDataset(perfTimes, cluster, annotation, genes)\n return dataset\n }", "function getServiceDetailsData(requestOptions, callback) {\n if (requestOptions && requestOptions[\"headers\"] && requestOptions[\"headers\"][\"regionid\"] && requestOptions[\"headers\"][\"platformid\"] && requestOptions[\"headers\"][\"categoryname\"]) {\n //forming http request string\n var getOptions = {\n url: 'https://api.github.com/gists/' + config.gistID,\n method: 'GET',\n headers: {\n 'Authorization': config.auth,\n 'user-agent': 'node.js'\n }\n };\n\n request(getOptions, function (err, response) {\n if (err) {\n return callback(err);\n }\n else {\n\n var stringData = JSON.parse(response.body);\n\n var serviceDetailsContent = stringData.files[config[\"serviceDetails\"]].content;\n if (serviceDetailsContent) {\n console.log(\"***getServiceDetailsData***\" + serviceDetailsContent);\n\n var serviceDetailsObj = JSON.parse(serviceDetailsContent);\n var servicesArray = serviceDetailsObj[requestOptions[\"headers\"][\"platformid\"]][requestOptions[\"headers\"][\"regionid\"]];\n\n if (servicesArray.length) {\n var serviceObj = servicesArray.filter(function (obj) {\n return obj[\"categoryName\"] === requestOptions[\"headers\"][\"categoryname\"];\n });\n console.log(\"***servicesArray***\" + JSON.stringify(serviceObj));\n\n if (serviceObj.length) {\n return callback(null, serviceObj[0]);\n }\n else {\n return callback({ \"Error\": \"No data available\" });\n }\n }\n else {\n return callback({ \"Error\": \"No data available\" });\n }\n }\n else {\n return callback({ \"Error\": \"No data available\" });\n }\n }\n });\n }\n else {\n return callback({ \"Error\": \"platformid or regionid are not provided in headers\" });\n }\n}", "function loadOrganizationsFromCKAN2() {\n\n const ckanURLgetOrganisations = \"api/3/action/organization_list?all_fields=true&include_extras=true&include_users=true\";\n\n var ckanURL = ckanServer + ckanURLgetOrganisations;\n \n axios.get(ckanURL, { crossdomain: true } )\n .then(function (response) {\n\n globalMembers = tidyOrganizations(response.data.result); // add and remove stuff\n console.log(JSON.stringify(globalMembers));\n displayMemberCards(); // display the members fetched into globalMembers array \n\n })\n .catch(function (error) {\n mylog(mylogdiv, \"organization_list ERROR: \" + JSON.stringify(error));\n console.log(\"organization_list ERROR: \" + JSON.stringify(error));\n });\n\n\n $('a[data-toggle=\"tooltip\"]').tooltip({\n animated: 'fade',\n placement: 'bottom',\n html: true\n });\n\n\n searching();\n getMembersDummyData();\n displayMemberCards();\n loginStatus();\n statistics();\n\n\n\n // for dockument ready use: });\n\n}", "getSemesters() {\n return this.#fetchAdvanced(this.#getSemestersURL()).then((responseJSON) => {\n let semesterBOs = SemesterBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(semesterBOs);\n })\n })\n }", "async function getData() {\n request.open('GET',\n 'https://services1.arcgis.com/0n2NelSAfR7gTkr1/arcgis/rest/services/Business_Licenses/FeatureServer/0/query?where=FID' + ' > ' + lastFID + ' AND FID <= ' + (lastFID + 500) + '&outFields=*&outSR=4326&f=json',\n true);\n\n //comment out the following line to quickly edit ui without making requests\n request.send();\n}", "function xhrCallbackContributors(data) {\n //console.log('data from server', data);\n contributors = JSON.parse(data);\n console.log('parsed contributor data:', contributors);\n \n showContributorsInList(contributors);\n}", "getScrpAuthr () {\n\t\t\tthis.$axios.get('/api/do_m_scrpt_code/getScrpAuthr/'+this.manu_script_id).then(res => {\n\t\t\t\tthis.allScrpAuthr = res.data;\n\t\t\t});\n\t\t}", "function fetchConsumerDCSO() {\n\t\tvar ret;\n\t\tfor (var i = 0; i < window.DataChannels.length; i++) {\n\t\t\tif (window.DataChannels[i]['role'] === \"consumer\") {\n\t\t\t\tret = window.DataChannels[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}", "function appendStudentDetailsToOneCCA(CCADirectoryID, CCAName, targetStudentDetails, resToClient){\n\n gapi.googleDrive.children.list({'folderId': CCADirectoryID}, function(err,res){\n if (res) {\n var numOfChildrenInRoot = res.items.length;\n var numOfChildrenInRootChecked = 0;\n var isTargetCCAFolderFound = false;\n\n for (var i = 0; i < numOfChildrenInRoot; i++) {\n var id = res.items[i].id;\n \n gapi.googleDrive.files.get({'fileId': id}, function(err,res){\n if (err) {\n resToClient.json({message:\"error when checking a file\", err:err});\n }\n\n if (res.title == CCAName && res.mimeType == 'application/vnd.google-apps.folder'){\n isTargetCCAFolderFound = true;\n\n\n var targetCCAFolderId = res.id;\n gapi.googleDrive.children.list({'folderId': targetCCAFolderId}, function(err,res){\n if (res) {\n var numOfChildrenInTargetFolder = res.items.length;\n var numOfChildrenInTargetFolderChecked = 0;\n var isMemberDetailsSpreadsheetFound = false;\n\n for (var i = 0; i < numOfChildrenInTargetFolder; i++) {\n var id = res.items[i].id;\n gapi.googleDrive.files.get({'fileId': id}, function(err,res){\n if (err) {\n resToClient.json({message:\"error when checking a file\", err:err});\n }\n\n if (res.title === memberDetailsFilename && res.mimeType == \"application/vnd.google-apps.spreadsheet\") {\n var memberDetailsFileId = id;\n isMemberDetailsSpreadsheetFound = true;\n\n googleSpreadsheet.load({\n debug: true,\n spreadsheetId: memberDetailsFileId,\n worksheetName: 'Sheet1',\n accessToken : {\n type: 'Bearer',\n token: gapi.oauth2Client.credentials.access_token\n }\n }, function sheetReady(err, spreadsheet) {\n if(err) {\n resToClient.json({message:\"error when loading the spreadsheet\", err:err});\n } else {\n spreadsheet.receive(function(err, rows, info) {\n if(err){\n throw err;\n }else {\n var numOfRows = info.totalRows;\n var nextRow = info.nextRow;\n console.log(targetStudentDetails);\n if (numOfRows > 1 && targetStudentDetails.length > 0) {\n targetStudentDetails.splice(0, 1);\n }\n console.log(numOfRows);\n\n contents = {};\n contents[nextRow] = targetStudentDetails;\n\n spreadsheet.add(contents);\n spreadsheet.send(function(err) {\n if(err) {\n resToClient.json({message:\"edit spreadsheet error\", err:err});\n // console.log(\"edit spreadsheet error\");\n // console.log(err);\n } else {\n resToClient.json({message:\"success\"});\n }\n \n });\n } \n });\n }\n\n }\n );\n }\n\n numOfChildrenInTargetFolderChecked++;\n if (numOfChildrenInTargetFolderChecked == numOfChildrenInTargetFolder && !isMemberDetailsSpreadsheetFound) {\n resToClient.json({message:\"Student Details Spreadsheet is not found under the target CCA folder\"});\n }\n });\n };\n\n } else {\n resToClient.json({message:\"error when accessing CCA Admin folder\", err:err});\n }\n });\n }\n\n numOfChildrenInRootChecked++;\n if (numOfChildrenInRoot == numOfChildrenInRootChecked && !isTargetCCAFolderFound) {\n resToClient.json({message:\"target CCA folder is not found under CCA-Admin folder\"});\n }\n });\n }\n\n } else {\n resToClient.json({message:\"error when accessing CCA Admin folder\", err:err});\n }\n });\n\n}", "function getContributions(author, permlink) {\r\n var url = `https://utopian.rocks/api/posts?author=`+author;\r\n var m_body = '';\r\n https.get(url, function(res) {\r\n res.on('data', function(chunk) {\r\n m_body += String(chunk);\r\n });\r\n res.on('end', function() {\r\n try {\r\n const response = JSON.parse(m_body);\r\n console.log(\"Total Contributions \", response.length);\r\n if (response.length > 0) {\r\n var contributionsObj = {\r\n \"total\": response.length,\r\n \"approved\": 0,\r\n \"staff_picked\": 0,\r\n \"total_payout\": 0.0\r\n };\r\n \r\n var first_contribution_date = timeConverter(response[0].created.$date);\r\n \r\n contributionsObj['category'] = {};\r\n contributionsObj['approved'] = response.filter(function (el) { return el.voted_on == true;});\r\n contributionsObj['staff_picked'] = response.filter(function (el) { return el.staff_picked == true;});\r\n\r\n contributionsObj['category']['analysis'] = response.filter(function (el) { return el.category === 'analysis' && el.voted_on === true;});\r\n contributionsObj['category']['blog'] = response.filter(function (el) { return el.category === 'blog' && el.voted_on === true;});\r\n contributionsObj['category']['bughunting'] = response.filter(function (el) { return el.category === 'bug-hunting' && el.voted_on === true;});\r\n contributionsObj['category']['copywriting'] = response.filter(function (el) { return el.category === 'copywriting' && el.voted_on === true;});\r\n contributionsObj['category']['development'] = response.filter(function (el) { return el.category === 'development' && el.voted_on === true;});\r\n contributionsObj['category']['documentation'] = response.filter(function (el) { return el.category === 'documentation' && el.voted_on === true;});\r\n contributionsObj['category']['graphics'] = response.filter(function (el) { return el.category === 'graphics' && el.voted_on === true;});\r\n contributionsObj['category']['suggestions'] = response.filter(function (el) { return el.category === 'suggestions' && el.voted_on === true;});\r\n contributionsObj['category']['taskrequests'] = response.filter(function (el) { return el.category === 'task-requests' && el.voted_on === true;});\r\n contributionsObj['category']['tutorials'] = response.filter(function (el) { return el.category === 'tutorials' && el.voted_on === true;});\r\n contributionsObj['category']['videotutorials'] = response.filter(function (el) { return el.category === 'video-tutorials' && el.voted_on === true;});\r\n contributionsObj['category']['translations'] = response.filter(function (el) { return el.category === 'translations' && el.voted_on === true;});\r\n contributionsObj['category']['iamutopian'] = response.filter(function (el) { return el.category === 'iamutopian' && el.voted_on === true;}); \r\n contributionsObj['category']['task'] = response.filter(function (el) { return el.category.startsWith(\"task\") && el.voted_on === true;});\r\n contributionsObj['category']['ideas'] = response.filter(function (el) { return el.category === 'ideas' && el.voted_on === true;});\r\n contributionsObj['category']['visibility'] = response.filter(function (el) { return el.category === 'visibility' && el.voted_on === true;});\r\n\r\n response.forEach(function(contribution) {\r\n if(contribution.voted_on === true){\r\n contributionsObj.total_payout = contributionsObj.total_payout + contribution.total_payout;\r\n }\r\n });\r\n\r\n for(var key in contributionsObj.category) {\r\n const value = contributionsObj.category[key];\r\n if(value.length == 0){\r\n delete contributionsObj.category[key];\r\n }\r\n }\r\n\r\n commentOnAuthorPost(contributionsObj, first_contribution_date, author, permlink);\r\n }\r\n } catch (e) {\r\n console.log('Err' + e);\r\n }\r\n });\r\n }).on('error', function(e) {\r\n req.abort();\r\n console.log(\"Got an error: \", e);\r\n });\r\n}", "function loadInitData() {\n var jsonData = new Object();\n jsonData.sequence_id = \"1\";\n jsonData.idtxn = gTrans.idtxn;\n var args = new Array();\n args.push(null);\n args.push(jsonData);\n var gprsCmd = new GprsCmdObj(CONSTANTS.get(\"CMD_BATCH_SALARY_MANAGER\"), \"\", \"\", gUserInfo.lang, gUserInfo.sessionID, args);\n var data = getDataFromGprsCmd(gprsCmd);\n requestMBServiceCorp(data, false, 0, function (data) {\n var resp = JSON.parse(data);\n if (resp.respCode == 0 && resp.respJsonObj.listMakers.length > 0) {\n //Danh sach nguoi duyet\n gTrans.listMakers = resp.respJsonObj.listMakers;\n } else\n gotoHomePage();\n }, function () {\n gotoHomePage();\n });\n}", "async function loadScripts() {\n await getDisplayData();\n}", "function fetchScormData(refresh) {\n return $mmaModScorm.getScorm(courseid, module.id, module.url).then(function(scormData) {\n scorm = scormData;\n\n $scope.title = scorm.name || $scope.title;\n $scope.description = scorm.intro || $scope.description;\n $scope.scorm = scorm;\n\n var result = $mmaModScorm.isScormSupported(scorm);\n if (result === true) {\n $scope.errorMessage = '';\n } else {\n $scope.errorMessage = result;\n }\n\n if (scorm.warningmessage) {\n return; // SCORM is closed or not open yet, we can't get more data.\n }\n\n return syncScorm(!refresh, false).catch(function() {\n // Ignore errors, keep getting data even if sync fails.\n }).then(function() {\n\n // No need to return this promise, it should be faster than the rest.\n $mmaModScormHelper.getScormReadableSyncTime(scorm.id).then(function(syncTime) {\n $scope.syncTime = syncTime;\n });\n\n // Get the number of attempts and check if SCORM is incomplete.\n return $mmaModScorm.getAttemptCount(scorm.id).then(function(attemptsData) {\n attempts = attemptsData;\n $scope.showSyncButton = attempts.offline.length; // Show sync button only if there are offline attempts.\n\n // Determine the attempt that will be continued or reviewed.\n return $mmaModScormHelper.determineAttemptToContinue(scorm, attempts).then(function(attempt) {\n lastAttempt = attempt.number;\n lastOffline = attempt.offline;\n if (lastAttempt != attempts.lastAttempt.number) {\n $scope.attemptToContinue = lastAttempt;\n } else {\n delete $scope.attemptToContinue;\n }\n\n return $mmaModScorm.isAttemptIncomplete(scorm.id, lastAttempt, lastOffline).then(function(incomplete) {\n var promises = [];\n\n scorm.incomplete = incomplete;\n scorm.numAttempts = attempts.total;\n scorm.grademethodReadable = $mmaModScorm.getScormGradeMethod(scorm);\n scorm.attemptsLeft = $mmaModScorm.countAttemptsLeft(scorm, attempts.lastAttempt.number);\n if (scorm.forceattempt && scorm.incomplete) {\n $scope.scormOptions.newAttempt = true;\n }\n\n promises.push(getReportedGrades());\n\n promises.push(fetchStructure());\n\n if (!scorm.packagesize && $scope.errorMessage === '') {\n // SCORM is supported but we don't have package size. Try to calculate it.\n promises.push($mmaModScorm.calculateScormSize(scorm).then(function(size) {\n scorm.packagesize = size;\n }));\n }\n\n // Handle status. We don't add getStatus to promises because it should be fast.\n setStatusListener();\n getStatus().then(showStatus);\n\n return $q.all(promises);\n });\n });\n }).catch(function(message) {\n return showError(message);\n });\n\n });\n\n }, function(message) {\n if (!refresh) {\n // Get scorm failed, retry without using cache since it might be a new activity.\n return refreshData();\n }\n return showError(message);\n });\n }", "function loadOrganizationsFromCKAN() {\n\n\n\n var client = new CKAN.Client(ckanServer, myAPIkey);\n\n client.action('organization_list', { all_fields: \"true\", include_extras: \"true\", include_users: \"true\" },\n function (err, result) {\n if (err != null) { //some error - try figure out what\n mylog(mylogdiv, \"organization_list ERROR: \" + JSON.stringify(err));\n console.log(\"organization_list ERROR: \" + JSON.stringify(err));\n } else // we have read the data\n {\n //globalMembers = JSON.parse(JSON.stringify(result.result.records)); \n globalMembers = tidyOrganizations(result.result); // add and remove stuff\n displayMemberCards(); // display the members fetched into globalMembers array \n }\n\n });\n\n\n\n\n $('a[data-toggle=\"tooltip\"]').tooltip({\n animated: 'fade',\n placement: 'bottom',\n html: true\n });\n\n\n searching();\n getMembersDummyData();\n displayMemberCards();\n loginStatus();\n statistics();\n\n\n\n // for dockument ready use: });\n\n}", "function main(organizationId = 'YOUR_NUMERIC_ORG_ID') {\n // [START securitycenter_list_assets_with_filter]\n // Imports the Google Cloud client library.\n const {SecurityCenterClient} = require('@google-cloud/security-center');\n\n // Creates a new client.\n const client = new SecurityCenterClient();\n // organizationId is the numeric ID of the organization.\n /*\n * TODO(developer): Uncomment the following lines\n */\n // const organizationId = \"1234567777\";\n const orgName = client.organizationPath(organizationId);\n\n // Call the API with automatic pagination.\n // You can also list assets in a project/ folder. To do so, modify the parent\n // value and filter condition.\n async function listFilteredAssets() {\n const [response] = await client.listAssets({\n parent: orgName,\n filter:\n 'security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"',\n });\n let count = 0;\n Array.from(response).forEach(result =>\n console.log(\n `${++count} ${result.asset.name} ${\n result.asset.securityCenterProperties.resourceName\n } ${result.stateChange}`\n )\n );\n }\n\n listFilteredAssets();\n // [END securitycenter_list_assets_with_filter]\n}", "function retriveBundle(sender) {\n\trequest({\n\t\turl: 'https://f9a1ba24.ngrok.io/prweb/PRRestService/PegaMKTContainer/V2/Container',\n\t\tmethod: 'POST',\n\t\tjson: {\n\t\t\tContainerName: \"RecommendedBundle\",\n\t\t\tCustomerID: customer_id\n\t\t}\n\t}, function(error, response, body) {\n\t\tif (error) {\n\t\t\tconsole.log('Error sending messages: ', error)\n\t\t} else if (response.body.error) {\n\t\t\tconsole.log('Error: ', response.body.error)\n\t\t} else {\n\t\t\t//console.log(\"RecommendedBundle ****************** \"+ JSON.stringify(response));\n\t\t\tlet bundle = response.body.ResponseData.RecommendedBundle.RankedResults\n\t\t\tsendRecommendedBundle(sender, bundle);\n\t\t}\n\t})\n}", "static getAllCampusContacts() {\n let serviceUrl = Config.REST_URL + Config.SERVICESTART + \"/odata/GetAllCampusContacts?$orderby=FirstName,LastSurname\";\n return new Promise((resolve, reject) => {\n fetch(serviceUrl, { \n method: \"get\",\n mode: 'cors',\n cache: 'no-cache',\n credentials: 'include'\n })\n .then(function (response) {\n resolve(response.json());\n })\n .catch(function (error) {\n reject(error);\n });\n });\n }", "async function getSiteData() {\n const text = await fetch(`${settingsUrl()}`)\n .then((res) => res.text())\n .then((text) => {\n return text;\n })\n .catch((error) =>\n console.error(`failed to get BMC providers from setting: ${error}`)\n );\n\n /*\n Looking for content in the following:\n\n url: \"https://mychartscheduling.bmc.org/mychartscheduling/SignupAndSchedule/EmbeddedSchedule?id=10033909,10033319,10033364,10033367,10033370,10033706,10033083,10033373&dept=10098252,10098245,10098242,10098243,10098244,10105138,10108801,10098241&vt=2008\",\n */\n const relevantText = text.match(/EmbeddedSchedule.+/)[0];\n const ids = relevantText.match(/id=([\\d,]+)&/)[1].split(\",\");\n const deptIds = relevantText.match(/dept=([\\d,]+)&/)[1].split(\",\");\n const vt = relevantText.match(/vt=(\\d+)/)[1];\n\n return { providerIds: ids, departmentIds: deptIds, vt: vt };\n}", "async function getResourceInformation( args ) { // Note: Parameters don'' necessarily need to be linked on the connector for this call to be successful\n const {user, context} = args;\n let [err, vsdm] = await formatPromiseResult( Y.doccirrus.dcTi.createVSDM( {user} ) );\n if( err ) {\n Y.log( `getResourceInformation: could not create VSDM: ${err.stack || err}`, 'warn', NAME );\n throw err;\n }\n\n let result;\n [err, result] = await formatPromiseResult( vsdm.getResourceInformation( context ) );\n if( err ) {\n Y.log( `getResourceInformation: could not init eventService: ${err.stack || err}`, 'warn', NAME );\n throw err;\n }\n\n return result;\n }", "function retrieveDescribeCoverage(serverIndex, coverageIndex) {\n\tTi.API.info('WcsCoverageMetadata.js - serverIndex: ' + serverIndex);\n\tTi.API.info('WcsCoverageMetadata.js - coverageIndex: ' + coverageIndex);\n\n\t// activity indicator for entertainment\n\tvar indicatorStyle;\n\tif (Ti.Platform.name === 'iPhone OS'){\n\t \tindicatorStyle = Ti.UI.iPhone.ActivityIndicatorStyle.DARK;\n\t}\n\telse {\n\t \tindicatorStyle = Ti.UI.ActivityIndicatorStyle.DARK;\n\t}\n\tvar actInd = Ti.UI.createActivityIndicator({\n \t\tcolor: 'black',\n \t\tfont: {fontFamily:'Helvetica Neue', fontSize:26, fontWeight:'bold'},\n \t\tmessage: 'Loading data...',\n \t\tstyle: indicatorStyle,\n \t\t//top: 10,\n \t\t//left: 10,\n \t\theight: Ti.UI.SIZE,\n \t\twidth: Ti.UI.SIZE\n\t});\n\twin.add(actInd);\n\tactInd.show();\n\n\t//Verify if describeCoverage response is null for the server with index choosen\n\tvar addedServers = [];\n\tif (Ti.App.Properties.hasProperty('addedServers')) {\n\t\taddedServers = Ti.App.Properties.getList('addedServers');\n\t};\n\t\n\tif (addedServers[serverIndex].describeCoverageArray[coverageIndex] == null) {\n\t\t//Inoltriamo la richiesta\n\t\tgetDescribeCoverage(addedServers, serverIndex, function(xmlText) {\n\t\t\t//now we have to use the variable `returnedData` any any other normal returned variable\n\n\t\t\tif (xmlText == null) {\n\t\t\t\talert(\"error\");\n\t\t\t} else {\n\t\t\t\t//Update the addedArray and then the property\n\t\t\t\taddedServers[serverIndex].describeCoverageArray[coverageIndex] = xmlText;\n\t\t\t\tTi.App.Properties.setList('addedServers', addedServers);\n\n\t\t\t\tactInd.hide();\n\n\t\t\t\twin2.xmlText = addedServers[serverIndex].describeCoverageArray[coverageIndex];\n\t\t\t\tif (Ti.App.isAndroid == true) {\n\t\t\t\t\twin2.open();\n\t\t\t\t} else {\n\t\t\t\t\twin.padre.openWindow(win2);\t\n\t\t\t\t};\n\t\t\t};\n\t\t});\n\t} else {\n\t\t//alert(\"Xml già presente\");\n\t\t//Set the xmlText win2 property\n\t\tactInd.hide();\n\t\twin2.xmlText = addedServers[serverIndex].describeCoverageArray[coverageIndex];\n\t\tif (Ti.App.isAndroid == true) {\n\t\t\twin2.open();\n\t\t} else {\n\t\t\twin.padre.openWindow(win2);\t\n\t\t};\n\t};\n}", "async function getAllSchools () {\r\n try {\r\n //Get Schools\r\n ///The api to get the schools, complete with query string parameters\r\n var api = apiRoot + \"/all-schools?username=\" + userSession.auth.username;\r\n\r\n ///Using an API call to retrieve the school data\r\n var schoolData = await callGetAPI(api, \"schools\");\r\n\r\n ///Parsing the school data\r\n schoolData = schoolData.schools;\r\n\r\n ///An array to store the schools\r\n var schools = [];\r\n\r\n ///Populating the schools array with the schools from the back end\r\n schoolData.forEach(element => {\r\n schools.push(element[0].stringValue);\r\n });\r\n\r\n ///Sorting the school array\r\n schools.sort();\r\n\r\n ///Adding each school to the \r\n schools.forEach(element => {\r\n $(\"#school-select\").append(newSelectItem(element));\r\n });\r\n\r\n ///Show the school select box\r\n $(\"#school-input-container\").show();\r\n } catch (e) {\r\n generateErrorBar(e);\r\n }\r\n}", "function getLicense (requestObj, cb, noExitOnError) {\n logger.debug({ msg: 'getLicense called', additionalInfo: { requestObj } })\n contentProvider.compositeSearch(requestObj, {}, (err, res) => {\n if (!err) {\n return cb(err, res)\n } else {\n logger.error({\n msg: 'Error from content provider while getting license details',\n err,\n additionalInfo: { requestObj }\n })\n if (!noExitOnError) {\n logger.fatal({\n msg: 'Exiting due to error from content provider while getting license details',\n err,\n additionalInfo: { requestObj, noExitOnError }\n })\n process.exit(1)\n }\n }\n })\n}", "async function getData(){\n var apiKey = \"qapDVIl1RrWwJ9hGkB3evT2ZtEgOZcRck37aylMX\";\n var url = \"https://api.data.gov/ed/collegescorecard/v1/schools.json?_zip=\" + zipCode + \"&_distance=\" + radius + \"mi&_per_page=100&fields=school.ownership,school.name,school.state,school.city,school.degrees_awarded.highest,school.school_url&api_key=\" + apiKey;\n var type = \"public\";\n // TODO\n if(type != \"public\"){\n url += \"&minmagnitude=\"+ magnitude;\n }\n\n let response = await fetch(url);\n let data = await response.json();\n\n var results = data.results;\n var colList = \"\";\n for(let i = 0; i < results.length; i++){\n var ownership = \"\";\n var schoolName = results[i][\"school.name\"];\n var city = results[i][\"school.city\"];\n var url = results[i][\"school.school_url\"];\n var state = results[i][\"school.state\"];\n var highestdegree = \"\";\n switch(results[i][\"school.degrees_awarded.highest\"]) {\n case 0:\n highestdegree = \"Non-degree-granting school.\";\n break;\n case 1:\n highestdegree = \"Most awards earned are certificates, but degrees may be offered.\";\n break;\n case 2:\n highestdegree = \"Most awards earned are 2-year associate's degrees, but other degrees and certificates may be offered.\";\n break;\n case 3:\n highestdegree = \"Most awards earned are 4-year bachelor's degrees, but other degrees and certificates may be offered.\";\n break;\n case 4:\n highestdegree = \"Most awards earned are graduate degrees, but other degrees and certificates may be offered.\";\n break;\n }\n switch(results[i][\"school.ownership\"]) {\n case 1:\n ownership = \"Public\";\n break;\n case 2:\n ownership = \"Private nonprofit\";\n break;\n case 3:\n ownership = \"Private for-profit\";\n break;\n }\n colList += '<div class=\"card right_box\" style=\"width: 20rem;\">' +\n '<div class=\"card-body\">' +\n '<h5 class=\"card-title\">' + schoolName + '</h5>' +\n '<h6 class=\"card-subtitle mb-2 text-muted\">' + city + ', ' + state +'</h6>' +\n '<p class=\"card-text\"><ul class=\"no-bullets\"><li>'+ ownership + '</li><li>'+ highestdegree + '</li></ul></p>' +\n '<a href=\"' + url + '\" class=\"card-link\">' + url + '</a>' +\n '</div>' +\n '</div>';\n }\n var alert = results.length + ' colleges returned';\n $(\"#alert\").html(alert);\n $(\"#alert\").show();\n $(\"#output\").html(colList);\n}", "function readManifest() {\n\n // read course manifest file\n var oImsmanifestXML = getXmlDocument(launchData.CourseLocation + \"/imsmanifest.xml\");\n\n if (!oImsmanifestXML) {\n alert(\"The imsmanifest.xml file course cannot be read.\");\n return null;\n }\n\n var aScormVersion = $(oImsmanifestXML).find(\"schemaversion\");\n if (!aScormVersion.length) {\n alert(\"The version of SCORM could not be determined.\");\n return null;\n } else {\n launchData.ScormVersion = $(aScormVersion[0]).text();\n if (!launchData.ScormVersion) {\n alert(\"The version of SCORM could not be determined.\");\n return null;\n }\n }\n\n // check the number of SCOs by counting organization item tags\n var SCOs = $(oImsmanifestXML).find(\"organizations organization item\");\n if (!SCOs.length || SCOs.length > 1) {\n alert(\"The manifest file has an invalid number of SCOs.\");\n return null;\n }\n // get the course title from the item title child element\n launchData.CourseTitle = $(\"title\", SCOs[0]).text();\n // get the launch URL\n launchData.LaunchURL = $(oImsmanifestXML).find(\"resources resource[identifier=\" + $(SCOs[0]).attr(\"identifierref\") + \"]\").attr(\"href\");\n // everything looks good so far, return true if we found a valid SCORM version in the manifest\n if (launchData.ScormVersion == \"1.2\" || launchData.ScormVersion == \"CAM 1.3\" || launchData.ScormVersion == \"2004 3rd Edition\" || launchData.ScormVersion == \"2004 4th Edition\") {\n return SCOs[0];\n } else {\n // invalid SCORM version\n alert(\"The version of SCORM could not be determined.\");\n }\n return null;\n}", "function dataProviderMaster() {\n setTimeout(function () {\n db_master.get_master_all().forEach(readTraceMaster);\n dataProviderMaster();\n }, 1000);\n}", "function getClinicalData(cancer_study_id) {\n\n d3.select(\"#par_coords\").remove();\n\n var clinicalDataQuery = serverUrl + \"cmd=getClinicalData&case_set_id=\" + cancer_study_id + \"_all\";\n pCColor = getColor(study_types[cancer_study_id]);\n\n console.log(clinicalDataQuery);\n\n new Promise(function(resolve) {\n d3.tsv(clinicalDataQuery, function(p) { resolve(p); })\n })\n .then(function(clinicalDataResult) {\n\n clinicalData = clinicalDataResult;\n plotParallelCoordinate(clinicalData);\n\n });\n\n}", "function azureQueryClientList(adminGUID) {\n var query = \"$filter=parent_id eq '\" + adminGUID + \"'\";\n Azureservice.read('kid', query).then(function (items) { // query to see if this 'name' exists\n if (items.length == 0) { // if admin guid not found, then\n console.log('admin guid not found')\n }\n else { // if admin guid found, get the client list (JSON) and put in array\n clientarray2 = items; //alert(clientarray2[0].name);\n };\n }).catch(function (error) {\n console.log(error);\n alert(error);\n })\n }", "getData(cb){\n\t\tlet promArray = [];\n\t\tthis.allUserNames.map((userName)=>{\n\t\t\tpromArray.push(fetch(`https://api.github.com/users/${userName}`).then(res=>res.json()))\n\t\t})\n\n\t\tPromise.all(promArray)\n\t\t\t.then(data => {\n\t\t \t\t// do something with the data\n\t\t \t\t cb(data);\n\t\t\t})\n\n\t}", "function getBooks() {\n clubID = this.value;\n // console.log('clubID', clubID);\n fetch('/get_books_in_genre?clubID=' + clubID)\n .then(function (response) {\n return response.json();\n }).then(function (json) {\n // console.log('GET response', json);\n if (json.length > 0) {\n set_book_select(json);\n };\n });\n}", "async function StartListaSCCD() {\n await loadAPI('GET','',api_list_sccd,{}).then((ret)=>{\n lista_SCCD(ret)\n })\n return 1\n}", "function getRaceListByYear (callack,championData){\n const url = baseUrl + championData.season+ '/results/1.json'\n const raceList= fetch(`${url}`).then(response => {\n return response.json()\n }).then(data => {\n let raceData = [];\n if (data &&\n data.MRData\n && data.MRData.RaceTable && data.MRData.RaceTable.Races.length) {\n for(let race of data.MRData.RaceTable.Races){\n const raceResult = race.Results && race.Results.length ? race.Results[0] : null\n const driverName = raceResult.Driver.givenName + \" \"+raceResult.Driver.familyName\n raceData.push({...race,...{\n \"fullName\":raceResult.Driver.givenName + \" \"+raceResult.Driver.familyName ,\n \"constructorName\":driverName,\n \"laps\":raceResult.laps,\n \"finishedTime\":raceResult.Time.time,\n \"grid\":raceResult.grid + \" Grid\" ,\n \"isHighLightRequired\": championData.fullName && driverName === championData.fullName\n }})\n }\n }\n console.log(raceData)\n callack(raceData)\n return raceData\n }).catch(error => {\n callack([])\n return Promise.reject(error)\n })\n}", "function getDisciplines() {\n $('#disciplines').multiselect({\n includeSelectAllOption: true,\n buttonText: function(options, select) {\n return 'Select one or more';\n },\n onChange: function(option, checked, select) {\n $(option).each(function(index, id) {\n let i = disciplineArr.indexOf(id.value);\n if (i === -1) {\n disciplineArr.push(id.value); \n } else {\n disciplineArr.splice(i, 1);\n if (disciplineArr.length === 0) {\n disciplineArr.push(0);\n }\n }\n });\n searchBooksObj.tagIds = disciplineArr;\n }\n });\n fetch(baseUrl + 'tag')\n .then(disciplineResponse => disciplineResponse.json())\n .then(disciplines => {\n let data = disciplines.map(discipline => {\n return {label: discipline.name, title: discipline.name, value: discipline.id};\n });\n // programmatically add data to select list using multiselect library\n $('#disciplines').multiselect('dataprovider', data);\n })\n .catch(error => console.error(error));\n}", "async function getAPaymentHsm() {\n const subscriptionId = \"00000000-0000-0000-0000-000000000000\";\n const resourceGroupName = \"hsm-group\";\n const name = \"hsm1\";\n const credential = new DefaultAzureCredential();\n const client = new AzureDedicatedHSMResourceProvider(credential, subscriptionId);\n const result = await client.dedicatedHsmOperations.get(resourceGroupName, name);\n console.log(result);\n}", "getLegislator(bioguide_id) {\n /* Potential performance improvement by fetching all legislator info at once,\n then storing in AsyncStorage:\n */\n /*\n const members = KeyValueStore.get('congress_members');\n if (members == null) {\n fetch(url, this.header)\n .then((response) => response.json())\n .then((responseJson) => {\n const result = responseJson['results']['members'];\n KeyValueStore.set('congress_members', result);\n }\n }\n */\n const url = `https://api.propublica.org/congress/v1/members/${\n bioguide_id}.json`;\n return fetch(url, this.propublicaHeader)\n .then(response => response.json())\n .then(response => response.results[0])\n .catch((error) => {\n console.log(`There was a problem fetching legislator: ${url}`);\n console.log(error);\n });\n }", "async function listVMSkus() {\n const subscriptionId =\n process.env[\"HYBRIDCONTAINERSERVICE_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const customLocationResourceUri =\n \"subscriptions/a3e42606-29b1-4d7d-b1d9-9ff6b9d3c71b/resourceGroups/test-arcappliance-resgrp/providers/Microsoft.ExtendedLocation/customLocations/testcustomlocation\";\n const credential = new DefaultAzureCredential();\n const client = new HybridContainerServiceClient(credential, subscriptionId);\n const result = await client.hybridContainerService.listVMSkus(customLocationResourceUri);\n console.log(result);\n}", "async function loadScript(path, callback) {\r\n\tlet element = document.createElement('script');\r\n\telement.className = \"citation-ext-script\";\r\n\telement.src = chrome.runtime.getURL(path);\r\n\r\n\tdocument.body.appendChild(element);\r\n\r\n\treturn new Promise((resolve, reject) => {\r\n\t\telement.onload = () => {\r\n\t\t\tif(typeof callback === 'function') callback();\r\n\t\t\tresolve();\r\n\t\t}\r\n\t});\r\n}", "function _getCourseList (callback) {\n\t\t_setNotice('loading course list...');\n\n\t\tfetch(_buildApiUrl('courselist'))\n\t\t\t.then((response) => response.json())\n\t\t\t.then((json) => {\n\t\t\t\t//console.log('json.status=' + json.status);\n\t\t\t\tif (json.status !== 'success') {\n\t\t\t\t\t_setNotice(json.message);\n\t\t\t\t}\n\t\t\t\t//console.log('json.data: ' + JSON.stringify(json.data));\n\t\t\t\tsettings.courseList = json.data.courselist;\n\t\t\t\t_setNotice('');\n\t\t\t\tcallback();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\t_setNotice('Unexpected error loading course list');\n\t\t\t\tconsole.log(error);\n\t\t\t})\n\t}", "getComscoreSites(cb) {\n //get all sites /sites\n let self = this;\n this.getGlobalConfig((err) => {\n if (err) cb(err);\n let sites = [];\n self.services.forEach((row) => {\n sites.push('/sites/' + row.site);\n });\n cb(null, sites);\n });\n }", "function getSchoolsData() {\n\n\t$.getJSON(\"js/columbia.json\", function(data, error) {\n\t\tconsole.log(data);\n\t});\n\n}", "function getCouncils(callback) {\n chrome.storage.local.get([\"file-data\"], function (data) {\n // Extract a list of councils from the data.\n let districtInfo = data[\"file-data\"].districtInfo.contents['district-councils'];\n let councils = [];\n for (let council in districtInfo) {\n councils.push(council);\n }\n // Callback with the array of councils.\n callback(councils);\n });\n}", "function initSCORM2004API(API_1484_11, userID, firstName, lastName, minProgressMeasure, timeLimitAction, dataFromLMS) {\n\t/* init the SCORM data list */\n initScorm2004Data(userID, firstName, lastName, minProgressMeasure, timeLimitAction, dataFromLMS);\n\n\t/* create the SCORM API callbacks */\n\tAPI_1484_11.Initialize = Initialize;\n\tAPI_1484_11.Terminate = Terminate;\n\tAPI_1484_11.SetValue = SetValue;\n\tAPI_1484_11.GetValue = GetValue;\n\tAPI_1484_11.GetLastError = GetLastError;\n\tAPI_1484_11.GetErrorString = GetErrorString;\n\tAPI_1484_11.Commit = Commit;\n\tAPI_1484_11.GetDiagnostic = GetDiagnostic;\n}", "async function managedCcfUpdate() {\n const subscriptionId =\n process.env[\"CONFIDENTIALLEDGER_SUBSCRIPTION_ID\"] || \"0000000-0000-0000-0000-000000000001\";\n const resourceGroupName =\n process.env[\"CONFIDENTIALLEDGER_RESOURCE_GROUP\"] || \"DummyResourceGroupName\";\n const appName = \"DummyMccfAppName\";\n const managedCCF = {\n location: \"EastUS\",\n properties: {\n deploymentType: {\n appSourceUri:\n \"https://myaccount.blob.core.windows.net/storage/mccfsource?sv=2022-02-11%st=2022-03-11\",\n languageRuntime: \"CPP\",\n },\n },\n tags: { additionalProps1: \"additional properties\" },\n };\n const credential = new DefaultAzureCredential();\n const client = new ConfidentialLedgerClient(credential, subscriptionId);\n const result = await client.managedCCFOperations.beginUpdateAndWait(\n resourceGroupName,\n appName,\n managedCCF\n );\n console.log(result);\n}", "async function getAllCTokens(block) {\n return (await sdk.api.abi.call({\n block,\n chain: 'heco',\n target: comptroller,\n params: [],\n abi: abi['getAllMarkets'],\n })).output;\n}", "function loadConsentData(cb) {\n let isDone = false;\n let timer = null;\n\n function done(consentData, shouldCancelAuction, errMsg, ...extraArgs) {\n if (timer != null) {\n clearTimeout(timer);\n }\n isDone = true;\n gppDataHandler.setConsentData(consentData);\n if (typeof cb === 'function') {\n cb(shouldCancelAuction, errMsg, ...extraArgs);\n }\n }\n\n if (!cmpCallMap.hasOwnProperty(userCMP)) {\n done(null, false, `GPP CMP framework (${userCMP}) is not a supported framework. Aborting consentManagement module and resuming auction.`);\n return;\n }\n\n const callbacks = {\n onSuccess: (data) => done(data, false),\n onError: function (msg, ...extraArgs) {\n done(null, true, msg, ...extraArgs);\n }\n }\n cmpCallMap[userCMP](callbacks);\n\n if (!isDone) {\n const onTimeout = () => {\n const continueToAuction = (data) => {\n done(data, false, 'GPP CMP did not load, continuing auction...');\n }\n processCmpData(consentData, {\n onSuccess: continueToAuction,\n onError: () => continueToAuction(storeConsentData())\n })\n }\n if (consentTimeout === 0) {\n onTimeout();\n } else {\n timer = setTimeout(onTimeout, consentTimeout);\n }\n }\n}", "async function organizationsListMinimumSetGen() {\n const subscriptionId = process.env[\"NEWRELICOBSERVABILITY_SUBSCRIPTION_ID\"] || \"nqmcgifgaqlf\";\n const userEmail = \"[email protected]\";\n const location = \"egh\";\n const credential = new DefaultAzureCredential();\n const client = new NewRelicObservability(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.organizations.list(userEmail, location)) {\n resArray.push(item);\n }\n console.log(resArray);\n}", "function loadOrganizations() {\n \t\t editPermission.header({\n \t\t token: localStorage.getItem(\"sessionToken\")\n \t\t }).bankNamesOrgId({\n \t\t orgId: commonDataService.getLocalStorage().orgId\n \t\t }, function(data) {\n \t\t $scope.bankList = data.response;\n\n \t\t configureBank()\n \t\t }, function(err) {\n \t\t $scope.bankList = [];\n \t\t });\n\n \t\t}", "async function getADedicatedHsm() {\n const subscriptionId = \"00000000-0000-0000-0000-000000000000\";\n const resourceGroupName = \"hsm-group\";\n const name = \"hsm1\";\n const credential = new DefaultAzureCredential();\n const client = new AzureDedicatedHSMResourceProvider(credential, subscriptionId);\n const result = await client.dedicatedHsmOperations.get(resourceGroupName, name);\n console.log(result);\n}", "function onRuntimeInitialized()\r\n{\r\n cs = new CsoundObj();\r\n\r\n //use this code to load a .csd file and have Csound compile and start it\r\n var fileManger = new FileManager(['csd'], console.log);\r\n fileManger.fileUploadFromServer(\"random.csd\", function(){\r\n cs.compileCSD(\"random.csd\");\r\n cs.start();\r\n cs.audioContext.resume();\r\n });\r\n\r\n csoundLoaded = true;\r\n\r\n}", "function fetchDomains(callback){\n\tchrome.storage.local.get(['selectedDomains'], function(result){\n\t\t\n\t\tif(result.selectedDomains===undefined)\n\t\t\tdomains=[];\n\t\telse\n\t\t\tdomains=result.selectedDomains;\n\n\t\tcallback();\n\t});\n}", "snippetsWorkspaceEncodedIdCommitsGet(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';\n // Configure HTTP basic authorization: basic\n let basic = defaultClient.authentications['basic'];\n basic.username = 'YOUR USERNAME';\n basic.password = 'YOUR PASSWORD';\n // Configure OAuth2 access token for authorization: oauth2\n let oauth2 = defaultClient.authentications['oauth2'];\n oauth2.accessToken = incomingOptions.accessToken;\n\n let apiInstance = new Bitbucket.SnippetsApi(); // String | // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`.\n /*let encodedId = \"encodedId_example\";*/ /*let workspace = \"workspace_example\";*/ apiInstance.snippetsWorkspaceEncodedIdCommitsGet(\n incomingOptions.encodedId,\n incomingOptions.workspace,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }", "function fetchStructure() {\n return $mmaModScorm.getOrganizations(scorm.id).then(function(organizations) {\n $scope.organizations = organizations;\n\n if (!$scope.currentOrganization.identifier) {\n // Load first organization (if any).\n if (organizations.length) {\n $scope.currentOrganization.identifier = organizations[0].identifier;\n } else {\n $scope.currentOrganization.identifier = '';\n }\n }\n\n return loadOrganizationToc($scope.currentOrganization.identifier);\n });\n }", "function loadCldrData(data) {\n registerMain(data.main);\n registerSupplemental(data.supplemental);\n globalize_dist_globalize__WEBPACK_IMPORTED_MODULE_1__[\"load\"](data);\n return Promise.resolve();\n}", "getClusters(region, deployment) {\n console.log('[DataProvider][getClusters] for region: %s deployment: %s begin', region, deployment);\n\n return Promise.timeout(1)\n .then(() => {\n console.log('[DataProvider][getClusters] for region: %s deployment: %s inside begin', region, deployment);\n\n return [\n {\n name: \"hello\",\n state: \"deploy\",\n status: \"inprogres\",\n actions: [{\n name: 'build'\n }, {\n name: 'push'\n }, {\n name: 'undeploy',\n confirm: true\n }]\n },\n {\n name: \"addr\",\n state: \"deploy\",\n status: \"completed\",\n actions: [{\n name: 'build'\n }, {\n name: 'push'\n }, {\n name: 'undeploy',\n confirm: true\n }]\n },\n {\n name: \"img\",\n state: \"undeploy\",\n status: \"error\",\n actions: [{\n name: 'build'\n }, {\n name: 'push'\n }, {\n name: 'deploy'\n }]\n },\n {\n name: \"addrf\",\n state: \"undeploy\",\n status: \"completed\",\n actions: [{\n name: 'build'\n }, {\n name: 'push'\n }, {\n name: 'deploy'\n }]\n }\n ];\n });\n }", "getComscoreSite(site, cb) {\n let self = this;\n dax.site(self.dax, site, c, function(err, data) {\n if (data === undefined) {\n cb(null, 'No continuation ids found');\n } else {\n cb(null, data);\n }\n });\n }", "function init() {\n studentSrv.getStudents().then(function (result) {\n for (let stu in result.data) {\n $scope.manifest.push(result.data[stu]);\n $scope.getStudentCalls.push($http.get(`/api/v1/students/${result.data[stu]}.json`)\n .then(function(result) {\n result.data.id = $scope.manifest[stu];\n result.data.startDate = new Date(result.data.startDate);\n $scope.students.push(result.data);\n }\n ));\n }\n });\n $scope.checkCookies();\n }", "function requestComponentsData() {\n chrome.send('requestComponentsData');\n}", "function retrieveKpccData(data){\n var dataSource = 'http://www.scpr.org/api/content/?types=segmentsORnewsORentries&query=mahony&limit=20';\n jqueryNoConflict.getJSON(dataSource, renderKpccTemplate);\n}", "async function exportsGetBySubscription() {\n const scope = \"subscriptions/00000000-0000-0000-0000-000000000000\";\n const credential = new DefaultAzureCredential();\n const client = new CostManagementClient(credential);\n const result = await client.exports.list(scope);\n console.log(result);\n}", "getStudents(){\n return this.#fetchAdvanced(this.#getStudentsURL()).then((responseJSON) => {\n let studentBOs = StudentBO.fromJSON(responseJSON);\n // console.info(studentBOs);\n return new Promise(function (resolve) {\n resolve(studentBOs);\n })\n })\n\n }", "function getCoAuthors(gsid) {\n\t\t\n\t\tvar publist = getPubList(gsid);\n\t\t\n\t\tvar pubid_authors = d3.nest()\n\t\t\t.key(function (d) { return d.pubid; })\n\t\t\t.rollup(function (d) {\n\t\t\t\tvar authidlist = [];\n\t\t\t\td.forEach(element => {\n\t\t\t\t\tauthidlist.push(element.gsid);\n\t\t\t\t});\n\t\t\t\treturn authidlist;\n\t\t\t})\n\t\t\t.entries(gAuth_pub_univ);\n\n\t\tvar coauthlist = [];\n\t\tpublist.values.forEach(pubid => {\n\t\t\t// get pubs for target author\n\t\t\tvar coauth = pubid_authors.filter(function (d) {\n\t\t\t\treturn pubid == d.key;\n\t\t\t});\n\t\t\t//get each coauth per pub\n\t\t\tvar cPub = coauth[0].key;\n\t\t\tcoauth[0].values.forEach(element => {\n\t\t\t\tif (element != gsid) {\n\t\t\t\t\tvar obj = {};\n\t\t\t\t\tobj[\"key\"] = element;\n\t\t\t\t\tobj[\"value\"] = cPub;\n\t\t\t\t\tcoauthlist.push(obj);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tvar nestedCoAuth = d3.nest()\n\t\t\t.key(function (d) {\n\t\t\treturn d.key;\n\t\t\t})\n\t\t\t.entries(coauthlist);\n\t\treturn nestedCoAuth\n\t}", "async function exportsGetByManagementGroup() {\n const scope = \"providers/Microsoft.Management/managementGroups/TestMG\";\n const credential = new DefaultAzureCredential();\n const client = new CostManagementClient(credential);\n const result = await client.exports.list(scope);\n console.log(result);\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 }", "async function getCourses() {\n return await microcredapi.get(`/unit/${window.localStorage.getItem('userId')}`).then(response => {\n setCourses(response.data.units);\n })\n }", "static async getTerritories(){\n\n\t\t//Get instance of TerritoriesOperations Class\n let territoriesOperations = new TerritoriesOperations();\n\n\t\t//Call getTerritories method\n let response = await territoriesOperations.getTerritories();\n\n if(response != null){\n\n\t\t\t//Get the status code from response\n console.log(\"Status Code: \" + response.statusCode);\n\n if([204, 304].includes(response.statusCode)){\n console.log(response.statusCode == 204? \"No Content\" : \"Not Modified\");\n\n return;\n }\n\n\t\t\t//Get object from response\n let responseObject = response.object;\n\n if(responseObject != null){\n\n\t\t\t\t//Check if expected ResponseWrapper instance is received \n if(responseObject instanceof ResponseWrapper){\n\n\t\t\t\t\t//Get the array of obtained Territory instances\n let territories = responseObject.getTerritories();\n\n territories.forEach(territory => {\n\n\t\t\t\t\t\t//Get the CreatedTime of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory CreatedTime: \" + territory.getCreatedTime());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the ModifiedTime of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory ModifiedTime: \" + territory.getModifiedTime());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the manager User instance of each Territory\n\t\t\t\t\t\tlet manager = territory.getManager();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Check if manager is not null\n\t\t\t\t\t\tif(manager != null){\n\t\t\t\t\t\t\t//Get the Name of the Manager\n\t\t\t\t\t\t\tconsole.log(\"Territory Manager User-Name: \" + manager.getName());\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Get the ID of the Manager\n\t\t\t\t\t\t\tconsole.log(\"Territory Manager User-ID: \" + manager.getId());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the ParentId of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory ParentId: \" + territory.getParentId());\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Get the Criteria instance of each Territory\n\t\t\t\t\t\tlet criteria = territory.getCriteria();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Check if criteria is not null\n\t\t\t\t\t\tif(criteria != null){\n\t\t\t\t\t\t\tthis.printCriteria(criteria);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the Name of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory Name: \" + territory.getName());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the modifiedBy User instance of each Territory\n\t\t\t\t\t\tlet modifiedBy = territory.getModifiedBy();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Check if modifiedBy is not null\n\t\t\t\t\t\tif(modifiedBy != null){\n\t\t\t\t\t\t\t//Get the Name of the modifiedBy User\n\t\t\t\t\t\t\tconsole.log(\"Territory Modified By User-Name: \" + modifiedBy.getName());\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Get the ID of the modifiedBy User\n\t\t\t\t\t\t\tconsole.log(\"Territory Modified By User-ID: \" + modifiedBy.getId());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the Description of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory Description: \" + territory.getDescription());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the ID of each Territory\n\t\t\t\t\t\tconsole.log(\"Territory ID: \" + territory.getId());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Get the createdBy User instance of each Territory\n\t\t\t\t\t\tlet createdBy = territory.getCreatedBy();\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Check if createdBy is not null\n\t\t\t\t\t\tif(createdBy != null){\n\t\t\t\t\t\t\t//Get the Name of the createdBy User\n\t\t\t\t\t\t\tconsole.log(\"Territory Created By User-Name: \" + createdBy.getName());\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Get the ID of the createdBy User\n\t\t\t\t\t\t\tconsole.log(\"Territory Created By User-ID: \" + createdBy.getId());\n\t\t\t\t\t\t}\n });\n }\n //Check if the request returned an exception\n\t\t\t\telse if(responseObject instanceof APIException){\n\t\t\t\t\t//Get the Status\n\t\t\t\t\tconsole.log(\"Status: \" + responseObject.getStatus().getValue());\n\n\t\t\t\t\t//Get the Code\n\t\t\t\t\tconsole.log(\"Code: \" + responseObject.getCode().getValue());\n\n\t\t\t\t\tconsole.log(\"Details\");\n\n\t\t\t\t\t//Get the details map\n\t\t\t\t\tlet details = responseObject.getDetails();\n\n\t\t\t\t\tif(details != null){\n\t\t\t\t\t\tArray.from(details.keys()).forEach(key => {\n\t\t\t\t\t\t\tconsole.log(key + \": \" + details.get(key)); \n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\t//Get the Message\n\t\t\t\t\tconsole.log(\"Message: \" + responseObject.getMessage().getValue());\n\t\t\t\t}\n }\n }\n\t}", "async function exportsGetByResourceGroup() {\n const scope = \"subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG\";\n const credential = new DefaultAzureCredential();\n const client = new CostManagementClient(credential);\n const result = await client.exports.list(scope);\n console.log(result);\n}", "function getRepoContributors(repoOwner, repoName, cb) {\n var options = {\n url: 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN + '@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors',\n headers:{\n 'User-Agent':'request'\n }\n };\n //when you request if the response is good, callback the data in JSON format\n request(options,function(error, response, body){\n if (!error && response.statusCode == 200){\n cb(JSON.parse(body));\n }\n });\n\n}", "async getProgramIndicators(){\r\n const st=this.setting\r\n let url=\"programs/\"+st.programid+\"/programIndicators?fields=id,name,programIndicatorGroups[id,code],aggregateExportCategoryOptionCombo\"\r\n return await this.getResourceSelected(url)\r\n }", "function getBudgetData() {\n budgetFactory.getBudget().then(function(response) {\n var budget = response;\n self.startingMonthID = budget.budget_start_month;\n self.startingYear = budget.budget_start_year;\n setStartingMonth();\n setYears();\n });\n } //end getBudgetData", "async function getSpecifiersDataFromFile(importDataDirectory) {\n const contents = await fs.readFileAsync(path.resolve(`${importDataDirectory}/.import-helper-data`));\n\n this.specifiersMap = JSON.parse(contents);\n this.ready = true;\n}", "function getClusterData (datacenter) {\n let query = 'SELECT cluster.externalIP,cluster.clusterID,cluster.name ' +\n 'FROM cluster LEFT OUTER JOIN equipmentGroup ON cluster.groupUUID=equipmentGroup.uuid ' +\n 'LEFT OUTER JOIN datacenter ON datacenter.uuid=equipmentGroup.datacenterUUID ' +\n 'WHERE datacenter.name=\"' + datacenter + '\"'\n q(query)\n .then(clusters => {\n totalClusters = clusters.length\n for(var c in clusters) {\n let thisCluster = clusters[c]\n cluster.getHosts(thisCluster)\n .then(newClusterData => {\n masterCollection.clusters.push(newClusterData)\n if (done(null,true)) {\n aggregate(masterCollection)\n }\n })\n .catch(err => {\n console.log('Failed to query cluster: ' + thisCluster + ' with err: ' + err)\n if (done(null, true)) {\n aggregate(masterCollection)\n }\n })\n }\n })\n .catch(err => {\n console.log('ERROR querying db: ' + err)\n process.exit()\n })\n}", "async function dataRun(card_name) {\n card_name = encodeURIComponent(card_name);\n // gets set data\n var setData = await nm\n .goto(base_url + find_url + card_name + find_url_end)\n .wait('body')\n .evaluate(() => document.querySelector('body').innerHTML)\n .then( response => {\n return hs.getSetData(response)\n }).catch( err => {\n console.log(err);\n });\n //console.log(setData)\n \n // write set Data to a file, later DB\n fs.writeFile(SET_FILE_FRONT + card_name + SET_FILE_END, JSON.stringify(setData), err => {\n if (err)\n console.log(err);\n } )\n\n var conjoinedCardData = []\n // LOOP through sets\n for (var i = 0; i < setData.length; i++)\n {\n //console.log(setData[i]['set_name'])\n var cardData = await nm\n .goto(base_url + setData[i]['full_href'])\n .wait('body')\n .wait(400)\n .evaluate(() => document.querySelector('body').innerHTML)\n .then( response => {\n return hs.getPriceData(response, setData[i]['set_name']);\n }).catch( err => {\n console.log(err);\n });\n for (var j in cardData)\n {\n conjoinedCardData.push(cardData[j])\n }\n }\n\n console.log(conjoinedCardData)\n nm.end()\n console.log('Completed card request.')\n}", "snippetsGet(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';\n // Configure HTTP basic authorization: basic\n let basic = defaultClient.authentications['basic'];\n basic.username = 'YOUR USERNAME';\n basic.password = 'YOUR PASSWORD';\n // Configure OAuth2 access token for authorization: oauth2\n let oauth2 = defaultClient.authentications['oauth2'];\n oauth2.accessToken = incomingOptions.accessToken;\n\n let apiInstance = new Bitbucket.SnippetsApi();\n let opts = {\n // 'role': \"role_example\" // String | Filter down the result based on the authenticated user's role (`owner`, `contributor`, or `member`).\n };\n\n if (incomingOptions.opts)\n Object.keys(incomingOptions.opts).forEach(\n (key) =>\n incomingOptions.opts[key] === undefined &&\n delete incomingOptions.opts[key]\n );\n else delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.snippetsGet(incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n });\n }", "function gatherResearchPapers(callback){\r\n $.getJSON(GITHUB_RESEARCH, function(data){\r\n \r\n research = data.filter(function(item){\r\n if (item.name != \"readme.json\"){\r\n return item;\r\n }\r\n });\r\n $.getJSON(GITHUB_RESEARCH_INFO, function(data){\r\n research_description = data;\r\n return callback();\r\n })\r\n });\r\n}", "function getChangeSetChanges(projectChangeSetsParam, gConfig, pullPushCommand, res, callback) {\r\n console.log('==> START :: ==> CodeReview.prototype.getChangeSetChanges *****************************');\n projectChangeSetsParam.changeSets.forEach(function (changeSet, index) {\r\n // if (changeSet.changesetId === 18) {\r\n console.log('==> INSIDE :: ==> FOR EACH LOOP CodeReview.prototype.getChangeSetChanges *****************************' + changeSet.changesetId);\n\n var changeSetParam = {};\n changeSetParam.changesetId = changeSet.changesetId;\r\n changeSetParam.author = changeSet.author.displayName;\r\n changeSetParam.changeSetLog = changeSet.comment;\r\n changeSetParam.messageText = \"/visualstudio get changeset \" + changeSet.changesetId + \" List\";\r\n\r\n doCodeReviewProcess(changeSetParam, gConfig, pullPushCommand, res, function (result) {\r\n if (result.statusCode) {\r\n res.send(JSON.stringify({ statusCode: 100, statusMessage: result.Status }));\r\n } else {\r\n callback(result);\r\n }\r\n });\r\n //}\r\n });\r\n}", "function tranFetchAllTc(tcNam) {\r\n\tpromFetchRange(vWork.db.work.handle, tcNam, [0], [99]).then(function (datAry) {\r\n\t\tvWork.al[tcNam] = datAry;\r\n\t\tnextSeq();\r\n }).catch(function (error) {\r\n console.log(error);\r\n });\r\n}", "function rcollaborationGetText(){\n YAHOO.util.Connect.asyncRequest('GET', 'type/rtcollaboration/text.php?id='+pageId+'&group='+groupId+'&mode='+rcollaborationMode, rcollaborationTextCallback, null);\n}", "function fetchCustomDomains () {\n var $errorMessage = $('.custom-domain-error-message'),\n $loader = $('.custom-domain-activity-indicator');\n\n $.get({\n url: scope.domainUrl + 'domains',\n xhrFields: { withCredentials: true }\n })\n .done(function (data) {\n //@todo: This is done for backward compatibility. Need to clear that later.\n renderCustomDomainDropdownItems(data.result || data.domains);\n })\n .fail(function (jqXHR) {\n var response = JSON.parse(jqXHR.responseText),\n defaultError = 'Something went wrong while loading your custom domains.';\n\n $errorMessage\n .text(_.get(response, 'error', defaultError))\n .show();\n })\n .always(function () {\n $loader.hide();\n });\n}", "async function newCourt() {\n code = await generateAccessCode();\n return await insertCourt(code);\n}", "getContributedStories() {\n\n return this._getCollection()\n .then(collection => collection.find().toArray());\n }", "function getCourses(callback) {\n uwclient.get('/courses.json', function (err, res) {\n if (err) return callback(err, null);\n else return callback(null, res.data);\n });\n}", "function getProviders(regionid, successfunction, errorfunction)\n{\n gReturnInfo = null;\n var requestString = gUrl + \"?action=providers&regionid=\" + regionid;\n var request = new XMLHttpRequest();\n request.open(\"Get\", requestString);\n request.send(null);\n // Register a handler to take care of the data on return\n request.onreadystatechange = function ()\n {\n if (request.readyState == 4)\n {\n if (request.status == 200)\n {\n // If we get here, we got a complete valid HTTP response\n var response = request.responseText;\n gReturnInfo = JSON.parse(response);\n if (gReturnInfo.severity)\n {\n if (errorfunction)\n errorfunction();\n return;\n }\n if (successfunction)\n successfunction();\n }\n else\n {\n alert(\"Error processing server request 'getProviders'\");\n }\n }\n } /* end callback function */\n}", "function fetchMasterData(qualName){\n var countryCode = surveyData.survey[0].locale.countryCode;\n var languageCode = surveyData.survey[0].locale.languageCode;\n var countryData = _.where(masterDatas,{masterKey:qualName});\n if(countryData && countryData.length > 0){\n if(countryData[0].hasOwnProperty('data') && countryData[0].data[countryCode] && countryData[0].data[countryCode][languageCode]){\n return (countryData[0].data[countryCode][languageCode]);\n }else{\n return countryData[0];\n }\n }else{\n return countryData;\n }\n }", "async getDataValueProgramIndicators(indicators,periods,ous){ \r\n let url=\"analytics?dimension=dx:\"+indicators+\"&dimension=pe:\"+periods+\"&dimension=ou:\"+ous+\"&displayProperty=NAME\"\r\n return await this.getResourceSelected(url)\r\n \r\n }", "async function reservationRecommendationsByResourceGroupLegacy() {\n const subscriptionId =\n process.env[\"CONSUMPTION_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const scope = \"subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testGroup\";\n const credential = new DefaultAzureCredential();\n const client = new ConsumptionManagementClient(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.reservationRecommendations.list(scope)) {\n resArray.push(item);\n }\n console.log(resArray);\n}" ]
[ "0.52447075", "0.5077303", "0.49935552", "0.49673036", "0.49642342", "0.4940104", "0.4933119", "0.4868681", "0.48507965", "0.48246887", "0.4806166", "0.47330528", "0.47272414", "0.46921158", "0.46838936", "0.46752548", "0.46752185", "0.46715802", "0.46340084", "0.4632241", "0.462247", "0.46199432", "0.4601575", "0.45985222", "0.45703062", "0.45683745", "0.45457372", "0.45424908", "0.4542375", "0.45367485", "0.4506363", "0.45000398", "0.44987002", "0.44982815", "0.4481768", "0.44688553", "0.44624344", "0.44356763", "0.44249684", "0.4424764", "0.44025743", "0.44005507", "0.43983707", "0.43961486", "0.43959802", "0.43836898", "0.43808094", "0.43794918", "0.43728438", "0.4369529", "0.43695223", "0.43598467", "0.4347334", "0.4346318", "0.43455213", "0.43434104", "0.43325782", "0.43316728", "0.43289128", "0.4323582", "0.43151832", "0.43109223", "0.43092895", "0.43070474", "0.4306447", "0.43061602", "0.4305532", "0.42912227", "0.42859468", "0.42825025", "0.42824504", "0.42815953", "0.4281193", "0.42784932", "0.42782968", "0.42692536", "0.4269128", "0.42632604", "0.42590156", "0.42567664", "0.42540577", "0.42522085", "0.42519593", "0.42488843", "0.42455134", "0.42440104", "0.42428243", "0.4234845", "0.4233549", "0.42325005", "0.4230538", "0.42267886", "0.42251766", "0.42220584", "0.42218438", "0.4221417", "0.4220099", "0.42165497", "0.42133453", "0.42131573" ]
0.8683864
0
connexion classique mail + mot de passe
function login(){ var email = document.getElementById('email_field').value; var password = document.getElementById('password_field').value; firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) { // An error happened. var errorMessage = error.message; alert("Error : " + errorMessage); }); document.querySelector('#logDialog').close(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sendLogin() {\n let email = document.getElementById('emailFieldLogin').value;\n let password = document.getElementById('passwordFieldLogin').value;\n\n if (!validateEmail(email)) {\n showErrorMsg(\"Email invalid\");\n } else if (!password) {\n showErrorMsg(\"Password missing\");\n } else {\n clearErrorMsg();\n sendData({\n cmd: \"lin\",\n ema: email,\n psw: password\n }, receiveLogin);\n }\n}", "function connexion(user, motdepasse) {\n if(user == email && motdepasse == mdp) { // -- && = AND\n return true;\n } else {\n return false;\n }\n}", "function enviarMail(mail) {\n mail = confirm(\"Desea recibir mails con novedades?\");\n if (mail == true) {\n alert(\n \"Estaremos enviandole las ultimas novedades a \" +\n localStorage.getItem(\"email\")\n );\n localStorage.setItem(\"mail\", mail);\n \n }\n }", "function connect() {\n pseudo = pseudoInput.value.trim();\n if (pseudo.length === 0) {\n alert(\"Votre pseudo ne doit pas être vide ! \");\n return;\n }\n if (!/^\\S+$/.test(pseudo)) {\n alert(\"Votre pseudo ne doit pas contenir d'espaces ! \");\n return;\n }\n sock.emit(\"login\", pseudo);\n }", "function connect(){\n var password = document.getElementById(\"passwordInput\");\n console.log(\"Mot de passe recu : \" + password.value)\n if (password.value == \"ecam\") {\n console.log(\"Mot de passe accepté, passage a la page suivante\")\n window.location = \"menu&authorized=true\";\n } else {\n console.log(\"Mot de passe refusé, refresh de la page\")\n window.location=\"/\";\n }\n}", "function resultado(){\nvar arroba = document.getElementById(\"inputEmail\").value;\nvar contrasenia = document.getElementById(\"inputPassword\").value;\n\n\n\nvar res = document.getElementById(\"email\"); // busco el id email en el html\nres.innerHTML = arroba //imprimo lo que el usuario ingresa como e-mail\nvar res2 = document.getElementById(\"contrasenia\"); //busco el id de contrasenia en el html\nres2.innerHTML = contrasenia; //imprimo la contraseña que ingrese el usuario\n\nvar titulo = document.getElementById(\"titulo\");\ntitulo.innerHTML= \"Datos de formulario\";\n\n\n}", "function check() {\n var formulaire = document.getElementById(\"utilisateur\");\n if (validateEmail(formulaire.elements[0].value)) { //Format @ mail valide\n if (window.XMLHttpRequest) {// Firefox\n var xhr_object = new XMLHttpRequest(); //Creation objet JSON\n xhr_object.open(\"POST\", \"https://identity2.fr1.cloudwatt.com/v2.0/tokens\", false); //Creation de la requete POST\n xhr_object.setRequestHeader(\"Content-Type\", \"application/json\");\n //Creation objet JSON en argument de la requete\n var obj = '{\"auth\": {\"passwordCredentials\": {\"username\": \"' + formulaire.elements[0].value + '\", \"password\": \"' + formulaire.elements[1].value + '\"}}}';\n xhr_object.send(obj);\n if (xhr_object.readyState === 4 && (xhr_object.status === 200 || xhr_object.status === 0)) {//Si tout Ok\n\n var response = JSON.parse(xhr_object.responseText); //Parsing de la reponse en format JSON\n welcome(response.access.user.name); // Message de bienvenue\n //require(['apps2']);\n selectTenant(response.access.token.id); //Selection du Tenant de l'utilisateur\n }\n else {\n displayForm(\"P\", \"BAD credential !!\")\n }\n } else { // XMLHttpRequest non supporté par le navigateur\n alert(\"Votre navigateur ne supporte pas les objets XMLHTTPRequest...\");\n }\n } else {\n displayForm(\"P\", \"format @ mail invalide\");\n }\n}", "function sendEmail(user, password){\n\n server.send({\n text: \"Hello \" + user.name + \", as per your request, here is your temporary password: \" + password,\n from: \"[email protected]\",\n to: email,\n subject: \"Password reseted\"\n }, function (err, message) {\n if(err){\n response.errorInternalServer(res, err);\n }\n else{\n response.successOK(res, \"Message sent\");\n console.log(message);\n }\n });\n}", "function ingreso() {\n //se ingresa la contraseña, correo y se le da un valor, firebase cacha el error en caso de existir y regresa un console con el error\n var emailadministrador = document.getElementById(\"email\").value;\n var contrasenaadministrador = document.getElementById(\"contraseña\").value;\n \n firebase.auth().signInWithEmailAndPassword(emailadministrador, contrasenaadministrador)\n .catch(function(error) {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n // ...\n console.log(errorCode);\n console.log(errorMessage);\n });\n }", "function mensagemErro(email, passi) {\r\n let mensagem = \"\"\r\n\r\n if (email) { //Ou seja o email não existe\r\n mensagem = \"O mail que introduziu não existe\"\r\n }\r\n else if (passi) { //Se o mail existe mas a pass é true, então é porque o mail e a pass não correspondem\r\n mensagem = \"A password está errada\"\r\n }\r\n\r\n return mensagem\r\n}", "function autoLogin(email,password,result) {\n var url = new Array;\n if(email===\"\" || password===\"\") {\n getAccounts();\n }\n if(email===\"\" && mailText.text.toString() === \"\") {\n result = \"信箱為空!\";\n }\n else if(password===\"\" && passText.text.toString() === \"\") {\n result = \"密碼為空!\";\n }\n else {\n //do httprequest post data to the login url.\n var data = \"\";\n if(result.indexOf(\"magic\")===0) {\n url[0] = \"http://10.1.230.254:1000/fgtauth?\";\n url[1] = \"http://www.gstatic.com/generate_204\";\n data = \"username=\"+mailText.text.toString()+\"&password=\"+passText.text.toString()+\"&4Tredir=http://google.com.tw&\"+result;\n result = httpPost(url,data,\"need_auth\");\n }\n if(result===\"need_auth2\") {\n data = \"user=your-school-email&password=your-pwd&authenticate=authenticate&accept_aup=accept_aup\";\n url[0] = \"https://securelogin.arubanetworks.com/cgi-bin/login\";\n result = httpPost(url[0],data,\"need_auth2\");\n }\n }\n return result;\n}", "function sendMail(name, mail, mesaj) {\n //create transport as SMTP with gmail service\n var transporter = nodemailer.createTransport({\n service: 'gmail',\n auth: {\n user: 'medicalcheck.application',\n pass: 'medicalparola'\n }\n });\n var mailOptions = {\n from: name,\n to: '[email protected]',\n subject: mail,\n text: mesaj,\n };\n transporter.sendMail(mailOptions, function (error, info) {\n if (error) {\n console.log(error);\n }\n else {\n console.log('Email:' + info.response);\n }\n });\n}", "function sendResetPassword(to, id,string){\r\n\r\n let link = \"https://wcu-surveytool.herokuapp.com/setPassword/\" + string ;\r\n //let link = \"http://localhost:3000/confirm/\" + randomString;\r\n //console.log(link);\r\n \r\n const msg = {\r\n to: to,\r\n from:\"[email protected]\",\r\n subject: \"Password Reset\",\r\n text: \"Hello,\\nYou are recieving this email because you have requested a password reset \" + \r\n \"for wcu-surveytool website.\\n\\n\" +\r\n \"\\nLogin with this your new password here:\\t\" +link +\r\n \"\\n\\n--WCU-SurveyTool\"\r\n }\r\n \r\n sgMail.send(msg)\r\n .then(()=>{\r\n console.log(\"Email sent\")\r\n return true;\r\n })\r\n .catch(error=>{\r\n console.log(error);\r\n return false;\r\n })\r\n}", "function checkinscription(){\r\n\tvar one = 0;\r\n\tvar check = true;\r\n\t$('#inscription .submit').click(function(){\r\n\t\tvar login = $('#inscription #login').val();\r\n\t\tvar mail = $('#inscription #mail').val();\r\n\t\tvar pass1 = $('#inscription #pass1').val();\r\n\t\tvar pass2 = $('#inscription #pass2').val();\r\n\r\n\t\tvar login_test = /^[0-9a-zA-Z]{3,}$/;\r\n\t\tvar mail_test = /^[a-z0-9]+([_|\\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\\.|-]{1}[a-z0-9]+)*[\\.]{1}[a-z]{2,6}$/;\r\n\t\tvar pass1_test = /^[0-9a-zA-Z]{5,}$/;\r\n\r\n\t\t//test du champs login ---\r\n\t\tif(!login || !login_test.test(login)){\r\n\t\t\tif(one < 4){\r\n\r\n\t\t\t\t$('#login').after('<span class=\" label label-important\"></span>');\r\n\t\t\t\t$('#login').css('border', '1px solid #b94a47').after(' <span class=\" label label-important\">Minimum 3 caractères et alphanuméric uniquement</span>');\r\n\t\t\t\t$('#login').prev().css('color', '#b94a47').css('font-weight', 'bold');\r\n\t\t\t\tone++;\r\n\t\t\t}\r\n\t\t\tcheck = false;\r\n\t\t}else{\r\n\t\t\t$('#login').css('border', '1px solid green').prev().css('color', 'green').css('font-weight', 'normal');\r\n\t\t\t$('#login').next().text('');\r\n\t\t\tcheck = true;\r\n\t\t}\r\n\t\t//test du champ mail ----\r\n\t\tif(!mail || !mail_test.test(mail)){\r\n\t\t\tif(one < 4){\r\n\r\n\t\t\t\t$('#mail').after('<span class=\" label label-important\"></span>');\r\n\t\t\t\t$('#mail').css('border', '1px solid #b94a47').after(' <span class=\" label label-important\">Cette adresse mail est invalide</span>');\r\n\t\t\t\t$('#mail').prev().css('color', '#b94a47').css('font-weight', 'bold');\r\n\t\t\t\tone++;\r\n\t\t\t}\r\n\t\t\tcheck = false;\r\n\t\t}else{\r\n\t\t\t$('#mail').css('border', '1px solid green').prev().css('color', 'green').css('font-weight', 'normal');\r\n\t\t\t$('#mail').next().text('');\r\n\t\t\tcheck = true;\r\n\t\t}\r\n\r\n\t\t//test du champ mot de pass1----\r\n\t\tif(!pass1 || !pass1_test.test(pass1)){\r\n\t\t\tif(one < 4){\r\n\t\t\t\t$('#pass1').css('border', '1px solid #b94a47').after(' <span class=\" label label-important\"> Il est préférable que votre mot de passe fasse au moins 5 caractères</span>');\r\n\t\t\t\t$('#pass1').prev().css('color', '#b94a47').css('font-weight', 'bold');\r\n\t\t\t\tone++;\r\n\t\t\t}\r\n\t\t\tcheck = false;\r\n\t\t}else{\r\n\t\t\t$('#pass1').css('border', '1px solid green').prev().css('color', 'green').css('font-weight', 'normal');\r\n\t\t\t$('#pass1').next().text('');\r\n\t\t\tcheck = true;\r\n\t\t}\r\n\r\n\t\t// test du champ mot de pass 2\r\n\t\tif(!pass2 || pass2 != pass1){\r\n\t\t\tif(one < 4){\r\n\t\t\t\t$('#pass2').css('border', '1px solid #b94a47').after(' <span class=\" label label-important\"> Vous avez mal comfirmé votre mot de passe</span>');\r\n\t\t\t\t$('#pass2').prev().css('color', '#b94a47').css('font-weight', 'bold');\r\n\t\t\t\tone++;\r\n\t\t\t}\r\n\t\t\tcheck = false;\r\n\t\t}else if(pass2 == pass1){\r\n\t\t\t$('#pass2').css('border', '1px solid green').prev().css('color', 'green').css('font-weight', 'normal');\r\n\t\t\t$('#pass2').next().text('');\r\n\t\t\tcheck = true;\r\n\t\t}\r\n\r\n\treturn check;\t\r\n\t});\r\n}", "async login(email, password)\n {\n let page = this.page;\n\n await page.goto('https://www.welcometothejungle.co/fr', {'waitUntil' : 'load'});\n let login_button = await page.$('a[title=\"Se connecter\"]');\n if (login_button)\n await login_button.click();\n await page.waitForNavigation(); \n \n let email_field = await page.$('input[name=\"email\"]');\n let password_field = await page.$('input[name=\"password\"]');\n let submit_button = await page.$$('button[type=\"submit\"]');\n\n if (email_field && password_field && submit_button.length == 2)\n {\n console.log('login in progress');\n \n await page.focus('#sessions-new-email', {delay: Math.ceil(Math.random() * 200)});\n await page.keyboard.type(email);\n \n await page.focus('input[name=\"password\"]');\n await page.keyboard.type(password, {delay: Math.ceil(Math.random() * 200)});\n \n await submit_button[1].hover();\n await page.waitFor(500);\n \n await submit_button[1].click(); \n await page.waitForNavigation();\n\n if (page.url() == 'https://www.welcometothejungle.co/fr')\n console.log('login success');\n else\n console.log('login failed'); \n }\n else\n {\n console.log('login failed -> try with a better internet connection.');\n } \n }", "function sendForm(){\n try{\n const userNameInput = document.getElementById(\"userName\");\n const passwordInput = document.getElementById(\"password\");\n\n const userName = userNameInput.value;\n const password = passwordInput.value;\n\n if(userName == \"\"){\n notificationService.showError(\"Adja meg felhasználónevét!\");\n }else if(password == \"\"){\n notificationService.showError(\"Adja meg jelszavát!\");\n }else{\n login(userName, password);\n }\n }catch(err){\n const message = arguments.callee.name + \" - \" + err.name + \": \" + err.message;\n logService.log(message, \"error\");\n }\n }", "function registrar_pantalla(conexion)\n{\n\tconexion.send(json_msj({type:'screen_conect'}));\n}", "function val(valor){\n var con = valor.value;\n // var pattmay = /^(?=.*[A-Z]).*$/;\n // var resmay = pattmay.test(cont);\n // var pattmin =/^(?=.*[a-z]).*$/;\n // var resmin = pattmin.test(cont);\n // var pattnum = /^(?=.*\\d).*$/;\n // var resnum =pattnum.test(cont);\n // var pattchar =/^(?=.*[!@#$%&*,.?]).*$/\n // var reschar = pattchar.test(cont);\n // if (!resmay){\n // $('val-feed').html('La contraseña debe contener al menos una mayuscula');\n // document.getElementById('con1').classList.add('is-invalid');\n // document.getElementById('con1').classList.remove('is-valid');\n // }else if(!resmin){\n // $('val-feed').html('La contraseña debe contener al menos una minuscula');\n // document.getElementById('con1').classList.add('is-invalid');\n // document.getElementById('con1').classList.remove('is-valid');\n // }else if(!resnum){\n // $('val-feed').html('La contraseña debe contener al menos un numero');\n // document.getElementById('con1').classList.add('is-invalid');\n // document.getElementById('con1').classList.remove('is-valid');\n // }else if(!reschar){\n // $('val-feed').html('La contraseña debe contener al menos un caracter especial(!@#$%&*,.?)');\n // document.getElementById('con1').classList.add('is-invalid');\n // document.getElementById('con1').classList.remove('is-valid');\n // }else{\n // document.getElementById('con1').classList.add('is-valid');\n // document.getElementById('con1').classList.remove('is-invalid'); \n // }\n var patt= /^(?=.*[!@#$%&*,.?])(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).*$/;\n var res = patt.test(con);\n // console.log(con);\n // console.log(res);\n if(!res){\n document.getElementById('con1').classList.add('is-invalid');\n document.getElementById('con1').classList.remove('is-valid');\n }else{\n document.getElementById('con1').classList.add('is-valid');\n document.getElementById('con1').classList.remove('is-invalid');\n }\n}", "async action() {\n let result = await this.userServiceDI.checkMailInDb({\n email: this.model.email\n });\n if (result != null) {\n let model = {\n body: {\n email: this.model.email,\n uid: result.uid,\n href: (new URL(this.referer)).origin,//this.referer,//CONFIG.FRONT_END_URL,\n name: result.name\n }\n };\n this.mailSenderDI.mailSend({\n xslt_file: EMAIL_TEMPLATE.forgot_password_step_1,\n model,\n email_to: this.model.email,\n language: result.language,\n mail_title: new CodeDictionary().get_trans(\n \"FORGOT_PASSWORD_FIRST_MAIL\",\n \"EMAIL\",\n result.language\n )\n });\n }\n }", "function controle(txt, id_controle) {\r\n var longueur = document.getElementById(id_controle).value.length;\r\n \r\n if (id_controle==\"email\") {\r\n if (document.getElementById(id_controle).value.indexOf('@')==-1 || document.getElementById(id_controle).value.indexOf('.')== -1 ) {\r\n document.getElementById(id_controle).style.border='blue 2px solid';\r\n document.getElementById(\"message\").classList.add(\"alert\", \"alert-danger\");\r\n document.getElementById(\"message\").textContent = \"Votre mail ne semble pas correct\";\r\n\r\n mail = false;\r\n }\r\n else{\r\n \r\n document.getElementById(id_controle).style.border='#ffffff 2px solid';\r\n mail = true;\r\n }\r\n }\r\n}", "function gmailSend(mensaje, nombre){\n const transporter = nodemailer.createTransport({\n service: 'gmail',\n auth:{\n user:'[email protected]',\n pass:'58385772y'\n }\n });\n\n var mailOption = {\n from: '[email protected]',\n to:'[email protected]',\n subject: nombre,\n text: mensaje\n };\n\n transporter.sendMail(mailOption, (error, infor)=>{\n if(error){\n console.log(\"error\");\n }else{\n console.log('Email sent' + infor.response);\n }\n });\n}", "function pruebaemail(valor) {\n\tre = /^([\\da-z_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$/\n\tif (!re.exec(valor)) {\n\t\talert('Formato de correo electónico erróneo, revíselo.');\n\t} else return;\n}", "function Mensaje2Pasajero(texto)\n {\n Mensaje={ servicio : DatosServicio.servicio_numero,\n userId : window.localStorage.getItem(\"Placa\"),\n mensaje : texto,\n accion: \"Mensaje\",\n desdehacia : 'Taxi'\n };\n enviarMsj(Mensaje, true);\n $('#modEnviarMensaje').modal('hide');\n }", "function emailLogin() {\n AccountKit.login(\n 'EMAIL',\n {},\n loginCallback\n );\n }", "function sendEmailForgot() {\n var password = newPss();\n var emailToSendPassword = $(\"#emailSendingInput\").val();\n\n if (!validateForm(emailToSendPassword)) {\n swal(\"טעות\", \"האימייל אינו נכון נסה שנית\", \"warning\");\n $('#emailSendingInput').focus();\n return\n }\n $.ajax({\n type: 'POST',\n url: sendPassByEmail,\n data: {\n email: emailToSendPassword,\n password: password,\n },\n success: function (response) {\n if (response) {\n swal(\"אימייל נשלח\", \"סיסמא חדשה נשלחה לאימייל שצויין\", \"success\");\n $(\"#myForgotPasswordModal\").modal('hide');\n $(\"#myLogin\").modal('hide');\n }\n else\n swal(\"שגיאה\", \"נסיון שליחת אימייל עם סיסמה חדשה נכשל\", \"error\");\n }\n });\n}", "constructor(user, url){//url for password reset\n this.to = user.email;\n this.firstName = user.name.split(' ')[0]; \n this.url = url;\n this.from = `Joseph Wimalasuriya 👻 <${process.env.EMAIL_FROM}>`;\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}", "constructor({ user, password }) {\n this.config = {\n imap: {\n user,\n password,\n host: 'mail.testemail.loanpal.com',\n port: 993,\n tls: true,\n authTimeout: 20000\n }\n };\n this.fetchOptions = {\n bodies: ['HEADER', 'TEXT', '']\n };\n }", "loginWithPassword(password) {\n this.open();\n this.login('[email protected]', password);\n }", "function enviar() {\n const formulario = document.getElementById('formulario');\n \n formulario.addEventListener('submit', (e) => {\n const correoValue = correo.value.trim();\n const contraseñaValue = contraseña.value.trim();\n \n e.preventDefault();//evita que se envien los datos y se refresque la pagina\n \n if (correoValue === \"\") {\n alert(\"Correo vacio\");\n }if (contraseñaValue === \"\") {\n alert(\"Contraseña vacia\")\n }\n \n if (campos.correo && campos.contraseña) {\n //Enviar AJAX\n buscarUsuario(formulario);\n \n //Iniciar sessión\n\n //Cargando\n document.querySelector('#cargando').classList.remove('invisible');//Logo de carga\n document.querySelector('#loguearse').classList.add('invisible');//Esconde el texto del boton\n }else{\n alert(\"No se pudo iniciar sesión\");\n }\n \n }); \n}", "envoyerMail(objet, contenu){\r\n\r\n console.log(\"envoyer un email a \" +\r\n this.mail+\" objet : \" +\r\n objet + \"contenu : \" + contenu );\r\n\r\n\r\n\r\n\r\n\r\n\r\n }", "async function sendMailToUser(user, token, type) {\n let transporter = nodemailer.createTransport({\n host: \"smtp.gmail.com\",\n port: 587,\n secure: false, // true for 465, false for other ports\n auth: {\n user: mail.user, // generated ethereal user\n pass: mail.psw // generated ethereal password\n }\n });\n console.log(type);\n const front_end_endpoint = \"http://localhost:3000/reset?token=\"\n const back_end_endpoint = \"http://localhost:5000/api/emailservice/confirm?token=\"\n // send mail with defined transport object\n if (type == RESETPSW) {\n let info = await transporter.sendMail({\n from: '\"Hiệu trưởng Quân\" <[email protected]>', // sender address\n to: user.email, // list of receivers\n subject: \"Reset Pasword\", // Subject line\n text: \"Click the below link to reset password\", // plain text body\n html: \"<b>Remember don't share this link to another people</b><br/>Link: \" + front_end_endpoint + token // html body\n })\n }\n if (type == VERIFY) {\n let info = await transporter.sendMail({\n from: '\"Hiệu trưởng Quân\" <[email protected]>', // sender address\n to: user.email, // list of receivers\n subject: \"Verify Mail\", // Subject line\n text: \"Thank you for using our service\", // plain text body\n html: \"<b>Click the link below to verify</b><br>Link: \"+ back_end_endpoint+token\n })\n }\n}", "function conexion(usr,contra,ip,puert,db) {\n this.usuario=usr;\n this.contraseña=contra;\n this.IP =ip;\n this.puerto=puert;\n this.DB=db;\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}", "function main(){\n var form = find_password_form();\n\n // Connexion, on rempli si possible, sinon on intercepte\n if(form[\"type\"] == \"login\"){\n login_id = {\"id\": \"Mathieu\", \"password\": \"p4ssw0rd\"}; //Aucun moyen de les récupérer...\n auto_login(form, login_id);\n // On écoute l'envoie du formulaire pour enregistrer id et mdp si changement\n ecouter(form);\n }\n // Inscription, on prérempli\n if(form[\"type\"] == \"signup\"){\n auto_signup(form);\n ecouter(form);\n // On écoute l'envoie du formulaire pour enregistrer id et mdp\n }\n}", "async function main(mailId,Id,pass){\n\n const cryptr = new Cryptr(pass);\n decrptionkey=pass; \n console.log(\"decryption key is \"+decrptionkey)\n let crptID=cryptr.encrypt(Id);\n\n \n let transporter=nodemailer.createTransport({\n service:'gmail',\n auth:{\n user:'[email protected]',\n pass:\"Abhi@11187\"\n }\n });\n var mailOptions={\n from:'[email protected]',\n to:mailId,\n subject:'Reset Password Link',\n text:`Click below link to Reset Your password\n\n http://localhost:4200/auth/reset/`+crptID\n }\n transporter.sendMail(mailOptions,function(error,info){\n if(error){\n console.log(error);\n }\n else{\n console.log(\"Mail send \"+info.response);\n }\n });\n\n // let testAccount = await nodemailer.createTestAccount();\n // let transporter = nodemailer.createTransport({\n // host: \"smtp.ethereal.email\",\n // port: 587,\n // secure: false, \n // auth: {\n // user: testAccount.user, \n // pass: testAccount.pass \n // }\n // });\n\n // let info = await transporter.sendMail({\n // from: '\"Fred Foo 👻\" <[email protected]>', // sender address\n // to: \"[email protected], [email protected]\", // list of receivers\n // subject: \"Hello ✔\", // Subject line\n // text: \"Hello world?\", // plain text body\n // html: \"<b>Hello world?</b>\" // html body\n // });\n\n}", "function loginMessages() {\n if (Session.get(\"sessionLanguage\") === \"portuguese\") {\n FlashMessages.sendError(\"Autenticação falhou\");\n } else {\n FlashMessages.sendError(\"Authentication failed.\");\n }\n}", "function handleRecoverPassword(){\n if(emailValid()){\n console.log(`send me my password to: ${email}`)\n setEmail('')\n }else{\n console.log('invalid')\n }\n }", "function viewPassword( scr_id ){\n if ($('#inputlabel').val() != '') {\n $.ajax({\n url: '../../SM-secrets.php?action=SCR_V',\n type: 'POST',\n data: $.param({'scr_id': scr_id}),\n dataType: 'json',\n success: function(reponse) {\n $('#afficherSecret').show();\n\n var statut = reponse['Statut'];\n var password = reponse['password'];\n var Message = '';\n\n if ( password == null ) {\n password = '('+reponse['l_invalid_mother_key']+')';\n var couleur_fond = '';\n //Message += resultat['responseText'];\n } else {\n var couleur_fond = 'bg-orange '; \n }\n\n if (statut == 'succes') {\n Message += '<p><span>'+reponse['l_host']+' : </span>'+\n '<span class=\"td-aere\">'+reponse['host']+'</span></p>'+\n '<p><span>'+reponse['l_user']+' : </span>'+\n '<span class=\"td-aere\">'+reponse['user']+'</span></p>'+\n '<p><span>'+reponse['l_password']+' : </span>'+\n '<span class=\"'+couleur_fond+'td-aere\">'+password+'</span></p>';\n\n $('#detailSecret').html(Message);\n }\n else if (statut == 'erreur') {\n $('#detailSecret').text(reponse['Message']);\n }\n\n },\n error: function(reponse) {\n alert('Erreur serveur : ' + reponse['responseText']);\n }\n });\n }\n}", "function template_validaCampos_login() {\n\tif (!isVacio($(\"#template_login_email\").val())) {\n\t\tif (correo($(\"#template_login_email\").val())) {\n\t\t\tif (!isVacio($(\"#template_login_pass\").val())) {\n\t\t\t\t$.ajax({\n\t\t\t\t\turl: \"lib_php/login.php\",\n\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\tdataType: \"json\",\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tFBId: $(\"#template_login_FBId\").val(),\n\t\t\t\t\t\tnombre: $(\"#template_login_nombre\").val(),\n\t\t\t\t\t\temail: $(\"#template_login_email\").val(),\n\t\t\t\t\t\tpassword: md5Script($(\"#template_login_pass\").val())\n\t\t\t\t\t}\n\t\t\t\t}).always(function(respuesta_json){\n\t\t\t\t\tif (respuesta_json.isExito == 1) {\n\t\t\t\t\t\turlActual = basename(String(window.location));\n\t\t\t\t\t\tgotoURL(urlActual);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t$(\"#template_alertPersonalizado td\").text(respuesta_json.mensaje);\n\t\t\t\t\t\ttemplate_alertPersonalizado();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$(\"#template_alertPersonalizado td\").text(\"El campo \"+$(\"#template_login_pass\").attr(\"placeholder\")+\" es obligatorio\");\n\t\t\t\ttemplate_alertPersonalizado();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t$(\"#template_alertPersonalizado td\").text(\"El correo \"+$(\"#template_login_email\").val()+\" no es un correo valido\");\n\t\t\ttemplate_alertPersonalizado();\n\t\t}\n\t}\n\telse {\n\t\t$(\"#template_alertPersonalizado td\").text(\"El campo \"+$(\"#template_login_email\").attr(\"placeholder\")+\" es obligatorio\");\n\t\ttemplate_alertPersonalizado();\n\t}\n}", "function sendPassword() {\n AuthService.forgotPassword(vm.user)\n .then(sendPasswordSuccess, sendPasswordError)\n .catch(sendPasswordError);\n // $state.go('app.changePassword');\n }", "function loginTomtGyldig(brukernr) {\r\n Aliases.linkAuthorizationLogin.Click();\r\n\r\n let brukernavn = \"\";\r\n let passord = bruker[brukernr].passord;\r\n loggInn(brukernavn, passord);\r\n\r\n //Sjekk om feilmelding kommer frem: \r\n aqObject.CheckProperty(Aliases.textnodeBeklagerViFantIngenMedDe, \"Visible\", cmpEqual, true);\r\n aqObject.CheckProperty(Aliases.textnodeFyllInnDinEPostadresse, \"contentText\", cmpEqual, \"Fyll inn din e-postadresse\");\r\n\r\n Aliases.linkHttpsTestOptimeraNo.Click();\r\n}", "function seleccionarUsuarioParaPW(usuario){\n document.querySelector('#idUsuarioContrasena').value = usuario[0];\n document.querySelector('#nombreUsuarioContrasena').innerHTML = usuario[1];\n document.querySelector('#emailUsuarioContrasena').innerHTML = usuario[2];\n $('#modalFormUsuarioContrasena').modal('show');\n}", "function loginMe() {\n alert(\"Chào mừng bạn tới trang web !!!\");\n var person = $('#myName').html().trim(); // take account's email => person = [email protected]\n console.log(\"Person: \" + person);\n \n socket.emit('newUser', person);\n \n}", "function sendEmail(email,code) {\n\n var mailOptions, smtpTransporter;\n console.log(\"--------------------------------------------------\");\n smtpTransporter = nodemailer.createTransport({\n host: 'smtp.gmail.com',\n port: 465,\n secure: true,\n auth: {\n user: '[email protected]',\n pass: '18April2018'\n\n }\n });\n console.log(\"--------------------------------------------------\");\n mailOptions = {\n from: '[email protected]',\n to: email,\n subject: 'Validate your account with the password',\n text: \"Your code is \" + code,\n };\n smtpTransporter.sendMail(mailOptions, function (error, info) {\n if (error) {\n console.log(error);\n throw error;\n }\n else {\n console.log('Email sent: ' + info.response);\n }\n\n });\n return smtpTransporter;\n}", "function EnvoyerMail(Commentaire){\n Pool.then(Connection => {\n Connection.query('SELECT T_UTILISATEUR.UTI_MAIL FROM T_UTILISATEUR WHERE T_UTILISATEUR.STA_ID = 2', []).then(RowsUtilisateur => {\n for(let i in RowsUtilisateur){\n var SMTPTransport = Mailer.createTransport(\"SMTP\", {\n host: 'smtp.gmail.com',\n port: 465,\n secure: true, // use SSL\n auth: {\n user: \"[email protected]\",\n pass: \"tutur2408\"\n }\n });\n console.log(RowsUtilisateur[0][0]['UTI_MAIL']);\n var Mail = {\n from: \"[email protected]\",\n to: RowsUtilisateur[0][0]['UTI_MAIL'],\n subject: \"Signaler\"+ Commentaire +\" :\",\n html: \"Nous vous signalons que \"+ Commentaire +\" a été signalé.\"\n }\n SMTPTransport.sendMailt(Mail, (Erreur, Reponse) => {\n if(Erreur){\n return Reponse.status(500).json({Status: 500, Message: \"Le mail n'a pas été envoyé.\"});\n }else{\n return Reponse.status(500).json({Status: 500, Message: \"Le mail a été envoyé.\"});\n }\n SMTPTransport.close();\n });\n }\n });\n });\n}", "login(pwd){\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"LOGIN\",\n\t\t\tparams: pwd\n\t\t});\n\t}", "function conrolEmail (){\n const Email = formValues.Email;\n \n if(regexEmail(Email)){\n \n document.querySelector(\"#email_manque\").textContent = \"\";\n return true;\n }else{\n document.querySelector(\"#email_manque\").textContent = \"E-mail n'ai pas valide\";\n alert(\"E-mail n'ai pas valide\");\n return false;\n }\n\n}", "function Registrarse(){\r\n\r\n\tvar name = document.getElementById('inputName').value;\r\n\tvar email = document.getElementById('input_email').value;\r\n\tvar password = document.getElementById(\"inputPassword1\").value;\r\n\tvar password2 = document.getElementById(\"inputPassword2\").value;\r\n\tvar errores = false;\r\n\t//CHECKEAMOS SI LAS CONTRASEÑAS COINCIDEN\r\n\tif(password.length > 5){\r\n\t\tif(password.toString() == password2.toString()){\r\n\t\t\tfirebaseAuth.createUserWithEmailAndPassword(email, password).catch(function(error) {\r\n\t\t\t\tvar errorCode = error.code;\r\n\t\t\t\tvar errorMessage = error.message;\r\n\r\n\t\t\t\tif (errorCode === 'auth/wrong-password') {\r\n\t\t\t alert('Contraseña equivocada.');\r\n\t\t\t errores = true;\r\n\t\t\t return;\r\n\t\t\t } else {\r\n\t\t\t \terrores = true;\r\n\t\t\t alert(errorMessage);\r\n\t\t\t return;\r\n\t\t\t }\r\n\t\t\t});\r\n\t\t}else{\r\n\t\t\twindow.alert(\"Las contraseñas son distintas, asegurate de escribirlas bien\");\r\n\t\t\treturn;\r\n\t\t}\t\r\n\t}else{\r\n\t\twindow.alert(\"La contraseña debe tener al menos 6 caracteres\");\r\n\t\t\treturn;\r\n\t}\r\n\r\n\tsetTimeout(function(){\r\n\t\tif(errores == false){\r\n\t\t InformacionBaseDatos(email,name);\r\n\t\t}else{\r\n\t\t\tconsole.log(\"problemas\");\r\n\t\t}\r\n\t},1000);\r\n\r\n}", "function logar() {\n firebase.auth().signInWithEmailAndPassword(email, senha)\n .then(result => {\n localStorage.setItem('espistemicapp', result.user.refreshToken);\n console.log(result);\n alert(\"Login feito com sucesso!\");\n })\n .catch((error) => {\n alert(\"Email ou senha inválidos\");\n });\n }", "function sendMail(to,user,tempPassword){\r\n let randomString;\r\n if(user == null){\r\n const slash = /\\//gi;\r\n const period =/\\./gi\r\n randomString = bcrypt.hashSync(to, bcrypt.genSaltSync(9));\r\n randomString = randomString.replace(slash,\"\");\r\n randomString = randomString.replace(period,\"\");\r\n }\r\n else{\r\n //console.log(\"getting from user\")\r\n randomString = user.confirmCode;\r\n }\r\n let link = \"https://wcu-surveytool.herokuapp.com/confirm/\" + randomString;\r\n //let link = \"http://localhost:3000/confirm/\" + randomString;\r\n //console.log(link);\r\n \r\n var msg = {\r\n to: to,\r\n from:\"[email protected]\",\r\n subject: \"Confirmation\",\r\n text: \"Hello,\\nYou are recieving this email because you have been registered \" + \r\n \"for wcu-surveytool website.\\n\\n\" +\r\n \"Please verify your email address using this link below \"+ link +\r\n \"\\n\\n--WCU-SurveyTool\"\r\n }\r\n if(tempPassword != null){\r\n link = \"https://wcu-surveytool.herokuapp.com/setPassword/\" + tempPassword;\r\n msg = {\r\n to: to,\r\n from: \"[email protected]\",\r\n subject: \"Confirmtion\",\r\n text: \"Hello,\\nYou are recieving this email because you have been registered \" + \r\n \"for wcu-surveytool website.\\n\\n\" +\r\n \"Please verify your email address using this link below \"+ link +\r\n \"\\n\\n--WCU-SurveyTool\"\r\n }\r\n }\r\n sgMail.send(msg)\r\n .then(()=>{\r\n console.log(\"Email sent\")\r\n })\r\n .catch(error=>{\r\n console.log(error);\r\n })\r\n if(user == null){\r\n return randomString;\r\n }\r\n}", "function regWebsite(elem){\n var error = new Array( 'Не все поля заполнены', 'Логин и / или e-mail занят', 'Неверный e-mail' );\n var answer = $(elem).parent().find('.dialog');\n var login = $('#reglogin').val();\n var mail = $('#regmail').val();\n var password = $('#regpsw').val();\n var type = 'user';\n var mod = 'reg';\n var subsc = document.getElementById('regsubsc').checked;\n answer.slideUp(350, function(){\n if(login == '' || mail == '' || password == ''){\n answer.removeClass().addClass(\"dialog dialog-danger\").html(error[0]).slideDown(350); \n return false;\n }\n var re = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if(!re.test(mail)){ \n answer.removeClass().addClass(\"dialog dialog-danger\").html(error[2]).slideDown(350); \n return false;\n }\n $.ajax({\n type: \"POST\", \n url: \"/ajax.php\",\n data:{type:type, mod:mod, uname:login, uemail:mail, upass:password, usubsc:subsc},\n success: function(data){\n if(data == 'ok'){\n location.reload();\n }else{\n answer.removeClass().addClass(\"dialog dialog-danger\").html(error[1]).slideDown(350); \n return false;\n }\n },\n });\n }); \n }", "preparingEmailSending() {\n const url = 'mailto:' + this.state.email + '?subject=Your Storj mnemonic&body=' + this.state.mnemonic;\n Linking.openURL(url); \n }", "function enviar_datos_form()\n{\n\tvar ff = Ext.getCmp('form_pass').form;\t\n// console.log(Ext.getCmp('form_pass'));\t\n\t\t\n\tif (ff.isValid() )\n\t{\n\t\tvar pass = Ext.getCmp('pass');\n\t\tvar nuevo_pass = Ext.getCmp('nuevopass');\n\t \tvar repass = Ext.getCmp('repass');\n\t\tvar user_nombre = Ext.getCmp('user_nombre');\n\t\tvar user_apellido = Ext.getCmp('user_apellido');\n\t\t\n\t\tExt.Ajax.request({ \n waitMsg: 'Por favor espere...',\n url: CARPETA+'/cambiar_pass_ad',\n method: 'POST',\n params: {\t\t \n pass \t\t: pass.getValue(),\n nuevopass : nuevo_pass.getValue(),\n repass \t\t: repass.getValue()\n// nombre \t\t: user_nombre.getValue(),\n// apellido \t\t: user_apellido.getValue()\n }, \n success: function(response){ \n var result=eval(response.responseText);\n switch(result){\n case 0:\n Ext.MessageBox.alert('Error','Debe completar correctamente los campos obligatorios');\n //ff.reset();\n pass.focus();\n break;\n case 1:\n Ext.MessageBox.alert('OK','La contrase&ntilde;a fue modificada con &eacute;xito.');\n ff.reset();\n window.location=URL+'/admin/salir';\n break;\n case 2:\n Ext.MessageBox.alert('Error','La contrase&ntilde;a actual ingresada es incorrecta.');\n //ff.reset();\n repass.focus();\n break;\n case 3:\n Ext.MessageBox.alert('Error','Las nuevas contrase&ntilde;as no coinciden.');\n repass.reset();\n break;\t\n default:\n Ext.MessageBox.alert('Error','No se pudo conectar con el servidor. Intente m&aacute;s tarde');\n break;\n } \n },\n failure: function(response){\n var result=response.responseText;\n Ext.MessageBox.alert('Error','No se pudo conectar con el servidor. Intente m&aacute;s tarde'); \n } \n });\n\t\t\t\t\n\t}else{\n\t\tExt.MessageBox.alert('Atenci&oacute;n','Debe completar correctamente los campos obligatorios');\n\t}\n}", "function sendVerificationMail(token, email) {\n var mail = \"<body style='direction:rtl;'><a href='http://www.mh2.co.il/#/verify?string=\" + token + \"'>להפעלת המנוי לחץ כאן</a></body>\";\n var transporter = nodemailer.createTransport({\n service: 'Gmail',\n auth: {\n user: '[email protected]', // Your email id\n pass: 'zflp6g43' // Your password\n }\n });\n var mailOptions = {\n from: '[email protected]', // sender address\n to: email, // list of receivers\n subject: 'מייל אימות משתמש ממחצית השקל', // Subject line\n html: mail //, // plaintext body\n // html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead\n };\n transporter.sendMail(mailOptions, function (error, info) {\n if (error) {\n console.log(error);\n res.json({yo: 'error'});\n } else {\n //console.log('Message sent: ' + info.response);\n res.json({yo: info.response});\n }\n });\n }", "function persona(usr,contra,ip,puert) {\n this.usuario=usr;\n this.contraseña=contra;\n this.IP =ip;\n this.puerto=puert;\n}", "async register(firstName, lastName, email) {\n const termo = strTermo.termo();\n const mail = strEmail.registerEmail(firstName);\n let transporter = nodemailer.createTransport({\n host: \"smtp.gmail.com\",\n port: 465,\n ignoreTLS: false,\n secure: true, // true for 465, false for other ports\n auth: {\n user: \"[email protected]\", \n pass: \"getpet1123\" \n },\n tls:{ rejectUnauthorized: false} //localhost\n });\n let info = transporter.sendMail({\n from: '\"GetPet 🐶🐭\" <[email protected]>',\n to: `${email}, [email protected], [email protected]`,\n subject: `Bem-vindo(a), ${firstName} ${lastName}!`,\n text: \"Mensagem de confirmação de registro\", \n html: `${mail}`, // salvo em src/mail templates\n attachments : [{ filename: 'termo.txt', content: termo }] //salvo em src/files\n });\n return mail;\n }", "function sendPasswordToUser(fld, email, minimizeBtn) {\n\t//send data to php\n\t$.ajax(\n\t{\n\t\turl: 'php_scripts/actions.php',\n\t\ttype: 'POST',\n\t\tdata: 'action=send-password&email='+email,\n\t\tdataType: 'JSON',\n\t\tsuccess: function(data) {\n\t\t\tfld.val(' Password sent!');\n\t\t\t//conver minimize UI to Close UI\n\t\t\tminimizeBtn.val('X');\n\t\t},\n\t\terror: function(response) {\n\t\t\tfld.val(' failed..');\n\t\t\t//conver minimize UI to Close UI\n\t\t\tminimizeBtn.val('X');\n\t\t}\n\t}\n\t);\n}", "function notificaUsuario(mail){\r\n\t\r\n\tvar textoHTML = '<div class=\"modal fade\" id=\"mostrarmodal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"basicModal\" aria-hidden=\"true\">'\r\n\t\ttextoHTML+='<div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\" style=\"text-align:center; background-color:#222; color:#FFF\"\"><h2>Notificacion de usuario</h2></div>'\t\t\r\n\t\ttextoHTML+='<div class=\"modal-body\">' \r\n\t\t\t\r\n\t\ttextoHTML += \"<form class=\\\"form-horizontal\\\" id=\\\"formNotificacion\\\">\";\r\n\t\ttextoHTML += \"\t<input type=\\\"hidden\\\" value=\\\"[email protected]\\\" name=\\\"from\\\"> \";\r\n\t\ttextoHTML += \" <div class=\\\"form-group\\\"><label for=\\\"to\\\" class=\\\"col-sm-2 control-label\\\">Para:<\\/label>\";\r\n\t\ttextoHTML += \"\t<div class=\\\"col-sm-10\\\"><input type=\\\"text\\\" class=\\\"form-control\\\" value=\\\"\"+mail+\"\\\" name=\\\"to\\\" id=\\\"to\\\" readonly=\\\"readonly\\\"><\\/div><\\/div>\";\r\n\t\ttextoHTML += \" \";\r\n\t\ttextoHTML += \" <div class=\\\"form-group\\\"><label for=\\\"subject\\\" class=\\\"col-sm-2 control-label\\\">Asunto:<\\/label>\";\r\n\t\ttextoHTML += \" <div class=\\\"col-sm-10\\\"><input type=\\\"text\\\" class=\\\"form-control\\\" value=\\\"\\\" name=\\\"subject\\\" id=\\\"subject\\\"><\\/div><\\/div>\";\r\n\t\ttextoHTML += \" \";\r\n\t\ttextoHTML += \" <div class=\\\"form-group\\\"><label for=\\\"body\\\" class=\\\"col-sm-2 control-label\\\"><\\/label>\";\r\n\t\ttextoHTML += \" <div class=\\\"col-sm-10\\\"><textarea name=\\\"body\\\" id=\\\"body\\\" class=\\\"form-control\\\"><\\/textarea><\\/div><\\/div>\";\r\n\t\ttextoHTML += \"<\\/form>\";\r\n\t\ttextoHTML += \"\";\r\n\t\t\r\n\t\ttextoHTML+='<div class=\"alert alert-danger\" role=\"alert\" id=\"NotificacionMessage\" style=\"text-align:center; font-size:20px; visibility: hidden\"></div> '\r\n\t\ttextoHTML+='</div><div class=\"modal-footer\">'\r\n\t\ttextoHTML+='<a href=\"#\" id=\"closeModal\" data-dismiss=\"modal\" class=\"btn btn-danger\">Cancelar</a>' \r\n\t\ttextoHTML+=\t'<button type=\"button\" onclick=\"validaNotificaUsuario()\" class=\"btn btn-success\">Enviar</button>'\r\n\t\ttextoHTML+='</div></div></div></div>' \r\n\t \r\n\tdocument.getElementById(\"modalDatos\").innerHTML=textoHTML;\r\n\t$(\"#mostrarmodal\").modal(\"show\");\t\r\n}", "function logueo (email,password){\n //argumentos /en este caso/ de signInWithEmailAndPassword email-password\n firebase.auth().signInWithEmailAndPassword(email,password).then((result) =>{\n window.location.hash = \"#welcome\"; \n })\n .catch( function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n});\n}", "function sendMail(){ \n\tlogincontroller.logincheck(name,password,(err,data)=>{\n \tif(err) throw err;\n \telse{\n \t\tconsole.log(\"\\n------------------------------Compose Mail---------------------------------\\n\\n\")\n \t\tconsole.log(\"------------------------------------------------------------------------------\")\n \t\tconsole.log(\"Sender Name=> \"+data[0].name+\" ---------Sender Email ID => \"+data[0].emailid);\n \t\tconsole.log(\"------------------------------------------------------------------------------\")\n \t\tvar reciever = readline.question(\"Reciever Email Id => \");\n \t\tconsole.log(\"------------------------------------------------------------------------------\")\n \t\tvar subject = readline.question(\"Subject => \");\n \t\tconsole.log(\"------------------------------------------------------------------------------\")\n \t\tvar message = readline.question(\"Message = >\")\n \t\tconsole.log(\"------------------------------------------------------------------------------\\n\")\n\t\tmailcontroller.sendmail(data[0].emailid,reciever,subject,message,(err)=>{\n\t\t\tif(err) throw err;\n\t\t\telse{\n\t\t\t\tconsole.log(\"\\n---------Mail Sent Successfully---------\");\n\t\t\t\tconsole.log(\"\\n---------------------------Welcome \"+data[0].name+\"------------------------\");\n\t\t\t\thomeUI();\n\t\t\t}\n\t\t});\t\n\t\n \t}\n\n });\n\n}", "login (email, password) {\n this.emailInput.setValue(email);\n this.passwordInput.setValue(password);\n }", "function validar_login() {\r\n // body...\r\n // expresion para validar la contraseña\r\n // var contra = /^(?=\\w*\\d)(?=\\w*[A-Z])(?=\\w*[a-z])\\S{8,16}$/; \r\n var usuario = document.getElementById(\"usuario\").value;\r\n var contraseña_login = document.getElementById(\"contraseña_login\").value;\r\n\r\n if (usuario === \"\" || contraseña_login === \"\") {\r\n Swal.fire({\r\n icon: 'warning',\r\n text: 'Todos los campos son obligatorios',\r\n position: 'top',\r\n toast: true,\r\n timer: 5000,\r\n allowQutsidClick: false,\r\n customClass:{\r\n content: 'content-class',\r\n },\r\n\r\n });\r\n document.getElementById(\"usuario\").focus();\r\n return false;\r\n\r\n } \r\n\r\n else if (usuario.length>30) {\r\n Swal.fire({\r\n icon: 'warning',\r\n text: 'Nombre de usuario muy largo maximo 30 caracteres',\r\n position: 'top',\r\n toast: true,\r\n timer: 5000,\r\n allowQutsidClick: false,\r\n customClass:{\r\n content: 'content-class',\r\n },\r\n\r\n });\r\n document.getElementById(\"usuario\").focus();\r\n document.getElementById(\"usuario\").value=\"\";\r\n return false;\r\n\r\n\r\n\r\n }else if (contraseña_login.length>16) {\r\n Swal.fire({\r\n icon: 'warning',\r\n text: 'Contraseña muy larga maximo 16 caracteres',\r\n position: 'top',\r\n toast: true,\r\n timer: 5000,\r\n allowQutsidClick: false,\r\n customClass:{\r\n content: 'content-class',\r\n },\r\n\r\n });\r\n document.getElementById(\"contraseña_login\").focus();\r\n document.getElementById(\"contraseña_login\").value=\"\";\r\n return false;\r\n\r\n\r\n }\r\n\r\n\r\n\r\n}", "async handle ({ name, email, token }) {\n const link = `${Env.get('URL_FRONT')}confirm?token=${token}`\n\n await Mail.send(\n ['mails.confirm_new_user', 'mails.confirm_new_user-text'],\n {\n name,\n email,\n token,\n link\n },\n message => {\n message\n .to(email)\n .from('[email protected]', 'Equipe Future Soluções')\n .subject('Confirme seu cadastro [ Future Soluções ]')\n }\n )\n }", "async login() {\n const I = this;\n I.amOnPage('/');\n I.fillField('input[type=\"email\"]', '[email protected]');\n I.fillField('input[type=\"password\"]', 'Heslo123');\n I.click(locate('button').withText('Prihlásiť sa'));\n }", "function gotoServer(email, name, type) {\n $http.post(RestURL.baseURL + 'j_spring_social_security_check?email=' + email + '&username=' + name + '&socialtype=' + type)\n .success(function (data) {\n $log.log(\"Valid login: \", JSON.stringify(data));\n if (data.status == \"failed\") {\n $scope.errormessage = \" Your user name or password is wrong. Please try again!\";\n loginform['email'].$dirty = true;\n loginform['password'].$dirty = true;\n } else {\n var user = data;\n authFactory.setUser(user);\n $location.url(\"/en-US/projects\");\n }\n }).error(function () {\n console.log(\"ERROR WITH SOCIAL SIGNIN\");\n });\n }", "function cekpass(){\n\tvar p2 = $('#passBTB2').val();\n\tvar p1 = $('#passBTB1').val();\n\tif(p2==p1){ // notif ketika sama\n\t\t$('#passinfo').html('<span class=\"label label-success\">password sesuai</span>'); \n\t}else{ //notif ketika beda/salah\n\t\t$('#passinfo').html('<span class=\"label label-important\">password harus sama</span>');\n\t}\n}", "function enviar_email(){\n\t\n\tvar ta= $(\".texemail\").val();\n\t\n\t\t$.ajax({\n\t\t\turl:\"enviar_correo.php\",\n\t\t\ttype:\"post\",\n\t\t\tdata:\"correo=\"+$(\"#selectmultiple\").val()+\"&mens=\"+ta+\"&info=\"+2,\n\t\t\tbeforeSend:function(){\n\t\t\t\t$(\"#enviar_email\").attr(\"disabled\",\"disabled\");\n\t\t\t\t$('.validar').html(\"<span class='mensajes_info_correo'>Enviando...</span>\");\n\t\t\t},\n\t\t\tsuccess:function(data){\n\t\t\t\t$('.validar').html(data);\n\t\t\t\t$(\"#enviar_email\").removeAttr(\"disabled\");\n\t\t\t}\n\t\t});\n}", "getUserLogin(userMail: string, callback: Function) {\n super.query(\n \"select mail, password from user where mail=? \",\n [userMail],\n callback\n );\n }", "function ConvalidaLogin() {\r\n\t\t// definisce la variabile booleana blnControllo e la setta a false\r\n\t\tvar blnControllo = false;\r\n \r\n\t\t// controllo del nome utente inserito \r\n if (document.getElementById(\"txtNomeUtente\").value.length ==0) {\r\n\t\t\t//alert (\"Non hai inserito il nome utente!\");\r\n\t\t\tsetTimeout(\"document.getElementById(\\\"txtNomeUtente\\\").focus();\", 1);\t\t\t// la setTimeout serve a farlo funzionare con FF\r\n\t\t\treturn;\r\n } \r\n\t\telse {\r\n\t\t\tblnControllo = true;\r\n }\r\n \r\n\t\t// controllo della password inserita\r\n if (document.getElementById(\"txtPassword\").value.length ==0) {\r\n\t\t\t//alert (\"Non hai inserito la password!\");\r\n\t\t\tsetTimeout(\"document.getElementById(\\\"txtPassword\\\").focus();\", 1);\t\t\t// la setTimeout serve a farlo funzionare con FF\r\n\t\t\treturn;\r\n } \r\n\t\telse {\r\n blnControllo = true;\r\n }\r\n \r\n return;\r\n } // chiusura della function ConvalidaLogin\t", "function ingreasar() {\n if (txtCor.Value==\"\" || txtCor.value==null){\n alert(\"ingrese su correo\");\n txtCor.focus();\n }else if(txtCon.value==\"\" || txtCon.value==null){\n alert(\"ingrese su contraseña\");\n txtCon.focus();\n }else{\n //capturando valores\n var cor=txtCor.value;\n var con=txtCon.value;\n //llamamos ala funcion de firebase para validar el usuario \n auth.signInWithEmailAndPassword(cor, con)\n .then((userCredential) => {\n alert(\"bienvenidos al sistema\")\n //nos dirigimos ala pagina 11\n window.location=\"pagina11.hmtl\";\n\n })\n .catch((error) => {\n alert(\"Usuario o clave no valida\")\n //var errorcode = error .code;\n //var errorMensaje = error .menssage\n })\n }\n}", "function enviarAyuda(correoUser, asunto, motivo, mensaje) {\n if (validarMail(correoUser.toUpperCase())) {\n enviarCorreo(\"[email protected]\", \"ayuda\", \"Ayuda: \" + motivo + \" - \" + asunto, mensaje);\n enviarCorreo(correoUser, \"ayuda\", \"Ayuda: \" + motivo + \" - \" + asunto, mensaje);\n } else {\n alert(\"Email no válido\");\n }\n}", "constructor (pNombres, pApellidos, pIdentificacion, pnIdentificacion, pCelular, pCorreoE, pPassword){\n this.nombres=pNombres\n this.apellidos=pApellidos\n this.identificacion=pIdentificacion\n this.nIdentificacion=pnIdentificacion\n this.celular=pCelular\n this.correoE=pCorreoE\n this.password=pPassword \n }", "function entrar() {\n\t\tif (debug) {\n\t\t\tconsole.log(\"Entrando...\");\t\n\t\t}\n\n\t\tif ($(\"#email\").val().length <= 0 || $(\"#senha\").val().length <= 0) {\n\t\t\tmensagemErro(\"Informe o usu&aacute;rio / senha!\");\n\t\t\t$(\"#email\").focus();\n\t\t} else {\n\t\t\tvar params = {\n\t\t\t\t'email' : $(\"#email\").val(),\n\t\t\t\t'senha' : $(\"#senha\").val(),\n\t\t\t\t'lembrarSenha' : $(\"#lembrarSenha\").prop('checked') ? \"1\" : \"0\"\n\t\t\t};\n\n\t\t\t$.ajax({\n\t\t\t\turl : \"login.login.action\",\n\t\t\t\ttype : \"POST\",\n\t\t\t\tdata : params,\n\n\t\t\t\tbeforeSend : function(data) {\n\t\t\t\t\t// debug(\"loading...\");\n\t\t\t\t},\n\n\t\t\t\tsuccess : function(data) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tconsole.log(data);\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tvar retorno = $.parseJSON(data);\n\t\t\t\t\t\n\t\t\t\t\tif (retorno.sucesso) {\n\t\t\t\t\t\tfinalLogin();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmensagemErro(retorno.mensagem);\n\t\t\t\t\t\t$(\"#login\").focus();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror : function(erro) {\n\t\t\t\t\t// debug(\"Erro no load ajax! \" + erro);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}", "async function existingUser(mail, pass) {\n // validating for user login\n try {\n const email = mail.value.toLowerCase().trim();\n const password = pass.value.trim();\n if (!email || !password) throw new Error(\"Please fill the form completely!\");\n\n const getData = await model.GET(email);\n\n if (email !== getData.email || password !== getData.pass)\n throw new Error(\"Invalid email or password\");\n\n // if login successful displaying mailme UI\n formLoaderAnimation(getData)(email);\n } catch (err) {\n errorHandler(err);\n }\n}", "async function login(Email, Contrasena) {\n const { data } = await Axios.post(`${ROOT_URL}/auth/login`, {\n Email,\n Contrasena\n });\n setUser(data.user);\n setToken(data.token);\n }", "processPassRep() {\n if (this.password.value !== this.passwordRepeat.value) {\n this.passwordRepeat.err = true;\n this.passwordRepeatErr.seen = true;\n this.valid = false;\n this.passwordRepeatErr.text = \"رمز عبور و تکرار آن یکسان نیستند\";\n } else {\n this.passwordRepeat.err = false;\n this.passwordRepeatErr.seen = false;\n }\n }", "function loginGyldigTomt(brukernr) {\r\n Aliases.linkAuthorizationLogin.Click();\r\n\r\n let brukernavn = bruker[brukernr].epost;\r\n let passord = \"\";\r\n loggInn(brukernavn, passord);\r\n\r\n //Sjekk om feilmelding kommer frem: \r\n aqObject.CheckProperty(Aliases.textnodeBeklagerViFantIngenMedDe, \"Visible\", cmpEqual, true);\r\n aqObject.CheckProperty(Aliases.textnodeFyllInnDittPassord, \"contentText\", cmpEqual, \"Fyll inn ditt passord\");\r\n \r\n Aliases.linkHttpsTestOptimeraNo.Click();\r\n}", "Mailing(orderNb) {\r\n const to = [\"[email protected]\"];\r\n email(to, {\r\n subject: \"Commande numéro : \" + orderNb,\r\n body:\r\n \" Veuillez détailler le problème que vous rencontrez au sujet de la commande numéro :\" +\r\n orderNb,\r\n }).catch(console.error);\r\n }", "function ChequearClave() {\n password= $(\"#password\").val()\n repassword=$(\"#repassword\").val()\n if ( password != repassword){\n $('#mjsRegistro').text(\"Las claves no coinciden!\");\n // alert('no clave')\n $(\"#repassword\").focus()\n \n }else if ( password == repassword){\n $('#mjsRegistro').text(\"\");\n } \n}", "async function sendMail(req, res) {\n const transporter = nodemailer.createTransport({\n host: process.env.HOSTMAIL,\n port: process.env.PORTMAIL,\n secure: false,\n auth: {\n user: process.env.USERMAIL,\n pass: process.env.PASSMAIL,\n },\n tls: {\n rejectUnauthorized: false,\n },\n });\n\n try {\n const respostaAdmin = await transporter.sendMail({\n from: `${req.body.nome} <${req.body.email}>`,\n to: [process.env.USERMAIL],\n replyTo: req.body.email,\n subject: \"Novo cadastro - Newsletter Fortuna Digital\",\n text: \"\",\n html: `\n <strong>Nome:</strong> ${req.body.nome}\n <br />\n <strong>Email:</strong> ${req.body.email}`,\n });\n\n const respostaCliente = await transporter.sendMail({\n from: `Fortuna Digital <${process.env.USERMAIL}>`,\n to: [req.body.email],\n replyTo: process.env.USERMAIL,\n subject: \"Ebook Fortuna Digital\",\n text: \"\",\n html: `\n <div style=\"display: flex; align-items: center; justify-content: center;\">\n <img style=\"width: 40px; height: 40px; margin: 10px;\" src=\"http://fortunadigitalacademy.com.br/images/globo.png\" />\n <h1>FORTUNA DIGITAL</h1>\n </div>\n <h2><strong>Olá, ${req.body.nome}!</strong></h2>\n <p>Obrigado por se cadastrar em nossa newsletter.</p>\n <p><strong><a href=\"https://www.fortunadigitalacademy.com.br/ebook/EBOOK_FORTUNA_DIGITAL.pdf\">Clique aqui e baixe seu ebook gratuitamente.</a></strong></p>`,\n });\n\n console.log(respostaAdmin);\n console.log(respostaCliente);\n res.send(respostaAdmin);\n } catch (error) {\n res.send(error);\n }\n}", "function checkPass() {\n\n\t//mengambil object dan dimasukan ke variabel \n\tvar pass_1 = document.getElementById('password');\n\tvar pass_2 = document.getElementById('password2');\n\t//mengambil object dan dimasukan ke variabel \n\tvar message = document.getElementById('pesan');\n\t//inisialisasi warna didalam variabel\n\tvar warnabenar = \"#66cc66\";\n\tvar warnasalah = \"#ff6666\";\n\t//membandingkan 2 variabel\n\tif (pass_1.value == pass_2.value) {\n\t\t//ketika password benar \n\t\t//ubah menjadi warna jelek\n\t\t//memeberi peringatanya bahwa benar\n\t\tdocument.validasi_form.daftar_process.disabled = false;\n\t\tpass_2.style.backgroundColor = warnabenar;\n\t\tmessage.style.color = warnabenar;\n\t\tmessage.innerHTML = \"\"\n\t} else {\n\t\t//ini ketika password tidak cocok\n\t\t//ubah menjadi warna jelek\n\t\t//memeberi peringatanya bahwa salah dengan tanda seru\n\t\tdocument.validasi_form.daftar_process.disabled = true;\n\t\talert(\"Password tidak Cocok!\");\n\t\tpass_2.style.backgroundColor = warnasalah;\n\t\tmessage.style.color = warnasalah;\n\t\tmessage.innerHTML = \"!\"\n\t}\n}", "function cambiarIdioma(idioma) {\n\t\tvar elTitulo = document.getElementById(\"form-signin-heading\");\n\t\tvar elEmail = document.getElementById(\"ingresoEmail\");\n\t\tvar elRemember = document.getElementById(\"remember\");\n\t\tvar elIngresarCta = document.getElementById(\"ingresarCta\");\n\n\t\tif(idioma == \"es\") {\n\t\t\telTitulo.innerHTML = \"Ingresa a tu cuenta\";\n\t\t\telEmail.innerHTML = \"Ingresa tu email\";\n\t\t\tdocument.getElementById(\"inputPassword\").setAttribute(\"placeholder\",\"Contraseña\");\n\t\t\telRemember.innerHTML = \"Recordar contraseña\";\n\t\t}\n\t\telse if(idioma == \"en\") {\n\t\t\telTitulo.innerHTML = \"Please sing in\";\n\t\t\telEmail.innerHTML = \"Please enter your email\";\n\t\t\tdocument.getElementById(\"inputPassword\").setAttribute(\"placeholder\",\"Password\");\n\t\t\telRemember.innerHTML = \"Remeber me\";\n\t}\n}", "function jsdomEndpointAccedi(req, res, urlFile, mail, password) {\r\n database.selectUtente(mail, password, function(giocatoreTemp) {\r\n if (giocatoreTemp != null) {\r\n giocatore = giocatoreTemp;\r\n database.terminaConnessione();\r\n let data = fs.readFileSync(\"./html/\" + urlFile);\r\n let mioJsdom = new JSDOM(data);\r\n let tagAccedi = mioJsdom.window.document.getElementById(\"Accedi\");\r\n tagAccedi.innerHTML = \"Benvenuto \" + giocatore.getUsername();\r\n let tagHumburger = mioJsdom.window.document.getElementById(\"AccediHumburger\");\r\n tagHumburger.innerHTML = \"Benvenuto \" + giocatore.getUsername();\r\n res.send(mioJsdom.window.document.documentElement.outerHTML);\r\n } else {\r\n let ritorno = fs.readFileSync(\"./html/accedi.html\");\r\n res.send(ritorno.toString());\r\n }\r\n });\r\n}", "function sendMail() {\n var link = \"mailto:\" + encodeURIComponent(document.getElementById('correo_D').value)\n + \"?cc=\" \n + \"&subject=\" + encodeURIComponent(document.getElementById('asunto').value)\n + \"&body=\" + encodeURIComponent(document.getElementById('mensaje').value)\n ;\n \n window.location.href = link;\n}", "async function sendUserDetails(){\nvar transporter = nodemailer.createTransport({\n host: \"smtp-mail.outlook.com\", // hostname\n secureConnection: false, // TLS requires secureConnection to be false\n port: 587, // port for secure SMTP\n tls: {\n ciphers:'SSLv3'\n },\n auth: {\n user: '[email protected]',\n pass: 'Kapoor@91'\n }\n});\n// const emailCreated = myMod.emailCreated\n console.log(`email is from nodemailer ${myMod}`)\n const mailOptions = {\n from: '[email protected]',\n to : '[email protected]',\n subject: 'Login credentials for Chatttel',\n text: \"Hello world? Manu\", // plain text body\n html: \"<div><label>Username:</div>\" // html body\n};\n\n // send mail with defined transport object\n\n let info = await transporter.sendMail(mailOptions, function(error, info){\n if (error) {\n console.log(error);\n } else {\n console.log('Email sent: ' + info.response);\n res.redirect('/');\n }\n });\n\n}", "function comentario(){\n event.preventDefault();\n $('#msg_email').html('');\n var nome = $('#nome').val();\n var email = $('#email').val();\n if (!IsEmail(email)) {\n $('#msg_email').html('Email invalido !').css('color','#EB0000');\n $('#email').focus();\n return False;\n }\n var message = $('#message').val();\n // pegando data de hj\n var d = new Date();\n var month = d.getMonth()+1;\n var day = d.getDate();\n var output = d.getFullYear() + '/' +\n (month<10 ? '0' : '') + month + '/' +\n (day<10 ? '0' : '') + day;\n\n var msg =\n ['<article>',\n '<header class=\"mensagem\">',\n '<h1>Comentario</h1>',\n 'Data: <time class=\"updated\" pubdate>'+output+'</time>',\n 'Nome:<p>'+nome+'</p>',\n '</header>',\n '<p class=\"mensagem\">'+message+'</p>',\n '</article>'\n ].join('\\n');\n $('section:first').append(msg).hide().fadeIn(1000);\n limpaform('contactform');\n return false;\n}", "function checa_email(campo) {\r\n\tvar mensagem = \"Informe corretamente endereco e-mail\"\r\n\tvar msg = \"\";\r\n\tvar email = /^\\w+[\\+\\.\\w-]*@([\\w-]+\\.)*\\w+[\\w-]*\\.([a-z]{2,4}|\\d+)$/i\r\n\r\n\tvar returnval = email.test(campo)\r\n\tif (returnval == false) {\r\n\t\tmsg = mensagem;\r\n\t}\r\n\r\n\treturn msg;\r\n}", "function anonima(){\r\n \r\n var http=new XMLHttpRequest();\r\n http.onreadystatechange=function(){\r\n console.log(\"llegó respuesta\", http.readyState, http.status);\r\n if(http.readyState==4){\r\n if(http.status===200){\r\n console.log(\"tenemos respuesta\",http.responseText);\r\n \r\n }\r\n /* funcion anonima. **/\r\n }\r\n }\r\n var pass=document.getElementById(\"pass\").value;\r\n var name=document.getElementById(\"txtUser\").value;\r\n console.log(pass);\r\n console.log(name);\r\n http.open(\"GET\",\" http://localhost:1337/login?usr=\"+pass+\"&pass=\"+name);\r\n http.send();\r\n}", "validarPassword() {\n if (!this.validador.validarPassword(this.state.password)) {\n // TO DO: mecanismo para informar qué \n Alert.alert('Error', `La contraseña debe tener al menos ${this.validador.passwordMinLength} caracteres.`);\n return false;\n }\n return true;\n }", "function login(mail, pass) {\n\n\tvar email = mail ? mail : $('#login input[name=\"txt_email\"]').val();\n\tvar password = pass ? pass : $('#login input[name=\"txt_password\"]').val();\n\t$.ajax({\n\turl: 'api.php',\n\ttype: 'post',\n\tdata: {'login': true, 'txt_email': email, 'txt_password': password},\n\tsuccess: function(json) {\n\t\tif(json.status == 'success'){\n\t\t\twindow.location.replace(\"home.php\");\n\t\t}\n\t\telse if(json.status == 'error'){\n\t\t\t$('#login .error').html(json.data);\n\t\t}\n\t},\n\terror: function(xhr, desc, err) {\n console.log(xhr);\n console.log(\"Details: \" + desc + \"\\nError:\" + err);\n\t}\t\n\t});\n}", "function signup() {\n let Username = document.getElementById('Username').value\n let email = document.getElementById('email').value\n let password = document.getElementById('password').value\n\n localStorage.setItem('Username', Username)\n localStorage.setItem('email', email)\n localStorage.setItem('password', password)\n\n if (Username && email && password != \"\") {\n\n // alert(\"SignUp successfully\")\n success()\n sendmail(Username, email, password)\n setTimeout(backtohomepage, 3000);\n }\n else {\n // alert(\"Fill The Form !!!!!\")\n error()\n\n }\n}", "function validerConnexionCompteExistant(form,document){\r\n \r\n login=form.vlogin.value;\r\n password=form.vpassword.value;\r\n formulaireValide = false;\r\n \r\n\tif(\t\r\n\t\t(login == \"\"\r\n\t\t|| \tlogin == null)\r\n\t\t&&\r\n\t\t(password == \"\"\r\n\t\t|| \tpassword == null)) {\t\t\t\r\n\t\talert(\"Veuillez remplir votre login ainsi que votre mot de passe.\");\t\t\r\n\t\tdocument.getElementById(\"vloginError\").innerHTML =\"Le login est obligatoire.\";\r\n\t\tdocument.getElementById(\"vpasswordError\").innerHTML =\"Le mot de passe est obligatoire.\";\r\n\t\treturn false;\r\n\t}\r\n\telse if(\r\n\t\t(login != \"\" \r\n\t\t&& login != null)\r\n\t\t&& \r\n\t\t(password == \"\"\r\n\t\t|| \tpassword == null)){\t\t\r\n\t\tdocument.getElementById(\"vloginError\").innerHTML =\"\";\r\n\t\tdocument.getElementById(\"vpasswordError\").innerHTML =\"Le mot de passe est obligatoire.\";\r\n\t\treturn false;\r\n\t}else if(\r\n\t\t(login == \"\" \r\n\t\t|| login == null)\r\n\t\t&& \r\n\t\t(password != \"\"\r\n\t\t&& password != null\r\n\t\t&& password.length%8 != 0)){\t\t\r\n\t\tdocument.getElementById(\"vloginError\").innerHTML =\"Le login est obligatoire.\";\r\n\t\tdocument.getElementById(\"vpasswordError\").innerHTML =\"Le mot de passe doit avoir une taille multiple de 8.\";\r\n\t\treturn false;\r\n\t}else if(\t\r\n\t\t(login == \"\"\r\n\t\t|| \tlogin == null)\r\n\t\t&&\r\n\t\t(password != \"\"\r\n\t\t&& password != null\r\n\t\t&& password.length%8 == 0)){\t\t\t\t\r\n\t\tdocument.getElementById(\"vloginError\").innerHTML =\"Le login est obligatoire.\";\r\n\t\tdocument.getElementById(\"vpasswordError\").innerHTML =\"\";\r\n\t\treturn false;\r\n\t}\t\t\r\n return true;\r\n}", "loginWithPassword(email: string, password: string) {\n if (global.__DEV__) console.log('Logging in with email and password.');\n const options = { user: { email }, password };\n return this.login(options);\n }", "function monUtilisateurEstCorrect(emailUser,mdpUser){\n if(emailUser === email && mdpUser === mdp){\n return true\n } else{\n return false\n }\n}", "function checkRegister() \r{\r\tvar u;\r\tvar p1;\r\tvar p2;\r\tvar em;\r\tvar ret = true;\r\t\r\t// Tomamos los valores de los campos del formulario\r\tu = document.getElementById(\"username\").value;\r\tp1 = document.getElementById(\"password\").value;\r\tp2 = document.getElementById(\"password2\").value;\r\tem = document.getElementById(\"email\").value;\r\r\t// refresca (Por si ha habido una llamada anterior a la función. Se necesita\r\t// para que no subraye como errores cosas que lo eran en la llamada anterior\r\t// pero que en la nueva llamada no lo son)\r\tdocument.getElementById(\"userlabel\").className = \"none\";\r\tdocument.getElementById(\"p1label\").className = \"none\";\r\tdocument.getElementById(\"p2label\").className = \"none\";\r\tdocument.getElementById(\"maillabel\").className = \"none\";\r\r\t// Errores sintácticos referidos al usuario el password y el email\r\tvar userError = checkUser(u);\r\tvar passError = checkPass(p1, p2);\r\tvar emailError = checkMail(em);\r\r\t// Si se ha producido error, lo escribe\r\tif (userError + passError + emailError)\r\t{\r\t\tdocument.getElementById(\"userError\").innerHTML = userError;\r\t\tdocument.getElementById(\"passError\").innerHTML = passError;\r\t\tdocument.getElementById(\"emailError\").innerHTML = emailError;\r\r\t\t// Ponemos el valor a vacio, para que la contraseña no permanezca en el\r\t\t// campo de texto si ha habido un error\r\t\tdocument.getElementById(\"password\").value = \"\";\r\t\tdocument.getElementById(\"password2\").value = \"\";\r\t\tret = false;\r\t}\r\r\treturn ret;\r}", "function validateLogin(e) {\n\t\tlet errorMsj = document.getElementById(\"errorMsj\");\n\t\tconst email = document.getElementById(\"email\").value,\n\t\t\tpassword = document.getElementById(\"password\").value;\n\t\tconst regexEmail = /^(([^<>()[\\]\\\\.,;:\\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,}))$/;\n\n\t\tif (email === \"\" || password === \"\") {\n\t\t\te.preventDefault();\n\t\t\tconsole.log(\"* Debe llenar los campos email y password!\");\n\t\t\terrorMsj.innerHTML = \"* Debe llenar los campos email y password!\";\n\t\t\terrorMsj.style.display = \"block\";\n\t\t} else if (regexEmail.test(email) === false) {\n\t\t\te.preventDefault();\n\t\t\terrorMsj.innerHTML = \"* Correo electronico invalido o no existe!\";\n\t\t\terrorMsj.style.display = \"block\";\n\t\t\tconsole.log(\"* Correo electronico invalido o no existe!\");\n\t\t}\n\t}", "function validiraj_mail(){\n\n var pattern = /^[a-zA-Z0-9]+@[a-z]{2,10}\\.[a-z]{2,4}$/;\n var tekst = document.getElementById(\"forma\").mail_input.value;\n var test = tekst.match(pattern);\n\n if (test == null) {\n document.getElementById(\"mail_error\").classList.remove(\"hidden\");\n valid_test = false;\n } else{\n console.log(\"validiran mail\");\n document.getElementById(\"mail_error\").classList.add(\"hidden\");\n }\n }", "function myPassword(password, confirm) {\n this.mypassword = password;\n this.confirmpassword = confirm;\n}", "function guardarSesion(){\n var parametros = \"\";\n parametros = \"nEmailUsername=\"+$('#email-username').val()+\"&nPassword=\"+$('#password').val();\n $.ajax({\n url:\"sesion/loguear.php\",\n method:\"POST\",\n data:parametros,\n dataType:\"html\",\n success:function(respuesta){\n //console.log(respuesta);\n if(respuesta == \"Registro encontrado\"){\n window.location.href=\"MenuPrincipal.php\"; \n }else if(respuesta == \"Acceso Denegado: Usuario/Email incorrecto u Contraseña incorrecta\"){\n alert(respuesta);\n }else{\n console.log(respuesta);\n }\n },\n error:function(error){\n console.log(error);\n } \n })\n}", "function send_message(expediteur,destinataire,message)\r\n{\r\n\r\n$.post('/php/lib/messagerie/post.php',{'expediteur':expediteur,'destinataire':destinataire,'message':message,'key':key})\r\n.success(\r\n function()\r\n {\r\n $('#tchat'+destinataire+' textarea').val('');\r\n $('.tchat textarea[data-expediteur='+expediteur+'][data-destinataire='+destinataire+']').removeAttr('disabled');\r\n $('.tchat textarea[data-expediteur='+expediteur+'][data-destinataire='+destinataire+']').focus();\r\n }\r\n);\r\n}" ]
[ "0.6103988", "0.59763664", "0.5898663", "0.58332855", "0.58259565", "0.57743156", "0.57723236", "0.5727024", "0.56248724", "0.558681", "0.55587107", "0.55449337", "0.55361825", "0.55269885", "0.55223006", "0.55149406", "0.549034", "0.5486027", "0.54812807", "0.54745513", "0.5463284", "0.54486245", "0.54350287", "0.5423411", "0.54224485", "0.5412891", "0.5409575", "0.540726", "0.54053193", "0.53998387", "0.53982025", "0.5389625", "0.5378709", "0.5374971", "0.53746736", "0.5373941", "0.5366184", "0.53530574", "0.5341257", "0.5332887", "0.53315574", "0.5325434", "0.5312754", "0.53040045", "0.5296155", "0.5290868", "0.5287259", "0.52849364", "0.5269935", "0.5265558", "0.5251534", "0.5249715", "0.524836", "0.524564", "0.52454275", "0.52440107", "0.52414256", "0.5238588", "0.5235638", "0.52351105", "0.5234382", "0.5227656", "0.52268577", "0.5221356", "0.5220804", "0.521985", "0.521775", "0.52162147", "0.52119106", "0.5211339", "0.5203601", "0.52027446", "0.51976", "0.519567", "0.51923525", "0.51858133", "0.5185275", "0.5176434", "0.51763165", "0.51736414", "0.5165642", "0.5163099", "0.51616895", "0.5159486", "0.5156401", "0.515503", "0.5154228", "0.5150473", "0.5140181", "0.51327485", "0.5125979", "0.5117204", "0.51023716", "0.5101466", "0.509613", "0.5086504", "0.50857335", "0.5084962", "0.50829583", "0.50797635", "0.5079555" ]
0.0
-1
recuperation de la liste des offres de jobs
function getJobs(){ var ref2 = firebase.database().ref("job_offers"); ref2.on('value', gotJobs, errData); console.log("ok"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getJobs () {\n }", "function loadJobs() {\n API.getAllJobs()\n .then(data => setJobList(data.data))\n .catch(err => console.log(err));\n }", "static async getAllJobs(data={}) {\n let res = await this.request('jobs/', data);\n return res.jobs;\n }", "get jobs () {\n return this._mem.jobs;\n }", "getAllCurrentJobs() { \n return this.items.map(ele=>ele.element);\n }", "function joblist() {\n jobFactory.joblist()\n .then (\n function(jobs) { \n self.joblist = jobs;\n for(var [job] in self.joblist) {\n // console.log(self.bloglist[blog].postDate);\n self.joblist[job].postDate = new Date(self.joblist[job].postDate[0],self.joblist[job].postDate[1] - 1,self.joblist[job].postDate[2]);\n // console.log(self.bloglist[blog].postDate);\n }\n console.log(self.joblist);\n },\n function(errResponse) {\n console.log('Failure!');\n }\n );\n }", "function getAllJobInfoFromServer() {\r\n\tMoCheck.aktJobs = new Array();\r\n\tif(MoCheck.getJobCoords().length > 0) {\r\n\t\t$each(MoCheck.getJobCoords(), function(jobCoords, index) {\r\n\t\t\tMoCheck.getJobInfoFromServer(jobCoords.pos.x, jobCoords.pos.y);\r\n\t\t});\r\n\t} else {\r\n\t\t/* MotivationWindow muss ggf. neu geladen werden, auch wenn die aktuelle Liste keine Jobs hat */\r\n\t\tMoCheck.reloadWindow();\r\n\t}\r\n}", "function _getListOfJobs() {\n\t\t//Get the Connection to the Database\n\t\tvar oConnection = $.db.getConnection();\n\n\t\t//Build the Query\n\t\tvar lvQuery = 'SELECT * FROM \"' + gvSchemaName + '\".\"' + gvTableName + '\"';\n\t\tlvQuery = lvQuery + ' WHERE \"JOB_NAME\" = ' + \"'\" + gvJobName + \"'\";\n\n\t\t//Prepare the SQL Statement to read the entries\n\t\tvar oStatement = oConnection.prepareStatement(lvQuery);\n\n\t\t//Execute the Query\n\t\tvar lsReturn = oStatement.executeQuery();\n\n\t\t//Map and Save the results\n\t\tvar Jobs = [];\n\n\t\twhile (lsReturn.next()) {\n\t\t\tvar oEntry = {\n\t\t\t\tID: lsReturn.getString(1),\n\t\t\t\tJOB_NAME: lsReturn.getString(2),\n\t\t\t\tXSCRON: lsReturn.getString(3)\n\t\t\t};\n\t\t\tJobs.push(oEntry);\n\t\t}\n\n\t\t//Close the DB Connection\n\t\toStatement.close();\n\t\toConnection.close();\n\n\t\t//Return the records\n\t\treturn Jobs;\n\t}", "async getJobs ({ commit, state }) {\n const { data } = await Api.jobs.get()\n commit('SET_JOBS', { jobs: data })\n commit('SET_JOBS_SHOW', { jobs: state.jobsList })\n }", "function listJobs (done) {\n let sql = 'Select * FROM application';\n db.getPool().query(sql, (err, results, fields) => {\n if (err) {\n return done({\n 'message': err,\n 'status': 500,\n }, results);\n }\n return done(err, results);\n });\n}", "function refreshJobsComplete() {\n // Loop through all active jobs and remove any that have finished\n // Notes: This breaks when arm child servers are added\n $.each(activeJobs, function (index, job) {\n if (typeof (job) !== \"undefined\" && !job.active) {\n console.log(\"Job isn't active:\" + job.job_id.split(\"_\")[1]);\n console.log(job)\n removeJobItem(job);\n activeJobs.splice(index, 1);\n }\n });\n\n $(\"#joblist .col-md-4\").sort(function (a, b) {\n if (a.id === b.id) {\n return 0;\n }\n return (a.id < b.id ? -1 : 1);\n }).each(function () {\n const elem = $(this);\n elem.remove();\n $(elem).appendTo(\"#joblist\");\n });\n}", "function fetchJobs () {\n JobsAPI.list().then(function(data){\n $scope.jobsList = data.jobs;\n })\n .catch(function(error){\n Notify.error(error);\n });\n }", "static async getJobs(search) {\n const res = await this.request(`jobs`, { search });\n return res.jobs;\n }", "function getJobs() {\n return this.__jobs__ = this.__jobs__ || {};\n }", "function onGetJobs (message) {\r\n let jobs = state.jobs;\r\n if (message.data.jobId) {\r\n jobs = jobs.filter(job => job.id === message.data.jobId);\r\n }\r\n return Promise.resolve(jobs);\r\n}", "function Jobs(_ref) {\n var namespace = _ref.namespace,\n jobs = _ref.jobs,\n onFetch = _ref.onFetch;\n return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(Poller, {\n namespace: namespace,\n onFetch: onFetch\n }), /*#__PURE__*/react_default.a.createElement(JobList, {\n jobs: jobs,\n monitoringEnabled: true,\n namespace: namespace\n }));\n}", "function _jobs(jobs) {\n if(_.size(jobs)>0) {\n _jobsHeader();\n _.each(jobs, function(job) { \n console.log(sprintf(headerstr,job.id, job.next, Number(job.progress*100).toFixed(0), job.name, job.description));\n });\n } else {\n console.log('** no jobs **');\n }\n}", "function getJobsData() {\n _axios.default.get(CORS_KEY + API_URL + `positions.json?description=${state.description}&location=${state.location}`).then(response => {\n dispatch({\n type: ACTIONS.LOADING_STATE,\n payload: response.data\n });\n }).catch(error => {\n dispatch({\n type: \"FETCH_ERROR\"\n });\n });\n } //searching for jobs by key words, use this function", "constructor() {\n /** @type {Job[]} The jobs that need be done */\n this._jobs = [];\n }", "function doIt() {\n Promise.all([\n jobPage.show().GET({ include: ['owner'] }),\n jobPage.jobUsers.index().GET({ include: ['ratings'] }),\n jobPage.skills.index().GET(),\n jobPage.comments.index().GET()\n ]).then(function() {\n var job = client.store.find('jobs', jobId)\n console.log('job', job.id, job.name)\n parseComments(job.comments)\n parseJobUsers(job.jobUsers)\n })\n}", "searchJob(event) {\n event.preventDefault();\n this.setState({searching: true, message: null, jobList: []});\n const query = this.state.job.query;\n const location = this.state.job.location;\n const queryString = JobSearch.getQueryString({query, location});\n api.initJobSearch({queryString}).then(\n resp => {\n this.setState({message: `Loading... Your results will appear here`});\n return api.pollResults({pollId: resp.pollId})\n }\n ).then(\n resp => {\n const appliedJobs = JSON.parse(localStorage.getItem(storageKey));\n const res = resp.map(eachJob => {\n let index = appliedJobs.findIndex(applied => applied === eachJob.id);\n eachJob.applied = index > -1;\n return eachJob;\n });\n this.setState({searching: false, jobList: res, message: null});\n }\n ).catch(\n err => {\n console.error(err);\n this.setState({searching: false, message: err});\n }\n );\n }", "function getTaskLists() {\n\n}", "job(id) {\n return this.__get(`jobs/${id}`);\n }", "function JobList() {\n console.debug(\"JobList\");\n\n const [jobs, setJobs] = useState(null);\n\n useEffect(function getAllJobsOnMount() {\n console.debug(\"JobList useEffect getAllJobsOnMount\");\n search();\n }, []);\n\n /** Triggered by search form submit; reloads jobs. */\n async function search(search) {\n let jobs = await JoblyApi.getJobs(search);\n setJobs(jobs);\n }\n\n /** Apply for job: save to API and update that job in jobs state. */\n async function apply(id) {\n let message = await JoblyApi.applyToJob(id);\n setJobs(j => j.map(job =>\n job.id === id ? { ...job, state: message } : job\n ));\n }\n\n if (!jobs) return <LoadingSpinner />;\n\n return (\n <div className=\"JobList col-md-8 offset-md-2\">\n <Search searchFor={search} />\n {jobs.length\n ? <JobCardList jobs={jobs} apply={apply} />\n : <p className=\"lead\">Sorry, no results were found!</p>\n }\n </div>\n );\n}", "createJobs () {\n }", "update(){\n return api.get(\"/workers/\")\n .then(r => {\n r.data.forEach(x => {\n if(x.entity.includes(\"/\")){\n this.jobs.push({\n id: x.id,\n kind: x.entity.split(\"/\")[0],\n namespace: x.entity.split(\"/\")[1],\n name: x.entity.split(\"/\")[2],\n entity: x.entity,\n })\n }else{\n service.jobs.push({\n id: x.id,\n entity: x.entity,\n })\n }\n });\n });\n }", "constructor() {\n this.jobs = {};\n this.tasks = tasks;\n }", "function JobList() {\n const [jobs, setJobs] = useState(null);\n\n /** fetch jobs data via search through the API */\n useEffect(function getAllJobsOnMount() {\n search();\n }, []);\n\n /** Function used by SearchForm. Triggers when form is submitted. */\n async function search(title) {\n // get job names via search term\n let jobs = await JoblyApi.getJobs(title);\n setJobs(jobs);\n }\n\n // Return loading if no jobs present yet\n if (!jobs) return <LoadingComponent />;\n\n return (\n <div className=\"JobList col-md-8 offset-md-2\">\n <SearchForm searchFor={search} />\n {jobs.length ? (\n <JobCardList jobs={jobs} />\n ) : (\n <p className=\"lead\">Sorry, no results were found!</p>\n )}\n </div>\n );\n}", "function getCompletedJobs () {\n return new Promise(function (resolve, reject) {\n var Job = mongoose.model('Job');\n Job.find({\n $and: [\n { status: 'C' },\n { current: { $exists: true } }\n ]\n }).sort('-current.completedOn').exec(function (err, jobs) {\n if (err) {\n reject(new Error('Failed to load active jobs.'));\n } else {\n resolve(jobs);\n }\n });\n });\n }", "get(){\n return new Promise((resolve, reject) => {\n resolve(this.jobs)\n })\n }", "function loadJobData() {\n $.ajax({\n dataType: \"xml\",\n url: server + \"/go/api/jobs/scheduled.xml\",\n timeout: 2000\n }).done(function(data) {\n $('#scheduled-jobs').html('');\n\n $(data).find('job').each(function() {\n job_hash = {\n 'name': $(this).find('buildLocator').text(),\n 'url': $(this).find('link').attr('href'),\n 'cancel_url': cancelUrl( $(this).find('buildLocator').text() )\n }\n $('#scheduled-jobs').append( scheduled_job_template( job_hash ))\n });\n });\n}", "function getJobs() {\n if(localStorage.getItem('jobs') === null) {\n jobs = [];\n } else {\n jobs = JSON.parse(localStorage.getItem('jobs'));\n }\n\n jobs.forEach(function(index){\n // create li\n const job = document.createElement('li');\n\n // create collapsible header at arr[0] since it's required and first\n const jobHeader = document.createElement('div');\n jobHeader.innerHTML = `<div id='job-name'><i class=\"material-icons\">business_center</i>${index[0][1]}</div><a href=\"#\" class=\"delete-icon\"><i class=\"material-icons\">clear</i>`;\n jobHeader.className = 'job-header';\n jobHeader.className = 'collapsible-header';\n // append li header to li\n job.appendChild(jobHeader);\n\n // Create the collapsible job body\n const jobBody = document.createElement('div');\n jobBody.className = 'collapsible-body';\n\n // Create collection inside body\n const bodyCollection = document.createElement('ul');\n bodyCollection.className = 'collection';\n\n\n\n // loop through remaining elements since the company name aka arr[0] is assigned\n for(let i = 1; i < index.length; i++) {\n // create collection items aka arr info\n const collectionItem = document.createElement('li');\n collectionItem.className = 'collection-item';\n\n // if link add anchor\n if(index[i][0] === 'link'){\n collectionItem.innerHTML = `<a href=${index[i][1]} class='teal-text lighten-2'>View Job</a>`\n } else {\n collectionItem.innerHTML = index[i][1];\n }\n\n // append collection item to the bodyCollection\n bodyCollection.appendChild(collectionItem);\n }\n\n // bodyCollection add to jobBody\n jobBody.appendChild(bodyCollection);\n\n // jobBody added to job\n job.appendChild(jobBody);\n\n // finally append the new job to the job list\n jobList.appendChild(job);\n })\n}", "function getAllJobTypes () {\n return jobTypes;\n}", "function jobsd(){\n\tvar jobs = window.jobsObj.jobslist;\n\tif (window.jobsObj.size(jobs) > 0) { // check if jobs is empty\n\t\tvar jobid;\n\t\tvar jobs_return = {};\n\t\tvar job_func;\n\t\tfor (jobid in jobs) {\n\t\t\tjob_func = jobs[jobid];\n\t\t\tconsole.log(\"Job ID \" + jobid);\n\t\t\tjobs_return[jobid] = job_func();\n\t\t}\n\t\tfor (jobid in jobs_return) {\n\t\t\tconsole.log(\"Job ID \" + jobid + \" returned \");\n\t\t\tconsole.log(jobs_return[jobid]);\n\t\t}\n\n\t\t//console.log(window.funcs);\n\t\twindow.jobsObj.resultSet = window.jobsObj.merge(window.jobsObj.resultSet, jobs_return);\n\n\t\twindow.jobsObj.jobslist = {};\n\t\tjobs = {};\n\t\tjobs_return = {};\n\t}\n\tsetTimeout(jobsd, 100); // Run jqmb_jobs 100ms later\n}", "function removeJob() {\n axios.delete(`/jobs/${info._id}`)\n .then(res => {\n console.log(res)\n setJobList(prevList => prevList.filter(savedJob => savedJob._id !== info._id))\n alert(`You have successfully removed ${info.position} at ${info.company} from your job list.`)\n })\n .catch(err => console.log(err.response.data.errMsg))\n }", "function JobCardList({ jobs, apply }) {\n\n return (\n <div className=\"JobCardList\">\n {jobs.map(job => (\n <JobCard\n key={job.id}\n id={job.id}\n title={job.title}\n salary={job.salary}\n equity={job.equity}\n companyName={job.companyName}\n />\n ))}\n </div>\n );\n}", "function getTaskList(indice) \n{\n RMPApplication.debug(\"begin getTaskList\");\n c_debug(dbug.task, \"=> getTaskList\");\n id_index.setValue(indice);\n var query = \"parent.number=\" + var_order_list[indice].wo_number;\n\n var options = {};\n var pattern = {\"wm_task_query\": query};\n c_debug(dbug.task, \"=> getTaskList: pattern = \", pattern);\n id_get_work_order_tasks_list_api.trigger(pattern, options, task_ok, task_ko);\n RMPApplication.debug(\"end getTaskList\");\n}", "function refreshJobs() {\n let serverCount = activeServers.length;\n $.each(activeServers, function (serverIndex, serverUrl) {\n $.ajax({\n url: serverUrl + \"/json?mode=joblist\",\n type: \"get\",\n timeout: 2000,\n error: function () {\n --serverCount;\n },\n success: function (data) {\n serverCount = refreshJobsSuccess(data, serverIndex, serverUrl, serverCount);\n },\n complete: function (data) {\n refreshJobsComplete();\n if(typeof data !== 'undefined' && data.responseJSON) {\n checkNotifications(data.responseJSON);\n }\n }\n });\n });\n}", "function getNewJobs () {\n return new Promise(function (resolve, reject) {\n var Job = mongoose.model('Job');\n Job.find({\n $and: [\n { status: 'A' },\n { current: { $exists: false } }\n ]\n }).sort('-created').exec(function (err, jobs) {\n if (err) {\n reject(new Error('Failed to load active jobs.'));\n } else {\n resolve(jobs);\n }\n });\n });\n }", "function JobList() {\n const [jobs, setJobs] = useState(null);\n\n useEffect(function getJobsOnMount() {\n search();\n }, []);\n\n// reloads jobs after search submit\n async function search(title) {\n let jobs = await JoblyApi.getJobs(title);\n setJobs(jobs);\n }\n\n if (!jobs) return \"LOADING...\";\n\n return (\n <div>\n <SearchForm searchFor={search} />\n {jobs.length\n ? <JobDetailList jobs={jobs} />\n : <p>Sorry, no results here!</p>\n }\n </div>\n );\n}", "async function _list(req, res) {\n try {\n const list = await controller.getAll();\n const jobListMessage = slackService.serializeJobList(list);\n\n return res\n .status(Responses.Jobs.Post.SuccessList.CODE)\n .send(jobListMessage);\n\n } catch (error) {\n return res\n .status(Responses.Jobs.Post.Help.CODE)\n .send(Responses.Jobs.Post.Help.MESSAGE);\n }\n}", "function joblist() {\n console.log('Inside factory now');\n var deferred = $q.defer();\n\n $http.get(jobUrl + '/job/list/status')\n .then (\n function(response) {\n deferred.resolve(response.data);\n },\n function(errResponse) {\n deferred.reject(errResponse);\n }\n );\n return deferred.promise;\n }", "static async getAll() {\n const result = await db.query(\n `SELECT * FROM jobs`);\n if (result.rows.length === 0) {\n throw new ExpressError(\"No jobs\", 400)\n };\n return result.rows.map(j => new Job(j.id, j.title, j.salary, j.equity, j.company_handle, j.date_posted));\n }", "async function list(req, res) {\n winston.info('jobs-router:list', { payload: req.body });\n\n try {\n const list = await controller.getAll();\n\n res\n .status(Responses.Jobs.List.Success.CODE)\n .json(list);\n } catch (error) {\n winston.error('jobs-router:list', { payload: req.body, error });\n return res\n .status(Responses.Jobs.List.Error.CODE)\n .send(Responses.Jobs.List.Error.MESSAGE);\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 }", "onJobSelect(event){\n let jobs = this.props.jobs.filter(j => j.value == event.target.value);\n let job = jobs[0];\n this.props.staffActions.jobSelectedSuccess(job);\n this.props.staffActions.loadApprovedStaff(job.value);\n }", "function getJobs(params, callback) {\n var executions = ['queued', 'failed', 'succeeded',\n 'canceled', 'running', 'retried', 'waiting'];\n var list_name;\n var execution;\n var offset;\n var limit;\n\n if (typeof (params) === 'object') {\n execution = params.execution;\n delete params.execution;\n offset = params.offset;\n delete params.offset;\n limit = params.limit;\n delete params.limit;\n }\n\n if (typeof (params) === 'function') {\n callback = params;\n params = {};\n }\n\n if (typeof (limit) === 'undefined') {\n limit = 1000;\n }\n\n if (typeof (offset) === 'undefined') {\n offset = 0;\n }\n\n if (typeof (execution) === 'undefined') {\n return client.smembers('wf_jobs', function (err, results) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return processJobList(\n results, params, client, offset, limit, callback);\n });\n } else if (executions.indexOf(execution !== -1)) {\n list_name = 'wf_' + execution + '_jobs';\n return client.llen(list_name, function (err, res) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return client.lrange(\n list_name,\n 0,\n (res + 1),\n function (err, results) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return processJobList(\n results, params, client, offset, limit, callback);\n });\n });\n } else {\n return callback(new wf.BackendInvalidArgumentError(\n 'excution is required and must be one of' +\n '\"queued\", \"failed\", \"succeeded\", \"canceled\", \"running\"' +\n ', \"retried\", \"waiting\"'));\n }\n }", "function searchClients(jobs, client){\n let jobList = \"\";\n\n for (let j of jobs){\n if(j.name == client){ // if client is found by name\n let status = \"\";\n let statusLabel = \"\";\n\n if (j.completed == true){\n status = \"DONE\"\n }\n if (j.completed == false){\n status = \"INCOMPLETE\"\n }\n\n if (status == \"DONE\"){\n statusLabel = `<p style=\"color: green\">${status}</p>`\n }\n if (status == \"INCOMPLETE\"){\n statusLabel = `<label style=\"color: red\">${status}</label>`\n }\n\n jobList += `\n <div class=\"form-group\">\\\n <h3>Job # ${j.id}</h3> <br>\n <b>Name: </b>${j.name} \n <b style=\"margin-left: 15px\">Email: </b>${j.email} \n <b style=\"margin-left: 15px\">Phone: </b>${j.phone}\n </div> \n <b>Type: </b>${j.type} <br> \n <b>Make: </b>${j.make} \n <b style=\"margin-left: 15px\">Model: </b>${j.model} <br>\n <b>Cost: </b>${j.cost} <br> \n <b>Description: </b>${j.description} <br> \n <b>Date: </b> ${j.date} <br>\n <b>Status: </b> ${status} </p>\n <br><br>\n `;\n }\n else{\n console.log(\"No clients found.\")\n }\n }\n if (jobList == \"\"){ // if the jobList string is still completely empty after searching through JSON file\n joblist = \"No jobs found for that client.\"\n }\n \n return jobList;\n}", "async getRunningReplicationJobs() {\n let docs = [];\n let replicator = this.nano.use(REPLICATOR_DB);\n\n let sched = await this.nano.request({ db: SCHEDULER_DB, path: 'jobs' });\n for (const sJob of sched.jobs) {\n const repJob = await replicator.get(sJob.doc_id);\n docs.push(repJob);\n }\n\n return Promise.all(docs);\n }", "function onCleanJobs () {\r\n state.jobs\r\n .filter(job => (job.state !== 'waiting' && job.state !== 'active'))\r\n .forEach(job => {\r\n let index = state.jobs.indexOf(job);\r\n state.jobs.splice(index, 1);\r\n });\r\n\r\n return Promise.resolve(state.jobs);\r\n}", "function Job(j, i) {\n let end = j.end;\n if(end === -1) {\n end = <small>present</small>;\n }\n\n\n // map the bullet points to an array of Bullet components\n // for each string in the array of strings \"desc\",\n // map that string to the function Bullet\n let bullets = j.desc.map(Bullet);\n\n return (\n <div key={i}>\n <h5 className=\"d-flex justify-content-between\">\n {j.title} <div>{j.start} - {end}</div>\n </h5>\n <h6><a href={j.link}>{j.org}</a></h6>\n <h6><a href={j.deptlink}><em>{j.dept}</em></a></h6>\n <ul>\n {bullets}\n </ul>\n </div>\n );\n \n }", "function ClearJobListing () {\r\n\t$(\"#\" + TAB_NOTIFICATION_LIST + \" li:gt(0)\").remove();\r\n\t\r\n}", "function extractJobs(jobs)\n {\n jobs = _.pluck(jobs.rows,'doc');\n return jobs\n }", "async function getJobs(page, jobs) {\n // here we are scrolling to the bottom within the jobs container because the jobs' inner html after 7th job are not loaded when they are not scrolled into. \n await page.evaluate(() => {\n // selecting the jobs div\n const jobsDivSelector = 'body > div.application-outlet > div.authentication-outlet > div.job-search-ext > div > div > section.jobs-search__left-rail > div > div'\n const jobsDiv = document.querySelector(jobsDivSelector)\n \n // scrolling to the bottom of it smoothly\n jobsDiv.scroll({\n top: jobsDiv.scrollHeight,\n behavior: 'smooth'\n })\n })\n\n // and we have to wait for like 1.5 - 2 seconds for this to work.\n await page.waitForTimeout(2000)\n\n // fetching html of every single job in the page\n const scrapedJobs = await page.evaluate(() => {\n const jobsSelector = 'body > div.application-outlet > div.authentication-outlet > div.job-search-ext > div > div > section.jobs-search__left-rail > div > div > ul > li'\n return Array.from(document.querySelectorAll(jobsSelector), elem => elem.innerHTML)\n })\n\n // iterating through jobs\n scrapedJobs.forEach(async elem => {\n const job = {}\n\n // loading job html to cheerio in order to use jQuery functionality\n const $ = cheerio.load(elem)\n\n // selectors\n const jobLinkSelector = '.artdeco-entity-lockup__content div:nth-child(1) a'\n const jobOffererSelector = '.artdeco-entity-lockup__content div:nth-child(2) a'\n const jobLocationSelector = '.artdeco-entity-lockup__content div:nth-child(3) li'\n\n // getting job properties from html \n const jobLink = $(jobLinkSelector).attr('href')\n const jobName = $(jobLinkSelector).text().replace(/\\s\\s+/gm, ' ')\n const jobOfferer = $(jobOffererSelector).text().replace(/\\s\\s+/gm, ' ')\n const jobLocation = $(jobLocationSelector).text().replace(/\\s\\s+/gm, ' ')\n\n // assigning them to job object\n job.link = 'www.linkedin.com' + jobLink\n job.jobName = jobName\n job.jobOfferer = jobOfferer\n job.jobLocation = jobLocation\n\n // pushing job to jobs array\n jobs.push(job)\n })\n\n // console.log(jobs)\n}", "function getJobs(id) {\n try {\n axios.get(`http://localhost:5000/jobs/${id}`)\n .then(res => {\n if (res.data.length !== 0) {\n setJobs(res.data[0].jobs);\n console.log(res.data[0].jobs)\n } else {\n console.log(\"no data\")\n }\n })\n .catch(err => console.log(err));\n } catch (error) {\n console.log(error);\n }\n }", "function notifyDesktopOfJobCompletion(){\n\tvar jobList = localStorage.getItem(\"jobStatusNotificationList\")\n\tif (jobList == null) return;\n\ttry {\n\t\tjobList = JSON.parse(localStorage.getItem(\"jobStatusNotificationList\"));\n\t} catch (e){\n\t\tjobList = [];\n\t}\n\t\n\t\n\tif (jobList.length == 0) return;\n\t\n\tvar qstr = \"\";\n\tjobMap = {};\n\tfor (var i=0; i < jobList.length; i++){\n\t\ttry {\n\t\t\tif (i != 0) qstr += \"&\";\n\t\t\tvar aJob = jobList[i];\n\t\t\tjobMap[aJob[\"jobId\"]] = aJob;\n\t\t\tqstr +=\"jobId=\"+aJob[\"jobId\"];\n\t\t} catch(e){\n\t\t\t// swallow bad data\n\t\t}\n\t}\n\t\n\n\t $.ajax({\n\t cache: false,\n\t type: \"GET\",\n\t url: \"/gp/rest/v1/jobs/jobstatus.json?\"+qstr,\n\t dataType: \"json\",\n\t success: function(data) {\n\t \tremainingJobs = [];\n\t \tfor (var i=0; i< data.length; i++){\n\t \t\tjobStatus = data[i];\n\t \t\tif (jobStatus.isFinished){\n\t \t\t\t\n\t \t\t\tvar moduleName = jobMap[jobStatus[\"gpJobNo\"]][\"moduleName\"];\n\t \t\t\tif (jobStatus.hasError){\n\t \t\t\t\tnotifyDesktop(\"Error: GenePattern\", moduleName + \" job \"+ jobStatus.gpJobNo + \" \" + jobStatus.statusFlag);\n\t \t\t\t} else {\n\t \t\t\t notifyDesktop(\"GenePattern\", moduleName + \" job \"+ jobStatus.gpJobNo + \" \" + jobStatus.statusFlag + \" \\n\" + jobStatus.statusMessage);\n\t \t\t\t}\n\t \t\t\t\n\t \t\t} else {\n\t \t\t\tremainingJobs.push(jobMap[jobStatus.gpJobNo]);\n\t \t\t}\n\t \t\t\n\t \t} \n\t \tlocalStorage.setItem(\"jobStatusNotificationList\", JSON.stringify(remainingJobs));\n\t },\n\t failure: function(err){\n\t \t\n\t \tconsole.error(err);\n\t }});\n\t\n}", "function getList(){\r\n // Re-add list items with any new information\r\n let dataSend = \"pullTasks=all\";\r\n let data = apiReq(dataSend, 2);\r\n}", "getJobs() {\n return service\n .get('/jobs/')\n .then((res) => res.data)\n .catch(errorHandler);\n }", "function JobList({ rightJobs }) {\n\n if (!rightJobs) {\n return (<div><p>No jobs available</p></div>)\n }\n return (\n <div className=\"col-md-4\">\n {rightJobs.map(job => (<JobCard job={job} />))}\n </div>\n );\n}", "function createJobListForGovJobs(dataInfo) {\n let result = \"\";\n for (let i = 0; i < dataInfo.length; i++) {\n result += \"<div class='list' style='cursor: pointer;' onclick='window.location=\" + '\"' + dataInfo[i].url + '\"' + \";'> \";\n result += \"<img src='https://search.gov/img/searchdotgovlogo.png'></img>\"\n result += \"<div> <h1>\" + dataInfo[i].position_title + \"</h1> </div>\";\n result += \"<div> <h2>\" + dataInfo[i].organization_name + \"</h2> </div>\";\n\n let fixedLocation = \"\";\n for (let y = 0; y < dataInfo[i].locations.length; y++) {\n fixedLocation += dataInfo[i].locations[y] + \"<br/>\";\n }\n result += \"<div> <h2>\" + fixedLocation + \"</h2> </div>\";\n\n // Date format DD MM YYYY\n let fixedDate = dataInfo[i].start_date.split(\"-\");\n result += \"<div> <h3>\" + fixedDate[2] + \"/\" + fixedDate[1] + \"/\" + fixedDate[0] + \"</h3> </div>\";\n result += \"</div> \"\n }\n return result;\n }", "_list() {\n const parameters = [\n 1,\n ['active', 'id', 'interval', 'language', 'last_run', 'name', 'run_on', 'tags'],\n {},\n 1000,\n 'name',\n ];\n return this.list.call(this, ...parameters);\n }", "renderMovieLists(results){\n const {currentPage} = this.props,\n jobsPerPage = 25,\n start = currentPage - 1,\n end = start + jobsPerPage;\n\n const jobsOnPage = results.slice(start, end);\n\n return (\n jobsOnPage.map((job)=>{\n const key = uuid();\n return(\n <JobList key={key} job={job}/>\n );\n })\n );\n }", "function runJobs() {\n // Add Class\n jobs.forEach(function(job){\n addClass(job.el, pseudoHide + \"-parent\");\n });\n\n // Insert el\n jobs.forEach(function(job){\n if(job.type === 'before'){\n job.el.insertBefore(job.pseudo, job.el.firstChild);\n } else {\n job.el.appendChild(job.pseudo);\n }\n });\n }", "function createJobs(_data) {\n\n //Checking for potential Lever source or origin parameters\n let pageUrl = window.location.href;\n let leverParameter = '';\n let trackingPrefix = '?lever-';\n\n if (pageUrl.indexOf(trackingPrefix) >= 0) {\n // Found Lever parameter\n let pageUrlSplit = pageUrl.split(trackingPrefix);\n leverParameter = '?lever-' + pageUrlSplit[1];\n }\n\n for (i = 0; i < _data.length; i++) {\n let posting = _data[i];\n let title = _data[i].title || 'Others';\n $('#jobs-container .jobs-list').append(\n '<h3 class=\"job-title\">' + title + '</h3>'\n );\n for (let j = 0; j < posting.postings.length; j++) {\n let jobText = posting.postings[j].text;\n let jobLink = posting.postings[j].hostedUrl + leverParameter;\n $('#jobs-container .jobs-list').append(\n '<div class=\"job\">' +\n '<a class=\"job-title-link\" target=\"_blank\" href=\"' + jobLink + '\"\">' + jobText + '</a>' +\n '</div>'\n );\n }\n }\n }", "function getActiveJobs () {\n return new Promise(function (resolve, reject) {\n var Job = mongoose.model('Job');\n Job.find({\n $and: [\n { status: 'A' },\n { current: { $exists: true } }\n ]\n }).sort('-created').exec(function (err, jobs) {\n if (err) {\n reject(new Error('Failed to load active jobs.'));\n } else {\n resolve(jobs);\n }\n });\n });\n }", "function getJobs(){\n\t firebase.database().ref(\"/jobs/\"+uid+\"/\")\n\t\t .on('value',function(snapshot) {\n\t\t if(!snapshot.val()){\n\t\t\t $scope.noJobs = \"You don't have jobs currently\";\n\t\t }\n\t\t else {\n\t\t\t $scope.noJobs = false;\t\n\t\t\n\t\t\t $scope.$apply(function(){\n\t\t\t\t $scope.userJobs = snapshot.val();\n\t\t\t\t})\n\t\t }\n\t\t \n\t\t console.log($scope.userJobs);\n\t\t console.log($scope.noJobs);\t\n\t \n\t })\n\t\n }", "function getJobs(){\n jobs_notifications.style.display = 'none';\n negotiation.style.display = 'none';\n posted_jobs.style.display = 'block';\n}", "createMiningJobs() {}", "function twpro_clickList() {\r\n\t\tif (TWPro.twpro_failure) return;\r\n\t\tif (document.getElementById('twpro_wait').text != TWPro.lang.CALCJOB && document.getElementById('twpro_wait').text != TWPro.lang.CHOOSEJOB) {\r\n\t\t\tdocument.getElementById('twpro_wait').text = TWPro.lang.CALCJOB;\r\n\t\t\twindow.setTimeout(TWPro.twpro_updateList, 0);\r\n\t\t}\r\n\t}", "function processJobList(jobList, params, client, offset, limit, callback) {\n var paramsCall = [];\n var getAllCalls = [];\n\n jobList.forEach(function (uuid) {\n paramsCall.push(function (callback) {\n client.hget('job:' + uuid, 'params', function (err, reply) {\n if (err) {\n return callback(err);\n }\n\n var jobParams = JSON.parse(reply);\n if (hasPropsAndVals(jobParams, params)) {\n getAllCalls.push(function (callback) {\n client.hgetall('job:' + uuid,\n function (err, reply) {\n return callback(err, reply);\n });\n });\n }\n return callback(null);\n });\n });\n });\n\n async.parallel(paramsCall, function (err) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n\n return async.parallel(getAllCalls, function (err, replies) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n replies.forEach(function (job, i, arr) {\n return _decodeJob(job, function (job) {\n replies[i] = job;\n });\n });\n\n return callback(null, replies.slice(offset, limit));\n });\n });\n }", "function receiveDataJobs(json){\n\tconst dataJobs = json;\n\treturn {\n\t\ttype: RECEIVE_DATAJOBS,\n\t\tdataJobs\n\t}\n}", "scheduleJobs(jobs) {\n\n const self = this;\n jobs.forEach((job, i) => {\n if (job.channelId && job.schedule) self.scheduleJob(job.channelId, job.schedule);\n });\n }", "getData(job) {\n const jobRuns = job.jobRuns.nodes;\n\n return jobRuns.map(function(jobRun) {\n const children = jobRun.tasks.nodes.map(function(jobTask) {\n const startedAt = jobTask.dateStarted;\n const finishedAt = jobTask.dateCompleted;\n const runTime = calculateRunTime(startedAt, finishedAt);\n\n return {\n taskID: jobTask.taskId,\n status: jobTask.status,\n startedAt,\n finishedAt,\n runTime\n };\n });\n\n const startedAt = jobRun.dateCreated;\n const finishedAt = jobRun.dateFinished;\n const runTime = calculateRunTime(startedAt, finishedAt);\n\n return {\n finishedAt,\n id: jobRun.jobID,\n jobID: job.id,\n startedAt,\n status: jobRun.status,\n runTime,\n children\n };\n });\n }", "function jobsLoaded(d) {\n //Match the data to the client\n for (var i = 0; i < d.length; i++) {\n if (d[i].get('data')['name'] === clientId) {\n //Store the current list of jobs in a separate object\n $scope.clientJobList.jobs = d[i].get('data').clientJobs;\n $scope.clientData.header = d[i].get('data').header;\n }\n }\n\n //If a job number is specified in the URL, we'll grab it now.\n if (projectId != undefined) {\n for (var j = 0; j < $scope.clientJobList.jobs.length; j++) {\n if ($scope.clientJobList.jobs[j].number === projectId) {\n $scope.job = $scope.clientJobList.jobs[j];\n }\n }\n }\n\n $scope.$apply();\n }", "addWaitingJob(job) {\n this.waitingQueue.push(job);\n }", "function finalizeJobs() {\n getCompletedJobs().then(function (jobs) {\n var Job = mongoose.model('Job');\n var ReportLog = mongoose.model('ReportLog');\n jobs.forEach(function (job) {\n var current=job.current;\n var modDate = new Date();\n\n Job.findOneAndUpdate({ '_id' : new mongoose.Types.ObjectId(job._id) }, { current:current ,modified: modDate, status: 'F' }, function(err, updatedJob) {\n if(err)\n console.error('Error updating job -> ', err);\n else {\n //creating jobLog\n createJobLogs(updatedJob, current);\n\n completeDurationLogs(job._id);\n }\n });\n });\n });\n }", "fetchAllJobs() {\n pushState(\n {currentJobId: null}, '/'\n );\n\n this.setState({\n currentJob: {},\n currentJobId: null\n })\n }", "function addBuildListItem(jobList, job, buildNumbers, hits, test) {\n var jobEl = addElement(jobList, 'li', null, [sparkLineSVG(hits), ` ${buildNumbers.length} ${job} ${rightArrow}`,\n createElement('p', {\n style: {display: 'none'},\n dataset: {job: job, test: test || '', buildNumbers: JSON.stringify(buildNumbers)},\n })\n ]);\n}", "run() {\n const ScrapingJob = db.getModelClass('scraping_job');\n ScrapingJob.findJobsToRun().then((scrapingJobs) => {\n scrapingJobs.forEach((job) => this._runSingleJob(job));\n }).catch((err) => {\n logger.logError(err);\n });\n }", "function getJoueurListe() {\r\n\trequest(\"GET\", \"admin.php?methode=JOUEUR_liste\" , true, setData);\r\n}", "function listAllTasks() {\n for (var ix = 0; ix < toDoList.length; ix++) {\n console.log(ix + 1 + \": \" + toDoList[ix]);\n }\n}", "function updateJobStatus() {\n\n // make the http request to get the job info\n jQuery.ajax({\n type:'POST',\n url:'/backgroundJob/listAjax',\n success:function(data, textStatus) {\n // on success, update the joblist div\n jQuery('#jobList').html(data);\n //see if we have any jobs still running by checking for the existence of an element with the class runningJob\n if ($('.runningJob').length > 0 || $('.queuedJob').length > 0) {\n //if we still have running jobs, set a timeout to check again in 3 seconds\n t = setTimeout(\"updateJobStatus()\", 1000);\n }\n },\n // on error, don't do anything\n error:function(XMLHttpRequest, textStatus, errorThrown) {\n }\n });\n}", "function getAvailableJobs(filter) {\n if (getAvailableJobsCache === null) {\n var gonogo = [];\n var others = [];\n var checkDependencies = false;\n if (typeof config.blacklist !== 'undefined' && typeof config.blacklist.dependencies !== 'undefined' && config.blacklist.dependencies.length > 0) {\n checkDependencies = true;\n }\n var jobPaths = [];\n jobPaths.push(path.join(config.P4_WORKSPACE_PATH, 'depot', 'Wakanda', config.WAKANDA_BRANCH, 'Common', 'tests'));\n jobPaths.push(path.join(config.P4_WORKSPACE_PATH, 'depot', 'Wakanda', config.WAKANDA_BRANCH, 'Server', 'tests'));\n if (isLinux() === false) {\n jobPaths.push(path.join(config.P4_WORKSPACE_PATH, 'depot', 'Wakanda', config.WAKANDA_BRANCH, 'Studio', 'tests'));\n }\n jobPaths.forEach(function(_path) {\n _path = actualPath(_path.toLowerCase());\n findFiles(_path, /^(pom|test\\.conf)\\.(xml|json)$/).forEach(function(pom) {\n var jobBaseName = pom.toLowerCase().replace(config.P4_WORKSPACE_PATH.toLowerCase(), '');\n jobBaseName = jobBaseName.replace(path.join('depot', 'Wakanda', config.WAKANDA_BRANCH).toLowerCase(), '');\n jobBaseName = jobBaseName.replace(path.sep + 'tests' + path.sep, path.sep);\n if (isWindows()) {\n jobBaseName = path.dirname(jobBaseName).replace(/\\\\/g, '_').replace(/__/g, '').toLowerCase();\n } else {\n jobBaseName = path.dirname(jobBaseName).replace(/\\//g, '_').replace(/__/g, '').toLowerCase();\n }\n if (/\\.xml$/i.test(pom)) {\n if (typeof config.noJavaTest === 'undefined' || config.noJavaTest === false) {\n var jobName = jobBaseName + '_core';\n jobName = jobName.replace(/core/g, 'main').replace(/main_+main/g, 'main').replace(/_+/g, '_');\n var pomContent = fs.readFileSync(pom);\n var keepIt = true;\n if (checkDependencies === true) {\n config.blacklist.dependencies.forEach(function(artifactid) {\n var testNameFilter = new RegExp('<artifactid>' + artifactid.replace(/\\*/ig, '.*') + '<\\/artifactid>', 'ig');\n if (testNameFilter.test(pomContent) === true) {\n keepIt = false;\n }\n });\n }\n if (isLinux()) {\n if (/<os>[\\s\\S]*<name>/ig.test(pomContent) === true && /<os>[\\s\\S]*<name>linux<\\/name>[\\s\\S]*<\\/os>/ig.test(pomContent) === false) {\n keepIt = false;\n }\n } else if (isMac()) {\n if (/<os>[\\s\\S]*<name>/ig.test(pomContent) === true && /<os>[\\s\\S]*<name>mac<\\/name>[\\s\\S]*<\\/os>/ig.test(pomContent) === false) {\n keepIt = false;\n }\n } else if (isWindows()) {\n if (/<os>[\\s\\S]*<name>/ig.test(pomContent) === true && /<os>[\\s\\S]*<name>windows<\\/name>[\\s\\S]*<\\/os>/ig.test(pomContent) === false) {\n keepIt = false;\n }\n }\n if (keepIt === true) {\n if (/<gonogo>\\s*true/i.test(pomContent) === true) {\n gonogo.push(jobName);\n } else {\n others.push(jobName);\n }\n }\n }\n } else if (/pom\\.json$/i.test(pom)) {\n var pomContent = fs.readFileSync(pom);\n var keepIt = true;\n if (isLinux()) {\n if (/\"os\"\\s*:\\s*\\[/ig.test(pomContent) === true && /\"os\"\\s*:\\s*\\[.*\"linux\"/ig.test(pomContent) === false) {\n keepIt = false;\n }\n } else if (isMac()) {\n if (/\"os\"\\s*:\\s*\\[/ig.test(pomContent) === true && /\"os\"\\s*:\\s*\\[.*\"mac\"/ig.test(pomContent) === false) {\n keepIt = false;\n }\n } else if (isWindows()) {\n if (/\"os\"\\s*:\\s*\\[/ig.test(pomContent) === true && /\"os\"\\s*:\\s*\\[.*\"windows\"/ig.test(pomContent) === false) {\n keepIt = false;\n }\n }\n if (keepIt === true) {\n var found = false;\n fs.readdirSync(path.dirname(pom)).forEach(function(fileName) {\n if (/^test.*\\.js$/i.test(fileName) === true) {\n var match = /^test(.*)\\.js$/i.exec(fileName);\n if (match === null || match[1] === '') {\n var jobName = jobBaseName + '_core';\n } else {\n var jobName = jobBaseName + '_' + match[1].toLowerCase();\n }\n jobName = jobName.replace(/core/g, 'main').replace(/main_+main/g, 'main').replace(/_+/g, '_');\n if (/\"gonogo\":\\s*true/i.test(pomContent) === true) {\n gonogo.push(jobName);\n } else {\n others.push(jobName);\n }\n found = true;\n }\n });\n if (found === false) {\n var jobName = jobBaseName + '_core';\n jobName = jobName.replace(/core/g, 'main').replace(/main_+main/g, 'main').replace(/_+/g, '_');\n if (/\"gonogo\":\\s*true/i.test(pomContent) === true) {\n gonogo.push(jobName);\n } else {\n others.push(jobName);\n }\n }\n }\n } else if (/test\\.conf\\.json$/i.test(pom)) { // NEW ARCHI\n var pomContent = fs.readFileSync(pom);\n var keepIt = true;\n if (/\"active\":\\s*true/i.test(pomContent) === false) {\n keepIt = false;\n }\n if (keepIt === true) {\n if (/\"gonogo\":\\s*true/i.test(pomContent) === true) {\n gonogo.push(jobBaseName + '_core');\n } else {\n others.push(jobBaseName + '_core');\n }\n }\n }\n });\n });\n gonogo.sort(function(a, b) {\n if (a.split('_').length < b.split('_').length) {\n return -1;\n } else if (a.split('_').length > b.split('_').length) {\n return 1;\n } else if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n });\n others.sort(function(a, b) {\n if (a.split('_').length < b.split('_').length) {\n return -1;\n } else if (a.split('_').length > b.split('_').length) {\n return 1;\n } else if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n });\n getAvailableJobsCache = gonogo.concat(others);\n }\n var availableJobs = JSON.parse(JSON.stringify(getAvailableJobsCache));\n if (typeof filter === \"function\") {\n availableJobs = availableJobs.filter(function(item) {\n return (filter(item) === true);\n });\n }\n if (typeof config.blacklist !== 'undefined' && typeof config.blacklist.name !== 'undefined' && config.blacklist.name.length > 0) {\n availableJobs = availableJobs.filter(function(item) {\n var blacklisted = false;\n config.blacklist.name.forEach(function(name) {\n var testNameFilter = new RegExp('^' + name.replace(/\\*/ig, '.*') + '$', 'i');\n if (testNameFilter.test(item) === true) {\n blacklisted = true;\n }\n });\n return (blacklisted === false);\n });\n }\n return availableJobs;\n}", "function locationizer(work_obj) {\n var locations = [];\n for(job in work_obj.jobs) {\n \tvar newLocation = work_obj.jobs[job].location;\n locations.push(newLocation);\n\n }\n return locations;\n}", "async function fetchGithubJobs() {\n \n let resultLength = 1;\n let page = 0;\n const allJobs = [];\n\n while(resultLength > 0) {\n const res = await fetch(`${baseURL}?page=${page}`);\n const jobs = await res.json();\n resultLength = jobs.length;\n allJobs.push(...jobs);\n console.log('got jobs', resultLength);\n page++;\n }\n\n \n\n const successResult = await setAsync('githubJobs', JSON.stringify(allJobs));\n console.log('allJobs', {successResult});\n}", "function poll_jobs(data) {\n var promises = [];\n\n if(debug) {\n console.log('Jobs data: ', data);\n }\n\n // Push promises into array\n for(var job in data) {\n var job_id = data[job].id;\n var api_url = '/job/'+job_id;\n\n if (debug) {\n console.log('Processing job: ', data[job]);\n }\n\n promises.push(new Promise(function(resolve, reject) {\n var maxRun = plugin_timeout/2;\n var timesRun = 0;\n\n // Timer function that polls the API for job results\n var pollJob = function() {\n ajaxReq = $.get(api_url);\n ajaxReq.done(function(getResponse) {\n // Verify job data\n var job_result = getResponse;\n\n if (debug) {\n console.log('Job results: ', job_result);\n }\n\n console.log(job_result);\n if(job_result.is_finished) {\n console.log('Resolving job: ', job_result);\n resolve(job_result);\n clearTimeout(timer);\n return(true);\n }\n\n if(job_result.is_failed) {\n console.log('Job failed: ', job_result);\n reject(job_result);\n clearTimeout(timer);\n return(false);\n }\n });\n\n ajaxReq.fail(function(XMLHttpRequest, textStatus, errorThrown) {\n console.log('Request Error: '+ XMLHttpRequest.responseText + ', status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);\n reject(XMLHttpRequest.responseText);\n });\n\n // Set timeout recursively until a certain threshold is reached\n if (++timesRun == maxRun) {\n clearTimeout(timer);\n reject(\"Job polling timed out\");\n return;\n } else {\n timer = setTimeout(pollJob, 2000);\n }\n };\n\n var timer = setTimeout(pollJob, 500);\n }));\n }\n\n // Run .all() on promises array until all promises resolve\n // This is resolve() above.\n Promise.all(promises).then(function(result) {\n var success = true;\n\n for(var i=0;i<result.length;i++) {\n var r = result[i].result;\n var meta = result[i].meta;\n if (meta.mandatory) {\n if (result[i].is_finished && result[i].is_failed) {\n do_error(r.error);\n success = false;\n break;\n }\n }\n }\n\n if (success) {\n // This is for Steve...\n // Apple devices don't poll their captiveportal URL,\n // so this is for them. Android devices will do their\n // own polling and close the wifi-portal before this.\n setTimeout(do_success, 30000);\n }\n\n // This is reject() above.\n }, function(reason) {\n do_error(reason);\n });\n}", "function listTasks() \n{\n\t\tgapi.client.taskitemendpoint.listTaskItem().execute(function(resp) {\n\t\t\tif (!resp.code) {\n\t\t\t\tresp.items = resp.items || [];\n\t\t\t\tvar result = \"\";\n\t\t\t\tfor (var i=0;i<resp.items.length;i++) {\n\t\t\t\t\tresult = result+resp.items[i].title + \"...\" + \"<b>\" + resp.items[i].timeStamp + \"</b>\" + \"[\" + resp.items[i].id + \"]\" + \"<br/>\";\n\t\t\t\t}\n\t\t\t\tdocument.getElementById('listQuotesResult').innerHTML = result;\n\t\t\t}\n\t\t});\n}", "function cancelJobs() {\r\n var salesOrder = nlapiLoadRecord('salesorder', nlapiGetRecordId());\r\n var i = 1, n = salesOrder.getLineItemCount('item') + 1;\r\n for (;i < n; i++) { \r\n var jobId = salesOrder.getLineItemValue('item', 'job', i);\r\n if (jobId != null) {\r\n cancelJob(jobId);\r\n }\r\n }\r\n}", "function appendSentJob(li) {\r\n\t$('#sent_jobs').append(li);\r\n\r\n\t// scrolling the list to bottom so that new message will be visible\r\n\t$('#sent_jobs li').last().focus();\r\n}", "function getTaskList(){\n\t$.ajax({\n\t\tmethod: 'GET',\n\t\turl : 'http://localhost:8080/task',\n\t\tsuccess: function(result){\n\t\t\t$('#todo-list').empty();\n\t\t\t$('#completed-list').empty();\n\t\t\tfor(i = 0; i < result.length; i++){\n\t\t\t\taddTaskList(result[i]);\n\t\t\t}\n\t\t}\n\t})\n}", "function renderJobs(jobs){\n const html = jobs.map(function(job, jobId) {\n // job is our object, it is iterating over an array and it is rendering the data from the keys that belong on the object\n return `\n <li class='job-item'> \n <h2 id=\"${jobId}\">${job.company}</h2>\n <p>Job Title: ${job.position}</p>\n <p>Job Level: ${job.level}</p>\n </li>\n `\n });\n \n return html.join('');\n /* converts array into a string, .innerHTML has to be a string,\n that is why we convert the array of objects to a string*/\n }", "removeWaitingJob(job) {\n this.waitingQueue = this.waitingQueue.filter(function(item) {\n return item !== job;\n });\n }", "getCompiledList(jobClusterId) {\n let newList = [];\n\n return this._setList().then((clusterList) => {\n console.log(clusterList);\n if (typeof clusterList !== \"undefined\" && clusterList !== null && clusterList !== 403) {\n clusterList.forEach((cluster, i) => {\n const checkObj = {\n value: cluster.id,\n label: cluster.name,\n selected: false\n };\n if (jobClusterId !== null && jobClusterId == cluster.id) {\n checkObj.selected = true;\n }\n newList.push(checkObj);\n });\n\n return newList;\n } else {\n return Promise.resolve(clusterList);\n }\n\n });\n }", "function status() {\n return list\n }", "function loadJobLabors()\n\t{\n\t\t//Get all jobs id\n\t\tvar count = 0, ids = \"\", sizeValue = \"\";\n\t\t\n\t\tcount = dsJob.getCount();\n\t\tsizeValue = size.getRawValue();\n\t\t\n\t\tfor (var i = 0; i < count; i++)\n\t\t{\n\t\t\trecord = dsJob.getAt(i);\n\t\t\t\t\t\t\n\t\t\tids += \"\" + record.get('id_job') + (i + 1 < count ? \",\" : \"\");\n\t\t} \n\t\t\n\t\tdsJobLabor.load(\n\t\t{\n\t\t\tparams: \n\t\t\t{\n\t\t\t\tid_job: ids,\n\t\t\t\tsize: sizeValue\n\t\t\t}\n\t\t});\n\t}", "function drawJobs() {\r\n var i, count;\r\n\r\n for (i = 0, count = animator.jobs.length; i < count; i += 1) {\r\n animator.jobs[i].draw();\r\n }\r\n }", "scrape() {\n return new Promise((resolve, reject) => {\n x(this.url, this.rootSelector, this.selectors)((err, result) => {\n if (err) { reject(err); }\n if (!result) { reject('No results available.'); }\n\n // Resolve the promise with a filtered and transformed set of jobs\n if (result)\n resolve(this.returnUniqueJobs(this.applyTransforms(this.jobfilter(result))));\n })\n .paginate(this.pagination)\n .limit(this.limit);\n });\n }", "function getNodeList(jenkinsBaseUrl) {\n\n var xmlhttp = new XMLHttpRequest();\n var urlToCall = jenkinsBaseUrl+\"/computer/api/json\";\n\n //console.log(\"Loading Nodes from Jenkins url: \"+jenkinsBaseUrl);\n\n xmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n\n var obj = JSON.parse(xmlhttp.responseText);\n\n /* create an array of json Object */\n for(var i=0; i<obj.computer.length; i++){\n\n try{\n /* if a job have no 'color' set, means that is a folder, and this statement generate an Exception */\n var tmp = obj.jobs[i].color.toString();\n\n /* if no exception, add job to the model */\n modelListNodes.append({\"jobName\" : obj.jobs[i].name, \"jobUrl\" : obj.jobs[i].url, \"jobColor\" : obj.jobs[i].color, \"jenkinsBaseUrl\":jenkinsBaseUrl } );\n\n }catch(e){\n //console.log(\"Found a folder, executing a recursive call to url: \"+obj.jobs[i].url)\n getJobList(obj.jobs[i].url);\n }\n }\n }\n }\n\n xmlhttp.open(\"GET\", urlToCall, true);\n xmlhttp.send();\n}", "async function scrapeJobs(listings, page) {\n for (let i = 0; i < listings.length; i++) {\n await page.goto(listings[i].url);\n const html = await page.content();\n const $ = cheerio.load(html); \n \n // getting job description \n const jobDescription = $('#postingbody').text();\n listings[i].jobDescription = jobDescription;\n\n // getting comp \n const compensation = $('p.attrgroup > span:nth-child(1) > b').text();\n listings[i].compensation = compensation; \n }\n return data = listings; \n}", "function locationizer(work_obj) {\n var locationArray = [];\n for (var i = 0; i < work.jobs.length; i++) {\n var newLocation = work_obj.jobs[i].location;\n locationArray.push(newLocation);\n }\n return locationArray;\n}" ]
[ "0.7148418", "0.7025621", "0.69584244", "0.69404244", "0.6911148", "0.6880452", "0.67893255", "0.67444444", "0.6595268", "0.65861154", "0.6584568", "0.6532439", "0.65292734", "0.6502544", "0.64014596", "0.6290411", "0.6269926", "0.6131509", "0.6109898", "0.60503525", "0.6031513", "0.6026856", "0.60207266", "0.5986455", "0.5983966", "0.5972388", "0.5946531", "0.59389675", "0.5897873", "0.5894335", "0.5893586", "0.5862025", "0.585984", "0.585717", "0.5856232", "0.5792587", "0.57866746", "0.57637686", "0.5759744", "0.57546455", "0.573629", "0.5735422", "0.5726098", "0.5712245", "0.57115006", "0.5705967", "0.5700467", "0.5697591", "0.5692893", "0.5690462", "0.56894815", "0.5684559", "0.56756926", "0.56685686", "0.56556016", "0.5653438", "0.5648905", "0.5643768", "0.564376", "0.56320703", "0.5605421", "0.5602683", "0.5601033", "0.55957514", "0.5589205", "0.5587618", "0.55871385", "0.5549429", "0.5540731", "0.5540502", "0.55336714", "0.5526733", "0.5475489", "0.54592466", "0.5440102", "0.5438479", "0.5434449", "0.5424845", "0.54226214", "0.5412585", "0.54065984", "0.5401651", "0.5399516", "0.53956115", "0.5392629", "0.53925645", "0.539105", "0.5384038", "0.5380574", "0.5374216", "0.536675", "0.5363281", "0.536068", "0.5356458", "0.5351785", "0.5344265", "0.5337648", "0.5327133", "0.5323054", "0.5309166" ]
0.55048627
72
recuperation des informations personnelles de l'utilisateur
function gotData(data){ var datas = data.val(); var keys = Object.keys(datas); console.log(keys); for (var i = 0; i<keys.length; i++){ if (keys[i] == userId){ var k = keys[i]; name = datas[k].name; document.getElementById('name').innerHTML = "Name : " + name; jobs = datas[k].jobs; document.getElementById('jobs').innerHTML = "Jobs : " + jobs; contact = datas[k].contact; document.getElementById('contact').innerHTML = "Contact : " + contact; tjm = datas[k].TJM; document.getElementById('tjm').innerHTML = "TJM : " + tjm; // console.log(name); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 }", "function persona(usr,contra,ip,puert) {\n this.usuario=usr;\n this.contraseña=contra;\n this.IP =ip;\n this.puerto=puert;\n}", "function arearecaudacion(){\n this.usuario;\n}", "ngOnInit() {\n this.fetch(data => {\n this.temp = [...data];\n this.rows = data;\n });\n //verificar id_usuario y id_rol\n const id_persona = localStorage.getItem('id_persona');\n this.registroRoleService.getPerson(id_persona)\n .subscribe((respuesta) => {\n this.registroroleperson = respuesta;\n this.registroroleperson.id_persona = id_persona;\n });\n }", "function utilisateur(e)\n { setuser({\n ...user,\n [e.target.name]:e.target.value\n })\n }", "function showFormarttedInfo(user) {\n console.log('user Info', \"\\n id: \" + user.id + \"\\n user: \" + user.username + \"\\n firsname: \" + user.firsName + \"\\n \");\n}", "ngOnInit() {\n this.fetch(data => {\n this.temp = [...data];\n this.rows = data;\n });\n // //verificar id_usuario y id_rol\n // const id_persona = localStorage.getItem('id_persona');\n // this.registroRoleService.getPerson(id_persona)\n // .subscribe((respuesta: Personas) => {\n // this.registroroleperson = respuesta;\n // this.registroroleperson.id_persona = id_persona;\n // });\n }", "function mostrarUsuarios(tipo) {\n const inscriptions = course.inscriptions;\n let lista = null;\n\n users = inscriptions?.map((inscription) => inscription.user);\n const teacher = new Array(course.creator);\n const delegate = new Array(course.delegate);\n\n if (tipo === 'Profesor') {\n lista = <UsersList courseId={courseId} users={teacher} setSelectedUser={(a)=>{console.log(a);}}/>;\n } else if (tipo === 'Delegados') {\n lista = <UsersList courseId={courseId} users={delegate} setSelectedUser={(a)=>{console.log(a);}} />;\n } else {\n lista = <UsersList courseId={courseId} users={users} setSelectedUser={(a)=>{console.log(a);}} />;\n }\n\n return lista;\n }", "afficher(){\r\n \tconsole.log('nom '+this.nom);\r\n \tconsole.log('prenom '+this.prenom);\r\n \tconsole.log('mail '+this.mail);\r\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 getUserInfo() {\n\n // Get the people picker object from the page.\n var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;\n\n // Get information about all users.\n var users = peoplePicker.GetAllUserInfo();\n var userInfo = '';\n for (var i = 0; i < users.length; i++) {\n var user = users[i];\n for (var userProperty in user) {\n userInfo += userProperty + ': ' + user[userProperty] + '<br>';\n }\n }\n $('#resolvedUsers').html(userInfo);\n\n // Get user keys.\n var keys = peoplePicker.GetAllUserKeys();\n $('#userKeys').html(keys);\n\n // Get the first user's ID by using the login name.\n getUserId(users[0].Key);\n}", "function getUsuarioActivo(nombre){\n return{\n uid: 'ABC123',\n username: nombre\n\n }\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}", "getUser(id) {\n return this.users.filter(user => user.id === id)[0]; //VOY A TENER EL PRIMER ELEMENTO DE LA LISTA ES DECIR SOLO UN USUARIO / AL COLOCARLE QUIERO EL PRIMER ELEMENTO SOLO ME DARA EL OBJETO YA NO COMO LISTA DE OBJETO SINO SOLO EL OBJETO\n }", "function mostrarInfoSesion($usuario){\n\n $('aside').css('display','flex');\n\n $user=new Usuario($usuario.idUsuario, $usuario.nombreUsuario, $usuario.email, $usuario.password, $usuario.codResp);\n\n $('aside div:nth-child(2)').text('user: '+$user.getIdUsuario()+'-'+$user.getNombreUsuario());\n $('aside div:nth-child(3)').text($user.getEmail());\n\n\n}", "function renderizarUsuarios(personas) {\n console.log(personas);\n var html = '';\n html += '<li>';\n html += ' <a href=\"javascript:void(0)\" class=\"active\"> Chat de <span> ' + sala + '</span></a>';\n html += '</li>';\n for (let i = 0; i < personas.length; i++) {\n const per = personas[i];\n html += '<li>';\n html += ' <a data-id=\"' + per.id + '\" href=\"javascript:void(0)\"><img src=\"assets/images/users/' + (i + 1) + '.jpg\" alt=\"user-img\" class=\"img-circle\"> <span>' + per.nombre + ' <small class=\"text-success\">online</small></span></a>';\n html += '</li>';\n }\n divUsuario.html(html);\n}", "function getUserList() {\n userService.getUsers()\n .then(function (users) {\n var result = users.filter(function (u) {\n return u.Id !== vm.current.details.ownerId;\n });\n vm.ownerForm.users = result;\n });\n }", "function getUserDetails(req,res,next){\n req.checkParams('id').isInt();\n req.getValidationResult().then(result=>{\n if(!result.isEmpty()){\n //la liste des users \n res.redirect(\"/admin/users\");\n return;\n }\n return users.find({\n include:[\n \n {\n model:comments,\n \n },\n {\n model:commandes,\n include:[\n {\n model: cp,\n attributes:[\"qtte\",\"size\"],\n include:[{\n model:pizza,\n attributes:[\"nom\"]\n }]\n }\n ]\n }\n ],\n where:{\n id: req.params.id\n }\n });\n }).then( dt=>{\n\n let client = dt.dataValues;\n console.log(client)\n client.commandes = client.commandes.map(el=>{\n let e = el.dataValues;\n console.log(e);\n \n e.pizzas = el.commandes_pizzas.map(p=>{\n let dv = p.dataValues;\n let pz = {\n qtte: dv.qtte,\n size: dv.size,\n pizza: dv.pizza.dataValues.nom\n };\n return pz;\n \n \n });\n return e;\n });\n client.comments = client.comments.map(el=>el.dataValues);\n req._user= client;\n \n next();\n }).catch(err=>next(err));\n \n \n}", "function renderizarUsuarios(personas) {\n console.log(personas);\n\n var html = '';\n\n // Html que se mostrara en el frontend\n html += '<li>';\n html += '<a href=\"javascript:void(0)\" class=\"active\"> Chat de <span>' + params.get('sala') + '</span></a>';\n html += '</li>';\n\n for (let i = 0; i < personas.length; i++) {\n\n html += '<li>';\n html += '<a data-id=\"' + personas[i].id + '\" href=\"javascript:void(0)\"><img src=\"assets/images/users/1.jpg\" alt=\"user-img\" class=\"img-circle\"> <span>' + personas[i].nombre + '<small class=\"text-success\">online</small></span></a>';\n html += '</li>';\n\n }\n\n // Inserta todo el contenido de la variable html, en el divUsuarios del front\n divUsuarios.html(html);\n\n}", "async bringUser(req,res){\n //función controladora con la lógica que muestra los usuarios\n }", "function printUser(user){\n console.log(\"Nombre: \"+ user.name + \"\\nEdad: \"+ user.age + \"\\nEmail: \"+ user.email + \"\\n\");\n}", "function escucha_users(){\n\t/*Activo la seleccion de usuarios para modificarlos, se selecciona el usuario de la lista que\n\tse muestra en la pag users.php*/\n\tvar x=document.getElementsByTagName(\"article\");/*selecciono todos los usuarios ya qye se encuentran\n\tdentro de article*/\n\tfor(var z=0; z<x.length; z++){/*recorro el total de elemtos que se dara la capacidad de resaltar al\n\t\tser seleccionados mediante un click*/\n\t\tx[z].onclick=function(){//activo el evento del click\n\t\t\t/*La funcion siguiente desmarca todo los articles antes de seleccionar nuevamente a un elemento*/\n\t\t\tlimpiar(\"article\");\n\t\t\t$(this).css({'border':'3px solid #f39c12'});\n\t\t\tvar y=$(this).find(\"input\");\n\t\t\tconfUsers[indice]=y.val();\n\t\t\tconsole.log(confUsers[indice]);\n\t\t\t/* indice++; Comento esta linea dado que solo se puede modificar un usuario, y se deja para \n\t\t\tun uso posterior, cuando se requiera modificar o seleccionar a mas de un elemento, que se\n\t\t\talmacene en el arreglo de confUser los id que identifican al elemento*/\n\t\t\tsessionStorage.setItem(\"conf\", confUsers[indice]);\n\t\t};\n\t}\n}", "function User(nombres, apellidos, email, password, password2, departamento, municipio, colonia, calle, casa,respuesta, dui, nit, numero, fecha){\r\n\tthis.nombres=nombres;\r\n\tthis.apellidos=apellidos;\r\n\tthis.email=email;\r\n\tthis.password=password;\r\n\tthis.password2=password2;\r\n\tthis.departamento= departamento;\r\n\tthis.municipio= municipio;\r\n\tthis.colonia= colonia;\r\n\tthis.calle= calle;\r\n\tthis.casa= casa;\r\n\tthis.respuesta=respuesta;\r\n\tthis.dui=dui;\r\n\tthis.nit=nit;\r\n\tthis.numero=numero;\r\n\tthis.fecha= fecha;\r\n\t//se inicializa cada variable a el valor que se ha pasado\r\n\tthis.comprobar= function(){\r\n\t\t//se crean los patrones\r\n\t\tvar pre= document.frmregistro.pregunseguri.options[frmregistro.pregunseguri.selectedIndex].text;\r\n\t\tvar nombs= /^([A-ZÁÉÍÓÚ]{1}[a-zñáéíóú]+[\\s]?)+$/;\r\n\t\tvar apells=/^([A-ZÁÉÍÓÚ]{1}[a-zñáéíóú]+[\\s]?)+$/;\r\n\t\tvar corr= /^[\\w]+@{1}[\\w]+\\.[a-z]{2,3}/;\r\n\t\tvar pass= /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])([A-Za-z\\d$@$!%*?&]|[^ ]){8,}$/;\r\n\t\tvar depar= ['Santa Ana', 'Sonsonate', 'Ahuachapan', 'La Libertad', 'Chalatenango', 'San Salvador', 'La Paz', 'Cuscatlan','San Vicente','Usulutan','Cabañas','Morazan','San Miguel','La Union'];\r\n\t\tvar du= /^\\d{8}-\\d{1}$/;\r\n\t\tvar ni= /^[0-9]{4}-[0-9]{6}-[0-9]{3}-[0-9]{1}$/;\r\n\t\tvar num= /^[6,7]{1}\\d{3}-\\d{4}$/;\r\n\t\tvar fechaNac= new Date(fecha);\r\n\t\tvar fechaact= new Date();\r\n\t\tvar mes= fechaact.getMonth();\r\n\t\tvar dia= fechaact.getDay();\r\n\t\tvar anio= fechaact.getFullYear();\r\n\t\tfechaact.setDate(dia);\r\n\t\tfechaact.setMonth(mes);\r\n\t\tfechaact.setFullYear(anio);\r\n\t\tvar edad= Math.floor(((fechaact-fechaNac)/(1000*60*60*24)/365));\r\n\t\t//se verifica con un if si todo es true y la longitud es mayor a 0\r\n\t\tif((nombs.test(nombres) && nombres.length!=0) && ((apells.test(apellidos) && apellidos.length!=0)) && ((corr.test(email) && email.length!=0)) && ((pass.test(password) && password.length!=0)) && ((password===password2)) && ((depar.includes(departamento))) && ((municipio.length!=0 && municipio.length!=\" \")) && ((colonia.length!=0 && colonia.length!=\" \")) && ((calle.length!=0 && calle.length!=\" \")) && ((casa.length!=0 && casa.length!=\" \")) && ((du.test(dui))) && ((respuesta.length!=0 && respuesta.length!=\" \")) && ((ni.test(nit))) && ((num.test(numero))) && (edad>=18)){\r\n\t\t\r\n\t\t//LocalStorage\r\n\t\tvar user = {\r\n\t\t\tUsuario: email,\r\n\t\t\tPassword: password,\r\n\t\t\tRespuesta: respuesta,\r\n\t\t\tPregunta: pre\r\n\t\t};\r\n\t\tvar usuarioGuardado = JSON.stringify(user);\r\n\t\tlocalStorage.setItem(\"UsuarioR\", usuarioGuardado);\r\n\t\tvar usuarioStr = localStorage.getItem(\"UsuarioR\");\r\n\t\tvar usuarioStr = JSON.parse(usuarioStr);\r\n\t\tusuarios[count] = usuarioStr;\r\n\t\tcount +=1;\r\n\t\t//Fin LocalStorage\r\n\r\n\t\t\t//se mmuestra la modal dependiendo del rsultado\r\n\t\t\tcontRegistro.style.display = \"none\";\r\n\t\t\tmodal.style.display = 'block';\r\n\t\t\tcont2.style.marginTop = '9.5%';\r\n\t\t\tcapaN.style.opacity = '0';\r\n\t\t\tsuccessM.style.color = '#40A798';\r\n\t\t\tlblalert.innerHTML = \"Datos correctos, el Registro ha sido exitoso\";\r\n\t\t\r\n\t\tbtncerrarmodal.onclick = function(){\r\n\t\twindow.location= \"../html/menu.html\";\r\n\t\tmodal.style.display = 'none';\r\n\t\tcontRegistro.style.display = \"block\";\r\n\t\tcont2.style.marginTop = '-5%';\r\n\t\tcapaN.style.opacity = '1';\r\n\t\tsuccessM.style.color = '#E23E57';\r\n\t\t\t}\r\n\t\t}else{\r\n\t\tcontRegistro.style.display = \"none\";\r\n\t\tmodal.style.display = 'block';\r\n\t\tcont2.style.marginTop = '9.5%';\r\n\t\tcapaN.style.opacity = '0';\r\n\tbtncerrarmodal.onclick = function(){\r\n\t\tmodal.style.display = 'none';\r\n\t\tcontRegistro.style.display = \"block\";\r\n\t\tcont2.style.marginTop = '-5%';\r\n\t\tcapaN.style.opacity = '1';\r\n\t}\r\n\t\t}\r\n\t\tif(nombs.test(nombres) && nombres.length!=0){\r\n\t\t\tdocument.frmregistro.input1.style.borderColor=\"#00FF08\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input1.style.borderColor=\"#FF0000\";\r\n\t\t}if(apells.test(apellidos) && apellidos.length!=0){\r\n\t\t\tdocument.frmregistro.input2.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input2.style.borderColor=\"#FF0000\";\r\n\t\t}if(corr.test(email) && email.length!=0){\r\n\t\t\tdocument.frmregistro.input3.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input3.style.borderColor=\"#FF0000\";\r\n\t\t}if(pass.test(password) && password.length!=0){\r\n\t\t\tdocument.frmregistro.input4.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input4.style.borderColor=\"#FF0000\";\r\n\t\t}if(password===password2 && password2.length!=0){\r\n\t\t\tdocument.frmregistro.input5.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input5.style.borderColor=\"#FF0000\";\r\n\t\t}if(depar.includes(departamento)){\r\n\t\t\tdocument.frmregistro.input6.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input6.style.borderColor=\"#FF0000\";\r\n\t\t}if(municipio.length!=0 && municipio.length!=\" \"){\r\n\t\t\tdocument.frmregistro.input7.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input7.style.borderColor=\"#FF0000\";\r\n\t\t}if(colonia.length!=0 && colonia.length!=\" \"){\r\n\t\t\tdocument.frmregistro.input8.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input8.style.borderColor=\"#FF0000\";\r\n\t\t}if(calle.length!=0 && calle.length!=\" \"){\r\n\t\t\tdocument.frmregistro.input9.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input9.style.borderColor=\"#FF0000\";\r\n\t\t}if(casa.length!=0 && casa.length!=\" \"){\r\n\t\t\tdocument.frmregistro.input10.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input10.style.borderColor=\"#FF0000\";\r\n\t\t}if(du.test(dui)){\r\n\t\t\tdocument.frmregistro.input11.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input11.style.borderColor=\"#FF0000\";\r\n\t\t}if(respuesta.length!=0 && respuesta.length!=\" \"){\r\n\t\t\tdocument.frmregistro.inputpregunta.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.inputpregunta.style.borderColor=\"#FF0000\";\r\n\t\t}if(ni.test(nit)){\r\n\t\t\tdocument.frmregistro.input12.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input12.style.borderColor=\"#FF0000\";\r\n\t\t}if(num.test(numero)){\r\n\t\t\tdocument.frmregistro.input13.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input13.style.borderColor=\"#FF0000\";\r\n\t\t}if(edad>=18){\r\n\t\t\tdocument.frmregistro.input14.style.borderColor=\"#00FF00\";\r\n\t\t}else{\r\n\t\t\tdocument.frmregistro.input14.style.borderColor=\"FF0000\";\r\n\t\t}\r\n\t}\r\n}", "function addUser() {\n const newUser = getNewUser()\n const tableBody = getTablebody()\n const htmlNewUser = htmlRowUser(newUser)\n tableBody.innerHTML += htmlNewUser\n saveUsers(newUser)\n getUsersId()\n resetForm()\n //Si el género del nuevo usuario agregado es femenino encontrándose en ese momento en el filtro 'solo mujeres', se mostrará en dicho filtro \n if( filter()==newUser.gender){ \n filter() \n }else{\n printUsers()\n }\n}", "updateList(e) {\n PersonaService.getTiposUser(e.target.value).then(data => this.setState({ Usuarios: data }))\n }", "function fillUserInfo(){\n $('#usrname').text(`${currentUser.username}`)\n $profileName.text(`Name: ${currentUser.name}`)\n $profileUsername.text(`Username: ${currentUser.username}`)\n $profileAccountDate.text(`Account Created: ${currentUser.createdAt.slice(0,10)}`)\n }", "function detalii_user() {\n\n var uid = getQueryVariable('UID')\n\n // pentru detaliile utilizatorului curent\n if (uid == false) {\n $.post('server/getuser.php', function(data) {\n var json_data = JSON.parse(data)\n if (json_data.status == 1) {\n var type_user = [\"Utilizator\", \"Angajat\"]\n const contin = `\n <div class=\"centered card card-success card-outline\" >\n <div class=\"card-body box-profile\">\n <div class=\"text-center\">\n <img class=\"profile-user-img img-fluid img-circle\" src=\"../../dist/img/user.png\" alt=\"User profile picture\">\n </div>\n \n <h3 class=\"profile-username text-center\">${json_data.first_name} ${json_data.last_name}</h3>\n \n <p class=\"text-muted text-center\">${type_user[json_data.user_type]}</p>\n \n <ul class=\"list-group list-group-unbordered mb-3\">\n <li class=\"list-group-item\">\n <b>Email</b> <a class=\"float-right\">${json_data.user_email}</a>\n </li>\n `\n\n if (json_data.user_type == 0) {\n caseta = contin + `<li class=\"list-group-item\">\n <b>Număr de animale adăugate</b> <a class=\"float-right\">${json_data.nr_owned_pets}</a>\n </li>\n </ul>\n <a href=\"animalele_mele.php\" class=\"btn btn-success btn-block\"><b>Animalele mele</b></a>\n </div>\n <!-- /.card-body -->\n </div>`\n } else\n if (json_data.user_type == 1) {\n caseta = contin + `</ul>\n </div>\n <!-- /.card-body -->\n </div>`\n }\n\n if (document.getElementById('continut_pag') != null) {\n document.getElementById('continut_pag').innerHTML += caseta;\n } else {\n console.log('Nu s-a gasit detalii_user.php')\n }\n }\n })\n } else\n // pentru angajatul care vrea sa vada contul unui utilizator\n {\n $.post('server/getuser.php', { WantedUID: uid },\n\n function(data) {\n var json_data = JSON.parse(data)\n if (json_data.status == 1) {\n var type_user = [\"Utilizator\", \"Angajat\"]\n const contin = `\n <div class=\"centered card card-success card-outline\" >\n <div class=\"card-body box-profile\">\n <div class=\"text-center\">\n <img class=\"profile-user-img img-fluid img-circle\" src=\"../../dist/img/user.png\" alt=\"User profile picture\">\n </div>\n \n <h3 class=\"profile-username text-center\">${json_data.first_name} ${json_data.last_name}</h3>\n \n <p class=\"text-muted text-center\">${type_user[json_data.user_type]}</p>\n \n <ul class=\"list-group list-group-unbordered mb-3\">\n <li class=\"list-group-item\">\n <b>Email</b> <a class=\"float-right\">${json_data.user_email}</a>\n </li>\n `\n\n if (json_data.user_type == 0) {\n caseta = contin + `<li class=\"list-group-item\">\n <b>Număr de animale adăugate</b> <a class=\"float-right\">${json_data.nr_owned_pets}</a>\n </li>\n </ul>\n </div>\n <!-- /.card-body -->\n </div>`\n } else\n if (json_data.user_type == 1) {\n caseta = contin + `</ul>\n </div>\n <!-- /.card-body -->\n </div>`\n }\n\n if (document.getElementById('continut_pag') != null) {\n document.getElementById('continut_pag').innerHTML += caseta;\n } else {\n console.log('Nu s-a gasit detalii_user.php')\n }\n }\n })\n\n }\n}", "function precargarUsers() {\n fetch(`${baseUrl}/${groupID}/${collectionID}`, {\n 'method': 'GET'\n }).then(res => {\n return res.json();\n }).then(json => {\n if (json.status === 'OK') {\n mostrarDatos(json.usuarios);\n };\n }); //agregar catch\n }", "function listUsersAdmin() {\n $scope.isDataUserReady = false;\n $http({\n method: 'GET',\n url: baseUrl + 'admin/user_entreprise/list/' + idInstitution + '/' + idAdmin,\n data: {},\n headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jeton') }\n }).then(function successCallback(response) {\n $scope.listUsers = response.data.entreprise_users_list;\n for (var i = 0; i < $scope.listUsers.length; i++) {\n if ($scope.listUsers[i].idUtilisateur == sessionStorage.getItem(\"iduser\")) {\n $scope.isuserInsessionLine = i;\n break;\n };\n };\n $scope.isDataUserReady = true;\n }).catch(function(err) {\n if (err.status == 500 && localStorage.getItem('jeton') != '' && localStorage.getItem('jeton') != null && localStorage.getItem('jeton') != undefined) {\n deconnectApi.logout(sessionStorage.getItem(\"iduser\")).then(function(response) {\n $location.url('/access/login');\n $state.go('access.login');\n }).catch(function(response) {});\n };\n });\n }", "function getSetUserDetail(){\n return userDetail;\n }", "function getUserInfo(){\n var f_name = $('#new_fname').val();\n var email = $('#new_username').val();\n var password = $('#new_password').val();\n var info = {\"user\":{\"name\":f_name,\"email\":email, \"password\":password ,\"privileges\":\"none\"}};\n return info;\n }", "getUser(email, password) {\n this.email = email;\n this.password = password;\n\n const userData = this.app.readDataFile(userFilePath);\n\n userData.forEach((item) => {\n if (item.email === this.email && item.password === this.password) {\n this.userInfo = item;\n }\n });\n\n return this.userInfo;\n }", "function acceder(){\r\n limpiarMensajesError()//Limpio todos los mensajes de error cada vez que corro la funcion\r\n let nombreUsuario = document.querySelector(\"#txtUsuario\").value ;\r\n let clave = document.querySelector(\"#txtClave\").value;\r\n let acceso = comprobarAcceso (nombreUsuario, clave);\r\n let perfil = \"\"; //variable para capturar perfil del usuario ingresado\r\n let i = 0;\r\n while(i < usuarios.length){\r\n const element = usuarios[i].nombreUsuario.toLowerCase();\r\n if(element === nombreUsuario.toLowerCase()){\r\n perfil = usuarios[i].perfil;\r\n usuarioLoggeado = usuarios[i].nombreUsuario;\r\n }\r\n i++\r\n }\r\n //Cuando acceso es true \r\n if(acceso){\r\n if(perfil === \"alumno\"){\r\n alumnoIngreso();\r\n }else if(perfil === \"docente\"){\r\n docenteIngreso();\r\n }\r\n }\r\n}", "function getListGeneralUserAuthorized() {\n var ListGeneralUserAuthorized = [];\n var temp;\n var len=0;\n var leng=0;\n var found=false;\n \n // Recuperation de la liste des users Admin\n temp = Get_ADMIN().split(',');\n len = temp.length;\n for(n=1;n<len+1;++n){\n ListGeneralUserAuthorized.push(temp[n-1]);\n }\n // Recuperation de la liste des users Admin du Suivi\n temp = Get_ADMIN_SUIVI().split(',');\n len = temp.length;\n leng = ListGeneralUserAuthorized.length;\n for(n=1;n<len+1;++n){\n found=false;\n for (m=1;m<leng+1;++m) {\n if (ListGeneralUserAuthorized[m-1] == temp[n-1]) {\n found=true;\n break;\n }\n }\n if (found == false) {\n ListGeneralUserAuthorized.push(temp[n-1]);\n }\n }\n // Recuperation de la liste des users de la BU SQLi Entreprise Paris\n temp = (GetManagerBU(BU_ENTREPRISE_PARIS)).split(',');\n len = temp.length;\n leng = ListGeneralUserAuthorized.length;\n for(n=1;n<len+1;++n){\n found=false;\n for (m=1;m<leng+1;++m) {\n if (ListGeneralUserAuthorized[m-1] == temp[n-1]) {\n found=true;\n break;\n }\n }\n if (found == false) {\n ListGeneralUserAuthorized.push(temp[n-1]);\n }\n } \n // Recuperation de la liste des users de la BU Compta Fournisseur\n temp = (GetManagerBU(BU_COMPTA_FOURNISSEUR)).split(',');\n len = temp.length;\n leng = ListGeneralUserAuthorized.length;\n for(n=1;n<len+1;++n){\n found=false;\n for (m=1;m<leng+1;++m) {\n if (ListGeneralUserAuthorized[m-1] == temp[n-1]) {\n found=true;\n break;\n }\n }\n if (found == false) {\n ListGeneralUserAuthorized.push(temp[n-1]);\n }\n }\n // Recuperation de la liste des users de la BU Assistante\n temp = (GetManagerBU(BU_ASSISTANTE_ENTREPRISE_PARIS)).split(',');\n len = temp.length;\n leng = ListGeneralUserAuthorized.length;\n for(n=1;n<len+1;++n){\n found=false;\n for (m=1;m<leng+1;++m) {\n if (ListGeneralUserAuthorized[m-1] == temp[n-1]) {\n found=true;\n break;\n }\n }\n if (found == false) {\n ListGeneralUserAuthorized.push(temp[n-1]);\n }\n }\n return ListGeneralUserAuthorized;\n}", "function obtenerPermisosUsuario(){\n\n\t\tvar user = $('select#usuario').val();\n\t\tvar table = $('select#tabla').val();\n\n\t\t$.ajax({\n\n\t\t\tdata: { user: usuario, \n\t\t\t\t\tpass: pasword,\n\t\t\t\t\tagencia: agencia,\n\t\t\t\t\tusuario: user,\n\t\t\t\t\ttabla: table},\n\t\t\t\t\turl: 'http://apirest/permisos/tabla/',\n\t\t\t\t\ttype: 'POST',\n\n\t\t\tsuccess: function(data, status, jqXHR) {\n\t\t\t\tconsole.log(data);\n\n\t\t\t\tif(data.message == 'Autentication Failure'){\n\t\t\t\t\tmostrarMensaje(\"No estas autorizado para la gestión de permisos\",\"../../index.php\");\n\t\t\t\t}else if(data.message == 'OK'){\n\t\t\t\t\tmostrarPermisos(data);\n\t\t\t\t}else{\n\t\t\t\t\tmostrarMensajePermisos(\"No estas autorizado para añadir/eliminar permisos a ese usuario\");\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\terror: function (jqXHR, status) { \n\t\t\t\tmostrarMensaje(\"Fallo en la petición al Servicio Web\",\"../../index.php\");\n\t\t\t}\n\t\t\t\n\t\t});\n\n\t}", "function user(){\r\n uProfile(req, res);\r\n }", "function fetchUserInfo(){\n\t gapi.client.load('oauth2', 'v1', function(){\n\t var userinfo = gapi.client.request('oauth2/v1/userinfo?alt=json');\n\t userinfo.execute(function(resp){\n\t window.user={\n\t \t\"email\":resp.email,\n\t \t//\"name\":resp.given_name,\n\t \t//\"id\":resp.id\n\t }\n\t loadTimeline();\n\t });\n\t });\n\t }", "getUserInfo() {\n if (this.infos && this.infos.length > 0)\n return;\n this.client.request(\"GET\", \"users/current\").then((response) => {\n this.infos = response.body;\n this.connect();\n });\n }", "function people(type, res) {\n sync.syncUsersInfo(type, function(err, repeatAfter, diaryEntry) {\n if(err) {\n \n } else {\n locker.diary(diaryEntry);\n locker.at('/getNew/' + type, repeatAfter);\n res.writeHead(200, {'content-type':'application/json'});\n res.end(JSON.stringify({success:\"done fetching \" + type}));\n }\n });\n }", "function getUserInformation(){\n console.log(userInformation);\n return userInformation;\n }", "function Info(user) {\n return `${user.name} tem ${user.age} anos.`;\n}", "function newUser() { // Ajout d'un nouvel utilisateur\n\n // Cible le container des profils\n const userProfileContainer = document.querySelector(\".user-profile-container\");\n\n let myName = prompt(\"Prénom de l'utilisateur\");\n\n if (myName.length !== 0) { // On vérifie que le prompt ne soit pas vide\n\n usersNumber+=1; // Incrémente le nombre d'utilisateurs\n\n // 1 - Créer un nouveau user-profile\n const userProfile = document.createElement(\"div\");\n // Lui assigner la classe userProfileContainer\n userProfile.classList.add(\"user-profile\");\n // Lui assigner un ID\n userProfile.id = `user-profile-${usersNumber}`; \n // L'ajouter au DOM \n userProfileContainer.insertBefore(userProfile, document.querySelector(\"#add-user\"));\n\n // 2 - Créer un nouveau user portrait\n const userPortrait = document.createElement(\"div\");\n // Lui assigner la classe portrait\n userPortrait.classList.add(\"user-portrait\");\n // Lui assigner un ID\n userPortrait.id = `user-portrait-${usersNumber}`;\n // L'ajouter au DOM\n document.getElementById(`user-profile-${usersNumber}`).appendChild(userPortrait);\n\n // 3 - Créer un nouveau user-portrait__image\n const userPortraitImage = document.createElement(\"img\");\n // Lui assigner la classe userImage\n userPortraitImage.classList.add(\"user-portrait__image\");\n // Lui assigner un ID\n userPortraitImage.id = `user-portrait-image-${usersNumber}`;\n // Ajouter une image automatiquement\n userPortraitImage.src = \"assets/img/new_user_added.png\";\n // L'ajouter au DOM\n document.getElementById(`user-portrait-${usersNumber}`).appendChild(userPortraitImage);\n\n // 4 - Créer un nouveau user-name\n const userName = document.createElement(\"h2\");\n // Lui assigner la classe profileName\n userName.classList.add(\"user-name\");\n // Utiliser un innerHTML pour afficher le nom\n userName.innerHTML = myName;\n // L'ajouter au DOM\n document.getElementById(`user-portrait-${usersNumber}`).appendChild(userName);\n }\n}", "constructor() {\n this.idUser;\n this.emailUser;\n this.nameUser;\n this.passwordUser;\n }", "function setVisitor() {\n\n\n $rootScope.muser.visitorID = $scope.user.name+ $scope.user.surname;\n $rootScope.muser.name = $scope.user.name;\n $rootScope.muser.surname = $scope.user.surname;\n\n\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 }", "function getUserInfo() {\n\t\t\treturn User.getUser({\n\t\t\t\tid: $cookieStore.get('userId')\n\t\t\t}).$promise.then(function(response) {\n\t\t\t\tswitch(response.code) {\n\t\t\t\t\tcase 0: {\n\t\t\t\t\t\t$scope.ganbaru.username = response.data.username;\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, function() {\n\t\t\t\t//Handling error\n\t\t\t});\n\t\t}", "function obtener_superior() {\n\tcargando('Obteniendo información')\n\tvar superiores = document.getElementsByClassName('refer')\n\tfor (var i = 0; i < superiores.length; i++) {\n\t\tenvio = { numero: i, nombre: superiores[i].innerText }\n\t\t$.ajax({\n\t\t\tmethod: \"POST\",\n\t\t\turl: \"/admin-reportes/cabeza_principal\",\n\t\t\tdata: envio\n\t\t}).done((respuesta) => {\n\t\t\tdocument.getElementsByClassName('superior')[respuesta.numero].innerHTML = respuesta.referido\n\t\t\tvar env = { numero: respuesta.numero, nombre: document.getElementsByClassName('superior')[respuesta.numero].innerHTML }\n\t\t\t$.ajax({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\turl: \"/admin-reportes/cabeza_principal\",\n\t\t\t\tdata: env\n\t\t\t}).done((respuesta) => {\n\t\t\t\tdocument.getElementsByClassName('principal')[respuesta.numero].innerHTML = respuesta.referido\n\t\t\t})\n\t\t})\n\t}\n\tno_cargando()\n}", "function getAllRegUser(){\n var filter = {};\n $scope.regUsers = [];\n userSvc.getUsers(filter).then(function(data){\n data.forEach(function(item){\n if(item.email)\n $scope.regUsers[$scope.regUsers.length] = item;\n });\n })\n .catch(function(err){\n Modal.alert(\"Error in geting user\");\n })\n }", "function perfilResponsavel(usuario, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select Responsavel.cpfResponsavel, Responsavel.nomeResponsavel, Responsavel.enderecoResponsavel, Responsavel.telefoneResponsavel, emailResponsavel from Responsavel where Responsavel.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}", "function loadusers() {\n fetch('https://milelym.github.io/scl-2018-05-bc-core-pm-datadashboard/data/cohorts/lim-2018-03-pre-core-pw/users.json')\n .then(function(resp) {\n return resp.json();\n //retorna la data\n })\n // maneja la data se crea una variable fuera de la funcion y los valores se guardan en un objeto//\n .then(function (valores) {\n data.user = valores;\n // console.log('data.user es :',data.user);\n // para imprimirlo cuando se obtenda la informacion//\n loadcortes();\n });\n}", "function abreUsuarioDialog(marker,idTarget) {\n\t// Activamos conexión con otro usuario\n\tvar index=usuarios.indexOf(idTarget);\n\tvar nombre=usuariosData[index].nombre;\n\tvar edadUser=usuariosData[index].edad;\n\tvar infoContent='<div class=\"id\">'+nombre+' ('+edadUser+')</div><div class=\"btnToChat\">chatea ></div>';\n\tinfowindow.content=infoContent;\n\tinfowindow.open(map,marker);\n\t $('.btnToChat').click(function(){\n\t\tabreChat(idTarget,index);\n\t});\n}", "updateUserDetails() {\n if (!activeUser()) return;\n $(conversations_area).find(`[data-user-id=\"${activeUser().id}\"] .sb-name,.sb-top > a`).html(activeUser().get('full_name'));\n $(conversations_area).find('.sb-user-details .sb-profile').setProfile();\n SBProfile.populate(activeUser(), $(conversations_area).find('.sb-profile-list'));\n }", "function GetAndPrepUsers(){\n var url = config.api.url + \"actie/users?id=\" + $scope.actieId;\n $http({\n url: url,\n method: 'GET'\n }).success(function(data, status, headers) {\n data.forEach(function(user) {\n console.log(user);\n var fullName = user.voornaam + \" \";\n //Prevent duble space with middle name\n if(user.tussenvoegsel || user.tussenvoegsel !== null){\n fullName += user.tussenvoegsel + \" \";\n }\n fullName += user.achternaam;\n \n var borgBetaald = \"Nee\";\n if(user.borg_betaald){\n borgBetaald = \"Ja\";\n $scope.totalBorg = $scope.totalBorg + 1;\n }\n \n var phone = \"\";\n if(user.telefoonnummer || user.telefoonnummer !== null){\n phone = \"0\" + user.telefoonnummer;\n }\n \n var selectedProvider = \"\";\n if(user.provider_id || user.provider_id !== null){\n var providerUrl = config.api.url + \"provider?id=\" + user.provider_id;\n $http({\n url: providerUrl,\n method: 'GET'\n }).success(function(data, status, headers, config) {\n selectedProvider = data.naam;\n $scope.rows.push({\n nr: user.gebruiker_id,\n naam: fullName,\n phone: phone,\n borg: borgBetaald,\n provider: selectedProvider\n });\n $scope.addNewRows();\n }).error(function(data, status, headers, config) {\n $scope.rows.push({\n nr: user.gebruiker_id,\n naam: fullName,\n phone: phone,\n borg: borgBetaald,\n provider: selectedProvider\n });\n $scope.addNewRows();\n });\n }\n else{\n $scope.rows.push({\n nr: user.gebruiker_id,\n naam: fullName,\n phone: phone,\n borg: borgBetaald,\n provider: selectedProvider\n });\n $scope.addNewRows();\n }\n $scope.totalUsers = $scope.totalUsers + 1;\n });\n $scope.addNewRows(); \n console.log(\"User load succes\");\n }).error(function(data, status, headers, config) {\n console.log(\"User load failed\");\n });\n }", "edit({ email, name, password, image }) {\n let details = { email, name, password, image };\n for (const key in details)\n if (details[key]) {\n currentUser[key] = details[key];\n }\n callFuture(updateUserListeners);\n }", "function getuser (param,res){\n req=\"SELECT UtilisateurJSON FROM Utilisateur where nom=?\"\n var paramarray = [param];\n console.log(\"requete : \"+req+\" \"+paramarray)\n reqsql.requetesql(req,paramarray,res); \n}", "info_user_to(){\n var username = this;\n var user_to = username.assigned_to;\n Meteor.subscribe('assigned_to_user_name', user_to);\n return user_details.find({\"user_id\" : user_to }).fetch();\n }", "function userInfo(name, email, password) {\r\n\tthis.name=name\r\n\tthis.email=email\r\n\tthis.password=password\r\n}", "getUserInfo(){\n return getUser()\n }", "function getUser () {return user;}", "info_user_by(){\n var username = this;\n var user_by = username.assigned_by;\n Meteor.subscribe('assigned_by_user_name', user_by);\n return user_details.find({'user_id' : user_by}).fetch();\n }", "list(req, res) {\n return Panic.findAll({\n include: [\n {\n model: User,\n as: \"user\",\n attributes: [\"user_name\", \"user_cell\"],\n },\n {\n model: Responder,\n as: \"responder\",\n attributes: [\"responder_name\", \"responder_cell\", \"responder_location\", \"responder_lat\", \"responder_lng\"],\n },\n ],\n })\n .then((users) => res.status(200).send(users))\n .catch((error) => {\n res.status(400).send(error);\n });\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 fillUsuarios() {\n $scope.dataLoading = true;\n apiService.get('api/user/' + 'GetAll', null, getAllUsuariosCompleted, apiServiceFailed);\n }", "function getUsersConnected() {\n //Quantidada de usuarios\n io.sockets.emit('qtdUsers', { \"qtdUsers\": usersConnected });\n\n //retorna os nomes dos usuarios\n io.sockets.emit('listaUsuarios', Object.keys(listUsers));\n}", "function etreasuryUsersAdmin() {\n $scope.isDataReadyEtUsers = false;\n $http({\n method: 'GET',\n url: baseUrl + 'admin/user_admin/list',\n data: {},\n headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jeton') }\n }).then(function successCallback(response) {\n $scope.etreasuryUsers = response.data.admin_list;\n for (var i = 0; i < $scope.etreasuryUsers.length; i++) {\n if ($scope.etreasuryUsers[i].idUtilisateur == sessionStorage.getItem(\"iduser\")) {\n $scope.isuserInsessionLine = i;\n break;\n };\n };\n $scope.isDataReadyEtUsers = true;\n }).catch(function(err) {\n if (err.status == 500 && localStorage.getItem('jeton') != '' && localStorage.getItem('jeton') != null && localStorage.getItem('jeton') != undefined) {\n deconnectApi.logout(sessionStorage.getItem(\"iduser\")).then(function(response) {\n $location.url('/access/login');\n $state.go('access.login');\n }).catch(function(response) {});\n };\n });\n }", "function fetchUserData(){\n\tlet xmlhttp = new XMLHttpRequest();\n xmlhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n\t\t let json = JSON.parse(this.responseText);\n\t\t\tdocument.getElementById(\"userName\").innerHTML = json.mensaje.username;\n\t\t\tdocument.getElementById(\"emailAddress\").innerHTML = \"<p>\" + json.mensaje.email + \"</p>\";\n }\n }\n\txmlhttp.open(\"GET\", \"../scripts/userInformation.php?action=user_data\", true);\n xmlhttp.send();\n}", "function seleccionePersona(tipo){\n elementos.mensajePanel.find('h3').text('Seleccione un '+tipo+' para ver las devoluciones disponibles');\n elementos.mensajePanel.removeClass('hide');\n elementos.devolucionesTabla.addClass('hide');\n elementos.mensajePanel.find('.overlay').addClass('hide');\n }", "function editInfo() {\n io.emit('usernames', userNameList);\n socket.emit('updateUser', currentUsers[socket.id]);\n }", "function imprimrir2( persona ) {\n\n console.log( persona.nombre+\" \"+persona.apellido );\n}", "function userInfo() {\n FB.api('/me', {\n fields: 'id,name,email'\n }, function (response) {\n\n $.ajax('/api/user/login?data=' + JSON.stringify(response))\n\n .done(function (data) {\n // console.log(data)\n })\n\n .fail(function () {\n window.location.reload();\n })\n \n });\n }", "function getUser(){\n return user;\n }", "function mostrarPermisos(data){\n\n\t\tif(data.add == 1){\n\t\t\taddIcoPermOk(\"add-est\");\n\t\t\taddBtnQuitar(\"add\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"add-est\");\n\t\t\taddBtnAdd(\"add\");\n\t\t}\n\t\tif(data.upd == 1){\n\t\t\taddIcoPermOk(\"upd-est\");\n\t\t\taddBtnQuitar(\"upd\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"upd-est\");\n\t\t\taddBtnAdd(\"upd\");\n\t\t}\n\t\tif(data.del == 1){\n\t\t\taddIcoPermOk(\"del-est\");\n\t\t\taddBtnQuitar(\"del\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"del-est\");\n\t\t\taddBtnAdd(\"del\");\n\t\t}\n\t\tif(data.list == 1){\n\t\t\taddIcoPermOk(\"list-est\");\n\t\t\taddBtnQuitar(\"list\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"list-est\");\n\t\t\taddBtnAdd(\"list\");\n\t\t}\n\n\t\t/*Una vez dibujados los permisos del usuario, \n\t\tel selector de usuario obtiene el foco */\n\t\t$('select#usuario').focus(); \n\n\t}", "get informations() {\n return this.pseudo + ' (' + this.classe + ') a ' + this.sante + ' points de vie et est au niveau ' + this.niveau + '.'\n }", "getUsuario(id) {\n for (let usuario of this.lista) {\n if (usuario.id === id) {\n return usuario;\n }\n }\n }", "getUserInfos() {\n return Api.get(\"client/user-infos\");\n }", "async function getUserInfo() {\n let userData = await Auth.currentAuthenticatedUser();\n setUser(userData.username);\n setUserEmail(userData.attributes.email);\n }", "function modificar_user(identidad) {\n\tcargando('Obteniedo información del usuario')\n\tenvio = { codigo: identidad }\n\t$.ajax({\n\t\tmethod: \"POST\",\n\t\turl: \"/admin-cliente/editar-cliente\",\n\t\tdata: envio\n\t}).done((datos) => {\n\t\tif (datos != 'Error') {\n\t\t\tno_cargando()\n\t\t\tasignar('txtnombre', datos.nombre)\n\t\t\tasignar('txtedad', datos.edad)\n\t\t\tasignar('txtsector', datos.sector)\n\t\t\tasignar('txtcedula', datos.cedula)\n\t\t\tasignar('txttelefono', datos.telefono)\n\t\t\tasignar('textdireccion', datos.direccion)\n\t\t\tasignar('txtmail', datos.username)\n\t\t\tvar opciones = document.getElementsByClassName('listado_referidos')\n\t\t\tfor (var i = 0; i < opciones.length; i++) {\n\t\t\t\topciones[i].removeAttribute('selected')\n\t\t\t}\n\t\t\tfor (var i = 0; i < opciones.length; i++) {\n\t\t\t\tif (datos.referido == opciones[i].value)\n\t\t\t\t\topciones[i].setAttribute('selected', '')\n\t\t\t}\n\t\t\t$('#modal-modificar-user').modal()\n\t\t} else {\n\t\t\tno_cargando()\n\t\t\tswal('Error', 'Ha ocurrido un error inesperado', 'error')\n\t\t}\n\t})\n}", "function initval(){\n user = JSON.parse(localStorage.getItem('user'));\n $('#homename').append(user.first_name + ' ' + user.last_name);\n $('#detname').append(user.first_name + ' ' + user.last_name);\n $('#detbirth').append( new Date(user.birth_date).toLocaleString());\n $('#detemail').append(user.email);\n }", "function usuarioNombre() {\n let currentData = JSON.parse(sessionStorage.getItem('currentUser'));\n if (currentData.rol == \"administrador\")\n return \"Administrador\";\n else if (currentData.rol == \"estudiante\")\n return currentData.Nombre1 + ' ' + currentData.apellido1;\n else if (currentData.rol == \"cliente\")\n return currentData.primer_nombre + ' ' + currentData.primer_apellido;\n else\n return currentData.nombre1 + ' ' + currentData.apellido1;\n}", "function getProfileData() {\n IN.API.Raw(\"/people/~\").result(onSuccess).error(onError);\n }", "function getProfileData() {\n IN.API.Raw(\"/people/~\").result(onSuccess).error(onError);\n }", "function fntViewUsuario(idpersona){\n\t// let btnViewUsuario = document.querySelectorAll('.btnViewUsuario');\n\t// btnViewUsuario.forEach(function(btnViewUsuario){\n\t// \tbtnViewUsuario.addEventListener('click', function(){\n\t\t\t// let idpersona = this.getAttribute('us');\n\t\t\tvar idpersona = idpersona;\n\t\t\tlet request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\n\t\t\tlet ajaxUrl = base_url+'/Usuarios/getUsuario/'+idpersona;\n\t\t\trequest.open(\"GET\", ajaxUrl, true);\n\t\t\trequest.send();\n\t\t\trequest.onreadystatechange = function(){\n\t\t\t\tif (request.readyState == 4 && request.status == 200) {\n\t\t\t\t\tlet objData = JSON.parse(request.responseText);\n\n\t\t\t\t\tif (objData.status)\n\t\t\t\t\t{\n\t\t\t\t\t\tlet estadoUsuario = objData.data.status == 1 ?\n\t\t\t\t\t\t'<span class=\"badge badge-success\">Activo</span>' :\n\t\t\t\t\t\t'<span class=\"badge badge-danger\">Inactivo</span>' ;\n\n\t\t\t\t\t\tdocument.querySelector('#celIdentificacion').innerHTML = objData.data.identificacion;\n\t\t\t\t\t\tdocument.querySelector('#celNombre').innerHTML = objData.data.nombres;\n\t\t\t\t\t\tdocument.querySelector('#celApellido').innerHTML = objData.data.apellidos;\n\t\t\t\t\t\tdocument.querySelector('#celTelefono').innerHTML = objData.data.telefono;\n\t\t\t\t\t\tdocument.querySelector('#celEmail').innerHTML = objData.data.email_user;\n\t\t\t\t\t\tdocument.querySelector('#celTipoUsuario').innerHTML = objData.data.nombrerol;\n\t\t\t\t\t\tdocument.querySelector('#celEstado').innerHTML = estadoUsuario;\n\t\t\t\t\t\tdocument.querySelector('#celFechaRegistro').innerHTML = objData.data.fechaRegistro;\n\t\t\t\t\t\t$('#modalViewUser').modal('show');\n\t\t\t\t\t}else{\n\t\t\t\t\t\tswal(\"Error\", objData.msg, \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t// });\n\t// });\n}", "function renderUsers(people) { \n console.log('DEBUG', 'renderUsers');\n var html = '';\n html += `<li>`;\n html += `<a href=\"javascript:void(0)\" class=\"active\"> Chat de <span> ${params.room}</span></a>`;\n html += `</li>`;\n \n people.forEach(person => {\n html += `<li>`;\n html += `<a data-id=\"${person.id}\" href=\"javascript:void(0)\"><img src=\"assets/images/users/1.jpg\" alt=\"user-img\" class=\"img-circle\"> <span> ${person.name} <small class=\"text-success\">online</small></span></a>`;\n html += `</li>`;\n });\n \n divUsuarios.html(html);\n}", "function obtenerPersonas(res){\n var personas = [];\n tb_persona.connection.query('SELECT * FROM persona', function(err, rows){\n if(err) throw err;\n rows.forEach(function(result){\n personas.push(result);\n });\n res.send(personas);\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}", "function editarUsers(){\n\t//debugger;\n\t// variable que obtengo el arreglo donde estan guardados los usuarios\n\tvar listChamba = JSON.parse(localStorage.getItem(\"usuarios\"));\n\t// obtengo el id para poder modificar el elemento actual\n\tmodificar = JSON.parse(localStorage.getItem(\"id\"));\n\t// recorro el arreglo de arreglos de los usuarios\n\tfor (var i = 0; i < listChamba.length; i++) {\n\t\t// recorro cada uno de los arreglos\n\t\tfor (var j = 0; j < listChamba[i].length; j++) {\n\t\t\t// pregunto que si el modificar es igual al id actual\n\t\t\tif(modificar == listChamba[i][j]){\n\t\t\t\t// si si es igual obtener id\n\t\t\t\tvar n = document.getElementById(\"numero\").value;\n\t\t\t// obtener el nombre completo\n\t\t\tvar fn = document.getElementById(\"fullName\").value;\n\t\t\t// obtener el nombre de usuario\n\t\t\tvar u = document.getElementById(\"user\").value;\n\t\t\t// obtener la contraseña\n\t\t\tvar p = document.getElementById(\"password\").value;\n\t\t\t// obtener la contraseña repetida\n\t\t\tvar pr = document.getElementById(\"password_repeat\").value;\n\t\t\t// pregunto si las contraseñas son vacias o nulas\n\t\t\tif(fn == \"\" || fn == null){\n\t\t\t\t// si es asi muestro un mensaje de error\n\t\t\t\talert(\"No puede dejar el campo de nombre completo vacio\");\n\t\t\t\tbreak;\n\t\t\t\t// si no, pregunto que si el nombre de usuario es vacio o nulo\n\t\t\t}else if(u == \"\" || u == null){\n\t\t\t\t// si es asi muestro un mensaje de error\n\t\t\t\talert(\"No puede dejar el campo de nombre de usuario vacio\");\n\t\t\t\tbreak;\n\t\t\t\t// si no \n\t\t\t}else{\n\t\t\t\t// pregunto que si nas contraseñas son iguales\n\t\t\t\tif(p == pr){\n\t\t\t\t\t// si es asi, le digo que elemento actual en la posicion 0 es igual al id\n\t\t\t\t\tlistChamba[i][j] = n;\n\t\t\t\t\t// la posicion 1 es igual al nombre completo\n\t\t\t\t\tlistChamba[i][j+1] = fn;\n\t\t\t\t\t// la posicion 2 es igual a el nombre de usuario\n\t\t\t\t\tlistChamba[i][j+2] = u;\n\t\t\t\t\t// la posicion 3 es igual a la contraseña\n\t\t\t\t\tlistChamba[i][j+3] = p;\n\t\t\t\t\t// y la posicion 4 es igual a la contraseña repetida\n\t\t\t\t\tlistChamba[i][j+4] = pr;\n\t\t\t\t\t// agrego la modificacion al localstorage\n\t\t\t\t\tlocalStorage['usuarios'] = JSON.stringify(listChamba);\n\t\t\t\t\t// muestro el mensaje para que se de cuenta el usuario que fue modificado\n\t\t\t\t\talert(\"Se Modificó correctamente\");\n\t\t\t\t\t// me voy a la tabla para corroborar que se modificó\n\t\t\t\t\tlocation.href = \"ver_usuarios.html\";\n\t\t\t\t\t// si no fuera asi\n\t\t\t\t}else{\n\t\t\t\t\t// muestro el mensaje de error porque las contraseñas son diferentes\n\t\t\t\t\talert(\"No puede modificar el usuario porque las contraseñas son diferentes\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n}", "function obtenerEquiposParticipantes(){\n wizardFactory.equiposParticipantes(vm.torneoSelected.tor_id)\n .success(function (data) {\n vm.equiposParticipantes = data;\n obtenerEquiposDisponibles();\n })\n .error( errorHandler );\n }", "async show ({ params, request, response, view }) {\n\n return await Database.select('ganadas,perdidas').from('users').where('usuarios','=', params.id)\n \n }", "function getOtherUserNameById(id) {\n // codigo\n return \"Regulus\";\n}", "function userData() {\n let id = \"\"\n if (sessionStorage.getItem(\"loggedUserId\")) {\n id = JSON.parse(sessionStorage.getItem('loggedUserId'))\n }\n for (const user of users) {\n if (user._id == id) {\n document.querySelector('.avatar').src = user._avatar\n }\n }\n}", "getPersonasPorSala(sala) {\n\n }", "async function getInfosUser(login){\n if (login === null) return null;\n try{ \n var value = await knex.raw(\"SELECT users.etat, users.login, users.partiesGagnees, users.partiesPerdues FROM users WHERE users.login= ?\", [login]);\n if (value.length == 1) { \n return value;\n } else {\n console.error('Erreur dans le select d\\'un utilisateur dans la table users'); \n }\n return null;\n }\n catch(err){\n console.error('Erreur dans la connection d\\'un utilisateur dans la table users (getInfosUser)'); \n }\n}", "function showBenutzer(user) {\n\n $(\"#username\").val(tier.tierUUID);\n $(\"#art\").val(tier.art);\n $(\"#name\").val(tier.name);\n $(\"#geburtsdatum\").val(tier.geburtsdatum);\n $(\"#alter\").val(tier.alter);\n $(\"#beine\").val(tier.beine);\n $(\"#fell\").prop(\"checked\", tier.fell);\n $(\"#zoo\").val(tier.zoo.zooUUID);\n\n if (Cookies.get(\"userRole\") != \"admin\") {\n $(\"#art, #name, #geburtsdatum, #alter, #beine, #fell, #zoo\").prop(\"readonly\", true);\n $(\"#save, #reset\").prop(\"disabled\", true);\n }\n}", "function recuperarDatosPunto(){\n vm.nuevoPtoInteres.nombre = vm.nombrePunto;\n vm.nuevoPtoInteres.lat = latPuntoCreacion;\n vm.nuevoPtoInteres.lon = lonPuntoCreacion;\n vm.nuevoPtoInteres.idTipo = vm.tipoSeleccionado.id;\n console.log(\" Datos del nuevo punto de interes.\");\n console.log(vm.nuevoPtoInteres);\n }", "function sacarUsuarios(json){\n \n for(let usuario of json){ \n var id = usuario.id;\n var email = usuario.email;\n var pass = usuario.password;\n\n var objetoUsers = new constructorUsers(id,email,pass);\n datosUser.push(objetoUsers);\n\n contadorId=usuario.id; //sacar el ultimo valor de ID que esta en el JSON\n }\n return datosUser; \n}", "function Usuario_registro (dni, nombre, apellidos, num_afiliacion, email, direccion) {\n \n var obj = {\n dni: dni,\n nombre: nombre,\n apellidos: apellidos,\n num_afiliacion: num_afiliacion,\n email: email,\n direccion: direccion\n };\n\n return obj; \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 agregar(usuario) {\n let data = {\n 'thing': usuario\n };\n\n fetch(`${baseUrl}/${groupID}/${collectionID}`, {\n 'method': 'POST',\n 'headers': {\n 'content-type': 'application/json'\n },\n 'body': JSON.stringify(data)\n }).then(res => {\n return res.json();\n }).then(dato => {\n precargarUsers();\n }).catch((error) => {\n console.log(error);\n })\n\n document.querySelector(\"#userName\").value = \"\";\n document.querySelector(\"#resetsUser\").value = \"\";\n document.querySelector(\"#viplevelUser\").value = \"\";\n document.querySelector(\"#levelUser\").value = \"\";\n }", "getPersonas() {\n return this.personas;\n }", "getPersonas() {\n return this.personas;\n }", "getPersonas() {\n return this.personas;\n }" ]
[ "0.62847126", "0.6095938", "0.60652065", "0.5992714", "0.5962982", "0.59618694", "0.5952589", "0.59513587", "0.58936346", "0.58826435", "0.5844063", "0.58405733", "0.57527953", "0.57335365", "0.57237", "0.5664147", "0.56596655", "0.5629717", "0.561217", "0.56054175", "0.5603901", "0.5596791", "0.559388", "0.55899465", "0.5573642", "0.55713296", "0.55687517", "0.55636036", "0.5562486", "0.5556248", "0.55542153", "0.5539981", "0.5530389", "0.55206734", "0.55202824", "0.55167675", "0.5512352", "0.5499732", "0.5488315", "0.5484484", "0.54844344", "0.54802006", "0.5478266", "0.5477217", "0.5477189", "0.5468237", "0.5468031", "0.54659486", "0.54591656", "0.5440362", "0.54395264", "0.54335856", "0.54311264", "0.54287976", "0.54235315", "0.5418984", "0.5417384", "0.541628", "0.54113054", "0.54093826", "0.54083884", "0.54033285", "0.54014146", "0.53951305", "0.5395037", "0.5393977", "0.5390964", "0.5390451", "0.5374308", "0.5371131", "0.5369695", "0.53693795", "0.53670865", "0.5366355", "0.53596437", "0.5355874", "0.5349533", "0.5343556", "0.534244", "0.5336847", "0.5336847", "0.5334188", "0.53256094", "0.5323536", "0.53224534", "0.5321645", "0.53187495", "0.5316414", "0.5308329", "0.5306924", "0.53021497", "0.5298806", "0.52969295", "0.5294331", "0.5291865", "0.52917105", "0.52908105", "0.52905655", "0.5279702", "0.5279702", "0.5279702" ]
0.0
-1
modification des infos personnelles des utilisateurs
function updateUserData(){ var new_name = document.getElementById('name_change').value; if (new_name == ""){ new_name = name; } var new_jobs = document.getElementById('jobs_change').value; if (new_jobs == ""){ new_jobs = jobs; } var new_contact = document.getElementById('contact_change').value; if (new_contact == ""){ new_contact = contact; } var new_tjm = document.getElementById('tjm_change').value; if (new_tjm == ""){ new_tjm = tjm; } writeUserData(userId, new_name, new_jobs, new_contact, new_tjm); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function editInfo() {\n io.emit('usernames', userNameList);\n socket.emit('updateUser', currentUsers[socket.id]);\n }", "function User_Update_Journaux_Liste_des_journaux0(Compo_Maitre)\n{\n var Table=\"journal\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tj_numero=GetValAt(52);\n if (tj_numero==\"-1\")\n tj_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"tj_numero\",TAB_GLOBAL_COMPO[52],tj_numero,true))\n \treturn -1;\n var jo_abbrev=GetValAt(53);\n if (!ValiderChampsObligatoire(Table,\"jo_abbrev\",TAB_GLOBAL_COMPO[53],jo_abbrev,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_abbrev\",TAB_GLOBAL_COMPO[53],jo_abbrev))\n \treturn -1;\n var jo_libelle=GetValAt(54);\n if (!ValiderChampsObligatoire(Table,\"jo_libelle\",TAB_GLOBAL_COMPO[54],jo_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_libelle\",TAB_GLOBAL_COMPO[54],jo_libelle))\n \treturn -1;\n var jo_provisoire=GetValAt(55);\n if (!ValiderChampsObligatoire(Table,\"jo_provisoire\",TAB_GLOBAL_COMPO[55],jo_provisoire,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_provisoire\",TAB_GLOBAL_COMPO[55],jo_provisoire))\n \treturn -1;\n var jo_visible=GetValAt(56);\n if (!ValiderChampsObligatoire(Table,\"jo_visible\",TAB_GLOBAL_COMPO[56],jo_visible,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_visible\",TAB_GLOBAL_COMPO[56],jo_visible))\n \treturn -1;\n var jo_contrepartie=GetValAt(57);\n if (!ValiderChampsObligatoire(Table,\"jo_contrepartie\",TAB_GLOBAL_COMPO[57],jo_contrepartie,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_contrepartie\",TAB_GLOBAL_COMPO[57],jo_contrepartie))\n \treturn -1;\n var cg_numero=GetValAt(58);\n if (cg_numero==\"-1\")\n cg_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cg_numero\",TAB_GLOBAL_COMPO[58],cg_numero,true))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tj_numero=\"+tj_numero+\",jo_abbrev=\"+(jo_abbrev==\"\" ? \"null\" : \"'\"+ValiderChaine(jo_abbrev)+\"'\" )+\",jo_libelle=\"+(jo_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(jo_libelle)+\"'\" )+\",jo_provisoire=\"+(jo_provisoire==\"true\" ? \"true\" : \"false\")+\",jo_visible=\"+(jo_visible==\"true\" ? \"true\" : \"false\")+\",jo_contrepartie=\"+(jo_contrepartie==\"true\" ? \"true\" : \"false\")+\",cg_numero=\"+cg_numero+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Types_de_lien_Liste_des_types_de_lien_entre_personne0(Compo_Maitre)\n{\n var Table=\"typelien\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tl_libelle=GetValAt(45);\n if (!ValiderChampsObligatoire(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle))\n \treturn -1;\n var tl_description=GetValAt(46);\n if (!ValiderChampsObligatoire(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tl_libelle=\"+(tl_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_libelle)+\"'\" )+\",tl_description=\"+(tl_description==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_description)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function changeInfoBody() {\n\tcreateProfilMenu();\n\tcreateH2('physique');\n\tcreateProfilFrom();\n\tcreateForm('js-form', '');\n\t// createLabel('.js-form-body', 'poid_u', 'Votre poid');\n\tcreateInput('.js-form', 'text', 'poid_u', 'Poids', '');\n\t// createLabel('.js-form-body', 'taille', 'Votre taille');\n\tcreateInput('.js-form', 'text', 'taille', 'Taille', '');\n\tcreateButtonSubmit('submit-body', '.js-form');\n}", "function setExtraInfo(){}", "function User_Update_Types_d_attribut_Liste_des_types_d_attribut_de_personne0(Compo_Maitre)\n{\n var Table=\"typeattribut\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ta_nom=GetValAt(30);\n if (!ValiderChampsObligatoire(Table,\"ta_nom\",TAB_GLOBAL_COMPO[30],ta_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ta_nom\",TAB_GLOBAL_COMPO[30],ta_nom))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ta_nom=\"+(ta_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(ta_nom)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function updateInfo(infos){\n document.getElementById(\"image_du_chat\").src = infos.profile_img ;\n document.getElementById(\"nom_du_chat\").textContent = infos.name ;\n document.getElementById(\"age_du_chat\").textContent = infos.age ;\n document.getElementById(\"description_du_chat\").textContent = infos.description ;\n}", "get informations() {\n return this.pseudo + ' (' + this.classe + ') a ' + this.sante + ' points de vie et est au niveau ' + this.niveau + '.'\n }", "function changeLInfo(event) {\n // \n event.preventDefault();\n \n // If the addLeistung panel is visible, hide it and show updateLeistung panel\n if($('#addLPanel').is(\":visible\")){\n togglePanels();\n }\n \n // Get Index of object based on _id value\n var _id = $(this).attr('rel');\n var arrayPosition = listData.map(function(arrayItem) { return arrayItem._id; }).indexOf(_id);\n \n // Get our Leistung Object\n var thisLObject = listData[arrayPosition];\n\n // Populate Info Box\n $('#updateBezeichnung').val(thisLObject.bezeichnung);\n $('#updatePreis').val(thisLObject.preis);\n $('#updateVon').val(thisLObject.von);\n $('#updateFuer').val(thisLObject.fuer);\n\n // Put the LeistungID into the REL of the 'update Leistung' block\n $('#updateL').attr('rel',thisLObject._id);\n}", "function User_Update_Ecritures_Liste_des_écritures_comptables0(Compo_Maitre)\n{\n var Table=\"ecriture\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ec_libelle=GetValAt(93);\n if (!ValiderChampsObligatoire(Table,\"ec_libelle\",TAB_GLOBAL_COMPO[93],ec_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ec_libelle\",TAB_GLOBAL_COMPO[93],ec_libelle))\n \treturn -1;\n var ec_compte=GetValAt(94);\n if (!ValiderChampsObligatoire(Table,\"ec_compte\",TAB_GLOBAL_COMPO[94],ec_compte,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ec_compte\",TAB_GLOBAL_COMPO[94],ec_compte))\n \treturn -1;\n var ec_debit=GetValAt(95);\n if (!ValiderChampsObligatoire(Table,\"ec_debit\",TAB_GLOBAL_COMPO[95],ec_debit,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ec_debit\",TAB_GLOBAL_COMPO[95],ec_debit))\n \treturn -1;\n var ec_credit=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"ec_credit\",TAB_GLOBAL_COMPO[96],ec_credit,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ec_credit\",TAB_GLOBAL_COMPO[96],ec_credit))\n \treturn -1;\n var pt_numero=GetValAt(97);\n if (pt_numero==\"-1\")\n pt_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"pt_numero\",TAB_GLOBAL_COMPO[97],pt_numero,true))\n \treturn -1;\n var lt_numero=GetValAt(98);\n if (lt_numero==\"-1\")\n lt_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"lt_numero\",TAB_GLOBAL_COMPO[98],lt_numero,true))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ec_libelle=\"+(ec_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ec_libelle)+\"'\" )+\",ec_compte=\"+(ec_compte==\"\" ? \"null\" : \"'\"+ValiderChaine(ec_compte)+\"'\" )+\",ec_debit=\"+(ec_debit==\"\" ? \"null\" : \"'\"+ValiderChaine(ec_debit)+\"'\" )+\",ec_credit=\"+(ec_credit==\"\" ? \"null\" : \"'\"+ValiderChaine(ec_credit)+\"'\" )+\",pt_numero=\"+pt_numero+\",lt_numero=\"+lt_numero+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function information(e) {\n let ancestro = Ancestro(e.target, 0);\n var id = ancestro.id;\n id = id.slice(0, -3);\n\n window.location = `../../html/administrador/AlumnoEditar.html?usu_id=${params.get('usu_id')}&alu_id=${id}`;\n}", "function User_Update_Etats_de_personne_Liste_des_états_de_personne0(Compo_Maitre)\n{\n var Table=\"etatpersonne\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ep_libelle=GetValAt(52);\n if (!ValiderChampsObligatoire(Table,\"ep_libelle\",TAB_GLOBAL_COMPO[52],ep_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ep_libelle\",TAB_GLOBAL_COMPO[52],ep_libelle))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ep_libelle=\"+(ep_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ep_libelle)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Villes_Liste_des_villes0(Compo_Maitre)\n{\n var Table=\"ville\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var vi_nom=GetValAt(126);\n if (!ValiderChampsObligatoire(Table,\"vi_nom\",TAB_GLOBAL_COMPO[126],vi_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"vi_nom\",TAB_GLOBAL_COMPO[126],vi_nom))\n \treturn -1;\n var ct_numero=GetValAt(127);\n if (ct_numero==\"-1\")\n ct_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"ct_numero\",TAB_GLOBAL_COMPO[127],ct_numero,true))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"vi_nom=\"+(vi_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(vi_nom)+\"'\" )+\",ct_numero=\"+ct_numero+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Impressions_Liste_des_modèles_d_impressions0(Compo_Maitre)\n{\n var Table=\"table_impression\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var im_societe=GetValAt(229);\n if (im_societe==\"-1\")\n im_societe=\"null\";\n if (!ValiderChampsObligatoire(Table,\"im_societe\",TAB_GLOBAL_COMPO[229],im_societe,true))\n \treturn -1;\n var im_libelle=GetValAt(230);\n if (!ValiderChampsObligatoire(Table,\"im_libelle\",TAB_GLOBAL_COMPO[230],im_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_libelle\",TAB_GLOBAL_COMPO[230],im_libelle))\n \treturn -1;\n var im_nom=GetValAt(231);\n if (!ValiderChampsObligatoire(Table,\"im_nom\",TAB_GLOBAL_COMPO[231],im_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_nom\",TAB_GLOBAL_COMPO[231],im_nom))\n \treturn -1;\n var im_modele=GetValAt(232);\n if (!ValiderChampsObligatoire(Table,\"im_modele\",TAB_GLOBAL_COMPO[232],im_modele,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_modele\",TAB_GLOBAL_COMPO[232],im_modele))\n \treturn -1;\n var im_defaut=GetValAt(233);\n if (!ValiderChampsObligatoire(Table,\"im_defaut\",TAB_GLOBAL_COMPO[233],im_defaut,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_defaut\",TAB_GLOBAL_COMPO[233],im_defaut))\n \treturn -1;\n var im_keytable=GetValAt(234);\n if (!ValiderChampsObligatoire(Table,\"im_keytable\",TAB_GLOBAL_COMPO[234],im_keytable,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keytable\",TAB_GLOBAL_COMPO[234],im_keytable))\n \treturn -1;\n var im_keycle=GetValAt(235);\n if (!ValiderChampsObligatoire(Table,\"im_keycle\",TAB_GLOBAL_COMPO[235],im_keycle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keycle\",TAB_GLOBAL_COMPO[235],im_keycle))\n \treturn -1;\n var im_keydate=GetValAt(236);\n if (!ValiderChampsObligatoire(Table,\"im_keydate\",TAB_GLOBAL_COMPO[236],im_keydate,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keydate\",TAB_GLOBAL_COMPO[236],im_keydate))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"im_societe=\"+im_societe+\",im_libelle=\"+(im_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(im_libelle)+\"'\" )+\",im_nom=\"+(im_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(im_nom)+\"'\" )+\",im_modele=\"+(im_modele==\"\" ? \"null\" : \"'\"+ValiderChaine(im_modele)+\"'\" )+\",im_defaut=\"+(im_defaut==\"true\" ? \"true\" : \"false\")+\",im_keytable=\"+(im_keytable==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keytable)+\"'\" )+\",im_keycle=\"+(im_keycle==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keycle)+\"'\" )+\",im_keydate=\"+(im_keydate==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keydate)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function accionModificar() {\n\tvar opcionMenu = get(\"formulario.opcionMenu\");\n\tvar oidPlantilla = null;\n\tvar numPlantilla = null;\n\tvar oidParamGrales = null;\n\tvar filaMarcada = null;\n\tvar codSeleccionados = null;\n\tvar datos = null;\t\n\n\tlistado1.actualizaDat();\n\tdatos = listado1.datos;\n\tcodSeleccionados = listado1.codSeleccionados();\n\n\tif (codSeleccionados.length > 1) {\n GestionarMensaje('8');\n\t\treturn;\n\t}\n\n\tif ( codSeleccionados.length < 1)\t{\n GestionarMensaje('4');\n\t\treturn;\n\t}\n\n\t// Obtengo el índice de la fila marcada (en este punto, solo una estará marcada)\n\tvar filaMarcada = listado1.filaSelecc;\n\n\t// Obtengo el oid de Param. Generales (oid del valor seleccionado, está al final de la lista por el tema del ROWNUM)\n\toidParamGrales = datos[filaMarcada][9]; \n\n\t// Obtengo Oid de la Entidad PlantillaConcurso (AKA Numero de Plantilla);\n\tnumPlantilla = datos[filaMarcada][3];\n\n\tvar oidVigenciaConcurso = datos[filaMarcada][10]; \n\tvar oidEstadoConcurso = datos[filaMarcada][11]; \n\tvar noVigencia = get(\"formulario.noVigencia\");\n\tvar estConcuAprobado = get(\"formulario.estConcuAprobado\");\n\n\tif((parseInt(oidVigenciaConcurso) == parseInt(noVigencia)) && \t\t\n\t(parseInt(oidEstadoConcurso)!=parseInt(estConcuAprobado))) {\n\t\tvar obj = new Object();\n\t\t// Seteo los valores obtenidos. \n\t\tobj.oidConcurso = oidParamGrales;\n\t\tobj.oidPlantilla = numPlantilla;\n\t\tobj.opcionMenu = opcionMenu;\n\t\tvar retorno = mostrarModalSICC('LPMantenerParametrosGenerales', '', obj);\n\t\taccionBuscar();\n\t}\n\telse {\n\t\tvar indDespacho = datos[filaMarcada][12];\n\t\tif (oidVigenciaConcurso == '1' && parseInt(indDespacho) == 0) {\n\t\t\tif (GestionarMensaje('3385')) {\n\t\t\t\tvar obj = new Object();\n\t\t\t\t// Seteo los valores obtenidos. \n\t\t\t\tobj.oidConcurso = oidParamGrales;\n\t\t\t\tobj.oidPlantilla = numPlantilla;\n\t\t\t\tobj.opcionMenu = opcionMenu;\n\t\t\t\tobj.oidVigenciaConcurso = oidVigenciaConcurso;\n\t\t\t\tvar retorno = mostrarModalSICC('LPMantenerParametrosGenerales', '', obj);\n\t\t\t\taccionBuscar();\n\t\t\t}\t\n\t\t}\n\t\telse {\n\t\t\t//El concurso seleccionado no puede ser modificado\n\t\t\tGestionarMensaje('INC052');\n\t\t}\n\t}\n}", "function User_Update_Types_d_attribut_Catégories_2(Compo_Maitre)\n{\n var Table=\"categorie\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cr_libelle=GetValAt(33);\n if (!ValiderChampsObligatoire(Table,\"cr_libelle\",TAB_GLOBAL_COMPO[33],cr_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cr_libelle\",TAB_GLOBAL_COMPO[33],cr_libelle))\n \treturn -1;\n var cr_description=GetValAt(34);\n if (!ValiderChampsObligatoire(Table,\"cr_description\",TAB_GLOBAL_COMPO[34],cr_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cr_description\",TAB_GLOBAL_COMPO[34],cr_description))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"cr_libelle=\"+(cr_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(cr_libelle)+\"'\" )+\",cr_description=\"+(cr_description==\"\" ? \"null\" : \"'\"+ValiderChaine(cr_description)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "onClickInfo() {\n if(!User.current.isAdmin) { return; }\n \n let infoEditor = new InfoEditor({ projectId: this.model.id });\n\n infoEditor.on('change', (newInfo) => {\n this.model.settings.info = newInfo;\n\n this.fetch();\n });\n }", "function User_Update_Agents_Liste_des_agents0(Compo_Maitre)\n{\n var Table=\"agent\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ag_nom=GetValAt(110);\n if (!ValiderChampsObligatoire(Table,\"ag_nom\",TAB_GLOBAL_COMPO[110],ag_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_nom\",TAB_GLOBAL_COMPO[110],ag_nom))\n \treturn -1;\n var ag_prenom=GetValAt(111);\n if (!ValiderChampsObligatoire(Table,\"ag_prenom\",TAB_GLOBAL_COMPO[111],ag_prenom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_prenom\",TAB_GLOBAL_COMPO[111],ag_prenom))\n \treturn -1;\n var ag_initiales=GetValAt(112);\n if (!ValiderChampsObligatoire(Table,\"ag_initiales\",TAB_GLOBAL_COMPO[112],ag_initiales,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_initiales\",TAB_GLOBAL_COMPO[112],ag_initiales))\n \treturn -1;\n var ag_actif=GetValAt(113);\n if (!ValiderChampsObligatoire(Table,\"ag_actif\",TAB_GLOBAL_COMPO[113],ag_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_actif\",TAB_GLOBAL_COMPO[113],ag_actif))\n \treturn -1;\n var ag_role=GetValAt(114);\n if (!ValiderChampsObligatoire(Table,\"ag_role\",TAB_GLOBAL_COMPO[114],ag_role,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_role\",TAB_GLOBAL_COMPO[114],ag_role))\n \treturn -1;\n var eq_numero=GetValAt(115);\n if (eq_numero==\"-1\")\n eq_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"eq_numero\",TAB_GLOBAL_COMPO[115],eq_numero,true))\n \treturn -1;\n var ag_telephone=GetValAt(116);\n if (!ValiderChampsObligatoire(Table,\"ag_telephone\",TAB_GLOBAL_COMPO[116],ag_telephone,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_telephone\",TAB_GLOBAL_COMPO[116],ag_telephone))\n \treturn -1;\n var ag_mobile=GetValAt(117);\n if (!ValiderChampsObligatoire(Table,\"ag_mobile\",TAB_GLOBAL_COMPO[117],ag_mobile,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_mobile\",TAB_GLOBAL_COMPO[117],ag_mobile))\n \treturn -1;\n var ag_email=GetValAt(118);\n if (!ValiderChampsObligatoire(Table,\"ag_email\",TAB_GLOBAL_COMPO[118],ag_email,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_email\",TAB_GLOBAL_COMPO[118],ag_email))\n \treturn -1;\n var ag_commentaire=GetValAt(119);\n if (!ValiderChampsObligatoire(Table,\"ag_commentaire\",TAB_GLOBAL_COMPO[119],ag_commentaire,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ag_commentaire\",TAB_GLOBAL_COMPO[119],ag_commentaire))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ag_nom=\"+(ag_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_nom)+\"'\" )+\",ag_prenom=\"+(ag_prenom==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_prenom)+\"'\" )+\",ag_initiales=\"+(ag_initiales==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_initiales)+\"'\" )+\",ag_actif=\"+(ag_actif==\"true\" ? \"true\" : \"false\")+\",ag_role=\"+(ag_role==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_role)+\"'\" )+\",eq_numero=\"+eq_numero+\",ag_telephone=\"+(ag_telephone==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_telephone)+\"'\" )+\",ag_mobile=\"+(ag_mobile==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_mobile)+\"'\" )+\",ag_email=\"+(ag_email==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_email)+\"'\" )+\",ag_commentaire=\"+(ag_commentaire==\"\" ? \"null\" : \"'\"+ValiderChaine(ag_commentaire)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function handleInfo() {\n\t\t// setJob({\n\t\t// \tjob: 'Front-end developer',\n\t\t// \tlang: 'JS',\n\t\t// });\n\n\t\tsetPerson({\n\t\t\tname: 'Sina',\n\t\t\temail: '[email protected]',\n\t\t});\n\t}", "function giftDetails(newGift){\r\n\r\n\t\thideEdit();\r\n\t\tshowEdit();\r\n\r\n\t\t//create circle with icon if it is given for this misison\r\n\t\t$('.edit ul.mission-neutral').append($('<li class=\"circle-big\">' + (newGift.icon ? '<img src='+ newGift.icon +'>' : \"\") + '</li>'))\r\n\r\n\t\t//creates empty form \r\n\t\t$('.edit').append(createEmptyForm());\r\n\r\n\t\t//if name is given show in the form\r\n\t\t$('input[name=\"newGiftName\"]').val(newGift.name ? newGift.name : \"\")\r\n\r\n\t\t//if points are given (which means it is user mission) show in the form \r\n\t\tif (newGift.hasOwnProperty('points')){\r\n\t\t\t$('input[name=\"newGiftPoints\"]').val(newGift.points)\r\n\t\t\t//for user mission save missionId\r\n\t\t\t$('.edit li.circle-big').attr('name',newGift.id)\r\n\r\n\t\t\t//for user mission show SAVE button\r\n\t\t\t$('.edit').append($('<button class=\"save\">ZAPISZ ZMIANY</button>'))\r\n\t\t\t// and FINISH / DELETE button\r\n\t\t\t$('.edit').append($('<button class=\"left infoDelete\">USUŃ</button>'))\r\n\t\t} else {\r\n\t\t\t//for NOT user missions show ADD button\r\n\t\t\t$('.edit').append($('<button class=\"add\">DODAJ</button>'))\r\n\t\t}\r\n }", "function User_Update_Profils_de_droits_Droits_2(Compo_Maitre)\n{\n var Table=\"droit\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var gt_numero=GetValAt(94);\n if (gt_numero==\"-1\")\n gt_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"gt_numero\",TAB_GLOBAL_COMPO[94],gt_numero,true))\n \treturn -1;\n var dr_select=GetValAt(95);\n if (!ValiderChampsObligatoire(Table,\"dr_select\",TAB_GLOBAL_COMPO[95],dr_select,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_select\",TAB_GLOBAL_COMPO[95],dr_select))\n \treturn -1;\n var dr_insert=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"dr_insert\",TAB_GLOBAL_COMPO[96],dr_insert,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_insert\",TAB_GLOBAL_COMPO[96],dr_insert))\n \treturn -1;\n var dr_update=GetValAt(97);\n if (!ValiderChampsObligatoire(Table,\"dr_update\",TAB_GLOBAL_COMPO[97],dr_update,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_update\",TAB_GLOBAL_COMPO[97],dr_update))\n \treturn -1;\n var dr_delete=GetValAt(98);\n if (!ValiderChampsObligatoire(Table,\"dr_delete\",TAB_GLOBAL_COMPO[98],dr_delete,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_delete\",TAB_GLOBAL_COMPO[98],dr_delete))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"gt_numero=\"+gt_numero+\",dr_select=\"+(dr_select==\"true\" ? \"true\" : \"false\")+\",dr_insert=\"+(dr_insert==\"true\" ? \"true\" : \"false\")+\",dr_update=\"+(dr_update==\"true\" ? \"true\" : \"false\")+\",dr_delete=\"+(dr_delete==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Cantons_Liste_des_cantons0(Compo_Maitre)\n{\n var Table=\"canton\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ct_nom=GetValAt(140);\n if (!ValiderChampsObligatoire(Table,\"ct_nom\",TAB_GLOBAL_COMPO[140],ct_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ct_nom\",TAB_GLOBAL_COMPO[140],ct_nom))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ct_nom=\"+(ct_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(ct_nom)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function upgradeInfoSec(obj){\n var newRows = obj.newRows;\n var angScope = angular.element(document.getElementById(\"infoTab\")).scope();\n angScope.removeLastRow();\n for (var i = 0; i < newRows.length; i++) {\n angScope.addRow(newRows[i].row,newRows[i].type);\n }\n }", "function updateInfoSecMenu(obj){\n clickMenuInfo1(obj.objInfoView.base);\n clickMenuInfo2(obj.objInfoView.category);\n mainData.infoSections[currentPanel][objInfoView.base][objInfoView.category] = obj.objBaseInfo;\n }", "function User_Update_Produits_Prix_5(Compo_Maitre)\n{\n var Table=\"prix\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var px_tarifht=GetValAt(170);\n if (!ValiderChampsObligatoire(Table,\"px_tarifht\",TAB_GLOBAL_COMPO[170],px_tarifht,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_tarifht\",TAB_GLOBAL_COMPO[170],px_tarifht))\n \treturn -1;\n var px_tarifttc=GetValAt(171);\n if (!ValiderChampsObligatoire(Table,\"px_tarifttc\",TAB_GLOBAL_COMPO[171],px_tarifttc,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_tarifttc\",TAB_GLOBAL_COMPO[171],px_tarifttc))\n \treturn -1;\n var tv_numero=GetValAt(172);\n if (tv_numero==\"-1\")\n tv_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"tv_numero\",TAB_GLOBAL_COMPO[172],tv_numero,true))\n \treturn -1;\n var px_datedebut=GetValAt(173);\n if (!ValiderChampsObligatoire(Table,\"px_datedebut\",TAB_GLOBAL_COMPO[173],px_datedebut,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_datedebut\",TAB_GLOBAL_COMPO[173],px_datedebut))\n \treturn -1;\n var px_actif=GetValAt(174);\n if (!ValiderChampsObligatoire(Table,\"px_actif\",TAB_GLOBAL_COMPO[174],px_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_actif\",TAB_GLOBAL_COMPO[174],px_actif))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"px_tarifht=\"+(px_tarifht==\"\" ? \"null\" : \"'\"+ValiderChaine(px_tarifht)+\"'\" )+\",px_tarifttc=\"+(px_tarifttc==\"\" ? \"null\" : \"'\"+ValiderChaine(px_tarifttc)+\"'\" )+\",tv_numero=\"+tv_numero+\",px_datedebut=\"+(px_datedebut==\"\" ? \"null\" : \"'\"+ValiderChaine(px_datedebut)+\"'\" )+\",px_actif=\"+(px_actif==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Comptes_auxiliaires_Liste_des_comptes_auxiliaires0(Compo_Maitre)\n{\n var Table=\"compteaux\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ca_numcompte=GetValAt(128);\n if (!ValiderChampsObligatoire(Table,\"ca_numcompte\",TAB_GLOBAL_COMPO[128],ca_numcompte,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ca_numcompte\",TAB_GLOBAL_COMPO[128],ca_numcompte))\n \treturn -1;\n var ca_libelle=GetValAt(129);\n if (!ValiderChampsObligatoire(Table,\"ca_libelle\",TAB_GLOBAL_COMPO[129],ca_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ca_libelle\",TAB_GLOBAL_COMPO[129],ca_libelle))\n \treturn -1;\n var ac_numero=GetValAt(130);\n if (ac_numero==\"-1\")\n ac_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"ac_numero\",TAB_GLOBAL_COMPO[130],ac_numero,true))\n \treturn -1;\n var ca_debit=GetValAt(131);\n if (!ValiderChampsObligatoire(Table,\"ca_debit\",TAB_GLOBAL_COMPO[131],ca_debit,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ca_debit\",TAB_GLOBAL_COMPO[131],ca_debit))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ca_numcompte=\"+(ca_numcompte==\"\" ? \"null\" : \"'\"+ValiderChaine(ca_numcompte)+\"'\" )+\",ca_libelle=\"+(ca_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ca_libelle)+\"'\" )+\",ac_numero=\"+ac_numero+\",ca_debit=\"+(ca_debit==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Produits_Liste_des_produits0(Compo_Maitre)\n{\n var Table=\"produit\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var pd_libelle=GetValAt(161);\n if (!ValiderChampsObligatoire(Table,\"pd_libelle\",TAB_GLOBAL_COMPO[161],pd_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_libelle\",TAB_GLOBAL_COMPO[161],pd_libelle))\n \treturn -1;\n var jo_numero=GetValAt(162);\n if (jo_numero==\"-1\")\n jo_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"jo_numero\",TAB_GLOBAL_COMPO[162],jo_numero,true))\n \treturn -1;\n var pd_actif=GetValAt(163);\n if (!ValiderChampsObligatoire(Table,\"pd_actif\",TAB_GLOBAL_COMPO[163],pd_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_actif\",TAB_GLOBAL_COMPO[163],pd_actif))\n \treturn -1;\n var pd_reduction=GetValAt(164);\n if (!ValiderChampsObligatoire(Table,\"pd_reduction\",TAB_GLOBAL_COMPO[164],pd_reduction,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_reduction\",TAB_GLOBAL_COMPO[164],pd_reduction))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"pd_libelle=\"+(pd_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(pd_libelle)+\"'\" )+\",jo_numero=\"+jo_numero+\",pd_actif=\"+(pd_actif==\"true\" ? \"true\" : \"false\")+\",pd_reduction=\"+(pd_reduction==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Types_de_personne_Liste_des_types_de_personne0(Compo_Maitre)\n{\n var Table=\"typepersonne\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tp_type=GetValAt(49);\n if (!ValiderChampsObligatoire(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tp_type=\"+(tp_type==\"\" ? \"null\" : \"'\"+ValiderChaine(tp_type)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function User_Update_Profils_de_droits_Liste_des_profils_de_droits0(Compo_Maitre)\n{\n var Table=\"droitprofil\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var dp_libelle=GetValAt(90);\n if (!ValiderChampsObligatoire(Table,\"dp_libelle\",TAB_GLOBAL_COMPO[90],dp_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dp_libelle\",TAB_GLOBAL_COMPO[90],dp_libelle))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"dp_libelle=\"+(dp_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(dp_libelle)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "displayInfo() {\n\t\t\tlet info = super.displayInfo() + ', разработчики: ' + this.getDevelopers() ;\n\t\t\tconsole.log( info );\n\t\t\treturn info\n\t\t\t}", "function User_Update_Services_Liste_des_services0(Compo_Maitre)\n{\n var Table=\"service\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var se_nom=GetValAt(71);\n if (!ValiderChampsObligatoire(Table,\"se_nom\",TAB_GLOBAL_COMPO[71],se_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"se_nom\",TAB_GLOBAL_COMPO[71],se_nom))\n \treturn -1;\n var se_agent=GetValAt(72);\n if (se_agent==\"-1\")\n se_agent=\"null\";\n if (!ValiderChampsObligatoire(Table,\"se_agent\",TAB_GLOBAL_COMPO[72],se_agent,true))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"se_nom=\"+(se_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(se_nom)+\"'\" )+\",se_agent=\"+se_agent+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function setpliInfo(id)\n{\n\tvar pro = gerProObj();\n\tvar index=parseInt(_(\"ProfileIndex\").value);\n\tvar cp=pro[index];\n\tvar lb=getChildNodes(cp,\"label\");\n\thtml(lb[0],html(lb[0])+',\"profileID\":\"'+id+'\",\"prior\":\"1\"');\n\tbug(\"lable\",html(lb[0]));\n\t\n}", "function remplirDtDictInformationBase()\n{\n var form = $('form[name=mairievoreppe_demandetravauxbundle_dtdict]');\n var inputs = form.find('#partie-dt .information-base input, #partie-dt .information-base textarea');\n var selects = form.find('#partie-dt .information-base select[recuperer-info=recuperer-info], #partie-dt .information-base div[recuperer-info=recuperer-info] select');\n \n inputs.each(function () {\n if($(this).val() !== '')\n {\n var valeur = $(this).val();\n var idSource = $(this).attr('id');\n var idCible = idSource.replace(/_dt_/, \"_\");\n $('#' + idCible).val(valeur);\n \n }\n });\n \n //Je ne parcours pas les selects volontairement: seul ceux ayant 'recuperer-info=recuperer-info' seront pris en compte. En effet, le maitre d'oeuvre et d'ouvrage\n // étant différent, c'est à l'utilisateur de les définirs dans chacun des cas\n selects.each(function () {\n var valueOptionSelected = $(this).find(':selected').val();\n var idSource = $(this).attr('id');\n console.log(\"idSource\" + idSource);\n var idCible = idSource.replace(/_dt_/, \"_\");\n $('#' + idCible).val(valueOptionSelected); \n \n });\n \n \n}", "function User_Update_Exercice_Liste_des_exercices_comptables0(Compo_Maitre)\n{\n var Table=\"exercice\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ex_datedebut=GetValAt(35);\n if (!ValiderChampsObligatoire(Table,\"ex_datedebut\",TAB_GLOBAL_COMPO[35],ex_datedebut,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ex_datedebut\",TAB_GLOBAL_COMPO[35],ex_datedebut))\n \treturn -1;\n var ex_datefin=GetValAt(36);\n if (!ValiderChampsObligatoire(Table,\"ex_datefin\",TAB_GLOBAL_COMPO[36],ex_datefin,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ex_datefin\",TAB_GLOBAL_COMPO[36],ex_datefin))\n \treturn -1;\n var ex_cloture=GetValAt(37);\n if (!ValiderChampsObligatoire(Table,\"ex_cloture\",TAB_GLOBAL_COMPO[37],ex_cloture,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ex_cloture\",TAB_GLOBAL_COMPO[37],ex_cloture))\n \treturn -1;\n var ex_compteattente=GetValAt(38);\n if (!ValiderChampsObligatoire(Table,\"ex_compteattente\",TAB_GLOBAL_COMPO[38],ex_compteattente,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ex_compteattente\",TAB_GLOBAL_COMPO[38],ex_compteattente))\n \treturn -1;\n var ex_actif=GetValAt(39);\n if (!ValiderChampsObligatoire(Table,\"ex_actif\",TAB_GLOBAL_COMPO[39],ex_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ex_actif\",TAB_GLOBAL_COMPO[39],ex_actif))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"ex_datedebut=\"+(ex_datedebut==\"\" ? \"null\" : \"'\"+ValiderChaine(ex_datedebut)+\"'\" )+\",ex_datefin=\"+(ex_datefin==\"\" ? \"null\" : \"'\"+ValiderChaine(ex_datefin)+\"'\" )+\",ex_cloture=\"+(ex_cloture==\"true\" ? \"true\" : \"false\")+\",ex_compteattente=\"+(ex_compteattente==\"\" ? \"null\" : \"'\"+ValiderChaine(ex_compteattente)+\"'\" )+\",ex_actif=\"+(ex_actif==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "async editUserInfo({ commit }, params) {\n const username = params.name;\n const res = await api.editUser(username, params);\n if (res.status === 202) {\n commit(\"editComment\", \"유저 정보가 변경되었습니다.\");\n } else {\n if (res.data.error) {\n commit(\"editComment\", res.data.error);\n } else {\n commit(\"editComment\", \"정보 수정을 실패했습니다.\");\n }\n }\n }", "displayInfo() {\n\t\t\tlet info = super.displayInfo() + ', менеджер: ' + this.manager.name ;\n\t\t\tconsole.log( info );\n\t\t\treturn info\n\t\t\t}", "function _AtualizaModificadoresAtributos() {\n // busca a raca e seus modificadores.\n var modificadores_raca = tabelas_raca[gPersonagem.raca].atributos;\n\n // Busca cada elemento das estatisticas e atualiza modificadores.\n var atributos = [\n 'forca', 'destreza', 'constituicao', 'inteligencia', 'sabedoria', 'carisma' ];\n for (var i = 0; i < atributos.length; ++i) {\n var atributo = atributos[i];\n // Valor do bonus sem base.\n var dom_bonus = Dom(atributo + '-mod-bonus');\n ImprimeSinalizado(gPersonagem.atributos[atributo].bonus.Total(['base']), dom_bonus, false);\n Titulo(gPersonagem.atributos[atributo].bonus.Exporta(['base']), dom_bonus);\n\n // Escreve o valor total.\n var dom_valor = Dom(atributo + '-valor-total');\n ImprimeNaoSinalizado(gPersonagem.atributos[atributo].bonus.Total(), dom_valor);\n Titulo(gPersonagem.atributos[atributo].bonus.Exporta(), dom_valor);\n\n // Escreve o modificador.\n ImprimeSinalizado(\n gPersonagem.atributos[atributo].modificador,\n DomsPorClasse(atributo + '-mod-total'));\n }\n}", "function alterPageUpdateForConsult() {\n clearFields(true);\n setTitleUpdate(\"\");\n setUpdateRegister(false);\n setIsReadonly(true);\n setSearchPersonBtnInactive(false);\n }", "function updateEditPage () {\n\n var nameMap = table.makePermissionMap(true);\n\n // todo: refactor these doubled 4 lines of code.\n // todo: refactor this doubled line of comments.\n var viewSummaryDiv = $(\"#permissions-view-summary\");\n var viewNames = [].concat(nameMap.group.view).concat(nameMap.user.view);\n if (viewNames.length) viewSummaryDiv.find(\".summary-content\").text(viewNames.join(\", \"));\n AJS.setVisible(viewSummaryDiv, viewNames.length);\n\n var editSummaryDiv = $(\"#permissions-edit-summary\");\n var editNames = [].concat(nameMap.group.edit).concat(nameMap.user.edit);\n if (editNames.length) editSummaryDiv.find(\".summary-content\").text(editNames.join(\", \"));\n AJS.setVisible(editSummaryDiv, editNames.length);\n\n /**\n * Updates the hidden fields that submit the edited permissions in the form. The fields are updated with the\n * data in the Permissions table.\n */\n permissionManager.permissionsEdited = false;\n var permissionStrs = permissionManager.makePermissionStrings();\n for (var key in permissionStrs) {\n var updatedPermStr = permissionStrs[key];\n $(\"#\" + key).val(updatedPermStr);\n\n if (permissionManager.originalPermissions[key] != updatedPermStr) {\n permissionManager.permissionsEdited = true;\n }\n }\n }", "function updateEditPage () {\n\n var nameMap = table.makePermissionMap(true);\n\n // todo: refactor these doubled 4 lines of code.\n // todo: refactor this doubled line of comments.\n var viewSummaryDiv = $(\"#permissions-view-summary\");\n var viewNames = [].concat(nameMap.group.view).concat(nameMap.user.view);\n if (viewNames.length) viewSummaryDiv.find(\".summary-content\").text(viewNames.join(\", \"));\n AJS.setVisible(viewSummaryDiv, viewNames.length);\n\n var editSummaryDiv = $(\"#permissions-edit-summary\");\n var editNames = [].concat(nameMap.group.edit).concat(nameMap.user.edit);\n if (editNames.length) editSummaryDiv.find(\".summary-content\").text(editNames.join(\", \"));\n AJS.setVisible(editSummaryDiv, editNames.length);\n\n /**\n * Updates the hidden fields that submit the edited permissions in the form. The fields are updated with the\n * data in the Permissions table.\n */\n permissionManager.permissionsEdited = false;\n var permissionStrs = permissionManager.makePermissionStrings();\n for (var key in permissionStrs) {\n var updatedPermStr = permissionStrs[key];\n $(\"#\" + key).val(updatedPermStr);\n\n if (permissionManager.originalPermissions[key] != updatedPermStr) {\n permissionManager.permissionsEdited = true;\n }\n }\n }", "function User_Update_Types_de_journaux_Liste_des_types_de_journaux0(Compo_Maitre)\n{\n var Table=\"typejournal\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tj_libelle=GetValAt(201);\n if (!ValiderChampsObligatoire(Table,\"tj_libelle\",TAB_GLOBAL_COMPO[201],tj_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tj_libelle\",TAB_GLOBAL_COMPO[201],tj_libelle))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tj_libelle=\"+(tj_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tj_libelle)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function updateUserInfo(id, user) {\n}", "function showInfo() {\n $('#user-name').text(curUser.first_name + ' ' + curUser.last_name);\n $('#first-name').text(curUser.first_name);\n $('#last-name').text(curUser.last_name);\n $('#email').text(curUser.email);\n $('#phone').text(curUser.phone_number);\n }", "function User_Update_Groupes_de_cantons_Liste_des_groupes_de_cantons0(Compo_Maitre)\n{\n var Table=\"groupecanton\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var gc_nom=GetValAt(37);\n if (!ValiderChampsObligatoire(Table,\"gc_nom\",TAB_GLOBAL_COMPO[37],gc_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gc_nom\",TAB_GLOBAL_COMPO[37],gc_nom))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"gc_nom=\"+(gc_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(gc_nom)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\n\n/* table canton*/\nLstDouble_Exec_Req(GetSQLCompoAt(41),CleMaitre);\nreturn CleMaitre;\n\n}", "afficher(){\r\n \tconsole.log('nom '+this.nom);\r\n \tconsole.log('prenom '+this.prenom);\r\n \tconsole.log('mail '+this.mail);\r\n }", "function User_Update_Produits_Comptes_généraux_11(Compo_Maitre)\n{\n var Table=\"compteproduit\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cg_numero=GetValAt(178);\n if (cg_numero==\"-1\")\n cg_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cg_numero\",TAB_GLOBAL_COMPO[178],cg_numero,true))\n \treturn -1;\n var ci_actif=GetValAt(179);\n if (!ValiderChampsObligatoire(Table,\"ci_actif\",TAB_GLOBAL_COMPO[179],ci_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ci_actif\",TAB_GLOBAL_COMPO[179],ci_actif))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"cg_numero=\"+cg_numero+\",ci_actif=\"+(ci_actif==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "atualizaNome() //controler\r\n {\r\n this._elemento.textContent = `[${this._idade}] ${this._nome}`;\r\n }", "function accessEdited(info,type,siteID,userOID,siteName,userName) {\n\tif (info[\"status\"].indexOf('ERROR') >= 0) {\n\t\t$('#dialogMessage').html('<p>There was an issue editing access.<br />Please try again.</p>');\n\t\t$('#dialogButtons').show();\n\t} else {\n\t\tcancelDialog();\n\t\t// Reload search results to visually see change in access.\n\t\tif (type == 'site') {\n\t\t\tsearchSites(siteID, siteName);\n\t\t} else {\n\t\t\tsearchUsers(userOID, userName);\n\t\t}\n\t}\n}", "function Modification(){\n Id_special = $(this).parent().parent().attr(\"id\");\n $('#Ajout_tache').attr(\"onclick\",\"chang_modify()\");\n for(var cpt = 0 ; cpt < Table.length; cpt++) {\n if(Table[cpt].return_this_id() == Id_special){\n var elem = Table[cpt].return_All_entred_element();\n $(\"#Time_stemp\").val(elem[2]);\n $(\"#Titre_Tach\").val(elem[0]);\n $(\"option:selected\").val(elem[1]);\n\n }\n }\n }", "function populate_info_panel($this_usuario){\n // populate basic information panel\n \n var type;\n $('#info_panel_heading').text($this_usuario.first_name + \" \" + $this_usuario.last_name1 + \" \" + $this_usuario.last_name2);\n if($this_usuario.middle_initial == null) {\n $('#usuario_info_name').text($this_usuario.first_name);\n } else {\n $('#usuario_info_name').text($this_usuario.first_name + \" \" + $this_usuario.middle_initial);\n }\n $('#usuario_info_lastname_paternal').text($this_usuario.last_name1);\n $('#usuario_info_lastname_maternal').text($this_usuario.last_name2);\n //$('#usuario_info_contact').text($this_usuario.email + \" \" + $this_usuario.phone_number);\n $('#usuario_info_telefono').text($this_usuario.phone_number);\n $('#usuario_info_contact').text($this_usuario.email);\n //$('#usuario_telefono').text($this_usuario.phone_number);\n\n\n\n if($this_usuario.type == 'agent')\n {\n type = 'Agente';\n $('#assigned_locations').show();\n } \n else if ($this_usuario.type == 'specialist')\n {\n type = 'Especialista';\n $('#assigned_locations').hide();\n } \n else \n {\n type = 'Administrador';\n $('#assigned_locations').hide();\n }\n\n $('#usuario_info_type').text(type);\n\n if(locations_array.length>0){\n // populate associated locations panel\n var table_content = '';\n $.each(locations_array, function(i){\n if($this_usuario.user_id == this.user_id){\n table_content += '<tr><td>'+this.location_name+'</td></tr>';\n }\n }); \n\n if(table_content == '')\n {\n table_content = \"Usuario no tiene localizaciones asignadas.\";\n }\n $('#usuario_locations').html(table_content);\n }\n\n\n $('#specialty_panel').show();\n\n if(specialties_array.length>0){\n populate_specialties_info($this_usuario);\n }\n \n\n //Categoria de Localizacion\n\n //$('#especializacion_title').text(\"Tipo de Especializacion\" + \" - \" + $this_usuario.email)\n \n // set id values of info panel buttons\n $('#btn_edit_panel').attr('data-id', $this_usuario.user_id);\n $('#btn_delete').attr('data-id', $this_usuario.user_id);\n $('#btn_delete').attr('data-username', $this_usuario.username); \n }", "function fillUserInfo(){\n $('#usrname').text(`${currentUser.username}`)\n $profileName.text(`Name: ${currentUser.name}`)\n $profileUsername.text(`Username: ${currentUser.username}`)\n $profileAccountDate.text(`Account Created: ${currentUser.createdAt.slice(0,10)}`)\n }", "function showFormarttedInfo(user) {\n console.log('user Info', \"\\n id: \" + user.id + \"\\n user: \" + user.username + \"\\n firsname: \" + user.firsName + \"\\n \");\n}", "function afficherModules(data){\n\n for(var i=0;i<data.length;i++){ \n \n //On recuper le module\n listeInfosModules[data[i].id] = data[i];\n\n //On charge les modules actifs\n if(data[i].active){\n\n //On compte\n nombreModuleActifs = nombreModuleActifs + 1;\n\n //On affiche le module\n ajouterUnItemLight(data[i].id, \"<i class='\"+data[i].icon+\"'></i>\", data[i].label, data[i].color);\n }\n }\n\n //On harmonise l'affiche au cas où il ya peut de module afficher\n if(nombreModuleActifs < 5){\n $('#bodyPrincipalPanelPart02Special').css(\"text-align\",\"center\");\n $('#bodyPrincipalPanelPart02Special').css(\"padding-left\",\"40px\");\n }\n }", "function mostrarUsuarios(tipo) {\n const inscriptions = course.inscriptions;\n let lista = null;\n\n users = inscriptions?.map((inscription) => inscription.user);\n const teacher = new Array(course.creator);\n const delegate = new Array(course.delegate);\n\n if (tipo === 'Profesor') {\n lista = <UsersList courseId={courseId} users={teacher} setSelectedUser={(a)=>{console.log(a);}}/>;\n } else if (tipo === 'Delegados') {\n lista = <UsersList courseId={courseId} users={delegate} setSelectedUser={(a)=>{console.log(a);}} />;\n } else {\n lista = <UsersList courseId={courseId} users={users} setSelectedUser={(a)=>{console.log(a);}} />;\n }\n\n return lista;\n }", "function notificaInfo()\n{\n\t$('#modalHeader').html('Preventivo accettato');\n\t$('#modalBody').html('<p>Un cliente ha accettato il tuo preventivo. Attende che lo contatti, vuoi visualizzare i suoi dati?</p>');\n\t$('#modalFooter').html('<a href=\"javascript:accendiSeNotifica()\" class=\"btn\" data-dismiss=\"modal\">Annulla</a>'+\n\t\t\t\t\t\t '<a href=\"mostraQualcosa.html\" class=\"btn btn-primary\">Visualizza</a>');\n\t$('#panelNotifiche').modal('show');\n\tspegniSeNotifica();\n}", "getEditInfo(id) {\n\t\treturn db.one(`SELECT * FROM user_information WHERE id=$1`, id)\n\t}", "actualizarNombre(id, nombre) {\n for (let usuario of this.lista) {\n if (usuario.id === id) {\n usuario.nombre = nombre;\n break;\n }\n //de la lista en cada interaccicon la variable \n //usuario va a ser el elmento de cada intereaccion\n }\n }", "function updateInfoMod(title, content, parent) {\n const titleNode = helper.createEle('p',`${title}:`, 'left-align', 'comment');\n const contentNode = helper.createEle('p',`${content}`);\n parent.appendChild(titleNode);\n parent.appendChild(contentNode);\n}", "function setUserInfo(userInfo) {\n\n wx.setStorage({\n key: 'userInfo',\n data: userInfo\n });\n wx.setStorage({\n key: 'nikename',\n data: userInfo.nikename\n });\n wx.setStorage({\n key: 'city',\n data: userInfo.city\n });\n wx.setStorage({\n key: 'country',\n data: userInfo.country\n });\n wx.setStorage({\n key: 'avatar_url',\n data: userInfo.avatarUrl\n });\n}", "updateList(e) {\n PersonaService.getTiposUser(e.target.value).then(data => this.setState({ Usuarios: data }))\n }", "function showUserInformation(user){\n setSideBar(user)\n setLists(user)\n}", "function openProfileInfo() {\n vm.showUserInfo = !vm.showUserInfo;\n }", "function directUserFromUpdateInfo () {\n if (nextStep == \"The role for an existing employee\") {\n updateEmployeeRole();\n }\n }", "function utilisateur(e)\n { setuser({\n ...user,\n [e.target.name]:e.target.value\n })\n }", "function updateInfo() {\n let newVals = grabFormValues();\n $.ajax({\n dataType: 'json',\n type: 'PUT',\n data: newVals,\n async: false,\n url: 'api/employees/' + curUser._id,\n success: function(response) {\n console.log(response);\n localStorage.setItem('currentUser', JSON.stringify(response));\n curUser = JSON.parse(localStorage.getItem('currentUser'));\n showInfo();\n },\n });\n }", "replacerChangNiveau(){\n this.viderLaFile();\n this.cellule = this.jeu.labyrinthe.cellule(0,0);\n this.direction = 1;\n\t\t\t\tthis.vitesse = 0;\n }", "function printDetailsModified() {\n\treturn `${this.name} (${this.type}) - ${this.age}`;\n}", "function Info(user) {\n return `${user.name} tem ${user.age} anos.`;\n}", "function User_Insert_Impressions_Liste_des_modèles_d_impressions0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 8\n\nId dans le tab: 229;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = societe,im_societe,so_numero\n\nId dans le tab: 230;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 231;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 232;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 233;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 234;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 235;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 236;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"table_impression\";\n var CleMaitre = TAB_COMPO_PPTES[226].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var im_societe=GetValAt(229);\n if (im_societe==\"-1\")\n im_societe=\"null\";\n if (!ValiderChampsObligatoire(Table,\"im_societe\",TAB_GLOBAL_COMPO[229],im_societe,true))\n \treturn -1;\n var im_libelle=GetValAt(230);\n if (!ValiderChampsObligatoire(Table,\"im_libelle\",TAB_GLOBAL_COMPO[230],im_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_libelle\",TAB_GLOBAL_COMPO[230],im_libelle))\n \treturn -1;\n var im_nom=GetValAt(231);\n if (!ValiderChampsObligatoire(Table,\"im_nom\",TAB_GLOBAL_COMPO[231],im_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_nom\",TAB_GLOBAL_COMPO[231],im_nom))\n \treturn -1;\n var im_modele=GetValAt(232);\n if (!ValiderChampsObligatoire(Table,\"im_modele\",TAB_GLOBAL_COMPO[232],im_modele,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_modele\",TAB_GLOBAL_COMPO[232],im_modele))\n \treturn -1;\n var im_defaut=GetValAt(233);\n if (!ValiderChampsObligatoire(Table,\"im_defaut\",TAB_GLOBAL_COMPO[233],im_defaut,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_defaut\",TAB_GLOBAL_COMPO[233],im_defaut))\n \treturn -1;\n var im_keytable=GetValAt(234);\n if (!ValiderChampsObligatoire(Table,\"im_keytable\",TAB_GLOBAL_COMPO[234],im_keytable,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keytable\",TAB_GLOBAL_COMPO[234],im_keytable))\n \treturn -1;\n var im_keycle=GetValAt(235);\n if (!ValiderChampsObligatoire(Table,\"im_keycle\",TAB_GLOBAL_COMPO[235],im_keycle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keycle\",TAB_GLOBAL_COMPO[235],im_keycle))\n \treturn -1;\n var im_keydate=GetValAt(236);\n if (!ValiderChampsObligatoire(Table,\"im_keydate\",TAB_GLOBAL_COMPO[236],im_keydate,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"im_keydate\",TAB_GLOBAL_COMPO[236],im_keydate))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",im_societe,im_libelle,im_nom,im_modele,im_defaut,im_keytable,im_keycle,im_keydate\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+im_societe+\",\"+(im_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(im_libelle)+\"'\" )+\",\"+(im_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(im_nom)+\"'\" )+\",\"+(im_modele==\"\" ? \"null\" : \"'\"+ValiderChaine(im_modele)+\"'\" )+\",\"+(im_defaut==\"true\" ? \"true\" : \"false\")+\",\"+(im_keytable==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keytable)+\"'\" )+\",\"+(im_keycle==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keycle)+\"'\" )+\",\"+(im_keydate==\"\" ? \"null\" : \"'\"+ValiderChaine(im_keydate)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function modificado(t) {\n datos();\n}", "function update_ui(\n status,\n all_person_modifier,\n names,\n change_selected_person,\n change_seleted_entry){\n if (status == true) {\n all_person_modifier(prev=>{\n const name = names[0]+\"-\"+names[1];\n delete prev[name];\n return prev;\n\n\n })\n change_selected_person(null);\n change_seleted_entry(null);\n \n }\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}", "function User_Update_TVA_Liste_des_T_V_A_0(Compo_Maitre)\n{\n var Table=\"tva\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tv_taux=GetValAt(154);\n if (!ValiderChampsObligatoire(Table,\"tv_taux\",TAB_GLOBAL_COMPO[154],tv_taux,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tv_taux\",TAB_GLOBAL_COMPO[154],tv_taux))\n \treturn -1;\n var tv_code=GetValAt(155);\n if (!ValiderChampsObligatoire(Table,\"tv_code\",TAB_GLOBAL_COMPO[155],tv_code,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tv_code\",TAB_GLOBAL_COMPO[155],tv_code))\n \treturn -1;\n var cg_numero=GetValAt(156);\n if (cg_numero==\"-1\")\n cg_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cg_numero\",TAB_GLOBAL_COMPO[156],cg_numero,true))\n \treturn -1;\n var tv_actif=GetValAt(157);\n if (!ValiderChampsObligatoire(Table,\"tv_actif\",TAB_GLOBAL_COMPO[157],tv_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tv_actif\",TAB_GLOBAL_COMPO[157],tv_actif))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"tv_taux=\"+(tv_taux==\"\" ? \"null\" : \"'\"+ValiderChaine(tv_taux)+\"'\" )+\",tv_code=\"+(tv_code==\"\" ? \"null\" : \"'\"+ValiderChaine(tv_code)+\"'\" )+\",cg_numero=\"+cg_numero+\",tv_actif=\"+(tv_actif==\"true\" ? \"true\" : \"false\")+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function changeVolInfo (name, address, email, phone, availability, activities){\n jCooper.volunteerInfo = (name + address + email + phone + availability + activities);\n console.log(jCooper.volunteerInfo); \n}", "function mostrarInfoSesion($usuario){\n\n $('aside').css('display','flex');\n\n $user=new Usuario($usuario.idUsuario, $usuario.nombreUsuario, $usuario.email, $usuario.password, $usuario.codResp);\n\n $('aside div:nth-child(2)').text('user: '+$user.getIdUsuario()+'-'+$user.getNombreUsuario());\n $('aside div:nth-child(3)').text($user.getEmail());\n\n\n}", "function User_Insert_Profils_de_droits_Droits_2(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 5\n\nId dans le tab: 94;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = groupetable,gt_numero,gt_numero\n\nId dans le tab: 95;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 96;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 97;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 98;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"droit\";\n var CleMaitre = TAB_COMPO_PPTES[91].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var gt_numero=GetValAt(94);\n if (gt_numero==\"-1\")\n gt_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"gt_numero\",TAB_GLOBAL_COMPO[94],gt_numero,true))\n \treturn -1;\n var dr_select=GetValAt(95);\n if (!ValiderChampsObligatoire(Table,\"dr_select\",TAB_GLOBAL_COMPO[95],dr_select,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_select\",TAB_GLOBAL_COMPO[95],dr_select))\n \treturn -1;\n var dr_insert=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"dr_insert\",TAB_GLOBAL_COMPO[96],dr_insert,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_insert\",TAB_GLOBAL_COMPO[96],dr_insert))\n \treturn -1;\n var dr_update=GetValAt(97);\n if (!ValiderChampsObligatoire(Table,\"dr_update\",TAB_GLOBAL_COMPO[97],dr_update,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_update\",TAB_GLOBAL_COMPO[97],dr_update))\n \treturn -1;\n var dr_delete=GetValAt(98);\n if (!ValiderChampsObligatoire(Table,\"dr_delete\",TAB_GLOBAL_COMPO[98],dr_delete,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dr_delete\",TAB_GLOBAL_COMPO[98],dr_delete))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",dp_numero,gt_numero,dr_select,dr_insert,dr_update,dr_delete\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[88].NewCle+\",\"+gt_numero+\",\"+(dr_select==\"true\" ? \"true\" : \"false\")+\",\"+(dr_insert==\"true\" ? \"true\" : \"false\")+\",\"+(dr_update==\"true\" ? \"true\" : \"false\")+\",\"+(dr_delete==\"true\" ? \"true\" : \"false\")+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function ajoutInfo()\n{ \tvar nom=$( \"#nom option:selected\" ).val();\n \t//var fimage=$( \"#image option:selected\" ).val();\n\t\tvar cap=$(\"#cap option:selected\").val();\n\t\tvar acc=$('input[name=\"acc\"]:first').val();\n\t\tvar env=$('input[name=\"env\"]:first').val();\n\t\tvar date=$('input[name=\"date\"]:first').val();\n\n\tlireBdJson();\n\tvar descJsonObjects=bd.descriptions;\n\tvar jsonObject={ //creation de json\n\t\t\"nom\":nom,\n\t\t//\"image\":fimage,\n\t\t\"capacite\":cap,\n\t\t\"acces\":acc,\n\t\t\"environemment\":env,\n\t\t\"date\":date,\n\t};\n\tdescJsonObjects.push(jsonObject);//ajout dans le tableau des description\n\tbd.descriptions=descJsonObjects;\n\tlocalStorage.setItem('bdjson', JSON.stringify(bd));\t\n\treturn(true);\n\t}", "function User_Insert_Produits_Liste_des_produits0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 6\n\nId dans le tab: 161;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 162;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = journal,jo_numero,jo_numero\n\nId dans le tab: 163;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 164;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 165;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = prix,pd_numero,pd_numero\n\nId dans le tab: 175;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = compteproduit,pd_numero,pd_numero\n\n******************\n*/\n\n var Table=\"produit\";\n var CleMaitre = TAB_COMPO_PPTES[158].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var pd_libelle=GetValAt(161);\n if (!ValiderChampsObligatoire(Table,\"pd_libelle\",TAB_GLOBAL_COMPO[161],pd_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_libelle\",TAB_GLOBAL_COMPO[161],pd_libelle))\n \treturn -1;\n var jo_numero=GetValAt(162);\n if (jo_numero==\"-1\")\n jo_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"jo_numero\",TAB_GLOBAL_COMPO[162],jo_numero,true))\n \treturn -1;\n var pd_actif=GetValAt(163);\n if (!ValiderChampsObligatoire(Table,\"pd_actif\",TAB_GLOBAL_COMPO[163],pd_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_actif\",TAB_GLOBAL_COMPO[163],pd_actif))\n \treturn -1;\n var pd_reduction=GetValAt(164);\n if (!ValiderChampsObligatoire(Table,\"pd_reduction\",TAB_GLOBAL_COMPO[164],pd_reduction,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pd_reduction\",TAB_GLOBAL_COMPO[164],pd_reduction))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pd_libelle,jo_numero,pd_actif,pd_reduction\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(pd_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(pd_libelle)+\"'\" )+\",\"+jo_numero+\",\"+(pd_actif==\"true\" ? \"true\" : \"false\")+\",\"+(pd_reduction==\"true\" ? \"true\" : \"false\")+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function mostrarPermisos(data){\n\n\t\tif(data.add == 1){\n\t\t\taddIcoPermOk(\"add-est\");\n\t\t\taddBtnQuitar(\"add\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"add-est\");\n\t\t\taddBtnAdd(\"add\");\n\t\t}\n\t\tif(data.upd == 1){\n\t\t\taddIcoPermOk(\"upd-est\");\n\t\t\taddBtnQuitar(\"upd\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"upd-est\");\n\t\t\taddBtnAdd(\"upd\");\n\t\t}\n\t\tif(data.del == 1){\n\t\t\taddIcoPermOk(\"del-est\");\n\t\t\taddBtnQuitar(\"del\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"del-est\");\n\t\t\taddBtnAdd(\"del\");\n\t\t}\n\t\tif(data.list == 1){\n\t\t\taddIcoPermOk(\"list-est\");\n\t\t\taddBtnQuitar(\"list\");\n\t\t}else{\n\t\t\taddIcoPermNOk(\"list-est\");\n\t\t\taddBtnAdd(\"list\");\n\t\t}\n\n\t\t/*Una vez dibujados los permisos del usuario, \n\t\tel selector de usuario obtiene el foco */\n\t\t$('select#usuario').focus(); \n\n\t}", "function modificarHtml ( valores )\n {\n var personas = valores;//capturo lo qu eme devolvio la perticion ajax\n console.log( personas );\n\n /*For que recorrera todos los arreglos que tenga el objeto que me paso la peticion*/\n for( var i = 0; i < personas.length ; i++ )\n {\n\n var personaActual = personas[i]; //capturo todo el objeto a array actual\n var tagsDePersona = \"\";\n\n /*For que recorrera cada objeto por individual y recorrera los tags ya que son un array*/\n for( var j = 0; j < personaActual.Tags.length ; j++ )\n {\n tagsDePersona += personaActual.Tags[j] + \" , \"; /*Ira concatenando cada valor que posea cada array*/\n }\n\n\n\n var html = \"\";\n html += '<tr>';\n html += ' <td>' + personas[i].nombre + '</td>';\n html += ' <td>' + personas[i].Edad + '</td>';\n html += ' <td>' + tagsDePersona + '</td>';\n html += '</tr>';\n\n /*Hago la insercion de cada tabla*/\n \n $('table#miTabla').append( html );\n }\n }", "function infogral(cabinet) {\n vm.asset = cabinet;\n if (vm.puncture) {\n vm.puncture.cabinet_id = vm.asset.economico;\n }\n }", "updateUserDetails() {\n if (!activeUser()) return;\n $(conversations_area).find(`[data-user-id=\"${activeUser().id}\"] .sb-name,.sb-top > a`).html(activeUser().get('full_name'));\n $(conversations_area).find('.sb-user-details .sb-profile').setProfile();\n SBProfile.populate(activeUser(), $(conversations_area).find('.sb-profile-list'));\n }", "function escucha_users(){\n\t/*Activo la seleccion de usuarios para modificarlos, se selecciona el usuario de la lista que\n\tse muestra en la pag users.php*/\n\tvar x=document.getElementsByTagName(\"article\");/*selecciono todos los usuarios ya qye se encuentran\n\tdentro de article*/\n\tfor(var z=0; z<x.length; z++){/*recorro el total de elemtos que se dara la capacidad de resaltar al\n\t\tser seleccionados mediante un click*/\n\t\tx[z].onclick=function(){//activo el evento del click\n\t\t\t/*La funcion siguiente desmarca todo los articles antes de seleccionar nuevamente a un elemento*/\n\t\t\tlimpiar(\"article\");\n\t\t\t$(this).css({'border':'3px solid #f39c12'});\n\t\t\tvar y=$(this).find(\"input\");\n\t\t\tconfUsers[indice]=y.val();\n\t\t\tconsole.log(confUsers[indice]);\n\t\t\t/* indice++; Comento esta linea dado que solo se puede modificar un usuario, y se deja para \n\t\t\tun uso posterior, cuando se requiera modificar o seleccionar a mas de un elemento, que se\n\t\t\talmacene en el arreglo de confUser los id que identifican al elemento*/\n\t\t\tsessionStorage.setItem(\"conf\", confUsers[indice]);\n\t\t};\n\t}\n}", "function findPantryInfo() {\n user.pantry.forEach(item => {\n let itemInfo = ingredientsData.find(ingredient => {\n return ingredient.id === item.ingredient;\n });\n let originalIngredient = pantryInfo.find(ingredient => {\n if (itemInfo) {\n return ingredient.name === itemInfo.name;\n }\n });\n if (itemInfo && originalIngredient) {\n originalIngredient.count += item.amount;\n } else if (itemInfo) {\n pantryInfo.push({name: itemInfo.name, count: item.amount});\n }\n });\n let sortedPantry = pantryInfo.sort((a, b) => a.name.localeCompare(b.name));\n sortedPantry.forEach(ingredient => domUpdates.displayPantryInfo(ingredient))\n}", "static modifyFields() {\n return [\n 'article_id',\n 'user_id',\n 'comment',\n 'flagged',\n ];\n }", "function ajouterProduit(nom_obj, val1, val2, mamethode) {\n\tconsole.log('Methode : '+mamethode)\n\tif (nom_obj === \"stock\" || nom_obj === \"employes\" || nom_obj === \"clients\" || nom_obj === \"fournisseurs\") {\n\t var stock = getLS(nom_obj);\n\t if (stock === null || typeof stock !== \"object\") {\n\t\tstock = {};\n\t }\n\t\tif (searchItem(val1, nom_obj) && mamethode==\"add\") {\n\t\t\t$('.erreurs').html('<p style=\"color:red;text-align:center;\">\"'+val1+'\" existe déjà. Veuillez sélectionner l\\'option \"modifier\" pour le modifier.</p>');\n\t\t} else {\n\t\t\tstock[val1] = val2;\n\t\t\tif (saveLS(nom_obj, stock)) {\n\t\t\t\tif (mamethode==\"mod\") {\n\t\t\t\t\t$('.erreurs').html('<p style=\"color:green;text-align:center;\">\"'+val1+'\" a correctement été modifié.</p>');\n\t\t\t\t} else {\n\t\t\t\t$('.erreurs').html('<p style=\"color:green;text-align:center;\">\"'+val1+'\" a correctement été ajouté.</p>');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n }", "function escucha_Permisos(){\n\t/*Activo la seleccion de usuarios para modificarlos, se selecciona el usuario de la lista que\n\tse muestra en la pag users.php*/\n\tvar x=document.getElementsByClassName(\"work_data\");/*selecciono todos los usuarios ya qye se encuentran\n\tdentro de article*/\n\tfor(var z=0; z<x.length; z++){/*recorro el total de elemtos que se dara la capacidad de resaltar al\n\t\tser seleccionados mediante un click*/\n\t\tx[z].onclick=function(){//activo el evento del click\n\t\t\tif($(this).find(\"input\").val()!=0){/*Encuentro el input con el valor de id de permiso*/\n\t\t\t\t/*La funcion siguiente desmarca todo los articles antes de seleccionar nuevamente a un elemento*/\n\t\t\t\tlimpiar(\".work_data\");\n\t\t\t\t$(this).css({'border':'3px solid #f39c12'});\n\t\t\t\tvar y=$(this).find(\"input\");/*Encuentro el input con el valor de id de permiso*/\n\t\t\t\tconfUsers[indice]=y.val();/*Obtengo el valor del input \"idPermiso\" y lo almaceno*/\n\t\t\t\tconsole.log(confUsers[indice]);\n\t\t\t\t/* indice++; Comento esta linea dado que solo se puede modificar un usuario, y se deja para \n\t\t\t\tun uso posterior, cuando se requiera modificar o seleccionar a mas de un elemento, que se\n\t\t\t\talmacene en el arreglo de confUser los id que identifican al elemento*/\n\t\t\t\tsessionStorage.setItem(\"confp\", confUsers[indice]);\n\t\t\t}\n\t\t};\n\t}\n}", "function User_Update_Groupe_de_tables_Liste_des_groupes_de_tables0(Compo_Maitre)\n{\n var Table=\"groupetable\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var gt_libelle=GetValAt(102);\n if (!ValiderChampsObligatoire(Table,\"gt_libelle\",TAB_GLOBAL_COMPO[102],gt_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gt_libelle\",TAB_GLOBAL_COMPO[102],gt_libelle))\n \treturn -1;\n var gt_tables=GetValAt(103);\n if (!ValiderChampsObligatoire(Table,\"gt_tables\",TAB_GLOBAL_COMPO[103],gt_tables,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gt_tables\",TAB_GLOBAL_COMPO[103],gt_tables))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"gt_libelle=\"+(gt_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(gt_libelle)+\"'\" )+\",gt_tables=\"+(gt_tables==\"\" ? \"null\" : \"'\"+ValiderChaine(gt_tables)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}", "function editTableModificarDescuento() {\n var nameTable = \"ModificarDescuento\";\n var nameCols = crearListaColumnas();\n var activaAdd = true;\n var activaDelete = true;\n\n return buildTableTools(nameTable, nameCols, activaAdd, activaDelete);\n}", "provincia() {\n return super.informacion('provincia');\n }", "function User_Insert_Journaux_Liste_des_journaux0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 8\n\nId dans le tab: 52;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = typejournal,tj_numero,tj_numero\n\nId dans le tab: 53;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 54;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 55;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 56;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 57;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 58;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = comptegen,cg_numero,cg_numero\n\nId dans le tab: 59;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = piece,jo_numero,jo_numero\n\n******************\n*/\n\n var Table=\"journal\";\n var CleMaitre = TAB_COMPO_PPTES[47].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tj_numero=GetValAt(52);\n if (tj_numero==\"-1\")\n tj_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"tj_numero\",TAB_GLOBAL_COMPO[52],tj_numero,true))\n \treturn -1;\n var jo_abbrev=GetValAt(53);\n if (!ValiderChampsObligatoire(Table,\"jo_abbrev\",TAB_GLOBAL_COMPO[53],jo_abbrev,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_abbrev\",TAB_GLOBAL_COMPO[53],jo_abbrev))\n \treturn -1;\n var jo_libelle=GetValAt(54);\n if (!ValiderChampsObligatoire(Table,\"jo_libelle\",TAB_GLOBAL_COMPO[54],jo_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_libelle\",TAB_GLOBAL_COMPO[54],jo_libelle))\n \treturn -1;\n var jo_provisoire=GetValAt(55);\n if (!ValiderChampsObligatoire(Table,\"jo_provisoire\",TAB_GLOBAL_COMPO[55],jo_provisoire,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_provisoire\",TAB_GLOBAL_COMPO[55],jo_provisoire))\n \treturn -1;\n var jo_visible=GetValAt(56);\n if (!ValiderChampsObligatoire(Table,\"jo_visible\",TAB_GLOBAL_COMPO[56],jo_visible,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_visible\",TAB_GLOBAL_COMPO[56],jo_visible))\n \treturn -1;\n var jo_contrepartie=GetValAt(57);\n if (!ValiderChampsObligatoire(Table,\"jo_contrepartie\",TAB_GLOBAL_COMPO[57],jo_contrepartie,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"jo_contrepartie\",TAB_GLOBAL_COMPO[57],jo_contrepartie))\n \treturn -1;\n var cg_numero=GetValAt(58);\n if (cg_numero==\"-1\")\n cg_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cg_numero\",TAB_GLOBAL_COMPO[58],cg_numero,true))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tj_numero,jo_abbrev,jo_libelle,jo_provisoire,jo_visible,jo_contrepartie,cg_numero\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+tj_numero+\",\"+(jo_abbrev==\"\" ? \"null\" : \"'\"+ValiderChaine(jo_abbrev)+\"'\" )+\",\"+(jo_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(jo_libelle)+\"'\" )+\",\"+(jo_provisoire==\"true\" ? \"true\" : \"false\")+\",\"+(jo_visible==\"true\" ? \"true\" : \"false\")+\",\"+(jo_contrepartie==\"true\" ? \"true\" : \"false\")+\",\"+cg_numero+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "information() {\n if (this.over()) {\n this.info.innerHTML = 'Joueur ' + this.activePlayer.id + ' vous avez gagné !';\n this.info.classList.add('alert-success');\n this.alert.classList.remove('show');\n } else {\n this.info.innerHTML = `C'est à vous de jouez : joueur ` + this.activePlayer.id;\n }\n\n player1.description();\n player2.description();\n }", "function afficheInfos(donnees) {\n\tvar HTML = Twig.twig({ href: \"templates/infos.twig.html\", async: false}).render();\t\t\n\t$(\"#content\").html(HTML);\n\t$(\".link-side-nav\").removeClass(\"active\");\n\t$(\".nav-link\").removeClass(\"active\");\n\n\t$(\".social\").addClass(\"none\");\n\n\t$(\".infos\").addClass(\"active\");\n}", "function updateUserMod (self, userID, authorisation) {\n //select the modal and clear it\n const userMod = document.querySelector('#userMod-content');\n helper.deleteChildren(userMod);\n //add title \n const modalTitle = helper.createEle('h1', 'My Details', 'centre-align');\n userMod.appendChild(modalTitle);\n\n //pass in 'self' argument to get the JSON about the logged in user\n const userInfo = getInfo(userID, authorisation, 'self');\n if(self !== 'self') {\n console.log('not self');\n //getInfo returns a promise to get a user's JSON \n userInfo = getInfo(userID, authorisation, 'not-self'); \n }\n\n //Updates all the text content in the modal with the data from the json returned from promise\n userInfo.then(async json => {\n updateInfoMod('Username', `${json.username}`, userMod);\n updateInfoMod('Email', `${json.email}`, userMod);\n updateInfoMod('# of posts', `${json.posts.length}`, userMod);\n updateInfoMod('# of upvotes', `${await getUpvotes(json)}`, userMod);\n });\n}", "function updateInformation() {\n// UPDATE MAP INFORMATION\ndojo.forEach(_maps, function (map) {\n updateInformationForMap(map);\n});\n}", "function caricamento(){\n \n var lg=document.getElementById(\"log\");\n var log=document.createElement('a');\n log.className=\"nav-link\";\n log.href=\"MyInfo.html\";\n\n if(tipoUtente==\"c\"){\n document.getElementById(\"myinfoV\").style.display=\"none\";\n log.innerHTML=utenti[0].Clienti[id].Nome;\n lg.appendChild(log);\n document.getElementById(\"Nome\").value=utenti[0].Clienti[id].Nome;\n document.getElementById(\"Cognome\").value=utenti[0].Clienti[id].Cognome;\n document.getElementById(\"Email\").value=utenti[0].Clienti[id].Email;\n document.getElementById(\"Password\").value=utenti[0].Clienti[id].Password;\n document.getElementById(\"Indirizzo\").value=utenti[0].Clienti[id].Indirizzo;\n document.getElementById(\"TipoPagamento\").value=utenti[0].Clienti[id].TipoPagamento;\n document.getElementById(\"DataDiNascita\").value=utenti[0].Clienti[id].DataDiNascita;\n }else{\n log.innerHTML=utenti[0].Venditori[id].Nome;\n document.getElementById(\"myinfo\").style.display=\"none\";\n \n lg.appendChild(log);\n document.getElementById(\"NomeV\").value=utenti[0].Venditori[id].Nome;\n document.getElementById(\"TipoDiAttivita\").value=utenti[0].Venditori[id].TipoDiAttivita;\n document.getElementById(\"EmailV\").value=utenti[0].Venditori[id].Email;\n document.getElementById(\"PasswordV\").value=utenti[0].Venditori[id].Password;\n document.getElementById(\"IndirizzoV\").value=utenti[0].Venditori[id].Indirizzo;\n document.getElementById(\"PartitaIva\").value=utenti[0].Venditori[id].PartitaIva;\n document.getElementById(\"Numero\").value=utenti[0].Venditori[id].NumeroDiTelefono;\n document.getElementById(\"DataDiNascitaV\").value=utenti[0].Venditori[id].DataNascita;\n document.getElementById(\"NomeAzienda\").value=utenti[0].Venditori[id].NomeAzienda;\n\n lg.appendChild(log);\n lg=document.getElementById(\"sell\");\n log=document.createElement('a');\n log.className=\"nav-link\";\n log.idName=\"sell\";\n log.href=\"SellProducts.html\";\n log.innerHTML=\"SellProducts\";\n // lg.appendChild(log);\n }\n \n console.log(utenti[0].Clienti[id]);\n \n \n\n\n \n /*prD=\"<div class='row justify-content-center'>Nome = \"+utent.Nome+\" <br> Cognome = \"+utent.Cognome+\"<br> Indirizzo Email = \"+utent.Email+\"<br> ID = \"+utent.ID+\"<br> Tipo di pagamento = \"+utent.TipoPagamento+\"<br> Data Di Nascita = \"+utent.DataNascita+\"<br> Indirizzo = \"+utent.Indirizzo+\" <br> </div> <div class='row justify-content-center'><button onclick='Delete()' class='btn btn-danger'>Delete Account</a></div>\";\n elem=document.getElementById(\"myinfo\");\n newElem=document.createElement('div');\n newElem.className=\"row \";\n newElem.innerHTML=prD;\n elem.appendChild(newElem);*/\n \n\n \n\n \n var bs=0;\n document.getElementById(\"bs\").innerHTML=bs;\n}", "edit({ email, name, password, image }) {\n let details = { email, name, password, image };\n for (const key in details)\n if (details[key]) {\n currentUser[key] = details[key];\n }\n callFuture(updateUserListeners);\n }", "function setInfo( json ) { rescate = json; }", "function User_Insert_Types_de_lien_Liste_des_types_de_lien_entre_personne0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 45;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 46;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typelien\";\n var CleMaitre = TAB_COMPO_PPTES[43].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tl_libelle=GetValAt(45);\n if (!ValiderChampsObligatoire(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle))\n \treturn -1;\n var tl_description=GetValAt(46);\n if (!ValiderChampsObligatoire(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tl_libelle,tl_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tl_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_libelle)+\"'\" )+\",\"+(tl_description==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function updateDisplay() {\n UserService.getUserInfo().then(function(response) {\n displayLogs();\n })\n }", "function addProduit (id, nom, prix) {\n\tlet detailProduit = [id, nom, prix];\n\tcontenuPanier.push(detailProduit);\n\tlocalStorage.panier = JSON.stringify(contenuPanier);\n\tcountProduits();\n}" ]
[ "0.61846715", "0.61479354", "0.6117794", "0.6071993", "0.6060675", "0.6033535", "0.5963548", "0.59511083", "0.59008926", "0.58876836", "0.5845607", "0.5843367", "0.58278704", "0.581477", "0.5812889", "0.5808275", "0.580382", "0.57536566", "0.5745093", "0.57272017", "0.57219785", "0.56987166", "0.5693651", "0.568159", "0.56625915", "0.5658115", "0.56056076", "0.5584676", "0.5581541", "0.5561361", "0.5550811", "0.5543567", "0.55356514", "0.5526571", "0.55121493", "0.55032605", "0.5503026", "0.54862946", "0.5465088", "0.5465088", "0.54650843", "0.5455826", "0.54466414", "0.54444844", "0.54270184", "0.54218453", "0.54049015", "0.54042363", "0.5402901", "0.5395409", "0.53793734", "0.5371747", "0.53664094", "0.5364913", "0.53604805", "0.5359239", "0.535487", "0.53510356", "0.53501964", "0.5339774", "0.53381145", "0.53379357", "0.5335945", "0.5328555", "0.5322691", "0.53188354", "0.5317168", "0.5311214", "0.5291603", "0.5285511", "0.5276915", "0.5274531", "0.52735895", "0.5261048", "0.52439076", "0.5239852", "0.523779", "0.5233559", "0.522706", "0.5224803", "0.52196056", "0.52190757", "0.52055144", "0.52051973", "0.52028763", "0.51973116", "0.51939154", "0.51934797", "0.5188666", "0.5186325", "0.5172241", "0.51677555", "0.51675487", "0.51510704", "0.5147168", "0.5142408", "0.51419365", "0.51412046", "0.5136696", "0.5135017", "0.51322985" ]
0.0
-1
ajout d'une offre de job
function addJobOffer(){ var jobName = document.querySelector('#sample1').value; var jobCity = document.getElementById('sample2').value; var jobDuration = document.getElementById('number').value; var jobStart = document.getElementById('date').value; var jobContact = document.getElementById('sample5').value; var ref = db.ref("job_offers"); var offer = { name: jobName, city: jobCity, duration: jobDuration, start: jobStart, contact: jobContact } console.log(offer); ref.push(offer); dialogJob.close(); var messageJob = { message: 'Your job offer has been added', timeout: 5000 }; snackbar.MaterialSnackbar.showSnackbar(messageJob); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function submit() {\n axios.post('/api/jobs', {\n company_name: company,\n job_title: job_title,\n status: status,\n color: color\n })\n .then(res => {\n props.add(res.data);\n props.hide();\n })\n }", "function ajoutPb(){\n\tlet pb=prompt('Signaler un problème :');\n\t$.post(\"php/ajout-probleme.php\",{id:$(this).data('id'),pb:pb},validePb);\n}", "function addJob(job) {\n $.post(\"/api/jobs\", job);\n console.log(`job added to room ${currentRoom}:` + job.title)\n }", "handleJob(event) {\n\n\n\t\twindow.open(\"https://www.naukri.com/\" + this.state.user.jbin + \"-jobs\")\n\t\twindow.open(\"https://www.indeed.co.in/\" + this.state.user.jbin + \"-jobs\")\n\n\t}", "function onSubmitAjout(e) {\n e.preventDefault();\n\n //On execute la requete sur le serveur distant\n let request = constructRequest(\"index.php?page=equipeajoutws\", \"POST\", $(this).serialize() );\n\n //En cas de succe de la requete\n request.done(function( infos ) {\n //on verifie si il n'y pas eu d'erreur lors du traitement par le controleur\n if(infos.message_invalid_ajout !== undefined) {\n //si il y en a eu une, on affiche le message d'erreur dans une alerte au dessus des entree du formulaire\n let ajoutMessage = $(\"#modal-ajout-message\");\n ajoutMessage.html(infos.message_invalid_ajout);\n ajoutMessage.show(250);\n } else {\n //sinon on cache le formulaire d'ajout et on affiche un message de succé tout en rechargeant les equipe\n $(\"#modal-ajout\").modal(\"hide\");\n showPopup(infos.popup_message, infos.popup_type);\n loadEquipes();\n }\n });\n}", "function ajouter(e, forceTheCreation = false) {\r\n doPost( \"modification/service/entrainement\",\r\n {\r\n training: $(\"#training\").val(),\r\n size: $(\"#size\").val(),\r\n trainingdate: $(\"#trainingdate\").val(),\r\n coach: $(\"#coach option:selected\").val(),\r\n force: forceTheCreation,\r\n poolsize: $('input[name=poolsize]:checked').val()\r\n },\r\n resp => actionDone(\"L'entrainement a bien été ajouté.\"),\r\n function (resp) { // error function\r\n if (resp.message.includes(\"Un entrainement existe le m\")) {\r\n // Obligé de remettre le message sinon contient un <li> bizarre\r\n if (confirm(\"Un entrainement existe le même jour, avec la même taille et le même entraineur. Voulez-vous quand même ajouter celui-ci ?\")) {\r\n ajouter(e, true);\r\n return;\r\n } else {\r\n actionError(\"L'entrainement n'a pas été ajouté.\");\r\n }\r\n } else {\r\n actionError(resp.message);\r\n }\r\n }\r\n );\r\n}", "function reportJobs() {\n postAnswer(DATA_NOT_AVAILABLE + 'aaaaaaa ');\n}", "submitExtra() {\n }", "function addJobCommand(ie) {\n var id = ie.id;\n var value = ie.value;\n var pname = ie.getAttribute('data-pname');\n // by putting the command_value in a <pre></pre> \n // we only need to replace &,< by &amp; &lt; to prevent html parsing\n // no need to add <br>'s\n value = value.replace(/&/g, \"&amp;\");\n value = value.replace(/</g, \"&lt;\");\n // \n $('#'+pname).html(value); \n // showMsg('debug: addJobCommand(\"'+pname+'\")');\n}", "setJob(job) {\n this.worker.postMessage({\n method: \"job\",\n params: job\n });\n }", "function addArbeit(divId, job) {\r\n\t//Arbeit in Array aufnehmen\r\n\tMoCheck.getAktArbeiten().splice(0, 0, job);\r\n\t\r\n\t//Arbeit ggf. in Tabelle anzeigen\r\n\tif($defined(AjaxWindow.windows['motivation']) && AjaxWindow.windows['motivation'].isReady) {\r\n\t\tMoCheck.printResults();\r\n\t}\r\n\t\r\n\t//Arbeit in Cookie speichern\r\n\tthis.setCookie();\r\n\t\r\n\tnew HumanMessage(MoCheck.getString('message.addedWork'), {type:'success'});\r\n}", "async function handleSubmit(e)\n {\n e.preventDefault();\n //check if empty\n if(ifEmpty(\"titel\", titel) && ifEmpty(\"inter\", inter) && ifEmpty(\"tech\", tech) /**&& ifEmpty(\"tech2\", tech2)*/ ){\n //add job to db\n const result = await addJobdb4params(titel, inter, tech, email)\n if(result === true){\n //get all jobs from db\n var jobs = await getJobs(email)\n //set all jobs in db\n props.updateUser(jobs)\n //redirect to /profile\n history.push(\"/profile\");\n }\n } \n }", "function onSubmitModif(e) {\n e.preventDefault();\n\n //On execute la requete sur le serveur distant\n let request = constructRequest(\"index.php?page=equipemodifws\", \"POST\", $(this).serialize() );\n\n //En cas de succe de la requete\n request.done(function( infos ) {\n //on verifie si il n'y pas eu d'erreur lors du traitement par le controleur\n if(infos.message_invalid_modif !== undefined) {\n //si il y en a eu une, on affiche le message d'erreur dans une alerte au dessus des entree du formulaire\n let modifMessage = $(\"#modal-modif-message\");\n modifMessage.html(infos.message_invalid_modif);\n modifMessage.show(250);\n } else {\n //sinon on cache le formulaire de modification et on affiche un message de succé tout en rechargeant les equipe\n $(\"#modal-modif\").modal(\"hide\");\n showPopup(infos.popup_message, infos.popup_type);\n loadEquipes();\n }\n });\n}", "function editHistorico(){\r\n submitForm($('#formHistorico').get(0), getContextApp()+'/proposta/editar.action', false);\r\n}", "send() {\n this.count++;\n var j = new brigadier_1.Job(`${this.name}-${this.count}`, this.notificationJobImage);\n j.imageForcePull = true;\n // GitHub limits this field to 65535 characters, so we\n // trim the length (from the beginning) prior to sending,\n // inserting a placeholder for the text omitted after truncation.\n if (this.text.length > exports.GITHUB_CHECK_TEXT_MAX_CHARS) {\n let textOmittedMsg = \"(Previous text omitted)\\n\";\n this.text = this.text.slice(this.text.length - (exports.GITHUB_CHECK_TEXT_MAX_CHARS - textOmittedMsg.length));\n this.text = textOmittedMsg + this.text;\n }\n j.env = {\n CHECK_CONCLUSION: this.conclusion,\n CHECK_NAME: this.name,\n CHECK_TITLE: this.title,\n CHECK_PAYLOAD: this.payload,\n CHECK_SUMMARY: this.summary,\n CHECK_TEXT: this.text,\n CHECK_DETAILS_URL: this.detailsUrl,\n CHECK_EXTERNAL_ID: this.externalID\n };\n return j.run();\n }", "submit() {\n\t\tif (!this.state.submitButtonEnabled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.state.executing = true;\n\t\tthis.opts.callback && this.opts.callback(this.project);\n\t\tetch.update(this);\n\t}", "function sendAjaxToJobs(id) {\n var jobId = id || '';\n var method = id ? 'PATCH' : 'POST';\n var job_params = makeAppropriateJSON();\n\n showErrorsModule.removeErrors();\n\n $.ajax({\n url: '/jobs/' + jobId,\n type: method,\n data: job_params,\n dataType: 'json',\n contentType: 'application/json',\n success: function(response) {\n if (response.flash) {\n showErrorsModule.showMessage(response.flash.notice, \"special-success\");\n }\n conversionTracking.trackPostAnAssignment( response.location );\n window.scrollTo(0, 0);\n },\n error: function(response) {\n $(formSubmitBtn).prop(\"disabled\", false);\n var permission_errors = response.responseJSON.permission_errors;\n var special_errors = response.responseJSON.errors;\n var main_error = response.responseJSON.message;\n if (permission_errors && permission_errors.length > 0) {\n showErrorsModule.showMessage(permission_errors, \"permission-error\");\n } else if (main_error) {\n showErrorsModule.showMessage([main_error], \"main-error\");\n } else if (special_errors) {\n showErrorsModule.showMessage(special_errors, \"special-error\");\n }\n window.scrollTo(0, 0);\n }\n });\n // console.log(makeAppropriateJSON());\n }", "static newTaskSubmit() {\n const newTaskData = document.querySelector('#newTaskData').elements;\n const name = newTaskData[0].value;\n const dueDate = newTaskData[2].value;\n const priority = () => {\n const radioHigh = document.querySelector('#radioTaskHigh')\n const radioMed = document.querySelector('#radioTaskMed')\n const radioLow = document.querySelector('#radioTaskLow')\n if (radioHigh.checked) return 3;\n else if (radioMed.checked) return 2;\n else if (radioLow.checked) return 1;\n }\n const notes = newTaskData[1].value;\n const _currentTask = new Task(currentProject.id, currentTask.id, `${name}`, `${notes}`, `${dueDate}`, +priority(), false);\n const overlay2 = document.querySelector('#overlay2');\n overlay2.style.display = 'none';\n currentProject.addTask(_currentTask);\n ProjectLibrary.getSharedInstance().saveProject(currentProject);\n DomOutput.loadTaskList(currentProject);\n document.querySelector('#newTaskData').reset();\n }", "function create() {\n // var name = [ 'tobi', 'loki', 'jane', 'manny' ][ Math.random() * 4 | 0 ];\n // console.log( '- creating job for %s', name );\n // jobs.create( 'video conversion', {\n // title: 'converting ' + name + '\\'s to avi', user: 1, frames: 200\n // } ).save();\n // setTimeout( create, Math.random() * 3000 | 0 );\n}", "_submitData(event) {\n\n // prevent submit form\n event.preventDefault();\n\n if( !this._controlDataBeforeSend() ) {\n document.body.scrollTop = document.documentElement.scrollTop = 0;\n return;\n }\n\n //let xhr = new XMLHttpRequest();\n let data = {\n name: this.options.title,\n description: this.options.describe,\n clients: this.options.data\n };\n\n var xhr = $.ajax({\n type: \"POST\",\n url: this._config.url,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n data: JSON.stringify(data)\n });\n\n var complete = false;\n\n xhr\n .done(function() {\n complete = true;\n\n })\n .fail(function() {\n complete = false;\n })\n .always(function() {\n if(complete) {\n window.location = \"/autodialer/tasks?saved\";\n } else {\n noty({\n text: 'К сожалению произошла ошибка, попробуйте ещё раз!'\n });\n }\n });\n }", "async handleSubmit() {\n const template_code = `public ${this.state.output_type_func} ${\n this.state.name_func\n }(${this.state.inputList\n .map(input => {\n return `${input.input_type} ${input.input_name}`;\n })\n .join()})\n{ \n}`;\n\n let newMiniTask = {\n template_code: template_code,\n unit_tests: this.state.unit_tests,\n task_id: this.state.task_id,\n mini_task_name: this.state.name,\n name_func: this.state.name_func,\n output_type_func: this.state.output_type_func,\n point_unlock: 0,\n status: \"chuahoanthanh\",\n vitri: false,\n mini_task_desc: this.state.mini_task_desc,\n level: this.state.level,\n code_point: parseInt(this.state.code_point),\n input_list: this.state.inputList\n };\n axios\n .post(\"https://hocodevn.com/api/v1/minitasks\", newMiniTask)\n .then(function(response) {\n window.location.reload();\n toast(\"Tạo bài thực hành thành công!\", {\n containerId: \"B\"\n });\n console.log(response);\n });\n console.log(newMiniTask);\n }", "ajouterPampmousseMutant()\r\n\t{\r\n\t\t//A faire : question 1\r\n\t}", "submitForm(e) {\n e.preventDefault();\n window.M.updateTextFields();\n let data = Util.getDataElementsForm(e.target, false);\n\n MakeRequest({\n method: 'post',\n url: 'actividad/post',\n data : data\n }).then(response => {\n if (response.error) {\n return Util.getMsnDialog('danger', Util.getModelErrorMessages(response.message));\n }\n\n this.getActivitiesByCategory();\n return Util.getMsnDialog('success', 'Created');\n });\n }", "function submitTask(url, message) {\r\n\r\n // $('#progress-bar-client').show();\r\n // disableButtons();\r\n\r\n $.get(url, function(result){\r\n // $('#progress-bar-client').hide();\r\n // enableButtons();\r\n if(result.sync_already_running){\r\n toastr.warning('Task already processing');\r\n }\r\n else if(result.sync_already_in_queue){\r\n toastr.warning('Task already in the queue');\r\n }\r\n else{\r\n \ttoastr.info(message || 'Task added to the queue.');\r\n }\r\n\r\n\r\n // lastTasksAmount[selectedDevice.details['_id']] = 1;\r\n // refreshTaskQueue(callback);\r\n });\r\n }", "function submitModalEdit(){\n let title = document.querySelector(\"#titleInputProjEdit\").value\n closeModalEdit()\n emitterProjEdit.emit(\"editProj\", title)\n }", "function genWorkRequest(){\n\tvar controller = View.controllers.get('abEditActionCtrl');\n\tvar form = View.panels.get('abEditAction_form');\n\tvar objChk = document.getElementById(\"generateWorkRequest\");\n\tif(objChk.checked == 1){\n\t\tform.setFieldValue(\"activity_log.autocreate_wr\", \"1\");\n\t}else{\n\t\tform.setFieldValue(\"activity_log.autocreate_wr\", \"0\");\n\t}\n}", "function newJob(client, data) {\n console.log(\"data new job :\"+data);\n var job = new Job(JSON.parse(data));\n qh.addJob(job);\n}", "function twpro_clickList() {\r\n\t\tif (TWPro.twpro_failure) return;\r\n\t\tif (document.getElementById('twpro_wait').text != TWPro.lang.CALCJOB && document.getElementById('twpro_wait').text != TWPro.lang.CHOOSEJOB) {\r\n\t\t\tdocument.getElementById('twpro_wait').text = TWPro.lang.CALCJOB;\r\n\t\t\twindow.setTimeout(TWPro.twpro_updateList, 0);\r\n\t\t}\r\n\t}", "function submitWorkout(e) {\n if (e.target.classList.contains(\"live-start\")) {\n // Form variables\n const name = ui.workoutName.value,\n activity = ui.workoutActivity.value;\n\n // Validation\n if (name === \"\" || activity === \"\") {\n // Alert\n ui.showAlert(\"Please fill in required fields\", \"alert alert-danger\");\n } else {\n // Alert\n ui.showAlert(\n \"Workout started\",\n \"alert alert-success fas fa-chevron-down d-flex\"\n );\n\n // Input data\n ui.workoutLive();\n\n // Clear fields\n ui.clearFields();\n\n // Disable input fields & buttons\n ui.disableFields();\n\n // Cancel || Finish\n document.querySelector(\".live-data\").addEventListener(\"click\", e => {\n if (e.target.classList.contains(\"finish\")) {\n // Time zone offset in milliseconds\n const tzoffset = new Date().getTimezoneOffset() * 60000;\n // 'yyyy-MM-ddTmm:ss:msms'\n const localISOTime = new Date(Date.now() - tzoffset)\n .toISOString()\n .slice(0, -1);\n\n // current date\n const curDate = new Date();\n // current Hours\n const hours = curDate.getHours();\n // Current Minutes\n const minutes = curDate.getMinutes();\n\n // Starting Hours\n const startHours = parseInt(\n e.target.previousElementSibling.previousElementSibling.previousElementSibling.firstElementChild.nextElementSibling.textContent.substring(\n 0,\n 2\n )\n ),\n // Starting Minutes\n startMinutes = parseInt(\n e.target.previousElementSibling.previousElementSibling.previousElementSibling.firstElementChild.nextElementSibling.textContent.substring(\n 3,\n 5\n )\n );\n\n // Difference between hours\n let diffHours = Math.abs(startHours - hours);\n // Add leading zeros\n if (diffHours < 10) {\n diffHours = `0${diffHours}`;\n }\n\n // difference between minutes\n let diffMinutes = Math.abs(startMinutes - minutes);\n // Add leading zeros\n if (diffMinutes < 10) {\n diffMinutes = `0${diffMinutes}`;\n }\n\n const timeValue = `${diffHours}:${diffMinutes}`,\n // Data variables\n name = e.target.parentElement.firstElementChild.textContent,\n activity =\n e.target.parentElement.firstElementChild.nextElementSibling\n .nextElementSibling.textContent,\n // \"yyyy-MM-dd\" from localISOTime\n date = localISOTime.substring(0, 10),\n // Current time - start time = duration\n time = localISOTime.substring(11, 16),\n // \"hh:mm\" from localISOTime\n duration = timeValue,\n distance =\n e.target.previousElementSibling.previousElementSibling\n .firstElementChild.textContent,\n notes = e.target.previousElementSibling.textContent,\n id = ui.idInput.value,\n data = {\n name,\n activity,\n date,\n time,\n distance,\n duration,\n notes\n };\n\n http\n .post(\"http://localhost:3000/workouts\", data)\n .then(data => {\n // Show alert\n ui.showAlert(\"Workout added\", \"alert alert-success\");\n\n // Enable fields, remove div\n ui.enableFields();\n\n // Call workouts including the new one\n getWorkouts();\n })\n .catch(() => {\n // Error message\n ui.showAlert(\n \"Failed. Please try again later\",\n \"alert alert-danger\"\n );\n });\n } else if (e.target.classList.contains(\"cancel\")) {\n // Alert\n ui.showAlert(\"Workout Cancelled\", \"alert alert-success\");\n\n // Enable fields, remove div\n ui.enableFields();\n }\n });\n }\n }\n\n // Submit Workout\n else if (e.target.classList.contains(\"workout-submit\")) {\n // Form variables\n const name = ui.workoutName.value,\n activity = ui.workoutActivity.value,\n date = ui.workoutDate.value,\n time = ui.workoutTime.value,\n distance = ui.workoutDistance.value,\n duration = ui.workoutDuration.value,\n notes = ui.workoutNotes.value,\n id = ui.idInput.value,\n data = {\n name,\n activity,\n date,\n time,\n distance,\n duration,\n notes\n };\n\n // Validate Form data\n if (name === \"\" || activity === \"\" || date === \"\" || time === \"\") {\n // Alert\n ui.showAlert(\"Please fill in required fields\", \"alert alert-danger\");\n } else {\n // Check for hidden ID input value\n if (id === \"\") {\n // Post request\n http\n .post(\"http://localhost:3000/workouts\", data)\n .then(data => {\n // Show alert\n ui.showAlert(\"Workout added\", \"alert alert-success\");\n\n // Clear fields\n ui.clearFields();\n\n // Call workouts including the new one\n getWorkouts();\n\n // Enable \"Live Workout\"\n document.querySelector(\".live-workout\").disabled = false;\n })\n .catch(() => {\n // Error message\n ui.showAlert(\n \"Failed. Please try again later\",\n \"alert alert-danger\"\n );\n });\n } else {\n // Edit post // Put request\n http\n .put(`http://localhost:3000/workouts/${id}`, data)\n .then(data => {\n // Show alert\n ui.showAlert(\"Workout edited\", \"alert alert-success\");\n\n // Change the state back to \"add\"\n ui.changeFormState(\"add\");\n\n // Call workouts including the new one\n getWorkouts();\n\n // Enable buttons\n document.querySelector(\".live-workout\").disabled = false;\n })\n .catch(() => {\n // Show error alert\n ui.showAlert(\n \"Failed. Please try again later\",\n \"alert alert-danger\"\n );\n });\n }\n }\n }\n\n e.preventDefault();\n}", "function submitJob(params, success, failure) {\r\n\t\tvar request = new XMLHttpRequest();\r\n\t\trequest.open(\"POST\", \"http://api.captchatrader.com/submit\", true);\r\n\t\trequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\r\n\t\trequest.setRequestHeader(\"Content-length\", params.length);\r\n\t\trequest.setRequestHeader(\"Connection\", \"close\");\r\n\t\trequest.onreadystatechange = function() {\r\n\t\t\tif(request.readyState == 4 && request.status == 200) {\r\n\t\t\t\tvar response = eval(request.responseText);\r\n\t\t\t\tif(response[0] == -1) {\r\n\t\t\t\t\tif(failure) {\r\n\t\t\t\t\t\tfailure(response[1]);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\t_activeJobId = response[0];\r\n\t\t\t\t\tsuccess(response[1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\t\trequest.send(params);\r\n\t}", "newCommonTask () {\n\t\tconst { dispatch, auth } = this.props\n\t\tconst assignee = Users.getUserById(auth.user.id)\n\n\t\tREST.rm(`issues.json`, data => {\n\t\t\tdispatch(addIssue(data.issue))\n\t\t\tREST.gl(`projects/${systems.gitlab.projectId}/issues`, data => {\n\t\t\t\tthis.newWrapper.style.display= 'none'\n\t\t\t\tthis.newDescription.value = ''\n\t\t\t\tthis.newTitle.value = ''\n\t\t\t\tdispatch(addGitlabIssue(data))\n\t\t\t}, 'POST', {\n\t\t\t\tlabels: 'To Do,' + (assignee.ids.gl === 4 ? 'Frontend' : 'Backend'),\n\t\t\t\tassignee_id: assignee.ids.gl,\n\t\t\t\ttitle: `${data.issue.id} - ${this.newTitle.value}`,\n\t\t\t\tdescription: this.newDescription.value,\n\t\t\t})\n\t\t}, 'POST', {\n\t\t\tissue: {\n\t\t\t\tproject_id: systems.redmine.projectId,\n\t\t\t\tstatus_id: statuses.idle.rm,\n\t\t\t\tsubject: this.newTitle.value,\n\t\t\t\tdescription: this.newDescription.value,\n\t\t\t\tassigned_to_id: assignee.ids.rm,\n\t\t\t}\n\t\t})\n\t}", "function acceptJob() {\n destroyCefBrowserHelper(jobInfoBrowser);\n API.triggerServerEvent(\"start_gas_trucking_job\");\n}", "function setJobDescrInfo(data) {\n // TODO: move this global to getChanData success\n currentRole = data.role;\n\n // insert asignment basic info to rpoper places\n $(creatorNameElement).html(data.creator_name);\n $(jobDateElement).html(data.job_date);\n $(subjectElement).text(data.subject);\n $(langFromElement).html(data.lang_from);\n $(langToElement).html(data.lang_to);\n $(qualificationElement).html(data.qualification);\n $(startDateElement).html(data.formated_date);\n $(genderElement).html(data.gender);\n $(startTimeElement).html(data.start_time);\n $(finishTimeElement).html(data.finish_time);\n\n // make appropriate job type block visible\n // remove all unappropriate job type blocks\n switch (data.job_type) {\n case 0: // video assignment\n $(jobTypeContVideo).removeClass(exampleClass);\n $(jobTypeContExample).remove();\n break\n case 1: // phone assignment\n $(jobTypeContPhone).removeClass(exampleClass);\n $(jobTypeContExample).remove();\n break\n case 2: // in person assignment\n // if job type is in person assignment we fill in location details and create map\n $(jobTypeContMeeting).removeClass(exampleClass);\n $(jobTypeContExample).remove();\n $(contactPersonElement).text(data.contact_person);\n $(phoneNumberElement).text(data.phone_number);\n $(locationElement).text(data.location);\n $(extraInfoElement).text(data.extra_info);\n showMapSnippet(data.location, data.lat, data.long);\n break\n case 3: // hub assignment\n // if job has hub type we check user role\n // if current user is interpreter we show info like on in person assignment (address, map etc)\n if (currentRole === 1) {\n $(jobTypeContHubInter).removeClass(exampleClass);\n $(jobTypeContExample).remove();\n $(contactPersonElement).text(data.contact_person);\n $(phoneNumberElement).text(data.phone_number);\n $(locationElement).text(data.location);\n $(extraInfoElement).text(data.extra_info);\n showMapSnippet(data.location, data.lat, data.long);\n } else {\n // if current user is business we show only hub tyle text (without address and map)\n $(jobTypeContHubBusiness).removeClass(exampleClass);\n $(jobTypeContExample).remove();\n }\n \n break\n };\n\n\n // check presence of call details for this assignment (appear only after reward before the call)\n if (data.call_details) {\n // if current user is interpreter and job type is hub type we don't show him call details\n if (currentRole === 1 && data.job_type === 3) {\n $(sessionDetailsCont).remove();\n } else {\n // if current user is interpreter we show phone details\n if (data.job_type === 1) {\n $(sessionPhoneNumber).text(data.call_details.phone_number);\n $(sessionPhoneBooking).text(data.call_details.phone_booking);\n $(sessionPhonePin).text(data.call_details.phone_pin);\n } else {\n // if user is business we remove block with phone details\n $(sessionPhoneBlock).remove();\n }\n // then we fill in call details blocks with appropriate info\n $(sessionDesktopLinkAddress).text(data.call_details.hostname);\n $(sessionDesktopLinkAddress).attr(\"href\", data.call_details.link_to_desktop);\n $(sessionSipAddress).text(data.call_details.sip_address);\n $(sessionSipBooking).text(data.call_details.sip_booking);\n $(sessionSipPin).text(data.call_details.sip_pin);\n $(sessionLyncAddress).text(data.call_details.lync_address);\n $(sessionLyncPin).text(data.call_details.lync_pin);\n $(sessionDetailsCont).removeClass(exampleClass);\n }\n } else {\n // if server hasn't provided us with call info we remove call info block\n $(sessionDetailsCont).remove();\n }\n\n if ((data.attenders && data.attenders.length > 0) && (data.permission && data.permission.can_manage_job)) {\n $(chosenAttenderList + \" *\").remove();\n makeChosenAttendersList(data.attenders);\n $(attendersSection).removeClass(\"is-hidden\");\n } else {\n $(attendersSection).remove();\n }\n if (data.permission && !data.permission.can_init_event) {\n $(\".js-cancel-job-popup\").remove();\n }\n $(\".js-assign-descr-cont\").removeClass(\"is-hidden\");\n }", "function ajuda(endereco)\r\n{\r\n // var nomeAjuda = '../ajuda/' + diretorioAjuda + '/ajuda.html#' + link + opcaoAjuda;\r\n janelaUrl = endereco;\r\n janelaTamanho = \"M\"\r\n janelaTarget = \"jaAjuda\";\r\n janela()\r\n}", "function job(){\n\tvar title= document.getElementById(\"jobTitle\").value;\n\n\tif(title.length>1)\n\t\tdocument.getElementById(\"jobTitleInsert\").innerHTML = title;\n\telse\n\t\tdocument.getElementById(\"jobTitleInsert\").innerHTML= \"ERROR: NO JOB TITLE!!\";\n}", "function submitForm()\n\t {\t\t\n\t\t\t\tvar data = $(\"#updatearqueocaja\").serialize();\n\t\t\t\tvar id= $(\"#updatearqueocaja\").attr(\"data-id\");\n\t\t var codarqueo = id;\n\t\t\t\t\n\t\t\t\t$.ajax({\n\t\t\t\t\n\t\t\t\ttype : 'POST',\n\t\t\t\turl : 'forarqueo.php?codarqueo='+codarqueo,\n\t\t\t\tdata : data,\n\t\t\t\tbeforeSend: function()\n\t\t\t\t{\t\n\t\t\t\t\t$(\"#error\").fadeOut();\n\t\t\t\t\t$(\"#btn-update\").html('<i class=\"fa fa-refresh\"></i> Verificando ...');\n\t\t\t\t},\n\t\t\t\tsuccess : function(data)\n\t\t\t\t\t\t {\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(data==1){\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t$(\"#error\").fadeIn(1000, function(){\n\t\t\t\t\t\t\t\t\t\t\t\n\t$(\"#error\").html('<center><div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button><span class=\"fa fa-info-circle\"></span> LOS CAMPOS NO PUEDEN IR VACIOS, VERIFIQUE NUEVAMENTE POR FAVOR !</div></center>');\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t$(\"#btn-update\").html('<span class=\"fa fa-edit\"></span> Actualizar');\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\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\t\telse if(data==2){\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t$(\"#error\").fadeIn(1000, function(){\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\n\t$(\"#error\").html('<center><div class=\"alert alert-warning\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button><span class=\"fa fa-info-circle\"></span> YA EXISTE UN ARQUEO ABIERTO DE ESTA CAJA, VERIFIQUE NUEVAMENTE POR FAVOR !</div></center>');\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t$(\"#btn-update\").html('<span class=\"fa fa-edit\"></span> Actualizar');\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\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\t\telse{\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t$(\"#error\").fadeIn(1000, function(){\n\t\t\t\t\t\t$(\"#error\").html('<center>'+data+' </center>');\n\t\t\t\t\t\t$('#btn-update').attr(\"disabled\", true);\n\t\t\t\t\t\t$(\"#btn-update\").html('<span class=\"fa fa-edit\"></span> Actualizar');\n\t\t\t\t\t setTimeout(\"location.href='arqueoscajas'\", 5000);\n\t\t\t\t\n\t\t\t\t\t\t\t\t\t});\n\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\t\t\t\t});\n\t\t\t\treturn false;\n\t\t}", "createJobs () {\n }", "function submitTask(title, detail, date){\n taskInput.current.value = \"\";\n detailInput.current.value = \"\";\n dateInput.current.value = \"\";\n const task = {\n author_id: currentUser._id,\n title: title,\n detail: detail,\n dueDate: date\n };\n API.submitTask(task)\n .then(response=>{\n console.log(response);\n getTasks();\n }).catch(err=>{\n console.log(err);\n });\n }", "function create_build_ota_link_job(username, build_id, go_to)\n{\n $.ajax({\n url: \"/\"+username+\"/builds/\"+build_id+\"/build_ota_link\",\n cache: false,\n type: \"GET\",\n beforeSend:function(result){\n $('#spin_rhohub').show();\n },\n success: function(result){\n if(result != 'failed')\n {\n rhohub_build_timer = setInterval(function() {\n if(rhohub_build_timer !=\"stop\") check_build_ota_link_finished_job(username, build_id, go_to);\n },1000);\n }\n else\n {\n rhohub_build_timer =\"stop\";\n $('#spin_rhohub').hide();\n show_modal_message('There was an error adding the RhoMobile build, please try again.','modal_error')\n }\n }\n });\n}", "startOptimization() {\n this.worker.postMessage({'cmd': 'start', 'courses': this.courses, 'maxHours': this.maxHours});\n }", "_submitForm() {\n\t\tconst { inputName, inputBio, inputLocation, inputImage } = this.state;\n\t\tconst { updateAbout, userId, getAbout, routeId } = this.props;\n\t\tupdateAbout(userId, inputName, inputBio, inputLocation, inputImage, (success) => {\n\t\t\tif (success) {\n\t\t\t\tthis._closeEdit();\n\t\t\t\tgetAbout(routeId); // Might be redundant\n\t\t\t}\n\t\t});\n\t}", "function puliziaForm() {\n var action = $(this).data(\"href\");\n // Invio il form\n $(\"#formInserisciPrimaNotaLibera\").attr(\"action\", action)\n .submit();\n }", "function newJob (){\n var job = jobs.create('new_job');\n job.save();\n}", "function handleSubmit(e) {\n e.preventDefault()\n\n axios.post('http://localhost:3001/orders/finished', {\n email: form.email,\n\n order_id: orderData.order_id,\n\n firstName: form.firstName,\n lastName: form.lastName,\n address: form.address,\n depto: form.depto,\n phone: form.phone,\n products: products,\n discount: form.discount\n\n }).then((res) => console.log('oka'))\n\n\n axios.put(`http://localhost:3001/orders/${orderData.order_id}`, {\n state: \"Procesando\"\n }).then(() => setshowPostVenta(true))\n\n }", "onClick() {\n this.sendRequest(this.state.submissionId);\n }", "onSubmitHandler(ev) {\n //Prevent refreshing the page\n ev.preventDefault();\n createMeeting(\n this.props.location.pathname.split('/')[2]\n ,this.state.topic,\n this.state.time,\n this.state.date,\n this.onCreateSuccess);\n }", "function updateTaskHandler(){\n let id = $(this).data('id');\n updateTask(id);\n\n // Notification of completion\n alert('NICE JOB!')\n\n} // end updateTaskHandler", "handleUserSubmit(feedback) {\n feedback.id = Date.now();\n //post len serve xu li\n axios.post(this.props.url, feedback)\n .then(alert(\"Gửi thành công\"))\n .catch(err => {\n console.error(err);\n });\n \n }", "function _submit() {\n let type = dialog.typeSelected;\n let content = dialog.annotations[type];\n\n // Pigrizia...\n if (type === 'denotesRhetoric') {\n content.rhetoric = _expandRhetoricURI(content.rhetoric);\n }\n\n content.type = type;\n dialog.provenance.time = new Date(); // Vogliamo l'ora aggiornata\n content.provenance = dialog.provenance;\n content.fragment = dialog.fragment;\n content.url = model.docUrl;\n content.subject = dialog.subject;\n let newAnno = newAnnotationService.generateAnnotation(content);\n newAnnotationService.saveLocal(newAnno);\n $mdToast.showSimple('Annotazione modificata.');\n $mdDialog.hide();\n }", "function requeueJob() {\n var dialogInstance = $uibModal.open({\n templateUrl: 'components/confirmation-dialog/confirmation-dialog.view.html',\n controller: 'ConfirmationDialogController',\n controllerAs: 'confirmationDialogCtrl',\n resolve: {\n confirmationText: function() {\n return 'This will re-submit the job for execution. Are you sure?';\n }\n }\n });\n\n dialogInstance.result.then(function(accept) {\n if (accept) {\n var jobData = vm.job;\n JobsManager.createJob(jobData).then(function(job) {\n scope.jobId = job.id;\n vm.job = job;\n });\n }\n });\n }", "handleSubmit(jira) {\n this.props.onSubmit({\n \"clusterName\": this.props.data.clusterName,\n \"clusterId\": this.props.data.clusterId,\n \"account\": this.props.data.account,\n steps: this.state.steps,\n \"role\": this.props.data.role,\n \"jiraTicket\": jira\n })\n this.toggleDialog();\n }", "function setTrigger() {\r\n\t$each(MoCheck.aktJobs, function(job, index) {\r\n\t\tvar aktJobId = job.pos.x + '_' + job.pos.y;\r\n\t\t\t\t\r\n\t\t/* checks if the player can do the job and sets the way time*/\r\n\t\tvar reload_task_points = Tasks.reload_task_points(job.jobCalc.task_skills, job.jobCalc.malus, 'job', job.window, job.jobCalc.jobId);\r\n\t\t\r\n\t\treload_task_points();\r\n\t\tjob.refresh_way_time();\r\n\r\n\t\tvar eventname = 'windowJob_' + aktJobId;\r\n\t\tWEvent.register('jobCalcDuration_' + aktJobId, MoCheck.durationChanged.store(job), eventname);\r\n\t\tWEvent.register('character_speed_changed', job.refresh_way_time.store(job), eventname);\r\n\t\tWEvent.register('character_values_changed', reload_task_points.store(job), eventname);\r\n\t\tWEvent.register('character_values_changed', job.calcDuration.store(job), eventname);\r\n\t\tjob.calcDuration();\r\n\t});\r\n}", "_addJob() {\n this.core.log.verbose(`Saving new job ${this.id} for ${this.queue}`);\n return this.core.client\n .addjob(\n this._toQueueKey('jobs'),\n this._toQueueKey('waiting'),\n this._toQueueKey('stats'),\n this.toData(),\n !!this.options.unique,\n this.id\n ).then((id) => {\n if (this.options.unique && id === 0) {\n this.status = 'duplicate';\n return Promise.reject(new Error(`ERR_DUPLICATE: Job ${this.id} already exists, save has been aborted.`));\n }\n\n this.core.log.verbose(`Saved job for ${this.queue}`);\n\n this.id = id;\n this.status = 'saved';\n return Promise.resolve(this.toObject(true));\n });\n }", "function Report_problem(name, topic, namefile, post_id, uid)\n {\n $(\"#myModal1\").modal(\"show\");\n var Div, listsp, Input;\n\n document.getElementById(\"tieudemodal\").innerHTML += '<label style=\"color:#59CB86;\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"'+uid+'\"><i>'+name+'</label></a>';\n Div = document.getElementById(\"phanhoivebaidang\");\n listp = Div.getElementsByTagName(\"p\");\n Input = Div.getElementsByTagName(\"input\");\n\n Input[0].value = post_id;//lay gia tri vao in put type hidden in modal\n listp[0].innerHTML += \"<b style='font-size:110%;'>\"+topic+\"</b>\";\n listp[1].innerHTML += \"<b style='font-size:110%;'>\"+namefile+\"</b>\";\n }", "function shareJob( elem ){\n\tvar usersStr = \"\";\n\t$.each( $(\"input.gmail_cb:checked\"), function( key, value ) {\n\t\tusersStr += $(value).attr(\"rel\")+\",\";\n\t\t});\n\tvar element = elem;\n\t$(elem).hide();\n\tvar idd = addLoadingImage( $(elem), 'before', 'loading_medium_purple.gif', 94, 20 );\n\tjQuery.ajax({\n url: \"/\" + PROJECT_NAME + \"job/share-job\",\n type: \"POST\",\n dataType: \"json\",\n data: { 'job_id' : $(\"#UjobId\").val(), 'users_str' : usersStr },\n//\t\tcache: false,\n timeout: 50000,\n success: function(jsonData) {\n \t//Show dialog after sharing.\n \tif( jsonData == 1 )\n \t{\n \t\t$('span#'+idd).remove();\n \t\t$(element).fadeIn();\n \t\t$('div#gmail_popup').bPopup().close();\n \t\tshowDefaultMsg( \"Job shared successfully.\", 1 );\n \t}\n \telse\n \t{\n \t\t$('span#'+idd).remove();\n \t\t$(element).fadeIn();\n \t\t$('div#gmail_popup').bPopup().close();\n \t\tshowDefaultMsg( \"Job not shared, please try again.\", 2 )\n \t}\n }\n\t});\n}", "function submit_fillter(){\n\n\t}", "static make_job(explicitly_start_job=false){\n let the_dex = (window.default_robot ? Dexter.default : Dexter.dexter0)\n let name = ((platform === \"dde\") ? \"dui2_for_\" + the_dex.name : \"dexter_user_interface2\") //the job engine Job name must match the file name (sans .js\")\n if (Job[name] && Job[name].is_active()) { //we're redefining the job so we want to make sure the\n //previous version is stopped first\n Job[name].stop_for_reason(\"interrupted\", \"User is redefining this job.\")\n setTimeout(function(){ dui2.make_job(true) }, 200)\n }\n else { //hits when job is undefined, or is defined but not active.\n //if job is defined but not active, it will be redefined,\n //with a new job_id. This should be fine.\n let new_job = new Job({\n name: name,\n robot: new Brain({name: \"dui_brain\"}),\n when_do_list_done: \"wait\",\n do_list: [dui2.init,\n the_dex.empty_instruction_queue() //needed because the next instruction may need to look a the measured_angles, and we want them updated to where dexter is really at.\n ]\n })\n if(explicitly_start_job) {\n new_job.start()\n }\n // else {} //this job will get started anyway via define_and_start_job which is called by dui2_id.onclick\n }\n }", "function submitAnswers(e) {\n var app = UiApp.getActiveApplication();\n \n /* Restauracao dos elementos de Callback */\n var ticket = e.parameter.ticket;\n var reference = e.parameter.referenceListBox;\n var escolarity = e.parameter.escolarityListBox;\n var wroteDown = e.parameter.wroteDownListBox;\n \n /* Abertura da planilha de controle de respostas */\n var answerSheet = SpreadsheetApp.openById(answerSSKey).getActiveSheet();\n \n /* Obtencao da posicao dos dados do usuario na planilha de controle de respostas */\n var currentUserPosition = getUserPosition(ticket, answerSheet);\n \n /* Adicao das respostas do usuario na planilha de controle de respostas */\n answerSheet.getRange(currentUserPosition, 8).setValue(reference);\n answerSheet.getRange(currentUserPosition, 9).setValue(escolarity);\n answerSheet.getRange(currentUserPosition, 10).setValue(wroteDown);\n \n /* Exibicao de outra mensagem de agradecimento e finalizacao do experimento */\n app.getElementById('submitButton2').setVisible(false);\n app.getElementById('thanksLabel').setVisible(true).setStyleAttribute('color','blue');\n \n return app;\n}", "function publish_finish(e){\n worder_content = e.target.parentNode.parentNode.children[0].textContent\n line = document.getElementsByClassName('min-line')\n circle = document.getElementsByClassName('min-circle')\n for(x=0;x<line.length;x++){\n line[x].className = 'min-line line_active'\n }\n for(i=0;i<circle.length;i++){\n circle[i].className = \"min-circle round_active\"\n }\n\n e.target.parentNode.previousSibling.children[0].textContent = \"已处理\"\n e.target.parentNode.previousSibling.children[0].className = \"label label-success\"\n time = e.target.getAttribute('time')\n postJSON(update_work_order_status_url,{\"time\":time}).then(function(data){\n if(data.status == 'success'){\n showSuccessNotic()\n postJSON(work_order_finish_notify,{\"title\":worder_content,\"status\": '已发布完成'})\n }else{\n showErrorInfo('更新出现异常')\n postJSON(work_order_finish_notify,{\"title\":worder_content,\"status\": '发布出现异常,紧急联系值班人员!'})\n }\n })\n}", "function promptForRenewingAJob( elem, jobId )\n{ \n\t$('div#append_div').remove();\n\t__addOverlay();\n\t$.ajax({\n\t\turl : \"/\" + PROJECT_NAME + \"job/get-job-detail\",\n\t\tmethod : \"POST\",\n\t\tdata : { 'job_id' : jobId },\n\t\ttype : \"post\",\n\t\tdataType : \"json\",\n\t\tbeforeSend: function(){\n\t\t\t\n\t\t },\n\t\tsuccess : function(jsonData) \n\t\t{\n\t\t\tvar html = '';\n\t\t\thtml += '<div id=\"append_div\">';\n\t\t\thtml += '<div class=\"chkbx-img img\" style=\"float: left; width: auto;\">';\n\t\t\thtml += '<div style=\"width: 60px; border: 1px solid rgb(196, 196, 196); vertical-align: middle; text-align: center; margin: auto; float: none;\">';\n\t\t\thtml += '<img style=\"max-height: 60px; max-width: 60px;\" src=\"'+PUBLIC_PATH+'/Imagehandler/GenerateImage.php?image='+ jsonData.job_image +'&amp;h=60&amp;w=60\">';\n\t\t\thtml += '</div>';\n\t\t\thtml += '</div>';\n\t\t\thtml += '<div class=\"mid\" style=\"margin: 0px 0px 0px 10px; float: left; text-align: left; width: 330px;\">';\n\t\t\thtml += '<h4 style=\"cursor: default;\">'+ jsonData.job_title +' | <font>'+ jsonData.job_reference +'</font></h4>';\n\t\t\thtml += '<p style=\"cursor: default;\">'+jsonData.company_name+'</p>';\n\t\t\thtml += '<p style=\"cursor: default;\">'+ jsonData.industryTitle +', '+ jsonData.job_location +'</p>';\n\t\t\thtml += '<p style=\"cursor: default;\">'+ jsonData.salary +' | '+ jsonData.jobTypeTitle +' | '+ jsonData.experience +'</p>';\n\t\t\thtml +='</div>';\n\t\t\thtml += '<div style=\"width: 100%; float: left; text-align: left; margin: 10px 0px; border-top: 1px solid rgb(149, 149, 149); padding: 10px 0px;\" class=\"right\">';\n\t\t\thtml += '<div class=\"top\" style=\"width: auto; float: left;\">Posted Job : '+ jsonData.postedDate +' </div>';\n\t\t\thtml += '<div id=\"save_job_button_holder_1067\" class=\"bot\" style=\"float: right;\">';\n\t\t\thtml += 'Expired Job : '+ jsonData.expiry_date +'';\n\t\t\thtml += '</div>';\n\t\t\thtml += '</div>';\n\t\t\thtml += '<div style=\"width:100%; float:right;\">New expiry date :</div>';\n\t\t\thtml += '</div>';\n\t\t\t$(\".job_expiry_date\").parent().prepend(html);\n\t\t\t__removeOverlay();\n\t\t}\n\t});\t\n\t\n $( \"div#renew_job_dialog_box\" ).data('renew_select_box', elem).dialog( \"open\" );\n}", "function addOrcamentoCoberturaIseg(){\r\n\tsubmitFormAjax('#formOrcCobIseg', getContextApp()+'/orcamentoSegAuto/addOrcamentoCoberturaIseg.action', '#coberturasIseg');\r\n}", "async function handleSubmit() {\n await api\n .post(`/delivery/${deliveryData.id}/problems`, {\n description: textInput,\n courier_id: profile.id,\n })\n .then(\n () => {\n Alert.alert('Sucesso!', 'Problema cadastrado com sucesso!');\n setTextInput('');\n },\n (error) => {\n console.tron.log(error);\n Alert.alert(\n 'Erro!',\n 'O problema não foi registrado. Por favor, tente mais tarde!'\n );\n }\n );\n }", "async handleFormSubmit() {\n event.preventDefault();\n var datas = {\n work_department: this.state.work_department\n };\n this.props\n .editProfile(this.props.user_id, datas)\n .then(() => {\n this.handleClose();\n this.props.setMessage({\n message: 'Votre poste est mis à jour!'\n });\n })\n .catch((err) => {\n console.log(err);\n });\n }", "_submitITOInfoToServer(ito)\r\n\t{\r\n\t\tvar self=this;\r\n\t\tthis.adminUtility.updateITOInfo(ito)\r\n\t\t.done(function(){\r\n\t\t\talert(\"The ITO information update success.\");\r\n\t\t\tself.showITOTable();\r\n\t\t})\r\n\t\t.fail(function(){\r\n\t\t\talert(\"The ITO information update failure.\");\r\n\t\t});\r\n\t}", "function createNewTask() {\n\n\tvar parms = centerParms(600,450,1) + \",scrollable=yes,resizable=yes\";\n\n\tvar url = \"index.php?module=managetasks&hideHeader=1\";\n\tvar ref = window.open(url,\"_task\",parms);\n\tref.focus();\n\n}", "function submitEditMeme() {\n var $row = memeTable.getSelectedRow(),\n url = siteUrl + 'meme/',\n method = 'PUT',\n data = {\n 'name': $('#meme-edit-name').val(),\n 'top_text_template': $('#meme-edit-toptemplate').val(),\n 'bottom_text_template': $('#meme-edit-bottomtemplate').val(),\n 'tags': $('#meme-edit-tags').val().split(' '),\n 'is_hidden': $('#meme-edit-hidden').val()\n };\n \n if ($row === null || $row.length === 0) {\n return bootbox.alert('You must select a row to edit.');\n }//end if\n \n url += $row.data('row-id');\n \n $.ajax({'url': url, 'type': method, 'data': data})\n .done(function () {\n $editModal.modal('hide');\n self.refreshGrid();\n })\n .fail(function () {\n bootbox.alert('There was a problem updating the meme.');\n });\n }//end submitEditMeme()", "queueJob(url, msg) {\n const newId = ++this.globalMsgId;\n var job = {\n \"url\": url,\n \"msg\": msg,\n \"id\": newId\n };\n this.jobs.push(job);\n\t\tconst thiz = this;\t\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\tthiz.resolves[newId] = resolve\n\t\t\tthiz.rejects[newId] = reject\n thiz.nextJob();\n\t\t}) \n }", "function addJob(x, y) {\r\n\t/* Jobcoords in Array aufnehmen TODO das geht doch auch schoener... */\r\n\tvar job = new Object();\r\n\tjob.pos = new Object();\r\n\tjob.pos.x = x;\r\n\tjob.pos.y = y;\r\n\t\r\n\tMoCheck.getJobCoords().splice(0, 0, job);\r\n\t\r\n\t/* Arbeit in Cookie speichern */\r\n\tthis.setCookie();\r\n\t\r\n\t/* Fenster schlieГџen, auslesen und neu oeffnen */\r\n\tMoCheck.getJobInfoFromServer(x, y);\r\n\t\r\n\tnew HumanMessage(MoCheck.getString('message.addedWork'), {type:'success'});\r\n}", "afterSubmit(knot) {}", "function submitEditNotes(ele){\n\t\t\tvar popup = document.getElementsByClassName(\"edit-notes-form\")[0],\n\t\t\t\tupdatedNotes = ele.parentNode.getElementsByTagName(\"textarea\")[0].value;\n\n\t\t\tif(!updatedNotes) updatedNotes = \"There are no notes for this event.\"\n\n\t\t\t// Update notes\n\t\t\tcurrentStepNode.setAttribute(\"data-notes\", updatedNotes);\n\n\t\t\t// Save notes to database\n\t\t\tsaveAction.enqueue( makeJsonFromNode(currentStepNode));\n\n\t\t\t// Remove popup\n\t\t\tremoveEditNotes(popup);\n\t\t}", "createMiningJobs() {}", "submit(work) {\n this.socket.send(JSON.stringify({\n method: \"submit\",\n params: work\n }));\n }", "submit(values) {\n const now = moment().format('YYYY-MM-DD HH:mm:ss');\n let create = (this.props.location.pathname).substring(11, 25);\n create = create.replace(/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/, '$1-$2-$3 $4:$5:$6');\n axios({\n method: 'post',\n url: 'https://agoquality-tmpw.aero.org/secure/TRAASweb/TRAAS.pl',\n data: {\n values,\n ID: this.id,\n Last_Modified: now,\n Create_Date: create,\n },\n })\n .then(() => {\n this.props.dispatch(toggleModal(true));\n window.open(`https://agoquality-tmpw.aero.org/tcpdf/examples/TRAAS_New.php?ID=${this.id}`);\n })\n .catch((err) => { console.log(err); });\n }", "function onCreateSubmit(event) {\n event.preventDefault();\n const newTestimony = {\n userTestimony: $(\"#userTestimony\").val(),\n userDisplayName: $(\"#userDisplayName\").val()\n };\n HTTP.createTestimony({\n authToken: STATE.authUser.authToken,\n newTestimony: newTestimony,\n onSuccess: function() {\n $(\".notification\").html(` Testimony was submitted successfully`);\n pastSubmittedTestimonies();\n },\n onError: err => {\n $(\".notification\").html(\n `ERROR: Testimony was not submitted successfully`\n );\n }\n });\n}", "addTaskButtonAction(elementId) {\n let content = this.get('newTaskContent');\n // If there is some content, add the task\n if(content !== null && content !== undefined && content.length > 0) {\n this.actions.createTask.bind(this)(content);\n }\n // If no content just focus or refocus the bar\n else {\n this.actions.focusBar.bind(this)(elementId);\n }\n }", "function setJobDetails(){\n let jobId = JobManager.getCurrentJobId();\n let jobOffer = JobManager.getJobOffer(jobId);\n document.getElementById('jobTitle').innerText = jobOffer.jobTitle;\n document.getElementById('jobType').innerText = jobOffer.jobType;\n document.getElementById('description').innerText = jobOffer.description;\n document.getElementById('skills').innerText = jobOffer.skills;\n document.getElementById('minYears').innerText = jobOffer.minYears;\n document.getElementById('maxYears').innerText = jobOffer.maxYears;\n document.getElementById('minSalary').innerText = jobOffer.minSalary;\n document.getElementById('maxSalary').innerText = jobOffer.maxSalary;\n document.getElementById('location').innerText = jobOffer.location;\n document.getElementById('noOfVacancy').innerText = jobOffer.noOfVacancy;\n document.getElementById('qualification').innerText = jobOffer.qualification;\n}", "function actionRoomReportAbuse(id, $this) {\n var message = \"<div id='reason' class='radio'>\"+\n \"<label><input type='radio' name='reason' value='Propos malveillants' checked>Propos malveillants</label><br>\"+\n \"<label><input type='radio' name='reason' value='Incitation et glorification des conduites agressives'>Incitation et glorification des conduites agressives</label><br>\"+\n \"<label><input type='radio' name='reason' value='Affichage de contenu gore et trash'>Affichage de contenu gore et trash</label><br>\"+\n \"<label><input type='radio' name='reason' value='Contenu pornographique'>Contenu pornographique</label><br>\"+\n \"<label><input type='radio' name='reason' value='Liens fallacieux ou frauduleux'>Liens fallacieux ou frauduleux</label><br>\"+\n \"<label><input type='radio' name='reason' value='Mention de source erronée'>Mention de source erronée</label><br>\"+\n \"<label><input type='radio' name='reason' value='Violations des droits auteur'>Violations des droits d\\'auteur</label><br>\"+\n \"<input type='text' class='form-control' id='reasonComment' placeholder='Laisser un commentaire...'/><br>\"+\n \"</div>\";\n var boxNews = bootbox.dialog({\n message: message,\n title: trad[\"askreasonreportabuse\"],\n buttons: {\n annuler: {\n label: \"Annuler\",\n className: \"btn-default\",\n callback: function() {\n mylog.log(\"Annuler\");\n }\n },\n danger: {\n label: \"Déclarer cet abus\",\n className: \"btn-primary\",\n callback: function() {\n // var reason = $('#reason').val();\n var reason = $(\"#reason input[type='radio']:checked\").val();\n var reasonComment = $(\"#reasonComment\").val();\n //actionOnNews($($this),action,method, reason, reasonComment);\n toastr.info(\"This feature is comming soon !\");\n //$($this).children(\".label\").removeClass(\"text-dark\").addClass(\"text-red\");\n }\n },\n }\n });\n boxNews.on(\"shown.bs.modal\", function() {\n $.unblockUI();\n });\n}", "submitFeedback() {\n submitOverAll({rating: this.feedbackRating, comment: this.feedbackComments, employeeId: this.employeeNumber, employeeName: this.employeeName})\n .then(result => {\n const goback = new CustomEvent('submit', { detail: result});\n this.dispatchEvent(goback);\n })\n .catch(error => {\n this.error = error;\n });\n }", "deleteJob(){\n\n }", "function onMyEdit() {\r\n const ss = SpreadsheetApp.getActiveSpreadsheet();\r\n const sheet = ss.getSheetByName('<SheetName e.g. sheet1>');\r\n const sheetUrl = ss.getUrl();\r\n const cell = sheet.getActiveCell().getA1Notation();\r\n const columnNameInAlphabet = cell.replace(/\\d+/,'');\r\n Logger.log(columnNameInAlphabet);\r\n if ('H' == columnNameInAlphabet) {\r\n const rowNameInNumber = sheet.getActiveCell().getRow();\r\n var RowNumberOfUpdatedStatus = round(rowNameInNumber) - 3;\r\n Logger.log(RowNumberOfUpdatedStatus);\r\n var editedTask = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn())\r\n .getValues()[RowNumberOfUpdatedStatus];\r\n Logger.log(editedTask);\r\n /*\r\n * No.\t: 0\r\n * Task Category : 1\r\n * Task Name ,Assignee, Slack User ID, Due Date,\r\n * Status : 7\r\n */\r\n //No.\r\n var taskNumber = round(editedTask[0]);\r\n //Task Category, カテゴリ\r\n var taskCategory = editedTask[1]; \r\n //Task Name, タスク名\r\n var taskName = editedTask[2];\r\n //Slack User ID of Assignee, 担当者のslackのプロフィールページからコピペするUser ID\r\n var slackId = editedTask[5]; \r\n //Due Date, 締切\r\n var dueDateTime = Moment.moment(editedTask[6]).format('YYYY年MM月DD日 hh時');\r\n //Status, done, doing, or todo???\r\n var status = editedTask[7]; \r\n var contents = writeMessages(taskNumber, taskCategory, taskName, slackId, dueDateTime, status, sheetUrl);\r\n sendMessages(contents);\r\n }\r\n}", "function onEdit(){\n var statusChange = new StatusObject();\n while (true){\n getChangeIndex(statusChange);\n if (statusChange.index == -1){\n return;\n } else {\n var request = new Submission(statusChange.row);\n if (statusChange.status){\n request.status = statusChange.status;\n if (statusChange.status == \"Approve\"){\n updateCalendar(request);\n }\n draftEmail(request);\n sendEmail(request);\n }\n }\n }\n}", "submit() {}", "function handleSubmit(e) {\n e.preventDefault();\n update({\n variables: {\n taskId: id,\n name: state.name,\n description: desc,\n parent: parent?.id,\n status: state.status,\n },\n });\n }", "function userForfeit(e) {\n var app = UiApp.getActiveApplication();\n\n /* Restauracao dos elementos de Callback */\n var ticket = e.parameter.ticket;\n \n /* Abertura da planilha de controle de respostas */\n var answerSheet = SpreadsheetApp.openById(answerSSKey).getActiveSheet();\n \n /* Obtencao da posicao dos dados do usuario na planilha de controle de respostas */\n var currentUserPosition = getUserPosition(ticket, answerSheet);\n \n /* Obtencao da tentativa atual do usuario */\n var tryNumber = Number(answerSheet.getRange(currentUserPosition, 7).getDisplayValue());\n \n /* Registro da tentativa atual do usuario */\n answerSheet.getRange(currentUserPosition, 4 + tryNumber).setValue('DESISTIU');\n\n /* Exibicao da mensagem de agradecimento e desbloqueio da proxima etapa */\n app.getElementById('confirmButton').setVisible(false);\n app.getElementById('forfeitButton').setVisible(false);\n var thanksLabel = app.createLabel('Obrigado pela participação!').setStyleAttribute(\"fontSize\", \"14\");\n thanksLabel.setStyleAttribute('color', 'green');\n app.getElementById('returnGrid').setWidget(1, 0, thanksLabel);\n app.getElementById('returnGrid').resize(2, 2);\n activateSurvey(app);\n \n return app;\n}", "function addInternalExecutiveMeet(){\n // alert(\"hi\");\n document.getElementById('emeetResultMessage').innerHTML ='';\n \n \n document.getElementById(\"emeetHeaderLabel\").style.color=\"white\";\n document.getElementById(\"emeetHeaderLabel\").innerHTML=\"Add Executive Meeting\";\n showRow('emmetAddTr');\n\n var overlay = document.getElementById('exeMeetoverlay');\n var specialBox = document.getElementById('exeMeetspecialBox');\n // hideRow(\"approvedBy\");\n //hideRow(\"tlcommentsTr\");\n // hideRow(\"hrcommentsTr\");\n overlay.style.opacity = .8;\n if(overlay.style.display == \"block\"){\n overlay.style.display = \"none\";\n specialBox.style.display = \"none\";\n }\n else {\n overlay.style.display = \"block\";\n specialBox.style.display = \"block\";\n }\n \n//window.location = \"jobSearch.action\";\n}", "updateTask() { \r\n\r\n }", "doHomework() {\n this.homeworkDone = true;\n }", "function replyAssignment(e) {\n // firstly we get current person id\n var personId = currentActiveDiscussionId,\n // then we pull text from chat texarea\n messageText = $(chatEventsMainCont).find(simpleMsgInput).val();\n // and get \"send message\" btn\n var currentButton = e.target;\n // then we check whether user entered a text or not\n if (messageText.trim()) {\n // if yes we add progress class to pressed btn\n $(currentButton).addClass(\"in-progress\");\n // and send AJAX request to the server\n $.post('/jobs/' + jobId + '/reply', {\n message: {\n text: messageText,\n person_id: personId\n }\n // if server has successfully receive simple msg text\n }).success(function(response) {\n // we get desctop notification text from response\n var desktopNotification = response.notice;\n // get new event for updating view and mutating main data\n var chatEvent = response.event;\n // get subscriber of this assignment chat\n var chat_subscriber = response.chat_subscriber;\n // and get job from response\n // TODO: What is this job???\n var job = response.job;\n // then we show desctop notification for subscribed user\n websocketsInteractionModule.publish_desktop_notification(desktopNotification);\n // and send him happened event\n websocketsInteractionModule.chat_publisher(chatEvent, job, chat_subscriber);\n // then we mutate our main data\n saveNewData(chatEvent);\n // and remove progress state from send msg btn\n $(currentButton).removeClass(\"in-progress\");\n\n // if we get some error as a response\n }).error(function(response) {\n // we properly show this error to user\n var main_error = response.responseJSON.message;\n if (main_error) {\n showErrorsModule.showMessage([main_error], \"main-error\");\n }\n $(currentButton).removeClass(\"in-progress\");\n });\n\n // if user clicked send msg btn without text in textarea\n } else {\n // we simply make textarea empty\n $(chatEventsMainCont).find(simpleMsgInput).val(\"\");\n };\n }", "function gestioneSubmitForm(e) {\n var $form = $('#formAggiornamentoAllegatoAtto');\n var button = $(e.target);\n var action = button.data('submitUrl');\n\n $form.attr('action', action)\n .submit();\n }", "set setJobId(id) {\n this.jobId = id;\n }", "function sendOhioNotification() {\n gso.getCrudService()\n .execute(constants.post,manageEmpUrlConfig.manageEmpApi + manageEmpUrlConfig.manageBaseUrl + manageEmpUrlConfig.resources.managegroup + \"/\" + gso.getAppConfig().companyId + \"/\" + gso.getAppConfig().userId+ \"/ohioemail\", null, function (response) {\n },\n function (data) {\n }\n );\n\n }", "async save() {\n await db.query(\n `UPDATE jobs SET title=$1, salary=$2, equity=$3, company_handle=$4 WHERE id = $5`, [this.title, this.salary, this.equity, this.company_handle, this.id]);\n }", "function onClickBtnModif(e) {\n e.preventDefault();\n\n //On recupere l'identifiant de l'equipe stocker en attribut\n let idEquipe = $(this).attr(\"idequipe\");\n\n //On execute la requete sur le serveur distant\n let request = constructRequest(\"index.php?page=equipemodifws&id=\" + idEquipe);\n\n //En cas de succe de la requete\n request.done(function( infos ) {\n //si les informations sur l'equipe sont definis\n if(infos.element_infos !== undefined) {\n //on modifie la valeur de tout les champ\n $(\"#modif-id\").val(infos.element_infos.id);\n $(\"#modif-libelle\").val(infos.element_infos.libelle);\n $(\"#modif-responsable\").val(infos.element_infos.idResponsable);\n\n //et on affiche le modal modif\n $(\"#modal-modif\").modal(\"show\");\n } else {\n //sinon on affiche un popup avec le message recu\n showPopup(infos.popup_message, infos.popup_type);\n }\n });\n}", "attachTask(message) {\n if (this._repeatOnList(message)) {\n $(\"#taskInput\").attr(\"placeholder\", \"Ja existe uma task identica!\")\n .parent().addClass(\"has-error\");\n return;\n }\n\n $(\"#taskInput\").attr(\"placeholder\", \"Insita sua tarefa...\")\n .parent().removeClass(\"has-error\");\n\n let task = {\n date : new Date(),\n open : true,\n message : message\n }, list = ls.getList();\n\n if(list[list.length - 1] != undefined) {\n var x = this.list[this.list.length - 1];\n task.id = x[\"id\"] + 1;\n } else {\n task.id =0;\n }\n\n ls.setItem(task);\n if (this.order == \"DESC\") {\n this.list.push(task)\n } else {\n let list = this.list.reverse();\n list.push(task);\n this.list = list.reverse();\n }\n }", "function chamarAperto(){\n commandAbortJob();\n commandSelectParameterSet(1);\n commandVehicleIdNumberDownload(\"ASDEDCUHBG34563EDFRCVGFR6\");\n commandDisableTool();\n commandEnableTool();\n}", "_handleButtonSave()\n {\n var element = this._getJQueryElement();\n if ($(element).is(':visible'))\n {\n this.model.set('job_settings', this._editor.getValue());\n Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__WORKFLOWJOB_SAVE, {workflowjob: this.model, workflow: this._workflow});\n }\n }", "function tiendaSubmitForm(task, form) {\r\n\tDsc.submitForm(task, form);\r\n}", "function executeMissionStep(request){\n\tvar aux, count, aux2;\n\tswitch(request.stepId){\n\t\t case \"chooseJob\": //It shows the first choice panel\n\t\t \taux = document.createElement(\"div\");\n\t\t \taux.id = \"gen-modal\";\n\t\t \taux.className = \"modal hide in\";\n\t\t \taux.tabindex = \"0\";\n\t\t \taux['aria-hidden'] = false;\n\t\t \taux.style.display = \"block\";\n\t\t\taux.innerHTML = \n\t\t \t'<div class=\"widget-title\">'+\n\t\t \t\t'<h5>Ok, here we go</h5>'+\n\t\t \t\t'<span class=\"label label-important hide1024\" style=\"float: right\">Bot</span>'+\n\t\t \t'</div>'+\n\t\t \t'<div class=\"modal-body\">'+\n\t\t \t\t'<b>Choose some action: </b><br><br>'+\n\t\t \t\t'<button id=\"set-check-account-status-job\" class=\"btn btn-success\">Perform check account status missions</button><br><br>'+\n\t\t \t\t'<button id=\"set-transfer-money-job\" class=\"btn btn-success\">Perform transfer money missions</button><br><br>'+\n\t\t \t\t'<button id=\"set-camping-bank-logs\" class=\"btn btn-success\"> Listen transfer bank logs on </button>'+\n\t\t \t\t'<input id=\"target-bank-ip\" class=\"controls\" type=\"text\" value=\"246.248.105.231\" style=\"vertical-align: top; margin-left: 10px; margin-right: 10px;\"> and transfer to my account: <input id=\"set-my-account\" class=\"controls\" type=\"text\" value=\"12345678\" style=\"vertical-align: initial; margin-left: 10px; margin-right: 10px;\"><br>'+\n\t\t \t\t'<button id=\"set-install-software\" class=\"btn btn-success\"> Upload, install and hide this</button>'+\n\t\t \t\t'<input id=\"installSoftware\" class=\"controls\" type=\"text\" value=\"Advanced Warez.vwarez, 5.0\" style=\"vertical-align: top; margin-left: 10px; margin-right: 10px;\"> software on these <input id=\"ip-install-targets\" class=\"controls\" type=\"text\" value=\"1.2.3.4, 10.11.12.13\" style=\"vertical-align: initial; margin-left: 10px; margin-right: 10px;\"> IPs.<br>'+\n\t\t \t\t'<button id=\"set-hide-menu\" class=\"btn btn-danger mission-abort\">Sleep bot and hide this menu</button><br><br>'+\n\t\t \t\t'<div style=\"font-size: 12px;\"><b>Important</b>: Ensure there are no tasks running. Click on BOT button anytime to abort the script process. Be careful with Safenet and FBI. Try to not fuck yourself. Do not make it too public. Enjoy it.<br><b>G programmer(2015)</b></div>'+\n\t\t \t\t'</div>'+\n\t\t \t'<div class=\"modal-footer\"></div>';\n\n\t\t \tdocument.getElementsByTagName(\"BODY\")[0].appendChild(aux);\n\t\t \tdocument.getElementById(\"set-check-account-status-job\").onclick = function(){\n\t\t \t\trequest.job = defaultJob.checkBalance;\n\t\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\t\tgoToPage(\"/missions\");\t\n\t\t\t};\n\t\t\tdocument.getElementById(\"set-transfer-money-job\").onclick = function(){\n\t\t \t\trequest.job = defaultJob.transferMoney;\n\t\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\t\tgoToPage(\"/missions\");\t\n\t\t\t};\n\t\t\tdocument.getElementById(\"set-camping-bank-logs\").onclick = function(){\n\t\t\t\trequest = resetRequestDada(request);\n\t\t \t\trequest.job = defaultJob.campingBankLogs;\n\t\t \t\trequest.ip[0] = getSomeElement(\"input\", \"id\", \"target-bank-ip\", 0).value;\n\t\t \t\trequest.myAccount = getSomeElement(\"input\", \"id\", \"set-my-account\", 0).value;\n\t\t\t\tsetNextStep(request, \"fillIPOnInternetPage\");\n\t\t\t\tgoToPage(\"/internet\");\t\n\t\t\t};\n\t\t\tdocument.getElementById(\"set-install-software\").onclick = function(){\n\t\t\t\trequest = resetRequestDada(request);\n\t\t \t\trequest.job = defaultJob.installSoftware;\n\t\t \t\trequest.software = document.getElementById(\"installSoftware\").value;\n\t\t \t\taux2 = document.getElementById(\"ip-install-targets\").value;\n\t\t \t\tif (aux2.search(\",\") >= 0){\n\t\t \t\t\taux2 = aux2.split(\",\");\n\t\t \t\t\tfor(aux = 0; aux <= aux2.length - 1; aux++){\n\t\t \t\t\t\trequest.ip[aux] = aux2[aux].trim();\n\t\t \t\t\t}\n\t\t \t\t} else {\n\t\t \t\t\trequest.ip[0] = aux2.trim();\n\t\t \t\t}\n\t\t\t\tsetNextStep(request, \"checkSoftware\");\n\t\t\t\tgoToPage(\"/software\");\t\n\t\t\t};\n\t\t\tdocument.getElementById(\"set-hide-menu\").onclick = function(){\n\t\t\t\trequest = resetRequestDada(request);\n\t\t \t\trequest.job = defaultJob.wait;\n\t\t \t\tsetNextStep(request, \"\");\n\t\t\t\tlocation.reload(true);\t\n\t\t\t};\n\t\t \tbreak;\n\t\t case \"accessMissionPage\":\n\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\tgoToPage(\"/missions\");\n\t\t \tbreak;\n\t\t case \"tryToGetSomeMission\":\n\t\t \trequest = resetRequestDada(request);\n\t\t \tdefineLanguage(request);\n\t\t \trequest = getSomeMission(request);\n\t\t \tif (request.url != null){\n\t\t\t\tsetNextStep(request, \"acceptMission\");\n\t\t\t\twindow.location.href = request.url;\n\t\t \t} else {\n\t\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\t\tcount = getSomeElement(\"b\", null, null, 0).childNodes[0].nodeValue; //Get the time missing to next missions package\n\t\t\t\tif (request.counter > 0){//Check of own log needs to be clean\n\t\t\t\t\tsetNextStep(request, \"cleanOwnLog\");\n\t\t\t\t\tgoToPage(\"/log\");\n\t\t\t\t} else\n\t\t\t\tif (count > 0){\n\n\t\t\t\t\taux = document.createElement(\"div\");\n\t\t\t\t\taux.id = \"secondsCounterContainer\";\n\t\t\t\t\tgetSomeElement(\"div\", \"class\", \"widget-content padding\", 0).appendChild(aux);\n\n\t\t\t\t\tcount = (count * 60) - 50;\n\t\t\t\t\tconsole.log(\"Wait \" + count + \" seconds\");\n\t\t\t\t\tcounterDelay = 0; \n\t\t\t\t\tdelay = setInterval(\n\t\t\t\t\t\tfunction(){\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tgetSomeElement(\"div\", \"id\", \"secondsCounterContainer\", 0).childNodes[0].nodeValue = \"or \" + (count - counterDelay) + \" seconds\";\n\t\t\t\t\t\t\t}catch(error){\n\t\t\t\t\t\t\t\tconsole.log(error.message);\n\t\t\t\t\t\t\t\taux = document.createTextNode(\"or \" + (count - counterDelay) + \" seconds\");\n\t\t\t\t\t\t\t\tgetSomeElement(\"div\", \"id\", \"secondsCounterContainer\", 0).appendChild(aux);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcounterDelay++; \n\t\t\t\t\t\t\tif (counterDelay >= count){\n\t\t\t\t\t\t\t\tclearInterval(delay); \n\t\t \t\t\t\t\t\tgoToPage(\"/missions\");\n\t\t \t\t\t\t\t}\n\t\t \t\t\t\t}, 1000); //Wait the specified time on the page\n\t\t\t\t} else {\n\t\t\t\t\tgoToPage(\"/missions\");\n\t\t\t\t\t//window.close();\n\t\t\t\t}\t\t\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"acceptMission\":\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){//Check is some error has happened \n\t\t\t\tsetNextStep(request, \"getMissionInformationAndGoToInternetPage\");\n\t\t \t\tgetSomeElement(\"span\", \"class\", \"btn btn-success mission-accept\", 0).click(); //Click on the Accept mission button\n\t\t \t\tcounterDelay = 0; \n\t\t \t\tdelay = setInterval(\n\t\t \t\t\tfunction(){\n\t\t \t\t\t\tcounterDelay++; \n\t\t \t\t\t\tif (counterDelay >= 1000/DEFAULT_DELAY){\n\t\t \t\t\t\t\tclearInterval(delay); \n\t\t \t\t\t\t\tcounterDelay = 0; \n\t\t \t\t\t\t\tgetSomeElement(\"input\", \"type\", \"submit\", 0).click(); //Click on the div float Accept mission button\n\t\t \t\t\t\t}\n\t\t \t\t\t}, DEFAULT_DELAY);\n\t\t \t} else {\n\t\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\t\tgoToPage(\"/missions\");\t\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"getMissionInformationAndGoToInternetPage\":\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){//Check is some error has happened \n\t\t \t\trequest = getMissionInformation(request);\n\t\t \t\trequest.counter++;\n\t\t\t\tsetNextStep(request, \"fillIPOnInternetPage\");\n\t\t\t\tgoToPage(\"/internet\");\t\n\t\t \t} else {\n\t\t\t\tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t\t\tgoToPage(\"/missions\");\t\n\t\t \t}\n\t\t\tbreak;\n\t\t case \"fillIPOnInternetPage\":\n\t\t \tif (getSomeElement(\"a\", \"href\", \"?view=logout\", 0) == null){\n\t\t \t\tswitch(request.job){\n\t\t \t\t\tcase defaultJob.stealBitcoinData:\n\t\t \t\t\t\tsetNextStep(request, \"goToServerTab\"); break;\n\t\t \t\t\tdefault: setNextStep(request, \"accessHackAccountTab\"); break;\n\t\t \t\t}\n\t\t\t\tgetSomeElement(\"input\", \"class\", \"browser-bar\", 0).value = request.ip[0]; //Fill IP Adress bar\n\t\t\t\tgetSomeElement(\"input\", \"type\", \"submit\", 0).click(); //Click on Go button\n\t\t \t} else {\n\t\t \t\tsetNextStep(request, \"fillIPOnInternetPage\");\n\t\t \t\t//getSomeElement(\"a\", \"href\", \"?view=logout\", 0).click(); //Click on the Logout Button\n\t\t \t\tgoToPage(\"/internet?view=logout\");\n\t\t \t}\n\t\t\tbreak;\n\t\t case \"accessHackAccountTab\":\n\t\t \tsetNextStep(request, \"hackAccount\");\n\t\t\tgoToPage(\"/internet?action=hack&type=bank\");\n\t\t \tbreak;\n\t\t case \"hackAccount\":\n\t\t\tsetNextStep(request, \"waitForEditAccountHackProcess\");\n\t\t\tgetSomeElement(\"input\", \"name\", \"acc\", 0).value = request.account[0]; //Fill Account to hack bar\n\t\t \tgetSomeElement(\"button\", \"type\", \"submit\", 0).click(); //Click on Hack button\n\t\t \tbreak;\n\t\t case \"waitForEditAccountHackProcess\":\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){ //Check for error message\n\t\t \t\tsetNextStep(request, \"signInAccount\");\t\n\t\t \t} else {\n\t\t\t\tsetNextStep(request, \"abortMission\");\n\t\t\t\tgoToPage(\"/missions\");\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"signInAccount\":\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){ //Check for success message\n\t\t \t\tswitch(request.job){\n\t\t \t\t\tcase defaultJob.checkBalance:\n\t\t \t\t\t\tsetNextStep(request, \"getTheAccountBalance\");\n\t\t \t\t\t\tbreak;\n\t\t \t\t\tcase defaultJob.transferMoney:\n\t\t \t\t\t\tsetNextStep(request, \"transferMoney\");\n\t\t \t\t\t\tbreak;\n\t\t \t\t\tdefault: break;\t\n\t\t \t\t}\n\t\t \t\t\n\t\t \t\tgetSomeElement(\"input\", \"name\", \"acc\", 0).value = request.account[0]; //Fill the account field\n\t\t \t\tgetSomeElement(\"input\", \"name\", \"pass\", 0).value = getSomeElement(\"strong\", null, null, 1).childNodes[0].nodeValue; //Fill the password field with the password on screen\n\t\t \t\tgetSomeElement(\"input\", \"type\", \"submit\", 1).click(); //Click on the Login button\n\t\t \t} else {\n\t\t\t\tsetNextStep(request, \"abortMission\");\n\t\t\t\tgoToPage(\"/missions\");\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"getTheAccountBalance\":\n\t\t \trequest.amount = getSomeElement(\"strong\", null, null, 0).childNodes[0].nodeValue; //Get the account balance\n\t\t\tsetNextStep(request, \"goToServerTab\");\n\t\t\t//getSomeElement(\"a\", \"href\", \"?bAction=logout\", 0).click(); //Click on the account logout button\n\t\t\tgoToPage(\"/internet?bAction=logout\");\n\t\t \tbreak;\n\t\t case \"transferMoney\":\n\t\t \tcounterDelay = 0;\n\t\t\tdelay = setInterval(\n\t\t\t\t\tfunction(){\t\t\t\t\t\t\n\t\t\t\t\t\tcounterDelay++; \n\t\t\t\t\t\tif (counterDelay >= 1){\n\t\t\t\t\t\t\tclearInterval(delay); \n\t\t\t\t\t\t\tsetNextStep(request, \"goOutToTheAccount\");\n\t\t \t\t\t\t\tgetSomeElement(\"input\", \"name\", \"acc\", 0).value = request.account[1]; //Fill the To field\n\t\t \t\t\t\t\tgetSomeElement(\"input\", \"name\", \"ip\", 1).value = request.ip[1]; //Fill the Bank IP field\n\t\t \t\t\t\t\tgetSomeElement(\"button\", \"class\", \"btn btn-success\", 0).click(); //Click on the Transfer Money button\n\t\t \t\t\t\t}\t\n\t\t\t\t\t\t\n\t\t \t\t\t}, 1000); //Wait the specified time on the page\n\t\t \tbreak;\n\t\t case \"goOutToTheAccount\":\n\t\t \tsetNextStep(request, \"goToServerTab\");\n\t\t \tgetSomeElement(\"a\", \"href\", \"?bAction=logout\", 0).click(); //Click on the account logout button\t\n\t\t \tbreak;\n\t\t case \"goToServerTab\":\n\t\t \tsetNextStep(request, \"signInKnownServer\");\n\t\t \tgetSomeElement(\"a\", \"href\",\t\"?action=login\", 0).click(); //Click on the server login tab\n\t\t \tbreak;\n\t\t case \"signInKnownServer\":\n\t\t \tif (getSomeElement(\"strong\", null, null, 1) != null){//Check if the password is avaiable \n\t\t \t\tsetNextStep(request, \"removeLogsFromTarget\");\n\t\t \t\taux = getSomeElement(\"span\", \"class\", \"small pull-left\", 0).childNodes[1].nodeValue;\n\t\t \t\taux = aux.substr(2, aux.length - 2);\n\t\t \t\tgetSomeElement(\"input\", \"name\", \"user\", 0).value = aux; //Fill the user field with the user on screen\n\t\t \t\taux = getSomeElement(\"span\", \"class\", \"small pull-left\", 1).childNodes[1].nodeValue;\n\t\t \t\taux = aux.substr(2, aux.length - 2);\n\t\t \t\tgetSomeElement(\"input\", \"type\", \"password\", 0).value = aux; //Fill the password field with the password on screen\n\t\t \t\tgetSomeElement(\"input\", \"type\", \"submit\", 1).click(); //Click on the Login button\n\n\t\t \t} else {\n\t\t \t\t//Go to server invader\n\t\t \t\tsetNextStep(request, \"signInNew-KnownServer\");\n\t\t \t\tgoToPage(\"/internet?action=hack&method=bf\"); //Atack by brute force method\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"signInNew-KnownServer\":\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){\n\t\t \t\tsetNextStep(request, \"signInKnownServer\");\n\t\t \t\t//getSomeElement(\"a\", \"href\",\t\"?action=login\", 0).click(); //Click on the server login tab\n\t\t \t} else {\n\t\t \t\tif (request.ip[0] == request.ip[1]){\n\t\t \t\t\tsetNextStep(request, \"goToFeedbackMissionPage\");\t\n\t\t \t\t} else {\n\t\t \t\t\tsetNextStep(request, \"fillIPOnInternetPage-SecondServer\");\t\n\t\t \t\t};\n\t\t \t\tlocation.reload(true); //Reload the page\n\t\t \t}\n\t\t \tbreak;\n\t\t case \"removeLogsFromTarget\":\n\t\t \tsetNextStep(request, \"waitForEditLogProcess\");\n\t\t \ttry{\n\t\t\t\tgetSomeElement(\"textarea\", \"class\", \"logarea\", 0).childNodes[0].nodeValue = \" \"; //Clean the logs\n\t\t\t}catch(error){};\n\t\t \tgetSomeElement(\"input\", \"type\", \"submit\", 1).click(); //Click on the Edit Log Data Button\n\t\t \tbreak;\n\t\t case \"waitForEditLogProcess\":\n\t\t \tsetNextStep(request, \"goOutFromBankServer\");\n\t\t \tbreak;goToServerTab\n\t\t case \"goOutFromBankServer\":\n\t\t \tswitch(request.job){\n\t\t \t\tcase defaultJob.checkBalance:\n\t\t \t\t\tsetNextStep(request, \"goToFeedbackMissionPage\");\n\t\t \t\t\tbreak;\n\t\t \t\tcase defaultJob.transferMoney:\n\t\t \t\t\tif (request.ip[0] == request.ip[1]){\n\t\t \t\t\t\tsetNextStep(request, \"goToFeedbackMissionPage\");\t\n\t\t \t\t\t} else {\n\t\t \t\t\t\tsetNextStep(request, \"fillIPOnInternetPage-SecondServer\");\t\n\t\t \t\t\t};\n\t\t \t\t\tbreak;\n\n\t\t \t\tdefault: break;\t\n\t\t \t}\n\t\t \t//getSomeElement(\"a\", \"href\", \"?view=logout\", 0).click(); //Click on the Logout button\t\n\t\t \tgoToPage(\"/internet?view=logOut\");\n\t\t \t\n\t\t \tbreak;\n\t\t case \"fillIPOnInternetPage-SecondServer\":\n\t\t \trequest.ip[0] = request.ip[1];\n\t\t \tsetNextStep(request, \"goToServerTab\");\n\t\t\tgetSomeElement(\"input\", \"class\", \"browser-bar\", 0).value = request.ip[1]; //Fill IP Adress bar\n\t\t\tgetSomeElement(\"input\", \"type\", \"submit\", 0).click(); //Click on Go button\n\t\t \tbreak;\n\t\t case \"goToFeedbackMissionPage\":\n\t\t \tswitch(request.job){\n\t\t \t\tcase defaultJob.checkBalance:\n\t\t \t\t\tsetNextStep(request, \"informBalance\");\n\t\t \t\t\tbreak;\n\t\t \t\tcase defaultJob.transferMoney:\n\t\t \t\t\tsetNextStep(request, \"confirmFinishMission\");\n\t\t \t\t\tbreak;\n\t\t \t\tdefault: break;\n\t\t \t}\n\t\t \tgoToPage(\"/missions\");\n\t\t \tbreak;\n\t\t case \"informBalance\":\n\t\t \tgetSomeElement(\"input\", \"id\", \"amount-input\", 0).value = request.amount; //Fill the balance field with the balance value\n\t\t \tsetNextStep(request, \"accessMissionPage\");\n\t\t \tgetSomeElement(\"span\", \"class\", \"btn btn-success mission-complete\", 0).click(); //Click on the Complete Mission Button\n\t\t \tcounterDelay = 0; \n\t\t \tdelay = setInterval( \n\t\t \t\tfunction(){\n\t\t \t\t\tcounterDelay++;\n\t\t \t\t\tif (counterDelay >= 2000/DEFAULT_DELAY){\n\t\t \t\t\t\tclearInterval(delay); \n\t\t \t\t\t\tcounterDelay = 0; \n\t\t \t\t\t\tgetSomeElement(\"input\", \"id\", \"modal-submit\", 0).click(); //Click on the float div Complete Mission button\n\t\t \t\t\t}\n\t\t \t\t}, DEFAULT_DELAY); \n\t\t \tbreak;\n\t\t case \"confirmFinishMission\":\n\t\t \tsetNextStep(request, \"accessMissionPage\");\n\t\t \tgetSomeElement(\"span\", \"class\", \"btn btn-success mission-complete\", 0).click();\n\t\t \tcounterDelay = 0; \n\t\t \tdelay = setInterval( \n\t\t \t\tfunction(){\n\t\t \t\t\tcounterDelay++;\n\t\t \t\t\tif (counterDelay >= 2000/DEFAULT_DELAY){\n\t\t \t\t\t\tclearInterval(delay); \n\t\t \t\t\t\tcounterDelay = 0; \n\t\t \t\t\t\tgetSomeElement(\"input\", \"id\", \"modal-submit\", 0).click(); //Click on the float div Complete Mission button\n\t\t \t\t\t}\n\t\t \t\t}, DEFAULT_DELAY); \n\t\t \tbreak;\n\t\t case \"abortMission\":\n\t\t\tsetNextStep(request, \"accessMissionPage\");\n\t\t\tgetSomeElement(\"span\", \"class\", \"btn btn-danger mission-abort\", 0).click(); //Click on the Abort button\n\t\t\tcounterDelay = 0; \n\t\t\tdelay = setInterval(\n\t\t\t\tfunction(){\n\t\t\t\t\tcounterDelay++; \n\t\t\t\t\tif (counterDelay >= 1000/DEFAULT_DELAY){\n\t\t\t\t\t\tclearInterval(delay); \n\t\t\t\t\t\tcounterDelay = 0; \n\t\t \t\t\t\tgetSomeElement(\"input\", \"type\", \"submit\", 0).click(); //Click on the float div Abort button\n\t\t \t\t\t}\n\t\t \t\t}, DEFAULT_DELAY);\n\t\t \tbreak;\n\t\t case \"cleanOwnLog\":\n\t\t \tsetNextStep(request, \"waitForEditOwnLogProcess\");\n\t\t \ttry{\n\t\t\t\tgetSomeElement(\"textarea\", \"class\", \"logarea\", 0).childNodes[0].nodeValue = \" \"; //Clean the logs\n\t\t\t}catch(error){};\n\t\t \t\n\t\t \tgetSomeElement(\"input\", \"type\", \"submit\", 0).click(); //Click on the Edit Log Data Button\n\t\t \tbreak;\n\t\t case \"waitForEditOwnLogProcess\":\n\t\t \trequest.counter = 0;\n\t\t \tsetNextStep(request, \"tryToGetSomeMission\");\n\t\t \tif (getSomeElement(\"div\", \"class\", \"alert alert-error\", 0) == null){\n\t\t\n\t\t \t} else {\n\t\t \t\tgoToPage(\"/missions\");\n\t\t \t}\n\t\t \tbreak;\n\n\t\tdefault: break;\n\t}\n}", "function start() {\n\n gw_job_process.UI();\n\n }", "function start() {\n\n gw_job_process.UI();\n\n }", "function start() {\n\n gw_job_process.UI();\n\n }" ]
[ "0.64774585", "0.6394553", "0.6333703", "0.61653733", "0.6110162", "0.5982311", "0.59495217", "0.5853259", "0.5795006", "0.5778456", "0.5726513", "0.56974155", "0.56930065", "0.5677544", "0.56761664", "0.56411624", "0.5593817", "0.5591097", "0.5568247", "0.556769", "0.55660427", "0.5545103", "0.55355555", "0.55355245", "0.5518067", "0.5516677", "0.55120933", "0.55041033", "0.55035937", "0.5496537", "0.5454024", "0.545035", "0.545025", "0.5449125", "0.5448742", "0.5442576", "0.5432172", "0.5431091", "0.5429058", "0.5420341", "0.542027", "0.5417095", "0.54161066", "0.54115826", "0.54086757", "0.53989667", "0.5387685", "0.53860736", "0.5379109", "0.53787625", "0.53712845", "0.5369996", "0.5366025", "0.5352366", "0.53402567", "0.53392065", "0.53378505", "0.5329206", "0.5326362", "0.5321574", "0.53205097", "0.5320276", "0.5319121", "0.53186333", "0.53174525", "0.53173244", "0.53135276", "0.530184", "0.5297031", "0.52877086", "0.52756476", "0.5274948", "0.52748364", "0.5263878", "0.5257738", "0.5248219", "0.52481085", "0.52474856", "0.52469295", "0.5246767", "0.5241564", "0.5234059", "0.523267", "0.5232562", "0.52320474", "0.5231797", "0.5226158", "0.5223272", "0.5222962", "0.522137", "0.5219095", "0.5217702", "0.5217343", "0.5214811", "0.5213244", "0.521222", "0.520299", "0.5202294", "0.5192261", "0.5192261", "0.5192261" ]
0.0
-1
countdown function is evoked when page is loaded
function countdown() { if (count === 0) { scoreboard(); } if (count === 1) { scoreboard(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function initCountdown() {\n\t\tconsole.log('countdown!');\n\t\tshowElement(countdown);\n\t\tvar sec = 3;\n\t\t$('.countdown h1').text('LOOK HERE!');\n\t\tvar timer = setInterval(function() {\n\t\t $('.countdown h1').animate({\n\t\t opacity: 0\n\t\t }, 1000, function() {\n\t\t $('.countdown h1').css('opacity', 1);\n\t\t $('.countdown h1').text(sec--);\n\t\t })\n\n\t\t if (sec == 0) {\n\t\t hideElement(countdown);\n\t\t clearInterval(timer);\n\t\t\t\tpicCapture();\n\t\t }\n\t\t}, 1000);\n\t}", "function countdown_init() {\n answered_timeout = false;\n countdown_number = 4;\n $(\"#countdown-text\").html(\"Time remaining: \")\n countdown_trigger();\n}", "function domCountDown() {\n $(`.timer`).text(`Game Begins in: ${countDown} Seconds`);\n }", "function startTimer(){\n \n \n setTimeout(\"countdown()\",1000);\n \n }", "function init_countdown()\n {\n if ($(\".count-down\").length)\n {\n var year = parseInt($(\".count-down\").attr(\"data-countdown-year\"), 10);\n var month = parseInt($(\".count-down\").attr(\"data-countdown-month\"), 10) - 1;\n var day = parseInt($(\".count-down\").attr(\"data-countdown-day\"), 10);\n $(\".count-down\").countdown(\n {\n until: new Date(year, month, day),\n padZeroes: true\n });\n }\n }", "function countDownTimer() {\n if (countDown != 0) {\n --countDown;\n } else {\n //when timer hits 0, exits function (avoids infinite counting)\n return;\n }\n //calls function to insert countdown timer into DOM\n domCountDown();\n }", "function startCountdown(){\n\n\t\tsetInterval(countdown, 1000);\n\n\t}", "function countdownTimer() {\n if (countdown > 0) \t{\n countdown = countdown-1;\n $(\"#time\").html(\"<p>Time remaining: \" + countdown + \" seconds.</p>\"); \n }\n else {loadQuestion() \n };\n }", "function OnStartCountdown(duration : int)\n{\n\ttCountdownExpires = duration;\n}", "function countDownTimer() {\n\n // Figure out the time to launch\n timeToLaunch();\n\n // Write to countdown component\n $(\"#days .number\").text(days);\n $(\"#hours .number\").text(hrs);\n $(\"#minutes .number\").text(min);\n $(\"#seconds .number\").text(sec);\n\n // Repeat the check every second\n setTimeout(countDownTimer, 1000);\n }", "function countdown(){\n \n \n $(\"#timer\").html(timer);\n //Sets a delay of one second before the timer starts\n // time = setInterval(showCountdown, 1000);\n // Shows the countdown function. IT WORKS.\n showCountdown();\n \n }", "function zähler (){\r\n\tnew countdown(1200, 'counter'); //alle Zeiten werden in Sekunden angegeben, rechnet selbst auf Minuten und Stunden um\r\n}", "function countDownTimer() {\n\n // Figure out the time to launch\n timeToLaunch();\n\n // Write to countdown component\n $(\"#days .timer-number\").text(days);\n $(\"#hours .timer-number\").text(hrs);\n $(\"#minutes .timer-number\").text(min);\n $(\"#seconds .timer-number\").text(sec);\n\n // Repeat the check every second\n setTimeout(countDownTimer, 1000);\n }", "function countdown() {\n runtime();\n}", "function timeCount() {\n secondsLeft--;\n timerEl.textContent = secondsLeft;\n if (secondsLeft == 0) {\n clearInterval(timerNum);\n initialPage();\n } \n}", "function countdown() {\n // timeRemaining is incremented down\n timeRemaining --;\n\n // If time runs out, runs gameOver()\n if (timeRemaining <= 0) {\n gameOver();\n }\n\n // Updates the timer element\n timer.text(timeRemaining);\n }", "function countDown() {\n // decrement time remaining\n timeRemaining--;\n // updates html with the time remaining\n $(\"#timer\").text(\"Time Remaining: \" + timeRemaining);\n // stops and removes the timer at zero \n if(timeRemaining < 1){\n \n // calls the stop timer function\n stopTimer();\n\n }\n }", "function countdownTimer() {\n // reduce countdown timer by 1 second\n timer--;\n if (timer === 0) {\n // timer expired\n endTest();\n } else if (timer < 10) {\n // prefix times less than ten seconds with 0\n // update timer on web page\n $('#timer').text('0' + timer);\n } else {\n // update timer on web page\n $('#timer').text(timer);\n }\n }", "function countItDown(){\n startTime -= 1\n $el.text(startTime);\n App.doTextFit('#hostWord');\n\n if( startTime <= 0 ){\n // console.log('Countdown Finished.');\n\n // Stop the timer and do the callback.\n clearInterval(timer);\n callback();\n return;\n }\n }", "_countDown() {\n // Setzen des Eventdatums: 24.12.2019, 00:00:00Uhr\n var christmas = new Date(\"Dec 24, 2019 00:00:00\").getTime();\n\n // Setzen eines Intervalls -> alle 1000ms Funktion aufgerufen\n var x = setInterval(function() {\n // aktuelle Daten holen\n var today = new Date().getTime();\n var timeLeft = christmas - today;\n // aus Differenz Tage, Stunden, Minuten und Sekunden berechnen\n var days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));\n var hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));\n var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));\n var seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);\n // HTML-Elemente mit berechneten Daten füllen\n // try-catch-Block um Funktion über return stoppen zu können\n try{\n document.getElementById(\"countDown\").innerHTML = days + \"d \" + hours + \"h \"\n + minutes + \"m \" + seconds + \"s \";\n\n if (timeLeft < 0) {\n clearInterval(x);\n document.getElementById(\"countDown\").innerHTML = \"EXPIRED\";\n }\n }catch(error){\n return;\n }\n\n }, 1000);\n\n }", "function startCountdown () {\n\tremaining_minutes = dom_totalminutes.value;\n\tremaining_seconds = Math.floor(dom_totalseconds.value/10)*10;\n\tdocument.title=\"▶ Activo\";\n\tdom_totaltime.style.display=\"none\";\n\tcountdown.style.display=\"inline-block\";\n\tbtn_startcount.style.display=\"none\";\n\tbtn_stopcount.style.display=\"block\";\n\tdom_countdown_m.innerHTML=dom_totalminutes.value;\n\tdom_countdown_s.innerHTML=formato(remaining_seconds);\n\tdom_frases.innerHTML=eligefrase();\n\tmyCountdown();\n}", "function countdown () {\n\ttimer--;\n\t$(\"#timeRemaining\").text(timer);\n\n\t// User ran out of time to answer the question\n\tif (timer === 0) {\n\t\tcheckAnswer(\"timeUp\");\n\t}\n}", "function countDown() {\n counter--;\n $(\"#timer\").html(\"<h2> Timer: 00:\" + counter + \"</h2>\");\n timeOut();\n }", "function view_blog_countdown(duration) {\n $('#countdown_box').show(); //countdown\n $.uiLock('');\n //alert(duration);\n //performs countdown then unlocks\n do_countdown(duration);\n}", "function countDown(){\n window.setTimeout(function(){\n toggleClickable();\n nextLink.style.display = 'block';\n facit.className = \"facitF2\";\n facit.innerHTML = \"Time's up!\";\n console.log(\"Time's up!\");\n }, 15000);\n }", "function countdown() {\n\n\t//get count from onscreen\n\tcount = document.getElementById('countdownClock').innerHTML;\n\tcount = parseInt(count);\n\n\t//if count is finished, add Time Up message and reveal solution\n\tif (count == 1) {\n\t \tvar stopCount = document.getElementById('countdownClock');\n\t \tstopCount.innerHTML = \"TIME UP!\";\n\t \trevealSolution(word);\n\t \treturn;\n\t}\n\t//reduce count on screen every 1 second\n\tcount--;\n\ttemp = document.getElementById('countdownClock');\n\ttemp.innerHTML = count;\n\ttime = setTimeout(countdown, 1000);\n}", "function countdown(){\n\t\tcountTimer--;\n \t$('#timer_number').html(countTimer + \" Seconds\");\n\n\t\t\t// User finishes before time is up and clicks done\n\t\t\t$(\"#done_button\").on(\"click\", function(){\n\n\t\t\t// Stop the countdown and run the timeUp function\n\t\t\tcountTimer = 0;\n\t\t\treturn;\n\n\t\t\t});\n\n\t\t\t// Finish the game after the timer reaches 0\n\t\t\tif(countTimer == -1){\n\t\t\t\ttimeUp();\n\n\t\t\t\t// Hide the game div from the user\n\t\t\t\t$(\"#game_container\").hide();\n\n\t\t\t}\n\n\t}", "function countDown(){\r\n\t\t$(\"#count-down-wrapper\").countdown({\r\n\t\t\tdate: \"1 january 2017 09:00:00\", // Change this to your desired date to countdown to\r\n\t\t\tformat: \"on\"\r\n\t\t});\r\n\t}", "function countdown(){\n\tif (variables.time > 0) {\n\t\tvariables.time--;\n\t\t$('#time').width(variables.time + '%');\n\t} else {\n\t\tif (variables.gamestate > 0) {\n\t\t\tclearInterval(timeInterval);\n\t\t\tvariables.gamestate = 0;\n\t\t\t$(\".container\").children().fadeOut(gameOver);\t\t\n\t\t}\n\t}\n}", "function countdown() {\r\n setTimeout('Decrement()', 60);\r\n }", "function countDown() {\n seconds -= 1;\n\n if (seconds < 0 && minutes > 0) {\n seconds += 60;\n minutes -= 1;\n }\n else if (seconds === -1 && minutes === 0) {\n // Timer is done. Call relevant functions\n stopTimer();\n PEvents.timerDone(currentTimerType);\n loadTimer();\n }\n \n render();\n }", "function countdown(callback) {\n window.setTimeout(callback)\n}", "function countdown() {\n \n \n if (timeLeft == -1) {\n clearTimeout(timerId);\n \n } else {\n $(\"#timer\").text(timeLeft + ' seconds remaining');\n timeLeft--;\n }\n }", "function countdown(){\n const countdown = setInterval(function() {\n timeRemaining--;\n $timer.text(timeRemaining);\n if(timeRemaining === 0){\n clearInterval(countdown);\n gameStarted = false;\n }\n }, 1000);\n }", "function showCountdown() {\n countdownPage.hidden = false;\n splashPage.hidden = true;\n countdownStart();\n}", "function showCountdown(){\n splashPage.hidden = true; \n countdownPage.hidden = false;\n let countdownStart = 3; \n countdown.textContent = `${countdownStart}`;\n const count = setInterval(() => { \n countdownStart--;\n countdown.textContent = `${countdownStart}`;\n if( countdownStart === 0){\n countdown.textContent = 'GO!'\n } else if ( countdownStart === -1) {\n clearInterval(count);\n showGamePage();\n }\n },1000); \n}", "function countdown() { \n setTimeout('Decrement()', 60); \n }", "function showCountdown(){\n seconds--;\n \n if(seconds < 10) {\n $(\"#timeLeft\").html(\"00:0\" + seconds);\t\n } else {\n $(\"#timeLeft\").html(\"00:\" + seconds);\t\n }\n \n if(seconds < 1){\n clearInterval(time);\n answered = false;\n answerPage();\n }\n }", "function countDown() {\n \n //if timeRemaining is less than or equal to 0\n if (timeRemaining <= 0){\n\n // //increment unansweredCounter\n // unansweredCounter++;\n\n //call losePage()\n losePage();\n }\n \n //decrement timeRemaining by 1\n timeRemaining--;\n \n //display timeRemaining to index.html by using the id #timeRemaining\n $(\"#timeRemaining\").text(timeRemaining + \" seconds\");\n\n}", "function countDown() {\n setTimeout('Decrement()', 60);\n }", "function countdown(){\n\t\tif(timeLeft == 0){\n\t\t\tend()\n\t\t}else{\n\t\t\t$(\"#Time-Remaining\").text(\"Time Left: \"+ timeLeft);\n\t\t\ttimeLeft--;\n\t\t}\n\t}", "function countDown() {\n var note = $(selectors.countdown),\n ts = new Date(2021, 07, 08, 18, 00, 00),\n offerEnd = true,\n message;\n\n if ((new Date()) > ts) {\n ts = (new Date()).getTime(),\n offerEnd = false;\n }\n $(selectors.countdown).countdown({\n timestamp: ts,\n callback: function (days, hours, minutes, seconds) {\n message = \"\";\n\n if (offerEnd) {\n message += days + \"d\" + (days == 1 ? '' : '') + \" \";\n message += hours + \"h\" + (hours == 1 ? '' : '') + \" \";\n message += minutes + \"m\" + (minutes == 1 ? '' : '') + \" \";\n message += seconds + \"s\" + (seconds == 1 ? '' : '') + \" <br />\";\n note.html(message);\n }\n else {\n message += \"You have just missed the above offer!! Please wait for next exciting offer\";\n $(selectors.offerText).html(message)\n }\n }\n });\n }", "function initCounter() {\n if (!$('.countdown').length) return false;\n $('.countdown').not('.initialized').each(function () {\n $(this).addClass('initialized').ClassyCountdown({\n end: $.now() + parseInt($(this).data('end')),\n labels: true,\n style: {\n element: \"\",\n days: {\n gauge: {\n thickness: $(this).data('line'),\n fgColor: $(this).data('fgcolor'),\n bgColor: $(this).data('bgcolor')\n }\n },\n hours: {\n gauge: {\n thickness: $(this).data('line'),\n fgColor: $(this).data('fgcolor'),\n bgColor: $(this).data('bgcolor')\n }\n },\n minutes: {\n gauge: {\n thickness: $(this).data('line'),\n fgColor: $(this).data('fgcolor'),\n bgColor: $(this).data('bgcolor')\n }\n },\n seconds: {\n gauge: {\n thickness: $(this).data('line'),\n fgColor: $(this).data('fgcolor'),\n bgColor: $(this).data('bgcolor')\n }\n }\n }\n });\n });\n }", "function timer() {\n countdown=countdown-1;\n if (countdown < 0){\n clearInterval(counter);\n alert(\"TIMES UP!\");\n calculateTotal();\n return;\n }\n $(\"#timer\").text(countdown);\n\n }", "function countDown() {\n $(\"#timer\").empty();\n clock = 20;\n var timeDiv = $(\"<h3>\");\n timeDiv.append(\"Time left: \" + clock + \" sec\");\n $(\"#timer\").append(timeDiv);\n time = setInterval(timer, 1000); //C alls the timer function every 1 second \n }", "function countdown() {\r\n document.getElementById('countdown-area').style.visibility = \"visible\";\r\n if (count > 0) {\r\n document.getElementById('countdown-area').innerHTML = count\r\n count--;\r\n setTimeout(countdown, 700);\r\n }\r\n else {\r\n count = 3;\r\n document.getElementById('countdown-area').style.visibility = \"hidden\";\r\n showPicks(pPick, cPick);\r\n updateScoreArea(getWinner());\r\n }\r\n}", "function countdownTimer() {\r\n\r\n\t\ttimerBar = timerBar-1;\r\n\r\n\t}", "function countdown(){\n $('.seconds_countdown').each(function (){\n var newSeconds = parseInt($(this).data('seconds')) - 1;\n $(this).data('seconds', newSeconds);\n if (newSeconds <= 0){\n $(this).html(\"募資已經結束\");\n }\n else{\n var daysLeft = secondsToDaysLeft(newSeconds);\n $(this).html(\"將於\" + daysLeft + \"後結束\");\n }\n })\n}", "function countdown(){\r\n time--;\r\n // replace the html with the new time\r\n $(\"#time-counter\").text(time)\r\n if(time <= 0) {\r\n // cease timer\r\n clearInterval(counterId);\r\n // show finished screen\r\n $(\"#finished\").removeAttr(\"style\")\r\n // update final score with current time\r\n $(\"#final-score\").text(time)\r\n }\r\n}", "function countDown() {\n seconds--;\n if (seconds > 0) {\n setTimeout(countDown, 1000);\n } else {\n submitAnswers();\n }\n console.log(seconds);\n $(\"#time-remaining\").html(\"<h4>\" + \"Time Remaining: \" + seconds + \" seconds\" + \"</h4>\");\n\n }", "function activate_timer() {\n var countdown_timer = window.setInterval(function() {\n timer--;\n document.getElementById(\"remaining_time\").innerHTML = timer;\n\n if (timer == 0 ) {\n clearInterval(countdown_timer);\n showLeaderboard();\n }\n \n },1000);\n\n}", "function countDownTimer(){\n\tweatherAPI();\n\tsetTimeout(count3,1000);\n\tsetTimeout(count2,2000);\n\tsetTimeout(count1,3000);\n\tsetTimeout(returnVideo,3500);\n\t//Put the third page\n/*\n\tsetTimeout(resultsPage,3700);\n\tsetTimeout(countReady,10000);\n*/\n\t\n}", "function timer() {\n count = count - 1;\n if (count <= 0) {\n clearInterval(counter);\n //counter ended, do something here\n\n $('#runadvert').prop('disabled', false);\n $('#runadvert').text('Run Advert');\n return;\n }\n\n //Do code for showing the number of seconds here\n $('#runadvert').text(count);\n }", "function start() {displayCountdown(setCountdown(month,day,hour,min,tz),lab);}", "function initialize(){\r\n\t document.getElementById(\"lightbox\").style.display=\"none\";\r\n\t document.getElementById(\"countdown\").innerHTML = timeleft + \"s\";\r\n\t loadQuestion();\r\n }", "function countdown() {\n if (countdownTime > 0) {\n countElement.innerHTML = `${countdownTime}`\n countdownTime = countdownTime\n countdownTime--\n } else if (countdownTime <= 0) {\n text = \"Go!\"\n countElement.innerHTML = `${text}`\n countdownTime = defaultCountdownTime\n clearInterval(countInterval)\n gameStarted()\n }\n}", "function countdownTimer() {\r\n setInterval(() => {\r\n roundComplete.play();\r\n swal(\"TIME IS UP\");\r\n }, 60000);\r\n}", "function countDown() {\n counter--;\n // puts the numbers on the users screen\n $(\"#time\").html(\"Timer: \" + counter);\n // if the counter reaches 0, run the timeUp function\n if (counter === 0) {\n timeUp();\n };\n }", "function countDown() {\n counter--;\n $(\"#time\").html(\"Timer: \" + counter);\n\n if (counter === 0) {\n timeReset();\n \n \n\n\n }\n}", "function countDown() {\n if (_timeRemaining > 0) {\n\n // This function will be called as frequently as the _refreshRate variable\n // dictates so we reduce the number of milliseconds remaining by the\n // _refreshRate value for accurate timing\n _timeRemaining -= _refreshRate;\n\n // Publish the fact that the remaining time has changed, passing along the\n // new time remaining as a percentage - which will help when we come to display\n // the remaining time on the game board itself\n Frogger.observer.publish(\"time-remaining-change\", _timeRemaining / _timeTotal);\n } else {\n\n // If the remaining time reaches zero, we take one of the player's remaining\n // lives\n loseLife();\n }\n }", "function countDown(){\n if (gameStart=true){\n remainingTime--;\n $(\"#timeRemain\").html(remainingTime + \" seconds\");\n if (remainingTime<=0){\n gameStart=false;\n }\n }\n }", "function showCountdown(){\n console.log(\"in showcountdown\");\n seconds--;\n $('#timeLeft').html('<h3>Time Remaining: ' + seconds + '</h3>');\n if(seconds < 1){\n clearInterval(time);\n answered = false; \n PopulateAllAnswers(); \n }\n }", "function startCountdown() {\r\n var actualTime,\r\n compareTime = new Date().getTime() / 1000;\r\n\r\n clearInterval(countdownInterval);\r\n\r\n // start countdown\r\n countdownInterval = setInterval(function() {\r\n actualTime = new Date().getTime() / 1000;\r\n\r\n if (actualTime - compareTime > 2) {\r\n socket.emit('request_departures_from_client');\r\n clearInterval(countdownInterval);\r\n countdownEl.innerHTML = 'loading';\r\n return;\r\n }\r\n\r\n compareTime = actualTime;\r\n\r\n if (counter > 0) {\r\n counter = counter - 1;\r\n counter2 = counter2 - 1;\r\n }\r\n\r\n countdownEl.innerHTML = secondsToTimeformat(counter);\r\n countdown2El.innerHTML = secondsToTimeformat(counter2);\r\n\r\n if (counter < 180) {\r\n countdownEl.className = 'hurry';\r\n } else if (counter < 360) {\r\n countdownEl.className = 'intermediate';\r\n } else {\r\n countdownEl.className = 'easy';\r\n }\r\n }, 1000);\r\n }", "function startCountDown() {\n countdownTime--;\n questionCounter.innerHTML = countdownTime;\n}", "function countdown(){\n console.log(\"incountdown\");\n seconds = 15;\n $('#timeLeft').html('<h3>Time Remaining: ' + seconds + '</h3>');\n answered = true; \n time = setInterval(showCountdown, 1000);\n }", "function countDown() {\n counter--;\n $('#timer').html(counter);\n if (counter === 0){\n timeUp()\n }\n}", "function countdown_trigger(){\n if (countdown_number > 0) {\n countdown_number--;\n $(\"#countdown-text-time\").html(countdown_number);\n if(countdown_number > 0) {\n countdown = setTimeout(countdown_trigger, 1000);\n }\n } \n if (countdown_number === 0) {\n answered_right = \"wrong\";\n answered_timeout = true;\n countdown_clear();\n answer_page();\n }\n}", "function timeCount () {\n timer--;\n $(\".timerArea\").html(\"remaining time : \" + timer);\n }", "function myClock() {\n document.getElementById(\"countdown\").innerHTML = --count;\n if (count == 0) {\n clearInterval(myTimer);\n alert(\"Times Up!\");\n }\n }", "function countdownTimer() {\n console.log(\"Here is a countdown timer\")\n}", "function cuentaRegresiva(){\r\n $('.cuenta-regresiva').countdown('2021/12/10 09:00:00', function(event){\r\n $('#dias').html(event.strftime('%D'));\r\n $('#horas').html(event.strftime('%H'));\r\n $('#minutos').html(event.strftime('%M'));\r\n $('#segundos').html(event.strftime('%S'));\r\n });\r\n}", "function countdown()\n{\n // Cette fonction va être exécutée chaque seconde... qu'est-ce que je veux faire chaque seconde ?\n\n // On décrémente de 1 le compte à rebours : soit on récupère la valeur actuelle dans le code HTML, soit on crée une variable pour stocker cette information\n // count = bomb.textContent; \n count--;\n\n // Si on est arrivé à 0 \n if (count == 0) {\n\n // Alors on arrête le chronomètre avec la fonction clearInterval()\n clearInterval(timer);\n\n // et on supprime la bombe du DOM\n bomb.remove();\n }\n // Sinon, on n'est pas encore arrivé à 0...\n else {\n\n // On affiche la nouvelle valeur du compteur\n bomb.textContent = count;\n }\n}", "function countdown() {\n\t\t\tif (secondsLeft == 0) {\n\t\t\t\tclearInterval(timerId); // Should stop the timer\n\t\t\t\tclearInterval(moveTimer); // Should stop the timer\n\t\t\t\tthis.gotoAndStop(\"GameOver\");\n\t\t\t} else {\n\t\t\t\tsecondsLeft--; // reduce seconds by 1\n\t\t\t\t// Next line is optional - same as above\n\t\t\t\tthis.countdownDisplay.text = secondsLeft; // update the text field\n\t\t\t}\n\t\t}", "static countdown() {\n jQuery('.js-countdown').countdown((new Date().getFullYear() + 2) + '/02/01', (e) => {\n jQuery(e.currentTarget).html(e.strftime('<div class=\"row items-push push text-center\">'\n + '<div class=\"col-6 col-md-3\"><div class=\"font-size-h1 font-w700 text-white\">%-D</div><div class=\"font-size-sm font-w700 text-muted\">DAYS</div></div>'\n + '<div class=\"col-6 col-md-3\"><div class=\"font-size-h1 font-w700 text-white\">%H</div><div class=\"font-size-sm font-w700 text-muted\">HOURS</div></div>'\n + '<div class=\"col-6 col-md-3\"><div class=\"font-size-h1 font-w700 text-white\">%M</div><div class=\"font-size-sm font-w700 text-muted\">MINUTES</div></div>'\n + '<div class=\"col-6 col-md-3\"><div class=\"font-size-h1 font-w700 text-white\">%S</div><div class=\"font-size-sm font-w700 text-muted\">SECONDS</div></div>'\n + '</div>'\n ));\n });\n }", "function startTimer(){\n $('.countDown').fadeIn('fast');\n $('.countDown').html('&nbsp;');\n\n\t\tvar timeRemain = 11;\n\n\t\tfunction run(){\n\t\t\tintervalId = setInterval(decrement, 1000);\n\t\t}\n\t\t\n \tfunction decrement() {\n\t\t\ttimeRemain--;\n\t\t\t$(\".countDown\").html(timeRemain);\n\t\t\tif (timeRemain === 0) {\n\t\t\t\t$('.countDown').html('0');\n\t\t\t\tstop();\n\t\t\t\ttimeUp();\n\t\t\t}\n\t\t\t\n \t}\n \tfunction stop() {\n\t\t\tclearInterval(intervalId);\n \t}\n run();\n \n }", "function countdown(){\n seconds = 20;\n $(\"#timeLeft\").html(\"00:\" + seconds);\n answered = true;\n //Sets a delay of one second before the timer starts\n time = setInterval(showCountdown, 1000);\n }", "function countDown() {\n counter--;\n\n $('#time').html(`\n <h5>:${counter}</h5><p>\n `)\n if (counter === 0) {\n timeUp();\n }\n}", "function timer() {\n count--;\n $(\"#countdown\").css(\"background\", \"#70D1FF\");\n $(\"#countdown\").css(\"color\", \"\");\n\n\n if (timerStop === true) {\n clearInterval(counter);\n return;\n\n } else if (count <= 5 && count > 0) {\n $(\"#countdown\").css({\n background: 'red',\n color: 'white'\n });\n } else if (count <= 0) {\n clearInterval(counter);\n timeUp();\n return;\n }\n\n $(\"#countdown\").html(\"Timer: \" + count)\n }", "function countdown() {\t\t\t\n\t\t\tsec--;\n\t\t\t\t\t\t\n\t\t\tif(min===0 && sec===0) { // use 'min < 0' for 0:00, 'min===0 && sec===0' for 0:01\t\t\t\t\n\t\t\t\tself.noCrew();\n\t\t\t\t$(timerID).addClass(\"fade-grey\");\n\t\t\t\tself.stopCountdown();\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tself.done = true;\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tself.resetTime();\n\t\t\t\ttimerDone();\t\t\t\t\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\n\t\t\telse if(sec === 0) {\n\t\t\t\t$(timerID).html(min+\":0\"+sec)\t\t\t\t\t\t\t\n\t\t\t\tmin--;\n\t\t\t\tsec = 60;\t\t\t\n\t\t\t}\n\t\t\telse if(sec > 9) {\n\t\t\t\t$(timerID).html(min+\":\"+sec);\t\t\t\t\t\t\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$(timerID).html(min+\":0\"+sec);\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\tif(timerID != \"#deck-timer\") {\n\t\t\t\t//Make timer red when timer is 1 min or less\n\t\t\t\tif(min === 0) {\n\t\t\t\t\t$(timerID).addClass(\"red-timer\");\t\t\t\t\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse{\n\t\t\t\t\t$(timerID).removeClass(\"red-timer\");\n\t\t\t\t}\n\t\t\t\t//Flash red at halfway point\t\t\t\t\n\t\t\t\tif(minute > 2) {\n\t\t\t\t\tif(minute%2 != 0 && sec === 30 && min === Math.floor(minute/2) || minute%2 === 0 && sec === 60 && min === minute/2-1) {\n\t\t\t\t\t\t$(timerID).addClass(\"fade-red\");\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\t\t\t\t\t\t\t\n\t\t\t}\t\t\t\t\t\t\n\t\t}//countdown() end", "function countdown() {\n\tcount = 20;\n\tcounter = setInterval(timer, 1000);\n\tfunction timer() {\n\t\tcount--;\n\t\tif (count === 0) {\n\t\t\t// Counter ended, stop timer and move on to the next question\n\t\t\tclearInterval(counter);\n\t\t\tgetNewQuestion();\n\t\t\treturn;\n\t\t}\n\t\t// Dispay the number of seconds\t\n\t\t$(\"#timer\").text(count);\n\t}\n}", "function beginCountDown() {\n\n // Countdown by the interval indentified in timerInterval\n time--;\n\n // When the time runs out (i.e. reaches zero) do the following...\n if (time <= 0) {\n\n playerScoreEl.textContent = score + \"/\" + questionsList.length;\n\n // Remove the 'hide' css class to display the store score page\n storeScore.removeAttribute(\"class\");\n\n // Apply the css styling to the store score page\n storeScore.setAttribute(\"class\", \"store-container\");\n\n // Clear the timer\n clearInterval(timerInterval);\n\n // Set timer to zero\n time = 0;\n\n // Reapply 'hide' css class to make the quiz section invisible\n revealQuiz.setAttribute(\"class\", \"hide\");\n };\n\n // Display time left as a text value in the timer element of the html\n timeLeftelement.textContent = time;\n}", "function userInterfaceCountdown() {\n // time--;\n $(\"#countitdown\").html(time + \" \" + \"Seconds\");\n if(time > 0) {\n time--;\n } else {\n // clearInterval(userInterfaceCountdown);\n $(\"#duringgame\").hide();\n $(\"#gameover\").show();\n gameFinished();\n }\n}", "timer() {\n\t\tlet minutes = 20;\n\t\tlet minInMs = minutes * 60 * 1000;\n\n\t\tlet chrono = setInterval(() => {\n\n\t\t\tlet time = Date.now() - Number(sessionStorage.getItem(\"count\"));\n\n\t\t\tlet timeRemain = minInMs - time;\n\n\t\t\tlet minuteRemain = Math.floor(timeRemain / 1000 / 60)\n\t\t\tlet secondsRemain = Math.floor(timeRemain / 1000 % 60);\n\n\t\t\tif (String(secondsRemain).length === 1) {\n\t\t\t\tsecondsRemain = \"0\" + secondsRemain;\n\t\t\t}\n\t\t\tif (time < minInMs) {\n\t\t\t\t$(\"#time\").text(minuteRemain + \"min \" + secondsRemain + \"s\");\n\t\t\t} else {\n\t\t\t\tclearInterval(chrono);\n\t\t\t\tsessionStorage.clear();\n\t\t\t\t$(\"#booking-details\").hide();\n\t\t\t}\n\t\t}, 1000);\n\t}", "function countDown() {\n countdown--;\n $(\"#countdown\").html(countdown);\n console.log(countdown);\n if (countdown === 0) {\n alert(\"Time is up!\");\n clearInterval(intervalId);\n scoreGame();\n }\n}", "function timer(){\n\t\n\t\n\tcounter--;\n\n\t\t\tif( counter >= 0 ){\n\t\t\t\t\n\t\t\t\tid = document.getElementById(\"count\");\n\t\t\t\tid.innerHTML = counter;\n\t\t\t}\n\n\t\t\tif( counter == 0 ){\n\t\t\t\talert(\"You are out of time, the order is canceleld \\n Returning to homepage\");\n\t\t\t\tlocalStorage.clear();\n\t\t\t\tlocation.href=\"index.php\";\n\t\t\t}\n\t\n}", "function countdown() {\n timer.textContent = timeLeft;\n if (timeLeft > 0) {\n timeLeft--;\n }\n if (timeLeft === 0) {\n clearInterval(intervalId);\n }\n}", "function countdown() {\n time--;\n timerCountdown.textContent = time;\n\n // check if user ran out of time\n if (time <= 0) {\n quizEnd();\n }\n}", "function countDown() {\n // Decrease one second\n timeLeft -= 1;\n\n // Update the time remaining on the web page\n if (timeLeft === 1) { // Change \"Seconds\" to \"Second\" for 1 secsond remaining\n $(\"#seconds\").text(timeLeft + \" Second\");\n } else {\n $(\"#seconds\").text(timeLeft + \" Seconds\");\n }\n\n // Shorten the bar after each second\n $(\".progress-bar\").css(\"width\", timeLeft / START_TIME * 100 + \"%\");\n\n // Change the bar color to red to inform the user that time is almost up\n if (timeLeft <= 3) {\n $(\".progress-bar\").removeClass(\"bg-info\");\n $(\".progress-bar\").addClass(\"bg-danger\");\n }\n\n // Once the user runs out of time\n if (timeLeft === 0) {\n // Increase the number of unaswered questions\n numUnaswered++;\n console.log(\"ran out of time\");\n\n // Pause timer and show answer\n showAnswer(\"time\");\n\n // Highlight correct answer in green\n highlightAnswer();\n\n // Wait 3 seconds before moving on to the next question\n setTimeout(function() {\n // Decide if there is still a question that still needs to be answered\n questionOrStats()\n }, 3000);\n }\n }", "function countdown(t) {\r\n display_element.querySelector('#rpm-feedback').innerHTML = '<p>'+t+'</p>';\r\n }", "function countDown() {\n timeRemaining--;\n $('#timeCount').text(timeRemaining);\n if (timeRemaining <= 0 && count === 10) {\n clearInterval(time);\n answered.push(\"0\")\n finalScreen();\n } else if (timeRemaining <= 0) {\n clearInterval(time);\n answered.push(\"0\");\n loadingScreen();\n }\n}", "function startCountDown() {\n counter = setInterval(function () {\n count--;\n document.getElementById(\"timer\").innerHTML = count + \" seconds\";\n if (count == 0) {\n clearInterval(counter);\n endQuiz();\n }\n }, 1000);\n\n }", "function countdown() {\n count--;\n counter.textContent = count;\n if (count == 0) {\n gameOver()\n }\n }", "countdown() {\n\t\tif(this.timer < 1) {\n\t\t\tthis.endInterval();\n\t\t\tthis.App.clientComms.emitToAllSockets('puzzle', this.App.game.puzzleArray);\n\t\t\tthis.endRound();\n\t\t} else {\n\t\t\tthis.timer--;\n\t\t\tthis.App.data.updateTimer(this.timer);\n\t\t\tthis.clueHandler();\n\t\t}\n\t}", "function start (){\n\t\tintervalId = setInterval(countdown, 1000);\n\t}", "function UpdateCountDown (time : float) {\n\tvar displayTime = Mathf.CeilToInt(time);\n\tvar displayText = displayTime==0 ? \"\" : displayTime.ToString();\n\tcountdown.text = displayText;\n}", "function counterFunc() {\n //check if seconds has reached zero to enable alarm sound\n if (timer < 0) {\n clearInterval(countDown); //stop the setInterval method\n playAlarm();\n } else {\n //convert the seconds to time and extract the relevant portion\n const timerVal = new Date(timer * 1000).toISOString().substr(14, 5); //.substr(11,8) to include hr\n counter.innerText = `Time Remaining: ${timerVal}`;\n timer -= 1; //decrement the seconds counter by one\n }\n }", "function countDown () {\n timer -= 1\n clock.textContent = timer\n if (timer === 0) {\n window.alert(\"'Time's up! your score is \" + scoreLine)\n window.location.reload()\n }\n }", "function countDown1() {\n // Set the date we're counting down to7\n // for (var addobject of dataArrayTijdStamp) {\n var countDownDate = SelfMadeTrainObject.realtime[0];\n console.log(countDownDate);\n\n // Update the count down every 1 second\n\n\n // Get today's date and time\n var now = Math.round(new Date().getTime() / 1000);\n\n // Find the distance between now and the count down date\n var distance = countDownDate - now;\n\n // Time calculations for days, hours, minutes and seconds\n var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60));\n var minutes = (Math.floor((distance % (60 * 60)) / (60)) < 10 ? '0' : '') + Math.floor((distance % (60 * 60)) / (60));\n var seconds = (Math.floor((distance % (60))) < 10 ? '0' : '') + Math.floor((distance % (60)));\n\n // Display the result in the element with id=\"demo\"\n AftelTijd = hours + \"h \" + minutes + \"min \" + seconds + \"sec \";\n\n document.getElementById(\"js-timer-1\").innerHTML = AftelTijd;\n console.log(AftelTijd);\n\n // If the count down is finished, write some text\n if (distance < 0) {\n // clearInterval(interval);\n AftelTijd = \"Trein vertrokken\";\n document.getElementById(\"js-timer-1\").innerHTML = AftelTijd;\n console.log(\"Expired\")\n }\n progressBar1(countDownDate);\n\n\n}", "function countdown() {\n // timer.innerHTML = timeLeft;\n var timeInterval = window.setInterval(function () {\n timeLeft--\n timer.innerHTML = timeLeft;\n if (timeLeft === 0) {\n clearInterval(timeInterval)\n }\n // console.log(\"time\", timer, timeLeft)\n }, 1000);\n\n introEl.classList.add('btn-hide')\n startBtn.classList.add('btn-hide');\n questionEl.classList.remove('hide');\n answersLi.classList.remove('hide');\n\n}", "function countdown(){\n if(timeLeft==0){\n clearTimeout(timerID);\n checkAnswer(\"\");\n }\n else{\n timeLeft--;\n $(\"#timeRemaining\").html(timeLeft + \" seconds\");\n }\n }", "function countdown() {\n\tconsole.log(\"countdown\");\n\tif(secsLeft.innerText<=0){\n\t\tsecsLeft.innerText=60;\n\t\tminsLeft.innerText--;\t\t\n\t};\n\tsecsLeft.innerText--;\n\t\n\tif(secsLeft.innerText<=0 && minsLeft.innerText<=0){\n\t\twindow.clearInterval(begin);\n\t};\n}" ]
[ "0.7374361", "0.72822064", "0.72148097", "0.7186722", "0.7177281", "0.7176871", "0.7135527", "0.7130493", "0.71292883", "0.70448345", "0.7040736", "0.69690907", "0.69690514", "0.6960145", "0.69167423", "0.6907455", "0.687414", "0.6863684", "0.68504184", "0.6841362", "0.68405104", "0.68288535", "0.68282235", "0.6815687", "0.68156713", "0.67959374", "0.67760104", "0.6752238", "0.6729381", "0.671838", "0.6712098", "0.6709981", "0.670836", "0.670553", "0.66950494", "0.66874593", "0.668468", "0.6665009", "0.665099", "0.6646718", "0.6643437", "0.6598097", "0.6591206", "0.6577406", "0.65562", "0.65550834", "0.6548914", "0.6542794", "0.6538673", "0.65343", "0.65270215", "0.6522707", "0.65133756", "0.65061444", "0.6499264", "0.6492676", "0.64740235", "0.6472834", "0.6469642", "0.6469607", "0.64678943", "0.64666885", "0.64633834", "0.64616096", "0.64456856", "0.64429986", "0.64411956", "0.6435983", "0.64272326", "0.64263546", "0.64247835", "0.64238316", "0.6422915", "0.6417942", "0.6416645", "0.641252", "0.6394844", "0.63841134", "0.6384027", "0.6374693", "0.63606775", "0.63577217", "0.63565093", "0.63484037", "0.63464534", "0.6345363", "0.6336418", "0.63323486", "0.6332133", "0.6308688", "0.63073385", "0.6306436", "0.6306228", "0.630098", "0.62959796", "0.62911093", "0.62904686", "0.6285677", "0.6273965", "0.6272934", "0.6272854" ]
0.0
-1
this will stop doubling the timer further when respective hit button is pressed
function timer() { setTimeout("decrement()", 60); if (click === 0) { btn1.removeEventListener("click", timer); } if (click === 1) { btn2.removeEventListener("click", timer); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function stopClick(){\n clearInterval(intervalId);\n currentTime= 1;\n time.innerHTML= currentTime;\n noDanger();\n next.click();\n}", "function theFinalCountDown(){\n var timerDisplay = $(\"#timerDisplay\");\n var timeCounter= 10;\n var countDownInterval = window.setInterval(function(){\n timeCounter--;\n timerDisplay.html(\"Timer \" + timeCounter);\n\n if(timeCounter<1){\n clearInterval(countDownInterval);\n // call function that stops everything\n keeprunning = false;\n startSound.stop();\n secondPlayerAnimate = true;\n // clears screen of objects when time runs out\n $('.target').hide(); \n $('.startButton').html(\"PLAYER2\");\n //Show the score div\n scoreShow();\n\n $('.startButton').click(startEverythingForPlayer2);\n } \n }, 1000);\n }", "function timesPress() {\n\ttimesModel = true;\n\tisHumanTimes = true;\n\tstart.style.display =\"none\";\n\tbutton3.style.display = 'block';\n\tif (!humanModel){\n\t\ttimesModel = false;\n\t\taimove();\t\n\t}\n\t\n}", "function countDown(){\n\t\ttime --;\n\t\tupdate($timer, time);\n\n\t\tif (time <= 0){\n\t\t\thide($timer);\n\t\t\tgameOver();\n\t\t}\n\t}", "handleStop() {\n console.log(\"Stop\");\n this.setState({ timerRunning: false })\n clearInterval(this.timer)\n this.state.buttonActive === \"shortBreak\" ?\n relaxingFive.pause() :\n relaxingTen.pause()\n }", "function stopTimer() {\n secondsElapsed = 0;\n setTime();\n renderTime();\n}", "_stopTimer() {\n this.game.time.events.remove(this.timer)\n }", "function stopTimer() {\n\tclearInterval(countUp);\n}", "function t_stopTimer() {\n \n if (t_mins>=0 && !t_istiming) {\n var t_stopbutton = document.getElementById(\"t_stopbutton\");\n t_stopbutton.innerHTML=\"Pause\"\n t_timer = setTimeout(\"t_updateTime()\",1000);\n t_istiming = true;\n } else if (t_istiming) {\n clearTimeout(t_timer);\n //var t_startbutton = document.getElementById(\"t_startbutton\");\n var t_stopbutton = document.getElementById(\"t_stopbutton\");\n t_stopbutton.innerHTML=\"Resume\"\n t_istiming = false;\n }\n \n}", "function stopTimer(){\r\n clearInterval(timer);\r\n }", "function timerClick() {\n\n \n\n if (timer === null) {\n timer = setInterval(countdown, 1000);\n } else {\n clearInterval(timer);\n timer = null;\n }\n}", "function stop_btn_OnTouch() {\n skb.SetValue(500);\n skb1.SetValue(900);\n _speed = 500;\n _angle = 900;\n}", "function countDown() {\n // decrease time by 1\n time--;\n // update the time displayed\n update($timer, time);\n // the game is over if the timer has reached 0\n if (time <= 0) {\n gameOver();\n }\n }", "function pauseTimer() {\n clearTimeout(timer);\n buttonElement.disabled = false;\n pomodoroElement.disabled = false;\n breakElement.disabled = false;\n}", "function minimumTimeHandler(a) {\n if(buttonTimeCountingDown < (minimumTime*1000)){\n resetButton();\n }\n}", "function stopTimer() {\n clearTimeout(timeCounter);\n }", "function abortTimer() {\n\t\t//actually set the right value, to fix rounding errors and the such.\n\t\tel.html(target);\n\t\t//clear the interval, huzzah!\n\t\tclearInterval(tid);\n\t}", "function countDown() {\n seconds -= 1;\n\n if (seconds < 0 && minutes > 0) {\n seconds += 60;\n minutes -= 1;\n }\n else if (seconds === -1 && minutes === 0) {\n // Timer is done. Call relevant functions\n stopTimer();\n PEvents.timerDone(currentTimerType);\n loadTimer();\n }\n \n render();\n }", "function unTouch() {\r\n // Clears setInterval timer\r\n clearInterval(time);\r\n}", "function countDown(){\n\t\t\ttime--;\n\t\t\tupdate($timer, time);\n\t\t\tif(time <= 0){\n\t\t\t\tgameOver();\n\t\t\t}\t\t\n\t\t}", "function onTimesUp() {\n clearInterval(timerInterval);\n}", "function stopCount() {\n\tclearTimeout(t);\n\ttimer_is_on = 0;\n}", "function stopTimer() {\r\n\r\n timerControl = false;\r\n stopTime = getCurrTime();\r\n totalPassedTime += calcPassedTime(initTime, stopTime);\r\n localStorage[\"timer\"] = JSON.stringify(totalPassedTime);\r\n lapInitialTimer = 0;\r\n \r\n initTime = stopTime;\r\n btnReset.classList.remove(\"inactive\");\r\n btnLap.classList.add(\"inactive\");\r\n}", "function stopTimer(){\r\n clearInterval(timeInterval);\r\n playBtn.style.display='block';\r\n pauseBtn.style.display='none';\r\n elapsedTime = 0;\r\n}", "function pauseTimer(){\n clearInterval(timerInterval);\n timerInterval = null;\n startButton.attr('disabled', false);\n }", "function stopTimer(){\n clearInterval(timer);\n }", "function stopTimer() {\n\n // stop the countdown\n clearInterval(time);\n // removes the timer from the html\n $(\"#timer\").empty();\n // call the check answers function\n checkAnswers();\n }", "function stopTime() {\n // Clear the timer\n clearInterval(countDown);\n}", "function onTimer(){\r\n\tif (turn == OPPONENT) return;\r\n\tupdate_handler({time:timer});\r\n\ttimer--;\r\n\tif (timer < 0){\r\n\t\tmissStep();\r\n }\r\n}", "function breakTimer() {}", "function startTimer(){\r\n timePlayed = 0;\r\n penaltyTime = 0;\r\n finalTime = 0 ;\r\n timer = setInterval(addTime,100);\r\n gamePage.removeEventListener('click',startTimer);\r\n}", "function stopTimer(){\r\n clearInterval(aux)\r\n document.getElementById(\"startButton\").disabled = false\r\n}", "function onStop(event)\n{\n tmp_pos=pos;\n pos=362;\n runBtnProp(false);\n stopBtnProp(true);\n\n}", "function stop () {\n if (updateTimer) {\n clearInterval(updateTimer)\n }\n }", "function stop () {\n if (updateTimer) {\n clearInterval(updateTimer)\n }\n }", "function endTracking() {\n tryingToTrack = false;\n timeCounter = 0;\n\n $(\"#stopTrackingMe\").css({\n \"display\": \"none\"\n });\n $(\"#extendTrackingMe\").css({\n \"display\": \"none\"\n });\n $(\"#extendTrackingMe\").on('click', () => {\n alert(\"Timer set to 30 mins\")\n });\n $(\"#startTrackingMe\").css({\n \"display\": \"inline-block\"\n });\n }", "function removeTime() {\r\n onlyOnce = false;\r\n setScreen();\r\n $(window).unbind('mousewheel keydown');\r\n setTimeout(function() {\r\n $('#close-gate').click();\r\n }, 10 * 1000);\r\n }", "function stop_the_game(){\n clearInterval(the_game);\n game_over = true;\n restart_btn.slideDown();\n }", "function timer(){\n\n decrease ++\n\n let timeLeft = seconds - decrease\n\n vision.innerHTML = convert(timeLeft)\n\n // console.log(\"current timer: \", seconds, decrease);\n //if count = 0 we set the input to the uri of the canvas\n if(timeLeft == 0){\n\n // sets th canvas to be unclickable\n canvas.style.setProperty(\"pointer-events\", \"none\")\n\n // stops the set interval\n clearInterval(countdown);\n\n }\n\n\n }", "function stopTimer() {\n if (!stoptime) {\n stoptime = true;\n }\n}", "function stop() {\n clearInterval(interval);\n able_start_button();\n $.post(\n '/server/index.php',\n { action : 'timer_pause', seconds : seconds }\n );\n }", "function stopTimer() {clearTimeout(startTimer)}", "function stopTimer(){\n clearInterval(timer); // stops interval.\n } // end stopTimer.", "function stopTime ()\t{\n\t\t\tclearInterval (time);\n\t\t}", "function startTimer() {\n timer = setTimeout(function () {\n $btn.removeClass('d-none');\n }, 60 * 1000);\n}", "function stopTimer (){\n if(currentPlayer == player1) {\n player1.time = seconds;\n $('#player1Time').text(seconds);\n switchTurns();\n } else {\n player2.time = seconds\n $('#player2Time').text(seconds);\n checkScore();\n switchTurns();\n }\n //return seconds = 0;\n clearInterval(timer);\n seconds=0;\n snitch.addEventListener('click', startTimer);\n}", "function level_screen_go()\n{\n //Decrement the value\n a--;\n\n //Reflect the modified value\n level_screen_timer.innerText=a;\n\n //Logic for when timer goes zero\n if(a==0)\n {\n //Make the question button appear\n level_screen_level_question_button.style.display=\"block\";\n //Clear the timer\n\n //Ref 4\n //Answer Link:https://stackoverflow.com/questions/21714860/stop-javascript-counter-once-it-reaches-number-specified-in-div\n clearInterval(tid);\n //Insert display meessage for the user\n level_screen_next_instruction.innerHTML=\"Well done ! Keep the counts ready and go solve the question on the next screen within 10 seconds!!\";\n }\n}", "function time_stop(){\n\t\t\t\tclearInterval(timeinterval);\n\t\t\t}", "function unTouch() {\n // Clears setInterval timer\n clearInterval(time);\n}", "function stopTimer() {\n // check timer is on or off\n if (stopTime == false) {\n stopTime = true;\n }\n }", "function stopTimer() {\n\tclearInterval(timer.timer);\n\t$(\"#final-time\").html($(\"#time\").html());\n}", "function verde2() {\n let interval=setInterval(()=>{\n if(object.time.className==\"red\" && object.start==null){\n object.time.className=\"green\"\n object.tap.removeEventListener(\"touchstart\", red)\n object.tap.addEventListener('touchend', start2)\n }\n else if(object.time.className==\"red\" && object.start==2){\n object.time.className=\"green\"\n object.tap.removeEventListener(\"touchstart\", red)\n object.tap.addEventListener('touchend', reset2)\n }\n },1000);\n \nobject.tap.addEventListener('touchend', ()=>clearInterval(interval))\n}", "function stopTimer() {\n clearInterval(timer);\n }", "function stop(){\r\n //this tells the timer to clear when the stop button is pressed. Start will start from beginning.\r\n clearInterval(timer);\r\n document.getElementById(\"stopButton\").disabled = true;\r\n document.getElementById(\"startButton\").disabled = false;\r\n}", "function decrement() {\n $(\"#timerL\").html(\"<h3>Watch the clock! \" + timer + \"</h3>\");\n timer--;\n if (timer === 0) {\n unAnswered++;\n stop();\n $(\"#answerblock\").html(\"<p>You didn't watch the clock! The correct answer is: \" + pick.choice[pick.answer] + \"</p>\");\n hidepicture();\n }\n }", "onStopClick ()\n {\n clearInterval(this.interval);\n this.interval = null;\n this.lastUpdated = null;\n }", "function timesUp() {\n timer--;\n\n $(\"#timer\").text(timer);\n if (timer === 0) {\n // clearInterval(countDown);\n // i++;\n timerTwo = 8;\n unanswered++;\n $(\"#gap-time\").show();\n // i++;\n gifTimer();\n booYou();\n }\n}", "stopGame() {\n if (this.state.isOn) {\n this.addScore();\n }\n this.setState({isOn: false, time: 0});\n clearInterval(this.timer);\n clearInterval(this.timerColor);\n }", "function stopwatch() {\n\tgameTime++;\n\titemTimer.innerText = gameTime /100;\n\t//statement to stop the game when time is too long\n\tif (gameTime == 9999) { // set max. time value (100 = 1 [s])\n\t\ttoStopWatch();\n\t\tmodalToLong();\n\t} else {\n\t\t\n\t}\n}", "function decrement() {\n number--;\n $(\"#timer\").text(number);\n if (number === 0) {\n stop();\n $(\"#question, #choices\").hide();\n $(\"#timer\").html(\"<h2>Times Run Out! Start Over!</h2>\");\n restarting = false;\n $(\"#start\").show();\n }\n }", "function timer()\n{\n\tdocument.getElementById(\"button\").disabled = true; //Disables the id that has 'button'.\n\ttimersubtract = setInterval(DealingHand, 1); //Goes to DealingHand() every 1 millisecond. defines timersubtract.\n}", "stop() {\n // TODO: set a 'stop' mode, that waits for a button press\n // TODO: check if this instruction's overloaded to also change the CPU clock\n // speed on GBC\n return 0;\n }", "function stopTimer(){ clearInterval(interval)}", "function stopTimer () {\n\t\tif (time) {\n\t\t\twindow.clearTimeout(time);\n\t\t}\n\t\ttime = 0;\n\t}", "function timer()\n\t{\n\t count=count-1;\n\t if (count <= 0)\n\t {\n\t \t$(\"#timer\").html(toMinutes(count));\n\t \tclearInterval(counter);\n\t $(\"#info\").html(\"<div width='100%' style='font-size:2em;text-align:center;font-weight:bold' >Time's up! Waiting for results...</div>\");\n\t $(\"#you-box\").attr(\"disabled\", true);\n\t $(\"#submit\").html(\"<h4>Thanks for your submission!</h4>\");\n\t $(\"#submit\").attr(\"submit\", \"true\");\n\t $(\"#submit\").attr(\"disabled\", true);\n\n\n\t return;\n\t }\n\n\t $(\"#timer\").html(toMinutes(count));\n\t updateOpponentBox();\n\t}", "function countDown() {\n // decrement time remaining\n timeRemaining--;\n // updates html with the time remaining\n $(\"#timer\").text(\"Time Remaining: \" + timeRemaining);\n // stops and removes the timer at zero \n if(timeRemaining < 1){\n \n // calls the stop timer function\n stopTimer();\n\n }\n }", "function cancelTimer() {\n clearInterval(timer);\n paused = true;\n newCountdown = true;\n startBtn.innerHTML = \"start\";\n countdown.style.color = \"black\";\n text.innerHTML = \"Move slider to set your timer, click start & begin studying...\";\n totalSecs = (slider.value)*60;\n clockKey = clockArr.length-1;\n displayTime();\n}", "function stopTimer()\n {\n clearInterval(timer);\n }", "function stopAnimation () {\r\n on = false; // Animation abgeschaltet\r\n clearInterval(timer); // Timer deaktivieren\r\n }", "function resetTimer(){\n clearInterval(timerInterval);\n timerInterval = null;\n startButton.attr('disabled', false);\n minutes.text('00');\n seconds.text('08');\n itsTimeFor.text('Time to do some work!');\n }", "stopTimer() {\n\t\t\tclearInterval(this.timer);\n\t}", "function tap () {\r\n startStop();\r\n if (tapTimer == null) {\r\n tapTimer = setTimeout(function () {\r\n tapTimer = null;\r\n }, 200)\r\n } else {\r\n clearTimeout(tapTimer);\r\n tapTimer = null;\r\n resetTheClock();\r\n alert('double tap');\r\n }\r\n}", "function timer(){\n countStartGame -= 1;\n console.log(countStartGame);\n if (countStartGame === 0){\n console.log (\"time's up\");\n //need to clear interval - add stop\n }\n}", "stopUpdate() {\n let timer = this.get('_timer');\n if (timer) {\n run.cancel(timer);\n }\n }", "function leClick(){\n startOrStop = !startOrStop;\n if (!startOrStop){\n if (clockState===0){\n $(\"#workHard\").css(\"font-size\", \"35px\");\n $(\"#playHard\").css(\"font-size\", \"18px\");\n }\n else{\n $(\"#workHard\").css(\"font-size\", \"18px\");\n $(\"#playHard\").css(\"font-size\", \"35px\");\n }\n $(\"#startButton\").text(\"Stop\");\n $(\"#startButton\").css(\"background-color\",\"red\");\n timerId = setInterval(finalCountdown, 1000);\n }\n \n if (startOrStop){\n $(\"#startButton\").text(\"Start\");\n $(\"#startButton\").css(\"background-color\",\"blue\");\n $(\"#workHard,#playHard\").css(\"font-size\", \"18px\");\n clearInterval(timerId);\n }\n }", "function stopTimer(){\n\t\tif(clock.inProgress == false){\n\t\t\taddInProgressRow();\n\t\t}\n\n\t\tclock.stopped = !clock.stopped;\n\t\tif(clock.stopped == false){\n\t\t\tclock.clockInterval = window.setInterval(addSecond, 1000);\n\t\t\tstop_btn.innerText= \"Stop\";\n\t\t\tstop_btn.style.backgroundColor = \"#96838F\";\n isTaskActive = true;\n\t\t} else{\n\t\t\tclearInterval(clock.clockInterval);\n\t\t\tstop_btn.innerText= \"Start\";\n\t\t\tstop_btn.style.backgroundColor = \"#53b56d\";\n isTaskActive = false;\n\t\t}\n\t}", "function onTimer(e) \n{\n\tif (e == \"clock\") \n\t{\n\t\tif (timerRunning) \n\t\t{\n\t\t\tdecreaseSecond();\n\t\t\tscene.setTimer(e, 1);\n\t\t}\n\t}\n}", "function startTimer() {\n //console.log(this); // the dom element clicked\n //console.log(this.dataset); // gives us the time associated to the element\n //console.log(this.dataset.time); // this gives us a string of the seconds\n // now let's put this into a variable\n const seconds = parseInt(this.dataset.time); // turning it into a real number\n //console.log(seconds); // perfecto amigo\n\n // from her let's just call the time functions and pass this variable\n timer(seconds);\n // oopsie doopsie youpsie moopsie daisy : when we click first it's perfect but when we click on another it goes back and forth between the last ones (yes all of them) and this one\n // we need a way to cancel the last timer as soon as we click / set up another\n // let's go back to the timer function\n}", "function stopDrag_2(){\n\t\tBasket_2.scale.setTo(0.3);\n\t\tif(Basket_2.y >410 && Basket_2.x <380 && Basket_2.x > 262){\n\t\t\t\t\t\tBasket_2.inputEnabled = false;\t\n\t\t\t\t\t\tBasket_2.x= '265.2';\n\t\t\t\t\t\tBasket_2.y= '529.7';\n\t\t\t\t\t\tScore++;\n\t\t\t\t\t\tsound[1].play();\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tBasket_2.x= BASKET_2_POSX;\n\t\t\t\t\t\t\t\t\tBasket_2.y= BASKET_2_POSY;\n\t\t\t\t\t\t\t\t\tBasket_2.scale.setTo(0.5);\n\t\t\t\t\t\t\t\t\tsound[2].play();\n\t\t\t\t\t\t\t\t\t}\n\t\tProcess();\t\t\n\t\t}", "function timerSeconds(){\n\t \t\t\n\t\t\twindow.setInterval(function(){\n\t\t\t$(\"#timer\").html(\"Timer: \" + seconds);\n\t\t \tseconds--;\n\t\t \tif (seconds === -2 && countAnswers !==40) {\n\t\t \n\t\t \t\t $(\"#timer\").off();\n\t\t \t\t $(\"#popLooser\").show();\n\t\t \t\t $(\"#mainContainer\").hide();\n\t\t \t}\n\t\t \n\t\t\t}, 1000);\n\t\t}", "function startGame()\n{\n \nbuttonStart.disabled = 'disabled';\nisPlaying = true;\nrenderScore();\n\ntimer = setInterval(clock,1000);// 1000 duration counting time\n}", "function ObserverButton() {\n\tclearTimeout(nextRound);\n\tclearTimeout(roundProgress);\n\tRoundTimer();\n}", "function question_screen_go()\n {\n //Fetch the Value of the timer storing HTML element\n // var a=parseInt(question_screen_timer.innerHTML);\n\n //Decrement the value\n aa--;\n\n //If value goes to zero then its time up\n if(aa==0)\n {\n //Clear the interval\n //Ref 4 based on stackoverflow in licenses.txt\n // Answer Link:https://stackoverflow.com/questions/21714860/stop-javascript-counter-once-it-reaches-number-specified-in-div\n\n clearInterval(question_screen_tid);\n //Set the Value again\n question_screen_timer.innerHTML=\"Times Up!!Try Again!!!!!!\";\n //Make the button disabled\n question_screen_check_button.disabled=true;\n question_screen_restart_button.style.display=\"block\";\n question_screen_welcome_button.style.display=\"block\";\n\n //Update the stats\n gameData.gamesPlayed++;\n gameData.timer=10;\n\n var present_highest_score=gameData.highestScore;\n\n if(question_score>present_highest_score)\n {\n gameData.highestScore=question_score;\n }\n\n\n }\n\n else if(aa>0)\n {\n //Again reset the value\n question_screen_timer.innerText=aa;\n\n }\n }", "function stopDrag_4(){\n\t\tBasket_4.scale.setTo(0.3);\n\t\tif(Basket_4.y >420 && Basket_4.x <120 && Basket_4.x >8 )\n\t\t{\n\t\t\tBasket_4.inputEnabled = false;\t\n\t\t\tBasket_4.x= '28.3';\n\t\t\tBasket_4.y= '536.3';\n\t\t\tScore++;\n\t\t\tsound[1].play();\n\t\t\t}else {\t\t\t\t\t\n\t\t\t\t\tBasket_4.x= BASKET_4_POSX;\n\t\t\t\t\tBasket_4.y= BASKET_4_POSY;\n\t\t\t\t\tBasket_4.scale.setTo(0.5);\n\t\t\t\t\tsound[2].play();\n\t\t\t\t\t}\n\t\tProcess();\t\t\n\t\t}", "function stopDrag_1(){\n\t\tBasket_1.scale.setTo(0.3);\n\t\tif(Basket_1.y >401 && Basket_1.x <560 && Basket_1.x >460){\n\t\t\tBasket_1.inputEnabled = false;\t\n\t\t\tBasket_1.x= '493.9';\n\t\t\tBasket_1.y= '542.9';\n\t\t\tScore++;\n\t\t\tsound[1].play();\n\t\t\t}else{\n\t\t\t\t\tBasket_1.x= BASKET_1_POSX;\n\t\t\t\t\tBasket_1.y= BASKET_1_POSY;\n\t\t\t\t\tBasket_1.scale.setTo(0.5);\n\t\t\t\t\tsound[2].play();\n\t\t\t\t\t}\n\t\tProcess();\t\t\t\t\t\t\t\n\t\t}", "function stopDrag_3(){\n\t\tBasket_3.scale.setTo(0.3);\n\t\tif(Basket_3.y >410 && Basket_3.x <840 && Basket_3.x > 730){\n\t\t\tBasket_3.inputEnabled = false;\t\n\t\t\tBasket_3.x= '721.8';\n\t\t\tBasket_3.y= '526.3';\n\t\t\tScore++;\n\t\t\tsound[1].play();\n\t\t\t}else{\n\t\t\t\tBasket_3.x= BASKET_3_POSX;\n\t\t\t\tBasket_3.y= BASKET_3_POSY;\n\t\t\t\tBasket_3.scale.setTo(0.5);\n\t\t\t\tsound[2].play();\n\t\t\t\t}\n\t\tProcess();\t\t\t\t\t\t\t\n\t\t}", "function stopTimer(){\n clearInterval(timer);\n}", "function stop() {\n\tclearTimeout(updating);\n}", "handleChangeTimer(options) {\n this.setState(options)\n relaxingFive.currentTime = 0;\n relaxingTen.currentTime = 0;\n relaxingFive.pause()\n relaxingTen.pause()\n this.setState({\n timerRunning: false,\n })\n clearInterval(this.timer)\n }", "_stopTimer() {\n this._tock.end();\n }", "function stop() {\n timer.stop();\n}", "function stopTimer() {\n\tclearInterval(counter);\n\t$(\"#timer\").text(count);\n\treturn;\n}", "function stopCare(){\n\tpress = false;\n\tdocument.activeElement.blur();\n\tnotifications.forEach(notify => notify.close());\n\tclearInterval(changeIcon);\n\tchangeIcon = 0;\n\tclearInterval(pressTimer);\n\tpressTimer = 0;\n\tcheckMood();\n\tif (!sad) defaultMood();\n}", "function timerStop() {\n clearInterval(timer);\n}", "function toggleTimer() {\n withUniqueClass(requireCursor(), TIMER_CLASSES, all, click);\n }", "function timer() {\n\tif(TIMER_STOPPED == false) {\n\t\tTIMER--;\n\t\tif (TIMER < 0) {\n\t\t\t// clearInterval(counter);\n\t\t\t//counter ended, do something here\n\n\t\t\t$('#start_timer').show();\n\t\t\t$('#stop_timer').hide();\n\t\t\tdisableButtons(false);\n\t\t\tsetDefault();\n\n\t\t\treturn;\n\t\t}\n\n\t\tsetTimer(TIMER);\n\t}\n}", "function decrement2() {\n\n // Decrease number by one.\n timerNumber--;\n\n // Once number hits zero...\n if (timerNumber === 0) {\n\n // ...run the stop function.\n stop();\n\n isGameOver(); \n \n }\n }", "function stop () {\n clearInterval(timerHandle)\n }", "function stopClock() {\n clearInterval(timer); \n }", "__stopInternalTimer() {\n this.fireEvent(\"release\");\n\n this.__timer.stop();\n\n this.removeState(\"abandoned\");\n this.removeState(\"pressed\");\n }" ]
[ "0.7086916", "0.7003422", "0.6968046", "0.69316846", "0.6838469", "0.6818079", "0.68083584", "0.67917424", "0.6781963", "0.6781121", "0.6774875", "0.6766777", "0.67615664", "0.6720698", "0.6718187", "0.670676", "0.66962636", "0.6687011", "0.66725296", "0.6663069", "0.6661286", "0.6657149", "0.665236", "0.66431475", "0.6641526", "0.66393965", "0.6637671", "0.6625184", "0.66240644", "0.66210103", "0.6620483", "0.6613737", "0.66054463", "0.66052306", "0.66052306", "0.6589671", "0.65888363", "0.6585671", "0.65837544", "0.65799415", "0.6571901", "0.654404", "0.6526042", "0.6521955", "0.6519668", "0.6517564", "0.64856565", "0.64841205", "0.647549", "0.64752656", "0.6473972", "0.6473516", "0.6466497", "0.64660394", "0.64649385", "0.6453479", "0.64505774", "0.6442955", "0.6439872", "0.6437294", "0.64351577", "0.6434158", "0.642771", "0.642594", "0.6421291", "0.64207774", "0.6416072", "0.64140505", "0.63982725", "0.6390735", "0.6389376", "0.63858026", "0.63799375", "0.63744366", "0.63674355", "0.63536507", "0.63524973", "0.63506943", "0.63500905", "0.6346373", "0.63449955", "0.6334496", "0.6332043", "0.6329467", "0.63274574", "0.6322858", "0.63177973", "0.6317026", "0.6315097", "0.6313646", "0.631302", "0.63124245", "0.6311778", "0.63092864", "0.6309118", "0.6307729", "0.63069105", "0.6305515", "0.630237", "0.62971103" ]
0.66042143
35
Returns a random item from a given array when called. Uses Math.floor and Math.random to generate a random number from the array's length.
function getRandomItem (array) { const randomItem = Math.floor(Math.random() * array.length) return array[randomItem] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function randomItem(array) {\n return array[Math.floor(Math.random() * array.length)];\n }", "function getRandomItem(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomItem(arr) {\n return arr[Math.floor(arr.length*Math.random())];\n}", "function randomItem(arr) {\n return arr[Math.floor(Math.random()*arr.length)]\n}", "function getRandomItem(arr) {\n\treturn arr[Math.floor(Math.random() * arr.length)];\n}", "function randomElement(array) {\n return array[randomInteger(array.length)];\n}", "function randomElement(array) {\n return array[randomInteger(array.length)];\n}", "function getRandomItem(arr){\n let num = Math.floor(Math.random() * arr.length)\n return arr[num];\n}", "function getRandomArrItem(arr) {\n var random = Math.floor(Math.random() * arr.length);\n return arr[random];\n}", "function chooseRandomFrom(array){\n return array[Math.floor(Math.random() * array.length)];\n}", "function randArrayElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function getRandom (array) {\n var randomIndex = Math.floor(Math.random() * array.length)\n var randomElement = array[randomIndex]\n\n return randomElement\n}", "function getRandomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n }", "function randPick(arr)\n{\n return arr[Math.floor(Math.random() * arr.length)]; \n}", "function getRandomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function getRandomElement(array) {\n return array[Math.floor(Math.random() * array.length)]\n}", "getRandomItem(array) {\n // get random index value\n const randomIndex = Math.floor(Math.random() * array.length);\n // get random item and return it\n return array[randomIndex];\n }", "function randomElement(array){\n //Creates a random number\n var randomNumber = Math.floor(Math.random() * array.length);\n return array[randomNumber];\n}", "function getRandomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function getRandomElement(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "static getRandom (arr) { return arr[ Math.floor( Math.random() * arr.length ) ] }", "function randomElement(array) {\n\t\treturn array[Math.floor(Math.random() * array.length)];\n\t}", "function getRandom(array){\n var index = Math.floor(Math.random()*array.length);\n var value = array[index];\n return value;\n}", "function pickFromArray(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function pickFromArray(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function randItem(selectedArray) {\n return selectedArray[Math.floor(Math.random()*selectedArray.length)];\n}", "function getRandom(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomValueFromArray(array){\n return array[Math.floor(Math.random()*array.length)];\n}", "function chooseRandom(arr) {\n return arr[Math.floor((Math.random() * arr.length))];\n}", "function randomPick(array){\n let choice = Math.floor(Math.random()*array.length);\n return array[choice]\n}", "function randomElement(arr)\n{\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function randomPick(array) {\n let choice = Math.floor(Math.random() * array.length);\n return array[choice];\n}", "function randomPick(array) {\n let choice = Math.floor(Math.random() * array.length);\n return array[choice];\n}", "function randomElement(array) {\n var randomize = Math.floor(Math.random() * array.length);\n var rand = array[randomize];\n return rand\n }", "function randomPick(array){\n\tlet choice = Math.floor(Math.random() * array.length);\n\treturn array[choice];\n}", "function getRandArrayValue(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomElement(arr) {\n return (arr[Math.floor(Math.random() * arr.length)]);\n}", "function randomValueFromArray(array){\n\treturn array[Math.floor(Math.random()*array.length)];\n}", "function random(array) {\n let randomIndex = Math.floor(Math.random() * array.length);\n return array[randomIndex];\n}", "function getRandomElement(array){\n\trandomIndex = Math.floor(Math.random()*array.length)\n\treturn array[randomIndex];\n}", "function getRandomElement(array) {\n const randomIndex = Math.floor(Math.random() * array.length);\n return array[randomIndex];\n}", "function random_choice(array){\n var l = array.length;\n var r = Math.floor(Math.random()*l);\n return array[r];\n}", "function randomValueFromArray(array){\n\treturn array[Math.floor(Math.random()*array.length)];\n\n}", "function getRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function getRandomElement(array) {\n const index = Math.floor(Math.random() * array.length);\n return array[index];\n}", "function randomChoice(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function getRandArrayValue(array) {\r\n\treturn array[Math.floor(Math.random() * array.length)];\r\n}", "function getRandom(arr) {\n var ranIndex = Math.floor(Math.random() * arr.length);\n var ranElement = arr[ranIndex];\n return ranElement;\n}", "function randomValueFromArray(array){\n const random = Math.floor(Math.random()*array.length);\n return array[random];\n }", "function choose(array) {\n\t\treturn array[getRandomInt(array.length)];\n\t}", "function randomValueFromArray(array){\n const random = Math.floor(Math.random()*array.length);\n return array[random];\n}", "function randomElement(array) {\n return array[Math.floor((Math.random() * array.length -1) +1)];\n}", "function getRandomElement(array) {\n // Math.floor means round a number downward to its nearest integer\n let element = array[Math.floor(Math.random() * array.length)];\n // return stops the execution of a function and returns a value\n // from that function\n return element;\n}", "function getRandom(arr) {\r\n var x = Math.floor(Math.random() * arr.length);\r\n return arr[x];\r\n}", "function getRandomArrayElement(array) {\n let element = array[Math.floor(Math.random() * array.length)];\n return element;\n}", "function getRandomElement(array) {\n let element = array[Math.floor(Math.random() * array.length)];\n return element;\n}", "function sample(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function randomFromArray(arr){\n\treturn arr[randomInteger(0,arr.length)];\n}", "function get_random_value(array){\n var value = array[Math.floor(Math.random() * array.length)];\n return value;\n}", "function pick(array = []) {\n\t\tvar rand = Math.random();\n\t\treturn array[Math.round(map(rand, 0, 1, 0, array.length - 1))];\n\t} //why haven't I done this already", "function getRandom(arr) {\n var randIndex = Math.floor(Math.random() * arr.length);\n var randElement = arr[randIndex];\n return randElement;\n}", "function getRandom(arr) {\n var randIndex = Math.floor(Math.random() * arr.length);\n var randElement = arr[randIndex];\n return randElement;\n}", "function pickRandom(arr) {\n var randomIndex = Math.floor(Math.random() * arr.length);\n var randomEl = arr[randomIndex];\n return randomEl;\n}", "function pick(arr){\r\n randompick=Math.floor(Math.random() * arr.length);\r\n return arr[randompick];\r\n}", "function randomFromArray(arr){\n\treturn arr[Math.floor(Math.random() * arr.length)]\n}", "function randElement(arr) {\n\treturn arr[Math.floor(Math.random()*arr.length)];\n}", "function sample(array) {\n const index = Math.floor(Math.random() * array.length)\n return array[index]\n}", "function random_choice(arr) {\n rand_num = Math.floor(Math.random() * arr.length);\n return arr[rand_num];\n}", "function getRandomItem(array) {\n let ticks = 0;\n // Get a random number and access that element in the array\n const item = array[Math.floor(Math.random() * array.length)];\n ticks++;\n return {\n result: item,\n ticks: ticks\n };\n}", "function getRandom(arr) {\n var randIndex = Math.floor(Math.random() * arr.length);\n var randElement = arr[randIndex];\n return randElement;\n }", "function getRandomValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function getRandom(arr) {\n var randIndex = Math.floor(Math.random() * arr.length);\n var randElement = arr[randIndex];\n\n return randElement;\n }", "function randomSelect(array) {\n var randomI = Math.floor(Math.random() * array.length);\n var randomE = array[randomI];\n return randomE;\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)]\n}", "function randomSelect(array) {\n return array[getRandomInt(0, array.length)];\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function randomSelection (array) {\n var randomNumber = Math.floor(Math.random() * array.length);\n return array[randomNumber];\n }", "function getRandom(arr) {\n const idx = Math.floor(Math.random() * arr.length);\n return arr[idx]\n}", "function pickRandom(arry) {\n return arry.splice(Math.floor(Math.random() * arry.length), 1)[0];\n}", "function selectRandomFromArray(array) {\n let randomNum = Math.floor(Math.random() * array.length);\n return array[randomNum];\n}", "function getRandomNumber(array) {\n return array[Math.random() * array.length | 0];\n}", "function getRandom(arr) {\n let randIndex = Math.floor(Math.random() * arr.length);\n let randElement = arr[randIndex];\n return randElement;\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function findRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function randomizer(array) {\n return array[Math.floor(Math.random() * array.length)];\n}", "function getRandomNumber(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}", "function randomValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }", "function getRandom(arr) {\n\tvar index = Math.floor(Math.random() * arr.length);\n\tvar value = arr[index];\n\treturn value;\n}", "function choice(arr){\n return arr[Math.floor(Math.random() * arr.length)];\n }", "function getRandomElement(arr) {\n\tvar ind = Math.floor(Math.random()*arr.length);\n\treturn arr[ind];\n}", "function getRandomNumber(array) {\n return Math.floor(Math.random() * array.length);\n}", "function random_choice(arr){\n let idx = Math.floor(Math.random() * arr.length);\n return arr[idx];\n}", "function randomValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }", "function randomValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }", "function randomValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }" ]
[ "0.8589939", "0.8543405", "0.84198713", "0.8411864", "0.8242904", "0.8228494", "0.8228494", "0.81731963", "0.815102", "0.81372774", "0.8111017", "0.81056434", "0.81056434", "0.81027895", "0.80907637", "0.8080127", "0.8078969", "0.80689394", "0.8065756", "0.8063431", "0.8058136", "0.8058136", "0.80539757", "0.80298865", "0.80275226", "0.80266136", "0.80266136", "0.800531", "0.79971814", "0.7986733", "0.79844254", "0.7976954", "0.79754704", "0.7969541", "0.7969541", "0.7966105", "0.79568595", "0.795666", "0.79517233", "0.791844", "0.7916363", "0.7900416", "0.7894204", "0.78915423", "0.7890522", "0.78701085", "0.78694284", "0.7853269", "0.78495175", "0.78486013", "0.78482914", "0.78468305", "0.7835716", "0.7835448", "0.78179365", "0.78129745", "0.7810577", "0.7807215", "0.77872425", "0.77852464", "0.7774365", "0.7758701", "0.7751889", "0.77442163", "0.7742276", "0.7728282", "0.7709917", "0.7706484", "0.77011055", "0.7694503", "0.76900876", "0.76848024", "0.7682351", "0.7681373", "0.7675926", "0.76670337", "0.7656745", "0.76538295", "0.76538295", "0.7645831", "0.76413125", "0.76334995", "0.762823", "0.7626295", "0.76173043", "0.76166797", "0.76166797", "0.76166797", "0.76166797", "0.7616201", "0.7615456", "0.7614458", "0.7610349", "0.7592395", "0.7588991", "0.7584798", "0.75774354", "0.7577413", "0.7577413", "0.7577413" ]
0.8387497
4
Changes the background colors of various elements when called.
function changeColors (arrayOfColors, doc) { const button = document.getElementById('load-quote') const quoteBox = document.getElementById('quote-box') const header = document.getElementById('random-quotes') const buttonHeaderColor = getRandomItem(arrayOfColors) button.style.backgroundColor = buttonHeaderColor quoteBox.style.backgroundColor = buttonHeaderColor header.style.backgroundColor = buttonHeaderColor document.body.style.backgroundColor = getRandomItem(arrayOfColors) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setAllColors(){\n\tfor (i=0; i<squares.length; i++){\n\t\tsquares[i].style.background = pickColor;\n\t}\n\th1.style.background = pickColor;\n}", "function setBackground(elements) {\n elements.each(function (k, element) {\n var element = $(element);\n var parent = $(element).parent();\n\n var elementBackground = element.css(\"background-color\");\n elementBackground = (elementBackground == \"transparent\" || elementBackground == \"rgba(0, 0, 0, 0)\") ? null : elementBackground;\n\n var parentBackground = parent.css(\"background-color\");\n parentBackground = (parentBackground == \"transparent\" || parentBackground == \"rgba(0, 0, 0, 0)\") ? null : parentBackground;\n\n var background = parentBackground ? parentBackground : \"white\";\n background = elementBackground ? elementBackground : background;\n\n element.css(\"background-color\", background);\n });\n }", "function updateColors() {\n SKIN.options.container = PAGE_BG_COLOR;\n if (SCHEME_NAME === 'custom') {\n SKIN.options.scheme = SCHEME_CUSTOM;\n } else {\n SKIN.options.scheme = SCHEME_NAME;\n }\n updateCSS();\n Y.one('.page-background').setStyle('backgroundColor', PAGE_BG_COLOR);\n }", "function backgroundColor(div) {\n document.body.style.backgroundColor = \"pink\";\n }", "setColors() {\n var squares = document.querySelectorAll('.square');\n\n for (var square of squares) {\n square.style.backgroundColor = 'hsl(' + this.fg + ',50%,50%)';\n }\n\n var hands = document.querySelectorAll('.hand');\n\n for (var hand of hands) {\n hand.style.backgroundColor = 'hsl(' + this.fg + ',20%,50%)';\n }\n\n var backColorFlr = Math.floor(this.bg);\n document.body.style.backgroundImage = 'linear-gradient(to bottom right, hsl(' + backColorFlr + ',50%,80%), hsl(' + backColorFlr + ',50%,50%))';\n }", "function backgroundColor(alien, color){\r\n $('#' + alien).css(\"background-color\", color);\r\n}", "function internalizeBackgroundColor() {\n var background_color = $('body').css('backgroundColor');\n $(\".tdcss-dom-example\").css('backgroundColor', background_color);\n }", "function ResetBackgrounds() {\n\t\t\t\ttry {\n\t\t\t\t\tiLog(\"ResetBackgrounds\", \"Called\");\n\t\t\t\t\t\n\t\t\t\t\t_cmdDiv.find(\"div\").css(\"background-color\", \"#fff\");\n\t\t\t\t\t_resDiv.find(\"div\").css(\"background-color\", \"#fff\");\n\t\t\t\t} catch (err) {\n\t\t\t\t\tiLog(\"ResetBackgrounds\", err, Log.Type.Error);\n\t\t\t\t}\n\t\t\t}", "function set_background (r, g, b) {\r\n red = r;\r\n green = g;\r\n blue = b;\r\n}", "function setElementBGColor(element, red, green, blue) {\n // An array containing the three primary colors\n // .join(',') adds commas between the indices\n let rgbVal = [red, green, blue].join(',');\n // the color box sends the rgb values to the background-color built-in function in the CSS file\n element.style.backgroundColor = \"rgb(\" + rgbVal + \")\";\n}", "function backgroundColor(color) {\n $(\".preview\").css(\"background\", color);\n}", "function setContentBgColor(rgbColor)\n{\n\tdocument.getElementById('scrolldiv_parentContainer').style.backgroundColor = rgbColor;\n}", "function changeColor(){\n play1button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play2button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play3button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play4button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play5button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play6button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play7button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play8button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play9button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n colordiv.style.color = (allButtons[getRndInteger(0, allColors.length)]).style.backgroundColor;\n }", "function changeBackground(id_){\n\n\tvar A = document.getElementById(\"input_database\");\n\tvar B = document.getElementById(\"data_annotation\");\n\tvar C = document.getElementById(\"data_i_profiling\");\n\tvar D = document.getElementById(\"simple_statistics_data_\");\n\tvar E = document.getElementById(\"Data_exp_constraint\");\n\tvar F = document.getElementById(\"data_exploration\");\n\tvar G = document.getElementById(\"query_exploration\");\n\n\tA.style = \"background: #aaa;\";\n\tB.style = \"background: #aaa;\";\n\tC.style = \"background: #aaa;\";\n\tD.style = \"background: #aaa;\";\n\tE.style = \"background: #aaa;\";\n\tF.style = \"background: #aaa;\";\n\tG.style = \"background: #aaa;\";\n\n\tvar H = document.getElementById(id_);\n\tH.style = \"background: green;\";\n\n}", "function changeColors(color){\r\nfor(var i=0 ; i<squares.length; i++){\r\n\tsquares[i].style.background=color;\r\n}\r\n}", "function changeBackgroundColor(){\n document.body.style.backgroundColor = getRandomItem(colors);\n}", "function backgroundColors() {\n\t// Add all <section class=\"width-100\"> elements to fullWidthSections\n\tlet fullWidthSections = document.querySelectorAll('section.width-100');\n\n\t// Loop through fullWidthSections and {{do stuff...}}\n\tfor (i = 0; i < fullWidthSections.length; i++) {\n\n\t\tif (i % 4 == 0) {\n\t\t\tfullWidthSections[i].style.backgroundColor = '#c5342f';\n\t\t}\n\t\telse if (i % 4 == 1) {\n\t\t\tfullWidthSections[i].style.backgroundColor = '#f47b3d';\n\t\t}\n\t\telse if (i % 4 == 2) {\n\t\t\tfullWidthSections[i].style.backgroundColor = '#5b9d7a';\n\t\t}\n\t\telse {\n\t\t\tfullWidthSections[i].style.backgroundColor = '#ffc63e';\n\t\t}\n\t}\n}", "function changebackground(element)\n{\n\tvar red = element.getAttribute(\"data-red\");\n\tvar green = element.getAttribute(\"data-green\");\n\tvar blue = element.getAttribute(\"data-blue\");\n\n\telement.style.backgroundColor = `rgb(${red},${green},${blue}`;\n\telement.setAttribute(\"data-revealed\" ,\"true\");\n\tcheckgame($(element).index());\n\t\n}", "function changeColors(color) {\r\n for (let i = 0; i < sq.length; i++) {\r\n sq[i].style.background = color;\r\n }\r\n}", "function setBackgroundColor() {\n document.body.style.backgroundColor = bg_color;\n}", "function setColours() {\r\n\tfor(var i = 0; i < colours.length; i++) {\r\n\t\tsquares[i].style.backgroundColor = colours[i]\r\n\t}\r\n}", "function bgBoxColors() {\r\n for (let i = 0; i < document.box_colors.children.length; i++) {\r\n\r\n document.box_colors.children[i].style.backgroundColor = document.box_colors.elements[i].value;\r\n\r\n\r\n }\r\n}", "function setColors () {\r\n for (let i = 0; i<squares.length; i++) {\r\n squares[i].style.backgroundColor = colors[i];\r\n}}", "function plainBackground(){\n document.body.style.backgroundColor = \"#ffffff\";\n}", "function changeColors(color1) {\n for(var i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color1;\n }\n}", "function setColor(squares){\n squares.each(function(){\n $(this).css( \"backgroundColor\",randomRGB());\n });\n}", "function changeBackground() {\n \n document.getElementById(\"changeBackGroundColor\").style.backgroundColor =\n \"violet\";\n}", "function changeColors(color) {\n\tfor (var i = 0; i < squares.length; i++) {\n\t\tsquares[i].style.background = color;\n\t}\n}", "function changeColours(colour) {\r\n\tfor(var i = 0; i < colours.length; i++) {\r\n\t\tsquares[i].style.backgroundColor = colour\r\n\t}\r\n\r\n\tbanner.style.backgroundColor = colour\r\n}", "function changeEachColor(pickedColor){\r\n for (var i=0;i<squares.length;i++){\r\n squares[i].style.background=pickedColor;\r\n }\r\n}", "function setBGColor(id, value) {\n getElm(id).style.backgroundColor = value;\n}", "function redBackground() {\r\n document.getElementById(\"main\").style.backgroundColor = \"red\";\r\n}", "function set_color(){\t\n\tfor (var i=0; i<objects.length; i++){\n\t\tif(i == diff)\n\t\t\tobjects[i].style.background = trans_color;\t\n\t\telse\n\t\t\tobjects[i].style.background = gener_color;\n\t}\n\t\n\t\n}", "function changeColors(color){\r\n\tfor(var i = 0; i < squares.length; i++){\r\n\t\tsquares[i].style.backgroundColor = color;\r\n\t}\r\n}", "function resetAllBackgrounds() {\n document.querySelectorAll('.robot-item-div').forEach((robot_item) => {\n robot_item.style.backgroundColor = 'rgb(34, 34, 34)'; \n });\n}", "function changeColorsWin(color){\r\n for(let i =0;i<squares.length;i++){\r\n squares[i].style.backgroundColor=color;\r\n }\r\n document.querySelector(\"h1\").style.backgroundColor=color;\r\n }", "setDefaultBackround(){\n \t$(this.element).css(\"background-color\",\"#fafafa\");\n\t}", "function changeColors(color){\n\tfor (var i =0; i <squares.length; i++) {\n\t\tsquares[i].style.background=color;\n\t}\n}", "updateColor(){\n\t\tvar _this = this;\n\t\tvar rowSel = this.getRowSelector();\n\t\t$(rowSel).find('.color_patch').css('background-color',_this.getColor());\n\t}", "function setColor(elmt) {\n for (i = 0; i < elmt.length; i++) {\n j=i%(tags.length);\n elmt[i].css(\"backgroundColor\", tags[sortd[j]]);\n }\n}", "function assignButtonColours(){\n var colorChoice= [\"blue\",\"brown\",\"silver\",\"green\",\"black\",\"red\",\"purple\",\"orange\"];\n for(var i=0;i<colorChoice.length;i++){\n document.getElementsByClassName(\"wires\")[i].style.cssText = `background-color:${colorChoice[i]};`;\n }\n}", "function pinkerton() {\n $('body').css('background', 'pink');\n $('header').css('background', 'pink');\n }", "function changeColors(color){\n\tfor(var i = 0; i < squares.length ; i++){\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "function changeColors(color) {\n for (var i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color;\n }\n}", "function changeBackground(hexColor){\n document.body.style.backgroundColor = hexColor;\n}", "function changeColors(color){\n\tfor(var i=0; i<difficulty; i++){\n\t\tsquares[i].style.backgroundColor=color;\n\t}\n\th1.style.backgroundColor=color;\n}", "function changeColor(color)\r\n{\r\n\tfor(var i=0;i<squares.length;i++)\r\n\t\tsquares[i].style.backgroundColor=color;\r\n\thead.style.backgroundColor=color;\r\n}", "function setBackground()\n{\n canvas.style.backgroundColor = 'rgb(' + [paintColor[0],paintColor[1],paintColor[2]].join(',') + ')';\n}", "function changeColors(color){\n for (var i = 0; i<colors.length; i++){\n squares[i].style.backgroundColor = color;\n }\n}", "function changeColors ( color ) {\n // loop through all colors.\n // change each color to match given color. \n\n for ( var i=0 ; i < colors.length ; i++ ) {\n squares[i].style.background = color ; \n }\n\n}", "function changeBackground() {\n let rateBackground = document.getElementsByClassName(\"rates\");\n Array.from(rateBackground).forEach((el) => {\n min % 2 !== 0\n ? el.setAttribute(\"style\", \"background-color:\t#37a08b\")\n : el.setAttribute(\"style\", \"background-color: #e85456\");\n });\n }", "function changeColors(color) {\n for (let i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = color;\n heading.style.backgroundColor = color;\n }\n}", "function changeBackground(hexColor) {\n document.body.style.backgroundColor = hexColor;\n}", "function bgColor(color) {\n $element.find('div').css(\"background-color\", color);\n }", "function change_background(){\r\n\r\n for(x=0;x<6;x++){\r\n generated = hexa[color_generator()];\r\n color += generated;\r\n\r\n };\r\n body.style.backgroundColor = color;\r\n span.innerText = color;\r\n color = \"#\"; // reinitialize the value of color to '#'\r\n \r\n\r\n \r\n\r\n \r\n}", "function changeBg() {\r\n\t\r\n\tdocument.body.style.backgroundColor='lightgrey';\r\n\t\r\n}", "function changeColors(color) {\n\tfor (var i = 0; i < circles.length; i++)\n\t\tcircles[i].style.background = color;\n}", "function changeColors(color){\n\tfor(i = 0; i < 6; i++){\n\t\tsquares[i].style.backgroundColor = color;\n\t}\n}", "set backgroundColor(value) {}", "function cC(element, color) {\r\n document.getElementById(element).style.backgroundColor = color;\r\n}", "function changebackground(){\n\tdocument.body.style.backgroundColor = 'green';\n}", "function changeBGColor() {\n // Gets the selected backgrounds value and assigns it to a variable\n var bgVal = getValue(bgSelect);\n\n // Removes the 2nd item in the card classList\n card.classList.remove(card.classList[1]);\n\n // Adds a background class to the card classList using the\n // bgVal variable and concatenation\n card.classList.add(bgVal + \"Background\");\n }", "function colorBg(colorBg) {\n noteDiv.style.background = colorBg;\n }", "function setPaletteDivs() {\n _appState.palette.data.forEach((color,i) => _palElems[i].style.backgroundColor = cmn.toCSSColorStr(color));\n setForeBackDivs();\n}", "function setBackground() {\n body.style.background =\n \"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\";\n cssColor.textContent = body.style.background + \";\";\n}", "function colorChange (){\n var newColor = \"rgb(\" + rGBNumber() + \",\" + rGBNumber() + \",\" + rGBNumber() + \")\";\n var x = document.getElementsByTagName('BODY');\n x[0].style.backgroundColor = newColor;\n document.getElementById('loadQuote').style.backgroundColor = newColor;\n }", "function changeBG(){\n document.body.style.backgroundColor = \"red\";\n}", "function defaultButtonColor() {\n\n button1.style.backgroundColor = \"black\";\n button2.style.backgroundColor = \"black\";\n button3.style.backgroundColor = \"black\";\n button4.style.backgroundColor = \"black\";\n\n}", "function color_list() {\n $('.todo').children().css(\"background-color\", \"#ffdddd\");\n $('.doing').children().css(\"background-color\", \"#DDFFDD\");\n $('.done').children().css(\"background-color\", \"#DDFFFF\");\n}", "function changeColors(color) {\r\n\t//loop through all squares:\r\n\tfor(var i = 0; i < squares.length; i++) {\r\n\t//change each color to match given color\r\n\tsquares[i].style.background = color;\r\n\t}\r\n\t\r\n}", "function changeColor(elementID, color) {\r\n\r\n document.getElementById(elementID).style.background=color;\r\n}", "function G1_in(){\n var a = document.getElementById(\"R2C1\");\n var b = document.getElementById(\"R2C3\");\n var c = document.getElementById(\"R3C2\");\n var d = document.getElementById(\"R4C4\");\n a.style.background = \"#fbed6a\";\n b.style.background = \"#fbed6a\";\n c.style.background = \"#fbed6a\";\n d.style.background = \"#fbed6a\";\n}", "function changeColors(color){\n\t//Change colors of all squares using for loop\n\tfor(var i = 0; i < squares.length; i++) {\n\t\tsquares[i].style.background = color;\n\t}\n}", "function changeBackground() {\n getId('img').style.display = 'none';\n getId(\"images-colors\").style.display = \"block\";\n getSel(\".bg-colors\").style.display = \"block\";\n getSel('.file').style.display = \"none\";\n let list = document.getElementsByClassName('parts-item');\n for (let i = 0; i < list.length; i++) {\n list[i].onclick = function () {\n document.body.style.backgroundColor = event.target.style.backgroundColor;\n }\n }\n}", "function bckgColor(){\n if (i > bgcolors.length) {i = 0; }\n document.getElementById(\"batman\").style.backgroundColor = bgcolors[i];\n i++;\n}", "function changeHeadingColor() {\n\tdocument.getElementById(\"heading\").style.backgroundColor = colors[colorIndex];\n\tcolorIndex = (colorIndex + 1) % colors.length; // Alternates the next heading background color. \n}", "function changeWhite() {\n $(this).css('background-color', 'white')\n }", "function setColors () {\n // SET ALL COLOR VARIABLES\n setColorValues();\n\n // UPDATE CSS COLOR STYLES\n setColorStyles();\n\n // SET CONTRAST COLOR STYLES\n setContrastStyles();\n}", "function changeColors(color){\r\n\t//loop through all squares\r\n\tfor(var i = 0; i < squares.length; i++){\r\n\t\t//change each color to match given color\r\n\t\tsquares[i].style.background = color;\r\n\t}\r\n}", "function changeColor (){\n\t\t$(this).css('background-color', 'red');\t\n\t}", "function changeColor() {\n\tvar newColor = generateColor();\n\tbody.style.background = newColor;\n\th5.textContent = \"New CSS Background Color: \" + newColor;\n\th4.textContent = \"One color background selected\";\n}", "function G6_in(){\n var a = document.getElementById(\"R2C1\");\n var b = document.getElementById(\"R2C2\");\n var c = document.getElementById(\"R2C3\");\n var d = document.getElementById(\"R2C4\");\n a.style.background = \"#fbed6a\";\n b.style.background = \"#fbed6a\";\n c.style.background = \"#fbed6a\";\n d.style.background = \"#fbed6a\";\n}", "function correctColorDisplay(){\r\n\theader.style.backgroundColor = colorPicked;\t\r\n\tfor(var x=0; x<squares.length; x++){\r\n\t\tsquares[x].style.backgroundColor = colorPicked;\r\n\t\tsquares[x].style.opacity = \"1\";\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t}\r\n}", "function setBackgroundColorToSpan(color) {\n for (let i = 0; i < color.length; i++) {\n colorEle[i].style.backgroundColor = color[i];\n handleColorClick(i, color[i]);\n }\n }", "function changeColor(element) {\n element.style.backgroundColor = '#333'\n}", "function setSliderBgColor(rgbColor)\n{\n\tdocument.getElementById('scrolldiv_scrollbar').style.backgroundColor = rgbColor;\n\tdocument.getElementById('scrolldiv_scrollUp').style.backgroundColor = rgbColor;\n\tdocument.getElementById('scrolldiv_scrollDown').style.backgroundColor = rgbColor;\n}", "function setRed() {\r\n document.body.style.background = \"Red\";\r\n}", "function changeBackgound(button, another_button)\n{ \n button.css(\"background-color\",\"rgb(232, 234, 237)\");\n button.css(\"color\",\"rgb(32, 33, 36)\");\n \n another_button.css(\"background-color\",\"rgb(32, 33, 36)\");\n another_button.css(\"color\",\"rgb(232, 234, 237)\");\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}", "function setAsCurrent(ele) {\n ele.style.backgroundColor = '#F1F1F1';\n}", "function setBackgroundColor() {\r\n document.getElementById(\"texttwo\").style.backgroundColor = \"red\";\r\n}", "function wygas()\r\n{\r\n $(\".field\").css('background-color', '#debb27');\r\n}", "function G4_in(){\n var a = document.getElementById(\"R3C1\");\n var b = document.getElementById(\"R3C2\");\n var c = document.getElementById(\"R5C3\");\n var d = document.getElementById(\"R3C4\");\n a.style.background = \"#fbed6a\";\n b.style.background = \"#fbed6a\";\n c.style.background = \"#fbed6a\";\n d.style.background = \"#fbed6a\";\n}", "function G3_in(){\n var a = document.getElementById(\"R1C1\");\n var b = document.getElementById(\"R2C4\");\n var c = document.getElementById(\"R3C2\");\n var d = document.getElementById(\"R3C3\");\n a.style.background = \"#fbed6a\";\n b.style.background = \"#fbed6a\";\n c.style.background = \"#fbed6a\";\n d.style.background = \"#fbed6a\";\n}", "function changeBackGroundColor() {\n \n \n document.body.style.backgroundColor =\n \"#2c7e87\";\n document.body.setAttribute('class', 'note'); \n \n }", "function changeColors(color)\n{\n\tfor (var i = 0; i < colors.length; i++)\n\t{\n\t\tsqrs[i].style.backgroundColor = color;\n\t}\n}", "function setBackgroundColorByClassName(strClassName, strHexColor){\r\n\tvar arrElements = document.getElementsByClassName(strClassName);\r\n\tfor (var i = 0; i < arrElements.length; i++){\t\r\n\t\tarrElements[i].style.backgroundColor = strHexColor;\r\n\t}\r\n}", "function Button201(){\n $('body').css('background-color','pink');\n}", "function changeColors(color){\n //loop through squares \n for(var i = 0; i < squares.length; i++){\n //change each color to match given color\n squares[i].style.backgroundColor = color;\n }\n}", "function background_color(id) {\n var location = document.getElementById(id);\n location.style.background = \"lightgrey\";\n}", "function change(ids) {\n const x = document.getElementById(ids);\n if (x !== null) {\n x.style.backgroundColor = '#ADD8E6';\n }\n}" ]
[ "0.7469339", "0.7369226", "0.69989985", "0.6975701", "0.69386196", "0.6912672", "0.6851615", "0.6847945", "0.6797477", "0.6783347", "0.66997266", "0.66977763", "0.66920155", "0.6676432", "0.6647599", "0.66395426", "0.6634584", "0.6618205", "0.6604011", "0.66025305", "0.65967137", "0.6580193", "0.65679085", "0.6563091", "0.6556178", "0.6556175", "0.6553637", "0.6552198", "0.6549782", "0.6549536", "0.6547905", "0.6542249", "0.6538361", "0.65381366", "0.6532383", "0.65251935", "0.6524515", "0.65199155", "0.6518445", "0.65154195", "0.6489259", "0.6488305", "0.6481173", "0.64790237", "0.6474394", "0.6474274", "0.6471919", "0.6459875", "0.64544225", "0.64438564", "0.64430207", "0.6436372", "0.64290136", "0.6423266", "0.64193296", "0.6416564", "0.64126575", "0.6410823", "0.6399658", "0.6385975", "0.63836765", "0.6382264", "0.6380484", "0.635843", "0.63581216", "0.6353459", "0.63507044", "0.6349912", "0.6349799", "0.63432765", "0.6342982", "0.6341454", "0.6338436", "0.6335205", "0.63304824", "0.632983", "0.6328172", "0.6318416", "0.6317992", "0.6315368", "0.63149714", "0.6310514", "0.62980974", "0.6295367", "0.62939405", "0.6282286", "0.62782896", "0.6272842", "0.6265715", "0.6265166", "0.6264645", "0.626413", "0.62630147", "0.6260278", "0.6253615", "0.6253438", "0.6247124", "0.62463737", "0.62429756", "0.6242836", "0.6236746" ]
0.0
-1
Prints a random quote and source to the page. Calls the getRandomItemfunction and stores a quote in randomQuote. Prints to the page the random quote with the quote's source, citation, year, and tag if applicable.
function printQuote () { const randomQuote = getRandomItem(quotes) let html = `<p class="quote">${randomQuote.quote}</p> <p class="source">${randomQuote.source}` if (randomQuote.citation && randomQuote.year) { html += `<span class="citation">${randomQuote.citation}</span> <span class="year">${randomQuote.year}</span>` } else if (randomQuote.citation && !randomQuote.year) { html += `<span class="citation">${randomQuote.citation}</span>` } else if (randomQuote.year && !randomQuote.citation) { html += `<span class="year">${randomQuote.year}</span>` } if (randomQuote.tag) { html += `<span class="tag">${randomQuote.tag}</span>` } html += `</p>` document.getElementById('quote-box').innerHTML = html changeColors(colors, document) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function printQuote() {\n\n var quote = getRandomQuote(); // Call getRandomQuote function and put the return into a variable\n\n // presentation structure\n var html = '<p class=\"quote\">' + quote.quote + '</p>';\n html += '<p class=\"source\">' + quote.source;\n if (quote.citation !== \"\") {\n html += '<span class=\"citation\">' + quote.citation + '</span>';\n }\n if (quote.year !== \"\") {\n html += '<span class=\"year\">' + quote.year + '</span>';\n }\n html += '</p>';\n if (quote.tag !== \"\") {\n html += '<h3>' + quote.tag + '</h3>';\n }\n\n \trandomColor();\n \tdocument.getElementById('bgcolor').style.backgroundColor = randomColor(); //Update background with new random color\n document.getElementById('quote-box').innerHTML = html; // Show in page the random quote\n }", "function printQuote(){\n let i = getRandomQuote(quotes);\n let quoteToPage = '<p class=\"quote\">' + i.quote + '</p> <p class=\"source\">' + i.source;\n\n //Checks if citation and year property exist for the quote object\n if(i.hasOwnProperty('citation')){\n quoteToPage += '<span class=\"citation\">' + i.citation + '</span>';\n };\n if(i.hasOwnProperty('year')){\n quoteToPage += '<span class=\"year\">' + i.year + '</span>';\n };\n\n //Adds IMDB Rating and Link\n if(i.hasOwnProperty('imdbRating')){\n quoteToPage += '<span class=\"year\"><a href=\"' + i.imdbLink + '\"> IMDB Rating: ' + i.imdbRating + '</a></span>';\n };\n quoteToPage += '<p/>';\n\n //Calls \"randomColor\" function to change backgrounnd color\n randomColor();\n\n //Inserts quote into HTML\n const printToPage = document.querySelector('#quote-box');\n printToPage.innerHTML = quoteToPage;\n}", "function printQuote() {\n const quoteObj = getRandomQuote();\n document.querySelector(\".quote\").textContent = quoteObj.quote;\n document.querySelector(\n \".source\"\n ).innerHTML = `${quoteObj.source} - <span class=\"achievement\">${quoteObj.achievement}</span><span class=\"citation\">${quoteObj.citation}</span><span class=\"year\">${quoteObj.year}</span><span class=\"tags\"> (${quoteObj.tags})</span>`;\n randomBodyColor();\n}", "function printQuote() {\r\n //Call `getRandomQuote` and assign to `getQuote`\r\n var getQuote = getRandomQuote(quotes);\r\n //This variable stores the quote and source string\r\n var html = '';\r\n html += '<p class=\"quote\">' + getQuote.quote + '</p>' + '<p class=\"source\">' + getQuote.source;\r\n //Check if quote has citation property, if so add to html string.\r\n if (getQuote.hasOwnProperty('citation')) {\r\n html += '<span class=\"citation\">' + getQuote.citation + '</span>';\r\n }\r\n //Check if quote has year property, add it to html string\r\n if (getQuote.hasOwnProperty('year')) {\r\n html += '<span class=\"year\">' + getQuote.year + '</span>';\r\n }\r\n \r\n document.getElementById('quote-box').innerHTML = html;\r\n \r\n }", "function getRandomQuote() {\n let randNum;\n function getRandomNum() {\n randNum= (Math.floor(Math.random()*60))-1;\n return randNum;\n }\n getRandomNum();\n function printQuote(message) {\n document.getElementById(\"quote-box\").innerHTML= message;\n }\n let output = \"<p class='quote'>\"+\"“\"+quotes[getRandomNum()].quote+\"</p> <p class='source'>\"+quotes[randNum].source+\", tag: \"+quotes[randNum].tag;\n // *add year if available\n if (quotes[randNum].year){\n output += \", year: \"+quotes[randNum].year;\n }\n output +=\"<span class='citation'><a href='https://litemind.com/best-famous-quotes/'>Litemind</a></span></p>\";\n printQuote(output);\n}", "function printQuote(){\n let html = '';\n let randomQuote = getRandomItem(quotes);\n\n html += '<p class=\"quote\">' + randomQuote.quote + '</p>';\n html += '<p class=\"source\">' + randomQuote.source;\n if(randomQuote.tags){\n html += '<span class=\"tags\">' + randomQuote.tags + '</span>';\n }\n if(randomQuote.citation){\n html += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n if(randomQuote.year){\n html += '<span class=\"year\">' + randomQuote.year + '</span>';\n }\n html += '</p>';\n\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote()\n{\n let randomQuote = getRandomQuote();\n\n let htmlOutput = ''; // the output that will be printed.\n\n let quote = '<p class=\"quote\">' + randomQuote.quote + '</p>'; // the quote\n htmlOutput += quote;\n\n let source = '<p class=\"source\">' + randomQuote.source; // the source\n htmlOutput += source;\n\n if (randomQuote.hasOwnProperty('citation')) // the citation will be added to the output only if it exists.\n {\n let citation = '<span class=\"citation\">' + randomQuote.citation + '</span>';\n htmlOutput += citation;\n }\n \n if (randomQuote.hasOwnProperty('year')) // the year will be added to the output only if it exists.\n {\n let year = '<span class=\"year\">' + randomQuote.year + '</span>';\n htmlOutput += year;\n }\n\n let tags = '<p class=\"tags\">' + randomQuote.tags.join(\" , \"); // the tags\n htmlOutput += tags;\n\n htmlOutput += '</p>'; // end of output. \n \n let quoteBoxDiv = document.getElementById(\"quote-box\"); // connection th HTML file. \n quoteBoxDiv.innerHTML = htmlOutput;\n \n document.querySelector(\"body\").style.background = getRandomColor(); // change background color.\n \n}", "function printQuote(){\n // retrieve the random quote and store it in a variable\n const randomQuote = getRandomQuote();\n // sets the html to the necessary paragraphs for the quote and source\n let html = `\n <p class='quote'> ${randomQuote.quote} </p>\n <p class='source'> ${randomQuote.source}\n `;\n\n // check if properties exist in quote object and insert those items into html variable\n if (randomQuote.citation) {\n html += `\n <span> - \"${randomQuote.citation}\",</span>\n `;\n }\n\n if (randomQuote.year) {\n html += `\n <span> (${randomQuote.year}) </span>\n `;\n }\n\n if (randomQuote.tags) {\n html += `\n <span class='tags'> #tags: ${randomQuote.tags} </span>\n `;\n }\n\n // add closing p tag to the html element\n html += `</p>`;\n\n // call random RGB color function to change the BG color of the page for each quote\n randomBackgroundColor();\n// show quote on the page\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote() {\n let randomQuote = getRandomQuote(quotes);\n let quoteToPrint = '<h1 class=\"quote\">' + randomQuote.quote + '</h1> <p class=\"source\">' + randomQuote.source;\n if (randomQuote.citation) {\n quoteToPrint += '<span class=\"citation\">' + randomQuote.citation + \"</span>\";\n }\n if (randomQuote.year) {\n quoteToPrint += '<span class=\"year\">' + randomQuote.year + \"</span>\";\n }\n if (randomQuote.tag) {\n quoteToPrint += '<span class=\"tag\">' + randomQuote.tag + \"</span>\";\n }\n quoteToPrint += \"</p>\";\n print(quoteToPrint);\n getRandomBgColor();\n}", "function printQuote(randomQuote) {\n\tvar html = '<p class=\"quote\">' + randomQuote.quote + '</p>';\n\thtml += '<p class=\"source\">' + randomQuote.source;\n\t\n\tif (randomQuote.hasOwnProperty('citation') && randomQuote.hasOwnProperty('year')) {\n\t\thtml += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n\t\thtml += '<span class=\"year\">' + randomQuote.year + '</span> </p>';\n\t} else if (randomQuote.hasOwnProperty('year')) {\n\t\thtml += '<span class=\"year\">' + randomQuote.year + '</span> </p>';\n\t} else if (randomQuote.hasOwnProperty('citation')) {\n\t\thtml += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n\t};\n\t\n\thtml += '<ul class=\"list-inline\">';\n\t\n\tfor (i=0; i<randomQuote.tags.length; i++) {\n\t\thtml += '<li>' + randomQuote.tags[i] + '</li>';\n\t}\n\thtml += '</ul>';\n\n\tvar quoteDiv = document.getElementById('quote-box');\n\tquoteDiv.innerHTML = html;\n}", "function printQuote () {\n getRandomQuote();\n if (citation !== \"\" && date !== \"\") {\n fullQuote = '<p class=\"quote\">' + quote + '</p><p class=\"source\">' + source + '<span class=\"citation\">' + \n citation + '</span><span class=\"year\">' + date + '</span></p><p class=\"source\">' + tags + ', Rated: ' +\n rating + ' stars<p>'\n } else if (citation !== \"\") {\n fullQuote = '<p class=\"quote\">' + quote + '</p><p class=\"source\">' + source + '<span class=\"year\">' + date +\n '</span></p><p class=\"source\">' + tags + ', Rated: ' + rating + ' stars</p>'\n } else { \n fullQuote = '<p class=\"quote\">' + quote + '</p><p class=\"source\">' + source + '<span class=\"citation\">' + \n citation + '</span></p><p class=\"source\">' + tags + ', Rated: ' + rating + ' stars</p>'\n }\n document.getElementById(\"quote-box\").innerHTML = fullQuote;\n //random color generator\n randomColor = '#'+Math.random().toString(16).slice(-6);\n document.body.style.backgroundColor = randomColor;\n document.getElementById(\"loadQuote\").style.backgroundColor = randomColor;\n}", "function printQuote() {\n var quote = getRandomQuote();\n var html = '<p class=\"quote\">' + quote.quote + '</p>';\n html += '<p class=\"source\">' + quote.source;\n\n if (quote.citation) {\n html += '<span class=\"citation\">' + quote.citation + '</span>';\n }\n if (quote.year) {\n html += '<span class=\"year\">' + quote.year + '</span>';\n }\n html += '</p>'\n\n document.getElementById('quote-box').innerHTML = html;\n\n randomColor(); // A new color is displayed simultaneously with a new quote\n}", "function printQuote() {\n\tlet randomQuote = getRandomQuote( quotes );\n\tconst hasCitation = randomQuote.hasOwnProperty( 'citation' ); \n\tconst hasYear = randomQuote.hasOwnProperty( 'year' );\n\tconst hasTags = randomQuote.hasOwnProperty( 'tags' );\n\t\n \t//source html phrase \n\tlet quoteView = `<p class=\\\"quote\\\"> ${ randomQuote[\"quote\"] } </p> \\n<p class=\\\"source\\\"> ${ randomQuote[\"source\"] } `;\n\n\tif ( hasCitation ) {\n\t\tquoteView += `\\n\\t<span class=\\\"citation\\\"> ${ randomQuote[\"citation\"] } </span>`;\n\t}\n\n\tif ( hasYear ) {\n\t\tquoteView += `\\n\\t<span class=\\\"year\\\"> ${ randomQuote[\"year\"] } </span>`;\n\t}\n\t\n\tif ( hasTags ) {\n\t\tquoteView += `\\n\\t<span class=\\\"tags\\\"> ${ randomQuote[\"tags\"] } </span>`;\n\t}\n\n\tquoteView += \"\\n</p>\";\n\n\treturn document.getElementById( 'quote-box' ).innerHTML = quoteView;\n}", "function printQuote() {\n // Choses and sets the background-color randomly when the button is pressed.\n document.body.style.backgroundColor\n = mBackgroundColors[Math.floor(Math.random() * mBackgroundColors.length)];\n\n selectedObject = getRandomQuote();\n mQuote = selectedObject.quote;\n mSource = selectedObject.source;\n mCitation = selectedObject.citation;\n console.log(mRandomNumber);\n\n // if there isn't a citation for a given quote, don't print one.\n if (mCitation != null) {\n document.getElementById(\"quote-box\").innerHTML=\"<p class=\\\"quote\\\">\"\n + mQuote + \"</p>\"\n + \"<p class=\\\"source\\\">\"\n + mSource + \"<span class=\\\"citation\\\">\"\n + mCitation + \"</span></p>\";\n } else {\n document.getElementById(\"quote-box\").innerHTML=\"<p class=\\\"quote\\\">\"\n + mQuote + \"</p>\"\n + \"<p class=\\\"source\\\">\"\n + mSource + \"</p>\";\n\n }\n}", "function printQuote() {\n\n let randomQuote = getRandomQuote(quotes);\n\n let quoteHTML = \"\";\n quoteHTML += `<p class=\"quote\">${randomQuote.quote}</p>`\n quoteHTML += '<p class=\"source\">'\n if (randomQuote.source) quoteHTML += randomQuote.source;\n if (randomQuote.citation) quoteHTML += `<span class=\"citation\"> ${randomQuote.citation} </span>`\n if (randomQuote.year) quoteHTML += `<span class=\"year\"> ${randomQuote.year} </span>`\n quoteHTML += '</p>'\n\n document.getElementById(\"quote-box\").innerHTML = quoteHTML;\n\n}", "function printQuote() {\n\t// On click event, function printQuote runs, then fires the getRandomQuote function\n\tvar quotes = getRandomQuote();\n\tmessage ='<p class=\"quote\">' + quotes.quote + '</p>';\n\tmessage += '<p class=\"source\">' + quotes.source;\n\tif ( quotes.citation ) {\n\t\tmessage += '<span class=\"citation\">' + quotes.citation + '</span>';\n\t} else {\n\t\tmessage += '';\n\t}\n\tif (quotes.year) {\n\t\tmessage += '<span class=\"year\">' + quotes.year + '</span></p>';\n\t} else {\n\t\tmessage += '';\n\t}\n\tif ( quotes.tags ) {\n\t\tmessage += '<h3>' + quotes.tags + '</h3>';\n\t} else {\n\t\tmessage += '';\n\t}\n\tprint(message);\n\t//Generate random color\n\trandomColorGenerator();\n\t//Update background with new random color\n\tdocument.getElementById('bgcolor').style.backgroundColor = randomColorGenerator();\n}", "function printQuote () {\n\tvar quoteObject = getRandomQuote(quotes), \t\t\t\t\t\t\t\t\t//selects a ramdom quote from the array\n\t\tresult = '';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//declares an empty string, here will be stored the html string\n\t\tresult += '<p class=\"quote\">' + quoteObject.quote + '</p>' +\t\t\t\t//starts to fill the array with the quote and the source\n\t\t\t\t '<p class=\"source\">' + quoteObject.source +\n\t\t\t\t \t'<span class=\"citation\">' + quoteObject.citation + '</span>';\n\t\tif (quoteObject.year !== undefined)\t\t\t\t\t\t\t\t\t\t\t//if the quote has a year stored in the object, it will be displayed\n\t\t\tresult += '<span class=\"year\">' + quoteObject.year + '</span>';\n\t\tresult += '</p>';\n\t\tif (quoteObject.funFact !== undefined) \t\t\t\t\t\t\t\t\t\t//if the quote has a fact stored in the object, it will be displayed\n\t\t\tresult += '<p>Fun Fact: ' + quoteObject.funFact + '</p>';\n\t\tdocument.getElementById('quote-box').innerHTML = result;\t\t\t\t\t//changes the html file to show the quote in the web page\n\t\t//this will chage the background color each time this function is called\n\t\tdocument.querySelector('body').style.backgroundColor = 'rgb(' + randomNumber(0,256) + ', ' + randomNumber(0,256) + ', ' + randomNumber(0,256) + ')';\n}", "function printQuote() {\n // variable to hold the quote\n var quote = getRandomQuote();\n\n\n /*\n Construct the html string, note that I used template literals (backticks)\n to add the variables into the strings for better readability then throwing in\n tons of plus(+)s \n */\n var html = '';\n html += `<p class=\"quote\"> ${quote.quote} </p>`;\n html += `<p class=\"source\"> ${quote.source}`;\n if (quote.citation != undefined) {\n html += `<span class=\"citation\"> ${quote.citation} </span>`;\n }\n if (quote.year != undefined) {\n html += `<span class=\"year\"> ${quote.year} </span>`;\n }\n html += '</p>';\n\n // Display the quote html on the page\n document.getElementById('quote-box').innerHTML = html;\n\n // Set the background color of the page to a new random color\n document.body.style.background = randomColor();\n}", "function printQuote() {\n const random = getRandomQuote(quotes, usedQuotes);\n \n const markup = `\n <p class=\"quote\">${random.quote}</p>\n <p class=\"source\">${random.source}${random.title ? `<span class=\"title\">${random.title}</span>` : ''}${random.citation ? `<span class=\"citation\">${random.citation}</span>` : ''}${random.year ? `<span class=\"year\">${random.year}</span>` : ''}</p>\n `;\n document.getElementById('quote-box').innerHTML = markup;\n\n getRandomColor(colors);\n}", "function PrintQuote() {\n let randomQuote = getRandomQuote();\n let randomColor = NewBackgroundColors();\n quote.textContent = randomQuote.quote;\n source.textContent = randomQuote.source;\n body.style.backgroundColor = randomColor;\n}", "function printQuote () {\n var randomItem= getRandomQuote();\n var codeHTML = '';\n codeHTML += '<p class=\"quote\">' + randomItem.quote + '</p>';\n codeHTML += '<p class=\"source\">' + randomItem.source;\n \n if (randomItem.citation !== '' && randomItem.citiation !== null) {\n codeHTML +='<span class = \"citation\">' + randomItem.citation + ' </span>';\n }\n\n if (randomItem.year !== '' && randomItem.year !== null) {\n codeHTML += '<span class = \"year\">'+ randomItem.year + '</span>';\n } \n\n if (randomItem.tag !== '' && randomItem.tag !== null) {\n codeHTML += '<p class = \"tag\"> Tags: ' + randomItem.tag + '</p>';\n }\n\n codeHTML += '</p>';\n\n document.getElementById('quote-box').innerHTML = codeHTML ; \n\n}", "function printQuote()\n{\n\t//call randomquote and store the returned quote in a variable\n\tgetRandomColor(colors);\n\tvar randomQuote = getRandomQuote(quotes);\n\tif (randomQuote.hasOwnProperty('tags'))\n\t{\n\t\tvar tags = \"\";\n\t\tfor (var i = 0; i < randomQuote.tags.length; i++)\n\t\t{\n\t\t\ttags += '<p class=\"tags\">' + randomQuote.tags[i] + '</p>';\n\t\t};\n\n\n\t\tdocument.getElementById('quote-box').innerHTML = '<p class=\"quote\">' + randomQuote.quote + '</p><p class=\"source\">' + randomQuote.source + '</p>' + tags;\n\n\t}\n\telse\n\t{\n\t\tdocument.getElementById('quote-box').innerHTML = '<p class=\"quote\">' + randomQuote.quote + '</p><p class=\"source\">' + randomQuote.source + '</p>';\n\t}\n}", "function printQuote() {\n let randomColor = getRandomColor();\n document.body.style.backgroundColor = randomColor;\n\n let randomQuote = getRandomQuote();\n let htmlString = `<p class=\"quote\"> ${randomQuote.quote} </p>\n <p class=\"source\"> ${randomQuote.source}`;\n\n if (randomQuote.hasOwnProperty(\"citation\")) {\n htmlString += `<span class=\"citation\"> ${randomQuote.citation} </span>`\n }\n\n if (randomQuote.hasOwnProperty(\"year\")) {\n htmlString += `<span class=\"year\"> ${randomQuote.year} </span>`\n }\n\n if (randomQuote.hasOwnProperty(\"type\")) {\n htmlString += `<br></br><span class=\"type\"> ${randomQuote.type} </span>`\n }\n\n htmlString += `</p>`;\n\n document.getElementById('quote-box').innerHTML = htmlString;\n}", "function printQuote(){\n let randomQuote = getRandomQuote(quotes);\n let quoteBox = document.getElementById(\"quote-box\");\n let htmlQuote = '';\n\n htmlQuote += '<p class=\"quote\">' + randomQuote.quote + '</p>';\n htmlQuote += '<p class=\"source\">' + randomQuote.source; \n\n //if the quote contains a citation, add it to the html string to be output\n if(randomQuote.citation){\n htmlQuote += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n\n //if the quote has a year specified, add it to the html string to be output\n if(randomQuote.year){\n htmlQuote += '<span class=\"year\">' + randomQuote.year + '</span>';\n }\n\n //if the quote has an added tag, add it to the html string to be output\n if(randomQuote.tag){\n htmlQuote += '<span class=\"tag\">' + randomQuote.tag + '</span>';\n }\n\n htmlQuote += '</p>';\n changeBackgroundColor(); \n quoteBox.innerHTML = htmlQuote; //add the html content to the web-page\n}", "function printQuote () {\n\tconst quoteBox = document.getElementById('quote-box');\n\tconst randomQuote = getRandomQuote( quotesCopy );\n\n\tconsole.log(randomQuote.quote)\n\n\tlet html = \"\";\n\thtml += `<p class=quote> ${randomQuote.quote} </p>`;\n\thtml += `<p class=source> ${randomQuote.citation} </span>`;\n\thtml += `<span class=year> ${randomQuote.year} </span>`;\n\t// display html\n\tquoteBox.innerHTML = html;\n}", "function printQuote() {\n var randomQuote = getRandomQuote();\n var rgbColor = 'rgb(' + randomRGB() + ',' + randomRGB() + ',' + randomRGB() + ')';\n var quote = ' ';\n quote += '<p class=\"quote\">' + randomQuote.quote + '</p>' +\n '<p class=\"source\">' + randomQuote.source;\n if (randomQuote.citation !== undefined) {\n quote += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n if (randomQuote.year !== undefined) {\n quote += '<span class=\"citation\">' + randomQuote.year + '</span>';\n }\n quote += '<span class=\"tag\">' + randomQuote.tag + '</span>'+'</p>';\n document.body.style.backgroundColor = rgbColor;\n document.getElementById('quote-box').innerHTML = quote;\n}", "function printQuote() {\n var quote = getRandomQuote();\n var html = '';\n html += `<p class=\"quote\">${quote.quote}</p>\n <p class=\"source\">${quote.source}`;\n if(quote.citation){\n html += `<span class=\"citation\"> ${quote.citation}</span>`;\n } \n if (quote.year){\n html += `<span class=\"year\"> ${quote.year}</span>`;\n }\n if (quote.tags && quote.tags.length > 0){\n html += `<span class=\"tags\">, tags: ${quote.tags.join(\", \")}</span>`;\n }\n html += \"</p>\";\n var div = document.getElementById(\"quote-box\");\n div.innerHTML = html;\n\n // Change background of body to a random Color\n document.body.style.backgroundColor = getRandomColor();\n}", "function printQuote(){\r\n ranquote = getRandomQuote()\r\n htmlString = '<p class = \"quote\">' + ranquote.quote + \"</p> <p class='source'>\" + ranquote.source \r\n if (ranquote.citation){\r\n htmlString = htmlString + '<span class=\"citation\">' + quote.citation + \"</span>\"\r\n }\r\n if (ranquote.year){\r\n htmlString = htmlString + '<span class=\"year\">' + ranquote.year + \"</span>\"\r\n }\r\n htmlString = htmlString + \"</p>\"\r\n quotebox = document.getElementById('quote-box')\r\n quotebox.innerHTML = htmlString\r\n document.getElementsByTagName('body')[0].style.background = selectRandomColor();\r\n}", "function printQuote() {\n\tquote = getRandomQuote();\n\thtml = \"\"\n\thtml += '<p class=\"quote\">' + quote.quote + '</p>'\n\thtml += '<p class=\"source\">' + quote.source\n\t\n\tif (quote.citation!= undefined) {\n\t\thtml += '<span class=\"citation\">' + quote.citation + '</span>'\n\t}\n\n\tif (quote.year!= undefined) {\n\t\thtml += '<span class=\"year\">' + quote.year + '</span>'\n\t}\n\t\n\thtml += '</p>'\n\tdocument.getElementById(\"quote-box\").innerHTML=html;\n}", "function printQuote() {\n var randomQuote = getRandomQuote(); \n html = '';\n html += '<p class=\"quote\">' + randomQuote.quote + '</p>';\n html += '<p class=\"source\">' + randomQuote.source; \n if(randomQuote.citation > 0) {\n html += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n if(randomQuote.year > 0 ) {\n html += '<span class=\"year\">' + randomQuote.year + '</span>';\n }\n html += '</p>';\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote(){\n\twindow.clearInterval(timer);\n\n\tvar quote = getRandomQuote();\n\tvar info = \"\";\n\n\tif(quote.citation !== null){\n\t info += \"<span class='citation'>\"+quote.citation+\"</span>\";\n\t}\n\tif (quote.year !== null) {\n\t\tinfo += \"<span class='year'>\"+quote.year.toString()+\"</span>\";\n\t}\n\n\tdocument.getElementsByClassName('quote')[0].innerHTML = quote.quote;\n\tdocument.getElementsByClassName('source')[0].innerHTML = quote.source + info;\n\n\tbody.style.backgroundColor = randomColor()\n\n\ttimerOut();\n}", "function printQuote() {\n\tdocument.querySelector('body').style.background = `rgb(${changeBackground()},${changeBackground()},${changeBackground()})`\n\tlet randomQuote = getRandomQuote();\n\tlet quote = `\n \t<p class=\"quote\">${randomQuote.quote}</p>\n \t<p class=\"source\">${randomQuote.source}\n\t\t`;\n\n\tif ( 'year' in randomQuote ) {\n\t\tquote += `<span class=\"year\">${randomQuote.year}</span>`;\n\t}\n\n\tif ( 'citation' in randomQuote ) {\n\t\tquote += `\n\t\t<span class=\"citation\">${randomQuote.citation}</span>`\n\t}\n\n\tif ( 'category' in randomQuote ) {\n\t\tquote += `\n\t\t<span class=\"citation\">${randomQuote.category}</span>`\n\t}\n\n\tquote += `</p>`;\n\n\treturn document.getElementById('quote-box').innerHTML = quote;\n}", "function printQuote(){\n var quote = getRandomQuote()\n var quoteString = \"<p class = 'quote'>\";\n quoteString += quote.quote;\n quoteString += \"</p> <p class='source'>\";\n quoteString += quote.source;\n\n if (typeof quote.citation != \"undefined\") {\n quoteString += \"<span class='citation'>\";\n quoteString += quote.citation;\n quoteString += \" </span>\";\n }\n if (typeof quote.year != \"undefined\") {\n quoteString += \"<span class='year'>\";\n quoteString += quote.year;\n quoteString += \" </span>\";\n }\n if (typeof quote.catagory != \"undefined\") {\n quoteString += \"<span class='category'> \";\n quoteString += quote.catagory;\n quoteString += \"</span>\";\n }\n quoteString += \"</p>\";\n document.getElementById('quote-box').innerHTML = quoteString;\n document.getElementById('loadQuote').style.backgroundColor = color;\n}", "function quoteGenerator() {\r\n var quoteNum = Math.floor(Math.random()*quotesList.length);\r\n\r\n var quotes = quotesList[quoteNum];\r\n\r\n textQuote.textContent = quotes.quote;\r\n textAuthor.textContent = quotes.author;\r\n}", "function printQuote() {\n var randomQuote = getRandomQuote(quotes);\n HTML = '';\n HTML += '<p class=\"quote\">' + randomQuote.quote + '</p>';\n HTML += '<p class=\"source\">' + randomQuote.source;\n\n document.getElementById(\"quote-box\").innerHTML = HTML;\n}", "function printQuote(){\n\n randomQuote = getRandomQuote(quotes);\n\n //log quote to console to test function\n console.log(randomQuote);\n\n //begin html string to insert into .html file\n let html = ' ';\n\n html = \n '<p class=\"quote\">' + randomQuote.quote + '</p>' +\n '<p class=\"source\">' + randomQuote.source;\n\n //Decide if citations and/or year should be added to the string\n\n if(randomQuote.citation) {\n html += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n };\n \n if (randomQuote.year){\n html += '<span class=\"year\">' + randomQuote.year + '</span>';\n };\n if (randomQuote.tag){\n html += '<span class=\"tag\">' + randomQuote.tag + '</span>';\n };\n\n //Add last closing p tag\n html += '</p>';\n\n //log html string to console for testing\n console.log(html);\n\n //Set inner html of \"quote-box\" to html string\n \n document.getElementById(\"quote-box\").innerHTML = html;\n\n //call random background color function\n randomBG();\n\n }", "function printQuote() {\n var theRandomQuote = getRandomQuote();\n var html = '<p class=\"quote\">' + theRandomQuote.quote + '</p>'\n + '<p class=\"source\">' + theRandomQuote.source +'</p>';\n document.getElementById('quote-box').innerHTML = html;\n\n}", "function printQuote() {\n const randomQuote = getRandomQuote();\n let randomQuoteHTML = `<p class=\"quotes\">${randomQuote.quote}</p>`;\n randomQuoteHTML += `<p class=\"source\">${randomQuote.source}`;\n if (randomQuote.citation !== undefined) {\n randomQuoteHTML += `<span class=\"citation\">${randomQuote.citation}</span>`;\n }\n if (randomQuote.year !== undefined) {\n randomQuoteHTML += `<span class=\"year\">${randomQuote.year}</span>`;\n }\n if (randomQuote.tags !== undefined) {\n randomQuoteHTML += `<span class=\"tags\">, (${randomQuote.tags})</span>`;\n }\n randomQuoteHTML += `</p>`\n function getRandomBgColor() {\n const x = Math.floor(Math.random() * 256);\n const y = Math.floor(Math.random() * 256);\n const z = Math.floor(Math.random() * 256);\n const color = `rgb(${x},${y},${z})`;\n document.body.style.background = color;\n }\n getRandomBgColor();\n return document.getElementById('quote-box').innerHTML = randomQuoteHTML;\n}", "function getRandomQuote() {\n var theQuoteAndAuthor = quotesArray[Math.floor(Math.random() * quotesArray.length)]\n document.getElementById(\"quote\").innerHTML = '\" ' + theQuoteAndAuthor[0];\n document.getElementById(\"author\").innerHTML = '- ' + theQuoteAndAuthor[1];\n }", "function printQuote() {\n // change body background-color to a randomly selected color\n document.body.style.backgroundColor = randomColor();\n var quote = getRandomQuote();\n var html = '<p class=\"quote\">' + quote.quote + '</p>';\n // only include existing quote properties\n if (quote.source !== undefined) {\n html += '<p class=\"source\">' + quote.source;\n if (quote.citation !== undefined) {\n html += '<span class=\"citation\">' + quote.citation + '</span>';\n }\n if (quote.year !== undefined) {\n html += '<span class=\"year\">' + quote.year + '</span>';\n }\n html += '</p>';\n }\n console.log(html);\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote() {\n\t// Get a random quote and color, and store them in variables\n\tvar selectedQuote = getRandomQuote();\n\tvar newColor = getRandomColor();\n\t// Construct HTML string using different properties of quote object\n\t// The properties Citation, Year, and Tags are optional\n\tvar quoteHTML = '<p class=\"quote\">' + selectedQuote.quote + '</p><p class=\"source\">' + selectedQuote.source;\n\tif (\"citation\" in selectedQuote)\n\t{\n\t\tquoteHTML = quoteHTML + '<span class=\"citation\">' + selectedQuote.citation + '</span>';\n\t}\n\tif (\"year\" in selectedQuote)\n\t{\n\t\tquoteHTML = quoteHTML + '<span class=\"year\">' + selectedQuote.year + '</span>';\n\t}\n\tquoteHTML = quoteHTML + '</p>';\n\tif (\"tags\" in selectedQuote)\n\t{\n\t\tquoteHTML = quoteHTML + '<p class=\"tags\">Tags: ' + selectedQuote.tags+ '</p>';\n\t}\n\t// Remove the selected quote and color from their array\n\trandomQuotes.splice(randomQuotes.indexOf(selectedQuote), 1);\n\trandomColor.splice(randomColor.indexOf(newColor), 1);\n\t// Insert final HTML string into quote-box div\n\tdocument.getElementById('quote-box').innerHTML = quoteHTML;\n\t// Change background color to a new random color\n\tdocument.body.style.backgroundColor = newColor;\n\tdocument.getElementById('loadQuote').style.backgroundColor = newColor;\n\t// When all the quotes have been used, refill the randomQuotes array\n\t// and empty the usedQuotes array\n\tif (randomQuotes.length === 0) {\n\t\trandomQuotes = usedQuotes;\n\t\tusedQuotes = [];\n\t}\n\t// When all the colors have been used, refill the randomColor array\n\t// and empty the usedColors array\n\tif (randomColor.length === 0) {\n\t\trandomColor = usedColors;\n\t\tusedColors = [];\n\t}\n}", "function printQuote() {\n var quoteHTML;\n var outputDiv;\n var randomObject = getRandomQuote();\n //conditional added for quote object lacking year or citation properties\n quoteHTML = `<p class=\"quote\">${randomObject.quote}</p>\n <p class=\"source\">${randomObject.author}</p>`\n outputDiv = document.getElementById('quote-box');\n outputDiv.innerHTML = quoteHTML;\n }", "function printQuote() {\n displayedQuote = getRandomQuote();\n message = `<p class=\"quote\">${displayedQuote.quote}</p>\n <p class=\"source\">${displayedQuote.source}`;\n if (displayedQuote.citation) {\n message += `<span class=\"citation\">${displayedQuote.citation}</span>`\n }\n if (displayedQuote.year) {\n message += `<span class=\"year\">${displayedQuote.year}</span>`\n }\n if (displayedQuote.group) {\n message += `<span class=\"group\">${displayedQuote.group}</span>`\n }\n\n message += `</p>`;\n return document.getElementById('quote-box').innerHTML = message; //applies random quote and props\n}", "function printQuote() {\n\n let quote = getRandomQuote()\n let template =\n `<p class=\"quote\"> ${quote.quote} </p>\n <p class=\"source\"> ${quote.source}\n ${quote.citation ? `<span class=\"citation\"> ${quote.citation} </span>` : \"\" }\n ${quote.year ? `<span class=\"year\"> ${quote.year} </span>` : \"\" }\n </p>`;\n\n document.getElementById('quote-box').innerHTML = template;\n document.body.style.backgroundColor = getRandomColor();\n}", "function printQuote() {\n var i = getRandomQuote();\n var HTML = \"\";\n\n HTML += \"<p class = 'quote'> \" + i.quote + \"</p>\";\n HTML += \"<p class = 'source'> \" + i.source;\n if (i.citation) {\n HTML += \"<span class 'citation'> \" + i.citation + \"</span>\";\n }\n if (i.year) {\n HTML += \"<span class = 'year'> \" + i.year + \"</span>\";\n }\n if (i.category) {\n HTML += \"<span class = 'category'>\" + i.category + \"</span>\"\n }\n HTML += \"<p>\";\n\n document.getElementById('quote-box').innerHTML = HTML;\n}", "function printQuote() {\n let randomQuote = getRandomQuote();\n let html = '';\n html += '<p class=\"quote\"> ' + randomQuote.quote + ' </p>';\n html += '<p class=\"source\"> ' + randomQuote.source;\n if(randomQuote.citation){\n html += '<span class=\"citation\"> ' + randomQuote.citation + ' </span>';\n }\n if(randomQuote.year){\n html += '<span class=\"year\"> ' + randomQuote.year + ' </span>';\n }\n if(randomQuote.tag){\n html += '<span class=\"tag\"> ' + randomQuote.tag + ' </span>';\n }\n html += '</p>';\n let quoteDiv = document.getElementById('quote-box');\n quoteDiv.innerHTML = html;\n}", "function printQuote() {\n var HTML = '';\n var display = getRandomQuote();\n \n HTML = \"<p class = 'quote'>\" + display.quote + \"</p>\";\n HTML += \"<p class = 'source'>\" + display.source;\n \n if (display.citation != \"\") {\n \n HTML += \"<span class = 'citation'>\" + display.citation + \"</span>\";\n }\n if (display.year != \"\") {\n \n HTML += \"<span class = 'year'>\" + display.year + \"</span>\";\n }\n \n HTML += \"</p>\";\n \n document.getElementById('quote-box').innerHTML = HTML;\n }", "function printQuote() {\n\t//calling the getRandomQuote function\n\tgetRandomQuote();\n\t//calling the random color generator\n\trandColor();\n\tdocument.getElementById('quote-box').innerHTML = '<p class=\"quote\">' + displayQuote.quote + '</p>' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t'<p class=\"source\">' + displayQuote.source + '<span class=\"citation\">' + \n\t\t\t\t\t\t\t\t\t\t\t\t\tdisplayQuote.citation + '</span>' + '<span class=\"year\">' + displayQuote.year + '</span>' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t'<span class=\"tag\">' + displayQuote.tag + '</span>' + '</p>';\n\tconsole.log(displayQuote);\n}", "function printQuote() {\n let randomQuote = getRandomQuote();\n \n html = '<p class = \"quote\">' + randomQuote.quote + '</p>';\n html += '<p class = \"source\">' + randomQuote.source;\n html += '<span class = \"citation\" > ' + randomQuote.citation + ' </span>';\n\n if (randomQuote.tags) {\n html += '<span class= \"tags\">' + randomQuote.tags.join(\" | \") + '</span>';\n };\n if (randomQuote.year) {\n html += '<span class= \"year\">' + randomQuote.year + '</span>'\n } \n html += '</p>'; \n //targets the quotebox id to add to the page container\n let quoteBox = document.getElementById('quote-box');\n quoteBox.innerHTML = html;\n}", "function printQuote(){\n\tvar selectedQuote = getRandomQuote();\n\n\tvar quoteString = '<p class=\"quote\">';\n\t\tquoteString += selectedQuote.quote;\n\t\tquoteString += '</p>';\n\t\tquoteString += '<p class=\"source\">';\n\t\tquoteString += selectedQuote.source;\n\t\n\t//check for empty citation property and don't add citation block if citation property empty\n\tif (selectedQuote.citation !== undefined){ \n\t\tquoteString += '<span class=\"citation\">';\n\t\tquoteString += selectedQuote.citation;\n\t\tquoteString += '</span>';\n\t}\n\n\t//check for empty year property and don't add year block if citation property empty\n\tif (selectedQuote.year !== undefined){\n\t\tquoteString += '<span class=\"year\">';\n\t\tquoteString += selectedQuote.year;\n\t\tquoteString += '</span>';\n\t}\n\t\tquoteString += '</p>';\n\n\t\t//add the built up string to html\n\t\tdocument.getElementById('quote-box').innerHTML = quoteString;\n}", "function printQuote(){\n var rgbColor;\n var myQuote = getRandomQuote(); // obtain the random quote from the quotes array\n\n // Determine if a previous quote already exist. If one does and if it's the same as the new one, then generate another one. Keep checking until the new one is unique.\n if(document.getElementById(\"quote\") != null) {\n var previousQuote = document.getElementById(\"quote\").innerText;\n while(myQuote.quote === previousQuote) {\n myQuote = getRandomQuote();\n }\n }\n \n // Add the quote and source paragraphs to the HTML output.\n HTML = `<p class=\"quote\" id=\"quote\">${myQuote.quote}</p>\n <p class=\"source\">${myQuote.source}`;\n\n if(myQuote.citation) {HTML += `<span class=\"citation\">${myQuote.citation}</span>`} // determine if quote object has a citation property and if so add it to the HTML output array.\n if(myQuote.year) {HTML += `<span class=\"year\">${myQuote.year}</span>`} // determine if quote object has a citation property and if so add it to the HTML output array.\n if(myQuote.tags) {HTML += `<span class=\"tags\">${myQuote.tags}</span>`} // determine if the quote object contain tags and if so add it to the HTML output array.\n\n HTML += `</p>`; // source paragraph closing\n\n document.body.style.backgroundColor = randomColor(); // change the page background color.\n document.getElementById('quote-box').innerHTML = HTML; // update the quote-box div on the main HTML page.\n}", "function printQuote() {\n let selectedQuote = getRandomQuote(quotes);\n let html = `\n <p class = \"quote\"> ${selectedQuote.quote}</p>\n <p class = \"source\"> ${selectedQuote.source}\n `\n if (selectedQuote.citation) {\n html += `<span class = \"citation\"> ${selectedQuote.citation}</span>`;\n }\n if (selectedQuote.year) {\n html += `<span class = \"year\"> ${selectedQuote.year}</span>`;\n }\n if (selectedQuote.type) {\n html += `<span class = \"type\"> ${selectedQuote.type}</span>`\n }\n html += '</p>';\n \n // 4. The html string prints the selected object onto the document\n document.getElementById('quote-box').innerHTML = html; \n\n /*\n 5. A random background color is loaded on the document\n # Code adapted from https://www.w3schools.com/jsref/prop_style_background.asp\n */\n document.body.style.background = randomBackgroundColor(); \n}", "function printQuote() {\n let chosenQuote = getRandomQuote();\n let html = `<p class=\"quote\">${chosenQuote.quote}</p>\n <p class=\"source\">${chosenQuote.source}`;\n if (chosenQuote.hasOwnProperty(\"citation\")) {\n html += `<span class=\"citation\">${chosenQuote.citation}</span>`;\n }\n if (chosenQuote.hasOwnProperty(\"year\")) {\n html += `<span class=\"year\">${chosenQuote.year}</span>`;\n }\n if (chosenQuote.hasOwnProperty(\"tags\")) {\n html += `<p class=\"tags\">tags: `\n for (let i = 0; i < chosenQuote.tags.length; i++) {\n html += `<span>${chosenQuote.tags[i]} </span>`;\n }\n html += `</p>`\n }\n html += `</p>`;\n changeBackgroundColor();\n document.getElementById('quote-box').innerHTML = html;\n }", "function printQuote() { \n var resultQuote = getRandomQuote(quotes); // variable that calls \"getRandomQuote\" function\n var displayColor = getRandomColor(colors); // variable that calls \"getRandomColor\" function\n var html = ''; // variable that initiates html string\n html = '<p class=\"quote\">' + resultQuote.quote + '</p>'; // \"quote\" property will be added to string\n html += '<p class=\"source\">' + resultQuote.source; // \"source\" property will be added to string\n if ( resultQuote.citation ) { // program checks to see if there is a \"citation\" property to add to the string\n html += '<span class=\"citation\">' + resultQuote.citation + '</span>'; // if there is, it will be added to the string\n } else { // otherwise\n html += ''; // the string will continue without printing \"citation\"\n } \n if ( resultQuote.year ) { // program checks to see if there is a \"year\" property to add to the string\n html += '<span class=\"year\">' + resultQuote.year + '</span>'; // if there is it will be added to the string\n } else { // otherwise\n html += ''; // the string will continue without printing \"year\"\n }\n if ( resultQuote.tags ) { // the program checks to see if there is a \"tags\" property to add to the string \n html += '<span class=\"tags\">' + resultQuote.tags + '</span>'; // if there is it will be added to the string\n } else { // otherwise\n html += '</p>'; // the string will close\n }\ndocument.getElementById('quote-box').innerHTML = html; // html string completed\ndocument.body.style.background = displayColor.backgroundColor; // background color will randomly change when each new quote is displayed\n}", "function printQuote() {\n quoteInfo = getRandomQuote();\n htmlString = '';\n htmlString += '<p class=\"quote\">' + quoteInfo.quote + '</p>';\n htmlString += '<p class=\"source\">' + quoteInfo.source;\n if (quoteInfo.citation != '') {\n htmlString += '<span class=\"citation\">' + quoteInfo.citation + '</span>';\n } else {''}\n if (quoteInfo.year != '') {\n htmlString += '<span class=\"year\">' + quoteInfo.year + '</span>';\n } else {''}\n htmlString += '</p>';\n console.log(quoteInfo);\n return document.getElementById('quote-box').innerHTML = htmlString;\n}", "function printQuote() {\n // getQuote is the return value of the getRandomQuote function\n getQuote = getRandomQuote();\n /* quoteText is the string of text we will be inserting into the index.html file to display our quotes */\n let quoteText = `<p class='quote'>${getQuote.quote}</p>\n <p class='source'>${getQuote.source}`;\n //*This if statements checks to see if there is a citation property in our object */\n if (getQuote.citation) {\n quoteText += `<span class='citation'>${getQuote.citation}</span>`;\n }\n //*This if statements checks to see if there is a year property in our object */\n if (getQuote.year) {\n quoteText += `<span class='year'>${getQuote.year}</span>`;\n }\n if (getQuote.category) {\n quoteText += `<span class='year'>${getQuote.category}</span>`\n }\n quoteText += `</p>`;\n // We are now assigning the inner HTML to our quoteText variable\n document.getElementById('quote-box').innerHTML = quoteText;\n}", "function printQuote() {\n randomQuote = getRandomQuote();\n console.log(randomQuote.quote);\n var stringHTML = '<p class=\"quote\">' + randomQuote.quote + '</p>';\n stringHTML += '<p class=\"source\">' + randomQuote.source;\n if (randomQuote.citation) {\n stringHTML += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n if (randomQuote.year) {\n stringHTML += '<span class=\"year\">' + randomQuote.year + '</span>';\n }\n stringHTML += '<span class=\"tags\"> ( ' + randomQuote.tags + ' ) </span></p>';\n\n var r = randomColor();\n var g = randomColor();\n var b = randomColor();\n\n document.getElementById('quote-box').innerHTML = stringHTML;\n document.body.style.backgroundColor = \"rgb(\" + r + \", \" + g + \", \" + b + \")\";\n\n }", "function printQuote(){\n //calls the getRandomQuote() function, then stores returned object into a variable\n getRandomQuote();\n //construct the string containing the different quote properties using HTML template\n}", "function printQuote(){\n var k = getRandomQuote();\n var completeQuote = '<p class=\"quote\">'+ k.quote + '</p>';\n completeQuote += '<p class=\"source\">' + k.source; \n if (k.citation !== ''){\n completeQuote += ' <span class=\"citation\">' + k.citation + '</span>';\n }\n if (k.year !== ''){\n completeQuote += ' <span class=\"year\">' + k.year + '</span></p>';\n }\n var quoteBox = document.getElementById('quote-box');\n quoteBox.innerHTML = completeQuote; \n }", "function printQuote() {\n let randomQuote = getRandomQuote();\n let htmlString = `<p class=\"quote\">${randomQuote.quote}</p><p class=\"source\">${randomQuote.source}`;\n // If Statements for optional properties (including subject which is for extra credit)\n if ( randomQuote.citation ) {\n htmlString += `<span class=\"citation\">${randomQuote.citation}</span>`;\n }\n if ( randomQuote.year ) {\n htmlString += `<span class=\"year\">${randomQuote.year}</span>`;\n }\n if ( randomQuote.subject ) {\n htmlString += `<span> - Subject: ${randomQuote.subject}</span>`;\n }\n htmlString += `</p>`;\n changeBackGroundColor();\n return document.getElementById('quote-box').innerHTML = htmlString;\n}", "function printQuote() {\n let currentQuote = getRandomQuote();\n let currentColor = getRandomColor();\n html = `<p class=\"quote\"> ${currentQuote.quote} \"</p>`;\n html += `<p class=\"source\"> ${currentQuote.source}`;\n if (currentQuote.citation !== \"\") {\n html += `<span class=\"citation\"> ${currentQuote.citation} </span>`;\n }\n if (currentQuote.year !== \"\") {\n html += '<span class=\"year\">' + currentQuote[\"year\"] + '</span>';\n }\n if (currentQuote.tags !== \"\") {\n html += `<span class=\"tags\"> <br> ${currentQuote.tags} </span>`;\n }\n html += '</p>';\n document.body.style.backgroundColor = currentColor;\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote() {\n\t// quote stores the random quote from the getRandomQuote() function.\n\tconst quote \t = getRandomQuote();\n\t// author stores the author part of the Quotes Object array.\n\tconst author = quote.source;\n\t// said stores the quote part of the Quotes Object array.\n\tconst said = quote.quotes;\n\t//print creates a template that will be used to display the quotes/source/year/citations\n\tvar print = '<p class=\"quote\">' + said + '</p>';\n\t\tprint += '<p class=\"source\">' + author \t;\n\t//if there is a citation in the Object Array it will be added to the output\n\tif(quote.citation){\n\t\tprint +=\t'<span class=\"citation\">' + quote.citation + '</span>';\n\t}\n\n\t//if there is a year in the Object Array it will be added to the output\n\tif(quote.year){\n\t\tprint += '<span class=\"year\">' + quote.year + '</span>';\n\t}\n\n\tprint += '</p>';\n\t//This will display the HTML template to the screen\n \tdocument.getElementById('quote-box').innerHTML = print;\n\nreturn;\n}", "function printQuote() {\n var randomQ, quote, source, citation, year, tags, printArray, bkColor;\n\n randomQ = getRandomQuote();\n\n // Variables that contain the content of array quotes\n quote = '<p class=\"quote\">' + randomQ.quote + '</p>';\n source = '<p class=\"source\">' + randomQ.source;\n tags = '<span class=\"tag\">' + randomQ.tags + '</span></p>';\n // *** THE HTML ABOVE ASSIGNED TO THE VARIABLES SOURCE, TAGS AND QUOTE WORK WELL BUT FOR SOME REASON IT DID NOT WORK FOR CITATION AND YEAR *** COULD YOU PLEASE COMMMENT ON THIS.\n citation = randomQ.citation;\n year = randomQ.year;\n\n // HTML Structure\n printArray = [\n // print QUOTE + SOURCE + TAGS\n quote + source + tags,\n // print QUOTE + SOURCE + CITATION + TAGS\n quote + source + '<span class=\"citation\">' + citation + '</span>' + tags,\n // print QUOTE + SOURCE + YEAR + TAGS\n quote + source + '<span class=\"year\">' + year + '</span>' + tags,\n // full print\n quote + source + '<span class=\"citation\">' + citation + '</span>' + '<span class=\"year\">' + year + '</span>' + tags\n ];\n\n // Call Color Generator function\n colorGenerator();\n\n // Conditions to print\n if (quote && source && citation && year && tags) {\n print(printArray[3]);\n } else if (quote && source && year && tags) {\n print(printArray[2]);\n } else if (quote && source && citation && tags) {\n print(printArray[1]);\n } else {\n print(printArray[0]);\n }\n}", "function printQuote () {\n let randomQuote = getRandomQuote();\n html = '<p class=\"quote\">' + randomQuote.quote + '</p>';\n html += '<p class=\"source\">' + randomQuote.source;\n\n\n//if citation is available...append onto the HTML script and print to the page\n if (randomQuote.citation) {\n html += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n }\n\n//if year is available...append onto the HTML script and print to the page\n if (randomQuote.year) {\n html += '<span class=\"year\">' + randomQuote.year + '</span>';\n }\n\n//if categorization is available...append onto the HTML script and print ot the page\n if (randomQuote.categorization) {\n html += '<h1>' + randomQuote.categorization + '</h1>';\n }\n\n//the div from the HTML file is called and set equal to the html script we create above\n let div = document.getElementById('quote-box').innerHTML = html;\n return html;\n}", "function printQuote() {\n var result = getRandomQuote(); // Calls and stores the getRandomQuote in a variable\n let main =\n `<p class='quote'>\n ${result.quote}\n </p>` +\n `<p class='source'>\n ${result.Author}\n </p>` +\n `<p class='citation'>\n ${result.citation} \n </p>` +\n `<p class='year'>\n ${result.year}\n </p>` +\n `<p class='tags'>\n ${result.tag}\n </p>`;\n document.getElementById('quote-box').innerHTML = main;\n}", "function printQuote() {\n var ranQuot = getRandomQuote();\n htmlString = ' ';\n htmlString += '<p class=\"quote\">' + ranQuot.quote + '</p>';\n htmlString += '<p class=\"source\">' + ranQuot.source;\n if (ranQuot.citation || ranQuot.year){\n htmlString += '<span class=\"citation\">' + ranQuot.citation + '</span>';\n htmlString += '<span class=\"year\">' + ranQuot.year + '</span>';\n '</p>';\n }\n document.getElementById('quote-box').innerHTML = htmlString;\n return htmlString;\n}", "function printQuote() {\n var result = getRandomQuote(quotes);\n var quoteString = `<p class='quote'> ${result.quote} </p>`;\n quoteString += `<p class='source'> ${result.source}`;\n if (result.citation !== undefined) {\n quoteString += `<span class='citation'> ${result.citation} </span>`;\n } if (result.year !== undefined) {\n quoteString += `<span class='year'> ${result.year}`;\n }\n quoteString += `<span class='year'> ${result.category}</span></p>`;\n /* This line of code will grab the body element from styles.css and\n change its background color to a random background color when button is clicked*/\n document.body.style.background = '#' + Math.floor(Math.random() * 1000);\n document.getElementById('quote-box').innerHTML = quoteString;\n}", "function printQuote(){\n\trColor()\n\tvar newQuote = getRandomQuote()\n\tvar messageQuote = '<p class=\"quote\">' + newQuote.quote + '</p>';\n\tvar messageSource ='<p class=\"source\">'+ newQuote.source ;\n\tvar fullQuote = messageQuote + messageSource; \n\n\tif (newQuote.citation){\n\t\tfullQuote += '<span class=\"citation\">' + newQuote.citation + '</span>';\n\t}\n\t\n\tif (newQuote.year){\n\t\tfullQuote += '<span class=\"year\">' + newQuote.year + '</span>';\n\t}\n\tif (newQuote.tag){\n\t\tfullQuote += '<span class=\"tag\">' + newQuote.tag + '</span>';\n\t}\n\t\n\tfullQuote += '</p>'\n\t\n return document.getElementById('quote-box').innerHTML = fullQuote; \n\n}", "function printQuote() {\n const randomQuote = getRandomQuote()\n const quoteBox = document.querySelector('#quote-box')\n \n // create and append paragraph with quote to #quote-box\n const quoteP = createEleClassContent('p', 'quote', randomQuote.quote)\n quoteBox.appendChild(quoteP)\n \n // create quote source paragraph and append to #quote-box\n const quoteSourceP = createEleClassContent('p', 'source', randomQuote.source)\n quoteBox.appendChild(quoteSourceP)\n \n // create quote citation span and qppend to paragraph with .source class\n const quoteCitationSpan = createEleClassContent('span', 'citation', randomQuote.citation)\n quoteSourceP.appendChild(quoteCitationSpan)\n \n //create quote year span and append to paragraph with .source class\n if( randomQuote.year != null ) {\n const quoteYearSpan = createEleClassContent('span', 'year', randomQuote.year)\n quoteSourceP.appendChild(quoteYearSpan)\n }\n \n}", "function printQuote(){\n var randomquote=getRandomQuote(quotes); \n var html='<p class=\"quote\">'+randomquote.quote+'</p>'+'<p class=\"source\">'+randomquote.saidby;\n\n if(randomquote.citation!=='')\n {html+='<span class=\"citation\">'+randomquote.citation+'</span>';}\n if(randomquote.date!=='')\n {html+='<span class=\"year\">'+randomquote.date+'</span></p>';}\n document.getElementById(\"quote-box\").innerHTML = html;\n\n\n}", "function printQuote() {\n randomColor();\n autoChange();\n var grq = getRandomQuote();\n var write1 = document.getElementById('quote-box')\n write1.innerHTML = '<p class=\"quote\">' + grq.quote + '</p>';\n write1.innerHTML += '<p class=\"source\">' + grq.source;\n if (grq['citation'] !== undefined) {\n write1.innerHTML += '<span class=\"citation\">' + grq.citation + '</span>'\n } else {\n write1.innerHTML += '</p>';\n }\n if (grq['year'] !== undefined) {\n write1.innerHTML += '<span class=\"year\">' + grq.year + '</span></p>';\n } else {\n write1.innerHTML += '</p>';\n }\n}", "function printQuote() {\n var changeBgColor = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);\n document.body.style.backgroundColor = changeBgColor;\n var getQuote = getRandomQuote();\n const citation = document.createElement('span');\n const year = document.createElement('span');\n citation.className = 'citation';\n year.className = 'year';\n\n quote.innerText = getQuote.quotes;\n source.innerText = getQuote.author;\n citation.innerText = getQuote.citation;\n source.appendChild(citation);\n year.innerText = getQuote.year;\n source.appendChild(year);\n\n\n\n\n}", "function printQuote(){\n const quoteObject = getRandomQuote();\n//The let variable holds the minimum necessary data to be displayed on the page\n let html = `\n <p class=\"quote\">${quoteObject.quote}</p>\n <p class=\"source\">${quoteObject.source}\n `;\n//This checks to see if there is a citation property in the object and adds it to the original html string\n if (quoteObject.citation !== undefined){\n let citation = `\n <span class=\"citation\"> ${quoteObject.citation} </span>\n `;\n html = `${html} ${citation}`;\n } \n//This checks to see if there is a year property in the quotes object and adds it to the html string\n if (quoteObject.year !== undefined){\n let year = `\n <span class=\"citation\"> ${quoteObject.year} </span>\n `;\n html = `${html} ${year}`;\n } \n if (quoteObject.tags !== undefined){\n let tags = `\n <span class=\"tags\"> ${quoteObject.tags} </span>\n `;\n html = `${html} ${tags}`;\n } \n html += `</p>`;\n\n//This takes the full string found in the html variable and displays in on the page in the proper format\n document.getElementById('quote-box').innerHTML = html; \n//This calls the background function to change the background to a random colour everytime the quote changes\n document.body.style.backgroundColor = background();\n}", "function printQuote ()\n{\n var quoteChoice = getRandomQuote();\n\n var html = '';\n html += '<p class = \"quote\">'+ quoteChoice.quote + '</p>';\n html += '<p class = \"source\">' + quoteChoice.source;\n\n if(quoteChoice.citation)\n {\n html += '<span class = \"citation\">' + quoteChoice.citation + '</span>';\n }\n if(quoteChoice.year)\n {\n html += '<span class = \"year\">' + quoteChoice.year + '</span>';\n }\n\nhtml += '</p>';\n\ndocument.getElementById('quote-box').innerHTML= html;\n\n return html;\n}", "function printQuote() {\n const printRandomQuote = getRandomQuote();\n let html = `\n<p class=\"quote\"> ${printRandomQuote.quote} </p>\n<p class=\"source\"> ${printRandomQuote.source}\n <span class=\"citation\"> ${printRandomQuote.citation} </span>\n <span class=\"year\"> ${printRandomQuote.year} </span>\n <span class=\"director\"> , directed by: <strong>${printRandomQuote.director}</strong> </span>\n</p>\n`\n document.getElementById('quote-box').innerHTML = html;\n randomRGB();\n}", "function printQuote(){\nvar rand = getRandomQuote();\nvar quote = rand[1];\nvar author = rand[0];\n\n//checks for year\nvar year = rand[2];\n\n\nvar html = '<p class=\"quote\">' + quote +'</p>' + '<p class=\"source\">' + author ;\nif (year != ''){\n html += '</span><span class=\"year\">' + year + \"</span></p>\";\n}\nelse{\n\n}\ndocument.getElementById('quote-box').innerHTML = html;\n}", "function printQuote () {\n var selectedQuote = getRandomQuote();\n var html = '<p class=\"quote\">' + selectedQuote.quote + '</p>' + '<p class=\"source\">' + selectedQuote.source +\n '<span class=\"citation\">' + selectedQuote.citation + '</span>' + '<span class=\"year\">' + selectedQuote.year + '</span>' + '<span class=\"tag\">' + selectedQuote.tag + '</span>' + '</p>';\n\n document.getElementById('quote-box').innerHTML = html;\n}", "function printQuote() {\n\tvar quote = getRandomQuote();\t// Assigns random quote object\n\tvar message = '';\n\n\t// Quote display\n\tmessage += '<p class=\"quote\">' + quote.text + '</p>';\n\tmessage += '<p class=\"source\">' + quote.source;\n\n\t// If citation property exists\n\tif (quote.citation !== 'N/A') {\n\t\tmessage += '<span class=\"citation\">' + quote.citation + '</span>';\n\t}\n\t// If year property exists\n\tif (quote.year !== 'N/A') {\n\t\tmessage += '<span class=\"year\">' + quote.year + '</span>';\n\t}\n\t// Displays the tag for the category\n\tmessage += '<span class=\"tags\">' + quote.tags + '</span>'\n\tmessage += '</p>';\n\n\tdocument.getElementById('quote-box').innerHTML = message;\n\tchangeColor();\n}", "function printQuote(quotes) {\n var words = getRandomQuote();\n html = '<p class=\"quote\">' + words.quote + '</p>' + '';\n html += '<p class=\"source\">' + words.source + ''; \n if (words.citation != null) {\n html += '<span class=\"citation\">' + words.citation + '</span>';\n };\n if (words.year != null) {\n html += '<span class=\"year\">' + words.year + '</span>';\n };\n if (words.tag != null) {\n html += '<span class=\"tag\">' + words.tag + '</span>';\n };\n html += '</p>';\n var outputDiv = document.getElementById('quote-box');\n outputDiv.innerHTML = html;\n document.body.style.background = randomColor();\n return html;\n}", "function printQuote() {\n let obj = getRandomQuote();\n\n let Color = getRandomColors();\n let print = \"\";\n\n print += '<p class=\"quote\">' + obj.quote + \"</p>\";\n\n print += '<p class=\"source\">' + obj.source;\n\n if (obj.citation) {\n print += '<span class=\"citation\">' + obj.citation + \"</span>\";\n }\n\n if (obj.year) {\n print += '<span class=\"year\">' + obj.year + \"</span>\";\n }\n\n if (obj.tag) {\n print += '<span class=\"tag\">' + obj.tag + \"</span>\";\n }\n (\"</p>\");\n\n document.getElementById(\"quote-box\").innerHTML = print;\n document.getElementById(\"body\").style.backgroundColor = Color;\n\n TimeClear();\n startTimer();\n}", "function renderNewQuote() {\n var item = Math.floor(Math.random() * 10); \n displayQuote(quoteData.data[item].quoteText, quoteData.data[item].quoteAuthor)\n}", "function printQuote(){\n var randomQuote =getRandomQuote();\n document.querySelector(\".quote\").innerHTML=randomQuote.quote;\n document.querySelector(\".source\").innerHTML=randomQuote.source;\n \n if(randomQuote.citation){\n var span = document.createElement(\"span\");\n span.className=\"citation\";\n document.querySelector(\".source\").appendChild(span);\n document.querySelector(\".citation\").innerHTML=randomQuote.citation;\n }\n if(randomQuote.year){\n var span = document.createElement(\"span\");\n span.className=\"year\";\n document.querySelector(\".source\").appendChild(span);\n document.querySelector(\".year\").innerHTML=randomQuote.year;\n }\n}", "function printQuote() {\n// random quote\n var randomQuote = getRandomQuote();\n\n var message = '<p class =\"quote\">' + randomQuote.quote + '</p>';\n message += '<p class =\"source\">' + randomQuote.source;\n if (! randomQuote.citation) {\n } else {\n message += '<span class =\"citation\">' + randomQuote.citation + '</span>';\n }\n if (! randomQuote.year) {\n } else {\n message += '<span class =\"year\">' + randomQuote.year + '</span>';\n }\n message += ', <span class=\"tags\">' + randomQuote.tags + '</span></p>';\n\n\n\n // prints final HTML to the page\n document.getElementById('quote-box').innerHTML = message;\n\n // random color\n var randomColor = getRandomColor();\n // prints final HTML to the page\n document.body.style.background=randomColor;\n\n}", "function printQuote() {\n clearTimeout(timer); // clear previous timeout in case quout is generated using the button\n\n let selectedQuote = getRandomQuote(quotes);\n let html = '';\n html += '<p class=\"quote\">' + selectedQuote.quote + '</p>';\n html += '<p class=\"source\">' + selectedQuote.source;\n\n // if there is a citation add it to the string\n if (selectedQuote.citation !== '') {\n html += '<span class=\"citation\">' + selectedQuote.citation + '</span>';\n }\n\n // if there is a year add it to the string\n if (selectedQuote.year !== -1) {\n html += '<span class=\"year\">' + selectedQuote.year + '</span>';\n }\n html += '</p>';\n\n document.getElementById('quote-box').innerHTML = html;\n setRandomColor();\n timer = setTimeout(updateQuote, delay);\n}", "function printQuote() {\n var randomQuote = getRandomQuote();\n var HTML = \"\";\n HTML += \"<p class='quote'>\" + randomQuote.quote + \"</p>\";\n HTML += \"<p class='source'>\" + randomQuote.source;\n if (randomQuote.citation) {\n HTML += \"<span class = 'citation'>\" + randomQuote.citation + \"</span>\"\n }\n if (randomQuote.category) {\n HTML += \"<span class='category'>\" + randomQuote.category + \"</span>\";\n }\n if (randomQuote.year) {\n HTML += \"<span class='year'>\" + randomQuote.year + \"</span>\"\n }\n HTML += \"</p>\";\n\n document.getElementById('quote-box').innerHTML = HTML;\n\n}", "function printQuote() {\n let chosenQuote = getRandomQuote();\n let quoteText = \n '<p class=\"quote\">' + chosenQuote.quote + '</p>';\n quoteText += '<p class=\"source\"> ' + chosenQuote.author + ' ';\n if (chosenQuote.citation) {\n quoteText += '<span class=\"citation\"> ' + chosenQuote.citation + '</span>';\n }\n if (chosenQuote.year) {\n quoteText += '<span class=\"year\"> ' + chosenQuote.year + '</span>';\n }\n '</p>';\n document.getElementById('quote-box').innerHTML = quoteText;\n }", "function printQuote () {\n var html = '';\n var randomQuote = getRandomQuote();\n html += \"<p class = 'quote'>\" + randomQuote.quote + \"</p>\";\n html += \"<p class = 'source'>\" + randomQuote.source ;\n if (randomQuote.citation) {\n html += \"<span class = 'citation' >\" + randomQuote.citation + \"</span>\";\n \n }\n if (randomQuote.year) {\n html += \"<span class = 'year ' >\" + randomQuote.year + \"</span>\";\n \n \n }\n html += '</p>';\n document.getElementById('quote-box').innerHTML = html;\n\n}", "function printQuote() {\n let color = rndRGB();\n let object = getRandomQuuote(quotes);\n let string = '';\n if (object.citation !== undefined && object.year !== undefined) {\n string = \"<p class=\\\"quote\\\">\" + \" \" + object.quote + \"</p>\" + \"\\n\" +\n \"<p class=\\\"source\\\">\" + object.source + \"\\n\" +\n \"<span class=\\\"citation\\\">\" + object.citation + \"</span>\" +\"\\n\" +\n \"<span class=\\\"year\\\">\" + object.year + \"</span>\" +\"\\n\" +\n \"<span class=\\\"tag\\\">\" + object.tag + \"</span>\" +\"\\n\" +\n \"</p>\"\n } else if (object.citation === undefined && object.year === undefined) {\n string = \"<p class=\\\"quote\\\">\" + \" \" + object.quote + \"</p>\" + \"\\n\" +\n \"<p class=\\\"source\\\">\" + object.source + \"\\n\" +\n \"<span class=\\\"tag\\\">\" + object.tag + \"</span>\" +\"\\n\" +\n \"</p>\"\n } else if (object.citation !== undefined && object.year === undefined) {\n string = \"<p class=\\\"quote\\\">\" + \" \" + object.quote + \"</p>\" + \"\\n\" +\n \"<p class=\\\"source\\\">\" + object.source + \"\\n\" +\n \"<span class=\\\"citation\\\">\" + object.citation + \"</span>\" +\"\\n\" +\n \"<span class=\\\"tag\\\">\" + object.tag + \"</span>\" +\"\\n\" +\n \"</p>\"\n } else if (object.citation === undefined && object.year !== undefined) {\n string = \"<p class=\\\"quote\\\">\" + \" \" + object.quote + \"</p>\" + \"\\n\" +\n \"<p class=\\\"source\\\">\" + object.source + \"\\n\" +\n \"<span class=\\\"year\\\">\" + object.year + \"</span>\" +\"\\n\" +\n \"<span class=\\\"tag\\\">\" + object.tag + \"</span>\" +\"\\n\" +\n \"</p>\"\n }\n document.getElementById('quote-box').innerHTML = string;\n document.getElementById('loadQuote').style.backgroundColor = color;\n document.getElementsByTagName('body')[0].style.backgroundColor = color;\n i = 0; // reset counter after the button is clicked\n}", "function printQuote(){\n\t\n\tvar newQuote=getRandomQuote();\n\n\tif (newQuote.length === 2) {\n\t\t\n\t\tdocument.getElementById('quote-box').innerHTML =\n\n\t\t'<p class=\"quote\">' + newQuote[0] + '</p>' +\n\t\t'<p class=\"source\">' + newQuote[1] +\n\t\t'</p>'\n\n\t}\n\n\telse if (newQuote.length === 3) {\n\t\t\n\t\tdocument.getElementById('quote-box').innerHTML =\n\n\t\t'<p class=\"quote\">' + newQuote[0] + '</p>' +\n\t\t'<p class=\"source\">' + newQuote[1] +\n\t\t\t'<span class=\"citation\">' + newQuote[2] + '</span>' +\n\t\t'</p>'\n\n\t}\n\n\telse {\n\t\t\n\t\tdocument.getElementById('quote-box').innerHTML =\n\n\t\t'<p class=\"quote\">' + newQuote[0] + '</p>' +\n\t\t'<p class=\"source\">' + newQuote[1] +\n\t\t\t'<span class=\"citation\">' + newQuote[2] + '</span>' +\n\t\t\t'<span class=\"year\">' + newQuote[3] + '</span>' +\n\t\t'</p>'\n\n\t}\n\n}", "function printQuote(){\n var randomQuote = getRandomQuote();\n\n var html = '<p class=\"quote\">' + randomQuote.quote + '</p>' + '<p class=\"source\">' + randomQuote.source + '</p>';\n\n if (randomQuote.citation){\n\n html += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n\n }\n\n if (randomQuote.year) {\n html += '<span class=\"year\">' + randomQuote.year + '</span>';\n\n }\n\n\n document.getElementById('quote-box').innerHTML = \"\";\n document.getElementById('quote-box').innerHTML = html;\n\n}", "function printQuote() {\n var selectedQuote = getRandomQuote();\n var randomColor = getRandomColor();\n var fullQuote = '<p class=\"quote\">' + selectedQuote.quote + '</p>';\n fullQuote += '<p class=\"source\">' + selectedQuote.source + '</p>';\n fullQuote += '<p class=tags>' + selectedQuote.tags + '</p>';\n fullQuote += '<style>body { background-color:' + randomColor + '}</style>';\n document.getElementById('quote-box').innerHTML = fullQuote;\n\n}", "function printQuote(quote) \n{\n let message = getRandomQuote(quotes);\n let template = ' ';\n\n template = \"<p class='quote'>\" + message.quote + \"</p>\";\n template += \"<p class='source'>\" + message.source;\n\n if (message.citation)\n { template += \"<span class='citation'>\" + message.citation + \"</span>\" ;}\n\n if (message.year) \n { template += \"<span class='year'>\" + message.year + \"</span>\" ;}\n\n if (message.tags) \n { template += \"<span class='tags'>\" + message.tags + \"</span>\"; }\n \n template += \"</p>\"\n\n document.getElementById(\"quote-box\").innerHTML = template;\n const colorResult = getRandomColor();\n document.body.style.background = colorResult;\n\n}", "function printQuote() {\n\tvar quoteToDisplay = getRandomQuote();\n\tvar displayedText = '<p class=\"quote\">'+ quoteToDisplay.quote + '</p>' +\n\t\t\t\t\t\t'<p class=\"source\">' + quoteToDisplay.source;\n\t\t// check to see if citation exist for \"this\" code\t\t\t\t\n\t\tif (quoteToDisplay.citation) {\n\t\t\tdisplayedText += '<span class=\"citation\">' + quoteToDisplay.citation + '</span>';\n\t\t}\n\t\t// check to see if year exist for this code\n\t\tif (quoteToDisplay.year) {\n\t\t\tdisplayedText += '</span> <span class=\"year\">' + quoteToDisplay.year + '</span></p>';\n\t\t}\n\t\n\tdocument.getElementById('quote-box').innerHTML= displayedText;\n\tdocument.querySelector(\"body\").style.background = ranColor();\n\n\t// anytime a quote is dispayed, the timer resets and then starts from 0 seconds\n\tstopSetInterval();\n\tstartSetIterval();\n} // print Quote", "function printQuote() {\n //load quote object to display into q\n var q = getRandomQuote();\n //start building htmlArray with the two required bits: quote and source,\n //with a paragraph between them will be closed at the end of the string\n var htmlArray = [\n '<p class=\"quote\">' + q.quote + \"</p>\",\n '<p class=\"source\">' + q.source\n ];\n //add to htmlArray any of year, citation and any tags present\n if (q.citation) {\n htmlArray.push('<span class=\"citation\">' + q.citation + \"</span>\");\n }\n if (q.year) {\n htmlArray.push('<span class=\"year\">' + q.year + \"</span>\");\n }\n //now that the second line is complete, close the p tag\n htmlArray.push(\"</p>\");\n\n //handling tags if present\n if (q.tags && q.tags.length) {\n //create a new paragraph for the tags\n htmlArray.push('<p class=\"tags\">');\n //add the tags as csv\n htmlArray.push(q.tags.join(\", \"));\n //close the tag paragraph\n htmlArray.push(\"</p>\");\n }\n //convert to a string\n var htmlString = htmlArray.join(\"\");\n //console.log('htmlString')\n //console.log(htmlString)\n\n //display\n document.getElementById(\"quote-box\").innerHTML = htmlString;\n\n //update color\n document.body.style.background = \"#\" + color();\n\n //set updateTime\n updateTime = new Date();\n}", "function printQuote(){\n\n\tlet randomQuote = getRandomQuote();\n\t\t\n\tlet message = '<p class=\"quote\">' + randomQuote.quote + '</p>';\n\tmessage += '<p class=\"source\">' + randomQuote.source ;\n\n\tif (randomQuote.citation){\n\t\tmessage += '<span class=\"citation\">' + randomQuote.citation + '</span>';\n\t}\n\n\tif (randomQuote.year){\n\t\tmessage += '<span class=\"year\">' + randomQuote.year + '</span>';\n\t} \n\t//Extra: tags on quotes show up if present\n\tif (randomQuote.tag){\n\t\tmessage += '<span class=\"tag\">, <i>tagged: ' + randomQuote.tag + '</i></span>';\n\t} \n\tmessage += '</p>';\n\n\tdocument.getElementById('quote-box').innerHTML = message;\n\treturn message;\n}", "function printQuote() {\n\tdisplayedQuote = getRandomQuote();\n\tsetHTML(displayedQuote);\n}", "function printQuote() {\n var currentQuote = getRandomQuote();\n\n if (currentQuote.citation) {\n textToPrint += '<span class=\"citation\"> ${currentQuote.citation} </span>'\n }\n\n if (currentQuote.year) {\n textToPrint += '<span class=\"year\"> ${currentQuote.year} </span> </p>'\n }\n\n\n var textToPrint = `<p class=\"quote\"> ${currentQuote.quote}</p>\n <p class=\"source\"> ${currentQuote.source}`\n\n\n if (currentQuote.job) {\n textToPrint += ` (${currentQuote.job})`\n }\n\n if (currentQuote.citation) {\n textToPrint += `<span class=\"citation\"> ${currentQuote.citation} </span>`\n }\n\n if (currentQuote.year) {\n textToPrint += `<span class=\"year\"> ${currentQuote.year} </span> </p>`\n }\n\n\n textToPrint += `<img src=\"${currentQuote.image}\" alt=\"gif of source\"></p>`;\n document.getElementById('quote-box').innerHTML = textToPrint;\n\n var newColor = getRandomColor();\n\n if (backgroundColor !== newColor){ //check so that the color never repeats twice in a row even when the quote changes\n backgroundColor = newColor;\n } else {\n backgroundColor = '#65BEA9';\n }\n\n document.body.style.backgroundColor = `${backgroundColor}`;\n}", "function showRandQuote() {\n var index = Math.floor(Math.random() * window.globals.quotes.length);\n $(\"#quote\").text(window.globals.quotes[index]);\n $(\"#quote-author\").text(\"- \" + window.globals.people[index]);\n}", "function printQuote() {\n randomColor()\n const randomQuote_object = getRandomQuote();\n let htmlString = `\n <p class= 'quote'> ${randomQuote_object.quote} </p>\n <p class= 'source'> ${randomQuote_object.source}\n \n`\n{\nif (randomQuote_object.citation){\n htmlString += `<span class= 'citation'> '${randomQuote_object.citation}' </span>`;\n}\nif (randomQuote_object.year){\n htmlString += `<span class= 'year'> '${randomQuote_object.year}' </span>`;\n} \n\nhtmlString += `\n</p><br>\n<h1><a href= '${randomQuote_object.more_info}'> Learn About ${randomQuote_object.source} </a></h1>`\n\n\ndocument.getElementById('quote-box').innerHTML = htmlString;\n\n\n}\n\n }", "function printQuote() {\n const quote = getRandomQuote();\n\n // To add extra info, don't include </p> at the end\n let html = `\n <p class=\"quote\">${quote.quote}</p>\n <p class=\"source\">${quote.source}`;\n\n // Check if there are citation or year or tags\n if (quote.citation !== undefined) {\n html += `<span class=\"citation\">${quote.citation}</span>`;\n }\n if (quote.year !== undefined) {\n html += `<span class=\"citation\">${quote.year}</span>`;\n }\n if (quote.tags !== undefined) {\n for (let i = 0; i < quote.tags.length; i++) {\n html += `<span class=\"tag\">${quote.tags[i]}</span>`;\n }\n }\n\n html += '</p>';\n\n setBackgroundColor();\n document.querySelector('#quote-box').innerHTML = html;\n}" ]
[ "0.76662225", "0.7648948", "0.76363146", "0.75433254", "0.7529829", "0.7508792", "0.74934775", "0.7486076", "0.7458956", "0.7439598", "0.743714", "0.7436879", "0.74291784", "0.74247473", "0.74184126", "0.74169546", "0.73882276", "0.7362797", "0.73611253", "0.7343178", "0.73221755", "0.7319266", "0.7318519", "0.72921216", "0.72888434", "0.7278278", "0.7270887", "0.727081", "0.7254001", "0.72314614", "0.72301877", "0.72166914", "0.72154146", "0.7198643", "0.7175405", "0.71667504", "0.7163029", "0.71524477", "0.7151729", "0.7147863", "0.7145323", "0.7142873", "0.71395737", "0.713904", "0.7136402", "0.7131631", "0.71252424", "0.7124484", "0.7121556", "0.7120082", "0.71179277", "0.71060324", "0.710528", "0.7103419", "0.71023643", "0.7086947", "0.7078097", "0.70719266", "0.70686054", "0.7067267", "0.70637053", "0.70611227", "0.7055088", "0.7052389", "0.7040082", "0.70360476", "0.7024472", "0.7022504", "0.7020291", "0.7020068", "0.7012892", "0.7011587", "0.7009896", "0.70053804", "0.6990151", "0.69872963", "0.69795656", "0.69747055", "0.69695026", "0.6968851", "0.6968604", "0.69685924", "0.6967071", "0.6946286", "0.6935395", "0.6933577", "0.69284546", "0.69185084", "0.69064665", "0.6905644", "0.6900067", "0.68992877", "0.6899039", "0.6894104", "0.6878056", "0.6877238", "0.68666553", "0.6864923", "0.68618685", "0.6847568" ]
0.749463
6
Javascript that deletes local storage data so that the name will be asked again if user wants to change it
function new_name(){ localStorage.removeItem('name'); location.reload(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeOldData() {\n\tlocalStorage.clear();\n}", "clear(){\r\n\r\n localStorage.removeItem(this.name)\r\n\r\n }", "function resetLocalStorage(){\n StorageArea.remove(['username', 'freq', 'name', 'gender'], function () {\n console.log('Removed username, name, gender and freq from storage.');\n });\n}", "function deleteUserData() {\r\n\tlocalStorage.clear();\r\n}", "function deleteData() {\n localStorage.clear();\n alert(\"Your user data has been deleted\");\n\t\n}", "function removeItemLocalStorage(name) {\n localStorage.removeItem(name);\n}", "function vaciar_local_storage(){\n localStorage.clear();\n}", "function removeFromLocalStorage(name) {\n locationData.forEach((location, i) => {\n if(location.name === name) {\n locationData.splice(i, 1);\n }\n });\n\n localStorage.setItem('locationData', JSON.stringify(locationData));\n}", "function delData() {\n document.getElementById(\"task_list\").innerHTML = \"\";\n localStorage.clear();\n\n}", "function vaciarLocalStorage() {\r\n localStorage.clear();\r\n}", "function effacer_local_storage() {\n\tlocalStorage.clear();\n\tdocument.getElementById('id_msg_localstorageeffacer').innerHTML=\"Toutes les observations ont été effacées de votre appareil.\";\n}", "function vaciarLocalStorage()\n{\n localStorage.clear();\n}", "function vaciarLocalStorage() {\n localStorage.clear();\n}", "function vaciarLocalStorage() {\n localStorage.clear();\n}", "function delete_save() {\n\tvamp_load_vals.forEach(\n\t\tfunction (val) {\n\t\t\tlocalStorage.removeItem(val);\n\t\t}\n\t);\n\t\t\n\t// Also delete special stuff:\n\tlocalStorage.removeItem('money_flag');\n\tlocalStorage.removeItem('energy_upgrade_flag');\n\tlocalStorage.removeItem('buffer');\n\t\n\tmessage('Your local save has been wiped clean.');\n}", "function clearFromLocalUsingBtn(){\n localStorage.clear()\n}", "lclear() {\n localStorage.clear()\n }", "function varciarLocalStorage() {\n localStorage.clear();\n}", "function vaciarLocalStorage(){\n localStorage.clear();\n}", "function vaciarLocalStorage() {\n localStorage.clear();\n}", "function vaciarLocalStorage() {\n localStorage.clear();\n}", "function removeUserData(name) {\n if (window.localStorage) { // eslint-disable-line\n window.localStorage.removeItem(name) // eslint-disable-line\n } else {\n Cookies.remove(name)\n }\n}", "function remove(){\n document.getElementById('textField').value = \"\";\n localStorage.removeItem('text');\n\n document.getElementById('emailField').value = \"\";\n localStorage.removeItem('email');\n\n\n document.getElementById('numField').value = \"\";\n localStorage.removeItem('num');\n\n\n document.getElementById('areaField').value = \"\";\n localStorage.removeItem('area');\n\n alert('The Form Local Storage Data Is Terminated !!!')\n }", "function clearLocalValue() {\n\twindow.localStorage.clear();\n}", "function eliminarLocalStorage(){\n\tlocalStorage.clear();\n}", "function vaciarLocalStorage(){\n localStorage.clear()\n}", "function vaciarCarritoLocalstorage() {\n localStorage.clear();\n}", "function remove(name) {\n\tif (typeof (Storage) !== \"undefined\") {\n\t\treturn localStorage.removeItem(name);\n\t} else {\n\t\twindow.alert('Please use a modern browser to properly view this template!');\n\t}\n}", "function deleteSave(){\n localStorage.removeItem(\"game\");\n location.reload();\n }", "vaciarLocalStorage(){\n localStorage.clear();\n }", "removeAll() {\n localStorage.clear()\n }", "function clearLocalData(){\n\t\tif(!localStorage.length){\n\t\t\talert(\"Sorry, there are no recipes to clear.\");\t\n\t\t} else {\n\t\t\t//Offer the user a confirmationBox\n var confirmListDelete = confirm(\"Are you sure you want to clear all of the recipe data?\");\n \n //If Confirmed, follow through.\n if(confirmListDelete === true) {\n \tlocalStorage.clear();\n\t \t\tvar pageContainer = $('mainContent');\n\t \t\tvar dataList = $('dataList');\n\t \t\t\tmainContent.removeChild(dataList); \t\n \talert(\"All recipes have been deleted!\");\n \t}\n\n\t\t};\n\t}", "function cleartasksfromlocalstorage(){\n localStorage.clear();\n}", "function cleared(){\r\n confirm('This action will going to clear your work exprience you stored; Do u want to continue?')\r\n \r\n localStorage.removeItem('wname');\r\n localStorage.removeItem('wdescription');\r\n localStorage.removeItem('wdateline');\r\n }", "function logOut(){\n localStorage.removeItem(\"name\");\n}", "function removeFromLocal(name, value) {\n let exists = localStorage.getItem(name);\n\n exists = exists ? JSON.parse(exists) : [];\n exists = exists.filter(item => item !== value);\n\n localStorage.setItem(name, JSON.stringify(exists));\n}", "function resetData() {\r\n if (window.localStorage.length == 0) { alert(\"You don't have any kittens to release. Press the 'Start Game' button to continue\") }\r\n else\r\n localStorage.clear();\r\n }", "function ClearLS(){\n localStorage.clear();\n}", "function clearLocalData(){\n\t\tif(!localStorage.length){\n\t\t\talert(\"Sorry, there are no recipes to clear.\");\n\t\t\tresetForm();\t\n\t\t} else {\n\t\t\t//Offer the user a confirmationBox\n var confirmListDelete = confirm(\"Are you sure you want to clear all of the recipe data?\");\n \n //If Confirmed, follow through.\n if(confirmListDelete === true) {\n \tlocalStorage.clear();\n\t\t\t\ttoggleDisplay('dataEntry'); \t\n \talert(\"All recipes have been deleted!\");\n \t};\n\n\t\t};\n\t}", "remover(id) {\n localStorage.removeItem(id)\n }", "function clear() {\n window.localStorage.clear();\n}", "function del (){\n\t\t//get the ID's of the inputs and remove the keys from local storage\n\tdocument.getElementById('heightType').value;\n\tlocalStorage.removeItem('key0');\n\tdocument.getElementById('Age').value;\n\tlocalStorage.removeItem('key1');\n\tdocument.getElementById('weightType').value;\n\tlocalStorage.removeItem('key2');\n\tlocation.reload();\n}", "function emptyLocalStorage() {\r\n localStorage.clear();\r\n}", "function clearLocalStorage() {\n\tlocalStorage.removeItem('userid');\n\tlocalStorage.removeItem('username');\n}", "rmLs() {\n for (var i = 0; i < arguments.length; i++) {\n localStorage.removeItem(arguments[i]);\n }\n }", "function remove(id) {\n if(localStorage[id]) {\n delete localStorage[id];\n }\n }", "function del(i){\nvar t = document.getElementById(\"game_\"+i);\nt.parentNode.remove(t);\nvar storage = window.localStorage;\nvar ii = storage.getItem(\"i\");\nii = ii - 1;\nstorage.removeItem(\"data_\"+i);\nstorage.setItem(\"i\",ii);\nlocation.reload(\"true\");\n}", "function clean_database() {\n localStorage.clear();\n}", "function clearTodoFromLocalStorage() {\n localStorage.clear();\n}", "function clearLS(){\n window.localStorage.removeItem(\"selection\");\n}", "function clearStorage(){\n localStorage.clear();\n}", "function clearData() {\n if (typeof(Storage) !== \"undefined\" && localStorage.getItem(\"jsdkvehicle\") !== null) {\n localStorage.removeItem(\"jsdkvehicle\");\n }\n if (document.cookie.split(';').filter((ind) => ind.trim().startsWith('jsdkvehicle=')).length) {\n document.cookie = 'jsdkvehicle=; path=/; expires=' + new Date(0).toUTCString() + ';';\n }\n}", "function clearLocalStorage (): void {\n window.localStorage.clear()\n}", "function deleteProductFromList(name) {\n\n var listArray = JSON.parse(window.localStorage.getItem(nickname));\n //Good old stream. Filter without that item and write new list.\n var newArray = listArray.filter(function (e) {\n return e.name !== name;\n });\n var JSONArray = JSON.stringify(newArray);\n window.localStorage.setItem(nickname, JSONArray);\n writeListToPage();\n\n\n}", "function ClearLocalStorage(){\n storageObject.clear();\n}", "function clearLocal() {\n localStorage.clear()\n location.reload()\n}", "_clear() {\n var local = this.localStorage(),\n itemRe = new RegExp(\"^\" + this.name + \"-\");\n\n // Remove id-tracking item (e.g., \"foo\").\n local.removeItem(this.name);\n\n // Match all data items (e.g., \"foo-ID\") and remove.\n for (var k in local) {\n if (itemRe.test(k)) {\n local.removeItem(k);\n }\n }\n\n this.records.length = 0;\n }", "clear() {\n return new Promise((resolve, reject) => {\n try {\n localStorage.removeItem(this.name);\n this.datastore = null;\n resolve(true);\n } catch (err) {\n reject(err);\n }\n });\n }", "clear() {\n return new Promise((resolve, reject) => {\n try {\n localStorage.removeItem(this.name);\n this.datastore = null;\n resolve(true);\n } catch (err) {\n reject(err);\n }\n });\n }", "function deleteLocal(key) {\n\t\t\tdelete localStorageObj[key];\n\t\t}", "function resetLocalStorage() {\n localStorage.clear();\n }", "function clearStrg() {\n console.log('about to clear local storage ');\n window.localStorage.clear();\n console.log('cleared');\n }", "function deleteSave() {\n\tlocalStorage.removeItem(\"ArkanusSave\");\n\tdisplayMessage(\"Save deleted.\", 3);\n}", "function clearStrg() {\n log('about to clear local storage');\n window.localStorage.clear();\n log('cleared');\n }", "function deleteLocalStorage(key) {\n localStorage.removeItem(key);\n}", "function h_resetLocalStorage()\n{\t\n\t// delete stored username\n\tlocalStorage.removeItem(\"playersName\");\n\t// delete setting for random Quotes\n\tlocalStorage.removeItem(\"enableRandomQuotes\");\n\t// delete highscore values\n\t// 30\n\tlocalStorage.removeItem(\"highscore_30\");\n\tlocalStorage.removeItem(\"player_30\");\n\tlocalStorage.removeItem(\"moneyPerDay_30\");\n\tlocalStorage.removeItem(\"date_30\");\n\t// 45\n\tlocalStorage.removeItem(\"highscore_45\");\n\tlocalStorage.removeItem(\"player_45\");\n\tlocalStorage.removeItem(\"moneyPerDay_45\");\n\tlocalStorage.removeItem(\"date_45\");\n\t// 90\n\tlocalStorage.removeItem(\"highscore_90\");\n\tlocalStorage.removeItem(\"player_90\");\n\tlocalStorage.removeItem(\"moneyPerDay_90\");\n\tlocalStorage.removeItem(\"date_90\");\n\t// 120\n\tlocalStorage.removeItem(\"highscore_120\");\n\tlocalStorage.removeItem(\"player_120\");\n\tlocalStorage.removeItem(\"moneyPerDay_120\");\n\tlocalStorage.removeItem(\"date_120\");\n\t\n\t// inform user\n\tvar n = noty({text: 'Deleted all game-related data from localStorage. Follow the white rabbit neo.'});\n\treturn;\n}", "function clearLocalStorage() {\r\n\tlocalStorage.removeItem('state');\r\n}", "function RemoveItem() {\n\tvar name = document.forms.ShoppingList.name.value;\n\tdocument.forms.ShoppingList.data.value = localStorage.removeItem(name);\n\tdoShowAll();\n}", "function RemoveItem() {\n\tvar name = document.forms.ShoppingList.name.value;\n\tdocument.forms.ShoppingList.data.value = localStorage.removeItem(name);\n\tdoShowAll();\n}", "nuke(key) {\n delete localStorage[key];\n chrome.storage.local.remove(key);\n if (chrome.storage.sync != null) {\n chrome.storage.sync.remove(key);\n }\n }", "function limpiar()\n{\n\n\t window.localStorage.removeItem(\"original\"); //borrar datos de localstorage\n\t \tdocument.getElementById('original').value = \"\"; //borrar contenido areatexto\n}", "function removeFromLocalStorage() {\n let storageArray = JSON.parse(localStorage.getItem(\"team\"));\n const updatedArray = storageArray.filter(\n (pokemon) => pokemon.id != $(this).attr(\"id\")\n );\n localStorage.setItem(\"team\", JSON.stringify(updatedArray));\n getDamageRelations()\n}", "function hard_reset() {\n localStorage.clear();\n}", "function clearEmployees() {\n localStorage.removeItem(\"employees\");\n location.reload();\n\n}", "function cleanLocalStorage() {\n if (chrome.storage) {\n chrome.storage.local.get(null, values => { for (const key of Object.keys(values)) { if (key.includes('PCM_')) chrome.storage.local.remove(key); } });\n chrome.storage.local.set({'PCM_running':false});\n }\n}", "function deleteStoredData() {\n\t\t// Detects if using cookies or local storage\n\t\tif (ie7) {\n\t\t\t// Grabs select elements on page to remove cookies\n\t\t\tvar selections = document.getElementsByTagName(\"select\");\n\n\t\t\t// Loops through select elements and deletes cookies named the same\n\t\t\tfor (selection in selections) {\n\t\t\t\tif (selections[selection].value != undefined) {\n\t\t\t\t\tDeleteCookie(selections[selection].name);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlocalStorage.clear();\n\t\t}\n}", "function clearScores(){\n localStorage.clear();\n}", "removeFromLocalStorage(target){\n let lists = this.getWordToLocalStorage()\n lists.forEach((value, index) => {\n if(target === value.english){\n lists.splice(index, 1)\n }\n })\n localStorage.setItem('todos', JSON.stringify(lists))\n }", "function clearUserData()\n {\n userData = userDataDefault;\n window.localStorage.setItem(localStorageName, JSON.stringify(userData));\n }", "function ClearStorage() { \n LSlength = localStorage.length;\n for (i=0; i<LSlength; i++) {\n element = localStorage.key(i);\n\t\t if (map.hasLayer(BeerList[element])) {map.removeLayer(BeerList[element]);}\n }\n localStorage.clear();\n LocalStorageList();\n\t\n \n }", "function clearStrg() {\n log('Clearing local storage');\n window.localStorage.clear();\n log('Local storage cleared.');\n}", "function deleteFavorites() {\n localStorage.clear();\n loadFavorites();\n}", "function delz (){\n\t//get the ID's of the inputs and remove the keys from local storage\n\tdocument.getElementById('StepsType').value;\n\tlocalStorage.removeItem('key3');\n\tdocument.getElementById('DistanceType').value;\n\tlocalStorage.removeItem('key4');\n\tdocument.getElementById('ActiveType').value;\n\tlocalStorage.removeItem('key5');\n\tdocument.getElementById('CaloriesType').value;\n\tlocalStorage.removeItem('key6');\n\tlocation.reload();\n}", "function eliminarTodo() {\n localStorage.clear(productosCarrito);\n productosCarrito=[];\n console.log(productosCarrito);\n actualizarElCarrito();\n}", "removeFromLocalStorage() {\n const songsInStorage = localStorage.getItem(\"Songs\");\n let currentArray = [];\n if (songsInStorage) {\n currentArray = JSON.parse(songsInStorage);\n const index = this.indexContainingID(currentArray, this.props.info.id);\n if (index > -1) {\n currentArray.splice(index, 1);\n }\n }\n localStorage.removeItem(\"Songs\");\n localStorage.setItem(\"Songs\", JSON.stringify(currentArray));\n }", "function removeSaved(selectElement) {\n //if 'id' is not there, use 'name'\n var key = $(selectElement).attr('id');\n key = key ? key : $(selectElement).attr('name');\n window.localStorage.removeItem(key);\n }", "function deleteUserDataFromSessionStorage() {\n localStorage.removeItem('userData');\n}", "function vaciarLocalStorage(){\n\t// Puede borrar otros tipos de Local Storage en el mismo dominio\n\t// localStorage.clear();\n\n\t// Borra el contenido solo de un valor llave en Local Storage\n\tlocalStorage.removeItem('carrito de cursos');\n}", "function clearData() {\n todos = [];\n localStorage.removeItem(LOCALSTORAGE_KEY);\n clearInputs();\n document.getElementById('todo-list').innerHTML = '';\n}", "function delsaveButton(){\r\n localStorage.removeItem(\"save\")\r\n location.reload();\r\n}", "function clearLocal() {\n if (localStorage.length === 0) {\n alert(\"No recipes to clear.\");\n } else {\n localStorage.clear();\n alert(\"All recipes have been deleted!\");\n window.location.reload();\n return false;\n }\n }", "function deleteitems(){\n localStorage.clear();\n location.reload();\n}", "function deleteLogin () {\n\tlocalStorage.removeItem(\"login\");\n}", "function removeItemFromLocalStorage (key){\n window.localStorage.removeItem(key);\n}", "function eliminar(nombre) {\n console.log(nombre)\n let datos = JSON.parse(localStorage.getItem('datos'));\n for(let i = 0; i < datos.length; i++) {\n if(datos[i].nombre == nombre) {\n datos.splice(i, 1);\n }\n }\n \n localStorage.setItem('datos', JSON.stringify(datos));\n IngresarDatos();\n}", "function clearLocalStorage() {\n $(cfg.select.classes.entry).remove();\n $.each(getEntries(), function (i, entry) {\n removeMarker(entry);\n });\n cfg.counter = 0;\n localStorage.clear();\n notifyUser('local storage cleared');\n }", "function clearData() {\n localStorage.clear();\n username.value = '';\n email.value = '';\n city.value = 'city';\n organisation.value = '';\n contact.value = '';\n message.value = '';\n}", "function clearStorage() {\n localStorage.clear(); \n listEl.hidden = true;\n}", "function clearStrg() {\n log('about to clear local storage');\n window.localStorage.clear(); // <-- Local storage!\n log('cleared');\n}", "function deleteData() {\n ref.unauth();\n $localStorage.$reset();\n lc.loginData = {};\n lc.message = 'google data deleted.';\n recipeService.loggedin.user = \"\";\n recipeService.loggedin.username = \"\";\n recipeService.loggedin.loggedin = false;\n lc.loginName = \"Login\";\n lc.loginHideGoogle = false;\n $(\"#loginDef\").css(\"display\", \"none\");\n lc.loginHideNative = true;\n }" ]
[ "0.79943126", "0.78904116", "0.7869835", "0.76576805", "0.76267236", "0.7625369", "0.7500418", "0.74822146", "0.74266934", "0.74051", "0.7399496", "0.7363018", "0.73619837", "0.73619837", "0.7350709", "0.7349437", "0.7339277", "0.73384535", "0.73374176", "0.73310184", "0.73310184", "0.73307174", "0.73133", "0.73050725", "0.73016316", "0.7299496", "0.7281239", "0.72327894", "0.72168344", "0.7211922", "0.72066194", "0.71938014", "0.7192198", "0.71848524", "0.71668726", "0.7158288", "0.71568555", "0.7150818", "0.7141653", "0.7129197", "0.7120097", "0.71087116", "0.71007794", "0.70750856", "0.7066668", "0.70622444", "0.7054482", "0.7049381", "0.70446527", "0.70384616", "0.70339996", "0.7033855", "0.703222", "0.7028913", "0.70273066", "0.7019033", "0.7018818", "0.70082915", "0.70082915", "0.6999835", "0.69952214", "0.6988473", "0.6982851", "0.69737685", "0.6959162", "0.69515294", "0.694964", "0.69470626", "0.69470626", "0.69453406", "0.6944881", "0.69299006", "0.69117194", "0.6911473", "0.6907171", "0.69015425", "0.689347", "0.6889562", "0.68825376", "0.6879558", "0.68773794", "0.68689966", "0.6866905", "0.68667305", "0.68641144", "0.68630064", "0.68606764", "0.6856589", "0.6853577", "0.6849615", "0.6846765", "0.68452257", "0.68422973", "0.6841425", "0.6831636", "0.682158", "0.6815183", "0.6813549", "0.6812496", "0.68109417" ]
0.7885775
2
private static vis: Visual;
function Visual(options) { console.log('Visual constructor', options); Visual.host = options.host; this.selectionIdBuilder = options.host.createSelectionIdBuilder(); this.target = options.element; this.selectionManager = options.host.createSelectionManager(); //Visual.vis = this; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Object_Visual(data) {\n Object_Visual.__super__.constructor.call(this);\n\n /**\n * Indiciates if the game object is visible on screen.\n * @property visible\n * @type boolean\n */\n this.visible = true;\n\n /**\n * The object's destination rectangle on screen.\n * @property dstRect\n * @type gs.Rect\n */\n this.dstRect = new Rect(data != null ? data.x : void 0, data != null ? data.y : void 0);\n\n /**\n * The object's origin.\n * @property origin\n * @type gs.Point\n */\n this.origin = new gs.Point(0, 0);\n\n /**\n * The object's offset.\n * @property offset\n * @type gs.Point\n */\n this.offset = new gs.Point(0, 0);\n\n /**\n * The object's anchor-point. For example: An anchor-point with 0,0 places the object with its top-left corner\n * at its position but with an 0.5, 0.5 anchor-point the object is placed with its center. An anchor-point of 1,1\n * places the object with its lower-right corner.\n * @property anchor\n * @type gs.Point\n */\n this.anchor = new gs.Point(0.0, 0.0);\n\n /**\n * The position anchor point. For example: An anchor-point with 0,0 places the object with its top-left corner\n * at its position but with an 0.5, 0.5 anchor-point the object will be placed with its center. An anchor-point of 1,1\n * will place the object with its lower-right corner. It has not effect on the object's rotation/zoom anchor. For that, take\n * a look at <b>anchor</b> property.\n *\n * @property positionAnchor\n * @type gs.Point\n */\n this.positionAnchor = new gs.Point(0, 0);\n\n /**\n * The object's zoom-setting for x and y axis. The default value is\n * { x: 1.0, y: 1.0 }\n * @property zoom\n * @type gs.Point\n */\n this.zoom = (data != null ? data.zoom : void 0) || new gs.Point(1.0, 1.0);\n\n /**\n * The object's z-index controls rendering-order/image-overlapping. An object with a smaller z-index is rendered\n * before an object with a larger index. For example: To make sure a game object is always on top of the screen, it\n * should have the largest z-index of all game objects.\n * @property zIndex\n * @type number\n */\n this.zIndex = 700;\n\n /**\n * The object's blend mode controls how the blending of the object's visual representation is calculated.\n * @property blendMode\n * @type number\n * @default gs.BlendMode.NORMAL\n */\n this.blendMode = gs.BlendMode.NORMAL;\n\n /**\n * The object's viewport.\n * @property viewport\n * @type gs.Viewport\n */\n this.viewport = Graphics.viewport;\n\n /**\n * The object's motion-blur settings.\n * @property motionBlur\n * @type gs.MotionBlur\n */\n this.motionBlur = new gs.MotionBlur();\n\n /**\n * Contains different kinds of shader effects which can be activated for the object.\n * @property effects\n * @type gs.EffectCollection\n */\n this.effects = new gs.EffectCollection();\n\n /**\n * The object's opacity to control transparency. For example: 0 = Transparent, 255 = Opaque, 128 = Semi-Transparent.\n * @property opacity\n * @type number\n */\n this.opacity = 255;\n }", "function Component_Visual() {\n Component_Visual.__super__.constructor.apply(this, arguments);\n }", "addDataVisuals () {\n }", "function Visuals(posX, posY, valR, valG, valB) {\r\n this.posX = posX;\r\n this.posY = posY;\r\n this.valR = valR;\r\n this.valG = valG;\r\n this.valB = valB;\r\n this.size = 100;\r\n\r\n this.showMe = function(keycode) {\r\n noStroke();\r\n fill(this.valR, this.valG, this.valB);\r\n ellipse(this.posX/200*windowWidth+keycode+100, this.posY/200*windowHeight-keycode*2+100, this.size*keycode/100, this.size*keycode/100);\r\n }\r\n\r\n this.showOther = function(posX, posY, valR, valG, valB, keycode) {\r\n noStroke();\r\n fill(valR, valG, valB);\r\n ellipse(posX/200*windowWidth+keycode+100, posY/200*windowHeight-keycode*2+100, this.size*keycode/100, this.size*keycode/100);\r\n }\r\n}", "static get visible() {}", "function VisualImmediate( area ) {\n Visual.call( this, area );\n this.init_events();\n }", "function drawVisualization() {\n // Create and populate a data table.\n formArrayFromObj(satData);\n\n\n // specify options\n var options = {\n width: '600px',\n height: '600px',\n style: 'dot',\n showPerspective: true,\n showGrid: true,\n showShadow: false,\n keepAspectRatio: true,\n verticalRatio: 0.5,\n tooltip: getName\n };\n\n // Instantiate our graph object.\n var container = document.getElementById('myGraph');\n graph = new vis.Graph3d(container, data, options);\n\n}", "function viz(id, width, height, pointerClickOverload, type, p){\n\t\n\t//ES 2016-08-16 (b_cmp_test_1): global variable for number of indentations\n\tthis._numIndents = 1;\n\t//ES 2016-09-11 (b_debugger): assign type of visualizer\n\tthis._type = type;\n\t//setup static variables\n\t//specify default font size\n\tviz.defFontSize = 14;\n\t//initialize symbol dialog instance to null\n\tviz.symbDlgInst = null;\n\t//create graph and save it's reference\n\t//ES 2016-09-11 (b_debugger): convert global variable to data field, since now we\n\t//\thave several visualizers (i.e. for debugging, for application ...)\n\tthis._graph = new joint.dia.Graph;\n\n\t//ES 2016-08-28 (b_log_cond_test): assign parser instance\n\tthis._parser = p;\n\n\t//specify class variables\n\t//assign dimensions\n\tthis._width = width;\n\tthis._height = height;\n\t//bookkeep container id\n\tthis._id = id;\n\t//ES 2017-11-09 (b_01): moved out statement from IF condition below, since it can be used for\n\t//\tall visualization platform types\n\tthis._postponeConnectionTasks = [];\n\t//ES 2017-11-09 (b_01): if drawing platform relies on Canvas\n\tif( viz.__visPlatformType == VIZ_PLATFORM.VIZ__CANVAS ) {\n\t\t//create canvas object (this._vp will now be Canvas context, which allows to perform pixel drawing operations)\n\t\tthis.createCanvasObj(type, id, width, height);\n\t\t//assign instance of visualizer\n\t\tvar tmpVizThis = this;\n\t\t//get exp id of DIV (for jquery) that will surrounds canvas map\n\t\tvar tmpCnvMapDivId = \"#\" + this.getCanvasElemInfo(type)[1];\n\t\t//establish mouse events: down, move, up, see: https://stackoverflow.com/a/6042235\n\t\t//create mouse-down event\n\t\t$(tmpCnvMapDivId).on('mousedown', function(evt) {\n\t\t\t//get cursor coordinates within boundaries of canvas map DIV\n\t\t\tvar tmpXY = tmpVizThis._cnvMap.getCanvasMapXY(evt, tmpCnvMapDivId);\n\t\t\t//try to get canvas element that was clicked\n\t\t\tvar tmpSelElem = tmpVizThis.getSelectedCanvasElement(\n\t\t\t\ttmpXY.x, tmpXY.y, type\n\t\t\t);\n\t\t\t//if selected item was found\n\t\t\tif( tmpSelElem != null ) {\n\t\t\t\t//compose abbreviated label for selected item\n\t\t\t\tvar tmpAbbrLabel = \"\";\n\t\t\t\t//if selected item is block\n\t\t\t\tif( tmpSelElem.obj != null && tmpSelElem.obj.getTypeName() == RES_ENT_TYPE.BLOCK ) {\n\t\t\t\t\t//assign prefix 'b_'\n\t\t\t\t\ttmpAbbrLabel = \"b_\";\n\t\t\t\t//else, if selected item is command\n\t\t\t\t} else if( tmpSelElem.obj != null && tmpSelElem.obj.getTypeName() == RES_ENT_TYPE.COMMAND ) {\n\t\t\t\t\t//assign prefix 'c_' followed by block id and '_'\n\t\t\t\t\ttmpAbbrLabel = \"c_\" + tmpSelElem.obj._blk._id + \"_\";\n\t\t\t\t//else, application view\n\t\t\t\t} else {\n\t\t\t\t\t//assign prefix 'a_' for application view\n\t\t\t\t\ttmpAbbrLabel = \"a_\";\n\t\t\t\t}\t//end if selected item is block\n\t\t\t\t//complete abbreviated label with item (block, command, ...) id\n\t\t\t\ttmpAbbrLabel += \"\" + (tmpSelElem.obj != null ? tmpSelElem.obj._id : tmpSelElem._id);\n\t\t\t\t//create DIV and add it to body at the clicked position\n\t\t\t\t$(tmpCnvMapDivId).append(\n\t\t\t\t\t\"<div id='\" + viz.__canvasSelectedObjDiv + \"' style='\" + \n\t\t\t\t\t\t\"position: absolute; \" + \n\t\t\t\t\t\t\"height: \" + (tmpSelElem.height + 3) + \"px; \" +\n\t\t\t\t\t\t\"width: \" + tmpSelElem.width + \"px; \" +\n\t\t\t\t\t\t\"top: \" + tmpSelElem.y + \"px; \" +\n\t\t\t\t\t\t\"left: \" + tmpSelElem.x + \"px; \" + \n\t\t\t\t\t\t\"background: orange; \" + \n\t\t\t\t\t\t\"opacity: 0.5;\" +\n\t\t\t\t\t\"' nc-sel-item='\" + tmpAbbrLabel + \n\t\t\t\t\t\"' nc-off-x='\" + (tmpSelElem.x - tmpXY.x) +\n\t\t\t\t\t\"' nc-off-y='\" + (tmpSelElem.y - tmpXY.y) +\n\t\t\t\t\t\"'></div>\"\n\t\t\t\t);\n\t\t\t}\t//end if selected item was found\n\t\t});\t//end mouse-down handler\n\t\t//create mouse-move event\n\t\t$(tmpCnvMapDivId).on('mousemove', function(evt) {\n\t\t\t//get cursor coordinates within boundaries of canvas map DIV\n\t\t\tvar tmpXY = tmpVizThis._cnvMap.getCanvasMapXY(evt, tmpCnvMapDivId);\n\t\t\t//try to locate bounding DIV that gets created by mousedown event\n\t\t\tvar tmpBoundDiv = $(\"#\" + viz.__canvasSelectedObjDiv);\n\t\t\t//if bounding DIV was found\n\t\t\tif( tmpBoundDiv.length > 0 ) {\n\t\t\t\t//compute Top-Left position of following div\n\t\t\t\tvar tmpDivTL = {\n\t\t\t\t\t\"y\": tmpXY.y + parseInt($(tmpBoundDiv).attr(\"nc-off-y\")),\n\t\t\t\t\t\"x\": tmpXY.x + parseInt($(tmpBoundDiv).attr(\"nc-off-x\"))\n\t\t\t\t};\n\t\t\t\t//get canvas element being reprsented by following div\n\t\t\t\tvar tmpSelCnvElem = tmpVizThis.getCnvElemFromFollowingDiv(tmpBoundDiv);\n\t\t\t\t//init parent instance for this canvas element\n\t\t\t\tvar tmpParent = null;\n\t\t\t\t//if this element is command\n\t\t\t\tif( tmpSelCnvElem.obj != null && tmpSelCnvElem.obj.getTypeName() == RES_ENT_TYPE.COMMAND ) {\n\t\t\t\t\t//parent of this command will block\n\t\t\t\t\ttmpParent = tmpSelCnvElem.obj._blk._canvasElemRef;\n\t\t\t\t//else, if this element is block\n\t\t\t\t} else if( tmpSelCnvElem.obj != null && tmpSelCnvElem.obj.getTypeName() == RES_ENT_TYPE.BLOCK ) {\n\t\t\t\t\t//parent of this block will be scope\n\t\t\t\t\ttmpParent = tmpSelCnvElem.obj._owner._canvasElemRef;\n\t\t\t\t}\t//end if this element is command\n\t\t\t\t//if there is parent and this element goes outisde of its borders\n\t\t\t\tif( tmpParent != null && \n\t\t\t\t\t(\n\t\t\t\t\t\ttmpParent.x > tmpDivTL.x || \n\t\t\t\t\t\ttmpParent.y > tmpDivTL.y || \n\t\t\t\t\t\t(tmpParent.x + tmpParent.width) < (tmpDivTL.x + tmpSelCnvElem.width) ||\n\t\t\t\t\t\t(tmpParent.y + tmpParent.height) < (tmpDivTL.y + tmpSelCnvElem.height)\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\t//quit\n\t\t\t\t\treturn;\n\t\t\t\t}\t//end if there is parent and this element goes outside of its borders\n\t\t\t\t//move DIV after cursor\n\t\t\t\t$(tmpBoundDiv).css({\n\t\t\t\t\ttop: tmpDivTL.y, \n\t\t\t\t\tleft: tmpDivTL.x\n\t\t\t\t});\n\t\t\t}\t//end if bounding DIV was found\n\t\t});\t//end mouse-move handler\n\t\t//create mouse-up event\n\t\t$(tmpCnvMapDivId).on('mouseup', function(evt) {\n\t\t\t//try to locate bounding DIV that gets created by mousedown event\n\t\t\tvar tmpBoundDiv = $(\"#\" + viz.__canvasSelectedObjDiv);\n\t\t\t//if bounding DIV was found\n\t\t\tif( tmpBoundDiv.length > 0 ) {\n\t\t\t\t//get canvas element being reprsented by following div\n\t\t\t\tvar tmpSelCnvElem = tmpVizThis.getCnvElemFromFollowingDiv(tmpBoundDiv);\n\t\t\t\t//get new position of selected element\n\t\t\t\tvar tmpNewPosX = parseInt($(tmpBoundDiv).css(\"left\").split(\"px\")[0]);\n\t\t\t\tvar tmpNewPosY = parseInt($(tmpBoundDiv).css(\"top\").split(\"px\")[0]);\n\t\t\t\t//compute displacement in X and Y direction\n\t\t\t\tvar dispX = tmpNewPosX - tmpSelCnvElem.x;\n\t\t\t\tvar dispY = tmpNewPosY - tmpSelCnvElem.y;\n\t\t\t\t//if element was moved\n\t\t\t\tif( dispX != 0 || dispY != 0 ) {\n\t\t\t\t\t//re-draw moved element on canvas map\n\t\t\t\t\ttmpVizThis._cnvMap.transformCanvasElement(\n\t\t\t\t\t\t//moving canvas element\n\t\t\t\t\t\ttmpSelCnvElem,\n\t\t\t\t\t\t//type of transformation - translate\n\t\t\t\t\t\tCANVAS_TRANSFORM_OPS_TYPE.TRANSLATE,\n\t\t\t\t\t\t//associative set with X and Y displacement\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"x\": dispX,\n\t\t\t\t\t\t\t\"y\": dispY\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t//else, element was clicked (not moved)\n\t\t\t\t} else {\n\t\t\t\t\t//if click handler is given by caller\n\t\t\t\t\tif( typeof pointerClickOverload != \"undefined\" ) {\n\t\t\t\t\t\t//invoke this handler\n\t\t\t\t\t\tpointerClickOverload(\n\t\t\t\t\t\t\t//canvas element that was clicked\n\t\t\t\t\t\t\ttmpSelCnvElem,\n\t\t\t\t\t\t\t//ignore this attribute (used solely by JointJS)\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t//position\n\t\t\t\t\t\t\ttmpNewPosX, tmpNewPosY\n\t\t\t\t\t\t);\n\t\t\t\t\t//else, use default click handler\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if symbol dialog already exists\n\t\t\t\t\t\tif( viz.symbDlgInst !== null ) {\n\t\t\t\t\t\t\t//remove this element\n\t\t\t\t\t\t\t//\tsee: https://stackoverflow.com/a/18120786\n\t\t\t\t\t\t\t$(viz.symbDlgInst).remove();\n\t\t\t\t\t\t}\t//end if symbol dialog already exists\n\t\t\t\t\t\t//if currently selected entry is either command or scope\n\t\t\t\t\t\tif( tmpSelCnvElem._type == RES_ENT_TYPE.COMMAND ||\n\t\t\t\t\t\t\ttmpSelCnvElem._type == RES_ENT_TYPE.SCOPE ) {\n\t\t\t\t\t\t\t//split symbol list into rows to be displayed inside dialog\n\t\t\t\t\t\t\t//\tand also measure size of resulting dialog\n\t\t\t\t\t\t\tvar tmpDlgInfo = viz.splitTextIntoRowsForSymbolDlg(\n\t\t\t\t\t\t\t\t//array of symbols\n\t\t\t\t\t\t\t\ttmpSelCnvElem._symbArr,\n\t\t\t\t\t\t\t\t//max number of items per row\n\t\t\t\t\t\t\t\t5\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t//create symbol dialog with specified shape and text content\n\t\t\t\t\t\t\tviz.symbDlgInst = viz.createSymbDlg(\n\t\t\t\t\t\t\t\ttmpNewPosX, tmpNewPosY, \n\t\t\t\t\t\t\t\ttmpDlgInfo.width, tmpDlgInfo.height, \n\t\t\t\t\t\t\t\ttmpDlgInfo.text\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t//add symbol dialog to canvas map\n\t\t\t\t\t\t\t$(tmpCnvMapDivId).append(viz.symbDlgInst);\n\t\t\t\t\t\t}\t//end if currently selected entry is either command or scope\n\t\t\t\t\t}\t//end if click handler is given by caller\n\t\t\t\t}\t//end if element was moved\n\t\t\t\t//remove DIV\n\t\t\t\t$(tmpBoundDiv).remove();\n\t\t\t}\t//end if bounding DIV was found\n\t\t});\t//end mouse-up handler\n\t//ES 2017-11-09 (b_01): else, drawing platform depends on JointJS (SVG)\n\t} else {\n\t\t//create JointJS viewport\n\t\tvar viewport = new joint.dia.Paper({\n\t\t\tel: $(\"#\" + this._id),\n\t\t\twidth: this._width,\n\t\t\theight: this._height,\n\t\t\tmodel: this._graph,\n\t\t\tgridsize: 10,\n\t\t});\n\t\t//ES 2016-09-11 (b_debugger): assign viewport to object data field '_vp'\n\t\tthis._vp = viewport;\n\t\t//create collection of postponed 'tasks' for connecting blocks\n\t\t//ES 2017-11-09 (b_01): move statement out of this condition, since it can be used for both\n\t\t//\tvisualization platform types\n\t\t//this._postponeConnectionTasks = [];\n\t\t//attach mouse-move event to show/hide symbolDlg\n\t\tviewport.on('cell:pointerclick', \n\t\t\tfunction(cellView, evt, x, y) {\n\t\t\t\tif( typeof pointerClickOverload == \"undefined\" ){\n\t\t\t\t\t//if symbol dialog already exists\n\t\t\t\t\tif( viz.symbDlgInst !== null ){\n\t\t\t\t\t\t//remove this element\n\t\t\t\t\t\tviz.symbDlgInst.remove();\n\t\t\t\t\t}\n\t\t\t\t\t//check that currently hovered entity is a command or scope\n\t\t\t\t\tif( cellView.model.attributes.type == \"command\" ||\n\t\t\t\t\t\tcellView.model.attributes.type == \"scp\" ){\n\n\t\t\t\t\t\t//get this command's chain of definition symbols\n\t\t\t\t\t\tvar dChainTxt = cellView.model.attributes.defSymbChain;\n\t\t\t\t\t\t//measure size of symbol info text to be displayed\n\t\t\t\t\t\tvar symbInfoTextDims = viz.measureTextDim(dChainTxt);\n\t\t\t\t\t\t//create globally accessible variable in VIZ scope for symbol dialog\n\t\t\t\t\t\t//initially it will be hidden\n\t\t\t\t\t\tviz.symbDlgInst = viz.createSymbDlg(\n\n\t\t\t\t\t\t\t//set position of symbol dialog\n\t\t\t\t\t\t\tx, y, \n\n\t\t\t\t\t\t\t//set dimensions for the symbol dialog\n\t\t\t\t\t\t\tsymbInfoTextDims.width + 40, symbInfoTextDims.height + 40,\n\n\t\t\t\t\t\t\t//specify symbols\n\t\t\t\t\t\t\tdChainTxt\n\t\t\t\t\t\t);\n\t\t\t\t\t\t//draw symbolic dialog\n\t\t\t\t\t\tviz.__visualizerInstanceDbg._graph.addCells([viz.symbDlgInst]);\n\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpointerClickOverload(cellView, evt, x, y);\n\t\t\t\t} \n\t\t\t}\n\t\t);\n\t}\t//ES 2017-11-09 (b_01): end if drawing platform relies on Canvas\n\t//create drawing stack\n\t//each object (e.g. scope, block, command or value) should be identified\n\t//using hashmap that contains following information:\n\t//\tx, y - top left corner of object (usually it is a rectangle)\n\t//\tw, h - dimension of object (width or height)\n\t//\tlevel - depth-level of node inside graph (start is at 0th level)\n\tthis._drawStack = {\n\t\tscope: [],\t//array of scopes in the order of drawing (i.e. start drawing \n\t\t\t\t\t//from 0th element and proceed to the end of array)\n\t\tblock: [],\t\t//series of blocks to draw\n\t\tcommand: [],\t//series of commands to draw\n\t\tcons: [],\t\t//series of connections (arrows) to render\n\t\tvalue: []\t\t//series of symbols to draw (subject to change...)\n\n\t\t//ES 2016-08-13 (b_cmp_test_1): series of Execution Command Stack (ECS) entries\n\t\t,ecsEntries: []\n\t};\n\t//ES 2016-09-04 (b_debugger): create collection that maps command id to framework entity\n\t//ES 2017-12-11 (b_01): renamed variable to avoid confusion, since this variable\n\t//\tis used by other visualization frameworks (a.k.a. Canvas)\n\tthis._cmdToFwkEnt = {};\n\t//collection of functions drawing commands (each has specific number of arguments)\n\tthis.cmdDrawFuncs = {};\t//key: (int) => number of args, value: (function) draw cmd\n}", "function setVisual () {\n window.cancelAnimationFrame(drawVisual)\n visualize()\n }", "init() {\n // Define this vis\n const vis = this;\n\n // Init topCounter from target\n vis.topCounterEl = d3.select(`#${vis.target}`);\n\n // Call wrangle\n vis.wrangle();\n }", "graphicVisibility(definitionName, projectData) {\n\n\t}", "static get is() { return 'bv-image-viewer'; }", "function initVis() {\n var eventHandlers = {};\n\n var mapSelectionChanged = function () {\n queue().defer(updateChildViews);\n };\n\n var activitySelectionChanged = function () {\n queue().defer(updateActivitiesVis);\n };\n\n var activitiesParkSelectionChanged = function (_newSelection)\n {\n ActivitiesPark = _newSelection;\n queue().defer(selectedParkChanged)\n }\n\n mapVis = new MapVis(\"#parks\", usStateData, dataloaded, allData, mapSelectionChanged);\n mapVis.updateVis();\n\n barVis = new barVis(\"#barVis\", allData, activitiesParkSelectionChanged, mapSelectionChanged,reset);\n BubbleVis = new BubbleVis(\"#bubble\", allData, activitySelectionChanged);\n // listVis = new listVis(\"#title\", allData, dataloaded, eventHandlers);\n infoVis = new InfoVis(\"#information\", dataloaded, mapSelectionChanged, eventHandlers);\n ActivitiesVis = new ActivitiesVis(\"#activityChart\",allData,activitiesParkSelectionChanged);\n }", "static set visible(value) {}", "function makeVis() {\n ScatterPlot = new ScatterPlot(\"scatter_plot\", all_data, lottery_data, round_1_data, round_2_data);\n Slider = new Slider('slider', all_data);\n\n}", "function LGraphGUIPanel()\r\n\t{\r\n\t\tthis.addOutput(\"pos\",\"vec2\");\r\n\t\tthis.addOutput(\"enabled\",\"boolean\");\r\n\t\tthis.properties = { enabled: true, draggable: false, title: \"\", color: [0.1,0.1,0.1], opacity: 0.7, titlecolor: [0,0,0], position: [10,10], size: [300,200], rounding: 8, corner: LiteGraph.CORNER_TOP_LEFT };\r\n\t\tthis._area = vec4.create();\r\n\t\tthis._color = vec4.create();\r\n\t\tthis._titlecolor = vec4.create();\r\n\t\tthis._offset = [0,0];\r\n\t}", "exportVisualModel() {\n let iv = this.i.u();\n return (iv);\n }", "function drawVisualization() {\n // Create and populate a data table.\n var data = new vis.DataSet();\n\n $.getJSON('/rawstars', function(stars) { \n for (i in stars) {\n var x = stars[i].x,\n y = stars[i].y,\n z = stars[i].z;\n starMemos[getKey(stars[i])] = stars[i];\n data.add({\n x: x,\n y: y,\n z: z,\n style: stars[i].lum\n });\n }\n\n // specify options\n var options = {\n width: '100%',\n height: '100%',\n style: 'dot-color',\n showPerspective: true,\n showGrid: true,\n showShadow: false,\n keepAspectRatio: true,\n verticalRatio: 0.5,\n legendLabel: \"Luminosity\",\n tooltip: function(star) {return generateTooltip(star);}\n };\n\n // create a graph3d\n var container = document.getElementById('mygraph');\n graph3d = new vis.Graph3d(container, data, options);\n });\n}", "function setUpVisual() {\n\n var container = d3.select('#visual').node().getBoundingClientRect();\n\n var margin = { top: 30 , right: 30 , bottom: 30 , left: 30 },\n width = container.width - margin.left - margin.right,\n height = container.height - margin.top - margin.bottom;\n\n var svg = d3.select('#visual')\n .append('svg')\n .attr('width', '100%')\n .attr('height', '100%')\n .attr('viewBox', '0 0 ' + container.width + ' ' + container.height)\n .append('g').attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')') // to translate\n .append('g').attr('class', 'chart-g'); // to base zoom on a 0, 0 coordinate system\n\n // Add to global\n vis.dims = { width: width, height: height, margin: margin };\n vis.elements = { svg: svg };\n\n} // setUpVisual()", "addVisual (options) {\n var type = pop(options, 'type');\n var VisualClass = visuals.types[type];\n if (!VisualClass)\n warn(`Cannot add visual \"${type}\", not available`);\n else\n return new VisualClass(this.element, options, this);\n }", "get isVisible () {\n return this._visible;\n }", "get graphic() { return this._graphic; }", "redondearVis(vis) {\n return vis / 1000;\n }", "initVis() {\n let vis = this;\n\n // areas\n vis.width = vis.config.containerWidth;\n vis.height = vis.config.containerHeight;\n vis.center = { x: 312, y: 312 };\n vis.svg = d3\n .select(vis.config.parentElement)\n .append(\"svg\")\n .attr(\"class\", \"chart\")\n .attr(\"width\", vis.config.containerWidth)\n .attr(\"height\", vis.config.containerHeight)\n .append(\"g\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y})`);\n\n // scales\n vis.radiusScale = d3\n .scalePow()\n .exponent(0.5)\n .range([15, 95])\n .domain([\n d3.min(vis.data, (d) => d.total_emissions),\n d3.max(vis.data, (d) => d.total_emissions),\n ]);\n vis.colorScale = d3\n .scaleOrdinal()\n .domain([\n \"Farm\",\n \"Land use change\",\n \"Transport\",\n \"Retail\",\n \"Packaging\",\n \"Animal feed\",\n \"Processing\",\n ])\n .range([\"#e1874b\", \"#1f78b4\", \"#bfc27d\", \"#446276\", \"#fccde5\", \"#b4de68\", \"#668fff\"]);\n // simulation\n vis.sim = d3\n .forceSimulation()\n .force(\"x\", d3.forceX(0).strength(0.0001))\n .force(\"y\", d3.forceY(0).strength(0.0001))\n .force(\n \"collision\",\n d3.forceCollide((d) => vis.radiusScale(d.total_emissions) + 1)\n );\n // defs\n var defs = vis.svg.append(\"defs\");\n vis.drawIcon = function (id) {\n defs.append(\"pattern\")\n .attr(\"id\", id)\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"patternContentUnits\", \"objectBoundingBox\")\n .append(\"image\")\n .attr(\"height\", 1)\n .attr(\"width\", 1)\n .attr(\"preserveAspectRatio\", \"none\")\n .attr(\"xlink:href\", `icon/${id}.png`);\n return `url(#${id})`;\n };\n\n // defs\n (vis.glow = vis.svg.append(\"defs\").append(\"filter\").attr(\"id\", \"glow\")),\n vis.glow\n .append(\"feGaussianBlur\")\n .attr(\"stdDeviation\", \"0.5\")\n .attr(\"result\", \"coloredBlur\")\n .append(\"feMerge\");\n (vis.feMerge = vis.glow.append(\"feMerge\")),\n vis.feMerge.append(\"feMergeNode\").attr(\"in\", \"coloredBlur\"),\n vis.feMerge.append(\"feMergeNode\").attr(\"in\", \"SourceGraphic\");\n\n // background circle\n vis.svg\n .append(\"circle\")\n .transition()\n .duration(200)\n .attr(\"r\", 310)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\");\n\n // color legend\n vis.legend_color = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.height / 2},${-vis.height / 2 + 20} )`);\n vis.legend_color\n .append(\"text\")\n .text(\"Most Emission Stage\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 10)`);\n const stages = [\n \"farm\",\n \"land_use_change\",\n \"animal_feed\",\n \"processing\",\n \"packaging\",\n \"transport\",\n \"retail\",\n ];\n const stages_names = [\n \"Farm\",\n \"Land use change\",\n \"Animal feed\",\n \"Processing\",\n \"Packaging\",\n \"Transport\",\n \"Retail\",\n ];\n for (let i = 0; i < stages.length; i++) {\n vis.legend_color\n .append(\"rect\")\n .attr(\"width\", 15)\n .attr(\"height\", 15)\n .attr(\"fill\", vis.colorScale(stages_names[i]))\n .attr(\"opacity\", 0.6)\n .attr(\"transform\", `translate(0, ${20 + i * 20})`);\n\n vis.legend_color\n .append(\"text\")\n .text(stages_names[i])\n .attr(\"transform\", `translate(18, ${27 + i * 20})`)\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"13px\")\n .attr(\"alignment-baseline\", \"central\");\n }\n\n // size legend\n vis.legend_size = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y - 200})`);\n vis.legend_size\n .append(\"text\")\n .text(\"Total Emission\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 10)`);\n vis.legend_size\n .append(\"text\")\n .text(\"(kg CO₂ / kg product)\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 35)`);\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(30))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${vis.radiusScale(30) + 55})`\n );\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(10))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${\n vis.radiusScale(30) + vis.radiusScale(2) + 55\n })`\n );\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(1))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${\n vis.radiusScale(30) + vis.radiusScale(12.5) + 55\n })`\n );\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", 55)\n .attr(\"y2\", 55)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"30\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"transform\", `translate(${vis.radiusScale(30) + 85}, 65)`);\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", vis.radiusScale(30) + 35.7)\n .attr(\"y2\", vis.radiusScale(30) + 35.7)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"10\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) + 85}, ${vis.radiusScale(30) + 45.7})`\n );\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", vis.radiusScale(30) + 82.8)\n .attr(\"y2\", vis.radiusScale(30) + 82.8)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"1\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) + 93}, ${vis.radiusScale(30) + 92.8})`\n );\n\n // icon legend\n vis.legend_icon = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y - 280})`);\n vis.legend_icon\n .append(\"circle\")\n .attr(\"fill\", vis.drawIcon(\"Icon\"))\n .attr(\"r\", 20)\n .attr(\"stroke\", \"#5a5a5a\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\"transform\", \"translate(20,20)\");\n vis.legend_icon\n .append(\"text\")\n .text(\"icon indicates the\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"transform\", \"translate(45, 40)\");\n vis.legend_icon\n .append(\"text\")\n .text(\"emission of CO₂ > 1.5 kg\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"transform\", \"translate(0, 60)\");\n vis.svg\n .append(\"g\")\n .attr(\"transform\", `translate(500, ${vis.center.y - 1000})`)\n .append(\"line\")\n .attr(\"x1\", 0)\n .attr(\"x2\", 0)\n .attr(\"y1\", 0)\n .attr(\"y2\", 1100)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n\n // page button\n vis.button = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${-vis.center.x + 80}, ${vis.center.y - 6})`);\n vis.button\n .append(\"circle\")\n .attr(\"class\", \"pagebtn\")\n .classed(\"one\", true)\n .attr(\"r\", 30)\n .attr(\"stroke\", \"#5a5a5a\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\"fill\", vis.drawIcon(\"One\"))\n .on(\"click\", function (event) {\n let page = 1;\n if (d3.select(this).classed(\"two\")) {\n page = 2;\n }\n if (d3.select(this).classed(\"three\")) {\n page = 3;\n }\n switch (page) {\n case 1:\n d3.select(this)\n .classed(\"one\", false)\n .classed(\"two\", true)\n .attr(\"fill\", vis.drawIcon(\"Two\"));\n vis.dispatcher.call(\"toP2\", event);\n break;\n case 2:\n d3.select(this)\n .classed(\"two\", false)\n .classed(\"three\", true)\n .attr(\"fill\", vis.drawIcon(\"Three\"));\n vis.dispatcher.call(\"toP3\", event);\n break;\n case 3:\n d3.select(this)\n .classed(\"three\", false)\n .classed(\"one\", true)\n .attr(\"fill\", vis.drawIcon(\"One\"));\n vis.dispatcher.call(\"toP1\", event);\n break;\n }\n });\n vis.buttonlabel = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${-vis.center.x + 120}, ${vis.center.y})`);\n vis.buttonlabel\n .append(\"text\")\n .text(\"Switch Page\")\n .attr(\"font-size\", \"20px\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"alignment-baseline\", \"central\");\n d3.select(\".page\").append(\"div\").attr(\"id\", \"tooltip1\");\n }", "function StaticSemantics() {\n }", "updateVisualScope (dim, vis) {\r\n var me = this;\r\n\r\n me.cells.selection\r\n .attr(dim.pos, function (d) { return (vis[d[dim.self]] ? me.cells.attrs[dim.pos](d) : 0); })\r\n .attr(dim.size, function (d) { return (vis[d[dim.self]] ? me.cells.attrs[dim.size]() : 0); });\r\n if (dim.annotated) {\r\n dim.cellsSide.selection\r\n .attr(dim.pos, function (d) { return (vis[d.key] ? dim.cellsSide.attrs[dim.pos](d) : 0); })\r\n .attr(dim.size, function (d) { return (vis[d.key] ? dim.cellsSide.attrs[dim.size]() : 0); });\r\n }\r\n }", "handleVisualize() {\n const { visualizeHandler } = this.props;\n visualizeHandler();\n }", "constructor(guiSys: GuiSys) {\n super();\n this.view = new UIView(guiSys);\n\n Object.defineProperty(\n this.props,\n 'pointerEvents',\n ({\n set: value => {\n if (value === null) {\n value = 'auto';\n }\n this.view.setPointerEvents(value);\n },\n }: Object),\n );\n Object.defineProperty(\n this.props,\n 'hitSlop',\n ({\n set: value => {\n if (value === null) {\n value = 0;\n }\n if (typeof value === 'number') {\n this.view.setHitSlop(value, value, value, value);\n } else {\n this.view.setHitSlop(\n value.left,\n value.top,\n value.right,\n value.bottom,\n );\n }\n },\n }: Object),\n );\n Object.defineProperty(\n this.props,\n 'cursorVisibilitySlop',\n ({\n set: value => {\n if (value === null) {\n value = 0;\n }\n if (typeof value === 'number') {\n this.view.setCursorVisibilitySlop(value, value, value, value);\n } else {\n this.view.setCursorVisibilitySlop(\n value.left,\n value.top,\n value.right,\n value.bottom,\n );\n }\n },\n }: Object),\n );\n Object.defineProperty(\n this.props,\n 'billboarding',\n ({\n set: value => {\n if (value === null) {\n value = 'off';\n }\n this.view.setBillboarding(value);\n },\n }: Object),\n );\n }", "wrangle() {\n // Define this vis\n const vis = this;\n\n // Update resultsCount from data\n vis.resultsCount = vis.data.length;\n\n // Call render\n vis.render();\n }", "function visualise(){\r\n//sets the background to grey to hide any text that was previously on it\r\n background(80);\r\n\r\n//creates a button that calls the function priceDraw when pressed\r\n visPrice = createButton('Prices');\r\n visPrice.position(10,630);\r\n visPrice.size(100,30);\r\n visPrice.mousePressed(priceDraw);\r\n\r\n//creates a button that calls the function quanDraw when pressed\r\n visQuan = createButton('Quantity');\r\n visQuan.position(10,600);\r\n visQuan.size(100,30);\r\n visQuan.mousePressed(quanDraw);\r\n\r\n//hides the other buttons so they don't interfere\r\n listButtons.hide();\r\n graphButton.hide();\r\n visButton.hide();\r\n }", "updateVisuals() {\r\n\t\tthis.props.updateVisuals()\r\n\t\tthis.animationFrameRequest = window.requestAnimationFrame(this.updateVisuals)\r\n\t}", "btnTv(){\n\n this.visibleMovie = false;\n this.visibleTv = true;\n\n }", "function drawVisualization() {\n // create the data table.\n data = new vis.DataSet();\n\n // create the animation data\n for (var i = 0; i < field1.length; i++) {\n x = field1[i];\n y = field2[i];\n z = field3[i];\n var style = clusters[i] == 0 ? \"#FFA500\" : clusters[i] == 1 ? \"#0000FF\" : clusters[i] == 2 ? \"#008000\" : clusters[i] == 3 ? \"#FFFF00\" : clusters[i] == 4 ? \"#4B0082\" : \"#000000\";\n\n data.add({ x: x, y: y, z: z, style: style });\n }\n\n // specify options\n var options = {\n width: \"100%\",\n height: \"100%\",\n style: \"dot-color\",\n showPerspective: true,\n showGrid: true,\n keepAspectRatio: true,\n verticalRatio: 1.0,\n showLegend: false,\n tooltip: {\n color: \"red\",\n },\n cameraPosition: {\n horizontal: -0.35,\n vertical: 0.22,\n distance: 1.8,\n },\n xLabel: field1Name,\n yLabel: field2Name,\n zLabel: field3Name\n };\n\n // create our graph\n var container = document.getElementById(\"mygraph\");\n graph = new vis.Graph3d(container, data, options);\n graph.on(\"click\", onclick);\n }", "function drawVisualization() {\n // create the data table.\n data = new vis.DataSet();\n\n // create the animation data\n for (var i = 0; i < pc1.length; i++) {\n x = pc1[i];\n y = pc2[i];\n z = pc3[i];\n var style = \"#0000CD\";\n\n data.add({ x: x, y: y, z: z, style: style });\n }\n\n // specify options\n var options = {\n width: \"100%\",\n height: \"100%\",\n style: \"dot-color\",\n showPerspective: true,\n showGrid: true,\n keepAspectRatio: true,\n verticalRatio: 1.0,\n showLegend: false,\n tooltip: {\n color: \"red\",\n },\n cameraPosition: {\n horizontal: -0.35,\n vertical: 0.22,\n distance: 1.8,\n },\n xLabel: \"PC1\",\n yLabel: \"PC2\",\n zLabel: \"PC3\"\n };\n\n // create our graph\n var container = document.getElementById(\"mygraph\");\n graph = new vis.Graph3d(container, data, options);\n graph.on(\"click\", onclick);\n }", "function initVis() {\r\n\r\n createMapChart();\r\n populateTable();\r\n createLineCharts();\r\n}", "function LGraphGUIPad()\r\n\t{\r\n\t\tthis.addInput(\"bg\",\"image,texture\");\r\n\t\tthis.addOutput(\"x\",\"number\");\r\n\t\tthis.addOutput(\"y\",\"number\");\r\n\t\tthis.addOutput(\"v\",\"vec2\");\r\n\t\tthis.properties = { enabled: true, value: [0,0], position: [20,20], min:[0,0], max:[1,1], size: [200,200], corner: LiteGraph.CORNER_TOP_LEFT };\r\n\t\tthis._area = vec4.create();\r\n\t\tthis._value_norm = vec2.create();\r\n\t}", "function Nevis() {}", "function Nevis() {}", "function Nevis() {}", "get visible() {\n return this._visible;\n }", "get visible() {\n return this._visible;\n }", "get visible() {\n return this._visible;\n }", "function animOnVisibility() {\n checkVisible(demos, dist);\n}", "function Scene() {}", "initVis(){\n let vis = this;\n\n // empty initial filters\n vis.filters = [];\n // Set a color for dots\n vis.color = d3.scaleOrdinal()\n // Adobe Color Analogous\n .range([\"#F7DC28\", \"#D9AE23\", \"#D98A23\", \"#F77E28\", \"#F0B132\"])\n // set color domain to number of census years\n .domain(v2RectData.map(d => d.count).reverse())\n\n // set a color for background boxes\n vis.rectColor = d3.scaleOrdinal()\n //https://colorbrewer2.org/#type=sequential&scheme=Greys&n=7\n .range(['#f7f7f7','#d9d9d9','#bdbdbd','#969696','#737373','#525252','#252525'])\n .domain(v2RectData.map(d=>d.id))\n\n // Set sizing of the SVG\n vis.margin = {top: 40, right: 10, bottom: 20, left: 10};\n vis.width = $(\"#\" + vis.parentElement).width() - vis.margin.left - vis.margin.right;\n vis.height = $(\"#\" + vis.parentElement).height() - vis.margin.top - vis.margin.bottom;\n vis.buffer = 40;\n\n // For the dots\n // Scale the cells on the smaller height or width of the SVG\n // let cellScaler = vis.height > vis.width ? vis.width: vis.height;\n vis.cellHeight = vis.width / (15 * v2RectData.length) ;\n vis.cellWidth = vis.cellHeight;\n vis.cellPadding = vis.cellHeight / 4;\n\n // For the rects\n vis.rectPadding = 10;\n vis.rectWidth = vis.width/(v2RectData.length) - vis.rectPadding; // fit all the rects in width wise\n vis.rectHeight = vis.rectWidth; //square\n\n\n // init drawing area\n vis.svg = d3.select(\"#\" + vis.parentElement).append(\"svg\")\n .attr(\"width\", vis.width)\n .attr(\"height\", vis.height)\n .attr('transform', `translate (0, ${vis.margin.top})`);\n\n // append a tooltip\n vis.tooltip = d3.select(\"body\").append('div')\n .attr('class', \"tooltip\")\n .attr('id', 'distanceVisToolTip');\n\n // The cell group that *must underlay* the rectangles for rect hover\n vis.cellGroup = vis.svg.append(\"g\")\n .attr(\"class\", \"cell-group\")\n // slightly more offset than the rect group\n .attr(\"transform\", `translate(0, ${vis.buffer + 3 * vis.cellPadding})`);\n\n\n // The background rectangle group that *overlays* the dots (for hover) ----\n vis.rectGroup = vis.svg.append(\"g\")\n .attr(\"class\", \"rect-container\")\n // move down to give room to legend\n .attr(\"transform\", `translate(0, ${vis.buffer})`);\n\n // ------ build a grid of cells ---\n vis.rects = vis.rectGroup\n .selectAll(\".census-rect\")\n .data(v2RectData)\n .enter()\n .append(\"rect\")\n .attr(\"class\", d =>`census-rect rect-${d.id}`)\n .attr(\"x\", (d,i) => i * vis.rectWidth + vis.rectPadding)\n .attr(\"y\", (d,i) => vis.rectPadding) // same y for each rect //Math.floor(i % 100 / 10);\n .attr(\"width\", d => d.id === \"NV\" ? vis.rectWidth/3 : vis.rectWidth)\n .attr(\"height\", vis.rectHeight)\n .attr(\"fill\", \"#f7f7f7\")\n .attr(\"stroke\", \"black\")\n .attr(\"opacity\", d => {\n if (d.count === 0) {\n return 0; // because nothing falls into 0 census with the current attribute set\n } else {\n return 0.3 // for dots to to be seen through it\n }\n })\n .attr(\"stroke-width\", 4)\n .on('mouseover', function(event, d) {\n vis.handleMouseOver(vis, event, d);\n })\n .on('mouseout', function(event, d) {\n vis.handleMouseOut(vis, event, d);\n });\n\n // legend to describe the color and shape\n vis.legend = vis.svg.append('g')\n .attr('class', 'v2-legend-group')\n .attr(\"transform\", `translate(0, 10)`);\n\n // All top row labels to the rectangles\n vis.labelTopGroup = vis.svg.append('g')\n .attr('class', 'v2-label-group-top')\n .attr(\"transform\", `translate(10, 20)`);\n\n vis.labels = vis.labelTopGroup\n .selectAll(\".census-rect-label-top\")\n .data(v2RectData)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"census-rect-label-top\")\n .attr(\"x\", (d,i) => i * vis.rectWidth )\n .attr(\"y\", 0)\n .style(\"fill\", \"black\")\n .text(d => {\n return ` ${d.title}`;\n })\n .attr(\"text-anchor\", \"center\")\n .style(\"alignment-baseline\", \"middle\")\n\n // Add labels to the rectangles\n vis.labelGroup = vis.svg.append('g')\n .attr('class', 'v2-label-group')\n .attr(\"transform\", `translate(10, 40)`);\n\n vis.labels = vis.labelGroup\n .selectAll(\".census-rect-label\")\n .data(v2RectData)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"census-rect-label\")\n .attr(\"x\", (d,i) => i * vis.rectWidth )\n .attr(\"y\", 0)\n .style(\"fill\", \"black\")\n .text(d => {\n return ` ${d.name}`;\n })\n .attr(\"text-anchor\", \"center\")\n .style(\"alignment-baseline\", \"middle\")\n\n vis.wrangleStaticData();\n }", "data() {\n\t\treturn {\n\t\t\tisVisible: true\n\t\t}\n\t}", "get _isVisible(){return Boolean(this.offsetWidth||this.offsetHeight);}", "contains(vis) {\n return (vis === this);\n }", "constructor(pos,type='forward') {\n super(pos)\n this.type=type;\n this.setSvg()\n }", "@autobind\n pauseVisuals() {\n this.pause = true;\n }", "function setVisualStructure() {\n // Get contexts.\n const contextnames = [\n 'scape',\n 'glassBottle',\n 'bottleText',\n 'bottleWave',\n 'chart',\n 'blackBox',\n 'globe',\n ];\n\n updateContexts(contextnames);\n setRoughCanvases();\n}", "function setVisualStructure() {\n // Get contexts.\n const contextnames = [\n 'scape',\n 'glassBottle',\n 'bottleText',\n 'bottleWave',\n 'chart',\n 'blackBox',\n 'globe',\n ];\n\n updateContexts(contextnames);\n setRoughCanvases();\n}", "constructor() {\n this.eGui = document.createElement(\"span\");\n }", "init()\n { this.animated_children.push( this.axes_viewer = new Axes_Viewer( { uniforms: this.uniforms } ) );\n // Scene defaults:\n this.shapes = { box: new defs.Cube() };\n const phong = new defs.Phong_Shader();\n this.material = { shader: phong, color: color( .8,.4,.8,1 ) };\n }", "function visualiserVilleControls(){\n var vControles = [\"lbledaddVille\",\"txtedaddVille\",\n \"lbledSaveVill\",\"btnedSaveVill\"];\n visualiserControls(\"btnedaddVill\",vControles,\"cboxedVill\");\n} // end visualiser", "function initViz() {\n console.log(\"Hello!\");\n // no const with viz as it has been assigned by let at the top\n viz = new tableau.Viz(vizContainer, url, options);\n}", "attached() {\n this.visible = false;\n }", "static toggle(visualization) {\n var el, otherEl, visual, otherVisual, noiseVisuals=[], otherNoiseVisuals=[], animalCallVisuals=[];\n if (visualization == 'spectro') {\n otherEl = document.getElementById('wave_button');\n el = document.getElementById('spectro_button');\n visual = document.getElementById('spectrogram_frame');\n otherVisual = document.getElementById('waveform_frame');\n noiseVisuals = document.getElementsByClassName('spectrogram_noise');\n animalCallVisuals = document.getElementsByClassName('spectrogram_call');\n otherNoiseVisuals = document.querySelectorAll('.waveform_noise, .waveform_call');\n } else if (visualization == 'wave') {\n el = document.getElementById('wave_button');\n otherEl = document.getElementById('spectro_button');\n visual = document.getElementById('waveform_frame');\n otherVisual = document.getElementById('spectrogram_frame');\n noiseVisuals = document.getElementsByClassName('waveform_noise');\n animalCallVisuals = document.getElementsByClassName('waveform_call');\n otherNoiseVisuals = document.querySelectorAll('.spectrogram_noise, .spectrogram_call');\n }\n\n // toggle player visuals\n if (el == null || otherEl == null || visual == null || otherVisual == null)\n throw \"Unknown visualization button\";\n el.classList.add('selected');\n visual.classList.add('selected');\n otherEl.classList.remove('selected');\n otherVisual.classList.remove('selected');\n\n // toggle noise visuals\n for (var n=0; n < otherNoiseVisuals.length; n++) {\n otherNoiseVisuals[n].classList.remove('selected');\n }\n for (var n=0; n < noiseVisuals.length; n++) {\n noiseVisuals[n].classList.add('selected');\n }\n if (animalCallVisuals) {\n for (var n=0; n < animalCallVisuals.length; n++) {\n animalCallVisuals[n].classList.add('selected');\n }\n }\n }", "function UI() {\n\n}", "function Visual( area ) {\n this.area = area;\n this.canvas = make_canvas( this.area );\n this.context = this.canvas.getContext( '2d' );\n this.target = arguments.length > 1 ? arguments[ 1 ] : null;\n }", "function visible(sw) {\n\treturn {\n\t\ttype: types.SIDE_VISIBLE,\n\t\tvalue: sw\n\t};\n}", "get visible() {\n return true;\n }", "setVisible(value) {\n this.visible = value;\n _.each(this.shapes, (shape) => {\n shape.visible = value;\n });\n }", "get canvas() { return this._.canvas; }", "static getStyles(){return this.styles;}", "handleVisualize() {\n const { selectedBrowserAssembly } = this.getSelectedAssemblyAnnotation();\n visOpenBrowser(this.props.context, this.state.currentBrowser, selectedBrowserAssembly, this.state.selectedBrowserFiles, this.context.location_href);\n }", "function createVis() {\n // Create event handler\n var gridSearch = new gridsearch(\"grid-search\",n_letters,8);\n\n var dropSearch = new dropdown(\"drop-search\",nameID);\n\n legendDraw();\n\n\n}", "setupEffectController(){\n this.effectControllerGUI = new dat.GUI({\n height:28*2 - 1\n });\n\n this.effectControllerGUI.domElement.id = 'effect-controller';\n\n this.effectControllerGUI.add(this.effectController, 'showGround').name(\"Show Ground Plane\");\n this.effectControllerGUI.add(this.effectController, 'showAxes').name(\"Show Axes\");\n this.effectControllerGUI.add(this.effectController,'viewSide', { front:1, back: 2, left: 3,right:4 }).name(\"View Side\");\n this.effectControllerGUI.add(this.effectController, 'lightType',{ default:1, spotlight:2}).name(\"Light Type\");\n\n }", "function clearVisual(gfx) {\n\n var oldVisual = gfx.select('.djs-visual');\n\n var newVisual = gfx.group().addClass('djs-visual').before(oldVisual);\n\n oldVisual.remove();\n\n return newVisual;\n}", "function UI() {\n }", "getVisibility() {\n var visibility = 'visible';\n if (this.state.position < 0 || this.state.position > this.state.max) {\n visibility = 'hidden';\n }\n return visibility;\n }", "function set_big_vis(vis) {\r\n $('.floating.popup').remove();\r\n big_vis = vis;\r\n $('#big_vis_map').removeClass('active');\r\n $('#big_vis_time').removeClass('active');\r\n \r\n $('#big_vis_' + vis).addClass('active');\r\n \r\n if(vis == 'time') {\r\n $('#timeline').css('display', 'block');\r\n $('#map').css('display', 'none');\r\n }\r\n else if(vis == 'map') {\r\n $('#map').css('display', 'block');\r\n $('#timeline').css('display', 'none');\r\n }\r\n }", "get _isVisible(){return!!(this.offsetWidth||this.offsetHeight)}", "function visuallyHide( el, className ) {\n\tel.classList.add( className );\n\n\tsetStylesOnElement( {\n\t\tclip: 'rect(1px, 1px, 1px, 1px)',\n\t\tclipPath: 'inset(50%)',\n\t\theight: '1px',\n\t\twidth: '1px',\n\t\toverflow: 'hidden',\n\t\tposition: 'absolute'\n\t}, el );\n}", "getViewMatrix() {\nreturn this.viewMat;\n}", "constructor(structure, viewer, params) {\n super(structure, viewer, params);\n this.n = 0; // Subclass create sets value\n this.parameters = Object.assign({\n labelVisible: {\n type: 'boolean'\n },\n labelSize: {\n type: 'number', precision: 3, max: 10.0, min: 0.001\n },\n labelColor: {\n type: 'color'\n },\n labelFontFamily: {\n type: 'select',\n options: {\n 'sans-serif': 'sans-serif',\n 'monospace': 'monospace',\n 'serif': 'serif'\n },\n buffer: 'fontFamily'\n },\n labelFontStyle: {\n type: 'select',\n options: {\n 'normal': 'normal',\n 'italic': 'italic'\n },\n buffer: 'fontStyle'\n },\n labelFontWeight: {\n type: 'select',\n options: {\n 'normal': 'normal',\n 'bold': 'bold'\n },\n buffer: 'fontWeight'\n },\n labelsdf: {\n type: 'boolean', buffer: 'sdf'\n },\n labelXOffset: {\n type: 'number', precision: 1, max: 20, min: -20, buffer: 'xOffset'\n },\n labelYOffset: {\n type: 'number', precision: 1, max: 20, min: -20, buffer: 'yOffset'\n },\n labelZOffset: {\n type: 'number', precision: 1, max: 20, min: -20, buffer: 'zOffset'\n },\n labelAttachment: {\n type: 'select',\n options: {\n 'bottom-left': 'bottom-left',\n 'bottom-center': 'bottom-center',\n 'bottom-right': 'bottom-right',\n 'middle-left': 'middle-left',\n 'middle-center': 'middle-center',\n 'middle-right': 'middle-right',\n 'top-left': 'top-left',\n 'top-center': 'top-center',\n 'top-right': 'top-right'\n },\n rebuild: true\n },\n labelBorder: {\n type: 'boolean', buffer: 'showBorder'\n },\n labelBorderColor: {\n type: 'color', buffer: 'borderColor'\n },\n labelBorderWidth: {\n type: 'number', precision: 2, max: 0.3, min: 0, buffer: 'borderWidth'\n },\n labelBackground: {\n type: 'boolean', rebuild: true\n },\n labelBackgroundColor: {\n type: 'color', buffer: 'backgroundColor'\n },\n labelBackgroundMargin: {\n type: 'number', precision: 2, max: 2, min: 0, rebuild: true\n },\n labelBackgroundOpacity: {\n type: 'range', step: 0.01, max: 1, min: 0, buffer: 'backgroundOpacity'\n },\n labelFixedSize: {\n type: 'boolean', buffer: 'fixedSize'\n },\n lineOpacity: {\n type: 'range', min: 0.0, max: 1.0, step: 0.01\n },\n linewidth: {\n type: 'integer', max: 50, min: 1, buffer: true\n }\n }, this.parameters, {\n flatShaded: null\n });\n }", "displayVisuals(helper) {\n //Cube Layer 1\n image(\n assets.visual.default.cubeLayer1,\n cube.x - 400 * cube.size,\n cube.y - 420 * cube.size,\n 763.4 * cube.size,\n 843.7 * cube.size\n );\n\n if (this.keyAction.interactedObject === \"boat\") {\n this.keyAction.boat(helper);\n } else if (this.keyAction.interactedObject === \"nets\") {\n this.keyAction.nets(helper);\n } else if (this.keyAction.interactedObject === \"port\") {\n this.keyAction.port(helper);\n } else if (this.keyAction.interactedObject === \"waterSurface\") {\n this.keyAction.waterSurface(helper);\n }\n this.keyAction.parameterNetwork.inputToOutput();\n this.keyAction.parameterNetwork.calculateScore();\n this.calculateEntities();\n for (let i = 0; i < this.coralArray.length; i++) {\n this.coralArray[i].render(assets);\n }\n\n //net\n if (this.hover.nets === true) {\n image(\n assets.visual.active.nets,\n cube.x - 200 * cube.size,\n cube.y - 290 * cube.size,\n 660 * 0.6 * cube.size,\n 501 * 0.9 * cube.size\n );\n } else {\n image(\n assets.visual.default.nets,\n cube.x - 200 * cube.size,\n cube.y - 290 * cube.size,\n 660 * 0.6 * cube.size,\n 501 * 0.9 * cube.size\n );\n }\n\n //Cube Layer 2\n image(\n assets.visual.default.cubeLayer2,\n cube.x - 310 * cube.size,\n cube.y - 375 * cube.size,\n 313.5 * cube.size,\n 732.6 * cube.size\n );\n for (let i = 0; i < this.fishArray.length; i++) {\n this.fishArray[i].move();\n this.fishArray[i].render();\n }\n\n //Cube Layer 3\n image(\n assets.visual.default.cubeLayer3,\n cube.x - 400 * cube.size,\n cube.y - 420 * cube.size,\n 763.4 * cube.size,\n 843.7 * cube.size\n );\n for (let i = 0; i < this.bycatchArray.length; i++) {\n this.bycatchArray[i].float();\n this.bycatchArray[i].render();\n }\n if (this.plasticTeppich.stage >= 0) {\n this.plasticTeppich.float();\n this.plasticTeppich.render(assets);\n }\n\n //boat\n if (this.hover.boat === true) {\n image(\n assets.visual.active.boat,\n cube.x + 150 * cube.size,\n cube.y - 370 * cube.size,\n 2203 * 0.08 * cube.size,\n 1165 * 0.08 * cube.size\n );\n } else {\n image(\n assets.visual.default.boat,\n cube.x + 150 * cube.size,\n cube.y - 370 * cube.size,\n 2203 * 0.08 * cube.size,\n 1165 * 0.08 * cube.size\n );\n }\n\n //house\n image(\n assets.visual.default.house,\n cube.x - 240 * cube.size,\n cube.y - 440 * cube.size,\n 1684 * 0.075 * cube.size,\n 1962 * 0.075 * cube.size\n );\n if (this.hover.house === true) {\n image(\n assets.visual.active.house,\n cube.x - 350 * cube.size,\n cube.y - 400 * cube.size,\n 1684 * 0.08 * cube.size,\n 1962 * 0.08 * cube.size\n );\n } else {\n image(\n assets.visual.default.house,\n cube.x - 350 * cube.size,\n cube.y - 400 * cube.size,\n 1684 * 0.08 * cube.size,\n 1962 * 0.08 * cube.size\n );\n }\n this.keyAction.parameterNetwork.display();\n if (\n this.keyAction.parameterNetwork.loseEnd === true ||\n this.keyAction.parameterNetwork.winEnd === true\n ) {\n helper.screenState = \"end\";\n }\n }", "function TViewNode() { }", "function TViewNode() { }", "function getVisualViewport() {\n // tslint:disable-next-line:no-any\n return ('visualViewport' in window) ? window.visualViewport : new VisualViewportPolyfill();\n}", "function init(vis, esResponse) {\n vis.aggs.forEach(function (agg, i) { agg.id = 'agg_' + (i + 1); });\n\n $rootScope.vis = vis;\n $rootScope.esResponse = esResponse;\n $rootScope.uiState = require('fixtures/mock_ui_state');\n $el = $('<visualize vis=\"vis\" es-resp=\"esResponse\" ui-state=\"uiState\">');\n $compile($el)($rootScope);\n $rootScope.$apply();\n }", "function renderStaticView() {\n\t// Text for class view\n\tclassViewText();\n\n\t// Rect for line under title\n\t//classViewLine();\n\t// ORDER LEVEL and FAMILY LEVEL label\n\tstaticLabels();\n\t// Legend\n\t//legend();\n\t//incrementProgress();\n\tinstructions();\n}", "initVis(){\n var vis = this;\n\n // SVG drawing area\n vis.svg = d3.select(\"#\" + vis.parentElement).append(\"svg\")\n .attr(\"width\", vis.width + vis.margin.left + vis.margin.right)\n .attr(\"height\", vis.height + vis.margin.top + vis.margin.bottom)\n vis.g = vis.svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + vis.margin.left + \",\" + vis.margin.top + \")\");\n \n\n\n // Scales and axes\n vis.x = d3.scaleLinear()\n .range([0,vis.width]);\n\n vis.countryScale = d3.scaleBand()\n .rangeRound([0, vis.width])\n .paddingInner(0.2);\n\n\n vis.y = d3.scaleLinear()\n .range([vis.height,0]);\n\n vis.xAxis = d3.axisBottom()\n .scale(vis.x);\n\n vis.yAxis = d3.axisLeft()\n .scale(vis.y);\n\n vis.g.append(\"g\")\n .attr(\"class\", \"x-axis axis\")\n .attr(\"transform\", \"translate(0,\" + vis.height + \")\");\n\n vis.g.append(\"g\")\n .attr(\"class\", \"y-axis axis\");\n\n // Axis title\n vis.g.append(\"text\")\n .attr(\"x\", -50)\n .attr(\"y\", -8)\n .text(vis.yAttr);\n\n // Axis title\n vis.g.append(\"text\")\n .attr('class', 'xlabel')\n .attr(\"x\", vis.width/2)\n .attr(\"y\", vis.height + 40)\n .style('text-anchor','middle')\n .text(vis.xAttr);\n\n\n // (Filter, aggregate, modify data)\n vis.wrangleData();\n }", "function NetVis(Options) {\n\tvar self = this;\n\tself._topologyPanel = Options.topologyPanel || \"#chart\";\n\tself._historyPanel = Options.historyPanel || \"#history\";\n\tself._timePanel = Options.timePanel || \"#timestamp\";\n\tself._playmode = false;\n\n\tself.config = {\n\t\t_root: self,\n\t\t_label: \"configuration\",\n\t\tnodeDefaultDistance: 30,\n\t\tnodeDefaultRadius: 10,\n\t\tloopPlay: false\n\t};\n\n\tself._constructNodes(); // constructor for self.nodes\n\tself._constructMessages(); // constructor for self.messages\n\tself._constructConnections(); // constructor for self.connections\n\tself._constructHistory(); // constructor for self.history\n self._constructLogger();\n\tself._selected = self; // _selected object's public attributes are shown at properties-table\n\n\n\tself.resetPositions = function() {\n\t\tself.nodes.resetPositions();\n\t\tself._selected = self;\n\t\tself.render();\n\t};\n\n\n\tself.updateAll = function() {\n\t\tthis.nodes.updateAll();\n\t\tthis.messages.updateAll();\n\t\tthis.history.updateAll();\n\n\t\tif (this.history.intervals) {\n\t\t\tthis._selectedTimeInterval = this.history.intervals[0];\n\t\t}\n\t};\n\n\tself.play = function() {\n\t\tself._playmode = !self._playmode;\n\t\tif (self._playmode) {\n\t\t\tself._playTicker = window.setInterval(function() {\n\t\t\t\tself.history.next();\n\t\t\t\tself.render();\n\t\t\t}, 800);\n\t\t} else {\n\t\t\twindow.clearInterval(self._playTicker); // clear play ticking timer\n\t\t}\n\t\tself.render();\n\t};\n\n\tself.next = function() {\n\t\tself.history.next();\n\t\tself.render();\n\t};\n\n\tself.prev = function() {\n\t\tself.history.prev();\n\t\tself.render();\n\t};\n\n\tself.loopPlay = function() {\n\t\tself.config.loopPlay = !self.config.loopPlay;\n\t\tself.render();\n\t};\n\n\t$(document).on(\"keydown\", function(event) {\n\t\tconsole.log(\"keydown logged!\", event);\n\t\tswitch (event.keyCode) {\n\t\t\tcase 32:\n\t\t\t\tself.play();\n\t\t\t\tbreak;\n\t\t\tcase 37:\n\t\t\t\tself.prev();\n\t\t\t\tbreak;\n\t\t\tcase 39:\n\t\t\t\tself.next();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n}", "setXY(x,y)\n {\n this.x = x;\n this.y = y;\n this.drawx = x;\n this.drawy = y;\n\n this.vis = {\n\t\tdx : 0,\n\t\tdy : 0,\n\t\tx : this.x,\n\t\ty : this.y\n\t\t};\n\n }", "function createVisualPanel() {\n const articleVisualElAll = document.querySelectorAll('.element-image:not(.header-image), .element-interactive, .element-atom--media');\n\n const visualPanelEl = document.createElement('div');\n const visualPanelInnerEl = document.createElement('div');\n\n visualPanelEl.classList.add('visual-panel');\n visualPanelInnerEl.classList.add('visual-panel__inner');\n visualPanelEl.appendChild(visualPanelInnerEl);\n\n articleVisualElAll.forEach(function (articleVisualEl) {\n const articleVisualElClone = articleVisualEl.cloneNode(true);\n visualPanelInnerEl.appendChild(articleVisualElClone);\n });\n\n const mainColEl = document.querySelector('.content__main .gs-container:not(.u-cf');\n mainColEl.insertBefore(visualPanelEl, mainColEl.firstChild);\n}", "function drawVisualization() {\n // create the data table.\n data = new vis.DataSet();\n\n // create the animation data\n\n for (var i = 0; i < pc1.length; i++) {\n x = pc1[i];\n y = pc2[i];\n z = pc3[i];\n var style = clusters[i] == 0 ? \"#FFA500\" : clusters[i] == 1 ? \"#0000FF\" : clusters[i] == 2 ? \"#008000\" : clusters[i] == 3 ? \"#FFFF00\" : clusters[i] == 4 ? \"#4B0082\" : \"#000000\";\n\n data.add({ x: x, y: y, z: z, style: style });\n }\n\n // specify options\n var options = {\n width: \"100%\",\n height: \"100%\",\n style: \"dot-color\",\n showPerspective: true,\n showGrid: true,\n keepAspectRatio: true,\n verticalRatio: 1.0,\n showLegend: false,\n tooltip: {\n color: \"red\",\n },\n cameraPosition: {\n horizontal: -0.35,\n vertical: 0.22,\n distance: 1.8,\n },\n xLabel: \"PC1\",\n yLabel: \"PC2\",\n zLabel: \"PC3\"\n };\n\n // create our graph\n var container = document.getElementById(\"mygraph\");\n graph = new vis.Graph3d(container, data, options);\n graph.on(\"click\", onclick);\n }", "function Scene() {\n SceneNode.call( this );\n this.drawableList = [];\n}", "show() {\n this.visible = true;\n }", "initVis() {\n let vis = this;\n\n /*vis.margin = {top: 30, right: 80, bottom: 30, left: 80};\n\n vis.width = $(\"#\" + vis.parentElement).width() - vis.margin.left - vis.margin.right,\n vis.height = 700 - vis.margin.top - vis.margin.bottom;\n\n // SVG drawing area\n vis.svg = d3.select(\"#\" + vis.parentElement).append(\"svg\")\n .attr(\"width\", vis.width + vis.margin.left + vis.margin.right)\n .attr(\"height\", vis.height + vis.margin.top + vis.margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + vis.margin.left + \",\" + vis.margin.top + \")\");*/\n\n vis.boxPlotDiv = document.getElementById(vis.parentElement)\n vis.boxPlotDiv.style.height = '650px'\n\n vis.colors = {\n 'navy': '#010D26',\n 'blue': '#024059',\n 'paleOrange': '#D98E04',\n 'orange': '#F28705',\n 'darkOrange': '#BF4904',\n 'purp': '#8F2051',\n 'tan': '#F2E1C9',\n }\n\n vis.filter = \"mean_vote\"\n\n vis.layout = {\n title: 'Distribution of Movie Ratings by Genre',\n yaxis: {\n // autorange: true,\n showgrid: true,\n zeroline: true,\n range: [0,10],\n // dtick: 0,\n gridcolor: 'rgb(255, 255, 255)',\n gridwidth: 1,\n zerolinecolor: 'rgb(255, 255, 255)',\n zerolinewidth: 2\n },\n margin: {\n l: 60,\n r: 50,\n b: 80,\n t: 100\n },\n paper_bgcolor: vis.colors.tan,\n plot_bgcolor: vis.colors.tan,\n showlegend: false\n };\n\n /*vis.pieChartGroup = vis.svg\n .append('g')\n .attr('class', 'pie-chart')\n .attr(\"transform\", \"translate(\" + vis.width / 2 + \",\" + vis.height / 2 + \")\");\n\n // Pie chart settings\n let outerRadius = vis.width / 2;\n let innerRadius = 20;\n\n // Path generator for the pie segments\n vis.arc = d3.arc()\n .innerRadius(innerRadius)\n .outerRadius(outerRadius);\n\n // Pie Layout\n vis.pie = d3.pie()\n .value(function(d){\n return d.value\n });*/\n\n vis.wrangleData()\n }", "function LGraphGUISlider()\r\n\t{\r\n\t\tthis.addOutput(\"v\");\r\n\t\tthis.properties = { enabled: true, text: \"\", min: 0, max: 1, value: 0, position: [20,20], size: [200,40], corner: LiteGraph.CORNER_TOP_LEFT };\r\n\t\tthis._area = vec4.create();\r\n\t}", "constructor(_parentElementID, _visWidth, _visHeight, _opacityViewPercentage, _updateRenderFunc, _getVolumeActorPropertyFunc, _minMax,\n _initOpaCtrolPoint, _initNumColorCtrlPoint, _initColorCtrlPoint){\n this.parentElementID = _parentElementID;\n this.tfSvgWidth = _visWidth;\n this.tfSvgHeight = _visHeight;\n this.opacityViewPercentage = _opacityViewPercentage;\n this.updateRenderFunc = _updateRenderFunc;\n this.getVolumeActorPropertyFunc = _getVolumeActorPropertyFunc;\n this.minMax = _minMax;\n if( _initOpaCtrolPoint === null ){\n this.opaCtrlPoint = [[this.minMax[0], 0], [this.minMax[1], 1]]; \n }else{\n this.opaCtrlPoint = _initOpaCtrolPoint;\n }\n this.opacityFactor = 1.0;\n if( _initNumColorCtrlPoint == -1 ){\n this.colorCtrlPoint = _initColorCtrlPoint;\n }else{\n let step = 1 / (_initNumColorCtrlPoint-1);\n this.colorCtrlPoint = []\n let colorMapValue = 0\n for(let i = 0; i<_initNumColorCtrlPoint; i++){\n let rgb = _initColorCtrlPoint(colorMapValue).split('(')[1].split(',');\n let r = parseFloat(rgb[0])/255.0;\n let g = parseFloat(rgb[1])/255.0;\n let b = parseFloat(rgb[2].split(')')[0])/255.0;\n this.colorCtrlPoint.push([colorMapValue * (this.minMax[1] - this.minMax[0]) + this.minMax[0], r, g, b]);\n colorMapValue += step;\n }\n }\n\n this.initProps(this, this.getVolumeActorPropertyFunc()); //set the volume Actor property (TF)\n\n this.initVis();\n\n this.updateRenderFunc();\n }", "function renderVis1() {\n\tdrunkButtonMode = false;\n\tv1part2g = svg1.append(\"g\")\n\tv1barsg = svg1.append(\"g\")\n\tv1part2g.attr(\"transform\", \"translate(\"+(vis1x0+vis1xspace)+\", \"+vis1part2y0+\")\");//.attr(\"opacity\", 0);\n\trenderV1Axis();\n\trenderV1Data();\n\trenderV1Titles();\n\tupdateAllV1(0);\t\n\trenderV1Part2();\n\t\n}", "function showtableau() {\n console.log(\"showing viz\");\n viz.show();\n}", "constructor() {\n this.mesh = null;\n }", "function VisualArray(sketch, x, y) {\n // Essential info\n this.p = sketch;\n this.numbers = [];\n this.y = y;\n this.x = x;\n\n //Formatting info\n this.numOffset = 30;\n // Methods\n this.add = function(num) {\n let xOffset = this.numbers.length * this.numOffset;\n\n let newNum = new VisualNumber(this.p, num, x + (xOffset % 480), y + Math.floor(xOffset / 480) * 50);\n this.numbers.push(newNum);\n }\n\n // Visualize the array\n this.show = function () {\n this.numbers.forEach ( element => {\n element.show();\n });\n }\n\n this.getNumberAtIndex = function (index) {\n return this.numbers[index].val;\n }\n\n this.getPositionAtIndex = function (index) {\n if (index > this.numbers.length)\n return null;\n\n return new Point(this.numbers[index].x, this.numbers[index].y);\n }\n\n this.changeColorOfIndex = function (index, color) {\n let num = this.numbers[index];\n num.changeColor(color);\n }\n}", "function vxlSceneDescriptor(scene, descriptorType, accessType){\r\n this.scene = scene;\r\n this.descriptorType = descriptorType;\r\n this.accessType = accessType;\r\n}", "function CartoDBLayerCommon() {\n this.visible = true;\n}", "getVSSkinMatRows() {\nreturn this.vsSkinMatRows;\n}", "function doc_visChange() {\n\t if (pageVisibilityAPI) {\n\t // @ts-ignore\n\t if (document[pageVisibilityAPI.hidden] === isPageActive) {\n\t // @ts-ignore\n\t isPageVisible = !document[pageVisibilityAPI.hidden];\n\t pageStateCheck();\n\t }\n\t }\n\t }" ]
[ "0.6412795", "0.63840026", "0.6101102", "0.59558827", "0.59144247", "0.5860045", "0.5819913", "0.58192855", "0.57873297", "0.5782663", "0.577427", "0.5762772", "0.5742079", "0.57368773", "0.5654134", "0.5634488", "0.5607981", "0.55945486", "0.55728716", "0.55708385", "0.55388135", "0.55345935", "0.5530843", "0.5517199", "0.5509573", "0.5481969", "0.5480608", "0.5469029", "0.5464449", "0.5461872", "0.5450146", "0.54471356", "0.5446601", "0.54358953", "0.5435362", "0.5430375", "0.5423542", "0.5423542", "0.5423542", "0.5422649", "0.5422649", "0.5422649", "0.5412575", "0.5411078", "0.54087466", "0.5407378", "0.5396262", "0.539379", "0.53931683", "0.5387941", "0.5382905", "0.5382905", "0.53676915", "0.5363979", "0.53436166", "0.5343253", "0.5342642", "0.53337574", "0.53300184", "0.53114176", "0.5309884", "0.53017986", "0.5296653", "0.5289332", "0.5285893", "0.52824044", "0.5281232", "0.5279286", "0.52549374", "0.52513266", "0.5243771", "0.52376765", "0.5229007", "0.5228917", "0.52282435", "0.5226869", "0.5225133", "0.52147156", "0.52147156", "0.5214128", "0.52124065", "0.52087945", "0.5208199", "0.52062076", "0.5205463", "0.52003616", "0.5191957", "0.51917064", "0.51908743", "0.51895034", "0.51892865", "0.51849633", "0.5166871", "0.5160724", "0.5158263", "0.5156651", "0.5153298", "0.51527166", "0.5150788", "0.5149435" ]
0.6597097
0
! Vue.js v2.4.2 (c) 20142017 Evan You Released under the MIT License.
function i(t){return void 0===t||null===t}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "mounted() {\n }", "mounted() {\n\n }", "mounted() {\n\n }", "constructor() {\n this.vue = new Vue();\n }", "mounted() {\n /* eslint-disable no-console */\n console.log('Mounted!');\n /* eslint-enable no-console */\n }", "created () {\n\n }", "created () {\n\n }", "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 vueTest() {\n new Vue({\n \n el: '#vueApp',\n \n data: {\n \"hello\" : \"Spinning Parrot\",\n image: 'img/spinning-parrot.gif'\n }\n \n });\n }", "created() {\n this.$nuxt = true\n }", "ready() {\n this.vm = new Vue({\n el: 'body',\n components: {\n rootvue: require('./vue'),\n },\n });\n }", "mounted() {\n console.log('Mounted!')\n }", "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 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 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}", "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 hM(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"interaction.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "data() {\n return {};\n }", "created() { }", "created() { }", "created() {\n\n }", "created() {\n\n }", "created() {\n\n }", "created() {\n\n }", "function JV(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "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}", "created(){\n\n }", "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}", "created() {\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}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "created() {\n\n\t}", "mounted(){\n console.log('Mounted');\n }", "mounted() {\n this.initialize()\n }", "mounted() {\n console.log(this.element); // eslint-disable-line\n }", "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}", "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}", "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 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 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 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 p(e,t){if(typeof console!==\"undefined\"){console.warn(\"[vue-i18n] \"+e);if(t){console.warn(t.stack)}}}", "function loadVue(){\n\n\tlisteObjBoutons = loadVueObjects();\n\n\tmvButtons = new Vue({\n\t\tel:\"#boutonsMots\",\n\t\tdata:{\n\t\t\tlisteMots:listeObjBoutons,\n\t\t\tsize: MOTS_NUMBER,\n\t\t\tetendu: (MOTS_NUMBER>4),\n\t\t\tdisplay:\"flex\"\n\t\t},\n\t\tmethods:{\n\t\t\ttestAnswer: verification,\n\t\t\treInit: function(){\n\t\t\t\tfor (let i = 0; i < this.listeMots.length; i++) {\n\t\t\t\t\tthis.listeMots[i].tvalue = false;\n\t\t\t\t\tthis.listeMots[i].fvalue = false;\n\t\t\t\t\tthis.listeMots[i].disabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\nmvNextButton = new Vue({\n\t\tel:\"#nextButton\",\n\t\tdata:{\n\t\t\tmessage : \"Image suivante\",\n\t\t\tdisplay: \"none\"\n\t\t},\n\t\tmethods:{\n\t\t\tnext: chargementImageMot,\n\t\t\tactive: function () {\n\t\t\t\tthis.display=\"block\";\n\t\t\t}\n\t\t}\n\t});\n}", "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 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}", "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 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}", "created() {\r\n\r\n\t}", "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 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}", "function __vue_normalize__(a,b,c,d,e){var f=(\"function\"==typeof c?c.options:c)||{};// For security concerns, we use only base name in production mode.\nreturn f.__file=\"/Users/hadefication/Packages/vue-chartisan/src/components/Pie.vue\",f.render||(f.render=a.render,f.staticRenderFns=a.staticRenderFns,f._compiled=!0,e&&(f.functional=!0)),f._scopeId=d,f}", "function initVue() {\n\n new Vue({\n\n el: \"#containerId\",\n data: {\n \"h1title\": 0,\n \"url\": \"img/scotland.jpeg\"\n }, // END OF DATA\n\n methods: {\n increase: function() {\n this.h1title++;\n }, // END OF INCREASE\n\n decrease: function() {\n this.h1title--;\n } // END OF DECREASE\n\n } // END OF METHODS\n }); // END OF VUE\n\n} // END OF FUNCTION initVue", "data() {\n return {\n saludocomponent: \"hola desde vue\"\n };\n }", "ready() {\n let logCtrl = this.$logTextArea;\n let logListScrollToBottom = function () {\n setTimeout(function () {\n logCtrl.scrollTop = logCtrl.scrollHeight;\n }, 10);\n };\n\n\n window.plugin = new window.Vue({\n el: this.shadowRoot,\n created() {\n },\n init() {\n },\n data: {\n logView: \"\",\n findResName: \"\",\n },\n methods: {\n _addLog(str) {\n let time = new Date();\n // this.logView = \"[\" + time.toLocaleString() + \"]: \" + str + \"\\n\" + this.logView;\n this.logView += \"[\" + time.toLocaleString() + \"]: \" + str + \"\\n\";\n logListScrollToBottom();\n },\n onBtnClickFindReferenceRes() {\n console.log(\"1\");\n },\n onResNameChanged() {\n console.log(\"2\");\n },\n dropFile(event) {\n event.preventDefault();\n let files = event.dataTransfer.files;\n if (files.length > 0) {\n let file = files[0].path;\n console.log(file);\n } else {\n console.log(\"no file\");\n }\n },\n drag(event) {\n event.preventDefault();\n event.stopPropagation();\n // console.log(\"dragOver\");\n },\n\n }\n });\n }", "function annulerAffichage(){\r\n var app = new Vue({\r\n el: '#meteo',\r\n data: {\r\n message:'ATTENTION : probleme de geolocalisation veuillez l\\'activer dans votre navigateur'\r\n }\r\n })\r\n}", "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}", "mounted() {\n this.local()\n }", "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 Vue(options) {\n var oberver = new Observer(options.data)\n var render = compile(options.el, oberver)\n render()\n}", "registerVmProperty() {\n const { vmProperty, modules } = this.options;\n this.Vue.prototype[vmProperty] = modules;\n }", "function wl(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "mounted() {\n\t\tvar h = document.createElement('DIV');\n\t\th.innerHTML = `<div>this is create append child</div>`;\n\t\tdocument.body.appendChild(h);\n\t\tconsole.log('this is log vue mounted function ', this.$el, this , this.el);\n\t}", "function Hr(e,t){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "function WD(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 i(t,e,n){if(o(t,e))return void(t[e]=n);if(t._isVue)return void i(t._data,e,n);var r=t.__ob__;if(!r)return void(t[e]=n);if(r.convert(e,n),r.dep.notify(),r.vms)for(var s=r.vms.length;s--;){var a=r.vms[s];a._proxy(e),a._digest()}return n}", "function a(e,t){'undefined'!=typeof console&&(console.warn('[vue-i18n] '+e),t&&console.warn(t.stack))}", "function i(t,e){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function i(t,e){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function i(t,e){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function i(t,e){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "data() {\n return {\n saludo: '¡Hola! Soy Desiré, te saludo desde un componente'\n }\n }", "function la(e,t){if(typeof console!==\"undefined\"){console.warn(\"[vue-i18n] \"+e);if(t){console.warn(t.stack)}}}", "function i(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function i(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "mounted() {\n store.commit('updateHash');\n }", "registerVmProperty() {\n const { vmProperty, modules } = this.options;\n this.registerError(modules);\n this.Vue.prototype[vmProperty] = modules;\n }", "function i(e,t){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "function Eu(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function Ht(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function bn(t,e){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+t),e&&console.warn(e.stack))}", "function q(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "install(vue) {\n \n vue.prototype.$renderer = this;\n vue.prototype.$engine = this.engine;\n \n vue.prototype.$start = this.start.bind(this);\n vue.prototype.$stop = this.stop.bind(this);\n vue.prototype.$pipe = this.pipe.bind(this);\n vue.prototype.$unpipe = this.unpipe.bind(this);\n }", "function i(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "function a(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "function a(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "ready() {\n this.vue = createVUE(this[\"$mainDiv\"]);\n Editor.log(\"ConvertHelper view ready\");\n }", "function vt(e,t){if(!e){throw new Error(\"[vue-router] \"+t)}}", "function r(t,e,n){if(a(t,e))return void(t[e]=n);if(t._isVue)return void r(t._data,e,n);var i=t.__ob__;if(!i)return void(t[e]=n);if(i.convert(e,n),i.dep.notify(),i.vms)for(var s=i.vms.length;s--;){var o=i.vms[s];o._proxy(e),o._digest()}return n}", "function ex(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}", "mounted() {\n let vm = this;\n\n vm.interval = null;\n vm.job = null;\n vm.editable = true;\n vm.rowId = null;\n vm.rowType = 'column';\n vm.refresh = false;\n $('#st-processsing-div').hide();\n\n show_loading('sample-template-contents');\n\n // Get the overview information from the server\n vm.updateSampleTemplateOverview();\n }", "install(vue) {\n /* globalize class */\n vue.prototype.$input = this;\n vue.prototype.$mouse = this.mouse;\n vue.prototype.$keyboard = this.keyboard;\n }", "created () {\n this.classNames = this.getDefaultClassName(this.$options.name)\n }" ]
[ "0.69328445", "0.68909883", "0.6867494", "0.65414625", "0.64629644", "0.63754064", "0.63754064", "0.6326233", "0.63201004", "0.63125116", "0.62708193", "0.6259883", "0.62272424", "0.62232596", "0.6221954", "0.62114173", "0.6200276", "0.61847085", "0.61762", "0.61762", "0.6157068", "0.6157068", "0.6157068", "0.6157068", "0.6141385", "0.61201125", "0.6071254", "0.60545343", "0.60389084", "0.6036638", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.6033361", "0.60234994", "0.6020878", "0.60101146", "0.59466815", "0.59277064", "0.59250677", "0.59193885", "0.5899467", "0.58813137", "0.58783084", "0.5870248", "0.58681726", "0.58674717", "0.58249426", "0.58226395", "0.5818221", "0.5808677", "0.57929134", "0.5775175", "0.573944", "0.5736676", "0.5734809", "0.5725589", "0.5717078", "0.57121414", "0.57058597", "0.56757057", "0.5675403", "0.5668386", "0.566778", "0.56362444", "0.56337917", "0.561596", "0.56141645", "0.56134135", "0.56134135", "0.56134135", "0.56134135", "0.5610675", "0.5597011", "0.55855334", "0.55855334", "0.5582017", "0.55752885", "0.55751145", "0.5573288", "0.5562156", "0.5560565", "0.556053", "0.555733", "0.5557297", "0.5549147", "0.5549147", "0.5544872", "0.5539323", "0.5509353", "0.55057865", "0.5494034", "0.54904747", "0.5481853" ]
0.0
-1
This function check if the input has a value
function isInputTextActive () { const mdInput = document.querySelectorAll('.md-form-control .md-input-text'); for (var i = 0; i < mdInput.length; i++) { if (mdInput[i].value.length > 0) { mdInput[i].parentElement.classList.add('focus'); }else { mdInput[i].parentElement.classList.remove('focus'); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "hasInput_(value) {\n return value.length > 0;\n }", "function inputValueCheck(el) {\n\t \tif (el.value === '') {\n\t \t\treturn false; // If element has no value, return false\n\t \t} else {\n\t \t\treturn true;\n\t \t}\n\t }", "isValueEmpty(input) {\n return input ? true : false\n }", "function inputAvailable(div) {\n if (div.value) {\n return false;\n } else if (!div.value || div.value === undefined) {\n return true;\n }\n}", "function hasValue(elem){\n\t\t\treturn $(elem).val() != '';\n\t\t}", "function inputCheck(){\n\tif(isNaN(input.value)){return false;}\n\telse return true;\n}", "checkInputBox(inputValue) {\n if(inputValue !== ''){\n return true\n } else {\n return false;\n }\n}", "function checkInput(value) {\n return !isNaN(value);\n}", "static checkEmptyUserInput(userValue){\n return (userValue==0 ? true : false);\n }", "function HasValue(inputVal) {\n\tif(inputVal){\n\t\tvar s = \"\" + inputVal + \"\";\n\t\tif(s == \"null\") return false;\n\t\tif(s == \"undefined\") return false;\n\t\tif(s.length === 0) return false;\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}", "isValid() {\n let value = this.input.value;\n return !isNaN(value);\n }", "function checkValidInput(value) {\n if (!value || value === \"\") {\n return false;\n } else {\n return true;\n }\n}", "function isEmpty(input){\r\n //console.log(input.val());\r\n if(input.val().length==0){\r\n return true;\r\n }\r\n return false;\r\n}", "static hasValue(val) {\n if (val == undefined || val == \"\" || val == NaN || val == null) {\n return false;\n }\n return true;\n }", "function validateInput(input){\n if(input == \"\" || input == undefined){\n message(\"Lén verður að vera strengur\");\n return false;\n }\n return true;\n }", "function valueChecker(variable) {\r\n\tif(variable.length > 0) {\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}", "function validate(value){\r\n \r\n if(typeof(value) !== \"undefined\" && value !== \"\"){\r\n // console.log(\"value exists: \", value);\r\n\r\n return value;\r\n\r\n }\r\n\r\n // console.log(\"value does not exist: \", value);\r\n \r\n return \"\";\r\n\r\n }", "isValid(input) {\n if (input == null || input == \"\") {\n return false;\n } else {\n return true;\n }\n }", "function catchEmpty(input){\n\n if(input===\"\"){\n return \"Please enter required information.\"\n } \n else{ \n return true};\n\n}", "valueExists(element) {\n if(element !== undefined && element !== null && element !== '') {\n return true;\n } else {\n return false;\n }\n }", "function canBeValue() { }", "function checkData(value) {\n var result = true;\n if (value === undefined || value === null || value === '') {\n result = false;\n } else if (_.isObject(value) && _.isEmpty(value)) {\n result = false;\n }\n return result;\n}", "function hasInput(fieldElement){\n\tif(fieldElement.value == null || trim(fieldElement.value) == \"\"){\n\t\treturn false;\n\t}\n\treturn true;\n}", "function vacio(value) {\n if (value === '') return true;\n return false;\n}", "function checkInputExists(input) { // check parameter exists\n if (input == undefined) {\n throw 'input does not exist'\n }\n}", "function checkEmptyInput() {\r\n let isEmpty = false;\r\n const CheckFullName = document.querySelector(\"#fname\").value;\r\n const CheckEmail = document.querySelector(\"#email\").value;\r\n const CheckAge = document.querySelector(\"#age\").value;\r\n // remember about empty input\r\n if (CheckFullName === \"\") {\r\n alert(\"Full Name Connot Be Empty\");\r\n isEmpty = true;\r\n } else if (CheckEmail === \"\") {\r\n alert(\"Email Connot Be Empty\");\r\n isEmpty = true;\r\n } else if (CheckAge === \"\") {\r\n alert(\"Age Connot Be Empty\");\r\n isEmpty = true;\r\n }\r\n return isEmpty;\r\n}", "isValid() {\n if (this.value) {\n return true;\n } else {\n return false;\n }\n }", "function vacio(value) {\r\nif (value === '') return true;\r\n return false;\r\n}", "function checkInput() {\n // Check to see if the (numeric) points input field contains a value\n if ($(\"#quest-points-input\").prop(\"value\") == null || $(\"#quest-points-input\").prop(\"value\").length == 0) {\n $(\"#feedback\").html(\"Enter a point value\");\n $(\"#feedback\").css({\n color: \"red\"\n });\n $(\"#feedback\").show(0);\n $(\"#feedback\").fadeOut(2000);\n } else {\n validInput = true;\n }\n}", "function hasValue(value) {\n return value !== undefined;\n}", "function emptyOrNot(input) {\n\n if (input) {\n return true\n } else {\n return false\n }\n \n }", "function isval(val){\n\t\tif(val === 0) return true;\n\t\telse if (val === false) return true;\n\t\telse if(val === null || val === undefined) return false;\n\t\telse if ( typeof val === 'object' && Object.keys(val).length === 0 ) return false;\n\t\telse return !!val;\n\t}", "'validateValue'(value) {}", "function valueCheck(inputVal) {\n console.log(\"enter fxn: valueCheck\");\n if (isNaN(inputVal)) {\n console.log(inputVal + \" is not a number!\");\n return 0;\n }\n else {\n console.log(inputVal + \" is a number!\");\n return inputVal;\n }\n}", "function isEmptyInput(text_input){\n if(text_input.is(\"input\")){\n return text_input.val().replace(/^\\s+|\\s+$/g, \"\").length == 0 ? true : false;\n }\n if(text_input.is(\"select\")){\n return text_input.find(\"option:not(:disabled)\").is(\":selected\") ? false : true;\n }\n }", "function isinputvalid() {\r\n let inputstr = field.value;\r\n let patt = /^[0-9]{1,3}$/g; //1-999\r\n let cond = patt.test(inputstr);\r\n\r\n if (!cond) {\r\n field.value = \"\";\r\n updateImg(data.default.bev);\r\n }\r\n return cond;\r\n}", "function formFieldHasInput(fieldElement){\n\t// Check if the text field has a value\n\tif ( fieldElement.value == null || trim(fieldElement.value) == \"\" )\n\t{\n\t\t// Invalid entry\n\t\treturn false;\n\t}\n\t\n\t// Valid entry\n\treturn true;\n}", "function isInputEmpty(input) {\n return (input === undefined || typeof (input) === \"boolean\");\n}", "function isNoteEmptyStringInput(input) {\n return input.value != \"\";\n}", "function checkNotNullInput()\n\t{\n\t\tvar check = true;\n\t\t$('.form_contact input.wpcf7-text').each(function(index, el) {\n\t\t\tif($(this).val() == \"\")\n\t\t\t{\n\t\t\t\tcheck = false;\n\t\t\t\t// console.log(\"Input text\" + index + ' : ' + check);\n\t\t\t}\n\t\t});\n\n\t\tif($('.form_contact textarea.wpcf7-textarea').val() == \"\")\n\t\t{\n\t\t\tcheck = false;\n\t\t}\n\n\t\treturn check;\n\t}", "validInput(value) {\n if (!value)\n return this.props.eReq;\n return null;\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}", "isValid() {\n if (\n this.state.isDanger ||\n this.state.apiValue === '' ||\n this.state.apiValue === undefined\n )\n return false;\n\n return true;\n }", "function isDefinedAndNotNull(input)\r\n{\r\n if (isDefined(input))\r\n return ((input != null) && !isNaN(input));\r\n else\r\n return false;\r\n}", "function isBlank (input) {\n if (input === \"\" ) {\n return true\n } \n return false \n}", "function checkEmptyInput() {\n let isEmpty = false,\n name = document.getElementById('name').value,\n semestre1 = document.getElementById('semestre1').value,\n semestre2 = document.getElementById('semestre2').value,\n frequencia = document.getElementById('frequencia').value;\n\n if (name === '') {\n alert('O campo \"Nome\" não pode está vazio');\n isEmpty = true;\n } else if (semestre1 === '') {\n alert('O campo \"1º Semestre\" não pode está vazio');\n isEmpty = true;\n } else if (semestre2 === '') {\n alert('O campo \"2º Semestre\" não pode está vazio');\n isEmpty = true;\n } else if (frequencia === '') {\n alert('O campo \"Frequência\" não pode está vazio');\n isEmpty = true;\n }\n return isEmpty;\n}", "function isEmpty(input) {\n if ( null === input || \"\" === input ) { \n return true; \n } \n return false; \n }", "function checkEmptyInput()\r\n {\r\n var isEmpty = false,\r\n name = document.getElementById(\"name\").value,\r\n bday = document.getElementById(\"bday\").value,\r\n gender = document.getElementById(\"gender\").value;\r\n \r\n if(name === \"\"){\r\n alert(\"Name is Empty\");\r\n isEmpty = true;\r\n }\r\n else if(bday === \"\"){\r\n alert(\"Birthdate is Empty\");\r\n isEmpty = true;\r\n }\r\n else if(gender === \"\"){\r\n alert(\"Gender is Empty\");\r\n isEmpty = true;\r\n }\r\n return isEmpty;\r\n }", "function checkInput() {\n if (inputText.value === \"\") {\n hideButton();\n } else {\n showButton();\n }\n }", "function validatePresenceOf(value) {\r\n return value && value.length;\r\n }", "check_if_passed() {\n const passed = this.input_area.value === this.text;\n if (!passed) {\n console.error(this.describe() + \" failed!\");\n }\n return passed;\n }", "function validateUserInput( $input ) {\r\r\n\r\r\n\t\tvar input = $input;\r\r\n\r\r\n\t\t// Check string for #NONE# indicating no vendor type selected\r\r\n\t\tif( input === '#NONE#' ) {\r\r\n\t\t\treturn false;\r\r\n\t\t}\r\r\n\r\r\n\t\t// Check for empty or null values\r\r\n\t\tif( !input.trim() ) {\r\r\n\t\t\treturn false;\r\r\n\t\t}\r\r\n\t\t\r\r\n\t\treturn true;\r\r\n\t}", "isValid(value){\n return !isNaN(value);\n }", "check (value) {\n return !!this.parse(value);\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 val_companyName(val) {\n if (val == '') {\n alert('Please Write an Company Name');\n return false;\n } else {\n return true;\n }\n}", "function validateInput() {\n\t\tif (!name) {\n\t\t\talert('Please input a name');\n\t\t\treturn false;\n\t\t}\n\t\tif (!description) {\n\t\t\talert('Please give a small description');\n\t\t\treturn false;\n\t\t}\n\t\tif (!value) {\n\t\t\talert('Please describe the sentimental value');\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}", "function validateInput() {\n // initialize boolean to return\n var isEmpty = false;\n // check for empty input\n $(\"input.validate\").each(function () {\n console.log($(this).val());\n if ($(this).val() === \"\") {\n isEmpty = true;\n }\n });\n return isEmpty;\n }", "function validateUserInput(){\n if(arg2.length>0){\n return true\n }else {\n return false\n }\n }", "checkValue() {\n let newInput;\n newInput = this.elName.value;\n\n if (newInput === '') {\n this.initializeValues();\n this.setFurigana();\n } else {\n newInput = this.removeString(newInput);\n\n if (this.input === newInput) return; // no changes\n\n this.input = newInput;\n\n if (this.isConverting) return;\n\n const newValues = newInput.replace(kanaExtractionPattern, '').split('');\n this.checkConvert(newValues);\n this.setFurigana(newValues);\n }\n\n this.debug(this.input);\n }", "function checkSearchInput(searchInput){\n console.log(\"length\" +searchInput.length);\n if(searchInput.length <= 0){\n return false;\n }\n return true;\n}", "function checkIfFieldHasValue() {\n if($('#input1').val()) {\n bundle();\n } else {\n $('#alert-container').hide().prepend(`\n <div class=\"error alert alert-danger alert-dismissible fade show\">\n <em>Please input an equation</em>\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n `).fadeIn();\n }\n}", "function nofalsey(input){\n\n return input != false && input != 0 && input != \"\" && input != NaN && input != undefined;\n }", "function required(inputtx) \n {\n if (inputtx.value.length == 0)\n { \n alert(\"message\"); \t\n return false; \n } \t\n return true; \n }", "function is_Blank(input){\n if (input.length === 0)\n return true;\n else \n return false;\n}", "checkEmptyInput() {\n if (\n this.state.selected === \"\" ||\n this.state.date === \"\" ||\n this.state.date2 === \"\" ||\n this.state.timeStart === \"\" ||\n this.state.timeEnd === \"\"\n ) {\n alert(\"Error!Dont Leave Blank Fields!\");\n return false;\n }\n return true;\n }", "isEmpty(){\r\n return (this.value+'' === 0+'');\r\n }", "function ngModelPipelineCheckValue(arg) {\n containerCtrl.setHasValue(!ngModelCtrl.$isEmpty(arg));\n return arg;\n }", "function ngModelPipelineCheckValue(arg) {\n containerCtrl.setHasValue(!ngModelCtrl.$isEmpty(arg));\n return arg;\n }", "function validatePresenceOf(value) {\n return value && value.length;\n }", "function valInput(value) {\r\n var integer = Number.isInteger(parseFloat(value));\r\n var sign = Math.sign(value);\r\n\r\n if (integer && (sign === 1)) {\r\n return true;\r\n } else {\r\n return 'Please enter a whole number.';\r\n }\r\n}", "function checkvalue() {\n \n var searchkeyword = $.trim(document.getElementById('tags').value);\n var searchplace = $.trim(document.getElementById('searchplace').value);\n \n if (searchkeyword == \"\" && searchplace == \"\") {\n return false;\n }\n }", "function peopleCheck() {\r\n if (numberOfPeopleInput.value <= 0 || numberOfPeopleInput == undefined) {\r\n numberOfPeopleErrorMessage.innerHTML = \"Can't be zero or negative\";\r\n } else {\r\n return true;\r\n }\r\n}", "function validInput(input) {\n return isInteger(input) && input > 0\n}", "checkUserInput() {\r\n const {\r\n drugId1, drugId2, sample, dataset,\r\n } = this.state;\r\n return drugId1 !== 'Any' || sample !== 'Any' || dataset !== 'Any' || drugId2 !== 'Any';\r\n }", "function checkForInput(element) {\n var $inputContainer = $(element).parents(\".m-input-group-field\");\n\n if ($(element).val().length > 0) {\n $inputContainer.addClass(\"is-filled\");\n } else {\n $inputContainer.removeClass(\"is-filled\");\n }\n }", "function isGood(val){ \n return val !== false && val !== null && val !== 0 && val !== \"\" && val !== undefined && !Number.isNaN(val); \n }", "function val_officeName (val) {\n if (val == '') {\n alert('Please Write an Office Name');\n return false;\n } else {\n return true;\n }\n}", "function val_loadName(val) {\n if (val == '') {\n alert('Please Write an Load Name');\n return false;\n } else {\n return true;\n }\n}", "validateValue (value) {\n return TypeNumber.isNumber(value) && !isNaN(value)\n }", "function validate (input) {\n \t//ver dps..\n \treturn true;\n }", "function validateValueWithInfo(input_value) {\n\t\tif (input_value != '') {\n\t\t\tif (input_value.length > 9) {\n\t\t\t\talertInfo(\"Za długa wartości wydatku.\");\n\t\t\t\t$expenseValue.val(\"\");\n\t\t\t\treturn false;\n\t\t\t} else if ((input_value <= 0) || (input_value.match(/^0+[,.]0+$/) != null)){\n\t\t\t\talertInfo(input_value+' (Wartość wydatku musi być większa od zera.)');\n\t\t\t\treturn false;\n\t\t\t} else if (input_value >= 1000000){\n\t\t\t\talertInfo(input_value+' (Wartość wydatku musi być mniejsza niż milion.)');\n\t\t\t\treturn false;\n\t\t\t} else if ((input_value.match(/^\\d{1,6}[,.]?\\d{0,2}$/) != null) \n\t\t\t\t\t\t\t&& (input_value.match(/^\\d{1,6}[,.]$/) == null)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\talertInfo(input_value+'<br/> (Niepoprawny format wartości wydatku.)');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\talertInfo(\"Nie podano wartości wydatku.\");\n\t\treturn false;\n\t}", "function campo_vacio(campo) {\n\tif (campo.value == \"\") {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function isEmpty() {\r\n\r\n if (nameInput.value == \"\" || emailInput.value == \"\" || passInput.value == \"\"|| repassInput.value == \"\"|| phoneInput.value.value == \"\"|| ageInput.value == \"\") {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "function verifyInput(){\r\n}", "function isValid(value) {\n\t return value !== '' && value !== undefined && value !== null;\n\t}", "function isValid(value) {\n\t return value !== '' && value !== undefined && value !== null;\n\t}", "function isValid(value) {\n\t return value !== '' && value !== undefined && value !== null;\n\t}", "function isValid(value) {\n\t return value !== '' && value !== undefined && value !== null;\n\t}", "function checkEmptyInput(){\r\n var isEmpty = false;\r\n var item = document.getElementById(\"text\").value;\r\n\r\n if(item === \"\"){\r\n alert(\"write an item!!\");\r\n document.getElementById(\"text\").focus(); //dupa alerta sa faca focus pe input\r\n isEmpty = true;\r\n }\r\n return isEmpty;\r\n}", "function isNotNull(f,noalert) {\n if (f.value.length ==0) {\n return false;\n }\n return true;\n}", "function isDefined(input)\r\n{\r\n return (typeof(input) != \"undefined\");\r\n}", "function check_estimate(){ \n showLoadingGif();\n if(jQuery('#lvalue').val()==''){\n alert('Category cannot be blank');\n return false;\n }\n}", "checkValue(val){\n if(val === ''){return 0}\n return val < 0 ? 0 : val;\n }", "function validateInput(){\n\tvar api_key_input = $('#api-key-input');\n\tvar search_input = $('#summoner-name-input');\n \tif (!isEmpty(search_input) && !isEmpty(api_key_input)){\n\t\tvar selected = getSelectedOption();\n\t\t//alert(empty_checker + ' | ' + selected);\n\t\tif (selected == 'summary'){\n\t\t\tsearchSummonerStatsSummary();\n\t\t} else {\n\t\t\tsearchSummonerStatsRanked();\n\t\t}\n\t}\n}", "function checkData(caller){\n if (caller.val() == \"\"){\n // console.log(caller.parent().closest('small'));\n \n return false;\n } else {\n return true;\n }\n }", "function validate(input) {\n \"use strict\";\n if (input.length <= 0) {\n return false;\n } else {\n return true;\n }\n \n}", "function oneDigitAtLeastInput(input) {\n return /\\d+/.test(input.value);\n}", "function isBlank(a) {\n\n var result;\n\n if(typeof a !== \"string\"){\n\n result = \"Input in not a string\";\n }\n else{\n result = a.length === 0;\n }\n return result;\n}", "function checkValue(value){\n\tif(value == \"\" || value == \"null\" || value == null || value == undefined){\n\t\tvalue = \"\";\n\t}\n\treturn value;\n}", "get empty() { return !this.inputElement.value; }" ]
[ "0.8111857", "0.78716815", "0.7745731", "0.76705307", "0.76291656", "0.75072837", "0.7404344", "0.73506147", "0.730056", "0.7245602", "0.7172446", "0.714344", "0.711454", "0.70703685", "0.7021145", "0.7003248", "0.6964873", "0.6936055", "0.693212", "0.6874725", "0.67384046", "0.67297465", "0.67185515", "0.671853", "0.6710218", "0.6699908", "0.66853946", "0.6657604", "0.66432726", "0.66363406", "0.660987", "0.6586515", "0.6553446", "0.6540675", "0.6527935", "0.6524594", "0.6518791", "0.6492105", "0.64884275", "0.64875555", "0.6485886", "0.6482466", "0.64320356", "0.64233506", "0.6418228", "0.6409934", "0.64021516", "0.63909686", "0.6388482", "0.63812166", "0.6380141", "0.637819", "0.63711596", "0.63590455", "0.63584083", "0.63581055", "0.63570195", "0.6353766", "0.6351863", "0.6333981", "0.6331134", "0.6330707", "0.63257605", "0.63212806", "0.6310326", "0.630808", "0.63060224", "0.6301497", "0.6301497", "0.6298776", "0.62926364", "0.62887794", "0.6277788", "0.6272229", "0.62705696", "0.62680584", "0.6261755", "0.62616795", "0.6258945", "0.62578404", "0.6250723", "0.62483555", "0.62474775", "0.6245771", "0.6241804", "0.6241779", "0.6241779", "0.6241779", "0.6241779", "0.62384003", "0.62130886", "0.62103164", "0.6209413", "0.62091035", "0.6196082", "0.61942816", "0.618976", "0.6187166", "0.6182835", "0.61699086", "0.6167557" ]
0.0
-1
Toggles the collapse menu of the navbar
toggle() { this.setState({ isOpen: (!this.state.isOpen) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function collapse() {\n $('.navbar-toggler').trigger('click');\n }", "function toggleMenu() {\n\t\ttoggle.classList.toggle('navbar-collapsed');\n\t\t// collapse.classList.toggle('mtn-navbar__collapse');\n\t\tcollapse.classList.toggle('in');\n\t}", "toggleMenu(collapse) {\n collapse.classList.toggle('collapse');\n collapse.classList.toggle('in');\n }", "function toggleMenu() {\n if ($('#menu-entries').attr('class').split(' ').includes('collapse')) {\n $('#menu-entries').attr('class', 'collapse.show navbar-collapse');\n } else {\n $('#menu-entries').attr('class', 'collapse navbar-collapse');\n }\n}", "function collapseMenu() {\n $('.navbar-collapse').collapse('hide');\n}", "toggleNavbar() {\n this.setState({\n collapsed: !this.state.collapsed\n });\n }", "collapse () {\n this.button.addEventListener('click', (e) => {\n this.button.classList.toggle('collapsed')\n this.button.classList.toggle('is-active')\n\n if (!this.button.classList.contains('is-active')) {\n this.navbarCollapse.style.animation = 'fadeOutLeft .5s forwards'\n } else {\n this.navbarCollapse.style.animation = 'fadeInLeft .5s forwards'\n }\n\n if (this.navbarCollapse.classList.contains('overlay')) {\n this.navbarCollapse.classList.toggle('hide')\n } else {\n this.navbarCollapse.classList.add('hide')\n }\n })\n }", "function toggleNavbar(collapseID) {\n\tdocument.getElementById(collapseID).classList.toggle(\"hidden\");\n\tdocument.getElementById(collapseID).classList.toggle(\"bg-white\");\n\tdocument.getElementById(collapseID).classList.toggle(\"dark:bg-gray-900\");\n\tdocument.getElementById(collapseID).classList.toggle(\"m-2\");\n\tdocument.getElementById(collapseID).classList.toggle(\"py-3\");\n\tdocument.getElementById(collapseID).classList.toggle(\"px-6\");\n}", "function navbarCollapse() {\n if ($(window).width() < 992) {\n $(document).on('click', function (event) {\n var clickover = $(event.target);\n var _opened = $(\"#navbar-collapse\").hasClass(\"in\");\n if (_opened === true && !(clickover.is('.dropdown'))) {\n $(\"button.navbar-toggle\").trigger('click');\n }\n });\n\n $('.dropdown').unbind('click');\n $('.dropdown').on('click', function () {\n $(this).children('.dropdown-menu').slideToggle();\n });\n\n $('.dropdown *').on('click', function (e) {\n e.stopPropagation();\n });\n }\n }", "toggleNav() {\n $('.nav-toggle').toggleClass('is-active');\n $('.nav-menu').toggleClass('is-active');\n }", "function collapseNav(){\n var navbarButton_li = $('#navbarButton_li');\n navbarButton_li.css('list-style', 'none');\n \n $('#navbarButton').click(function(){\n $(this).next().toggle()});\n /* \n navbarButton_li.click(function(){\n $(this).find(\"ul\").css('display', 'block');\n });\n navbarButton_li.mouseleave(function(){\n $(this).find(\"ul\").css('display', 'none');\n });\n */\n}", "function navbarToggle() {\n $('#navbar').classList.toggle('toggle-hidden') \n}", "function toggleMobileMenu(e) {\n e.preventDefault();\n toggleButtonIcon();\n if (!navListOpen) {\n navListOpen = true;\n gsap.to(\".navbar__list\", 0.5, {\n height: \"auto\",\n });\n } else {\n navListOpen = false;\n gsap.to(\".navbar__list\", 0.5, {\n height: \"0\",\n });\n }\n}", "function navCollapser()\n{\n $('.navbar').on('show', function () {\n var actives = $(this).find('.collapse.in')\n , hasData\n if (actives && actives.length) {\n hasData = actives.data('collapse')\n if (hasData && hasData.transitioning) return\n actives.collapse('hide')\n hasData || actives.data('collapse', null)\n }\n })\n}", "toggle() {\n this.setState({ collapse: !this.state.collapse });\n }", "collapseMenu() {\r\n\t}", "function toggleNavbar() {\n\n (burger.classList.contains('open'))? burger.classList.remove('open'): burger.classList.add('open'); \n navMenu.classList.toggle('active-navbar');\n \n}", "function collapse() {\n\t\tif($menu.hasClass('inline-menu')){\n\t\t\t$menu.removeClass('inline-menu').addClass('dropdown-menu');\n\t\t\t$button.removeClass('visible-xs');\n\t\t\t$edit.removeClass('hidden-xs');\n\t\t\t$edit.removeClass('hidden-sm');\n\t\t}\n\t}", "function collapseMenu() {\n var windowsize = $window.width();\n if (windowsize < hamburgerWidth) {\n // hamburger menu\n $(\".ked-navigation .sidebar\").css(\"height\", \"\");\n } else {\n // normal menu\n $(\".ked-navigation .sidebar\").css(\"width\", \"\");\n }\n pinIcon.css(\"opacity\", 0);\n $(\".ked-navigation .logo span\").css(\"opacity\", \"0\");\n $(\".ked-navigation .offcanvas-nav li a span\").css(\"opacity\", \"0\");\n $(\".ked-navigation .offcanvas-nav li a .state-indicator\").css(\"opacity\", \"0\");\n $(\".ked-navigation .search .search-field\").css(\"opacity\", \"0\");\n $(\".ked-navigation .offcanvas-nav li a span\").css(\"opacity\", \"0\");\n $(\".subnav\").stop().hide();\n $(\".state-indicator\").removeClass('fa-caret-up').addClass('fa-caret-down');\n }", "function toggleMenu() {\n menuNav.classList.toggle('menu-toggle');\n }", "toggle() {\n\t\tthis.setState(state => ({ collapse: !state.collapse }));\n\t}", "function toggleNav(){\n\tdocument.getElementById('nav-toggle').classList.toggle('hide-menu');\n}", "function openCloseNav (e) {\n // Select .nav-collapse within same .navbar as current button\n var nav = $(e.target).closest('.navbar').find('.nav-collapse');\n if (nav.height() != 0) {\n // If it has a height, hide it\n nav.height(0);\n } else {\n // If it's collapsed, show it\n nav.height('auto');\n }\n}", "function navtoggle(){\n\tvar navTop = document.querySelector('.nav-top');\n\t\n\tdocument.querySelector('.nav-btn').addEventListener('click', function(e){\n\t\te.preventDefault(); \n\t\n\t\t//if the \n\t\tif (navTop.getAttribute('data-state') == 'expanded'){\n\t\t\t\n\t\t\tnavTop.setAttribute('data-state', 'collapsed');\n\t\t\tthis.setAttribute('data-state','inactive');\n\t\t}else{\n\t\t\n\t\t\tnavTop.setAttribute('data-state', 'expanded');\n\t\t\tthis.setAttribute('data-state','active');\n\t\t}\n\t});\n}", "_toggleCollapsedState() {\n const that = this;\n\n if (!that.collapsible) {\n return;\n }\n\n if (!that.collapsed) {\n that.collapse();\n }\n else {\n that.expand();\n }\n }", "function openCloseNav( e ) {\n // Select .nav-collapse within same .navbar as current button\n var nav = $( e.target ).closest( '.navbar' ).find( '.nav-collapse' );\n\n if( nav.height() != 0 ) {\n // If ot has a height, hide it\n nav.height( 0 );\n } else {\n // If it's collapsed, show it\n nav.height( 'auto' );\n }\n}", "function scrollToCollapsed(target, mTarget)\n{\n $(target).collapse('show');\n if(mTarget != '')\n $(mTarget).scrollView();\n else $(target).scrollView();\n if($('.navbar-toggle').is(':visible'))\n $('.navbar-toggle').click()\n}", "function dropDown() {\n\t\t$navButton = $('.navbar-toggler');\n\t\t$navButton.on('click', () => {\n\t\t\t$('#navbarTogglerDemo03').toggle('collapse');\n\t\t});\n\t}", "function toggleMenu() {\n navUl.classList.toggle(\"open\");\n}", "function toggleNavExpansion() {\n $(\"#menu-toggle\").click(function() {\n if ($(\"#navbar\").hasClass(\"reduced\")) {\n $(\"#navbar\").removeClass(\"reduced\");\n $(\"#navbar\").addClass(\"expanded\");\n } else {\n $(\"#navbar\").removeClass(\"expanded\");\n $(\"#navbar\").addClass(\"reduced\");\n }\n });\n\n $(\".extended-list-item\").click(e => {\n $(\"#navbar\").removeClass(\"expanded\");\n $(\"#navbar\").addClass(\"reduced\");\n $(\".hamburger-menu\").removeClass(\"active\");\n });\n}", "toggle() {\n this.collapsed = !this.collapsed\n }", "toggle() {\n this.collapsed = !this.collapsed\n }", "function toggleCollapse(selector) {\r\n\t$(selector).collapse('toggle');\r\n}", "function close_toggle() {\n if ($(window).width() <= 768) {\n $('.navbar-collapse a').on('click', function () {\n $('.navbar-collapse').collapse('hide');\n });\n }\n else {\n $('.navbar .navbar-inverse a').off('click');\n }\n}", "function toggleMenu() {\n const navbarLinks = document.querySelector(\"ul\");\n navbarLinks.classList.toggle('active');\n}", "function toggleMenu() {\n const burger = document.querySelector('.navbar-burger');\n const mobileMenu = document.getElementsByClassName('navbar-menu-link');\n for (let i = 0; i < mobileMenu.length; i += 1) {\n mobileMenu[i].classList.toggle('open');\n }\n burger.classList.toggle('open');\n}", "function close_toggle() {\r\n if ($(window).width() <= 768) {\r\n $('.navbar-collapse a').on('click', function () {\r\n $('.navbar-collapse').collapse('hide');\r\n });\r\n }\r\n else {\r\n $('.navbar .navbar-inverse a').off('click');\r\n }\r\n }", "function toggleNavbar(e) {\n uiElements.menuBars.classList.toggle('change');\n uiElements.overlay.classList.toggle('change');\n if (uiElements.navItems[0].classList.contains('slide-in-1')) {\n slideNavItems('out', 'in');\n } else {\n slideNavItems('in', 'out');\n }\n}", "function closeNav() {\n $('.navHeaderCollapse').collapse('hide');\n}", "function hamburgerMenu() {\n mainNav.classList.toggle('slide-toggle');\n hamNavCon.classList.toggle('slide-toggle');\n hamburger.classList.toggle('expanded');\n }", "function toggleMobileMenu() {\n if (mobileMenuVisible) {\n //close menu\n nav.style.removeProperty(\"top\");\n burgerMenuSpan.forEach(span => {\n span.style.removeProperty(\"background\");\n });\n } else {\n //open menu\n nav.style.top = \"0px\";\n burgerMenuSpan.forEach(span => {\n span.style.background = \"#e9e9e9\";\n });\n }\n mobileMenuVisible = !mobileMenuVisible;\n}", "function collapse() {\n\t\tif($element.hasClass('inline-menu')){\n\t\t\t$element.removeClass('inline-menu');\n\t\t\t$submenu.addClass('dropdown-menu');\n\t\t\t$button.attr('data-toggle', 'dropdown');\n\t\t\t$button.children('i.fa').removeClass('visible-xs');\n\t\t\t$submenu.children('li:first').removeClass('visible-xs');\n\t\t}\n\t}", "function toggleNavbar() {\n navItemContainer.classList.toggle(\"open-nav-items\")\n}", "function close_toggle() {\r\n if ($(window).width() <= 768) {\r\n $('.navbar-collapse a').on('click', function () {\r\n $('.navbar-collapse').collapse('hide');\r\n });\r\n }\r\n else {\r\n $('.navbar .navbar-inverse a').off('click');\r\n }\r\n }", "function toggleNav() {\n if (nav.hidden) {\n openNav()\n nav.hidden = false\n } else {\n closeNav()\n nav.hidden = true\n }\n}", "function toggleMenu() {\n document.getElementById(\"nav-menu\").classList.toggle(\"show-menu\");\n}", "function toggleNav() {\n if (menuOpen) {\n closeNav();\n } else {\n openNav();\n }\n}", "closeMenu() {\n if (!this.state.collapsed) {\n this.setState({\n collapsed: true,\n });\n }\n }", "function toggleMenu() {\n if (nav.classList.contains(\"show-menu\")) {\n nav.classList.remove(\"show-menu\")\n } else {\n nav.classList.add(\"show-menu\")\n }\n}", "function close_toggle() {\n if ($(window).width() <= 768) {\n $('.navbar-collapse a').on('click', function () {\n $('.navbar-collapse').collapse('hide');\n });\n }\n else {\n $('.navbar .navbar-default a').off('click');\n }\n }", "function collapseMenu(){\n\t\tjQuery('#noqbot-navigationm-mobile .menu-item-has-children').prepend('<span class=\"noqbot-dropdowarrow\"><i class=\"fa fa-angle-down\"></i></span>');\n\t\tjQuery('#noqbot-navigationm-mobile .menu-item-has-children span').on('click', function() {\n\t\t\tjQuery(this).next().next().slideToggle(300);\n\t\t\tjQuery(this).parent('#noqbot-navigationm-mobile .menu-item-has-children').toggleClass('noqbot-open');\n\t\t});\n\t}", "function CloseNav() {\n $(\".navbar-collapse\").stop().css({ 'height': '1px' }).removeClass('in').addClass(\"collapse\");\n $(\".navbar-toggle\").stop().removeClass('collapsed');\n }", "function close_toggle() {\n if ($(window).width() <= 768) {\n $('.navbar-collapse a').on('click', function() {\n $('.navbar-collapse').collapse('hide');\n });\n }\n else {\n $('.navbar .navbar-default a').off('click');\n }\n}", "function toggleNavbarButton(){\n\t\tjq(\"#mainHeader #mainMenu .navbar-toggle\").click(function(){\n\t\t\tjq(\"#mainHeader #mainMenu .navbar-toggle i.menu-icon\").toggleClass(\"close\");\n\t\t\tjq(\"#mainHeader #mainMenu .navbar-header\").toggleClass(\"collapsed\");\n\n\t\t\tif(jq(window).innerWidth() <= 768){\n\t\t\t\tif(!jq(\"#mainHeader #mainMenu #navbar\").hasClass(\"in\")){\n\t\t\t\t\tjq(\"#mainHeader #mainMenu .navbar-toggle\").attr(\"style\", \"background-color: transparent !important\");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tjq(\"#mainHeader #mainMenu .navbar-toggle\").attr(\"style\", \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function navClick(link){\n window.location.href=link;\n var mobileNavElement = document.getElementById(\"bs-example-navbar-collapse-1\");\n mobileNavElement.className=\"navbar-collapse collapse\";\n mobileNavElement.setAttribute(\"aria-expanded\", false);\n \n}", "menuToggle(event) {\n var navItem = document.getElementsByTagName('nav')[0];\n if ('block' === navItem.style.display) {\n navItem.style.display = 'none';\n } else {\n navItem.style.display = 'block';\n navItem.className = navItem.className + ' menuhidden';\n }\n\n }", "function toggleCollapse(event){\n let collapseID = event.currentTarget.getAttribute(\"data-target\")\n document.querySelector(collapseID).classList.toggle(\"hidden\");\n}", "function toggleNavbarIcon() {\r\n if (navbarIconMenu.classList.contains('navbar-open')) {\r\n openNavbar();\r\n } else if (navbarIconMenu.classList.contains('navbar-close')) {\r\n closeNavbar();\r\n }\r\n }", "function mobileMenu() {\n document.getElementsByClassName('affix')[0].classList.toggle('nav-toggle')\n document.getElementById('hamburger').children[0].classList.toggle('opened')\n document.getElementById('hamburger').children[1].classList.toggle('opened')\n}", "function mobileMenu() {\n hamburger.classList.toggle(\"active\");\n navMenu.classList.toggle(\"active\");\n}", "function toggleHamburger(){\r\n navbar.classList.toggle(\"showNav\")\r\n ham.classList.toggle(\"showClose\")\r\n hamClose.classList.toggle(\"showClose\")\r\n }", "toggleMenu(){\n this.menuContent.toggleClass('site-nav--is-visible');\n this.siteHeader.toggleClass('site-header--is-expanded');\n this.menuIcon.toggleClass('site-header__menu-icon--close-x');\n this.siteHeaderLogo.toggleClass ('site-header__logo--transparent');\n }", "collapse() {\n const that = this;\n\n if (!that.collapsible || that.collapsed) {\n return;\n }\n\n that.collapsed = true;\n }", "function navbarToggle() {\r\n\tif ($(window).width() <= 767) { \r\n\t\t$('.nav-style > li > a').on('click', function(){\r\n\t\t\t$('.navbar-toggle').click();\r\n\t\t});\r\n\t}\r\n}", "function classToggle() {\n const navs = document.querySelectorAll('.Navbar__Items')\n navs.forEach(nav => nav.classList.toggle('Navbar__ToggleShow'));\n }", "function togglemenu(){\n this.isopen = !this.isopen;\n }", "function collapseMenu(){\n\t\t$('#tg-navigation ul li.menu-item-has-children').prepend('<span class=\"tg-dropdowarrow\"><i class=\"icon-chevron-right\"></i></span>');\n\t\t$('#tg-navigation ul li.menu-item-has-children span').on('click', function() {\n\t\t\t$(this).next().next().slideToggle(300);\n\t\t\t$(this).parent('#tg-navigation ul li.menu-item-has-children').toggleClass('tg-open');\n\t\t});\n\t}", "function doToggle(element) {\n if (isCollapsed(element)) {\n removeClass(element, 'collapse');\n delete g_collapsed[element.id];\n g_n_collapsed--;\n } else {\n addClass(element, 'collapse');\n g_collapsed[element.id] = true;\n g_n_collapsed++;\n }\n}", "function toggleMenu(){\r\n\t\tlet navigation = document.querySelector('.navigation');\r\n\t\tnavigation.classList.toggle('opensidebar');\r\n\t}", "function closeNavbarMobile() {\n $(document).click(function(event) {\n var clickedArea = $(event.target);\n var _opened = $(\".navbar-collapse\").hasClass(\"show\");\n if (_opened === true && !clickedArea.hasClass(\"navbar\")) {\n $(\"button.navbar-toggler\").click();\n }\n });\n}", "toggleNav() {\n if ($(\"#offcanvas-menu-react\").hasClass(\"navslide-show\")) {\n $(\"#offcanvas-menu-react\").removeClass(\"navslide-show\").addClass(\"navslide-hide\")\n $(\".navbar\").removeClass(\"navslide-show\").addClass(\"navslide-hide\")\n $(\".nav-canvas\").removeClass(\"navslide-show\").addClass(\"navslide-hide\")\n }\n else {\n $(\".nav-canvas\").css(\"position\", \"relative\")\n $(\"#offcanvas-menu-react\").removeClass(\"navslide-hide\").addClass(\"navslide-show\")\n $(\".navbar\").removeClass(\"navslide-hide\").addClass(\"navslide-show\")\n $(\".nav-canvas\").removeClass(\"navslide-hide\").addClass(\"navslide-show\")\n }\n }", "function toggleMobileNavigation() {\n nodes.htmlEl.classList.toggle('nav-open');\n }", "function toggle()\n {\n menuBtn.classList.toggle(\"open\");\n menuItems.classList.toggle(\"open\");\n }", "function toggleHamburgerMenu() {\n $('.hamburger-icon').click(event => {\n $('.main-menu-link').toggleClass('toggle-links');\n });\n}", "function toggleHamburgerMenu() {\n $('.hamburger-icon').click(event => {\n $('.main-menu-link').toggleClass('toggle-links');\n });\n}", "function toggleHamburgerMenu() {\n $('.hamburger-icon').click(event => {\n $('.main-menu-link').toggleClass('toggle-links');\n });\n}", "function toggleHamburger() {\n navbar.classList.toggle(\"showNav\");\n ham.classList.toggle(\"showClose\");\n}", "function toggleHamburger(){\r\n navbar.classList.toggle(\"showNav\")\r\n ham.classList.toggle(\"showClose\")\r\n}", "function toggleMenu(e) {\n e.preventDefault();\n $mainNav.slideToggle(function (){\n if ($mainNav.is(':hidden')) {\n $mainNav.removeAttr('style');\n }\n });\n $menuToggle.toggleClass('open');\n }", "function collapseNavbar() {\n if ($(\".navbar\").offset().top > 50) {\n $(\".navbar-fixed-top\").addClass(s.top_nav_collapse);\n } else {\n $(\".navbar-fixed-top\").removeClass(s.top_nav_collapse);\n }\n }", "function toggleHamburger() {\n navbar.classList.toggle(\"showNav\");\n ham.classList.toggle(\"showClose\");\n}", "function togglemenu(){\r\n\t\tvar menuToggle = document.querySelector('.toggle');\r\n\t\tvar menu = document.querySelector('.menu');\r\n\t\tmenuToggle.classList.toggle('active');\r\n\t\tmenu.classList.toggle('active');\r\n\t}", "function closeBurgerMenu(e) {\n\tvar clickedOn = $(e.target) ;\n\tvar navOpened = $('.navbar-collapse').hasClass('show') ;\n\tif (navOpened === true && !clickedOn.hasClass('navbar-toggler')) {\n\t\t$('.navbar-toggler').click() ;\n\t}\n}", "onClickToggleCollapse (event) {\n return\n }", "function toggleList() {\n $log.info(' NavbarController $mdSidenav=');\n $mdSidenav('left').toggle();\n }", "function toggleNavMenu() {\n document.getElementById(\"nav-hidden-menu\").classList.toggle(\"ninja\")\n \n}", "function toggleHamburger(){\n navbar.classList.toggle(\"showNav\")\n ham.classList.toggle(\"showClose\")\n}", "function toggleNav() {\n const nav = body.querySelector('#nav');\n \n nav.classList.toggle('toggle-nav');\n}", "function toggleMenu(event) {\n\tif (event.type === \"touchstart\") event.preventDefault();\n\n\n\tconst navigationMenu = document.querySelector(\".c-menu\");\n\n\tnavigationMenu.classList.toggle(\"is-menu--active\");\n\n\tconst activeNavigation = navigationMenu.classList.contains(\n\t\t\"is-menu--active\"\n\t);\n\tevent.currentTarget.setAttribute(\"aria-expanded\", activeNavigation);\n\n\n\tif (activeNavigation) {\n\t\tevent.currentTarget.setAttribute(\"aria-label\", \"Fechar Menu\");\n\t\t\n\t} else {\n\t\tevent.currentTarget.setAttribute(\"aria-label\", \"Abrir Menu\");\n\t}\n}", "function toggleSectionCollapse(toggle){\n if (toggle == \"open\") {\n $(\"#accordion .collapse\").removeClass('hide');\n $(\"#accordion .collapse\").addClass('show');\n defaultHeroBanner();\n $(\"#open-close\").children().children('.open-close-text').text(\"Close all \");\n $(\"#open-close\").children().children('i').removeClass(\"fa-level-down-alt\").addClass(\"fa-level-up-alt\");\n } else if (toggle == \"closed\") {\n $(\".collapse\").removeClass('show');\n $(\".collapse\").addClass('hide');\n defaultHeroBanner();\n $(\"#open-close\").children().children('.open-close-text').text(\"Open all \");\n $(\"#open-close\").children().children('i').removeClass(\"fa-level-up-alt\").addClass(\"fa-level-down-alt\");\n }\n}", "function toggleNav() {\n\tvar ele = document.getElementById(\"mobile-navigation-toggle\");\n\tvar text = document.getElementById(\"mobile-nav-button-link\");\n\tif(ele.style.display == \"block\") {\n \t\tele.style.display = \"none\";\n \t}\n\telse {\n\t\tele.style.display = \"block\";\n\t}\n}", "function toggleMobileMenu() {\n \ttoggleIcon.addEventListener('click', function(){\n\t\t this.classList.toggle(\"open\");\n\t\t mobileMenu.classList.toggle(\"open\");\n \t});\n }", "function toggleNav() {\n document.querySelector(\".sm-nav\").classList.toggle(\"hidden\");\n document.querySelector(\".sm-nav\").classList.toggle(\"opacity-0\");\n}", "function toggleMenu() {\n document.querySelector('.main-nav').classList.toggle('display-menu');\n document.querySelector('.screen').toggleAttribute('hidden');\n}", "function initNavbarToggle() {\n $('.navbar-toggle').on('click', function(e) {\n e.preventDefault();\n $('body').toggleClass('nav-active');\n\n });\n}", "toggleCollapse() {\n this.setState({ isOpen: !this.state.isOpen })\n }", "function toggle() {\n const state = isActiveMenuState();\n const burgerMenuMarketingImage = document.querySelector('.js-burger-menu-marketing-widget__img');\n\n initLayeredMenuState();\n\n if (state) { // closing the menu\n switchClass(document.body, 'nav-is-closed-body', 'nav-is-open-body');\n switchClass(getContentWrapper(), 'nav-is-closed', 'nav-is-open');\n switchClass(getCurtain(), 'nav-is-closed-curtain', 'nav-is-open-curtain');\n switchClass(getButton(), INACTIVE_STATE_CLASS, ACTIVE_STATE_CLASS);\n } else { // opening the menu\n switchClass(document.body, 'nav-is-open-body', 'nav-is-closed-body');\n switchClass(getContentWrapper(), 'nav-is-open', 'nav-is-closed');\n switchClass(getCurtain(), 'nav-is-open-curtain', 'nav-is-closed-curtain');\n switchClass(getButton(), ACTIVE_STATE_CLASS, INACTIVE_STATE_CLASS);\n\n // lazyload the image for the burger-menu-marketing widget\n if (burgerMenuMarketingImage) {\n lazyLoading.lazyLoadImage(burgerMenuMarketingImage);\n }\n }\n\n triggerMenuStateEvent(state);\n}", "function toggleBurger() {\n\t\tvar toggles = $(\".c-hamburger\");\n\n\t\ttoggles.click(function(e){\n\t\t\te.preventDefault();\n\t\t\t$(this).toggleClass('is-active');\n\t\t\t$(\"#rhd-nav-menu\").slideToggle();\n\t\t});\n\t}", "function collapseSubMenu() {\n navbarMenu.querySelector('.menu-item-has-children.active .sub-menu').removeAttribute('style');\n navbarMenu.querySelector('.menu-item-has-children.active').classList.remove('active');\n }", "collapse () {\n this.root.toggle(true, false);\n }", "function toggleMobileSubnav(e) {\n var clicked = e.currentTarget.parentElement;\n var current = document.querySelectorAll(\".is-open\");\n\n if (clicked.classList.contains(\"is-open\")) {\n clicked.classList.remove(\"is-open\");\n } else if (current.length) {\n current[0].classList.remove(\"is-open\");\n clicked.classList.add(\"is-open\");\n } else {\n clicked.classList.add(\"is-open\");\n }\n e.preventDefault();\n e.stopPropagation();\n}" ]
[ "0.82967776", "0.82390314", "0.7836361", "0.76158655", "0.74567425", "0.7431856", "0.73397756", "0.7267149", "0.7211442", "0.71399754", "0.70945776", "0.7093044", "0.70641786", "0.7049426", "0.70408", "0.7006897", "0.70055026", "0.7003146", "0.69993573", "0.6976472", "0.69709045", "0.69316274", "0.69273245", "0.6915577", "0.69099116", "0.6894168", "0.68892336", "0.683991", "0.6814946", "0.6810932", "0.68047696", "0.68047696", "0.6802852", "0.67993623", "0.679664", "0.6783981", "0.6778112", "0.67675555", "0.67624193", "0.675889", "0.67556137", "0.6743542", "0.67328393", "0.6723856", "0.672364", "0.6718538", "0.6716469", "0.67131436", "0.6709527", "0.6704034", "0.670228", "0.6700197", "0.66963476", "0.66941416", "0.6685485", "0.667902", "0.66520965", "0.6647425", "0.66258067", "0.6600884", "0.65947455", "0.6591229", "0.65885246", "0.6587602", "0.6575979", "0.6563475", "0.6546646", "0.65336215", "0.6527802", "0.6526656", "0.6516265", "0.6508932", "0.65068555", "0.6499841", "0.6499841", "0.6499841", "0.64844316", "0.648251", "0.6475591", "0.64591455", "0.64493686", "0.64460564", "0.6436895", "0.64337116", "0.64265245", "0.64132756", "0.6410555", "0.64105374", "0.64080596", "0.6396868", "0.6386525", "0.6386325", "0.6382098", "0.63709265", "0.6370655", "0.6367745", "0.635955", "0.63523716", "0.633676", "0.6326617", "0.6321855" ]
0.0
-1
this method works in the case where you insert at the position this.length
insert(index,value) { if (index < 0 || index>this.length){ throw new Error('Index error') } if (this.length >= this._capacity){ this._resize((this.length + 1)*Array.SIZE_RATIO) } Memory.copy(this.ptr+index+1,this.ptr+index,this.length-index) this.length ++ this.set(index,value) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "insert(index_num, value){\n if(index_num<0 || index_num>this.length){\n console.log(\"INSERT - false\");\n return false;\n }\n if(index_num===0){\n this.unshift(value);\n console.log(\"INSERT using UNSHIFT - true\");\n return true;\n } \n if(index_num===this.length){\n this.push(value);\n console.log(\"INSERT using PUSH - true\");\n return true;\n } \n let newNode = new Node(value);\n let before_position = this.get(index_num-1); // 1. we neet to find item at the position one before!!\n let needed_position = before_position.next;\n before_position.next = newNode;\n newNode.next = needed_position;\n this.length +=1;\n console.log(\"INSERT - true\");\n return true;\n }", "insert(val, idx) {\n // Accept val and idx\n // Check if the idx is valid: less than zero or greater than or eqaul to this.length\n // return false. \n if(idx < 0 || idx > this.length) return false;\n // if the index is 0.\n if(idx === 0) {\n // call unshift.\n this.unshift(val);\n // return true.\n return true;\n }\n // if index is the same as the length -1 push. \n if(idx === this.length ) {\n this.push(val);\n return true;\n }\n // Create a newNode with val. \n let newNode = new Node(val);\n // Create a foundNode call get with idx.\n let foundNode = this.get(idx - 1);\n // Set newNode next to foundNode\n newNode.next = foundNode.next;\n // Set foundNode.next to newNode. \n foundNode.next = newNode;\n // Set NewNode.prev to foundNode\n newNode.prev = foundNode;\n // Set NowNOde.next.prev to newNode.\n newNode.next.prev = newNode;\n // increment length\n this.length++;\n // return true.\n return true;\n }", "insert(index, value) {\n if(index > this.length) {\n console.log(`add to the end`)\n return this.append(value);\n } else if (index === 0) {\n console.log(`Invalid`)\n return undefined;\n }\n\n const newNode = new Node(value);\n const previusPointer = this.getTheIndex(index - 1);\n const holdingPointer = previusPointer.next;\n newNode.prev = previusPointer\n newNode.next = holdingPointer;\n previusPointer.next = newNode;\n holdingPointer.prev = newNode;\n this.length++;\n return this;\n }", "insert(index, val){\n if(index < 0 || index > this.length) return undefined;\n if(index === 0) return !!this.unshifting(val);\n if(index === this.length) return !!this.push(val);\n \n let newNode = new Node(val);\n let beforeNode = this.get(index-1);\n let afterNode = beforeNode.next;\n\n beforeNode.next = newNode;\n newNode.prev = beforeNode;\n afterNode.prev = newNode;\n newNode.next = afterNode;\n\n this.length++;\n console.log(true);\n }", "insert(index, val) {\n // check if the index less than zero ang greater than the length.\n if(index < 0 || index > this.length) {\n return false;\n }\n // if the index is the same as length use push.\n if(index === this.length){\n this.push(val);\n return true;\n }\n // if the index is zero use unshift. \n if(index === 0) {\n this.unshift(val);\n return true;\n }\n // get the node at the target position\n let targetNode = this.get(index);\n // find the node before the target index.\n let beforeTargetNode = this.get(index - 1);\n // Create new Node with val. \n let newNode = new Node(val);\n // set the next prop on the node be the new node. \n newNode.next = targetNode;\n // set the before target node next prop to the new Node. \n beforeTargetNode.next = newNode;\n // increment the length\n this.length++;\n\n // return true.\n return true;\n }", "insert(r) {\n r = cobalt.range(r);\n var s = this;\n for (var i=r.count-1; i>=0; i--) {\n s = insertLength(s, r.get(i).start, r.get(i).size);\n }\n return s;\n }", "insert(pos, val){\r\n\r\n if(pos > this.length || pos < 0) return false;\r\n\r\n if(pos === this.length){\r\n this.push(val);\r\n }else if(pos === 0){\r\n this.unshift(val);\r\n }else{\r\n let selectedNode = this.getNode(pos-1);\r\n let oldNext = selectedNode.next;\r\n\r\n let newNode = new Node(val);\r\n selectedNode.next = newNode;\r\n newNode.next = oldNext; \r\n newNode.prev = selectedNode;\r\n selectedNode.prev = newNode;\r\n this.length += 1;\r\n }\r\n\r\n return true;\r\n\r\n }", "insert(index, value) {\n //si el valor del indice es mayor a la longitud lo agrega de último\n if (index >= this.length) {\n return this.append(value);\n }\n\n const newNode = new Node(value);\n //primer pointer guarda el pointer del elemento anterior a donde vamos a insertar\n const firstPointer = this.getTheIndex(index - 1);\n //es el segundo pointer, el nodo que va después del que vamos a agregar\n const holdingPointer = firstPointer.next;\n //unimos el first pointer con el nuevo nodo\n firstPointer.next = newNode;\n //unimos el nuevo nodo con el segundo pointer\n newNode.next = holdingPointer;\n\n this.length++;\n return this;\n }", "insert(ind, val) {\n let nodeAtIndex = this.get(ind);\n let nodeAtPriorIndex = this.get(ind - 1);\n let newNode = new Node(val);\n\n if (ind > length || ind < 0 || this.length === 0) return;\n if (nodeAtIndex && nodeAtPriorIndex) {\n nodeAtPriorIndex.next = newNode;\n newNode.next = nodeAtIndex;\n this.length += 1;\n return true;\n } else if (!nodeAtIndex && nodeAtPriorIndex) {\n !!this.push(val);\n } else if (nodeAtIndex && !nodeAtPriorIndex) {\n !!this.unshift(val);\n }\n }", "insertAt(index, item) {\n // loop until it reaches index to modify\n for (let i = this.length; i >= index; i--) {\n // sets a new length to the object while opening the modified index\n this.data[i] = this.data[i - 1];\n }\n\n // add value to empty index\n this.data[index] = item;\n\n // increase length\n this.length++;\n\n return this.data;\n }", "insert(index, val) {\n //create a new node with the given value\n let newnode = new Node(val);\n //if index > length or smaller then zero then return false\n if (index > this.length || index < 0) {\n return false;\n }\n //if index is equal to 0 then add a new element in front {use unshifting method}\n if (index === 0) {\n this.unshifting(val);\n return true\n } else\n //if index is equal to length then add a new element in last {use push method }\n if (this.length === index) {\n this.push(val);\n return true\n }\n //get method return the specified indexed node \n //store the index -1 node in previous\n let previousnode = this.get(index - 1);\n //store index node in next node\n let nextnode = previousnode.next;\n //point the previous node --> to the new node and point new node ----> to the next node\n previousnode.next = newnode;\n newnode.next = nextnode;\n //increament the length\n this.length++;\n return true;\n }", "insert(element) {\n this.list[this.size] = element;\n this.size = this.size + 1;\n }", "insert(index, value) { // adding a node by a certain position\n if (index < 0 || index > this.length) return false\n if (index === 0) this.unshift(value)\n if (index === this.length) this.push(value)\n\n let node = new Node(value)\n let prevNode = this.get(index - 1)\n let nextNode = prevNode.next\n\n prevNode.next = node\n node.prev = prevNode\n node.next = nextNode\n nextNode.prev = node\n\n this.length++\n return true\n }", "insert(index, val) {\n\n //if index is less than zero or greater than the length return false;\n if (index < 0 || index > this.length) return false;\n //if index is equal to the length of the list call push(val)\n if (index === this.length) {\n this.push(val);\n return true;\n }\n //if index is equal to zero call unshift(val)\n else if (index === 0) {\n this.unshift(val);\n return true;\n }\n else {\n //creating new node with the value\n let node = new Node(val);\n let pre = this.get(index - 1); // getting previous elemnt \n node.next = pre.next;// setting new node next property to the previous element next property\n pre.next = node; //setting previous element next property to new node\n this.length++; //incrementing the length by 1\n return true;\n }\n\n }", "insert(index, value) {\n if (index < 0 || index > this.length) return false;\n if (index == this.length) return !!this.push(value);\n if (index == 0) return !!this.unshift(value);\n let newNode = new Node(value);\n let prevNode = this.get(index - 1);\n newNode.next = prevNode.next;\n prevNode.next = newNode;\n this.length++;\n return true;\n }", "insert(index, value) {\n if (index < 0 || index > this.length) {\n return false;\n } else if (index === 0) {\n return this.unshift(value);\n } else if (index === this.length) {\n return this.push(value);\n } else {\n const newNode = new Node(value);\n let prev = this.get(index - 1);\n let curr = prev.next;\n prev.next = newNode;\n newNode.next = curr;\n this.length++;\n return this;\n }\n }", "insert(index, val) {\n if(index < 0 || index > this.length) return false;\n if (index === this.length) return !!this.push(val); //returns true\n if(index === 0) return !!this.unshift(val); //returns true\n \n var newNode = new Node(val);\n var prev = this.get(index - 1);\n var temp = prev.next; //temp is used to store prev.next because if \n //we dont and change prev.next, \n //the value will be deleted\n prev.next = newNode;\n newNode.next = temp;\n this.length++;\n return true;\n\n }", "insert(index,value){\n // check params\n if(index>=this.length){\n return this.append(value);\n }\n\n const newNode = new Node(value);\n const leader = this.traverseToIndex(index-1);\n newNode.next = leader.next;\n leader.next = newNode;\n this.length++;\n\n}", "insert(index, value) {\n if (index < 0 || index > this.length) return false;\n if (index === this.length) return !!this.push(value);\n if (index === 0) return !!this.unshift(value);\n let newNode = new Node(value);\n let prev = this.get(index - 1);\n const temp = prev.next;\n prev.next = newNode;\n newNode.next = temp;\n this.length++;\n return true;\n }", "insert(index, val) {\n if (index < 0 || index > this.length) return false\n if (index === this.length) return !!this.push(val)\n if (index === 0) return !!this.unshift(val)\n\n let newNode = new Node(val)\n let prevNode = this.get(index - 1)\n let nextNode = prevNode.next\n prevNode.next = newNode\n newNode.prev = prevNode\n newNode.next = nextNode\n nextNode.prev = newNode\n this.length++\n return true\n }", "insert(index, val) {\n if (index < 0 || index > this.length) return false;\n\n if (index === 0) this.unshift(val);\n else if (index === this.length) this.push(val);\n else {\n let beforeNode = this.get(index - 1);\n let newNode = new Node(val);\n let afterNode = beforeNode.next;\n\n beforeNode.next = newNode;\n newNode.previous = beforeNode;\n newNode.next = afterNode;\n afterNode.previous = newNode;\n this.length++;\n }\n\n return true;\n }", "insert(index, val) {\n if (index < 0 || index > this.length) return false\n if (index === this.length) return this.push(val)\n if (index === 0) return this.unshift(val);\n\n let node = new Node(val)\n let beforeNode = this.get(index - 1);\n node.next = beforeNode.next;\n beforeNode.next = node\n this.length++\n return true\n }", "insertAt(element, pos) {\n let nodeToInsert = new Node(element);\n let count = 0;\n let current = this.head;\n let previous;\n if (pos === 0) {\n nodeToInsert.next = this.head;\n this.head = nodeToInsert;\n } else if (pos == this.size) {\n while (count < pos) {\n previous = current;\n current = current.next;\n count++;\n }\n previous.next = nodeToInsert;\n }\n else {\n while (count < pos) {\n previous = current;\n current = current.next;\n count++;\n }\n nodeToInsert.next = previous.next;\n previous.next = nodeToInsert;\n this.size++;\n }\n }", "insert(index, value) {\n if (index < 0 || index > this.length) {\n return false;\n }\n if (index === this.length) {\n return !!this.push(value);\n }\n else if (index === 0) {\n return !!this.unshift(value);\n } else {\n let prev = this.get(index - 1);\n let newNode = new Node(value);\n newNode.next = prev.next;\n prev.next = newNode;\n }\n this.length++;\n return true;\n }", "addLast(e) {\n // let { data, size } = this;\n // // last time, size become data.length\n // if ( size >= data.length ) {\n // \tthrow new Error('addLast failed. Array is stuffed');\n // }\n // data[size] = i;\n // size ++; 归并到add方法\n\n // if (this.data.length === this.size) {\n // \tthis.resize(2 * this.size);\n // } 不应该只放在这里\n this.add(this.size, e);\n }", "insert(val,idx){\n if(idx < 0 || idx > this.length) return false;\n if(index === this.length) return !!this.push(val);\n if(index === 0) return !!this.unshift(val);\n\n var newNode = new Node(val);\n var nodeFound = this.get(idx);\n if(nodeFound){\n var pNode = this.get(idx - 1);\n pNode.next = newNode;\n newNode.next = nodeFound\n this.length++\n return true;\n }\n return false;\n }", "insert(index, value) {\n\t\tif (index < 0) {\n\t\t\treturn false\n\t\t}\n\t\tif (index > this.length) {\n\t\t\treturn false\n\t\t}\n\t\tif (index === 0) {\n\t\t\tthis.prepend(value)\n\t\t} else {\n\t\t\t//we create the node to be added\n\t\t\tconst newNode = new Node(value)\n\n\t\t\t//we want to get the index subtract by one because we are inserting before\n\t\t\t//the index since the new node becomes the new index.\n\t\t\t//Example: [0,1,2,3] When index = 2, it means we're inserting between the 1 and 2.\n\t\t\t//In other words, we are inserting one before the index of 2 in the array.\n\t\t\t//We create a pointer called currentNode that now points to the object in the before the index.\n\t\t\tconst currentNode = this.getIndex(index - 1)\n\n\t\t\t//We create another pointer called holdPtr that points to currentNode.next's object, so that we do not lose\n\t\t\t//the singly linked list\n\t\t\tconst holdPtr = currentNode.next\n\t\t\tcurrentNode.next = newNode\n\t\t\tnewNode.next = holdPtr\n\t\t\tthis.length++\n\t\t\treturn this\n\t\t}\n\t}", "insert(char, index) {\n if (index > this.totalLen) return\n\n let curr = this.head\n while (curr !== null && index >= 0) {\n if (index >= curr.len) {\n index -= curr.len\n } else {\n if (curr.len === curr.chars.length) {\n let newNode = new Node()\n newNode.chars[0] = curr.chars[curr.chars.length - 1]\n newNode.len = 1\n newNode.next = curr.next\n curr.next = newNode\n curr.len -= 1\n }\n curr.len += 1\n for (let i = curr.len - 1; i > index; i--) {\n curr.chars[i] = curr.chars[i-1]\n }\n curr.chars[i] = char\n break\n }\n curr = curr.next\n }\n\n if (curr === null) {\n let newNode = new Node()\n newNode.chars[0] = char\n newNode.len = 1\n let tail = new Node()\n tail.next = this.head\n while (tail.next !== null) {\n tail = tail.next\n }\n tail.next = newNode\n }\n totalLen += 1\n return\n }", "insert(i, item) {\n }", "insert(elem, current = this.root, parentIndex = -1, side = false) {\n if (current.empty()) {\n this.callStack.push([]);\n current.addFirst(new Element(elem));\n this.addAtLastIndexOfCallStack(\n this.undoAddFirst.bind(this, current)\n );\n this.size++;\n this.addAtLastIndexOfCallStack(()=>{\n this.size--;\n });\n this.previous.push({action:\"insert\", data: elem});\n if(this.clearForwardOnAction)\n this.forward = [];\n } else if (elem >= current.last().value) {\n if (current.hasRightmostChild()) {\n this.insert(elem, current.getRightmostChild(), current.size() - 1, true);\n } else {\n this.callStack.push([]);\n current.addLast(new Element(elem));\n this.addAtLastIndexOfCallStack(\n this.undoAddLast.bind(this, current)\n );\n this.size++;\n this.addAtLastIndexOfCallStack(\n () => {\n this.size--;\n }\n );\n this.previous.push({action:\"insert\", data: elem});\n if(this.clearForwardOnAction)\n this.forward = [];\n }\n } else {\n for (let idx = 0; idx < current.size(); idx++) {\n if (elem < current.valueAt(idx)) {\n if (current.hasLeftChildAt(idx)) {\n this.insert(elem, current.leftChildAt(idx), idx, false);\n break;\n } else {\n this.callStack.push([]);\n current.addAt(idx, new Element(elem));\n this.addAtLastIndexOfCallStack(\n this.undoAddAt.bind(this, current, idx)\n );\n this.size++;\n this.addAtLastIndexOfCallStack(\n () => {\n this.size--;\n }\n );\n this.previous.push({action:\"insert\", data: elem});\n if(this.clearForwardOnAction)\n this.forward = [];\n break;\n }\n }\n }\n }\n if (current.size() === this.base) {\n this.liftUp(current, parentIndex, side);\n }\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 }", "insert(idx, value) {\n // Check if maxSize has been reached\n if (this.size === this.maxSize) {\n return -1;\n }\n\n // If idx <= 0, unshift\n if (idx <= 0) {\n return this.unshift(value);\n }\n\n // If idx >= this.size, push\n if (idx >= this.size) {\n return this.push(value);\n }\n\n // Otherwise, insert in the middle\n // Instantiate a new node\n const newNode = new Node(value);\n\n // set a pointer (prevNode) to the result of findByIdx(idx-1)\n const prevNode = this.findByIdx(idx - 1);\n\n // set a pointer (nextNode) to prevNode.next\n const nextNode = prevNode.next;\n\n // set next pointer of prevNode to newNode\n prevNode.next = newNode;\n\n // set prev pointer of newNode to prevNode\n newNode.prev = prevNode;\n\n // set next pointer of newNode to nextNode\n newNode.next = nextNode;\n\n // set prev pointer of nextNode to newNode\n nextNode.prev = newNode;\n\n // Increment the size\n this.size++;\n\n // return the linked list\n return this;\n }", "insert(index, val) {\n if (index > this.length || index < 0) {\n return false;\n }\n\n if (index === this.length) {\n return this.push(val);\n }\n\n if (index === 0) {\n return this.unshift(val);\n }\n\n const newNode = new Node(val);\n const prev = this.get(index - 1);\n const temp = prev.next;\n prev.next = newNode;\n newNode.next = temp;\n return true;\n }", "insertAt(index, data) {}", "insert(index, val) {\n // if the index is not in the list\n if (index < 0 || index > this.length) return false;\n // if the index is at the beginning add it to the front\n if (index === 0) return !!this.unshift(val);\n // if the index is at the end add it to the end\n if (index === this.length) return !!this.push(val);\n\n // create the newNode\n const newNode = new Node(val);\n // find the node before the given index\n const prevNode = this.get(index - 1);\n // set the next index on the newNode to the next node on the prevNode\n newNode.next = prevNode.next;\n // set the prev node on the newNode to the prevNode\n newNode.prev = prevNode;\n // set the next node on the prevNode to the newNode\n prevNode.next = newNode;\n // increase the length\n this.length++;\n return true;\n }", "insert(index, val) {\n if (index > this.length - 1) {\n return false;\n }\n if( index === 0 ){\n this.addToHead(val)\n return true\n }\n this.length++\n let node = this.get(index - 1);\n node.next = new Node(val, node.next)\n return true\n }", "insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }", "function insertAt_(as, i, a) {\n return i < 0 || i > as.length ? _index.none : (0, _index.some)(unsafeInsertAt_(as, i, a));\n}", "insert(index, element) {\n if (index < 0 || index > this.count) return false;\n if (index === this.count) return !!this.push(element);\n if (index === 0) return !!this.unshift(element);\n\n const node = new Node(element);\n let prevNode = this.get(index - 1);\n let nextNode = prevNode.next;\n\n prevNode.next = node, node.prev = prevNode;\n node.next = nextNode, nextNode.prev = node;\n\n this.count++;\n\n return true;\n }", "insertAtHead(data) {\n this.insertAfter(-1, data)\n }", "insert(operation, item) {\r\n const wrapper = {\r\n item: item\r\n };\r\n\r\n if (operation % 1 === 0) {// it is an insert\r\n wrapper.op = 'insert';\r\n buffer.splice(operation, 0, wrapper);\r\n } else {\r\n wrapper.op = operation;\r\n switch (operation) {\r\n case 'append':\r\n buffer.push(wrapper);\r\n break;\r\n case 'prepend':\r\n buffer.unshift(wrapper);\r\n break;\r\n }\r\n }\r\n }", "InsertArrayElementAtIndex() {}", "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 }", "insertAt(data, index) {\n // if index is out of range\n if (index < 0 || index >= this.size) {\n return;\n }\n // If first index\n if (index === 0) {\n this.head = new Node(data, this.head);\n return;\n }\n\n const node = new Node(data);\n let current, previous;\n\n // set current to first \n current = this.head\n let count = 0;\n\n while(count < index) {\n previous = current; // Node before index we want to insert\n count++;\n current = current.next; // Node after index\n }\n\n node.next = current;\n previous.next = node;\n\n this.size\n }", "insertAt(newItem, pos) {\n let stepper = 0;\n let currNode = this.head;\n while (stepper !== pos) {\n stepper++;\n currNode = this.head.next;\n }\n if (currNode === null) {\n return console.log(\"Item not found\");\n }\n if (stepper === pos) {\n this.insertAfter(newItem, currNode.value);\n return;\n }\n }", "insertAt(idx, val) {\n \n // check if index is valid.\n if (idx < 0 || idx > this.length) {\n throw new Error(\"Invalid Index.\");\n }\n \n if (idx === 0) return this.unshift(val);\n if (idx === this.length) return this.push(val);\n \n // create new node.\n let newNode = new Node(val);\n let prevNode = this._get(idx - 1);\n newNode.next = prevNode.next; \n prevNode.next = newNode;\n\n ++this.length; // increment the list by 1.\n \n }", "insert(index, val) {\n if (index < 0 || index > this.length) return false;\n if (index === this.length) return !!this.push(val);\n if (index === 0) return !!this.unshift(val);\n\n var newNode = new Node(val);\n var prev = this.get(index - 1);\n var temp = prev.next;\n prev.next = newNode;\n newNode.next = -temp;\n this.length++;\n return true;\n }", "function insertOrAppend(container, pos, el) {\n var childs = container.childNodes;\n if (pos < childs.length) {\n var refNode = childs[pos];\n container.insertBefore(el, refNode);\n } else {\n container.appendChild(el);\n }\n }", "insert(index, val) {\n if(index < 0 || index > this.length) return false\n if(index === 0) {\n if(this.addToHead(val)) return true\n }\n let newNode = new Node(val)\n let prevNode = this.get(index - 1)\n let oldNext = prevNode.next\n prevNode.next = newNode\n newNode.next = oldNext\n this.length++\n return true \n }", "insertAt(idx, val) {\n\n }", "insertAt(index, data) {\n if (index < 0 || index > this.size) {\n console.log(\"Please enter a valid index\");\n } else {\n let newNode = new Node(data);\n let current = this.head;\n let position = 0;\n\n if (index === 0) {\n newNode.next = current;\n this.head = newNode;\n } else {\n while (position < index - 1) {\n position++;\n current = current.next;\n }\n newNode.next = current.next;\n current.next = newNode;\n }\n }\n this.size++;\n }", "insert(val, idx) {\n\n }", "insert(index, value) {\n // If the index argument is out of bounds\n if (index < 0 || index >= this.length) {\n // Throw an error if invalid index\n throw new Error('Index error');\n }\n // If the array's capacity isn't large enough to accomodate\n if (this.length >= this._capacity) {\n // We increase the size of the array to 1 larger than it's length and add our size ratio constant\n this._resize((this.length + 1) * Array.SIZE_RATIO);\n }\n // Move the array in memory to accomodate the new item\n memory.copy(this.ptr + index + 1, this.ptr + index, this.length - index);\n // Copy our provided value into the provided index\n memory.set(this.ptr + index, value);\n // Increase our array's length\n this.length++;\n }", "insertAt(idx, val) {\n if (idx > this.length || idx < 0) {\n throw new Error(\"Invalid index.\");\n }\n\n if(idx === 0) return this.unshift(val);\n if(idx === this.length) return this.push(val);\n\n let previous = this._get(idx - 1);\n\n let newNode = new Node(val);\n newNode.next =previous.next;\n previous.next = newNode;\n\n this.length += 1;\n }", "insert(index, val){\n if(index < 0 || index > this.length){\n return false;\n }\n if(index === this.length){\n // !! convert it to boolean\n return !!this.push(val);\n }\n if(index === 0){\n return !!this.unshift(val);\n }\n \n let newNode = new Node(val);\n let foundNode = this.getByIndex(index - 1);\n let temp = foundNode.next;\n foundNode.next = newNode;\n newNode.next = temp;\n this.length++;\n return true;\n }", "insert(index, value) {\n if(index < 0 || index >= this.length) {\n throw new Error('Index error')\n }\n if(this.length >= this._capacity) {\n this._resize((this.length + 1) * this.ARRAY_SIZE_RATIO)\n }\n memory.copy(this.ptr + index + 1, this.ptr + index, this.length - index)\n //[1,2,3] ==> [1,2,2,3]\n memory.set(this.ptr + index, value)\n //[1, value, 2, 3]\n this.length++\n }", "insert(index,value){\n//check parameters\nif(index >= this.length){\n return this.append(value)\n}\nconst newNode ={\n value:value,\n next:null\n}\nconst leader =this.tracerseToIndex(index-1)\nconst holdingPointer = leader.next\nleader.next =newNode\nnewNode.next =holdingPointer\nthis.length++;\nreturn this.printList\n}", "insert(index, val) {\n if (index >= this.length) return false;\n\n let node = this.head;\n let newNode = new Node(val, null);\n let nextNode;\n for (let i = 0; i < this.length; i++) {\n if (i === index - 1 || index === 0) {\n this.length += 1;\n nextNode = node.next;\n node.next = newNode;\n newNode.next = nextNode;\n return true;\n }\n node = node.next;\n }\n }", "insertAt(idx, val) {\n const newN = new Node(val);\n if (!this.head) {\n this.head = newN;\n this.tail = newN;\n };\n if (idx === 0) {\n const oldHead = this.head;\n this.head = newN;\n this.head.next = oldHead;\n } else {\n let i = 1;\n let current = this.head;\n while (i !== idx) {\n i ++;\n current = current.next;\n };\n if (this.tail === current) {\n current.next = newN;\n this.tail = newN;\n } else {\n const oldNext = current.next;\n current.next = newN;\n newN.next = oldNext;\n };\n };\n this.length ++;\n }", "insert(index, val) {\n let newNode = new Node(val);\n if (index < 0 || index > this.length) return false;\n if (index === this.length) this.push(newNode);\n if (index === 0) this.unshift(newNode);\n\n let prev = this.get(index - 1);\n let temp = prev.next;\n prev.next = newNode;\n newNode.next = temp;\n this.length++;\n return true;\n }", "insert(element, position) {\n // check for out-of-bounds values\n if(index >= 0 && index <= this.count) { \n const node = new Node(element);\n // change the head reference to node and add a new element to the list\n if(index === 0) { \n node.next = current; \n this.head = node;\n // to loop through the list until the desired position\n } else {\n const previous = this.getElementAt(index - 1);\n node.next = previous.next; // to link the new node and the current\n previous.next = node; \n }\n this.count++;\n return true;\n }\n return false;\n }", "insert (packet) {\n if ((this._length + 1) > this._buffer.length) {\n this.remove()\n }\n\n const next = this._start + this._length\n const index = next % this._buffer.length\n this._buffer[index] = packet\n this._length += 1\n }", "insert(item, index){\n let id;\n if (!item) throw new Error(\"item is not defined\");\n if (index < 0) throw new Error(\"index should be a positive int\");\n\n if (typeof index === \"undefined\" || index > this._items.length) {\n id = this._items.length;\n } else { \n id = index;\n }\n\n item.id = id;\n this._items.splice(id, 0, item);\n this.length = this._items.length;\n\n for (let i = id + 1; i < this._items.length; i++){\n this._items[i].id = i;\n }\n }", "insert(index, value) {\n //if index is less than zero or greater than the length of the list, return false\n if (index < 0 || index > this.length) return false;\n //if the index is the same as the length of the list, use push method to add a new node to the end of the list\n // double bang (double negation)\n if (index === this.length) return !!this.push(value);\n //if the index is 0, use the unshift method to add a new node to the beginning of the list\n if (index === 0) return !!this.unshift(value);\n //otherwise, using the get method, access the node at (index - 1) meaning we are getting the index\n //at the position left of where we are adding the new node\n const previousNode = this.get(index - 1);\n //instanstiate a new Node\n const newNode = new Node(value);\n //set that new Node's next property to the old node that previousNode was pointing to\n //(can also create intermediate variable that holds the value of previousNode.next and set newNode.next to it)\n newNode.next = previousNode.next\n //then set previousNode's next property to the new Node\n previousNode.next = newNode;\n //increment the length of the list\n this.length++\n //return true\n return true;\n }", "insert(index, value) {\n if (index < 0 || index >= this.length) {\n throw new Error(\"Index error\");\n }\n if (this.length >= this._capacity) {\n this._resize((this.length + 1) * Array.SIZE_RATIO);\n }\n memory.copy(this.ptr + index + 1, this.ptr + index, this.length - index);\n memory.set(this.ptr + index, value);\n this.length++;\n }", "insertAt(idx, val) {\n if(idx > this.length) {\n return undefined;\n }\n\n const newNode = new Node(val);\n this.length ++;\n\n if(this.head === null){\n this.head = newNode;\n this.tail = newNode;\n return undefined;\n }\n\n if(idx === 0){\n newNode.next = this.head;\n this.head = newNode;\n\n return undefined;\n }\n\n if(idx === this.length - 1){\n this.tail.next = newNode;\n this.tail = newNode;\n\n return undefined;\n }\n\n let currNode = this.head;\n\n for(let i = 0; i < idx - 1; i++){\n currNode = currNode.next;\n }\n\n newNode.next = currNode.next;\n currNode.next = newNode;\n }", "insertAt(data, index) {\n if (index > 0 && index > this.size) {\n return;\n }\n\n //Kapag walang data insertFirst\n if (index === 0) {\n this.insertFirst(data);\n return;\n }\n\n const node = new Node(data);\n let current, previous;\n\n current = this.head;\n let count = 0;\n\n while (count < index) {\n previous = current;\n\n current = current.next;\n\n count++;\n }\n\n node.next = current;\n previous.next = node;\n\n this.size++;\n }", "get insertPosition() { return this.insertPositionIn; }", "insertAt(idx, val) {\n if(!this.head) return this.push(val);\n let curr = this.head;\n let newNode = new Node(val);\n\n let i = 0;\n while(i < idx - 1){\n if(curr){\n curr = curr.next;\n i ++\n } else {\n throw new Error(\"invalid index\");\n }\n }\n\n if(curr.next){\n newNode.next = curr.next;\n }else {\n this.tail = newNode;\n }\n\n curr.next = newNode;\n this.length++;\n\n return undefined;\n }", "insert(position, element){\n if (position >= 0 && position < this.length){\n var node = new Node(element);\n var current = this.head;\n var previous;\n var counter = 0;\n // if adding element at the beginning of the list...\n if (position === 0){\n // push back the 1st element...\n node.next = current;\n // point head to inserted node\n this.head = node;\n } else {\n // loop thru til we reach the desired position...\n while (counter++ < position){\n previous = current;\n current = current.next;\n }\n // when finally bust out of the loop, CURRENT is referencing element after the position we would like to insert... (want to add new item b/w prev and current)\n // point previous.next to node && point node.next to current\n // make a link b/w the new item and current\n node.next = current;\n // change link b/w previous and current\n previous.next = node;\n }\n this.length++;\n return true;\n } else {\n return false;\n }\n }", "insertAt(data, index) {\n //if the index is out of range\n if (index > 0 && index > this.size) {\n return;\n }\n //if it's the first index\n if (index === 0) {\n this.head = new Node(data, this.head);\n return;\n }\n const node = new Node(data);\n let current, previous;\n\n //set current to first\n current = this.head;\n let count = 0;\n\n while (count < index) {\n previous = current; //The node before the index\n count++;\n current = current.next; //The node after teh index\n }\n\n node.next = current;\n previous.next = node;\n this.size++;\n }", "insert(index, val){\n // handling the edge case of an index smaller than 0\n if (index < 0) return undefined;\n // simply prepending if the index is 0\n if (index === 0) return this.prepend(val);\n // simply appending if the index is the size\n if (index === this.size) return this.append(val);\n // getting the previous node befoore the postion we want to\n // insert in\n index = index -1;\n let count, current;\n // transversing either from the head or tail depending the closeness of \n // of the index\n if(index <= this.length/2){\n count = 0;\n current = this.head;\n while(count !== index){\n current = current.next;\n count++;\n }\n } else {\n count = this.length - 1;\n current = this.tail;\n while(count !== index){\n current = current.prev;\n count--;\n }\n }\n\n // chaining the nodes together\n\n let newNode = new Node(val);\n let NextNode = current.next;\n current.next = newNode;\n newNode.pre = current;\n newNode.next = NextNode;\n NextNode.pre = newNode;\n this.size++;\n }", "insert(data, index) {\n // If index is out of range\n if (index > 0 && index > this.size) return;\n let node = new Node(data);\n\n // If index = 0: insert at head\n if (index === 0) {\n if (!this.head) {\n this.head = node;\n this.tail = node;\n this.size++;\n } else {\n let current = this.head;\n node.next = current;\n current.prev = node;\n this.head = node;\n this.size++;\n }\n } else if (index === this.size) {\n let current = this.tail;\n node.prev = current;\n current.next = node;\n this.tail = node;\n this.size++;\n } else {\n // Insert at given index k\n let counter = 0;\n let current = this.head;\n while (counter < index) {\n current = current.next;\n counter++;\n }\n node.next = current;\n current.prev.next = node;\n node.prev = current.prev;\n this.size++;\n }\n }", "insertAt(data, index){\n // check if index is out of range\n if(index > 0 && index > this.size){\n // return false\n return;\n }\n // create a new node\n const node = new Node(data);\n // we need two variables to hold the current and previous node\n let current; \n let previous;\n\n // assign head to current variable\n current = this.head;\n\n // check if index is 0 \n if(index === 0){\n // if so then the existing head should be next to the node\n node.next = this.head;\n // if so then add created node as the head of the linked list\n this.head = node;\n }\n else {\n // set current to head\n current = this.head;\n // create a variable to count\n let count = 0;\n\n // iterate to the right position\n while(count < index){\n // increase the count\n count++;\n previous = current;\n current = current.next;\n }\n // when you find right position add the new node there between previous and current\n node.next = current;\n previous.next = node;\n }\n // increase the linked list size\n this.size++;\n }", "insertAtInd(data, index){\n if(index > 0 && index > this.size){\n return\n }\n if(index === 0){\n this.head = new Node(data, this.head)\n return\n\n }\n const node = new Node(data);\n let current,previous;\n current = this.head;\n let count = 0;\n while(count < index){\n previous = current;\n current = current.next;\n count++;\n\n }\n node.next = current;\n previous.next = node\n this.size++\n }", "insertAt(element, index){\n // fail safe to prevent adding element where\n // specified index is greater than size of list\n if (index > 0 && index > this.size){\n return false;\n } \n else {\n // creates a new node\n var node = new Node(element)\n var curr, prev;\n\n //whatever list head is at this moment\n curr = this.head;\n\n // add the element to the first index\n if (index == 0){\n\n //create pointer to next node which is null\n node.next = null;\n\n //head of node is specified element\n this.head = node;\n\n } else {\n \n curr = this.head;\n var iterate = 0;\n\n // iterate over list to find\n // the position to insert\n\n while (iterate < index){\n iterate++;\n prev = curr;\n curr = curr.next;\n }\n // adding an element\n node.next = curr;\n prev.next = node;\n }\n this.size++;\n }\n }", "insertAt(idx, val) {\n if (idx < 0 || idx > this.length) {\n throw new Error(\"Invalid Index\");\n }\n\n const node = new Node(val);\n\n if (this.length === 0) {\n this.head = node;\n this.tail = node;\n this.length = 1;\n\n return;\n }\n\n if (idx === this.length) {\n this.tail.next = node;\n this.tail = node;\n\n this.length++;\n }\n\n let currentNode = this.head;\n let i = 0;\n\n while (i < idx - 1) {\n currentNode = currentNode.next;\n i++;\n }\n\n node.next = currentNode.next;\n currentNode.next = node;\n\n this.length++;\n }", "function insertElement(array,insert,position){\n newArray = [];\n if (position < array.length){\n for (i=0; i < array.length && i <= position; i++){\n if(i === position){\n newArray[i] = insert\n }\n else {\n newArray[newArray.length] = array[i];\n } \n }\n for (j = 0; j < array.length - position; j++){\n newArray[newArray.length] = array[position+j]\n }\n return newArray\n }\n else{\n console.log('Error, array is too short to enter input in this position')\n }\n}", "insertAtCaret(el) {\n var self = this;\n var caret = Math.min(self.caretPos, self.items.length);\n var target = self.buffer || self.control;\n\n if (caret === 0) {\n target.insertBefore(el, target.firstChild);\n } else {\n target.insertBefore(el, target.children[caret]);\n }\n\n self.setCaret(caret + 1);\n }", "insert(n, val) {\n /**\n * Pseudocode \n * if index is same as length use push \n * if index is zero use unshift \n * otherwise use get to find n-1 node \n */\n let newNode = new Node(val)\n if (n > this.length || n < 0) return false\n if (n == this.length) {\n this.push(val)\n return true\n } else if (n == 0) {\n this.unshift(val)\n return true\n }\n let prev = this.get(n)\n let after = prev.next\n newNode.next = after\n prev.next = newNode\n this.length++\n return true\n }", "insertAt(element,index)\r\n {\r\n if( index > 0 && index > this.size)\r\n {\r\n return false;\r\n }\r\n else\r\n {\r\n //create a new node\r\n var node = new Node(element);\r\n var curr, prev;\r\n curr = this.head;\r\n\r\n //if index=0 add at first index\r\n if(index === 0)\r\n {\r\n node.next = head;\r\n this.head = node;\r\n }\r\n\r\n else\r\n {\r\n curr = this.head;\r\n var it =0;\r\n //iterate over the list to find the postion to insert\r\n while(it < index)\r\n {\r\n it++;\r\n prev = curr;\r\n curr = curr.next;\r\n }\r\n\r\n //add an element\r\n node.next = curr;\r\n prev.next = node;\r\n }\r\n this.size++;\r\n }\r\n }", "insert(index, value) {\n const newNode = new Node(value);\n\n if (index < 0 || index > this.length) {\n return false;\n }\n if (index === this.length) {\n this.tail.next = newNode;\n this.tail = newNode;\n this.length++;\n return true;\n }\n if (index === 0) {\n if (!this.head) {\n this.head = newNode;\n this.tail = this.head;\n } else {\n newNode.next = this.head;\n this.head = newNode;\n }\n this.length++;\n return true;\n }\n\n let current = this.head;\n let count = 0;\n // get to the variable before the given index. You can use a .get here as well\n while (count < index - 1) {\n current = current.next;\n count++;\n }\n // don't forget to increment length!!\n let after = current.next;\n current.next = newNode;\n newNode.next = after;\n this.length++;\n\n return true;\n }", "insertAt(item, position) {\n if(this.head === null) {\n this.head = new _Node(item, this.head)\n }\n let currNode = this.head\n let count = 0\n while(count < position - 1) {\n currNode = currNode.next\n count++\n }\n currNode.next = new _Node(item, currNode.next)\n }", "function insertAt(arr, idx, val){\n if(idx === arr.length){\n arr.push(val);\n }\n else{\n arr.push()\n for(var i = arr.length - 2; i >= idx; i--){\n arr[i + 1] = arr[i];\n }\n arr[idx] = val;\n }\n return arr;\n }", "insertAt(element, index) {\n if (index > 0 && index > this.size) return false;\n else {\n let node = new Node(element);\n\n if (index == 0) {\n node.next = head;\n this.head = node;\n } else {\n let curr = this.head;\n let i;\n for (i = 0; i < index - 1; i++) {\n curr = curr.next;\n }\n node.next = curr.next;\n curr.next = node;\n }\n }\n }", "insert(index, val) {\n if (index < 0 || index > this.length - 1) return false;\n if (index === 0) this.addToHead(val);\n if (index === this.length) this.addToTail(val);\n\n let targetNode = this.get(index - 1);\n if (targetNode === null) {\n return false;\n } else {\n let newNode = new Node(val);\n let originalNext = targetNode.next;\n targetNode.next = newNode;\n newNode.next = originalNext;\n\n this.length += 1;\n return true;\n }\n }", "insertAt(position,item){\n \n if(this.head === null){\n this.insertFirst(item);\n }\n \n let ticker = 0;\n let currNode = this.head;\n let nextNode = this.head;\n \n while ((nextNode !== null) && (ticker !== position)) {\n //save the previous node \n currNode = nextNode;\n nextNode = currNode.next;\n ticker++;\n }\n \n currNode.next = new _Node(item,nextNode);\n \n }", "insert(index, value) {\n\t\tif (index < 0 || index > this.length) return false;\n\t\tif (index === this.length) {\n\t\t\tthis.push(value);\n\t\t\treturn true;\n\t\t}\n\t\tif (index === 0) {\n\t\t\tthis.unshift(value);\n\t\t\treturn true;\n\t\t}\n\n\t\tconst newNode = new Node(value);\n\t\tconst prev = this.get(index - 1);\n\t\tconst curr = this.get(index);\n\t\tnewNode.next = curr;\n\t\tprev.next = newNode;\n\t\tthis.length++;\n\t\treturn true;\n\t}", "insertAt(data,index){\n // primero validamos que el indice sea un numero valido dentro de la lista\n if(index < 0 || index > this.size){\n return null;\n }\n // creamos el nuevo nodo llamando a la clase node\n const newNode = new node(data);\n // guardamos los datos de la cabeza en current y inicializamos previous\n let current = this.head;\n let previous;\n // si el indice es igual a 0 significa que el nuevo nodo debe estar al principio de todo\n if(index === 0){\n newNode.next = current;\n this.head = newNode;\n }else{\n // el siguiente siclo hace avanzar al nodo indicado dependiendo el indice escrito\n for(let i = 0;i < index; i++){\n previous = current;\n current = current.next;\n }\n newNode.next = current;\n previous.next = newNode;\n }\n this.size++;\n }", "insert() { }", "function insertAt(arr,givenIndex,val){\n for (var index = arr.length; index >= givenIndex; index--){\n var currentValue = arr[index-1];\n arr[index] = currentValue;\n }\n arr[givenIndex] = val;\n return arr;\n}", "insertIndexedNode(data, index){\n //edge cases when index = 0, when index = last index,\n //when index is out of range\n if (index === 0){\n //insert node at head\n this.insertHeadNode(data);\n \n } else if (index === this.size - 1){\n //insert node at tail\n this.insertTailNode(data);\n }else if (index < 0 || index >= this.size){\n console.log('error: index is out of range');\n return;\n } else {\n //if no edge cases...\n //find index where node will be inserted\n let current = this.head;\n let previous = null;\n let count = 0;\n while(count < index){\n previous = current;\n current = current.next;\n count++; //increments count until count == index which stops loop\n }\n //create the node to insert\n let babyNode = new Node(data, current);\n previous.next = babyNode;\n this.size++;\n}\n}", "addOnIndex(index, value) {\n if (index < 0) {\n console.error(`Index must be greater than 0!`);\n return false;\n }\n\n index = Math.floor(index);\n\n if (this.length <= index) {\n this.add(value);\n } else {\n const temp = this.get(index);\n this.data[index] = value;\n\n for (let i = index + 1; i < this.length; i++) {\n this.data[i + 1] = this.data[i];\n }\n\n this.data[index + 1] = temp;\n this.length++;\n }\n }", "function insertAt(arr,idx, val){\n for(var i =arr.length; idx <= i; i--){\n console.log(i + \": i value, \" + idx + \": insert here\");\n arr[i] = arr[i-1];\n console.log(arr);\n if(i === idx){\n arr[i] = val;\n }\n }\n // return arr;\n console.log(arr);\n}", "insertEnd(arr, n, length, capacity) {\n if (length < capacity) {\n arr[length] = n;\n }\n }", "function insert(arr, num, index){\n arr.length += 1;\n for (var i = arr.length-1; i > index; i--){\n arr[i] = arr[i-1];\n }\n arr[index] = num;\n return arr;\n}", "function insert(element, after){\n var insertPos = this.find(element)\n if(insert > -1){\n this.dataStore.splice(insertPos+1, 0, element)\n ++this.listSize\n return true\n }\n return false\n}", "push(item) {\n this.data[this.lenght] = item;\n this.lenght++;\n return this.lenght;\n }", "insertMiddle(arr, i, n, length) {\n // Shift starting from the end to i.\n for (let index = length - 1; index > i - 1; index--) {\n arr[index + 1] = arr[index];\n }\n //Insert at i\n arr[i] = n;\n }", "function unsafeInsertAt(i, a) {\n return as => unsafeInsertAt_(as, i, a);\n}" ]
[ "0.7203813", "0.6965906", "0.6765198", "0.67382383", "0.672827", "0.66598845", "0.6654216", "0.66512036", "0.6649753", "0.6641324", "0.661329", "0.6609445", "0.6607198", "0.6600132", "0.6597229", "0.6584083", "0.6561471", "0.6547141", "0.6529939", "0.65191644", "0.649897", "0.6447396", "0.6435909", "0.6423105", "0.641818", "0.6415993", "0.6412025", "0.6409173", "0.6405672", "0.639827", "0.6380866", "0.6375762", "0.6362415", "0.6346134", "0.634321", "0.6336616", "0.6328073", "0.63224137", "0.632225", "0.6320282", "0.6309784", "0.62945366", "0.6289974", "0.6285723", "0.6281264", "0.6271637", "0.62569827", "0.62436306", "0.6242528", "0.62367916", "0.6235503", "0.6232204", "0.62227", "0.62206984", "0.6212518", "0.62116325", "0.62070394", "0.6187757", "0.618325", "0.61823213", "0.61730766", "0.61671007", "0.6165403", "0.6157688", "0.6155025", "0.61544967", "0.6151855", "0.6150379", "0.61430895", "0.6139301", "0.61275965", "0.61228585", "0.6119149", "0.61185473", "0.60834765", "0.60637224", "0.6057993", "0.6040923", "0.6037615", "0.60320777", "0.6028851", "0.60255766", "0.60084665", "0.6002531", "0.59988445", "0.59952056", "0.5991467", "0.59899616", "0.5989913", "0.59772366", "0.5955919", "0.5947919", "0.59468555", "0.59401107", "0.59317565", "0.59299433", "0.59268355", "0.5917798", "0.5908512", "0.59039944" ]
0.6575339
16
returns array where position i is the product of all array items at position !== i
function products(arr){ let newArr = [] let p ; for (let i=0;i<arr.length;i++){ p=1 for (let j=0;j<arr.length;j++){ if (i !== j){ p = p * arr[j] } } newArr.push(p) } return newArr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function products(arr){\n let result = [];\n for (let i = 0 ; i < arr.length; i ++ ){\n let prod = 1\n for (let j = 0; j < arr.length; j++){\n if (i !== j){\n prod *= arr[j]\n }\n }\n result.push(prod);\n }\n return result;\n\n}", "function getProductsOfAllIntsExceptAtIndex(array) {\n var answer = [];\n\n // initialze every element with 1\n // [1,1,1,1]\n initialize(answer, array.length);\n var answer_index = 0;\n\n while (answer_index < answer.length) {\n for (var i = 0; i < array.length; i++) {\n if (answer_index === i) {\n continue;\n } else {\n answer[answer_index] *= array[i];\n }\n }\n answer_index++;\n }\n}", "function product_array_except_self(array) {\n let output = []; \n // let left = array[0]; \n for (let i = 0; i < array.length; i++) {\n let product = 1; \n for (let j = 0; j < array.length; j++) {\n if (j !== i) {\n product *= array[j]; \n }\n }\n output.push(product); \n }\n return output; \n}", "function products(arr) {\n\n let newArr = [];\n for (let i = 0; i < arr.length; i++) {\n let total = 1;\n //For every number, loop through the array.\n for (let j = 0; j < arr.length; j++) {\n //If the indexes are the same, don't do anything, else multiply the total with the number\n if (j !== i) {\n total = arr[j] * total\n }\n }\n newArr.push(total)\n }\n return newArr\n }", "function products(arr) {\n let prodArr = [];\n for(let i = 0; i < arr.length; i++) {\n let product = 1;\n for(let j = 0; j < arr.length; j++) {\n if(arr[i] !== arr[j]) {\n product = product * arr[j];\n }\n }\n prodArr.push(product);\n }\n console.log(prodArr);\n}", "function arrayOfProducts(array) {\n return array.map((num1,i) => {\n\t\tlet product = 1;\n\t\tarray.forEach((num2,j) => {\n\t\t\tif (i !== j) product *= num2;\n\t\t})\n\t\treturn product\n\t})\n}", "function arrayOfProducts(array) {\n\nlet newArr = new Array(array.length).fill(1)\n\nfor(let i=0; i< array.length; i++){\n\tlet value = 1\n\t\t\n\t\tfor(let j=0; j < array.length; j++){\n\t\t\tif(i === j) continue\n\t\t\t\n\t\t\tvalue *= array[j]\n\t\t}\n\t\n\tnewArr[i] = value\n}\n\nreturn newArr\n\t\n}", "function arrayOfProducts1(array) {\n // Write your code here.\n const output = [];\n for (let i = 0; i < array.length; i++) {\n let product = 1;\n for (let j = 0; j < array.length; j++) {\n if (!(i === j)) {\n product *= array[j];\n }\n }\n output.push(product);\n }\n return output;\n}", "function productArray(numbers){\n let result = []\n numbers.forEach((number, index) => {\n let res = 1;\n numbers.forEach((subNumber, subIndex) => {\n if(index !== subIndex) {\n res *= subNumber\n }\n })\n result.push(res)\n })\n return result\n }", "function otherProd(arr){\n let ans = []\n let red = []\n \n for( let i = 0; i < arr.length; i++){\n for(let j = 0; j < arr.length; j++){\n //only i and j are not the same will the value\n //be pushed to the red array.\n if ( j !== i) {\n red.push(arr[j])\n }\n }\n //Reduces the value of the array\n let resultOfMult = red.reduce( (a,b) => (a * b ));\n //pushed the resulting value to our ans Array.\n ans.push(resultOfMult)\n red = []\n \n }\n }", "function products(arr) {\n\tlet ret = [];\n\tfor (let idx1 = 0; idx1 < arr.length; ++idx1) {\n\t\tlet prod = 1;\n\t\tfor (let idx2 = 0; idx2 < arr.length; ++idx2) {\n\t\t\tif (idx1 != idx2) {\n prod *= arr[idx2];\n }\n\t\t}\n\t\tret.push(prod);\n\t}\n\treturn ret;\n}", "function arrayOfProducts(array) {\n let left_products = Array(array.length).fill(1); \n let right_products = Array(array.length).fill(1); \n let result_products = Array(array.length).fill(1); \n \n let left_running_prod = 1; \n for(let i = 0; i < array.length; i++) {\n left_products[i] = left_running_prod; \n left_running_prod *= array[i]; \n }\n\n let right_running_prod = 1; \n for (let i = array.length - 1; i >= 0; i--) {\n right_products[i] = right_running_prod; \n right_running_prod *= array[i]; \n }\n\n for(let i = 0; i < array.length; i++) {\n result_products[i] = left_products[i] * right_products[i]; \n }\n\n return result_products; \n}", "function getProductsOfAllIntsExceptAtIndex (ints) {\n if (ints.length < 2) {\n throw new Error(\"Getting the product of numbers at other indices requires at least 2 numbers\");\n }\n var products = [], curProduct = 1;\n for (var i = 0; i < ints.length; i++) {\n products[i] = curProduct;\n curProduct *= ints[i];\n }\n curProduct = 1;\n for (var j = ints.length - 1; j >= 0; j--) {\n products[j] *= curProduct;\n curProduct *= ints[j];\n }\n return products;\n}", "function arrayOfProductsOptimized(arr) {\n\tconst result = new Array(arr.length).fill(1)\n\n let leftProduct = 1\n for (let i = 0; i < arr.length; i++) {\n result[i] = leftProduct\n leftProduct *= arr[i];\n }\n\n let rightProduct = 1\n for (let i = arr.length - 1; i <= 0; i--) {\n result[i] *= rightProduct\n rightProduct *= arr[i]\n }\n\n return result;\n}", "function productsExceptAtIndex(intArray) {\n if (intArray.length < 2) {\n throw new Error('Getting the product of numbers at other indices requires at least 2 numbers');\n }\n const productsOfAllExceptAtIndex = [];\n\n let productSoFar = 1;\n for (let i = 0; i < intArray.length; i++) {\n productsOfAllExceptAtIndex[i] = productSoFar;\n productSoFar *= intArray[i];\n }\n\n productSoFar = 1;\n for (let j = intArray.length - 1; j >= 0; j--) {\n productsOfAllExceptAtIndex[j] *= productSoFar;\n productSoFar *= intArray[j];\n }\n\n return productsOfAllExceptAtIndex;\n}", "function arrayOfProducts(array) {\n // Write your code here.\n let products = Array(array.length).fill(1); \n \n let left_running_prod = 1; \n for(let i = 0; i < array.length; i++) {\n products[i] = left_running_prod; \n left_running_prod *= array[i]; \n }\n \n let right_running_prod = 1; \n for (let i = array.length - 1; i >= 0; i--) {\n products[i] = right_running_prod*products[i]; \n right_running_prod *= array[i]; \n }\n \n return products; \n}", "function reduceThisNoDivision(newArray) {\n return newArray.map((index) => {\n return newArray.filter(i => i !== index).reduce((total, current) => total * current);\n });\n}", "function getProductsOfAllIntsExceptAtIndex2 (ints) {\n var zeroLocations = [], productWithoutZeros = 1, products = [];\n for (var i = 0; i < ints.length; i++) {\n if (ints[i] == 0) {\n zeroLocations.push(i);\n }\n productWithoutZeros *= ints[i];\n }\n finalProduct = zeroLocations.length == 0 ? productWithoutZeros : 0;\n for (var j = 0; j < ints.length; j++) {\n products[j] = finalProduct/ints[j];\n }\n if (zeroLocations.length == 1) {\n products[zeroLocations[0]] = productWithoutZeros;\n }\n return products;\n}", "function productOfArrayExceptSelf(nums) {\n let res = [1],\n back = 1\n for (let index = 1; index < nums.length; index++) {\n res[index] = res[index - 1] * nums[index - 1]\n }\n for (let index = nums.length - 2; index >= 0; index--) {\n back = back * nums[index + 1]\n res[index] = res[index] * back\n }\n return res\n}", "function arrayOfProducts(array) {\n\tlet res = [];\n\t\n let preIprod = 1, \n\t\tpostIprod = 1; \n\t\n\tfor(let i = 0; i < array.length; i++) {\n\t\tres[i] = preIprod;\n\t\tpreIprod = preIprod * array[i];\n\t}\n\t\n\tfor(let j = array.length-1; j >= 0; j--) {\n\t\tres[j] = res[j] * postIprod; \n\t\tpostIprod = postIprod * array[j]\n\t}\n\t\n\treturn res;\n}", "function arrayOfProducts(array) {\n let newArr = new Array(array.length).fill(1)\n\t\n\tlet left = 1 \n\tfor(let i=0; i<array.length; i++){\n\t\tnewArr[i] = left //always have to reassign the idx before incrementing the left val\n\t\tleft *= array[i]\n\t}\n\t\n\tlet right = 1\n\tfor(let i=array.length-1; i >= 0; i--){\n\t\tnewArr[i] *= right //always have to reassign and multiple before incremeneting the right val\n\t\tright *= array[i]\n\t}\n\t\n\treturn newArr\n}", "function getProductsOfAllIntsExceptAtIndex(intArray) {\n if (intArray.length < 2) { throw new Error(\"Array must have 2 more more ints\"); }\n\n // Make a list of the products\n const output = [];\n for (let i = 0; i < intArray.length; i++) {\n const current = intArray[i];\n\n let product = 1;\n for (let j = 0; j < intArray.length; j++) {\n if (j !== i) {\n product *= intArray[j];\n }\n }\n output.push(product);\n }\n\n return output;\n}", "function getProductsOfAllIntsExceptAtIndex(intArray) {\n\n // Make a list of the products\n\n if (intArray.length < 2) {\n throw new Error('array length must be at least 2!')\n }\n let result = []\n\n let productSoFar = 1;\n for (let i = 0; i < intArray.length; i++) {\n result.push(productSoFar);\n productSoFar *= intArray[i]\n }\n\n let productSoFarBackwards = 1;\n for (let j = intArray.length - 1; j >= 0; j--) {\n result[j] = result[j] * productSoFarBackwards\n productSoFarBackwards *= intArray[j]\n }\n\n return result\n}", "function arrayProducts(arr){\n let newArr = []\n let product = arr.reduce( (a,b) => a*b )\n for (let n=0; n<arr.length; n++){\n newArr.push(product/arr[n])\n }\n return newArr\n}", "function multiplyAll(arr) {\n var product = 1;\n for (var i = 0; i < arr.length; i++) {\n for (var k = 0; k < arr[i].length; k++) {\n product *= arr[i][k];\n }\n }\n return product;\n}", "function multiplyAll(arr){\n var product = 1;\n\n for(var i = 0; i < arr.length; i++){\n for(var j = 0; i < arr[i].length; j++){\n product *=arr[i][j];\n }\n }\n}", "function productOfArray(arr) {\n \n}", "function multiplyAll(arr){\n var product = 1;\n for (var i=0; i < arr.length; i++){\n for (var j=0; j < arr[i].length; j++){\n product *= arr[i][j];\n }\n }\n return product;\n}", "function adjacentElementsProduct(array) {\n\n let show = []\n array = array.map((item, ind, ar) => {\n if (ind != ar.length - 1) {\n show.push(item * ar[ind + 1])\n }\n })\n\n return Math.max(...show)\n\n}", "function multiplyAll(arr) {\n var product = 1;\n for (var i = 0; i < arr.length; i++) {\n for (var j = 0; j < arr[i].length; j++) {\n product = product * arr[i][j];\n }\n }\n return product;\n}", "function multiplyAll(arr) {\n var product = 1;\n\n for (var i = 0; i < arr.length; i++) {\n for (var j = 0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }\n }\n\n return product;\n}", "function findProd(array) {\n let sumArray = [];\n let sum = 1;\n\n for (let i = 0; i < array.length; i++) {\n sum = sum * array[i];\n }\n\n for (let i = 0; i < array.length; i++) {\n sumArray.push(sum / array[i]);\n }\n return sumArray;\n}", "function multiplyAll(arr) {\r\n var product = 1;\r\n for (var i = 0; i < arr.length; i++) {\r\n for (var j = 0; j < arr[i].length; j++) {\r\n product = product * arr[i][j];\r\n }\r\n }\r\n return product;\r\n }", "function production (arr){\n\n var newArray =[];\n for (var i=0;i<arr.length;i++){\n newArray.push(arr[i]*arr[i]);\n }\n\n return newArray;\n}", "function findProduct2 (arr) {\n var left = 1,\n product = []\n for (let ele of arr) {\n product.push(left)\n left = left * ele\n }\n\n let right = 1\n for (let i = arr.length - 1; i >= 0; i--) {\n product[i] *= right\n right *= arr[i]\n }\n return product\n}", "function getProducts(arr) {\n\tlet afters = [];\n\tlet before = [];\n\tlet newArr = [];\n\tlet prod = 1;\n\n\tfor (let i = arr.length-1; i >=0; i--){\n\t\tafters[i] = prod;\n\t\tprod = prod * arr[i];\n\t}\n\n\tprod = 1;\n\tfor (let i = 0; i < arr.length; i++){\n\t\tbefore[i] = prod;\n\t\tprod = prod * arr[i];\n\t}\n\n\tfor (let i = 0; i < arr.length; i++){\n\t\tnewArr[i] = before[i] * afters[i];\n\t}\n\n\treturn newArr;\n}", "function findProductB(arr) {\n var temp = 1,\n product = []\n for ( i=0; i < arr.length; i++ ) {\n product[i] = temp\n temp *= arr[i]\n }\n temp = 1\n for ( i = arr.length - 1; i > -1; i--) {\n product[i] *= temp\n temp *= arr[i]\n }\n return product\n}", "function findProduct(arr) {\n const product = arr.reduce((acc, element) => acc *= element )\n return arr.map(element => product / element)\n}", "function productPerIndex(arr) {\n \n // lol, JS array default value intialization\n let leftArr = (new Array(arr.length)).fill(1);\n let rightArr = (new Array(arr.length)).fill(1);\n\n for(let i = 1; i < arr.length; i++) { \n leftArr[i] = leftArr[i-1] * arr[i-1];\n }\n for(let i = arr.length-2; i >= 0; i--) { \n rightArr[i] = rightArr[i+1] * arr[i+1];\n }\n\n let new_arr = new Array(arr.length);\n for(let i = 0; i < new_arr.length; i++) {\n new_arr[i] = leftArr[i] * rightArr[i];\n } \n return new_arr;\n}", "function productify(arr) {\n let res = [];\n let leftProd = 1;\n for (let i = 0; i < arr.length; i++) {\n res.push(leftProd);\n leftProd = leftProd * arr[i];\n }\n let rightProd = 1;\n for (let j = arr.length - 1; j >= 0; j--) {\n res[j] = res[j] * rightProd;\n rightProd = rightProd * arr[j];\n }\n return res;\n}", "function productExceptSelf(nums) {\n const output = nums.map(n => 1)\n let product = 1\n\n // Multiply from the left\n for (let i = 0; i < nums.length; i++) {\n output[i] *= product\n product *= nums[i]\n }\n\n product = 1\n\n // Multiply from the right\n for (let j = nums.length - 1; j >= 0; j--) {\n output[j] *= product\n product *= nums[j]\n }\n\n return output\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 products(arr) {\n let product=1;\n for (let i=0; i<arr.length; i++){\n product*=arr[i];\n }\n for (let j=1; j<arr.length; j++){\n arr[j]=product/arr[j];\n }\n return arr;\n}", "function products(arr) {\n let totalProduct = 1;\n\n for (let i = 0; i < arr.length; i++) {\n totalProduct *= arr[i];\n }\n\n for (let i = 0; i < arr.length; i++) {\n arr[i] = totalProduct / arr[i];\n }\n return arr;\n}", "function findProductA (arr) {\n var result = []\n var left = 1, currentProduct;\n for ( i = 0; i < arr.length; i++ ) {\n currentProduct = 1\n for ( j=i+1; j < arr.length; j++ ) {\n currentProduct *= arr[j]\n }\n result.push(currentProduct * left)\n left *= arr[i]\n }\n return result\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 elementsProduct(arr) {\r\n let res = -Infinity;\r\n for (let i = 0; i < arr.length - 1; i++) {\r\n if (arr[i] * arr[i + 1] >= res) {\r\n res = arr[i] * arr[i + 1];\r\n }\r\n }\r\n return res;\r\n}", "function productOfArray(arr){\n if (toString.call(arr) !== \"[object Array]\"){\n return false;\n }\n return arr.reduce(function(product, cur){\n if (isNaN(cur)){\n return product;\n }\n return product *= cur;\n });\n}", "function product(arr) {\n if (arr.length === 0) {\n return 0;\n } else {\n return arr.reduce((prod, el)=> {\n return prod *= el\n })\n }\n}", "static mul(array1, array2) {\n if (!Array.isArray(array2)) {\n array2 = Kbase_1.Kbase.repeat(array2, array1.length);\n }\n let mul = [];\n if (array1.length === array2.length) {\n //div only when two arraies have the save length\n for (let i = 0; i < array1.length; i++) {\n if (array2[i] === undefined || isNaN(array2[i]) || array2[i] === 0 || array1[i] === undefined || isNaN(array1[i])) {\n //illegal oprand check\n mul.push(NaN);\n }\n else {\n mul.push(array1[i] * array2[i]);\n }\n }\n }\n else {\n throw new Error(\"must have the same length\");\n }\n return mul;\n }", "function product(arr) {\n let product = 1;\n if(arr.length === 0){\n product = 0;\n } else {\n arr.forEach( (el) => product *= el);\n }\n return product;\n}", "function productOfArray(arr) {\n if (arr.length < 1) return 0;\n let product = 1;\n function helper(arr) {\n if (arr.length < 1) return product;\n product *= arr[0];\n helper(arr.slice(1));\n }\n helper(arr);\n return product;\n}", "function arrayProd(pArray)\n{\n return pArray.reduce(function(tot,item){return tot*=item},1,this)\n}", "function pairProduct(arr, num)\n{\n\tvar multiples = [];\n\n\tfor(var i = 0; i<= arr.length - 1; i++)\n\t{\n\t\tvar outerNum = arr[i];\n\t\tfor(var j = i + 1; j<= arr.length - 1; j++)\n\t\t{\n\t\t\tvar innerNum = arr[j];\n\t\t\tif(outerNum * innerNum === num)\n\t\t\t{\n\t\t\t\tmultiples.push([i,j]);\n\t\t\t}\n\t\t}\n\t}\n\treturn multiples;\n}", "function multiplyAll(arr) {\n var product = 1;\n // Only change code below this line\n for (var i = 0; i < arr.length; i++) {\n for (var j = 0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }\n }\n // Only change code above this line\n return product;\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 multiplyAll(arr) {\n var product = 1;\n // Only change code below this line\n for (var i=0; i < arr.length; i++) {\n for (var j=0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }}\n // Only change code above this line\n return product;\n}", "function productExceptSelf(nums) {\n let n = nums.length;\n const res = Array(n);\n res[0] = 1;\n for (let i = 1; i < n; i++) {\n res[i] = res[i - 1] * nums[i - 1];\n }\n let right = 1;\n for (let i = n - 1; i >= 0; i--) {\n res[i] *= right;\n right *= nums[i];\n }\n return res;\n}", "function products(arr) {\n const maxProduct = arr.reduce((acc, val) => {\n acc *= val;\n return acc;\n });\n \n return arr.map(num => maxProduct / num);\n}", "static mult(a, b) {\n let x = [];\n for (let row = 0; row < a.length; row++) {\n let y = [];\n for (let col = 0; col < b[0].length; col++) {\n let sum = 0;\n for (let k = 0; k < b.length; k++) {\n sum += a[row][k] * b[k][col];\n }\n y.push(sum);\n }\n x.push(y);\n }\n return x;\n }", "function productReduce(array) {\n return array.reduce((total, n) => { return total *= n});\n}", "function cartesianProduct(arr1, arr2) {\n let result = [];\n for (let i = 0; i < arr1.length; i++) {\n let partial = 0;\n for (let j = 0; j < arr1[0].length; j++) {\n partial += arr1[i][j] * arr2[j]\n }\n result.push(partial)\n }\n return result\n}", "function multiEveryPositiv(array) {\n newArr = [];\n for (var i = 0; i < array.length; i++) {\n if (array[i] > 0) {\n newArr[i] = array[i] * 2;\n } else {\n newArr[i] = array[i];\n }\n }\n return newArr;\n}", "function productOfArray(arr) {\n if (arr.length === 0) return;\n return arr[0] * productOfArray(arr.slice(1));\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 product(arr) {\n var sum = 1;\n\n for (var i = 0; i < arr.length; i++) {\n sum *= arr[i];\n }\n\n return sum;\n}", "function productOfArray(arr){\n if(arr.length === 0) return 1;\n\n return arr.pop() * productOfArray(arr);\n}", "function multiplies_positive_elements(a) {\n var res = [];\n var i;\n\n for (i = 0; i < a.length; i++) {\n if (a[i] > 0) {\n res[i] = a[i] * 2\n } else {\n res[i] = a[i]\n }\n }\n\n return res;\n}", "function main(arr) {\n let product = 1; //=24\n let isZero = false;\n let zerocounter = 0; //\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > 0) product = product * arr[i];\n else isZero = true;\n }\n\n let arr2 = [];\n for (let j = 0; j < arr.length; j++) {\n if (arr[j] !== 0) {\n if (!isZero) arr2[j] = product / arr[j];\n else arr2[j] = 0;\n } else arr2[j] = product;\n }\n\n return arr2;\n}", "function productOfArray(arr) {\n if (!arr.length) return 0;\n if (arr.length === 1) return arr[0];\n return arr.shift() * productOfArray(arr)\n}", "function multiplies(array) {\n var newArray = []\n for (var i = 0; i < array.length; i++) {\n if (array[i] <= 0) {\n newArray[i] = array[i]\n } else {\n newArray[i] = array[i] * 2\n }\n }\n return newArray\n}", "function productOfArray(arr){\n\n\n function helper(Arrinp){\n if(Arrinp.length === 0) return 1;\n return Arrinp[0] * helper(Arrinp.slice(1));\n }\n\n return helper(arr);\n}", "function adjacentElementsProduct(array) {\n let arr = [];\n for (let i = 0; i < array.length-1; i++)\n arr.push(array[i]*array[i+1]);\n return Math.max(...arr); \n}", "function productOfArray(arr) {\n if (arr.length === 0) return 1;\n return arr[0] * productOfArray(arr.slice(1));\n}", "function multiplyAll(arr) {\n var product = 1;\n // Only change code below this line\n for (var i=0; i < arr.length; i++) {\n for (var j=0; j < arr[i].length; j++) {\n product = product * arr[i][j];\n }\n}\n // Only change code above this line\n return product;\n}", "function mult3(arr){\n var newArray = []\n for(let i=0;i<arr.length;i++){\n newArray.push(arr[i] * 3)\n }\n return newArray\n}", "function productOfArray(arr) {\n if (arr.length === 0) return 1\n return arr[0] * productOfArray(arr.slice(1))\n}", "function arrayMultiplyAgain(num, arr) {\n const newArr = arr.map(item => item * num)\n return newArr\n}", "function productOfArray(arr) {\n if (arr.length === 0) {\n return 1;\n }\n return arr[0] * productOfArray(arr.slice(1));\n}", "function productOfArray(arr) {\n if (arr.length === 0) {\n return 1;\n }\n return arr[0] * productOfArray(arr.slice(1));\n}", "function productOfArray(arr) {\n if (arr.length === 0) {\n return 1;\n }\n return arr[0] * productOfArray(arr.slice(1));\n}", "function getAllProdsBuN(inArr) {\n var productAllButIndex = [];\n var productSoFar = 1;\n\n\n for ( var i = 0; i < intArr.length; i++ ) {\n productAllButIndex.push(productSoFar);\n productSoFar *= inArr[i]\n };\n}", "function productOfArray(arr) {\n if (arr.length === 0) return 1;\n\n return arr[0] * productOfArray(arr.slice(1));\n}", "function productOfArray(arr) {\n if(arr.length === 0) {\n return 1;\n }\n return arr[0] * productOfArray(arr.slice(1));\n}", "function productOfArray(arr) {\n let result = 1;\n function helper(helperArr) {\n if (helperArr.length === 0) {\n return;\n } else {\n result = helperArr[0] * result;\n }\n helper(helperArr.slice(1));\n }\n helper(arr);\n return result;\n}", "function computeProductOfAllElements(arr) {\n\t//if arr length is zero\n\tif (arr.length === 0) {\n\t\t// then return 0\n\t\treturn 0;\n\t}\n\t// use reduce with the starting point = 0\n\treturn arr.reduce((prev, next) => {\n\t\treturn prev * next;\n\t});\n\t// add the acc + currentVal and return it\n}", "function productCLoop(arr) {\n let output = 1;\n for (let i = 0; i < arr.length; i++) {\n output = output * arr[i]\n }\n return output;\n}", "function arrayMultiply (array1, array2){\n let arrayProduct = 0\n let i\n for (i=0;i<array1.length;i++){\n arrayProduct = arrayProduct + (array1[i]*array2[i])\n }\n return arrayProduct\n}", "function productOfArray2(arr) {\n if (arr.length === 0) {\n return 1;\n }\n return arr[0] * productOfArray(arr.slice(1));\n}", "function multiplyAll(array) {\n var result = 1;\n for (var i = 0; i < array.length; i++) {\n result *= array[i];\n }\n return result;\n}", "function productExceptSelf(nums) {\n let n = nums.length;\n if(n === 0) return nums;\n\n let result = new Array(n).fill(1);\n\n let productBefore = nums[0];\n let productAfter = nums[n-1];\n \n // 1st pass for computing product before\n for(let i=1; i<n; i++) {\n result[i] = productBefore;\n productBefore *= nums[i];\n }\n\n // 2nd pass for computing product after\n for(let i=n-2; i>=0; i--) {\n result[i] *= productAfter;\n productAfter *= nums[i];\n }\n\n return result;\n}", "function multiplies(arr){\n let result=1;\n for(i=0; i<arr.length; i++){\n result *=arr[i];\n }\n return result;\n }", "function product(nums) {\n return nums.reduce(function(prod, curr) { return prod *= curr })\n}", "function products(arr) { \n //find the product of the entire arr\n let total_product = 1;\n for (let i = 0; i < arr.length; i++) {\n total_product = total_product * arr[i];\n }\n //loop through the array and find total_product/value for each element\n let newArr = [];\n for (let i = 0; i < arr.length; i++) {\n newArr.push(total_product/arr[i]);\n }\n //return new array\n return newArr;\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 productEach(arr){\n let product = 1;\n arr.forEach(el => {\n product = product * el;\n })\n return product;\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_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 calculate(arr) {\n let product = arr.reduce((prev, curr) => prev * curr)\n return product;\n\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}" ]
[ "0.7924141", "0.75988436", "0.75666434", "0.7527754", "0.75120986", "0.74601114", "0.739436", "0.7383821", "0.73430246", "0.7331095", "0.72412246", "0.7159923", "0.7079049", "0.7061158", "0.7027686", "0.6867319", "0.6836262", "0.68275666", "0.67885095", "0.6773457", "0.67721516", "0.67307484", "0.6720501", "0.67025787", "0.6648935", "0.66468227", "0.66452825", "0.6642823", "0.6641174", "0.66016686", "0.65942544", "0.6578374", "0.6564963", "0.6559655", "0.6546091", "0.65447986", "0.65412897", "0.6541048", "0.6476563", "0.6461548", "0.646013", "0.6455401", "0.64466953", "0.6430392", "0.6411099", "0.6409924", "0.64083356", "0.63986415", "0.6395855", "0.6378519", "0.6340303", "0.6316461", "0.63151354", "0.6313129", "0.63100225", "0.6307455", "0.6306307", "0.6295294", "0.6289706", "0.62809736", "0.626659", "0.62646365", "0.62630343", "0.62580484", "0.6257913", "0.62434953", "0.6225607", "0.62236166", "0.6221435", "0.620244", "0.6199917", "0.6197364", "0.6196605", "0.61913204", "0.6186588", "0.6178849", "0.6177818", "0.6176468", "0.6172632", "0.6172632", "0.6157965", "0.6156143", "0.61455816", "0.61439663", "0.6139328", "0.6135344", "0.6124167", "0.6117998", "0.61156857", "0.6113777", "0.608942", "0.60764337", "0.6054183", "0.6035005", "0.6034281", "0.6019104", "0.6008565", "0.600258", "0.6000777", "0.5996668" ]
0.775681
1
Listen on SIGINT, SIGTERM
function controlledShutdown(signal) { console.warn(`Caught ${signal}. Removing pid-file and will then exit.`); FS.unlinkSync(pidFile); process.exit(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "handleExits() {\r\n process.on('SIGINT', () => {\r\n logger.info('Shutting down gracefully...');\r\n this.server.close(() => {\r\n logger.info(colors.red('Web server closed'));\r\n process.exit();\r\n });\r\n });\r\n }", "setupTerminationHandlers() {\n // Process on exit and signals.\n process.on('exit', () => { this.terminator(); });\n\n // Removed 'SIGPIPE' from the list - bugz 852598.\n ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',\n 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'\n ].forEach((element) => {\n process.on(element, () => { this.terminator(element); });\n });\n }", "function init() {\n // https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits\n\n process.stdin.resume();//so the program will not close instantly\n\n//do something when app is closing\n process.on('exit', exitHandler.bind());\n\n//catches ctrl+c event\n process.on('SIGINT', exitHandler.bind());\n\n// catches \"kill pid\" (for example: nodemon restart)\n process.on('SIGUSR1', exitHandler.bind());\n process.on('SIGUSR2', exitHandler.bind());\n\n//catches uncaught exceptions\n process.on('uncaughtException', exitHandler.bind());\n}", "listen() {\n this.session.on('changed', this[cookieChangedHandler]);\n ipcMain.on('open-web-url', this[openSessionWindowHandler]);\n ipcMain.handle('cookies-session-get-all', this[getAllCookiesHandler]);\n ipcMain.handle('cookies-session-get-domain', this[getDomainCookiesHandler]);\n ipcMain.handle('cookies-session-get-url', this[getUrlCookiesHandler]);\n ipcMain.handle('cookies-session-set-cookie', this[setCookieHandler]);\n ipcMain.handle('cookies-session-set-cookies', this[setCookiesHandler]);\n ipcMain.handle('cookies-session-remove-cookie', this[removeCookieHandler]);\n ipcMain.handle('cookies-session-remove-cookies', this[removeCookiesHandler]);\n app.on('certificate-error', this[handleCertIssue]);\n }", "function _safely_install_sigint_listener() {\n\n const listeners = process.listeners(SIGINT);\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n if (lstnr.name === '_tmp$sigint_listener') {\n existingListeners.push(lstnr);\n process.removeListener(SIGINT, lstnr);\n }\n }\n process.on(SIGINT, function _tmp$sigint_listener(doExit) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](false);\n } catch (err) {\n // ignore\n }\n }\n try {\n // force the garbage collector even it is called again in the exit listener\n _garbageCollector();\n } finally {\n if (!!doExit) {\n process.exit(0);\n }\n }\n });\n}", "function _safely_install_sigint_listener() {\n\n const listeners = process.listeners(SIGINT);\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n if (lstnr.name === '_tmp$sigint_listener') {\n existingListeners.push(lstnr);\n process.removeListener(SIGINT, lstnr);\n }\n }\n process.on(SIGINT, function _tmp$sigint_listener(doExit) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](false);\n } catch (err) {\n // ignore\n }\n }\n try {\n // force the garbage collector even it is called again in the exit listener\n _garbageCollector();\n } finally {\n if (!!doExit) {\n process.exit(0);\n }\n }\n });\n}", "function _safely_install_sigint_listener() {\n\n const listeners = process.listeners(SIGINT);\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n if (lstnr.name === '_tmp$sigint_listener') {\n existingListeners.push(lstnr);\n process.removeListener(SIGINT, lstnr);\n }\n }\n process.on(SIGINT, function _tmp$sigint_listener(doExit) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](false);\n } catch (err) {\n // ignore\n }\n }\n try {\n // force the garbage collector even it is called again in the exit listener\n _garbageCollector();\n } finally {\n if (!!doExit) {\n process.exit(0);\n }\n }\n });\n}", "function on_term() {\n // Close the server as a response to a terminate signal.\n if (server && server.close) {\n server.close(function() {\n // Exit with code 0 after close finishes.\n process.exit(0);\n });\n } else {\n // Exit right away if server doesn't exist or close is unavailable.\n process.exit(0);\n }\n}", "_listen() {\n let onExit = () => {\n this._log('exit signal');\n\n this._exit();\n };\n\n let onMessage = (data) => {\n if (data && data.event === SIGNAL_OUT_OF_MEMORY) {\n this.rotate();\n }\n\n this.emit('message', data);\n };\n\n let onDisconnect = () => {\n this._log('disconnect signal');\n\n if (!this.started || this._disconnecting) {\n return;\n }\n\n this._exit();\n };\n\n let onClose = () => {\n this._log('close signal');\n };\n\n this.worker.on('exit', onExit);\n this.worker.on('message', onMessage);\n this.worker.on('disconnect', onDisconnect);\n this.worker.on('close', onClose);\n }", "function HandleSigInt()\n{\n console.log(''); // (for linefeed after CTRL-C)\n Log('Exiting on SIGINT');\n Cleanup();\n // exit after giving time to log last message\n setTimeout(function() { process.exit(); }, 10);\n}", "function onExit() {\n httpServer.kill('SIGINT');\n process.exit(1);\n}", "listen() {\n /* global ipc */\n ipc.on('search-count', this._searchCoundHandler);\n ipc.on('focus-input', this._focusHandler);\n }", "_bindProcessSignals() {\n this._signalHandlers = {\n SIGINT: () => {\n this.prepareForShutdown(false);\n },\n SIGTERM: () => { // ubuntu shutdown / restart\n this.prepareForShutdown(false);\n }\n };\n process.on('SIGINT', this._signalHandlers.SIGINT);\n process.on('SIGTERM', this._signalHandlers.SIGTERM);\n }", "register() {\n process.on('uncaughtException', err => {\n console.error('Uncaught exception');\n logger_1.sendCrashResponse({ err, res: latestRes, callback: killInstance });\n });\n process.on('unhandledRejection', err => {\n console.error('Unhandled rejection');\n logger_1.sendCrashResponse({ err, res: latestRes, callback: killInstance });\n });\n process.on('exit', code => {\n logger_1.sendCrashResponse({\n err: new Error(`Process exited with code ${code}`),\n res: latestRes,\n silent: code === 0,\n });\n });\n ['SIGINT', 'SIGTERM'].forEach(signal => {\n process.on(signal, () => {\n console.log(`Received ${signal}`);\n this.server.close(() => {\n // eslint-disable-next-line no-process-exit\n process.exit();\n });\n });\n });\n }", "function shutDown() {\n console.log('Received kill signal (SIGINT || SIGTERM), shutting down gracefully');\n server.close(() => {\n console.log('Server closed');\n process.exit(0);\n });\n\n setTimeout(() => {c\n console.error('Could not close remaining connections in time, forcing server shutdown');\n process.exit(1);\n }, cleanShutdownLimit); \n}", "register() {\n process.on('uncaughtException', err => {\n console.error('Uncaught exception');\n logAndSendError(err, latestRes, killInstance);\n });\n process.on('unhandledRejection', err => {\n console.error('Unhandled rejection');\n logAndSendError(err, latestRes, killInstance);\n });\n process.on('exit', code => {\n logAndSendError(new Error(`Process exited with code ${code}`), latestRes);\n });\n process.on('SIGTERM', () => {\n this.server.close(() => {\n process.exit();\n });\n });\n }", "function handleListen() {\n console.log(\"Listening\");\n }", "function handleListen() {\n console.log(\"Listening\");\n }", "init() {\n let {\n args,\n flags\n } = this.parse();\n this.flags = flags;\n this.args = args; // sets the log level from verbose, quiet, and silent flags\n\n _logger.default.loglevel('info', flags); // ensure cleanup is always performed\n\n\n let cleanup = () => this.finally(new Error('SIGTERM'));\n\n process.on('SIGHUP', cleanup);\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n }", "listen() {\n /* global ipc */\n ipc.on('search-count', this._searchCoundHandler);\n ipc.on('focus-input', this._focusHandler);\n this.addEventListener('keydown', this._keydownHandler);\n }", "function handleListen() {\r\n console.log(\"Listening\"); //gibt Listening in der console aus \r\n }", "function onSIGINT() {\n\tconsole.error( '' );\n\tprocess.exit( 1 );\n} // end FUNCTION onSIGINT()", "async function startServer(){\n await loaders({ expressApp:app })\n server.listen(port);\n server.on('error', onError);\n server.on('listening', onListening);\n process.on('SIGINT', function(){\n mongoose.connection.close(function(){\n console.log(\"Mongoose default connection is disconnected due to application termination\");\n process.exit(0);\n });\n });\n}", "static async onSignal(signal) {\n this.logger.info('[midway:bootstrap] receive signal %s, closing', signal);\n try {\n await this.stop();\n this.logger.info('[midway:bootstrap] close done, exiting with code:0');\n process.exit(0);\n }\n catch (err) {\n this.logger.error('[midway:bootstrap] close with error: ', err);\n process.exit(1);\n }\n }", "onTerminate() {}", "function launchingServer() {\n console.info(\"Server will listen on address : \" + getIps()[0] + \" on port \" + port);\n var child = fork(\"./server.js\", [port]);\n process.on('exit', exitHandler.bind(null, child));\n process.on('SIGINT', exitHandler.bind(null, child));\n}", "function processTerminator(sig) {\n if (typeof sig === 'string') {\n process.exit(1);\n }\n console.log('%s: Node server stopped.', Date(Date.now()));\n}", "function gracefulStop (signal) {\n logger.info('Graceful Stop began because of', signal);\n server.close(() => {\n logger.info('The HTTP server is deinitialized successful');\n mongoose.connection.close(false, () => {\n logger.info('The DB connection is deinitialized successful');\n logger.info('The end of the graceful stop');\n setTimeout(() => process.exit(0), 0).unref();\n });\n });\n}", "function startServer(config) {\n var server = magikServer.createServer(config);\n server.listen(config.port, config.address, function() {\n\n if(config.open) {\n opener(config.protocol+'://'+config.address + ':' + config.port.toString());\n }\n\n displaySplashScreen();\n });\n\n // apparently this doesn't work on windows\n if(process.platform !== 'win32') {\n\n // restore on CTRL+C\n process.on('SIGINT', function() {\n try {\n onSignalInterrupt(server);\n } catch(e) {\n console.log('Hold on...'.red);\n process.exit(1);\n }\n });\n\n // restore the cursor back to normal on exit\n process.on('exit', onExit);\n }\n}", "function start() {\n listen();\n}", "function start () {\n listen()\n}", "function terminator(sig) {\n if (typeof sig === \"string\") {\n winston.info('%s: Received %s - terminating Node server ...',Date(Date.now()), sig); \n process.exit(1);\n\t app.close();\n }\n winston.info('%s: Node server stopped.'.red, Date(Date.now()) );\n}", "function listener() {\r\n if (logged == 1) return;\r\n logged = 1;\r\n cfg.port = app.address().port;\r\n csl.log('Server running on port := ' + cfg.port);\r\n // Log the current configuration\r\n for (var key in cfg) {\r\n if (key != 'spdy' || key != 'https')\r\n csl.log(key + ' : ' + cfg[key]);\r\n }\r\n\r\n // If browser is true, launch it.\r\n if (cfg.browser) {\r\n var browser;\r\n switch (process.platform) {\r\n case \"win32\":\r\n browser = \"start\";\r\n break;\r\n case \"darwin\":\r\n browser = \"open\";\r\n break;\r\n default:\r\n browser = \"xdg-open\";\r\n break;\r\n }\r\n csl.warn('Opening a new browser window...');\r\n require('child_process').spawn(browser, ['http://localhost:' + app.address().port]);\r\n }\r\n }", "function onSignalInterrupt(server) {\n\n config.windowSize = process.stdout.getWindowSize();\n arciiArt.font(' magikServer', 'Doom', 'red+bold', function(rendered) {\n console.log('\\u001B[2J\\u001B[0;0f');\n console.log(rendered);\n console.log(pad(config.windowSize[0], config.versionInfo).red);\n console.log(pad('-', config.windowSize[0], '-').grey);\n console.log('magik-server shutting down'.red);\n\n // gracefully shut down the server and exit the process\n server.close(function() {\n process.exit(0);\n });\n });\n}", "function listen_handler(){\n console.log(`Now Listening On Port ${port}`);\n}", "startServer() {\n window.addEventListener('storage', this._answerReqest.bind(this), false);\n this._startHardbeat();\n }", "function handleListen() {\n //Die handleListen-Funktion vom Typ void benötigt keine Parameter und...\n console.log(\"Listening\");\n //gibt nur \"Listening\" in der Console aus\n }", "stop() {\n if (!this.#child) {\n verboseLog('Cannot stop server as no subprocess exists');\n return;\n }\n\n verboseLog('Forcibly stopping server');\n // kill the process\n this.#child.kill('SIGINT');\n\n // ...kill it again just to make sure it's dead\n spawn('kill', ['-9', this.#child.pid]);\n }", "listen() {\n }", "function gracefulShutdown() {\n console.log('Received kill signal, shutting down gracefully.');\n server.close(() => {\n console.log('Closed out remaining connections.');\n process.exit();\n });\n // if after\n setTimeout(() => {\n console.error('Could not close connections in time, forcefully shutting down');\n process.exit();\n }, 10 * 1000);\n}", "_realStart() {\n\t\t// No known way to make it work reliably on Windows\n\t\tif (process$3.platform === 'win32') {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#rl = f$2.createInterface({\n\t\t\tinput: process$3.stdin,\n\t\t\toutput: this.#mutedStream,\n\t\t});\n\n\t\tthis.#rl.on('SIGINT', () => {\n\t\t\tif (process$3.listenerCount('SIGINT') === 0) {\n\t\t\t\tprocess$3.emit('SIGINT');\n\t\t\t} else {\n\t\t\t\tthis.#rl.close();\n\t\t\t\tprocess$3.kill(process$3.pid, 'SIGINT');\n\t\t\t}\n\t\t});\n\t}", "_cliHandlerStart()\n\t\t{\n\t\t\tif(process.stdout.isTTY)\n\t\t\t{\n\t\t\t\tkeypress(process.stdin);\n\t\t\t\tprocess.stdin.on('keypress', this._keypressHandler);\n\t\t\t\tprocess.stdin.setRawMode(true);\n\t\t\t\tprocess.stdin.resume();\n\t\t\t}\n\t\t}", "function startWorker() {\n var stdin = new net.Stream(0, 'unix'),\n app = requireApp(getAppPath());\n stdin.on('data', function (json) {\n process.sparkEnv = env = JSON.parse(json.toString());\n });\n stdin.on('fd', function(fd) {\n sys.error('Spark server(' + process.pid + ') listening on '\n + (env.socket ? 'unix socket ' + env.socket : 'http' + (env.sslKey ? 's' : '') + '://' + (env.host || '*') + ':' + env.port)\n + ' in ' + env.name + ' mode');\n enableSSL(app, env);\n app.listenFD(fd);\n });\n stdin.resume();\n\n ['SIGINT', 'SIGHUP', 'SIGTERM'].forEach(function(signal) {\n process.on(signal, function() {\n process.exit();\n });\n });\n}", "function __TRIGGER_TERMINATE_SIGNAL(...args) {\n\tprocess.emit( 'TERMINATE_SIGNAL', ...args );\n}", "stopped() {\n\t\tif (this.app.listening) {\n\t\t\tthis.app.close(err => {\n\t\t\t\tif (err)\n\t\t\t\t\treturn this.logger.error(\"Server close error!\", err);\n\n\t\t\t\tthis.logger.info(\"Server Stopped\");\n\t\t\t});\n\t\t}\n\t}", "function runServer() {\n server.listen(port);\n server.on('error', onError);\n server.on('listening', onListening);\n /**\n * Signaling Server\n */\n require('../Signaling-Server.js')(server);\n}", "function handle(signal) {\n logger.info(`Received ${signal}. Exiting...`);\n process.exit(1)\n }", "function handleClientEvents(socket) {\n socket.on(\"start\", function(data) {\n processStart(socket, data);\n });\n\n socket.on(\"stop\", function(data) {\n processStop(socket, data);\n });\n}", "kill(signal = \"SIGINT\") {\n if (running) {\n child.kill(signal);\n }\n if (unreffable) {\n unreffable.unref();\n }\n }", "doListen(registry) {}", "function startWorker(id) {\n console.log(`Started worker ${id}`);\n\n process.on(\"SIGTERM\", () => {\n console.log(`Worker ${id} exiting...`);\n console.log(\"(cleanup would happen here)\");\n process.exit();\n });\n}", "function listening(){\n\tconsole.log('listening');\n}", "function listenSubProcess(host) {\n const daemon = spawn(`./daemon/daemon`, host,\n { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] })\n // Keep the process in a store for messaging\n processes[host[2].toLowerCase()] = daemon;\n daemon.stdout.pipe(access);\n daemon.stderr.pipe(error);\n daemon.on('close', () => {\n setTimeout(() => {\n console.log(new Date(), 'Process terminated listening to', host);\n listenSubProcess(host);\n }, 1000);\n })\n\n // Every message is of form: { to, from, body }\n daemon.on('message', (message) => {\n processes[message.to.toLowerCase()].send(message);\n })\n}", "function onTerminate() {\n console.log('')\n \n // Handle Database Connection\n switch (config.schema.get('db.driver')) {\n case 'mongo':\n dbMongo.closeConnection()\n break\n case 'mysql':\n dbMySQL.closeConnection()\n break\n }\n\n // Gracefully Exit\n process.exit(0)\n}", "function destroyAndRelaunch() {\n fork(\"./server-init.js\", {detached: true});\n process.exit();\n}", "function terminate() {\n if (terminating) return\n terminating = true\n \n // don't restart workers\n cluster.removeListener('disconnect', onDisconnect)\n // kill all workers\n Object.keys(cluster.workers).forEach(function (id) {\n console.log('sending kill signal to worker %s', id)\n cluster.workers[id].kill('SIGTERM')\n })\n process.exit(0)\n }", "function listening(){console.log(\"listening. . .\");}", "startListening() {\n\t\tthis.server.listen(this.port, () => {\n\t\t\tconsole.log('Server started listening on port', this.port);\n\t\t});\n\t}", "startRfidListener() {\n const { listenAddress, listenPort } = this.store.getState().config;\n if (this.rfidListener) this.rfidListener.close();\n\n this.rfidListener = net.createServer();\n this.rfidListener.on('connection', this.handleConnection);\n\n this.rfidListener.on('error', () => {\n log.error(`Error starting server on: ${listenAddress}:${listenPort}`);\n });\n\n this.rfidListener.on('close', () => {\n // log.info('Alien Runway Server stopped.');\n });\n\n this.rfidListener.listen(listenPort, listenAddress, () => {\n log.info(`Alien Runway Server started on: ${listenAddress}:${listenPort}`);\n });\n }", "function listen() {\n app.listen(config.port, () => {\n console.log('Express server listening on %d, in %s mode', // eslint-disable-line\n config.port, app.get('env'));\n });\n}", "shutdown() {\r\n runner.stdin.write('shutdown\\n');\r\n }", "stop() {\n\t\t// Call service `started` handlers\n\t\tthis.services.forEach(service => {\n\t\t\tif (service && service.schema && isFunction(service.schema.stopped)) {\n\t\t\t\tservice.schema.stopped.call(service);\n\t\t\t}\n\t\t});\n\n\t\tif (this.metricsTimer) {\n\t\t\tclearInterval(this.metricsTimer);\n\t\t\tthis.metricsTimer = null;\n\t\t}\n\t\t\n\t\tif (this.transit) {\n\t\t\tthis.transit.disconnect();\n\n\t\t\tif (this.heartBeatTimer) {\n\t\t\t\tclearInterval(this.heartBeatTimer);\n\t\t\t\tthis.heartBeatTimer = null;\n\t\t\t}\n\n\t\t\tif (this.checkNodesTimer) {\n\t\t\t\tclearInterval(this.checkNodesTimer);\n\t\t\t\tthis.checkNodesTimer = null;\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info(\"Broker stopped.\");\n\n\t\tprocess.removeListener(\"beforeExit\", this._closeFn);\n\t\tprocess.removeListener(\"exit\", this._closeFn);\n\t\tprocess.removeListener(\"SIGINT\", this._closeFn);\n\t}", "listen() {\n this.app.listen(this.port, () => {\n console.log('Servidor ejecutandose en el puerto', this.port)\n })\n }", "function listen(fd, backlog) {\n // debug('listen', fd, backlog);\n return syscall(x86_64_linux_1.SYS.listen, fd, backlog);\n}", "function shutdown(){\n socket.emit('shutdown app');\n $('#startstopbutton').html('Start');\n msgs_received = [];\n numbers_received = [];\n}", "function onListening() \n{\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n console.log('init - awesome server');\n // logger.info('init - awesome server');\n}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "stopped() {}", "function onListening() {\n const addr = server.address()\n const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port\n mainWindow.webContents.send('listening', bind)\n}", "stopped () {}", "listen() {\n this.ipc.on('profile', this.listener.bind(this));\n }", "function startListening() {\n\tapp.listen(8080, function() {\n\t\tconsole.log(\"Sever started at http://localhost:8080 Start chatting!\");\n\t});\n}", "start() {\n this._.on('request', this.onRequest.bind(this));\n this._.on('error', this.onError.bind(this));\n this._.on('listening', this.onListening.bind(this));\n\n this._.listen(this.config.port);\n }", "function terminate() {\n if (terminating) return;\n terminating = true;\n\n // don't restart workers\n cluster.removeListener('disconnect', onDisconnect)\n // kill all workers\n Object.keys(cluster.workers).forEach(function (id) {\n console.log('[worker %s] receiving kill signal', id);\n cluster.workers[id].kill('SIGTERM');\n });\n}", "function kill() {\n require('async-each')(kill.hooks, function each(fn, next) {\n fn(next);\n }, function done(err) {\n if (err) return process.exit(1);\n\n process.exit(0);\n });\n}", "function _safely_install_exit_listener() {\n const listeners = process.listeners(EXIT);\n\n // collect any existing listeners\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n // TODO: remove support for legacy listeners once release 1.0.0 is out\n if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) {\n // we must forget about the uncaughtException listener, hopefully it is ours\n if (lstnr.name !== '_uncaughtExceptionThrown') {\n existingListeners.push(lstnr);\n }\n process.removeListener(EXIT, lstnr);\n }\n }\n // TODO: what was the data parameter good for?\n process.addListener(EXIT, function _tmp$safe_listener(data) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](data);\n } catch (err) {\n // ignore\n }\n }\n _garbageCollector();\n });\n}", "function _safely_install_exit_listener() {\n const listeners = process.listeners(EXIT);\n\n // collect any existing listeners\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n // TODO: remove support for legacy listeners once release 1.0.0 is out\n if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) {\n // we must forget about the uncaughtException listener, hopefully it is ours\n if (lstnr.name !== '_uncaughtExceptionThrown') {\n existingListeners.push(lstnr);\n }\n process.removeListener(EXIT, lstnr);\n }\n }\n // TODO: what was the data parameter good for?\n process.addListener(EXIT, function _tmp$safe_listener(data) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](data);\n } catch (err) {\n // ignore\n }\n }\n _garbageCollector();\n });\n}", "function _safely_install_exit_listener() {\n const listeners = process.listeners(EXIT);\n\n // collect any existing listeners\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n // TODO: remove support for legacy listeners once release 1.0.0 is out\n if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) {\n // we must forget about the uncaughtException listener, hopefully it is ours\n if (lstnr.name !== '_uncaughtExceptionThrown') {\n existingListeners.push(lstnr);\n }\n process.removeListener(EXIT, lstnr);\n }\n }\n // TODO: what was the data parameter good for?\n process.addListener(EXIT, function _tmp$safe_listener(data) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](data);\n } catch (err) {\n // ignore\n }\n }\n _garbageCollector();\n });\n}", "shutdown() {}", "listen() {\n this.rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });\n this.rl.on('line', (line) => {\n line = line || '';\n if (line.toLowerCase() == 'quit') {\n this.rl.close();\n process.exit();\n }\n else {\n this.receive(line);\n }\n });\n return this;\n }", "async stop() {\n // 1. Stop listening for connections at http-server \n this.server.close();\n logger.info('Server closed', {\n eventType: 'INFO',\n eventSubType: 'SERVER_NOT_LISTENING',\n });\n // 2. Serve ongoing requests \n // Wait for a given time for ongoing requests to complete.\n await wait(this.config.params.timeout);\n let numConnections = 0;\n for (const key in this.connections) {\n numConnections += 1;\n this.connections[key].destroy();\n }\n logger.info(`Closed ${numConnections} connections`, {\n eventType: 'INFO',\n eventSubType: 'CONNS_CLOSED',\n });\n }", "function listening(){\n console.log(\"server running\"); \n console.log(`running on localhost: ${port}`);\n}", "stopped() { }", "exit() {\n const { server } = this;\n server.close().then(\n () => {\n server.log.info(Strings.SHUTDOWN_MESSAGE);\n },\n (error) => {\n server.log.error(Errors.DEFAULT_ERROR, error);\n }\n )\n }", "function main() {\n // we need a port to connect to for the fun to start.\n var serverPort = env.get('FAKESERVER_IPC_PORT');\n if (!serverPort)\n return dump('pass environment variable FAKESERVER_IPC_PORT ! (stopping)');\n\n\n // initialize the handler\n var handler = new FakeServerProxyHandler(parseInt(serverPort, 10));\n}", "constructor() {\n this.#listen();\n }", "constructor() {\n this.#listen();\n }", "function listening(){\n console.log(\"server running\");\n console.log(`running on localhost: {$port}`);\n}", "function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n var startMessage = 'Server listening on ' + bind;\n console.log(startMessage);\n\n // If the process is a child process (e.g. started in Gulp)\n // then inform the parent process that the server has started.\n if (process.send) {\n process.send(startMessage);\n }\n}", "function startListening() {\n app.listen(8000, function() {\n console.log(\"server is started: http://localhost:8000 ⚡️\");\n });\n}", "function listening(){\n console.log(\"server running\"); \n console.log(`running on localhost: ${port}`);\n}", "function exit(message){\n\tconsole.log(message);\n\tconsole.log('Press any key to exit from application');\n\tprocess.stdin.setRawMode(true);\n\tprocess.stdin.resume();\n\tprocess.stdin.on('data',process.exit.bind(process,0));\n}" ]
[ "0.6797574", "0.6779071", "0.6668288", "0.64953864", "0.64800245", "0.64800245", "0.64800245", "0.64739484", "0.63946885", "0.6386353", "0.62767696", "0.6132052", "0.61204475", "0.6086918", "0.60660744", "0.60128516", "0.5998729", "0.5998729", "0.5993028", "0.59504896", "0.59458333", "0.5893166", "0.5828896", "0.5822524", "0.576738", "0.57546026", "0.57224226", "0.5713165", "0.5634271", "0.563114", "0.5628254", "0.5626021", "0.5537581", "0.5515543", "0.546201", "0.5451317", "0.54494405", "0.5418674", "0.54025024", "0.5397752", "0.53889585", "0.5387095", "0.53486043", "0.53119475", "0.52923083", "0.52835065", "0.52507156", "0.5218956", "0.52110523", "0.51915777", "0.5188568", "0.51690906", "0.51416045", "0.5110089", "0.50967354", "0.50924456", "0.5077402", "0.5074522", "0.50466716", "0.5028404", "0.5018143", "0.50148875", "0.5007725", "0.500621", "0.49982682", "0.4997863", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49926877", "0.49870133", "0.4987", "0.49867466", "0.49846897", "0.49815077", "0.49762535", "0.49729005", "0.4967985", "0.4967985", "0.4967985", "0.49675536", "0.49650976", "0.49601096", "0.49592036", "0.49590966", "0.49495086", "0.49492195", "0.4945979", "0.4945979", "0.49410886", "0.49390504", "0.4938739", "0.49136698", "0.49070048" ]
0.0
-1
Chamada de quando o elemento for exibido na tela
componentWillMount() { axios.get(baseUrl,{ crossdomain: true }) .then(resp => { this.setState({ list: resp.data }) /**salvando dentro da lista de requisições */ }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function CeEx (){\t\t// Cerrar explicación\n\tif (explicacionMostrando != ''){\n\t\tvar nodo = document.getElementById(explicacionMostrando + '_ex');\n\t\tnodo.parentNode.removeChild(nodo);\n\t}\n}", "function entramosEnEscuderia(e){\n\t\n\testamosDentroEscuderia=true;\n\t/*e.preventDefault();\n\telemento = e.target;\n\t\n\tif (elemento != todosLosPilotos[2]){\n\t\tescuderiaDestino.style.border=\"5px solid #3dd719\";\n\t}else{\n\t\tescuderiaDestino.style.border=\"5px solid #fb05b3\";\n\t}*/\n}", "function ClickAdicionarEscudo() {\n gEntradas.escudos.push({ chave: 'nenhum', obra_prima: false, bonus: 0 });\n AtualizaGeralSemLerEntradas();\n}", "function eliminaConto(e) {\n var elementoStruttura = e.data[0];\n var idx = e.data[1];\n var str = \"\";\n\n if(elementoStruttura.movimentoDettalgio && elementoStruttura.movimentoDettaglio.conto && elementoStruttura.movimentoDettaglio.conto.descrizione) {\n str = \" \" + elementoStruttura.movimentoDettaglio.conto.descrizione;\n }\n $(\"#modaleEliminazioneElementoSelezionato\").html(str);\n // Apro il modale\n $(\"#modaleEliminazione\").modal(\"show\");\n // Lego l'azione di cancellazione\n $(\"#modaleEliminazionePulsanteSalvataggio\").substituteHandler(\"click\", function() {\n eliminazioneConto(idx);\n });\n }", "function eliminaSingolo(elemento){\n\tif (confirm('Confermare la cancellazione di questo punteggio?')) { \n\tfunzioneCancella(elemento);\n }\n}", "function clickExpell() {\n if (student.firstName === \"Caroline\"){\n student.expelled = false;\n canNotExpell();\n } else {\n student.expelled = !student.expelled;\n }\n buildList();\n }", "function aterrizarElemento(e) {\n\t\t\t\te.preventDefault();\n\t\t\t\tlistaHecha.style.background = \"#99b5b9\";//cambia el color de fondo a azul cuando la tarjeta pasa por encima\n\t\t\t}", "function ClickEstilo(nome_estilo, id_select_secundario) {\n var select_secundario = Dom(id_select_secundario);\n if (nome_estilo == 'uma_arma' || nome_estilo == 'arma_escudo' || nome_estilo == 'arma_dupla' || nome_estilo == 'rajada' || nome_estilo == 'tiro_rapido') {\n select_secundario.disabled = true;\n } else if (nome_estilo == 'duas_armas') {\n select_secundario.disabled = false;\n } else {\n Mensagem(Traduz('Nome de estilo invalido') + ': ' + Traduz(nome_estilo));\n }\n AtualizaGeral();\n}", "function ocultable_click() {\n if (!edicion) {\n $(this).siblings('.ocultable-contenido').slideToggle();\n $(this).parent('.ocultable').siblings('.ocultable').children('.ocultable-contenido').slideUp()();\n }\n }", "function elementoPerteneceAEntrevista(elemento) {\n if (elemento.className.indexOf(\"perteneceEntrevista\") != -1) {\n return true;\n }\n return false;\n}", "function desclickear(e){\n movible = false;\n figura = null;\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 agregarElemento() {\n var li = document.createElement(\"li\"); //Creando elemento de tipo \"li\"\n var valor = document.getElementById(\"miValor\").value; //Devuelve el valor\n var t = document.createTextNode(valor);\n li.appendChild(t);\n if (valor === '') {\n alert(\"Debes escribir un elemento\");\n } else {\n document.getElementById(\"miListaDeTareas\").appendChild(li);\n }\n document.getElementById(\"miValor\").value = \"\";\n \n // Creando de nuevo el boton cerrar\n var span = document.createElement(\"SPAN\");\n var txt = document.createTextNode(\"\\u00D7\");\n span.className = \"cerrar\";\n span.appendChild(txt);\n li.appendChild(span);\n \n // añadiendo la funcion al boton cerrar\n for (i = 0; i < cerrar.length; i++) {\n cerrar[i].onclick = function() {\n var div = this.parentElement;\n div.style.display = \"none\";\n }\n }\n }", "function invisivel(elemento) {\n if (elemento != null) {\n elemento.style.display = \"none\";\n } else {\n alert(\"Elemento \" + elemento + \" não encontrado.\")\n }\n}", "function mostrarOcultarElemento(elemento){\n\t$(elemento).toggle();\n $(\"#general\").toggle();\n}", "function rimuoviDaiPreferiti(event) {\n event.stopPropagation();\n const sezionePreferiti = document.querySelector(\"#preferiti\");\n const icona = event.currentTarget;\n let nodi = document.querySelectorAll(\"#preferiti .item\");\n for (let nodo of nodi) { //Cerco l'elemento da riuuovere dalla sezione dei preferiti\n if (nodo.querySelector(\".titolo h1\").textContent === icona.parentNode.querySelector(\"h1\").textContent) {\n nodo.remove();\n icona.src = \"img/aggiungipreferiti.png\";\n icona.removeEventListener(\"click\", rimuoviDaiPreferiti);\n icona.addEventListener(\"click\", aggiungiPreferiti);\n if (sezionePreferiti.childNodes.length === 0)\n sezionePreferiti.parentNode.classList.add(\"hidden\");\n }\n }\n}", "function quitarSeleccion(mensaje){\n\n // Remueve la clase lesionActiva de cada elemento <li> de la lista #listaLesiones\n // Esto elimina el efecto de selección de la lesión\n $('.body_m_lesiones > .item_lesion').each(function (indice , elemento) {\n $(elemento).removeClass('lesionActiva');\n });\n\n // Remueve la clase lesionActiva de cada elemento <li> de la lista\n // #cont-barraFracturasSelectId\n // Elimina de la barra superior todas las lesiones\n $('#cont-barraFracturasSelectId li').each(function (indice , elemento) {\n $(elemento).remove();\n });\n\n // Setear variable global\n seleccion = false;\n\n var msjExito = false;\n\n // Si no hay ninguna selección no saco el mensaje de exito\n if (infoLesion.length > 0) {\n msjExito = true;\n }\n\n // Vaciar información de la selección\n infoLesion = [];\n\n // Actualizar valor de la cantidad de lesiones seleccionadas\n var bola_plus = document.getElementById('bola_plus');\n bola_plus.setAttribute('fracturasSeleccionadas' , '0');\n\n\n // Muestra la alerta si la variable mensaje es true\n // Esta condición se ejecuta cuando elimino toda la selección\n if (mensaje) {\n\n if (msjExito) {\n // alerta de exito de eliminación\n Notificate({\n tipo: 'success',\n titulo: 'Operación exitosa',\n descripcion: 'Se a eliminado la seleccion de las lesiones correctamente.',\n duracion: 4\n });\n }else {\n // alerta de información cuando no hay seleccion\n Notificate({\n tipo: 'info',\n titulo: 'Informacion:',\n descripcion: 'No hay ninguna selección.',\n duracion: 4\n });\n }\n\n }\n\n }", "function teclado(e) {\n const textoTarget = e.target.innerText;\n if (textoTarget == '--') {\n swal(\"Esta letra no esta disponible\", {\n className: \"swal-text\",\n icon: \"success\",\n });\n } else if (textoTarget == 'reset') {\n inputletras.textContent = '';\n inputNumeros.textContent = '';\n }\n\n const arregloLetrasNumeros = textoTarget.split(\"-\");\n if (terminarNumeros == true) {\n validacionNumeros(obtenerNumeroDigitado(arregloLetrasNumeros));\n } else {\n validacionLetras(obtenerLetraDigitada(arregloLetrasNumeros));\n }\n\n\n}", "function ClickDescansar(valor) {\n // Cura letal e nao letal.\n EntradasAdicionarFerimentos(-PersonagemNivel(), false);\n EntradasAdicionarFerimentos(-PersonagemNivel(), true);\n EntradasRenovaSlotsFeiticos();\n AtualizaGeralSemLerEntradas();\n AtualizaGeral();\n}", "function failedRetrieval() {\n $(\"#articleslist\").remove(\"#art0\").append(\"\\n\t<p><i class=\\\"fa fa-exclamation-triangle\\\" aria-hidden=\\\"true\\\" style=\\\"color: #AA0000;\\\"></i>&nbsp;Le notizie non sono al momento disponibili!</p>\");\n console.error(\"Errore nell'invio della richiesta di recupero notizie!\");\n}", "function insertar (idb, idp, heroe) {\n idb.onclick = (e) => {\n idp.innerHTML = heroe.formateando();\n idb.disabled = true; //Deshabilitar el botón\n console.log(e); // Para ver que el evento no se siga ejecutando\n }\n}", "function handleExeption(ex) {\n\n let alertElem = document.createElement(\"div\");\n\n alertElem.classList.add(\"alert\");\n\n setTimeout(() => {\n alertElem.classList.add(\"open\");\n }, 1);\n\n let innerElem = document.createElement(\"div\");\n innerElem.classList.add(\"alert-block\");\n alertElem.append(innerElem);\n\n let titleElem = document.createElement(\"div\");\n titleElem.classList.add(\"alert-title\");\n titleElem.append(\"Hay problemas\");\n innerElem.append(titleElem);\n\n let messageElem = document.createElement(\"div\");\n messageElem.classList.add(\"alert-message\");\n messageElem.append(ex);\n innerElem.append(messageElem);\n\n alertsDisplay.append(alertElem);\n removeAlert(alertElem);\n}", "function posarBoleta(e) {\r\n// console.log(\"has clicat el \"+ e.target.getAttribute('id'));\r\n if (numDeClics==0) {\r\n //si guanya\r\n if (e.target.getAttribute('id')==aleatorio) {\r\n resultat(\"guany\", \"Felicitats :)\");\r\n // resultat(\"Felicitats :)\");\r\n //si perd\r\n }else{\r\n // resultat(\"Torna a provar! :S\");\r\n resultat(\"perd\", \"Torna a provar! :S\");\r\n\r\n }\r\n numDeClics=numDeClics+1;\r\n }\r\n}", "function sacarDeCarrito(e) {\r\n //Obtenemos el elemento desde el cual se disparó el evento\r\n let boton = e.target;\r\n let id = boton.id;\r\n //Nos quedamos solo con el numero del ID\r\n let index = id.substring(3);\r\n\r\n carrito.splice(index, 1);\r\n\r\n //Despues que actulizamos el carrito volvemos a actualizar el DOM\r\n $(`#carrito${index}`).fadeOut(\"slow\", function () {\r\n actualizarCarritoLocal(carrito);\r\n });\r\n}", "productError() {\n\t\tthis.DOM.innerHTML = \"Oups, le produit demandé n'existe pas !\"\n\t}", "function checkIfEpisodioIsValidOrNotLVL2(episodio, it){\n if(episodio['estado'] == \"0\"){\n } else if(episodio['estado'] == \"1\"){\n $(\"#container_pendente_gdh_\"+it).html(\"<div class='episodioValidado_check'><i class='fas fa-check-circle tooltip_container' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Episódio Validado.</div></i></div>\");\n $(\"#episodio\"+it).addClass('episodioValidado');\n $(\"<i onclick='removeValidationPendenteSecretariado(\"+it+\")' class='tooltip_container removeValidation fas fa-times-circle' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Desvalidar o episódio.</div></i>\").insertAfter(\"#toggle\"+it);\n $(\"#edit\"+it).remove();\n }\n}", "exibirElemento(elemento) {\n document.getElementById(elemento).style.display = \"block\";\n }", "function habilitarMovimento(sentido, casaBaixo){\n\t\t\t\tif(sentido == 'baixo'){ baixo(casaBaixo); }\n\t\t\t\telse{ $('#baixo_btn').off(); }\n\n\t\t\t\tif(sentido == 'direita'){ direita(); }\n\t\t\t\telse{ $('#direita_btn').off(); }\n\n\t\t\t\tif(sentido == 'esquerda'){ esquerda(); }\n\t\t\t\telse{ $('#esquerda_btn').off(); }\n\t\t\t}", "function ControleErreur(){\n//récupération des valeurs nécessaires à la validation d'un ajout ou d'une modification\n\tvar nom = document.getElementById(\"txtNom\").value;\n\tif(nom != \"\")\n\t{\n\t\t//Le boutton redevient clicable\n\t\tdocument.getElementById(\"cmdCreerProjet\").disabled = false;\n\t\tdocument.getElementById(\"cmdCreerProjet\").className = \"button\";\t\n\t}\n\telse {\n\t\t//Le boutton d'ajout devient inclicable\n\t\tdocument.getElementById(\"cmdCreerProjet\").disabled = true;\n\t\tdocument.getElementById(\"cmdCreerProjet\").className = \"\";\n\t}\n}", "function confermaCespite(){\n \tvar uids = \tfiltraCespitiSelezionati.bind(this)();\n \tvar numeroCespiti = uids.length;\n \tvar event;\n\n // Se non ho selezionato sufficienti predocumenti, fornisco un messaggio di errore ed esco\n if(!numeroCespiti) {\n impostaDatiNegliAlert(['Necessario selezionare almeno un cespite da collegare.'], this.$alertErrori);\n return;\n }\n this.$alertErrori.slideUp();\n\t event = $.Event('cespitiCaricati', {'uidsCespiti': uids});\n $document.trigger(event);\n this.$modale.modal('hide');\n }", "function abreAviso(texto, modo, cor){ \n modo = ((modo === undefined) || (modo === ''))? 'ok': modo;\n cor = ((cor === undefined) || (cor === ''))? 'ok': cor;\n \n $(\"#popFundo\").fadeIn();\n $(\"#avisoTexto\").html(texto);\n $(\"#aviso\").addClass(\"avisoEntrada\");\n \n\n}", "function ClickGerarElite() {\n GeraElite();\n AtualizaGeral();\n}", "function inserisciOspitiDaAccettare(listaOfferte){\r\n //nascondo gli esempi\r\n $(\"#div-offerta-da-accettare-esempio\").css('display','none');\r\n for(var i=0;i < listaOfferte.length;i++){\r\n var docId = listaOfferte[i].id;\r\n\r\n //Se l'ospite ancora non esiste e se l'offerta non è stata caricata la carico\r\n if(!listaOfferte[i].value.ospitato && !offerteInCuiUtentePresente[docId]){\r\n offerteInCuiUtentePresente[docId] = listaOfferte[i].value;\r\n creaWrapperPerOfferta(listaOfferte[i].value);\r\n }\r\n\r\n }\r\n}", "function articuloTomado(e) {\n e.preventDefault(); \n\n let articulo;\n if ( e.target.classList.contains(\"llevar-articulo\") ) {\n // toma el elementoHTML del articulo.\n // take the article's htmlElement.\n articulo = e.target.parentElement.parentElement;\n leerDatosDeArticulo(articulo);\n }\n}", "function ClickGerarAleatorioElite() {\n GeraAleatorioElite();\n AtualizaGeral();\n}", "function escreveConteudo(){}", "function etapa4() {\n \n //recebe a quantidade de funcionario selecionado\n var qtdFuncionario = document.getElementById('qtdFuncioanrio').value;\n \n //verifica se tem pelo menos 1 funcionario\n if(qtdFuncionario == 0){\n \n msgTratamentoEtapa3.textContent = \"Não foi possível seguir para a 4º Etapa! É obrigatório adicionar no mínimo um animador. =)\" \n \n }else{\n \n msgTratamentoEtapa3.innerHTML = \"\";\n \n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"4º Etapa - Pacote & Adicionais\"; \n \n document.getElementById('selecionarPacotes').style.display = ''; //habilita a etapa 4\n document.getElementById('selecionarFuncionarios').style.display = 'none'; //desabilita a etapa 3 \n }\n \n }", "function_Cargando(elemento){\n if(this.cargando){\n return elemento.innerHTML = \"<span class='cargaterri'>Creando territorio...<i class='fa fa-spinner fa-spin' style='font-size:30px'></i></span>\";\n }\n elemento.innerHTML = \"\";\n }", "function soltarElemento(e) {\n\t\t\t\te.stopPropagation();\n \t\t\te.preventDefault();\n \t\t\tdata = e.dataTransfer.getData(\"text\");\n \t\t\tlistaHecha.appendChild(document.getElementById(data));\n\t\t\t}", "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}", "function choiceSano(id) { \r\n \r\n //recupero coordinata x del cestino e dell'elemento cliccato\r\n var posizione = document.getElementById(id).getAttribute('position');\r\n var xCestino = document.getElementById(\"cestino\").getAttribute(\"position\").x;\r\n var xImg = posizione.x;\r\n var aelem;\r\n \r\n //recupero il numero dell'id che ha generato il click\r\n var num = parseInt(id.charAt(id.length-1));\r\n\r\n //se l'altro elemento è stato spostato torna alla sua posizione originaria\r\n if(num==1) {\r\n document.getElementById(\"elm2\").setAttribute(\"position\", {x: parseFloat(pos2[0]), y: parseFloat(pos2[1]), z: parseFloat(pos2[2])});\r\n aelem = 'elm2';\r\n }\r\n else if(num=2) {\r\n document.getElementById(\"elm1\").setAttribute(\"position\", {x: parseFloat(pos1[0]), y: parseFloat(pos1[1]), z: parseFloat(pos1[2])});\r\n aelem = 'elm1';\r\n }\r\n else \r\n console.log('errore');\r\n \r\n //sposto se non arriva al cestino, fase di scelta iniziata\r\n if(xImg < xCestino+0.2)\r\n document.getElementById(id).setAttribute(\"position\", {x:xImg+0.2, y:2.5, z:posizione.z});\r\n \r\n //butto nel cestino (si avvicina al cestino e sparisce dopo timeout) nonappena raggiungo il cestino stesso e parte la valutazione per feedback\r\n else {\r\n document.getElementById(id).setAttribute(\"position\", {x: xCestino+0.2, y: 1.5, z: posizione.z});\r\n document.getElementById(id).removeAttribute('onmouseenter');\r\n document.getElementById(aelem).removeAttribute('onmouseenter');\r\n setTimeout(function() {\r\n document.getElementById(id).setAttribute(\"visible\", false);\r\n document.getElementById(aelem).setAttribute(\"visible\", false);\r\n }, 1000);\r\n \r\n feedbackSano(id); \r\n } \r\n \r\n}", "function agregar_nuevo_producto(item_nuevo){\r\n //ALERTA DE CONFIRMACION QUE SE AGREGO UN NUEVO PRODUCTO\r\n const alert = document.querySelector('.alert');\r\n setTimeout(function(){\r\n alert.classList.add('hide')\r\n }, 2000)\r\n alert.classList.remove('hide')\r\n //AGREGANDO NUEVO ELEMENTO AL CARRITO\r\n const input_elemento = tbody.getElementsByClassName('input_elemento')\r\n for (let i =0; i< carrito.length; i++){\r\n if (carrito[i].nombre.trim() === item_nuevo.nombre.trim()){\r\n carrito[i].cantidad ++;\r\n const valor = input_elemento[i]\r\n valor.value++;\r\n total_carrito()\r\n return null;\r\n };\r\n };\r\n carrito.push(item_nuevo);\r\n tabla_carrito();\r\n}", "function mostraNotas(){}", "function intento(letra) {\r\n //document.getElementById(letra).disabled = true;\r\n if(palabra.indexOf(letra) != -1) {\r\n for(var i=0; i<palabra.length; i++) {\r\n if(palabra[i]==letra){\r\n oculta[i] = letra;\r\n }\r\n }\r\n hueco.innerHTML = oculta.join(\"\");\r\n document.getElementById(\"acierto\").innerHTML = \"Correcto!\";\r\n document.getElementById(\"acierto\").className += \"acierto verde\";\r\n }else{\r\n cont--;\r\n document.getElementById(\"intentos\").innerHTML = cont;\r\n document.getElementById(\"acierto\").innerHTML = \"Incorrecto\";\r\n document.getElementById(\"acierto\").className += \"acierto rojo\";\r\n document.getElementById(\"image\"+cont).className += \"fade-in\";\r\n }\r\n compruebaFin();\r\n setTimeout(function () { \r\n document.getElementById(\"acierto\").className = \"\"; \r\n }, 750);\r\n}", "function handlerAlert() {\r\n for (let campo of document.getElementsByClassName(\"erroreSpecifico\")) {\r\n console.log(campo);\r\n if(campo.style.display === \"block\") {\r\n setAlertDivVisible();\r\n //console.log(\"campo alert visibile!\");\r\n return;\r\n }\r\n }\r\n setAlertDivInvisible();\r\n //console.log(\"campo alert invisibile!\");\r\n}", "function habilitaDesabilitaBotaoAvancar(){\n\tif(clicked == errosExistentes){ // se a quantidade de marcacoes for igual aa quantidade de erros\n\t\t$(\"input\").addClass(\"enable\");// habilita o botao\n\t\t$(\"input\").addClass(\"hover\"); // permite que o mouse fique no formato de maozinha ao ser passado por cima do botao\n\n\t\t$(\"input\").removeClass(\"disable\"); // remove a class de desabilitado\n\n\t} else{ // se nao desabilita o botao novamente\n\n\t\t$(\"input\").removeClass(\"enable\");\n\t\t$(\"input\").removeClass(\"hover\");\n\t\t$(\"input\").addClass(\"disable\");\n\t}\n}", "function validarResaltarAlHacerClick(event) {\r\n}", "function tehty(event){\n var emoNimi=document.getElementById(this.id).parentElement.id;\n var emoElem=document.getElementById(emoNimi);\n emoElem.style.textDecoration = 'line-through';\n}", "function agregar(){\n // Elemento ingresado en el textbox\n var elemento = document.getElementById('elemento');\n // Verificacion de repeticion de valores\n var repe = cola.verificar(spc_elemento.value);\n var chek_Repe = btn_Repetir.checked;\n if (repe == true && chek_Repe == true){\n \n alert(\"No se pueden repetir valores\");\n spc_elemento.value =\"\";\n spc_elemento.focus();\n \n } else {\n agregar2(spc_elemento,spc_elemento.value);\n }\n}", "function showInvalidErrorArchivo(){\n\t\tvar msg = 'Este archivo está dañado o es ilegible, intenta con un nuevo archivo.';\n\n\t\t$('#archivo-invalido').remove();\n\t\t$('.lineas-archivo .extra-info').hide();\n\t\t$('.lineas-archivo .add-lines-ge-mod' ).append('<div class=\"error-dd error\" id=\"archivo-invalido\">'+msg+'</div>');\n\t\t$('#archivo').parent().addClass('error');\n\n\t\t$('#autogestion-form').find('button[type=\"submit\"]').prop('disabled', true);\n\t}", "function checkIfEpisodioIsValidOrNotLVL1(episodio, it){\n if(meuServico['dupla_validacao_equipa'] == '1'){\n if(episodio['estado'] == \"0\"){\n $(\"#container_pendente_secretariado_\"+it).html(\"\");\n } else if(episodio['estado'] == \"1\"){\n $(\"#container_pendente_gdh_\"+it).html(\"<div class='episodioValidado_check'><i class='fas fa-check-circle tooltip_container' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Episódio Validado.</div></i></div>\");\n $(\"#episodio\"+it).addClass('episodioValidado');\n $(\"#edit\"+it).remove();\n }\n } else {\n if(episodio['estado'] == \"1\"){\n $(\"#container_pendente_gdh_\"+it).html(\"<div class='episodioValidado_check'><i class='fas fa-check-circle tooltip_container' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Episódio Validado.</div></i></div>\");\n $(\"#episodio\"+it).addClass('episodioValidado');\n $(\"<i onclick='removeValidationPendenteSecretariado(\"+it+\")' class='tooltip_container removeValidation fas fa-times-circle' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Desvalidar o episódio.</div></i>\").insertAfter(\"#toggle\"+it);\n $(\"#edit\"+it).remove();\n } \n }\n}", "function dispararEvento(elemento, evento){\r\n\tevento = evento.toLowerCase();\r\n\tif(ExpYes){\r\n\t\tvar evObj = document.createEventObject();\r\n\t\telemento.fireEvent(evento, evObj);\r\n\t}\r\n\telse{\r\n\t\tvar evObj = document.createEvent('MouseEvents');\r\n\t\tevObj.initMouseEvent( evento.replace(\"on\",\"\"), true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );\r\n\t\telemento.dispatchEvent(evObj);\r\n\t}\t\t\r\n}", "function aggiornaConto(e) {\n alertErrori.slideUp();\n alertInformazioni.slideUp();\n\n // Popolo i dati\n var elementoStruttura = e.data[0];\n var idx = e.data[1];\n\n // Popolo i dati del conto\n var dareAvere = elementoStruttura.contoTipoOperazione.operazioneSegnoConto._name;\n var importo = elementoStruttura.movimentoDettaglio && elementoStruttura.movimentoDettaglio.importo || 0;\n $(\"input[type='radio'][data-\" + dareAvere + \"]\").prop('checked', true);\n // Disabilito i radio se e' da causale\n $(\"input[type='radio'][data-DARE], input[type='radio'][data-AVERE]\").prop('disabled', $(\"#HIDDEN_contiCausale\").val() === \"true\");\n\n $(\"#segnoConto\").val(elementoStruttura.contoTipoOperazione.operazioneSegnoConto._name);\n $(\"#importoModale\").val(importo.formatMoney());\n\n // Imposto l'indice\n $(\"#indiceContoModale\").val(idx);\n // Apro il modale\n alertErroriModale.slideUp();\n $(\"#modaleAggiornamentoConto\").modal(\"show\");\n }", "function checkIfEpisodioIsValidOrNotLVL3(episodio, it) {\n if(episodio['estado'] == \"0\"){\n $(\"#container_pendente_secretariado_\"+it).html(\"<div class='simulatedCheckbox_unchecked'></div>\");\n $(\"#edit\"+it).remove();\n }\n else if(episodio['estado'] == \"2\"){\n $(\"#container_pendente_pagamento_\"+it).html(\"<div class='episodioValidado_check'><i class='fas fa-check-circle tooltip_container' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Episódio Validado.</div></i></div>\");\n $(\"#episodio\"+it).addClass('episodioValidado');\n $(\"<i onclick='removeValidationPendenteGDH(\"+it+\")' class='tooltip_container removeValidation fas fa-times-circle' onmouseover='showTooltip(this)' onmouseout='hideTooltips()'><div class='tooltip right_tooltip'>Desvalidar o episódio.</div></i>\").insertAfter(\"#toggle\"+it);\n $(\"#edit\"+it).remove();\n }\n}", "function deleteCheck(event) {\r\n const item = event.target;\r\n\r\n //verificam daca cea mai de sus clasa(adica sa nu dam click in body say html) e clasa delete sau check\r\n if (item.classList[0] === \"delete-btn\") {\r\n const todo = item.parentElement;\r\n //animatia\r\n todo.classList.add(\"deleted\");\r\n //stergem la finalul tranzitiei\r\n todo.addEventListener(\"transitionend\", function () {\r\n todo.remove();\r\n removeTodos(todo);\r\n isCheckedDelete(todo.innerText)\r\n });\r\n }\r\n if (item.classList[0] === \"complete-btn\") {\r\n const todo = item.parentElement;\r\n //toggle pt a avea varianta de click again pt revenire\r\n todo.classList.toggle(\"completed\");\r\n if(todo.classList.contains(\"completed\")){\r\n //localStorage.setItem(\"checked\", \"x\")\r\n console.log(todo.innerText);\r\n isChecked(todo.innerText);\r\n }else {\r\n isCheckedDelete(todo.innerText);\r\n }\r\n }\r\n}", "function validerAmEdi(){\n var result=true;msg=\"\";\n if(document.getElementById(\"txtedNomEditeur\").value==\"\")\n msg=\"ajouter un Nom d'Editeur s'il te plait\";\n // if(msg==\"\" && document.getElementById(\"cboxedPays\").value==0)\n // msg=\"ajouter un pays s'il te plait\";\n if(msg==\"\" && document.getElementById(\"cboxedVill\").value==0)\n msg=\"ajouter una ville s'il te plait\";\n if(msg!=\"\") {\n // bootbox.alert(msg);\n bootbox.alert(msg);\n result=false;\n }\n return result;\n}// end valider", "function pinchar(e) {\n\n document.getElementById(e.target.id).remove();\n txtBolasEliminadas.text(`Bolas Eliminadas : ${eliminadas+=1}`);\n }", "function cerrarPoligono(){\n if(poligono.getTamanio()>=3){\n poligono.cerrar();\n // lo agrego al arreglo de poligonos\n poligonos[poligonos.length-1] = poligono;\n cerrado = true;\n\n\n }\n\n}", "function end(){\n //window.alert(\"clicked the x\");\n var el = document.getElementById(\"not\");\n el.style.display = 'none';\n }", "function redirecionar3(elemento) {\n elemento.innerHTML = \"O texto mudou!!!\";\n}", "function nuevoPuntoMitigacion(element) {\n if (nuevoPunto) {\n document.getElementById(element.id).className = \"btnMitigacion btn filters\";\n }\n else {\n document.getElementById(element.id).className = \"btnMitigacion_Pressed btn filters\";\n }\n\n nuevoPunto = !nuevoPunto;\n}", "function confirmarCompra (){\n $('#grillaContainer').fadeOut()\n grillaFinal.removeClass('d-none')\n if (carrito.length !=0){\n changuito.verTotal(grillaFinal)\n }\n $('#1cuota').click()\n}", "onClickCheckBtn(e) {\n const item = e.target.parentNode;\n if(item.hasAttribute(\"completed\")) {\n this.cancelItem(item);\n } else {\n this.selectItem(item);\n }\n }", "function nascondiIngredienti(event){\r\n const arrow = event.currentTarget;\r\n //Cambia l'orientamento della freccia\r\n arrow.src = \"images/arrow_down.png\";\r\n //Rimuove l'attuale event listener\r\n arrow.removeEventListener('click', nascondiIngredienti);\r\n //Aggiunge l'event listener per nasconderli\r\n arrow.addEventListener('click', mostraIngredienti);\r\n //Seleziona il blocco\r\n const blocco_padre = arrow.parentNode;\r\n const descr = blocco_padre.childNodes[3];\r\n //E lo nasconde\r\n descr.classList.add('hidden');\r\n}", "function statusSaveTour(resultado){\n\n\tif (resultado.indexOf(\"EXITO\")==-1) {\n\t\t//algo ocurrio mal\n\t\talert(resultado);\n\t} \t\t \n\telse {\n\t\talert(\"Horario agregado con EXITO!\");\n\t\t$(\"#formHorariosTour\").trigger(\"reset\");\n\t\tloadTours();\n\t}\n\n}", "function bloccoBottoneRecensioneLibro() {\n \"use strict\";\n if (document.contains(document.getElementById(\"inserisci_recensione_libro\"))) {\n document.getElementById(\"inserisci_recensione_libro\").disabled = true;\n document.getElementById(\"inserisci_recensione_libro\").style.cursor = \"default\";\n }\n}", "function btnClick() {\n\t//On écoute l'évènement du clic sur le bouton d'ajout au panier\n\tbouton.addEventListener(\"click\", () => {\n\t if (quantiteProduit.value >= 1 && quantiteProduit.value <= 20) { //On borne la quantité entre 1 et 20 articles\n\t\t //Si la quantité est correcte, on lance la fonction pour ajouter notre produit\n\t\t ajouterProduit();\n\t\t // Puis on réinitialise l'input de quantité à 1\n\t\t quantiteProduit.value = 1;\n\t\t} else { //Si une mauvaise quantité de produits a été entrée, on affiche un message d'erreur\n\t\terreurQte.style.color = \"#ba7894\";\n\t\terreurQte.style.fontWeight = \"bold\";\n\t\terreurQte.innerHTML = \"La quantité doit être d'au moins 1 article et ne doit pas excéder 20 articles.\";\n\t\tsetTimeout(function() {\n\t\t\terreurQte.innerHTML = \"\";\n\t\t},5000);\n\t}\n});\n}", "function alertaPorCantidad(domElement){\n domElement.setAttribute(\"type\",\"disabled\");\n domElement.setAttribute(\"placeholder\",\"Ingrese por favor la cantidad de dinero\")\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 editzselex_cancel()\n{\n Element.update('zselex_modify', '&nbsp;');\n Element.show('zselex_articlecontent');\n editing = false;\n return;\n}", "function validerEdi(){\n var result=true;msg=\"\";\n if(document.getElementById(\"txtediNom\").value==\"\")\n msg=\"ajouter un Nom d'Editeur s'il te plait\";\n if(msg==\"\" && document.getElementById(\"cboxedicodeville\").value==\"\")\n msg=\"ajouter une ville s'il te plait\";\n if(msg!=\"\") {\n // bootbox.alert(msg);\n bootbox.alert(msg);\n result=false;\n }\n return result;\n}// end valider", "function funzione_nascondi(event){\n const elemento=event.currentTarget;\n const nodoSup=elemento.parentNode;\n const listaDesc=nodoSup.querySelectorAll(\".descrizione\");\n for(let singoloDesc of listaDesc){\n singoloDesc.classList.add('nascondi');\n }\n const mostra=nodoSup.querySelector(\".mostra\");\n mostra.classList.remove('nascondi');\n}", "function proposer(element){\n\t\t\t\t\t\n\t\t\t\t\t// Si la couleur de fond est lightgreen, c'est qu'on a déja essayé - on quitte la fonction\n\t\t\t\t\tif(element.style.backgroundColor==\"lightGreen\" ||fini) return;\n\t\t\t\t\t\n\t\t\t\t\t// On récupere la lettre du clavier et on met la touche en lightgreen (pour signaler qu'elle est cliqu�e)\n\t\t\t\t\tvar lettre=element.innerHTML;\n\t\t\t\t\tchangeCouleur(element,\"lightGrey\");\n\t\t\t\t\t\n\t\t\t\t\t// On met la variable trouve false;\n\t\t\t\t\tvar trouve=false;\n\t\t\t\t\t\n\t\t\t\t\t// On parcours chaque lettre du mot, on cherche si on trouve la lettre s�l�ectionn�e au clavier\n\t\t\t\t\tfor(var i=0; i<tailleMot; i++) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Si c'est le cas :\n\t\t\t\t\t\tif(tableauMot[i].innerHTML==lettre) {\n\t\t\t\t\t\t\ttableauMot[i].style.visibility='visible';\t// On affiche la lettre\n\t\t\t\t\t\t\ttrouve=true;\n\t\t\t\t\t\t\tlettresTrouvees++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// Si la lettre n'est pas présente, trouve vaut toujours false :\n\t\t\t\t\tif(!trouve){\n\t\t\t\t\t\tcoupsManques++;\n\t\t\t\t\t\tdocument.images['pendu'].src=\"asset/image/pendu_\"+coupsManques+\".jpg\"; // On change l'image du pendu\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Si on a rate 9 fois :\n\t\t\t\t\t\tif(coupsManques==8){\n\t\t\t\t\t\t\talert(\"Vous avez perdu !\");\n\t\t\t\t\t\t\tfor(var i=0; i<tailleMot; i++) tableauMot[i].style.visibility='visible';\n\t\t\t\t\t\t\tfini=true;\n\t\t\t\t\t\t\t// on affiche le mot, on fini le jeu\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(lettresTrouvees==tailleMot){\n\t\t\t\t\t\talert(\"Bravo ! Vous avez découvert le mot secret !\");\n\t\t\t\t\t\tfini=true;\n\t\t\t\t\t}\n\t\t\t\t}", "function MenuElementoCheck(objeto)\n{\n\tdebugger;\n\tvar IdObjeto=$(this).attr('Elemento');\n\tvar Estado=localStorage[\"hjm_elm\"+IdObjeto];\n\tvar color;\n\tvar obj=DarObjeto(IdObjeto);\n\tif(Estado==\"1\")\n\t\t{\n\t\t\tEstado=\"0\";\n\t\t\tcolor=\"#DFE0DF\";\n\t\t\tobj.set(\"Visible\",false);\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEstado=\"1\";\n\t\t\tcolor=\"#000000\";\n\t\t\tobj.set(\"Visible\",true);\n\t\t\t\n\t\t}\n\t\t\n\t\tlocalStorage[\"hjm_elm\"+IdObjeto]=Estado;\n\t\t$(this).attr(\"Estado\",Estado);\n\t\t$(\"#check\"+IdObjeto).css(\"color\",color);\n\t\t\n\t\n\t\n}", "function mOut(src) {\r\n\t/*\r\n\tif (!src.contains(event.toElement)) {\r\n\t src.style.cursor = 'default';\r\n\t}\r\n\t*/\r\n\t//\tCON INTERNETEXPLORER VIEJO DA ERROR.... COMPROBAR QUE CON LAS DEMAS NO LO DA\r\n}", "function CambioExamen()\n{\n\t$('label#MensajeEliminar').css('display','none');\n}", "cerrarItem(id, titulo){\n\t\taxios.get(`x/v1/ite/item/id/${id}`)\n\t\t.then(res=>{\n\t\t\tconsole.log(res.data.mensaje[0].asignados)\n\t\t\tlet data = []\n\t\t\tres.data.mensaje[0].asignados.filter(e=>{\n\t\t\t\tdata.push(e.nombre)\n\t\t\t})\n\t\t\tdata = data.join('\\n')\n\t\t\tAlert.alert(\n\t\t\t\t`Estas seguro de cerrar ${titulo}, luego no podras abrirlo`,\n\t\t\t\t`los usuarios que quedaran asignados son:\\n ${data}`,\n\t\t\t[\n\t\t\t\t{text: 'Mejor Luego', onPress: () => console.log('OK Pressed')},\n\t\t\t\t{text: 'Si Cerrar', onPress: () => this.confirmaCerrarItem(id)},\n\t\t\t],\n\t\t\t\t{ cancelable: false }\n\t\t\t)\n\t\t})\n\t\t\n\t}", "function rimuovi_preferiti(event){\n const elemento=event.currentTarget;\n const nodoSup=elemento.parentNode;\n nodoSup.remove();\n const lista_slot=document.querySelectorAll(\"#preferiti div h1\");\n if(lista_slot.length<=0){\n document.querySelector(\"#box_pref\").classList.add(\"nascondi\");\n }\n}", "function funzione_mostra(event){\n const elemento=event.currentTarget;\n elemento.classList.add('nascondi');\n const nodoSup=elemento.parentNode;\n const listaDesc=nodoSup.querySelectorAll(\".descrizione\");\n for(let singoloDesc of listaDesc){\n singoloDesc.classList.remove('nascondi');\n }\n const meno=nodoSup.querySelector(\".meno\");\n meno.addEventListener(\"click\", funzione_nascondi);\n}", "function visivel(elemento) {\n if (elemento != null) {\n elemento.style.display = \"\";\n } else {\n alert(\"Elemento \" + elemento + \" não encontrado.\")\n }\n}", "function setAlert(){\n if (comprobarFormulario()) {\n $('<form>')\n .addClass('pre-form')\n .append(createInput(INTIT, 'text', 'Titulo del boton'))\n .append(createInput(INCONT, 'text', 'Contenido del alert'))\n .append(inputBotones(click))\n .appendTo('body');\n }\n\n /**\n * Funcion que realiza la craeción del alert.\n * @param {Event} e Evento que ha disparado esta accion.\n */\n function click(e) {\n e.preventDefault();\n var contenido = $('#'+INCONT).val();\n var titulo = $('#'+INTIT).val();\n if (titulo && contenido) {\n divDraggable()\n .append(\n $('<button>')\n .html(titulo)\n .data('data', contenido)\n .on('click', (e)=>{\n alert($(e.target).data('data'));\n })\n )\n .append(botonEliminar())\n .appendTo('.principal');\n $(e.target).parents('form').remove();\n } else {\n alert('Rellene el campo de \"Titulo\" y \"Contenido\" o pulse \"Cancelar\" para salir.');\n }\n }\n}", "function animerPente() {\n\ttriangle.setAttribute({\n\t\tvisible : true\n\t});\n\tif ( typeof bullePente != \"undefined\") {//si l'object existe on le detruis.\n\t\tboard.removeObject(bullePente);\n\t}\n\tbullePente = board.create('text', [-2, 0, \" La pente = \" + dynamiqueA()], {\n\t\tanchor : triangle,\n\t\tstrokeColor : \"#fff\",\n\t\tcssClass : 'mytext'\n\t});\n\tbullePente.on('move', function() {//function pour cacher le bulles avec un event.\n\t\tboard.removeObject(bullePente);\n\t});\n\ttriangle.on('move', function() {//function pour cacher le bulles avec un event.\n\t\tbullePente.update();\n\t});\n}", "function rimuoviPreferiti(event) {\n const icona = event.currentTarget;\n const sezionePreferiti = document.querySelector(\"#preferiti\");\n icona.src = \"img/aggiungipreferiti.png\";\n icona.removeEventListener(\"click\", rimuoviPreferiti);\n icona.addEventListener(\"click\", aggiungiPreferiti);\n icona.parentNode.parentNode.remove();\n if (sezionePreferiti.childNodes.length === 0) {\n sezionePreferiti.parentNode.classList.add(\"hidden\");\n }\n let nodi = document.querySelectorAll(\"#container .item\");\n for (let nodo of nodi) { //Cerco l'elemento tra tutti i cerchi per poter modificare l'icona e riassegnare il giusto listener\n if (nodo.querySelector(\".item h1\").textContent === icona.parentNode.querySelector(\"h1\").textContent) {\n nodo.querySelector(\".titolo img\").src = \"img/aggiungipreferiti.png\";\n nodo.querySelector(\".titolo img\").removeEventListener(\"click\", rimuoviDaiPreferiti);\n nodo.querySelector(\".titolo img\").addEventListener(\"click\", aggiungiPreferiti);\n }\n }\n}", "function borrarFila(elemento){\n $(\"tr[name=\" + elemento + \"]\").fadeOut(600, function(){\n var x = $(this).attr(\"name\");\n $.ajax({\n url: \"../Controller/administracion.php\",\n method: \"GET\",\n data: \"borradoEvento=\" + x,\n success: function(){\n $(\".dialog\").dialog( \"close\" );\n //llama a la función de paginacion\n eventosPaginados();\n }\n });\n }); \n }", "function editCompletedTasks(e) {\r\n if (e.target.classList.contains('fas')) {\r\n if (confirm('Are you Sure ?')) {\r\n e.target.parentElement.parentElement.remove();\r\n removeComFromLS(e.target.parentElement.parentElement);\r\n }\r\n }\r\n}", "function extraer_elemento(mensaje) {\n let elemento = mensaje.elemento;\n delete mensaje.elemento;\n return elemento;\n}", "function onyeshaYaliyomo(kiungo, e, rangi, id) {\n e.preventDefault();\n let viungo, yaliyomo;\n viungo = document.getElementsByClassName(\"kiungo\");\n yaliyomo = document.getElementsByClassName(\"yaliyomo\");\n\n // ficha 'yaliyomo' zote kabla ya yote\n for (let index = 0; index < yaliyomo.length; index++) {\n const element = yaliyomo[index];\n element.style.display = \"none\";\n }\n\n // Ondoa darasa la 'hai' kwenye viungo vyote\n for (let index = 0; index < viungo.length; index++) {\n const kiungo = viungo[index];\n kiungo.className = kiungo.className.replace(\" hai\", \"\");\n kiungo.style.backgroundColor = \"transparent\";\n }\n\n // Onyesha kiungo hai na Yaliyomo yake\n kiungo.className += \" hai\";\n kiungo.style.backgroundColor = rangi;\n let yaliyomoHai = document.getElementById(id);\n let seksheni = document.getElementById(\"tabu-kurasa-nzima\");\n yaliyomoHai.style.display = \"block\";\n // yaliyomoHai.style.backgroundColor = rangi;\n seksheni.style.backgroundColor = rangi;\n}", "function voltarEtapa5() {\n \n msgTratamentoEtapa6.innerHTML = \"\";\n \n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"5º Etapa - Valores Adicionais & Desconto\";\n\n document.getElementById('inserirValorAdicional').style.display = ''; //habilita a etapa 5\n document.getElementById('inserirDespesas').style.display = 'none'; //desabilita a etapa 6\n }", "function borrarDelCarrito(e){\n\tif (e.target.classList.contains(\"borrar-curso\")) {\n\t\tlet elemento = e.target.parentElement.parentElement;\n\t\telemento.remove();\n\t\tbotonVacio.textContent = \"Productos en carrito: \"+productos.children.length;\n\t}\n\n\tif (productos.children.length === 0) {\n\t \tbotonVacio.textContent = `Carrito Vacio`;\t\n\t}\n\n}", "function fBuscarEjsPE() {\n hideEverythingBut(\"#ejerciciosBusquedaPE\");\n //la limpieza de búsquedas se hará al terminar sesión, de modo que al volver a la búsqueda, se podrá ver la última búsqueda realiza y sus resultados\n}", "function onClickBtnSuppr(e) {\n e.preventDefault();\n\n //On recupere l'identifiant de l'equipe stocker en attribut\n let idEquipe = $(this).attr(\"idequipe\");\n\n //On execute la requete sur le serveur distant\n let request = constructRequest(\"index.php?page=equipesupprws&id=\" + idEquipe);\n\n //En cas de succe de la requete\n request.done(function( infos ) {\n //on affiche le message envoyer par le controleur (succé ou echec) tout en rechargeant les equipes\n showPopup(infos.popup_message, infos.popup_type);\n loadEquipes();\n });\n}", "function inputStatus(status, elemento){\n\tclasses = status ? 'fa fa-check text-success' : 'fa fa-times text-danger';\n\telemento.after('<i class=\"status-icon ' + classes + '\" style=\"position: absolute; right: -2px; top: 8px;\"></i>');\n\telemento.next('.status-icon').delay(2000).fadeOut(500).delay(500).queue(function() { $(this).remove(); });\n}", "function ValidarTipoContratoComEscolaridade() {\n\n if ($('#cphConteudo_ucContratoFuncao_chblContrato_1').attr('checked')) {\n if ($('.rcbList').find('.rcbHovered:first:contains(\"Incompleto\")').length == 0) {\n alert('Escolaridade não condiz com o tipo de contrato Estágio!');\n }\n }\n}", "function ImprimirMensaje(mensaje = null, id = null) {\n if (mensaje == null) {\n mensaje = 'Lo sentimos, no se encontro ningun vehiculo con esas caracteristicas.'\n\n }\n if (id == null) {\n contenedorVehiculoEncontrado.innerHTML = `\n <div class=\"notification\" id='notificationId'>\n <button class=\"delete\" id=\"closeMensaje\"></button>\n ${mensaje}\n </div> \n `\n } else {\n document.getElementById(id).innerHTML = `\n <div class=\"notification\" id='notificationId'>\n <button class=\"delete\" id=\"closeMensaje\"></button>\n ${mensaje}\n </div>\n <br> \n `\n }\n\n closeMensaje.addEventListener('click', e => {\n contenedorVehiculoEncontrado.innerHTML = `\n <figure class=\"image is-3by2\">\n <img id=\"imgState\" src=\"/img/buscarVehiculo.jpg\" alt=\"buscar vehiculos\">\n </figure>\n `\n })\n\n}", "function inserisciOfferteAccettate(listaOfferte){\r\n //nascondo gli esempi\r\n $(\"#div-offerte-accettate-esempio\").css('display','none');\r\n\r\n for(var i=0;i < listaOfferte.length;i++){\r\n var doc = listaOfferte[i];\r\n //Se l'offerta accettata non è presente la inserisco\r\n if(doc.value.ospitato && !offerteAccettate[doc.id]){\r\n offerteInCuiUtentePresente[doc.id] = doc.value;\r\n if(doc.value.ospitato === JSON.parse(localStorage.utente).username){\r\n creaBoxOffertaAccettata(doc.id,doc.value,\"Ospitato\");\r\n }\r\n else if(doc.value.ospitante === JSON.parse(localStorage.utente).username){\r\n creaBoxOffertaAccettata(doc.id,doc.value,\"Ospitante\");\r\n }\r\n }\r\n }\r\n}", "function deleteAndCheck (occasion){\n const item = occasion.target;\n if (item.classList[0] === 'deleted-btn'){ //delete trashcan\n const todo = item.parentElement;\n todo.classList.add('collapse');\n removeLocalTodos(todo);\n todo.addEventListener('transitionend', function(){\n todo.remove();\n })\n };\n// marks as complete\n if (item.classList[0] === 'completed-btn'){\n const todo = item.parentElement;\n todo.classList.toggle(\"completed\");\n }\n }", "function gestioneSoggettoAllegato() {\n var overlay = $('#sospendiTuttoAllegatoAtto').overlay('show');\n // Pulisco i dati\n $(\"#datiSoggettoModaleSospensioneSoggettoElenco\").html('');\n $(\"#modaleSospensioneSoggettoElenco\").find('input').val('');\n // Nascondo gli alert\n datiNonUnivociModaleSospensioneSoggetto.slideUp();\n alertErroriModaleSospensioneSoggetto.slideUp();\n\n $.postJSON('aggiornaAllegatoAtto_ricercaDatiSospensioneAllegato.do')\n .then(handleRicercaDatiSoggettoAllegato)\n .always(overlay.overlay.bind(overlay, 'hide'));\n }", "function OnExitoActualizarEncuesta(result) {\n OcultarLoading();\n if (result.Exitoso) {\n estaHabilitadoEdicion = false;\n datosActualizados = true;\n mostrarNotificacion({\n titulo: \"\",\n mensaje: result.Mensaje,\n tipo: \"info\"\n });\n OnExitoEncuestas(result);\n\n }\n else {\n HabilitarEdicionEncuesta();\n mostrarNotificacion({\n titulo: \"Error\",\n mensaje: result.Mensaje,\n tipo: \"error\"\n });\n }\n}", "function setValidacaoRemota(erro) {\n\n if (!erro) {\n $(\"#salvar-erros\").html(null);\n return;\n }\n\n $(\"#salvar-erros\").append(\"<p>\" + erro + \"</p>\")\n }", "function ClickHabilidadeEspecial() {\n // TODO da pra melhorar.\n AtualizaGeral();\n}", "function noElement() {\r\n clickedElement = \"\";\r\n}" ]
[ "0.6341398", "0.627739", "0.6101217", "0.6055294", "0.6025185", "0.59946585", "0.59715515", "0.59475726", "0.5936613", "0.59285897", "0.5891073", "0.58023816", "0.5786556", "0.5768657", "0.57285595", "0.572832", "0.57169247", "0.57082736", "0.57082623", "0.56661916", "0.56551397", "0.5646413", "0.56384045", "0.56338024", "0.5623262", "0.56202865", "0.5611108", "0.56069815", "0.5604959", "0.55973256", "0.5594657", "0.558952", "0.5588742", "0.55826", "0.55763465", "0.55753285", "0.5573644", "0.5567981", "0.5564371", "0.55548054", "0.55512697", "0.5539235", "0.5537037", "0.55295056", "0.5528872", "0.552659", "0.54957306", "0.5495286", "0.5489852", "0.54893184", "0.54858714", "0.5484671", "0.54785836", "0.5478131", "0.546563", "0.5465383", "0.5463828", "0.54561996", "0.54512703", "0.5446251", "0.54433143", "0.5431396", "0.54292965", "0.5428438", "0.5425239", "0.54250705", "0.542506", "0.54124993", "0.54095715", "0.5408001", "0.5404787", "0.5404062", "0.54018563", "0.53945476", "0.53943425", "0.5391386", "0.53822166", "0.538083", "0.5379243", "0.53776824", "0.5369205", "0.536819", "0.5365515", "0.53643495", "0.5362723", "0.53623223", "0.53587", "0.5358685", "0.5358397", "0.5356642", "0.5356297", "0.53537047", "0.53535116", "0.53507346", "0.5346859", "0.5345462", "0.5338466", "0.5335836", "0.533478", "0.5333095", "0.5332853" ]
0.0
-1
Iteration 1: Ordering by year Order by year, ascending (in growing order)
function orderByYear(array) { let newArray = array.map(elm => { return elm }) newArray.sort((a, b) => { if (a.year > b.year) return 1 if (a.year < b.year) return -1 if ((a.year == b.year) && (a.title > b.title)) return 1 if ((a.year == b.year) && (a.title < b.title)) return -1 }) return newArray }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function orderByYear(someArr){\n const order = someArr.sort((a, b) => a.year > b.year ? 1 : -1)\n return order;\n}", "function orderByYear(arr) {\n let byYear = [...arr].sort((s1, s2) => {\n if (s1.year > s2.year) return 1;\n else return -1\n })\n return byYear\n}", "function orderByYear(array) {\n // array.forEach(elm => console.log(elm.duration))\n const yearArray = [...array]\n yearArray.sort((a, b) => {\n a.year - b.year\n\n if (a.year - b.year == 0) {\n\n if (a.title < b.title) {\n return -1\n }\n\n return 1\n\n }\n return a.year - b.year\n\n })\n\n return yearArray\n}", "function orderByYear (arr){\n let byYear = []\n const sortedYears = arr.sort((a, b) => {\n let alpha = a.year - b.year \n if (alpha === 0){\n return a.title.localeCompare(b.title)\n }\n return alpha\n }) \n byYear = sortedYears\n return byYear\n}", "function sorterenyear(a, b) {\r\n return d3.ascending(year(a), year(b));\r\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 }", "function orderByYear(moviesArray) {\n\n\n const orderByYear = moviesArray.map(function (e) {\n return { title: e.title, year: e.year }\n })\n\n orderByYear.sort((a, b) => (a.year > b.year) ? 1 : -1)\n\n const objectOrderByYear = {}\n const arrayOrderByYear = []\n\n orderByYear.forEach(function (e, idx) {\n objectOrderByYear.year = e.year\n arrayOrderByYear.push({ year: objectOrderByYear.year })\n })\n\n // console.log(arrayOrderByYear);\n\n return arrayOrderByYear\n}", "function orderByYear(movies) {\n if (movies.length > 0) {\n return [];\n } \n else {\n return movies.sort((num1, num2) => {\n if(num1.year !== num2.year){\n return num1.year - num2.year\n }\n else {\n if(word1.year < word2.year) {\n return 1\n }\n else {\n if(word1.year > word2.year) {\n return -1\n }\n else {\n return 0\n }\n }\n }\n })\n } \n}", "function orderByYear(array) {\n const order = [...array].sort(function(a, b) {\n if(a.year === b.year){\n return a.title.localeCompare(b.title)\n }\n return a.year - b.year;\n });\n return order;\n }", "function orderByYear(array){\n\n \n array.sort(function (a, b) {\n if (a.year > b.year) return 1; // 1 here (instead of -1 for ASC)\n if (a.year < b.year) return -1; // -1 here (instead of 1 for ASC)\n //if (a.year === b.year) return 0;\n if (a.year === b.year) {\n if (a.title > b.title) return 1;\n if (a.title < b.title) return -1;\n if (a.title === b.title) return 0;\n }\n });\n\n const newArray = Array.from(array)\n\n return newArray;\n\n}", "filterAndSortDataByYear () {\n }", "function orderByYear (array) {\n\tconst yearsOrdered = array.slice().sort (function (a, b) {\n\t\tif (a.year > b.year) {\n\t\t\treturn 1\n\t\t}\n\t\tif (a.year < b.year) {\n\t\t\treturn -1\n\t\t}\n\t\tif (a.year === b.year) {\n\t\t\tif (a.title > b.title) {\n\t\t\t\treturn 1\n\t\t\t}\n\t\t\tif (a.title < b.title) {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t})\n\treturn yearsOrdered\n}", "function orderByYear() {\n \n}", "function orderByYear(array){\n \n array.sort(function(a, b) {\n // Sort by year\n var dCount = a.year - b.year;\n if(dCount) return dCount;\n \n // If there is a tie, sort by title\n var dYear = ('' + a.title).localeCompare(b.title);\n return dYear;\n });\n let newArr = [...array]\n return newArr\n }", "function orderByYear(arr) {\n let sortedByYear = [];\n for (let movie of arr) {sortedByYear.push(movie);}\n sortedByYear.sort((a, b) => {\n if (a.year < b.year) {return -1;}\n if (a.year > b.year) {return 1;}\n return a.title.localeCompare(b.title); // com ajuda da solução\n });\n return sortedByYear;\n}", "function orderByYear (anArr) {\n return anArr.sort((a, b) => {\n if (a.year > b.year) {\n return 1;\n } else if (a.year < b.year) {\n return -1;\n } else {\n if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n }\n }\n})\n}", "function orderByYear(movies) {\n const newYearOrder = [...movies]\n\n newYearOrder.sort((a, b) => {\n\n if (a.year === b.year) {\n return a.title.localeCompare(b.title)\n } else {\n return a.year - b.year\n }\n })\n return newYearOrder\n}", "function orderByYear(arr) {\n return arr.map(function (movie) {\n return movie.year;\n });\n orderByYear\n}", "function sortByYear\n(\n array\n) \n{\n return array.sort(function(a,b)\n {\n var x = parseInt(a.number.split('-')[1]);\n var y = parseInt(b.number.split('-')[1]);\n return ((x < y) ? -1 : ((x > y) ? 0 : 1));\n }).reverse();\n}", "function orderByYear(arr) {\n let clone = JSON.parse(JSON.stringify(arr))\n \n clone.sort((first, second) => {\n if(first.year > second.year){\n return 1\n }\n else if(first.year < second.year){\n return -1\n }\n else{\n if(first.title > second.title){\n return 1\n }\n else if(first.title < second.title){\n return -1\n }\n else{\n return 0\n }\n }\n })\n return clone\n}", "function orderByYear(movies) {\n var sortedArray = movies.sort(function (movie1, movie2) {\n var movie1Year = movie1.year;\n var movie2Year = movie2.year;\n if (movie1Year < movie2Year) {\n // console.log(\"first movie is older \" + movie1Year + \" \" + movie2Year);\n return -1;\n } else if (movie1Year > movie2Year) {\n // console.log(\"first movie is younger \" + movie1Year + \" \" + movie2Year);\n return +1;\n } else {\n // console.log(\"movies came out the same year \" + movie1Year + \" \" + movie2Year);\n var movie1Name = movie1.title;\n var movie2Name = movie2.title;\n if (movie1Name > movie2Name) {\n // console.log(\"the first movie should go after \" + movie1Name + \" \" + movie2Name)\n return +1;\n } else if (movie1Name < movie2Name) {\n // console.log(\"the first movie should go first \" + movie1Name + \" \" + movie2Name);\n return -1;\n }\n }\n })\n // console.log(sortedArray);\n return sortedArray;\n}", "function orderByYear(arr) {\n \n const moviesOrdered = [...arr].sort((a, b) => {\n if (a.year > b.year) {\n return 1;\n } else if (a.year < b.year) {\n \n return -1;\n }\n else if (a.year == b.year && a.title > b.title) {\n return 1;\n } \n else if (a.year == b.year && a.title < b.title) {\n return -1;\n } \n });\nreturn moviesOrdered;\n}", "function orderByYear(array) {\n const sortedArray = array.slice().sort((a, b) => {\n if (a.year !== b.year) {\n return a.year - b.year;\n } else {\n return a.title.localeCompare(b.title);\n }\n });\n return sortedArray;\n}", "function orderByYear(arr){\n return arr.sort((mov1, mov2)=> {\n if (mov1.year - mov2.year ===0){\n if (mov1.title > mov2.title)return 1;\n if (mov1.title< mov2.title) return -1\n return 0\n }\n return mov1.year - mov2.year;\n })\n}", "function orderByYear(myArray) {\n const newArray = Array.from(myArray.sort((a, b) => {\n if (a.year === b.year) {\n const stringOrderArray = [a.title,b.title]\n stringOrderArray.sort()\n if (stringOrderArray[0] === a.title) {\n return -1\n }\n return 1\n }\n return a.year - b.year\t\t\n }))\n return newArray\n}", "function orderByYear(array) {\n\n let newSortedArray = [...array];\n newSortedArray.sort(function (a, b) {\n let year = a.year - b.year;\n if (year === 0) {\n return a.title.localeCompare(b.title);\n }\n return year;\n });\n return newSortedArray;\n}", "function orderByYear(arr){\n let sortedArr = arr.concat().sort((a,b) => {\n if(a.year === b.year){\n if(a.title < b.title) return -1;\n if(a.title > b.title) return 1;\n else return 0;\n }\n else return a.year - b.year\n });\n return sortedArr;\n}", "function orderByYear(array) {\n const sortedArray = array.slice().sort(function (a, b) {\n if (a.year !== b.year) {\n return a.year - b.year;\n } else {\n return a.title.localeCompare(b.title);\n }\n });\n return sortedArray;\n}", "function orderByYear(arr) {\n const newOrderByYear = arr;\n if (newOrderByYear.length === 0) return null;\n newOrderByYear.sort(function tata(a, b) {\n if (a.year === b.year) {\n\n if (a.title.toLowerCase() < b.title.toLowerCase()) return -1;\n if (a.title.toLowerCase() > b.title.toLowerCase()) return 1;\n return 0;\n\n }\n return a.year - b.year;\n });\n\n return newOrderByYear;\n}", "function orderByYear(yearOfMovie) {\n\n let copiaMovies = [...yearOfMovie];\n function ordenar(a,b) {\n if (a.year !== b.year){\n return a.year - b.year;\n } else {\n return a.title.localeCompare(b.title);\n }\n }\n\n return copiaMovies.sort(ordenar);\n}", "function yearComparator(auto1, auto2){\n return auto2.year - auto1.year;\n}", "function orderByYear (array) {\n array.sort((a, b) => {\n if (parseInt(a.year) > parseInt(b.year)) {\n return 1\n } else if (parseInt(a.year) < parseInt(b.year)) {\n return -1\n } else {\n if (a.title > b.title) {\n return 1\n } else if (a.title < b.title) {\n return -1\n } else {\n return 0\n }\n }\n })\n return array\n}", "function orderByYear(data){\n return data.slice(0).sort(function(a,b){\n if(a.year - b.year == 0 ){\n if (a.title.toLowerCase() > b.title.toLowerCase()){\n return 1\n }else if (a.title.toLowerCase() < b.title.toLowerCase()){\n return -1\n }else{\n return 0\n }\n }else{\n return a.year - b.year\n }\n })\n}", "function orderByYear(arr) {\n let objFromArray = arr.slice();\n let ordered = objFromArray.sort(function(a, b) {\n if(a.year === b.year) {\n return a.title.localeCompare(b.title);\n }else {\n return a.year - b.year\n }\n });\n return ordered;\n}", "function orderByYear(arr) {\n let mappedArr=arr.map(obj=>obj).sort(function(a,b){\n if (a.year === b.year) {\n return a.title.localeCompare(b.title);\n }\n return a.year - b.year;\n });\n return mappedArr;\n}", "function orderByYear (array) { \n let orderedArray = array.sort((a, b) => { \n if(a.year === b.year && a.title.toLowerCase() > b.title.toLowerCase()){ \n return 1;\n } else if(a.year === b.year && a.title.toLowerCase() < b.title.toLowerCase()) { \n return -1;\n } else if (a.year > b.year) { \n return 1;\n } else if (a. year < b.year){ \n return -1;\n } else { \n return 0; \n } \n });\n return orderedArray;\n }", "function orderByYear(movies) {\n let newArr = movies.sort((x, y) => {\n if (x.year > y.year) {\n return 1;\n } else if (x.year < y.year) {\n return -1;\n }\n });\n let sortedArr = [...newArr];\n return sortedArr;\n}", "function orderByYear(arr) {\n const ordenado = [...arr].sort((movie1, movie2) => {\n if (Number(movie1.year) === Number(movie2.year)) {\n return movie1.title.localeCompare(movie2.title);\n } else {\n return movie1.year - movie2.year;\n }\n });\n return ordenado;\n}", "function orderByYear(someArray) {\n\n let moviesCopy = JSON.parse(JSON.stringify(someArray));\n \n let orderedMovies = moviesCopy.sort((a,b) => a.year - b.year);\n\n \n return orderedMovies;\n}", "function orderByYear(movies) {\n let newArray =[...movies];\n return newArray.sort((movie1,movie2) => {\n if(movie1.year > movie2.year) {return 1}\n else {return -1}})\n}", "function orderByYear(array) {\n\n let newSortedArray = JSON.parse( JSON.stringify(people) )\n\n newSortedArray.sort( (first, second) => {\n if (first.year > second.year) {\n return 1\n }\n else if (first.year < second.year) {\n return -1\n }\n else {\n return 0\n }\n\n })\n\n return newSortedArray\n}", "function orderByYear (array) {\n const clone = Array.from(array)\n return clone.sort((movieA, movieB) => {\n if (movieA.year < movieB.year) {\n return -1\n } else if (movieA.year > movieB.year) {\n return 1\n } else {\n if (movieA.title < movieB.title) {\n return -1\n } else if (movieA.title > movieB.title) {\n return 1\n }\n return 0\n }\n })\n}", "function orderByYear(array) {\n const arrayYear = array.filter((movieYear) => {\n return year = movieYear.year;\n });\n return arrayYearSorted = arrayYear.sort((a, b) => {\n if (a.year > b.year) { //YEAR SORTING\n return 1;\n } else if (a.year === b.year) { //IF YEAR IS EQUAL THEN TITLE SORT\n if (a.title > b.title) {\n return 1;\n } else return -1;\n return 1;\n } else return -1;\n });\n}", "function orderByYear(movies){\n const total = [...movies]\n \n total.sort((a,b) => {\n if(a.year > b.year){\n return 1;\n } else if (a.year < b.year){\n return -1;\n }else {\n if (a.title > b.title){\n return 1;\n } else if (a.title < b.title){\n return -1; \n } else{\n return 0\n }\n}\n } );\n return total\n}", "function orderByYear(array) {\n\n let copy = [...array];\n\n copy.sort((a, b) => {\n if (a.year > b.year) return 1;\n if (a.year < b.year) return -1;\n if (a.year == b.year) {\n if (a.title > b.title) return 1;\n if (a.title < b.title) return -1;\n }\n\n });\n return copy;\n}", "function orderByYear(arr) {\n const sorted = [...arr].sort(function(a, b) {\n if (a.year === b.year) {\n return a.title.localeCompare(b.title);\n }\n return a.year - b.year;\n });\n return sorted;\n}", "function orderByYear(array) {\n let arrayTitle = array.map(movie => {\n \n let container = {};\n\n container.title = movie.title;\n container.year = movie.year;\n\n return container\n });\n\n console.log(arrayTitle);\n\n let ordenPorTitulo = arrayTitle.sort(function(a,b){\n if (a.title > b.title) {\n return 1;\n }\n if (a.title < b.title) {\n return -1;\n }// a must be equal to b\n return 0;\n });\n\n console.log(ordenPorTitulo);\n\n let ordenPorYear = ordenPorTitulo.sort(function(a,b){\n if (a.year > b.year) {\n return 1;\n }\n if (a.year < b.year) {\n return -1;\n }// a must be equal to b\n return 0;\n });\n\n return ordenPorYear;\n\n}", "function orderByYear(movies) {\n const moviesOrderedByYear = [...movies]\n\n moviesOrderedByYear.sort(function (a, b) {\n if (a.year !== b.year) {\n return a.year - b.year\n }\n if (a.title === b.title) {\n return 0;\n }\n return a.year > b.year ? 1 : -1;\n });\n\n return moviesOrderedByYear\n\n}", "function orderByYear(someArray) {\n let newArr = someArray.sort((a, b) => {\n if (a.year < b.year) {return -1;} \n if (a.year > b.year) {return 1;} \n return a.title.localeCompare(b.title);\n });\n return newArr;\n}", "function sortBubblesYear(b1, b2) {\n return b1.year - b2.year;\n}", "function orderByYear(itemsToSort) {\n let sortedItems = [...itemsToSort];\n\n sortedItems.sort(function(a, b) {\n if (a.year === b.year) {\n return a.title.localeCompare(b.title);\n }\n return a.year - b.year;\n });\n return sortedItems;\n}", "function orderByYear(arr){\n const newArr = JSON.parse(JSON.stringify(arr));\n newArr.sort((a,b) => {\n if(a.year < b.year) return -1;\n if(a.year === b.year){\n if(a.title.localeCompare(b.title)<0){\n return -1;\n }\n }\n });\n return newArr;\n}", "function orderByYear(array) {\n\n const newArray = [...array];\n\n const newArray2 = newArray.sort((a, b) => {\n return a.year === b.year ? a.title.localeCompare(b.title) : a.year - b.year;\n })\n\n return newArray2;\n\n}", "function orderByYear(array) {\n let myArray = JSON.parse(JSON.stringify(array));\n return myArray.sort(function(a,b) {\n // Check the order of year\n if (a.year > b.year) return 1;\n if (a.year < b.year) return -1;\n // Years are equal. Check oder of title\n if (a.title > b.title) return 1; \n if (a.title < b.title) return -1;\n return 0; \n });\n}", "function orderByYear(movies) {\n const copySort = [...movies].sort((a, b) => {\n if(a.year === b.year) {\n //localeCompare() devuelve -1 o 1 en función de la precedencia entre los títulos a comparar, muy útil para combinar con el sort. Devuelve 0 en caso de ser iguales.\n return a.title.localeCompare(b.title)\n } else {\n return a.year - b.year\n }\n })\n return copySort\n}", "function orderByYear(movies) {\n const sortedYear = [...movies]\n return sortedYear.sort((a, b) => {\n if (a.year > b.year) {\n return 1;\n } else if (a.year < b.year) {\n return -1;\n } else {\n if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n }\n\n }\n })\n}", "function orderByYear(arr){\n let myArr = JSON.parse(JSON.stringify(arr))\n let pelisOrdenadas=myArr.sort(function(a,b){\n if(a.year===b.year){\n return a.title.localeCompare(b.title);\n }\n return a.year - b.year});\n return pelisOrdenadas\n }", "function orderByYear(yearMovies) {\n return yearMovies.concat().sort((a, b) => {\n if (a.year > b.year) return 1;\n else return -1;\n });\n}", "function orderByYear(movies) {\n const sorted = movies.slice().sort(function (a, b) {\n if (a.year !== b.year) {\n return a.year - b.year; \n } else {\n return a.title.localeCompare(b.title);\n }\n });\n return sorted;\n}", "function orderByYear(peliculas) {\n const sortedPeliculas = [...peliculas];\n sortedPeliculas.sort((a, b) => {\n if (a.year - b.year)\n return a.year - b.year\n else {\n if (a.title < b.title) return -1\n else if (a.title > b.title) return 1\n else return 0\n }\n })\n return sortedPeliculas\n}", "function orderByYear(movies) {\n return movies.slice().sort(function(a, b) {\n if (a === b){\n return a.title.localeCompare(b.title);\n } else {\n return a.year - b.year\n }\n })\n }", "function orderByYear(someArray){\n someArray.sort((a, b) => (a.year > b.year) ? 1 : (a.year === b.year) ? ((a.title.toLowerCase() > b.title.toLowerCase()) ? 1 : -1) : -1 )\n return someArray;\n}", "function orderByYear(movies) {\n const newArray = movies.map(i => i)\n return newArray.sort((a,b)=> a.year - b.year === 0 ? a.title > b.title? 1 : -1 : a.year - b.year)\n}", "function orderByYear(array) {\n const newArray = [...array].sort((a, b) => (a.year > b.year) ? 1 : (a.year === b.year) ? ((a.title > b.title) ? 1 : -1) : -1)\n return newArray\n}", "function orderByYear(movies){\n let moviesClone = JSON.parse(JSON.stringify(movies)); // deep clone\n \n let orderByYear = moviesClone.sort(function(movie1, movie2){\n \n if(movie1.year === movie2.year){\n \n // sorting same year movies alphabetically:\n if(movie1.title < movie2.title){\n return -1\n } else if(movie1.title > movie2.title){\n return 1\n } else {\n return 0\n }\n \n } else {\n \n return movie1.year - movie2.year\n }\n \n })\n return orderByYear\n }", "function cmp(a, b) {\n let yearA = a[0].years[0]\n let yearB = b[0].years[0]\n return (yearB > yearA) ? 1 : ((yearB < yearA) ? -1 : 0)\n }", "function orderByYear(array) {\n let sortedArray = array.slice().sort(function(a, b) {\n if (a[\"year\"] === b[\"year\"]) {\n return a[\"title\"].localeCompare(b[\"title\"]);\n }\n\n return a[\"year\"] - b[\"year\"];\n });\n\n return sortedArray;\n}", "function orderByYear (movies) {\n if (movies.length === 0) return 0;\n const copy=[...movies];\n copy.sort(function(a, b) {\n return a.year - b.year || a.title.localeCompare(b.title);\n });\n return copy\n }", "function orderByYear(arr) {\n\tlet sortedMovies = [ ...arr ].sort((a, b) => {\n\t\tif (a.year < b.year) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (a.year > b.year) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tif (a.title < b.title) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (a.title > b.title) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t});\n\treturn sortedMovies;\n}", "function buildYearly() {\n yearlyData = [];\n originalData.forEach(buildYearlyForEach);\n}", "next() {\n return this.d.clone().add(1, 'year')\n }", "function orderByYear(moviesArray) {\n let sortedMovies = moviesArray.slice().sort(function (movie1, movie2) {\n if (movie1.year === movie2.year) {\n return -1;\n }\n return movie1.year - movie2.year;\n }); return sortedMovies;\n}", "function orderByYear([...movies]){\n return movies.sort( (a, b) => {\n if (a.year > b.year){\n return 1;\n } else if (a.year < b.year){\n return -1;\n } else if (a.title > b.title){\n return 1;\n } else {\n return -1;\n }\n })\n}", "function compareYear(a, b) {\r\n if (a.YEAR < b.YEAR)\r\n return -1;\r\n else if (a.YEAR > b.YEAR)\r\n return 1;\r\n else\r\n return 0;\r\n}", "function orderByYear(array){\n let newArray=JSON.parse(JSON.stringify(array))\n\n\nlet sortNewArray=newArray.sort((a,b)=>{\n if (a.year>b.year){\n return 1\n }\n\n else if (a.year<b.year){\n return -1\n }\n\n else {\n if (a.title>b.title){\n return 1\n }\n else if ( a.title<b.title){\n return -1\n }\n else return 0\n }\n \n }) \n return sortNewArray \n}", "function orderByYear (arrayOfMovies) {\n let sortedArr = arrayOfMovies.slice().sort((a,b) => {\n if (a.year > b.year) return 1;\n if (a.year < b.year) return -1;\n if (a.title > b.title) return 1;\n if (a.title < b.title) return -1;\n }); \n return sortedArr;\n }", "function orderByYear(array) {\n let moviesByYear = [];\n if(array.length===0){\n return moviesByYear\n }\n moviesByYear = array.sort((a, b) => \n (a.year > b.year) ? 1 : (a.year === b.year) \n ?\n ((a.title > b.title) ? 1 : -1)\n : -1\n )\n\n return moviesByYear;\n}", "function yearComparator( auto1, auto2) {\n //put auto2 as arg1 and auto1 as arg2 to sort the cars in \"reverse\"\n //this produces the desired \"newest cars on top\" sorting effect\n return exComparator(auto2.year, auto1.year);\n}", "function yearComparator( auto1, auto2){\n /* your code here*/\n if (auto1.year < auto2.year) {\n \treturn true;\n }\n else {\n \treturn false;\n }\n}", "function orderByYear (movies) {\n const result = movies\n .map(movie => movie)\n .sort(function(aMovie, anotherMovie){\n if (aMovie.year === anotherMovie.year) {\n const nameA = aMovie.title.toUpperCase(); // ignore upper and lowercase\n const nameB = anotherMovie.title.toUpperCase(); // ignore upper and lowercase\n\n if (nameA < nameB) {\n return -99;\n }\n if (nameA > nameB) {\n return 111222;\n }\n // names must be equal\n return 0;\n } else {\n // 2003-2015 ==> negative\n // 2003-2003 ==> zero\n // 2003-1999 ==> positive\n return aMovie.year - anotherMovie.year;\n }\n });\n return result;\n}", "function orderByYear(movies) {\n const newArray = movies.map(function(item){\n return item;\n })\n const oldestFirst = newArray.sort(function(a, b){\n if (a.year === b.year) {\n if (a.title > b.title) {\n return 1;\n } \n if (a.title < b.title) {\n return -1;\n }\n return 0;\n }\n return a.year - b.year; \n }); \n return oldestFirst;\n}", "function orderByYear(movies) {\n const newMovies = [...movies];\n\n newMovies.sort((a, b) => {\n if (a.year - b.year) {\n return a.year - b.year;\n } else if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n } else return 0;\n });\n\n return newMovies;\n}", "function yearComparator( auto1, auto2){\r\n if(auto1.year >= auto2.year){\r\n\t\treturn true;\r\n\t}\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}", "function alphabetique(){\n entrepreneurs.sort.year\n }", "function yearComparator( auto1, auto2){\r\n\r\n if (auto1.year > auto2.year){\r\n return false;\r\n }else if(auto1.year < auto2.year){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n}", "function orderByYear(arr) {\n var newArray = arr.map(function(movie) {\n return movie;\n });\n newArray.sort(function(a, b) {\n if (a.year === b.year) {\n if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n }\n return 0;\n }\n return a.year - b.year;\n });\n return newArray;\n}", "function orderByYear(moviesArray) {\n let sortMovies = moviesArray.map((x) => x).sort((a, b) => {\n if (a.title < b.title){\n return -1;\n }\n if (a.title > b.title){\n return 1;\n }\n return 0;\n })\n .sort ((a, b) => {\n return a.year - b.year;\n });\n return sortMovies;\n}", "listYears () {\n const dates = []\n let currentDate = Moment(this.minMoment)\n while (currentDate <= this.maxMoment) {\n dates.push({\n text: currentDate.year(),\n value: currentDate.year()\n })\n currentDate = Moment(currentDate).add(1, 'year')\n }\n return dates\n }", "function sortByYear() {\n if (!window.confirm(\"Sort releases by year?\"))\n return false;\n \n var items = document.getElementsByTagName(\"tr\");\n var years = new Array();\n for (var i=1; i<items.length; i++) { //Starts at one to skip the heading\n var info = items[i].getElementsByTagName(\"td\");\n var year = info[1].innerHTML;\n year = year.split(\"[\")[1].split(\"]\")[0];\n years.push(year);\n }\n years = years.sort();\n GM_log(years);\n \n //Go through each year in the array\n var foundsList = new Array(); //Array of what ones have been ordered\n foundsList.push(null);\n for (i in years)\n foundsList.push(false);\n GM_log(foundsList);\n \n for (i in years) {\n //Find the first torrent in the list that has that year\n var notFound = true;\n var index = 0;\n while (notFound) {\n index++; //Again, start search at one, not zero\n var info = items[index].getElementsByTagName(\"td\");\n var year = info[1].innerHTML;\n year = year.split(\"[\")[1].split(\"]\")[0];\n //Check if this is the year we're looking for\n if ( (years[i] == year) && (foundsList[index] == false) ) {\n notFound = false; //We found it\n foundsList[index] = true;\n //info[0].getElementsByTagName(\"input\")[3].value = i + \"0\";\n //Submit the data to update it\n pending++; //One more is pending\n var postdata = \"action=manage_handle\";\n var data = info[0].getElementsByTagName(\"input\");\n postdata += \"&collageid=\" + data[1].value;\n postdata += \"&groupid=\" + data[2].value;\n postdata += \"&sort=\" + (i*1+1) + '0';\n postdata += \"&submit=Edit\";\n GM_xmlhttpRequest({ 'method' : \"POST\",\n 'url' : data[0].form.action,\n 'headers' : {'Content-Type' : 'application/x-www-form-urlencoded'},\n 'data' : postdata,\n 'onload' : function() {\n pending--;\n if (pending == 0)\n alert(\"Done!\");\n window.location.reload();\n }\n });\n }\n }\n }\n \n //alert(\"Done!\");\n}", "function orderByYear(movies) {\n const orderedMovies = movies.map((item) => {\n return item;\n });\n orderedMovies.sort((a, b) => {\n if (a.year > b.year) {\n return 1;\n } else if (b.year > a.year) {\n return -1;\n } else if (a.title > b.title) {\n return 1;\n } else if (b.title > a.title) {\n return -1;\n }\n });\n return orderedMovies;\n}", "function yearComparator( auto1, auto2){\n /* your code here*/\n if (auto1.year > auto2.year) {\n return true;\n } else {\n return false;\n }\n}", "function orderByYear(moviesArray) {\n let orderedArray = moviesArray.slice().sort(function compare(a, b) {\n if (a.year < b.year) {\n return -1;\n }\n if (a.year > b.year) {\n return 1;\n }\n if (a.year === b.year) {\n if (a.title < b.title) {\n return -1;\n }\n if (a.title > b.title) {\n return 1;\n }\n }\n });\n\n return orderedArray;\n}", "function compare(a, b) {\n if (a.year < b.year)\n return -1;\n if (a.year > b.year)\n return 1;\n return 0;\n }", "function sortCollectionByDate(collection){\n\treturn collection.sort(function(a, b){\n\t\tif(a[year] < b[year]) return -1;\n\t\tif(a[year] > b[year]) return 1;\n\t\treturn 0;\n\t});\n}", "function orderByYear(movies) {\n let moviesArr = JSON.parse(JSON.stringify(movies))\n\n moviesArr.sort((a,b)=>{\n if(a.year > b.year){\n return 1\n }else if (b.year > a.year) {\n return -1\n } else{\n if(a.title > b.title){\n return 1;\n }else if (b.title > a.title){\n return -1\n }\n return 0\n }\n })\n return moviesArr\n}", "function orderByYear(movies) {\n var order = movies.slice().sort(function(a, b) {\n if (a.year !== b.year) {\n return a.year - b.year;\n } else {\n return a.title.localeCompare(b.title);\n // NOTA : El método localeCompare() devuelve un\n //número que indica si la cadena de caracteres actual es anterior, posterior o igual a la\n //cadena pasada como parámetro, en orden lexicográfico.\n }\n });\n return order;\n}", "function orderByYear(moviesArray) {\n let copiedArray = JSON.parse(JSON.stringify(moviesArray));\n copiedArray.sort((a, b) => {\n if (a.year === b.year && a.title < b.title) {\n return -1;\n } else if (a.year === b.year && a.title > b.title) {\n return 1;\n }\n return a.year - b.year;\n });\n return copiedArray;\n}", "function logSortedByYear(movies) {\r\n var sorted = Object.keys(movies).map(function(key) {\r\n return movies[key];\r\n }).sort(function(a, b) {\r\n return a.Year - b.Year;\r\n })\r\n sorted.forEach(function(movie) {\r\n console.log(movie.Title + \" - \" + movie.Year);\r\n });\r\n}", "function orderByYear(moviesArray) {\n let moviesByYear = [...moviesArray].sort(function(movie1, movie2) {\n if (movie1.year > movie2.year) {\n return 1;\n } else if (movie1.year < movie2.year) {\n return -1;\n } else {\n //compare them by title\n if (movie1.title > movie2.title) {\n return 1;\n } else if (movie2.title < movie2.title) {\n return -1;\n }\n }\n });\n return moviesByYear;\n}", "function orderByYear(movies) {\n movies.sort(function(a, b) {\n if (a.year === b.year) {\n return a.title.localeCompare(b.title);\n } else {\n return a.year - b.year;\n }\n });\n return movies;\n}" ]
[ "0.72275954", "0.7135998", "0.7133108", "0.71112806", "0.7054949", "0.7049193", "0.7022546", "0.7011991", "0.70116156", "0.6954844", "0.69396275", "0.6934575", "0.69301045", "0.69145787", "0.6911264", "0.6902474", "0.68897897", "0.68856317", "0.6878473", "0.68769145", "0.68690395", "0.68431896", "0.681411", "0.6805637", "0.6794412", "0.6782319", "0.67639816", "0.67622405", "0.67406553", "0.6738976", "0.67358917", "0.6720242", "0.6718489", "0.6714301", "0.67134804", "0.671082", "0.6693813", "0.6687453", "0.6682643", "0.6679445", "0.6676967", "0.6667572", "0.6665452", "0.66624945", "0.66565406", "0.6650118", "0.66176116", "0.66160566", "0.66029745", "0.6586019", "0.6579377", "0.6577413", "0.65717566", "0.6567641", "0.65454537", "0.6545076", "0.6531398", "0.65059644", "0.64872354", "0.64793694", "0.64574736", "0.6452797", "0.6449836", "0.6442533", "0.6419658", "0.6419242", "0.6415512", "0.64099216", "0.6407974", "0.6397767", "0.63886684", "0.63801515", "0.63759196", "0.6373964", "0.63665026", "0.6364882", "0.6361794", "0.6356472", "0.6351498", "0.63319296", "0.63214517", "0.63172", "0.631003", "0.6305043", "0.62983936", "0.62770474", "0.6276163", "0.62654597", "0.62213343", "0.6220167", "0.620918", "0.6193142", "0.6187818", "0.617361", "0.61706555", "0.616964", "0.61308664", "0.6125306", "0.610566", "0.6099813" ]
0.67686546
26
Iteration 2: Steven Spielberg. The best? How many drama movies did STEVEN SPIELBERG direct
function howManyMovies(movieNum) { let dramaMovies = movieNum.filter(elm => elm.genre.includes("Drama") && elm.director === "Steven Spielberg") return dramaMovies.length }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function howManyMovies(movies){\n if (movies == 0){}\n else {\n var dramaFilms = [];\n for (var i = 0; i < movies.length; i++){\n for (var j = 0; j < movies[i].genre.length; j++){\n if (movies[i].genre[j] === 'Drama'){\n dramaFilms.push(movies[i])\n }\n }\n}\n var stevenFilms = dramaFilms.filter(function(elm){\n return elm.director == 'Steven Spielberg';\n });\n return 'Steven Spielberg directed ' + stevenFilms.length + ' drama movies!'\n}\n}", "function main(total, numReqs, movies) {\r\n\r\n var output = \"9 19 29 31 13 72 58 73 10 7 64 69 83 73 33 79 28 0 66 65 77 18 12 39 0 66 55 15 26 55 73 67 38 65 29 47 80 69 27 82 53 55 47 31 31 62 51 29 15 83 43 44 0 28 80 0 76 11 3 79 59 33 83 29 11 20 8 83 52 49 61 69 66 32 17 41 2 57 21 45 10 3 18 77 79 27 76 43 7 5 81 57 11 28 74 60 64 38 72 55 22 1 82 42 28 41 27 14 83 39 70 43 6 67 69 76 7 12 76 11 37 10 2 70 1 77 51 59 21 80 46 21 52 22 74 15 12 32 57 16 40 81 2 5 61 44 14 66 1 56 40 6 49 82 31 56 27 38 6 42 35 51 36 40 82 36 67 69 16 73 20 42 53 0 2 66 26 29 8 17 33 12 54 0 67 8 56 67 6 24 77 81 21 37 28 16 21 45 68 16 74 13 51 73 16 21 78 72 56 12 71 50 46 82 37 32 61 50 13 76 48 79 21 6 10 34 68 63 72 43 65 28 51 36 17 12 56 11 11 78 17 35 58 47 65 81 24 68 68 47 0 73 23 48 82 77 40 79 66 30 49 15 10 44 37 65 67 62 25 45 29 22 26 60 18 3 72 31 45 30 57 67 45 76 55 70 73 24 59 53 66 21 49 59 12 61 25 71 78 26 2 32 59 80 56 77 78 41 74 9 74 44 56 31 43 43 41 37 10 13 74 65 36 25 56 19 12 24 4 81 18 75 81 10 14 68 25 55 26 42 69 56 24 73 56 62 43 10 51 38 26 55 31 23 71 2 64 14 2 0 40 42 24 33 78 8 22 32 6 39 54 51 74 22 39 17 42 46 76 31 29 42 19 7 71 71 5 50 76 22 77 71 39 28 44 13 75 66 69 12 26 39 23 52 34 7 81 41 17 71 60 15 45 0 64 11 54 72 49 25 16 72 38 73 42 22 82 35 47 25 10 42 22 38 82 38 50 49 44 57 53 22 35 7 24 82 82 2 56 41 58 17 24 7 60 47 55 70 10 30 55 25 8 8 3 8 52 39 65 72 20 32 45 70 34 2 72 19 67 62 65 4 8 72 16 78 24 71 0 1 36 8 50 78 12 76 37 50 18 80 21 15 79 83 35 3 32 41 47 37 6 4 62 69 42 82 72 72 10 39 47 25 7 59 79 0 35 23 14 57 5 58 35 70 59 26 47 7 75 42 26 7 36 79 48 55 47 49 24 65 40 56 18 83 56 60 21 26 16 35 0 50 6 33 19 74 23 11 4 67 66 46 54 47 75 77 5 62 49 61 33 41 56 21 23 2 72 5 27 5 10 4 21 2 13 29 8 10 40 63 23 12 55 79 5 82 42 5 83 83 56 39 54 45 29 29 33 2 12 83 72 12 77 69 61 66 79 51 33 12 20 74 75 81 67 24 57 63 24 6 45 70 14 39 51 74 70 21 66 78 62 31 83 54 55 15 29 20 5 58 29 79 69 32 17 17 25 26 51 33 34 54 83 43 52 62 10 7 31 17 75 47 75 36 67 63 60 81 38 31 48 40 47 67 71 25 7 23 32 38 76 42 45 50 3 70 16 33 1 78 1 35 30 59 31 10 53 78 19 0 25 80 42 76 15 71 31 0 9 13 5 50 20 63 82 49 41 37 27 24 70 77 24 28 69 35 82 17 7 13 8 34 38 79 34 31 35 47 13 42 35 38 4 35 39 77 10 5 27 37 82 29 7 16 20 43 70 4 58 82 54 13 62 66 70 35 46 75 49 18 71 4 10 62 56 24 78 35 13 6 18 16 44 79 78 11 13 15 5 60 75 13 83 9 48 66 53 63 79 27 80 74 47 30 8 5 29 61 6 38 61 66 56 51 47 33 20 27 53 83 36 31 67 48 21 27 47 29 55 35 62 2 56 61 31 16 65 50 23 78 30 51 28 58 5 22 71 5 44 3 4 73 37 33 78 10 33 13 75 11 47 4 49 64 6 27 36\";\r\n var fs = require('fs');\r\n var _ = require('lodash');\r\n var moviesArr = getMovies(total);\r\n var requests = movies.split(' ');\r\n var result = [];\r\n\r\n for (var i = 0; i < requests.length; i++) {\r\n var cnt = 0;\r\n //fs.writeFileSync(\"log\" + requests[i] + \".json\", JSON.stringify(moviesArr));\r\n for (var j = 0; j < moviesArr.length; j++) {\r\n\r\n if (moviesArr[j].value === parseInt(requests[i])) {\r\n // console.log(moviesArr[j].index);\r\n for (var k = 0; k < moviesArr.length; k++) {\r\n\r\n if (moviesArr[k].index < moviesArr[j].index) {\r\n moviesArr[k].index++;\r\n } else if (moviesArr[k].index === moviesArr[j].index) {\r\n // console.log(moviesArr[k]);\r\n cnt = moviesArr[k].index - 1;\r\n moviesArr[k].index = 1;\r\n moviesArr = _.orderBy(moviesArr, 'index');\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n else {\r\n // cnt++;\r\n }\r\n\r\n }\r\n\r\n\r\n result.push(cnt);\r\n }\r\n\r\n console.log(result.join(' ') === output);\r\n return result.join(' ');\r\n}", "function howManyMovies(movies) {\n if (movies.length === 0) {\n return;\n }\n\n var spielbergFilms = movies.filter(function(oneMovie) {\n return oneMovie.director === \"Steven Spielberg\";\n });\n\n var dramas = dramaOnly(spielbergFilms);\n\n return \"Steven Spielberg directed \" + dramas.length + \" drama movies!\";\n}", "function howManyMovies(movies) {\n let movieString = \"\";\n let spielbergMovies = movies.filter(movie => movie.director === 'Steven Spielberg' && movie.genre.includes('Drama'))\n let total = movieString += spielbergMovies.length\n if (total === 0) return undefined\n return `Steven Spielberg directed ${total} drama movies!`\n }", "function howManyMovies(movies)\n{\n if (movies.length==0) return;\n var moviesSpielberg = movies.filter(function(movie){\n return (movie.genre.indexOf('Drama')!=-1 && movie.director === 'Steven Spielberg');\n });\n return \"Steven Spielberg directed \" + moviesSpielberg.length + \" drama movies!\";\n}", "function countSpielbergDramaMovies(steve) {\n let moviesBySteven = steve.filter((movie) => {\n for (let i = 0; i < movie.genre.length; i++)\n if (movie.genre[i].toLowerCase() === 'drama'){\n return true\n }});\n\n const steveActual = moviesBySteven.filter((movie => movie.director === 'Steven Spielberg'));\n\n return steveActual.length;\n }", "function howManyMovies(movies){\n\n if (moviesSpielberg.length == 0){\n return undefined\n }\n\n let moviesSpielberg = movies.filter(elm => {\n \n\n return elm.director == 'Steven Spielberg' && elm.genre.includes('Drama')\n })\n\n return `Steven Spielberg directed ${moviesSpielberg.length} drama movies`\n\n console.log(moviesSpielberg)\n}", "function howManyMovies(array){\n var spielbergDrama =\n array.filter(function(oneMovie){\n return oneMovie.director == \"Steven Spielberg\" && oneMovie.genre.includes(\"Drama\");\n });\n // if(spielbergDrama.length < 1){\n // return \"Steven Spielberg directed 0 drama movies!\";\n // // return undefined;\n // }\n return \"Steven Spielberg directed \" + spielbergDrama.length + \" drama movies!\";\n}", "function dramaMoviesRate(movies){\n const dramaMovie = movies.filter (function(movie)}\n return movie.genre.indexOf(\"Drama\")\n})", "function howManyMovies(movies) {\n var sortedSteven = movies.filter(function(oneMovie) {\n return (\n oneMovie.director === \"Steven Spielberg\" &&\n oneMovie.genre.indexOf(\"Drama\") !== -1\n );\n });\n if (sortedSteven.length === 0) {\n return undefined;\n } else {\n return (\n \"Steven Spielberg directed \" + sortedSteven.length + \" drama movies!\"\n );\n }\n}", "function howManyMovies(movies) {\n if(movies.length === 0){\n return undefined;\n }\n var spielbergMovies = movies.filter(function(movie) {\n var filterGenres = movie.genre.filter(function(genre) {\n return genre === \"Drama\"; \n })\n if(filterGenres.length > 0 && movie.director === \"Steven Spielberg\"){\n return true;\n }else {\n return false;\n }\n });\n return `Steven Spielberg directed ${spielbergMovies.length} drama movies!`;\n}", "function howManyMovies(moviesArray) {\n let dramaMoviesBySpielberg = moviesArray.filter(movie => (movie.genre.includes('Drama')) && (movie.director.includes('Steven Spielberg')))\n if (moviesArray.length == 0) { return undefined }\n return `Steven Spielberg directed ${dramaMoviesBySpielberg.length} drama movies!`\n\n}", "function dramaMoviesScore(movies) {\n dramaMovies = movies.filter(i => i.genre.includes('Drama'))\n return (dramaMovies.reduce((acc, item)=> acc + (item.score || 0), 0) / dramaMovies.length).toFixed(2) * 1 || 0\n}", "function howManyMovies(movies){\n if (movies.length === 0){\n return undefined\n }\n let movisDrama = movies.filter(movie => movie.genre.includes(`Drama`))\n let moviesSpilber = movisDrama.filter(movie =>movie.director.includes('Steven Spielberg'))\n \n return (`Steven Spielberg directed ${moviesSpilber.length} drama movies!`)\n }", "function howManyMovies(someArray) {\n let stevenMovies = 0;\n \n someArray.forEach(eachMovie => {\n if ((eachMovie.director === \"Steven Spielberg\") && (eachMovie.genre.includes('Drama'))) {\n stevenMovies ++\n }\n });\n \n return stevenMovies; \n}", "function howManyMovies(array){\n if (array.length === 0){\n return undefined;\n }\n counter = 0;\n for (var i = 0; i < array.length; i++){\n if ((array[i].director === 'Steven Spielberg') \n /* && (movie.genre.indexOf(\"Drama\") !== -1 *//* || movie.genre === \"Drama\") */){\n counter += 1;\n };\n }\n return (\"Steven Spielberg directed \" + counter + \" drama movies!\")\n\n /* var newMovies = \n array.filter(function(movie){\n return (movie.director === 'Steven Spielberg') && (movie.genre.indexOf(\"Drama\") !== -1 || movie.genre === \"Drama\")\n });\n return newMovies; */\n}", "function howManyMovies(movies) {\n if(movies.length === 0) {\n return undefined;\n }\n\n var dramasBySpielberg = movies.filter(function(movie) {\n if(movie.director === 'Steven Spielberg' && movie.genre.indexOf('Drama') !== -1) {\n return movie;\n }\n });\n\n return 'Steven Spielberg directed ' + dramasBySpielberg.length + ' drama movies!';;\n}", "function bestYearForCinema(movies) {}", "function howManyMovies (movies) {\n const moviesSpielberg = movies.filter(aMovie => aMovie.director === \"Steven Spielberg\")\n const moviesSpielbergDrama = moviesSpielberg.filter(aMovie => aMovie.genre.includes(\"Drama\"))\n \n if (moviesSpielbergDrama.length == 0) {\n return 0;\n } \n else {\n return moviesSpielbergDrama.length;\n }\n }", "function howManyMovies(moviesArray) {\n if(moviesArray.length === 0){return undefined;}\n let stevenDramaMovies = moviesArray.filter((eachMovie)=>{\n return (eachMovie.genre.includes(\"Drama\")) && (eachMovie.director === 'Steven Spielberg');\n });\n\n return `Steven Spielberg directed ${stevenDramaMovies.length} drama movies!`;\n}", "function howManyMovies(movies) {\n const stevenDrama = movies.filter(elm => elm.director === \"Steven Spielberg\" && elm.genre.includes(\"Drama\"))\n return stevenDrama.length\n}", "function howManyMovies(arrayOfMovieObjects){\n if(arrayOfMovieObjects.length ===0){return}//this is the same as return undefined\n let dramasBySteven = arrayOfMovieObjects.filter((eachMovie)=>{\n return eachMovie.director === \"Steven Spielberg\" && eachMovie.genre.includes('Drama');\n })\n return `Steven Spielberg directed ${dramasBySteven.length} drama movies!`; \n}", "function howManyMovies(movies) {\n if (movies.length == 0) return;\n\n var dramaMovies = filterDrama(movies);\n\n var result = dramaMovies.filter(function(movie) {\n return movie.director == \"Steven Spielberg\";\n }).length;\n\n return `Steven Spielberg directed ${result} drama movies!`;\n}", "function howManyMovies(aArray){\n var dramaMovies = aArray.filter(function(item){\n return (item.genre.indexOf('Drama')>-1);\n });\n var dramaMoviesOfstevenSpielberg = dramaMovies.filter(function(item){\n return item.director==='Steven Spielberg';\n });\n if (dramaMovies!=0)\n return 'Steven Spielberg directed '+dramaMoviesOfstevenSpielberg.length+' drama movies!';\n}", "function howManyMovies(movies) {\n const spielbergDrama = movies.filter(movie => movie.director === \"Steven Spielberg\" && movie.genre.includes(\"Drama\"))\n return spielbergDrama.length\n }", "function howManyMovies(array) {\n if (array.length === 0) {\n return undefined\n }\n else {\n const dramaBySpielberg = array.filter(element => element.genre.includes('Drama') && element.director === 'Steven Spielberg')\n return `Steven Spielberg directed ${dramaBySpielberg.length} drama movies!`\n }\n}", "function howManyMovies (movies) {\n \n}", "function howManyMovies(movies) {\n const stevenDrama = movies.filter(function (e, i) {\n return (e.director === 'Steven Spielberg' && e.genre.includes('Drama'));\n });\n return stevenDrama.length;\n}", "function howManyMovies(movies) {\n const dramaSpielberg = movies.filter(elm => elm.director === \"Steven Spielberg\" && elm.genre.includes(\"Drama\"))\n return dramaSpielberg.length\n}", "function howManyMovies(movies) {\n\tif (movies.length == 0) {\n\t\treturn undefined;\n\t}\n\tvar dramaMovies = movies.filter(function(movie) {\n\t\treturn movie.director.includes('Steven Spielberg') && movie.genre.includes('Drama');\n\t});\n\tif (dramaMovies.length >= 0) {\n\t\treturn `Steven Spielberg directed ${dramaMovies.length} drama movies!`;\n\t}\n}", "function howManyMovies(arr) {\n const dramaSpielbergMovies = arr.reduce((acc, movie) => {\n if (\n movie.director === 'Steven Spielberg' &&\n movie.genre.includes('Drama')\n ) {\n return acc + 1;\n } else {\n return acc;\n }\n }, 0);\n return dramaSpielbergMovies;\n}", "function dramaMoviesRate() {\n\n}", "function bestYearAvg(movies){\n movies.sort((a,b) => {\n if (a.year < b.year) {return -1}\n if (a.year > b.year) {return 1}\n return 0;\n });\n let bestAvg = 0;\n let year = 0, \n sum = 0,\n count = 0;\n\n for(let i =0; i.movies.length; i++) { \n if (movies[i].year = year){\n if(bestAvg < sum / count){\n bestAvg = (sum / count)\n beatYear = movies[i].year;\n }\n }\n sum +=Number(movies[i].rate)\n count += 1;\n console.log(Number)\n } \n\n return\n}", "function bonus1() { \n count = {}\n highestCounter = 0\n for(i=0; i < morseCode.length; i++){\n currentCounter = 0\n for (j=0; j < morseCode.length; j++){\n if(morseCode[i] === morseCode[j]){\n currentCounter++\n }\n }\n if(currentCounter > highestCounter){\n highestCounter = currentCounter\n console.log(highestCounter)\n }\n }\n\n highest = 0\n repeated = ''\n\n for(prop in count) {\n if(count[prop] > highest) {\n highest = count[prop];\n repeated = prop.toString()\n console.log(\"Repeated:\" + repeated + \"Highest Count: \" + highest)\n }\n }\n repeatArray = []\n\n for(i=0; i < morseCode.length; i++){\n if(repeated === morseCode[i]){\n repeatArray.push(wordList[i])\n }\n }\n console.log(repeated + ' is repeated ' + highest + ' times.')\n console.log('Words: ' + repeatArray.join(', '))\n}", "function howManyMovies(movies) {\n let madeBySpielberg = movies.filter(\n element =>\n element.director === \"Steven Spielberg\" && element.genre.includes(\"Drama\")\n );\n return madeBySpielberg.length;\n}", "function howManyMovies(moviesArray) {\n if (moviesArray == \"\") {\n return;\n }\n\n var dramaSpielberg = moviesArray.filter(function (movie) {\n return (\n movie.genre.includes(\"Drama\") && movie.director == \"Steven Spielberg\"\n );\n });\n\n if (dramaSpielberg.length == 0) {\n return \"Steven Spielberg directed 0 drama movies!\";\n }\n\n return (\n \"Steven Spielberg directed \" + dramaSpielberg.length + \" drama movies!\"\n );\n}", "function dramaMoviesScore(movielist) {\n let drama = movielist.filter(function(movie){\n return (movie.genre.includes('Drama'));\n })\n\n let total = 0\n let result = drama.map(x => total += x.score);\n return total/drama.length\n}", "function howManyMovies(moviesArray) {\n if (moviesArray.length === 0) {\n return undefined;\n }\n var directorSpiel = moviesArray.filter(function (elemento) {\n return elemento.director === 'Steven Spielberg' && elemento.genre.indexOf('Drama') !=-1;\n });\n return 'Steven Spielberg directed ' + directorSpiel.length + ' drama movies!';\n }", "function dramaMoviesRate(movies){\n var moviesDrama = movies.filter(function(a){\nif (a.genre.includes(\"Drama\"))\n{\n return true;\n}\n});\n if (!moviesDrama.length)\n {\n return 0;\n }\n\n // llamo al metodo de la iteracion 4 para no generar mas codigo pero ahora le paso el includes de la variable moviesDrama retornando true. \n var avarage = ratesAverage(moviesDrama);\n return avarage;\n}", "function howManyMovies(sumMovies) {\n if (sumMovies.length == 0) {\n return undefined;\n }\n\n var onlySteven = sumMovies.filter(function (movie) {\n return movie.director.includes(\"Steven Spielberg\");\n });\n const onlyDramaSteven = onlySteven.filter(function (movie) {\n return movie.genre.includes(\"Drama\");\n });\n\n return (\n \"Steven Spielberg directed \" + onlyDramaSteven.length + \" drama movies!\"\n );\n}", "function dramaMoviesRate(movies){\n var dramaFilms = []\nfor (var i = 0; i < movies.length; i++){\n for (var j = 0; j < movies[i].genre.length; j++){\n if (movies[i].genre[j] === 'Drama'){\n dramaFilms.push(movies[i])\n }\n }\n}\nif (dramaFilms == 0){} else {return ratesAverage(dramaFilms);}\n}", "function dramaMoviesScore(movies) {\n let dramaMovies = movies.filter(movie => movie.genre.includes('Drama'))\n let scores = dramaMovies.map(movie => movie.score)\n let totalScore = scores.reduce(function (result, score){\n return result + score\n })\n return Number((totalScore / scores.length).toFixed(2))\n }", "function dramaMoviesRate(movies){\n // filter out the drama movies\n const dramas = movies.filter(function (movie))\n\n}", "function dramaMoviesRate(movies) {\n const dramaMov = movies.filter(elm => elm.genre.includes(\"Drama\"))\n if (dramaMov < 1) return 0\n let dramaRate = dramaMov.filter(elm => elm.rate).reduce((acc, elm) => acc + elm.rate, 0)\n let finalRate = dramaRate / dramaMov.length\n return +finalRate.toFixed(2)\n}", "function howManyMovies(oldarr) {\r\n if (oldarr.length > 0) {\r\n let mitjaDrama = oldarr.filter((e) => {\r\n if ((e.genre.indexOf('Drama') !== -1) && (e.director.indexOf('Steven Spielberg') !== -1))\r\n return e\r\n });\r\n if (mitjaDrama.length >= 0) { return `Steven Spielberg directed ${mitjaDrama.length} drama movies!`; }\r\n } else return undefined;\r\n}", "function howManyMovies (listMovies) {\n\n if (listMovies.length === 0){\n return undefined;\n }\n else{\n var dramaSp= \n listMovies.filter (function (array){\n return array.genre.includes('Drama') && array.director.includes ('Steven Spielberg')\n });\n\n } \n return \"Steven Spielberg directed \"+ dramaSp.length + \" drama movies!\";\n\n}", "function bestYearAvg(arrayOfMovies){\n if(arrayOfMovies.length ===0){return}\n let trackerThing = {};\n arrayOfMovies.forEach((eachMovie)=>{\n if(trackerThing[eachMovie.year]){\n trackerThing[eachMovie.year].number +=1;\n trackerThing[eachMovie.year].totalRate += Number(eachMovie.rate);\n } else{\n trackerThing[eachMovie.year] = {number: 1, totalRate: Number(eachMovie.rate)};\n }\n\n })\n\n let biggest = 0;\n let year = \"\";\n\n for(let yearKey in trackerThing){\n if(trackerThing[yearKey].totalRate / trackerThing[yearKey].number > biggest){\n biggest = trackerThing[yearKey].totalRate / trackerThing[yearKey].number\n year = yearKey;\n }\n }\n console.log(trackerThing);\n return `The best year was ${year} with an average rate of ${biggest}`\n}", "function dramaMoviesRate(movies){\n var onlyDrama = movies.filter(function(movie){\n return movie.genre.includes(\"Drama\");\n });\n var totalDrama = onlyDrama.reduce(function(sum,rating){\n return sum + rating.rate;\n }, 0);\nreturn totalDrama / onlyDrama.length;\n}", "function howManyMovies(e){\n var arr = e.filter(e => e.director.includes('Steven')); \n arr = arr.filter(e => e.genre.includes('Drama'));\n return \"Steven Spielberg directed \" +arr.length +\" drama movies!\" \n}", "function howManyMovies(arrayDramaMovies) {\nvar ssDramaMovies = arrayDramaMovies.fliter (function(directorname){\n return directorname.director.includes(\"Steven Spielberg\");\n});\n}", "function howManyMovies(movies) {\n const spielberg = movies.filter (function(movie) { \n if(movie.director === 'Steven Spielberg' && movie.genre.includes('Drama')) \n return movie\n })\n return spielberg.length\n}", "function howManyMovies(arr) {\n const stevensDramaMovies = arr.filter(movie => {\n return (\n movie.director === \"Steven Spielberg\" && movie.genre.includes(\"Drama\")\n );\n });\n return stevensDramaMovies.length;\n }", "function highestRating(movieList){\r\n //first find out which video has the higest rating, then check to see if there are any other videos with that rating.\r\n //push all videos with highest rating into var topVideos array.\r\n //access movieLists[0].videos[0].rating\r\n //access movieLists[0].videos[0].title\r\n //use a forEach loop to check every rating.\r\n var highestRating = 0;\r\n var topMovies = [];\r\n movieList.forEach(genre => {\r\n genre.videos.forEach(video => {\r\n if(video.rating > highestRating){\r\n highestRating = video.rating;\r\n }\r\n });\r\n });\r\n \r\n movieList.forEach(genre => {\r\n genre.videos.forEach(video => {\r\n if(video.rating === highestRating){\r\n topMovies.push(video.title);\r\n }\r\n });\r\n });\r\n return topMovies;\r\n}", "function howManyMovies(arr) {\n let spielbergMovies = [...arr].filter(movie => movie.director === \"Steven Spielberg\");\n let spilbergDramaMovies = spielbergMovies.filter(movie => movie.genre.includes(\"Drama\"));\n return spilbergDramaMovies.length;\n }", "function findBestMatch() {\n bestMatch = songMatches[0];\n for (let i = 1; i < songMatches.length; ++i) {\n if ( songMatches[i].popularity > bestMatch.popularity ) {\n bestMatch = songMatches[i];\n }\n }\n}", "function howManyMovies(arr){\n var dramaSteveFilms = arr.filter(function(obj){\n return (obj.genre.includes('Drama') && obj.director==='Steven Spielberg');\n })\n//'Steven Spielberg directed 0 drama movies!'\n if(dramaSteveFilms.length === 0) {\n return undefined;\n }\n\n return 'Steven Spielberg directed ' + dramaSteveFilms.length + ' drama movies!';\n}", "function howManyMovies(movies){\n if (movies.length==0) return undefined;\n var moviesCount=movies.filter(function(movie){\n return movie.genre.indexOf(\"Drama\")!=-1 && movie.director==\"Steven Spielberg\";\n }).length;\n return `Steven Spielberg directed ${moviesCount} drama movies!`;\n}", "function howManyMovies(sS) {\n if (!sS) return undefined;\n\n const drama = sS.filter(function(movie) {\n if (movie.genre === \"Drama\");\n {\n return movie.genre.includes(\"Drama\");\n }\n });\n\n const filteredDrama = drama.filter(function(film) {\n if (!drama) {\n return \"Steven Spielbierg directed 0 drama movies!\";\n }\n return film.director.includes(\"Steven Spielberg\");\n });\n if (filteredDrama) {\n return `Steven Spielberg directed ${filteredDrama.length} drama movies!`;\n }\n}", "function howManyMovies(arr) {\n if (!arr || arr.length === 0) {\n return undefined;\n }\n var spielbergMovies = arr.filter(function(movie) {\n return (\n movie.director === \"Steven Spielberg\" &&\n movie.genre.indexOf(\"Drama\") !== -1\n );\n });\n\n return (\n \"Steven Spielberg directed \" + spielbergMovies.length + \" drama movies!\"\n );\n}", "function dramaMoviesRate(arr){\n\nlet dramaMovie = 0;\nlet dramaRate = 0;\n\narr.forEach(function(a){\nif(a.genre.includes('Drama')){\n dramaMovie++;\n dramaRate += a.rate\n};\n}); if (dramaMovie === 0){\n return undefined;\n} \n return parseFloat((dramaRate / dramaMovie).toFixed(2));\n}", "function howManyMovies(arr){\n let filter = arr.filter(function(value){\n return value.director === 'Steven Spielberg';\n });\n return `Steven Spielberg directed ${filter.length} drama movies!`\n }", "function howManyMovies(movies) {\n return movies.reduce(function(acc, val) {\n if (val.director === \"Steven Spielberg\" && val.genre.includes(\"Drama\")) {\n acc += 1;\n }\n return acc;\n }, 0);\n}", "function howManyMovies(arr) {\n if (arr.length === 0){\n return undefined;\n }\n let filteredArray = arr.filter(movie => {\n return movie.genre.indexOf(\"Drama\") !== -1;\n });\n let spielbergMovies = filteredArray.filter(movie => {\n return movie.director.indexOf(\"Steven Spielberg\") !== -1;\n }).length;\n return `Steven Spielberg directed ${spielbergMovies} drama movies!`\n}", "function howManyMovies (movieArray) {\n if (movieArray.length===0) return undefined;\n var dramaMovies=movieArray.filter(function(elem){\n //if (elem.genre.indexOf(\"Drama\")>=0) console.log(elem.genre);\n return elem.genre.includes(\"Drama\") && elem.director.includes(\"Steven Spielberg\") ;\n });\n //console.log(dramaMovies.length);\n return \"Steven Spielberg directed \"+ dramaMovies.length+\" drama movies!\";\n}", "evaluate() {\n let highest = 0.0;\n let index = 0;\n for (let i = 0; i < this.population.length; i++) {\n if (this.population[i].fitness > highest) {\n index = i;\n highest = this.population[i].fitness;\n }\n }\n\n this.best = this.population[index].getPhrase();\n if (highest === this.perfectScore) {\n this.finished = true;\n }\n }", "function dramaMoviesRate(array) {\n\n}", "function dramaMoviesRate(array) {\n const drama = array.filter(elm => elm.genre.includes(\"Drama\"))\n sumRating = drama.reduce((acc, elm) => {\n return acc + elm.rate\n }, 0)\n\n div = 0\n drama.forEach((elm, index) => {\n div++\n if (elm.rate == undefined) div--\n })\n let result = sumRating / div\n if (drama.length == 0) return 0\n return +result.toFixed(2)\n\n}", "function dramaMoviesRate(movies) {\n const dramaMovies = movies.filter(function(item){\n const isDrama = item.genre.indexOf('Drama') >= 0;\n return isDrama;\n })\n return ratesAverage (dramaMovies);\n \n}", "function howManyMovies(movies) {\n let dramaMoviesSteven = movies.filter(function(movie) {\n return (\n movie.director === \"Steven Spielberg\" && movie.genre.includes(\"Drama\")\n );\n });\n return dramaMoviesSteven.length;\n}", "function dramaMoviesRate(movies){\n let titles = movies.filter((movie) => movie.genre.includes(\"Drama\"));\n titles = titles.map(movie => movie.rate);\n return titles.reduce((ac, cu) => {\n return ac + cu\n });\n console.log(titles);\n}", "function dramaMoviesRate(movies) {\n let drama = movies.filter(function(elem){\n return elem.genre.includes('drama')\n })\n\n let avg = drama.reduce(function(sum, elem){\n return sum + elem.rate;\n }, 0) \n \n / drama.length;\n}", "function howManyMovies (movies) {\n let stevenMovies = movies.filter (function (movie) {\n return movie.director === 'Steven Spielberg' && movie.genre.includes('Drama') \n\n });\n\n return stevenMovies.length\n}", "function howManyMovies(array){\n \n const stevenDrama = array.filter(function(movie){\n return movie.director === \"Steven Spielberg\" && movie.genre.includes(\"Drama\")\n \n })\n return stevenDrama.length\n }", "function howManyMovies(arrayMovies) {\n var movies = [];\n if (arrayMovies.length > 0) {\n movies = arrayMovies.filter(function (element) {\n return element.genre.indexOf('Drama') > -1 && element.director === 'Steven Spielberg';\n });\n return ('Steven Spielberg directed ' + movies.length + ' drama movies!');\n } else return undefined;\n}", "function howManyMovies(moviesArray, SearchDirector) {\n if (moviesArray != \"undefined\") {\n var dramaMovies = moviesArray.filter(function (movie) {\n return movie.genre.indexOf(\"Drama\") != -1\n });\n var directorMoviesArray = dramaMovies.filter(function (movie) {\n return movie.director == \"Steven Spielberg\";\n })\n console.log(directorMoviesArray);\n if (directorMoviesArray.length >= 0) {\n return \"Steven Spielberg directed \" + directorMoviesArray.length + \" drama movies!\";\n }\n }\n}", "function howManyMovies(movies){\n\n}", "function howManyMovies(arr){\n // directedMovies = 0;\n // for(i = 0; i < arr.directed){\n // if(directedMovies = direct )\n // }\n\n let newArray = arr.filter(function(d){\n \n if(d.director === 'Steven Spielberg' && d.genre.includes('Drama')){\n return d\n } \n });\n\n // newArray.forEach(oneMovie => {\n // if(oneMovie.genre.includes('Drama')){\n // directedMovies += 1;\n // }\n // })\n if(arr.length === 0) {\n return undefined;\n }\n\n return `Steven Spielberg directed ${newArray.length} drama movies!`\n}", "function howManyMovies (array) {\n\treturn array.filter (dramaMovies => dramaMovies.director === \"Steven Spielberg\" && dramaMovies.genre.includes (\"Drama\")).length\n}", "function howManyMovies(movies) {\n let drama = movies.filter(function(movie) {\n return movie.genre.includes(\"Drama\") && movie.director === \"Steven Spielberg\"\n })\n return drama.length\n}", "function howManyMovies (array) {\n let stevenSpiel = array.filter(movie => movie.genre.includes('Drama') && movie.director === 'Steven Spielberg')\n return stevenSpiel.length\n}", "function howManyMovies (movies){\n var drama = movies.filter(function(movie){\n return movie.genre.includes(\"Drama\") && (movie.director === \"Steven Spielberg\")\n });\n \n return drama.length\n }", "function dramaMoviesRate(movies) {\n var drama = movies.filter((movie) => movie.genre.includes(\"Drama\"));\n return ratesAverage(drama)\n\n}", "recursiveGetMovie(movies, i, numVotes, SciFiInstance, web3) {\n return SciFiInstance.votes(i).then((result)=>{\n\n const amount = result[1].c[0],\n hexname = result[2],\n retracted = result[3];\n\n if(!retracted) {\n // check if movie exists\n if(movies.find((movie)=>{ return movie.name === web3.toAscii(hexname) })){\n // adjust movie\n const objIndex = movies.findIndex((movie)=>{ return movie.name === web3.toAscii(hexname)})\n movies[objIndex].amount += amount/10000\n\n } else {\n // new movie\n movies = [...movies, {\n name : web3.toAscii(hexname),\n amount : parseFloat(amount/10000)}\n ]\n }\n }\n\n // get the next movie if we're not finished, otherwise: return the movies\n if (i === numVotes) {\n return movies;\n } else {\n return this.recursiveGetMovie(movies, i+1, numVotes, SciFiInstance, web3);\n }\n })\n }", "function getDramas(){\n const dramaMovies = movies.filter(function(movies){\n return movies.genre == \"Drama\"\n })\n dramaRatings = []\n\n for (let i = 0; i<dramaMovies.length; i+=1){\n dramaRatings.push(dramaMovies[i].rate)\n }\n avgDramaRating(dramaRatings)\n }", "function howManyMovies(movies) {\n const dramaMovies = []\n movies.map(function(movie){\n if (movie.director === 'Steven Spielberg') {\n movie.genre.filter(function(genre){\n if (genre === 'Drama') {\n dramaMovies.push(movie)\n }\n })\n }\n })\n \n return dramaMovies.length\n}", "function dramaMoviesScore(movies) {\n const dramaMovies = movies.filter(function(movie){\n if (movie.genre.includes('Drama')) return movie\n })\n\n if (movies.length >= 1) {\n return scoresAverage(dramaMovies)\n }\n}", "function howManyMovies(array) {\n const splilbergDrama = array.filter(elm => elm.director == \"Steven Spielberg\" && elm.genre.includes(\"Drama\"))\n return splilbergDrama.length\n\n}", "function dramaMoviesRate(movies) {\n\n var arrayDramaMovies = movies.filter (function(genredrama){\n return genredrama.genre.includes(\"drama\")\n }); \n\n var totalDramaRates = arrayDramaMovies.reduce (function(accumulator,dramaMovies) {\n return accumulator + Number(dramaMovies.rate);\n },0);\n console.log (\"The average of dramam movies is \" + dramaMoviesRate(movies));\n return (totalDramaRates/arrayDraMaMovies.length)\n}", "function directorMovies(){\nconst director = movies.filter(function(movies){\n return movies.director == \"Steven Spielberg\"\n})\n\nspielBergMovies = []\n\nfor (let i = 0; i<director.length; i+=1){\n spielBergMovies.push(director[i].title)\n}\nconsole.log(\"Steven Spielberg movies has \"+ spielBergMovies.length+ \" movies: \"+ spielBergMovies )\n}", "function howManyMovies(movies) {\n if (movies.length === 0) {\n return 0\n } \n let moviesStevenDra = movies.filter(function(item, index) {\n if (item.genre.includes(\"Drama\") && item.director === \"Steven Spielberg\") {\n return true\n } else {\n return false\n }\n }) \n return moviesStevenDra.length\n}", "function dramaMoviesRate (movies) {\n var dramaMovie = movies.filter(function(film){\n return film.genre.indexOf('Drama') !== -1;\n });\n if (dramaMovie .length<1){\n return undefined;\n }\n return ratesAverage(dramaMovie);\n}", "function howManyMovies(movieList) {\n let howMany = 0;\n movieList.filter(function(drama) {\n if (\n drama.director === \"Steven Spielberg\" &&\n drama.genre.includes(\"Drama\")\n ) {\n return howMany++;\n } else if (drama.director !== \"Steven Spielberg\") {\n return 0;\n } else {\n return 0;\n }\n });\n return howMany;\n}", "function dramaMoviesScore(moviesArray) {\n const dramaMovies = moviesArray.filter(function(movie){\n if (movie.genre.indexOf('Drama') !== -1) {\n return movie;\n } \n }); \n if (dramaMovies.length === 0) {\n return 0;\n };\n const averageDramaMovies = dramaMovies.reduce(function (sum, movie){\n return sum + movie.score; \n }, 0); return Math.round((averageDramaMovies / dramaMovies.length) * 100) /100\n}", "function howManyMovies(collection){\n var filterMovies;\n if(collection === undefined || collection.length === 0){\n return undefined;\n }\n else{\n filterMovies = collection.filter(function(movie){\n return (movie.genre.includes(\"Drama\") && movie.director.includes(\"Steven Spielberg\"));\n });\n var numberOfMovies;\n if (filterMovies.length === 0){\n numberOfMovies = 0;\n }\n else{\n numberOfMovies = filterMovies.length;\n }\n var msg = \"Steven Spielberg directed \"+ numberOfMovies +\" drama movies!\"\n return msg;\n }\n}", "function howManyMovies(moviesArray) {\n let spielbergArray = moviesArray.filter(\n (movie) =>\n movie.director === \"Steven Spielberg\" && movie.genre.includes(\"Drama\")\n );\n return spielbergArray.length;\n}", "function howManyMovies (arr) {\n const steven = arr.filter (movie => movie.director === 'Steven Spielberg' && movie.genre.includes('Drama'))\n return steven.length \n }", "function dramaMoviesRate (movies) {\n if (movies.length === 0) return 0 \n const result = movies.filter (movie => movie.genre.includes('Drama'))\n return ratesAverage(result)\n}", "function howManyMovies(array) {\n return array.reduce(function(prevVal, elem) {\n if (elem.director === \"Steven Spielberg\" && elem.genre.indexOf(\"Drama\") >= 0) return prevVal + 1;\n return prevVal;\n }, 0);\n}", "function howManyMovies(array){\n var stevenMovies = array.filter(function(movie){\n if(movie.director ===\"Steven Spielberg\" && movie.genre.indexOf('Drama')!= -1){\n return true;\n }else{\n return false;\n }\n return array.map\n \n });\n\nif(array.length===0){\n //si no encuentra ninguna película => devuleve undefined\n return undefined;\n \n}else{ \n return \"Steven Spielberg directed \" + stevenMovies.length + \" drama movies!\";}\n\n}", "function dramaMoviesRate(movies) {\n var drama = movies.filter(movie => movie.genre.includes(\"Drama\"));\n if (drama.length === 0) {\n return 0;\n }\n return ratesAverage(drama);\n }", "function dramaMoviesRate(movies) {\n const drama = movies.filter(elm => elm.genre.includes(\"Drama\"))\n if(drama.length === 0) {\n return 0\n } else {\n const avgDramaRates = drama.reduce((acc, elm) => {\n if(elm.rate) {\n return acc + elm.rate\n } else {\n return acc\n }\n }, 0) / drama.length\n let avgDramaFixed = Math.round(avgDramaRates * 100) / 100\n return avgDramaFixed\n }\n}" ]
[ "0.6601088", "0.64523566", "0.63859904", "0.6343344", "0.6334379", "0.63339186", "0.6318041", "0.6316198", "0.62765855", "0.627466", "0.62453973", "0.6232094", "0.61976904", "0.61933565", "0.6190182", "0.6167203", "0.6165928", "0.61546344", "0.6128751", "0.61215264", "0.61038184", "0.6096414", "0.60902166", "0.6083345", "0.60751283", "0.60670775", "0.60179406", "0.6017238", "0.6014854", "0.60051775", "0.5997188", "0.59961784", "0.5992279", "0.5991633", "0.59745115", "0.59736145", "0.597003", "0.5966789", "0.59642196", "0.59623575", "0.5961302", "0.5959161", "0.59582645", "0.5955282", "0.5949671", "0.59414", "0.5928127", "0.5918386", "0.59178776", "0.59165615", "0.5911631", "0.5905343", "0.59034556", "0.5898603", "0.588972", "0.5877272", "0.586626", "0.58602124", "0.5859786", "0.5828513", "0.5827014", "0.58200496", "0.58199763", "0.58179224", "0.5816822", "0.58158576", "0.5811489", "0.5804034", "0.5784847", "0.57813406", "0.5775673", "0.57741606", "0.5772921", "0.57671756", "0.57669455", "0.5753727", "0.57524055", "0.5744153", "0.5742469", "0.5740075", "0.57332766", "0.5733225", "0.57324046", "0.57304883", "0.5724481", "0.5720509", "0.57190317", "0.57128316", "0.5712625", "0.57062507", "0.5706091", "0.56986994", "0.56849277", "0.5678904", "0.5678137", "0.56712574", "0.56685936", "0.5668023", "0.56677914", "0.56656843", "0.56635016" ]
0.0
-1
Iteration 3: Alphabetic Order Order by title and print the first 20 titles
function orderAlphabetically(moviesAlph) { let alphArray = moviesAlph.map(elm => { return elm.title }) alphArray.sort((a, b) => { if (a > b) return 1 if (a < b) return -1 if (a == b) return 0 }) return alphArray.slice(0, 20) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function orderAlphabetically(array){\n let titles = array.map(i=>i.title)\n if (array.length <= 20) {\n for (i = 0; i<array.length; i++) {\n console.log(titles.sort()[i]);\n }\n } else {\n for (i = 0; i<20; i++) {\n console.log(titles.sort()[i]);\n }\n }\n}", "function orderAlphabetically(movies) {\nvar arrayTitleMovies = movies.sort(function(movie){\n return movie.title.sort();\n});\nvar i = 0; \nwhile (i<arrayTitleMovies.length) {\n if (i == 20) {\n break;\n }\n i += 1;\n}\n}", "function orderAlphabetically(arr) {\n let sorted20s = [...arr]\n let finalList = []\n sorted20s = sorted20s.sort((a,b) =>{\n if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n }\n })\n sorted20s = sorted20s.slice(0,20)\n for (let key in sorted20s) {\n // console.log(sorted20s[key].title)\n finalList.push(sorted20s[key].title)\n }\n return finalList\n}", "function orderAlphabetically(movies)\n{\n //ordenar per title\n //print els primers 20\n\n var moviesOrdered = movies.sort(function(movieA, movieB){\n if (movieA.title > movieB.title) return 1;\n else return -1;\n });\n var movies20 = moviesOrdered.slice(0,20);\n\n var titles = [];\n movies20.forEach(function(movie){\n titles.push(movie.title);\n });\n console.log(titles);\n return titles;\n}", "function orderAlphabetically (array) { \n array.sort((a, b) => {\n if(a.title > b.title) { \n return 1;\n } else if (a.title < b.title) { \n return -1;\n } else {\n return 0;\n } \n }); \n const titles = array.map((value) => { \n return value.title\n }); \n const topTwenty = titles.slice(0, 20); \n return topTwenty; \n }", "function orderAlphabetically(arr) {\n const newOrderByTitle = arr.map(function toto(element) {\n return element.title;\n });\n\n newOrderByTitle.sort(function tata(a, b) {\n if (a.toLowerCase() < b.toLowerCase()) return -1;\n if (a.toLowerCase() > b.toLowerCase()) return 1;\n return 0;\n });\n const printTitle = newOrderByTitle.reduce(function tata(\n counter,\n currentValue,\n i\n ) {\n if (i < 20) {\n counter.push(currentValue);\n return counter;\n }\n return counter;\n },\n []);\n return printTitle;\n}", "function orderAlphabetically(movie) {\n const alphabet = movie.sort(function(a,b) {\n if (a.title < b.title) {\n return -1;\n } else if (a.title > b.title) {\n return 1;\n } else {\n return 0 \n }\n});\n const orderedTitles = alphabet.map(list => list.title)\n if (orderedTitles.length > 20) {\n return orderedTitles.slice(0, 20);\n }\n return orderedTitles;\n }", "function orderAlphabetically (data){\n const alphaSortedArry = data.slice(0).sort(function(a,b){\n if (a.title.toLowerCase() > b.title.toLowerCase()){\n return 1\n }else if (a.title.toLowerCase() < b.title.toLowerCase()){\n return -1\n }else{\n return 0\n }\n })\n \n const topTwenty = alphaSortedArry.slice(0,20);\n let topTitles = [];\n let arrLengthReturn = 0;\n \n if(topTwenty.length<20){\n arrLengthReturn = topTwenty.length\n }else{\n arrLengthReturn = 20\n }\n\n for (i=0; i<arrLengthReturn; i++){\n topTitles.push(topTwenty[i].title)\n }\n \n return topTitles\n \n\n\n}", "function orderAlphabetically (movies){\n var orden = movies.sort(function(a,b){\n if (a.title>b.title) return 1;\n if (a.title<b.title) return -1;\n if (a.title === b.title) return 0;\n });\n \n for (i=0; i<20; i++){\n console.log(orden[i].title);\n }\n }", "function orderAlphabetically(arr) {\n let resultArray = arr.sort((a, b) => {\n if (a.title > b.title) {\n return 1;\n }\n if (a.title < b.title) {\n return -1\n } \n return 0;\n\n})\n let titleArray = resultArray.map(x => {\n return x.title;\n });\n return titleArray.slice(0, 20);\n}", "function orderAlphabetically(tab){\n var tab2= tab.map(function(elt){\n return elt.title;\n })\n\n console.log(tab2);\n var res= tab2.sort();\n return res.slice(0,20);\n}", "function orderAlphabetically(arr){\n let contador = [];\n for(let i =0; i<arr.length; i++){\n contador.push(arr[i].title)\n }\n contador.sort();\n return contador.slice(0,20);\n }", "function orderAlphabetically(array) {\n const alphabetArray = [...array]\n alphabetArray.sort((a, b) => {\n if (a.title < b.title) return -1\n if (a.title > b.title) return 1\n return 0\n\n })\n let titles = []\n alphabetArray.forEach(elm => titles.push(elm.title))\n\n let first20 = titles.filter((elm, index) => index < 20)\n return first20\n}", "function orderAlphabetically(array){\n var sortedArray =\n array.sort(function(a,b){\n if(a.title.toLowerCase() < b.title.toLowerCase()){\n return -1;\n } else if(a.title.toLowerCase() > b.title.toLowerCase()){\n return 1;\n }\n });\n var byTitle20 = [];\n // for(var i = 0; i < 20; i++){\n // byTitle20.push(sortedArray[i].title);\n // }\n var count = 0;\n sortedArray.forEach(function(oneMovie){\n if(count < 20){\n byTitle20.push(oneMovie.title);\n count++;\n } \n });\n \n return byTitle20;\n \n}", "function orderAlphabetically(someArray){\n someArray.sort((a, b) => (a.title > b.title) ? 1 : -1);\n const onlyTitles = someArray.map((value) => {\n return value.title\n});\n const top20 = onlyTitles.slice(0,20);\n return top20\n console.log(top20)\n}", "function orderAlphabetically(arr){\n let sorted = arr.concat().sort((a,b) => {\n if(a.title > b.title){\n return 1;\n } \n else if(a.title < b.title){\n return -1;\n }\n });\n let first20 = sorted.slice(0,20);\n let titles = first20.map(movie => {\n return movie.title;\n });\n return titles;\n}", "function orderAlphabetically(arr){\n return arr.map(movie => {\n return movie.title\n }).sort((a,b) => {\n if(a > b) return 1;\n if( a < b) return -1;\n return 0;\n }).slice(0,20)\n }", "function orderAlphabetically (movies) {\n const first20Titles = movies.map(aMovie => aMovie.title).sort();\n // if (first20Titles.length < 20) {\n // return firstTwentyTitles;\n // }\n // else {\n return first20Titles.slice(0, 20);\n }", "function orderAlphabetically(movieArray) {\n\n const titleAlpha = []\n const top20titleAlpha = []\n\n const first20Titles = movieArray.filter(e => e.title.toString())\n\n first20Titles.forEach(e => titleAlpha.push(e.title))\n titleAlpha.sort()\n\n titleAlpha.forEach(function (e, idx) {\n idx < 20 ? top20titleAlpha.push(e) : null\n })\n\n return top20titleAlpha\n}", "function orderAlphabetically(movies) {\n const sorted = movies.map((item) => {\n return item.title;\n});\nsorted.sort ((a,b) => {\n return a.localeCompare(b);\n});\nreturn sorted.slice(0,20);\n}", "function orderAlphabetically(array) {\n let orderAlphArray = array.sort(function (movie1, movie2) { \n let title1 = movie1.title.toLowerCase();\n let title2 = movie2.title.toLowerCase();\n if (title1 > title2) { \n return 1;\n } else if (title1 < title2) {\n return -1;\n }\n return 0;\n })\n return orderAlphArray.map(function (movie) { \n return movie.title\n }).slice(0, 20) \n \n }", "function orderAlphabetically(movies){\n movies.sort(function(a,b){\n return a.title < b.title ? -1 : 1;\n });\n var first20=[];\n var limit = 20;\n if (movies.length<20){\n limit= movies.length;\n }\n for (var i = 0; i<limit; i++){\n first20.push(movies[i].title);\n }\n return first20;\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 orderAlphabetically(arr) {\n\n let orderArr = [];\n let total = 0;\n arr.sort((a, b) => {\n if (a.title < b.title) {\n return -1;\n }\n if (a.title > b.title) {\n return 1;\n }\n return 0;\n });\n if (arr.length < 20) {\n total = arr.length;\n } else {\n total = 20;\n }\n for (let i = 0; i < total; i += 1) {\n orderArr.push(arr[i].title);\n }\n //console.log(orderArr)\n return orderArr;\n}", "function orderAlphabetically(movies) {\n\n return movies.map(a => a.title).sort().slice(0, 20)\n\n}", "function orderAlphabetically(movies) {\n const movieTitle = movies.map(movie => movie.title);\n return movieTitle.sort(function(a,b) {\n return a.localeCompare(b);\n }).slice(0,20)\n \n}", "function orderAlphabetically(movies) {\n let alphaOrder = movies.map(elm => elm.title).sort((a, b) => a.localeCompare(b))\n const top20Alpha = alphaOrder.splice(0, 20)\n return top20Alpha;\n}", "function orderAlphabetically(array){\nlet newArray = array.map(function(order){\n return order.title\n});\nlet title = newArray.sort();\nreturn title.slice(0,20);\n}", "function orderAlphabetically(array){\n const arrayOfTitles = array.map(element => element.title)\n const sortedArrayOfTitles = arrayOfTitles.sort()\n if(arrayOfTitles.length < 20){\n return sortedArrayOfTitles\n }\n else{\n return sortedArrayOfTitles.slice(0,20)\n }\n}", "function orderAlphabetically([...movies]){\n let orderArr = movies.sort( (a, b) => {\n if (a.title > b.title){\n return 1;\n } else {\n return -1;\n }\n })\n \n return orderArr.slice(0, 20).map(movie => movie.title);\n}", "function orderAlphabetically(arr) {\n let clone = JSON.parse(JSON.stringify(arr))\n \n clone.sort((first, second) =>{\n if(first.title > second.title){\n return 1\n }\n else if(first.title < second.title){\n return -1\n }\n else{\n return 0\n }\n })\n \n return clone.map((elem) => {\n return elem.title\n }).slice(0,20)\n}", "function orderAlphabetically(arr){\n let myArr = JSON.parse(JSON.stringify(arr));\n let alphabetical=myArr.sort(function(a,b){\n return a.title.localeCompare(b.title);\n }); \n let first20=alphabetical.filter(function(a,b){\n return a, b<20;\n })\n let first20Title=first20.map(function(movie){\n return movie.title\n })\n return first20Title;\n }", "function orderAlphabetically(myArray) {\n\tconst titleArray = []\n\tfor (const movie of myArray) {\n\t\ttitleArray.push(movie.title.toLowerCase());\n\t}\n\ttitleArray.sort()\n\treturn titleArray.slice(0,20)\n}", "function orderAlphabetically(movies) {\n const copySortTitle = [...movies].sort((a, b) => a.title.localeCompare(b.title))\n const twentyTitles = copySortTitle.map(elm => elm.title).slice(0, 20)\n return twentyTitles\n}", "function orderAlphabetically(movies){\n if (movies.length === 0) return 0;\n let titleList = movies.map(function(movie) {\n return movie.title;\n })\n titleList.sort(function(a,b){\n let title1 = a.toLowerCase();\n let title2 = b.toLowerCase();\n if (title1 < title2) return -1;\n if (title1 > title2) return 1;\n if (title1 === title2) return 0;\n })\n if (titleList.length < 20){\n return titleList.slice(0,titleList.length)\n }\n return titleList.slice(0,20)\n }", "function orderAlphabetically(movies) {\n let movAlphab = movies.sort(function(a, b) {\n if (a.title > b.title) {\n return 1\n } else if (a.title < b.title) {\n return -1\n } else {\n return 0\n }\n })\n return movAlphab.map(function(item){\n return item.title\n }).slice(0, 20);\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 orderAlphabetically(movies) {\n const ordered = movies.sort(function (a, b) {\n if (a.title < b.title) {\n return -1\n } else if (a.title > b.title) {\n return 1\n } else {\n return 0\n };\n });\n return ordered.slice(1, 20);\n\n}", "function orderAlphabetically(movies) {\n let firstTwenty = movies.map(movie => movie.title);\n firstTwenty.sort();\n if (movies.length >=20){\n firstTwenty = firstTwenty.slice(0,20);\n }\n\n return firstTwenty;\n \n}", "function orderAlphabetically(arr) {\n arr.sort(function(a, b) {\n if (a.title > b.title) {\n return 1;\n }\n if (a.title < b.title) {\n return -1;\n }\n return 0;\n });\n if(arr.length<20){\n return arr;\n \n }else{\n return arr.splice(0,20);\n }\n }", "function orderAlphabetically(arr) {\n return arr\n // let orderTop20 = [...arr].sort((a, b) => {\n // if (a.title > b.title) {\n // return 1;\n // } else if (a.title < b.title) {\n // return -1;\n // }\n // })\n .map(movies => movies.title)\n .sort()\n .slice(0, 20);\n return orderTop20;\n }", "function orderAlphabetically(arr) {\n let movieTitles = arr.map(movie => movie.title);\n const alpha = movieTitles.sort((a, b) => a > b ? 1 : -1).slice(0, 20);\n return alpha;\n}", "function orderAlphabetically(arr) {\n let newArray = arr.sort((a, b) => {\n if (a.title > b.title) {\n return 1;\n }\n if (a.title < b.title) {\n return -1;\n }\n return 0;\n });\n newArray = newArray.map(function (movie) {\n return movie.title;\n });\n return newArray.slice(0, 20);\n}", "function orderAlphabetically(movies) {\n\n var movieTitles = [...movies];\n \n movieTitles = movies.map(movie => {\n return movie.title;\n });\n\n movieTitles.sort((a, b) => {\n if (a.toLowerCase() > b.toLowerCase())\n return 1;\n if (a.toLowerCase() < b.toLowerCase())\n return -1;\n return 0;\n });\n\n\n const top20= movieTitles.slice(0,20);\n return top20;\n}", "function orderAlphabetically(array) {\n let alphaOrdered = array.slice().sort(function(a, b) {\n return a[\"title\"].localeCompare(b[\"title\"]);\n });\n\n let top20 = alphaOrdered.slice(0, 20).map(function(movie) {\n return movie[\"title\"];\n });\n\n return top20;\n}", "function orderAlphabetically(arr) {\n let titles = arr.map(function(movie) {\n return movie.title\n });\n let alphabeticOrder = titles.sort(function(a , b) {\n return a.localeCompare(b)\n });\n return alphabeticOrder.slice(0, 20)\n}", "function orderAlphabetically(moviesArray){\n return moviesArray.map((x) => x.title)\n sort()\n .slice(0, 20);\n}", "function orderAlphabetically(movies) {\n const sortedArr = movies.sort((movieA, movieB) => movieA.title.localeCompare(movieB.title));\n const orderedTitles = sortedArr.map(list => list.title)\n if (orderedTitles.length > 20) {\n return orderedTitles.slice(0, 20);\n }\n return orderedTitles;\n}", "function orderAlphabetically(movies) {\n var moviesSorted = movies.sort(function(itemA, itemB) {\n if (itemA.title < itemB.title) {\n return -5;\n } else {\n return 10;\n }\n });\n var moviesFirst20 = [];\n for (var i = 0; i < 20; i += 1) {\n moviesFirst20.push(moviesSorted[i].title);\n }\n return moviesFirst20;\n}", "function orderAlphabetically (movies) {\n var filmTitle = movies\n .map(function(film){\n return film.title\n })\n .sort(function(a,b){\n return a>b? 1 : -1 \n })\n \n if (filmTitle.length >20)\nreturn filmTitle.filter(function(film){\n return filmTitle.indexOf(film)<20;\n })\n else return filmTitle;\n }", "function orderAlphabetically(movies) {\r\n let moviesSorted = movies.sort((a, b) => {\r\n if (a.title < b.title) return -1\r\n else return 1\r\n });\r\n let result = [];\r\n if (moviesSorted.length < 20) {\r\n moviesSorted.forEach(e => result.push(e.title));\r\n }\r\n else {\r\n for (let index = 0; index < 20; index++) {\r\n result.push(moviesSorted[index].title);\r\n }\r\n }\r\n return result;\r\n}", "function orderAlphabetically (array) {\n array.sort((a,b) => {\n if (a.title > b.title) {\n return 1\n } else if (a.title < b.title) {\n return -1\n } else {\n return 0\n }\n })\n let titleArray = [];\n if (array.length > 0){\n if (array.length < 20) {\n for (let i = 0; i < array.length; i++){\n titleArray.push(array[i].title);\n }\n } else {\n for (let i = 0; i < 20; i++) {\n titleArray.push(array[i].title);\n }\n }\n }\n\n return titleArray\n}", "function orderAlphabetically(movies) {\n movieTitles = [];\n for (let i = 0; i < movies.length; i++) {\n movieTitles.push(movies[i].title);\n }\n var sortedTitles = movieTitles.sort(function(a, b) {\n if (a > b) return 1;\n if (a < b) return -1;\n return 0;\n });\n var longSortedTitles = [];\n if (sortedTitles.length <= 20) {\n return sortedTitles;\n } else if (sortedTitles.length > 20) {\n for (let i = 0; i < 20; i++) {\n longSortedTitles.push(sortedTitles[i]);\n }\n return longSortedTitles;\n }\n}", "function orderAlphabetically(movies) {\n let moviesArr = [...movies];\n let newArr = moviesArr.sort((x, y) => {\n if (x.title > y.title) {\n return 1;\n } else if (x.title < y.title) {\n return -1;\n }\n });\n return newArr\n .map(function(movies) {\n return movies.title;\n })\n .slice(0, 20);\n}", "function orderAlphabetically(array) {\n const titleArray = array.map(movie => movie.title).sort((a, b) => a.localeCompare(b));\n return titleArray.slice(0, 20);\n}", "function orderAlphabetically (array) {\n\tconst sortedTitlesArray = array.map(movie => {\n\t\treturn movie.title\n\t}).sort()\n\tif (sortedTitlesArray.length > 20) {\n\t\tlet firstTwenty = []\n\t\tfor (let i=0; i < 20; i++) {\n\t\t\tfirstTwenty.push(sortedTitlesArray[i])\n\t\t}\n\t\treturn firstTwenty\n\t} else {\n\t\treturn sortedTitlesArray\n\t}\n}", "function orderAlphabetically(array) {\n let arrayTitle = array.map(movie => movie.title);\n\n return arrayTitle.sort().slice(0,20);\n\n\n}", "function orderAlphabetically (array){\n\n var titulosPeliculas = array.map(function(element){\n \n return element.title;\n });\n\n return titulosPeliculas.sort().slice(0,20);\n}", "function orderAlphabetically(movies){\n let moviesOrder = movies.sort(function(a,b) {\n if (a.title > b.title) return 1\n if (a.title < b.title) return -1\n }) \n \n let movisTittle = moviesOrder.map(movie => {\n return movie.title \n })\n \n return movisTittle.splice(0,20)\n\n}", "function orderAlphabetically(movies) {\n var onlyMoviesTitle = []\n var alphabeticallOrder = movies.sort(function (movie1, movie2) {\n var title1 = movie1.title;\n var title2 = movie2.title;\n if (title1 > title2) {\n // console.log(title1 + \" should be under \" + title2);\n return +1;\n } else if (title1 < title2) {\n // console.log(title1 + \" should be above \" + title2);\n return -1;\n }\n })\n\n alphabeticallOrder.reduce(function (allmovietitle, movie) {\n onlyMoviesTitle.push(movie.title);\n }, []);\n // console.log(onlyMoviesTitle);\n if (onlyMoviesTitle.length <= 20) {\n return onlyMoviesTitle;\n } else {\n // console.log(onlyMoviesTitle.slice(0, 20))\n return onlyMoviesTitle.slice(0, 20)\n }\n}", "function orderAlphabetically(collection){\n var arrayTitleSort = collection.sort(function(movieA,movieB){\n var movieAupper = movieA.title.toUpperCase();\n var movieBupper = movieB.title.toUpperCase();\n if (movieAupper < movieBupper){\n return -1;\n }\n if (movieAupper > movieBupper){\n return 1;\n }\n });\n var titlesArray = [];\n arrayTitleSort.forEach(function(movie,index) {\n if (index < 20)\n {\n titlesArray[index] = movie.title;\n }\n });\n return titlesArray;\n}", "function orderAlphabetically(array) {\n const orderedByTitle = [...array].sort((a, b) => a.title < b.title ? -1 : 1);\n let onlyTitle = orderedByTitle.slice(0, 20).map(function (a) {\n return a.title\n })\n return onlyTitle\n\n}", "function orderAlphabetically(movies){\n var orderMovies = movies.sort(function(a,b){\n if (a.title > b.title) {return 1;}\n else if (a.title < b.title) {return -1;} \n else {return 0;}\n });\n var newArray = [];\n orderMovies.forEach(function(orderMovies) {\n newArray.push(orderMovies.title);\n });\n return newArray.slice(0,20);\n}", "function orderAlphabetically(lotsOfMovies) {\n return [...lotsOfMovies]\n .sort((a, b) => {\n if (a.title > b.title) return 1;\n else if (a.title < b.title) return -1;\n else return 0;\n })\n .map((eachMovie) => eachMovie.title)\n .slice(0, 20);\n}", "function orderAlphabetically() {}", "function orderAlphabetically(movies) {\n let sortedMovies = [...movies]\n sortedMovies.sort((a, b) => {\n if (a.title.toLowerCase() > b.title.toLowerCase()) {\n return 1\n } else if (a.title.toLowerCase() < b.title.toLowerCase()) {\n return -1\n } else {\n return 0\n }\n });\n let titlesList = sortedMovies.map((value) => value.title)\n return titlesList.slice(0, 20);\n}", "function orderAlphabetically(arr) {\n let moviesCopy = [];\n let sortedTitles = [];\n for (let movie of arr) {moviesCopy.push(movie.title);}\n moviesCopy.sort();\n if (moviesCopy.length < 20) {\n for (let j = 0; j < moviesCopy.length; j++) {sortedTitles.push(moviesCopy[j]);}\n } else for (let i = 0; i < 20; i++) {sortedTitles.push(moviesCopy[i]);}\n return sortedTitles;\n}", "function orderAlphabetically(arr) {\n const moviesTitles = arr.map((movie) => {\n return movie.title;\n });\n moviesTitles.sort();\n if (moviesTitles.length > 20) {\n return moviesTitles.slice(0, 20);\n };\n return moviesTitles;\n}", "function orderAlphabetically(array) {\n // step1: create an array of strings (title of each movie)\n // step2: order them alphabetically\n // step3: return the first 20 movies (max)\n\n let myArray = array.map(function(elem) {\n return elem.title}); \n myArray.sort();\n return myArray.filter(function(elem, index) {\n return index < 20;\n });\n}", "function orderAlphabetically(movies) {\n const onlyTitles = movies.map(i => i.title)\n const allpha = onlyTitles.sort((a,b) => a > b? 1 : b> a? -1 : 0)\n return allpha.filter((item, index)=> index <= 19)\n}", "function orderAlphabetically(arr) {\n var newArray = arr.map(function(movie) {\n return movie.title;\n });\n return newArray.sort().slice(0, 20);\n}", "function orderAlphabetically(movies) {\n return movies\n .map(movie => movie.title)\n .sort((a, b) => a.localeCompare(b))\n .slice(0, 20);\n}", "function orderAlphabetically(movies){\n let titles = movies.map(movie => movie.title);\n return titles.sort().splice(0,20);\n}", "function orderAlphabetically(moviesArray) {\n let firstTwentyAlpha = [...moviesArray]\n .sort(function(movie1, movie2) {\n if (movie1.title > movie2.title) {\n return 1;\n } else if (movie1.title < movie2.title) {\n return -1;\n } else {\n return 0;\n }\n })\n .map(function(movieTitle) {\n return movieTitle.title;\n })\n .slice(0, 20);\n return firstTwentyAlpha;\n}", "function orderAlphabetically(movies) {\n var onlyTitles = movies.map(a => {\n return a.title;\n });\n\n var orderedOnlyTitles = onlyTitles.sort();\n return orderedOnlyTitles.slice(0, 20);\n}", "function orderAlphabetically(array) {\n array = array.sort((a, b) => { return (a.title > b.title) ? 1 : -1 });\n let newArray = []\n array.forEach(function (movie) { newArray.push(movie.title) })\n if (newArray.length >= 20) {\n return newArray.slice(0, 20);\n } else {\n return newArray;\n }\n}", "function orderAlphabetically(movies) {\n const moviesArr = JSON.parse(JSON.stringify(movies))\nconst sortedMoviesArr = moviesArr\n .sort((a, b) => {\n if (a.title > b.title) {\n return 1;\n } else if (a.title < b.title) {\n return -1;\n } else {\n return 0;\n }\n })\n .map(eachMovie => eachMovie.title)\n .slice(0, 20);\n\n return sortedMoviesArr\n}", "function orderAlphabetically(movies) {\n const copy = [...movies];\n const sortCopy = copy.sort(function (a, b) {\n return a.title.localeCompare(b.title)\n });\n const firstTwenty = sortCopy.slice(0, 20);\n let array = [];\n firstTwenty.forEach((movie) => array.push(movie.title));\n return array;\n }", "function orderAlphabetically(movies) {\n const copy = [...movies]\n const ordered = copy.sort(function(a, b){\n return a.title.localeCompare(b.title)\n }).map(function(movie){\n return movie.title\n })\n return ordered.slice(0, 20)\n}", "function orderAlphabetically(bunchaMovies){\n let arrayToUse = [...bunchaMovies];\n arrayToUse.sort((a,b)=>{\n if(a.title < b.title){\n return -1;\n } else if (b.title < a.title){\n return 1\n }\n return 0;\n })\n let blah = arrayToUse.slice(0,20);\n let titlesOnly = blah.map((eachMovieObject)=>{\n return eachMovieObject.title;\n })\n return titlesOnly;\n}", "function orderAlphabetically(alphabetOrderedArr) {\n let copiaMovies = Array.from(alphabetOrderedArr);\n\n function ordenarAZ(a,b) {\n return a.title.localeCompare(b.title);\n }\n\n copiaMovies.sort(ordenarAZ);\n\n copiaMovies = copiaMovies.map(movies => {\n\n return movies.title\n }).slice(0,20);\n\n return copiaMovies;\n}", "function orderAlphabetically(movies){\n var sortedTitles=[];\n movies.sort(function (a,b){\n return ((a.title>b.title)?1:-1);\n });\n for (i=0;i<20 && i<movies.length;i++){\n sortedTitles.push(movies[i].title);\n }\n return sortedTitles;\n}", "function orderAlphabetically(movies) {\n\tconst sortedMovies = movies.sort(titleComparison);\n\tselectedMovies = sortedMovies.slice(0, 20); // pour cibler les 20 premiers\n\treturn selectedMovies.map((movie) => movie.title); // pour avoir juste le titre\n}", "function orderAlphabetically(arrayOfMovies){\n const moviesByTitle = [...arrayOfMovies];\n moviesByTitle.sort((movieA, movieB) => {\n if (movieA.title.toLowerCase() > movieB.title.toLowerCase()) {\n return 1;\n } else if (movieA.title.toLowerCase() < movieB.title.toLowerCase()) {\n return -1;\n } else {\n return 0;\n }\n });\n //maximize the minimum\n let numberOfMoviesToReturn = Math.max(Math.min(moviesByTitle.length, 20), 0);\n const top20movieTitles = [];\n for (let i=0; i<numberOfMoviesToReturn; i++){\n top20movieTitles.push(moviesByTitle[i].title);\n }\n return top20movieTitles;\n}", "function orderAlphabetically(array) {\n\n let movieByTitle = array.map(movie => movie.title)\n let topTwenty = movieByTitle.sort((a, b) => (a > b) ? 1 : -1)\n topTwenty.length > 20 ? topTwenty.splice(20) : topTwenty;\n\n return topTwenty\n }", "function orderAlphabetically(movies) {\n return movies.sort(function(movie1, movie2) {\n return movie1.title.localeCompare(movie2.title);\n })\n .slice(0, 20)\n .map(function(movie) {\n return movie.title;\n });\n}", "function orderAlphabetically (array) {\n const clone = Array.from(array)\n const sorted = clone.sort((movieA, movieB) => {\n if (movieA.title < movieB.title) {\n return -1\n } else if (movieA.title > movieB.title) {\n return 1\n } else {\n return 0\n }\n })\n return sorted.reduce((total, movie) => {\n if (total.length < 20) {\n total.push(movie.title)\n }\n return total\n }, [])\n}", "function orderAlphabetically (arrayOfMovies) {\n let sortedArr = arrayOfMovies.slice().sort((a,b) => {\n if (a.title > b.title) return 1;\n if (a.title < b.title) return -1;\n }); \n let limitArr = [];\n for (let i=0; (i<sortedArr.length)&&i<20; i++) {\n limitArr.push(sortedArr[i].title);\n } \n return limitArr; \n}", "function orderAlphabetically(arr){\n let newArr = JSON.parse(JSON.stringify(arr));\n newArr.sort((a,b) => {\n if(a.title < b.title) return -1;\n });\n newArr = newArr.slice(0,20).map(e=>{\n return e.title;\n });\n return newArr;\n}", "function orderAlphabetically(movieList) {\n let ordered = movieList.sort(function(a, b) {\n return a.title.localeCompare(b.title);\n });\n ordered = ordered.map(function(movie) {\n return movie.title;\n });\n return ordered.slice(0, 20);\n}", "function orderAlphabetically () {\n movies.sort(function (itemA,itemB){\n if (itemA.title<itemB.title){\n //if itemA comes before itemB return negative\n //(the order is good)\n return -1;\n }\n else{\n //if itemB comes before itemA return positive\n //they need to switch\n return 50;\n }\n })\n \n console.log(movies);\n}", "function orderAlphabetically(moviesArray) {\n let movieTitles = moviesArray.map(function(movie) {\n return movie.title\n }); \n\n movieTitles.sort(function(title1, title2){\n if (title1 > title2) {\n return 1;\n } else if (title1 < title2) {\n return -1;\n }\n }); return movieTitles.slice(0, 20);\n}", "function generateRemainingTitles() {\n for (let i = 0; i < (3 - acceptedTitleAmount); i++) {\n suggestion();\n addCurrentTitle();\n }\n}", "function orderAlphabetically(moviesArray) {\n\n const moviesArrayCopy = JSON.parse(JSON.stringify(moviesArray));\n\n const titlesArray = moviesArrayCopy.map(function(element) {\n return element.title;\n });\n\n const firstTwentyMoviesArray = titlesArray.sort(function(element1, element2){\n\n return element1.localeCompare(element2);\n });\n\n return firstTwentyMoviesArray.slice(0,20);\n\n}", "function orderAlphabetically(movies) {\n const newArray = movies.map(function(item){\n return item.title;\n });\n const oldestFirst = newArray.sort();\n\nreturn oldestFirst.slice(0, 20);\n}", "function orderAlphabetically(arr) {\n let alphArr = [...arr].sort((s1, s2) => {\n if (s1.title > s2.title) return 1;\n else return -1\n })\n alphArr.splice(20)\n return alphArr.map(movies => movies.title)\n\n}", "function orderAlphabetically(movies) {\n var sortedArray = movies.sort(function(a,b) {\n if(a.title < b.title) {\n return -1;\n }\n if(a.title > b.title) {\n return 1;\n }\n return 0;\n })\n var titlesArray = sortedArray.map(function(movie) {\n return movie.title;\n })\n return titlesArray.splice(0, 20);\n}", "function orderAlphabetically(arr){\n var moviesTitle = arr.map(function(obj){\n return obj.title;\n });\n var moviesSorted = moviesTitle.sort();\n if (moviesSorted.length > 20){\n moviesSorted.splice(20);\n }\n return moviesSorted\n}", "function orderAlphabetically(array) {\n if(array.length > 19) {\n let moviesArray= [...array];\n\n let alphabeticalMovies = moviesArray.sort(\n (a,b) => (a.title > b.title) ? 1 : -1\n )\n let alphaMovSliced = alphabeticalMovies.slice(0, 20);\n\n let movieByTitle = alphaMovSliced.map(movie => movie.title)\n \n return movieByTitle\n }\n let moviesArray= [...array];\n\n let alphabeticalMovies = moviesArray.sort(\n (a,b) => (a.title > b.title) ? 1 : -1\n )\n\n let movieByTitle = alphabeticalMovies.map(movie => movie.title)\n \n return movieByTitle\n\n}", "function orderAlphabetically(array) {\n let newarray = [];\n newarray = array.map(function (movie) {\n if (array.length > 20) {\n return movie.title[(0, 20)];\n }\n return movie.title;\n });\n return newarray.sort();\n}" ]
[ "0.7802424", "0.7719607", "0.7523073", "0.75131094", "0.74586827", "0.7456341", "0.74306804", "0.7410855", "0.74006325", "0.73221534", "0.7291631", "0.7289742", "0.7282026", "0.7262289", "0.7215079", "0.7188504", "0.71582454", "0.7137464", "0.7134475", "0.7132253", "0.71109486", "0.70997685", "0.70994407", "0.7098699", "0.70894665", "0.70830417", "0.7075468", "0.7072703", "0.7066192", "0.70632184", "0.7052559", "0.7050976", "0.7041337", "0.7028665", "0.69961876", "0.6991402", "0.6991106", "0.6988897", "0.69805497", "0.6968195", "0.69579256", "0.6952311", "0.69463867", "0.6942509", "0.69397473", "0.6925188", "0.6923916", "0.6923694", "0.691964", "0.69149554", "0.69031066", "0.68961513", "0.6892672", "0.6890716", "0.68887067", "0.68860954", "0.6872493", "0.68723315", "0.68662506", "0.6864456", "0.6852884", "0.68517625", "0.6844429", "0.6832256", "0.6828545", "0.6822386", "0.68146825", "0.679844", "0.6788701", "0.67857647", "0.678443", "0.6783357", "0.675402", "0.6725816", "0.6719853", "0.6699432", "0.66937846", "0.6693761", "0.66862595", "0.6669669", "0.6661703", "0.6658893", "0.66586095", "0.66500807", "0.6647631", "0.6633643", "0.6621958", "0.6621901", "0.6616897", "0.6610978", "0.6608512", "0.6602767", "0.659869", "0.65891004", "0.65812063", "0.65427756", "0.654044", "0.6529066", "0.6526827", "0.65205634" ]
0.70316327
33
Iteration 4: All rates average Get the average of all rates with 2 decimals
function ratesAverage(avgRate) { if (avgRate.length === 0) { return 0; } let ratesArray = avgRate.reduce((acc, elm) => { return acc + elm.rate }, 0); return number(ratesArray / avgRate.length.toFixed(2)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ratesAverage(arr) {\n var allRates = arr.reduce(function(acc, elem) {\n return (acc += Number(elem.rate));\n }, 0);\n return parseFloat((allRates / arr.length).toFixed(2));\n}", "function ratesAverage(allRates) {\n\n if (allRates.length === 0) {\n return 0;\n }\n\n meanRates = allRates.reduce( (acc, elem) => elem.rate ? acc + elem.rate : acc + 0, 0)/allRates.length;\n \n return Math.round(meanRates * 100) / 100;\n }", "function ratesAverage(arr) {\n let temp = arr.reduce(function(cont, obj) {\n return cont + Number(obj.rate);\n }, 0);\n let result = temp / arr.length;\n let roundedResult = Number(result.toFixed(2));\n return roundedResult;\n }", "function ratesAverage(arr) { \n var rates = arr.map(function(obj){\n return obj.rate;\n });\n var total = rates.reduce(function(acc,number){\n return acc+number; \n }, 0); \n return parseFloat((total/rates.length).toFixed(2));\n}", "function ratesAverage(array) {\n return parseFloat((array.reduce((acc, current) => acc + parseFloat(current.rate), 0) / array.length).toFixed(2))\n}", "function ratesAverage(array){\n return parseFloat((array.reduce((acc, current) => acc + parseFloat(current.rate), 0) / array.length).toFixed(2))\n}", "function ratesAverage(array){\n //arrayRates => array que tiene en cada posición el rate de cada película\n var arrayRates = array.map(function(element){\n if(isNaN(parseFloat(element.rate))){\n //caso por si la propiedad rate es rate: \"\"; \n return 0.0;\n }\n \n return parseFloat(element.rate);\n });\n \n //total => variable que tiene el total de rates de todas las películas\n var total = arrayRates.reduce(function(accumulator, current){\n \n return accumulator + current;\n }, 0);\n \n //se redondea a 2 decimales\n return Math.round(((total/(array.length))) * 100) / 100;\n }", "function ratesAverage(array){\n if (array.length > 0 ){\n const avgRates = array.reduce(function (acc,val){\n if (!val.rate){\n return acc\n }\n return acc + val.rate\n \n },0)\n \n let average = (avgRates/array.length)\n return Number(average.toFixed(2))\n }\n return 0\n }", "function ratesAverage(arr){\n if (arr.length === 0){\n return 0\n }else{\n\n const totalRates = arr.reduce((accumulator,value) => {\n if(!value.rate) { \n return value.rate = 0; }\n \n return accumulator + value.rate;\n \n},0);\n\nreturn parseFloat((totalRates / arr.length).toFixed(2));\n }\n}", "function ratesAverage(array){\n var total = array.reduce(function (accumulator, item) {\n return accumulator + Number(item.rate); \n },0).toFixed(2);\n return total/array.length;\n}", "function ratesAverage(arr) {\n let sum = 0;\n sum = arr.reduce((total, item) => total += item.rate, 0);\n return parseFloat((sum / arr.length).toFixed(2))\n}", "function ratesAverage(array) {\n let result = array.reduce((accumulator, currentValue) => accumulator + currentValue.rate, 0);\n return parseFloat((result / array.length).toFixed(2));\n}", "function ratesAverage (arr) {\n if (arr.length === 0){\n return 0\n } \n \n else {\n const rateArr = arr.map(item => item.rate)\n console.log(rateArr)\n\n const onlyActualRatesArr = rateArr.filter(element => typeof element === 'number')\n \n const sumOfRates = onlyActualRatesArr.reduce((acc, c) => acc + c);\n const averageRates = sumOfRates/rateArr.length;\n return Number(averageRates.toFixed(2));\n }\n}", "function ratesAverage(array) {\n let average = array.reduce((a, b) => {\n return a + Number(b.rate)\n }, 0) / array.length;\n return parseFloat(average.toFixed(2))\n}", "function ratesAverage(array){\n\n const total = array.reduce(function (sum, item) {\n if (typeof item.rate === 'number')\n {\n return sum + item.rate;\n }else {\n return sum + 0;\n }\n \n },0);\n \n let avgTotal = 0;\n \n if (array.length === 0){\n return 0\n }\n\n avgTotal = total / array.length;\n \n return parseFloat(avgTotal.toFixed(2));\n}", "function ratesAverage(arr){\n if(arr.length === 0) return 0;\n let sumRate = arr.reduce((sum, elem) => {\n if(elem.rate === undefined) return sum;\n return sum += elem.rate;\n },0);\n return parseFloat((sumRate/arr.length).toFixed(2));\n}", "function ratesAverage(array) {\n\n if (array.length == 0) {\n return 0\n }\n let totalRates = array.reduce((a, c) => {\n\n return a + (c.rate ? c.rate : 0);\n }, 0);\n let avgRate = (totalRates / array.length).toFixed(2);\n\n return Number(avgRate);\n\n}", "function ratesAverage(array){\n if(array.length===0)\n {return 0};\n let totRate=array.reduce((acc,elem)=>{\n return acc+elem.rate\n },0)\n\n let avgRate=totRate/array.length\n return Number(avgRate.toFixed(2))\n}", "function ratesAverage(array) {\n const sum = array.reduce((sum, element) => sum + parseFloat(element.rate), 0)\n return sum / array.length\n}", "function ratesAverage(array) {\n let ratesSum = array.reduce(function(prevVal, elem) {\n if (typeof(elem.rate) === \"undefined\") return prevVal;\n return prevVal + elem.rate;\n }, 0);\n if (array.length > 0) \n return Math.round(100*(ratesSum / array.length)) / 100;\n //alternatively: return Number((ratesSum / array.length).toFixed(2));\n return 0;\n}", "function ratesAverage(array) {\n div = 0\n sumRating = array.reduce((acc, elm) => {\n if (elm.rate == undefined) {\n elm.rate = 0\n }\n return acc + elm.rate\n }, 0)\n\n\n array.forEach((elm, index) => {\n div++\n if (elm.rate == undefined) {\n\n div--\n }\n })\n // console.log(sumRating)\n // console.log(div)\n let result = sumRating / div\n if (array.length == 0) return 0\n //console.log(+result)\n return +result.toFixed(2)\n}", "function ratesAverage(array) {\n const mappedArr = array.map(rates => parseFloat(rates.rate));\n const sum = (sumarizer, currentElement) => sumarizer + currentElement;\n let avg = parseFloat(((mappedArr.reduce(sum)) / mappedArr.length).toFixed(2));\n return avg;\n}", "function ratesAverage(array) {\n let result = array.reduce(function (acc, movie) { \n return acc + Number(movie.rate)\n }, 0) / array.length;\n \n let averageResult = Number(result.toFixed(2)) \n return averageResult\n }", "function ratesAverage(arr) {\n if (arr.length === 0) return 0;\n const avrRate =\n arr.reduce((acc, val) => {\n if (!val.rate) val.rate = 0;\n return acc + val.rate;\n }, 0) / arr.length;\n return parseFloat(avrRate.toFixed(2));\n}", "function ratesAverage (array) {\n\tif (array.length === 0) {\n\t\treturn 0\n\t} else {\n\t\tconst averageRate = array.reduce ((accumulator, current) => {\n\t\t\tif (!current.rate) {\n\t\t\t\treturn accumulator + 0\n\t\t\t}\n\t\t\treturn accumulator + current.rate\n\t\t}, 0)\n\t\treturn Number ((averageRate / array.length).toFixed(2))\n\t}\n}", "function ratesAverage(arr) {\n\n var total = arr.reduce(function (sum, item) {\n return sum + Number(item.rate);\n\n }, 0);\n\n return total / arr.length;\n}", "function ratesAverage(array){\n var num = \n array.reduce(function(sum, current){\n return sum += parseFloat(current.rate);\n }, 0);\n var average = parseFloat((num / array.length).toFixed(2));\n return average;\n}", "function ratesAverage(arr) {\n if (arr.length === 0) {\n return 0;\n }\n let totalRates = arr.map(function(movie) {\n return movie.rate;\n });\n const sumRates = totalRates.reduce(function(acc, val) {\n return (acc += val);\n }, 0);\n let totalAverange = sumRates / totalRates.length;\n let totalAverangeRounded = Math.round(totalAverange * 100) / 100;\n return totalAverangeRounded;\n}", "function ratesAverage (arr){\n let sumRate = arr.reduce((acc, item)=> {\n return acc += parseInt(item.rate);\n }, 0)\n return sumRate / arr.length;\n}", "function ratesAverage(array) {\n var sumOfRatings=array.reduce(function(acc, item){\n var rateNumber=item.rate*1; \n return acc+rateNumber;\n },0)\n \n return parseFloat((sumOfRatings/array.length).toFixed(2))*1;\n }", "function ratesAverage (array) {\n\n var totalRates = array.reduce (function (sum, oneFilm) {\n \n return sum + Number(oneFilm.rate);\n }, 0);\n\n return Number( (totalRates / array.length).toFixed(2));\n}", "function ratesAverage(arr){\n if(arr.length === 0) return 0;\n const averageRate = arr.reduce((accum, currentValue) => {\n if(!currentValue.rate){\n return accum + 0;\n } else {\n return accum + currentValue.rate; \n }\n },0) / arr.length;\n return Number(averageRate.toFixed(2));\n}", "function ratesAverage (movies){\n let ratesArray = movies.map(movie => /*or Number*/parseFloat(movie.rate))\n let sum= ratesArray.reduce((x, y) => x+y, 0)\n let average= sum/ratesArray.length\n return Math.round(average*100)/100;\n // return Number(average.toFixed(2)); (DONT KNOW WHY ITS NOT WORKING)\n //different solution than Maxence\n}", "function ratesAverage(arr) {\n if (arr.length > 0) {\n let noZero = arr.filter((movies) => movies.rate);\n let ratesArr = noZero.reduce((ac, cu) => ac += cu.rate, 0) / arr.length;\n return +ratesArr.toFixed(2)\n }\n return 0\n}", "function ratesAverage(arr) {\n if (arr.length === 0) return 0;\n const total = arr.reduce(function (counter, currentValue, i) {\n if (typeof currentValue.rate === \"number\") {\n return (counter += currentValue.rate);\n }\n return counter;\n }, 0);\n var average = Math.round((total / arr.length) * 100) / 100;\n return average;\n}", "function ratesAverage(arr) {\n return arr.reduce((total, movie) => {\n if (!movie.rate) {return total + 0;} // Essa linha precisei da ajuda do vídeo de solução\n return parseFloat((total + movie.rate / arr.length).toFixed(2));\n }, 0);\n}", "function ratesAverage(arr) {\n\n return Number((arr.reduce((total, movie) => {\n return total + Number(movie.rate);\n }, 0)/arr.length).toFixed(2))\n\n}", "function ratesAverage(oldarr) {\r\n let mitja = oldarr.reduce((t, e, i, a) => { return t + e.rate / a.length }, 0);\r\n return (Math.round(mitja * 100) / 100);\r\n}", "function ratesAverage (arr){\n if(arr.length===0) {\n return 0;\n }\n let reducedArr = arr.reduce(function(acc, current){\n let updatedAcc = acc + current.rate;\n return updatedAcc;\n }, 0);\n\n let avgArr = reducedArr / arr.length;\n return (Math.round(avgArr * 100)) / 100;\n}", "function ratesAverage(tab){\n var rate = tab.reduce(function(sum,el){\n return sum + el.rate;\n }, 0);\n return rate/tab.length;\n}", "function ratesAverage(array) {\n var sum = array.reduce(function(acc, currentValue){\n return acc + currentValue.rate;\n },0);\n return sum/array.length;\n\n}", "function ratesAverage(array){\n var rateSum = array.reduce(function(sum, item){\n return sum+= item.rate;\n },0);\n return rateSum/array.length;\n}", "function ratesAverage(movies){\n if (movies.length === 0) {return 0}\n\n const ratesArray = movies.map (function (movies) {\n return movies.rate;\n });\n\n const totalRate = ratesArray.reduce(function (acc, value) {\n if (typeof(value) !== 'number') { \n return acc\n } \n else {\n return acc + value / (ratesArray.length)};\n }, 0);\n\n return Math.round(totalRate*10**2)/10**2;\n}", "function ratesAverage(movies) {\n let ratesArray = movies.map(function(movies) {\n return movies.rate;\n });\n let rates =\n ratesArray.reduce(function(sum, value) {\n return sum + value;\n }, 0) / ratesArray.length;\n console.log(rates);\n return Number(rates.toFixed(2));\n}", "function ratesAverage(myArray) {\n if ( myArray.length === 0) {\n return 0\n }\n const totalRates = myArray.reduce((acc,curr) => {\n return acc + (curr.rate || 0)\n },0)\n return Math.round((totalRates / myArray.length) * 100) / 100\n}", "function ratesAverage (movies) {\n if(movies.length == 0) return 0\n const reducer = (acc, currentValue) => currentValue.rate !== undefined ? acc + currentValue.rate : acc;\n\n sum = (movies.reduce(reducer, 0));\n avg = sum / movies.length;\n avgdecimals2 = avg.toFixed(2) \n\n console.log(Number(avgdecimals2));\n return Number(avgdecimals2)\n}", "function ratesAverage(array) {\n let averageRate = array.reduce(function(accumulator, value) {\n return accumulator + value.rate;\n });\n return averageRate / array.lenght;\n}", "function ratesAverage(movies)\n{var sumRates = movies.reduce(function(sum, movie){\n var temp = parseFloat(movie.rate);\n return sum + temp;\n}, 0);\nreturn Math.floor((sumRates/movies.length)*100)/100;\n}", "function ratesAverage(movies){\n const sumRate = movies.reduce((accumulator, movie) => {\n const rate = parseFloat(movie.rate)\n //console.log(`Accumulator: ${accumulator}, Current rate: ${rate}`)\n return (accumulator + rate)\n }, 0)\n return parseFloat((sumRate / movies.length).toFixed(2))\n}", "function ratesAverage (mov) {\n const sumRates = mov.reduce((acc, obj) => {\n if (! obj.rate) obj.rate = 0\n return acc + parseFloat(obj.rate) \n }, 0) \n return Number((sumRates/mov.length).toFixed(2))\n}", "function ratesAverage(movies) {\n var totalRates = movies.reduce (function(accumulator,movie) {\n return accumulator + Number(movie.rate);\n },0);\n var avg = (totalRates/movies.length).toFixed(2);\n // console.log(avg);\n return avg;\n}", "function ratesAverage(movies) {\n\n //return (movies.reduce((sum, movie) => sum + parseFloat(movie.rate), 0).toFixed(2) / movies.lenght)\n\n let x = movies.reduce((suma, movie) => {\n return suma + parseFloat(movie.rate)\n }, 0)\n return parseFloat((x / movies.length).toFixed(2));\n\n /*let y = 0;\n let x = movies.reduce((suma, movie) => {\n if(!movie.rate) {\n y++\n } else {\n return suma + parseFloat(movie.rate)\n }\n }, 0)\n return (x.toFixed(2) / movies.length - y);*/\n}", "function ratesAverage (movie){\n var rate=0.0;\n for (var i=0; i<movie.length;i++){\n rate+=parseFloat(movie[i].rate.toString());\n }\n return ((rate/movie.length).toFixed(2));\n }", "function ratesAverage (data) {\n if(data.length === 0){\n return 0\n }\n\n function isEmpty(obj) {\n return Object.keys(obj).length === 0;\n }\n\n const totalRates = data.reduce(function(accu, cur){\n if(isEmpty(cur)){\n return accu + 0\n }else if (cur.rate == ''){\n return accu + 0\n }else{\n return accu + cur.rate\n }\n }, 0)\n\n return Number((totalRates / data.length).toFixed(2))\n}", "function ratesAverage(arr){\n\nlet rating = 0; \n\narr.forEach(function(n){\nrating += n.rate; \n});\n\nreturn (rating / arr.length);\n}", "function ratesAverage(array) {\n if (array.length === 0) {\n return 0;\n }\n\n let rateArray = array.map(function(movie) {\n if (!movie.rate) {\n return 0;\n } else {\n return movie.rate;\n }\n });\n\n let sum = rateArray.reduce(function(accumulator, value) {\n return accumulator + value;\n }, 0);\n\n let finalRate = sum / array.length;\n\n return parseFloat(finalRate.toFixed(2));\n}", "function ratesAverage(someArray) {\n let sum = someArray.reduce((a, b) => {\n return a + Number(b.rate)\n }, 0);\n return sum / someArray.length;\n}", "function ratesAverage (movies){\n var rateArray= movies.map(function(film){\n return Number(film.rate); \n })\n .reduce(function(acc,value){\n return acc+value;\n },0)\n ;\n return Math.round((rateArray/movies.length) * 100) / 100;\n}", "function ratesAverage(movies){\n const totalItems = movies.length;\n console.log(totalItems);\n const totalRate = movies.map(mRate => mRate.rate).filter(item => typeof item === 'number').reduce((totalRate, movie) => { return totalRate + movie; }, 0);\n //const totalRate = movies.reduce((totalRate, movie) => (totalRate + movie.rate) + 0);\n\n if (totalItems == 0 ){\n return 0;\n }\n return parseFloat((totalRate / totalItems).toFixed(2));\n }", "function ratesAverage(inputArray)\n{ \n var summary ={\n count:0,\n sum:0\n };\n \n var sumCount = (accumulator,item) =>{\n accumulator.count ++;\n accumulator.sum += Number(item.rate);\n return accumulator;\n };\n\n var object= inputArray.reduce(sumCount,summary); \n var average= object.sum/object.count;\n return Number(average.toFixed(2));\n}", "function ratesAverage(movies){\n\n let avg = movies.reduce((prev, current) => {\n return prev + current.rate\n\n }, 0) / movies.length\n\n return parseFloat(avg.toFixed(2))\n}", "function ratesAverage(movies) {\n let totalRates = movies.reduce(function(acumulador, item){\n let mov =0;\n if(item.rate != \"\"){\n mov = parseFloat(item.rate)\n } \n \n return acumulador + mov\n }, 0)\n return parseFloat((totalRates / movies.length).toFixed(2))\n}", "function ratesAverage(arr) {\n var ratesArray = [];\n arr.forEach(function(movie) {\n ratesArray.push(Number(movie.rate));\n });\n\n var accumulatedMovies = ratesArray.reduce(function(accumulator, number) {\n return accumulator + number;\n });\n\n return accumulatedMovies / (ratesArray.length);\n}", "function ratesAverage(movies){\n if(movies.length == 0){\n return 0;\n } \n var avg = movies.reduce(function(a , b){\n \n if(typeof a && typeof b.rate === 'number'){\n return a += b.rate;\n }else{\n return a+= 0;\n }\n\n },0)\n var average = avg/movies.length; \n return Number(average.toFixed(2)) ;\n\n \n \n \n}", "function ratesAverage(array) {\n if (!array.length) {\n return 0;\n }\n let avg = array.reduce(function (acc, movie) {\n if (\"rate\" in movie) {\n return acc + movie.rate;\n } else {\n return acc;\n }\n }, 0);\n avg /= array.length;\n return Number(avg.toFixed(2));\n}", "function ratesAverage(array){\nconst rating = array.reduce(accumulator, currentValue){\n return currentValue.rate / array.length \n}\n}", "function ratesAverage(movies) {\n const totalRates = movies.reduce((acc, movie, i) => {\n acc += parseFloat(movie.rate);\n return acc;\n }, 0);\n return totalRates / movies.length;\n}", "function ratesAverage(movies) {\n\n const arrOfrates = movies.map(function (e) {\n return e.rate\n });\n const allRate = arrOfrates.reduce(function (accumulator, currentValue) {\n return accumulator + currentValue;\n }, 0);\n var avgRate = allRate / arrOfrates.length;\n return avgRate.toFixed(2)\n}", "function ratesAverage(arr){\n let sum = 0;\n if(arr.length === 0){\n return 0\n }\n \n for(i=0; i<arr.length; i++){\n if(arr[i].rate){ // check if the rate of the movie exists\n sum += arr[i].rate;\n }\n }\n\n let avg = sum/arr.length;\n return Number(avg.toFixed(2));\n}", "function ratesAverage(collection){\n var allRatings = collection.map(function(movie){\n var ratingsArr = parseFloat(movie.rate);\n return ratingsArr\n });\n var moviesSum = allRatings.reduce(function(rate,movie){\n return (rate + movie); \n },0);\n var moviesAvg = parseFloat(moviesSum) / allRatings.length;\n return parseFloat(moviesAvg.toFixed(2));\n}", "function ratesAverage(movieArray) {\n return Math.round(movieArray.reduce(function(sum,elem){\n return sum+Number(elem.rate);\n },0)/movieArray.length*100)/100;\n}", "function ratesAverage(movies) {\n if (movies.length === 0) return 0\n const rateMovie = movies.filter(elm => elm.rate).reduce((acc, elm) => acc + elm.rate, 0)\n let result = rateMovie / movies.length\n return +result.toFixed(2);\n}", "function ratesAverage(movies){\n let rates = movies.reduce( (acc, current) => {\n if (typeof current.rate == 'number'){\n return acc + current.rate;\n } else {\n return acc;\n }\n }, 0 );\n\n if (rates > 0){\n return parseFloat( (rates / movies.length).toFixed(2) );\n } else {\n return 0;\n }\n}", "function ratesAverage(movies){\n if(movies.length === 0){\n return 0\n }\n let filteredMovies = movies.filter(function(movie){\n return movie.rate\n })\n \n let sum = filteredMovies.reduce(function(acc, movie){\n return acc + movie.rate\n }, 0)\n \n return Number((sum / movies.length).toFixed(2))\n }", "function ratesAverage(movies){\n var ratesAverage = movies.reduce(function(sum,oneMovies){\n \n return sum + Number(oneMovies.rate);\n \n },0);\n return ratesAverage/movies.length\n \n }", "function ratesAverage(moviesArray) {\n var sumaRates = moviesArray.reduce(function (accumulator, movie) {\n return accumulator + Number(movie.rate);\n }, 0);\n return Number((sumaRates/ moviesArray.length).toFixed(2));\n }", "function ratesAverage(moviesArray){\n var sumTotal = moviesArray.reduce(function (acc,elem) {\n return acc + parseFloat(elem.rate);\n },0)\n return sumTotal / moviesArray.length;\n\n}", "function ratesAverage(arrayOfMovies) {\n if (!arrayOfMovies.length) return 0;\n let sumOfRates = arrayOfMovies.reduce((accumValue, currValue) => {\n if (currValue.rate > 0) \n return accumValue + currValue.rate; \n return accumValue;\n }, 0)\n return parseFloat((sumOfRates / arrayOfMovies.length).toFixed(2));\n }", "function ratesAverage(bestMoviesArr) {\n // console.log(movies);\n const totalRate = bestMoviesArr.reduce(\n (acc, cur) => acc + Number(cur.rate),\n 0\n );\n var result = totalRate / bestMoviesArr.length;\n return Number(result.toFixed(2));\n}", "function ratesAverage (e){\n \n var mov = movies.map(e => {\n e.rate= Number(e.rate);\n return e\n}) ;\n\nvar avg = mov.reduce((sum, ele) => {\n return sum + ele.rate/ mov.length;\n},0)\n\navg = Math.round(avg * 100) /100\n \nreturn avg;\n \n}", "function ratesAverage (movies) {\n var total = movies.reduce(function (acc, item) {\n return acc + Number(item.rate);\n }, 0);\n var average = total / movies.length ;\n return Number(average.toFixed(2));\n}", "function ratesAverage(movies) {\n var average = movies.reduce(function(total, movie) {\n return total + parseFloat(movie.rate||0 ) / movies.length;\n }, 0);\n return parseFloat(average.toFixed(2));\n}", "function ratesAverage(movies){\n if (movies.length==0){\n return undefined;\n }\n return Math.round((movies.reduce(function(acc,movie){\n return acc + parseFloat(movie.rate==''?0:movie.rate);\n },0)/movies.length)*100)/100;\n \n }", "function ratesAverage(peliculas) {\n if (!peliculas.length) return 0\n let sum = 0;\n peliculas.forEach(function(pelicula) {\n if (pelicula.rate)\n sum += pelicula.rate\n })\n return parseFloat((sum / peliculas.length).toFixed(2))\n}", "function ratesAverage(movies) {\n if (movies.length === 0) {\n return 0;\n }\n let sum = movies.reduce((ac, movie) => {\n if (typeof(movie.rate) != \"number\") {\n movie.rate = 0\n } return movie.rate + ac\n }, 0)\n return parseFloat((sum/movies.length).toFixed(2));\n}", "function ratesAverage(array) {\n // RETURN AVERAGE EVEN RATE IS EMPTY\n const average = array.reduce((sum, array) => {\n return sum += array.rate;\n }, 0);\n if (!average) {\n return 0;\n } else {\n return Math.round((average / array.length) * 100) / 100;\n }\n}", "function ratesAverage(moviesArray) {\n if (moviesArray.length === 0) {\n return 0;\n }\n\n const rates = moviesArray.map(function (film) {\n return film.rate;\n });\n\n console.log(rates);\n\n let totalRate = rates.reduce(function (acc, el) {\n if (el) {\n return acc + el;\n } else {\n return acc;\n }\n }, 0);\n\n return Math.round((totalRate / moviesArray.length) * 100) / 100;\n}", "function ratesAverage(arr){\n if(arr.length===0){\n return 0;\n }else{\n let filmsWithRate=arr.filter(function(movie){\n return movie.rate>=0;\n })\n let totalRate=filmsWithRate.reduce(function(rate, curr){\n return rate+curr.rate\n },0);\n let avgRate=Math.round(totalRate/arr.length*100)/100;\n return avgRate}\n }", "function ratesAverage(movies) {\n if(movies.length === 0){\n return undefined;\n }\n var total = movies.reduce(function(acc,current){\n acc += current.rate;\n return acc;\n },0);\n\n total = total / movies.length;\n return parseFloat(total.toFixed(2));\n}", "function ratesAverage(arrayMovies) {\n if (arrayMovies.length > 0) {\n return Number((arrayMovies.reduce(function (accumulated, element) {\n if (!element.rate>0) {element.rate=0.00;}\n return accumulated += parseFloat(element.rate);\n }, 0) / arrayMovies.length).toFixed(2));\n } else return undefined;\n}", "function ratesAverage(array) {\n\n const movieAvg = array.reduce((total, movie) => {\n return movie.rate ? total + movie.rate : total;\n }, 0)\n\n let avgCalc = !array.length ? 0 : movieAvg / array.length\n\n return Math.round((avgCalc * 100)) / 100;\n}", "function ratesAverage (moviesArray) {\n if(moviesArray.length === 0) {\n return 0;\n }\n const averageRate = moviesArray.reduce(function(acc, element) {\n if (!element.rate) {\n return acc + 0;\n }\n return acc + element.rate;\n }, 0) / moviesArray.length;\n \n \n return +averageRate.toFixed(2);\n\n}", "function ratesAverage (array) {\n const sumRatingCalc = array.reduce((total, movie) => {\n return (total + (movie.rate || 0)) // Does this make sense??? [6, , ] should average out to 6 not 2\n }, 0)\n const averageCalc = sumRatingCalc / array.length || 0\n return Math.round(averageCalc * 100) / 100\n}", "function ratesAverage(moviesArray){\n if (moviesArray.length === 0){\n return 0;\n }\n let emptyRates = movies.filter((x) => !x.rate).map((x) => (x.rate = 0));\n\n let mAgv = Math.round((movies.reduce(acc, x) => acc + x.rate, 0) * 100) / moviesArray.length) / 100;\n return mAgv;\n\n}", "function ratesAverage(moviesArray) {\n\n let averageRate = moviesArray.reduce((accumulator, eachMovie)=>{\n return accumulator + eachMovie.rate; \n },0) / moviesArray.length;\n\n return Number(averageRate.toFixed(2))\n}", "function ratesAverage(movies){\n var total = movies.reduce(function(acc, film){\n parseFloat(movies.rate) //pasamos de string a number, para poder sumarlos con reduce\n return acc + film.rate / movies.length\n },0);\n var totalDecimal = total.toFixed(2) //redondeamos a 2 decimales\n var totalNumber = parseFloat(totalDecimal)\n return totalNumber;\n}", "function ratesAverage(movies) {\n\nlet sumOfRates = movies.map(movie => movie.rate).reduce((acc, cv) => acc + cv)\nreturn sumOfRates / movie.length\n}", "function ratesAverage(movies) {\n const moviesAverageRate = [...movies.filter(eachMovie => eachMovie.rate > 0)]\n\n if (moviesAverageRate.length) {\n\n return (parseFloat((moviesAverageRate.reduce((acc, eachMovie) => acc + eachMovie.rate, 0) / movies.length).toFixed(2)));\n\n } else {\n\n return 0\n }\n}", "function ratesAverage(movies) {\n return +(sum() / +(movies.length).toFixed(2));\n}", "function ratesAverage(movies) {\n if (movies.length === 0) {return 0};\n let totalRates = movies.reduce(function(sum, movie) {\n return sum + movie.rate;\n }, 0)\n let averageRate = totalRates / movies.length\n return Number(averageRate.toFixed(2))\n}" ]
[ "0.81201476", "0.8045915", "0.8008566", "0.79965955", "0.7941593", "0.7932597", "0.7908035", "0.79006124", "0.7883331", "0.78420365", "0.7804975", "0.7800371", "0.7782459", "0.7768673", "0.77451664", "0.7740817", "0.77304035", "0.7724927", "0.7723992", "0.77208954", "0.7695896", "0.7684506", "0.7681695", "0.7671956", "0.76688194", "0.7644262", "0.76421916", "0.76380366", "0.7626947", "0.7602264", "0.7600664", "0.75941306", "0.75861144", "0.75797844", "0.75693256", "0.7556698", "0.7550687", "0.75398123", "0.7535733", "0.7517571", "0.7516812", "0.751335", "0.75111824", "0.74886006", "0.74811125", "0.74715036", "0.7449801", "0.74380213", "0.74371475", "0.74228007", "0.7415424", "0.7412579", "0.7399203", "0.7382685", "0.73790216", "0.7342943", "0.7317681", "0.73047096", "0.7289143", "0.7281601", "0.72783864", "0.7267617", "0.72638017", "0.72558594", "0.7252093", "0.72382814", "0.7224107", "0.72174495", "0.7206878", "0.71826345", "0.7171926", "0.71623576", "0.7157851", "0.71490914", "0.7146715", "0.71269125", "0.7124756", "0.712041", "0.71130383", "0.710601", "0.71057814", "0.7093538", "0.7080594", "0.7066723", "0.7052855", "0.7050785", "0.704333", "0.70426965", "0.70333904", "0.70177364", "0.70168614", "0.70144516", "0.70122164", "0.700895", "0.70066655", "0.700567", "0.7004999", "0.6992814", "0.6986353", "0.6981957" ]
0.78522944
9
Iteration 5: Drama movies Get the average of Drama Movies
function dramaMoviesRate(dMovies) { let dramaMov = dMovies.filter(function (dMovie) { return dMovie.genre.includes("Drama") }) if (dramaMov.length == 0) { return 0; } else { let totalDramaRates = dramaMov.reduce(function (acc, dramaMov) { return acc + dramaMov.rate; }, 0); return number(totalDramaRates / dramaMov.length.toFixed(2)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculateMovieAverage() {\n\tfor (let i = 0; i < movies.length; i++) {\n\t\tlet sumOfRatings = movies[i].ratings.reduce((a, b) => a + b, 0);\n\t\tmovies[i].average = sumOfRatings / movies[i].ratings.length;\n\t}\n}", "function dramaMoviesRate(movies) {\n let drama = movies.filter(function(elem){\n return elem.genre.includes('drama')\n })\n\n let avg = drama.reduce(function(sum, elem){\n return sum + elem.rate;\n }, 0) \n \n / drama.length;\n}", "function moviesAverageOfDirector(array, director) {\n \n let movies = getMoviesFromDirector(array, director);\n\n console.log(movies);\n \n let total = 0;\n\n movies.map(({score}) => total+=score)\n \n const resultado = total / movies.length;\n\n return resultado;\n \n}", "function dramaMoviesScore(movies) {\n let dramaMoviesArr = movies.filter(function(eachMovie){\n return eachMovie.genre.includes('Drama')\n })\n return scoresAverage(dramaMoviesArr)\n}", "function dramaMoviesRate(movies) {\n\n var arrayDramaMovies = movies.filter (function(genredrama){\n return genredrama.genre.includes(\"drama\")\n }); \n\n var totalDramaRates = arrayDramaMovies.reduce (function(accumulator,dramaMovies) {\n return accumulator + Number(dramaMovies.rate);\n },0);\n console.log (\"The average of dramam movies is \" + dramaMoviesRate(movies));\n return (totalDramaRates/arrayDraMaMovies.length)\n}", "function dramaMoviesScore(movies) {\n const dramaMovies = movies.filter(function(movie){\n if (movie.genre.includes('Drama')) return movie\n })\n\n if (movies.length >= 1) {\n return scoresAverage(dramaMovies)\n }\n}", "function dramaMoviesRate (movies){\n var dramaM = movies.filter(function(h){\n return h.genre.includes(\"Drama\")\n })\n \n \n var ratAVG = dramaM.map(function(m){\n var ratNum = parseFloat(m.rate);\n m.rate = ratNum;\n return m\n });\n \n var avg = dramaM.reduce(function(acc,l){\n return acc + l.rate/dramaM.length;\n },0);\n console.log(avg);\n }", "function dramaMoviesScore(moviesArray) {\n const dramaMovies = moviesArray.filter(function(movie){\n if (movie.genre.indexOf('Drama') !== -1) {\n return movie;\n } \n }); \n if (dramaMovies.length === 0) {\n return 0;\n };\n const averageDramaMovies = dramaMovies.reduce(function (sum, movie){\n return sum + movie.score; \n }, 0); return Math.round((averageDramaMovies / dramaMovies.length) * 100) /100\n}", "function dramaMoviesScore(movielist) {\n let drama = movielist.filter(function(movie){\n return (movie.genre.includes('Drama'));\n })\n\n let total = 0\n let result = drama.map(x => total += x.score);\n return total/drama.length\n}", "function dramaMoviesRate (e){\n \n var mov = movies.filter(e => {\n return e.genre.includes('Drama')\n })\n \n var avg = mov.reduce((sum, ele) => {\n return sum + ele.rate/ mov.length;\n },0)\n \n avg = Math.round(avg * 100) /100\n if(avg === 0){\n return undefined\n}\n return avg;\n \n }", "function calculateAverageDramaRate(movies) {\n const drama = movies.filter((value) => {\n return value.genre.includes(\"Drama\")\n }); if (drama.length === 0) {\n return 0\n } else {\n return calculateAverageMovieRate(drama)\n }\n\n\n}", "function dramaMoviesScore(someMovies) {\n const dramaMovies = someMovies.filter((someMovies) =>\n someMovies.genre.includes(\"Drama\"));\n const avgRate = scoresAverage(dramaMovies);\n return avgRate;\n}", "function dramaMoviesRate (movies) {\n if (movies.length === 0) return 0 \n const result = movies.filter (movie => movie.genre.includes('Drama'))\n return ratesAverage(result)\n}", "function dramaMoviesRate(movies){\n var dramaFilms = []\nfor (var i = 0; i < movies.length; i++){\n for (var j = 0; j < movies[i].genre.length; j++){\n if (movies[i].genre[j] === 'Drama'){\n dramaFilms.push(movies[i])\n }\n }\n}\nif (dramaFilms == 0){} else {return ratesAverage(dramaFilms);}\n}", "function dramaMoviesRate(movies) {\n var drama = movies.filter((movie) => movie.genre.includes(\"Drama\"));\n return ratesAverage(drama)\n\n}", "function getDramas(){\n const dramaMovies = movies.filter(function(movies){\n return movies.genre == \"Drama\"\n })\n dramaRatings = []\n\n for (let i = 0; i<dramaMovies.length; i+=1){\n dramaRatings.push(dramaMovies[i].rate)\n }\n avgDramaRating(dramaRatings)\n }", "function dramaMoviesRate(movies) {\n const dramaMovies = movies.filter(function(item){\n const isDrama = item.genre.indexOf('Drama') >= 0;\n return isDrama;\n })\n return ratesAverage (dramaMovies);\n \n}", "function dramaMoviesRate (movies) {\n var dramaMovie = movies.filter(function(film){\n return film.genre.indexOf('Drama') !== -1;\n });\n if (dramaMovie .length<1){\n return undefined;\n }\n return ratesAverage(dramaMovie);\n}", "function dramaMoviesRate(movies){\n if(movies.length == 0){\n return 0;\n } \n var avgDrama = movies.filter(function(movie){\n return movie.genre.includes(\"Drama\");\n\n })\n return ratesAverage(avgDrama) ;\n\n}", "function dramaMoviesRate(movies){\n var moviesDrama = movies.filter(function(a){\nif (a.genre.includes(\"Drama\"))\n{\n return true;\n}\n});\n if (!moviesDrama.length)\n {\n return 0;\n }\n\n // llamo al metodo de la iteracion 4 para no generar mas codigo pero ahora le paso el includes de la variable moviesDrama retornando true. \n var avarage = ratesAverage(moviesDrama);\n return avarage;\n}", "function dramaMoviesRate(movies) {\n\n const moviesAverageRateDrama = [...movies.filter(eachMovie => eachMovie.genre.includes('Drama'))]\n\n return ratesAverage(moviesAverageRateDrama)\n\n}", "function dramaMoviesRate(movies){\n var onlyDrama = movies.filter(function(movie){\n return movie.genre.includes(\"Drama\");\n });\n var totalDrama = onlyDrama.reduce(function(sum,rating){\n return sum + rating.rate;\n }, 0);\nreturn totalDrama / onlyDrama.length;\n}", "function dramaMoviesRate(movies){\n\n return ratesAverage(movies.filter(function(movie){\n return movie.genre.indexOf(\"Drama\")!=-1;\n }));\n}", "function dramaMoviesRate(movies) {\n let dramaMovies = movies.filter(function (movie) {\n return movie.genre.includes(\"Drama\");})\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesScore(array) {\n\n \n let dramaArray = array.reduce( (sum, elem) => {\n if (elem.genre.includes('Drama')) {\n return sum + Number( (elem.genre.includes('Drama')))\n }\n }, 0 )\n\n \nlet average = Number( (elem.genre.includes('Drama')))\nreturn average;\n}", "function dramaMoviesRate(movies) {\n let dramaMovies = movies\n .filter(movie => movie.genre.includes('Drama'))\n return ratesAverage(dramaMovies)\n}", "function dramaMoviesScore(movies) {\n dramaMovies = movies.filter(i => i.genre.includes('Drama'))\n return (dramaMovies.reduce((acc, item)=> acc + (item.score || 0), 0) / dramaMovies.length).toFixed(2) * 1 || 0\n}", "function dramaMoviesRate (movArr) {\n const dramaMovies = movArr.filter(function findDrama(movie) {\n return movie.genre.find(function (genre) {\n return genre === 'Drama'})\n}) \n return ratesAverage (dramaMovies)\n}", "function dramaMoviesRate(movies) {\n let newArr = [...movies];\n let dramaArray = newArr.filter(element => element.genre.includes(\"Drama\"));\n return ratesAverage(dramaArray);\n}", "function dramaMoviesRate(movies) {\n var drama = movies.filter(movie => movie.genre.includes(\"Drama\"));\n if (drama.length === 0) {\n return 0;\n }\n return ratesAverage(drama);\n }", "function dramaMoviesRate(movies){\n let dramaMovies = movies.filter(movie => movie.genre.some(genre => genre === 'Drama'));\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesRate(array)\n{\n const stevenDrama = array.filter(function(movie){\n return movie.genre.includes(\"Drama\")\n \n })\n const totalRates = stevenDrama.reduce(function (acc,val){\n if (!val.rate){\n return acc\n }\n return acc + val.rate\n \n },0) \n \n let average = (totalRates/array.length)\n return Number(average.toFixed(2))\n}", "function dramaMoviesRate(array) {\n let dramamov = array.filter(function (movies) {\n return movies.genre.includes('Drama');\n });\n \n let dramaSum = dramamov.reduce((acc, curr) => {\n return acc + curr.rate;\n }, 0);\n\n let avgDrama = Math.round(dramaSum / dramamov.length);\n return avgDrama;\n}", "function dramaMoviesRate(array) { \n\n let dramaMovies = array.filter(function (movie) { \n return movie.genre.indexOf('Drama') >= 0;\n })\n \n let result = dramaMovies.map(function (movie) { \n return movie.rate;\n }).reduce(function (acc, rate) { \n return acc + Number(rate);\n }, 0)\n \n let average = result / dramaMovies.length \n if (dramaMovies.length === 0) {\n return 0;\n } else {\n return Number(average.toFixed(2));\n }\n }", "function calculateAverageDramaRate (drama){\n let dramaMovies = drama.filter((movie) => {\n if (movie.genre.indexOf('Drama') > -1){\n return true\n } \n });\n\n if (dramaMovies.length === 0) {\n return 0\n } else {\n return calculateAverageMovieRate(dramaMovies);\n }\n}", "function dramaMoviesScore(movies) {\n let dramaMovies = movies.filter(movie => movie.genre.includes('Drama'))\n let scores = dramaMovies.map(movie => movie.score)\n let totalScore = scores.reduce(function (result, score){\n return result + score\n })\n return Number((totalScore / scores.length).toFixed(2))\n }", "function dramaMoviesRate(array) {\n let dramaWord = 0;\n let sum = array.reduce((accumulator, value) => {\n if (value.genre.includes(\"Drama\")) {\n dramaWord += 1;\n return accumulator + value.rate;\n } else {\n return accumulator;\n }\n }, 0);\n if (!dramaWord) {\n return 0;\n }\n\n let average = parseFloat((sum / dramaWord).toFixed(2));\n return average;\n}", "function dramaMoviesRate(movies){\n \n const totalItems = movies.length;\n const totalDramaRate = movies.reduce((totalDramaRate, movieDrama) => { return totalDramaRate + movieDrama.rate; } ,0);\n\n return avgDramaRate = (parseFloat((totalDramaRate / totalItems).toFixed(2)));\n}", "function dramaMoviesRate (moviesArray){\n var dramas = moviesArray.filter(function(elem){\n return elem.genre.indexOf(\"Drama\") != -1;\n });\n return ratesAverage(dramas);\n}", "function dramaMoviesRate(arr) {\n let dramaMovies = [];\n for (let movie of arr) {\n if (movie.genre.includes('Drama')) {\n dramaMovies.push(movie);\n }\n }\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesRate(movies){\n \n let dramaMovies = movies.filter(function(movie){\n return movie.genre == \"Drama\";});\n\n let dramaMoviesLength = dramaMovies.length;\n\n if(dramaMoviesLength == 0)\nreturn 0;\n \n else {\n let ratesDramaSum = dramaMovies.reduce(function (acc, value){\n return acc + value.rate;\n },0);\n\n let avgDramaRate = (ratesDramaSum/dramaMovies.length).toFixed(2);\n let avgDramaRateNumber = Number (avgDramaRate);\n return avgDramaRateNumber;\n }\n}", "function dramaMoviesRate(array){\n\n const somaTotal = array.reduce(function (sum, item) {\n if (item.genre.indexOf('Drama')>=0){\n\n if (typeof item.rate === 'number')\n {\n return sum + item.rate;\n }else {\n return sum + 0;\n }\n\n }else{\n return sum + 0;\n }\n },0);\n\n const contDrama = array.reduce(function (cont, item) {\n if (item.genre.indexOf('Drama')>=0){\n return cont + 1;\n }else{\n return cont + 0;\n }\n },0); \n \n let avgTotal = 0;\n \n if (contDrama === 0){\n return 0\n }\n\n avgTotal = somaTotal / contDrama;\n \n return parseFloat(avgTotal.toFixed(2));\n}", "function dramaMoviesRate(movies) {\n const dramaMovies = movies.filter(function (e, i) {\n if (e.genre.includes('Drama')) {\n return e;\n }\n });\n const arrOfrates = dramaMovies.map(function (e) {\n return e.rate\n });\n const allRate = arrOfrates.reduce(function (accumulator, currentValue) {\n return accumulator + currentValue;\n }, 0);\n var avgRate = allRate / arrOfrates.length;\n return avgRate.toFixed(2)\n}", "function dramaMoviesRate(movies){\n \n var dramas = movies.filter(function(item) {\n if (item.genre.indexOf('Drama') !== -1){\n return true;\n };\n });\n if (dramas.length === 0) {\n return;\n }\n return ratesAverage(dramas);\n}", "function dramaMoviesRate(array) {\n const dramaMovies = array.filter(element => element.genre.includes(\"Drama\"));\n if (dramaMovies.length === 0) {\n return 0;\n }\n const mapDramaMovies = dramaMovies.map(rates => rates.rate);\n mapDramaMovies.forEach(function (element, index) {\n if (element === \"\") {\n mapDramaMovies[index] = \"0\";\n }\n })\n const sum = (sumarizer, currentElement) => parseFloat(sumarizer) + parseFloat(currentElement);\n let avg = parseFloat(((mapDramaMovies.reduce(sum)) / mapDramaMovies.length).toFixed(2));\n return avg;\n}", "function dramaMoviesRate(moviePar){\n let dramaMovies = moviePar.filter(movie=> movie.genre.includes ('Drama'))\n return ratesAverage (dramaMovies)\n}", "function dramaMoviesRate(movies) {\n const drama = movies.filter(elm => elm.genre.includes(\"Drama\"))\n if(drama.length === 0) {\n return 0\n } else {\n const avgDramaRates = drama.reduce((acc, elm) => {\n if(elm.rate) {\n return acc + elm.rate\n } else {\n return acc\n }\n }, 0) / drama.length\n let avgDramaFixed = Math.round(avgDramaRates * 100) / 100\n return avgDramaFixed\n }\n}", "function dramaMoviesRate(arr) {\n let drama = arr.filter(function(movie) {\n return movie.genre.includes(\"Drama\")\n });\n let maped = drama.map(function(e) {\n return e.rate\n })\n let averageDrama = maped.reduce(function(acc, val) {\n return acc + (val|| 0) / maped.length\n }, 0)\nreturn Math.round(averageDrama * 100) / 100\n}", "function dramaMoviesScore(someArray) {\n\n \n let dramaMovies = someArray.filter(eachMovie => {\n return eachMovie.genre.includes('Drama');\n });\n\n let sumDramaScores = dramaMovies.reduce((acc, eachScore) => {\n return acc + eachScore.score;\n },0) ;\n\n let avgDramaScore = sumDramaScores / dramaMovies.length;\n\n let roundedDramaScore = Math.round((avgDramaScore + Number.EPSILON) * 100) / 100;\n\n return roundedDramaScore;\n\n}", "function ratesAverage(movies) {\n\nlet sumOfRates = movies.map(movie => movie.rate).reduce((acc, cv) => acc + cv)\nreturn sumOfRates / movie.length\n}", "function dramaMoviesRate(movies){\n let moviDrama = movies.filter(movie => movie.genre.includes(`Drama`))\n\n if (moviDrama.length == 0){\n return undefined\n }\n return ratesAverage(moviDrama)\n\n}", "function dramaMoviesRate(mov) {\n let dramaMovies = mov.filter(function(item, index) {\n if (item.genre.includes(\"Drama\")) {\n return true\n } else {\n return false\n }\n }) \n if (dramaMovies.length === 0) {\n return 0\n }\n return ratesAverage(dramaMovies)\n}", "function dramaMoviesRate(arr){\n\n let dramaMovies=arr.filter(function(movie){\n return movie.genre.includes(\"Drama\");\n });\n if(dramaMovies.length===0){return 0;}\n else{\n let totalRateDM=dramaMovies.reduce(function(rate, curr){\n return rate+curr.rate\n },0);\n \n let avgRateDM=Math.round(totalRateDM/dramaMovies.length*100)/100;\n \n return avgRateDM; }\n \n }", "function dramaMoviesRate(arr){\n let dramaMovies = [];\n arr.map(movie => {\n if(movie.genre.includes(\"Drama\")){\n dramaMovies.push(movie);\n }\n return dramaMovies;\n });\n if(dramaMovies.length === 0) return 0;\n let averageRateDrama = dramaMovies.reduce((accum, currentValue) => {\n return accum + currentValue.rate;\n },0) / dramaMovies.length;\n return Number(averageRateDrama.toFixed(2));\n}", "function dramaMoviesRate(movies) {\n console.log(movies);\n let dramaMovies = movies.filter(function(movie) {\n // console.log(movie.genre);\n // console.log(movie.genre.includes(\"Drama\"))\n return movie.genre.includes(\"Drama\");\n });\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesRate (movies) {\n const dramaMovies = movies.filter (function(movie) { \n return movie.genre.indexOf('Drama') != -1;\n });\n if (dramaMovies.length != 0) {\n return ratesAverage (dramaMovies) // en vez de hacer de nuevo una funcion para calcular la media, usamos la anterior funcion pero ahora que ataque a dramaMovies\n }\n else {\n return undefined;\n }\n\n}", "function dramaMoviesRate(movies) {\n /*console.log(ratesAverage(movies.filter(movie => movie.genre.indexOf('Drama') !== -1)))*/\n //return ratesAverage(movies.filter(movie => movie.genre.indexOf('Drama') !== -1))\n\n const drama = movies.filter(movie => movie.genre.indexOf('Drama') !== -1)\n if(drama.length === 0) return undefined\n return parseFloat(ratesAverage(drama));\n\n}", "function dramaMoviesScore(arr) {\n const dramaMovies = arr.filter((movie) => {\n return movie.genre.includes('Drama');\n });\n if (!dramaMovies.length) {\n return 0;\n }\n const averageDramaScore = dramaMovies.reduce((acc, movie) => {\n return acc + movie.score;\n }, 0);\n return Number.parseFloat((averageDramaScore / dramaMovies.length).toFixed(2));\n}", "function dramaMoviesScore(arr){\n let dramas = arr.filter((elem) => {\n if(elem.genre.includes(\"Drama\")){\n return elem\n }\n })\n \n let total = dramas.reduce((sum,elem) => {\n return sum + elem.score\n },0)\n return +((total / dramas.length).toFixed(2))\n}", "function dramaMoviesRate(array) {\n \n const moviesDrama = array.map(\n movie => {\n if(movie.genre.includes('Drama')) return movie\n }).filter(movie => movie !== undefined)\n \n return ratesAverage(moviesDrama)\n}", "function dramaMoviesRate (array) {\n const dramaMovies = array.filter(movie => movie.genre.includes('Drama'))\n return ratesAverage(dramaMovies)\n}", "function calculateAverageMovieRate(movies) {\n const moviesRates = movies.reduce((accumulator, value) => {\n return accumulator + value.rate\n\n }, 0);\n\n return (moviesRates / movies.length)\n}", "function dramaMoviesRate(movies){\n let totalDramaMovies = 0\n let rate = 0;\n const sumRate = movies.reduce((accumulator, movie) => { \n (movie.rate !== '') ? rate = parseFloat(movie.rate) : rate = 0\n \n if((movie.genre.length === 1) && (movie.genre.indexOf('Drama') !== -1)){\n totalDramaMovies ++\n //console.log(`Title: ${movie.title}, Accumulator: ${accumulator}, Current rate: ${rate}`)\n return (accumulator + rate)\n } else {\n return accumulator\n }\n }, 0)\n return (totalDramaMovies !== 0) ? parseFloat((sumRate / totalDramaMovies).toFixed(2)) : undefined\n}", "function dramaMoviesRate(arrayMovies) {\n var moviesDrama = [];\n\n moviesDrama = arrayMovies.filter(function (element) {\n return element.genre[0]==='Drama' ;//&& element.rate>0;\n });\n return ratesAverage(moviesDrama);\n}", "function dramaMoviesRate(moviesArray){\n let dramaMovies = moviesArray.filter((eachMovie)=>{\n return eachMovie.genre.includes(\"Drama\");\n });\n if(dramaMovies.length === 0){return undefined;}\n return ratesAverage(dramaMovies);\n}", "function ratesAverage(movies){\n var totalRating = movies.reduce(function(sum, rating){\n return sum + rating.rate ;\n }, 0);\n return totalRating / movies.length ;\n}", "function dramaMoviesRate(movies)\n{\n var dramaMovies = movies.filter(function(movie){\n var genreMovie = movie.genre.filter(function(genre){\n return genre==='Drama';\n });\n return genreMovie.length!=0;\n });\n var result = dramaMovies.length===0 ? undefined : parseFloat(ratesAverage(dramaMovies).toFixed(2));\n console.log(result);\n return result;\n}", "function dramaMoviesRate(movies) {\n var dramaMovies = movies.filter(function(movie) {\n if(movie.genre.indexOf('Drama') !== -1) {\n return movie;\n }\n });\n\n var averageDramaRating = ratesAverage(dramaMovies);\n if(isNaN(averageDramaRating)) {\n return undefined;\n }\n return averageDramaRating;\n}", "function dramaMoviesRate(array){\n if(array.length===0 && array.genre.length >1 && array.movie.genre !=\"Drama\")\n {return 0};\n \n let totRate=array.reduce((acc,elem)=>{\n return acc+elem.rate\n },0)\n\n let avgRate=totRate/array.length\n return Number(avgRate.toFixed(2))\n}", "function dramaMoviesRate(movie) {\n const dramaMovies = movie.filter((x) => {\n return x.genre.includes('Drama');\n })\n // console.log(ratesAverage(dramaMovies));\n let average = ratesAverage(dramaMovies);\n return isNaN(average) ? 0 : average;\n\n // or \n // let average = Number(ratesAverage(dramaMovies).toFixed(2));\n // return average;\n}", "function dramaMoviesRate(movies) {\n var dramaMovies = filterDrama(movies);\n\n if (dramaMovies.length == 0) return;\n\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesRate(arr) {\n let movieDramas = arr.filter(function(movie) {\n return movie.genre.includes(\"Drama\");\n });\n return ratesAverage(movieDramas);\n}", "function dramaMoviesRate(moviesArray) {\n\n const dramaMovies = []\n let totalRate = 0;\n\n moviesArray.filter(function (drama) {\n drama.genre.map(function (d) {\n d === 'Drama' ? dramaMovies.push(drama.rate) : null\n })\n })\n\n dramaMovies.forEach(e => totalRate += e)\n\n return (totalRate / dramaMovies.length) ? Math.round((totalRate / dramaMovies.length) * 100) / 100 : 0\n\n}", "function dramaMoviesRate(array) {\n const dramaMovies = array.filter(y =>\n y.genre.includes(\"Drama\")\n )\n if (dramaMovies.length === 0) return 0\n const averageDrama = dramaMovies.reduce(function (sum, movie) {\n return sum + movie.rate\n }, 0)\n return roundToTwo(averageDrama / dramaMovies.length)\n}", "function dramaMoviesRate(array) {\n let dramaRates = array.filter(array => array.genre.includes(\"Drama\"));\n\n let dramaAverage = ratesAverage(dramaRates);\n\n return dramaAverage;\n}", "function dramaMoviesRate (movieArray) {\n var dramaMovies=movieArray.filter(function(elem){\n //if (elem.genre.indexOf(\"Drama\")>=0) console.log(elem.genre);\n return elem.genre.indexOf(\"Drama\")>=0;\n });\n console.log(dramaMovies.length);\n if (dramaMovies.length===0) return undefined;\n return ratesAverage(dramaMovies);\n}", "function dramaMoviesRate(movies) {\n var dramaMoviesRate = [];\n var avgDramaRate = 0;\n\n var dramaMovies = movies.filter(function(movie) {\n return movie.genre.includes(\"Drama\");\n });\n dramaMovies.map(function(element) {\n dramaMoviesRate.push(Number.parseFloat(element.rate).toFixed(2) * 1);\n });\n if (dramaMovies.length === 0) {\n return undefined;\n } else if (dramaMovies.length === 1) {\n var result = Number.parseFloat(dramaMovies[0].rate).toFixed(2); //al fer el fixed to torna a string\n return Number.parseFloat(result);\n } else if (dramaMovies.length > 1) {\n avgDramaRate = dramaMoviesRate.reduce(function(acc, val) {\n return acc + val;\n });\n }\n var finalRate = (avgDramaRate / dramaMovies.length).toFixed(2);\n return Number.parseFloat(finalRate);\n}", "function dramaMoviesRate(array) {\n const drama = array.filter(elm => elm.genre.includes(\"Drama\"))\n sumRating = drama.reduce((acc, elm) => {\n return acc + elm.rate\n }, 0)\n\n div = 0\n drama.forEach((elm, index) => {\n div++\n if (elm.rate == undefined) div--\n })\n let result = sumRating / div\n if (drama.length == 0) return 0\n return +result.toFixed(2)\n\n}", "function dramaMoviesRate(movies) {\n var drama = movies.filter(function(oneDrama) {\n return oneDrama.genre.indexOf(\"Drama\") !== -1;\n });\n if (isNaN(ratesAverage(drama))) {\n return undefined;\n } else {\n return ratesAverage(drama);\n }\n}", "function dramaMoviesRate(moviesArray) {\n let result = ratesAverage(moviesArray.filter(movie => movie.genre.includes('Drama')))\n\n console.log(result)\n return (result)\n}", "function dramaMoviesRate(moviesArray) {\n var dramaMovie = moviesArray.filter(function (pelicula) {\n return pelicula.genre.indexOf('Drama') !== -1;\n });\n if (dramaMovie.length===0) {\n return ;\n }\n return (ratesAverage(dramaMovie));\n }", "function ratesAverage(movies) {\n\n var promedio = movies.reduce(function(valor, movie) {\n return valor + parseFloat(movie.rate);\n }, 0);\n\n let sumaPromedio = (promedio / movies.length);\n return sumaPromedio\n}", "function dramaMoviesRate(arrayOfMovies){\n let filteredMovies = arrayOfMovies.filter(function(movie) {\n if (movie.genre.includes('Drama')) {\n return movie\n }\n }); \n return ratesAverage(filteredMovies);\n}", "function dramaMoviesRate (arrayOfMovies) {\n let dramaMovies = arrayOfMovies.filter(movie => (movie.genre.includes(\"Drama\")));\n if (!dramaMovies.length) return 0;\n return ratesAverage(dramaMovies);\n }", "function dramaMoviesRate(array) {\n let dramaMovies = array.filter(function(movie) {\n if (movie.genre.indexOf('Drama') !== -1) {\n return true;\n }\n return false\n });\n \n if (dramaMovies.length == 0 ){\n return 0;\n }\n \n return (ratesAverage(dramaMovies));\n \n }", "function dramaMoviesRate(array){\n var dramaArray = array.filter(function(movie){\n return (movie.genre.indexOf(\"Drama\") !== -1 || movie.genre === \"Drama\");\n });\n counter = 0;\n for (var i = 0; i < length.dramaArray; i++){\n if(dramaArray.rate === ''){\n dramaArray.rate = 0;\n counter += 1;\n };\n }\n\n if (dramaArray === []){\n return undefined;\n };\n return ratesAverage(dramaArray);\n\n var num = \n dramaArray.reduce(function(sum, current){\n return sum += parseFloat(current.rate);\n }, 0);\n var average = parseFloat((num / (dramaArray.length - counter).toFixed(2)));\n return average;\n}", "function dramaMoviesRate(movies) {\n\tvar dramaMovies = movies.filter((movie) => {\n\t\treturn movie.genre.includes('Drama');\n\t});\n\tif (dramaMovies.length > 0) {\n\t\treturn ratesAverage(dramaMovies);\n\t} else {\n\t\treturn undefined;\n\t}\n}", "function dramaMoviesRate(array) {\n const arrayDrama = array.filter((movieDrama) => {\n return drama = movieDrama.genre.includes('Drama');\n });\n return ratesAverage(arrayDrama);\n}", "function scoresAverage(movies) {\n let scores = movies.map(movie => movie.score)\n let totalScore = scores.reduce(function (result, score){\n return result + score\n })\n return Number((totalScore / scores.length).toFixed(2))\n }", "function dramaMoviesRate(movies) {\n var filterMovies = movies.filter(function(movie) {\n var filterGenres = movie.genre.filter(function(genre) {\n return genre === \"Drama\"; \n })\n //console.log(filterGenres);\n return filterGenres.length > 0;\n })\n console.log(filterMovies);\n return ratesAverage(filterMovies);\n}", "function dramaMoviesRate(movies) {\n const dramaMov = movies.filter(elm => elm.genre.includes(\"Drama\"))\n if (dramaMov < 1) return 0\n let dramaRate = dramaMov.filter(elm => elm.rate).reduce((acc, elm) => acc + elm.rate, 0)\n let finalRate = dramaRate / dramaMov.length\n return +finalRate.toFixed(2)\n}", "function dramaMoviesRate(array){\n var dramaMovies =\n array.filter(function(oneMovie){\n var movieGenre = oneMovie.genre;\n // console.log(movieGenre);\n // console.log(movieGenre.includes('Drama'));\n if(oneMovie.rate == \"\" ){\n oneMovie.rate=0;\n }\n if (movieGenre.includes('Drama')===false){\n return undefined;\n }\n return movieGenre.includes('Drama');\n });\n if(dramaMovies.length < 1){\n return undefined;\n }\n var ratesCount = 0;\n dramaMovies.forEach(function(oneDrama){\n ratesCount += parseFloat(oneDrama.rate);\n });\n var avgRate = ratesCount/dramaMovies.length;\n avgRate = precisionRound(avgRate);\n // console.log(avgRate);\n return avgRate;\n \n // return dramaMovies;\n \n }", "function dramaMoviesRate(dramaMovies) {\n if (dramaMovies.length === 0) return 0;\n const filteredMovies = dramaMovies.filter(function(movie) {\n if (movie.rate === \"\") movie.rate = 0;\n return movie.genre.includes(\"Drama\");\n });\n if (!filteredMovies.length) return undefined;\n const avg = ratesAverage(filteredMovies);\n return avg;\n // return avg;\n}", "function scoresAverage(movies) {\n return (movies.reduce((acc, item)=> acc + (item.score || 0), 0) / movies.length).toFixed(2) * 1 || 0\n}", "function dramaMoviesRate(array){\n var drama = array.filter(function(item){\n return item.genre.forEach(function(genreType){\n return genreType === \"Drama\";\n });\n });\n return ratesAverage(drama);\n}", "function ratesAverage(movies){\n var ratesAverage = movies.reduce(function(sum,oneMovies){\n \n return sum + Number(oneMovies.rate);\n \n },0);\n return ratesAverage/movies.length\n \n }", "function dramaMoviesRate(myArray) {\n const totalDramaArray = myArray.filter(dramaMovies => dramaMovies.genre.includes(\"Drama\"))\n return ratesAverage(totalDramaArray)\n \n}", "function ratesAverage(movies) {\n let totalSum = movies.reduce(function(accumulator, value) {\n return accumulator + parseInt(value.rate, 10);\n }, 0);\n return totalSum / movies.length;\n}", "function rateAverage(movies){\n var ratAVG = movies.map(function(m){\n var ratNum = parseFloat(m.rate);\n m.rate = ratNum;\n return m\n });\n \n var avg = movies.reduce(function(acc,l){\n return acc + l.rate/movies.length;\n },0);\n}", "function dramaMoviesRate(movies){\n const dramaMovie = movies.filter (function(movie)}\n return movie.genre.indexOf(\"Drama\")\n})", "function dramaMoviesRate(arrayOfMovieObjects){\n let dramasOnly = arrayOfMovieObjects.filter((eachMovie)=>{\n return eachMovie.genre.includes(\"Drama\");\n })\n if(dramasOnly.length ===0){return undefined};\n return ratesAverage(dramasOnly);\n}" ]
[ "0.8198215", "0.8126122", "0.80235314", "0.79801685", "0.7953655", "0.79192615", "0.78840476", "0.78715247", "0.7824512", "0.7768616", "0.77648723", "0.775556", "0.7724957", "0.7711103", "0.7704011", "0.7691488", "0.7689545", "0.76855373", "0.7682447", "0.7660273", "0.763618", "0.7616673", "0.76105005", "0.7609253", "0.76082194", "0.75874346", "0.7585205", "0.7581184", "0.7580893", "0.7580523", "0.7578728", "0.75693756", "0.7551127", "0.75510144", "0.7547509", "0.7538063", "0.7534089", "0.75326896", "0.75236", "0.7521615", "0.75133204", "0.750327", "0.7496505", "0.7490106", "0.74838215", "0.74685323", "0.745707", "0.7454576", "0.7452892", "0.7445481", "0.7439739", "0.7431205", "0.7423747", "0.74114656", "0.73989344", "0.73857474", "0.7367693", "0.7357314", "0.73476344", "0.73404044", "0.73345983", "0.733416", "0.7333551", "0.732949", "0.73209006", "0.73094964", "0.730838", "0.7298217", "0.7289517", "0.7284382", "0.7273183", "0.72686243", "0.7267248", "0.72567356", "0.7236891", "0.7225925", "0.7224499", "0.72200966", "0.72171336", "0.72141063", "0.72105193", "0.7205093", "0.7204912", "0.7201593", "0.7201366", "0.7198169", "0.71921915", "0.7179965", "0.7177998", "0.7150094", "0.714815", "0.71421754", "0.71414137", "0.7139069", "0.71386725", "0.71381974", "0.71367824", "0.7135952", "0.71349573", "0.71254736", "0.710858" ]
0.0
-1
Iteration 6: Time Format Turn duration of the movies from hours to minutes;
function turnHoursToMinutes(duration) {}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function turnHoursToMinutes (movie){\n for (var i=0; i<movie.length;i++){\n var horas=parseInt(movie[i].duration.split(\" \")[0].toString().replace('h',''));\n var minutos=parseInt(movie[i].duration.split(\" \")[1].toString().replace('min',''));\n var tiempo=(horas*60)+minutos\n movie[i].duration=tiempo + ' mins';\n }\n return movie\n }", "function turnHoursToMinutes(movies) {\n return movies.map(movie => {const duration = movie.duration.split(\" \");\n //console.log(movie.duration);\n let mins = 0;\n for (let time of duration) {\n if (time.includes(\"h\")) {\n mins += parseFloat(time) * 60;\n } else {\n mins += parseFloat(time);\n }\n }\n return {duration: mins};\n });\n }", "function turnHoursToMinutes(movies) {\n return movies.map(i =>{\n const splited = i.duration.split(\" \")\n const hoursToMinutes = splited[0].substring(0, splited[0].length-1) * 60\n const minutes = splited[1]? splited[1].substring(0, splited[1].length-3) * 1 : 0\n return {\n ...i,\n duration : hoursToMinutes + minutes\n }\n })\n}", "function turnHoursToMinutes (movies) {\n return movies.map((movie) => {\n const duration = movie.duration.split('');\n let minutes = 0;\n for (let time of duration) {\n if (time.includes('h')) {\n minutes += parseInt(time)*60;\n } else {\n minutes += parseInt(time)\n }\n }\n\n return {\n ...movie,\n duration: minutes\n };\n });\n\n\n}", "function turnHoursToMinutes(movies) {\n return movies.map(movie => {\n let strDuration = movie.duration\n let duration // We need to \n\n // When strDuration === \"Xh XXmin\"\n if (strDuration.length === \"Xh XXmin\".length)\n duration = strDuration[0]*60 + strDuration[3]*10 + strDuration[4]*1\n // When strDuration === \"Xh Xmin\"\n if (strDuration.length === \"Xh Xmin\".length)\n duration = strDuration[0]*60 + strDuration[3]*1\n // When strDuration === \"XXmin\"\n if (strDuration.length === \"XXmin\".length)\n duration = strDuration[0]*10 + strDuration[1]*1\n // When strDuration === \"Xh\"\n if (strDuration.length === \"Xh\".length)\n duration = strDuration[0]*60\n\n return {\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: duration,\n genre: movie.genre,\n rate: movie.rate\n }\n })\n}", "function turnHoursToMinutes(movies) {\n return movies.map(movie => {\n let strDuration = movie.duration\n let duration // We need to \n\n // When strDuration === \"Xh XXmin\"\n if (strDuration.length === \"Xh XXmin\".length)\n duration = strDuration[0]*60 + strDuration[3]*10 + strDuration[4]*1\n // When strDuration === \"Xh Xmin\"\n if (strDuration.length === \"Xh Xmin\".length)\n duration = strDuration[0]*60 + strDuration[3]*1\n // When strDuration === \"XXmin\"\n if (strDuration.length === \"XXmin\".length)\n duration = strDuration[0]*10 + strDuration[1]*1\n // When strDuration === \"Xh\"\n if (strDuration.length === \"Xh\".length)\n duration = strDuration[0]*60\n\n return {\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: duration,\n genre: movie.genre,\n rate: movie.rate\n }\n })\n}", "function turnHoursToMinutes(movies){\n return movies.map( original => {\n let movie = {...original}\n if (!movie.duration) movie.duration = \"\"\n let min = 0\n movie.duration.split(\" \").forEach( el => {\n if( el.includes('h')) min += parseInt(el) * 60\n if ( el.includes('min')) min += parseInt(el)\n })\n movie.duration = min\n return movie\n })\n }", "function turnsHoursToMinutes(movies){\n var fixedMovies = movies.map(\n function(oneMovie) {\n var splitDuration = oneMovie.duration.split(\"\")\n var getHours = splitDuration[0]\n \n var getMinutes = 0\n if (splitDuration[4]===\"m\") {\n getMinutes = splitDuration[3]\n }\n else {\n var arrayMinutes = [splitDuration [3], splitDuration [4]] \n getMinutes = arrayMinutes.join(\"\") \n };\nvar minutes = Number(getHours*60) + Number(getMinutes)\noneMovie.duration = String(minutes)\nreturn oneMovie}\n)\nreturn fixedMovies\n}", "function turnHoursToMinutes(movies){\n let cleanMovies = movies.map(movie => {\n const splittedWord = movie.duration.split(' ')\n const hour = parseInt(splittedWord[0], 10)\n let minute = parseInt(splittedWord[1], 10)\n if (isNaN(minute)) minute = 0\n const duration = (hour * 60) + minute\n movie.duration = duration\n //console.log(`Title:${movie.title}, Hours:${hour}, Minutes:${minute}, Duration: ${duration}`)\n return movie\n })\n return cleanMovies\n}", "function turnHoursToMinutes(movies) {\n var filmsMinute = movies.map(function(film) {\n var newMovie = {};\n // var hoursToMinutes;\n // hoursToMinutes = parseInt(film.duration) * 60 + parseInt(film.duration.substr(2));\n var hoursToMinutes;\n if (film.duration.length <= 2 && film.duration.length > 0 ) {\n hoursToMinutes = parseInt(film.duration) * 60;\n } else if (film.duration.length > 2 && film.duration.length <= 5) {\n hoursToMinutes = parseInt(film.duration);\n } else {\n hoursToMinutes = parseInt(film.duration) * 60 + parseInt(film.duration.substr(2));\n }\n\n (newMovie.title = film.title);\n (newMovie.year = film.year);\n (newMovie.director = film.director);\n (newMovie.duration = hoursToMinutes);\n (newMovie.genre = film.genre);\n (newMovie.rate = film.rate);\n\n return newMovie;\n });\n return filmsMinute;\n}", "function turnHoursToMinutes(movies){\n return movies.map(function (movie){\n var newEl = Object.assign({}, movie)\n var splitedTime = newEl.duration.split(' ');\n if (splitedTime.length == 1){\n if (splitedTime[0].length > 2){\n splitedTime.unshift(0 + \"h\");\n } else{splitedTime.push(0 + \"min\");} \n } \n var hours = parseFloat(splitedTime[0]) * 60;\n var minutes = parseFloat(splitedTime[1]);\n newEl.duration = hours + minutes;\n return newEl;\n }); \n}", "function turnHoursToMinutes (movies) {\n let newMovies = movies.slice();\n //let newMovies = [...movies.slice];\n let hours = '';\n let minutes = '';\n \n newMovies.forEach(elem => {\n hours = parseInt(elem.duration.match(/[^h]+/));\n minutes = parseInt(elem.duration.match(/([\\d.]+) *min/));\n //console.log(hours, \" \", minutes);\n //BREAK\n if ((hours > 0) && (minutes > 0)) elem.duration = hours * 60 + minutes;\n else if (hours > 0) elem.duration = hours * 60;\n else if (minutes > 0) elem.duration = minutes;\n\n });\n\n return newMovies;\n}", "function turnHoursToMinutes(moviesArray) {\n var moviesWithCorrectTimeFormat = [];\n var eachMovieHours, eachMovieMinutes, totalMinutes, singleMovieWithCorrectTimeFormat;\n moviesArray.map(function(eachMovie) {\n eachMovieHours = 0;\n eachMovieMinutes = 0;\n totalMinutes = 0;\n if(eachMovie.duration.indexOf(\"h\")!==-1){\n eachMovieHours = eachMovie.duration.slice(0, eachMovie.duration.indexOf(\"h\"));\n }\n else{\n eachMovieHours=0;\n }\n eachMovieMinutes = eachMovie.duration.slice(eachMovie.duration.indexOf(\"h\") + 1, eachMovie.duration.indexOf(\"m\"));\n totalMinutes = (60 *eachMovieHours) + (1* eachMovieMinutes);\n singleMovieWithCorrectTimeFormat = Object.assign({},eachMovie);\n singleMovieWithCorrectTimeFormat.duration = totalMinutes;\n moviesWithCorrectTimeFormat.push(singleMovieWithCorrectTimeFormat);\n });\n return moviesWithCorrectTimeFormat;\n }", "function turnHoursToMinutes(collection){ \n var newFormat = collection.map(function(movie){\n var newMovie = Object.assign({}, movie);\n var movieTime = newMovie.duration;\n var tempMovieTime = \"\";\n if (movieTime.includes(\"h\") && movieTime.includes(\"m\")){\n tempMovieTime = movieTime.toString().split(\" \");\n tempMovieTime = parseInt(tempMovieTime[0]) * 60 + parseInt(tempMovieTime[1]);\n }else if (movieTime.includes(\"h\")){\n tempMovieTime = parseInt(movieTime);\n tempMovieTime *= 60;\n }else if (movieTime.includes(\"m\")){\n tempMovieTime = parseInt(movieTime);\n }\n var hoursInMinutes = tempMovieTime;\n newMovie.duration = hoursInMinutes;\n return newMovie;\n });\n return newFormat;\n}", "function turnHoursToMinutes(movies) {\n var formatTime = movies.map(function(movie) {\n var durationArray = movie.duration.replace(/[hmin]/g, '').split(\" \");\n // Create a copy of the object (otherwise, movie.duration change the original object property)\n var obj = Object.assign({}, movie, {\n // In case the array has only one element, it means it's minutes, or hour. \n duration: (durationArray.length === 1) ? (durationArray[0].length === 1) ? parseInt(durationArray[0]) * 60 : parseInt(durationArray[0])\n : (parseInt(durationArray[0]) * 60 + parseInt(durationArray[1])),\n });\n return obj;\n })\n return formatTime;\n}", "function turnHoursToMinutes (movies) {\n const newList = [];\n for (let i = 0; i < movies.length; i++) {\n const originalMovie = movies[i];\n const movieCopy = Object.assign({}, originalMovie);\n const oldDuration = movieCopy.duration;\n const oldDurationPair = oldDuration.split(' '); // => [\"1h\", \"34min\"]\n const hoursInMins = Number.parseInt(oldDurationPair[0]) * 60 \n const minsInMins = Number.parseInt(oldDurationPair[1])\n let durationInMinutes; \n\n if (oldDurationPair[1] != undefined) {\n durationInMinutes = hoursInMins + minsInMins\n }\n else if (oldDurationPair[0].includes(\"min\")) {\n durationInMinutes = Number.parseInt(oldDurationPair[0]);\n }\n else if (oldDurationPair[0].includes(\"h\")) {\n durationInMinutes = hoursInMins;\n }\n \n movieCopy.duration = durationInMinutes;\n newList.push(movieCopy);\n }\n return newList;\n}", "function turnHoursToMinutes(movies){\n let moviesArr = JSON.parse(JSON.stringify(movies));\n\n return moviesArr.map(movie => {\n let time = movie.duration.split(' ');\n\n let minutes = time.reduce((acc, current) => {\n if (current.indexOf('h') != -1) {\n return parseInt(current.replace('h', '')) * 60;\n } else {\n return acc + parseInt(current.replace('min', ''));\n }\n }, 0);\n \n movie.duration = minutes;\n return movie;\n })\n}", "function turnHoursToMinutes(movies) {\n const timeList = movies.map((value) => { return { duration: value.duration.split(\" \") } });\n const timeInMin = timeList.map((value) => {\n let sum = 0;\n /* console.log('value', value) */\n for (i = 0; i < value.duration.length; i++) {\n\n if (value.duration[i].includes(\"h\")) {\n sum += parseInt(value.duration[i]) * 60;\n /* console.log('value', value.duration[i])\n console.log(`adding hours in minutes-sum`, sum) */\n } else if (value.duration[i].includes(\"m\")) {\n sum += parseInt(value.duration[i]);\n /* console.log('value', value.duration[i])\n console.log(`adding minutes to hours-sum`, sum) */\n }\n }\n return { duration: sum };\n });\n return timeInMin;\n}", "function turnHoursToMinutes(movieArray) {\n\n const durationMovie = movieArray.map(e => e.duration)\n let minutesPerHour = 0\n let minutes = 0\n const totalMinutes = []\n\n durationMovie.forEach(function (m, idx) {\n for (i = 0; i < m.length; i++) {\n if (m[i] === 'h') {\n minutesPerHour = parseInt(m[i - 1] * 60)\n } else if (m[i] === 'm') {\n minutes = parseInt(m[i - 2] + m[i - 1])\n }\n }\n totalMinutes.push({ duration: minutesPerHour + minutes })\n })\n\n return totalMinutes\n}", "function turnHoursToMinutes(movies) {\n const minutes = movies.map(function(movie){\n let left = parseInt(movie.duration.split('h')[0]) * 60\n let right = parseInt(movie.duration.split('min')[0].split('h ')[1]) || 0\n return {\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: left + right,\n genre: movie.genre,\n score: movie.score\n }\n })\n return minutes\n}", "function turnHoursToMinutes (movies){\n let moviesMin = movies.map(movie => {\n let duracion = movie.duration;\n let newDuration = duracion.split(\" \")\n\n if (duracion.includes(\"h\") && duracion.includes(\"min\") ){\n let horasToMin = parseInt(newDuration[0]) * 60 + parseInt(newDuration[1])\n duracion= horasToMin \n\n } else if (duracion.includes(\"h\") ){\n let calculo = parseInt(newDuration[0]) * 60 \n duracion = calculo; \n\n }else if(duracion.includes(\"min\")){\n let minutes = parseInt(newDuration[0])\n duracion = minutes;\n }\n \n return {...movie, duration: parseInt(duracion)}\n \n })\n return moviesMin\n}", "function changeDurationMovies(arr){\nvar horasIndex = arr.indexOf(\"h\");\n\nvar horas = 0;\nif (horasIndex >= 0){\n horas = parseInt(arr.slice(0,horasIndex));\n}\nvar minutos = 0\nif (arr.includes(\"min\"))\n{\n minutos = parseInt(arr.split(\" \").pop());\n}\n\nreturn horas * 60 + minutos;\n}", "function turnHoursToMinutes(movies){\n\n var minutesArray = movies.map(function(eachMovie){ //looped through all movies\n let movie = eachMovie.duration.split(\" \") //made the duration string into array\n // console.log(\"=================================== \", movie);\n let totalMinutes = 0; \n movie.forEach((arr)=>{ //loop through array \n if(arr.includes('h')){ \n totalMinutes+=Number(arr.replace('h',''))*60 //if has h do this math\n } \n if(arr.includes('min')){\n totalMinutes+=Number(arr.replace('min','')) //if has min do this\n }\n })\n return {...eachMovie, duration: totalMinutes} //return all the old movie stuff with different duration\n\n })\n\n return minutesArray //return ENTIRE new ARRAY with durations \n\n}", "function turnHoursToMinutes(movies){\n\tvar moviesMinutes = movies.map(function(m){\n var hora = m.duration.slice(0,1);\n var min = m.duration.slice(3,5);\n var horaNum = parseInt(hora*60);\n var minNum = parseInt(min);\n if (horaNum == 0) m.duration = minNum;\n m.duration = horaNum + minNum;\n \n return m\n });\n console.log(moviesMinutes);\n}", "function turnHoursToMinutes(movies) {\n // let moviesInMinutes = [...movies];\n let moviesInMinutes = movies.map(function(movie) {\n return { ...movie };\n });\n// console.log(moviesInMinutes);\n// console.log(moviesInMinutes[0] === movies[0])\n // console.log(moviesInMinutes.filter(el => el.duration));\n // console.log(moviesInMinutes.map(el => el).length);\n\n let movieDurations = moviesInMinutes.map(function(movie) {\n let timeValues = movie.duration.split(\" \");\n let movieDurationinMinutes = 0;\n for (value of timeValues) {\n if (value.includes(\"h\")) {\n movieDurationinMinutes += parseInt(value.replace(\"h\", \"\")) * 60;\n } else if (value.includes(\"min\")) {\n movieDurationinMinutes += parseInt(value.replace(\"min\", \"\"));\n }\n }\n return movieDurationinMinutes;\n });\n\n moviesInMinutes.forEach(function(movie, index) {\n movie.duration = movieDurations[index];\n });\n\n return moviesInMinutes;\n}", "function turnHoursToMinutes(array) {\nvar durationInLetters = movies.map(function(movies){\n return movies.duration.split('');\n});\nvar horasSinLetras= durationInLetters.map(function(elem, i){\n return (durationInLetters[i][0] * 60);\n});\nvar minutosSinLetras= durationInLetters.map(function(elem,i){\n if (elem.indexOf(\"m\")!=-1){\n return elem.splice(elem.indexOf(' ')+1,elem.indexOf('m')-elem.indexOf(' ')-1).join(\"\");\n } else {\n return 0;\n }\n});\nvar tiempoEnMinutos = horasSinLetras.map(function(elem, i){\n return horasSinLetras[i] + parseInt(minutosSinLetras[i]);\n});\nvar last = movies.map(function(elem,i){\n return elem.duration === tiempoEnMinutos[i];\n});\nreturn tiempoEnMinutos\n}", "function turnHoursToMinutes(array) { // 1\n return array.map(function (movie) { // 2\n \n let newMovie = Object.assign({}, movie); // 3\n let hoursArray = movie.duration.split(' '); // 4\n let total = 0; // 5\n \n if (hoursArray.length === 2) { // 6\n total = (parseInt(hoursArray[0]) * 60) + parseInt(hoursArray[1]);\n } else if (hoursArray.length === 1 && hoursArray[0].indexOf('h') > -1) { // 7\n total = (parseInt(hoursArray[0]) * 60);\n } else if (hoursArray.length === 1 && hoursArray[0].indexOf('min') > -1) { // 8\n total = parseInt(hoursArray[0]);\n }\n newMovie.duration = total; // 9\n return newMovie; // 10\n })\n \n }", "function turnHoursToMinutes(arr) {\n const moviesArr = [...arr];\n\n const newArr = moviesArr.map(movie => durationToMinutes(movie));\n function durationToMinutes(movie) {\n const movieCopy = { ...movie };\n if (typeof movieCopy.duration === \"number\") {\n return movieCopy;\n }\n movieDuration = movieCopy.duration;\n let hours = 0;\n let minutes = 0;\n\n const timeString = movieDuration.split(\" \");\n \n const minutesDuration = timeString.reduce(function(total, string) {\n if (string.includes(\"h\")) {\n const numOfHours = parseInt(string);\n return total + numOfHours * 60;\n } else {\n const numOfMinutes = parseInt(string);\n return total + numOfMinutes;\n }\n }, 0);\n\n movieCopy.duration = minutesDuration;\n return movieCopy;\n }\n\n return newArr;\n}", "function turnHoursToMinutes(movies) {\n const newMovies = movies.map(elm => {\n let hours = elm.duration.slice(0, 1)\n let minutes = elm.duration.slice(3, 5).replace(/[a-z]/gi, '') //Aunque Jasmine lo pase, se hace necesario el .replace() para evitar que luego aparezcan NaN en el nuevo array\n\n if(elm.duration.charAt(1) === \"h\") {\n let total = (hours * 60) + Number(minutes)\n return {\n ...elm,\n duration: total\n }\n } else {\n let total2 = Number(elm.duration.slice(0, 2))\n return {\n ...elm,\n duration: total2\n }\n }\n })\n return newMovies\n}", "function turnHoursToMinutes(movies) {\n var moviesWithMinutes = movies.map(function(movie) {\n var hours = 0;\n var hoursToMinutes = 0;\n var minutes = 0;\n\n var indexHour = movie.duration.indexOf('h');\n if(indexHour !== -1) {\n hours = parseInt(movie.duration.substring(0, indexHour));\n hoursToMinutes = hours * 60;\n }\n\n var indexMinute = movie.duration.indexOf('min');\n if(indexMinute !== -1) {\n if(indexHour !== -1) {\n minutes = parseInt(movie.duration.substring(indexHour + 1, indexMinute));\n } else {\n minutes = parseInt(movie.duration.substring(0, indexMinute));\n }\n }\n\n var movieWithMinutes = Object.assign({}, movie, { duration: hoursToMinutes + minutes });\n return movieWithMinutes;\n });\n\n return moviesWithMinutes;\n}", "function turnHoursToMinutes (movieArray) {\n var newMovieArray = movieArray.map(function(elem) {\n var arr = elem.duration.toString().split('h'); \n if (arr.length < 2) {\n arr.unshift(\"0\"); \n } \n var hours = Number(arr[0]);\n var minutes = Number(arr[1].toString().split(\"min\")[0]);\n elem.duration=hours*60+minutes;\n return elem;\n })\nreturn newMovieArray.reverse();\n}", "function turnHoursToMinutes(array1) {\n array = [...array1]\n let movieDuration = []\n let minutes = 0\n array.forEach(elm => {\n\n movieDuration = elm.duration.split(\" \")\n console.log(movieDuration)\n movieDuration.forEach(elm2 => {\n\n\n if (elm2.includes(\"h\")) {\n minutes = parseInt(elm2) * 60\n\n } else if (elm2.includes(\"min\")) {\n minutes += parseInt(elm2)\n\n }\n\n\n })\n console.log(minutes)\n elm.duration = minutes\n\n\n\n })\n return array\n}", "function turnHoursToMinutes (moviesArray){\n\n let newMoviesArray = moviesArray.map((movie)=>{\n\n let editedMovie={};\n\n Object.assign(editedMovie,movie);\n if(editedMovie.duration.includes(\"h\") && editedMovie.duration.includes(\"min\")){\n \n editedMovie.duration = editedMovie.duration.replace(\"h\",\"\");\n editedMovie.duration = editedMovie.duration.replace(\"min\",\"\");\n let arrayDuration = editedMovie.duration.split(\" \");\n editedMovie.duration = Number(arrayDuration[0] * 60) + Number(arrayDuration[1]);\n\n return editedMovie;\n\n }else if(editedMovie.duration.includes(\"h\")){\n \n editedMovie.duration = editedMovie.duration.replace(\"h\",\"\");\n let arrayDuration = editedMovie.duration.split();\n editedMovie.duration = Number(arrayDuration[0] * 60);\n\n return editedMovie;\n\n }else{\n\n editedMovie.duration = editedMovie.duration.replace(\"min\",\" \");\n let arrayDuration = editedMovie.duration.split();\n editedMovie.duration = Number(arrayDuration[0]);\n\n return editedMovie;\n\n }\n \n \n })\n\n return newMoviesArray;\n}", "function turnHoursToMinutes(e) {\n const movie = e;\n \n var mov = movie.map(e => {\n var arr = Object.assign({},e); \n arr.duration = arr.duration.split('');\n console.log(arr.duration);\n if (arr.duration.includes('h') && arr.duration.includes('m'))\n {\n console.log('min et h')\n arr.duration = arr.duration.map(e => Number(e));\n console.log(arr.duration);\n arr.duration = arr.duration.filter(e => e > 0)\n console.log(arr.duration);\n arr.duration = arr.duration[0]*60 + arr.duration[1]*10+arr.duration[2]; \n } \n else if (arr.duration.includes('h') && !arr.duration.includes('m')){\n console.log('juste h ') \n arr.duration = arr.duration.map(e => Number(e));\n console.log(arr.duration);\n arr.duration = arr.duration.filter(e => e > 0)\n console.log(arr.duration);\n arr.duration = arr.duration= Number(arr.duration.join(''))*60; \n } \n else if (!arr.duration.includes('h') && arr.duration.includes('m'))\n {console.log('min') \n arr.duration = arr.duration.map(e => Number(e));\n console.log(arr.duration);\n arr.duration = arr.duration.filter(e => e > 0)\n console.log(arr.duration);\n arr.duration = arr.duration= Number(arr.duration.join(''))\n }\n return arr\n })\n\n return mov;\n \n }", "function turnHoursToMinutes(moviesArray){\n return moviesArray.map((eachMovie)=>{\n let newMovie = {...eachMovie}; // spread \n let regexHours = /[0-9]+h/g; //regex to find hours\n let regexMinutes = /([0-9]+min)/g; //regex to find minutes\n\n let hoursArray = newMovie.duration.toString().match(regexHours); //find hours\n let minutesArray = newMovie.duration.toString().match(regexMinutes); //find minutes\n \n let durationInMin = 0;\n \n if(hoursArray !== null){\n let hours = parseInt(hoursArray[0].replace(/\\D/g, \"\")); //remove the h in hours\n durationInMin += hours*60;\n }\n\n if(minutesArray !== null){\n let minutes = parseInt(minutesArray[0].replace(/\\D/g, \"\")); //remove the h in hours\n durationInMin += minutes; \n }\n\n newMovie.duration = durationInMin;\n return newMovie;\n });\n\n}", "function turnHoursToMinutes(movies) {\n var changeMovieTime = movies.map(function (movie) {\n var movieDuration = movie.duration;\n var hours = Number(movieDuration[0] * 60);\n var minutes1digit = Number(movieDuration[3]);\n var minutes2digit = Number(movieDuration[3] + movieDuration[4]);\n var minutesNoHour = Number(movieDuration[0] + movieDuration[1]);\n var hoursNoMinutes = Number(movieDuration[0] * 60)\n var totalTime1 = hours + minutes1digit;\n var totalTime2 = hours + minutes2digit;\n var newMovie = movie;\n\n\n if (movieDuration.length === 7) {\n newMovie.duration = totalTime1;\n return newMovie;\n } else if (movieDuration.length === 8) {\n newMovie.duration = totalTime2;\n return newMovie;\n } else if (movieDuration.length === 5) {\n newMovie.duration = minutesNoHour;\n return newMovie;\n } else {\n newMovie.duration = hoursNoMinutes;\n return newMovie;\n }\n })\n console.log(changeMovieTime)\n return changeMovieTime;\n}", "function turnHoursToMinutes(moviesArray) {\n return moviesArray.map(function(elem) {\n var hours = 0;\n var minutes = 0;\n \n if (typeof elem.duration !== \"number\") {\n if (elem.duration.indexOf(\"h\") !== -1) {\n hours = parseInt(elem.duration[0], 10) * 60;\n }\n if (elem.duration.indexOf(\"min\") !== -1) {\n minutes = parseInt(\n elem.duration.substring(\n elem.duration.length - 5,\n elem.duration.length - 3\n ),\n 10\n );\n }\n return Object.assign({}, elem, { duration: hours + minutes });\n } else {\n return elem;\n }\n });\n }", "function turnHoursToMinutes(moviesArray) {\n return moviesArray.map(function (elem) {\n var hours = 0;\n var minutes = 0;\n if (elem.duration.indexOf('h') !== -1) {\n hours = parseInt(elem.duration[0], 10) * 60;\n }\n if (elem.duration.indexOf('min') !== -1) {\n minutes = parseInt(elem.duration.substring(elem.duration.length - 5, elem.duration.length - 3), 10);\n }\n return Object.assign({}, elem, { duration: hours + minutes });\n });\n }", "function turnHoursToMinutes(moviesArray) {\n return moviesArray.map(function (elem) {\n var hours = 0;\n var minutes = 0;\n if (elem.duration.indexOf('h') !== -1) {\n hours = parseInt(elem.duration[0], 10) * 60;\n }\n if (elem.duration.indexOf('min') !== -1) {\n minutes = parseInt(elem.duration.substring(elem.duration.length - 5, elem.duration.length - 3), 10);\n }\n return Object.assign({}, elem, { duration: hours + minutes });\n });\n }", "function turnHoursToMinutes(movies) {\n \n let turnHour = JSON.parse(JSON.stringify(movies)).map(function(item){\n let positionH = item.duration.indexOf(\"h\")\n let hour = parseInt(item.duration.slice(0, positionH))\n let positionM = item.duration.indexOf(\"m\")\n let min=0\n if(positionH===-1){\n min = parseInt(item.duration.slice(0, positionM))\n item.duration=min\n }else{\n if (positionM === -1) {\n item.duration = hour * 60\n } else {\n min = parseInt(item.duration.slice((item.duration.indexOf(\" \")), positionM))\n item.duration = (hour * 60) + min\n }\n }\n return item\n })\n return turnHour\n}", "function turnHoursToMinutes(movieLength) {\n const total = movieLength.map((value, index, originalArray) => {\n return {duration: value.duration};\n });\n//console.log(total);\n const minsArray = total.map((value, index, originalArray) => {\n let totalMin = 0;\n let durationSplit = value.duration.split(' ');\n //console.log(\"split\", durationSplit);\n for (let i = 0; i < durationSplit.length; i++){\n if(durationSplit[i].includes('h')){\n totalMin += parseInt(durationSplit[i])*60;\n } else {\n totalMin += parseInt(durationSplit[i]);\n }\n }\n return {duration: totalMin};\n\n });\n\n //console.log(\"HERE\",minsArray);\n\n // let parsed = parseInt('h');\n // if (isNaN(parsed)) { return 0 }\n // return parsed * 60;\n return minsArray;\n}", "function turnHoursToMinutes(array){\n var returnArray = \n array.map(function(movie){\n if (movie.duration.length === 8){\n var newtime = parseFloat(movie.duration[0])*60 + parseFloat(movie.duration.slice(3,5));\n } else if (movie.duration.length === 2){\n var newtime = parseFloat(movie.duration[0]*60);\n } else if (movie.duration.length === 5){\n var newtime = parseFloat(movie.duration.slice(0,2));\n };\n //duration: '2h 55min',\n var newmovie = {\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: newtime,\n genre: movie.genre,\n rate: movie.rate,\n }\n return newmovie;\n }, 0);\n return returnArray;\n}", "function turnHoursToMinutes(arr){\n let conversion = arr.map((movie) => { \n let newMovie = {...movie};\n if(movie.duration){\n const cadenaPrueba = movie.duration;\n let mins;\n \n if(movie.duration.indexOf(\"h\") === -1){\n let tempMin = cadenaPrueba.split(\"min\");\n newMovie.duration = parseInt(tempMin[0]);\n } else {\n let temp = cadenaPrueba.split(\"h \");\n let tempMin = \"0\";\n if(temp[1]){\n tempMin = temp[1].split(\"min\");\n }\n mins = parseInt(temp[0]) * 60 + parseInt(tempMin[0]);\n newMovie.duration = mins;\n }\n }\n return newMovie;\n });\n return conversion; \n }", "function turnHoursToMinutes(arr) {\n var newMovieDurationArray = arr.map(function(movie) {\n var newMovie = Object.assign({}, movie);\n var durationArray = newMovie.duration.split(\" \");\n if (durationArray.length === 2) {\n var hours = durationArray[0].replace(\"h\", \"\");\n hours = parseInt(hours) * 60;\n var minutes = durationArray[1].replace(\"min\", \"\");\n minutes = parseInt(minutes);\n newMovie.duration = hours + minutes;\n } else if (durationArray[0].includes(\"h\")) {\n var hours = durationArray[0].replace(\"h\", \"\");\n hours = parseInt(hours) * 60;\n newMovie.duration = hours;\n } else {\n var minutes = durationArray[0].replace(\"min\", \"\");\n minutes = parseInt(minutes);\n newMovie.duration = minutes;\n }\n return newMovie;\n });\n return newMovieDurationArray;\n}", "function turnHoursToMinutes(movies) {\n const copyMovies = JSON.parse(JSON.stringify(movies))\n const newMovies = copyMovies.map(movie => {\n const duration = movie.duration;\n let hoursInMin = 0;\n let minInMin = 0;\n if (duration.includes(\"h\")) {\n hoursInMin = parseInt(duration.slice(0, duration.indexOf(\"h\"))) * 60;\n }\n if (duration.includes(\"min\") && duration.includes(\"h\")) {\n minInMin = parseInt(duration.slice((duration.indexOf(\"h\") + 2), duration.indexOf(\"min\")));\n } else if (duration.includes(\"min\") && !duration.includes(\"h\")) {\n minInMin = parseInt(duration.slice(0, duration.indexOf(\"min\")));\n }\n movie.duration = hoursInMin + minInMin\n return movie\n })\n return newMovies;\n}", "function turnHoursToMinutes(movies) {\n return movies.map(function(movie) {\n var hours = 0;\n var minutes = 0;\n\n if (movie.duration.indexOf(\"h\") != -1) {\n hours = parseInt(movie.duration.slice(0, movie.duration.indexOf(\"h\")));\n }\n\n if (movie.duration.indexOf(\"m\") != -1) {\n minutes = parseInt(\n movie.duration.slice(\n movie.duration.indexOf(\"m\") - 2,\n movie.duration.indexOf(\"m\")\n )\n );\n }\n\n var duration = hours * 60 + minutes;\n\n return Object.assign({}, movie, { duration: duration });\n });\n}", "function refresh_time(duration) {\n var mm = Math.floor(Math.floor(duration) / 60) + \"\";\n var ss = Math.ceil(Math.floor(duration) % 60) + \"\";\n\n if (mm.length < 2) { mm = \"0\" + mm; }\n if (ss.length < 2) { ss = \"0\" + ss; }\n container.html(mm + \":\" + ss);\n\n }", "function turnHoursToMinutes(array){\n const newDuration = array.map(movie => {\n return movie.duration.split(\"\");\n });\n return newDuration;\n }", "function turnHoursToMinutes(arr){\n let newArr = JSON.parse(JSON.stringify(arr));\n\n let newDuration = newArr.map(movie => {\n let splittedDuration = movie.duration.toString().split(\" \");\n \n if(splittedDuration.length === 1){\n if(splittedDuration[0].includes(\"h\")){\n let total = parseFloat(splittedDuration[0]) * 60;\n movie.duration = total;\n } else{\n let total = parseFloat(splittedDuration[0]);\n movie.duration = total;\n }\n }\n else if(splittedDuration.length === 2){\n let hours = parseFloat(splittedDuration[0]) * 60;\n let mins = parseFloat(splittedDuration[1]);\n let total = hours + mins;\n movie.duration = total;\n }\n return{\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: movie.duration,\n genre: movie.genre,\n rate: movie.rate\n }\n });\n return newDuration;\n}", "function turnHoursToMinutes(movies) {\n\n return JSON.parse(JSON.stringify(movies)).map((movie) => {\n const hours = movie.duration.match(/\\d+(?=h)/g);\n const minutes = movie.duration.match(/\\d+(?=min)/g);\n if (hours) {\n movie.duration = (Number(hours) * 60 + Number(minutes));\n return movie;\n }\n movie.duration = Number(minutes);\n return movie;\n })\n}", "function turnHoursToMinutes(arr){\n var newArray = arr.map(function(movie){\n return movie.duration.split(\" \");\n });\n var arrTimeFormated = []; \n for (var i = 0; i < newArray.length; i++){\n var horas = Number(newArray[i][0].slice(0,1));\n var min = Number(newArray[i][1].slice(0,2));\n arrTimeFormated.push(horas*60 + min);\n }\n return arrTimeFormated;\n}", "function turnHoursToMinutes(array){\n var returnArray = \n array.map(function(oneMovie){\n\n var duration = oneMovie[\"duration\"];\n var hour = 0;\n var minute = 0;\n duration = duration.split(\" \");\n\n for(var i = 0; i < duration.length; i++){\n if(i == 0 && duration[i].indexOf('h') != -1){\n hour = parseInt(duration[0])*60;\n } else if(i == 0 && duration[i].indexOf('min') != -1) {\n minute = parseInt(duration[0]);\n } else if(i == 1 && duration[i].indexOf('min') != -1){\n minute = parseInt(duration[1]);\n }\n }\n duration = parseInt(hour + minute);\n\n var newMovie = {\n title: oneMovie.title,\n year: oneMovie.year,\n director: oneMovie.director,\n duration: duration,\n genre: oneMovie.genre,\n rate: oneMovie.rate\n };\n return newMovie;\n });\n return returnArray;\n}", "function turnHoursToMinutes(movies) {\n // function that will take a string and will return the total minutes per hour as a number.\n function convertHours(hourString) {\n let calculateHour = hourString.split('h'); // split to divide the string in two. The first element will be the number as a string.\n return Number(calculateHour[0]) * 60; // return the hours in minutes\n }\n \n // function that will take a string and will return the minutes as a number.\n function convertMinutes(minuteString) {\n let calculateMinutes = minuteString.split('min'); // split to divide the string in two. The first element will be the number as a string.\n return Number(calculateMinutes[0]); // return the minutes\n }\n \n // function that will use both functions (convertHours & convertMinutes) to get the total amount of minutes\n function convertDuration(duration) {\n let timePieces = duration.split(' '); // split will divide the duration string into two strings (hours & minutes)\n \n // reduce to sum hours (in minutes) and minutes\n let minutes = timePieces.reduce((sum, onePiece) => {\n if (onePiece.includes('h')) {\n return sum + convertHours(onePiece); \n }\n return sum + convertMinutes(onePiece);\n }, 0);\n \n return minutes; // return total minutes\n }\n\n // map to add the newly found minutes amount as number to a new array\n let moviesHoursToMinArr = movies.map(function(eachMovie) {\n let fixedMovie = JSON.parse(JSON.stringify(eachMovie)) // deep clone to not mutate original\n fixedMovie.duration = convertDuration(fixedMovie.duration) // dot operator to change the value of the duration attribute with the result of calling the function convertDuration\n return fixedMovie\n })\n\n return moviesHoursToMinArr // return the new array\n}", "function turnHoursToMinutes(arrayMovies) {\n\n return arrayMovies.map(function (element) {\n var hours = 0,\n minutes = 0,\n movie = [];\n\n if (element.duration == '') {\n hours = 0;\n minutes = 0;\n } else if (element.duration.indexOf('min') < 0) {\n hours = element.duration.slice(0, element.duration.indexOf('h'));\n minutes = 0;\n } else if (element.duration.indexOf('h') < 0) {\n hours = 0;\n minutes = element.duration.slice(0, element.duration.indexOf('min'));\n } else {\n hours = element.duration.slice(0, element.duration.indexOf('h'));\n minutes = element.duration.slice(element.duration.indexOf('h') + 2, element.duration.indexOf('min'));\n }\n movie = {\n \"title\": element.title,\n \"year\": element.year,\n \"director\": element.director,\n \"duration\": (parseInt(hours) * 60 + parseInt(minutes)),\n \"genre\": element.genre,\n \"rate\": element.rate\n };\n return movie;\n });\n}", "function turnHoursToMinutes (array) {\n var newArray = [];\n\n array.forEach (function (oneMovie) {\n\n var durationArray = oneMovie.duration.split (' ');\n \n // var min = parseInt (durationArray[1], 10);\n \n if (durationArray.length === 1 && durationArray[0].includes(\"min\")) {\n var hr = 0;\n var min = parseInt (durationArray[0], 10);\n }\n else {\n var min = parseInt (durationArray[1], 10);\n var hr = parseInt (durationArray[0], 10);\n }\n\n if (isNaN (min)) {\n var min = 0;\n };\n \n \n var duration = hr*60 + min;\n\n newArray.push ({\n title : oneMovie.title,\n year : oneMovie.year,\n director : oneMovie.director,\n duration : duration,\n genre : oneMovie.genre,\n rate : oneMovie.rate,\n });\n \n\n });\n\n return newArray;\n}", "function turnHoursToMinutes(movies)\n{\n var moviesMod = movies.map(function(movie){\n if(typeof(movie.duration)==='number') return movie;\n var h = parseInt(movie.duration.substring(0,movie.duration.indexOf(\"h\")));\n if (movie.duration.indexOf(\"h\")===-1) h=0; \n var min = parseInt(movie.duration.substring(movie.duration.indexOf(\"h\")+1, movie.duration.indexOf(\"min\")));\n if (movie.duration.indexOf(\"min\")===-1) min=0; \n\n var movieMod = Object.assign({}, movie);\n movieMod.duration = parseInt((h*60)+min);\n return movieMod;\n });\n\n return moviesMod;\n}", "function turnHoursToMinutes(films) {\n\n return films.map(function (movie) {\n\n var hours = 0;\n var minutes = 0;\n\n if (movie.duration.indexOf(\"h\") !== - 1) {\n\n hours = parseInt(movie.duration[0], 10) * 60;\n\n }\n if (movie.duration.indexOf(\"min\") !== -1) {\n\n minutes = parseInt(movie.duration.substr(movie.duration.length - 5, movie.duration.length - 3), 10);\n\n }\n return Object.assign({}, movie, { duration: hours + minutes });\n\n });\n}", "function turnHoursToMinutes(array){\n return array.map(function(element){\n var movie = Object.assign({}, element);\n var duration = movie.duration.split(' ').reduce(function(acc, curr){\n if (curr.indexOf('h') !== -1) {\n return Number(curr.replace('h', '')) * 60 + acc;\n } else{\n return Number(curr.replace('min', '')) + acc;\n }\n }, 0);\n movie.duration = duration; \n return movie;\n }); \n\n}", "function turnHoursToMinutes(arr){\n const copy =JSON.parse(JSON.stringify(arr));\n copy.forEach(movie => {\n let duration = 0 ; \n const splittedTime = movie.duration.split(\" \");\n if(splittedTime.length === 1){\n let hoursOrMinutes = splittedTime[0];\n if(hoursOrMinutes.includes(\"h\")){\n duration = parseFloat(hoursOrMinutes) * 60;\n movie.duration = duration;\n return;\n }\n if(hoursOrMinutes.includes(\"min\")){\n movie.duration = parseFloat(hoursOrMinutes)\n return;\n }\n }\n let hours = parseFloat(splittedTime[0]) * 60;\n let minutes = parseFloat(splittedTime[1]);\n movie.duration = hours + minutes;\n })\n return copy;\n }", "function turnHoursToMinutes(array) {\n\n return array.map(movie => {\n\n let hourSearchChar = \"h\"\n let minSearchChar = \"min\"\n let arrayHoursMin = movie.duration.split(\" \");\n let duration = 0;\n\n if (arrayHoursMin.length == 2) {\n let hours = (Number(arrayHoursMin[0].replace(hourSearchChar, \"\")) * 60);\n let minutes = (Number(arrayHoursMin[1].replace(minSearchChar, \"\")));\n duration = Number(hours + minutes);\n } else if (arrayHoursMin[0].indexOf(hourSearchChar) != -1) {\n duration = (Number(arrayHoursMin[0].replace(hourSearchChar, \"\")) * 60);\n } else {\n duration = Number(arrayHoursMin[0].replace(minSearchChar, \"\"));\n }\n let newMovie = {...movie }\n newMovie.duration = duration;\n return newMovie\n\n });\n}", "function turnHoursToMinutes(array) {\n return array.map(movie => {\n const originalDuration = movie.duration\n let duration = 0\n for (let value of originalDuration.split(' ')) {\n const hour = parseInt(value)\n if (value.includes('h')) {\n duration += hour * 60\n } else if (value.includes('min')) {\n duration += hour\n }\n }\n return {\n ...movie,\n duration\n }\n })\n}", "function hoursToMinutes(array) {\n\n\n let result = array.map(movie => {\n\n let container = {};\n\n container.title = movie.title;\n container.year = movie.year;\n container.director = movie.director;\n\n let duracion = movie.duration;\n let duracionArray = duracion.split(\"h\");\n let horas = parseInt(duracionArray[0]);\n\n let minutosArray = duracionArray[1].split(\"min\");\n let minutos = parseInt(minutosArray[0]);\n\n if (isNaN(minutos)) {\n minutos = 0;\n } \n\n let duracionMinutos = (horas * 60) + minutos;\n console.log(duracionMinutos);\n \n container.duration = duracionMinutos;\n container.genre = movie.genre;\n container.score = movie.score;\n\n return container;\n });\n\n return result;\n}", "function turnHoursToMinutes(moviesArray) {\n return moviesArray.map(function (elem) {\n var hours = 0;\n var minutes = 0;\n if (elem.duration.indexOf('h') !== -1) {\n hours = parseInt(elem.duration[0], 10) * 60;\n }\n if (elem.duration.indexOf('min') !== -1) {\n minutes = parseInt(elem.duration.substring(elem.duration.length - 5, elem.duration.length - 3), 10);\n }\n return Object.assign({}, elem, { duration: hours + minutes });\n });\n}", "function turnHoursToMinutes (array) {\n let newArray = array.map(movie => {\n let newMovie = {\n title: movie.title,\n year: movie.year,\n director: movie.director,\n duration: movie.duration,\n genre: movie.genre,\n rate: movie.rate\n };\n if (newMovie.duration.indexOf(' ') >= 0) {\n let newTimes = newMovie.duration.split(' ');\n newMovie.duration = (parseInt(newTimes[0]) * 60) + parseInt(newTimes[1]);\n } else if (newMovie.duration.indexOf('h') >= 0) {\n newMovie.duration = parseInt(newMovie.duration) * 60;\n } else {\n newMovie.duration = parseInt(newMovie.duration);\n }\n return newMovie\n });\n return newArray\n}", "function turnHoursToMinutes(someArray) {\n\n let arrayCopy = JSON.parse(JSON.stringify(someArray));\n let hours = 0;\n let minutes = 0;\n\n arrayCopy.forEach(eachMovie => {\n let newArray = eachMovie.duration.split(\"\");\n //console.log(newArray);\n //console.log(newArray[0]*60);\n eachMovie.duration = (parseInt(newArray[0], 10)*60+(parseInt (newArray[3], 10)*10)+(parseInt(newArray[4], 10)))\n //console.log(arrayCopy);\n return arrayCopy\n })\n}", "function turnHoursToMinutes(moviesArray) {\n return moviesArray.map(function (elem) {\n var hours = 0;\n var minutes = 0;\n if (elem.duration.indexOf('h') !== -1) {\n hours = parseInt(elem.duration[0], 10) * 60;\n }\n if (elem.duration.indexOf('min') !== -1) {\n minutes = parseInt(elem.duration.substring(elem.duration.length - 5, elem.duration.length - 3), 10);\n }\n return Object.assign({}, elem, { duration: hours + minutes });\n });\n}", "function turnHoursToMinutes(movies) {\n\n\n if (movies.duration.includes(\"h\")) {\n let hours = movies.duration.slice(0, movies.duration.indexOf(\"h\"))\n } else {\n let hours = 0;\n }\n console.log(hours)\n}", "function turnHoursToMinutes(arr){\n /*var duration = arr.map(function(obj){\n return obj.duration.split(' ');\n });\n */ \n //erase(duration);\n\n //arr[i].duration\n for( var i =0; i < arr.length; i++){\n var durationEachFilm = arr[i].duration.split(' ');\n var result = erase(durationEachFilm).toString();\n arr[i].duration = result;\n }\n}", "function turnHoursToMinutes(time) {\n\n let finalArray = time.map((eachMovie) => {\n\n eachMovie = Object.assign({}, eachMovie);\n // console.log(eachMovie)\n const t = eachMovie.duration\n //console.log(t)\n\n if (t.includes('h') && t.includes('min')) {\n const h = Number(t.split('h')[0] * 60);\n const m = Number(t.split(' ')[1].split('min')[0]);\n const sum = h + m\n eachMovie.duration = sum\n //console.log(eachMovie)\n } else if (!t.includes('min')) {\n const h = Number(t.split('h')[0] * 60);\n eachMovie.duration = h\n //console.log(eachMovie)\n } else {\n const m1 = Number(t.split('min')[0]);\n eachMovie.duration = m1\n //console.log(eachMovie)\n }\n // console.log(eachMovie)\n return eachMovie\n })\n console.log(finalArray);\n\n return finalArray\n}", "function turnHoursToMinutes(arr) {\n let newArray = 0\n let duration = arr.map(movies => movies.duration)\n let pelisPorMinutos = []\n for (let i = 0; i < duration.length; i++) {\n let hours = duration[i].split(\" \");\n if (hours[0].indexOf('h') === -1) {\n hours[0] = '0h'\n }\n let hour = (hours[0]) ? parseInt(hours[0]) : 0; // if ternario\n let minutes = (hours[1]) ? parseInt(hours[1]) : 0;\n let totalMinutes = (hour * 60) + minutes;\n pelisPorMinutos.push(totalMinutes)\n };\n for (i = 0; i < arr.length; i++) {\n arr[i].duration = null\n }\n for (j = 0; j < pelisPorMinutos.length; j++) {\n arr[j].duration += pelisPorMinutos[j]\n\n }\n return newArray = arr\n\n}", "function turnHoursToMinutes(arr) {\n let durationMin = [];\n let movieTime = 0;\n //forma de fazer a cópia criando um novo array sem referenciar\n const newArr = JSON.parse(JSON.stringify(arr));\n durationMin = newArr.map(function (item, index) {\n //verificar se existe parâmetro de horas.\n //Se tiver, o indexOf vai retornar um valor acima de -1.\n //Se tiver o h, pegar o valor do inicio até o indice do h, que são as horas, e multiplica por 0.\n if (item.duration.indexOf('h') >= 0) {\n movieTime += item.duration.slice(0, item.duration.indexOf('h')) * 60;\n //se tiver minutos, pega o valor entre o espaço e o m e converte em numero, com a multiplicação por 1\n if (item.duration.indexOf('m') >= 0) {\n movieTime += 1 * item.duration.slice(item.duration.indexOf(' '), item.duration.indexOf('m'));\n }\n } else {\n // se nao tiver h, o valor do inicio até o indice de m será os minutos.\n // o 1* é pra converter rapidamente a string em numero.\n movieTime += 1 * item.duration.slice(0, item.duration.indexOf('m'));\n }\n //atribui o valor calculado para a duraçao de cada objeto\n item.duration = movieTime;\n //retorna o objeto, ou seja, o item.\n return item;\n });\n return durationMin;\n }", "function turnHoursToMinutes(arr){\n const newMoviesArr = arr.map(item => item)\n // console.log(newMoviesArr)\n \n newMoviesArr.forEach((item, i) => {\n if(typeof item.duration === 'string'){\n newMoviesArr[i].duration = (Number(newMoviesArr[i].duration[0]) * 60) + Number(newMoviesArr[i].duration.slice(-5, -3)) \n }\n })\n return newMoviesArr\n }", "function turnHoursToMinutes(moviesArray) {\n let result = moviesArray.map((movie) => {\n console.log(\"movie.genre : \" + movie.genre)\n return {\n title: movie.title,\n duration: stringToMinutes(movie.duration),\n genre: movie.genre\n }\n })\n \n return result\n \n }", "function turnHoursToMinutes(arr) {\n \n var finalArr = [];\n var newArr = arr.map(function(movie){\n var timeString = movie.duration;\n var timeStringArray = timeString.split(\" \");\n var hours;\n var minutes;\n if(timeStringArray.length === 1) {\n if(timeStringArray[0].indexOf('h') > 0) {\n minutes = 0;\n hours = parseInt(timeStringArray[0][0]);\n } else {\n hours = 0;\n minutes = parseInt(timeStringArray[0].split(\"m\")[0]);\n }\n } else {\n hours = parseInt(timeStringArray[0][0]);\n minutes = parseInt(timeStringArray[1].split(\"m\")[0]);\n } \n var newDuration = hours * 60 + minutes;\n return newDuration;\n }); \n \n arr.forEach(function(element, index) {\n var newElement = Object.assign({}, element); \n newElement.duration = newArr[index];\n finalArr.push(newElement);\n });;\n\n return finalArr;\n}", "function turnHoursToMinutes(array) {\n let movieArr = Array.from(array);\n let newDuration = 0;\n let splitDuration = [];\n for (i = 0; i <= movieArr.length - 1; i++) {\n splitDuration = movieArr[i].duration.split(\" \");\n if (splitDuration.length > 1) {\n newDuration = (parseInt(splitDuration[0]) * 60) + parseInt(splitDuration[1]);\n } else {\n newDuration = parseInt(splitDuration[0]) * 60;\n }\n movieArr[i].duration = newDuration;\n };\n return movieArr;\n}", "function turnHoursToMinutes(array) {\n function minutes(string) {\n let minutesTemplate = string.split(\" \");\n\n let time = 0;\n\n minutesTemplate.forEach(function(el) {\n if (el.includes(\"h\")) {\n time += parseInt(el) * 60;\n }\n if (el.includes(\"m\")) {\n time += parseInt(el);\n }\n });\n\n return time;\n }\n\n let moviesInMinutes = array.map(function(movie) {\n return {\n ...movie,\n duration: minutes(movie.duration)\n };\n });\n\n return moviesInMinutes;\n}", "function turnHoursToMinutes(array) {\n let copy = [...array]\n\n let duration = copy.map(eachMovie => {\n const copyArr = {\n ...eachMovie\n }\n if (eachMovie.duration.includes('min') && eachMovie.duration.includes('h')) {\n copyArr.duration = (eachMovie.duration[0] * 60) + parseInt(eachMovie.duration.substr(- 5, 2))\n return copyArr\n } else if (eachMovie.duration.includes('h')) {\n copyArr.duration = (eachMovie.duration[0] * 60)\n return copyArr\n } else if (eachMovie.duration.includes('min')) {\n copyArr.duration = parseInt(eachMovie.duration.substr(- 5, 2))\n return copyArr\n } else {\n copyArr.duration = 0\n return copyArr\n }\n });\n\n return duration\n\n}", "function turnHoursToMinutes() {\n let duration = \n}", "function turnHoursToMinutes (array){\n let newArray = array.map((movieContent)=>{\n let newMovieContent = {...movieContent};\n\n let hour = movieContent.duration.match(/[0-9]h/g);\n let min = movieContent.duration.match(/[0-9]+min/g);\n if(hour === null){\n hour = 0;\n }else{\n hour = parseInt(hour) * 60;\n }\n if(min === null){\n min = 0;\n }else{\n min = parseInt(min)\n }\n newMovieContent.duration = hour + min;\n return newMovieContent;\n });\n return newArray; \n }", "function turnHoursToMinutes(array) {\n // 1h 22min\n // 2h\n // 30min\n const hourRegex = /(\\d+)h/g\n const minuteRegex = /(\\d+)min/g\n const test = array.map(movie => {\n const hours = hourRegex.exec(movie.duration)[1]\n const minutes = minuteRegex.exec(movie.duration)[1]\n const cloneMovie = { ...movie }\n cloneMovie.duration = hours * 60 + minutes\n return cloneMovie\n })\n return test\n\n}", "function formatDuration(timeInMinutes)\r\n{\r\n var minutesInHour = 60;\r\n var hours = Math.floor(timeInMinutes / minutesInHour);\r\n var minutes = timeInMinutes % minutesInHour;\r\n \r\n return hours + \"h \" + minutes + \"m\";\r\n}", "function formatTime(duration) {\n\t\tlet hours = Math.floor(duration / 60 / 60);\n\t\tlet minutes = Math.floor(duration / 60 - hours * 60);\n\t\tlet seconds = Math.floor(duration - hours * 3600 - minutes * 60);\n\t\tif ( hours > 0 && minutes < 10 ) minutes = '0' + minutes;\n\t\tif ( seconds < 10 ) seconds = '0' + seconds;\n\t\tlet timeStack = hours > 0 ? [hours] : [];\n\t\ttimeStack.push(minutes, seconds);\n\t\treturn timeStack.join(':');\n\t}", "function turnHoursToMinutes(array) {\n\n let newList = JSON.stringify(array);\n newList = JSON.parse(newList);\n\n newList = newList.map(function (e) {\n\n let time = e.duration.split(\" \");\n let movieTime = 0;\n if (time.length === 2) {\n let nbHour = time[0].split(\"h\");\n let nbMin = time[1].split(\"min\");\n movieTime += (nbHour[0] * 60) + parseInt(nbMin[0]);\n } else {\n if (time[0].includes(\"h\")) {\n let nbHours = time[0].split(\"h\");\n movieTime += nbHours[0] * 60;\n } else {\n let nbMin = time[0].split(\"min\");\n movieTime += parseInt(nbMin);\n }\n }\n e.duration = movieTime;\n return e;\n });\n return newList;\n}", "timeConvert(numOfMins){\n // Divide the entered by 60 to return the value for hours\n let hours = numOfMins/60;\n let hoursRounded = Math.floor(hours);\n \n let mins = numOfMins%60;\n let minsRounded = Math.floor(mins);\n let minsConvert = minsRounded%60\n \n // Save the whole number(hours) and remainder returned into two separate variables\n let seconds = mins*60;\n let secondsRemainder = seconds%60;\n \n // Return all three values with a colon between each \n return hoursRounded + \":\" + minsConvert + \":\" + secondsRemainder; \n }", "function turnHoursToMinutes(myArray) {\n const newArray = JSON.parse(JSON.stringify(myArray))\n return newArray.map(movie => {\n\t\t\tconst time = movie.duration.split(/[\\s\\D]+/)\n\t\t\tif (movie.duration.indexOf(\"h\")>0)\n\t\t\t{\n\t\t\t\tmovie.duration = Number(time[0]*60) + Number(time[1])\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmovie.duration = Number(time[0])\n\t\t\t}\n\t\t\treturn movie\n\t\t})\n}", "convertDuration (seconds){\n let hours = Math.floor(seconds / 3600);\n seconds %= 3600;\n let minutes = Math.floor(seconds / 60);\n\n return hours+\"h \"+minutes+\"m\";\n }", "function timeConversion(duration) {\n const portions = [];\n duration = parseFloat(duration);\n const msInHour = 1000 * 60 * 60;\n const hours = Math.trunc(duration / msInHour);\n if (hours > 0) {\n portions.push(hours + ' Hours');\n duration = duration - (hours * msInHour);\n }\n\n const msInMinute = 1000 * 60;\n const minutes = Math.trunc(duration / msInMinute);\n if (minutes > 0) {\n portions.push(minutes + ' Minutes');\n duration = duration - (minutes * msInMinute);\n }\n\n const seconds = Math.trunc(duration / 1000);\n if (seconds > 0) {\n portions.push(seconds + ' Seconds');\n }\n\n return portions.join(' ');\n}", "function converstionTime(list) {\n // your code here..\n for (let j = 0; j < list.length; j++) {\n let hasil = []\n let temp = ''\n for (let i = 0; i < list[j][2].length; i++) {\n if (list[j][2][i] !== ':') {\n temp += list[j][2][i]\n } else {\n hasil.push(temp)\n temp = ''\n }\n }\n hasil.push(temp)\n\n let menitTotal = Number(hasil[0] * 60) + Number(hasil[1])\n list[j][2] = menitTotal\n }\n\n return list\n}", "function fancyTimeFormat(duration)\n{ \n // Hours, minutes and seconds\n var hrs = ~~(duration / 3600);\n var mins = ~~((duration % 3600) / 60);\n var secs = ~~duration % 60;\n\n // Output like \"1:01\" or \"4:03:59\" or \"123:03:59\"\n var ret = \"\";\n\n if (hrs > 0) {\n ret += \"\" + hrs + \":\" + (mins < 10 ? \"0\" : \"\");\n }\n\n ret += \"\" + mins + \":\" + (secs < 10 ? \"0\" : \"\");\n ret += \"\" + secs;\n return ret;\n}", "function fancyTimeFormat(duration)\n{ \n // Hours, minutes and seconds\n var hrs = ~~(duration / 3600);\n var mins = ~~((duration % 3600) / 60);\n var secs = ~~duration % 60;\n\n // Output like \"1:01\" or \"4:03:59\" or \"123:03:59\"\n var ret = \"\";\n\n if (hrs > 0) {\n ret += \"\" + hrs + \":\" + (mins < 10 ? \"0\" : \"\");\n }\n\n ret += \"\" + mins + \":\" + (secs < 10 ? \"0\" : \"\");\n ret += \"\" + secs;\n return ret;\n}", "function humanizeDuration(duration) {\n const months = duration.months();\n const weeks = duration.weeks();\n let days = duration.days();\n const hours = duration.hours();\n const minutes = duration.minutes();\n const seconds = duration.seconds();\n\n // console.log(duration);\n\n const str = [];\n\n if (weeks > 0) {\n const weekTitle = pluralize('week', weeks);\n str.push(`${weeks} ${weekTitle}`);\n }\n\n if (days > 0) {\n if (weeks > 0) days -= 7 * weeks;\n\n const dayTitle = pluralize('day', days);\n str.push(`${days} ${dayTitle}`);\n }\n\n if (hours > 0 && (weeks < 1 && days < 2)) {\n const hourTitle = pluralize('hour', hours);\n str.push(`${hours} ${hourTitle}`);\n }\n\n if (minutes > 0 && (weeks < 1 && days < 1)) {\n const minuteTitle = pluralize('minute', minutes);\n str.push(`${minutes} ${minuteTitle}`);\n }\n\n if (seconds > 0 && (weeks < 1 && hours < 1)) {\n const secondTitle = pluralize('second', seconds);\n str.push(`${seconds} ${secondTitle}`);\n }\n\n return str.join(' ');\n}", "function parseMovies(responseJson) {\n const showtimes = responseJson._embedded.showtimes;\n console.log(showtimes)\n let myMovies = [];\n showtimes.forEach(movieName => {\n return myMovies.push(movieName);\n })\n\n\nfunction combine(arr) {\n var combined = arr.reduce(function(result, item) {\n var current = result[item.movieName];\n result[item.movieName] = !current ? item : {\n movieName: item.movieName,\n showDateTimeLocal: current.showDateTimeLocal + ', ' + item.showDateTimeLocal,\n posterDynamic: item.media.posterDynamic,\n mpaaRating: item.mpaaRating,\n runTime: item.runTime,\n genre: item.genre,\n };\n \n//need to format HH:MM & conditional - if same time, only display once\n // let oldDate = Object.entries(showDateTimeLocal);\n // console.log(oldDate)\n \n return result;\n }, {});\n \n return Object.keys(combined).map(function(key) {\n return combined[key];\n });\n }\n \n \n\n var result = combine(myMovies);\n console.log(result);\n displayShowtimeResults(result)\n}", "timeConvert(numOfMins){\n //create a variable to for hours and make it round down and divide it by 3600 seconds\n var hours = Math.floor(numOfMins/3600);\n //create a variable for minutes. Once you get hours, then divide it by 60 minutes to get minutes\n var minutes = Math.floor((numOfMins % 3600)/60);\n //create a variable. Minutes divided by 60 seconds\n var seconds = minutes/60;\n //After calculation, make sure it returns the proper time format\n return hours + \":\" + minutes + \":\" + seconds;\n }", "function orderByDuration (movies){\n var moviesMinutes = movies.map(function(m){\n var hora = m.duration.slice(0,1);\n var min = m.duration.slice(3,5);\n var horaNum = parseInt(hora*60);\n var minNum = parseInt(min);\n if (horaNum == 0) m.duration = minNum;\n m.duration = horaNum + minNum;\n \n return m\n });\n \n var orden = movies.sort(function(a,b){\n if (a.duration>b.duration) return 1;\n if (a.duration<b.duration) return -1;\n if (a.duration === b.duration) return 0;\n });\n console.log(orden);\n }", "function displayDurationTime()\r\n\t{\r\n\t\t//display duration of the video in minutes and seconds - MinutesMinutes:SecondsSeconds\r\n\t\tlet minutes = Math.floor ( myVideo.duration / 60 ); //divides the current playback time by 60 & uses Math.floor to round the real number into an integer (whole number)\r\n\t\tlet seconds = Math.floor ( myVideo.duration % 60 ); //gets the remainder of the currentTime of the video and thus will represent the seconds - uses Math.floor to round the real number into an integer (whole number)\r\n\t\t\r\n\t\t//if statements; outcome differs depending on conditions\r\n\t\tif ( minutes < 10 )\r\n\t\t{\r\n\t\t\tminutes = \"0\" + minutes; //display time is less than 10 minutes: a zero is in front e.g. \"01:00\", instead of \"1:00\"\r\n\t\t} //end if statement\r\n\t\t\r\n\t\tif ( seconds < 10 )\r\n\t\t{\r\n\t\t\tseconds = \"0\" + seconds; //display time is less than 10 seconds: a zero is in front e.g. \"00:09\", instead of \"00:9\"\r\n\t\t} //end if statement\r\n\t\tdurationDisplay.setAttribute ( \"value\", ( minutes + \":\" + seconds) ); //sets value for durationDisplay to the minutes and seconds of the entire duration playback time\r\n\t}", "function convertMinutesToDuration (totalMinutes){\n\n var durationStr = \"\"; \n\n var numHours = parseInt (totalMinutes / 60);\n var numMinutes = parseInt(totalMinutes % 60);\n\n //alert ('h ' + numHours + ' m ' + numMinutes); \n\n if (numHours == 0){\n durationStr = ':' + numMinutes;\n }\n else {\n durationStr = numHours + \":\" + numMinutes; \n }\n return durationStr; \n}", "function formatDuration (seconds) {\n //year, day, hour, minute, second\n // convert seconds to each of the units of time\n let yr = seconds / 60 / 60 / 24 / 365; // min, hr, day, year\n let day = seconds / 60 / 60 / 24;\n let hr = seconds / 60 / 60;\n let min = seconds / 60;\n\n let yStr, dStr, hStr, mStr, sStr;\n yStr = dStr = hStr = mStr = sStr = ''; // initialize values of interest as blank strings\n\n let totalS = seconds; // tracking total seconds\n if (totalS === 0) {\n return 'now';\n }\n console.log(totalS);\n if (yr > 1) { // check if time divisible by year\n console.log('checking years')\n let iYr = Math.floor(yr); // rounded to lowest whole\n yStr = (iYr === 1) ? mStr = `${iYr} year` : mStr = `${iYr} years`; // depending on if the rounded down value is 1 or not\n totalS -= iYr*31536000 // subtract total years in seconds from total seconds\n if (totalS > 0) { // check remainder for days\n day = Math.floor(totalS / 86400); // find number of days remaining\n if (day > 1) {\n totalS -= day*86400;\n dStr = `${day} days`;\n } else if (day === 1) {\n totalS -= day*86400;\n dStr = `${day}} day`;\n }\n if (totalS > 0) { // check remainder for hours\n console.log('checking hr');\n hr = Math.floor(totalS / 3600);\n if (hr > 1) {\n totalS -= hr*3600;\n hStr = `${hr} hours`;\n } else if (hr === 1){\n totalS -= hr*3600;\n hStr = `${hr} hour`;\n }\n }\n if (totalS > 0) { //check remainder for minutes\n console.log('checking min');\n min = Math.floor(totalS / 60);\n if (min > 1) {\n totalS -= min*60;\n mStr = `${min} minutes`\n } else if (min === 1) {\n totalS -= min*60;\n mStr = `${min} minute`\n }\n }\n }\n if (totalS > 0) { // check remainder for seconds\n console.log('checking sec');\n sStr = `${totalS} seconds`;\n }\n if (totalS === 1) {\n sStr = `${totalS} second`;\n }\n }\n else if (yr === 1) { // if it is exactly 1 year\n yStr = `${yr} year`;\n }\n else { // <1 year\n if (day > 1) {\n let iDay = Math.floor(day); // rounded to lowest whole\n dStr = (iDay === 1) ? mStr = `${iDay} day` : mStr = `${iDay} days`; // depending on if the rounded down value is 1 or not\n totalS -= iDay*60*60*24 // subtract total days in seconds from total seconds\n if (totalS >0) { // check remainder for hours\n console.log('checking hr');\n hr = Math.floor(totalS / 3600);\n if (hr > 1) {\n totalS -= hr*3600;\n hStr = `${hr} hours`;\n } else if (hr === 1) {\n totalS -= hr*3600;\n hStr = `${hr} hour`;\n }\n }\n if (totalS > 0) { //check remainder for minutes\n console.log('checking min');\n min = Math.floor(totalS / 60);\n if (min > 1) {\n totalS -= min*60;\n mStr = `${min} minutes`;\n } else if (min === 1) {\n totalS -= min*60;\n mStr = `${min} minute`;\n }\n }\n if (totalS > 0) { // check remainder for seconds\n console.log('checking sec');\n sStr = `${totalS} seconds`;\n }\n if (totalS === 1) {\n sStr = `${totalS} second`;\n }\n } else if (day === 1) { // if it is exactly 1 year\n dStr = `${day} day`;\n }\n else { // <1 day\n if (hr > 1) {\n let iHr = Math.floor(hr); // rounded to lowest whole\n hStr = (iHr === 1) ? mStr = `${iHr} hour` : mStr = `${iHr} hours`; // depending on if the rounded down value is 1 or not\n totalS -= iHr*60*60 // subtract total days in seconds from total seconds\n if (totalS >= 0) { //check remainder for minutes\n console.log('checking min');\n min = Math.floor(totalS / 60);\n if (min > 1) {\n totalS -= min*60;\n mStr = `${min} minutes`\n } else if (min === 1) {\n totalS -= min*60;\n mStr = `${min} minute`\n }\n }\n if (totalS > 0) { // check remainder for seconds\n console.log('checking sec');\n sStr = `${totalS} seconds`;\n }\n if (totalS === 1) {\n sStr = `${totalS} second`;\n }\n } else if (hr === 1) { // if it is exactly 1 year\n hStr = `${hr} hour`;\n }\n else { // <1 hr\n if (min > 1) {\n let iMin = Math.floor(min); // rounded to lowest whole\n mStr = (iMin === 1) ? mStr = `${iMin} minute` : mStr = `${iMin} minutes`; // depending on if the rounded down value is 1 or not\n totalS -= iMin*60 // subtract total days in seconds from total seconds\n if (totalS > 1) { // check remainder for seconds\n console.log('checking sec');\n sStr = `${totalS} seconds`;\n }\n if (totalS === 1) {\n sStr = `${totalS} second`;\n }\n } else if (min === 1) { // if it is exactly 1 year\n mStr = `${min} minute`;\n }\n else { // <1 min\n if (seconds > 1) {\n sStr = `${seconds} seconds`\n } else {\n sStr = `${seconds} second`\n }\n }\n }\n }\n }\n\n console.log(totalS + ' seconds remaining'); // return total remaining seconds\n\n let strArr = [yStr,dStr,hStr,mStr,sStr];\n let finalArr = [];\n strArr.forEach((string)=> { // pushes non empty strings for next function\n if (string !== '') {\n finalArr.push(string);\n }\n });\n\n // let min = seconds / 60;\n // let hr = min / 60;\n // let day = hr / 24;\n // let yr = day / 365;\n return finalArr.join(', ').replace(/, ([^,]*)$/, ' and $1'); // regex replacing the last comma separated element with and instead of ', ';\n}", "function convertDuration(duration) {\n let timePieces = duration.split(' '); // split will divide the duration string into two strings (hours & minutes)\n \n // reduce to sum hours (in minutes) and minutes\n let minutes = timePieces.reduce((sum, onePiece) => {\n if (onePiece.includes('h')) {\n return sum + convertHours(onePiece); \n }\n return sum + convertMinutes(onePiece);\n }, 0);\n \n return minutes; // return total minutes\n }", "function turnHoursToMinutes(data){\n\n return data.slice(0).map(function(el){\n console.log\n let timeString = el.duration\n let splitString = timeString.split(' ')\n let timeHours = 0;\n let timeMinutes = 0;\n\n if(splitString.length==1){\n if(splitString[0].includes('h')){\n timeHours = splitString[0].replace('h', '') * 60\n }else if (splitString[0].includes('min')){\n timeMinutes = splitString[0].replace('min', '') * 1\n }\n }else{\n timeHours = splitString[0].replace('h', '') * 60\n timeMinutes = splitString[1].replace('min', '') * 1\n }\n \n let totalTimeMinutes = timeHours + timeMinutes\n return { duration: totalTimeMinutes }\n })\n}", "function fn() {\r\n let hours = Number.parseInt(counter / 3600);//\"Number.parseInt\" string ko no. mai convert kardega\r\n let RemSeconds = counter % 3600;\r\n let mins = Number.parseInt(RemSeconds / 60);\r\n let seconds = RemSeconds % 60;\r\n hours = hours < 10 ? `0${hours}` : hours;\r\n mins = mins < 10 ? `0${mins}` : mins;\r\n seconds = seconds < 10 ? `0${seconds}` : seconds;\r\n\r\n timings.innerText = `${hours}:${mins}:${seconds}`;\r\n counter++;\r\n }" ]
[ "0.8079936", "0.7859964", "0.7851876", "0.78014445", "0.77884597", "0.77884597", "0.77513224", "0.76728314", "0.7625841", "0.762416", "0.76172984", "0.7615136", "0.76059455", "0.7568617", "0.75211906", "0.75048834", "0.7458502", "0.74136585", "0.74086255", "0.74062926", "0.7402034", "0.7392849", "0.734769", "0.7339185", "0.7330952", "0.7330811", "0.73198223", "0.73146653", "0.7312648", "0.7269429", "0.7249298", "0.7230484", "0.72127306", "0.7199664", "0.71873087", "0.7172606", "0.71642923", "0.7160154", "0.7160154", "0.71543765", "0.7134193", "0.7131466", "0.7128741", "0.7123214", "0.7120088", "0.7097697", "0.7081762", "0.7077062", "0.70575064", "0.7053606", "0.70485806", "0.70454824", "0.70444334", "0.70426756", "0.7041327", "0.70374376", "0.70356035", "0.7035217", "0.70200133", "0.7015362", "0.70043856", "0.700351", "0.6984725", "0.6977682", "0.69705445", "0.696842", "0.6967839", "0.69457614", "0.6937755", "0.6934735", "0.69276416", "0.6923658", "0.68890744", "0.68871653", "0.6884202", "0.68541896", "0.6831039", "0.6689146", "0.66136694", "0.6531001", "0.65258086", "0.64980215", "0.64957327", "0.6474805", "0.6455107", "0.63946474", "0.63696045", "0.6340052", "0.63272274", "0.63272274", "0.63231695", "0.63197964", "0.6286528", "0.62791294", "0.62781537", "0.627521", "0.627063", "0.622821", "0.621428", "0.6214196" ]
0.68605906
75
This does all the d3 drawing, I wish we could just databind in aurelia but it seems to slow right now.
scaleUpdated() { this.pointCoords = this.data.map(d=>[this.xaxis.scale(d[0]), this.yscale(d[1])]); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "drawCanvas(arrData) {\n const W = +this.elements.$tags.contentWrap.getBoundingClientRect().width;\n const H = +this.panel.svgHeight;\n const dateFrom = this.range.from.clone();\n const dateTo = this.range.to.clone();\n\n // область визуализации с данными (график)\n const margin = this.elements.sizes.marginAreaVis;\n const widthAreaVis = W - margin.left - margin.right;\n const heightAreaVis = H - margin.top - margin.bottom;\n const heightRowBar = parseInt(heightAreaVis / arrData.length, 10);\n\n const xScaleDuration = d3.scaleTime()\n .domain([0, new Date(dateTo).getTime() - new Date(dateFrom).getTime()])\n .range([0, widthAreaVis]);\n\n const xScaleTime = d3.scaleTime()\n .domain([new Date(dateFrom).getTime(), new Date(dateTo).getTime()])\n .range([0, widthAreaVis]);\n\n const canvasElement = d3.select(document.createElement('canvas'))\n .datum(arrData) // data binding\n .attr('width', widthAreaVis)\n .attr('height', heightAreaVis);\n\n const context = canvasElement.node().getContext('2d');\n\n // clear canvas\n context.fillStyle = 'rgba(0,0,0, 0)';\n context.rect(0, 0, canvasElement.attr('width'), canvasElement.attr('height'));\n context.fill();\n\n let top = 0;\n const sizeDiv = 1; // dividing line\n\n _.forEach(arrData, (changes, i, arr) => {\n _.forEach(changes, (d) => {\n context.beginPath();\n context.fillStyle = d.color;\n context.rect(\n xScaleTime(d.start) < 0 ? 0 : xScaleTime(d.start),\n top, xScaleDuration(d.ms),\n arr.length - 1 !== i ? heightRowBar - sizeDiv : heightRowBar,\n );\n context.fill();\n context.closePath();\n });\n\n top += heightRowBar;\n });\n return canvasElement.node();\n }", "bindData(){\n this.itemg = this.gcenter.selectAll('.chart__slice-group')\n .data(this.pie(this.data), d => d.data[this.cfg.key]);\n\n // Set transition\n this.transition = d3.transition('t')\n .duration(this.cfg.transition.duration)\n .ease(d3[this.cfg.transition.ease]);\n }", "drawRect() {\n\n //Converting all the dataset objects in to integer\n for (var i = 0; i < this.dataset.length; i++) {\n this.dataset[i] = parseInt(this.dataset[i], 10);\n }\n\n //width of svg\n this.width = $(\".svgDiv\").width();\n\n //height of svg \n this.height = $(\".svgDiv\").height() / 1.5;\n\n //Small padding that will be at the start and end of the svg\n this.padding = (1.95 / 100) * this.width;\n\n //storing 'this' into 'that' so that we can use it inside a function\n var that = this;\n\n //radius of circle\n this.radius = (0.4 / 100) * this.width;\n\n //scaling the domain and range \n this.xScale = d3.scaleLinear()\n .domain([0, this.basepair])\n .range([this.padding, this.width - this.padding]);\n\n //creating x-axis\n this.x_axis = d3.axisBottom(this.xScale);\n\n //position of the x-axis in height\n this.xAxisTranslate = this.height / 2;\n\n //declare properties of svg\n this.svg = d3.select(this.element)\n .append(\"svg\")\n .attr(\"width\", this.width)\n .attr(\"height\", this.height)\n .attr(\"transform\", \"translate(0,20)\")\n .call(d3.zoom()\n .extent([[this.padding, 0], [this.width - this.padding, 0]])\n .scaleExtent([1,this.xScale.ticks()[1]]) //Max zoom will give us differece of 1 between ticls\n .translateExtent([[this.padding, 0], [this.width - this.padding, 0]])\n .on(\"zoom\", zoomed));\n\n //calling x-axiks \n this.gX = this.svg.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + this.xAxisTranslate + \")\")\n .call(this.x_axis);\n\n //If the user selects one or more enzymes\n if (this.dataset.length != 0) {\n\n //Add circle to the line\n this.circ = this.svg.selectAll(\"circle\")\n .data(this.dataset)\n .enter()\n .append(\"circle\")\n .attr(\"class\", \"cir\")\n .attr(\"cx\", function (d) { return (that.xScale(d)); })\n .attr(\"cy\", this.xAxisTranslate)\n .attr(\"r\", this.radius)\n .on(\"mouseover\", function (d) {\n d3.select(this)\n .transition()\n .duration(50)\n .style(\"cursor\", \"pointer\")\n .attr(\"r\", that.radius / 0.75)\n })\n\n .on(\"mouseout\", function (d) {\n d3.select(this)\n .transition()\n .duration(50)\n .style(\"cursor\", \"normal\")\n .attr(\"r\", that.radius)\n })\n .append(\"title\")\n .text((d) => d)\n .text();\n }\n\n\n //adding line at the end of the axis\n this.line = this.svg.append(\"line\") //adding line\n .attr(\"x1\", this.width - this.padding)//start point x\n .attr(\"x2\", this.width - this.padding)//end point of x\n .attr(\"y1\", this.xAxisTranslate - 5)//start point of y\n .attr(\"y2\", this.xAxisTranslate + 5)//end point of y\n .attr(\"stroke\", \"black\")//drawing with red line\n .attr(\"stroke-width\", 5)\n .attr(\"class\", \"endLine\")\n .append(\"title\")\n .text(this.basepair); //adding width to the line\n\n //function that will be called when the zoom occurs\n function zoomed() {\n //create new scale objects based on event\n that.new_xScale = d3.event.transform.rescaleX(that.xScale);\n\n //update axes\n that.gX.call(that.x_axis.scale(that.new_xScale));\n\n //If the user selects one or more enzymes\n if (that.dataset.length != 0) {\n that.svg.selectAll(\"circle\").data(that.dataset)\n .attr('cx', function (d) { return that.new_xScale(d) })\n .attr('cy', that.xAxisTranslate);\n }\n }\n\n $('<p class = \"para\">' + this.enzyme + ' cuts ' + this.phage + ' ' + this.dataset.length + ' times</p>').appendTo(this.element);\n $(\".para\").css(\"padding-left\", this.padding);\n\n }", "draw() {\n this._updateWidthHeight();\n\n this.initSvg();\n // bar char\n if (this.keysBar) {\n this.aggregateLabelsByKeys(this.selection, this.keysBar);\n }\n\n if (this.keysX && this.keysY) {\n this.aggregateValuesByKeys(this.selection, this.keysX, this.keysY);\n }\n\n this.barChart.draw();\n // scatterplot\n // this.scatter.draw();\n }", "setup(){\n let min = d3.min(this.data, d => parseInt(d[this.y_attribute]))\n let max = d3.max(this.data, d => parseInt(d[this.y_attribute])) //we here assume the max is highe than 0\n let padding = (max - min) * 0.05\n this.y = d3.scaleLinear()\n .domain([min - padding, max + padding])\n .range([this.AXIS_HEIGHT, this.label_height])\n \n this.y_mirrored = d3.scaleLinear()\n .domain([min - padding, max + padding])\n .range([this.label_height, this.AXIS_HEIGHT])\n //x scaling\n this.x = d3.scaleLinear()\n .domain([this.parent.year0, this.parent.year0 - this.parent.window])\n .range([this.X0, this.W])\n\n //scale to place the current g\n this.year_to_x_for_g = d3.scaleLinear()\n .domain([this.parent.oldest, this.parent.window])\n .range([this.X0, this.W - this.g_width])\n //drawn background color\n this.draw_background()\n\n // //finds current index and sets buffer\n this.set_current()\n this.update_current()\n\n\n this.distribution_graph = this.svg.append('g')\n .attr('transform', `rotate(90) translate(${this.label_height}, ${-this.X0})`)\n .attr('width', `${this.AXIS_HEIGHT - this.label_height}`)\n .attr('height', `${this.W / 4}`)\n\n this.update_graph() \n //g containing the circles\n this.circles = this.svg.append('g')\n .attr('width', this.g_width)\n .attr('height', this.AXIS_HEIGHT - this.label_height)\n .attr('transform', `translate(${this.year_to_x_for_g(this.parent.year0)}, ${this.label_height})`)\n\n // //draws the axis\n this.draw_axis()\n // //draws all the points\n this.update_points()\n // //draws the labels\n this.draw_label()\n\n this.info_rect = this.circles.append('g')\n .attr('class', 'info_box')\n .attr('height', this.info_box_height)\n .style('opacity', 0)\n\n\n }", "static draw(cfg, h, ls) {\n\n ls.d.forEach((item, j) => {\n\n let dFcn = h.configGen(this.point(), cfg, ls, item);\n let c = {\n d:dFcn(item),\n data:item,\n cfg:cfg,\n layerState:ls,\n target:'path',\n };\n\n let rv = h.configElement(c);\n let x = ls.sa.x(item) + (cfg.jitter?h.getDrawWidth(ls.sa.x(),Math.random()*cfg.jitter):0);\n rv.e.setAttribute('transform', `translate(${x} ${ls.sa.y(item)})`);\n\n // let type;\n // sym.forEach((s, i) => { // create composite symbols\n //\n // if (d3[`symbol${s}`])\n // type = d3[`symbol${s}`]; // from d3\n // else {\n // type = extra[s]; // extra from above\n // }\n //\n // var symbolGenerator = d3.symbol()\n // .type(type)\n // .size(ls.sa.size(item)**2);\n //\n // let id = `${ls.g.id}-${cfg.id}-${j}`\n // let attr = {\n // 'id':id,\n // \"d\":symbolGenerator(),\n // \"transform\":`translate(${x} ${y})`,\n // \"fill\":ls.sa.color(item),\n // ...h.parseCfgFill(ls.sa, item),\n // ...h.parseCfgStroke(ls.sa, item, cfg.stroke)\n // };\n //\n // h.eventRegister(id, ls.g.id, cfg.ev, {popup:{attr:attr, idx:j, title:cfg.title, data:ls.d}});\n // h.createElement(attr, 'path', ls.g);\n // });\n\n });\n }", "renderColor(dom_elements, data){\n\n // Save object (Color map) instance\n var self = this;\n\n // Update color map selected map (Moisture, Temperature, etc)\n self.selected_map = dom_elements.selected_map;\n\n //\n d3.selection.prototype.moveToFront = function(){\n return this.each(function(){\n this.parentNode.appendChild(this);\n });\n };\n\n // Define data array\n var data_f = new Array(self.x_interp * self.y_interp);\n\n // Get minimum and maximum of data to display\n var min_val = data.map['z_0'];\n var max_val = data.map['z_0'];\n for(var i = 0; i < Object.keys(data.map).length; i++){\n data_f[i] = data.map['z_'+i];\n if(data.map['z_'+i] < min_val){\n min_val = data.map['z_'+i];\n }\n if(data.map['z_'+i] > max_val){\n max_val = data.map['z_'+i];\n }\n }\n\n // Delete old color map information\n self.heatmap_svg.selectAll('path').remove();\n self.heatmap_svg.selectAll('defs').remove();\n for(var i = 0; i < self.x_interp*self.y_interp; i++){\n self.heatmap_svg.select('rect#node_acc_'+i).remove();\n self.heatmap_svg.select('line#arrow_line_'+i).remove();\n }\n\n // Add calibration rectangle depending on selected map (Moisture, Temperature, etc)\n if(self.selected_map == 'MoistureNode'){\n // Minimum moisture value: 0%\n // Maximum moisture value: 60%\n min_val = 0.0;\n max_val = 60.0;\n\n // Use normal color gradient for moisture\n self.calibration_svg.append('rect')\n .attr('id', 'calib_rect')\n .attr('width', self.svgWidth)\n .attr('height', 20)\n .style('fill', 'url(#svgGradient_normal)');\n }\n else if(self.selected_map == 'TemperatureNode'){\n // Minimum temperature value: 0 °C\n // Maximum temperature value: 30 °C\n min_val = 0.0;\n max_val = 30.0;\n\n // Use inverted color gradient for temperature\n self.calibration_svg.append('rect')\n .attr('id', 'calib_rect')\n .attr('width', self.svgWidth)\n .attr('height', 20)\n .style('fill', 'url(#svgGradient_inverted)');\n }\n else if(self.selected_map == 'AccelerationNode' || self.selected_map == 'ElevationNode' || self.selected_map == 'AzimuthNode'){\n // Minimum acceleration value: 0 °\n // Maximum acceleration value: 60 °\n min_val = 0.0;\n max_val = 60.0;\n\n // Use inverted color gradient for accelerations\n self.calibration_svg.append('rect')\n .attr('id', 'calib_rect')\n .attr('width', self.svgWidth)\n .attr('height', 17)\n .style('fill', 'url(#svgGradient_inverted)');\n }\n\n $('#less').text(min_val.toFixed(2) + '')\n $('#more').text(max_val.toFixed(2) + '')\n\n // Add color map depending on selected map (Moisture, Temperature, etc)\n if(self.selected_map == 'AccelerationNode' || self.selected_map == 'ElevationNode' || self.selected_map == 'AzimuthNode'){\n\n var rect_w = self.svgWidth/self.x_elements;\n var rect_h = self.svgHeight/self.y_elements;\n var thresholds = d3.range(0.0, 60.0);\n\n // Used for color map SVG definitions\n var defs = self.heatmap_svg.append('svg:defs');\n\n // Define arrow for inclination display\n var marker = defs.append('svg:marker')\n .attr('id', 'arrow')\n .attr('refX', 0)\n .attr('refY', 2)\n .attr('markerWidth', 15)\n .attr('markerHeight', 15)\n .attr('markerUnits', 'strokeWidth')\n .attr('orient', 'auto')\n .attr('fill', '#000');\n marker.append('path').attr('d', \"M0,0 L0,4 L6,2 z\");\n\n // Use inverted color for accelerations color map\n var color = d3.scaleLinear()\n .domain(d3.extent(thresholds))\n .interpolate(function() { return self.invert_scheme;});\n\n // Make color map for accelerations\n for(var i = 0; i < self.x_elements; i++){\n for(var j = 0; j < self.y_elements; j++){\n\n var force = data.nodes['node_'+(i+self.x_elements*j)]['AccelerationNode'];\n var elev = data.nodes['node_'+(i+self.x_elements*j)]['ElevationNode'];\n var azim = data.nodes['node_'+(i+self.x_elements*j)]['AzimuthNode'] * Math.PI/180.0;\n\n // Add rectangle as color map for accelerations\n self.heatmap_svg.append('rect')\n .attr('id', 'node_acc_'+(i+self.x_elements*j))\n .attr('x', rect_w*i)\n .attr('y', rect_h*j)\n .attr('width', rect_w)\n .attr('height', rect_h)\n .attr('fill', color(Math.abs(elev)));\n\n // Add arrow over color map for accelerations\n self.heatmap_svg.append('line')\n .attr('id', 'arrow_line_'+(i+self.x_elements*j))\n .attr('x1', rect_w*(i + 1/2))\n .attr('y1', rect_h*(j + 1/2))\n .attr('x2', rect_w*(i + 1/2) + elev/60 * rect_w/2 * Math.cos(azim))\n .attr('y2', rect_h*(j + 1/2) - elev/60 * rect_h/2 * Math.sin(azim))\n .attr('stroke-width', 3)\n .attr('stroke', 'black')\n .attr('marker-end', 'url(#arrow)');\n }\n }\n }\n else if(self.selected_map == 'MoistureNode'){\n\n var off_th = 50.9;\n var epsilon = 0.5;\n var thresholds = d3.range(min_val, max_val);\n var thresholds2 = d3.range(off_th-epsilon, off_th+epsilon);\n\n // Use normal color gradient for temperature\n var color = d3.scaleLinear()\n .domain(d3.extent(thresholds))\n .interpolate(function() { return d3.interpolateSpectral; });\n\n // Define contour for color map\n var contours = d3.contours()\n .size([self.x_interp, self.y_interp])\n .thresholds(thresholds);\n\n // Define contour for flooding area\n var contours2 = d3.contours()\n .size([self.x_interp, self.y_interp])\n .thresholds(thresholds2);\n\n // Select path svg elements\n var path_tmp = self.heatmap_svg.selectAll('path');\n\n // Add data to color map\n path_tmp.data(contours(data_f))\n .enter().append('path')\n .attr('d', d3.geoPath(d3.geoIdentity().scale(self.svgWidth / self.x_interp)))\n .attr('fill', function(d) { return color(d.value); });\n\n // Add data to flooding area region\n path_tmp.data(contours2(data_f))\n .enter().append('path')\n .attr('d', d3.geoPath(d3.geoIdentity().scale(self.svgWidth / self.x_interp)))\n .attr('stroke', 'black')\n .attr('stroke-width', 5)\n .attr('fill', 'none');\n\n // Add data to flooding area blinking region\n path_tmp.data(contours2(data_f))\n .enter().append('path')\n .attr('class', 'blink_me')\n .attr('d', d3.geoPath(d3.geoIdentity().scale(self.svgWidth / self.x_interp)))\n .attr('stroke', 'none')\n .attr('fill', 'rgba(0, 0, 255, 0.75)');\n }\n else{\n var thresholds = d3.range(min_val, max_val);\n var color = d3.scaleLinear()\n .domain(d3.extent(thresholds))\n .interpolate(function() { return self.invert_scheme; });\n var contours = d3.contours()\n .size([self.x_interp, self.y_interp])\n .thresholds(thresholds);\n self.heatmap_svg.selectAll('path')\n .data(contours(data_f))\n .enter().append('path')\n .attr('d', d3.geoPath(d3.geoIdentity().scale(self.svgWidth / self.x_interp)))\n .attr('fill', function(d) { return color(d.value); });\n }\n\n // Move to front if there's a tip and rectangle hovering\n for(var i = 0; i < self.x_elements*self.y_elements; i++){\n self.heatmap_svg.select('rect#node_'+i).moveToFront();\n }\n d3.select('#tip_rect').moveToFront();\n d3.select('#tip_text').moveToFront();\n d3.select('#tip_line').moveToFront();\n d3.select('#tip_circle').moveToFront();\n }", "function reDraw() {\n svg.selectAll('.land')\n .attr('d',path)\n svg.selectAll('.flow')\n .attr('d',path) \n svg.selectAll('.points')\n .attr('transform', function(d) {return 'translate(' + projection(d.coordinates) + ')';})\n svg.selectAll('.graticule')\n .attr('d',path)\n}", "function databind(data) {\n\n\tvar join = custom.selectAll('custom.circles')\n\t\t.data(data);\n\n\tvar enterSel = join.enter()\n\t\t.append('custom')\n\t\t.classed('circles', true)\n\t\t.attr('cx', function(d) { return d.x; })\n\t\t.attr('cy', -10)\n\t\t.attr('r', function(d) { return d.radius; })\n\t\t.attr('fillStyle', '#5892A9');\n\n\tjoin\n\t\t.merge(enterSel)\n\t\t.transition().duration(5000)\n\t\t.delay(function(d,i) { return (Math.random()*i) / nodes.pos.n * 1000; })\n\t\t.attr('fillStyle', function(d) { return d.colour; })\n\t\t.attr('cy', function(d) { return d.y; });\n\n\tvar exitSel = join.exit()\n\t\t.transition().duration(5000)\n\t\t.delay(function(d,i) { return (Math.random()*i) / nodes.pos.n * 1000; })\n\t\t.attr('cy', height + 10)\n\t\t.remove();\n\n} // databind()", "draw(data) {\n //clear the svg\n this.vis.selectAll(\"*\").remove();\n\n //our graph, represented through nodes and links\n let nodes = [];\n let links = [];\n\n //add our nodes\n //add the committee nodes\n let init_y = 0;\n Object.keys(data.committees || {}).forEach((key) => {\n nodes.push({id:\"c_\"+data.committees[key].id, name: data.committees[key].name, x: 300, fx: 300, y: init_y+=60});\n });\n\n //add the representative nodes\n init_y = 0;\n Object.keys(data.representatives || {}).forEach((key) => {\n nodes.push({id:\"r_\"+data.representatives[key].id, name: data.representatives[key].name,party:data.representatives[key].party, x:600, fx: 600, y: init_y+=60});\n });\n\n //add the bill nodes\n init_y = 0;\n Object.keys(data.bills || {}).forEach((key) => {\n nodes.push({id:\"b_\"+data.bills[key].bill_id, name: data.bills[key].name, bill:true, x: 900, fx: 900, y: init_y+=60});\n });\n\n //add our links\n //add the donation links between committees and representatives\n Object.keys(data.donations || {}).forEach((key) => {\n if(data.donations[key].source in data.committees && data.donations[key].destination in data.representatives){\n links.push({source:\"c_\"+data.donations[key].source, target: \"r_\"+data.donations[key].destination,thickness:data.donations[key].amount, status:data.donations[key].support == \"S\" ? 1 : 2});\n }\n });\n\n //add the vote links between representatives and bills\n Object.keys(data.votes || {}).forEach((key) => {\n if(data.votes[key].source in data.representatives && data.votes[key].destination in data.bills){\n links.push({source:\"r_\"+data.votes[key].source, target: \"b_\"+data.votes[key].destination, status:data.votes[key].position == \"Yes\" ? 1 : data.votes[key].position == \"No\" ? 2 : 3});\n }\n });\n\n //a scaling function that limits how think or thin edges can be in our graph\n let thicknessScale = d3.scaleLinear().domain([0,d3.max(data.donations,(d) => {return d.amount;})]).range([2, 20]);\n\n //function that calls our given context menu with the appropria parameters\n let contextMenu = (d) => {\n let event = d3.getEvent();\n event.preventDefault();\n this.nodeMenu(d, event);\n };\n\n //Create a force directed graph and define forces in it\n //Our graph is essentially a physics simulation between nodes and edges\n let force = d3.forceSimulation(nodes)\n .force(\"charge\", d3.forceManyBody().strength(250).distanceMax(300))\n .force('link', d3.forceLink(links).distance(0).strength(.1).id((d) => {return d.id;}))\n .force(\"collide\", d3.forceCollide().radius(30).iterations(2).strength(.7))\n .force(\"center\", d3.forceCenter())\n .force('Y', d3.forceY().y(0).strength(.001));\n //Draw the edges between the nodes\n let edges = this.vis.selectAll(\"line\")\n .data(links)\n .enter()\n .append(\"line\")\n .style(\"stroke-width\", (d) => { return thicknessScale(d.thickness); })\n .style(\"stroke\", (d) => {\n if(d.status == 1) {\n return \"Green\";\n } else if(d.status == 2) {\n return \"Purple\";\n }\n return \"White\";\n })\n .attr(\"marker-end\", \"url(#end)\");\n //Draw the nodes themselves\n let circles = this.vis.selectAll(\"circle\")\n .data(nodes)\n .enter()\n .append(\"circle\")\n .attr(\"r\", 20)\n .style(\"stroke\", \"black\")\n .style(\"fill\", (d) => {\n if(d.party == \"R\"){\n return d.color = \"#E64A19\"; //red\n } else if(d.party==\"D\"){\n return d.color = \"#1976D2\"; //blue\n } else {\n return d.color = \"#BCAAA4\"; //brown\n }\n })\n .on('contextmenu', contextMenu);\n //Draw text for all the nodes\n let texts = this.vis.selectAll(\"text\")\n .data(nodes)\n .enter()\n .append(\"text\")\n .attr(\"fill\", \"black\")\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", \"10px\")\n .html((d) => { return d.name; })\n .each((d, i, nodes) => { d.bbox = nodes[i].getBBox(); })\n .on('contextmenu', contextMenu);\n //Draw text background for all the nodes\n let textBGs = this.vis.selectAll(\"rect\")\n .data(nodes)\n .enter()\n .insert(\"rect\", \"text\")\n .attr(\"fill\", (d) => {return d.color;})\n .attr(\"width\", (d) => {return d.bbox.width+10})\n .attr(\"height\", (d) => {return d.bbox.height+10})\n .on('contextmenu', contextMenu);\n\n //For every tick in our simulation, we update the positions for all ui elements\n force.on(\"tick\", () => {\n edges.attr(\"x1\", (d) => { return d.source.x; })\n .attr(\"y1\", (d) => { return d.source.y; })\n .attr(\"x2\", (d) => { return d.target.x; })\n .attr(\"y2\", (d) => { return d.target.y; });\n circles.attr(\"cx\", (d) => { return d.x; })\n .attr(\"cy\", (d) => { return d.y; })\n texts.attr(\"transform\", (d) => { return \"translate(\" + (d.party || d.bill ? d.x : d.x-d.bbox.width) + \",\" + (d.y+(d.bbox.height/4)) + \")\"; });\n textBGs.attr(\"transform\", (d) => { return \"translate(\" + (d.party || d.bill ? d.x-5 : d.x-d.bbox.width-5) + \",\" + (d.y-(d.bbox.height*.5)-5) + \")\"; });\n }); // End tick func\n\n //zoom and pan our graph such that all elements are visible\n setTimeout(() => {this.zoomTo(this.vis)}, 500);\n }", "display(data){\n var plot = this.scrollVis();\n d3.select(\"#vis\")\n .datum(data)\n .call(plot)\n\n var scroll = this.scroller(this.refs.scrollWindow)\n .container(d3.select('#graphic'));\n\n scroll(d3.selectAll('.step'));\n\n scroll.on('active', function (index){\n d3.selectAll('.step')\n .style('opacity', function(d,i) {return i === index ? 1: 0.1;});\n\n plot.activate(index)\n })\n\n scroll.on('progress', function (index, progress) {\n plot.update(index, progress);\n })\n\n return(plot)\n\n}", "_draw(callback) {\n super._draw(callback);\n\n const height = this._height - this._margin.top - this._margin.bottom,\n width = this._width - this._margin.left - this._margin.right;\n\n const diameter = Math.min(height, width);\n const transform = `translate(${(width - diameter) / 2}, ${(height - diameter) / 2})`;\n\n let nestedData = nest();\n for (let i = 0; i <= this._drawDepth; i++) nestedData.key(this._groupBy[i]);\n nestedData = nestedData.entries(this._filteredData);\n\n const packData = this._pack\n .padding(this._layoutPadding)\n .size([diameter, diameter])(\n hierarchy({key: nestedData.key, values: nestedData}, d => d.values).sum(this._sum).sort(this._sort)\n )\n .descendants();\n\n packData.forEach((d, i) => {\n d.__d3plus__ = true;\n d.i = i;\n d.id = d.parent ? d.parent.data.key : null;\n d.data.__d3plusOpacity__ = d.height ? this._packOpacity(d.data, i) : 1;\n d.data.__d3plusTooltip__ = !d.height ? true : false;\n });\n\n this._shapes.push(\n new Circle()\n .data(packData)\n .select(\n elem(\"g.d3plus-Pack\", {\n parent: this._select,\n enter: {transform},\n update: {transform}\n }).node()\n )\n .config(configPrep.bind(this)(this._shapeConfig, \"shape\", \"Circle\"))\n .render()\n );\n\n return this;\n }", "function build(dataset, elementToBind, cfg) {\n var container = d3.select(elementToBind),\n width = container.node().getBoundingClientRect().width,\n height = container.node().getBoundingClientRect().height,\n tau = 2 * Math.PI,\n formatPercent = d3.format(\".0%\");\n\n \n\n var data = dataset;\n var arc = d3.arc()\n .startAngle(0)\n .endAngle(function (d) {\n return d.percentage / 100 * tau;\n })\n .innerRadius(function (d) { \n return config.innerRadius[d.index];\n })\n .outerRadius(function (d) {\n return config.outerRadius[d.index];\n });\n\n //Create the opaque background ring\n var background = d3.arc()\n .startAngle(0)\n .endAngle(tau)\n .innerRadius(function (d, i) {\n return config.innerRadius[i];\n })\n .outerRadius(function (d, i) {\n return config.outerRadius[i];\n });\n\n //Append the background ring to the body\n var svg = d3.select(elementToBind)\n .append('svg')\n .attr('width', '100%')\n .attr('height', '100%')\n .attr('viewBox', '0 0 ' + Math.min(width, height) + ' ' + Math.min(width, height))\n .attr('preserveAspectRatio', 'xMinYMin')\n .append('g')\n .attr('transform', 'translate(' + Math.min(width, height) / 2 + ',' + Math.min(width, height) / 2 + ')');\n\n\n\n //enter the data set and loop through it\n var field = svg.selectAll('g')\n .data(dataset)\n .enter().append('g');\n\n //Attach the filled in progress path\n field.append('path').attr('class', 'bg')\n .attr(\"fill\", '#e9eef4')\n .attr(\"d\", background);\n\n field.append('path')\n .attr('class', 'progress')\n .style(\"fill\", function (d) {\n return colors[d.index];\n });\n \n // d3.transition().duration(1750).each(update);\n \n\n var description1 = field.append('text')\n .attr('text-anchor', 'middle')\n .attr('class', 'description_text description_text_01')\n .attr('dx', '4px')\n .attr('dy', '-5px');\n\n var description2 = field.append('text')\n .attr('text-anchor', 'middle')\n .attr('class', 'description_text description_text_02')\n .attr('dx', '4px')\n .attr('dy', '25px');\n\n function update() {\n field = field\n .each(function (d) {\n this._value = d.percentage;\n })\n .data(dataset)\n .each(function (d) {\n d.previousValue = this._value;\n });\n field.selectAll('path.progress')\n .transition()\n .duration(function(d) {\n return d.percentage * 25\n })\n .delay(50)\n .ease(d3.easeSin)\n .attrTween(\"d\", arcTween);\n\n /*field.select(\"text.icon\").text(function (d) {\n return d.icon;\n })\n .attr(\"transform\", function (d) {\n return \"translate(5,\" + -((innerRadius + 7) - d.index * (30 + gap)) + \")\"\n \n });\n \n field.select(\"text.completed\").text(function (d) {\n return Math.round(d.percentage / 100 * 10);\n });*/\n }\n\n function arcTween(d) {\n var i = d3.interpolateNumber(0, d.percentage);\n return function (t) {\n d.percentage = i(t);\n description1.text(formatPercent(data[0].percentage / 100));\n description2.text(formatPercent(data[1].percentage / 100));\n return arc(d);\n };\n }\n update();\n }", "drawChart () {\r\n\t\t\r\n\t\t// Converts color range value (eg. 'red', 'blue') into the appropriate color array\r\n\t\tthis.colorRange = this.convertColorRange(this.colorRange);\r\n\r\n\t\t// Set width and height of graph based on size of bounding element and margins\r\n\t\tvar width = document.getElementById(this.elementName).offsetWidth - this.marginLeft - this.marginRight;\r\n\t\tvar height = document.getElementById(this.elementName).offsetHeight - this.marginTop - this.marginBottom;\r\n\r\n\t\t// Create axis, streams etc.\t\t\r\n\t\tvar x = d3.time.scale()\r\n\t\t\t.range([0, width]);\r\n\r\n\t\tvar y = d3.scale.linear()\r\n\t\t\t.range([height - 10, 0]);\r\n\r\n\t\tvar z = d3.scale.ordinal()\r\n\t\t\t.range(this.colorRange);\r\n\r\n\t\tvar xAxis = d3.svg.axis()\r\n\t\t\t.scale(x)\r\n\t\t\t.orient('bottom')\r\n\t\t\t.ticks(d3.time.years);\r\n\r\n\t\tvar yAxis = d3.svg.axis()\r\n\t\t\t.scale(y);\r\n\r\n\t\tvar stack = d3.layout.stack()\r\n\t\t\t.offset('silhouette')\r\n\t\t\t.values(function (d) { return d.values; })\r\n\t\t\t.x(function (d) { return d.date; })\r\n\t\t\t.y(function (d) { return d.value; });\r\n\r\n\t\tvar nest = d3.nest()\r\n\t\t\t.key(function (d) { return d.key; });\r\n\r\n\t\tvar area = d3.svg.area()\r\n\t\t\t.interpolate('cardinal')\r\n\t\t\t.x(function (d) { return x(d.date); })\r\n\t\t\t.y0(function (d) { return y(d.y0); })\r\n\t\t\t.y1(function (d) { return y(d.y0 + d.y); });\r\n\t\r\n\t\t// Create SVG area of an appropriate size\r\n\t\tvar svg = d3.select(this.element).append('svg')\r\n\t\t\t.attr('width', width + this.marginLeft + this.marginRight)\r\n\t\t\t.attr('height', height + this.marginTop + this.marginBottom)\r\n\t\t\t.append('g')\r\n\t\t\t.attr('transform', 'translate(' + this.marginLeft + ',' + this.marginTop + ')');\r\n\r\n\t\t// Read CSV file\r\n\t\td3.csv(this.csvfile, function (data) {\r\n\t\t\tvar format = d3.time.format('%Y-%m-%d');\r\n\t\t\tdata.forEach(function (d) {\r\n\t\t\t\td.date = format.parse(d.date);\r\n\t\t\t\td.value = +d.value;\r\n\t\t\t});\r\n\r\n\t\t\tvar layers = stack(nest.entries(data));\r\n\r\n\t\t\tx.domain(d3.extent(data, function (d) { return d.date; }));\r\n\t\t\ty.domain([0, d3.max(data, function (d) { return d.y0 + d.y; })]);\r\n\r\n\t\t\t// Apply data to graph\r\n\t\t\tsvg.selectAll('.layer')\r\n\t\t\t\t.data(layers)\r\n\t\t\t\t.enter().append('path')\r\n\t\t\t\t.attr('class', 'layer')\r\n\t\t\t\t.attr('d', function (d) { return area(d.values); })\r\n\t\t\t\t.style('fill', function (d, i) { return z(i); });\r\n\r\n\t\t\t// Add a black outline to streams\r\n\t\t\tsvg.selectAll('.layer')\r\n\t\t\t\t.attr('stroke', 'black')\r\n\t\t\t\t.attr('stroke-width', '0.5px');\r\n\r\n\t\t\tsvg.append('g')\r\n\t\t\t\t.attr('class', 'x axis')\r\n\t\t\t\t.attr('transform', 'translate(0,' + height + ')')\r\n\t\t\t\t.call(xAxis);\r\n\r\n\t\t\tsvg.append('g')\r\n\t\t\t\t.attr('class', 'y axis')\r\n\t\t\t\t.attr('transform', 'translate(' + width + ', 0)')\r\n\t\t\t\t.call(yAxis.orient('right'));\r\n\r\n\t\t\tsvg.append('g')\r\n\t\t\t\t.attr('class', 'y axis')\r\n\t\t\t\t.call(yAxis.orient('left'));\r\n\r\n\t\t\t// Other streams fade when one stream is hovered over with the cursor\r\n\t\t\tsvg.selectAll('.layer')\r\n\t\t\t\t.attr('opacity', 1)\r\n\t\t\t\t.on('mouseover', function (d, i) {\r\n\t\t\t\t\tsvg.selectAll('.layer').transition()\r\n\t\t\t\t\t\t.duration(250)\r\n\t\t\t\t\t\t.attr('opacity', function (d, j) {\r\n\t\t\t\t\t\t\treturn j !== i ? 0.2 : 1;\r\n\t\t\t\t\t\t});\r\n\t\t\t\t})\r\n\r\n\t\t\t\t// Move the label which appears next to the cursor.\r\n\t\t\t\t.on('mousemove', function (d, i) {\r\n\t\t\t\t\tvar mousePos = d3.mouse(this);\r\n\t\t\t\t\tvar mouseX = mousePos[0];\r\n\t\t\t\t\tvar mouseY = mousePos[1];\r\n\t\t\t\t\tvar mouseElem = document.getElementById('besideMouse');\r\n\t\t\t\t\tdocument.getElementById('besideMouse').style.left = mouseX + 50 + 'px';\r\n\t\t\t\t\tmouseElem.style.top = mouseY - 10 + 'px';\r\n\t\t\t\t\tmouseElem.innerHTML = d.key;\r\n\t\t\t\t})\r\n\t\t\t\r\n\t\t\t\t// Set opacity back to 1 when the cursor is no longer hovering over a stream.\r\n\t\t\t\t.on('mouseout', function (d, i) {\r\n\t\t\t\t\tsvg.selectAll('.layer')\r\n\t\t\t\t\t\t.transition()\r\n\t\t\t\t\t\t.duration(250)\r\n\t\t\t\t\t\t.attr('opacity', '1');\r\n\t\t\t\t\tdocument.getElementById('besideMouse').innerHTML = '';\r\n\t\t\t\t});\r\n\t\t});\r\n\t}", "componentDidMount() {\n\n this.svg = d3.select(this.refs.svg);\n\n this._plotChina();\n this._addMarkup();\n this._listenForResize();\n this._listenForMove();\n\n }", "render() {\n const total = this.values.reduce((a, b) => a + b, 0);\n\n const rest = 100 - total;\n const dataset = rest > 0 ? [...this.values, rest] : this.values;\n\n this._renderSvg();\n this._renderGroups(dataset, rest);\n this._renderRects(dataset);\n this._renderMarkers();\n }", "function create_deriv_view() {\n var deriv_vis = null;\n var deriv_x = null;\n var deriv_y = null;\n $(__div_memderiv).css(\"border\", \"solid green 2px\"); \n __vS.addListener(\"init\", function(eventname, event, caller) {\n __db.f_counts(function(counts) { \n var xmax = counts.event-1,\n ymax = Math.round(counts.max_addr / 1024),\n w = 450,\n h = 450,\n p = 20;\n\n deriv_x = d3.scale.linear().domain([0,xmax]).range([0, w]);\n deriv_y = d3.scale.linear().domain([0,ymax]).range([h, 0]);\n\n deriv_vis = d3.select(__div_memderiv).append(\"svg\")\n .attr(\"width\", w + p * 2)\n .attr(\"height\", h + p * 2)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + p + \",\" + p + \")\");\n/*\n var xrule = deriv_vis.selectAll(\"g.x\")\n .data(deriv_x.ticks(10))\n .enter().append(\"g\")\n .attr(\"class\", \"x\");\n\n xrule.append(\"line\")\n .attr(\"x1\", deriv_x)\n .attr(\"x2\", deriv_x)\n .attr(\"y1\", 0)\n .attr(\"y2\", h);\n\n xrule.append(\"text\")\n .attr(\"x\", deriv_x)\n .attr(\"y\", h + 3)\n .attr(\"dy\", \".71em\")\n .attr(\"text-anchor\", \"middle\")\n .text(deriv_x.tickFormat(10));\n*/\n var yrule = deriv_vis.selectAll(\"g.y\")\n .data(deriv_y.ticks(10))\n .enter().append(\"g\")\n .attr(\"class\", \"y\");\n\n yrule.append(\"line\")\n .attr(\"x1\", 0)\n .attr(\"x2\", w)\n .attr(\"y1\", deriv_y)\n .attr(\"y2\", deriv_y);\n\n yrule.append(\"text\")\n .attr(\"x\", -3)\n .attr(\"y\", deriv_y)\n .attr(\"dy\", \".35em\")\n .attr(\"text-anchor\", \"end\")\n .text(deriv_y.tickFormat(10));\n\n deriv_vis.append(\"rect\")\n .attr(\"width\", w)\n .attr(\"height\", h);\n });\n });\n\n __vS.addListener(\"frameslider_change\", function(eventname, event, caller) { \n __db.f_memderiv(event, function(data) {\n deriv_vis.data(data.events).append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"d\", d3.svg.line()\n .x(function(d) { return deriv_x(d.index); })\n .y(function(d) { return deriv_y(d.delta); }));\n /*lines.transition().duration(0)\n .attr(\"class\", \"line\")\n .attr(\"d\", d3.svg.line()\n .x(function(d) { return deriv_x(d.index); })\n .y(function(d) { return deriv_y(d.delta); }));*/\n\n var points = deriv_vis.selectAll(\"circle.line\")\n .data(data.events);\n points.enter().append(\"circle\")\n .attr(\"class\", \"line\")\n .attr(\"cx\", function(d) { return deriv_x(d.index); })\n .attr(\"cy\", function(d) { return deriv_y(d.delta); })\n .attr(\"r\", 3.5)\n points.transition().duration(0)\n .attr(\"class\", \"line\")\n .attr(\"cx\", function(d) { return deriv_x(d.index); })\n .attr(\"cy\", function(d) { return deriv_y(d.delta); })\n .attr(\"r\", 3.5)\n points.exit().remove();\n });\n });\n }", "function draw() {\n\n /*\n * Resize canvas in accordance with size of parent container\n */\n scope.defaultWidth = scope.width;\n scope.width = element[0].clientWidth;\n if (scope.width === 0) {\n scope.width = element[0].parentElement.clientWidth;\n if (scope.width === 0)\n scope.width = scope.defaultWidth; // fallback to passed in width\n }\n\n scope.defaultHeight = scope.height;\n scope.height = element[0].clientHeight;\n if (scope.height === 0) {\n scope.height = element[0].parentElement.clientHeight;\n if (scope.height === 0)\n scope.height = scope.defaultHeight; // fallback to passed in height\n }\n\n svg.attr(D3V.CSS_WIDTH, scope.width)\n .attr(D3V.CSS_HEIGHT, scope.height);\n\n /*\n * clear the elements inside of the directive\n */\n svgGroup.selectAll(SYNTAX.STAR).remove();\n\n var treeData = initNode(scope.vdbEntry);\n\n /*\n * Assign the selection listener to the click event of the svg\n * Call an initial zoom on the svg\n */\n svg.on(D3V.HTML_CLICK, selectionCallback).call(zoomListener);\n\n root = treeData;\n\n // Will call update\n expandCollapseChildCallback(root);\n }", "function draw() {\n console.log(\"Drawing function\")\n\n // + FILTER DATA BASED ON STATE\n const filteredData = state.data\n .filter(d => {\n if (state.selectStatus == \"All\") return true\n else return d.stroke == state.selectStatus\n })\n\n var symbol = d3.symbol();\n\n svg.selectAll(\"circle\")\n .data(filteredData, d => d.id)\n .join(\n enter => enter.append(\"circle\")\n .attr(\"r\", radius)\n .attr(\"cy\", margin.top)\n // .attr(\"opacity\", \"0.5\")\n .attr(\"fill\", d => {\n if (d.stroke == \"Had stroke\") return \"#fc3232\"\n else return \"rgba(0,70,274, 0.3)\"\n })\n .call(enter => enter.transition()\n .duration(1500)\n .attr(\"cy\", d => yScale(d.bmi))\n )\n ,\n update => update,\n exit => exit.remove()\n )\n // .attr(\"r\", radius)\n // .attr(\"cx\", d => xScale(d.age))\n .attr(\"cx\", d => xScale(d.age))\n\n // const dot = svg\n // .selectAll(\"circle\")\n // .data(filteredData, d => d.name)\n // .join(\n // enter => enter, // + HANDLE ENTER SELECTION\n // update => update, // + HANDLE UPDATE SELECTION\n // exit => exit // + HANDLE EXIT SELECTION\n // );\n}", "drawPlot(){\n\n // Insert HTML elements\n\n d3.select(\".dataviz-element\").remove(); // remove old element\n d3.select(\".viz-header\").remove(); // remove old header\n const container = d3.select(\".dataviz-elements\");\n const header = container.append(\"div\")\n .attr(\"class\", \"dataviz-element\")\n .attr(\"id\", \"dataviz-scatterplot\")\n .append(\"div\")\n .attr(\"class\", \"viz-header--scatterplot\");\n header.append(\"div\")\n .attr(\"class\", \"viz-header__text--scatterplot\")\n .html(\"Scatterplot</br>\")\n .append(\"text\")\n .text(\"Click to view building on map.\");\n\n // Create svg\n\n d3.select('#dataviz-scatterplot').append('div').attr('id', 'chart-view');\n let mainSvg=d3.select('#chart-view')\n .append('svg').classed('plot-svg', true)\n .attr(\"width\", this.width + this.margin.left + this.margin.right)\n .attr(\"height\", this.height + this.margin.top + this.margin.bottom);\n\n mainSvg.attr('xlmns','http://www.w3.org/2000/svg').attr('xmlns:xlink','http://www.w3.org/1999/xlink').append('filter').attr('id','shadow').append('feGaussianBlur').attr('in','SourceGraphic').attr('stdDeviation',3)\n mainSvg.append('g').attr('id','BG_g').append('rect').attr('x','1%').attr('y','1%')\n .attr('width','98%').attr('height','98%')\n .style('filter','url(#shadow)').style('fill','#a2a2a2').classed('BG_rect',true);\n mainSvg.select('#BG_g').append('rect').attr('x','2%').attr('y','2%')\n .attr('width','96%').attr('height','96%')\n .style('fill','#d9d9d9').classed('BG_rect',true);\n d3.select('#chart-view').select('.plot-svg').append('g').classed(\"brush\", true);\n let svgGroup = d3.select('#chart-view').select('.plot-svg').append('g').classed('wrapper-group', true);\n\n // Add axes\n\n svgGroup.append('g').attr('id', 'axesX');\n svgGroup.append('g').attr('id', 'axesY');\n svgGroup.append('text').attr('id', 'axesXlabel').attr('x',0).attr('y',0)\n svgGroup.append('text').attr('id', 'axesYlabel').attr('x',0).attr('y',0)\n\n // Create dropdown panel\n\n let dropdownWrap = d3.select('#chart-view').append('div').classed('dropdown-wrapper', true);\n let cWrap = dropdownWrap.append('div').classed('dropdown-panel', true);\n\n // Add legend and axis labels\n\n cWrap.append('div').classed('c-label', true)\n .append('text')\n .text('Circle Size').classed('SP_DD_text',true);\n\n cWrap.append('div').attr('id', 'dropdown_c').classed('dropdown', true).append('div').classed('dropdown-content', true)\n .append('select');\n\n let xWrap = dropdownWrap.append('div').classed('dropdown-panel', true);\n\n xWrap.append('div').classed('x-label', true)\n .append('text')\n .text('X Axis Data').classed('SP_DD_text',true);\n\n xWrap.append('div').attr('id', 'dropdown_x').classed('dropdown', true).append('div').classed('dropdown-content', true)\n .append('select');\n\n let yWrap = dropdownWrap.append('div').classed('dropdown-panel', true);\n\n yWrap.append('div').classed('y-label', true)\n .append('text')\n .text('Y Axis Data').classed('SP_DD_text',true);\n\n yWrap.append('div').attr('id', 'dropdown_y').classed('dropdown', true).append('div').classed('dropdown-content', true)\n .append('select');\n\n d3.select('#chart-view')\n .append('div')\n .classed('circle-legend', true)\n .append('svg').attr('width', 250)\n .append('g').classed('sizeLegend',true)\n .attr('transform', 'translate(0, 0)');\n d3.select('#chart-view')\n .select('.circle-legend').select('svg')\n .append('g').classed('typeLegend',true);\n\n // Draws default scatterplot and dropdown behavior\n\n this.updatePlot('DamageRatio', 'GroundAcceleration(m/s2)', 'Stories')\n this.drawDropDown('DamageRatio', 'GroundAcceleration(m/s2)', 'Stories')\n this.lineRender()\n\n }", "function draw() {\n svg.select(\"g.x.axis\").call(xAxis);\n svg.select(\"g.y.axis\").call(yAxis);\n svg.select(\"path.area\").attr(\"d\", area);\n svg.select(\"path.line\").attr(\"d\", line);\n //svg.select(\"g.circles\").attr(\"d\", circle);\n\n\n}", "drawChart () {\n this.chartHeight = 340 // Chart height\n this.chartWidth = 900 // Chart width\n\n this.chartMargin = { // Chart margins\n top: 30,\n right: 30,\n bottom: 30,\n left: 30\n }\n\n // Grab the chart div and add the viewBox to the page.\n this.chartSVG = d3 \n .select('#d3chart')\n .append('svg')\n .attr('viewBox', `0 -20 ${this.chartWidth} ${this.chartHeight}`)\n .attr('preserveAspectRatio', 'xMinYMin meet')\n .append('text')\n .text('D3 Content Here')\n\n this.createScales()\n this.createAxes()\n this.createGrids()\n this.addAxes()\n this.addGridLines()\n this.addDataVisuals()\n this.addHighlighTooltip()\n this.addHighlightListeners()\n this.addLegend()\n }", "setUp() {\n this.g = d3\n .select(this.root)\n .append(\"g\");\n this.update();\n }", "drawChart() {\n let margin = {top: 20, right: 20, bottom: 30, left: 40},\n width = this.props.width - margin.left - margin.right,\n height = this.props.height - margin.top - margin.bottom;\n\n // set up to adjust width of nodes based on cost/time\n const maxWidth = Math.max(...Object.values(this.props.nodeWidths));\n\n // create faux DOM\n const div = new ReactFauxDOM.Element('div')\n\n let svg = d3.select(div).append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", `translate(${margin.left},${margin.top})`);\n\n var formatNumber = d3.format(\",.0f\"),\n format = function(desc, val) { return \"\\n\" + desc + \": \" + formatNumber(val); };\n\n var sankey = d3sankey.sankey()\n .nodeWidth(15)\n .nodePadding(10)\n .extent([[1, 1], [width - 1, height - 6]]);\n\n var link = svg.append(\"g\")\n .attr(\"class\", \"links\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke-opacity\", 0.2)\n .selectAll(\"path\");\n\n var node = svg.append(\"g\")\n .attr(\"class\", \"nodes\")\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-size\", 10)\n .selectAll(\"g\");\n\n sankey(this.props.data);\n\n node = node\n .data(this.props.data.nodes)\n .enter().append(\"g\");\n\n node.append(\"polygon\")\n .attr(\"points\", function(d) { return this._getTrapezoidCoordinates(d, maxWidth); }.bind(this))\n .attr(\"fill\", function(d) { return this._getColorForNode(d.id); }.bind(this))\n // .attr(\"stroke\", \"#000\")\n .on(\"click\", function(d) { this.props.onFocusNodeChange(d.id); }.bind(this));\n\n node.append(\"text\")\n .attr(\"x\", function(d) { return d.x0 - 6; })\n .attr(\"y\", function(d) { return (d.y1 + d.y0) / 2; })\n .attr(\"dy\", \"0.35em\")\n .attr(\"text-anchor\", \"end\")\n .text(function(d) { return d.id; })\n .on(\"click\", function(d) { this.props.onFocusNodeChange(d.id); }.bind(this))\n .filter(function(d) { return d.x0 < width / 2; })\n .attr(\"x\", function(d) { return d.x1 + 6; })\n .attr(\"text-anchor\", \"start\");\n\n link = link\n .data(this.props.data.links)\n .enter().append(\"path\")\n .attr(\"d\", this._getCustomLinkHorizontal())\n .attr(\"stroke\", function(d) { return this._getColorForLink(d.source.id, d.target.id); }.bind(this))\n .attr(\"stroke-width\", function(d) { return Math.max(1, d.width); });\n\n link.append(\"title\")\n .text(function(d) { return d.source.id + \" → \" + d.target.id + format('Volume', d.value); });\n\n node.append(\"title\")\n .text(function(d) { return d.id + format('Input Volume', d.value) +\n format('Cost', this.props.nodeCosts[d.id]) +\n format('Time', this.props.nodeTimes[d.id]); }.bind(this));\n\n // export as actual DOM\n return div.toReact();\n }", "initVis(){\n let vis = this;\n\n // empty initial filters\n vis.filters = [];\n // Set a color for dots\n vis.color = d3.scaleOrdinal()\n // Adobe Color Analogous\n .range([\"#F7DC28\", \"#D9AE23\", \"#D98A23\", \"#F77E28\", \"#F0B132\"])\n // set color domain to number of census years\n .domain(v2RectData.map(d => d.count).reverse())\n\n // set a color for background boxes\n vis.rectColor = d3.scaleOrdinal()\n //https://colorbrewer2.org/#type=sequential&scheme=Greys&n=7\n .range(['#f7f7f7','#d9d9d9','#bdbdbd','#969696','#737373','#525252','#252525'])\n .domain(v2RectData.map(d=>d.id))\n\n // Set sizing of the SVG\n vis.margin = {top: 40, right: 10, bottom: 20, left: 10};\n vis.width = $(\"#\" + vis.parentElement).width() - vis.margin.left - vis.margin.right;\n vis.height = $(\"#\" + vis.parentElement).height() - vis.margin.top - vis.margin.bottom;\n vis.buffer = 40;\n\n // For the dots\n // Scale the cells on the smaller height or width of the SVG\n // let cellScaler = vis.height > vis.width ? vis.width: vis.height;\n vis.cellHeight = vis.width / (15 * v2RectData.length) ;\n vis.cellWidth = vis.cellHeight;\n vis.cellPadding = vis.cellHeight / 4;\n\n // For the rects\n vis.rectPadding = 10;\n vis.rectWidth = vis.width/(v2RectData.length) - vis.rectPadding; // fit all the rects in width wise\n vis.rectHeight = vis.rectWidth; //square\n\n\n // init drawing area\n vis.svg = d3.select(\"#\" + vis.parentElement).append(\"svg\")\n .attr(\"width\", vis.width)\n .attr(\"height\", vis.height)\n .attr('transform', `translate (0, ${vis.margin.top})`);\n\n // append a tooltip\n vis.tooltip = d3.select(\"body\").append('div')\n .attr('class', \"tooltip\")\n .attr('id', 'distanceVisToolTip');\n\n // The cell group that *must underlay* the rectangles for rect hover\n vis.cellGroup = vis.svg.append(\"g\")\n .attr(\"class\", \"cell-group\")\n // slightly more offset than the rect group\n .attr(\"transform\", `translate(0, ${vis.buffer + 3 * vis.cellPadding})`);\n\n\n // The background rectangle group that *overlays* the dots (for hover) ----\n vis.rectGroup = vis.svg.append(\"g\")\n .attr(\"class\", \"rect-container\")\n // move down to give room to legend\n .attr(\"transform\", `translate(0, ${vis.buffer})`);\n\n // ------ build a grid of cells ---\n vis.rects = vis.rectGroup\n .selectAll(\".census-rect\")\n .data(v2RectData)\n .enter()\n .append(\"rect\")\n .attr(\"class\", d =>`census-rect rect-${d.id}`)\n .attr(\"x\", (d,i) => i * vis.rectWidth + vis.rectPadding)\n .attr(\"y\", (d,i) => vis.rectPadding) // same y for each rect //Math.floor(i % 100 / 10);\n .attr(\"width\", d => d.id === \"NV\" ? vis.rectWidth/3 : vis.rectWidth)\n .attr(\"height\", vis.rectHeight)\n .attr(\"fill\", \"#f7f7f7\")\n .attr(\"stroke\", \"black\")\n .attr(\"opacity\", d => {\n if (d.count === 0) {\n return 0; // because nothing falls into 0 census with the current attribute set\n } else {\n return 0.3 // for dots to to be seen through it\n }\n })\n .attr(\"stroke-width\", 4)\n .on('mouseover', function(event, d) {\n vis.handleMouseOver(vis, event, d);\n })\n .on('mouseout', function(event, d) {\n vis.handleMouseOut(vis, event, d);\n });\n\n // legend to describe the color and shape\n vis.legend = vis.svg.append('g')\n .attr('class', 'v2-legend-group')\n .attr(\"transform\", `translate(0, 10)`);\n\n // All top row labels to the rectangles\n vis.labelTopGroup = vis.svg.append('g')\n .attr('class', 'v2-label-group-top')\n .attr(\"transform\", `translate(10, 20)`);\n\n vis.labels = vis.labelTopGroup\n .selectAll(\".census-rect-label-top\")\n .data(v2RectData)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"census-rect-label-top\")\n .attr(\"x\", (d,i) => i * vis.rectWidth )\n .attr(\"y\", 0)\n .style(\"fill\", \"black\")\n .text(d => {\n return ` ${d.title}`;\n })\n .attr(\"text-anchor\", \"center\")\n .style(\"alignment-baseline\", \"middle\")\n\n // Add labels to the rectangles\n vis.labelGroup = vis.svg.append('g')\n .attr('class', 'v2-label-group')\n .attr(\"transform\", `translate(10, 40)`);\n\n vis.labels = vis.labelGroup\n .selectAll(\".census-rect-label\")\n .data(v2RectData)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"census-rect-label\")\n .attr(\"x\", (d,i) => i * vis.rectWidth )\n .attr(\"y\", 0)\n .style(\"fill\", \"black\")\n .text(d => {\n return ` ${d.name}`;\n })\n .attr(\"text-anchor\", \"center\")\n .style(\"alignment-baseline\", \"middle\")\n\n vis.wrangleStaticData();\n }", "static draw(cfg, h, ls) {\n\n let element = h.configGen(this.node().h(h).ls(ls), cfg, ls);\n\n ls.d.forEach((item, j) => {\n let c = {\n data:item,\n cfg:cfg,\n layerState:ls,\n target:element(item)\n };\n\n let rv = h.configElement(c);\n d3.select(ls.g).selectAll('*').attr('data-svgid',rv.attr.id) // for popups\n });\n }", "initVis(){\n var vis = this;\n\n // SVG drawing area\n vis.svg = d3.select(\"#\" + vis.parentElement).append(\"svg\")\n .attr(\"width\", vis.width + vis.margin.left + vis.margin.right)\n .attr(\"height\", vis.height + vis.margin.top + vis.margin.bottom)\n vis.g = vis.svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + vis.margin.left + \",\" + vis.margin.top + \")\");\n \n\n\n // Scales and axes\n vis.x = d3.scaleLinear()\n .range([0,vis.width]);\n\n vis.countryScale = d3.scaleBand()\n .rangeRound([0, vis.width])\n .paddingInner(0.2);\n\n\n vis.y = d3.scaleLinear()\n .range([vis.height,0]);\n\n vis.xAxis = d3.axisBottom()\n .scale(vis.x);\n\n vis.yAxis = d3.axisLeft()\n .scale(vis.y);\n\n vis.g.append(\"g\")\n .attr(\"class\", \"x-axis axis\")\n .attr(\"transform\", \"translate(0,\" + vis.height + \")\");\n\n vis.g.append(\"g\")\n .attr(\"class\", \"y-axis axis\");\n\n // Axis title\n vis.g.append(\"text\")\n .attr(\"x\", -50)\n .attr(\"y\", -8)\n .text(vis.yAttr);\n\n // Axis title\n vis.g.append(\"text\")\n .attr('class', 'xlabel')\n .attr(\"x\", vis.width/2)\n .attr(\"y\", vis.height + 40)\n .style('text-anchor','middle')\n .text(vis.xAttr);\n\n\n // (Filter, aggregate, modify data)\n vis.wrangleData();\n }", "function setup(){\n loadData(\"life_expectancy_data_csv.csv\", \"fertility_rate_data_csv.csv\", \"africa_scatterplot.csv\");\n _vis = document.getElementById(\"vis\");\n _vis = d3.select(\"#vis\");\n // grab our container's dimension\n _vis_width = d3.select(\"#vis\").node().getBoundingClientRect().width;\n _vis_height = d3.select(\"#vis\").node().getBoundingClientRect().height;\n\n _vis2 = document.getElementById(\"vis2\");\n _vis2 = d3.select(\"#vis2\");\n // grab our container's dimension\n _vis2_width = d3.select(\"#vis2\").node().getBoundingClientRect().width;\n _vis2_height = d3.select(\"#vis2\").node().getBoundingClientRect().height;\n}", "function Gauge(myContainer, name, configuration) {\n this.name = name;\n this.myContainer = myContainer;\n\n var self = this; // some internal d3 functions do not \"like\" the \"this\" keyword, hence setting a local variable\n\n this.configure = function (configuration) {\n this.config = configuration;\n\n this.config.size = this.config.size * 0.9;\n\n this.config.raduis = this.config.size * 0.97 / 2;\n this.config.cx = this.config.cx;// + this.config.size / 4;\n this.config.cy = this.config.cy;// + this.config.size / 2;\n\n this.config.min = configuration.min || 0;\n this.config.max = configuration.max || 100;\n this.config.range = this.config.max - this.config.min;\n\n this.config.majorTicks = configuration.majorTicks || 5;\n this.config.minorTicks = configuration.minorTicks || 2;\n\n this.config.greenColor = configuration.greenColor || greenColor;\n this.config.orangeColor = configuration.orangeColor || orangeColor;\n this.config.defaultColor = configuration.defaultColor || defaultColor;\n this.config.yellowColor = configuration.yellowColor || yellowColor;\n this.config.redColor = configuration.redColor || redColor;\n };\n \n this.render = function (gauge_1, gauge_2, gauge_3) {\n this.body = this.myContainer//dashContainer//d3.select(\"#\" + this.placeholderName)\n .append(\"svg:svg\")\n .attr(\"class\", \"gauge\")\n .attr(\"x\", this.myContainer.x)//this.config.cx-this.config.size/4)\n .attr(\"y\", this.myContainer.y)//this.config.cy-this.config.size/4)\n .attr(\"width\", this.myContainer.width)//this.config.size)\n .attr(\"height\", this.myContainer.height)//this.config.size);\n\n var bandsContainer = this.body.append(\"svg:g\").attr(\"class\", \"bandsContainer\"); // for day/night changes\n \n this.redrawDimmableFace(xDim);//0);\n \n var pointerContainer = this.body.append(\"svg:g\").attr(\"class\", \"pointerContainer\");\n\n var arr = [];\n for(var i=0; i<arguments[count].length; i++){\n var json = {\n \"color\": \"\",\n \"value\": \"\",\n \"lineHeight\": \"\"\n }\n\n json.value = arguments[count][i];\n\n if(i == 0){\n json.color = \"#000\";\n json.lineHeight = 1.00;\n }else if(i == 1){\n json.color = \"#409dad\";\n json.lineHeight = 0.85;\n }else if(i == 2){\n json.color = \"#96c5f1\";\n json.lineHeight = 0.75;\n } \n\n arr.push(json);\n }\n\n if(!arguments[5]){ arr.splice(2, 1); }\n\n if(!arguments[6]){ arr.splice(1, 1);; }\n\n arguments[0] = arr;\n\n this.drawPointer(arguments[count]);\n // count++;\n };\n\n this.drawBands = function(bandsContainer) { \n for (var index in this.config.defaultZones) {\n this.drawBand(bandsContainer,this.config.defaultZones[index].from, this.config.defaultZones[index].to, self.config.defaultColor);\n }\n \n for (var index in this.config.greenZones) {\n this.drawBand(bandsContainer,this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor);\n }\n\n for (var index in this.config.yellowZones) {\n this.drawBand(bandsContainer,this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor);\n }\n\n for (var index in this.config.orangeZones) {\n this.drawBand(bandsContainer,this.config.orangeZones[index].from, this.config.orangeZones[index].to, self.config.orangeColor);\n }\n\n for (var index in this.config.redZones) {\n this.drawBand(bandsContainer,this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor);\n }\n };\n\n this.redrawDimmableFace = function (value) {\n this.drawFace(value < 0.5 ? self.config.defaultColor : self.config.defaultColor, // facecolor\n value < 0.5 ? self.config.defaultColor : defaultColor);\n }\n\n this.drawTicks = function (ticksContainer,color) {\n\n var fontSize = Math.round(this.config.size / 16);\n var majorDelta = this.config.range / (this.config.majorTicks - 1);\n for (var major = this.config.min; major <= this.config.max; major += majorDelta) {\n var minorDelta = majorDelta / this.config.minorTicks;\n for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta) {\n var minorpoint1 = this.valueToPoint(minor, 0.75);\n var minorpoint2 = this.valueToPoint(minor, 0.85);\n\n ticksContainer.append(\"svg:line\")\n .attr(\"x1\", minorpoint1.x)\n .attr(\"y1\", minorpoint1.y)\n .attr(\"x2\", minorpoint2.x)\n .attr(\"y2\", minorpoint2.y)\n .style(\"stroke\", color)\n .style(\"stroke-width\", \"1px\");\n }\n\n var majorpoint1 = this.valueToPoint(major, 0.7);\n var majorpoint2 = this.valueToPoint(major, 0.85);\n\n ticksContainer.append(\"svg:line\")\n .attr(\"x1\", majorpoint1.x)\n .attr(\"y1\", majorpoint1.y)\n .attr(\"x2\", majorpoint2.x)\n .attr(\"y2\", majorpoint2.y)\n .style(\"stroke\", color)\n .style(\"stroke-width\", \"2px\");\n\n if (major == this.config.min || major == this.config.max) {\n var point = this.valueToPoint(major, 0.63);\n\n ticksContainer.append(\"svg:text\")\n .attr(\"x\", point.x)\n .attr(\"y\", point.y)\n .attr(\"dy\", fontSize / 3)\n .attr(\"text-anchor\", major == this.config.min ? \"start\" : \"end\")\n .text(major)\n .style(\"font-size\", fontSize + \"px\")\n .style(\"fill\", color)\n .style(\"stroke-width\", \"0px\");\n }\n }\n };\n\n this.redraw = function (value) {\n //this.drawPointer(value);\n };\n\n this.dimDisplay = function (value) {\n this.redrawDimmableFace(value);\n };\n\n this.drawBand = function (bandsContainer, start, end, color) {\n if (0 >= end - start) return;\n\n bandsContainer.append(\"svg:path\")\n .style(\"fill\", color)\n .attr(\"d\", d3.svg.arc()\n .startAngle(this.valueToRadians(start))\n .endAngle(this.valueToRadians(end))\n .innerRadius(0.60 * this.config.raduis)\n .outerRadius(0.85 * this.config.raduis))\n .attr(\"transform\", function () {\n return \"translate(\" + self.config.cx + \", \" + self.config.cy + \") rotate(270)\";\n });\n };\n\n this.drawFace = function (colorFace,colorTicks) {\n var arc0 = d3.svg.arc()\n .startAngle(0) //this.valueToRadians(0))\n .endAngle(2 * Math.PI)\n .innerRadius(0.00 * this.config.raduis)\n .outerRadius(0.9 * this.config.raduis);\n\n var faceContainer = this.body.selectAll(\".faceContainer\");\n var bandsContainer = this.body.selectAll(\".bandsContainer\");\n var ticksContainer = this.body.selectAll(\".ticksContainer\");\n var pointerContainer = this.body.selectAll(\".pointerContainer\");\n var face = faceContainer.selectAll(\"path\");\n if (face == 0)\n {\n faceContainer\n .append(\"svg:path\")\n .attr(\"d\", arc0) //d3.svg.arc()\n .style(\"fill\", colorFace)\n .style(\"fill-opacity\", 0.7)\n .attr(\"transform\",\n \"translate(\" + self.config.cx + \", \" + self.config.cy + \")\");\n\n this.drawBands(bandsContainer);\n this.drawTicks(ticksContainer,colorTicks);\n var fontSize = Math.round(this.config.size / 9);\n faceContainer.append(\"svg:text\")\n .attr(\"x\", this.config.cx)\n .attr(\"y\", this.config.cy - this.config.size/6 - fontSize / 2 )\n .attr(\"dy\", fontSize / 2)\n .attr(\"text-anchor\", \"middle\")\n .text(this.config.label)\n .style(\"font-size\", fontSize + \"px\")\n .style(\"fill\", colorTicks)\n .style(\"stroke-width\", \"0px\");\n }\n else\n {\n face.style(\"fill\", colorFace);\n var facetxt = faceContainer.selectAll(\"text\");\n facetxt.style(\"fill\", colorTicks);\n var ptrtxt = pointerContainer.selectAll(\"text\");\n ptrtxt.style(\"fill\", colorTicks);\n var ticks = ticksContainer.selectAll(\"line\");\n ticks.style(\"stroke\", colorTicks);\n var texts = ticksContainer.selectAll(\"text\");\n texts.style(\"fill\", colorTicks);\n \n }\n };\n\n this.drawPointer = function (valArr) {\n\n var head = [];\n var head1 = [];\n var head2 = [];\n var tail = [];\n var tail1 = [];\n var tail2 = [];\n var data = {}; \n var delta = this.config.range / 13;\n\n for(var k =0;k<valArr.length;k++){\n var value = valArr[k].value;\n\n head.push(this.valueToPoint(value, valArr[k].lineHeight));\n head1.push(this.valueToPoint(value - delta, 0.35));\n head2.push(this.valueToPoint(value + delta, 0.35));\n\n var tailValue = value - (this.config.range * (1 / (270 / 360)) / 2);\n tail.push(this.valueToPoint(tailValue, 0.38));\n tail1.push(this.valueToPoint(tailValue - delta, 0.35));\n tail2.push(this.valueToPoint(tailValue + delta, 0.35));\n data[k] = [head[k], head1[k], tail2[k], tail[k], tail1[k], head2[k], head[k]];\n \n var line = d3.svg.line()\n .x(function (d) {\n return d.x;\n })\n .y(function (d) {\n return d.y;\n })\n .interpolate(\"basis\");\n\n var pointerContainer = this.body.select(\".pointerContainer\");\n\n var pointer = pointerContainer.selectAll(\"path[k]\").data([data[k]]);\n pointer.enter().append(\"svg:path\").attr(\"d\", line).style(\"fill\", valArr[k].color).style(\"fill-opacity\", 1);\n\n pointer.transition()\n .attr(\"d\", line)\n //.ease(\"linear\")\n .duration(i>=0 ? 50 : 500);\n }\n };\n\n this.valueToDegrees = function (value) {\n return value / this.config.range * 270 - 45;\n };\n\n this.valueToRadians = function (value) {\n return this.valueToDegrees(value) * Math.PI / 180;\n };\n\n this.valueToPoint = function (value, factor) {\n value = parseFloat(value);\n var len = this.config.raduis * factor;\n var inRadians = this.valueToRadians(value);\n var point = {\n x: this.config.cx - len * Math.cos(inRadians),\n y: this.config.cy - len * Math.sin(inRadians)\n };\n\n return point;\n };\n\n // initialization\n this.configure(configuration);\n}", "draw() {\n if (!this.layout || typeof this.layout === 'string') {\n return;\n }\n // Calc view dims for the nodes\n this.applyNodeDimensions();\n // Recalc the layout\n const result = this.layout.run(this.graph);\n const result$ = result instanceof rxjs__WEBPACK_IMPORTED_MODULE_7__[\"Observable\"] ? result : Object(rxjs__WEBPACK_IMPORTED_MODULE_7__[\"of\"])(result);\n this.graphSubscription.add(result$.subscribe(graph => {\n this.graph = graph;\n this.tick();\n }));\n if (this.graph.nodes.length === 0) {\n return;\n }\n result$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_8__[\"first\"])()).subscribe(() => this.applyNodeDimensions());\n }", "function drawChart() {\n\n // create scales for axes\n let xScale = d3.scaleTime().range([0, this.width]);\n xScale.domain([new Date(2008, 0, 0), new Date(2017, 0, 0)]);\n let yScale = d3.scaleLinear().range([this.height, 0]);\n yScale.domain([-1,1]);\n\n this.x = d3.scaleLinear()\n .domain([d3.min(this.data, xMin), d3.max(this.data, xMax)])\n .range([0, this.width]);\n\n this.y = d3.scaleLinear()\n .domain([d3.min(this.data, stackMin), d3.max(this.data, stackMax)])\n .range([this.height, 0]);\n\n // create areas with mouse events: tooltip\n let that = this;\n this.svg.append('g')\n .attr('id', 'area')\n .selectAll(\"path\")\n .data(this.data)\n .enter().append(\"path\")\n .attr(\"d\", function(d) {\n return this.area(d.data)\n }.bind(this))\n .attr(\"fill\", function(d) {\n return this.colorMap[d.label];\n }.bind(this))\n .on(\"mouseover\", function(d) {\n d3.select(\"#tooltip\").classed(\"hidden\", false);\n })\n .on(\"mousemove\", function(d){\n let rect = document.getElementById('div-stream').getBoundingClientRect();\n let xPosition = d3.event.pageX - rect.x;\n let yPosition = d3.event.pageY;\n\n let date = xScale.invert(xPosition - that.margins.left);\n let index = date.getYear()+1900-2008;\n\n let tooltip = d3.select(\"#tooltip\")\n .style(\"left\", xPosition + \"px\")\n .style(\"top\", yPosition + \"px\");\n\n tooltip.select(\"#tooltip-year\")\n .text(date.getYear()+1900);\n\n let lastVal = 0;\n for (let i =0; i < 5; i++){\n tooltip.select(\"#value-q-\"+i)\n .text((100*(that.data[i].data[index][2] - lastVal)).toFixed(2)+\"%\");\n lastVal = that.data[i].data[index][2]\n }\n\n lastVal = 0;\n for (let i =0; i < 5; i++){\n tooltip.select(\"#value-a-\"+i)\n .text((-100*(that.data[i+5].data[index][2] - lastVal)).toFixed(2)+\"%\");\n lastVal = that.data[i+5].data[index][2]\n }\n })\n .on(\"mouseout\", function() {\n d3.select(\"#tooltip\").classed(\"hidden\", true);\n });\n\n // add axes\n this.svg.append(\"g\")\n .attr('class', 'axis')\n .attr(\"transform\", \"translate(0,\" + this.height/2 + \")\")\n .call(d3.axisBottom(xScale));\n\n this.svg.append(\"g\")\n .attr('class', 'axis')\n .attr(\"transform\", \"translate(0,0)\")\n .call(d3.axisLeft(yScale));\n\n // add legend\n if (this.legend){\n let legend6 = d3.select('#div-stream-legend').selectAll(\"legend\")\n .data(getLabels(that.data));\n\n let p = legend6.enter().append(\"div\")\n .attr(\"class\",\"legends\")\n .append(\"p\").attr(\"class\",\"country-name\");\n\n p.append(\"span\").attr(\"class\",\"key-dot\").style(\"background\",function(d) { return that.colorMap[d] } );\n p.insert(\"text\").text(function(d,i) { return d } );\n }\n }", "function init() {\n\n svg = d3\n .select(\"#d3-container-1\")\n .append(\"svg\")\n\n draw(); // calls the draw function\n }", "draw() {\n // Set up the nodes and links of the graph.\n this.addNodes();\n this.addLinks();\n\n // Create the d3 simulation.\n this.createSimulation();\n\n // Set up SVG to draw the simulation.\n this.setupSvg();\n }", "init(){\n let dv = this,\n elementNode = d3.select(dv.element).node(),\n elementWidth = elementNode.getBoundingClientRect().width,\n aspectRatio = elementWidth < 800 ? elementWidth * 0.65 : elementWidth * 0.5;\n\n const breakPoint = 678;\n \n // margin\n dv.margin = { };\n\n dv.margin.top = elementWidth < breakPoint ? 40 : 50;\n dv.margin.bottom = elementWidth < breakPoint ? 30 : 80;\n\n dv.margin.right = elementWidth < breakPoint ? 20 : 150;\n dv.margin.left = elementWidth < breakPoint ? 20 : 80;\n \n dv.width = elementWidth - dv.margin.left - dv.margin.right;\n dv.height = aspectRatio - dv.margin.top - dv.margin.bottom;\n\n d3.select(dv.element).select(\"svg\").remove();\n \n // add the svg to the target element\n dv.svg = d3.select(dv.element)\n .append(\"svg\")\n .attr(\"width\", dv.width + dv.margin.left + dv.margin.right)\n .attr(\"height\", dv.height + dv.margin.top + dv.margin.bottom);\n \n // add the g to the svg and transform by top and left margin\n dv.g = dv.svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + dv.margin.left + \n \", \" + dv.margin.top + \")\");\n \n // set transition variable\n dv.t = function() { return d3.transition().duration(1000); };\n\n // dv.colourScheme = [\"#aae0fa\",\"#00929e\",\"#ffc20e\",\"#16c1f3\",\"#da1e4d\",\"#086fb8\"];\n dv.colourScheme =d3.schemeBlues[5].slice(1);\n \n // set colour function\n dv.colour = d3.scaleOrdinal(dv.colourScheme);\n\n // for the tooltip from the d3 book\n dv.bisectDate = d3.bisector( d => { return d.date; } ).left;\n\n // tick numbers\n dv.tickNumber = \"undefined\";\n\n // tick formats\n dv.tickFormat = \"undefined\";\n \n dv.addAxis();\n \n }", "createMap() {\n\n let that = this;\n\n var MapView = d3.select(\"#MapView\")\n\n MapView.append(\"div\").attr(\"id\", \"break1\");\n MapView.append(\"div\").attr(\"id\", \"slider\");\n MapView.append(\"div\").attr(\"id\", \"map\");\n MapView.append(\"div\").attr(\"id\", \"info\");\n MapView.append(\"div\").attr(\"id\", \"break2\");\n MapView.append(\"div\").attr(\"id\", \"charts\");\n\n var MapSVG = d3.select(\"#map\")\n .append(\"svg\")\n .attr(\"id\", \"map-svg\")\n .attr(\"width\", this.width)\n .attr(\"height\", this.height)\n .attr('x', 0);\n\n var infoSVG = d3.select(\"#info\")\n .append(\"svg\")\n .attr(\"id\", \"info-svg\")\n .attr(\"width\", this.width)\n .attr(\"height\", this.height);\n\n var breakDiv = d3.select(\"#break\")\n .append(\"br\")\n .append(\"br\")\n .append(\"br\")\n .append(\"br\");\n\n var chartSVG = d3.select(\"#charts\")\n .append(\"svg\")\n .attr(\"id\", \"chart-svg\")\n .attr(\"width\", screen.availWidth-50)\n .attr(\"height\", 300);\n \n let translate1 = screen.availWidth/4+10;\n let translate2 = screen.availWidth/2+10;\n let translate3 = screen.availWidth*3/4+10;\n let translate4 = translate1 - 100;\n\n chartSVG.append('g').attr('id', 'text-group').attr('width', screen.availWidth).attr('transform', 'translate(0, 40)'); \n chartSVG.append('g').attr('id', 'text-group2').attr('width', screen.availWidth).attr('transform', 'translate(0, 80)'); \n chartSVG.append('g').attr('id', 'dropdown-group').attr('width', screen.availWidth).attr('transform', 'translate('+translate4+', 20)'); \n chartSVG.append('g').attr('id', 'CO-group').attr('width', screen.availWidth/4 - 10).attr('transform', 'translate(20, 90)'); \n chartSVG.append('g').attr('id', 'SO2-group').attr('width', screen.availWidth/4 - 10).attr('transform', 'translate('+translate1+', 90)');\n chartSVG.append('g').attr('id', 'NO2-group').attr('width', screen.availWidth/4 - 10).attr('transform', 'translate('+translate2+', 90)');\n chartSVG.append('g').attr('id', 'O3-group').attr('width', screen.availWidth/4 -10).attr('transform', 'translate('+translate3+', 90)');\n\n //TODO: add projections to resize map\n\n \n var path = d3.geoPath();\n MapSVG.append(\"g\")\n .attr(\"class\", \"states\")\n .selectAll(\"path\")\n .data(topojson.feature(this.usData, this.usData.objects.states).features)\n .enter().append(\"path\")\n .attr(\"d\", path)\n .attr(\"transform\", 'scale(+'+this.scaleFactor+','+this.scaleFactor+')')\n .on(\"click\", function(d) {\n that.highlightState(d, path, this)\n });\n\n this.updateMapForTime(this.activeTime);\n\n }", "layer (data) {\n return _layer.draw(data)\n }", "init() {\n\t\t\t\tstructureData()\n\t\t\t\ttyper.prepare($trendText1);\n\t\t\t\ttyper.prepare($trendText2);\n\t\t\t\ttyper.prepare($outro1);\n\n\t\t\t\twidth = $sel.node().offsetWidth - marginLeft - marginRight;\n\t\t\t\theight = $sel.node().offsetHeight - marginTop - marginBottom;\n\n\t\t\t\t$svg = $sel.append('svg')\n\t\t\t\t\t.attr('class', 'pudding-chart')\n\t\t\t\t\t.attr('width', width + marginLeft + marginRight)\n\t\t\t\t\t.attr('height', height + marginTop + marginBottom);\n\n\t\t\t\tconst $g = $svg.append('g');\n\n\t\t\t\t// offset chart for margins\n\t\t\t\t$g.attr('transform', `translate(${marginLeft}, ${marginTop})`);\n\n\t\t\t\t// create axis\n\t\t\t\t$axis = $svg.append('g').attr('class', 'g-axis');\n\n\t\t\t\txAxisGroup = $axis.append('g')\n\t\t\t\t\t.attr('class', 'x axis')\n\t\t\t\t\t.attr('transform', `translate(${marginLeft},${height})`)\n\n\t\t\t\tyAxisGroup = $axis.append('g')\n\t\t\t\t\t.attr('class', 'y axis')\n\n\t\t\t\txScale\n\t\t\t\t\t.domain([minX, maxX])\n\t\t\t\t\t.range([0, width])\n\n\t\t\t\tyScale\n\t\t\t\t\t.domain([0, maxY])\n\t\t\t\t\t.range([height, 0])\n\n\t\t\t\txAxis = d3\n\t\t\t\t\t.axisBottom(xScale)\n\t\t\t\t\t.tickPadding(8)\n\t\t\t\t\t.ticks(10)\n\t\t\t\t\t.tickFormat(d3.format('d'))\n\n\t\t\t\tyAxis = d3\n\t\t\t\t\t.axisLeft(yScale)\n\t\t\t\t\t.tickPadding(8)\n\t\t\t\t\t.tickSize(-width)\n\t\t\t\t\t.ticks(8)\n\n\t\t\t\t$axis.select('.x')\n\t\t\t\t\t.attr('transform', `translate(${marginLeft},510)`)\n\t\t\t\t\t.call(xAxis);\n\n\t\t\t\t$axis.select('.y')\n\t\t\t\t\t.attr('transform', `translate(${marginLeft + 20},0)`)\n\t\t\t\t\t.call(yAxis);\n\n\t\t\t\t// setup viz group\n\t\t\t\t$vis = $g.append('g').attr('class', 'g-vis');\n\n\t\t\t\tgenderLines = d3.line()\n\t\t\t\t\t.x(d => xScale(d.year))\n\t\t\t\t\t.y(d => yScale(d.flat))\n\n\t\t\t\tgenderArea = d3.area()\n\t\t\t\t\t.x(d => xScale(d.key))\n\t\t\t\t\t.y0(d => yScale(d.value.female))\n\t\t\t\t\t.y1(d => yScale(d.value.male))\n\n\t\t\t\tdrawArea = $vis.append('path')\n\t\t\t\t\t.datum(dataByYear)\n\t\t\t\t\t.attr('class', 'area')\n\t\t\t\t\t.attr('d', genderArea)\n\n\t\t\t\tlineGroup = $svg.select('.g-vis')\n\n\t\t\t\tfemaleLine = lineGroup.append('path')\n\t\t\t\t\t.datum(femaleData)\n\t\t\t\t\t.attr('class', 'Female')\n\t\t\t\t\t.attr('d', genderLines)\n\n\t\t\t\tmaleLine = lineGroup.append('path')\n\t\t\t\t\t.datum(maleData)\n\t\t\t\t\t.attr('class', 'Male')\n\t\t\t\t\t.attr('d', genderLines)\n\n\t\t\t\tconst xTicks = d3.selectAll('.x.axis text')\n\n\t\t\t\txTicks.attr('transform', `translate(32,0)`)\n\n\t\t\t}", "function redraw() {\n // using raw attributes means we need to explicitly pass the data in\n crossValueAttribute.data(columnValues(data.table, 'x'));\n mainValueAttribute.data(columnValues(data.table, 'y'));\n if (!LO_FI_VERSION) {\n languageAttribute.data(columnValues(data.table, 'language'));\n yearAttribute.data(columnValues(data.table, 'date'));\n indexAttribute.data(columnValues(data.table, 'ix'));\n }\n\n // scale the points as the user zooms, but at a slower rate\n const scale = (xScale.domain()[1] - xScale.domain()[0]) / 100;\n const size = 1 / (1 + (scale - 0.9) * 1);\n pointSeries.size(size);\n\n d3.select('#chart')\n .datum(data)\n .call(chart);\n\n}", "function render() {\n dots\n .attr(\"cx\", function (d) {\n return project(d).x;\n })\n .attr(\"cy\", function (d) {\n return project(d).y;\n });\n }", "function draw(){\n\n\n // canvas.save();\n // canvas.clearRect(0, 0, width, height);\n // canvas.translate(transform_x, transform_y);\n // canvas.scale(scale_value, scale_value);\n\n coresetData.forEach(function(d){\n canvas.beginPath();\n canvas.rect(parseFloat(d.x), -parseFloat(d.y), parseFloat(d.delta), parseFloat(d.delta));\n canvas.fillStyle = d.color;\n canvas.fill();\n //canvas.closePath();\n });\n }", "function drawPlot(dataset) {\n // define and set the scale functions\n let xScale, colorScaleMap, radiusScaleMap, yPositionScaleMap;\n [xScale, colorScaleMap, radiusScaleMap, yPositionScaleMap] = getScales(\n dataset\n );\n\n // initializing the tooltip\n initializeTooltip();\n\n // initialize current sorting order status for each field of the dataset\n initializeSortingState();\n\n //Select SVG element\n let svg = d3\n .select(\"body\")\n .append(\"svg\")\n .attr(\"width\", pageWidth)\n .attr(\"height\", svgHeight);\n\n // set a background color using a rect which spans the whole svg canvas\n svg\n .append(\"rect\")\n .attr(\"width\", pageWidth)\n .attr(\"height\", svgHeight)\n .attr(\"fill\", \"#E0FFFF\");\n\n //Create christmas trees placeholders\n let christmasTrees = svg\n .selectAll(\"g.christmas-tree\")\n .data(dataset)\n .enter()\n .append(\"g\")\n .classed(\"christmas-tree\", true)\n .attr(\"pointer-events\", \"none\");\n\n // put a pine and six christmas balls for each placeholder\n CHRISTMAS_ITEMS.forEach(function(svgID) {\n let item = null;\n\n if (svgID === \"pine\") {\n item = christmasTrees\n .append(\"use\")\n .attr(\"href\", \"images/christmas-tree.svg#\" + svgID);\n } else {\n item = christmasTrees.append(\"svg\").attr(\"viewBox\", \"-3 0 512 512.00001\");\n }\n\n item\n .classed(svgID, true)\n .attr(\"x\", function(d, i) {\n return xScale(i);\n })\n .attr(\"width\", xScale.bandwidth())\n .attr(\"pointer-events\", \"auto\")\n .on(\"mouseover\", function(d) {\n onMouseOverListener.call(this);\n })\n .on(\"mouseout\", function() {\n onMouseOutListener.call(this);\n });\n\n // considering only christmas balls svg container\n if (svgID !== \"pine\") {\n item\n .on(\"click\", function() {\n onClickListener.call(this, xScale);\n })\n .attr(\"preserveAspectRatio\", \"xMidYMax meet\")\n .append(\"title\")\n .text(function(d) {\n let key = classNameToKeyMap[svgID];\n return \"This value is \" + d[key];\n });\n\n let circle = item\n .append(\"circle\")\n .attr(\"stroke\", \"black\")\n .attr(\"stroke-width\", 1)\n .attr(\"fill\", function(d, i) {\n let key = classNameToKeyMap[svgID];\n let value = d[key];\n let scaleFunction = colorScaleMap[svgID];\n return scaleFunction(value);\n })\n .attr(\"r\", function(d, i) {\n let key = classNameToKeyMap[svgID];\n let value = d[key];\n let scaleFunction = radiusScaleMap[svgID];\n return scaleFunction(value);\n })\n .attr(\"cy\", function(d, i) {\n let key = classNameToKeyMap[svgID];\n let value = d[key];\n let scaleFunction = yPositionScaleMap[svgID];\n return scaleFunction(value);\n });\n\n // setting cx coordinates for each christmas balls\n switch (svgID) {\n case \"top-left-circle\":\n circle.attr(\"cx\", \"69\");\n break;\n case \"top-right-circle\":\n circle.attr(\"cx\", \"437\");\n break;\n case \"center-left-circle\":\n case \"bottom-left-circle\":\n circle.attr(\"cx\", \"44\");\n break;\n case \"center-right-circle\":\n case \"bottom-right-circle\":\n circle.attr(\"cx\", \"462\");\n break;\n }\n }\n });\n}", "function transition_data() {\n\tsvg.selectAll(\".physical_dot\")\n\t .data(vtlib)\n\t .transition()\n\t .duration(500)\n\t .attr(\"cx\", function(d) { return phy_x(d.duration); });\n}", "function draw() {\n\n // + FILTER DATA BASED ON STATE\n const filteredData = state.data // <--- update to filter\n\n // + DRAW CIRCLES\n const dot = svg\n .selectAll(\"circle\")\n .data(filteredData, d => d.BioID) // second argument is the unique key for that row\n .join(\n // + HANDLE ENTER SELECTION\n enter => enter.append(\"circle\"),\n\n // + HANDLE UPDATE SELECTION\n update => update,\n\n // + HANDLE EXIT SELECTION\n exit => exit.remove()\n\n );\n}", "render() {\n const { data } = this.state;\n\n return (\n <div className='main'>\n <div className='example'>\n <h4>Example 1 - Basic SVG Drawing</h4>\n <VisExample1 width={400} height={200} />\n </div>\n <div className='example'>\n <h4>Example 2 - SVG Drawing from Data Array</h4>\n <VisExample2 width={400} height={200} />\n </div>\n <div className='example'>\n <h4>Example 3 - External Data Points</h4>\n <VisExample3 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 4 - D3 Scales</h4>\n <VisExample4 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 5 - Inner Margin</h4>\n <VisExample5 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 6 - Highlight Behaviour (flickers)</h4>\n <VisExample6 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 7 - Highlight Behaviour (slow)</h4>\n <VisExample7 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 8 - Highlight Behaviour (optimized)</h4>\n <VisExample8 width={400} height={200} data={data} />\n </div>\n <div className='example'>\n <h4>Example 9 - Highlight Behaviour (optimized, auto width)</h4>\n <AutoWidth>\n <VisExample8 height={400} data={data} />\n </AutoWidth>\n </div>\n </div>\n );\n }", "function draw() {\n //if(sliceCount == 5000 ) return;\n //if all data has been shown, return\n if (usefulData.length < sliceCount * sliceSize) return;\n \n //get the data to be shown in this slice\n var start = sliceCount * sliceSize;\n var end = Math.min(usefulData.length, (sliceCount + 1) * sliceSize);\n var slicedData = usefulData.slice(start, end);\n sliceCount++;\n \n var minTime = slicedData[0].time;\n var cyOffset = eachHeight * 0.4 ;\n webgl\n .selectAll('.points_' + sliceCount)\n .data(slicedData).enter()\n .append('circle')\n .attr({\n cx:function(d){return startOffset + d.currentTime;},\n cy:function(d){return cyOffset + eachHeight * videoNames[d['videoID']];},\n r:0,\n fill:function (d) {return colors(d['type']);},\n opacity:0,\n class:'event',\n filter:'url(#ball-glow2)'\n })\n .transition()\n .delay(function (d, i) { return (d.time - minTime) / config.playrate }).duration(1000)\n .attr({\n opacity:0.3,\n r:15\n })\n .transition()\n .duration(1000)\n .attr({\n opacity:0,\n r:0\n })\n .remove();\n setTimeout(draw, (slicedData[slicedData.length - 1].time - minTime) / config.playrate);\n }", "function GraphVisualization() {\n this.element = null; // DOM element to display in\n this.selection = null; // d3 selection of DOM element\n this.dataSource = null; // Data source for vertices/edges\n this.svg = null; // SVG inside DOM element\n this.width = 100; // Width of visualization\n this.height = 100; // Height of visualization\n this.onvertexmousedown = null; // Mouse down event on a vertex\n this.onedgemousedown = null; // Mouse down event on an edge\n this.oncanvasmouseodwn = null; // Mouse down event on the background\n this.force = d3.layout.force(); // d3 force layout underlying visualization\n this.edgeStroke = \"black\"; // Edge stroke color\n this.edgeRadius = 1; // Edge radius\n this.vertexStroke = \"black\"; // Vertex stroke color\n this.vertexFill = \"blue\"; // Vertex fill color\n this.vertexRadius = 8; // Vertex radius\n this.edgeLength = 50; // Edge length\n\n /*\n * Bind the visualization to a DOM element\n */\n this.bindElement = function(element) {\n this.element = element;\n this.selection = d3.select(element);\n this.svg = this.selection.append(\"svg\");\n\n this.updateSVGAttribs();\n this.refresh();\n\n return this;\n };\n\n /*\n * Bind the visualization to a data source\n */\n this.bindDataSource = function(dataSource) {\n this.dataSource = dataSource;\n this.refresh();\n\n return this;\n };\n\n /*\n * Set the size of the visualization\n */\n this.size = function(width, height) {\n this.force.size([width, height]);\n\n this.width = width;\n this.height = height;\n\n this.updateSVGAttribs();\n this.refresh();\n\n return this;\n };\n\n /*\n * Update attributes SVG for color, size, etc. Called when these properties\n * change or the DOM element is rebound.\n */\n this.updateSVGAttribs = function() {\n this.svg\n .attr(\"width\", this.width)\n .attr(\"height\", this.height);\n };\n\n /*\n * Update the visualization when the data from the data source changes. This\n * is called automatically when the visualization is bound to a new data\n * source or DOM element.\n */\n this.refresh = function() {\n if (!this.dataSource || !this.svg)\n return;\n\n var vertices = this.dataSource.getVertices();\n var edges = this.dataSource.getEdges();\n\n var edge = this.svg.selectAll(\".link\")\n .data(edges);\n edge.enter()\n .append(\"line\")\n .attr(\"class\", \"link\")\n .attr(\"stroke-width\", this.edgeRadius)\n .style(\"stroke\", this.edgeStroke);\n edge.exit()\n .remove();\n\n var node = this.svg.selectAll(\".node\")\n .data(vertices);\n node.enter()\n .append(\"circle\")\n .attr(\"class\", \"node\")\n .attr(\"r\", this.vertexRadius)\n .style(\"fill\", this.vertexFill)\n .style(\"stroke\", this.vertexStroke)\n .call(this.force.drag);\n node.exit()\n .remove();\n\n this.edgeSelection = edge;\n this.nodeSelection = node;\n\n this.updateEvents();\n\n var tick = function(e) {\n edge.attr(\"x1\", function(d) { return d.source.x; })\n .attr(\"y1\", function(d) { return d.source.y; })\n .attr(\"x2\", function(d) { return d.target.x; })\n .attr(\"y2\", function(d) { return d.target.y; });\n\n node.attr(\"cx\", function(d) { return d.x; })\n .attr(\"cy\", function(d) { return d.y; });\n };\n\n this.force\n .nodes(vertices)\n .links(edges)\n .on(\"tick\", tick)\n .linkDistance(this.edgeLength)\n .start();\n };\n\n /*\n * Update events on d3 selections\n */\n this.updateEvents = function() {\n if (!this.edgeSelection)\n return;\n\n this.edgeSelection.on(\"mousedown\", this.edgemousedown);\n this.nodeSelection.on(\"mousedown\", this.vertexmousedown);\n this.svg.on(\"mousedown\", this.canvasmousedown);\n };\n\n /*\n * Handle various events:\n *\n * vertexmousedown: Mouse down on a vertex\n * edgemousedown: Mouse down on an edge\n * canvasmousedown: Mouse down on background\n */\n this.on = function(evt_name, f) {\n if (evt_name == \"vertexmousedown\")\n this.vertexmousedown = f;\n else if (evt_name == \"edgemousedown\")\n this.edgemousedown = f;\n else if (evt_name == \"canvasmousedown\")\n this.canvasmousedown = f;\n\n this.updateEvents();\n\n return this;\n };\n}", "_renderSvg() {\n this._svg = d3\n .select(this.parent)\n .append(\"svg\")\n .attr(\"class\", \"chart-svg\")\n .append(\"g\")\n .attr(\"class\", \"data-container\")\n .append(\"g\")\n .attr(\"class\", \"markers-container\");\n }", "function draw() {\n let filteredData = state.data;\n if (state.selectedDir !== 'Both') {\n filteredData = state.data.filter(d => d.direction === state.selectedDir);\n console.log(filteredData);\n }\n const dot = svg\n .selectAll(\".dot\")\n .data(filteredData, d => d.name)\n .join(\n enter =>\n enter \n .append(\"circle\")\n .attr('class', 'dot')\n .attr('stroke', 'black')\n .attr('opacity', 0.2)\n .attr('fill', d => {\n if (d.direction === \"Towards Manhattan\") return \"pink\";\n else return \"purple\";\n })\n .attr(\"r\", radius)\n .attr(\"cy\", d => height)\n .attr(\"cx\", d => margin.top) \n .call(enter => enter\n .transition()\n .delay(500)\n .attr(\"cx\", d => xScale(d.count))\n .attr(\"cy\", d => yScale(d.temperature))\n .attr(\"opacity\", 0.6)\n ),\n update => \n update.call(update => \n update\n .transition()\n .duration(50)\n .attr(\"stroke\", \"black\")\n ),\n exit => \n exit.call(exit => \n exit\n .transition()\n .attr(\"opacity\", 1)\n .delay(700)\n .duration(500)\n .attr(\"opacity\", .2)\n .remove()\n )\n );\n}", "function create()\n\t{\n\t\t \n\t\tvar drawArea = d3.select(\"body\")\n\t\t .append(\"svg:svg\")\n\t\t .attr(\"width\", width) \n\t\t .attr(\"height\", height)\n\t\t .style(\"position\", 'absolute')\n\t\t\t.style(\"left\", x +'px')\n\t\t\t.style(\"top\", y +'px')\n\t\t\t// .attr('fill', 'red')\n\t\t\t// .style('background', 'rgba(5, 5, 5, 0.5)');\n\t\t\t// .attr('background', 'rgba(5, 5, 5, 0.5)');\n\t\t\t// trabnsistion to obacjit y 00 -- 0.4\n\t\t\t// .attr('fill', 'rgba(250,0,0, 0.5)');\n\t\t\t// .style('fill', 'rgba(0, 0, 0, 0.8)')\n\n\t\t// append rect\n\t\tdrawArea.append('rect')\n\t\t\t.attr(\"x\", 0)\n\t\t\t.attr(\"y\", 0)\n\t\t\t.attr(\"width\", width)\n\t\t\t.attr(\"height\", height)\n\t\t\t.style(\"opacity\", 0)\n\t\t\t// .attr('fill', '#efefef')\n\t\t\t.attr('fill', '#666')\n\t\t\t.transition()\n\t\t\t.delay(400)\n\t\t\t.duration(2000)\n\t\t\t.style(\"opacity\", 0.8)\n\t\t\t// .style('fill', 'rgba(5, 5, 5, 0.5)')\n\n\n\t\t// append grid\n\t\tvar lineData = [ { \"x\": 0, \"y\": 0}, { \"x\": 400, \"y\": 0}];\n\n\t\tvar lineFunction = d3.svg.line()\n\t\t\t.x(function(d) { return d.x; })\n\t\t\t.y(function(d) { return d.y; })\n\t\t\t.interpolate(\"linear\")\n\n\t\tlineData = [ { \"x\": 0, \"y\": 0}, { \"x\": 400, \"y\": 0}];\n\t\tfor (var i = 0; i < height; i++) {\n\t\t\tdrawArea.append(\"line\")\n\t\t\t\t.attr(\"x1\", 0)\n\t\t\t\t.attr(\"y1\", i * 2 + 0.5)\n\t\t\t\t.attr(\"x2\", 0)\n\t\t\t\t.attr(\"y2\", i * 2 + 0.5)\n\t\t\t\t.attr(\"stroke\", \"#222\")\n\t\t\t\t.attr(\"stroke-width\", 1)\n\t\t\t\t.style(\"stroke-dasharray\", (\"1, 1\")) \n\t\t\t\t.attr(\"fill\", \"none\")\n\t\t\t\t.transition()\n\t\t\t\t.delay(1200 + (3*i*Math.random()))\n\t\t\t\t.duration(200)\n\t\t\t\t.attr('x2', width)\n\t\t\t\t.ease(\"quad\")\n\t\t};\n\n\t\t\n\n\t\n\t\t// // return object\n\t\t// return i_container;\n\t}", "showData(data) {\n\n let {positionScale, yScale} = this.getScales(data)\n\n this.getDragObject(data)\n\n this.dataBinding = d3.select(`#${this.boundingPanel}barChart`).selectAll(\"rect\").data(data)\n \n let self = this\n this.dataBinding.enter()\n .append(\"rect\")\n .attr(\"fill\", \"rgb(32,142,183)\")\n .attr(\"class\", \"barChartRectangles\")\n .attr(\"id\", d => {\n let rectNumber = d[this.numericalColumn].split(\"-\").length\n return `${this.boundingPanel}${d[this.categoricalColumn]}${rectNumber}`\n })\n .attr(\"width\", positionScale.bandwidth())\n .attr(\"transform\", d => {\n let sumOfAllEntries = d3.sum(d[this.numericalColumn].split(\"-\").map(k => +k))\n return `translate(${positionScale(d[this.categoricalColumn])}, ${yScale(sumOfAllEntries)})`\n })\n .attr(\"height\", d => {\n let sumOfAllEntries = d3.sum(d[this.numericalColumn].split(\"-\").map(k => +k))\n return this.BAR_CHART_HEIGHT - yScale(sumOfAllEntries)\n })\n .attr(\"stroke\", \"black\")\n .on('mouseover', function(d) {\n self.tip.attr('class', 'd3-tip animate').show(d)\n })\n .on('mouseout', function(d) {\n self.tip.attr('class', 'd3-tip').show(d)\n self.tip.hide()\n })\n \n this.dataBinding.attr(\"fill\", \"rgb(32,142,183)\")\n .transition()\n .attr(\"id\", d => {\n let rectNumber = d[this.numericalColumn].split(\"-\").length\n return `${this.boundingPanel}${d[this.categoricalColumn]}${rectNumber}`\n })\n .attr(\"width\", positionScale.bandwidth())\n .attr(\"transform\", d => {\n let sumOfAllEntries = d3.sum(d[this.numericalColumn].split(\"-\").map(k => +k))\n let xPosition = positionScale(d[this.categoricalColumn])\n let yPosition = yScale(sumOfAllEntries)\n return `translate(${xPosition}, ${yPosition})`\n })\n .attr(\"height\", d => {\n let listOfAllEntries = d[this.numericalColumn].split(\"-\").map(k => +k)\n let length = listOfAllEntries.length\n let sumOfAllEntries = listOfAllEntries[length - 1]\n return this.BAR_CHART_HEIGHT - yScale(sumOfAllEntries)\n })\n\n this.dataBinding.exit().remove()\n\n // Create xAxis\n let xAxis = d3.axisBottom(positionScale)\n .tickFormat(function(e) { \n let maxLength = 15\n e = e.replace(\"_or_\", \"\\/\").replace(\"_\", \" \")\n if(e.length > maxLength){\n return e.substring(0, maxLength) + \"...\"\n }\n return e\n })\n\n d3.select(`#${this.boundingPanel}xAxis`).transition().call(xAxis)\n .call(\n g => {\n g.selectAll(\"g\").selectAll(\"text\").attr(\"transform\", \"translate(-10, 10) rotate(-90)\")\n .style(\"text-anchor\", \"end\")\n .style(\"alignment-baseline\", \"ideographic\")\n }\n )\n\n // Create yAxis\n let yAxis = d3.axisLeft(yScale)\n .ticks(4)\n .tickFormat(function(e){\n if(Math.floor(e) != e)\n return\n if(e >= 1000000000){\n return `${e/1000000000}B`\n }\n if(e >= 1000000){\n return `${e/1000000}M`\n }\n if(e >= 1000){\n return `${e/1000}K`\n }\n return e;\n })\n d3.select(`#${this.boundingPanel}yAxis`).transition().call(yAxis)\n \n // Create Drag Functionality for merge and split\n d3.select(`#${this.boundingPanel}barChart`).selectAll(\"rect\").call(this['drag'+this.boundingPanel])\n\n // Create Brush Functionality for changing number of bins\n /*d3.select(\".brush\").call(\n d3.brushX()\n .extent([\n [this.paddingForBarCharts.left + this.marginsForBarCharts.left, this.paddingForBarCharts.top + this.marginsForBarCharts.top],\n [this.paddingForBarCharts.left + this.marginsForBarCharts.left + this.BAR_CHART_WIDTH, this.paddingForBarCharts.top + this.marginsForBarCharts.top + this.BAR_CHART_HEIGHT]\n ])\n .on(\"brush\", d => {\n console.log(\"brushed\")\n console.log(d)\n })\n )*/\n\n\n /*d3.select(`#${this.boundingPanel}barChart`).selectAll(\"rect\")\n .on(\"mousemove\", function(d) {\n d3.select(`#${self.boundingPanel}toolTip`)\n .attr(\"transform\", d => {\n console.log(document.getElementById(`middle_graph_panel_barChart_container`).getBoundingClientRect().x)\n return `translate(${d3.event.x - document.getElementById(`middle_graph_panel_barChart_container`).getBoundingClientRect().x - self.boundingRect.x + self.marginsForBarCharts.left + self.paddingForBarCharts.left + self.marginsForBarCharts.right + self.paddingForBarCharts.right + 80 }, ${d3.event.y - self.boundingRect.y + 10})`\n })\n .style(\"display\", \"block\")\n })\n .on(\"mouseleave\", function(d) {\n //d3.select(`#${self.boundingPanel}toolTip`).style(\"display\", \"none\")\n })*/\n\n }", "function renderData(pos) {\n\n if(typeof scaleSize[pos] == 'undefined') return;\n\n var context = canvas[pos].node().getContext('2d');\n var offscreenContext = offscreen[pos].node().getContext('2d');\n\n context.clearRect(0, 0, width, height);\n offscreenContext.clearRect(0, 0, width, height);\n \n data[pos].forEach(function(d, i) {\n \n if(d.originX < 0 || d.originX > width || \n d.originY < 0 || d.originY > height) return;\n\n const color = getColor(i);\n\n colorToDataIndex[color] = i;\n\n offscreenContext.fillStyle = color;\n\n context.strokeStyle = 'black';\n\n context.beginPath();\n offscreenContext.beginPath();\n\n context.arc(d.originX, d.originY, scaleSize[pos](d.vectors[vectorIndices[pos].size]), 0, 2 * Math.PI);\n offscreenContext.arc(d.originX, d.originY, scaleSize[pos](d.vectors[vectorIndices[pos].size]), 0, 2 * Math.PI);\n \n //k = [0, 1]\n //checkbox ui for deciding to apply k factor\n var k = (isKEnabled[pos])? scaleK[pos](d.vectors[vectorIndices[pos].k]) : 1;\n var c = d3.rgb(scaleRed[pos](d.vectors[vectorIndices[pos].r]) * k,\n scaleGreen[pos](d.vectors[vectorIndices[pos].g]) * k,\n scaleBlue[pos](d.vectors[vectorIndices[pos].b]) * k).toString();\n \n context.fillStyle = c;\n context.fill();\n context.stroke();\n offscreenContext.fill();\n });\n\n infoSVG[pos].on('mousemove', function() {\n const mouse = d3.mouse(this);\n \n\n var imageData = offscreenContext.getImageData(mouse[0], mouse[1], 1, 1);\n const color = d3.rgb.apply(null, imageData.data).toString();\n selectedIndex = colorToDataIndex[color];\n\n //console.log(color, selectedIndex, data[pos][selectedIndex]);\n\n let hidden = (typeof selectedIndex == 'undefined' || Math.abs(data[pos][selectedIndex].originX - mouse[0]) > 5 \n || Math.abs(data[pos][selectedIndex].originY - mouse[1]) > 5);\n\n highlight[pos].classed('hidden', hidden);\n \n infoSVG[pos].style('cursor', 'default');\n\n if(!hidden) {\n highlight[pos].attr('cx', data[pos][selectedIndex].originX)\n .attr('cy', data[pos][selectedIndex].originY);\n highlight[pos].attr('r', scaleSize[pos](data[pos][selectedIndex].vectors[vectorIndices[pos].size]) + 3);\n infoSVG[pos].style('cursor', 'pointer');\n } else selectedIndex = -1;\n });\n\n infoSVG[pos].on('click', function() {\n if(selectedIndex == -1 || typeof selectedIndex == 'undefined') return;\n\n var d = data[pos][selectedIndex];\n \n if(d.textbox.created == false) {\n var textboxMargin = { \n top: 15,\n bottom: 10,\n left: 10,\n right: 25\n };\n\n var textbox = infoSVG[pos].append('g')\n .attr('id', selectedIndex)\n .attr('class', 'textbox')\n .style('cursor', 'pointer');\n\n var text = textbox.append('text')\n .attr('x', d.originX + textboxMargin.left)\n .attr('y', d.originY)\n .style('text-anchor', 'start')\n .attr('dominant-baseline', 'hanging')\n .text(function() {\n //console.log(d.vectors_link[selectedIndex]);\n return d.text.trim();\n }).call(wrap, 300);\n\n textbox.on('mouseover', function() {\n text.style('fill', 'blue');\n })\n .on('mouseout', function() {\n text.style('fill', 'black')\n })\n .on('click', function() {\n var posToUpdate = (pos == LEFT)? RIGHT : LEFT;\n vectorIndices[posToUpdate].y = d.idx + 2; //+1 because 'All Topics' or 'Entire Corpus'\n vectorIndices[posToUpdate].r = d.idx + 2; //+1 because 'All Topics' or 'Entire Corpus'\n setChartZoom(posToUpdate);\n updateSizeScale(posToUpdate);\n updateColorScale(posToUpdate);\n updateKValueScale(posToUpdate);\n renderData(posToUpdate);\n redraw(posToUpdate);\n updateAxesTitle(posToUpdate);\n\n gui.yAxis[posToUpdate].setValue(data[posToUpdate].vectors_metadata[vectorIndices[posToUpdate].y]);\n gui.red[posToUpdate].setValue(data[posToUpdate].vectors_metadata[vectorIndices[posToUpdate].r]);\n \n });\n\n var bbox = text.node().getBBox();\n bbox.y = d.originY - bbox.height - textboxMargin.bottom;\n text.selectAll('tspan').attr('y', bbox.y);\n\n d.textbox.bbox = bbox;\n d.textbox.bbox.x -= textboxMargin.left;\n d.textbox.bbox.y -= textboxMargin.top;\n d.textbox.bbox.width += textboxMargin.left + textboxMargin.right;\n d.textbox.bbox.height += textboxMargin.top + textboxMargin.bottom;\n d.x = d.textbox.bbox.x;\n d.y = d.textbox.bbox.y;\n\n if(d.textbox.bbox.width < 160) d.textbox.bbox.width = 160;\n textbox.append('rect')\n .attr('x', d.textbox.bbox.x)\n .attr('y', d.textbox.bbox.y)\n .attr('width', d.textbox.bbox.width)\n .attr('height', d.textbox.bbox.height)\n .style('fill', d3.rgb(200, 200, 200, 0.5));\n\n textbox.append('line')\n .style('stroke', 'black')\n .attr('x1', d.textbox.bbox.x)\n .attr('y1', d.textbox.bbox.y + d.textbox.bbox.height)\n .attr('x2', d.textbox.bbox.x)\n .attr('y2', d.textbox.bbox.y + d.textbox.bbox.height);\n\n var linkbox = null;\n \n var width = (d.textbox.bbox.width > 160)? d.textbox.bbox.width : 160;\n\n var listX = d.vectors_link[vectorIndices[pos].x];\n var listY = d.vectors_link[vectorIndices[pos].y];\n \n var list = \"\";\n if(typeof listX != 'undefined') list = listX.trim();\n list += \" \";\n if(typeof listY != 'undefined') list += listY.trim();\n list = list.trim();\n\n if(list != \"\") {\n linkbox = infoSVG[pos].append('g')\n .attr('id', 'linkbox-' + selectedIndex)\n .style('cursor', 'pointer');\n\n var fo = linkbox.append('foreignObject')\n .attr('x', d.originX)\n .attr('y', d.originY)\n .attr('width', width)\n .attr('height', '150')\n .on('mouseover', function() { infoSVG[pos].on('.zoom', null); })\n .on('mouseout', function() { setChartZoom(pos);});\n \n var URLFormat = dataLinks[data_type_name[selectedDataType]];\n \n var div = fo.append('xhtml:div')\n .attr('class', 'linkbox')\n .style('font-size', '11px')\n .style('overflow-y', 'scroll')\n .style('word-break', 'break-all')\n .style('word-wrap', 'break-word')\n .style('background-color', d3.rgb(200, 200, 200, 0.9))\n .style('height', '100%')\n .html(function() {\n list = list.split(' ');\n var html = \"<ul>\";\n for(var i = 0; i < list.length;) {\n if(list[i] == \"\") {\n i++;\n } else {\n \n html += \"<li><span><a href='\" + URLFormat + list[i] \n + \"' target=\\'_blank\\'>\" + list[i] \n + \"(\" + list[i + 1] + \")</a></span></li>\" \n i += 2;\n }\n }\n html += \"</ul>\"\n\n return html;\n });\n\n d.linkbox.created = true;\n }\n\n var closeButton = textbox.append('g').on('click', function() {\n d.textbox.hidden = !d.textbox.hidden;\n \n textbox.classed('hidden', d.textbox.hidden);\n\n if(d.linkbox.created) {\n d.linkbox.hidden = !d.linkbox.hidden;\n linkbox.classed('hidden', d.linkbox.hidden);\n }\n\n d3.event.stopPropagation();\n });;\n\n let buttonRadius = 8;\n let crossOffset = buttonRadius * 0.5;\n let buttonCenterX = d.textbox.bbox.x + d.textbox.bbox.width - buttonRadius * 1.5;\n let buttonCenterY = d.textbox.bbox.y + buttonRadius * 1.5;\n\n closeButton.append('circle')\n .classed('closeButton', true)\n .attr('cx', buttonCenterX)\n .attr('cy', buttonCenterY)\n .attr('r', buttonRadius)\n .style('fill', d3.rgb(0, 0, 0, 0.5))\n .style('cursor', 'pointer');\n \n var cross = closeButton.append('g');\n\n cross.style('cursor', 'pointer');\n\n cross.append('line')\n .attr(\"x1\", buttonCenterX - buttonRadius + crossOffset)\n .attr(\"y1\", buttonCenterY)\n .attr(\"x2\", buttonCenterX + buttonRadius - crossOffset)\n .attr(\"y2\", buttonCenterY);\n \n cross.append('line')\n .attr(\"x1\", buttonCenterX)\n .attr(\"y1\", buttonCenterY - buttonRadius + crossOffset)\n .attr(\"x2\", buttonCenterX)\n .attr(\"y2\", buttonCenterY + buttonRadius - crossOffset);\n\n cross.attr(\"transform\", \"rotate (45,\" + buttonCenterX + \",\" + buttonCenterY + \")\");\n\n cross.style('stroke', 'white')\n .style('stroke-width', 1.5);\n\n d.x = 0, d.y = 0;\n\n textbox.call(d3.drag()\n .on('start', function() {\n //d3.select(this).moveToFront();\n })\n .on('drag', function() {\n if(d3.select(this).select('rect').classed('active') == false) {\n d3.select(this).select('rect').classed('active', true);\n d3.select(this).select('line').classed('active', true);\n textbox.style('cursor', 'move');\n }\n\n d.textbox.bbox.x += d3.event.dx;\n d.textbox.bbox.y += d3.event.dy;\n\n d.x += d3.event.dx;\n d.y += d3.event.dy;\n\n d3.select(this).attr(\"transform\", \"translate(\" + (d.x) + \",\" + (d.y) + \")\");\n //console.log(d.linkbox.created);\n if(d.linkbox.created) {\n var id = d3.select(this).attr('id')\n //console.log(id);\n infoSVG[pos].select(\"g[id='linkbox-\" + id + \"']\").attr(\"transform\", \"translate(\" + (d.x) + \",\" + (d.y) + \")\");\n //linkbox.select('ul').attr(\"transform\", \"translate(\" + (d.x) + \",\" + (d.y) + \")\");\n }\n\n d3.select(this).select('line')\n .attr(\"transform\", \"translate(\" + (-d.x) + \",\" + (-d.y) + \")\")\n .attr('x1', d.originX)\n .attr('y1', d.originY)\n .attr(\"x2\", (d.textbox.bbox.x))\n .attr(\"y2\", (d.textbox.bbox.y + d.textbox.bbox.height));\n })\n .on('end', function() {\n d3.select(this).select('rect').classed('active', false);\n d3.select(this).select('line').classed('active', false);\n\n textbox.style('cursor', 'pointer');\n }));\n\n d.textbox.created = true;\n d.textbox.hidden = false;\n } else if(d.textbox.hidden) {\n d.textbox.hidden = !d.textbox.hidden;\n infoSVG[pos].select(\".textbox[id='\" + selectedIndex + \"']\").classed('hidden', d.textbox.hidden);\n\n if(d.linkbox.created) {\n d.linkbox.hidden = !d.linkbox.hidden;\n infoSVG[pos].select(\"g[id='linkbox-\" + selectedIndex + \"']\").classed('hidden', d.linkbox.hidden);\n }\n }\n });\n\n infoSVG[pos].on('mouseout', () => {\n highlight[pos].classed('hidden', true);\n infoSVG[pos].style('cursor', 'default');\n });\n}", "createVis(debugData, otherDebugData, cp_idx, tc_idx) {\n\t\t// Deep copy object arrays. Transform it to\n\t\t// be able to differentiate between the current\n\t\t// run's and the other run's data\n\t\tvar dataArr1 = debugData.dataArray.map((el, i) => {\n\t\t\treturn JSON.parse(JSON.stringify(el));\n\t\t});\n\t\tvar dataArr2 = otherDebugData.dataArray.map((el, i) => {\n\t\t\treturn JSON.parse(JSON.stringify(el));\n\t\t});\n\n\t\tvar data1 = dataArr1.map((el, i) => {\n\t\t\tif (el[\"@current\"] === undefined) el[\"@current\"] = true;\n\t\t\treturn el;\n\t\t});\n\t\tvar data2 = dataArr2.map((el, i) => {\n\t\t\tif (el[\"@current\"] === undefined) el[\"@current\"] = false;\n\t\t\treturn el;\n\t\t});\n\n\t\t// Trick to maintain the color saliency of rendering; if we have\n\t\t// the display of data of another run overlaid, we want to maintain\n\t\t// the color mapping of (blue: another run result, orange: this run result)\n\t\t//var data = data2.concat(data1);\n\t\tvar data = data2.concat(data1);\n\n\t\t// If the student changed the variable names...\n\t\tvar varDataSet1 = debugData.localVarNames;\n\t\tvar varDataSet2 = otherDebugData.localVarNames;\n\t\tvar varData = Array.from(new Set(function*() { yield* varDataSet1; yield* varDataSet2; }()));\n\t\tvarData.push(\"@line no.\");\n\t\tvarData.push(\"@execution step\");\n\n\t\tvar width = 780,\n\t\t\theight = 780,\n\t\t\tpadding = 20,\n\t\t size = (width - 2 * padding) / varData.length;\n\t\t\n\t\tvar x = d3.scale.linear()\n\t\t .range([padding / 2, size - padding / 2]);\n\n\t\tvar y = d3.scale.linear()\n\t\t .range([size - padding / 2, padding / 2]);\n\n\t\tvar xAxis = d3.svg.axis()\n\t\t .scale(x)\n\t\t .orient(\"bottom\")\n\t\t .ticks(6);\n\n\t\tvar yAxis = d3.svg.axis()\n\t\t .scale(y)\n\t\t .orient(\"left\")\n\t\t .ticks(6);\n\n\t\tvar color = d3.scale.category10();\n\n\t\tvar domainByVarName = {},\n\t\t\tvarNames = d3.values(varData),\n\t\t\tn = varData.length;\n\n\t\tvarData.forEach(function (name) {\n\t\t\tvar tmpDomain = d3.extent(data, function(d) { return d[name]; });\n\t\t\tif (tmpDomain[0] === tmpDomain[1]) { // If there's only value in the domain, extend it\n\t\t\t\t\t\t\t\t\t\t\t\t // by including its -1 and +1 values\n\t\t\t\tdomainByVarName[name] = [tmpDomain[0] - 1, tmpDomain[1] + 1];\n\t\t\t} else {\n\t\t\t\tdomainByVarName[name] = tmpDomain;\n\t\t\t}\n\t\t});\n\n\t\txAxis.tickSize(size * n);\n\t\tyAxis.tickSize(-size * n);\n\t\t\n\t\t// Remove the old SVG\n\t\td3.select(\"#cross-vis-div-svg\" + cp_idx + \"-\" + tc_idx).remove();\n\n\t\t// Create a new one\n\t\tvar svg = d3.select(\"#cross-vis-div\" + cp_idx + \"-\" + tc_idx)\n\t\t\t\t .append(\"svg\")\n\t\t\t\t .attr(\"id\", () => { return \"cross-vis-div-svg\" + cp_idx + \"-\" + tc_idx; })\n\t\t\t\t\t.attr(\"width\", width)\n\t\t\t\t\t.attr(\"height\", height)\n\t\t\t\t\t.append(\"g\")\n\t\t\t\t\t.attr(\"transform\", \"translate(\" + padding + \",\" + padding + \")\");\n\n\t\tvar brush = d3.svg.brush()\t\t\n\t\t .x(x)\t\t\n\t\t .y(y)\t\t\n\t\t .on(\"brushstart\", brushstart)\n\t\t .on(\"brush\", (p) => { // Highlight the selected circles.\n\t\t\t\tvar e = brush.extent();\n\t\t\t\tvar brushedCircleLines1 = new Set();\n\t\t\t\tvar brushedCircleLines2 = new Set();\n\t\t\t\tsvg.selectAll(\"circle\").classed(\"hidden\", function(d) {\n\t\t\t\t\t// NOTE: e[0][0] = x0, e[0][1] = y0, e[1][0] = x1, e[1][1] = y1,\n\t\t\t\t\t// where [x0, y0] is the top-left corner\n\t\t\t\t\t// and [x1, y1] is the bottom-right corner\n\t\t\t\t\tif (e[0][0] > d[p.x] || d[p.x] > e[1][0]\n\t\t\t\t\t|| e[0][1] > d[p.y] || d[p.y] > e[1][1]) {\n\t\t\t\t\t\t// Hide the circles\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\td[\"@current\"] ? brushedCircleLines1.add(d[\"@line no.\"])\n\t\t\t\t\t\t\t\t : brushedCircleLines2.add(d[\"@line no.\"]);\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\n\t\t\t\tthis.removeMouseupGutterHighlights();\n\t\t\t\tthis.highlightCodeLines(Array.from(brushedCircleLines1));\n\t\t\t\tthis.highlightCodeLinesInDiffView(Array.from(brushedCircleLines2));\n\t\t })\n\t\t .on(\"brushend\", () => { // If the brush is empty, select all circles.\n\t\t \tif (brush.empty()) {\n\t\t \t\tsvg.selectAll(\".hidden\").classed(\"hidden\", false);\n\t\t \t\tthis.removeMouseupGutterHighlights();\n\t\t \t\tthis.dehighlightPrevCodeLinesInDiffView();\n\t\t \t}\n\t\t });\n\n\t\tsvg.selectAll(\".x.axis\")\n\t\t\t.data(varNames)\n\t\t.enter().append(\"g\")\n\t\t\t.attr(\"class\", \"x axis\")\n\t\t\t.attr(\"transform\", function(d,i) { return \"translate(\" + (n - i - 1) * size + \",0)\"; })\n\t\t\t.each(function(d) { x.domain(domainByVarName[d]); d3.select(this).call(xAxis); });\n\n\t\tsvg.selectAll(\".y.axis\")\n\t\t\t.data(varNames)\n\t\t.enter().append(\"g\")\n\t\t\t.attr(\"class\", \"y axis\")\n\t\t\t.attr(\"transform\", function(d, i) { return \"translate(0,\" + i * size + \")\"; })\n\t\t\t.each(function(d) { y.domain(domainByVarName[d]); d3.select(this).call(yAxis); });\n\n\t\tvar cell = svg.selectAll(\".cell\")\n\t\t\t\t\t.data(this.cross(varNames, varNames))\n\t\t\t\t.enter().append(\"g\")\n\t\t\t\t\t.filter(function(d) { return d.i > d.j; })\n\t\t\t\t\t.attr(\"class\", \"cell\")\n\t\t\t\t\t.attr(\"transform\", function(d) { return \"translate(\" + (n - d.i - 1) * size + \",\" + d.j * size + \")\"; });\n\n\t\t// y axis labels\n\t\tcell.filter(function(d) { return (d.i - d.j) === 1; })\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"x\", function(d, i) { return d.i * size + padding; })\n\t\t\t.attr(\"y\", function(d, i) { return size / 2; })\n\t\t\t.attr(\"dy\", \".71em\")\n\t\t\t.text(function(d) { return d.y; });\n\n\t\t// x axis labels\n\t\tcell.filter(function(d) { return (d.i - d.j) === 1; })\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"x\", function(d, i) { return padding; })\n\t\t\t.attr(\"y\", function(d, i) { return (n - 1 - d.j) * size + padding; })\n\t\t\t.attr(\"dy\", \".71em\")\n\t\t\t.text(function(d) { return d.x; });\n\n\t\tcell.call(brush);\n\t\tcell.each(plot);\n\t\tcell.selectAll(\"circle\")\n\t\t .on(\"mouseover\", function() {\n\t\t \treturn tooltip.style(\"visibility\", \"visible\");\n\t\t })\n\t \t\t.on(\"mousemove\", (d) => {\n\t \t\t\tconsole.log(cell);\n\t \t\t\tvar cell = d3.select(this); // we replaced this with the outer context by using the (d) => {} function...\n\t \t\t\t//console.log(d);\n\t \t\t\t//console.log(cell.data()[0]);\n\t \t\t\t//console.log(cell.data());\n\t \t\t\t//var x = cell.data()[0].x;\n\t \t\t\t//var y = cell.data()[0].y;\n\n\t \t\t\t//var translate = d3.transform(cell.attr(\"transform\")).translate;\n\t \t\t\tvar coordinates = d3.mouse(svg.node()); // position relative to the svg element\n\t \t\t\t\n\t \t\t\ttooltip.html(\"<p><strong>Execution step\" + \": \" + d[\"@execution step\"] + \"</strong></p><p><strong>Code line: \" + d[\"@line no.\"] + \"</strong></p>\");\n\t \t\t\tthis.removeMouseupGutterHighlights();\n\t \t\t\td[\"@current\"] ? this.highlightCodeLines([d[\"@line no.\"]])\n\t \t\t\t\t\t\t : this.highlightCodeLinesInDiffView([d[\"@line no.\"]]);\n\n\t \t\t\treturn tooltip.style(\"top\", (coordinates[1] + 500) + \"px\")\n\t \t\t\t\t\t\t .style(\"left\", coordinates[0] + \"px\");\n\t \t\t})\n\t \t\t.on(\"mouseout\", () => {\n\t \t\t\tthis.removeMouseupGutterHighlights();\n\t \t\t\tthis.dehighlightPrevCodeLinesInDiffView();\n\t \t\t\treturn tooltip.style(\"visibility\", \"hidden\");\n\t \t\t});\n\n\t\tvar svgContainer = d3.select(\"#cross-vis-div\" + cp_idx + \"-\" + tc_idx);\n\t\tvar tooltip = svgContainer.append(\"div\")\n\t\t\t\t\t\t\t\t .style(\"position\", \"absolute\")\n\t\t\t\t\t\t\t\t .style(\"z-index\", \"1001\")\n\t\t\t\t\t\t\t\t .style(\"visibility\", \"hidden\");\n\n\t\tvar brushCell;\n\n\t\tfunction plot(p) {\n\t\t\tvar cell = d3.select(this);\n\n\t\t\tx.domain(domainByVarName[p.x]);\n\t\t\ty.domain(domainByVarName[p.y]);\n\n\t\t\tcell.append(\"rect\")\n\t\t\t .attr(\"class\", \"frame\")\n\t\t\t .attr(\"x\", padding / 2)\n\t\t\t .attr(\"y\", padding / 2)\n\t\t\t .attr(\"width\", size - padding)\n\t\t\t .attr(\"height\", size - padding)\n\t\t\t .style(\"pointer-events\", \"none\");\n\n\t\t\t// Cross for other data\n\t\t\tcell.selectAll(\"path\")\n\t\t\t .data(data)\n\t\t\t .enter().append(\"path\")\n\t\t\t .filter(function(d) { return (d[p.x] !== undefined) && (d[p.y] !== undefined) && !d[\"@current\"]; })\n\t\t\t \t.attr(\"d\", d3.svg.symbol()\n\t\t\t \t\t.size(function(d) { return 5 * 5; }) // size in square pixels\n\t\t\t \t\t.type(function(d) { return \"diamond\"; }))\n\t\t\t \t.attr(\"transform\", function(d) { return \"translate(\" + x(d[p.x]) + \",\" + y(d[p.y]) +\")\"; })\n\t\t\t .style(\"fill\", function(d) { return d3.rgb(82,209,255,0.2); });\n\n\t\t\t// Dot for current data\n\t\t\tcell.selectAll(\"circle\")\n\t\t\t .data(data)\n\t\t\t .enter().append(\"circle\")\n\t\t\t .filter(function(d) { return (d[p.x] !== undefined) && (d[p.y] !== undefined) && d[\"@current\"]; })\n\t\t\t .attr(\"cx\", function(d) { return x(d[p.x]); })\n\t\t\t .attr(\"cy\", function(d) { return y(d[p.y]); })\n\t\t\t .attr(\"r\", 2)\n\t\t\t .style(\"fill\", function(d) { return d3.rgb(255,127,80,0.2); });\n\t\t}\n\n\t\t// Clear the previously-active brush, if any.\n\t\tfunction brushstart(p) {\n\t\t\tif (brushCell !== this) {\t\t\n\t\t\t\td3.select(brushCell).call(brush.clear());\t\t\n\t\t\t\tx.domain(domainByVarName[p.x]);\t\t\n\t\t\t\ty.domain(domainByVarName[p.y]);\t\t\n\t\t\t\tbrushCell = this;\t\t\n\t\t\t}\t\t\n\t\t}\n\t}", "createVisualization(json) {\n var that = this;\n var path;\n var radius = Math.min(this.opt.width, this.opt.height) / 2.1;\n this.radius = radius;\n var formatNumber = d3.format(\",d\");\n var x = d3.scaleLinear()\n .range([0, 2 * Math.PI]);\n var y = d3.scaleSqrt()\n .range([0, radius]);\n d3.select(this.opt.selectors.chart);\n var arc = d3.arc()\n .startAngle(function (d) {\n return Math.max(0, Math.min(2 * Math.PI, x(d.x0)));\n })\n .endAngle(function (d) {\n return Math.max(0, Math.min(2 * Math.PI, x(d.x1)));\n })\n .innerRadius(function (d) {\n return Math.max(0, y(d.y0));\n })\n .outerRadius(function (d) {\n return Math.max(0, y(d.y1));\n });\n var svg = d3.select(this.opt.selectors.chart).append(\"svg\")\n .attr(\"width\", this.opt.width)\n .attr(\"height\", this.opt.height)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + this.opt.width / 1.8 + \",\" + (this.opt.height / 1.8) + \")\");\n svg.append(\"svg:circle\")\n .attr(\"r\", radius)\n .style(\"opacity\", 0);\n\n this.svg = svg;\n\n function click(d) {\n svg.transition()\n .duration(950)\n .tween(\"scale\", function () {\n var xd = d3.interpolate(x.domain(), [d.x0, d.x1]), yd = d3.interpolate(y.domain(), [d.y0, 1]),\n yr = d3.interpolate(y.range(), [d.y0 ? 20 : 0, radius]);\n return function (t) {\n x.domain(xd(t));\n y.domain(yd(t)).range(yr(t));\n };\n })\n .selectAll(\"path\")\n .attrTween(\"d\", function (d) {\n return function () {\n return arc(d);\n };\n });\n }\n\n\n var root = d3.hierarchy(json)\n .sum(function (d) {\n return d.size;\n })\n .sort(function (a, b) {\n return b.height - a.height;\n });\n var partition = d3.partition()\n\n var nodes = partition(root).descendants().filter(function (d) {\n return (d.x1 - d.x0 > 0.002); // 0.005 radians = 0.29 degrees\n });\n\n path = this.svg.selectAll(\"path\")\n .data(nodes)\n var exit = path.exit().remove();\n path\n .enter().append(\"path\").attr(\"d\", arc)\n .style(\"fill\", function (d) {\n if (d.data.name == \"root\") {\n return \"#fff\";\n }\n else {\n var color = that.getColor(d.data.name.split(\"/\")[0], d.data.name.split(\"/\")[1]);\n //return that.opt.color(d.data.name.split(\"/\")[0]);\n console.log(d.data.name, color)\n return color;\n }\n })\n .on(\"click\", click)\n .on(\"mouseover\", this.mouseover.bind(this));\n this.initializeBreadcrumbTrail();\n\n let namesArr = this.getNodeNames(nodes[0]);\n try {\n this.drawLegend(namesArr.sort());\n\n\n //this.updateScale(namesArr[0].split(\"/\").length)\n }\n catch (e) {\n console.log(e);\n }\n svg.select(\"circle\").on(\"mouseleave\", this.mouseleave.bind(this));\n //d3.select(\"#togglelegend\").on(\"click\", that.toggleLegend.bind(this));\n //this.toggleLegend.call()\n d3.select(\"#reset\").on(\"click\", this.reset.bind(this));\n this.totalSize = root.value;\n this.root = root;\n // d3.select(\"#treshold\").on(\"input\", this.filterData(root));\n\n }", "constructor(element){\n // select the div in the ChartWrapper return\n // append svg canvas, set width and height\n // store svg in a var to keep track of where it is\n const svg = d3.select(element)\n .append(\"svg\")\n .attr(\"width\", 500)\n .attr(\"height\", 500)\n\n // append rectangle to svg canvas\n // x and y position rect based on top left corner of canvas\n svg.append(\"rect\")\n .attr(\"x\", 50)\n .attr(\"y\", 50)\n .attr(\"width\", 100)\n .attr(\"height\", 400)\n .attr(\"fill\", \"grey\")\n }", "constructor(legos, tableChart, topThemesChart, biggestSetsChart, mostExpensiveSetsChart, priceVTimeChart, sizeVTimeChart) {\r\n\r\n this.legos = legos;\r\n this.years = new Array();\r\n for (var i = 1971; i < 2016; i++) {\r\n this.years.push(i);\r\n }\r\n this.firstTime = true;\r\n this.tableChart = tableChart;\r\n this.biggestSetsChart = biggestSetsChart;\r\n this.topThemesChart = topThemesChart;\r\n this.mostExpensiveSetsChart = mostExpensiveSetsChart;\r\n this.priceVTimeChart = priceVTimeChart;\r\n this.sizeVTimeChart = sizeVTimeChart;\r\n\r\n this.updateCharts(this.years);\r\n\r\n // Initializes the svg elements required for this chart\r\n this.margin = { top: 10, right: 20, bottom: 30, left: 50 };\r\n let divyearChart = d3.select(\"#year-chart\").classed(\"fullView\", true);\r\n\r\n //fetch the svg bounds\r\n this.svgBounds = divyearChart.node().getBoundingClientRect();\r\n this.svgWidth = this.svgBounds.width - this.margin.left - this.margin.right;\r\n this.svgHeight = 120;\r\n\r\n //add the svg to the div\r\n this.svg = divyearChart.append(\"svg\")\r\n .attr(\"width\", this.svgWidth)\r\n .attr(\"height\", this.svgHeight);\r\n\r\n this.selected = null;\r\n }", "function draw() {\n // + FILTER DATA BASED ON STATE\n let filteredData = [];\n if (state.selectedCountry !== null) {\n filteredData = state.data.filter(d => d.country === state.selectedCountry)\n }\n console.log(filteredData);\n //\n // + UPDATE SCALE(S), if needed\n yScale.domain([0, d3.max(filteredData, d => d.number)]);\n // + UPDATE AXIS/AXES, if needed\n d3.select(\"g.y-axis\")\n .transition()\n .duration(1000)\n .call(yAxis.scale(yScale));\n\n // we define our line function generator telling it how to access the x,y values for each point\n\n const lineFunc = d3\n .line()\n .x(d => xScale(d.year))\n .y(d => yScale(d.number));\n const areaFunc = d3\n .area()\n .x(d => xScale(d.year))\n .y1(d => yScale(d.number))\n .y0(yScale(0));\n\n // + DRAW CIRCLES, if you decide to\n const dot = svg\n .selectAll(\".dot\")\n .data(filteredData, d => d.country) // use `d.year` as the `key` to match between HTML and data elements\n .join(\n enter => // + HANDLE ENTER SELECTION\n enter // enter selections -- all data elements that don't have a `.dot` element attached to them yet\n .append(\"circle\")\n .attr(\"fill\", \"green\")\n .attr(\"class\", \"dot\")\n .attr(\"r\", radius)\n .attr(\"cx\", d => xScale(d.year))\n .attr(\"cy\", d => yScale(d.number)),\n\n\n\n update => update, // + HANDLE UPDATE SELECTION\n exit => // + HANDLE EXIT SELECTION\n exit.call(exit =>\n // exit selections -- all the `.dot` element that no longer match to HTML elements \n exit\n .remove()\n\n )\n )\n\n .call(\n selection =>\n selection\n .transition()\n .duration(1000)\n .attr(\"cy\", d => yScale(d.number))\n );\n //\n // + DRAW LINE AND AREA\n const line = svg\n .selectAll(\"path.trend\")\n .data([filteredData])\n .join(\n enter =>\n enter\n .append(\"path\")\n .attr(\"class\", \"trend\")\n .attr(\"opacity\", 0),\n // .attr(0, \"opacity\"), // start them off as opacity 0 and fade them in\n update => update, // pass through the update selection\n exit => exit\n .transition()\n .remove(),\n )\n .call(selection =>\n selection\n .transition()\n .duration(1000)\n .attr(\"opacity\", 0.8)\n .attr(\"d\", d => lineFunc(d))\n )\n const area = svg\n .selectAll(\".area\")\n .data([filteredData])\n .join(\"path\")\n .attr(\"class\", \"area\")\n .attr(\"cx\", (width - margin.left))\n .attr(\"d\", d => areaFunc(d));\n\n\n\n\n}", "updateGraphicsData() {\n // override\n }", "function graphical_Application(id, w, h){\r\n\t\t\t\r\n\tthis.width = w;\r\n\tthis.height = h;\r\n\t\t\r\n\tthis.graphical_Switch = d3.select(id).transition();\r\n\r\n\tthis.current_Element = 0;\r\n\tthis.element_Array = new Array();\r\n\t\t\t\r\n\tfor(var index = 0; index < 15; index++){\r\n\t\t\t\t\r\n\t\tthis.element_Array[index] = new Object();\r\n\t\tthis.element_Array[index].id = \"rect\" + index;\r\n\t\tthis.element_Array[index].value = index + 1;\r\n\t} \r\n\t\t\t\r\n\tthis.svg = d3.select(id).append(\"svg\");\r\n\tthis.svg.attr(\"height\", this.height)\r\n\t\t\t.attr(\"width\", this.width); \r\n\t\t\t\t\t\r\n\tthis.randomise_Elements();\r\n\tthis.display_Rectangles();\r\n\t\t\t\t\t\t\r\n\tthis.frame_Work = new Array();\r\n\t\t\t\r\n\tthis.create_Frame_Work(function(){\r\n\t\t\t\t\r\n\t\treturn d3.select(id).transition();\r\n\t});\r\n\t\t\r\n\tthis.selection_Sort(); \r\n\r\n\tthis.activate_Sort = false;\r\n}", "initVis() {\n let vis = this;\n\n // Define size of SVG drawing area\n vis.svg = d3.select(vis.config.parentElement)\n .attr('width', vis.config.containerWidth)\n .attr('height', vis.config.containerHeight)\n .attr(\"rx\", 20).attr(\"ry\", 20);\n\n // add a lightgray outline for the rect of lexis svg\n vis.svg\n .append(\"rect\")\n .attr(\"width\", vis.config.containerWidth)\n .attr(\"height\", vis.config.containerHeight)\n .attr(\"stroke\", \"lightgray\")\n .attr(\"fill\", \"none\");\n\n\n // Append group element that will contain our actual chart \n // and position it according to the given margin config\n vis.chartArea = vis.svg.append('g')\n .attr('transform', `translate(${vis.config.margin.left},${vis.config.margin.top})`);\n\n\n\n // define inner box size\n vis.innerHeight =\n vis.config.containerHeight -\n vis.config.margin.top -\n vis.config.margin.bottom;\n\n vis.innerWidth =\n vis.config.containerWidth -\n vis.config.margin.left -\n vis.config.margin.right;\n\n vis.chart = vis.chartArea.append('g');\n\n\n /**\n * Have implemented this part in HTML file\n */\n // Create default arrow head\n // Can be applied to SVG lines using: `marker-end`\n // vis.chart.append('defs').append('marker')\n // .attr('id', 'arrow-head')\n // .attr('markerUnits', 'strokeWidth')\n // .attr('refX', '2')\n // .attr('refY', '2')\n // .attr('markerWidth', '10')\n // .attr('markerHeight', '10')\n // .attr('orient', 'auto')\n // .append('path')\n // .attr('d', 'M0,0 L2,2 L 0,4')\n // .attr('stroke', '#ddd')\n // .attr('fill', 'none');\n\n\n // apply clipping mask to 'vis.chart', restricting the region at the very beginning and end of a year\n vis.chart\n .append(\"defs\")\n .append(\"clipPath\")\n .attr(\"id\", \"chart-mask\")\n .append(\"rect\")\n .attr(\"width\", vis.config.containerWidth)\n .attr(\"height\", vis.config.containerHeight);\n vis.chart.attr(\"clip-path\", \"url(#chart-mask)\");\n\n // text label for lexischart\n vis.svg\n .append(\"text\")\n .attr(\"y\", 25)\n .attr(\"x\", 10)\n .attr(\"class\", \"text-label\")\n .text(\"Age\");\n\n // Todo: initialize scales, axes, static elements, etc.\n\n // define x-axis scale\n vis.yearScale = d3\n .scaleLinear()\n .domain([1950, 2021])\n .range([0, vis.innerWidth]);\n\n // define y-axis scale\n vis.ageScale = d3\n .scaleLinear()\n .domain([25, 95])\n .range([vis.innerHeight, 0]);\n\n //define y-axis\n vis.chartArea\n .append(\"g\")\n .call(d3.axisLeft(vis.ageScale).tickValues([40, 50, 60, 70, 80, 90]));\n\n // define x-axis\n vis.chartArea\n .append(\"g\")\n .attr(\"transform\", `translate(0,${vis.innerHeight})`)\n .call(d3.axisBottom(vis.yearScale).tickFormat(d3.format(\"\"))); // tickFormat can make x-axis tick's label without comma, like 1,950\n\n // remove path on the axis\n vis.chartArea.selectAll(\"path\").remove();\n\n // define tooltip\n d3.select(\"body\")\n .append(\"div\")\n .attr(\"class\", \"tip\")\n .attr(\"visible\", \"hidden\")\n .style(\"position\", \"absolute\");\n }", "function render_panel() {\n\n var width = $(elem[0]).width(),\n height = $(elem[0]).height();\n\n //Projection is dependant on the map-type\n if (scope.panel.display.data.type === 'mercator') {\n dr.projection = d3.geo.mercator()\n .translate([width/2, height/2])\n .scale(dr.scale);\n\n } else if (scope.panel.display.data.type === 'orthographic') {\n dr.projection = d3.geo.orthographic()\n .translate([width/2, height/2])\n .scale(100)\n .clipAngle(90);\n\n //recenters the sphere more towards the US...not really necessary\n dr.projection.rotate([100 / 2, 20 / 2, dr.projection.rotate()[2]]);\n\n }\n\n dr.path = d3.geo.path()\n .projection(dr.projection).pointRadius(0.2);\n\n console.log(scope.data);\n\n //Geocoded points are decoded into lonlat\n dr.points = _.map(scope.data, function (k, v) {\n //console.log(k,v);\n var decoded = geohash.decode(v);\n return [decoded.longitude, decoded.latitude];\n });\n\n //And also projected projected to x/y. Both sets of points are used\n //by different functions\n dr.projectedPoints = _.map(dr.points, function (coords) {\n return dr.projection(coords);\n });\n\n dr.svg.select(\".overlay\").remove();\n\n dr.svg.append(\"rect\")\n .attr(\"class\", \"overlay\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n\n\n //Draw the countries, if this is a choropleth, draw with fancy colors\n var countryPath = dr.g.selectAll(\".land\")\n .data(dr.countries);\n\n countryPath.enter().append(\"path\")\n .attr(\"class\", function(d) {\n if (scope.panel.display.choropleth.enabled) {\n return 'land ' + dr.quantize(scope.data[d.short]);\n } else {\n return 'land';\n }\n })\n .attr(\"d\", dr.path);\n\n countryPath.exit().remove();\n\n //If this is a sphere, set up drag and keypress listeners\n if (scope.panel.display.data.type === 'orthographic') {\n dr.svg.style(\"cursor\", \"move\")\n .call(d3.behavior.drag()\n .origin(function() { var rotate = dr.projection.rotate(); return {x: 2 * rotate[0], y: -2 * rotate[1]}; })\n .on(\"drag\", function() {\n if (scope.keylistener.keyActive(17)) {\n dr.projection.rotate([d3.event.x / 2, -d3.event.y / 2, dr.projection.rotate()[2]]);\n\n //dr.svg.selectAll(\"path\").attr(\"d\", dr.path);\n dr.g.selectAll(\"path\").attr(\"d\", dr.path);\n\n }\n }));\n\n\n }\n\n //Special fix for when the user changes from mercator -> orthographic\n //The globe won't redraw automatically, we need to force it\n if (scope.panel.display.data.type === 'orthographic') {\n dr.svg.selectAll(\"path\").attr(\"d\", dr.path);\n }\n\n\n /**\n * Display option rendering\n * Order is important to render order here!\n */\n\n //@todo fix this\n var dimensions = [width, height];\n displayBinning(scope, dr, dimensions);\n displayGeopoints(scope, dr);\n displayBullseye(scope, dr);\n\n\n\n\n //If the panel scale is not default (e.g. the user has moved the maps around)\n //set the scale and position to the last saved config\n if (scope.panel.display.scale != -1) {\n dr.zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);\n dr.g.style(\"stroke-width\", 1 / scope.panel.display.scale).attr(\"transform\", \"translate(\" + scope.panel.display.translate + \") scale(\" + scope.panel.display.scale + \")\");\n\n }\n\n }", "createGraph(data) {\n\n if (!data) return;\n\n if (this.svg) this.svg.remove();\n\n this.svg = d3.select('#' + this.compId).append('svg').attr('width', this.width).attr('height', this.height);\n\n // Create ranges\n // Define the min and max x values\n let xMin = d3.min(data, (d) => {return d.x});\n let xMax = d3.max(data, (d) => {return d.x});\n\n // Define the min and max y values\n // let yMin = d3.min(data, (d) => {return d.y});\n let yMax = d3.max(data, (d) => {return d.y});\n\n // Update the scales\n this.x = d3.scaleLinear().range([this.marginH - this.textPaddingH, this.width - this.marginH + this.textPaddingH]).domain([xMin, xMax]);\n this.y = d3.scaleLinear().range([this.height - this.marginV, this.marginV + this.textPaddingV]).domain([0, yMax]);\n\n // Lines\n this.createLines(data);\n // Caps\n if (this.props.showValuePoints == null || this.props.showValuePoints) this.createCaps(data);\n // Text\n if (this.props.valueLabelTransform) this.createValueLabels(data);\n // X Labels\n if (this.props.xAxisTransform) this.createXAxis(data);\n\n }", "updateVis() {\n let vis = this;\n\n // Data Processing Functions: \n vis.groups = d3.rollup(vis.data, v => d3.mean(v, d => d.Consumption), d => d.Country, d => d.Type); // Mean Consumption across all time for country by type\n vis.countries = d3.rollup(vis.data, v => [v[0].lat, v[0].lon], d => d.Country); // LatLon by Country\n vis.linegroups = d3.group(vis.data, d => d.Country, d => d.Type); // Scatterplot Data for each type, by country\n vis.years = d3.extent(vis.data, d => d.Year); // Extent Year Range\n vis.consumption = d3.rollup(vis.data, v => d3.extent(v, d => d.Consumption), d => d.Country); // Consumption extent, by country\n vis.renderVis();\n }", "constructor(element) {\n // by convention, we store SVG canvas in a variable - svg\n // so that we can modify our SVG canvas\n const svg = d3\n .select(element)\n // here we are saying we want to add SVG canvas to this element\n .append('svg')\n // overriding default width & height with attr method\n .attr('width', 500)\n .attr('height', 500);\n\n // adding rectangle with its attribs to show up in the screen\n // data.forEach((item, i) => {\n // svg\n // .append('rect')\n // .attr('x', i * 100)\n // .attr('y', 50)\n // .attr('width', 50)\n // // array data\n // .attr('height', item)\n // .attr('fill', 'grey');\n // });\n\n // d3.json() to fetch JSON data & to convert into an array of data\n // d3.json(url) returns a Promise\n d3.json(url).then(agesData => {\n // Data Joins in D3 - to add Dynamic Data into DOM\n // selecting all the rectangles in our screen\n const rects = svg\n .selectAll('rect')\n // data binding - to add our Array 'data' above using data method into DOM elements\n .data(agesData);\n\n rects\n // enter method gets a data & appends to the DOM\n .enter()\n // adding rectangle in SVG with its attribs to show up in the screen\n .append('rect')\n // setting x value with callback function\n // d is array item, i is an array index\n .attr('x', (d, i) => i * 100)\n .attr('y', 50)\n .attr('width', 50)\n // array data - Height value should be equal to the 'age' property of each objects\n // * 10 - to make the bars size 10 times larger\n .attr('height', d => d.age * 10)\n // just with any attr, we set fill by using a function\n .attr('fill', d => {\n // to customize bars according to the data\n if (d.age > 10) {\n return 'red';\n }\n return 'green';\n });\n });\n }", "function bind(chartData) {\n var node = this,\n transformName = chartData.transformName || _transformName,\n title = chartData.title || _title,\n margin = chartData.margin || _margin,\n outerSize = chartData.size || _size,\n defaultPlotter = chartData.plotter || _plotter,\n dataApi = chartData.dataApi || _dataApi,\n transitionTime = chartData.transitionTime || _transitionTime,\n padding = chartData.padding || _padding,\n showLegend = (\"showLegend\" in chartData) ? chartData.showLegend : _showLegend,\n selection = d3.select(this),\n inheritedTransition = d3.transition(selection),\n paddedPlotSize = [outerSize[0] - margin.left - margin.right,\n outerSize[1] - margin.top - margin.bottom],\n plotSpot = [margin.left + padding[0],\n margin.top + padding[1]], \n plotSize = [paddedPlotSize[0] - (2 * padding[0]), \n paddedPlotSize[1] - (2 * padding[1])],\n titleMargin = chartData.titleMargin || _titleMargin,\n groups = chartData.groups || emptyGroups,\n timeSeries = (\"timeSeries\" in chartData) ? chartData.timeSeries : _timeSeries,\n showXAxis = (\"showXAxis\" in chartData) ? chartData.showXAxis: _showXAxis,\n xScale = chartData.xScale || _xScale || timeSeries ? d3.time.scale.utc() : d3.scale.linear(),\n chartId = domCache.saveIfEmpty(node, \"chartId\", function() {\n return randomAlphaNum(8);\n });\n\n\n // data driven css styling of the chart\n if (chartData.styles) { selection.classed(chartData.styles, true); }\n\n // title\n showTitle(title, selection, plotSize[0], margin, titleMargin);\n\n namedSeriesMetaData(groups, dataApi)\n .then(seriesMetaDataLoaded);\n\n selection.on(\"resize\", resize);\n\n var redraw = function() { bind.call(node, chartData); };\n\n function seriesMetaDataLoaded() {\n var allSeries = collectSeries(groups);\n\n var errors = displayErrors(groups, allSeries, selection, outerSize);\n\n if (!errors) {\n if (allSeries.length > 0) {\n trackMaxDomain(chartData, allSeries);\n\n var requestUntil = chartData.displayDomain[1] == chartData.maxDomain[1] ?\n undefined // unspecified end (half bounded range) if selection is max range\n : chartData.displayDomain[1] + 1; // +1 to be inclusive of last element\n var requestDomain = [ chartData.displayDomain[0], requestUntil ];\n\n allSeries.forEach(function (series) {\n series.transformName = series.transformName ? series.transformName : transformName;\n });\n var fetched = fetchData(dataApi, allSeries, requestDomain, timeSeries, plotSize[0], moreData);\n fetched.then( function(){dataReady(allSeries);} ).otherwise(rethrow);\n }\n }\n }\n\n /** Update chart meta data and re-plot based on new data received from the server. */\n function moreData(series, data) {\n if (data.length) { // TODO try trackMaxDomain here\n var lastKey = data[data.length-1][0];\n var newEnd = Math.max(lastKey, chartData.displayDomain[1]);\n series.data = series.data.concat(data); // TODO overwrite existing keys not just append\n chartData.displayDomain[1] = newEnd;\n transitionRedraw();\n }\n }\n\n /** Plot the chart now that the data has been received from the server. */\n function dataReady(allSeries) {\n var transition = useTransition(inheritedTransition);\n // data plot drawing area\n var plotSelection = attachByClass(\"g\", selection, \"plotArea\")\n .attr(\"width\", plotSize[0])\n .attr(\"transform\", \"translate(\" + plotSpot[0] + \",\" + plotSpot[1] +\")\");\n var plotClipId = \"chart-plot-clip-\" + chartId;\n var labelLayer = attachByClass(\"g\", selection, \"label-layer\")\n .attr(\"width\", plotSize[0])\n .attr(\"transform\", \"translate(\" + plotSpot[0] + \",\" + plotSpot[1] +\")\");\n\n // x axis\n var xAxisSpot = [plotSpot[0], \n plotSpot[1] + plotSize[1] + padding[1]];\n \n keyAxis(transition, chartData.displayDomain, timeSeries, xAxisSpot, plotSize[0], xScale, showXAxis);\n\n attachSideAxes(groups, transition, plotSize, paddedPlotSize, margin);\n selection.on(\"toggleMaxLock\", transitionRedraw);\n selection.on(\"zoomBrush\", brushed);\n\n // setup clip so we can draw lines that extend a bit past the edge \n // or animate clip if we're in a transition\n timeClip(plotSelection, plotClipId, paddedPlotSize, [-padding[0], -padding[1]],\n chartData.displayDomain, xScale);\n\n // copy some handy information into the series object\n allSeries.forEach(function (series) { \n series.xScale = xScale;\n series.plotSize = deepClone(plotSize);\n series.labelLayer = labelLayer;\n series.displayDomain = chartData.displayDomain;\n });\n\n // draw data plot\n var plotTransition = transition.selectAll(\".plotArea\");\n attachSeriesPlots(plotTransition, groups, defaultPlotter);\n attachGroupPlots(plotSelection, plotTransition, groups, defaultPlotter);\n\n // legends \n if (showLegend)\n attachLegends(labelLayer, allSeries);\n\n // resizer\n bindResizer(transition);\n \n // zooming support\n bindZoomBrush(plotTransition, xScale, plotSize[1]);\n\n // notify that we've completed drawing (e.g. for testing)\n drawCompleteNotify(transition, node);\n }\n\n /** set size from a resize event, then redraw. */\n function resize() {\n size = chartData.size = d3.event.detail.size;\n redraw();\n }\n\n /** the user has zoomed via the brush control */\n function brushed() {\n if (d3.event.detail.zoomReset) {\n chartData.displayDomain = chartData.maxDomain; \n } else if (d3.event.detail.extent) {\n // convert date back to millis if necessary\n var newDomain = d3.event.detail.extent.map( function(maybeDate) {\n if (isDate(maybeDate)) {\n return maybeDate.getTime();\n } else {\n return maybeDate;\n }\n });\n chartData.displayDomain = newDomain; // consider: make a setDomain interface? \n } else { \n return;\n }\n var transition = transitionRedraw();\n\n var chartZoom = {\n displayDomain: chartData.displayDomain, \n chartTransition: transition\n };\n var eventInfo = {detail: chartZoom, bubbles:true};\n node.dispatchEvent(new CustomEvent(\"chartZoom\", eventInfo));\n }\n\n /** trigger our own transition and redraw. return the transition so\n * that other animations can share our transition timing. */\n function transitionRedraw() {\n var transition = selection.transition()\n .duration(transitionTime);\n\n transition.each(function() {\n redraw();\n });\n\n return transition;\n }\n }", "renderVis() {\n let vis = this;\n let type;\n\n // Append world map\n let geoPath = vis.chart.selectAll('.geo-path')\n .data(topojson.feature(vis.geoData, vis.geoData.objects.countries).features)\n .join('path');\n\n geoPath.attr('class', d => `geo-path ${countryNameToCodeMap.get(d.properties.name)} country`)\n .transition().duration(d => {\n return animationPlaying ? 10 : 2000;\n }).on('start', function () {\n d3.select(this).attr('pointer-events', 'none'); // disable clicking as the map is being drawn\n }).on('end', function () {\n d3.select(this).attr('pointer-events', 'all'); // enable clicking after the map has been drawn \n })\n .attr('d', vis.geoPath)\n .attr('stroke', d => {\n try {\n if (vis.africanLocales.includes(d.properties.name)) {\n throw 'Part of a Bigger Locale';\n }\n else {\n vis.groups.get(d.properties.name).entries();\n return 'black';\n }\n } catch (e) { return 'grey'; }\n })\n .attr('fill', d => {\n try {\n type = [...vis.groups.get(d.properties.name).entries()].reduce((a, e) => e[1] > a[1] ? e : a);\n if (type[1] === 0) {\n throw 'no data available'\n }\n if (countryFilter.length != 0 && (countryCodeToNameMap.get(countryFilter[0]) == d.properties.name)) {\n return vis.createFillPattern(d, type[0]);\n }\n return vis.colorScale(type[0]);\n } catch (e) {\n return '#c5cacb';\n }\n })\n\n\n // Append pie charts for major countries\n for (const [key, value] of (vis.groups.entries())) {\n let lonlat = vis.projection([vis.countries.get(key)[1], vis.countries.get(key)[0]]);\n if (vis.mainCountries.includes(key)) { // change to hover to display instead\n let c = vis.chart.selectAll('.' + classKey(key))\n .data(d3.sum(value.values()) == 0 ? pie(0) : pie(Array.from(value.values())))\n .join('path');\n c.attr('transform', `translate(${lonlat[0]}, ${lonlat[1]})`)\n .attr('class', classKey(key))\n .attr('stroke', 'black')\n .attr('stroke-width', '0.5px')\n .attr('fill', d => {\n return vis.indexColorScale(d.index);\n })\n .transition().duration(d => {\n return animationPlaying ? 0 : 3000;\n })\n .attrTween('d', function (d) {\n var start = { startAngle: d.startAngle, endAngle: d.startAngle };\n var interpolate = d3.interpolate(start, d);\n return function (t) {\n return arc(interpolate(t));\n }\n });\n }\n }\n\n // Mouse Event Handler\n geoPath.on('mouseover', function (event, d) {\n const countryCode = countryNameToCodeMap.get(d.properties.name);\n if (!animationPlaying && doesCountryExist(countryCode)) {\n d3.select(this).style('cursor', 'pointer')\n } else {\n d3.select(this).attr('pointer-events', 'none');\n }\n return animationPlaying ? null : vis.tooltipShow(event, d, vis);\n })\n .on('mousemove', (event, d) => vis.tooltipMove(event, d, vis))\n .on('mouseleave', function () {\n d3.select(this).style('cursor', 'default');\n vis.tooltipHide(vis)\n })\n .on('click', function (event, d) {\n if (animationPlaying) return;\n removeTypeFilter();\n dispatcher.call('selectCountry', event, countryNameToCodeMap.get(d.properties.name));\n });\n }", "function exports(_selection) {\n\n _selection.each(function (_data) {\n\n\n \n chartW = width - margin.left - margin.right;\n chartH = height - margin.top - margin.bottom;\n\n xScale\n .range([0, chartW])\n .domain(xDomain);\n\n xScaleBrush\n .range([0, chartW])\n .domain(xScale.domain());\n\n yScale\n .rangeRound([chartH, 0])\n .domain(yDomain);\n\n // Update tick size for x and y axis\n //xAxis.tickSize(-(chartH-20));\n //yAxis1.tickSize(-(chartW-20));\n\n xAxis.tickSize(5);\n yAxis1.tickSize(5);\n\n let yearRange = []\n _data[0].values[0].values.forEach(function(d) {\n \n \n yearRange.push(parseInt(d.key))\n\n });\n\n let tickValues = []\n for(var i=d3.min(yearRange); i<=d3.max(yearRange)+10;i=i+10) {\n\n tickValues.push(new Date(i, 0))\n }\n console.log(\"testtest\")\n console.log(tickValues)\n xAxis \n .tickValues(tickValues)\n\n\n // Select the s*vg element, if it exists.\n \n const div = d3.select(this).selectAll(`.${chartClass}`).data(_data);\n\n data = _data;\n\n div.enter()\n .append('div')\n .attr('class', chartClass);\n \n\n div.exit()\n .remove();\n\n div.selectAll('svg').data([]).exit().remove();\n\n svg = div.append('svg').attr('width', 400).attr('height', 250);\n\n // Add a group element called Container that hold all elements in the chart\n svg.append('g')\n .attr('class', 'container')\n .attr(\"transform\", \"translate(80, 15)\");\n \n\n container = svg.selectAll('g.container'); \n\n svg = d3.select(this).selectAll('svg').data([_data]);\n data = _data;\n\n \n const svgEnter = svg.enter()\n .append('svg')\n .classed(chartClass, true);\n\n // Add defintions of graphical objects to be used later inside\n // a def container element.\n const defs = svgEnter.append('defs');\n\n // Add a clip path for hiding parts of graph out of bounds\n defs.append('clipPath')\n .attr('id', 'clip')\n .append('rect')\n .attr('width', chartW)\n .attr('height', chartH);\n\n // Add a marker style (http://bl.ocks.org/dustinlarimer/5888271)\n defs.append('marker')\n .attr('id', 'marker_stub')\n .attr('markerWidth', 5)\n .attr('markerHeight', 10)\n .attr('markerUnits', 'strokeWidth')\n .attr('orient', 'auto')\n .attr('refX', 0)\n .attr('refY', 0)\n .attr('viewBox', '-1 -5 2 10')\n .append('svg:path')\n .attr('d', 'M 0,0 m -1,-5 L 1,-5 L 1,5 L -1,5 Z')\n .attr('fill', '#DDD');\n\n\n // Add a group element called Container that hold all elements in the chart\n /*container = svgEnter\n .append('g')\n .classed('', true);*/\n\n // Add group element to Container for x axis\n container.append('g').classed('x-axis-group axis', true);\n\n // Add group element to Container to hold data that will be drawn as area\n container.append('g').classed('timeseries-area', true);\n\n // Add group element to Container for y axis on left and right of chart\n container.append('g').classed('y-axis-group-1 axis', true);\n container.append('g').classed('y-axis-group-2 axis', true);\n\n // Add group element to Container tp hold data that will be drawn as lines\n container.append('g').classed('timeseries-line', true);\n\n container.append('g').classed('mouse-over-effects', true);\n\n // Group element to hold annotations, explanatory text, legend\n const annotation = container.append('g').classed('annotation', true);\n\n // Add Y axis label to annotation\n annotation.append('text')\n .attr('transform', 'rotate(-90)')\n .attr('y', 0 - (margin.left - 20))\n .attr('x', 0 - (chartH / 2))\n .attr('dy', '1em')\n .style('text-anchor', 'middle')\n .classed('y-axis-label', true);\n\n // Hover line for click events\n container.append('g')\n .append('line')\n .classed('hover-line', true)\n .attr('x1', 0)\n .attr('x2', 0)\n .attr('y1', 0)\n .attr('y2', chartH)\n .style('stroke-opacity', 0);\n\n // Invisible rect for mouse tracking since you\n // can't catch mouse events on a g element\n /* container.append('svg:rect')\n .attr('width', chartW)\n .attr('height', chartH)\n .attr('fill', 'none')\n .attr('pointer-events', 'all')\n .on('mouseout', function () {\n dispatch.mouseout();\n })\n .on('click', function () {\n const mouse = d3.mouse(this);\n // Dispatch click event\n dispatch.click(mouse, xScale);\n });*/\n\n\n\n\n /*\n * End of all the elements appended to svg only once\n */\n\n /*\n * Following actions happen every time the svg is generated\n */\n // Update the outer dimensions.\n\n svg.transition()\n .attr('width', width)\n .attr('height', height);\n\n // Update the inner dimensions.\n svg.selectAll('g.container')\n .attr({ transform: `translate(${margin.left}, ${margin.top})` });\n\n // Update the x-axis.\n container.select('.x-axis-group.axis')\n .attr({ transform: `translate(0, ${chartH})` });\n\n container.select('.x-axis-0-group.axis')\n .attr({ transform: `translate(0, ${yScale(0)})` });\n \n // Call render chart function\n exports.render();\n });\n }", "function build_visualization(d) {\n\n circles = svg.selectAll(\"circle\")\n .data(root.descendants().slice(1))\n .enter().append(\"g\").append(\"circle\")\n .attr(\"r\", function(d) {\n return d.r;\n })\n .attr(\"cx\", function(d) {\n return d.x;\n })\n .attr(\"cy\", function(d) {\n return d.y;\n })\n .style(\"fill\", function(d) {\n return color(d.data.atom);\n })\n\n .on(\"mouseover\", function(d) {\n d3.select(this.parentNode)\n .moveToFront()\n .append(\"text\")\n .attr(\"x\", d.x)\n .attr(\"y\", d.y)\n .attr(\"text-anchor\", \"middle\")\n .text(d.data.symbol)\n .style(\"fill\", \"black\")\n .style(\"font-size\", \"15px\");\n\n d3.select(this)\n .attr(\"r\", \"25px\")\n .style(\"stroke\", \"white\");\n\n d3.select(\"#element_info\")\n .append(\"text\")\n .text(d.data.element);\n })\n\n .on(\"mouseout\", function(d) {\n d3.select(this)\n .attr(\"r\", function(d) {\n return d.r;\n })\n .style(\"stroke\", null);\n\n d3.select(this.parentNode)\n .select(\"text\").remove();\n\n d3.select(\"#element_info\")\n .select(\"text\").remove();\n });\n\n } // end build visualization function", "attached() {\n\t\tif (isServerSide()) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst w =\n\t\t\ttypeof this._width === 'string' ? this._width : `${this._width}px`;\n\t\tconst h =\n\t\t\ttypeof this._height === 'string'\n\t\t\t\t? this._height\n\t\t\t\t: `${this._height}px`;\n\n\t\tthis.svg = d3\n\t\t\t.select(this._element)\n\t\t\t.append('svg')\n\t\t\t.attr('width', w)\n\t\t\t.attr('height', h);\n\n\t\tthis._handleClickHandler = this._handleClick.bind(this);\n\n\t\tthis.rect = this.svg\n\t\t\t.append('rect')\n\t\t\t.attr('fill', 'rgba(1, 1, 1, 0)')\n\t\t\t.attr('width', w)\n\t\t\t.attr('height', h)\n\t\t\t.on('click', this._handleClickHandler);\n\n\t\tconst bounds = this.svg.node().getBoundingClientRect();\n\n\t\tthis.svgGroup = this.svg.append('g');\n\t\tthis.mapLayer = this.svgGroup.append('g');\n\t\tthis.projection = d3\n\t\t\t.geoMercator()\n\t\t\t.scale(100)\n\t\t\t.translate([bounds.width / 2, bounds.height / 2]);\n\n\t\tthis.path = d3.geoPath().projection(this.projection);\n\t\tthis._selected = null;\n\n\t\tthis._onDataLoadHandler = this._onDataLoad.bind(this);\n\n\t\tresolveData(this._data)\n\t\t\t.then(val => {\n\t\t\t\tthis._onDataLoadHandler.apply(this, [null, val]);\n\n\t\t\t\tif (this._internalPollingInterval) {\n\t\t\t\t\tclearInterval(this._internalPollingInterval);\n\t\t\t\t}\n\n\t\t\t\tif (this.pollingInterval) {\n\t\t\t\t\tthis._internalPollingInterval = setInterval(() => {\n\t\t\t\t\t\tthis._updateData(this.data);\n\t\t\t\t\t}, this._pollingInterval);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tthis._onDataLoadHandler.apply(this, [err, null]);\n\t\t\t});\n\t}", "updateSingleArticlePlot(dom, data) {\n\n // Update x axis\n this.updateXAxis(dom);\n\n // Update y axis\n this.updateYAxis(data);\n\n // Update highlighted events\n this.updateHighlightedEvents();\n\n // Remove color legend\n d3.select(\"#color-legend\")\n .style(\"display\", \"none\");\n\n // Remove previous lines\n d3.selectAll(\".line\")\n .remove();\n\n // Generate new line\n let line = d3.line()\n .x(d => this.xScale(d.peak_date))\n .y(d => this.yScale(d.view_count))\n .curve(d3.curveMonotoneX);\n\n // Animate addition of new line\n const path = this.focus_area.append(\"path\")\n .attr(\"d\", line(data))\n .attr(\"class\", \"line\");\n\n const totalLength = path.node().getTotalLength();\n\n path.attr(\"stroke-dasharray\", totalLength + \" \" + totalLength)\n .attr(\"stroke-dashoffset\", totalLength)\n .transition()\n .duration(1000)\n .attr(\"stroke-dashoffset\", 0);\n\n\n // Update circles\n let circles = this.focus_area.selectAll(\"circle\")\n // Bind each svg circle to a\n // unique data element\n .data(data, d => d.article_id);\n\n // Update()\n circles.transition()\n .attr(\"cx\", d => this.xScale(d.peak_date))\n .attr(\"cy\", d => this.yScale(d.view_count));\n\n\n // Enter() \n circles.enter()\n .append(\"circle\")\n .attr(\"id\", d => \"article_\" + d.article_id)\n .attr(\"r\", 0)\n .attr(\"cx\", d => this.xScale(d.peak_date))\n .attr(\"cy\", d => this.yScale(d.view_count))\n .attr(\"fill\", \"#a50f15\")\n // Tooltip behaviour\n .on(\"mouseover\", this.onMouseOverCircle)\n .on(\"mouseout\", this.onMouseOutCircle)\n .transition()\n .attr(\"r\", 2);\n\n // Exit()\n circles.exit()\n .transition()\n .attr(\"r\", 0)\n .remove();\n }", "function drawCustom(data) {\n\n var dataBinding = dataContainer.selectAll(\"custom.rect\")\n .data(data);\n\n dataBinding\n .attr(\"fillStyle\", function(d) {return z(d.z)});\n \n dataBinding.enter()\n .append(\"custom\")\n .classed(\"rect\", true)\n .attr(\"x\", function(d) {return x(d.x)})\n .attr(\"y\", function(d, i) {return y(d.y)})\n .attr(\"width\", y.rangeBand())\n .attr(\"height\", x.rangeBand())\n .attr(\"fillStyle\", function(d) {return z(d.z)})\n .attr(\"strokeStyle\", \"white\")\n .attr(\"lineWidth\", strokeWidth)\n \n drawCanvas();\n \n }", "_animationFrame() {\n // get the d3 selected handles\n // since the group elems both exist, we dont have to do anything on isRange change\n var startHandle = Px.d3.select(this.$$('#handleStart'));\n var endHandle = Px.d3.select(this.$$('#handleEnd'));\n\n // save the d3 selected handles\n this.set('_startHandle', startHandle);\n this.set('_endHandle', endHandle);\n\n // initial config for our handle paths\n this._buildHandles();\n\n // set up our listeners\n this._setupListeners();\n }", "function draw(){\n\t\t// Needed to comply with Tool Delegate design pattern\n\t}", "function draw(dur) {\r\n if (dur == null || isNaN(dur))\r\n dur = defaultAnimationDuration;\r\n if (dur <= 0)\r\n dur = 1;\r\n\r\n innerVertex.transition()\r\n .duration(dur)\r\n .attr(\"cx\", attributeList[\"innerVertex\"][\"cx\"])\r\n .attr(\"cy\", attributeList[\"innerVertex\"][\"cy\"])\r\n .attr(\"x\", attributeList[\"innerVertex\"][\"x\"])\r\n .attr(\"y\", attributeList[\"innerVertex\"][\"y\"])\r\n .attr(\"fill\", attributeList[\"innerVertex\"][\"fill\"])\r\n .attr(\"r\", attributeList[\"innerVertex\"][\"r\"])\r\n .attr(\"width\", attributeList[\"innerVertex\"][\"width\"])\r\n .attr(\"height\", attributeList[\"innerVertex\"][\"height\"])\r\n .attr(\"stroke\", attributeList[\"innerVertex\"][\"stroke\"])\r\n .attr(\"stroke-width\", attributeList[\"innerVertex\"][\"stroke-width\"]);\r\n \r\n \r\n\r\n outerVertex.transition()\r\n .duration(dur)\r\n .attr(\"cx\", attributeList[\"outerVertex\"][\"cx\"])\r\n .attr(\"cy\", attributeList[\"outerVertex\"][\"cy\"])\r\n .attr(\"x\", attributeList[\"outerVertex\"][\"x\"])\r\n .attr(\"y\", attributeList[\"outerVertex\"][\"y\"])\r\n .attr(\"fill\", attributeList[\"outerVertex\"][\"fill\"])\r\n .attr(\"r\", attributeList[\"outerVertex\"][\"r\"])\r\n .attr(\"width\", attributeList[\"outerVertex\"][\"width\"])\r\n .attr(\"height\", attributeList[\"outerVertex\"][\"height\"])\r\n .attr(\"stroke\", attributeList[\"outerVertex\"][\"stroke\"])\r\n .attr(\"stroke-width\", attributeList[\"outerVertex\"][\"stroke-width\"]);\r\n \r\n \r\n text.transition()\r\n .duration(dur)\r\n .attr(\"x\", attributeList[\"text\"][\"x\"])\r\n .attr(\"y\", attributeList[\"text\"][\"y\"])\r\n .attr(\"fill\", attributeList[\"text\"][\"fill\"])\r\n .attr(\"font-family\", attributeList[\"text\"][\"font-family\"])\r\n .attr(\"font-size\", attributeList[\"text\"][\"font-size\"])\r\n .attr(\"font-weight\", attributeList[\"text\"][\"font-weight\"])\r\n .attr(\"text-anchor\", attributeList[\"text\"][\"text-anchor\"])\r\n .text(function() {\r\n return attributeList[\"text\"][\"text\"];\r\n });\r\n\r\n extratext.transition()\r\n .duration(dur).attr(\"x\", attributeList[\"extratext\"][\"x\"]).attr(\"y\", attributeList[\"extratext\"][\"y\"]).attr(\"fill\", attributeList[\"extratext\"][\"fill\"])\r\n .attr(\"font-family\", attributeList[\"extratext\"][\"font-family\"]).attr(\"font-size\", attributeList[\"extratext\"][\"font-size\"])\r\n .attr(\"font-weight\", attributeList[\"extratext\"][\"font-weight\"]).attr(\"text-anchor\", attributeList[\"extratext\"][\"text-anchor\"])\r\n .text(function() {\r\n return attributeList[\"extratext\"][\"text\"];\r\n });\r\n }", "function finalDraw() {\n\t Shapes.drawAll(gd);\n\t Images.draw(gd);\n\t Plotly.Annotations.drawAll(gd);\n\t Legend.draw(gd);\n\t RangeSlider.draw(gd);\n\t RangeSelector.draw(gd);\n\t }", "function buildVis() {\n // Update scale\n xScale.rangeRoundBands([0, width], .1, .4);\n yScale.rangeRound([height, 0]);\n\n xScale.domain(data.map(xValue));\n yScale.domain([0, d3.max(data, yValue)]);\n\n if (!chart) {\n chart = container.append(\"g\");\n chart.append(\"rect\").classed(\"background\", true).style(\"opacity\", 0);\n }\n chart.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n chart.select(\"background\").attr(\"width\", width).attr(\"height\", height);\n\n // Brush: should place before bars so that bars are on top of the brush\n if (!brush) {\n brush = chart.append(\"g\")\n .datum(function() { return { selected: false, previouslySelected: false}; })\n .attr(\"class\", \"brush\");\n }\n brush.call(d3.svg.brush()\n .x(xScale)\n .y(yScale)\n .on(\"brushstart\", function(d) {\n bars.each(function(d) { d.previouslySelected = d3.event.sourceEvent.ctrlKey && d.selected; });\n }).on(\"brush\", function() {\n var extent = d3.event.target.extent();\n var extentRect = { left: extent[0][0], right: extent[1][0], top: extent[0][1], bottom: extent[1][1] };\n bars.classed(\"selected\", function(d) {\n var rect = { left: xScale(xValue.call(this, d)), right: xScale(xValue.call(this, d)) + xScale.rangeBand(), top: 0, bottom: yValue.call(this, d) };\n var intersected = ivs.helpers.d3.isIntersected(extentRect, rect);\n d.selected = d.previouslySelected ^ intersected;\n d3.select(this).select(\".name\").style(\"fill\", d.selected ? \"block\" : \"none\");\n\n return d.selected;\n });\n module.setSelected(bars, key);\n }).on(\"brushend\", function() {\n d3.event.target.clear();\n d3.select(this).call(d3.event.target);\n }));\n\n // Bars\n var barsContainer = chart.selectAll(\"g.ivs-barChart-barContainer\").data([0]);\n barsContainer.enter().append(\"g\").classed(\"ivs-barChart-barContainer\", true);\n\n var bars = barsContainer.selectAll(\"g\").data(data);\n var newbars = bars.enter().append(\"g\").attr(\"class\", \"ivs-barChart-bar\");\n newbars.append(\"rect\")\n .attr(\"x\", function(d) { return xScale(xValue.call(this, d)); })\n .attr(\"width\", xScale.rangeBand());\n // .on(\"click\", function(d) {\n // if (d3.event.altKey) { return; } // Pan\n\n // if (d3.event.ctrlKey) {\n // var parent = d3.select(this.parentNode);\n // parent.classed(\"selected\", d.selected = !d.selected);\n // parent.select(\".name\").style(\"fill\", d.selected ? \"black\" : \"none\");\n // } else {\n // bars.classed(\"selected\", function(p) { \n // p.selected = d === p\n // d3.select(this).select(\".name\").style(\"fill\", p.selected ? \"black\" : \"none\");\n\n // return p.selected; \n // });\n // }\n // });\n bars.select(\"rect\")\n .transition().duration(ivs.TRANSITION_MOVEMENT)\n .attr(\"y\", function(d) { return yScale(yValue.call(this, d)); })\n .attr(\"height\", function(d) { return height - yScale(yValue.call(this, d)); });\n var titleFunction = module.activeMapping() === \"authors\" ? function(d) { return d.name + \": \" + d.x + \" out of \" + d.totalPublications + \" total publications\\n\" + d.articles; } : function(d) { return d.articles; };\n bars.append(\"title\")\n .text(titleFunction);\n\n // Register click event\n module.registerClickEvent(newbars, key);\n\n // Update selection, brushing\n module.updateSelectionBrushing(bars, key, updateDotText);\n\n // Register to be brushed\n module.registerBrushedEvent(bars, key, updateDotText);\n\n // Register for dragging items\n module.registerDragEvent(newbars);\n\n // Register for deselection when clicking on empty space\n module.registerDeselection(chart, newbars);\n\n // x-axis\n if (!xAxis) {\n xAxis = d3.svg.axis()\n .scale(xScale)\n .orient(\"bottom\")\n .tickFormat(String);\n }\n\n var g = chart.selectAll(\".x.axis\").data([0]);\n g.enter().append(\"g\").classed(\"x axis\", true);\n g.attr(\"transform\", \"translate(0,\" + height + \")\").call(xAxis);\n g.selectAll(\"text\")\n .attr(\"x\", -10)\n .attr(\"dy\", \".5em\")\n .attr(\"transform\", \"rotate(-30)\");\n\n // y-axis\n var mappingTexts = attributeMappings.map(function(d) { return d.name; });\n if (!yAxis) {\n yAxis = d3.svg.axis()\n .scale(yScale)\n .orient(\"left\")\n .tickFormat(d3.format(\"d\"));\n }\n if (!yLabel) {\n yLabel = ivs.widgets.cycleButton().className(\"ivs-baseVis-cycleButton\") \n .on(\"indexChanged\", function(index) {\n yIndex = index;\n mapAttributes();\n });\n }\n yLabel.texts(mappingTexts).currentIndex(yIndex);\n\n g = chart.selectAll(\".y.axis\").data([0]);\n g.enter().append(\"g\").classed(\"y axis\", true);\n g.call(yAxis);\n g2 = g.selectAll(\".yLabel\").data([0]);\n g2.enter().append(\"g\").classed(\"yLabel\", true);\n g2.attr(\"transform\", \"translate(16,0) rotate(-90)\").call(yLabel);\n }", "initVis() {\n let vis = this;\n\n // areas\n vis.width = vis.config.containerWidth;\n vis.height = vis.config.containerHeight;\n vis.center = { x: 312, y: 312 };\n vis.svg = d3\n .select(vis.config.parentElement)\n .append(\"svg\")\n .attr(\"class\", \"chart\")\n .attr(\"width\", vis.config.containerWidth)\n .attr(\"height\", vis.config.containerHeight)\n .append(\"g\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y})`);\n\n // scales\n vis.radiusScale = d3\n .scalePow()\n .exponent(0.5)\n .range([15, 95])\n .domain([\n d3.min(vis.data, (d) => d.total_emissions),\n d3.max(vis.data, (d) => d.total_emissions),\n ]);\n vis.colorScale = d3\n .scaleOrdinal()\n .domain([\n \"Farm\",\n \"Land use change\",\n \"Transport\",\n \"Retail\",\n \"Packaging\",\n \"Animal feed\",\n \"Processing\",\n ])\n .range([\"#e1874b\", \"#1f78b4\", \"#bfc27d\", \"#446276\", \"#fccde5\", \"#b4de68\", \"#668fff\"]);\n // simulation\n vis.sim = d3\n .forceSimulation()\n .force(\"x\", d3.forceX(0).strength(0.0001))\n .force(\"y\", d3.forceY(0).strength(0.0001))\n .force(\n \"collision\",\n d3.forceCollide((d) => vis.radiusScale(d.total_emissions) + 1)\n );\n // defs\n var defs = vis.svg.append(\"defs\");\n vis.drawIcon = function (id) {\n defs.append(\"pattern\")\n .attr(\"id\", id)\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"patternContentUnits\", \"objectBoundingBox\")\n .append(\"image\")\n .attr(\"height\", 1)\n .attr(\"width\", 1)\n .attr(\"preserveAspectRatio\", \"none\")\n .attr(\"xlink:href\", `icon/${id}.png`);\n return `url(#${id})`;\n };\n\n // defs\n (vis.glow = vis.svg.append(\"defs\").append(\"filter\").attr(\"id\", \"glow\")),\n vis.glow\n .append(\"feGaussianBlur\")\n .attr(\"stdDeviation\", \"0.5\")\n .attr(\"result\", \"coloredBlur\")\n .append(\"feMerge\");\n (vis.feMerge = vis.glow.append(\"feMerge\")),\n vis.feMerge.append(\"feMergeNode\").attr(\"in\", \"coloredBlur\"),\n vis.feMerge.append(\"feMergeNode\").attr(\"in\", \"SourceGraphic\");\n\n // background circle\n vis.svg\n .append(\"circle\")\n .transition()\n .duration(200)\n .attr(\"r\", 310)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\");\n\n // color legend\n vis.legend_color = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.height / 2},${-vis.height / 2 + 20} )`);\n vis.legend_color\n .append(\"text\")\n .text(\"Most Emission Stage\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 10)`);\n const stages = [\n \"farm\",\n \"land_use_change\",\n \"animal_feed\",\n \"processing\",\n \"packaging\",\n \"transport\",\n \"retail\",\n ];\n const stages_names = [\n \"Farm\",\n \"Land use change\",\n \"Animal feed\",\n \"Processing\",\n \"Packaging\",\n \"Transport\",\n \"Retail\",\n ];\n for (let i = 0; i < stages.length; i++) {\n vis.legend_color\n .append(\"rect\")\n .attr(\"width\", 15)\n .attr(\"height\", 15)\n .attr(\"fill\", vis.colorScale(stages_names[i]))\n .attr(\"opacity\", 0.6)\n .attr(\"transform\", `translate(0, ${20 + i * 20})`);\n\n vis.legend_color\n .append(\"text\")\n .text(stages_names[i])\n .attr(\"transform\", `translate(18, ${27 + i * 20})`)\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"13px\")\n .attr(\"alignment-baseline\", \"central\");\n }\n\n // size legend\n vis.legend_size = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y - 200})`);\n vis.legend_size\n .append(\"text\")\n .text(\"Total Emission\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 10)`);\n vis.legend_size\n .append(\"text\")\n .text(\"(kg CO₂ / kg product)\")\n .attr(\"font-size\", \"20px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"font-family\", \"Marker Felt\")\n .attr(\"transform\", `translate(0, 35)`);\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(30))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${vis.radiusScale(30) + 55})`\n );\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(10))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${\n vis.radiusScale(30) + vis.radiusScale(2) + 55\n })`\n );\n vis.legend_size\n .append(\"circle\")\n .attr(\"r\", vis.radiusScale(1))\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#999999\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) - 10}, ${\n vis.radiusScale(30) + vis.radiusScale(12.5) + 55\n })`\n );\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", 55)\n .attr(\"y2\", 55)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"30\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\"transform\", `translate(${vis.radiusScale(30) + 85}, 65)`);\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", vis.radiusScale(30) + 35.7)\n .attr(\"y2\", vis.radiusScale(30) + 35.7)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"10\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) + 85}, ${vis.radiusScale(30) + 45.7})`\n );\n vis.legend_size\n .append(\"line\")\n .attr(\"x1\", vis.radiusScale(30) - 10)\n .attr(\"x2\", vis.radiusScale(30) + 110)\n .attr(\"y1\", vis.radiusScale(30) + 82.8)\n .attr(\"y2\", vis.radiusScale(30) + 82.8)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n vis.legend_size\n .append(\"text\")\n .text(\"1\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"alignment-baseline\", \"central\")\n .attr(\n \"transform\",\n `translate(${vis.radiusScale(30) + 93}, ${vis.radiusScale(30) + 92.8})`\n );\n\n // icon legend\n vis.legend_icon = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${vis.center.x}, ${vis.center.y - 280})`);\n vis.legend_icon\n .append(\"circle\")\n .attr(\"fill\", vis.drawIcon(\"Icon\"))\n .attr(\"r\", 20)\n .attr(\"stroke\", \"#5a5a5a\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\"transform\", \"translate(20,20)\");\n vis.legend_icon\n .append(\"text\")\n .text(\"icon indicates the\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"transform\", \"translate(45, 40)\");\n vis.legend_icon\n .append(\"text\")\n .text(\"emission of CO₂ > 1.5 kg\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"font-size\", \"15px\")\n .attr(\"transform\", \"translate(0, 60)\");\n vis.svg\n .append(\"g\")\n .attr(\"transform\", `translate(500, ${vis.center.y - 1000})`)\n .append(\"line\")\n .attr(\"x1\", 0)\n .attr(\"x2\", 0)\n .attr(\"y1\", 0)\n .attr(\"y2\", 1100)\n .attr(\"stroke-width\", \"3px\")\n .attr(\"stroke\", \"#999999\");\n\n // page button\n vis.button = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${-vis.center.x + 80}, ${vis.center.y - 6})`);\n vis.button\n .append(\"circle\")\n .attr(\"class\", \"pagebtn\")\n .classed(\"one\", true)\n .attr(\"r\", 30)\n .attr(\"stroke\", \"#5a5a5a\")\n .attr(\"stroke-width\", \"3px\")\n .attr(\"fill\", vis.drawIcon(\"One\"))\n .on(\"click\", function (event) {\n let page = 1;\n if (d3.select(this).classed(\"two\")) {\n page = 2;\n }\n if (d3.select(this).classed(\"three\")) {\n page = 3;\n }\n switch (page) {\n case 1:\n d3.select(this)\n .classed(\"one\", false)\n .classed(\"two\", true)\n .attr(\"fill\", vis.drawIcon(\"Two\"));\n vis.dispatcher.call(\"toP2\", event);\n break;\n case 2:\n d3.select(this)\n .classed(\"two\", false)\n .classed(\"three\", true)\n .attr(\"fill\", vis.drawIcon(\"Three\"));\n vis.dispatcher.call(\"toP3\", event);\n break;\n case 3:\n d3.select(this)\n .classed(\"three\", false)\n .classed(\"one\", true)\n .attr(\"fill\", vis.drawIcon(\"One\"));\n vis.dispatcher.call(\"toP1\", event);\n break;\n }\n });\n vis.buttonlabel = vis.svg\n .append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"transform\", `translate(${-vis.center.x + 120}, ${vis.center.y})`);\n vis.buttonlabel\n .append(\"text\")\n .text(\"Switch Page\")\n .attr(\"font-size\", \"20px\")\n .attr(\"fill\", \"#5a5a5a\")\n .attr(\"alignment-baseline\", \"central\");\n d3.select(\".page\").append(\"div\").attr(\"id\", \"tooltip1\");\n }", "function draw() {\n requestAnimationFrame(draw);\n\n // Copy frequency data to frequencyData array.\n analyser.getByteFrequencyData(dataArray);\n\n // Update d3 chart with new data.\n svg.selectAll('rect').data(dataArray).attr('y', function(d) {\n return svgHeight - d;\n })\n .attr('height', function(d) {\n return d;\n })\n}", "update_points(){\n this.get_buffer()\n //adds all the circles\n let c = this.circles.selectAll('circle')\n .data(this.buffer)\n \n const classReference = this\n\n c.enter()\n .append('circle')\n .merge(c)\n .attr('cy', d => this.y(d.value.mean) - this.label_height)\n .attr('cx', d => this.x(d.key) - this.year_to_x_for_g(this.parent.year0))\n .attr('r', d => {\n if(d.key == classReference.year_selected){return 10\n }else{return this.RADIUS}\n })\n .style('fill', d => {\n if(d.key == classReference.year_selected){return 'red'\n }else{return this.rgb}\n })\n .style('stroke', 'blue')\n .style('stroke-width', d => {\n if(d.key == classReference.year_selected){return 5\n }else{ return 0}\n })\n .style('opacity', '0.8')\n .attr('class','roll_points')\n\n c.exit()\n .remove()\n\n\n\n // adds the listener for the information pannel \n this.circles.selectAll('circle')\n .each(function(point_data){classReference.add_hover_function(this, point_data)})\n\n // adds the listener for the point highlight\n this.circles.selectAll('circle')\n .on('click', function(point_data){\n classReference.year_selected = parseInt(point_data.key)\n classReference.update_points()\n classReference.parent.map.highlight_points(classReference.type, parseInt(point_data.key))\n })\n\n \n }", "componentDidMount() {\n var me = this;\n var element = ReactDOM.findDOMNode(this);\n var state = this.getChartState();\n this.getData(state, function(output) {\n state.data = output;\n state.d3component.create(element, {}, state);\n me.setState({\n showLoading: false,\n loadingFailed: false,\n });\n });\n }", "drawMap() {\n // Calculate total market cap of each state \n this.stateData.forEach(function (element) {\n element.marketCap = 0;\n });\n for (let company of this.companyData) {\n this.company_id_dict[company.company_id] = company.company;\n for (let state of this.stateData) {\n if (company.state.includes(state.abbreviation)) {\n state.marketCap += parseInt(company.market_cap);\n }\n }\n }\n for (let state of this.stateData) {\n this.totalMarketCap += state.marketCap;\n }\n\n // Filter company links for companies we have\n let newCompLinks = [];\n for (let link of this.compLinks) {\n let fr = link.from_company_id;\n let to = link.to_company_id;\n let from_lat = false;\n let from_lng = false;\n let to_lat = false;\n let to_lng = false;\n for (let company of this.companyData) {\n if (company.company_id === fr) {\n from_lat = company.lat;\n from_lng = company.lng;\n } else if (company.company_id === to) {\n to_lat = company.lat;\n to_lng = company.lng;\n }\n }\n if (from_lat && to_lat) {\n link.from_lat = from_lat;\n link.from_lng = from_lng;\n link.to_lat = to_lat;\n link.to_lng = to_lng;\n newCompLinks.push(link);\n }\n }\n this.compLinks = newCompLinks;\n\n let that = this;\n let us = this.mapData;\n let path = d3.geoPath();\n let map = d3.select(\"#map-view\");\n map = map.append('svg')\n .attr('id', 'map')\n .attr('viewBox', '-90 -30 1100 700');\n\n // Bounding rect\n let map_width = map.node().getBoundingClientRect().width; //1100\n let map_height = map.node().getBoundingClientRect().height; // 700\n\n map.on('click', function () {\n //If the map (but not a state) is clicked, clear company table/reset sector table\n if (!that.stateClicked) {\n d3.selectAll('path').classed('outline-state', false);\n that.stateInfo(null);\n d3.select('#comp-dropdown').select('tbody').selectAll('tr').remove();\n d3.select('#map').selectAll('line').remove();\n d3.selectAll('circle').classed('selected', false);\n that.findSectors(that.companyData);\n that.currentState = null;\n that.resetView();\n that.companyDropdown.elements = that.companyDropdown.countryData;\n that.companyDropdown.stateData = that.companyDropdown.countryData;\n that.companyDropdown.makeTable();\n that.companyDropdown.clicked = false;\n d3.select('#help-text').text('Tip: Click on a state to see companies in that state');\n }\n that.sectorTable.clicked = false;\n d3.select('#sectors').selectAll('tr').classed('bold', false);\n that.stateClicked = false;\n });\n\n\n let mapGroup = map.append(\"g\")\n .attr(\"class\", \"states\");\n\n //Scale for coloring states by market cap\n let minMcap = d3.min(this.stateData, (d) => d.marketCap);\n let maxMcap = d3.max(this.stateData, (d) => d.marketCap);\n let scaleStateColor = d3.scaleLinear()\n .domain([minMcap, maxMcap])\n .range([0, 1]);\n\n // let scaleLegend = d3.scaleLinear()\n // .domain([minMcap, maxMcap])\n // .range([0, 100]);\n\n // let xAxis = d3.axisBottom(scaleLegend)\n // // .tickSize(16)\n // // .tickValues(xTicks);\n\n\n // Draw US map\n mapGroup.selectAll(\"path\")\n .data(topojson.feature(us, us.objects.states).features)\n .enter().append(\"path\")\n .attr('class', 'state')\n // //Color states by market cap\n .attr('style', function (d, i) {\n return 'fill: ' + d3.interpolateRgb('#EEEFEE', 'gray')(scaleStateColor(that.stateData[i].marketCap))\n })\n .attr(\"d\", path)\n //Display state name and companies in that state when clicked\n .on('click', function (d, i) {\n d3.selectAll('path').classed('outline-state', false);\n d3.select(this).classed('outline-state', true);\n that.stateClicked = true;\n that.currentState = that.stateData[i];\n that.stateInfo(that.stateData[i]);\n let companies = that.findCompanies(that.stateData[i].abbreviation, \"Address\");\n that.findSectors(companies);\n that.clicked(d, this);\n d3.select('#help-text').text('Tip: Click on the ocean to reset selection');\n });\n\n // Draw all interior state borders\n mapGroup.append(\"path\")\n .attr(\"class\", \"state-borders\")\n .attr(\"d\", path(topojson.mesh(us, us.objects.states, function (a, b) {\n return a !== b;\n })));\n\n // Remove universities with lat lng outside of our US bounding box\n let i = this.univData.length;\n while (i--) {\n if (!this.projection([this.univData[i].lng, this.univData[i].lat])) {\n this.univData.splice(i, 1);\n }\n }\n\n // Make the map view zoomable\n const zoom = d3.zoom()\n .scaleExtent([1, 6])\n .translateExtent([[0, 0], [map_width, map_height]])\n .extent([[0, 0], [map_width, map_height]])\n .on(\"zoom\", function () {\n mapGroup.attr(\"transform\", d3.event.transform);\n });\n map.call(zoom);\n\n // Draw companies on the map\n this.drawNodes(this.companyData);\n\n //Draw infoBox to display company information\n this.infoBox = new companyInfoBox;\n\n // // Give university and company toggle buttons functionality\n // d3.select('#univ-button').on('click', () => this.drawNodes(this.univData));\n // d3.select('#comp-button').on('click', () => this.drawNodes(this.companyData));\n\n // Create sector table\n this.findSectors(this.companyData);\n\n // Create company table\n this.companyDropdown = new Table(this.companyData, \"#comp-dropdown\", this);\n this.companyDropdown.countryData = this.companyData;\n this.companyDropdown.stateData = this.companyData;\n this.companyDropdown.makeTable();\n\n d3.select(\"#map-view\").append(\"div\").attr('id', \"company-in-state\").append(\"text\")\n // .attr(\"x\", 0).attr(\"y\", 0)\n .text('United States');\n\n // Give the user tips about how to explore our visualization\n let title_height = d3.select('#title').node().getBoundingClientRect().height;\n d3.select('#map-view').append('div')\n .attr('id', 'help-text')\n .attr('style', 'top: ' + (map_height + title_height - 20) + 'px; left: 1%; position: absolute;')\n .append('text')\n .text('Tip: Click on a state to see companies in that state');\n\n // Add color gradient legend\n let legendTitle = d3.select('#map-view').append('div')\n .attr('style', 'top: ' + (map_height + title_height - 40) + 'px; left: ' + (map_width - 260) + 'px; position: absolute;')\n .append('text')\n .classed('legend-text', true)\n .text('Aggregate market cap in millions');\n\n let legend = d3.select('#map-view').append('div')\n .attr('id', 'gradient-legend')\n .attr('style', 'top: ' + (map_height + title_height - 20) + 'px; left: ' + (map_width - 300) + 'px; position: absolute;');\n legend.append('text')\n .classed('legend-text', true)\n .text('$' + minMcap);\n\n let legSVG = legend.append('svg')\n .attr('width', '200')\n .attr('height', '10');\n\n legend.append('text')\n .classed('legend-text', true)\n .text('$' + maxMcap);\n //Append a defs element to the svg\n let defs = legSVG.append(\"defs\");\n //Append a linearGradient element\n let linearGradient = defs.append(\"linearGradient\")\n .attr(\"id\", \"linear-gradient\");\n linearGradient\n .attr(\"x1\", \"0%\")\n .attr(\"y1\", \"0%\")\n .attr(\"x2\", \"100%\")\n .attr(\"y2\", \"0%\");\n //Set the color for the start \n linearGradient.append(\"stop\")\n .attr(\"offset\", \"0%\")\n .attr(\"stop-color\", \"#EEEEEE\");\n //Set the color for the end\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"100%\")\n .attr(\"stop-color\", () => d3.interpolateRgb('#EEEFEE', 'gray')(scaleStateColor(maxMcap)));\n //Draw the rectangle and fill with gradient\n legSVG.append(\"rect\")\n .attr(\"width\", 200)\n .attr(\"height\", 10)\n .style(\"fill\", \"url(#linear-gradient)\");\n }", "function my(selection) {\n\n\t\t// pass the data to each selection (multiples-friendly)\n\t\tselection.each(function(data, i) {\n\n\t\t\tvar minX = 0;\n\t\t\tvar maxX = d3.max(data, function(d) { return d[xVar]; });\n\n\t\t\tvar scaleX = d3.scale.linear().domain([minX, maxX]).range([0, width]);\n\t\t\tvar scaleY = d3.scale.ordinal().domain(d3.range(data.length)).rangePoints([height, 0], 1);\n\t\t\t\n\n // In the following we'll attach an svg element to the container element (the 'selection') when and only when we run this the first time.\n // We do this by using the mechanics of the data join and the enter selection. \n // As a short reminder: the data join (on its own, not chained with .enter()) checks how many data items there are \n // and stages a respective number of DOM elements.\n // An join on its own - detached from the .enter() method - checks first how many data elements come in new \n // (n = new data elements) to the data join selection and then it appends the specified DOM element exactly n times. \n\n // Here we do exactly that with joining the data as one array element with the non-existing svg first:\n\n\t\t\tvar svg = d3.select(this) \t// conatiner (here 'body')\n\t\t\t\t\t.selectAll('svg')\t\t\t\t// first time: empty selection of staged svg elements (it's .selectAll not .select)\n\t\t\t\t\t.data([data]);\t\t\t\t\t// first time: one array item, hence one svg will be staged (but not yet entered); \n\n svg \t\t\t\t\t\t\t\t\t\t\t\t// one data item [data] staged with one svg element\n\t \t.enter() // first time: initialise the DOM element entry; second time+: empty\n\t \t.append(\"svg\"); // first time: append the svg; second time+: nothing happens\n\n // If we have more elements apart from the svg element that should only be appended once to the chart \n // like axes, or svg > g-elements for the margins, \n // we would store the enter-selection in a unique variable (like 'svgEnter', or if we inlcude another g 'gEnter'. \n // This allows us to reference just the enter()-selection which would be empty with every update, \n // not invoking anything that comes after .enter() - apart from the very first time.\n\n\t\t\tsvg\n\t\t\t\t.attr('width', width)\n\t\t\t\t.attr('height', height);\t\t\t\t\n\n\n\t\t\t// Here comes the general update pattern:\n\n\t\t\t// Data join\n\t\t\tvar bar = svg\n\t\t\t\t\t.selectAll('.bar')\n\t\t\t\t\t.data(data, function(d) { return d[yVar]; }); // key function to achieve object constancy\n\n\t\t\t// Enter\n\t\t\tbar\n\t\t\t\t\t.enter()\n\t\t\t\t.append('rect')\n\t\t\t\t\t.classed('bar', true)\n\t\t\t\t\t.attr('x', scaleX(minX))\n\t\t\t\t\t.attr('height', 5)\n\t\t\t\t\t.attr('width', function(d) { return scaleX(minX); });\n\n\t\t\t// Update\n\t\t\tbar\n\t\t\t\t.transition().duration(1000).delay(function(d,i) { return i / (data.length-1) * 1000; }) // implement gratuitous object constancy\n\t\t\t\t\t.attr('width', function(d) { return scaleX(d[xVar]); })\n\t\t\t\t\t.attr('y', function(d, i) { return scaleY(i); });\n\n\t\t\t// Exit\n\t\t\tbar\n\t\t\t\t\t.exit()\n\t\t\t\t.transition().duration(1000)\n\t\t\t\t\t.attr('width', function(d) { return scaleX(minX); })\n\t\t\t\t\t.remove();\n\n\t\t}); // selection.each()\n\n\t\ttriggerTooltip(yVar); // invoke tooltip - not necessary, forget about it, remove it to keep it simple\n\n\t} // Closure", "initVis() {\n let vis = this;\n\n // Define Main Countries and Exceptions, Energy Types\n vis.mainCountries = ['Central America', 'Canada', 'US', 'Brazil', 'Russian Federation', 'India', 'Australia', 'China'];\n vis.combinedLocales = ['Western Africa', 'Eastern Africa', 'Middle Africa', 'Central America'];\n vis.energyTypes = ['Oil', 'Gas', 'Coal', 'Nuclear', 'Hydro', 'Renewables', 'Solar', 'Wind', 'Geo', 'No Data'];\n\n // Calculate inner chart size. Margin specifies the space around the actual chart.\n vis.width = vis.config.containerWidth - vis.config.margin.left - vis.config.margin.right;\n vis.height = vis.config.containerHeight - vis.config.margin.top - vis.config.margin.bottom;\n\n // Define size of SVG drawing area\n vis.svg = d3.select(vis.config.parentElement)\n .attr('width', vis.config.containerWidth)\n .attr('height', vis.config.containerHeight);\n\n // Append group element that will contain our actual chart \n // and position it according to the given margin config\n vis.chart = vis.svg.append('g')\n .attr('transform', `translate(${vis.config.margin.left},${vis.config.margin.top})`);\n\n // Defines the scale and translate of the projection so that the geometry fits within the SVG area\n // We crop Antartica because it takes up a lot of space that is not needed for our data\n vis.projection = d3.geoEquirectangular()\n .center([0, 15]) // set centre to further North\n .scale([vis.width / (2 * Math.PI)]) // scale to fit size of svg group\n .translate([vis.width / 2, vis.height / 2]); // ensure centered within svg group\n\n // Set projection\n vis.geoPath = d3.geoPath().projection(vis.projection);\n\n // Define color scale for all energy types\n vis.colorScale = d3.scaleOrdinal()\n // OIL GAS COAL NUCLEAR HYDRO RENEWABLES SOLAR WIND GEO\n .range(['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6'])\n .domain(['Oil', 'Gas', 'Coal', 'Nuclear', 'Hydro', 'Renewables', 'Solar', 'Wind', 'Geo']);\n\n vis.indexColorScale = d3.scaleOrdinal()\n // OIL GAS COAL NUCLEAR HYDRO RENEWABLES SOLAR WIND GEO\n .range(['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6'])\n .domain(d3.range([0, 8]));\n\n\n // Add Legend\n vis.chart.selectAll('legendDots')\n .data(vis.energyTypes)\n .join('circle')\n .attr('class', 'legendCircle')\n .attr('cx', 50)\n .attr('cy', (d, i) => 200 + i * 20)\n .attr('r', 7)\n .style('fill', d => {\n if (d === 'No Data') return '#c5cacb';\n return vis.colorScale(d);\n });\n\n vis.chart.selectAll('legendText')\n .data(vis.energyTypes)\n .join('text')\n .text(d => d)\n .attr('transform', (d, i) => `translate(60, ${205 + i * 20})`)\n .attr('fill', 9)\n .attr('');\n\n // Set Linechart tooltip\n vis.linechart = d3.select('#mapchart-tooltip')\n .attr('width', vis.tooltipWidth)\n .attr('height', vis.tooltipHeight)\n .append('g');\n\n // Append axes groups for Linechart\n vis.xAxisG = vis.linechart.append('g')\n .attr('class', 'axis x-axis')\n .attr('transform', `translate(0,${vis.tooltipHeight * 0.9})`);\n\n vis.yAxisG = vis.linechart.append('g')\n .attr('class', 'axis y-axis')\n .attr('transform', `translate(40, 0)`);\n\n // Set Linechart tooltip scales and axes\n vis.xScale = d3.scaleTime();\n vis.yScale = d3.scaleLinear();\n\n vis.xScale.range([40, vis.tooltipWidth - 30]);\n vis.yScale.range([vis.tooltipHeight * .9, vis.tooltipHeight * .15]);\n\n // Initialize axes\n vis.xAxis = d3.axisBottom(vis.xScale)\n .ticks(10)\n .tickFormat(d3.format('y'))\n .tickSizeOuter(0)\n .tickPadding(10);\n\n vis.yAxis = d3.axisLeft(vis.yScale)\n .ticks(5, '.1f')\n .tickSize(-vis.width)\n .tickSizeOuter(0)\n .tickPadding(10);\n\n // Set tooltip title and axis labels\n vis.tooltipTitle = d3.select('#mapchart-tooltip')\n .append('text')\n .attr('class', 'title')\n .attr('x', vis.tooltipWidth / 2)\n .attr('y', 25)\n .attr('font-size', 16)\n .style('text-anchor', 'middle');\n\n vis.tooltipAxis = d3.select('#mapchart-tooltip')\n .append('text')\n .attr('class', 'axis-title')\n .attr('x', 25)\n .attr('y', 50)\n .attr('font-size', 10)\n .text('Energy Consumption (exJ)');\n\n vis.updateVis();\n }", "function draw() {\n\n \n\n const lineFunc = d3\n .line()\n .x(d => xScale(d.year))\n .y(d => yScale(d.amount));\n\n const dot = svg\n .selectAll(\".dot\")\n .data(state.data, d => d.year) // use `d.year` as the `key` to match between HTML and data elements\n .join(\n enter =>\n // enter selections -- all data elements that don't have a `.dot` element attached to them yet\n enter\n .append(\"circle\")\n .attr(\"class\", \"dot\")\n .attr(\"r\", radius)\n .attr(\"cy\", d => yScale(d.amount))\n .attr(\"cx\", d => xScale(d.year)),\n update => update,\n exit => exit.remove()\n );\n\n const line = svg\n .selectAll(\"path.trend\")\n .data(state.data)\n .join(\n enter =>\n enter\n .append(\"path\")\n .attr(\"class\", \"trend\")\n .attr(\"d\", d => lineFunc(d)),\n update => update, // pass through the update selection\n exit => exit.remove()\n );\n\n console.log(\"drawn!\");\n}", "async drawQFLines(){\n let that = this;\n let QuarterfinalLines = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\n let QFLines = d3.select(\"#QF-Lines\").selectAll('line');\n let joined = QFLines.data(QuarterfinalLines).join('line')\n joined.attr(\"x1\", d =>{\n if(d < 4)\n return that.buffer + that.lineLength;\n else if (d >= 4 && d < 8)\n return that.svgWidth - that.buffer - that.lineLength * 2 - that.lineThickness / 2;\n else if (d >= 8 && d < 10)\n return that.lineLength * 2 + that.buffer;\n else\n return that.svgWidth - that.buffer - that.lineLength * 2;})\n .attr(\"y1\", d =>{\n if(d < 4)\n return that.buffer + that.R16Separation * 2 * d + that.R16Separation / 2;\n else if (d >= 4 && d < 8)\n return that.buffer + that.R16Separation * 2 * (d - 4) + that.R16Separation / 2;\n else if (d >= 8 && d < 10)\n return that.buffer + that.R16Separation * 4 * (d - 8) + that.R16Separation / 2;\n else\n return that.buffer + that.R16Separation * 4 * (d - 10) + that.R16Separation / 2;})\n .attr(\"x2\", d =>{\n if(d < 4)\n return that.buffer + that.lineLength * 2 + that.lineThickness / 2;\n else if (d >= 4 && d < 8)\n return that.svgWidth - that.buffer - that.lineLength;\n else if (d >= 8 && d < 10)\n return that.lineLength * 2 + that.buffer;\n else\n return that.svgWidth - that.buffer - that.lineLength * 2;})\n .attr(\"y2\", d =>{\n if(d < 4)\n return that.buffer + that.R16Separation * 2 * d + that.R16Separation / 2;\n else if (d >= 4 && d < 8)\n return that.buffer + that.R16Separation * 2 * (d - 4) + that.R16Separation / 2;\n else if (d >= 8 && d < 10)\n return that.buffer + that.R16Separation * 4 * (d - 8) + 2 * that.R16Separation + that.R16Separation / 2;\n else\n return that.buffer + that.R16Separation * 4 * (d - 10) + 2 * that.R16Separation + that.R16Separation / 2;})\n .attr(\"class\", \"bracket-line\"); \n }", "function renderIterates(div) {\n\n // Render the other stuff\n var intDiv = div.style(\"width\", w + \"px\")\n .style(\"height\", h + \"px\")\n .style(\"box-shadow\",\"0px 3px 10px rgba(0, 0, 0, 0.4)\")\n .style(\"border\", \"solid black 1px\")\n\n // Render Contours \n var plotCon = contour_plot.ContourPlot(w,h)\n .f(function(x,y) { return f([x,y])[0] })\n .drawAxis(false)\n .xDomain(axis[0])\n .yDomain(axis[1])\n .contourCount(num_contours)\n .minima([{x:xstar[0], y:xstar[1]}]);\n\n var elements = plotCon(intDiv);\n\n var svg = intDiv.append(\"div\")\n .append(\"svg\")\n .style(\"position\", 'absolute')\n .style(\"left\", 0)\n .style(\"top\", 0)\n .style(\"width\", w)\n .style(\"height\", h)\n .style(\"z-index\", 2) \n\n\n // var X = d3.scaleLinear().domain([0,1]).range(axis[0])\n // var Y = d3.scaleLinear().domain([0,1]).range(axis[1])\n\n var X = d3.scaleLinear().domain(axis[0]).range([0, w])\n var Y = d3.scaleLinear().domain(axis[1]).range([0, h])\n \n // Rendeer Draggable dot\n var circ = svg.append(\"circle\")\n .attr(\"cx\", X(w0[0])) \n .attr(\"cy\", Y(w0[1]) )\n .attr(\"r\", 4)\n .style(\"cursor\", \"pointer\")\n .attr(\"fill\", colorbrewer.OrRd[3][1])\n .attr(\"opacity\", 0.8)\n .attr(\"stroke-width\", 1)\n .attr(\"stroke\", colorbrewer.OrRd[3][2])\n .call(d3.drag().on(\"drag\", function() {\n var pt = d3.mouse(this)\n var x = X.invert(pt[0])\n var y = Y.invert(pt[1])\n this.setAttribute(\"cx\", pt[0])\n this.setAttribute(\"cy\", pt[1])\n w0 = [x,y]\n onDrag(w0)\n iter(state_alpha, state_beta, w0);\n }))\n\n var iterColor = d3.scaleLinear().domain([0, totalIters]).range([\"black\", \"black\"])\n\n var update2D = plot2dGen(X, Y, iterColor)(svg)\n\n // Append x^star\n svg.append(\"path\")\n .attr(\"transform\", \"translate(\" + X(xstar[0]) + \",\" + Y(xstar[1]) + \")\")\n .attr(\"d\", \"M 0.000 2.000 L 2.939 4.045 L 1.902 0.618 L 4.755 -1.545 L 1.176 -1.618 L 0.000 -5.000 L -1.176 -1.618 L -4.755 -1.545 L -1.902 0.618 L -2.939 4.045 L 0.000 2.000\")\n .style(\"fill\", \"white\")\n .style(\"stroke-width\",1)\n\n \n function iter(alpha, beta, w0) {\n\n // Update Internal state of alpha and beta\n state_alpha = alpha\n state_beta = beta\n\n // Generate iterates \n var OW = runMomentum(f, w0, alpha, beta, totalIters)\n var W = OW[1]\n\n update2D(W)\n\n circ.attr(\"cx\", X(w0[0]) ).attr(\"cy\", Y(w0[1]) )\n circ.moveToFront()\n\n }\n\n iter(state_alpha, state_beta, w0);\n \n return { control:iter, \n w0:function() { return w0 }, \n alpha:function() { return state_alpha }, \n beta:function() {return state_beta} }\n\n }", "drawPaths(data) {\n \t\t let that= this;\n let color = CONSTANT.MAP_COLOR;\n\n let googleMapProjection = (coordinates) => {\n var googleCoordinates = new google.maps.LatLng(coordinates[1], coordinates[0]);\n var pixelCoordinates = that.overlayProjection.fromLatLngToDivPixel(googleCoordinates);\n return [pixelCoordinates.x, pixelCoordinates.y];\n }\n\n let path = d3.geo.path().projection(googleMapProjection);\n\n let g = that.svgContainer.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr('class', 'layer-path')\n .attr('pointer-events', 'all');\n\n let gPath = g.selectAll(\"path\")\n .data((d) => {\n return d;\n })\n .enter()\n .append(\"path\")\n .attr(\"d\", path);\n\n if (that.selectedPath.type === 'line') {\n gPath.style(\"fill\", 'none')\n .style(\"stroke\", \"#4886b8\")\n .style('opacity', .9);\n } else {\n gPath.style(\"fill\", (d, i) => {\n return color[i % color.length];\n })\n .style(\"stroke\", \"#4886b8\")\n .style('opacity', .5);\n }\n\n \t}", "renderElements(data, xScale, renderGroups) {\n\n let { lineG, circleG,/* arrowG,*/ tagG } = renderGroups;\n\n lineG.selectAll('rect').remove();\n circleG.selectAll('circle').remove();\n tagG.selectAll('polyline').remove();\n tagG.selectAll('text').remove();\n\n\n this.renderLines(data, xScale, lineG);\n this.renderCircles(data, xScale, circleG);\n this.renderTags(data, xScale, tagG);\n //if(!data.realEndDate) this.renderArrows(data, xScale,arrowG);\n\n }", "componentDidMount() {\n this.svg = d3.select(`#${this.getDivId()}`).append('svg')\n }", "function render(data) {\n xScale.domain(\n d3.extent(data, d => {\n return d[xColumn];\n })\n );\n yScale.domain(\n d3.extent(data, d => {\n return d[yColumn];\n })\n );\n rScale.domain(\n d3.extent(data, d => {\n return d[rColumn];\n })\n );\n\n let circles = g.selectAll(\"circle\").data(data);\n circles\n .enter()\n .append(\"circle\")\n .attr(\"cx\", function(d) {\n return xScale(d[xColumn]);\n })\n .attr(\"cy\", function(d) {\n return yScale(d[yColumn]);\n })\n .attr(\"r\", function(d) {\n return rScale(d[rColumn]);\n })\n .attr(\"fill\", function(d) {\n return colorScale(d[colorColumn]);\n });\n\n circles.exit().remove();\n}", "function init() {\n\n // Scales\n xScale = d3\n .scaleTime()\n .domain(d3.extent(state.data, d => d.year))\n .range([margin.left, width - margin.right]);\n\n yScale = d3\n .scaleLinear()\n .domain([0, d3.max(state.data, d => d.amount)])\n .range([height - margin.bottom, margin.top]);\n\n // Axes\n xAxis = d3.axisBottom(xScale);\n yAxis = d3.axisLeft(yScale);\n\n // UI element setup\n\n\n // SVG setup\n svg = d3\n .select(\"#d3-container\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n\n svg\n .append(\"g\")\n .attr(\"class\", \"axis x-axis\")\n .attr(\"transform\", `translate(0,${height - margin.bottom})`)\n .call(xAxis)\n .append(\"text\")\n .attr(\"class\", \"axis-label\")\n .attr(\"x\", \"50%\")\n .attr(\"dy\", \"3em\")\n .text(\"Year\");\n\n svg\n .append(\"g\")\n .attr(\"class\", \"axis y-axis\")\n .attr(\"transform\", `translate(${margin.left},0)`)\n .call(yAxis)\n .append(\"text\")\n .attr(\"class\", \"axis-label\")\n .attr(\"y\", \"50%\")\n .attr(\"dx\", \"-3em\")\n .attr(\"writing-mode\", \"vertical-rl\")\n .text(\"Amount Owed in Billions of Dollars\");\n\n\n // Draw\n draw();\n console.log(\"initialized!\")\n}", "function redrawCastle(castle) {\n\n if (!gridTranslate) gridTranslate = [0, 0];\n if (!castleTranslate) castleTranslate = [width / 2, height / 2];\n if (!gridAndCastleScale) gridAndCastleScale = 1;\n\n console.log(\"redrawing castle\");\n d3.select(\"#currentCastle\").remove();\n\n currentCastle = svg.append(\"g\")\n .attr(\"id\", \"currentCastle\")\n .attr(\"transform\", function(d) {\n return \"translate(\" + castleTranslate[0] + \",\" + castleTranslate[1] + \"),scale(\" + gridAndCastleScale + \")\";\n });\n\n var roomTiles = currentCastle.selectAll(\"g\")\n .data(castle)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function(d) {\n var snapX = Math.round(d.boardPosition[0] / 10) * 10;\n var snapY = Math.round(d.boardPosition[1] / 10) * 10;\n console.log(width, height);\n return \"rotate(\" + d.rotation + \" \" + (snapX + d.containerDim[0] / 2) + \" \" + (snapY + d.containerDim[1] / 2) + \"),translate(\" + snapX + \",\" + snapY + \")\";\n })\n .call(drag)\n .on(\"dblclick\", rotate);\n\n var roomImages = roomTiles.append(\"image\")\n .attr(\"xlink:href\", function(d) {\n return d.imagePath;\n })\n .attr(\"height\", function(d) {\n return d.containerDim[1];\n })\n .attr(\"width\", function(d) {\n return d.containerDim[0];\n });\n\n\n var polyRooms = roomTiles.append(\"polygon\")\n .filter(function(d) {\n return !d.radius;\n })\n .attr(\"points\", function(d) {\n return d.points.map(function(v) {\n return v.join(\",\");\n }).join(\" \");\n })\n .style(\"stroke\", \"black\")\n .style(\"stroke-width\", \"0\")\n .classed(\"polygon\", true)\n .classed(\"shadow\", true)\n .classed(\"normal\", true);\n // .classed(\"normal\", \"normal\" === checkOverlaps(d))\n // .classed(\"overlapping\", \"overlapping\" === checkOverlaps(d));\n\n var circleRooms = roomTiles.append(\"circle\")\n .filter(function(d) {\n return d.radius;\n })\n .attr(\"cx\", function(d) {\n return d.points[0][0];\n })\n .attr(\"cy\", function(d) {\n return d.points[0][1];\n })\n .attr(\"r\", function(d) {\n return d.radius;\n })\n .style(\"stroke\", \"black\")\n .style(\"stroke-width\", \"0\")\n .classed(\"circle\", true)\n .classed(\"shadow\", true)\n .classed(\"normal\", true);\n }", "update () {\n\n //Domain definition for global color scale\n let domain = [-60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60];\n\n //Color range for global color scale\n let range = [\"#063e78\", \"#08519c\", \"#3182bd\", \"#6baed6\", \"#9ecae1\", \"#c6dbef\", \"#fcbba1\", \"#fc9272\", \"#fb6a4a\", \"#de2d26\", \"#a50f15\", \"#860308\"];\n\n //ColorScale be used consistently by all the charts\n this.colorScale = d3.scaleQuantile()\n .domain(domain)\n .range(range);\n\n // ******* TODO: PART I *******\n\n // Create the chart by adding circle elements representing each election year\n //The circles should be colored based on the winning party for that year\n //HINT: Use the .yearChart class to style your circle elements\n //HINT: Use the chooseClass method to choose the color corresponding to the winning party.\n\n //Append text information of each year right below the corresponding circle\n //HINT: Use .yeartext class to style your text elements\n\n //Style the chart by adding a dashed line that connects all these years.\n //HINT: Use .lineChart to style this dashed line\n\n //Clicking on any specific year should highlight that circle and update the rest of the visualizations\n //HINT: Use .highlighted class to style the highlighted circle\n\n //Election information corresponding to that year should be loaded and passed to\n // the update methods of other visualizations\n\n\n //******* TODO: EXTRA CREDIT *******\n\n //Implement brush on the year chart created above.\n //Implement a call back method to handle the brush end event.\n //Call the update method of shiftChart and pass the data corresponding to brush selection.\n //HINT: Use the .brush class to style the brush.\n\n }", "function draw(data) {\n // Set your scales and axes\n setScales(data);\n setAxes();\n\n // Do a datajoin between your path elements and the data passed to the draw function\n // Make sure to set the identifying key\n var countries = g.selectAll('.countries')\n .data(data, function (d) {\n //console.log(d);\n return d.key\n })\n\n // Handle entering elements (see README.md)\n var path = countries.enter()\n .append('path')\n .attr(\"class\", \"countries\")\n .attr(\"d\", function (d) {\n return line(d.values)\n })\n .attr(\"fill\", \"none\")\n .attr(\"stroke-width\", 1.5)\n .attr(\"stroke\", function (d) {\n return colorScale(d.key)\n })\n .attr(\"stroke-dashoffset\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength()\n return -LENGTH;\n })\n .transition()\n .duration(2000)\n .attr(\"stroke-dasharray\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength();\n return LENGTH + \" \" + LENGTH;\n })\n .transition().duration(1000).attr('stroke-dashoffset', 0)\n .attr(\"stroke-dashoffset\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength()\n return 0;\n })\n\n // Handle updating elements (see README.md)\n countries\n .attr(\"stroke-dasharray\", \"none\")\n .transition()\n .duration(2000)\n .attr(\"d\", function (d) {\n return line(d.values)\n })\n\n\n // Handle exiting elements (see README.md)\n countries\n .exit()\n .remove();\n\n var countries2 = g.selectAll('.countries2')\n .data(data, function (d) {\n //console.log(d);\n return d.key\n })\n\n // Handle entering elements (see README.md)\n var path2 = countries2.enter()\n .append('path')\n .attr(\"class\", \"countries2\")\n .attr(\"d\", function (d) {\n return line2(d.values)\n })\n .attr(\"fill\", \"none\")\n .attr(\"stroke-width\", 1.5)\n .attr(\"stroke\", function (d) {\n return colorScale(d.key)\n })\n .attr(\"stroke-dashoffset\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength()\n return -LENGTH;\n })\n .transition()\n .duration(2000)\n .attr(\"stroke-dasharray\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength();\n return LENGTH + \" \" + LENGTH;\n })\n .attr(\"stroke-dashoffset\", function (d) {\n var LENGTH = d3.select(this).node().getTotalLength()\n return 0;\n });\n\n // Handle updating elements (see README.md)\n countries2\n .attr(\"stroke-dasharray\", \"none\")\n .transition()\n .duration(2000)\n .attr(\"d\", function (d) {\n return line2(d.values)\n });\n\n\n // Handle exiting elements (see README.md)\n countries2.exit().remove();\n\n\n }", "renderWorld() {\n this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);\n\n for (let row = 0; row < this.rowNumber; row++) {\n this.drawLine({ num: row, isRow: true });\n }\n for (let col = 0; col < this.colNumber; col++) {\n this.drawLine({ num: col, isRow: false });\n }\n\n this.hoverCell();\n this.renderLiveCells();\n }", "render(svg, events) {\n let prevSvg = document.querySelector(`${this.eCfg.selector} svg`);\n if (prevSvg) prevSvg.remove();\n\n svg._visualization = this.drawableElement._visualization;\n this.drawableElement = svg;\n d3.select(svg).selectAll('path').attr('vector-effect', 'non-scaling-stroke'); // for zoom\n\n svg.style.top = '0px';\n svg.style.left = '0px';\n svg.style.position = 'absolute';\n this.element.append(svg) // this.v.element.selector\n\n return this.attachEvents(svg, events);;\n }", "async drawSFLines(){\n let that = this;\n let SemifinalLines = [0, 1, 2, 3, 4, 5];\n let SFLines = d3.select(\"#SF-Lines\").selectAll('line');\n let joined = SFLines.data(SemifinalLines).join('line');\n joined.attr(\"x1\", d =>{\n if(d < 2)\n return that.buffer + that.lineLength * 2;\n else if (d >= 2 && d < 4)\n return that.svgWidth - that.buffer - that.lineLength * 3 - that.lineThickness / 2;\n else if (d == 4)\n return that.lineLength * 3 + that.buffer;\n else\n return that.svgWidth - that.buffer - that.lineLength * 3;})\n .attr(\"y1\", d =>{\n if(d < 2)\n return that.buffer + that.R16Separation * 4 * d + that.R16Separation / 2 * 3;\n else if (d >= 2 && d < 4)\n return that.buffer + that.R16Separation * 4 * (d - 2) + that.R16Separation / 2 * 3;\n else\n return that.buffer + that.R16Separation / 2 * 3;})\n .attr(\"x2\", d =>{\n if(d < 2)\n return that.buffer + that.lineLength * 3 + that.lineThickness / 2;\n else if (d >= 2 && d < 4)\n return that.svgWidth - that.buffer - that.lineLength * 2;\n else if (d == 4)\n return that.lineLength * 3 + that.buffer;\n else\n return that.svgWidth - that.buffer - that.lineLength * 3;})\n .attr(\"y2\", d =>{\n if(d < 2)\n return that.buffer + that.R16Separation * 4 * d + that.R16Separation / 2 * 3;\n else if (d >= 2 && d < 4)\n return that.buffer + that.R16Separation * 4 * (d - 2) + that.R16Separation / 2 * 3;\n else\n return that.buffer + that.R16Separation / 2 * 3 + that.R16Separation * 4;})\n .attr(\"class\", \"bracket-line\"); \n }", "getDragObject(data) {\n\n let {positionScale, yScale} = this.getScales(data)\n\n // custom invert function\n let positionScaleInvert = this.invertScale(positionScale)\n let yScaleInvert = this.invertScale(yScale)\n \n /* 3 phases of drag\n * Phase 1: Drag Start - Here we do two things\n * 1. Change color of target element to red\n * 2. Create a temp rectangle that guides the user where the outcome will be when he/she stops\n * Phase 2: Dragging - Here only one thing happens\n * 1. Based on where the user is trying to drag the element, the UI will display how the output will look like when the user stops the drag\n * Phase 3: Drag ends - Here a lot of things happen, but mainly one thing happens and a lot of different sceanrios\n * 1. Based on where the user stops dragging, we update the data and then call showdata again.\n * Cases to handle in drag end:\n * i) \n */\n\n this['drag'+this.boundingPanel] = d3.drag()\n .on(\"start\", d => {\n let x = 1\n\n // Get the target element\n let targetRectNumber = d[this.numericalColumn].split(\"-\").length\n let targetElement = d3.select(`#${this.boundingPanel}${d[this.categoricalColumn]}${targetRectNumber}`)\n\n // Change targets color to red\n targetElement.attr(\"fill\",\"rgb(7,77,101)\")\n\n // Get the properties of target element to create a temp rectangle\n let targetHeight = targetElement.attr(\"height\")\n let targetWidth = targetElement.attr(\"width\")\n let targetTransform = targetElement.attr(\"transform\")\n\n // Actually create the temp rectangle\n d3.select(`#${this.boundingPanel}barChart`)\n .append(\"rect\")\n .attr(\"id\", \"tempRect\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"rgb(7,77,101)\")\n .style(\"stroke-dasharray\", (\"3, 3\"))\n .style(\"stroke-width\", \"2\")\n .attr(\"width\", targetWidth)\n .attr(\"height\", targetHeight)\n .attr(\"transform\", targetTransform)\n })\n .on(\"drag\", (d, i, arr) => {\n\n d3.selectAll(\"#tempArrow\").remove()\n\n // Get the target element\n let targetRectNumber = d[this.numericalColumn].split(\"-\").length\n let targetElement = d3.select(`#${this.boundingPanel}${d[this.categoricalColumn]}${targetRectNumber}`)\n\n // Get the properties of target element to move the temp rectangle\n let targetHeight = targetElement.attr(\"height\")\n let targetWidth = targetElement.attr(\"width\")\n\n // Get the current position of mouse to decide where the user is trying to place the target\n let mouseX = d3.event.x\n let mouseY = d3.event.y\n\n // Get the nearest category based on the x-coordinate of mouse to identify where the user is trying to place the target\n let nearestCategory = positionScaleInvert(mouseX)\n\n // Get the topmost element of the stack of bars where the user is trying to place the target, lets call it nearestElement\n let nearestRectNumber = 1\n while(true) {\n let x = d3.select(`#${this.boundingPanel}${nearestCategory}${nearestRectNumber}`)\n if(x.empty()) {\n nearestRectNumber -= 1\n break\n }\n nearestRectNumber += 1\n }\n let nearestElement = d3.select(`#${this.boundingPanel}${nearestCategory}${nearestRectNumber}`)\n \n // Move the target along with the mouse\n targetElement.attr(\"transform\", `translate(${mouseX - targetWidth/2}, ${mouseY - targetHeight/2})`)\n \n // If the nearestCategory is not the same as target's current category, then move the temp rect to new category position\n let newTarget = d3.select(\"#tempRect\")\n if(nearestCategory != d[this.categoricalColumn]) {\n\n let nearestHeight = nearestElement\n .attr(\"transform\")\n .replace(\"translate(\",\"\")\n .replace(\")\",\"\").split(\",\")[1] - targetHeight\n\n newTarget\n .transition()\n .duration(100)\n .ease(d3.easeLinear)\n .attr(\"transform\", `translate(${positionScale(nearestCategory)}, ${nearestHeight})`)\n }\n // Otherwise just place the temp rect back to target's original position\n else {\n\n // For each data element do this\n let targetCategoryIndex = []\n data.forEach((element, index) => {\n // If the element encountered is the target element\n if(element[this.categoricalColumn] == d[this.categoricalColumn]){\n targetCategoryIndex.push(index)\n }\n });\n\n // Sort the targetCategoryIndex based on the length of the numerical value at that index. This way the index at 0th position of targetCategoryIndex represents the bottommost element in the stack and the last element represents the topmost element\n let self = this\n targetCategoryIndex.sort(function(a, b){\n return data[a][self.numericalColumn].length - data[b][self.numericalColumn].length;\n });\n\n // Finding the data index that has longest numerical value among the values in \"targetCategoryIndex\", i.e. finding the topmost element with category = targetCategory\n let targetTopmostElementIndex = targetCategoryIndex[targetRectNumber - 1]\n\n // FInding the overall category of the target and the original category of the target\n let targetOriginalNumerical = data[targetTopmostElementIndex][this.numericalColumn].split(\"-\").pop()\n\n let targetY = targetElement\n .attr(\"transform\")\n .replace(\"translate(\",\"\")\n .replace(\")\",\"\").split(\",\")[1]\n \n let overallHeightOfStack = yScale(d3.sum(data[targetTopmostElementIndex][this.numericalColumn].split(\"-\").slice(0,-1).map(k => +k)))\n \n let topOfTargetStack = this.BAR_CHART_HEIGHT - overallHeightOfStack\n let yPositionOfTarget = yScale(targetOriginalNumerical) - parseFloat(targetY)\n\n if(targetRectNumber == targetCategoryIndex.length && targetRectNumber != 1 && yPositionOfTarget - topOfTargetStack > 25){\n newTarget\n .transition()\n .duration(100)\n .ease(d3.easeLinear)\n .attr(\"transform\", `translate(${positionScale(d[this.categoricalColumn])}, ${yScale(d3.sum(d[this.numericalColumn].split(\"-\").map(k => +k))) - 25})`)\n \n d3.select(`#${this.boundingPanel}barChart`)\n .append(\"path\")\n .attr(\"id\", \"tempArrow\")\n .attr(\"fill\", \"rgb(7,77,101)\")\n .attr(\"d\", \"M 0 0 L 6 4 L 4 4 L 4 8 L -4 8 L -4 4 L -6 4 L 0 0\")\n .style(\"text-align\", \"center\")\n .style(\"display\", \"block\")\n .attr(\"transform\", `translate(${positionScale(d[this.categoricalColumn]) + positionScale.bandwidth()/2}, ${(yScale(d3.sum(d[this.numericalColumn].split(\"-\").slice(0, -1).map(k => +k))) - 25/2 - 4)})`)\n }\n else {\n d3.selectAll(\"#tempArrow\").remove()\n newTarget\n .transition()\n .duration(100)\n .ease(d3.easeLinear)\n .attr(\"transform\", `translate(${positionScale(d[this.categoricalColumn])}, ${yScale(d3.sum(d[this.numericalColumn].split(\"-\").map(k => +k)))})`)\n }\n\n \n } \n\n })\n .on(\"end\", (d,i,arr) => {\n\n // Basically the idea here is that the target element will always be the topmost element.\n // Therefore, its numerical value will always be of maximum length.\n // If we want to drop some middle or lower element then we have to think of some other logic.\n\n //What I want: (For merge)\n // 1. Category of nearest element change to A-C. Other things remain same\n // 2. Category of target element change to A-C. and value also change. Other things remain same\n\n // What I want: (For split)\n // 1. Category of all elements (except target element) whose category is same as target elements category does not have target category in it anymore\n \n \n // Since we have dropped the element we can remove the temp rectangle\n \n d3.selectAll(\"#tempArrow\").remove()\n d3.select(\"#tempRect\").remove()\n\n // Get the target SVG topmost element (i.e. one that has the targetRectNumber = number of numerical values separated by '-' in \"numericalColumn\")\n let targetRectNumber = d[this.numericalColumn].split(\"-\").length\n let targetElement = d3.select(`#${this.boundingPanel}${d[this.categoricalColumn]}${targetRectNumber}`)\n \n // Get the nearest category where we are planning to drop the element needed later\n let mouseX = d3.event.x\n let nearestCategory = positionScaleInvert(mouseX)\n\n // If the target element is not at the same position when we drop it, \n // then we find all the datapoints which are at the category of target element\n // and all the datapoints which are at the category of nearest category\n let nearestCategoryIndex = []\n let targetCategoryIndex = []\n\n if(nearestCategory != d[this.categoricalColumn]) {\n\n // For each data element do this\n data.forEach((element, index) => {\n\n // If the element encountered is the place where we are planning to drop\n if(element[this.categoricalColumn] == nearestCategory){\n nearestCategoryIndex.push(index)\n }\n\n // Else if the element encountered is the target element\n else if(element[this.categoricalColumn] == d[this.categoricalColumn]){\n targetCategoryIndex.push(index)\n }\n });\n\n // Sort the targetCategoryIndex based on the length of the numerical value at that index. This way the index at 0th position of targetCategoryIndex represents the bottommost element in the stack and the last element represents the topmost element\n let self = this\n targetCategoryIndex.sort(function(a, b){\n return data[a][self.numericalColumn].length - data[b][self.numericalColumn].length;\n });\n\n // Finding the data index that has longest numerical value among the values in \"targetCategoryIndex\", i.e. finding the topmost element with category = targetCategory\n let targetTopmostElementIndex = targetCategoryIndex[targetRectNumber - 1]\n\n // FInding the overall category of the target and the original category of the target\n let targetCategory = data[targetTopmostElementIndex][this.categoricalColumn]\n let tempCategory = targetCategory.split(\"-\")[targetRectNumber - 1]\n \n // Now for each element that has the same category as the current taregt element, \n // we will remove the original numerical value of the target element from them if they \n // lie on top of the target element, i.e. their index in targetCategoryIndex is higher \n // than our actual target\n data.forEach((element, index) => {\n\n // If the element encountered is not the target element but category is same\n if(element != d && element[this.categoricalColumn] == targetCategory) {\n if (targetCategoryIndex.indexOf(index) > targetRectNumber-1){ \n let numericalValueArray = element[this.numericalColumn].split(\"-\")\n numericalValueArray.splice(targetRectNumber-1, 1)\n element[this.numericalColumn] = numericalValueArray.join(\"-\")\n }\n }\n\n })\n\n // Now for each element that has the same category as the current taregt element, we will remove the original category of the target element from them\n data.forEach((element, index) => {\n\n // If the element encountered is not the target element but category is same\n if(element != d && element[this.categoricalColumn] == targetCategory) {\n let x = element[this.categoricalColumn].split(\"-\").filter(function(value) {\n return value != tempCategory;\n }).join(\"-\")\n element[this.categoricalColumn] = x\n }\n\n })\n\n // Find the original numerical value of the target element\n let tempNumerical = data[targetTopmostElementIndex][this.numericalColumn].split(\"-\").pop()\n\n // Sort the nearestCategoryIndex based on the length of the numerical value at that index. This way the index at 0th position of nearestCategoryIndex represents the bottommost element in the stack and the last element represents the topmost element\n nearestCategoryIndex.sort(function(a, b){\n return data[a][self.numericalColumn].length - data[b][self.numericalColumn].length;\n });\n \n // Finding the data index that has longest numerical value among the values in \"nearestCategoryIndex\", i.e. finding the topmost element with category = nearestCategoryIndex\n let nearestTopmostElementIndex = nearestCategoryIndex[nearestCategoryIndex.length - 1]\n\n // Adding the original category and numerical value of the target element to the nearest category\n data[targetTopmostElementIndex][this.categoricalColumn] = `${data[nearestTopmostElementIndex][this.categoricalColumn]}-${tempCategory}`\n data[targetTopmostElementIndex][this.numericalColumn] = `${data[nearestTopmostElementIndex][this.numericalColumn]}-${tempNumerical}`\n \n // Adding the original category of the target element to all the elements in the stack of nearest category\n nearestCategoryIndex.forEach(index => {\n data[index][this.categoricalColumn] = `${data[index][this.categoricalColumn]}-${tempCategory}`\n });\n }\n // Else if the element is at the same category as earlier and is the topmost element\n else {\n\n // For each data element do this\n let targetCategoryIndex = []\n data.forEach((element, index) => {\n // If the element encountered is the target element\n if(element[this.categoricalColumn] == d[this.categoricalColumn]){\n targetCategoryIndex.push(index)\n }\n });\n\n // Sort the targetCategoryIndex based on the length of the numerical value at that index. This way the index at 0th position of targetCategoryIndex represents the bottommost element in the stack and the last element represents the topmost element\n let self = this\n targetCategoryIndex.sort(function(a, b){\n return data[a][self.numericalColumn].length - data[b][self.numericalColumn].length;\n });\n\n // Finding the data index that has longest numerical value among the values in \"targetCategoryIndex\", i.e. finding the topmost element with category = targetCategory\n let targetTopmostElementIndex = targetCategoryIndex[targetRectNumber - 1]\n\n // FInding the overall category of the target and the original category of the target\n let targetCategory = data[targetTopmostElementIndex][this.categoricalColumn]\n let targetOriginalCategory = targetCategory.split(\"-\")[targetRectNumber - 1]\n let targetOriginalNumerical = data[targetTopmostElementIndex][this.numericalColumn].split(\"-\").pop()\n\n // Finding the height of elements below our target + height of target\n let targetY = targetElement\n .attr(\"transform\")\n .replace(\"translate(\",\"\")\n .replace(\")\",\"\").split(\",\")[1]\n \n let overallHeightOfStack = yScale(d3.sum(data[targetTopmostElementIndex][this.numericalColumn].split(\"-\").slice(0,-1).map(k => +k)))\n \n let topOfTargetStack = this.BAR_CHART_HEIGHT - overallHeightOfStack\n let yPositionOfTarget = yScale(targetOriginalNumerical) - parseFloat(targetY)\n\n // Checking if the element is the topmost element and there are elements below it and that we have dragged it up enough\n if(targetRectNumber == targetCategoryIndex.length && targetRectNumber != 1 && yPositionOfTarget - topOfTargetStack > 25) {\n\n // Now for each element that has the same category as the current taregt element, \n // we will remove the original numerical value of the target element from them if they \n // lie on top of the target element, i.e. their index in targetCategoryIndex is higher \n // than our actual target\n data.forEach((element, index) => {\n\n // If the element encountered is not the target element but category is same\n if(element != d && element[this.categoricalColumn] == targetCategory) {\n if (targetCategoryIndex.indexOf(index) > targetRectNumber-1){ \n let numericalValueArray = element[this.numericalColumn].split(\"-\")\n numericalValueArray.splice(targetRectNumber-1, 1)\n element[this.numericalColumn] = numericalValueArray.join(\"-\")\n }\n }\n\n })\n\n // Now for each element that has the same category as the current taregt element, we will remove the original category of the target element from them\n data.forEach((element, index) => {\n\n // If the element encountered is not the target element but category is same\n if(element != d && element[this.categoricalColumn] == targetCategory) {\n let x = element[this.categoricalColumn].split(\"-\").filter(function(value) {\n return value != targetOriginalCategory;\n }).join(\"-\")\n element[this.categoricalColumn] = x\n }\n\n })\n\n // Changing the original category and numerical value of the target element to the original category and numerical value\n data[targetTopmostElementIndex][this.categoricalColumn] = targetOriginalCategory\n data[targetTopmostElementIndex][this.numericalColumn] = targetOriginalNumerical\n\n }\n }\n this.showData(data)\n targetElement.attr(\"fill\",\"rgb(32,142,183)\")\n })\n }", "function drawVisualization() {\n // Create and populate a data table.\n var data = new vis.DataSet();\n\n $.getJSON('/rawstars', function(stars) { \n for (i in stars) {\n var x = stars[i].x,\n y = stars[i].y,\n z = stars[i].z;\n starMemos[getKey(stars[i])] = stars[i];\n data.add({\n x: x,\n y: y,\n z: z,\n style: stars[i].lum\n });\n }\n\n // specify options\n var options = {\n width: '100%',\n height: '100%',\n style: 'dot-color',\n showPerspective: true,\n showGrid: true,\n showShadow: false,\n keepAspectRatio: true,\n verticalRatio: 0.5,\n legendLabel: \"Luminosity\",\n tooltip: function(star) {return generateTooltip(star);}\n };\n\n // create a graph3d\n var container = document.getElementById('mygraph');\n graph3d = new vis.Graph3d(container, data, options);\n });\n}", "function update(data) {\n\n // DATA JOIN\n // Join new data with old elements, if any.\n gemCircles = svgGroup.selectAll(\".gemCircle\")\n .data(data);\n\n text = svgGroup.selectAll(\"text\")\n .data(data);\n\n\n // UPDATE\n // Update old elements as needed.\n gemCircles.transition()\n .duration(750);\n text.transition()\n .duration(750);\n\n //delete all old lines\n d3.selectAll(\".line\").remove();\n var line = d3.svg.line()\n .x(function(d) {\n return d.x;\n })\n .y(function(d) {\n return d.y;\n })\n .interpolate(\"bundle\")\n .tension(sliderVal);\n\n\n // draw all lines\n _.forEach(data, function(obj){\n _.forEach(obj[\"connections\"], function(elem, i){ //e.g. elem = 0-1\n var moveFromTo = i.split(\"-\"); // split \"0-2\" = i into {0, 2} 0= from 2 = to\n var from = moveFromTo[0];\n var to = moveFromTo[1];\n var reverseKey = to + \"-\" + from; //make \"2-3\" from i = \"3-2\"\n\n //draw line\n _.forEach(elem[\"pathEnds\"], function(item, j){ //all path elements -> array with 0-7 e.g.\n var numOfPeople = (Math.abs(elem[\"delta\"]) > alphaLimit) ? alphaLimit : Math.abs(elem[\"delta\"]);\n var alphaMap = d3.scale.linear() //map number of people to an alpha value\n .domain([1, 100])\n .range([0.15, 1]);\n var strokeColor = \"rgba(254, 255, 223,\" + alphaMap(numOfPeople) + \")\";\n\n //prohibit program to draw double lines\n if (from >= to){\n var x = data[to][\"connections\"][reverseKey][\"pathEnds\"][j][\"x\"];\n var y = data[to][\"connections\"][reverseKey][\"pathEnds\"][j][\"y\"];\n var path = [];\n //define path animation direction\n if (data[to][\"connections\"][reverseKey][\"delta\"] < 0){\n path[0] = {\"x\": item[\"x\"] , \"y\": item[\"y\"]};\n path[1] = { x: bgCircCenterX, y: bgCircCenterY }; //center of circle as control point\n path[2] = {\"x\": x , \"y\": y};\n } else {\n path[2] = {\"x\": item[\"x\"] , \"y\": item[\"y\"]};\n path[1] = { x: bgCircCenterX, y: bgCircCenterY }; //center of circle as control point\n path[0] = {\"x\": x , \"y\": y};\n }\n\n\n\n lines = svgGroup.append(\"path\")\n .data(path)\n .attr(\"class\", \"line\")\n .attr(\"d\", line(path))\n .style(\"fill\", \"none\")\n .style(\"stroke-width\", 1)\n .style(\"stroke\", strokeColor)\n .style(\"stroke-dasharray\", \"2\")\n\n\n // lines.data(path)\n // .enter()\n // .append(\"path\")\n // .transition()\n // .duration(750)\n // .style(\"fill-opacity\", 1);\n\n // lines.exit()\n // .transition()\n // .duration(750)\n // .style(\"fill-opacity\", 1e-6) //1e-6 extremly small number -> prohibit flickering ??\n // .remove();\n\n // var lineAttr = lines\n // .attr(\"class\", \"line\")\n // .attr(\"d\", line(path))\n // .style(\"fill\", \"none\")\n // .style(\"stroke-width\", 1)\n // .style(\"stroke\", strokeColor)\n // .style(\"stroke-dasharray\", \"2\")\n\n }\n\n });\n });\n });\n\n\n // ENTER\n // Create new elements as needed.\n gemCircles.enter()\n .append(\"circle\")\n .transition()\n .duration(750)\n .style(\"fill-opacity\", 1);\n\n text.enter()\n .append(\"text\")\n .transition()\n .duration(750)\n .style(\"fill-opacity\", 1);\n\n\n // EXIT\n // Remove old elements as needed.\n gemCircles.exit()\n .transition()\n .duration(750)\n .style(\"fill-opacity\", 0) //1e-6 extremly small number -> prohibit flickering ??\n .remove();\n\n text.exit()\n .transition()\n .duration(750)\n .style(\"fill-opacity\", 0) //1e-6 extremly small number -> prohibit flickering ??\n .remove();\n\n\n\n\n\n //add text to circles\n var offset;\n var textLabels = text\n .attr(\"x\", function(d) {\n offset = 11; // in pixel\n return (rad * Math.cos(d[\"angle\"]) + bgCircCenterX + offset);\n })\n .attr(\"y\", function(d) {\n return (rad * Math.sin(d[\"angle\"]) + bgCircCenterY + 2); //last number = y offset to align text with center of circle\n })\n .text(function(d) {\n return d[\"name\"];\n })\n .attr(\"transform\", function(d) {\n var degrees = d[\"angle\"] * (180/Math.PI);\n return \"rotate(\" + degrees + \" \" + (rad * Math.cos(d[\"angle\"]) + bgCircCenterX) +\",\" + (rad * Math.sin(d[\"angle\"]) + bgCircCenterY) +\")\";\n })\n .attr(\"class\", function(d) {\n return \"label \" + d[\"name\"] ;\n })\n\n\n\n\n //set circle Attributes\n var gemCircAttr = gemCircles\n .each(function(d, i){\n d3.select(this).attr({\n cx: function(){\n return d[\"centerPos\"][\"xM\"];\n },\n cy: function(){\n return d[\"centerPos\"][\"yM\"];\n },\n r: function(d){\n return d[\"circleRad\"];\n }, //todo: write mapping function and set a max size\n fill: function(d) {\n //use mapping function to map trafficCosts to RGB from 0 - 255\n var colorMap = map_range(d[\"trafficcostPerPerson\"], 0, maxTraffCost, 35, 0 ); //hsl 0 -350\n colorMap = Math.floor(colorMap); //and round it to whole numbers to use as rgb\n // console.log(colorMap + \" - \" + d[\"trafficCosts\"]);\n return \"hsla(\" + colorMap + \", 100%, 58%, 0.7)\";\n },\n class: \"gemCircle\"\n })\n .transition()\n .duration(750)\n .style(\"fill-opacity\", 1);\n\n\n\n })\n\n } //update function", "function add(){\n addDatapoints(1);\n // we add new code below:\n\n//UPDATE BARS\n\n// we add new code below:\nconsole.log(\"new data\", data)\n\nelementsForPage = graphGroup.selectAll(\".datapoint\").data(data);\n update();\n elementsForPage.transition().duration(1000).attr(\"transform\", function(d, i){//horizontal\n return \"translate(\"+ xScale(d.key)+ \",\" + (h - padding) + \")\"\n });\n elementsForPage.select(\"rect\")\n .attr(\"fill\",\"black\")\n .transition()\n .delay(100)\n .duration(2000)//vertical\n .attr(\"width\", function(){\n return xScale.bandwidth();\n })\n .attr(\"y\", function(d,i){\n return -yScale(d.value);\n })\n .attr(\"height\", function(d, i){\n return yScale(d.value);\n })\n ;\n\n// note, we don't need \"let\" because the variable elementsForPage already exists\nconsole.log(elementsForPage);\n\nlet incomingDataGroups = enteringElements\n .append(\"g\")\n .classed(\"datapoint\", true)\n;\n// position the groups:\nincomingDataGroups.attr(\"transform\", function(d, i){\n return \"translate(\"+ xScale(d.key)+ \",\" + (h - padding) + \")\"\n});\n\n incomingDataGroups\n .append(\"rect\")\n .attr(\"y\", function(d,i){\n return 0;\n })\n .attr(\"height\", function(d, i){\n return 0;\n })\n .attr(\"width\", function(){\n return xScale.bandwidth();\n })\n .transition()\n .delay(120)\n .duration(2000)//pink\n .attr(\"y\", function(d,i){\n return -yScale(d.value);\n })\n .attr(\"height\", function(d, i){\n return yScale(d.value);\n })\n .attr(\"fill\", \"#F27294\")\n ;\n}", "function update(rawdata){\n\t\tconsole.log('----WARNING: ITEMS ARE DRAWN IN LAYERS IN THE ODER IN WHICH THEIR SVG ELEMENT WAS CREATED------\\n'); \n\t\t//console.log('mousedLine ' + mousedLine +'\\n');\n\t\tlinesSVG.selectAll(\"path.line\").each(function(d,i){\t\t\t\t\t\t//<----------use .each for d3 selections (can use 'this'), and .forEach for traditional arrays \n\t\t\tlineIDX = i;\n\t\t\tif(mousedLine !== -1){\n\t\t\t\t//----DO NOT CHANGE THE ORDER OF THESE CHECKS...\n\t\t\t\t//....THE COLORING OF THE DATA POINTS IMPLICITLY DEPENDS ON IT!!!!!!-----\n\t\t\t\t\tif( \"US Average\" === this.getAttribute('idKey')) {\n\t\t\t\t\t\t//console.log('modifying line ' + mousedLine + '\\n'); \n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.75);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\t\n\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(parseInt(sampleData.us_average_data.time_category_data[i].key)))\n\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(sampleData.us_average_data.time_category_data[i].values))\t\t\t\t\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"r\", 6)\n\t\t\t\t\t\t\td3.select(this).attr(\"idKey\", parseInt(sampleData.us_average_data.time_category_data[i].key))\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 1)\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.85)\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke\", \"rgb(64, 64, 64)\")\n\t\t\t\t\t\t\t//d3.select(this).attr(\"fill\", \"rgb(255, 0, 0)\")\n\t\t\t\t\t\t\t//d3.select(this).attr(\"fill-opacity\", 0.5)\t\n\t\t\t\t\t\t}); \n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i) {\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(parseInt(sampleData.us_average_data.time_category_data[i].key)) + \",\" + yScale(sampleData.us_average_data.time_category_data[i].values - 35) + \")\");\n\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\tts = t.selectAll(\"tspan\");\n\t\t\t\t\t\t\tts[0][0].textContent = sampleData.us_average_data.category_state;\n\t\t\t\t\t\t\tts[0][1].textContent = Math.round(sampleData.us_average_data.time_category_data[i].values * 100)/100;\t\t\t\t\t\t\t \n\t\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse if(mousedLine === this.getAttribute('idKey')) {\n\t\t\t\t\t\t//apply no oppacity to the line that has been mousedOver.\n\t\t\t\t\t\t//make the line thicker\n\t\t\t\t\t\t\t//console.log('points on lineIDX = ' + lineIDX + '\\n');\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.75);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t\t//-------move the points to the one for the selected line-----\n\t\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i].key)))\t\t\t//lineIDX-1 because svg idexing it 1 indexed and d3 javascript is 0 indexed\n\t\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(sampleData.state_category_data[lineIDX-1].time_category_data[i].values))\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"r\", 6)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"idKey\", parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i].key))\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 1)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.85)\n\t\t\t\t\t\t\t\td3.select(this).attr(\"stroke\", \"rgb(64, 64, 64)\")\n\t\t\t\t\t\t\t\t//d3.select(this).attr(\"fill\", \"rgb(0, 0, 255)\")\n\t\t\t\t\t\t\t\t//d3.select(this).attr(\"fill-opacity\", 0.5)\t\n\t\t\t\t\t\t\t}); \n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i1) {\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(parseInt(sampleData.state_category_data[lineIDX-1].time_category_data[i1].key)) + \",\" + yScale(sampleData.state_category_data[lineIDX-1].time_category_data[i1].values) + 35 + \")\");\n\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\tts = t.selectAll(\"tspan\");\n\t\t\t\t\t\t\tts[0][0].textContent = sampleData.state_category_data[lineIDX-1].category_state;\n\t\t\t\t\t\t\tts[0][1].textContent = Math.round(sampleData.state_category_data[lineIDX-1].time_category_data[i1].values * 100)/100;\t\t\t\t\t\t\t \n\t\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// dim the non-moused over lines\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.2);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 2);\n\t\t\t\t\t}\n\t\t\t\t\ttooltipsSVG.attr(\"opacity\", 0.85);\t\n\t\t\t}\n\t\t\telse {\n\t\n\t\t\t\t//-------- Reset all lines to default ----------\n\t\t\t\t\tif( \"US Average\" === this.getAttribute('idKey')) {\n\t\t\t\t\t\t// reset the US Average line\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.5);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 4);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// reset all the other lines\n\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0.5);\n\t\t\t\t\t\td3.select(this).attr(\"stroke-width\", 2);\n\t\t\t\t\t}\n\t\n\t\t\t\t\t//-------hide all the points-----\n\t\t\t\t\t\tpointsSVG.selectAll(\"circle\").each(function(d,i){\n\t\t\t\t\t\t\td3.select(this).attr(\"cx\", xScale(-100))\n\t\t\t\t\t\t\td3.select(this).attr(\"cy\", yScale(-100))\t\t\t\t\t\t\n\t\t\t\t\t\t\td3.select(this).attr(\"stroke-opacity\", 0)\n\t\t\t\t\t\t\td3.select(this).attr(\"fill-opacity\", 0)\t\n\t\t\t\t\t\t}); \t\t\t\t\n\t\t\t\t\t//--------- Move and hide all tool tips and points to keep them out of the way ---------\t\t\t\t\n\t\t\t\t\t\ttooltipsSVG.selectAll('g').each(function(d,i) {\t\t\n\t\t\t\t\t\t\t\td3.select(this).attr(\"transform\", \"translate(\" + xScale(-100) + \",\" + yScale(-100) + \")\");\t\t\t\t\t//moving the tool tips off the edge of the svg object window to hide them.\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\tt = d3.select(this).select(\"text\");\n\t\t\t\t\t\t\t\t\tt.selectAll(\"tspan\").each( function(d,i) {\n\t\t\t\t\t\t\t\t\t\td3.select(this).text(Math.round(0 * 100)/100);\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});\n\t\t\t\t\t\ttooltipsSVG.attr(\"opacity\", 0);\t\t\t\t\t\t\n\t\n\t\t\t}\n\t\n\t\t});\n\t\t\n\t\tthis.test1 = linesSVG.selectAll(\"path.line\");\n\t\tthis.test2 = pointsSVG.selectAll(\"circle\");\n\t\tthis.test3 = tooltipsSVG.selectAll('g');\n\t}" ]
[ "0.6549076", "0.64834744", "0.6460986", "0.6456793", "0.6455284", "0.6453635", "0.6431173", "0.64093983", "0.6392877", "0.63787854", "0.6356816", "0.63239366", "0.6311759", "0.6289212", "0.62745196", "0.6274105", "0.6241139", "0.6204532", "0.62030774", "0.6201816", "0.61971754", "0.61793953", "0.616653", "0.6156181", "0.6153356", "0.6147454", "0.6134858", "0.6132938", "0.61291224", "0.6128324", "0.6128055", "0.611759", "0.6088422", "0.6068199", "0.6067818", "0.6063736", "0.60613066", "0.6049777", "0.6041075", "0.6036623", "0.60269445", "0.6024724", "0.6016917", "0.6015489", "0.60154766", "0.60128665", "0.6012314", "0.5999859", "0.59914047", "0.5983293", "0.5978442", "0.59755284", "0.59732515", "0.59667605", "0.5965558", "0.5965157", "0.5963924", "0.5963695", "0.5961068", "0.5960831", "0.59584534", "0.59465706", "0.5942717", "0.5941817", "0.59364754", "0.593519", "0.593484", "0.59329647", "0.5930475", "0.5929761", "0.59270865", "0.59240663", "0.5914313", "0.5907146", "0.59026194", "0.5902232", "0.58940136", "0.5892444", "0.5890847", "0.5889453", "0.58776593", "0.5874195", "0.587332", "0.5870884", "0.5865839", "0.58622855", "0.5853995", "0.5852353", "0.58512163", "0.58510643", "0.58510387", "0.5846088", "0.58460087", "0.5845073", "0.58444077", "0.58419967", "0.5840433", "0.58357406", "0.58355904", "0.5830833", "0.58225626" ]
0.0
-1
When a new async handle is created
function init(uid, handle, provider, parentId) { if (hasContext(parentId || currentUid)) { // This new async handle is the child of a handle with a context. // Set this handles context to that of its parent. contexts.set(uid, contexts.get(parentId || currentUid)); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "[kSetHandle](handle) {\n const state = this[kInternalState];\n const current = this[kHandle];\n this[kHandle] = handle;\n if (handle !== undefined) {\n handle.onread = onStreamRead;\n handle[owner_symbol] = this;\n this[async_id_symbol] = handle.getAsyncId();\n state.id = handle.id();\n state.dataRateHistogram = new Histogram(handle.rate);\n state.dataSizeHistogram = new Histogram(handle.size);\n state.dataAckHistogram = new Histogram(handle.ack);\n state.sharedState = new QuicStreamSharedState(handle.state);\n state.session[kAddStream](state.id, this);\n state.ready = true;\n this.emit(kReady);\n } else {\n if (current !== undefined) {\n current.stats[IDX_QUIC_STREAM_STATS_DESTROYED_AT] =\n process.hrtime.bigint();\n state.stats = new BigInt64Array(current.stats);\n }\n state.sharedState = undefined;\n if (state.dataRateHistogram)\n state.dataRateHistogram[kDestroyHistogram]();\n if (state.dataSizeHistogram)\n state.dataSizeHistogram[kDestroyHistogram]();\n if (state.dataAckHistogram)\n state.dataAckHistogram[kDestroyHistogram]();\n }\n }", "async onFinished() {}", "onCreatedHandler() {\n this.fetchData();\n }", "AsyncProcessResponse() {\n\n }", "async postCreate () {\n\t}", "async created() {\n\n\t}", "async created() {\n\n\t}", "async processFile(hndl) {\n }", "async processFile(hndl) {\n }", "async onHandle({ cmd, data, node }, realm) {\n const handle = handlers[cmd];\n let callbackId = data && getOwnProp(data, CALLBACK_ID);\n if (callbackId) {\n data = data.data;\n }\n let res;\n try {\n res = handle === true\n ? sendCmd(cmd, data)\n : node::handle(data, realm || PAGE);\n if (isPromise(res)) {\n res = await res;\n }\n } catch (e) {\n callbackId = 'Error';\n res = e;\n }\n if (callbackId) {\n bridge.post('Callback', { id: callbackId, data: res }, realm);\n }\n }", "created() {\n this.onCreatedHandler();\n }", "handle() {}", "get handle() {\n\t\treturn this._h;\n\t}", "function async_io_normal(cb) {\n\n}", "static using(config, handler) {\n return Promise.using(Client.disposer(config), handler);\n }", "afterCreate(result) {}", "handle(command, responseHandler) {\n if (this._task) {\n const err = new Error(\"User launched a task while another one is still running. Forgot to use 'await' or '.then()'?\");\n err.stack += `\\nRunning task launched at: ${this._task.stack}`;\n this.closeWithError(err);\n // Don't return here, continue with returning the Promise that will then be rejected\n // because the context closed already. That way, users will receive an exception where\n // they called this method by mistake.\n }\n return new Promise((resolveTask, rejectTask) => {\n this._task = {\n stack: new Error().stack || \"Unknown call stack\",\n responseHandler,\n resolver: {\n resolve: arg => {\n this._stopTrackingTask();\n resolveTask(arg);\n },\n reject: err => {\n this._stopTrackingTask();\n rejectTask(err);\n }\n }\n };\n if (this._closingError) {\n // This client has been closed. Provide an error that describes this one as being caused\n // by `_closingError`, include stack traces for both.\n const err = new Error(`Client is closed because ${this._closingError.message}`); // Type 'Error' is not correctly defined, doesn't have 'code'.\n err.stack += `\\nClosing reason: ${this._closingError.stack}`;\n err.code = this._closingError.code !== undefined ? this._closingError.code : \"0\";\n this._passToHandler(err);\n return;\n }\n // Only track control socket timeout during the lifecycle of a task. This avoids timeouts on idle sockets,\n // the default socket behaviour which is not expected by most users.\n this.socket.setTimeout(this.timeout);\n if (command) {\n this.send(command);\n }\n });\n }", "function waitForInstance(handle) {\n return $mdComponentRegistry.when(handle).catch($log.error);\n }", "onCreatedHandler() {\n this.setSelection(this.qs_url);\n this.fetchData();\n }", "async init () {}", "onNew(handler) {\n return this.onEvent(handler, 'issue.new');\n }", "doOpen() {\n this.poll();\n }", "doOpen() {\n this.poll();\n }", "doOpen() {\n this.poll();\n }", "function waitForInstance(handle) {\n return $mdComponentRegistry.when(handle).catch($log.error);\n }", "async init() {}", "async init() {}", "doOpen() {\n this.poll();\n }", "doOpen() {\n this.poll();\n }", "function resolveWhen() {\n var dfd = pendings[handle];\n if ( dfd ) {\n dfd.forEach(function (promise) {\n promise.resolve(instance);\n });\n delete pendings[handle];\n }\n }", "function Handle() {}", "async created() {\n\t\tthis.redis = await new Redis();\n\t}", "doOpen() {\n this.poll();\n }", "async init() {\n\n }", "async asyncConstruct() {\n // In single process mode, we flush the redis on startup.\n this.getRedis().flushallAsync();\n }", "function resolveWhen() {\n var dfd = pendings[handle];\n if ( dfd ) {\n dfd.forEach(function (promise) {\n promise.resolve(instance);\n });\n delete pendings[handle];\n }\n }", "function asyncRouteHandler(handle){\n return async (request,response,next)=>{\n try {\n await handle(request,response);\n } catch (error) {\n next(error);\n }\n };\n}", "setAsync(){\n this.async = true;\n }", "createdCallback() {}", "function resolveWhen() {\n var dfd = pendings[handle];\n if (dfd) {\n dfd.forEach(function (promise) {\n promise.resolve(instance);\n });\n delete pendings[handle];\n }\n }", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "function NoOpHandle() {\n // MUST have no state as the object is effectively used as a\n // singleton.\n}", "AsyncCode()\n {\n\n }", "function subscribeToOnAsyncResponse() { \n _self.onAsyncResponse.subscribe(function (e, args) { \n if (!args || !args.itemDetail) {\n throw 'Slick.RowDetailView plugin requires the onAsyncResponse() to supply \"args.itemDetail\" property.'\n }\n\n // If we just want to load in a view directly we can use detailView property to do so\n if (args.detailView) {\n args.itemDetail._detailContent = args.detailView;\n } else {\n args.itemDetail._detailContent = _options.postTemplate(args.itemDetail);\n }\n\n args.itemDetail._detailViewLoaded = true;\n\n var idxParent = _dataView.getIdxById(args.itemDetail.id);\n _dataView.updateItem(args.itemDetail.id, args.itemDetail);\n\n // trigger an event once the post template is finished loading\n _self.onAsyncEndUpdate.notify({\n \"grid\": _grid,\n \"itemDetail\": args.itemDetail\n }, e, _self);\n });\n }", "async init () {\r\n debug.log('called init');\r\n return;\r\n }", "init (asyncId, type, triggersAsyncId, resource) {\n fs.writeSync(1, \"\\n\\t>>>>>> Hook init <<<<<<<<\"+asyncId+\"\\n\")\n }", "static async method(){}", "onDispose() {}", "set handle1 (_) { }", "function resolveWhen() {\n var dfd = pendings[handle];\n if ( dfd ) {\n dfd.resolve( instance );\n delete pendings[handle];\n }\n }", "function resolveWhen() {\n var dfd = pendings[handle];\n if ( dfd ) {\n dfd.resolve( instance );\n delete pendings[handle];\n }\n }", "addHandler(handler) {\n handlers.push(handler);\n }", "createHandler({ path, disableHealthCheck, onHealthCheck } = {}) {\n // We'll kick off the `willStart` right away, so hopefully it'll finish\n // before the first request comes in.\n const promiseWillStart = this.willStart();\n return async (req, res) => {\n this.graphqlPath = path || '/graphql';\n await promiseWillStart;\n if (typeof apollo_server_core_1.processFileUploads === 'function') {\n await this.handleFileUploads(req, res);\n }\n if (this.isHealthCheckRequest(req, disableHealthCheck)) {\n return this.handleHealthCheck({\n req,\n res,\n onHealthCheck,\n });\n }\n if (this.isPlaygroundRequest(req)) {\n return this.handleGraphqlRequestsWithPlayground({ req, res });\n }\n return this.handleGraphqlRequestsWithServer({ req, res });\n };\n }", "afterHandling() {}", "function resolveWhen(){var dfd=pendings[handle];if(dfd){dfd.forEach(function(promise){promise.resolve(instance);});delete pendings[handle];}}", "async onTick() {}", "destroy() {\n this._handlerDeferred.resolve();\n }", "_onEnd() {}", "handleCreated(event) {\n //If \"Create Issue and Upload Screenshot\" button has been clicked then we can use this flag to show file dialog after Issue has been crated\n if(this.fileUploadButtonClicked){\n this.showUploadFileDialog = true;\n }\n this.newIssueRecordId = event.detail.id;\n //Reset the form so we can enter more data for next issue; if needed\n this.handleResetFields();\n this.dispatchEvent(\n new ShowToastEvent({\n title: 'Success',\n message: '{0} was successfully created!',\n \"messageData\": [\n {\n url: '/'+ event.detail.id,\n label: 'Issue:: ' + event.detail.fields.Name.value\n }\n ],\n variant: 'success'\n })\n );\n }", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "function Handler() {}", "async function invokeHandler(event) {\n return (0, auto_delete_objects_handler_1.handler)(event);\n}", "startRequest(handle) {\n this.activeRequestCount++;\n }", "startRequest(handle) {\n this.activeRequestCount++;\n }", "function waitForInstance(handle){return $mdComponentRegistry.when(handle)[\"catch\"]($log.error);}", "async init () {\r\n return;\r\n }", "async onLoad() {}", "async begin() {\n return;\n }", "function handleLoadAsync() {\n\t\t\t\t\tlogWithPhase( \"handleLoad - Async\" );\n\t\t\t\t\t$scope.$apply(\n\t\t\t\t\t\tfunction() {\n\t\t\t\t\t\t\thandleLoadSync();\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}", "onInit() {\n return __awaiter(this, void 0, void 0, function* () {\n console.log(\"onInit CALLED\");\n class_exporter_1.logger.getLastBlock.then((val) => (this.mostRecentBlock = val));\n });\n }", "async initialize() {\n\n }", "async initialize() {\n\n }", "async method(){}", "async finalize() {\n await this.pgClient.end();\n }", "async function registerCommandHandler(newHandler) {\n const commandHandler = await E(newHandler).getCommandHandler();\n registeredHandlers.push(commandHandler);\n }", "promiseResolve (asyncId) {\n fs.writeSync(1, \"\\n\\tHook promiseResolve \"+asyncId+\"\\n\")\n }", "requestRemoteData(handler) {\n }", "initSocket(callback, idhandler, userhandler) {\n this.io.on('assignment', idhandler);\n this.io.on('questionAsked', callback);\n this.io.on('newUser', userhandler);\n }", "async init() {\n\n if (this.initPromise == null) {\n\n this.initPromise = new Promise((resolve, reject) => {\n AsyncStorage.getItem(this.id, (e, r) => {\n\n if (e) {\n reject(e);\n } else {\n this.obj = r ? JSON.parse(r) : this.obj;\n\n console.log(\"Initialized store '\" + this.id + \"': \", this.obj);\n\n this.initialized = true;\n resolve(this.obj);\n }\n });\n });\n }\n\n await this.initPromise\n }", "function handleConnection(client) {\n console.log(\"New Connection\");\n connections.push(client);\n client.on('close', function() {\n console.log(\"Connection closed\");\n var position = connections.indexOf(client);\n connections.splice(position, 1);\n })\n}", "[kSetHandle](handle) {\n const state = this[kInternalState];\n this[kHandle] = handle;\n if (handle !== undefined) {\n handle[owner_symbol] = this;\n state.state = new QuicSessionSharedState(handle.state);\n state.handshakeAckHistogram = new Histogram(handle.ack);\n state.handshakeContinuationHistogram = new Histogram(handle.rate);\n state.state.ocspEnabled = state.ocspHandler !== undefined;\n state.state.clientHelloEnabled = state.clientHelloHandler !== undefined;\n if (handle.qlogStream !== undefined) {\n this[kSetQLogStream](handle.qlogStream);\n handle.qlogStream = undefined;\n }\n } else {\n if (state.handshakeAckHistogram)\n state.handshakeAckHistogram[kDestroyHistogram]();\n if (state.handshakeContinuationHistogram)\n state.handshakeContinuationHistogram[kDestroyHistogram]();\n }\n }", "static _onListenDone () {\n }", "async end() { }", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}" ]
[ "0.6204729", "0.59472567", "0.5932039", "0.57917786", "0.5751853", "0.56844246", "0.56844246", "0.56794965", "0.56794965", "0.5599177", "0.5566484", "0.55219877", "0.54567814", "0.5456563", "0.5445722", "0.5427156", "0.5422927", "0.54227614", "0.54101485", "0.5377925", "0.5375756", "0.53756434", "0.53756434", "0.53756434", "0.53529793", "0.5326751", "0.5326751", "0.5319126", "0.5319126", "0.5313803", "0.53110975", "0.5286404", "0.5285956", "0.5274089", "0.5263706", "0.52633494", "0.5262596", "0.52594775", "0.5249711", "0.5247722", "0.5220646", "0.5220646", "0.5220646", "0.5220646", "0.5220646", "0.51895934", "0.51811534", "0.51794875", "0.5174259", "0.51695627", "0.51558816", "0.5145111", "0.51162404", "0.51081675", "0.51081675", "0.51080215", "0.5103693", "0.5080915", "0.5078759", "0.506183", "0.50532186", "0.50501984", "0.50470454", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5046097", "0.5045046", "0.50409305", "0.50409305", "0.5020924", "0.5020503", "0.50117975", "0.50072855", "0.50068545", "0.50020874", "0.50002664", "0.50002664", "0.49992955", "0.49833968", "0.49814302", "0.49795705", "0.49547443", "0.49541163", "0.49479786", "0.49417368", "0.493674", "0.49345574", "0.49333575", "0.49311435", "0.49311435", "0.49311435", "0.49311435" ]
0.55969024
10
Before a handle starts
function pre(uid) { currentUid = uid; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "function BeforeStart(){return}", "preStart() {\n }", "beforeHandling() {}", "onStart(side) {\n\t\t\t\tthis.add('-sidestart', side, 'move: Sticky Needles');\n\t\t\t}", "async before(ctx, args) {\n return true;\n }", "_before(uid) {\n const context = this._contexts.get(uid);\n if (context !== undefined) {\n this._enterContext(context);\n }\n }", "during_setup(e) {\n\t\tlet state = e.state;\n\t\tif (state === undefined) state = this.old_state;\n\t\tthis.enter(state);\n\t}", "beforeHandlers (event) {\n\n }", "beforeStep() {\n this.clearKeys();\n this.slimesChase();\n this.clearTempBuff();\n this.handleOnGoingSkills();\n this.updateAttackTimer();\n this.slimesAttack();\n }", "onStart(side) {\n\t\t\t\tthis.add('-sidestart', side, 'move: Stunning Spikes');\n\t\t\t}", "started() {\r\n\r\n\t}", "function before(object){\n if(object.before)\n object.before();\n }", "started () {}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "set handle1 (_) { }", "before (callback) {\n\t\tBoundAsync.series(this, [\n\t\t\tsuper.before,\t// do the usual test prep\n\t\t\tthis.changePath,\n\t\t], callback);\n\t}", "handleStart(inputData) {\n return this.startHandler(inputData);\n }", "before (callback) {\n\t\tBoundAsync.series(this, [\n\t\t\tsuper.before,\n\t\t\tthis.connectToMongo,\n\t\t\tthis.createVersionInfo\n\t\t], callback);\n\t}", "function preRunFunc() {\n\t\tonglets_ui.tabs();\n\t\tgetOngletsChannels();\n\t\tonInputFocus();\n\t\tonInputFocusOut();\n\t\tformSubmit();\n\t\tputButtonsEvents();\n\t}", "function handleStart(e) {\n if (e.kind === 'start') {\n if (startCallback) {\n startCallback(e);\n }\n return true;\n }\n\n return false;\n }", "before (callback) {\n\t\tBoundAsync.series(this, [\n\t\t\tCodeStreamAPITest.prototype.before.bind(this),\n\t\t\tthis.init\n\t\t], callback);\n\t}", "onLineStart() { }", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "onStart(side) {\n\t\t\t\tthis.add('-sidestart', side, 'move: Toxic Spikes');\n\t\t\t\tthis.effectData.layers = 1;\n\t\t\t}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "beforeClose() {\n\t\t}", "handleStart(e){\n this.setState({ready: e});\n }", "_autobegin(){\r\n if(!this._started)\r\n this.begin(false);\r\n }", "before (callback) {\n\t\tthis.init(callback);\n\t}", "before (callback) {\n\t\tthis.init(callback);\n\t}", "before (callback) {\n\t\tthis.init(callback);\n\t}", "before (callback) {\n\t\tthis.init(callback);\n\t}", "started() {\n\t}", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "before (callback) {\n\t\tsuper.before(error => {\n\t\t\tif (error) { return callback(error); }\n\t\t\tthis.data.streamId = ObjectId(); // substitute an ID for a non-existent stream\n\t\t\tcallback();\n\t\t});\n\t}", "function onBeforeEnter() {\n if (!Util.hasPreviousStates(noLoadingStates)) {\n Util.loading(zPostCreateModel);\n initPromise = init();\n } else {\n Util.freeze(false);\n }\n }", "_start_instruction() {\n\t\t\tthis.current_start_time = Date.now();\n\t\t\tthis._start_mouse_track();\n\t\t}", "onLoadStarted() {\n this.messageLoading = true;\n this.messageLoaded = false;\n }", "function handleStart() {\n startTimer(START_TIMER_LENGTH, marker.startAnimation);\n clearInterval(trackerInterval)\n setHidden(document.getElementsByClassName('before'), true);\n setHidden(document.getElementsByClassName('during'), false);\n sendAll(message(MessageType.START, START_TIMER_LENGTH))\n}", "before (callback) {\n\t\tBoundAsync.series(this, [\n\t\t\tsuper.before,\n\t\t\tthis.setPath\t\t\t// set the path for the request\n\t\t], callback);\n\t}", "started() { }", "started() {\n\n }", "started() {\n\n }", "started() {\n\n }", "[kSetHandle](handle) {\n const state = this[kInternalState];\n this[kHandle] = handle;\n if (handle !== undefined) {\n handle[owner_symbol] = this;\n state.state = new QuicSessionSharedState(handle.state);\n state.handshakeAckHistogram = new Histogram(handle.ack);\n state.handshakeContinuationHistogram = new Histogram(handle.rate);\n state.state.ocspEnabled = state.ocspHandler !== undefined;\n state.state.clientHelloEnabled = state.clientHelloHandler !== undefined;\n if (handle.qlogStream !== undefined) {\n this[kSetQLogStream](handle.qlogStream);\n handle.qlogStream = undefined;\n }\n } else {\n if (state.handshakeAckHistogram)\n state.handshakeAckHistogram[kDestroyHistogram]();\n if (state.handshakeContinuationHistogram)\n state.handshakeContinuationHistogram[kDestroyHistogram]();\n }\n }", "function start ( event, data ) {\n\n\t\t// Mark the handle as 'active' so it can be styled.\n\t\tif( data.handles.length === 1 ) {\n\t\t\tdata.handles[0].children().addClass(Classes[15]);\n\t\t}\n\n\t\t// A drag should never propagate up to the 'tap' event.\n\t\tevent.stopPropagation();\n\n\t\t// Attach the move event.\n\t\tattach ( actions.move, doc, move, {\n\t\t\tstart: event.calcPoint,\n\t\t\thandles: data.handles,\n\t\t\tpositions: [\n\t\t\t\t$Locations[0],\n\t\t\t\t$Locations[$Handles.length - 1]\n\t\t\t]\n\t\t});\n\n\t\t// Unbind all movement when the drag ends.\n\t\tattach ( actions.end, doc, end, null );\n\n\t\t// Text selection isn't an issue on touch devices,\n\t\t// so adding cursor styles can be skipped.\n\t\tif ( event.cursor ) {\n\n\t\t\t// Prevent the 'I' cursor and extend the range-drag cursor.\n\t\t\t$('body').css('cursor', $(event.target).css('cursor'));\n\n\t\t\t// Mark the target with a dragging state.\n\t\t\tif ( $Handles.length > 1 ) {\n\t\t\t\t$Target.addClass(Classes[12]);\n\t\t\t}\n\n\t\t\t// Prevent text selection when dragging the handles.\n\t\t\t$('body').on('selectstart' + namespace, false);\n\t\t}\n\t}", "onStartHeaders() {}", "function onBeforeEnter() {\n // console.log(\"$state.params :::\\n\", $state.params);\n if (!Util.hasPreviousStates(noLoadingStates)) {\n Util.loading(vm.Model);\n initPromise = init();\n //2개의 array Promise가 들어있는 Promise array 를 initPromise 변수에 대입\n } else {\n Util.freeze(false);\n }\n }", "before (callback) {\n\t\t// create an initial comment, then reply to that comment,\n\t\t// then we'll set the test to reply to that comment\n\t\tBoundAsync.series(this, [\n\t\t\tsuper.before,\n\t\t\tthis.createNRComment,\n\t\t\tthis.createReply,\n\t\t\tthis.setParentPost\n\t\t], callback);\n\t}", "function onInit() {}", "beforeStart_() {\n throw 'Cannot call beforeStart_() in abstract BookBinder';\n }", "function Handler() {\n\t\t\t\tthis.state = 0;\n\t\t\t}", "startRequest(handle) {\n this.activeRequestCount++;\n }", "startRequest(handle) {\n this.activeRequestCount++;\n }", "function onStart(data) {\n\t\tconsole.log(\"Player \" + data.name + \" has started the game\");\n\t\tdocument.getElementById('debugoutput').innerText = \"Player \" + data.name + \" has started the game\";\n\t\n\t\t// Set client \"running\" state here?\n}", "function handler() {\n fired = true;\n }", "function preExecute(commandId, event) {}", "function preExecute(commandId, event) {}", "onStart() {\n log('starting the core...');\n history.start({pushStart: false});\n\n /**\n * App has started.\n *\n * @event App#start\n */\n this.channel.trigger('start');\n\n // Remove loading class\n $('.-loading').removeClass('-loading');\n }", "function eltdOnWindowLoadHeaderBehaviour() {\n }", "async beforeStart(context) {\n const { store } = context;\n\n if (!store) return;\n\n if (store && context.isClient && window.__DATA__ && window.__DATA__.state) {\n const { state } = window.__DATA__;\n store.replaceState(state);\n }\n\n if (!context.app._isMounted) {\n // onHttpRequest\n await this.resolveOnHttpRequest(context);\n }\n }", "started () {\n\n }", "started () {\n\n }", "started () {\n\n }", "function Handler() {\n\t\t\tthis.state = 0;\n\t\t}", "before (asyncId) {\n fs.writeSync(1, \"\\n\\tHook before \"+asyncId+\"\\n\")\n }", "before (callback) {\n\t\tthis.testBegins = Date.now();\n\t\tthis.init(callback);\n\t}", "beforeInit() {\r\n return true;\r\n }" ]
[ "0.6353478", "0.6353478", "0.6353478", "0.6353478", "0.6353478", "0.6353478", "0.6353478", "0.6353478", "0.5956316", "0.59344554", "0.5929525", "0.59088933", "0.5886011", "0.5876046", "0.5837104", "0.57874477", "0.56936026", "0.5689687", "0.5654993", "0.56520075", "0.5633241", "0.5633241", "0.5633241", "0.5633241", "0.5633241", "0.5633241", "0.5633241", "0.5633241", "0.56178725", "0.56136304", "0.56074744", "0.55911654", "0.55575466", "0.5540451", "0.5534691", "0.5512079", "0.55117327", "0.55117327", "0.55117327", "0.55117327", "0.55117327", "0.55117327", "0.55117327", "0.54888624", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.5485356", "0.54821813", "0.54800224", "0.5473956", "0.5466692", "0.5466692", "0.5466692", "0.5466692", "0.54598254", "0.54570657", "0.54570657", "0.54570657", "0.54570657", "0.54570657", "0.5454081", "0.5449388", "0.5438855", "0.5426993", "0.54091686", "0.5405028", "0.5400017", "0.5394059", "0.5394059", "0.5394059", "0.53902566", "0.5371507", "0.53622353", "0.53432465", "0.53337514", "0.5332194", "0.53171676", "0.52980316", "0.52951556", "0.52951556", "0.5294333", "0.52821445", "0.52792716", "0.52792716", "0.52741426", "0.5271785", "0.52712286", "0.5269908", "0.5269908", "0.5269908", "0.5265678", "0.52637696", "0.52535534", "0.52460665" ]
0.0
-1
After a handle ends
function post() { currentUid = null; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_onEnd() {}", "handleFinish(useful) {\n recordFinish(this.state.currentGuide.id, useful);\n closeGuide();\n }", "async end() { }", "function handleFinished() {\n resolve(Buffer.concat(_this.buffers));\n cleanup();\n }", "function HandleEnd()\n{\n this.device.close(); // close the device\n}", "async end() {\n return;\n }", "function handleFinish(event) {\n cleanup(null, responseData)\n }", "function handleFinish(_event) {\n cleanup(null, responseData)\n }", "afterHandling() {}", "function handleFinish(values) {\n job.current = getJob(values, job.current, writeMessage);\n setBusy(job.current.pendingTime);\n }", "function doneClosing()\n\t{\n\t\tthat.terminate();\n\t}", "setEndHandle(handle) {\n this.end.handle = handle\n }", "onEnd() {\n\t\tthis.debug('onEnd');\n\t}", "end() { }", "onend() {\n if (this.done)\n return;\n this.done = true;\n this.parser = null;\n this.handleCallback(null);\n }", "end(event) {\n\n }", "async onEnd() {\n\t\tawait this.say('Exiting...');\n\t}", "get end() {}", "doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }", "onMessageEnd() { }", "end() {\n this._client.release();\n }", "end() {\n this.medals();\n this.endMessage();\n this.cleanUp();\n this.gc();\n }", "handleEnd(inputData, isCancel) {\n return this.endHandler(inputData, isCancel);\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "endRequest(handle) {\n this.activeRequestCount--;\n this._issueNewRequests();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function endEvent(){}", "function onclose() {\r\n dest.removeListener('finish', onfinish);\r\n unpipe();\r\n }", "end() {\n }", "end() {\n }", "end() {\n\t\tif (this.process)\n\t\t\tthis.process.kill()\n\t}", "end(){\n this.request({\"component\":this.component,\"method\":\"end\",\"args\":[\"\"]})\n this.running = false\n }", "async onFinished() {}", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function finished(err){\n }", "end(_endTime) { }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onFinish() {\n\t\tclbk();\n\t}", "onClosed() {\r\n // Stub\r\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }", "function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }" ]
[ "0.68474317", "0.6664979", "0.6641499", "0.65521944", "0.6507137", "0.6491127", "0.63348365", "0.63143176", "0.62901276", "0.6277134", "0.6264915", "0.6178254", "0.6159167", "0.6144463", "0.61310816", "0.61133814", "0.6111553", "0.60959893", "0.6052513", "0.6010353", "0.5993265", "0.59898597", "0.59770864", "0.5953009", "0.59500784", "0.59310985", "0.59260553", "0.59156877", "0.59093493", "0.58956254", "0.5891676", "0.5891676", "0.5874503", "0.58540213", "0.58534867", "0.58444864", "0.58444864", "0.5837871", "0.58327246", "0.58318996", "0.58318996", "0.58318996", "0.5802545", "0.5802171", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592", "0.5782592" ]
0.0
-1
When a handle is destroyed
function destroy(uid) { if (hasContext(uid)) { contexts.delete(uid); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "destroy() {\n if (!this._destroyCallback) {\n throw new Error('Destroying an inactive handle');\n }\n\n // We give the handle rather than set it as the this, because setting it as the this is @#$#@\n // confusing.\n this._destroyCallback(this, this._userData);\n\n // Releasing these will allow them to be gc'ed even if the caller keeps them\n this._destroyCallback = undefined;\n this._userData = undefined;\n }", "onDestroy() {}", "destroy() {\n this._handlerDeferred.resolve();\n }", "onDestroy(e) {\n\n }", "function handleDestroy() {\n win.off(\"focus\", handleFocus);\n }", "willDestroy() {}", "willDestroy() {}", "destroy() {\n // what do we do here?\n }", "destroy() {\r\n this.off();\r\n }", "willDestroy() { }", "function handleDestroy() {\n win.off(\"blur\", handleBlur);\n }", "disposeInternal() {\n\t\tthis.eventHandles_ = null;\n\t}", "_destroy() {\n if (this._destroyed) {\n return;\n }\n this._destroyed = true;\n this.emit('end');\n }", "_destroy() {\n if (this._destroyed) {\n return;\n }\n this._destroyed = true;\n this.emit('end');\n }", "_destroy() {\n if (this._destroyed) {\n return;\n }\n this._destroyed = true;\n this.emit('end');\n }", "function destroy () {\n\t\t// TODO\n\t}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "doDestroy() {}", "destroy () {}", "_destroy() {}", "_destroy() {\r\n\t\tif (this._interval) clearInterval(this._interval)\r\n\t\tthis._internalStream.removeAllListeners()\r\n\t\tthis._internalStream = null\r\n\t\tthis._destroyed = true\r\n\t}", "destroy() { }", "destroy() { }", "destroy() { }", "function destroy(){\n\t\t// TODO\n\t}", "function destroy() {\n\t\tif ( error ) {\n\t\t\tself.emit( 'error', error );\n\t\t}\n\t\tself.emit( 'close' );\n\t}", "function onStreamError(streamHandle, error) {\n streamHandle[owner_symbol].destroy(error);\n}", "handleClose() {\n this.clearContainer();\n }", "destroy() {\n this.off();\n super.destroy();\n }", "ondestruct() {\n\t\tsuper.ondestruct();\n\t\tthis._unobserve && this._unobserve();\n\t}", "function destroy(){}", "destroy() {\r\n this.native.destroy();\r\n }", "onDispose() {}", "destroy() {\n //TODO this.\n }", "destroy() {\n this._end();\n }", "onDestroy() {\n this.unlisten()\n }", "destroy () {\n this.emit('destroyed', [true]);\n super.destroy();\n }", "destroy () {\n this.emit('destroyed', [true]);\n super.destroy();\n }", "[PRIVATE.$onDestroy] () {\n this[PRIVATE.callSymbols](PRIVATE.onDestroySymbols, []);\n }", "destroy() {\n }", "doDestroy() {\n this.trigger('destroy');\n this.removeAllListeners();\n super.doDestroy();\n }", "destroy() {\n\t\t/**\n\t\t * @event Resource.destroy\n\t\t * Called whenever the resource is about to be destroyed\n\t\t */\n\t\tthis.emit(\"destroy\");\n\t\tthis.removeAllListeners();\n\t}", "destroyed(){\n console.log('Destroyed');\n }", "didDestroy() {\n }", "dispose() {}", "dispose() {}", "dispose() {}", "dispose() {}", "dispose() {}", "onDestroy() {\n STATE.wheats--;\n }", "destroy() {\n\t\tthis._stopErrorHandling();\n\n\t\tthis._listeners = {};\n\t}", "_onClose() {\n this._socket = null;\n this._osk = null;\n this._connectedAt = 0;\n }", "willDestroy() {\n }", "ngOnDestroy() {\n this._destroyed = true;\n this._completeExit();\n }", "destroy() {\n if (this.destroyed) {\n return\n }\n\n this.markerDestroyDisposable?.dispose?.()\n this.destroyed = true\n this.emitter.emit(\"did-destroy\")\n this.emitter.dispose()\n }", "function onunload() {\n channel.destroy();\n channel = null;\n remoteControl.dispose();\n}", "destroy() {\n this.$close().then(e => {\n this.$i && window.clearInterval(this.$i);\n });\n }", "destroy () {\n this.type = null;\n this.target = null;\n }", "destroy() {\n this._pipe && this._pipe.destroy();\n this._inbound && this._inbound.destroy();\n this._outbound && this._outbound.destroy();\n this._pipe = null;\n this._inbound = null;\n this._outbound = null;\n this._presets = null;\n this._context = null;\n this._proxyRequest = null;\n }", "destroy() {\n this._clearListeners();\n this._pending = [];\n this._target = undefined;\n }", "async disconnectedCallback() {\n // unregister events\n this._button.removeEventListener(\"click\", this._doSomethingHandler);\n\n // free up pointers\n this._button = null;\n this._header = null;\n this._content = null;\n this._doSomethingHandler = null;\n }", "destroy() {\n\n // skip if already destroyed\n if (this._state == Actor.DESTROYED) return;\n\n // queue destroy event\n var self = this;\n Actor._destroy_trigger_queue.in(() => {\n self._state = Actor.DESTROYED;\n self.trigger('destroy', self);\n });\n }", "off() {\n this.ref.off();\n }", "function destroy(){\r\n }", "function destroy(){\r\n }", "function cleanup() {\n res.removeListener('finish', makePoint);\n res.removeListener('error', cleanup);\n res.removeListener('close', cleanup);\n }", "destroy() {\n this.notify('destroy', {});\n super.destroy();\n }", "destroy() {\n this.notify('destroy', {});\n super.destroy();\n }", "destroy() {\n this.notify('destroy', {});\n super.destroy();\n }", "destroy() {\n this.instance.disconnect();\n return;\n }", "unloadTrack () {\n if (this.howlHandler) {\n this.howlHandler.unload();\n }\n }", "destroy() {\n if (!this.destroyed) {\n this.onResize.removeAll();\n this.onResize = null;\n this.onUpdate.removeAll();\n this.onUpdate = null;\n this.destroyed = true;\n this.dispose();\n }\n }", "_onClosing() {\n this._watcher.stop();\n this.emit(\"closing\");\n }", "$onDestroy() {\n dispose(this.keyHandler_);\n\n this.element_ = null;\n }", "destroy() {\n this.emit('destroy');\n this.removeAllListeners();\n }", "destroy() {\n this.state = {\n code: NetworkingStatusCode.Closed,\n };\n }", "off() {\n this.ref.off();\n }", "function onDestroy(callback) {\n\t // Use this to get early callback for server render\n\t return _baseStreams2.default.onValue(this.devStreams.onDestroyStream, _lib2.default.baconTryD(callback));\n\t}", "onDestroy() {\n this._userTracker.stopTracking();\n if(this._currentGuide) {\n this._currentGuide.finish();\n this._currentGuide = null;\n }\n this._state = MAP_STATE_DESTROYED;\n }", "destroy() {\n this.dead = true;\n }", "$onDestroy() {\n this.tlc_.unlisten(TimelineEventType.SHOW, this.update_, false, this);\n this.scope_ = null;\n this.element_ = null;\n }", "destroy() {\n CommonUtils.callback('onDelete', this);\n }", "destructResources() {\n this.peerComm.removeEventListener(\n PeerCommunicationConstants.PEER_DATA,\n this.onPeerDataReceived.bind(this)\n );\n this.receivedBuffer = null;\n }", "destroy() {\n this.removeListeners();\n window.removeEventListener(GoogEventType.BEFOREUNLOAD, this.onClose.bind(this), true);\n this.scope = null;\n }", "$onDestroy() {\n this.$unwatchData();\n this.$unwatchUser();\n\n if (this.data && this.data.$destroy) {\n this.data.$destroy();\n }\n\n if (this.$disableRefresh) {\n this.$timeout.cancel(this.$disableRefresh);\n this.$disableRefresh = undefined;\n }\n }", "ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }", "destroy() {\n window.removeEventListener('resize', this._updateBoundingRect);\n this.$el.removeEventListener('touchstart', this._handleTouchStart);\n this.$el.removeEventListener('touchmove', this._handleTouchMove);\n this.$el.removeEventListener('touchend', this._handleTouchEnd);\n this.$el.removeEventListener('touchcancel', this._handleTouchEnd);\n // delete pointers\n this.$el = null;\n this.listeners = null;\n }", "onUnload() {\n\t\tthis.$container.off(this.namespace);\n\t}", "function HandleEnd()\n{\n this.device.close(); // close the device\n}", "destroy() {\n this.context\n .trigger(`${scopeName}${this.constructor.name}.destroy`)\n .removeClass(scopeName + this.constructor.name)\n .removeData(scopeName + this.constructor.name)\n .removeAttr(`data-${scopeName}${this.constructor.name}`);\n }", "function onUnload() {\r\n \tcontrols.log('onUnload');\r\n stop();\r\n }" ]
[ "0.8037547", "0.70259666", "0.6890695", "0.67938477", "0.6737528", "0.661633", "0.661633", "0.6615557", "0.6578729", "0.65628374", "0.6530463", "0.652776", "0.6527581", "0.6527581", "0.6527581", "0.64884436", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.6485455", "0.64759445", "0.64750314", "0.6474231", "0.6459033", "0.64515835", "0.64515835", "0.64515835", "0.64462996", "0.64433014", "0.6442131", "0.6437099", "0.6412567", "0.6397089", "0.6396711", "0.6376457", "0.6370604", "0.6365396", "0.6354076", "0.63467056", "0.6311334", "0.6311334", "0.6281069", "0.6269763", "0.62694407", "0.62597466", "0.6256589", "0.62511045", "0.61996573", "0.61996573", "0.61996573", "0.61996573", "0.61996573", "0.6177505", "0.6173249", "0.61659646", "0.61592734", "0.61575586", "0.61547863", "0.6151372", "0.6144833", "0.61416805", "0.6133887", "0.61250293", "0.61223286", "0.6119567", "0.61184114", "0.6111418", "0.6111418", "0.6111172", "0.6109654", "0.6109654", "0.6109654", "0.610353", "0.609794", "0.60838765", "0.60796124", "0.60787576", "0.607444", "0.6073936", "0.60735935", "0.6070198", "0.606497", "0.6056035", "0.6052471", "0.6045075", "0.6038077", "0.60332006", "0.6019778", "0.6017631", "0.601086", "0.60091287", "0.6007318", "0.6006366", "0.60059005" ]
0.0
-1
const BASE_COLOR="rgb(52, 73, 94)"; const OTHER_COLOR="7f8c8d";
function handleClick(){ title.classList.toggle(CLICK_CLASS); /*const hasClass=title.classList.contains(CLICK_CLASS); if(hasClass){ title.classList.remove(CLICK_CLASS); } else{ title.classList.add(CLICK_CLASS); }*/ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _named(str) {\r\n var c = __WEBPACK_IMPORTED_MODULE_1__colorValues__[\"COLOR_VALUES\"][str.toLowerCase()];\r\n if (c) {\r\n return {\r\n r: c[0],\r\n g: c[1],\r\n b: c[2],\r\n a: MAX_COLOR_ALPHA\r\n };\r\n }\r\n}", "function color (i){\n\tif (i===0){\n\t\treturn \"rgb(1, 95, 102)\";\n\t} else if (i===1) {\n\t\treturn \"rgb(45, 241, 255)\";\n\t} else if (i===2) {\n\t\treturn \"rgb(34, 86, 150)\";\n\t} else if (i===3) {\n\t\treturn \"rgb(0, 132, 88)\";\n\t} else if (i===4) {\n\t\treturn \"rgb(56, 255, 188)\";\n\t} else if (i===5) {\n\t\treturn \"rgb(77, 168, 137)\";\n\t} else {\n\t\treturn \"rgb(1, 95, 102)\";\n\t}\n}", "function rgb(r, g, b){\n return `rbg(${r}, ${g}, ${b})`\n}", "function colorRGB(){\n var coolor = \"(\"+generarNumero(255)+\",\" + generarNumero(255) + \",\" + generarNumero(255) +\")\";\n return \"rgb\" + coolor;\n }", "function generateColor(){\r\n const color=\"rgb(\"+genColorVal()+\", \"+genColorVal()+\", \"+genColorVal()+\")\";\r\n return color;\r\n }", "function getTheColor(red, green, blue) {\r\n var theColor = \"\";\r\n theColor = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\r\n return (theColor);\r\n }", "function seeColor(str){\n if(str.substring(0, 3) === 'red'){\n return 'red';\n }\n else if(str.substring(0,4) === 'blue'){\n return 'blue';\n }\n else\n return '';\n}", "function getColour(){\n return 'rgb(' + _.random(0, 255) + ',' + _.random(0, 255) + ',' + _.random(0, 255) + ')';\n }", "function getColour(){\n return 'rgb(' + _.random(0, 255) + ',' + _.random(0, 255) + ',' + _.random(0, 255) + ')';\n }", "function color(interest1) { //interest1 is 0-1 scaled relative value of first word in pair\n if (interest1 === undefined || interest1 === GREYVALUE) {\n return GREYCOLOR;\n }\n let red = 255 * interest1;\n let blue = 255 * (1 - interest1);\n return `rgb(${red}, 25, ${blue})` //backtick means string, ${} interpolates rgb values \n}", "function rgb(r, g, b)\n{ return 'rgb('+clamp(Math.round(r),0,255)+', '+clamp(Math.round(g),0,255)+', '+clamp(Math.round(b),0,255)+')';}", "function getColor(str){\n\treturn partyColors[str];\n}", "function colorConverter (string) {\n \n// todo: study the Object.freeze \n const colorCodes = Object.freeze({\n \"blue\":\"rgb(40, 116, 237)\",\n \"brown\":\"rgb(255, 102, 102)\",\n \"brownish-red\":\"rgb(196, 136, 124)\",\n \"coral\":\"rgb(255, 102, 102)\",\n \"cream\":\"rgb(240, 237, 218)\",\n \"creamyWhite\":\"rgb(255, 253, 230)\",\n \"darkBlue\":\"rgb(0, 0, 153)\",\n \"darkPink\":\"rgb(255, 102, 153)\",\n \"darkPurple\":\"rgb(103, 0, 103)\",\n \"deepGreen\":\"rgb(0, 102, 0)\",\n \"deepPink\":\"rgb(212, 30, 90)\",\n \"emeraldGreen\":\"rgb(38, 115, 38)\",\n \"gold\":\"rgb(217, 195, 33)\",//stopped here, finish adding colors\n \"green\":\"rgb(50, 133, 59)\",\n \"greenish-white\":\"rgb(217, 242, 217)\",\n \"greenish-yellow\":\"rgb(230, 255, 179)\",\n \"indigoBlue\":\"rgb(74, 51, 222)\",\n \"lavender\":\"rgb(150, 153, 255)\",\n \"lightBlue\":\"rgb(179, 218, 255)\",\n \"lightGreen\":\"rgb(204, 255, 204)\",\n \"lightPink\":\"rgb(255, 204, 225)\",\n \"lilac\":\"rgb(230, 204, 255)\",\n \"magenta\":\"rgb(255, 0, 255)\",\n \"peach\":\"rgb(253, 217, 181)\",\n \"pink\":\"rgb(255, 102, 153)\",\n \"pinkish-lavender\":\"rgb(242, 211, 227)\",\n// \"purple and yellow\":\"rgba(0,100,0,0.75)\",//todo: need code instead of dark green\n \"purpleRed\":\"rgb(192, 0, 64)\",\n \"purplish-pink\":\"rgb(192, 96, 166)\",\n \"rose\":\"rgb(255, 153, 204)\",\n \"violet\":\"rgb(230, 130, 255)\",\n \"whiteAndPurple\":\"rgb(240, 240, 240)\",//todo: need code instead of dark green\n \"yellowish-green\":\"rgb(198, 210, 98)\", \n \"yellowCenter\":\"rgb(200, 200, 0)\"\n });\n \n //remove i_ (used to make inconspicuous) that might be in a name\n \n\t//if an rgb code is sent, return the color name\n if (string.slice(0,3) === \"rgb\") {\n for(let key in colorCodes) {\n if(colorCodes[key] === string) {\n return key;\n }\n }\n }\n //if a color name that needs to be converted is sent, return rgb\n else if (string in (colorCodes)) {\n return colorCodes[string];\n }\n //otherwise return a color name in camel case when needed\n //this is used when the color isn't listed in colorCodes, but\n //its name is valid as is or if converted to camel case notation\n else {\n return camelCase(string);\n }\n \n}", "function rgb(r, g, b) \n{ \n\treturn 'rgb('+clamp(Math.round(r),0,255)+', '+clamp(Math.round(g),0,255)+', '+clamp(Math.round(b),0,255)+')';\n}", "function rgb(r, g, b) \n{ \n\treturn 'rgb('+clamp(Math.round(r),0,255)+', '+clamp(Math.round(g),0,255)+', '+clamp(Math.round(b),0,255)+')';\n}", "function rgb(r, g, b) {\r\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\r\n}", "function rgb(){\n\tvar string = \"rgb(\";\n\tstring += randomInteger(0,255) + \", \";\n\tstring += randomInteger(0,255) + \", \";\n\tstring += randomInteger(0,255) + \")\";\n\treturn string;\n}", "function rgbOrange() {\n var val1 = randRGB();\n var val2 = randRGB();\n var val3 = randRGB();\n return \"rgb(\" + (val1 + 20) + \", \" + val1 / 2.3 + \", \" + 0 + \")\";\n}", "function getColor(cName) {\n\t\tswitch(cName){\n\t\t\tcase \"light_yellow\":\tc = \"#E6FB04\";\n\t\t\tcase \"neon_red\": \t\tc = \"#FF0000\";\n\t\t\tcase \"neon_purple\": \tc = \"#7CFC00\";\n\t\t\tcase \"neon_pink\":\t\tc = \"#FF00CC\";\n\t\t\tcase \"neon_yellow\":\tc = \"#FFFF00\";\n\t\t\tcase \"neon_green\": c = \"#00FF66\";\n\t\t\tcase \"light_blue\": c = \"#00FFFF\";\n\t\t\tcase \"dark_blue\": c = \"#0033FF\";\n\t\t\tdefault: \t\t\t\t\tc = '#FAEBD7';\n\t\t}\n \treturn c;\n\t}", "function rgb(r, g, b) {\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function rgb(r, g, b) {\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function rgb(r, g, b) {\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function rgb(r, g, b) {\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function determine_color(num) {\n if (num === 0) {\n return \"beige\";\n } else if (num === 2) {\n return \"beige\";\n } else if (num === 4) {\n return \"yellow\";\n } else if (num === 8) {\n return \"#f4b042\";\n } else if (num === 16) {\n return \"#f48641\";\n } else if (num === 32) {\n return \"#f45241\";\n } else if (num === 64) {\n return \"#ff1800\";\n } else if (num === 128) {\n return \"#ff00b2\";\n } else {\n return \"black\";\n }\n}", "function colourNameToRGB(colourName) {\n\n}", "function randomColor(){\n return `rgb(${randomInt(0,256)},${randomInt(0,256)},${randomInt(0,256)})`;\n}", "function rgb(r, g, b) {\n \n}", "static get INACTIVE_COLOR() { return [128, 128, 128, 100]; }", "function rgb(r, g, b) { \n\treturn 'rgb('+clamp(Math.round(r),0,255)+', '+clamp(Math.round(g),0,255)+', '+clamp(Math.round(b),0,255)+')';\n}", "function rgb(r, g, b){\n if (r <=0){r = 0}\n if (g <=0){g = 0}\n if (b <=0){b = 0}\n if (r > 255){r = 255}\n if (g > 255){g = 255}\n if (b > 255){b = 255}\n r = r.toString(16).toUpperCase().padStart(2,\"0\")\n g = g.toString(16).toUpperCase().padStart(2,\"0\")\n b = b.toString(16).toUpperCase().padStart(2,\"0\")\n \n return `${r}${g}${b}`\n }", "function rgbBlue() {\n var val1 = randRGB();\n var val2 = randRGB();\n var val3 = randRGB();\n return \"rgb(\" + 30 + \", \" + val1 + \", \" + val1 + \")\";\n}", "set ETC_RGB4(value) {}", "function rgbGreen() {\n var val1 = randRGB();\n var val2 = randRGB();\n var val3 = randRGB();\n return \"rgb(\" + val1 + \", \" + val1 + \", \" + 0 + \")\";\n}", "function _named(str) {\n var c = COLOR_VALUES[str.toLowerCase()];\n if (c) {\n return {\n r: c[0],\n g: c[1],\n b: c[2],\n a: MAX_COLOR_ALPHA\n };\n }\n}", "function RGBColor(color_string)\n{\n this.ok = false;\n\n // strip any leading #\n if (color_string.charAt(0) == '#') { // remove # if any\n color_string = color_string.substr(1,6);\n }\n\n color_string = color_string.replace(/ /g,'');\n color_string = color_string.toLowerCase();\n\n // before getting into regexps, try simple matches\n // and overwrite the input\n var simple_colors = {\n aliceblue: 'f0f8ff',\n antiquewhite: 'faebd7',\n aqua: '00ffff',\n aquamarine: '7fffd4',\n azure: 'f0ffff',\n beige: 'f5f5dc',\n bisque: 'ffe4c4',\n black: '000000',\n blanchedalmond: 'ffebcd',\n blue: '0000ff',\n blueviolet: '8a2be2',\n brown: 'a52a2a',\n burlywood: 'deb887',\n cadetblue: '5f9ea0',\n chartreuse: '7fff00',\n chocolate: 'd2691e',\n coral: 'ff7f50',\n cornflowerblue: '6495ed',\n cornsilk: 'fff8dc',\n crimson: 'dc143c',\n cyan: '00ffff',\n darkblue: '00008b',\n darkcyan: '008b8b',\n darkgoldenrod: 'b8860b',\n darkgray: 'a9a9a9',\n darkgreen: '006400',\n darkkhaki: 'bdb76b',\n darkmagenta: '8b008b',\n darkolivegreen: '556b2f',\n darkorange: 'ff8c00',\n darkorchid: '9932cc',\n darkred: '8b0000',\n darksalmon: 'e9967a',\n darkseagreen: '8fbc8f',\n darkslateblue: '483d8b',\n darkslategray: '2f4f4f',\n darkturquoise: '00ced1',\n darkviolet: '9400d3',\n deeppink: 'ff1493',\n deepskyblue: '00bfff',\n dimgray: '696969',\n dodgerblue: '1e90ff',\n feldspar: 'd19275',\n firebrick: 'b22222',\n floralwhite: 'fffaf0',\n forestgreen: '228b22',\n fuchsia: 'ff00ff',\n gainsboro: 'dcdcdc',\n ghostwhite: 'f8f8ff',\n gold: 'ffd700',\n goldenrod: 'daa520',\n gray: '808080',\n green: '008000',\n greenyellow: 'adff2f',\n honeydew: 'f0fff0',\n hotpink: 'ff69b4',\n indianred : 'cd5c5c',\n indigo : '4b0082',\n ivory: 'fffff0',\n khaki: 'f0e68c',\n lavender: 'e6e6fa',\n lavenderblush: 'fff0f5',\n lawngreen: '7cfc00',\n lemonchiffon: 'fffacd',\n lightblue: 'add8e6',\n lightcoral: 'f08080',\n lightcyan: 'e0ffff',\n lightgoldenrodyellow: 'fafad2',\n lightgrey: 'd3d3d3',\n lightgreen: '90ee90',\n lightpink: 'ffb6c1',\n lightsalmon: 'ffa07a',\n lightseagreen: '20b2aa',\n lightskyblue: '87cefa',\n lightslateblue: '8470ff',\n lightslategray: '778899',\n lightsteelblue: 'b0c4de',\n lightyellow: 'ffffe0',\n lime: '00ff00',\n limegreen: '32cd32',\n linen: 'faf0e6',\n magenta: 'ff00ff',\n maroon: '800000',\n mediumaquamarine: '66cdaa',\n mediumblue: '0000cd',\n mediumorchid: 'ba55d3',\n mediumpurple: '9370d8',\n mediumseagreen: '3cb371',\n mediumslateblue: '7b68ee',\n mediumspringgreen: '00fa9a',\n mediumturquoise: '48d1cc',\n mediumvioletred: 'c71585',\n midnightblue: '191970',\n mintcream: 'f5fffa',\n mistyrose: 'ffe4e1',\n moccasin: 'ffe4b5',\n navajowhite: 'ffdead',\n navy: '000080',\n oldlace: 'fdf5e6',\n olive: '808000',\n olivedrab: '6b8e23',\n orange: 'ffa500',\n orangered: 'ff4500',\n orchid: 'da70d6',\n palegoldenrod: 'eee8aa',\n palegreen: '98fb98',\n paleturquoise: 'afeeee',\n palevioletred: 'd87093',\n papayawhip: 'ffefd5',\n peachpuff: 'ffdab9',\n peru: 'cd853f',\n pink: 'ffc0cb',\n plum: 'dda0dd',\n powderblue: 'b0e0e6',\n purple: '800080',\n red: 'ff0000',\n rosybrown: 'bc8f8f',\n royalblue: '4169e1',\n saddlebrown: '8b4513',\n salmon: 'fa8072',\n sandybrown: 'f4a460',\n seagreen: '2e8b57',\n seashell: 'fff5ee',\n sienna: 'a0522d',\n silver: 'c0c0c0',\n skyblue: '87ceeb',\n slateblue: '6a5acd',\n slategray: '708090',\n snow: 'fffafa',\n springgreen: '00ff7f',\n steelblue: '4682b4',\n tan: 'd2b48c',\n teal: '008080',\n thistle: 'd8bfd8',\n tomato: 'ff6347',\n turquoise: '40e0d0',\n violet: 'ee82ee',\n violetred: 'd02090',\n wheat: 'f5deb3',\n white: 'ffffff',\n whitesmoke: 'f5f5f5',\n yellow: 'ffff00',\n yellowgreen: '9acd32'\n };\n for (var key in simple_colors) {\n if (color_string == key) {\n color_string = simple_colors[key];\n }\n }\n // emd of simple type-in colors\n\n // array of color definition objects\n var color_defs = [\n {\n re: /^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,\n example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],\n process: function (bits){\n return [\n parseInt(bits[1]),\n parseInt(bits[2]),\n parseInt(bits[3])\n ];\n }\n },\n {\n re: /^(\\w{2})(\\w{2})(\\w{2})$/,\n example: ['#00ff00', '336699'],\n process: function (bits){\n return [\n parseInt(bits[1], 16),\n parseInt(bits[2], 16),\n parseInt(bits[3], 16)\n ];\n }\n },\n {\n re: /^(\\w{1})(\\w{1})(\\w{1})$/,\n example: ['#fb0', 'f0f'],\n process: function (bits){\n return [\n parseInt(bits[1] + bits[1], 16),\n parseInt(bits[2] + bits[2], 16),\n parseInt(bits[3] + bits[3], 16)\n ];\n }\n }\n ];\n\n // search through the definitions to find a match\n for (var i = 0; i < color_defs.length; i++) {\n var re = color_defs[i].re;\n var processor = color_defs[i].process;\n var bits = re.exec(color_string);\n if (bits) {\n channels = processor(bits);\n this.r = channels[0];\n this.g = channels[1];\n this.b = channels[2];\n this.ok = true;\n }\n\n }\n\n // validate/cleanup values\n this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);\n this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);\n this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);\n\n // some getters\n this.toRGB = function () {\n return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';\n }\n this.toHex = function () {\n var r = this.r.toString(16);\n var g = this.g.toString(16);\n var b = this.b.toString(16);\n if (r.length == 1) r = '0' + r;\n if (g.length == 1) g = '0' + g;\n if (b.length == 1) b = '0' + b;\n return r + g + b;\n }\n\n // help\n this.getHelpXML = function () {\n\n var examples = new Array();\n // add regexps\n for (var i = 0; i < color_defs.length; i++) {\n var example = color_defs[i].example;\n for (var j = 0; j < example.length; j++) {\n examples[examples.length] = example[j];\n }\n }\n // add type-in colors\n for (var sc in simple_colors) {\n examples[examples.length] = sc;\n }\n\n var xml = document.createElement('ul');\n xml.setAttribute('id', 'rgbcolor-examples');\n for (var i = 0; i < examples.length; i++) {\n try {\n var list_item = document.createElement('li');\n var list_color = new RGBColor(examples[i]);\n var example_div = document.createElement('div');\n example_div.style.cssText =\n 'margin: 3px; '\n + 'border: 1px solid black; '\n + 'background:' + list_color.toHex() + '; '\n + 'color:' + list_color.toHex()\n ;\n example_div.appendChild(document.createTextNode('test'));\n var list_item_value = document.createTextNode(\n ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()\n );\n list_item.appendChild(example_div);\n list_item.appendChild(list_item_value);\n xml.appendChild(list_item);\n\n } catch(e){}\n }\n return xml;\n\n }\n\n}", "function RGBColor(color_string)\r\n{\r\n this.ok = false;\r\n\r\n // strip any leading #\r\n if (color_string.charAt(0) == '#') { // remove # if any\r\n color_string = color_string.substr(1,6);\r\n }\r\n\r\n color_string = color_string.replace(/ /g,'');\r\n color_string = color_string.toLowerCase();\r\n\r\n // before getting into regexps, try simple matches\r\n // and overwrite the input\r\n var simple_colors = {\r\n aliceblue: 'f0f8ff',\r\n antiquewhite: 'faebd7',\r\n aqua: '00ffff',\r\n aquamarine: '7fffd4',\r\n azure: 'f0ffff',\r\n beige: 'f5f5dc',\r\n bisque: 'ffe4c4',\r\n black: '000000',\r\n blanchedalmond: 'ffebcd',\r\n blue: '0000ff',\r\n blueviolet: '8a2be2',\r\n brown: 'a52a2a',\r\n burlywood: 'deb887',\r\n cadetblue: '5f9ea0',\r\n chartreuse: '7fff00',\r\n chocolate: 'd2691e',\r\n coral: 'ff7f50',\r\n cornflowerblue: '6495ed',\r\n cornsilk: 'fff8dc',\r\n crimson: 'dc143c',\r\n cyan: '00ffff',\r\n darkblue: '00008b',\r\n darkcyan: '008b8b',\r\n darkgoldenrod: 'b8860b',\r\n darkgray: 'a9a9a9',\r\n darkgreen: '006400',\r\n darkkhaki: 'bdb76b',\r\n darkmagenta: '8b008b',\r\n darkolivegreen: '556b2f',\r\n darkorange: 'ff8c00',\r\n darkorchid: '9932cc',\r\n darkred: '8b0000',\r\n darksalmon: 'e9967a',\r\n darkseagreen: '8fbc8f',\r\n darkslateblue: '483d8b',\r\n darkslategray: '2f4f4f',\r\n darkturquoise: '00ced1',\r\n darkviolet: '9400d3',\r\n deeppink: 'ff1493',\r\n deepskyblue: '00bfff',\r\n dimgray: '696969',\r\n dodgerblue: '1e90ff',\r\n feldspar: 'd19275',\r\n firebrick: 'b22222',\r\n floralwhite: 'fffaf0',\r\n forestgreen: '228b22',\r\n fuchsia: 'ff00ff',\r\n gainsboro: 'dcdcdc',\r\n ghostwhite: 'f8f8ff',\r\n gold: 'ffd700',\r\n goldenrod: 'daa520',\r\n gray: '808080',\r\n green: '008000',\r\n greenyellow: 'adff2f',\r\n honeydew: 'f0fff0',\r\n hotpink: 'ff69b4',\r\n indianred : 'cd5c5c',\r\n indigo : '4b0082',\r\n ivory: 'fffff0',\r\n khaki: 'f0e68c',\r\n lavender: 'e6e6fa',\r\n lavenderblush: 'fff0f5',\r\n lawngreen: '7cfc00',\r\n lemonchiffon: 'fffacd',\r\n lightblue: 'add8e6',\r\n lightcoral: 'f08080',\r\n lightcyan: 'e0ffff',\r\n lightgoldenrodyellow: 'fafad2',\r\n lightgrey: 'd3d3d3',\r\n lightgreen: '90ee90',\r\n lightpink: 'ffb6c1',\r\n lightsalmon: 'ffa07a',\r\n lightseagreen: '20b2aa',\r\n lightskyblue: '87cefa',\r\n lightslateblue: '8470ff',\r\n lightslategray: '778899',\r\n lightsteelblue: 'b0c4de',\r\n lightyellow: 'ffffe0',\r\n lime: '00ff00',\r\n limegreen: '32cd32',\r\n linen: 'faf0e6',\r\n magenta: 'ff00ff',\r\n maroon: '800000',\r\n mediumaquamarine: '66cdaa',\r\n mediumblue: '0000cd',\r\n mediumorchid: 'ba55d3',\r\n mediumpurple: '9370d8',\r\n mediumseagreen: '3cb371',\r\n mediumslateblue: '7b68ee',\r\n mediumspringgreen: '00fa9a',\r\n mediumturquoise: '48d1cc',\r\n mediumvioletred: 'c71585',\r\n midnightblue: '191970',\r\n mintcream: 'f5fffa',\r\n mistyrose: 'ffe4e1',\r\n moccasin: 'ffe4b5',\r\n navajowhite: 'ffdead',\r\n navy: '000080',\r\n oldlace: 'fdf5e6',\r\n olive: '808000',\r\n olivedrab: '6b8e23',\r\n orange: 'ffa500',\r\n orangered: 'ff4500',\r\n orchid: 'da70d6',\r\n palegoldenrod: 'eee8aa',\r\n palegreen: '98fb98',\r\n paleturquoise: 'afeeee',\r\n palevioletred: 'd87093',\r\n papayawhip: 'ffefd5',\r\n peachpuff: 'ffdab9',\r\n peru: 'cd853f',\r\n pink: 'ffc0cb',\r\n plum: 'dda0dd',\r\n powderblue: 'b0e0e6',\r\n purple: '800080',\r\n red: 'ff0000',\r\n rosybrown: 'bc8f8f',\r\n royalblue: '4169e1',\r\n saddlebrown: '8b4513',\r\n salmon: 'fa8072',\r\n sandybrown: 'f4a460',\r\n seagreen: '2e8b57',\r\n seashell: 'fff5ee',\r\n sienna: 'a0522d',\r\n silver: 'c0c0c0',\r\n skyblue: '87ceeb',\r\n slateblue: '6a5acd',\r\n slategray: '708090',\r\n snow: 'fffafa',\r\n springgreen: '00ff7f',\r\n steelblue: '4682b4',\r\n tan: 'd2b48c',\r\n teal: '008080',\r\n thistle: 'd8bfd8',\r\n tomato: 'ff6347',\r\n turquoise: '40e0d0',\r\n violet: 'ee82ee',\r\n violetred: 'd02090',\r\n wheat: 'f5deb3',\r\n white: 'ffffff',\r\n whitesmoke: 'f5f5f5',\r\n yellow: 'ffff00',\r\n yellowgreen: '9acd32'\r\n };\r\n for (var key in simple_colors) {\r\n if (color_string == key) {\r\n color_string = simple_colors[key];\r\n }\r\n }\r\n // emd of simple type-in colors\r\n\r\n // array of color definition objects\r\n var color_defs = [\r\n {\r\n re: /^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,\r\n example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1]),\r\n parseInt(bits[2]),\r\n parseInt(bits[3])\r\n ];\r\n }\r\n },\r\n {\r\n re: /^(\\w{2})(\\w{2})(\\w{2})$/,\r\n example: ['#00ff00', '336699'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1], 16),\r\n parseInt(bits[2], 16),\r\n parseInt(bits[3], 16)\r\n ];\r\n }\r\n },\r\n {\r\n re: /^(\\w{1})(\\w{1})(\\w{1})$/,\r\n example: ['#fb0', 'f0f'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1] + bits[1], 16),\r\n parseInt(bits[2] + bits[2], 16),\r\n parseInt(bits[3] + bits[3], 16)\r\n ];\r\n }\r\n }\r\n ];\r\n\r\n // search through the definitions to find a match\r\n for (var i = 0; i < color_defs.length; i++) {\r\n var re = color_defs[i].re;\r\n var processor = color_defs[i].process;\r\n var bits = re.exec(color_string);\r\n if (bits) {\r\n channels = processor(bits);\r\n this.r = channels[0];\r\n this.g = channels[1];\r\n this.b = channels[2];\r\n this.ok = true;\r\n }\r\n\r\n }\r\n\r\n // validate/cleanup values\r\n this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);\r\n this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);\r\n this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);\r\n\r\n // some getters\r\n this.toRGB = function () {\r\n return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';\r\n }\r\n this.toHex = function () {\r\n var r = this.r.toString(16);\r\n var g = this.g.toString(16);\r\n var b = this.b.toString(16);\r\n if (r.length == 1) r = '0' + r;\r\n if (g.length == 1) g = '0' + g;\r\n if (b.length == 1) b = '0' + b;\r\n return '#' + r + g + b;\r\n }\r\n\r\n // help\r\n this.getHelpXML = function () {\r\n\r\n var examples = new Array();\r\n // add regexps\r\n for (var i = 0; i < color_defs.length; i++) {\r\n var example = color_defs[i].example;\r\n for (var j = 0; j < example.length; j++) {\r\n examples[examples.length] = example[j];\r\n }\r\n }\r\n // add type-in colors\r\n for (var sc in simple_colors) {\r\n examples[examples.length] = sc;\r\n }\r\n\r\n var xml = document.createElement('ul');\r\n xml.setAttribute('id', 'rgbcolor-examples');\r\n for (var i = 0; i < examples.length; i++) {\r\n try {\r\n var list_item = document.createElement('li');\r\n var list_color = new RGBColor(examples[i]);\r\n var example_div = document.createElement('div');\r\n example_div.style.cssText =\r\n 'margin: 3px; '\r\n + 'border: 1px solid black; '\r\n + 'background:' + list_color.toHex() + '; '\r\n + 'color:' + list_color.toHex()\r\n ;\r\n example_div.appendChild(document.createTextNode('test'));\r\n var list_item_value = document.createTextNode(\r\n ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()\r\n );\r\n list_item.appendChild(example_div);\r\n list_item.appendChild(list_item_value);\r\n xml.appendChild(list_item);\r\n\r\n } catch(e){}\r\n }\r\n return xml;\r\n\r\n }\r\n\r\n}", "function RGBColor(color_string)\r\n{\r\n this.ok = false;\r\n\r\n // strip any leading #\r\n if (color_string.charAt(0) == '#') { // remove # if any\r\n color_string = color_string.substr(1,6);\r\n }\r\n\r\n color_string = color_string.replace(/ /g,'');\r\n color_string = color_string.toLowerCase();\r\n\r\n // before getting into regexps, try simple matches\r\n // and overwrite the input\r\n var simple_colors = {\r\n aliceblue: 'f0f8ff',\r\n antiquewhite: 'faebd7',\r\n aqua: '00ffff',\r\n aquamarine: '7fffd4',\r\n azure: 'f0ffff',\r\n beige: 'f5f5dc',\r\n bisque: 'ffe4c4',\r\n black: '000000',\r\n blanchedalmond: 'ffebcd',\r\n blue: '0000ff',\r\n blueviolet: '8a2be2',\r\n brown: 'a52a2a',\r\n burlywood: 'deb887',\r\n cadetblue: '5f9ea0',\r\n chartreuse: '7fff00',\r\n chocolate: 'd2691e',\r\n coral: 'ff7f50',\r\n cornflowerblue: '6495ed',\r\n cornsilk: 'fff8dc',\r\n crimson: 'dc143c',\r\n cyan: '00ffff',\r\n darkblue: '00008b',\r\n darkcyan: '008b8b',\r\n darkgoldenrod: 'b8860b',\r\n darkgray: 'a9a9a9',\r\n darkgreen: '006400',\r\n darkkhaki: 'bdb76b',\r\n darkmagenta: '8b008b',\r\n darkolivegreen: '556b2f',\r\n darkorange: 'ff8c00',\r\n darkorchid: '9932cc',\r\n darkred: '8b0000',\r\n darksalmon: 'e9967a',\r\n darkseagreen: '8fbc8f',\r\n darkslateblue: '483d8b',\r\n darkslategray: '2f4f4f',\r\n darkturquoise: '00ced1',\r\n darkviolet: '9400d3',\r\n deeppink: 'ff1493',\r\n deepskyblue: '00bfff',\r\n dimgray: '696969',\r\n dodgerblue: '1e90ff',\r\n feldspar: 'd19275',\r\n firebrick: 'b22222',\r\n floralwhite: 'fffaf0',\r\n forestgreen: '228b22',\r\n fuchsia: 'ff00ff',\r\n gainsboro: 'dcdcdc',\r\n ghostwhite: 'f8f8ff',\r\n gold: 'ffd700',\r\n goldenrod: 'daa520',\r\n gray: '808080',\r\n green: '008000',\r\n greenyellow: 'adff2f',\r\n honeydew: 'f0fff0',\r\n hotpink: 'ff69b4',\r\n indianred : 'cd5c5c',\r\n indigo : '4b0082',\r\n ivory: 'fffff0',\r\n khaki: 'f0e68c',\r\n lavender: 'e6e6fa',\r\n lavenderblush: 'fff0f5',\r\n lawngreen: '7cfc00',\r\n lemonchiffon: 'fffacd',\r\n lightblue: 'add8e6',\r\n lightcoral: 'f08080',\r\n lightcyan: 'e0ffff',\r\n lightgoldenrodyellow: 'fafad2',\r\n lightgrey: 'd3d3d3',\r\n lightgreen: '90ee90',\r\n lightpink: 'ffb6c1',\r\n lightsalmon: 'ffa07a',\r\n lightseagreen: '20b2aa',\r\n lightskyblue: '87cefa',\r\n lightslateblue: '8470ff',\r\n lightslategray: '778899',\r\n lightsteelblue: 'b0c4de',\r\n lightyellow: 'ffffe0',\r\n lime: '00ff00',\r\n limegreen: '32cd32',\r\n linen: 'faf0e6',\r\n magenta: 'ff00ff',\r\n maroon: '800000',\r\n mediumaquamarine: '66cdaa',\r\n mediumblue: '0000cd',\r\n mediumorchid: 'ba55d3',\r\n mediumpurple: '9370d8',\r\n mediumseagreen: '3cb371',\r\n mediumslateblue: '7b68ee',\r\n mediumspringgreen: '00fa9a',\r\n mediumturquoise: '48d1cc',\r\n mediumvioletred: 'c71585',\r\n midnightblue: '191970',\r\n mintcream: 'f5fffa',\r\n mistyrose: 'ffe4e1',\r\n moccasin: 'ffe4b5',\r\n navajowhite: 'ffdead',\r\n navy: '000080',\r\n oldlace: 'fdf5e6',\r\n olive: '808000',\r\n olivedrab: '6b8e23',\r\n orange: 'ffa500',\r\n orangered: 'ff4500',\r\n orchid: 'da70d6',\r\n palegoldenrod: 'eee8aa',\r\n palegreen: '98fb98',\r\n paleturquoise: 'afeeee',\r\n palevioletred: 'd87093',\r\n papayawhip: 'ffefd5',\r\n peachpuff: 'ffdab9',\r\n peru: 'cd853f',\r\n pink: 'ffc0cb',\r\n plum: 'dda0dd',\r\n powderblue: 'b0e0e6',\r\n purple: '800080',\r\n red: 'ff0000',\r\n rosybrown: 'bc8f8f',\r\n royalblue: '4169e1',\r\n saddlebrown: '8b4513',\r\n salmon: 'fa8072',\r\n sandybrown: 'f4a460',\r\n seagreen: '2e8b57',\r\n seashell: 'fff5ee',\r\n sienna: 'a0522d',\r\n silver: 'c0c0c0',\r\n skyblue: '87ceeb',\r\n slateblue: '6a5acd',\r\n slategray: '708090',\r\n snow: 'fffafa',\r\n springgreen: '00ff7f',\r\n steelblue: '4682b4',\r\n tan: 'd2b48c',\r\n teal: '008080',\r\n thistle: 'd8bfd8',\r\n tomato: 'ff6347',\r\n turquoise: '40e0d0',\r\n violet: 'ee82ee',\r\n violetred: 'd02090',\r\n wheat: 'f5deb3',\r\n white: 'ffffff',\r\n whitesmoke: 'f5f5f5',\r\n yellow: 'ffff00',\r\n yellowgreen: '9acd32'\r\n };\r\n for (var key in simple_colors) {\r\n if (color_string == key) {\r\n color_string = simple_colors[key];\r\n }\r\n }\r\n // emd of simple type-in colors\r\n\r\n // array of color definition objects\r\n var color_defs = [\r\n {\r\n re: /^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,\r\n example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1]),\r\n parseInt(bits[2]),\r\n parseInt(bits[3])\r\n ];\r\n }\r\n },\r\n {\r\n re: /^(\\w{2})(\\w{2})(\\w{2})$/,\r\n example: ['#00ff00', '336699'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1], 16),\r\n parseInt(bits[2], 16),\r\n parseInt(bits[3], 16)\r\n ];\r\n }\r\n },\r\n {\r\n re: /^(\\w{1})(\\w{1})(\\w{1})$/,\r\n example: ['#fb0', 'f0f'],\r\n process: function (bits){\r\n return [\r\n parseInt(bits[1] + bits[1], 16),\r\n parseInt(bits[2] + bits[2], 16),\r\n parseInt(bits[3] + bits[3], 16)\r\n ];\r\n }\r\n }\r\n ];\r\n\r\n // search through the definitions to find a match\r\n for (var i = 0; i < color_defs.length; i++) {\r\n var re = color_defs[i].re;\r\n var processor = color_defs[i].process;\r\n var bits = re.exec(color_string);\r\n if (bits) {\r\n channels = processor(bits);\r\n this.r = channels[0];\r\n this.g = channels[1];\r\n this.b = channels[2];\r\n this.ok = true;\r\n }\r\n\r\n }\r\n\r\n // validate/cleanup values\r\n this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);\r\n this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);\r\n this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);\r\n\r\n // some getters\r\n this.toRGB = function () {\r\n return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';\r\n }\r\n this.toHex = function () {\r\n var r = this.r.toString(16);\r\n var g = this.g.toString(16);\r\n var b = this.b.toString(16);\r\n if (r.length == 1) r = '0' + r;\r\n if (g.length == 1) g = '0' + g;\r\n if (b.length == 1) b = '0' + b;\r\n return '#' + r + g + b;\r\n }\r\n\r\n // help\r\n this.getHelpXML = function () {\r\n\r\n var examples = new Array();\r\n // add regexps\r\n for (var i = 0; i < color_defs.length; i++) {\r\n var example = color_defs[i].example;\r\n for (var j = 0; j < example.length; j++) {\r\n examples[examples.length] = example[j];\r\n }\r\n }\r\n // add type-in colors\r\n for (var sc in simple_colors) {\r\n examples[examples.length] = sc;\r\n }\r\n\r\n var xml = document.createElement('ul');\r\n xml.setAttribute('id', 'rgbcolor-examples');\r\n for (var i = 0; i < examples.length; i++) {\r\n try {\r\n var list_item = document.createElement('li');\r\n var list_color = new RGBColor(examples[i]);\r\n var example_div = document.createElement('div');\r\n example_div.style.cssText =\r\n 'margin: 3px; '\r\n + 'border: 1px solid black; '\r\n + 'background:' + list_color.toHex() + '; '\r\n + 'color:' + list_color.toHex()\r\n ;\r\n example_div.appendChild(document.createTextNode('test'));\r\n var list_item_value = document.createTextNode(\r\n ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()\r\n );\r\n list_item.appendChild(example_div);\r\n list_item.appendChild(list_item_value);\r\n xml.appendChild(list_item);\r\n\r\n } catch(e){}\r\n }\r\n return xml;\r\n\r\n }\r\n\r\n}", "function getRgbCss(r, g, b) {\r\n\treturn 'color: rgb(' + r + ',' + g + ',' + b + ');';\r\n}", "getDefaultColor() {\n return [0.69921875, 0.69921875, 0.69921875];\n }", "function rgb(r, g, b)\n{\n\treturn 'rgb('+clamp(Math.round(r),0,255)+', '+clamp(Math.round(g),0,255)+', '+clamp(Math.round(b),0,255)+')';\n}", "function oldColor() {\n if (ALaxis === 'distanceSpot')\n return '#ff0000';\n else if (ALaxis === 'angleSpot')\n return '#0000ff';\n else if (ALaxis === 'colorRing' || ALaxis === 'lightnessRing')\n return '#888';\n}", "function rgbc(a,b,c) {\n return 'rgb(' + a + ',' + b + ',' + c + ')';\n}", "function color() {\n var map = {\n \"black\" : [ 0/255,0/255,0/255 ],\n \"silver\": [ 192/255,192/255,192/255 ],\n \"gray\" : [ 128/255,128/255,128/255 ],\n \"white\" : [ 255/255,255/255,255/255 ],\n \"maroon\": [ 128/255,0/255,0/255 ],\n \"red\" : [ 255/255,0/255,0/255 ],\n \"purple\": [ 128/255,0/255,128/255 ],\n \"fuchsia\": [ 255/255,0/255,255/255 ],\n \"green\" : [ 0/255,128/255,0/255 ],\n \"lime\" : [ 0/255,255/255,0/255 ],\n \"olive\" : [ 128/255,128/255,0/255 ],\n \"yellow\": [ 255/255,255/255,0/255 ],\n \"navy\" : [ 0/255,0/255,128/255 ],\n \"blue\" : [ 0/255,0/255,255/255 ],\n \"teal\" : [ 0/255,128/255,128/255 ],\n \"aqua\" : [ 0/255,255/255,255/255 ],\n \"aliceblue\" : [ 240/255,248/255,255/255 ],\n \"antiquewhite\" : [ 250/255,235/255,215/255 ],\n \"aqua\" : [ 0/255,255/255,255/255 ],\n \"aquamarine\" : [ 127/255,255/255,212/255 ],\n \"azure\" : [ 240/255,255/255,255/255 ],\n \"beige\" : [ 245/255,245/255,220/255 ],\n \"bisque\" : [ 255/255,228/255,196/255 ],\n \"black\" : [ 0/255,0/255,0/255 ],\n \"blanchedalmond\" : [ 255/255,235/255,205/255 ],\n \"blue\" : [ 0/255,0/255,255/255 ],\n \"blueviolet\" : [ 138/255,43/255,226/255 ],\n \"brown\" : [ 165/255,42/255,42/255 ],\n \"burlywood\" : [ 222/255,184/255,135/255 ],\n \"cadetblue\" : [ 95/255,158/255,160/255 ],\n \"chartreuse\" : [ 127/255,255/255,0/255 ],\n \"chocolate\" : [ 210/255,105/255,30/255 ],\n \"coral\" : [ 255/255,127/255,80/255 ],\n \"cornflowerblue\" : [ 100/255,149/255,237/255 ],\n \"cornsilk\" : [ 255/255,248/255,220/255 ],\n \"crimson\" : [ 220/255,20/255,60/255 ],\n \"cyan\" : [ 0/255,255/255,255/255 ],\n \"darkblue\" : [ 0/255,0/255,139/255 ],\n \"darkcyan\" : [ 0/255,139/255,139/255 ],\n \"darkgoldenrod\" : [ 184/255,134/255,11/255 ],\n \"darkgray\" : [ 169/255,169/255,169/255 ],\n \"darkgreen\" : [ 0/255,100/255,0/255 ],\n \"darkgrey\" : [ 169/255,169/255,169/255 ],\n \"darkkhaki\" : [ 189/255,183/255,107/255 ],\n \"darkmagenta\" : [ 139/255,0/255,139/255 ],\n \"darkolivegreen\" : [ 85/255,107/255,47/255 ],\n \"darkorange\" : [ 255/255,140/255,0/255 ],\n \"darkorchid\" : [ 153/255,50/255,204/255 ],\n \"darkred\" : [ 139/255,0/255,0/255 ],\n \"darksalmon\" : [ 233/255,150/255,122/255 ],\n \"darkseagreen\" : [ 143/255,188/255,143/255 ],\n \"darkslateblue\" : [ 72/255,61/255,139/255 ],\n \"darkslategray\" : [ 47/255,79/255,79/255 ],\n \"darkslategrey\" : [ 47/255,79/255,79/255 ],\n \"darkturquoise\" : [ 0/255,206/255,209/255 ],\n \"darkviolet\" : [ 148/255,0/255,211/255 ],\n \"deeppink\" : [ 255/255,20/255,147/255 ],\n \"deepskyblue\" : [ 0/255,191/255,255/255 ],\n \"dimgray\" : [ 105/255,105/255,105/255 ],\n \"dimgrey\" : [ 105/255,105/255,105/255 ],\n \"dodgerblue\" : [ 30/255,144/255,255/255 ],\n \"firebrick\" : [ 178/255,34/255,34/255 ],\n \"floralwhite\" : [ 255/255,250/255,240/255 ],\n \"forestgreen\" : [ 34/255,139/255,34/255 ],\n \"fuchsia\" : [ 255/255,0/255,255/255 ],\n \"gainsboro\" : [ 220/255,220/255,220/255 ],\n \"ghostwhite\" : [ 248/255,248/255,255/255 ],\n \"gold\" : [ 255/255,215/255,0/255 ],\n \"goldenrod\" : [ 218/255,165/255,32/255 ],\n \"gray\" : [ 128/255,128/255,128/255 ],\n \"green\" : [ 0/255,128/255,0/255 ],\n \"greenyellow\" : [ 173/255,255/255,47/255 ],\n \"grey\" : [ 128/255,128/255,128/255 ],\n \"honeydew\" : [ 240/255,255/255,240/255 ],\n \"hotpink\" : [ 255/255,105/255,180/255 ],\n \"indianred\" : [ 205/255,92/255,92/255 ],\n \"indigo\" : [ 75/255,0/255,130/255 ],\n \"ivory\" : [ 255/255,255/255,240/255 ],\n \"khaki\" : [ 240/255,230/255,140/255 ],\n \"lavender\" : [ 230/255,230/255,250/255 ],\n \"lavenderblush\" : [ 255/255,240/255,245/255 ],\n \"lawngreen\" : [ 124/255,252/255,0/255 ],\n \"lemonchiffon\" : [ 255/255,250/255,205/255 ],\n \"lightblue\" : [ 173/255,216/255,230/255 ],\n \"lightcoral\" : [ 240/255,128/255,128/255 ],\n \"lightcyan\" : [ 224/255,255/255,255/255 ],\n \"lightgoldenrodyellow\" : [ 250/255,250/255,210/255 ],\n \"lightgray\" : [ 211/255,211/255,211/255 ],\n \"lightgreen\" : [ 144/255,238/255,144/255 ],\n \"lightgrey\" : [ 211/255,211/255,211/255 ],\n \"lightpink\" : [ 255/255,182/255,193/255 ],\n \"lightsalmon\" : [ 255/255,160/255,122/255 ],\n \"lightseagreen\" : [ 32/255,178/255,170/255 ],\n \"lightskyblue\" : [ 135/255,206/255,250/255 ],\n \"lightslategray\" : [ 119/255,136/255,153/255 ],\n \"lightslategrey\" : [ 119/255,136/255,153/255 ],\n \"lightsteelblue\" : [ 176/255,196/255,222/255 ],\n \"lightyellow\" : [ 255/255,255/255,224/255 ],\n \"lime\" : [ 0/255,255/255,0/255 ],\n \"limegreen\" : [ 50/255,205/255,50/255 ],\n \"linen\" : [ 250/255,240/255,230/255 ],\n \"magenta\" : [ 255/255,0/255,255/255 ],\n \"maroon\" : [ 128/255,0/255,0/255 ],\n \"mediumaquamarine\" : [ 102/255,205/255,170/255 ],\n \"mediumblue\" : [ 0/255,0/255,205/255 ],\n \"mediumorchid\" : [ 186/255,85/255,211/255 ],\n \"mediumpurple\" : [ 147/255,112/255,219/255 ],\n \"mediumseagreen\" : [ 60/255,179/255,113/255 ],\n \"mediumslateblue\" : [ 123/255,104/255,238/255 ],\n \"mediumspringgreen\" : [ 0/255,250/255,154/255 ],\n \"mediumturquoise\" : [ 72/255,209/255,204/255 ],\n \"mediumvioletred\" : [ 199/255,21/255,133/255 ],\n \"midnightblue\" : [ 25/255,25/255,112/255 ],\n \"mintcream\" : [ 245/255,255/255,250/255 ],\n \"mistyrose\" : [ 255/255,228/255,225/255 ],\n \"moccasin\" : [ 255/255,228/255,181/255 ],\n \"navajowhite\" : [ 255/255,222/255,173/255 ],\n \"navy\" : [ 0/255,0/255,128/255 ],\n \"oldlace\" : [ 253/255,245/255,230/255 ],\n \"olive\" : [ 128/255,128/255,0/255 ],\n \"olivedrab\" : [ 107/255,142/255,35/255 ],\n \"orange\" : [ 255/255,165/255,0/255 ],\n \"orangered\" : [ 255/255,69/255,0/255 ],\n \"orchid\" : [ 218/255,112/255,214/255 ],\n \"palegoldenrod\" : [ 238/255,232/255,170/255 ],\n \"palegreen\" : [ 152/255,251/255,152/255 ],\n \"paleturquoise\" : [ 175/255,238/255,238/255 ],\n \"palevioletred\" : [ 219/255,112/255,147/255 ],\n \"papayawhip\" : [ 255/255,239/255,213/255 ],\n \"peachpuff\" : [ 255/255,218/255,185/255 ],\n \"peru\" : [ 205/255,133/255,63/255 ],\n \"pink\" : [ 255/255,192/255,203/255 ],\n \"plum\" : [ 221/255,160/255,221/255 ],\n \"powderblue\" : [ 176/255,224/255,230/255 ],\n \"purple\" : [ 128/255,0/255,128/255 ],\n \"red\" : [ 255/255,0/255,0/255 ],\n \"rosybrown\" : [ 188/255,143/255,143/255 ],\n \"royalblue\" : [ 65/255,105/255,225/255 ],\n \"saddlebrown\" : [ 139/255,69/255,19/255 ],\n \"salmon\" : [ 250/255,128/255,114/255 ],\n \"sandybrown\" : [ 244/255,164/255,96/255 ],\n \"seagreen\" : [ 46/255,139/255,87/255 ],\n \"seashell\" : [ 255/255,245/255,238/255 ],\n \"sienna\" : [ 160/255,82/255,45/255 ],\n \"silver\" : [ 192/255,192/255,192/255 ],\n \"skyblue\" : [ 135/255,206/255,235/255 ],\n \"slateblue\" : [ 106/255,90/255,205/255 ],\n \"slategray\" : [ 112/255,128/255,144/255 ],\n \"slategrey\" : [ 112/255,128/255,144/255 ],\n \"snow\" : [ 255/255,250/255,250/255 ],\n \"springgreen\" : [ 0/255,255/255,127/255 ],\n \"steelblue\" : [ 70/255,130/255,180/255 ],\n \"tan\" : [ 210/255,180/255,140/255 ],\n \"teal\" : [ 0/255,128/255,128/255 ],\n \"thistle\" : [ 216/255,191/255,216/255 ],\n \"tomato\" : [ 255/255,99/255,71/255 ],\n \"turquoise\" : [ 64/255,224/255,208/255 ],\n \"violet\" : [ 238/255,130/255,238/255 ],\n \"wheat\" : [ 245/255,222/255,179/255 ],\n \"white\" : [ 255/255,255/255,255/255 ],\n \"whitesmoke\" : [ 245/255,245/255,245/255 ],\n \"yellow\" : [ 255/255,255/255,0/255 ],\n \"yellowgreen\" : [ 154/255,205/255,50/255 ] };\n\n var o, i = 1, a = arguments, c = a[0], alpha;\n\n if(a[0].length<4 && (a[i]*1-0)==a[i]) { alpha = a[i++]; } // first argument rgb (no a), and next one is numeric?\n if(a[i].length) { a = a[i], i = 0; } // next arg an array, make it our main array to walk through\n if(typeof c == 'string')\n c = map[c.toLowerCase()];\n if(alpha!==undefined)\n c = c.concat(alpha);\n for(o=a[i++]; i<a.length; i++) {\n o = o.union(a[i]);\n }\n return o.setColor(c);\n}", "function getcolor(c) {\n if(c == \"naranja\") return '#FCAF00'; else\n if (c == \"tradicional\") return '#3FDAD6';\n\tif (c == \"aliado\") return '#FE52D4';\n }", "function generateColor(red, green, blue)\n{\n paintColor[0] = red;\n paintColor[1] = green;\n paintColor[2] = blue;\n}", "function randomColor(){\n return `rgb(${randomNum()}, ${randomNum()}, ${randomNum()})`;\n}", "function getColor(type) {\n\tswitch (type) {\n\t\tcase \"reconstruction\":\treturn \"Red\";\n\t\tcase \"finishing\":\treturn \"Yellow\";\n\t\tcase \"done\": \t\treturn \"Green\";\n\t\tcase \"planned\":\t\treturn \"Blue\";\n\t\tdefault:\t\treturn \"Pink\";\n\t}\n}", "function determineColor(){\n var red = randomInt(255);\n var green = randomInt(255);\n var blue = randomInt(255);\n}", "get ETC_RGB4() {}", "function generateColor(r, g, b)\n{\n\treturn \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}", "function color(i) {\n\tlet ret = \"white\";\n\tswitch (i) {\n\t\tcase 0:\n\t\t\tret = \"bisque\";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tret = \"lightgreen\";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tret = \"lightsalmon\";\n\t\t\tbreak;\n\t\tdefault:\n\t}\n\treturn ret;\n}", "getColor() {\n if (this.type == 'home' || this.type == 'goal') {\n return ['#B5FEB4', '#B5FEB4'];\n }\n\n else if (this.type == 'board') {\n return ['#F7F7FF', '#E6E6FF'];\n }\n\n else if (this.type == 'back'){\n return ['#B4B5FE', '#B4B5FE'];\n }\n }", "function colorScheme(str) {\n\t\tlet hashes = hashNines(str);\n\t\tlet r = 100 + 15 * hashes[1];\n\t\tlet g = 100 + 15 * hashes[2];\n\t\tlet b = 100 + 15 * hashes[0];\n\t\tlet lightColor = `rgb(${r},${g},${b})`;\n\t\tlet lighterColor = `rgb(${r+20},${g+20},${b+20})`;\n\t\tlet darkColor = `rgb(${r-60},${g-60},${b-60})`;\n\t\treturn [lightColor, darkColor, lighterColor];\n\t}", "function addColors() {\n\tvar temp = \"rgb(\" + generateRGB() + \", \" + generateRGB() + \", \" + generateRGB() + \")\";\n\treturn temp;\n}", "function get_color(rgb) {\n if (typeof rgb !== 'undefined') {\n\n if (rgb.indexOf(\"rgba\") != -1) {\n return rgb.replace(/\\s+/g, \"\");\n }\n\n rgb = rgb.match(/^rgba?[\\s+]?\\([\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?/i);\n\n return (rgb && rgb.length === 4) ? \"#\" + (\"0\" + parseInt(rgb[1], 10).toString(16)).slice(-2) + (\"0\" + parseInt(rgb[2], 10).toString(16)).slice(-2) + (\"0\" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';\n\n } else {\n return '';\n }\n }", "function colorForCurrent(){\n\n}", "function background() {\n let red = Math.floor(Math.random()*256);\n let green = Math.floor(Math.random()*256);\n let blue = Math.floor(Math.random()*256);\n\n//This combines all of the value to creat a string that house the rgb value for a random colour\nreturn `rgb(${red}, ${green}, ${blue})`\n}", "function getColor(color) {\n\tif (color.includes(\"Magno-Gold\"))\n\t\treturn \"#F6A723\"\n\telse if (color.includes(\"Gold\"))\n\t\treturn \"#6E5012\"\n\telse if (color.includes(\"Carbon Crystal\"))\n\t\treturn \"#BC3731\"\n\telse if (color.includes(\"Carbon\"))\n\t\treturn \"#7C322E\"\n\telse if (color.includes(\"TetraCobalt\"))\n\t\treturn \"#025B85\"\n\telse if (color.includes(\"Cobalt\"))\n\t\treturn \"#0B4762\"\n\telse if (color.includes(\"Cadmium\"))\n\t\treturn \"#581115\"\n\telse if (color.includes(\"Copper\"))\n\t\treturn \"#946714\"\n\telse if (color.includes(\"Emeril\"))\n\t\treturn \"#294C23\"\n\telse if (color.includes(\"Indium\"))\n\t\treturn \"#0C3662\"\n\telse if (color.includes(\"Chromatic Metal\"))\n\t\treturn \"#251314\"\n\telse if (color.includes(\"Ammonia\"))\n\t\treturn \"#0A723C\"\n\telse if (color.includes(\"Aronium\"))\n\t\treturn \"#F6A723\"\n\telse if (color.includes(\"Ferrite\"))\n\t\treturn \"#5B5A55\"\n\telse if (color.includes(\"Silver\"))\n\t\treturn \"#5C5A55\"\n\telse if (color.includes(\"Cactus Flesh\"))\n\t\treturn \"#1D6827\"\n\telse if (color.includes(\"Destablised Sodium\"))\n\t\treturn \"#F16E17\"\n\telse if (color.includes(\"Sodium\"))\n\t\treturn \"#9C4E22\"\n\telse if (color.includes(\"Salt\"))\n\t\treturn \"#1B623A\"\n\telse if (color.includes(\"Solanium\"))\n\t\treturn \"#78361E\"\n\telse if (color.includes(\"Chlorine\"))\n\t\treturn \"#113611\"\n\telse if (color.includes(\"Chloride Lattice\"))\n\t\treturn \"#1E8941\"\n\telse if (color.includes(\"Coprite\"))\n\t\treturn \"#533E2D\"\n\telse if (color.includes(\"Di-hydrogen Jelly\"))\n\t\treturn \"#C21646\"\n\telse if (color.includes(\"Di-hydrogen\"))\n\t\treturn \"#25465C\"\n\telse if (color.includes(\"Dioxite\"))\n\t\treturn \"#1C3D8C\"\n\telse if (color.includes(\"Mordite\"))\n\t\treturn \"#392634\"\n\telse if (color.includes(\"Dirty Bronze\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Grantine\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Herox\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Geodesite\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Iridesite\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Lemmium\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Thermic Condensate\"))\n\t\treturn \"#F1AA22\"\n\telse if (color.includes(\"Platinum\"))\n\t\treturn \"#385457\"\n\telse if (color.includes(\"Pyrite\"))\n\t\treturn \"#925113\"\n\telse if (color.includes(\"Gamma Root\"))\n\t\treturn \"#7E5E21\"\n\telse if (color.includes(\"Fungal Mould\"))\n\t\treturn \"#08733C\"\n\telse if (color.includes(\"Frost Crystal\"))\n\t\treturn \"#193F8C\"\n\telse if (color.includes(\"Kelp Sac\"))\n\t\treturn \"#1B768F\"\n\telse if (color.includes(\"Oxygen\"))\n\t\treturn \"#7B3430\"\n\telse if (color.includes(\"Living Slime\"))\n\t\treturn \"#3E522F\"\n\telse if (color.includes(\"Runaway Mould\"))\n\t\treturn \"#405130\"\n\telse if (color.includes(\"Marrow Bulb\"))\n\t\treturn \"#475930\"\n\telse if (color.includes(\"Nitrogen\"))\n\t\treturn \"#8D6623\"\n\telse if (color.includes(\"Sulphurine\"))\n\t\treturn \"#214532\"\n\telse if (color.includes(\"Radon\"))\n\t\treturn \"#36305E\"\n\telse if (color.includes(\"Paraffinium\"))\n\t\treturn \"#383442\"\n\telse if (color.includes(\"Phosphorus\"))\n\t\treturn \"#8C240F\"\n\telse if (color.includes(\"Nanite\"))\n\t\treturn \"#192E3F\"\n\telse if (color.includes(\"Pugneum\"))\n\t\treturn \"#4C2A56\"\n\telse if (color.includes(\"Rare Metal Element\"))\n\t\treturn \"#8B7E71\"\n\telse if (color.includes(\"Residual Goop\"))\n\t\treturn \"#5B6F35\"\n\telse if (color.includes(\"Viscous Fluid\"))\n\t\treturn \"#40512F\"\n\telse if (color.includes(\"Glass\"))\n\t\treturn \"#F3A923\"\n\telse if (color.includes(\"Star Bulb\"))\n\t\treturn \"#296879\"\n\telse if (color.includes(\"Rusted Metal\"))\n\t\treturn \"#3E5230\"\n\telse if (color.includes(\"Superoxide Crystal\"))\n\t\treturn \"#BA3930\"\n\telse if (color.includes(\"Tritium\"))\n\t\treturn \"#DDDCD0\"\n\telse if (color.includes(\"Uranium\"))\n\t\treturn \"#A37610\"\n\telse if (color.includes(\"Unstable Plasma\"))\n\t\treturn \"#C01746\"\n\telse if (color.includes(\"Warp Cell\"))\n\t\treturn \"#C01746\"\n\telse if (color.includes(\"Starship Launch Fuel\"))\n\t\treturn \"#C01746\"\n\telse if (color.includes(\"Ion Battery\"))\n\t\treturn \"#F3A923\"\n\telse if (color.includes(\"Life Support Gel\"))\n\t\treturn \"#C01746\"\n\telse if (color.includes(\"Deuterium\"))\n\t\treturn \"#25465C\"\n}", "function getColor(colorNum) {\n switch (colorNum) {\n case Colors.Blue:\n return \"rgb(0,147,208)\";\n case Colors.Green:\n return 'rgb(98,161,25)';\n case Colors.Red:\n return 'rgb(186, 36, 65)';\n case Colors.Orange:\n return 'rgb(255, 127, 42)';\n case Colors.White:\n return 'rgb(255,255,255)';\n }\n}", "function randomRGB() {\n return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;\n}", "function rgbRed() {\n var val1 = randRGB();\n var val2 = randRGB();\n var val3 = randRGB();\n return \"rgb(\" + val1 + \", \" + 0 + \", \" + val1 / 4 + \")\";\n}", "brighter(){\n\t\tthis.addColorValue(\"red\", 30);\n\t\tthis.addColorValue(\"green\", 30);\n\t\tthis.addColorValue(\"blue\", 30);\n\t}", "function createColour() {\n\n // pick random rgb values from 0-255\n let red = Math.floor(Math.random() * 256);\n let green = Math.floor(Math.random() * 256);\n let blue = Math.floor(Math.random() * 256);\n\n // return synthesized property string\n return \"rgb(\" + red + \", \" + green + \", \" + blue + \")\";\n}", "set color(value) {}", "function rgb(r,g,b){\n return [r,g,b]\n .map(x => {\n if(x >= 255) return 'FF';\n if(x <= 0) return '00';\n\n const hex = x.toString(16);\n return hex.length === 1 ? `0${hex}` : hex;\n }).join('').toUpperCase();\n}", "function makeRGB(tuple=[0,0,0]) {\n return \"rgb(\" + tuple + \")\";\n}", "getColor(i) {\n switch(i) {\n case 1:\n return 'blue';\n case 2:\n return 'red';\n case 3:\n return 'yellow';\n default:\n return 'grey';\n }\n }", "function getRGB() {\n var rr = color.slice(1, 3);\n var gg = color.slice(3, 5);\n var bb = color.slice(3, 7);\n var r10 = parseInt(rr, 16);\n // Ponemos rr, 16 en el parseInt para que sepa que se trata de un hexadecimal y no de un entero normal. Sino, si pusiéramos letras no me lo cogería\n var g10 = parseInt(gg, 16);\n var b10 = parseInt(bb, 16);\n return 'rgb(' + r10 + ', ' + g10 + ', ' + b10 + ')';\n}", "static color() {\n return '#' + Math.floor(Math.random() * 16777215).toString(16)\n }", "function color(grey){\n return {r:grey, g:grey, b:grey};\n}", "set ETC2_RGB4(value) {}", "function rgb(...rgb){\n return rgb.map(val => val <= 0 ? \"00\" : (val > 255 ? 255 : val).toString(16).toUpperCase()).join(\"\");\n }", "function makeColors() {\n colors.push([\"rgb(205,230,245)\",\"rgb(141,167,190)\"])\n colors.push([\"rgb(24,169,153)\",\"rgb(72,67,73)\"])\n colors.push([\"rgb(24,169,153)\",\"rgb(242,244,243)\"])\n colors.push([\"rgb(237,242,244)\",\"rgb(43,45,66)\"])\n colors.push([\"rgb(192,248,209)\",\"rgb(189,207,181)\"])\n colors.push([\"rgb(141,177,171)\",\"rgb(88,119,146)\"])\n colors.push([\"rgb(80,81,104)\",\"rgb(179,192,164)\"])\n colors.push([\"rgb(34,34,34)\",\"rgb(99,159,171)\"])\n}", "getColor(value) {\n // Test Max\n if (value === 255) {\n console.log(\"MAX!\");\n }\n let percent = (value) / 255 * 50;\n // return 'rgb(V, V, V)'.replace(/V/g, 255 - value);\n return 'hsl(H, 100%, P%)'.replace(/H/g, 255 - value).replace(/P/g, percent);\n }", "function RGBColor(color_string)\n{\n this.ok = false;\n\n // strip any leading #\n if (color_string.charAt(0) == '#') { // remove # if any\n color_string = color_string.substr(1,6);\n }\n\n color_string = color_string.replace(/ /g,'');\n color_string = color_string.toLowerCase();\n\n // array of color definition objects\n var color_defs = [\n {\n re: /^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,\n example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],\n process: function (bits){\n return [\n parseInt(bits[1]),\n parseInt(bits[2]),\n parseInt(bits[3])\n ];\n }\n },\n {\n re: /^(\\w{2})(\\w{2})(\\w{2})$/,\n example: ['#00ff00', '336699'],\n process: function (bits){\n return [\n parseInt(bits[1], 16),\n parseInt(bits[2], 16),\n parseInt(bits[3], 16)\n ];\n }\n },\n {\n re: /^(\\w{1})(\\w{1})(\\w{1})$/,\n example: ['#fb0', 'f0f'],\n process: function (bits){\n return [\n parseInt(bits[1] + bits[1], 16),\n parseInt(bits[2] + bits[2], 16),\n parseInt(bits[3] + bits[3], 16)\n ];\n }\n }\n ];\n\n // search through the definitions to find a match\n for (var i = 0; i < color_defs.length; i++) {\n var re = color_defs[i].re;\n var processor = color_defs[i].process;\n var bits = re.exec(color_string);\n if (bits) {\n channels = processor(bits);\n this.r = channels[0];\n this.g = channels[1];\n this.b = channels[2];\n this.ok = true;\n }\n\n }\n\n // validate/cleanup values\n this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);\n this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);\n this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);\n}", "function rgb(r, g, b) {\n\tif (r > 255) {\n\t\tr = 255;\n\t}\n\tif (g > 255) {\n\t\tg = 255;\n\t}\n\tif (b > 255) {\n\t\tb = 255;\n\t}\n\tif (r < 0) {\n\t\tr = 0;\n\t}\n\tif (g < 0) {\n\t\tg = 0;\n\t}\n\tif (b < 0) {\n\t\tb = 0;\n\t}\n\tr = r.toString(16).toUpperCase();\n\tg = g.toString(16).toUpperCase();\n\tb = b.toString(16).toUpperCase();\n\tif (r.length < 2) {\n\t\tr = `0${r}`;\n\t}\n\tif (g.length < 2) {\n\t\tg = `0${g}`;\n\t}\n\tif (b.length < 2) {\n\t\tb = `0${b}`;\n\t}\n\treturn `${r}${g}${b}`;\n}", "function rgbColorScheme() {\r\n let red = randomNumber(25, 255);\r\n let green = randomNumber(25, 255);\r\n let blue = randomNumber(25, 255);\r\n return {r: red, g: green, b: blue};\r\n}", "function parseColor(str){\n\t\tvar result;\n\t\n\t\t/**\n\t\t * rgb(num,num,num)\n\t\t */\n\t\tif((result = /rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(str)))\n\t\t\treturn new Color(parseInt(result[1]), parseInt(result[2]), parseInt(result[3]));\n\t\n\t\t/**\n\t\t * rgba(num,num,num,num)\n\t\t */\n\t\tif((result = /rgba\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\s*\\)/.exec(str)))\n\t\t\treturn new Color(parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), parseFloat(result[4]));\n\t\t\t\n\t\t/**\n\t\t * rgb(num%,num%,num%)\n\t\t */\n\t\tif((result = /rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(str)))\n\t\t\treturn new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);\n\t\n\t\t/**\n\t\t * rgba(num%,num%,num%,num)\n\t\t */\n\t\tif((result = /rgba\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\s*\\)/.exec(str)))\n\t\t\treturn new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));\n\t\t\t\n\t\t/**\n\t\t * #a0b1c2\n\t\t */\n\t\tif((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)))\n\t\t\treturn new Color(parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16));\n\t\n\t\t/**\n\t\t * #fff\n\t\t */\n\t\tif((result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)))\n\t\t\treturn new Color(parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16));\n\n\t\t/**\n\t\t * Otherwise, we're most likely dealing with a named color.\n\t\t */\n\t\tvar name = str.strip().toLowerCase();\n\t\tif(name == 'transparent'){\n\t\t\treturn new Color(255, 255, 255, 0);\n\t\t}\n\t\tresult = lookupColors[name];\n\t\treturn new Color(result[0], result[1], result[2]);\n\t}", "get color() {}", "tag(){return\"simple-colors-shared-styles\"}", "function colour() {\n //let c = Math.random();\n //console.log(c);\n //c = c.toString(16)\n //console.log(c)\n return '#' + Math.random().toString(16).substring(2,8); //substring (2,8) \n}", "function calculateColor(value) {\n\tvar c = Math.round( 255 - ((value/globalSettingMax)*255) );\n\tvar color = \"rgb(255,\"+c+\",0)\";\n\treturn color;\n}", "function randomHardColor(redBase, greenBase, blueBase, range){\n\tvar red = getRangedNumber(redBase, range);\n var green = getRangedNumber(greenBase, range);\n var blue = getRangedNumber(blueBase, range);\n\n\treturn \"rgb(\" + red +\", \" + green + \", \"+ blue + \")\";\n\n}", "function colorValue() {\n return randomHex() + randomHex();\n}", "function randomColorGen(){\n // return `#${Math.floor(Math.random()*16777215).toString(16)}`;\n return \"#\" + Math.random().toString(16).slice(2, 8)\n}", "function getColorRGB(name) {\n\tvar nameLC = name.toLowerCase();\n\tvar leftIndex = 0;\n\tvar rightIndex = AllColorsRGB.length-1;\n\treturn getColorRGBSub(nameLC, leftIndex, rightIndex);\n}", "function randomColor(){\n //pick \"red\" from 0 -> 255\n let red = Math.floor(Math.random()*256);\n //pick \"green\" from 0 -> 255\n let green = Math.floor(Math.random()*256);\n //pick \"blue\" from 0 -> 255\n let blue = Math.floor(Math.random()*256);\n //construct string to match rgb format\n return \"rgb(\"+red+\", \"+green+\", \"+blue+\")\";\n}", "function fullColorString(clr, a) {\n return \"#\" + ((Math.ceil(a*255) + 256).toString(16).substr(1, 2) +\n clr.toString().substr(1, 6)).toUpperCase();\n}", "function Colour(){\n\n /* Returns an object representing the RGBA components of this Colour. The red,\n * green, and blue components are converted to integers in the range [0,255].\n * The alpha is a value in the range [0,1].\n */\n this.getIntegerRGB = function(){\n\n // get the RGB components of this colour\n var rgb = this.getRGB();\n\n // return the integer components\n return {\n 'r' : Math.round(rgb.r),\n 'g' : Math.round(rgb.g),\n 'b' : Math.round(rgb.b),\n 'a' : rgb.a\n };\n\n };\n\n /* Returns an object representing the RGBA components of this Colour. The red,\n * green, and blue components are converted to numbers in the range [0,100].\n * The alpha is a value in the range [0,1].\n */\n this.getPercentageRGB = function(){\n\n // get the RGB components of this colour\n var rgb = this.getRGB();\n\n // return the percentage components\n return {\n 'r' : 100 * rgb.r / 255,\n 'g' : 100 * rgb.g / 255,\n 'b' : 100 * rgb.b / 255,\n 'a' : rgb.a\n };\n\n };\n\n /* Returns a string representing this Colour as a CSS hexadecimal RGB colour\n * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB\n * are two-digit hexadecimal numbers.\n */\n this.getCSSHexadecimalRGB = function(){\n\n // get the integer RGB components\n var rgb = this.getIntegerRGB();\n\n // determine the hexadecimal equivalents\n var r16 = rgb.r.toString(16);\n var g16 = rgb.g.toString(16);\n var b16 = rgb.b.toString(16);\n\n // return the CSS RGB colour value\n return '#'\n + (r16.length == 2 ? r16 : '0' + r16)\n + (g16.length == 2 ? g16 : '0' + g16)\n + (b16.length == 2 ? b16 : '0' + b16);\n\n };\n\n /* Returns a string representing this Colour as a CSS integer RGB colour\n * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b\n * are integers in the range [0,255].\n */\n this.getCSSIntegerRGB = function(){\n\n // get the integer RGB components\n var rgb = this.getIntegerRGB();\n\n // return the CSS RGB colour value\n return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';\n\n };\n\n /* Returns a string representing this Colour as a CSS integer RGBA colour\n * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and\n * b are integers in the range [0,255] and a is in the range [0,1].\n */\n this.getCSSIntegerRGBA = function(){\n\n // get the integer RGB components\n var rgb = this.getIntegerRGB();\n\n // return the CSS integer RGBA colour value\n return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';\n\n };\n\n /* Returns a string representing this Colour as a CSS percentage RGB colour\n * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and\n * b are in the range [0,100].\n */\n this.getCSSPercentageRGB = function(){\n\n // get the percentage RGB components\n var rgb = this.getPercentageRGB();\n\n // return the CSS RGB colour value\n return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';\n\n };\n\n /* Returns a string representing this Colour as a CSS percentage RGBA colour\n * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,\n * and b are in the range [0,100] and a is in the range [0,1].\n */\n this.getCSSPercentageRGBA = function(){\n\n // get the percentage RGB components\n var rgb = this.getPercentageRGB();\n\n // return the CSS percentage RGBA colour value\n return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';\n\n };\n\n /* Returns a string representing this Colour as a CSS HSL colour value - that\n * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and\n * s and l are in the range [0,100].\n */\n this.getCSSHSL = function(){\n\n // get the HSL components\n var hsl = this.getHSL();\n\n // return the CSS HSL colour value\n return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';\n\n };\n\n /* Returns a string representing this Colour as a CSS HSLA colour value - that\n * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],\n * s and l are in the range [0,100], and a is in the range [0,1].\n */\n this.getCSSHSLA = function(){\n\n // get the HSL components\n var hsl = this.getHSL();\n\n // return the CSS HSL colour value\n return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';\n\n };\n\n /* Sets the colour of the specified node to this Colour. This functions sets\n * the CSS 'color' property for the node. The parameter is:\n *\n * node - the node whose colour should be set\n */\n this.setNodeColour = function(node){\n\n // set the colour of the node\n node.style.color = this.getCSSHexadecimalRGB();\n\n };\n\n /* Sets the background colour of the specified node to this Colour. This\n * functions sets the CSS 'background-color' property for the node. The\n * parameter is:\n *\n * node - the node whose background colour should be set\n */\n this.setNodeBackgroundColour = function(node){\n\n // set the background colour of the node\n node.style.backgroundColor = this.getCSSHexadecimalRGB();\n\n };\n\n}", "function getTextColor(r, g, b) {\n let tempTextColor = '#000000'\n if (r < 128 && g < 128 && b < 128) {\n tempTextColor = '#ffffff'\n }\n return tempTextColor;\n}", "function color_pick () {\n\tif (current_profile() == null)\n\t\treturn (\"#ffffff\");\n\telse if (current_profile() == \"bw\")\n\t\treturn (\"#ffffff\");\n\telse if (current_profile() == \"antique\")\n\t\treturn (\"#f4ecd9\");\n\telse if (current_profile() == \"blue\")\n\t\treturn (\"#eeeeff\");\n\telse if (current_profile() == \"gray\")\n\t\treturn (\"#eeeeee\");\n\telse if (current_profile() == \"white\")\n\t\treturn (\"#ffffff\");\n\telse if (current_profile() == \"low\")\n\t\treturn (\"#f9e2e3\");\n\telse\n\t\treturn (\"#ffffff\");\n\n}", "get color() {\n\n\t}", "function setColorValues () {\n // CONVERT RGB AND SET HEXIDECIMAL\n hex = rgbToHex(r, g, b);\n\n // CONVERT RGB AND SET HSL\n var hslvalues = rgbToHsl(r, g, b);\n h = hslvalues[0];\n s = hslvalues[1];\n l = hslvalues[2];\n}", "set ASTC_RGB_10x10(value) {}", "function color() {\n return colorValue() + colorValue() + colorValue();\n}", "constructor(white, red, green, blue) {\n this.white = white;\n this.red = red;\n this.green = green;\n this.blue = blue;\n }", "function create_colour() {\r\n return \"#\" + colour_val[getRandom(0, 15)]\r\n + colour_val[getRandom(0, 15)]\r\n + colour_val[getRandom(0, 15)]\r\n + colour_val[getRandom(0, 15)]\r\n + colour_val[getRandom(0, 15)]\r\n + colour_val[getRandom(0, 15)];\r\n}", "function getBGColor(num){\n switch (num) {\n case 2:return \"#eee4da\";break;\n case 4:return \"#ede0c8\";break;\n case 8:return \"#f2b179\";break;\n case 16:return \"#f59563\";break;\n case 32:return \"#f67c5f\";break;\n case 64:return \"#f65e3b\";break;\n case 128:return \"#edcf72\";break;\n case 256:return \"#edcc61\";break;\n case 512:return \"#9c0\";break;\n case 1024:return \"#33b5e5\";break;\n case 2048:return \"#09c\";break;\n case 4096:return \"#a6c\";break;\n case 8192:return \"#93c\";break;\n }\n }", "function GetCheerColorInfo(a){/* exported GetCheerColorInfo */var b=a,c=\"color\",d=\"style\",e=\"color\";return a.startsWith(\"bg-\")&&(b=a.substr(3),c=\"bgcolor\",d=\"wstyle\",e=\"background-color\"),ColorNames.hasOwnProperty(b)?[c,d,e,ColorNames[b]]:b.match(/^#[0-9a-f]{6}/i)?[c,d,e,b]:[null,null,null,null]}", "function backgroundColor() {\n return Math.floor(Math.random() * 256);\n}", "function getColor(num){\r\n\t\tcolor = \"\";\r\n\t\tswitch(num){\r\n\t\t\tcase 1: color = \"#009900\";break;\r\n\t\t\tcase 2:\tcolor = \"#0000FF\";break;\r\n\t\t\tcase 3: color = \"#9900CC\";break;\r\n\t\t\tcase 4:\tcolor = \"#66CCFF\";break;\r\n\t\t\tcase 5: color = \"#CC00FF\";break;\r\n\t\t\tcase 6: color = \"#CC0000\";break;\r\n\t\t\tcase 7: color = \"#FF9900\";break;\r\n\t\t\tcase 8: color = \"#CC0099\";break;\r\n\t\t\tcase 9: color = \"#660099\";break;\r\n\t\t\tcase 10: color = \"#330099\";break;\r\n\t\t\tcase 11: color = \"#006600\";break;\r\n\t\t\tcase 12: color = \"#993366\";break;\r\n\t\t\tcase 13: color = \"#FF0066\";break;\r\n\t\t\tcase 14: color = \"#FF0000\";break;\r\n\t\t\tcase 15: color = \"#FFEE00\";break;\r\n\r\n\t\t}\r\n\t\treturn color;\r\n}" ]
[ "0.6961668", "0.68916845", "0.6700817", "0.6678551", "0.66782284", "0.66608876", "0.6643742", "0.66131294", "0.66131294", "0.6605643", "0.6589712", "0.657579", "0.6565881", "0.65377825", "0.65377825", "0.6521719", "0.64915735", "0.6485219", "0.6475696", "0.6474047", "0.6474047", "0.6474047", "0.6474047", "0.6473719", "0.6467022", "0.6463803", "0.64552367", "0.64429", "0.6421247", "0.640658", "0.64019823", "0.63990754", "0.63772404", "0.6376425", "0.6366819", "0.63387275", "0.63387275", "0.6333692", "0.63296545", "0.63273084", "0.6324125", "0.6311193", "0.6308365", "0.6306817", "0.6293939", "0.62879324", "0.6283335", "0.62777823", "0.6255504", "0.62549144", "0.6251517", "0.6248698", "0.6242373", "0.6240857", "0.6225675", "0.62224543", "0.62221766", "0.62117153", "0.62029725", "0.619979", "0.61961895", "0.61934656", "0.6191333", "0.6188776", "0.61854476", "0.6181644", "0.61644953", "0.61529577", "0.61455774", "0.6137581", "0.6131123", "0.6124627", "0.6123443", "0.6121739", "0.61044115", "0.6100859", "0.60976505", "0.60964596", "0.60962427", "0.6092747", "0.6089668", "0.6086354", "0.60736287", "0.60706496", "0.60676754", "0.6062537", "0.6058218", "0.60570765", "0.60562927", "0.60540396", "0.60495806", "0.6047821", "0.603924", "0.6031649", "0.6029964", "0.6028261", "0.6027054", "0.6026468", "0.6023847", "0.6022473", "0.6018114" ]
0.0
-1
THEN YOU CAN CONSUME THE ABOVE REST ENDPOINT ON THE FRONTEND IN YOUR APP
function userRequest() { $.getJSON('/users/userlist', function (data) { // For each item in our JSON, do something like render some HTML to the DOM $.each(data, function () { // mock up some html }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function showEndpoint(response){\n}", "function homepage(req, res) {\n let url = `https://thesimpsonsquoteapi.glitch.me/quotes?count=10`\n\n superagent.get(url).set('User-Agent', '1.0').then(resp =>{\n\nres.render('./pages/index.ejs' , {data: resp.body});\n }).catch(err => console.log(err));\n}", "GET() {\n }", "function main_page(req, res, next) {\n\n \n const url = 'https://thesimpsonsquoteapi.glitch.me/quotes?count=10';\n \n superagent.get(url).set('User-Agent', '1.0').then(results=>{\n \n const data_list = results.body;\n\n let arr=[];\n\n arr = data_list.map(item=>{\n return new Data_obj(item);\n })\n\n res.render('home',{array:arr});\n }).catch(err=>{\n res.status(200).send(err);\n })\n\n\n // res.status(200).send('okkkk');\n // res.render('home');\n}", "function prepRest() {\n targetStr = \"&@target='\" + hostUrl + \"'\";\n baseUrl = appUrl + \"/_api/SP.AppContextSite(@target)/\";\n executor = new SP.RequestExecutor(appUrl);\n }", "async index({request, response}) {\r\n\r\n\t\t\r\n\t}", "function showQutes(request,response){\n const url = `https://thesimpsonsquoteapi.glitch.me/quotes?count=10`;\n superagent.get(url).set('User-Agent','1.0').then(data=>{\n const dataArr = data.body;\n response.render('home',{dataArr});\n });\n}", "function NousTrougerGet(req, res) {\n res.send('/api/noustrouver');\n}", "show(req, res) {\n logging.logTheinfo(\"widgets show Router\");\n res.status(200).send(\"show\");\n\n }", "function rendermain(){\n var Init = { method:'GET',headers:{'Access-Control-Allow-Origin':'*'},mode:'cors'};\n fetch(stackurl,Init)\n .then((resp) => resp.json())\n .then((data) => {\n renderpage(data)\n });\n}", "function mainPage() { //Fetch from Web service and get Json data with Fetch\n\n fetch(DATA.showUrl.url).then( (response)=> {//Response is Promise object\n return response.json();\n }).then(function (myJson) {\n const shows = DATA.createShow(myJson); //Create Shows\n UI.createMainPage(shows) //Append show to Page\n }).catch((myJsonError)=>{\n alert(\"Your request failed\",myJsonError);\n });\n }", "async function fetchMyAPI() {\t\t\n\t\tPromotionsService.getActivePromotions().then(\n\t\t\tresponse => {\n\t\t\t\tsetData(response);\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tif (error.response.status === 404) {\n\t\t\t\t\talert(`L'application nécessite une mise à jour`);\n\t\t\t\t} else {\n\t\t\t\t\talert(`Uho, il semblerait que notre serveur soit indisponible :(`);\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t}", "function getResourceUrl() { return \"http://\"+location.href.split(\"//\")[1].split(\"/\").splice(0,3).join(\"/\")+'.json?api_key='+MoviePilot.apikey;}", "async function App( res) {\r\n\r\n\r\n axios.get(' http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=' + process.env.ARTICLES_API)\r\n .then(response => {\r\n res.send(response.data)\r\n })\r\n\r\n .catch(error => {\r\n console.log(error);\r\n });\r\n\r\n\r\n}", "function route() {\n if (getUrlParam(\"photo\")) {\n loadPhotoCardBasedOnUrl();\n }\n else {\n loadPhotosBasedOnUrl();\n }\n }", "function GET(){\n \n}", "function showHome(request){\n request.serveFile(\"index.html\"); \n}", "function showHome(request){\n\trequest.respond(\"This is the home page.\");\n}", "function render(url) {\n\n /**\n * Get request keyword from url\n * @type {string}\n */\n const request = url.split('/')[0];\n\n get(\"loading-status\").update(\"Organizando as informações...\");\n\n const routes = {\n\n /**\n * Home\n */\n '': function () {\n /**\n * App Page element\n * @type {Element}\n */\n let page = new Element({\n properties: {\n id: \"app\",\n className: \"\"\n }\n });\n\n /**\n * Page Header\n */\n new Element({\n type: \"header\",\n properties: {\n className: \"app-header\"\n },\n content: [\n new Element({\n type: \"h1\",\n content: \"Busca Marvel\",\n properties: {\n className: \"app-title\"\n }\n }),\n new Element({\n type: \"h2\",\n content: \"Teste front-end\",\n properties: {\n className: \"app-subtitle\"\n }\n }),\n new Element({\n type: \"h3\",\n content: \"Paulo Cézar Francisco Júnior\",\n properties: {\n className: \"app-developer hide-on-mobile\"\n }\n })\n ]\n }, page);\n\n /**\n * Detail\n */\n new Element({\n properties: {\n className: \"app-line\"\n },\n content: new Element\n }, page);\n\n /**\n * Search box\n */\n new Element({\n type: \"section\",\n properties: {\n id: \"search-container\",\n placeholder: \"Pesquisar\"\n },\n content: [\n new Element({\n type: \"label\",\n content: \"Nome do Personagem\",\n properties: {\n htmlFor: \"search-box\",\n className: \"app-search-label\"\n }\n }),\n new Element({\n type: \"input\",\n properties: {\n id: \"search-box\",\n className: \"app-search-box\",\n title: \"Digite o nome de um herói da Marvel\",\n placeholder: \"ex. Iron Man\",\n oninput: function(){\n filterList();\n }\n }\n }),\n ]\n }, page);\n\n /**\n * Heroes List\n */\n new Element({\n type: \"section\",\n properties: {\n className: \"app-hero-list\",\n },\n content: [\n new Element({\n properties: {\n className: \"app-hero-list-header\",\n },\n content: [\n new Element({\n content: \"Nome\"\n }),\n new Element({\n content: \"Séries\",\n properties: {\n className: \"hide-on-mobile\"\n }\n }),\n new Element({\n content: \"Eventos\",\n properties: {\n className: \"hide-on-mobile\"\n }\n })\n ]\n }),\n new Element({\n properties: {\n id: \"hero-list\",\n className: \"app-hero-list-rows\",\n },\n content: goPage(1, HERO_LIST, true)\n }),\n ]\n }, page);\n\n new Element({\n properties: {\n id: \"pagination-container\",\n className: \"app-pagination-container row-4\",\n },\n type: \"section\",\n content: [\n new Element({\n properties: {\n className: \"app-pagination\"\n },\n content: [\n new Element({\n type: \"span\",\n content: \"&#9664;\",\n properties: {\n className: \"disabled\",\n id: \"app-pagination-prev\",\n onclick: function () {\n goPage(prevPage());\n }\n }\n }),\n new Element({\n type: \"ul\",\n properties: {\n id: \"pagination-list\"\n },\n content: [\n new Element({\n type: \"li\",\n content: \"1\",\n properties: {\n className: \"app-pagination-page active\",\n onclick: function () {\n goPage(1);\n }\n }\n })\n ]\n }),\n new Element({\n type: \"span\",\n content: \"&#9654;\",\n properties: {\n className: \"disabled\",\n id: \"app-pagination-next\",\n onclick: function () {\n goPage(nextPage());\n }\n }\n })\n ]\n })\n ]\n }, page);\n\n new Element({\n properties: {\n id: \"footer\",\n },\n type: \"footer\",\n content: [\n new Element({\n type: \"span\",\n properties: {\n id: \"copyright\"\n },\n content: HERO_DATA.copyright\n })\n ]\n }, page);\n\n ROOT.update(page, function(){\n trigger(\"list-updated\");\n });\n },\n\n /**\n * Detail page\n */\n '#hero': function () {\n\n /**\n * App Page element\n * @type {Element}\n */\n let page = new Element({\n properties: {\n id: \"app\",\n className: \"detail\"\n }\n });\n\n /**\n * Get the hero name\n * @type {string}\n */\n let idHero = url.split('#hero/')[1].trim();\n\n let hero = HERO_LIST.find(function (h) {\n if(parseInt(h.id) === parseInt(idHero)){\n return h;\n }\n });\n\n let series = [\n new Element({\n properties: {\n className: \"detail-block\"\n },\n content: [\n new Element({\n type: \"header\",\n properties: {\n className: \"detail-block-header\"\n },\n content: \"Não há dados para exibir nesta categoria.\"\n })\n ]\n })\n ];\n\n let events = [\n new Element({\n properties: {\n className: \"detail-block\"\n },\n content: [\n new Element({\n type: \"header\",\n properties: {\n className: \"detail-block-header\"\n },\n content: \"Não há dados para exibir nesta categoria.\"\n })\n ]\n })\n ];\n\n if(hero.series.returned > 0){\n\n /**\n * Fetch (more) information about series\n */\n series = hero.series.items.map(function(s){\n idSerie = \"detail-serie-\" + s.resourceURI.toString().split(\"/\").slice(-1).toString().trim();\n\n setTimeout(function(){\n fetch(s.resourceURI.toString().replace(\"http://\", \"https://\") + \"?apikey=5e8ca1959f7f23db54436ae4b3661243\").then(r => r.json()).then(function(json){\n let data = json.data.results[0];\n get(\"detail-serie-\" + data.id).update(new Element({\n properties: {\n className: \"detail-card\"\n },\n content: [\n new Element({\n properties: {\n className: \"detail-card-description\"\n },\n content: data.description || \"Sem descrição.\"\n }),\n new Element({\n type: \"a\",\n properties: {\n className: \"detail-card-link\",\n href: data.urls[0].url,\n target: \"_blank\",\n title: \"Veja mais no site da MARVEL\"\n },\n content: \"&#9654; Veja mais em MARVEL.com\"\n }),\n new Element({\n properties: {\n className: \"detail-card-properties\"\n },\n content: [\n new Element({\n content: [\n \"Creators:\",\n data.creators.items.map(function(c){\n return c.name;\n }).join(\", \")\n ].join(\" \").trim()\n })\n ]\n }),\n ]\n }));\n }).catch(function(err){\n get(idSerie).update(\"Desculpe, não foi possível obter dados da MARVEL.\");\n console.error(err);\n });\n }, 300);\n\n return new Element({\n properties: {\n className: \"detail-block\"\n },\n content: [\n new Element({\n type: \"header\",\n properties: {\n className: \"detail-block-header\"\n },\n content: s.name\n }),\n new Element({\n type: \"section\",\n properties: {\n className: \"detail-block-content\",\n id: idSerie,\n style: {\n textAlign: \"center\"\n }\n },\n content: [\n new Element({\n className: \"detail-loading\",\n type: \"img\",\n properties: {\n src: \"img/loading.gif\",\n alt: \"Obtendo dados...\",\n height: \"40\",\n width: \"40\"\n }\n }),\n ]\n })\n ]\n });\n });\n }\n\n if(hero.events.returned > 0){\n\n /**\n * Fetch (more) information about events\n */\n events = hero.events.items.map(function(s){\n idEvent = \"detail-event-\" + s.resourceURI.toString().split(\"/\").slice(-1).toString().trim();\n\n setTimeout(function(){\n fetch(s.resourceURI.toString().replace(\"http://\", \"https://\") + \"?apikey=5e8ca1959f7f23db54436ae4b3661243\").then(r => r.json()).then(function(json){\n let data = json.data.results[0];\n console.log(data);\n get(\"detail-event-\" + data.id).update(new Element({\n properties: {\n className: \"detail-card\"\n },\n content: [\n new Element({\n properties: {\n className: \"detail-card-description\"\n },\n content: data.description || \"Sem descrição.\"\n }),\n new Element({\n properties: {\n className: \"detail-card-properties\"\n },\n content: [\n new Element({\n content: [\n \"Criadores:\",\n data.creators.items.map(function(c){\n return c.name;\n }).join(\", \")\n ].join(\" \").trim()\n })\n ]\n }),\n ]\n }));\n }).catch(function(err){\n get(idSerie).update(\"Desculpe, não foi possível obter dados da MARVEL.\");\n console.error(err);\n });\n }, 300);\n\n return new Element({\n properties: {\n className: \"detail-block\"\n },\n content: [\n new Element({\n type: \"header\",\n properties: {\n className: \"detail-block-header\"\n },\n content: s.name\n }),\n new Element({\n type: \"section\",\n properties: {\n className: \"detail-block-content\",\n id: idEvent\n },\n content: [\n new Element({\n className: \"detail-loading\",\n type: \"img\",\n properties: {\n src: \"img/loading.gif\",\n alt: \"Obtendo dados...\",\n height: \"40\",\n width: \"40\",\n style: {\n display: \"block\",\n margin: \"10px auto\",\n }\n }\n }),\n ]\n })\n ]\n });\n });\n }\n\n /**\n * Back home link\n */\n new Element({\n type: \"a\",\n properties: {\n onclick: function(){\n window.location.hash = \"\";\n },\n id: \"back-home\",\n title: \"Voltar à busca\"\n },\n content: \"&#9664;\"\n }, page);\n\n /**\n * Page Header\n */\n new Element({\n type: \"header\",\n properties: {\n id: \"detail-header\",\n className: \"app-header\"\n },\n content: [\n new Element({\n content: [\n new Element({\n id: \"detail-img\",\n type: \"img\",\n properties: {\n src: (['path', 'extension'].map(p => hero.thumbnail[p])).join(\".\").replace(\"http://\", \"https://\"),\n alt: hero.name,\n height: \"180\",\n width: \"180\"\n }\n }),\n new Element({\n type: \"h1\",\n content: hero.name,\n properties: {\n className: \"app-title\"\n }\n }),\n ]\n }),\n new Element({\n type: \"h3\",\n content: HERO_DATA.copyright,\n properties: {\n className: \"detail-logo hide-on-mobile\"\n }\n })\n ]\n }, page);\n\n new Element({\n properties: {\n id: \"detail-content\",\n },\n type: \"section\",\n content: [\n new Element({\n type: \"section\",\n properties: {\n className: \"detail-content-section\"\n },\n content: [\n new Element({\n type: \"header\",\n content: \"Séries\"\n }),\n new Element({\n type: \"section\",\n content: series\n })\n ]\n }),\n new Element({\n type: \"section\",\n properties: {\n className: \"detail-content-section\"\n },\n content: [\n new Element({\n type: \"header\",\n content: \"Eventos\"\n }),\n new Element({\n type: \"section\",\n content: events\n })\n ]\n })\n ]\n }, page);\n\n /**\n * Footer\n */\n new Element({\n properties:{\n id: \"detail-footer\"\n },\n content: [\n new Element({\n content: HERO_DATA.attributionText\n }),\n new Element({\n content: \"PAULO CÉZAR FRANCISCO JÚNIOR\"\n })\n ]\n }, page);\n\n ROOT.update(page);\n }\n };\n\n /**\n * Load the page requested\n */\n if (routes[request]) {\n get(\"loading-status\").addClass(\"hidden\");\n routes[request]();\n }\n /**\n * If the request is not registered, load main page\n */\n else {\n window.location.hash = \"\";\n }\n}", "async index({ request, response, view }) {\n }", "index(req, res) {\n\t\tres.status(200).send({status: 'live'})\n\t}", "function start() {\n\n id = realtimeUtils.getParam('id');\n if (id) {\n // Load the document id from the URL\n realtimeUtils.load(id.replace('/', ''), onFileLoaded, onInitialize);\n init();\n } else {\n // Create a new document, add it to the URL\n realtimeUtils.createRealtimeFile('MyWebb App', function (createResponse) {\n window.history.pushState(null, null, '?id=' + createResponse.id);\n id=createResponse.id;\n realtimeUtils.load(createResponse.id, onFileLoaded, onInitialize);\n init();\n });\n \n }\n \n \n }", "get feed(){\n return fbpage+\"/feed\";\n }", "function getFromApiAndRender(req, res) {\n const url = 'https://thesimpsonsquoteapi.glitch.me/quotes?count=10'\n superagent.get(url).set('User-Agent', '1.0').then(results => {\n const quotesApi = results.body.map(obj => new Quote(obj))\n // console.log(quotes);\n res.render('pages/index', {quotes:quotesApi })\n\n })\n // const quotesApi = results.map(obj => new Quote(obj))\n // res.render('pages/index', {quotes: quotesApi})\n \n}", "async index ({ request, response, view }) {\n }", "async index ({ request, response, view }) {\n }", "async index ({ request, response, view }) {\n }", "async index ({ request, response, view }) {\n }", "function loadingPage(req, res, next) {\n console.log(\"GET '/'\");\n res.render('index');\n}", "function getPath(req, res, next) {\n\tvar client = new Client();\t \n\tclient.get(\"http://DoSComputev2.mybluemix.net/api/dummy\", function (data, response) {\n\t console.log(response);\n\t\tres.render('process', data);\n\t});\n}", "function rootRes(req,res,next) { res.json({\"status\" : \"running\"}); return next()}", "onRoute (info) {\n openApi.addRoute(info, {\n basePath: env.REST_API_PREFIX\n })\n }", "feed() {\n const key = this.io.getSessionKey();\n\n this.whenAuthenticated('/', (key, user) =>\n this.render(Feed, {\n user: user,\n edit: () => this.io.navigate('/a/edit/'),\n newTab: () => this.io.navigate('/tabs/new/'),\n getPage: (page, done) =>\n this.logs.frontpage(key, page, {\n success: done,\n error: () => done([])\n }),\n }));\n }", "prefetch() {\n if (!this.p || true) return; // Prefetch the JSON page if asked (only in the client)\n\n const {\n pathname\n } = window.location;\n const {\n href: parsedHref\n } = this.formatUrls(this.props.href, this.props.as);\n const href = (0, _url.resolve)(pathname, parsedHref);\n\n _router.default.prefetch(href);\n }", "prefetch() {\n if (!this.p || true) return; // Prefetch the JSON page if asked (only in the client)\n\n const {\n pathname\n } = window.location;\n const {\n href: parsedHref\n } = this.formatUrls(this.props.href, this.props.as);\n const href = (0, _url.resolve)(pathname, parsedHref);\n\n _router.default.prefetch(href);\n }", "function api(req, res, next) {\n // TODO parse the path and things\n console.log('Referrer! And things', req._parsedUrl.pathname);\n next();\n}", "function handleAPILoaded() {\n requestPlaylist();\n}", "function homePage(req,res) {\r\n superagent.get('https://digimon-api.herokuapp.com/api/digimon')\r\n .then((data)=>{\r\n let allDigimon = data.body.map((val)=>{\r\n return new Digimon(val);\r\n })\r\n res.render('digimonExam/index', {results:allDigimon});\r\n }).catch((err)=>errorHandler(err,req,res));\r\n}", "async home() {\n const resp = await api.get(`/home`)\n\n return resp\n }", "prefetch() {\n if (!this.p || true) return; // Prefetch the JSON page if asked (only in the client)\n\n var {\n pathname\n } = window.location;\n var {\n href: parsedHref\n } = this.formatUrls(this.props.href, this.props.as);\n var href = (0, _url.resolve)(pathname, parsedHref);\n\n _router.default.prefetch(href);\n }", "prefetch() {\n if (!this.p || true) return; // Prefetch the JSON page if asked (only in the client)\n\n var {\n pathname\n } = window.location;\n var {\n href: parsedHref\n } = this.formatUrls(this.props.href, this.props.as);\n var href = (0, _url.resolve)(pathname, parsedHref);\n\n _router.default.prefetch(href);\n }", "async function hentData() {\n const respons = await fetch(link);\n products = await respons.json();\n vis(products);\n}", "function ping_the_rest() {\n this._pinger.addNodes(this._nodesToPing.map(a => a.url), false, \"app_init.check_latency_feedback_rest\");\n\n this._pinger.pingNodes(this._callback);\n }", "function route(...etc)\n{\n etc.unshift(stockAPI);\n let sOut = etc.reduce((acc, curr)=>acc+=curr+'/');\n return sOut;\n}", "function doGet(e) {\n // do whatever this webapp is for\n var result = doSomeStuff(e); \n // prepare the result\n var s = JSON.stringify(result);\n // publish result\n return ContentService\n .createTextOutput(result.params.callback ? result.params.callback + \"(\" + s + \")\" : s )\n .setMimeType(result.params.callback ? ContentService.MimeType.JAVASCRIPT : ContentService.MimeType.JSON); \n}", "function goToURL() {\n location.href = 'http://127.0.0.1:8000/apps/reservoir-management/sabana-yegua/';\n}", "function startAPIRequests()\t{\n // Get app configuration.\n loadConfig().then(() => {\n // -> Get save data.\n afterConfigLoaded();\n loadVideoInformation().then(() => {\n // -> start requesting subs.\n requestSubs();\n });\n });\n}", "_request() {\n var options = url.parse(this._url);\n options.headers = {\n 'User-Agent': 'Benjamin Tambourine',\n 'If-None-Match': this._etag\n };\n https.get(options, this._onResponse.bind(this));\n }", "function API(){}", "function API(){}", "fetchSuppliers(){\r\n return Api().get('/suppliers')\r\n }", "function getAllDrinksHandler(req,res){\nlet url =`https://www.thecocktaildb.com/api/json/v1/1/filter.php?a=Non_Alcoholic`;\nsuperagent.get(url).then((response)=>{\nres.send(response.body.drinks);\n})\n.catch((err)=>{\nres.status(500).send('there is error',err\n)})\n\n}", "getAPI(request, response) {\n let message = {};\n message.name = 'implementation pending';\n message.version = 'implementation pending';\n return response.jsonp(message);\n }", "async show({ params, request, response, view }) {}", "function deliverWebPage(req, res){\n p_renderPage(req, res, 'Create a Service Object...');\n }", "async loadProducts() {\n try {\n this.moreBtn.innerHTML = \"Carregando...\"\n const response = await axios.get(`https://frontend-intern-challenge-api.iurykrieger.now.sh/products?page=${this.pageNumber}`)\n const { products } = response.data\n this.render(products)\n this.pageNumber++\n } catch (err) {\n console.warn('Não foi possível acessar a api')\n }\n this.moreBtn.innerHTML = \"Ainda mais produtos aqui!\"\n }", "landingPage() {\n this.app.get(\"/\", (req, res) => {\n // console.log(`request.body: `, req.body);\n // Basic route that sends the user first to the Landing Page\n res.sendFile(path.join(__dirname, \"landingPage.html\"));\n })\n }", "function getQuotesformAPI(req, res) {\n const url = 'https://thesimpsonsquoteapi.glitch.me/quotes?count=10';\n superagent.get(url).set('User-Agent', '1.0').then(results => {\n //console.log(results.body);\n const quotes = results.body.map(quote => {\n return new Quote(quote);\n });\n res.render('index', { quotes: quotes });\n }).catch(error => {\n console.error(error);\n });\n}", "static getInitialData({ match, req, res }) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve({\n article: `\nThis text is ALSO server rendered if and only if it's the initial render.\n `,\n currentRoute: match.pathname,\n });\n }, 500);\n });\n }", "async ReTableAl() {\n const reqOpts = {\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\"\n },\n method: \"GET\", \n }; \n let resp = await fetch('http://localhost:5000/OtherTaAl', reqOpts); \n let response = await resp.json();\n return response;\n }", "servePing() {\n if (this.uibRouter === undefined) throw new Error('this.uibRouter is undefined')\n\n this.uibRouter.get('/ping', (req, res) => {\n res.status(204).end()\n })\n this.routers.user.push( { name: 'Ping', path: `${this.uib.httpRoot}/uibuilder/ping`, desc: 'Ping/keep-alive endpoint, returns 201', type: 'Endpoint' } )\n }", "async getPublicContent() {\n // return axios.get(API_URL);\n const response = await fetch(`${API_URL}`, {\n method: \"GET\" // requires NO authorization header\n });\n if (response.ok) {\n let data = await response.json();\n // console.log(\"USER SERVICE - fetch WELCOMING MESSAGE\")\n // console.log(data) // data = \"Welcome to the TUTORIALS api\"\n return data;\n }\n else\n throw Error(handleResponses(response.status));\n }", "show(id, query_params = {}) {\n const query = Object(_api__WEBPACK_IMPORTED_MODULE_5__[\"toQueryString\"])(query_params);\n const key = `show|${id}|${query}`;\n const services = ['guests', 'events'];\n const serviceName = this.api_route;\n if (!this._promises[key]) {\n this._promises[key] = new Promise((resolve, reject) => {\n const url = `${this.route()}/${id}${query ? '?' + query : ''}`;\n let result = null;\n //resolve(this.process({\"name\":\"shamir\",\"email\":\"[email protected]\",\"phone\":\"0556257959\",\"organisation\":\"Nuevezo\",\"notes\":\"great guy\",\"checked_in\":false,\"visit_expected\":true,\"extension_data\":{\"whatever\":\"you want\",\"perferred_coffee\":\"Flat white, skim milk, one sugar\"}}))\n if (!services.includes(serviceName)) {\n Object(_placeos_ts_client__WEBPACK_IMPORTED_MODULE_2__[\"get\"])(url).subscribe((d) => {\n console.log(d);\n result = this.process(d);\n }, (e) => {\n reject(e);\n this._promises[key] = null;\n }, () => {\n resolve(result);\n this.timeout(key, () => (this._promises[key] = null), 1000);\n });\n }\n else {\n if (serviceName === 'guests') {\n Object(_placeos_ts_client__WEBPACK_IMPORTED_MODULE_2__[\"post\"])('http://localhost:3000/visitorcheck', {\n email: id,\n }).subscribe((d) => {\n if (d === null) {\n result = null;\n }\n else {\n result = this.process(d);\n }\n }, (e) => {\n reject(e);\n this._promises[key] = null;\n }, () => {\n resolve(result);\n this.timeout(key, () => (this._promises[key] = null), 1000);\n });\n }\n else if (serviceName === 'events') {\n resolve(this.process({\n id: 'aqmkadawatnizmyazc1jntuams1knzljltawai0wmaoargaaa5drsxwsq85fn',\n status: 'accepted',\n host: 'rishabh.awa@email',\n hostphone: '055443322',\n attendees: [\n {\n name: 'shamir',\n email: '[email protected]',\n },\n ],\n title: 'name of the meeting',\n body: 'event details',\n private: false,\n date: 1609851180,\n event_start: 1609851180,\n event_end: 1614662400,\n timezone: 'Sydney',\n all_day: false,\n location: 'clear text location',\n recurring: true,\n recurrence: {\n range_start: 12345,\n range_end: 23456,\n days_of_week: 4,\n interval: 2,\n pattern: 1,\n },\n extension_data: { whatever: 'you want' },\n }));\n //1609853180\n }\n }\n });\n }\n return this._promises[key];\n }", "getSiteImage() {\n var hostname = window.location.hostname;\n var hostAddress = \"http://\" + hostname + \":8081\"\n return this.$http.get(hostAddress+\"/dashboard/sites?context=Plant\")\n .then(response => {\n return response.data.list;\n });\n }", "function onGetResponse(err, res) {\n removePreloader();\n\n if(err) {\n showAlert(err, 'error-msg');\n return;\n }\n\n if(!res.articles.length) {\n // show empty message\n return;\n }\n renderNews(res.articles);\n}", "requestFrontend(url) {\n\n return new Promise((resolve, reject) => {\n\n let request = new XMLHttpRequest(url);\n request.open(\"GET\", url, true);\n\n request.onload = () => {\n if (request.readyState == 4 && request.status == 200) {\n resolve(request.responseText);\n } else {\n reject(\"error\")\n console.warn(\"requesting frontend failed\", this)\n }\n }\n request.send();\n })\n }", "function myHouse() {\n var ourRequest = new XMLHttpRequest();\n ourRequest.open('GET', 'http://localhost:8080/realestate/all');\n ourRequest.send();\n ourRequest.onload = function () {\n const ourData = JSON.parse(ourRequest.responseText);\n myHome(ourData);\n };\n\n}", "async show({ params, request, response, view }) {\n }", "function getProducts() {\n loadingSpinner(1)\n return fetch(`${apiUrl}/api/cameras`)\n .then(res => {\n loadingSpinner(0)\n if (res.status === 200) {\n return res.json()\n } else {\n serverOffline()\n return 0\n }\n })\n .catch(err => {\n console.error(err)\n alert(\n \"La connexion au serveur semble être plus longue que d' habitude. Le serveur hébergeant l' API est entré en sommeil, veuillez patienter puis réactualisez la page !\"\n );\n });\n}", "load(url, object, app) {\n url = /api/ + url;\n\n const router = express.Router();\n\n const controller = new object(router);\n\n app.use(url, router);\n \n }", "function flow() {\n var Flow = window.Flow;\n var ko = window.ko;\n var H2O = window.H2O;\n var $ = window.jQuery;\n var getContextPath = function getContextPath() {\n window.Flow.ContextPath = '/';\n return $.ajax({\n url: window.referrer,\n type: 'GET',\n success: function success(data, status, xhr) {\n if (xhr.getAllResponseHeaders().indexOf('X-h2o-context-path') !== -1) {\n window.Flow.ContextPath = xhr.getResponseHeader('X-h2o-context-path');\n return window.Flow.ContextPath;\n }\n },\n\n async: false\n });\n };\n var checkSparklingWater = function checkSparklingWater(context) {\n context.onSparklingWater = false;\n return $.ajax({\n url: window.Flow.ContextPath + '3/Metadata/endpoints',\n type: 'GET',\n dataType: 'json',\n success: function success(response) {\n var route = void 0;\n var _i = void 0;\n var _len = void 0;\n var _ref = response.routes;\n var _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n route = _ref[_i];\n if (route.url_pattern === '/3/scalaint') {\n _results.push(context.onSparklingWater = true);\n } else {\n _results.push(void 0);\n }\n }\n return _results;\n },\n\n async: false\n });\n };\n if ((typeof window !== 'undefined' && window !== null ? window.$ : void 0) != null) {\n $(function () {\n var context = {};\n getContextPath();\n checkSparklingWater(context);\n window.flow = flowApplication(context, H2O.Routines);\n h2oApplication(context);\n ko.applyBindings(window.flow);\n context.ready();\n return context.initialized();\n });\n }\n }", "function init() {\n // var promise = WebsiteService.findAllWebsitesForUser(userId);\n // promise\n // .success(function(websites) {\n // vm.websites = websites;\n // })\n // var url = \"https://bgg-json.azurewebsites.net/hot\";\n // $http.get(url)\n // .success(function(result) {\n // vm.games = result;\n // });\n\n }", "getview() {\n return apiClient.get(`films/view`)\n }", "productsPage(req) {\n return __awaiter(this, void 0, void 0, function* () {\n });\n }", "function getProducts() {\n\n $.get(\"/api/products\", function (data) {\n displayProducts(data);\n });\n }", "function responseHandler (app) {\n let ingr = req.query.food;\n request('https://api.edamam.com/api/food-database/parser?app_id=1f42d8bb&app_key=8ca5e6822e9abfd927289b214749ae7d&ingr=' + ingr, function (error, response, body) {\n body = JSON.parse(body);\n console.log('body', body);\n if (_.isEmpty(body.hints)) {\n console.log('could not find the nutrition values for the given food item, please try with different name');\n } else {\n\n console.log('body has data');\n }\n app.tell('response', response);\n app.tell('error', error);\n //console.log('hello');\n //res_body = body.hints;\n //res.send(res_body);\n // console.log('error:', error); // Print the error if one occurred\n // console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received\n // console.log('body:', body); // Print the HTML for the Google homepage.\n // app.tell(response);\n // app.tell(error);\n });\n\n }", "fetchContent() {\n Axios.jsonp(\n `${CONTENT_PATH}${startIndex_param}${startIndex}&${count_param}${count}`\n )\n .then(res => {\n this.setContent(res);\n\n this.fetchComments(res);\n })\n .catch(err => {\n console.log(err);\n });\n }", "static defaultEndpoint(req : $Request, res : $Response) {\n res.json({\n version: '1.0',\n });\n }", "all(){\nreturn this.post(Config.API_URL + Constant.REFFERAL_ALL);\n}", "function onRequest(request, response){\n var pathName = url.parse(request.url).pathname\n //console.log(pathName);\n showPage(response, pathName);\n}", "async function artdecoWebsite() {\n console.log('@artdeco/website called');\n}", "function getData(requestUrl) {\n \n\n}", "init() {\n this.router.get(\"/\", (req, res, next) => {\n res.status(200).json(this._service.defaultMethod());\n });\n }", "constructor() {\n this.baseUrl = 'http://localhost:9000/api/expenses'\n }", "async function getData() {\n let daten = new FormData(document.forms[0]);\n query = new URLSearchParams(daten);\n // url = \"https://gissose2021.herokuapp.com\"; //herokuapnpm p link einfügen als url variable \n url = \"http://localhost:8100\";\n url += \"/getData\";\n url = url + \"?\" + query.toString(); //Url in String umwandeln\n let response = await fetch(url); //auf url warten\n let responseText = await response.text(); //json okject erstellen\n serverResponse.innerHTML = responseText;\n }", "function Action()\n{\n\tweb.url(\n\t\t{\n\t\t\t\t\t\tname : 'www.elcorteingles.es', \n\t\t\turl : 'http://www.elcorteingles.es/', \n\t\t\ttargetFrame : '', \n\t\t\tresource : 0, \n\t\t\trecContentType : 'text/html', \n\t\t\treferer : '', \n\t\t\tsnapshot : 't1.inf', \n\t\t\tmode : 'HTML', \n\t\t\textraRes : [\n\t\t\t\t{url : '/sgfm/SGFM/assets/stylesheets/fonts/opensans-regular-webfont.woff', referer : 'http://www.elcorteingles.es/sgfm/SGFM/assets/stylesheets/crs.css'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/stylesheets/fonts/opensans-bold-webfont.woff', referer : 'http://www.elcorteingles.es/sgfm/SGFM/assets/stylesheets/crs.css'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/stylesheets/fonts/moonshine-font.woff', referer : 'http://www.elcorteingles.es/sgfm/SGFM/assets/stylesheets/crs.css'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/javascripts/library/external/dust-helpers.min.js'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/stylesheets/fonts/lato-regular-webfont.woff', referer : 'http://www.elcorteingles.es/sgfm/SGFM/assets/stylesheets/crs.css'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/javascripts/library/external/dust-core.min.js'},\n\t\t\t\t{url : 'http://www.googletagmanager.com/gtm.js?id=GTM-TMQVMD'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/javascripts/compiled/templates.js'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/javascripts/library/external/form2js.min.js'},\n\t\t\t\t{url : '/sgfm/SGFM/assets/stylesheets/images/confianza-online-icon.svg', referer : 'http://www.elcorteingles.es/sgfm/SGFM/assets/stylesheets/crs.css'}\n\t\t\t]\n\t\t}\n\t);\n\n\treturn 0;\n}", "index(req,res) {\n res.json({\n msg: \"Hello Ninjutsu World!\",\n });\n }", "function index(req, res) {\n \n}", "static show(cityId){\n return fetch(`${url}/${cityId}`)\n .then((response)=> response.json())\n .catch((err)=>{\n console.log(err)\n })\n \n }", "async function getApi(){ // async function uses await for response.\n console.log('getApi');\n const response = await fetch('/api', options ); // first promise received\n const data = await response.json(); // processing json triggers seconde promise\n // Open panomaker in new tab.\n console.log(\"response: \", data);\n }", "getApiResult(data) {\n this.flaskURL = this.flaskURL + data;\n console.log(this.flaskURL);\n return this._http.get(this.flaskURL, { responseType: 'text' });\n }", "function handleAPILoaded() {\n requestUserPlaylistId();\n}", "function handleAPILoaded()\n{\n requestSubscriptionList();\n}", "getMovies() {\n authClient.get('https://myflix-2388-app.herokuapp.com/movies')\n .then(response => {\n this.props.setMovies(response.data);\n })\n .catch(function (error) {\n console.log(error);\n });\n }", "function pageHome(request, response) {\r\n response.send('<h1>Welcome to Phonebook</h1>')\r\n}", "function start() {\n console.log(\"entro a strart\");\n $http.get('http://' + vm.localhost + ':3000/getCategoria/').then(function (response) {\n console.log(response.data);\n $scope.vm.getCategoria = response.data;\n });\n \n }", "async function routes(fastify, options) {\n\tfastify.get('/', async (request, reply) => {\n\t\treturn { name: 'Hydrant API', version: process.env.npm_package_version, routes: 'api' }\n\t})\n\n\tfastify.get('/measurement', (request, reply) => {\n\t\tconst $top = request.query.top;\n\t\tif ($top)\n\t\t\tdb.all('SELECT * FROM Measurements LIMIT $top', { $top }, (err, rows) => {\n\t\t\t\treply.send(rows);\n\t\t\t});\n\t\telse\n\t\t\tdb.all('SELECT * FROM Measurements', (err, rows) => {\n\t\t\t\treply.send(rows);\n\t\t\t})\n\t});\n}", "function getProduct(id) {\n console.log(\"view product was clicked\");\n\n axios\n .get(\"http://localhost:8080/products/\" + id)\n\n .then(response => {\n body.innerHTML = generateResponse(response, \"single\");\n console.log(response.data);\n });\n}", "async show ({ params, request, response, view }) {\n }", "async show ({ params, request, response, view }) {\n }", "async show ({ params, request, response, view }) {\n }" ]
[ "0.6349256", "0.62948835", "0.620569", "0.61175245", "0.6066087", "0.60186315", "0.59338164", "0.59224004", "0.5835331", "0.5821035", "0.58198047", "0.58032036", "0.5780124", "0.57164294", "0.57122374", "0.5694852", "0.56575316", "0.56528956", "0.56261426", "0.56086445", "0.55966645", "0.559393", "0.5580089", "0.5571275", "0.55709475", "0.55709475", "0.55709475", "0.55709475", "0.55594134", "0.5549823", "0.5548278", "0.55395675", "0.5535407", "0.5526959", "0.5526959", "0.5524231", "0.55138904", "0.55087304", "0.5488396", "0.54775834", "0.54775834", "0.547528", "0.5473428", "0.5467125", "0.5465973", "0.5462196", "0.54611564", "0.5458275", "0.545279", "0.545279", "0.54471135", "0.5444465", "0.5442621", "0.542482", "0.5424057", "0.54221904", "0.5421356", "0.5417689", "0.5406477", "0.54044867", "0.54003304", "0.53998333", "0.5393208", "0.5387282", "0.5384819", "0.5369508", "0.536241", "0.53524005", "0.53446156", "0.53422827", "0.53355914", "0.5333282", "0.5326055", "0.53209734", "0.5316672", "0.53144974", "0.5310259", "0.5306966", "0.53060144", "0.5304011", "0.5301249", "0.52987075", "0.5298251", "0.5297589", "0.529614", "0.52956825", "0.5289373", "0.5285023", "0.5284697", "0.5276679", "0.5272103", "0.5271869", "0.52650243", "0.52626705", "0.5259904", "0.5259191", "0.5256644", "0.52527124", "0.5252408", "0.5252408", "0.5252408" ]
0.0
-1
The purpose of mixins is to take one object and mix in the functionalities of another object jquery has its own $.extend() method that is used for the puspose of mixing functionalities
function extend(target){ //target is the target object to which we want to //add the functionalities of other objects to //extend() when invoked should take multiple //parameters...the first param is the target //object and the params starting from index 1 // are the mixin objects //if there are no mixin objects return nothing. if(!arguments[1]){ return; } for(var i = 1; i < arguments.length; i++){ //source is an object var source = arguments[i]; //loop through source for(prop in source){ //if the property doesnt exist on the target object //and the property is the source object's own property //and not on its prototype...the assign the property to target if(!target[prop] && source.hasOwnProperty(prop)){ target[prop] = source[prop]; } } } console.log(source); console.log(target); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Mixin() {}", "function _extend()\n {\n // copy reference to target object\n var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy, copyIsArray;\n\n // Handle a deep copy situation\n if ( typeof target === \"boolean\" ) \n {\n deep = target;\n target = arguments[1] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== \"object\" && !_isFunction(target)) \n {\n target = {};\n }\n\n // extend jQuery itself if only one argument is passed\n if ( length === i ) \n {\n target = MCR;\n --i;\n }\n\n for ( ; i < length; i++ ) \n {\n // Only deal with non-null/undefined values\n if ( (options = arguments[i]) != null ) \n {\n // Extend the base object\n for ( name in options ) \n {\n src = target[ name ];\n copy = options[ name ];\n\n // Prevent never-ending loop\n if ( target === copy ) \n {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n var clone;\n if ( deep && copy && ( _isPlainObject(copy) || (copyIsArray = _isArray(copy)) ) ) \n {\n if ( copyIsArray ) \n {\n copyIsArray = false;\n clone = src && _isArray(src) ? src : [];\n\n } \n else \n {\n clone = src && _isPlainObject(src) ? src : {};\n }\n\n // Never move original objects, clone them\n target[ name ] = _extend( deep, clone, copy );\n\n // Don't bring in undefined values\n }\n else if ( copy !== undefined ) \n {\n target[ name ] = copy;\n }\n }\n }\n }\n\n // Return the modified object\n return target;\n }", "function Mixin() {\n\t}", "function jQueryExtend() {\n var options, name, src, copy, copyIsArray, clone,\n target = arguments[0] || {},\n i = 1,\n length = arguments.length,\n deep = false;\n\n // Handle a deep copy situation\n if ( typeof target === \"boolean\" ) {\n deep = target;\n target = arguments[1] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== \"object\" && GetType(target) != 'function') {\n target = {};\n }\n\n // extend jQuery itself if only one argument is passed\n if ( length === i ) {\n target = this;\n --i;\n }\n\n for ( ; i < length; i++ ) {\n // Only deal with non-null/undefined values\n if ( (options = arguments[ i ]) != null ) {\n // Extend the base object\n for ( name in options ) {\n src = target[ name ];\n copy = options[ name ];\n\n // Prevent never-ending loop\n if ( target === copy ) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {\n if ( copyIsArray ) {\n copyIsArray = false;\n clone = src && jQuery.isArray(src) ? src : [];\n } else {\n clone = src && jQuery.isPlainObject(src) ? src : {};\n }\n\n // Never move original objects, clone them\n target[ name ] = jQuery.extend( deep, clone, copy );\n\n // Don't bring in undefined values\n } else if ( copy !== undefined ) {\n target[ name ] = copy;\n }\n }\n }\n }\n\n // Return the modified object\n return target;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = underscore[name] = obj[name];\n underscore.prototype[name] = function() {\n var args = [this._wrapped];\n _setup.push.apply(args, arguments);\n return _chainResult(this, func.apply(underscore, args));\n };\n });\n return underscore;\n}", "function mixin(target,...source){\n Object.assign(target,...source)\n}", "function performMixins(){for(var i=0;i<mixins.length;i+=2){mixin(mixins[i],mixins[i+1]);}mixins.length=0;}", "function mixins(...args) {\n return external_Vue_default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixins() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ mixins: args });\n}", "function mixin(obj) {\n each(functions(obj), function (name) {\n console.log('name', name);\n var func = (_[name] = obj[name]);\n _.prototype[name] = function () {\n //把方法挂到原型链上\n var args = [this._wrapped]; //['京城一灯']\n push.apply(args, arguments); //['京城一灯',回调函数]\n console.log(\"合并之后的args\", arguments);\n return func.apply(_, args)\n };\n });\n }", "function mixins() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"].extend({\n mixins: args\n });\n}", "function mixin(dest, src) {\n\t if (type(src) == 'function') {\n\t extend(dest, src.prototype)\n\t }\n\t else {\n\t extend(dest, src)\n\t }\n\t}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixins() {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({\n mixins: args\n });\n}", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixin(obj) {\n each(functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return chainResult(this, func.apply(_, args));\n };\n });\n return _;\n }", "function mixins_mixins(...args) {\n return external_commonjs_vue_commonjs2_vue_root_Vue_default.a.extend({\n mixins: args\n });\n}", "function extendJQuery() {\n jQuery.extend(Object.create(null, {\n 'alert': { value: alert, configurable: true, enumerable: true, writable: true },\n 'confirm': { value: createShowShorthand('success', 'S011'), configurable: true, enumerable: true, writable: true, },\n 'notice': { value: createShowShorthand('info'), configurable: true, enumerable: true, writable: true, },\n 'warn': { value: createShowShorthand('warning', 'S012'), configurable: true, enumerable: true, writable: true, },\n 'alarm': { value: createShowShorthand('error', 'S013'), configurable: true, enumerable: true, writable: true, },\n }));\n }", "function mixin(target, ...source){\n Object.assign(target,...source)\n}", "function mixins_mixins(...args) {\n return vue_runtime_esm[\"a\" /* default */].extend({\n mixins: args\n });\n}", "function mixin( /* objects */ ) {\n var mixed = {};\n for (var arg of arguments) {\n for (var name of Object.getOwnPropertyNames(arg)) {\n var desc = Object.getOwnPropertyDescriptor(arg, name);\n Object.defineProperty(mixed, name, desc);\n }\n }\n return mixed;\n }", "function mixins(...args) {\n return external_commonjs_vue_commonjs2_vue_root_Vue_default.a.extend({\n mixins: args\n });\n}", "function mixins(...args) {\n return external_commonjs_vue_commonjs2_vue_root_Vue_default.a.extend({\n mixins: args\n });\n}", "function mixin(target, source) {\n source = source || {};\n Object.keys(source).forEach(function(key) {\n target[key] = source[key];\n });\n\n return target;\n}", "function mixin(target, source) {\n for (var key in source) {\n target[key] = source[key]\n }\n return target\n}", "function __extend__(a,b) {\n\tfor ( var i in b ) {\n\t\tvar g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);\n\t\tif ( g || s ) {\n\t\t\tif ( g ) a.__defineGetter__(i, g);\n\t\t\tif ( s ) a.__defineSetter__(i, s);\n\t\t} else\n\t\t\ta[i] = b[i];\n\t} return a;\n}", "function __extend__(a,b) {\n\tfor ( var i in b ) {\n\t\tvar g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);\n\t\tif ( g || s ) {\n\t\t\tif ( g ) a.__defineGetter__(i, g);\n\t\t\tif ( s ) a.__defineSetter__(i, s);\n\t\t} else\n\t\t\ta[i] = b[i];\n\t} return a;\n}", "extend() {}", "extend() {}", "function mixin(targetObj, ...sources) {\n Object.assign(targetObj, ...sources);\n}", "function $extend(destiny, source) {\r\n\t\tif (!$defined(destiny) || !$defined(source)) return destiny;\r\n\t\tfor (var prop in source) {\r\n\t\t\tif (destiny.prototype) destiny.prototype[prop] = source[prop];\r\n\t\t\telse destiny[prop] = source[prop];\r\n\t\t}\r\n\t\treturn destiny;\r\n\t}", "function mixin( sourceObj, targetObj ) {\n\t for (var key in sourceObj) {\n\t // only copy if not already present\n\t if (!(key in targetObj)) {\n\t targetObj[key] = sourceObj[key];\n\t }\n\t }\n\n\t return targetObj;\n\t}", "function Mixin() {\n this.mixins = [];\n this.properties = {};\n}", "function mixin(e,t,i,r){return t&&eachProp(t,function(t,n){(i||!hasProp(e,n))&&(!r||\"object\"!=typeof t||!t||isArray(t)||isFunction(t)||t instanceof RegExp?e[n]=t:(e[n]||(e[n]={}),mixin(e[n],t,i,r)))}),e}//Similar to Function.prototype.bind, but the 'this' object is specified", "function mixins(...args) {\n return vue__WEBPACK_IMPORTED_MODULE_0__.default.extend({\n mixins: args\n });\n}", "function extend(a,b){for(var prop in b){a[prop]=b[prop];}return a;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions || {};for(key in src) {if(src[key] !== undefined){(flatOptions[key]?target:deep || (deep = {}))[key] = src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function mixin(ctor,methods){var keyCopier=function keyCopier(key){ctor.prototype[key]=methods[key];};Object.keys(methods).forEach(keyCopier);Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(methods).forEach(keyCopier);return ctor;}", "function mixin(ctor,methods){var keyCopier=function keyCopier(key){ctor.prototype[key]=methods[key];};Object.keys(methods).forEach(keyCopier);Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(methods).forEach(keyCopier);return ctor;}", "function mixin(ctor,methods){var keyCopier=function keyCopier(key){ctor.prototype[key]=methods[key];};Object.keys(methods).forEach(keyCopier);Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(methods).forEach(keyCopier);return ctor;}", "function mixin (target, ...sources){\n Object.assign(target, ...sources); //... here is the spread operator. ie to spread array element got from rest operator\n\n}", "function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}}", "function safeMixin(target, source){\n\t\t// summary:\n\t\t//\t\tMix in properties skipping a constructor and decorating functions\n\t\t//\t\tlike it is done by declare().\n\t\t// target: Object\n\t\t//\t\tTarget object to accept new properties.\n\t\t// source: Object\n\t\t//\t\tSource object for new properties.\n\t\t// description:\n\t\t//\t\tThis function is used to mix in properties like lang.mixin does,\n\t\t//\t\tbut it skips a constructor property and decorates functions like\n\t\t//\t\tdeclare() does.\n\t\t//\n\t\t//\t\tIt is meant to be used with classes and objects produced with\n\t\t//\t\tdeclare. Functions mixed in with dojo.safeMixin can use\n\t\t//\t\tthis.inherited() like normal methods.\n\t\t//\n\t\t//\t\tThis function is used to implement extend() method of a constructor\n\t\t//\t\tproduced with declare().\n\t\t//\n\t\t// example:\n\t\t//\t|\tvar A = declare(null, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tconsole.log(\"A.m1\");\n\t\t//\t|\t\t},\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tconsole.log(\"A.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tvar B = declare(A, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"B.m1\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tB.extend({\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"B.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tvar x = new B();\n\t\t//\t|\tdojo.safeMixin(x, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"X.m1\");\n\t\t//\t|\t\t},\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"X.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tx.m2();\n\t\t//\t|\t// prints:\n\t\t//\t|\t// A.m1\n\t\t//\t|\t// B.m1\n\t\t//\t|\t// X.m1\n\n\t\tvar name, t;\n\t\t// add props adding metadata for incoming functions skipping a constructor\n\t\tfor(name in source){\n\t\t\tt = source[name];\n\t\t\tif((t !== op[name] || !(name in op)) && name != cname){\n\t\t\t\tif(opts.call(t) == \"[object Function]\"){\n\t\t\t\t\t// non-trivial function method => attach its name\n\t\t\t\t\tt.nom = name;\n\t\t\t\t}\n\t\t\t\ttarget[name] = t;\n\t\t\t}\n\t\t}\n\t\tif(has(\"bug-for-in-skips-shadowed\")){\n\t\t\tfor(var extraNames= lang._extraNames, i= extraNames.length; i;){\n\t\t\t\tname = extraNames[--i];\n\t\t\t\tt = source[name];\n\t\t\t\tif((t !== op[name] || !(name in op)) && name != cname){\n\t\t\t\t\tif(opts.call(t) == \"[object Function]\"){\n\t\t\t\t\t\t// non-trivial function method => attach its name\n\t\t\t\t\t\t t.nom = name;\n\t\t\t\t\t}\n\t\t\t\t\ttarget[name] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t}", "function safeMixin(target, source){\n\t\t// summary:\n\t\t//\t\tMix in properties skipping a constructor and decorating functions\n\t\t//\t\tlike it is done by declare().\n\t\t// target: Object\n\t\t//\t\tTarget object to accept new properties.\n\t\t// source: Object\n\t\t//\t\tSource object for new properties.\n\t\t// description:\n\t\t//\t\tThis function is used to mix in properties like lang.mixin does,\n\t\t//\t\tbut it skips a constructor property and decorates functions like\n\t\t//\t\tdeclare() does.\n\t\t//\n\t\t//\t\tIt is meant to be used with classes and objects produced with\n\t\t//\t\tdeclare. Functions mixed in with dojo.safeMixin can use\n\t\t//\t\tthis.inherited() like normal methods.\n\t\t//\n\t\t//\t\tThis function is used to implement extend() method of a constructor\n\t\t//\t\tproduced with declare().\n\t\t//\n\t\t// example:\n\t\t//\t|\tvar A = declare(null, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tconsole.log(\"A.m1\");\n\t\t//\t|\t\t},\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tconsole.log(\"A.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tvar B = declare(A, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"B.m1\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tB.extend({\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"B.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tvar x = new B();\n\t\t//\t|\tdojo.safeMixin(x, {\n\t\t//\t|\t\tm1: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"X.m1\");\n\t\t//\t|\t\t},\n\t\t//\t|\t\tm2: function(){\n\t\t//\t|\t\t\tthis.inherited(arguments);\n\t\t//\t|\t\t\tconsole.log(\"X.m2\");\n\t\t//\t|\t\t}\n\t\t//\t|\t});\n\t\t//\t|\tx.m2();\n\t\t//\t|\t// prints:\n\t\t//\t|\t// A.m1\n\t\t//\t|\t// B.m1\n\t\t//\t|\t// X.m1\n\n\t\tvar name, t;\n\t\t// add props adding metadata for incoming functions skipping a constructor\n\t\tfor(name in source){\n\t\t\tt = source[name];\n\t\t\tif((t !== op[name] || !(name in op)) && name != cname){\n\t\t\t\tif(opts.call(t) == \"[object Function]\"){\n\t\t\t\t\t// non-trivial function method => attach its name\n\t\t\t\t\tt.nom = name;\n\t\t\t\t}\n\t\t\t\ttarget[name] = t;\n\t\t\t}\n\t\t}\n\t\tif(has(\"bug-for-in-skips-shadowed\")){\n\t\t\tfor(var extraNames= lang._extraNames, i= extraNames.length; i;){\n\t\t\t\tname = extraNames[--i];\n\t\t\t\tt = source[name];\n\t\t\t\tif((t !== op[name] || !(name in op)) && name != cname){\n\t\t\t\t\tif(opts.call(t) == \"[object Function]\"){\n\t\t\t\t\t\t// non-trivial function method => attach its name\n\t\t\t\t\t\t t.nom = name;\n\t\t\t\t\t}\n\t\t\t\t\ttarget[name] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t}", "function ajaxExtend(target,src){var deep,key,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function ajaxExtend(target,src){var deep,key,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}", "function $merge(){\r\n var mix = {};\r\n for (var i = 0; i < arguments.length; i++) {\r\n for (var property in arguments[i]) {\r\n var ap = arguments[i][property];\r\n var mp = mix[property];\r\n if (mp && $type(ap) == 'object' && $type(mp) == 'object') \r\n mix[property] = $merge(mp, ap);\r\n else \r\n mix[property] = ap;\r\n }\r\n }\r\n return mix;\r\n }", "function extend( a, b ) {\n for ( var prop in b ) {\n a[ prop ] = b[ prop ];\n }\n return a;\n }", "function mixInto(obj, mix) {\n for (var prop in mix) {\n obj[prop] = mix[prop];\n }\n}", "function extend( a, b ) {\r\n for ( var prop in b ) {\r\n a[ prop ] = b[ prop ];\r\n }\r\n return a;\r\n }", "function mixinObjs(objs, target) {\n objs.forEach(mixin, target);\n return target;\n }", "function mixin(){\n\tvar __slice = [].slice;\n\tvar consumer = arguments[0],\n\t\tproviders = __slice.call(arguments, 1),\n\t\tkey,\n\t\tprovider;\n\tfor(var i = 0; i < providers.length; i++){\n\t\tprovider = providers[i];\n\t\tfor(key in provider.prototype){\n\t\t\tif(provider.prototype.hasOwnProperty(key)){\n\t\t\t\tconsumer.prototype[key] = provider.prototype[key];\n\t\t\t}\n\t\t}\n\t}\n\treturn consumer;\n}", "function _mixin(t, items, skip) {\n \n // copy reference to target object\n var len = items.length,\n target = t || {},\n idx, options, key, src, copy;\n\n for (idx=skip; idx < len; idx++ ) {\n if (!(options = items[idx])) continue ;\n for(key in options) {\n if (!options.hasOwnProperty(key)) continue ;\n\n src = target[key];\n copy = options[key] ;\n if (target===copy) continue ; // prevent never-ending loop\n if (copy !== undefined) target[key] = copy ;\n }\n }\n \n return target;\n}", "function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}", "function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}", "function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}", "function mixin(inObj/*, inProps, inMoreProps, ...*/) {\n var obj = inObj || {};\n for (var i = 1; i < arguments.length; i++) {\n var p = arguments[i];\n try {\n for (var n in p) {\n copyProperty(n, p, obj);\n }\n } catch(x) {\n }\n }\n return obj;\n }", "function numberMixin(obj)\n{\n obj.printNumber = function()\n {\n console.log(this.number);\n }\n}", "function extend(a, b) {\n for (var prop in b) {\n a[prop] = b[prop];\n }\n return a;\n }", "function extend( a, b ) {\n for ( var prop in b ) {\n a[ prop ] = b[ prop ];\n }\n return a;\n }", "function extend( a, b ) {\n for ( var prop in b ) {\n a[ prop ] = b[ prop ];\n }\n return a;\n }", "function extend(a, b) {\n for (var prop in b) {\n a[ prop ] = b[ prop ];\n }\n return a;\n }", "function extend( a, b ) {\n\t for ( var prop in b ) {\n\t a[ prop ] = b[ prop ];\n\t }\n\t return a;\n\t}", "function extend() {\n // copy reference to target object\n var target = arguments[0] || {},\n i = 1,\n length = arguments.length,\n deep = false,\n options,\n name,\n src,\n copy;\n\n // Handle a deep copy situation\n if (typeof target === \"boolean\") {\n deep = target;\n target = arguments[1] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if (typeof target !== \"object\" && !typeof target === 'function')\n target = {};\n\n var isPlainObject = function(obj) {\n // Must be an Object.\n // Because of IE, we also have to check the presence of the constructor\n // property.\n // Make sure that DOM nodes and window objects don't pass through, as well\n if (!obj || toString.call(obj) !== \"[object Object]\" || obj.nodeType\n || obj.setInterval)\n return false;\n\n var has_own_constructor = hasOwnProperty.call(obj, \"constructor\");\n var has_is_prop_of_method = hasOwnProperty.call(obj.constructor.prototype,\n \"isPrototypeOf\");\n // Not own constructor property must be Object\n if (obj.constructor && !has_own_constructor && !has_is_prop_of_method)\n return false;\n\n // Own properties are enumerated firstly, so to speed up,\n // if last one is own, then all properties are own.\n\n var last_key;\n for (var key in obj)\n last_key = key;\n\n return last_key === undefined || hasOwnProperty.call(obj, last_key);\n };\n\n\n for (; i < length; i++) {\n // Only deal with non-null/undefined values\n if ((options = arguments[i]) !== null) {\n // Extend the base object\n for (name in options) {\n src = target[name];\n copy = options[name];\n\n // Prevent never-ending loop\n if (target === copy)\n continue;\n\n // Recurse if we're merging object literal values or arrays\n if (deep && copy && (isPlainObject(copy) || Array.isArray(copy))) {\n var clone = src && (isPlainObject(src) || Array.isArray(src)\n ? src : (Array.isArray(copy) ? [] : {}));\n\n // Never move original objects, clone them\n target[name] = extend(deep, clone, copy);\n\n // Don't bring in undefined values\n } else if (copy !== undefined)\n target[name] = copy;\n }\n }\n }\n\n // Return the modified object\n return target;\n}", "function extend() {\n // copy reference to target object\n var target = arguments[0] || {},\n i = 1,\n length = arguments.length,\n deep = false,\n options,\n name,\n src,\n copy;\n\n // Handle a deep copy situation\n if (typeof target === \"boolean\") {\n deep = target;\n target = arguments[1] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if (typeof target !== \"object\" && !typeof target === 'function')\n target = {};\n\n var isPlainObject = function(obj) {\n // Must be an Object.\n // Because of IE, we also have to check the presence of the constructor\n // property.\n // Make sure that DOM nodes and window objects don't pass through, as well\n if (!obj || toString.call(obj) !== \"[object Object]\" || obj.nodeType\n || obj.setInterval)\n return false;\n\n var has_own_constructor = hasOwnProperty.call(obj, \"constructor\");\n var has_is_prop_of_method = hasOwnProperty.call(obj.constructor.prototype,\n \"isPrototypeOf\");\n // Not own constructor property must be Object\n if (obj.constructor && !has_own_constructor && !has_is_prop_of_method)\n return false;\n\n // Own properties are enumerated firstly, so to speed up,\n // if last one is own, then all properties are own.\n\n var last_key;\n for (var key in obj)\n last_key = key;\n\n return last_key === undefined || hasOwnProperty.call(obj, last_key);\n };\n\n\n for (; i < length; i++) {\n // Only deal with non-null/undefined values\n if ((options = arguments[i]) !== null) {\n // Extend the base object\n for (name in options) {\n src = target[name];\n copy = options[name];\n\n // Prevent never-ending loop\n if (target === copy)\n continue;\n\n // Recurse if we're merging object literal values or arrays\n if (deep && copy && (isPlainObject(copy) || Array.isArray(copy))) {\n var clone = src && (isPlainObject(src) || Array.isArray(src)\n ? src : (Array.isArray(copy) ? [] : {}));\n\n // Never move original objects, clone them\n target[name] = extend(deep, clone, copy);\n\n // Don't bring in undefined values\n } else if (copy !== undefined)\n target[name] = copy;\n }\n }\n }\n\n // Return the modified object\n return target;\n}", "function extend(a, b) {\n for (var prop in b) {\n a[prop] = b[prop];\n }\n return a;\n }", "function mixin(inObj/*, inProps, inMoreProps, ...*/) {\n var obj = inObj || {};\n for (var i = 1; i < arguments.length; i++) {\n var p = arguments[i];\n try {\n for (var n in p) {\n copyProperty(n, p, obj);\n }\n } catch(x) {\n }\n }\n return obj;\n}", "static mixInto (Constructor) {\n const target = Constructor.prototype || Constructor\n const mixin = LifeCycle.prototype\n for (let prop of Object.getOwnPropertyNames(mixin)) {\n target[prop] = mixin[prop]\n }\n }", "function extend( a, b ) {\n for ( var prop in b ) {\n a[ prop ] = b[ prop ];\n }\n return a;\n }", "function mixInto(object, mixIn){\n\t forEachIn(mixIn, function(propertyName, value){\n\t object[propertyName] = value;\n\t });\n\t}", "function extend(a, b) {\r\n for (var prop in b) {\r\n a[prop] = b[prop];\r\n }\r\n return a;\r\n }", "function extend(target) {\n\t\t\tfor(var i = 1; i < arguments.length; i++) {\n\t\t\t\ttarget = _mergeProperties(target, arguments[i]);\n\t\t\t}\n\t\t\n\t\t\treturn target;\n\t\t}", "function mixin(target, source) {\r\n var i, len, element, item;\r\n\r\n if (isArray(target) && isArray(source)) {\r\n len = source.length;\r\n\r\n for (i = 0; i < len; ++i) {\r\n element = source[i];\r\n\r\n if (!inArray(element, target)) {\r\n target.push(element);\r\n }\r\n }\r\n } else {\r\n for (item in source) {\r\n if (source.hasOwnProperty(item)) {\r\n if (isObject(target[item])) {\r\n target[item] = mixin(target[item], source[item]);\r\n } else {\r\n target[item] = source[item];\r\n }\r\n }\r\n }\r\n }\r\n return target;\r\n }", "function _extend( target /*[, source]...*/ ) {\n\t\tfor( var i=1; i<arguments.length; i++ ) {\n\t\t\tif( arguments[i] instanceof Object ) {\n\t\t\t\tfor( var key in arguments[i] ) {\n\t\t\t\t\ttarget[key] = arguments[i][key];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t}", "function extend(a, b) {\n for (var prop in b) {\n a[prop] = b[prop];\n }\n return a;\n }", "static mixInto (Constructor) {\n const target = Constructor.prototype || Constructor;\n const mixin = LifeCycle.prototype;\n for (let prop of Object.getOwnPropertyNames(mixin)) {\n target[prop] = mixin[prop];\n }\n }", "function extend(a, b) {\n for (var prop in b) {\n a[prop] = b[prop];\n }\n return a;\n }", "function extend(a, b) {\n for (var prop in b) {\n a[prop] = b[prop];\n }\n return a;\n }" ]
[ "0.71583384", "0.69417536", "0.69385594", "0.68285346", "0.6706275", "0.6662885", "0.6653502", "0.6639317", "0.6616183", "0.6616183", "0.6616183", "0.6616183", "0.6616183", "0.6616183", "0.66160655", "0.6604702", "0.6592668", "0.65924734", "0.65924734", "0.65924734", "0.65924734", "0.65924734", "0.65924734", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6585248", "0.6549814", "0.6504064", "0.64656895", "0.6428029", "0.6420918", "0.63934183", "0.63934183", "0.63613445", "0.63569194", "0.6317067", "0.6317067", "0.63055205", "0.63055205", "0.6303837", "0.62432593", "0.6216704", "0.6210579", "0.6199948", "0.6193388", "0.6186183", "0.61454177", "0.6133647", "0.6133647", "0.6133647", "0.6133647", "0.6133647", "0.6133647", "0.61301637", "0.61301637", "0.61301637", "0.61237824", "0.61072797", "0.6104706", "0.6104706", "0.609925", "0.609925", "0.60852295", "0.6076068", "0.6009735", "0.598964", "0.5988542", "0.59814847", "0.5958233", "0.59512436", "0.59512436", "0.59512436", "0.5951046", "0.59356344", "0.59338564", "0.59322524", "0.59322524", "0.5929322", "0.59260356", "0.59259343", "0.59259343", "0.5924858", "0.59244215", "0.5919968", "0.5918771", "0.58988076", "0.5892057", "0.5877153", "0.58697295", "0.5864093", "0.5855276", "0.5855276", "0.5855276", "0.58513886" ]
0.6564246
32
Recursively finds the biggest decimal odd that is smaller than num
function findNearestLadderKey(startIndex, endIndex, num) { var middleIndex = startIndex + Math.ceil((endIndex - startIndex)/2); if((middleIndex === 0 && ladderKeys[middleIndex] > num) || (middleIndex === ladderKeys.length - 1 && ladderKeys[middleIndex] < num) || (ladderKeys[middleIndex] < num && num < ladderKeys[middleIndex + 1])) { return ladderKeys[middleIndex]; } else { if(ladderKeys[middleIndex] < num) { return findNearestLadderKey(middleIndex, endIndex, num); } else { return findNearestLadderKey(startIndex, middleIndex-1, num); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function nextBigger(n){\n let arr = n.toString().split(\"\") // creates string from number and splits it to an array\n let num = -1\n for (let i = arr.length-1; i >0; i--) { // sets up loop to look for the moment when the digit to the right if \"i\" is larger than \"i\"\n if (arr[i] > arr[i-1]) {\n num = i-1\n break // ends the loop once the digit is found\n }\n }\n if (num == -1) { // can't find the digits, so return the original number\n return num\n }\n}", "function stupidNextHighest(num) {\n var arr = num.toString().split('');\n\n if (arr.length === 1) {\n return \"No results.\"\n }\n if (arr.length === 2 && arr[0] >= arr[1]) {\n return \"No results.\"\n }\n while (true) {\n num++;\n // console.log(num);\n var temp = num.toString().split('');\n if (arr.length != temp.length) {\n return \"No results.\"\n }\n if (matchingDigits(temp, arr)) {\n return temp.join('');\n }\n }\n}", "function nextBigger(num){\n if(num < 10){\n \treturn -1;\n }\n // always start from the ones position and switch it with the tens\n var number = num.toString().split('')\n for(var i = number.length-1; i >= 0; i--){\n \tif(number[i] > number[i-1]){\n \t\tvar temp = number[i-1];\n \t\tnumber[i-1] = number[i];\n \t\tnumber[i] = temp;\n \t\tbreak;\n \t} else {\n \t\tcontinue;\n \t}\n }\n number = JSON.parse(number.join(''));\n if(number > num){\n \treturn number;\n } else {\n \treturn -1;\n }\n}", "function greatestDicisor(x, y) {\n if (x <= y) {\n var pom = x;\n }else{\n pom = y;\n }\n for (var i = pom; i > 0; i--) {\n if (x % i === 0 && y % i === 0) {\n return i\n }\n } \n}", "calcClosestPowerOf2Gt(num) {\n \tvar curExp = 0;\n \n while (Math.pow(2, curExp) < num) {\n curExp = curExp + 1;\n }\n \n return (Math.pow(2, curExp));\n \n }", "function generalizedGCD(num, arr) {\n\t// WRITE YOUR CODE HERE\n\tif (num == null || num === 0) return false;\n\tif (arr == null || arr.length === 0) return false;\n\n\t//no need to run the rest\n\tif (num === 1) {\n\t\treturn 1;\n\t}\n\n\tlet result = 1; // min GCD\n\tlet isFind = false;\n\tlet div = 2; //first test\n\n\twhile (div <= num) {\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tif (arr[i] % div === 0) {\n\t\t\t\tisFind = true;\n\t\t\t} else {\n\t\t\t\tisFind = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (isFind) {\n\t\t\tresult = div;\n\t\t}\n\t\tdiv++;\n\t}\n\n\treturn result;\n}", "function biggestdivisor (n) {\n\tvar divisor = 2;\n\tvar number = n;\n\n\twhile ( number > 1) { //when reaches biggest factor, number will be 0;\n\t\tif ( number % divisor == 0 ) {\n\t\t\tnumber /= divisor;\n\t\t\tdivisor--;//Try this factor again...\n\t\t}\n\t\tdivisor++;\n\t}\n\treturn divisor;\n}", "function bgstdivisorskp2 (n) {\n\tvar number = n, divisor,sqrt;\n\n\twhile ( number % 2 == 0 ) { \n\t\tnumber /= 2;\n\t}\n\n\tif (number < 1) return 2;\n\n\tdivisor = 3;\n\tsqrt = Math.sqrt(n);\n\twhile ( number > 1 && divisor < sqrt ) { //when reaches biggest factor, number will be 0;\n\t\tif ( number % divisor == 0 ) {\n\t\t\tnumber /= divisor;\n\t\t\tdivisor -= 2;//Try this factor again...\n\t\t}\n\t\tdivisor += 2; //Skip over even numbers\n\t}\n\treturn divisor;\n}", "function wholeNumberify(num) {\n if (Math.abs(Math.round(num) - num) < EPSILON_HIGH) {\n num = Math.round(num);\n }\n return num;\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 largestPrimeFactor(num) {\n var i = 2,\n primes = [];\n\n //if num is prime, return num\n if (isPrime(num)) {\n return num;\n }\n\n //recursivly return next prime until at lowest point.\n while (i < num) {\n if (num % i === 0) {\n return largestPrimeFactor(num / i);\n }\n i += 1;\n }\n}", "function greatestDivisor(x, y) {\n \n if (x <= y) {\n var res = x;\n }else{\n res = y;\n }\n for (var i = res; i > 0; i--) {\n if (x % i === 0 && y % i === 0) {\n return i\n }\n } \n}", "function minNumberOfStepsToGenerateNumber(num) {\n let q = [1];\n let numOfSteps = 0;\n while (q.length > 0) {\n let len = q.length;\n numOfSteps++;\n for (let i = 0; i < len; i++) {\n let curr = q.shift();\n let multipliedByTwo = curr * 2;\n let dividedByTree = Math.floor(curr / 3);\n if (multipliedByTwo === num || dividedByTree === num) {\n return numOfSteps;\n }\n q.push(multipliedByTwo);\n if (dividedByTree > 0) q.push(dividedByTree);\n }\n }\n return numOfSteps;\n}", "function largestPrimeNumOf(n) {\n\n let prime = 1;\n upperBoundary = n\n\n while(true) {\n prime = smallestPrimeOf(upperBoundary);\n if(prime < upperBoundary) {\n upperBoundary /= prime;\n }\n else {\n return upperBoundary\n }\n\n }\n\n}", "function largestPrime(n){\n // initiate at 2 because 2 is the lowest prime\n var i = 2;\n // keep checking up to the number passed in\n while(i < n){\n // while the number is divisible by a number between 2 and n, keep dividing\n while(n % i === 0){\n n = parseInt(n/i);\n }\n // increment\n i++;\n }\n // when number is not divisible by any number between 2 and the number, return the number\n return n;\n}", "function digital_root(num) {\n while (num >= 10){\n num = digital_root_helper(num);\n }\n\n return num;\n}", "function largestPrimeFactor(number) {\n var divider = 2;\n while (divider !== number && divider * divider <= number) {\n if (number % divider === 0) {\n number /= divider;\n } else {\n divider++;\n }\n }\n\n return number;\n}", "function main(n) {\n\n\t//Biggest possible number that is a multiple of 2 n digit numbers\n\tvar checkNum = Math.pow((Math.pow(10, n) - 1), 2);\n\t//Smallest possible number that is a multiple of 2 n digit numbers\n\tvar smallest = Math.pow((Math.pow(10, n - 1)), 2);\n\n\twhile(checkNum >= smallest) {\n\t\twhile(!isPalNum(checkNum)) {\n\t\t\tcheckNum--;\n\t\t}\n\n\t\tvar div = findMiddleDivisor(checkNum, n);\n\t\tif(div != 0){\n\t\t\tconsole.log(checkNum + ': ' + div + ', ' + checkNum / div);\n\t\t\treturn;\n\t\t}\n\t\tcheckNum--;\n\t}\n}", "function findNear(num){\n var ceil = Math.ceil(num);\n if ((ceil-num)<=0.5) return ceil;\n else return Math.floor(num);\n }", "function findDec(element) {\n return num < element;\n }", "function oddsSmallerThan(n) {\n // Your code here\n return Math.floor(n / 2);\n}", "function largestPair(num) {\n let output = 0;\n let str = num.toString();\n for (let i = 0; i < str.length - 1; i += 1) {\n let test = str.slice(i, i + 2);\n if (test > output) {output = test}\n }\n return output;\n}", "function greatest_common_factor(number1, number2) {\n let divider = 1;\n let largeNum = number1 >= number2 ? number1 : number2;\n let smallNum = largeNum === number1 ? number2 : number1;\n while (divider <= smallNum) {\n let testNum = smallNum / divider;\n if (largeNum % testNum === 0) {\n return testNum;\n }\n divider++;\n }\n}", "function nextSmaller(n) {\n let temp = n.toString().split(\"\"),res=-1;\n let index=-1;\n for(let i=temp.length-1;i>0;i--){\n if(temp[i]<temp[i-1]){\n index = i;\n break;\n }\n }\n if(index===-1){return -1;}\n res = temp.slice(0,index-1).join(\"\");\n if(res[0]==0){return -1;}\n \n let resnext = temp.slice(index-1,temp.length);\n let maxnum=-1;\n for(let j=1;j<resnext.length;j++){\n if(resnext[0]>resnext[j]){\n maxnum = Math.max(maxnum,resnext[j]);\n }\n }\n if(maxnum===-1){return -1;}\n res+=maxnum;\n resnext.splice(resnext.indexOf(maxnum+\"\"),1);\n resnext = resnext.sort((a,b)=>{return b-a})\n resnext= resnext.join(\"\");\n res+=resnext;\n if(res[0]==0){return -1;}\n return parseInt(res);\n}", "function nextSmaller(n) {\n \n //get the length of the input\n let length = Math.floor(Math.log10(n)) + 1;\n\n //return obivious combinations\n //for single digit nothing can be calculated\n if (length === 1) return -1;\n\n //for 2 digits try the swap\n if (length === 2) {\n let smaller = (n % 10) * 10 + Math.floor(n / 10);\n return smaller < n ? (smaller > 10) ? smaller : -1 : -1;\n }\n\n //for other cases try to build up a number from the available digits\n //collect available digits from the input\n let original = n.toString().split('');\n\n //copy them to another array in reversed order\n let digits = [...original].sort((a,b) => b - a);\n\n smaller = '';\n\n let pos = 0;\n let back = 2;\n let needSmaller = false;\n \n while (true) { \n while (smaller.length < length) {\n let _original = +original[pos] - (needSmaller ? 1 : 0); //if original search has not found anything find a smaller number\n\n let hit = false;\n\n //find a number into the position which is <= than the number in the same position of the original number\n for (let i = 0; i < digits.length; i++) {\n let _new = +digits[i];\n\n //if number is >= then use it\n if (_new <= _original) {\n //add the number to the result\n smaller += _new;\n\n //remove it from the available digits list\n digits.splice(i, 1);\n\n //go to next position\n pos++;\n\n //we found a number which looks fine\n hit = true;\n \n //if we found a bigger number then add all other digits to the number\n if (hit && needSmaller) {\n smaller += digits.join('');\n digits = [];\n break;\n }\n \n //stop the for loop for this search\n break;\n }\n }\n\n //if we have not found a bigger then use the first number\n if (!hit) {\n smaller += digits.splice(0, 1);\n pos++;\n\n //we already found a bigger number no need to do it further\n needSmaller = false;\n }\n\n }\n\n\n if (+smaller >= n) {\n //cut down last 'back' digits and add them back to digits array for selection\n smaller.slice(-back).split('').forEach(digit => digits.push(digit));\n digits.sort((a, b) => b - a);\n smaller = smaller.substring(0, length - back);\n pos -= back;\n\n //we need a biggernumber\n needSmaller = true;\n back++;\n } else {\n return smaller[0] === '0' ? -1 : +smaller;\n }\n\n if (back > length + 1) {\n smaller = '-1';\n break;\n }\n\n }\n\n return -1;\n}", "function divisor(num1, num2){\n var small = getSmall(num1, num2);\n //var primes = [2,3,5,7];\n \n for (var i = small; i > 0; i--){\n if ( num1 % i === 0 && num2 % i === 0){\n return i;\n }\n \n // else, check if divisible by primes starting with highest number\n // don't need this\n /*for (var j = primes.length; j > 0; j--){\n if ( num1 % primes[j - 1] === 0 && num2 % primes[j - 1] === 0 ){\n return i;\n }\n }*/\n \n }\n \n return 1;\n}", "function Division(num1, num2) {\n var greatestSoFar = 1;\n var min = Math.min(num1, num2);\n for(var i = 2; i <= min; i++) {\n if(num1%i === 0 && num2%i === 0) {\n greatestSoFar = i;\n }\n }\n return greatestSoFar;\n}", "findGCD (num1, num2) {\n let max = num1 > num2 ? num1 : num2\n let min = num1 > num2 ? num2 : num1\n let diff = max - min\n while (diff !== 0) { \n let temp = min % diff\n min = diff\n diff = temp\n }\n return min\n }", "function euler003( num ) {\n // starting index (first prime)\n var i = 2;\n\n // while the number to process is greater than the index\n while ( num > i ) {\n // if the index is a factor of the number\n if ( num % i === 0 ) {\n // then divide by the index\n num = num / i;\n console.log('num is: ' + num);\n }\n\n // increment the index\n i++;\n console.log('i is: ' + i);\n }\n\n // return the greatest factor that is only divisible by itself\n return i;\n}", "function greatestCommonDivisor(a, b){\n if(b == 0)\n return a;\n else \n return greatestCommonDivisor(b, a%b);\n}", "function getBinary(num) {\n if (num === 0) return 0;\n else return (num % 2) + 10 * getBinary(Math.floor(num / 2));\n}", "function nextBigger (number) {\n // convert into an array of digits\n var digitsArray = String(number).split(\"\").map((num) => {\n return Number(num)\n })\n \n if (digitsArray.length == 1)\n return -1;\n\n // go the array from right to left and find the first digit (its position) that is less than the previous element\n var positionTochange = -1;\n for (var i = digitsArray.length - 2; i >= 0; i--) {\n if (digitsArray[i] < digitsArray[i + 1]) {\n // position found!\n positionTochange = i;\n break;\n }\n }\n if (positionTochange < 0)\n return -1;\n var digitToChange = digitsArray[positionTochange];\n // now, set to the found position the next bigger digit from the rest array part to the right from the found position\n\n // copy the left part of the array to the result array\n var result = new Array();\n for (var i = 0; i < positionTochange; i++)\n result.push(digitsArray.shift());\n var restBiggestDigits = digitsArray.filter(el => el > digitToChange).sort(function (a, b) {\n return a - b;\n });\n if (restBiggestDigits.length == 0)\n return -1;\n\n // the first element ist the next biggest digit to the found\n var digitToBePlacedFirst = restBiggestDigits[0];\n result.push(digitToBePlacedFirst);\n\n // remove the element from the initial array\n var indexToRemove = digitsArray.indexOf(digitToBePlacedFirst);\n if (indexToRemove >= 0)\n digitsArray.splice(indexToRemove, 1);\n\n // concat the result and the sorted initial array\n result = result.concat(digitsArray.sort(function (a, b) { return a - b;}))\n\n // output\n var resultNumber = parseInt(result.join(''), 10);\n if (resultNumber == number)\n return -1;\n\n return resultNumber;\n\n}", "function findGdivisor(num1, num2) {\n var tmp;\n for (var i = 0; i <= num2; i++) {\n if (num1 % i === 0 && num2 % i === 0) {\n tmp = i;\n }\n } return tmp;\n}", "function selfDivide(num) {\n let factors = num.toString().split('').map(Number) // numbers to divide by\n for (let j = 0; j < factors.length; j++) {\n if (num % factors[j] !== 0) {\n return num\n }\n }\n }", "function largestPrimeFactor(number) {\n if(isPrime(number)) return number\n \n let sqrt = Math.floor(Math.sqrt(number))\n \n sqrt = sqrt % 2 === 0 ? sqrt + 1 : sqrt\n \n for( let i = sqrt; i >= 1; i-= 2){\n if(((number % i) === 0) && isPrime(i)){\n return i\n }\n }\n }", "function excercice(num) {\n if(num <= 0 || isNaN(num)){\n return(\"ERROR\");\n } else if (num >= 1000000){\n return(num);\n } else{\n while(num < 1000000)\n {\n num= num * 10;\n }\n return(num);\n }\n}", "function search(arr, num) {\n let min = 0,\n max = arr.length;\n while (min <= max) {\n let middle = Math.floor((min + max) / 2);\n console.log(middle);\n if (arr[middle] > num) max = middle + 1;\n else if (arr[middle] < num) min = middle - 1;\n else return middle + 1;\n }\n}", "function gcdMoreThanTwoNum(input){\n if (toString.call(input) !== \"[object Array]\"){\n return false;\n }\n var len, a, b;\n len = input.length;\n if (!len){\n return null;\n }\n a = input[0];\n for (var i=1; i<len; i++){\n b = input[i];\n a = gcdTwoNum(a, b);\n }\n return a;\n}", "function largestPrimeFactor(number) {\n var i = 2;\n while (i <= number){\n if (number % i === 0) {\n number /= i;\n } else {\n i++;\n }\n }\n console.log(i);\n}", "function check(num) {\n if (Number.isNaN(num) || num <= 0) {\n return console.log(\"ERROR!\");\n }\n if (num >= 1000000) {\n return num;\n }\n num *= 10;\n\n return check(num);\n}", "function maxSub(arr,num){\n if(num > arr.length){\n return null;\n }\n\n var max = -Infinity\n\n for(let i=0; i < arr.length - num + 1; i++){\n temp = 0;\n for(let j=0; j < num; j++){\n //j < num means we want to look ahead by 3 elements\n temp += arr[i+j];\n }\n if(temp > max){\n max = temp;\n }\n }\n\nreturn max;\n}", "function greatestCommonDenominator(arr) {\n if (arr.length == 1) {\n return arr[0];\n }\n for (let i = 0; i < arr.length - 1; i++) {\n if (arr[arr.length - 1] == 0) {\n return arr[arr.length - 2];\n } else if (arr[i] > arr[i + 1]) {\n let temp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = temp;\n return greatestCommonDenominator(arr);\n } else if (arr[i] > 0 && arr[i + 1] >= arr[i]) {\n arr[i + 1] = arr[i + 1] % arr[i];\n return greatestCommonDenominator(arr);\n }\n }\n }", "function solution(number, limit, power) {\n let answer = 0;\n \n for (let i = 1; i <= number; i++) {\n let tempNum = 0;\n for (let j = 1; j <= Math.sqrt(i); j++) {\n if (!(i % j)) {\n if (i / j === j) {\n tempNum += 1;\n } else {\n tempNum += 2;\n }\n }\n \n if (tempNum > limit) {\n tempNum = power;\n break;\n }\n }\n answer += tempNum;\n }\n \n return answer;\n}", "function greatestCommonDivisor(num1, num2) {\n var divisor = 2,\n greatestDivisor = 1;\n\n // if num1 or num2 are negative values\n if (num1 < 2 || num2 < 2) return 1;\n\n while (num1 >= divisor && num2 >= divisor) {\n if (num1 % divisor == 0 && num2 % divisor == 0) {\n greatestDivisor = divisor;\n }\n divisor++;\n }\n return greatestDivisor;\n}", "function findLargestPrime(number) {\n var factor;\n var prime;\n var largestPrime\n\n for (i = 2; i < number / 2; i++) {\n if (number % i === 0) { // then i is a factor\n var k = 2;\n for (k = 2; k < i; k++) {\n if (i % k !== 0 || i === 2) { // if i is only divisible by itself and 1\n prime = i\n }\n else { // i is not a prime number\n console.log(largestPrime);\n return largestPrime;\n }\n }\n console.log(prime + \" is a prime factor\");\n largestPrime = prime\n }\n }\n return largestPrime;\n} //end function", "function greatestCommonDivisor(a, b) {\n if(b == 0) {\n return a;\n } else {\n return greatestCommonDivisor(b, a%b);\n }\n}", "function findBiggestNumber(arr) {\n let biggestNumber;\n // run a loop as long as the array\n for (i = 0; i < arr.length; i++) {\n let currentNumber = arr[i];\n // the first number is the biggest number\n if (i === 0) {\n biggestNumber = currentNumber;\n }\n // is the current number bigger than the biggest number\n // if it is keep looping\n else {\n if (currentNumber > biggestNumber) {\n biggestNumber = currentNumber;\n }\n }\n }\n return biggestNumber;\n }", "function smallestDivisor(nums, threshold){\n let divisor = 1\n let sum = 0\n\n while (sum <= threshold){\n for (let i = 0; i < nums.length; i++) {\n sum += (Math.ceil(nums[i] / divisor))\n } \n if (sum > threshold) {\n divisor ++\n sum = 0\n } else {\n return divisor\n }\n }\n // return divisor\n}", "function isPriNum (num){\n if (num%1 !== 0 | num ===1){\n return false;\n }\n \n if(num === 2){\n return true\n }\n if (num%2 === 0){\n return false\n }\n\n else{\n for (var a = num-2; a >= 2; a = a-2){\n if (num%a === 0){\n return false\n } \n }\n return true\n }\n}", "function shortestStepsToNum(num) {\n if (num < 3) return num - 1;\n let n = 0;\n while (num > 1)\n num % 2 == 0 ? num /= 2 : num--, n++;\n return n;\n}", "function convertToBinary(num){\n if(num>0){ //constant\n let binary = Math.floor(num%2); //save the reminder in binary\n //divide the number by 2 and send that to the function again\n //carry the reminder to the next recursion call\n return (convertToBinary(Math.floor(num/2))+ binary); // O(log(n))\n }else{\n return ''; //base case - at some point the divisions will lead to 0\n }\n}", "function findNumber(x, n) {\n var tmp = n;\n while (tmp < x) {\n tmp += n;\n }\n return tmp;\n}", "function digitalRoot(num) {\n while (num > 10) {\n num = digitalRootStep(num);\n }\n\n return num;\n}", "function solution(n){\n let temp = Math.floor((n - Math.floor(n)) * 100);\n \n if(temp < 10){\n temp *= 10;\n };\n \n if(temp >= 25 && temp <= 74){\n return Math.floor(n) + 0.5;\n };\n \n if(temp >= 75 && temp <= 99){\n return Math.floor(n) + 1;\n };\n \n return Math.floor(n);\n}", "function closestMultipleOf10(num) {\n \t//your code is here\n \t\n \tfor(var i =num ; i>=0 ; i--){\n \t\tif(i%10===0){\n \t\t\treturn i;\n \t\t}\n \t}\n }", "function largestNumber(n) {\r\n let x=\"\"\r\n for(i=0;i<n;i++){\r\n x+=\"9\";\r\n }\r\n return parseInt(x);\r\n }", "function smallestCommons(arr) {\n\n\t// use only one order to simplify things\n\tarr = (arr[0] < arr[1]) ? arr : arr.reverse();\n\n\tlet found = false;\n\tlet curr = arr[1];\n\n\twhile (found === false) {\n\n\t\t// key to efficiency is increase by largest factor each pass\n\t\tcurr += arr[1];\n\t\t\n\n\t\t// flag to switch off if a remainder from division attempt\n\t\tlet divisible = true;\n\t\tfor (let i = arr[1]; i >= arr[0]; i--) {\n\t\t\t\n\t\t\tif(curr % i !== 0) {\n\n\t\t\t\tdivisible = false;\n\n\t\t\t\t// we need to return to while loop to try a bigger num\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// if we are still divisible here we made it through inner loop,\n\t\t// this will be our lowest multiple.\n\t\tif(!divisible) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tfound = curr;\n\t\t\tbreak;\n\t\t}\n\t}\n\n return found;\n\t\t\n}", "function greatesrDivisor(num1, num2) {\n let divisors = [];\n for(i=1; i <= num2; i++)\n if(num1%i === 0 && num2%i === 0){\n divisors.push(i)\n }\n let largestDivisors = divisors.reduce(function(a,b){\n return Math.max(a, b);\n })\n return largestDivisors;\n\n}", "function primaBerikutnya(n){\r\n if (isNaN(n) || !isFinite(n)) return NaN; \r\n if (n<2) return 2;\r\n n = Math.floor(n);\r\n for (var i=n+n%2+1; i<9007199254740992; i+=2) {\r\n if (cekPrima(i)) return i;\r\n }\r\n return NaN;\r\n }", "function sqrtInt(num) {\n if (num === 0 || num === 1) return num;\n\n var start = 0,\n end = num,\n result;\n while (start <= end) {\n let midPoint = parseInt((start + end) / 2);\n if (midPoint * midPoint == num) {\n return midPoint;\n } else if (midPoint * midPoint > num) {\n end = midPoint - 1;\n } else {\n start = midPoint + 1;\n }\n }\n}", "function lcm(num1, num2) {\n var least = num2;\n if(num1 > num2){\n least = num1;\n }\n\n while (true) {\n if(least % num1 === 0 && least % num2 === 0){\n return least;\n }\n least += 1;\n }\n}", "function halfCalc(num){\n if(num < 19){\n return 1;\n }else{\n return 2;\n }\n}", "function powerOfTwoCeil(x){\n var result = 1;\n while(result * result < x){\n result *= 2;\n }\n return result;\n}", "function greedy(num, den) {\n /*\n if (num >= den) {\n console.log(\"This is not a proper fraction, please choose a numerator smaller than the denominator\");\n return false;\n }\n if (num < 0 || den < 0) {\n console.log(\"Please use positive integers for both the numerators and denominators\");\n return false;\n }\n */\n if (num === 0) {\n console.log(\" \");\n return 0;\n } else { //always possible when numerator is not 0\n //only integer values w/o division and w/o math lib funcs\n //int division func + remainder func\n const unit_fraction_den = Math.ceil(den/num); //func for int div or directly here\n // next step of greedy is not necessarily the next unit fraction,\n // but the next step for int div\n console.log(unit_fraction_den); //just output result\n //fractions explanation\n greedy(num * unit_fraction_den - den, den * unit_fraction_den);\n }\n}", "function secondLargestElement(tree) {\n var current = tree;\n var previous = tree.value;\n\n while (current) {\n if (current.left && !current.right) {\n previous = Math.max(current.value, previous);\n current = current.left;\n } else if (current.right) {\n previous = Math.max(current.value, previous);\n current = current.right;\n } else if (!current.right && !current.left) {\n return Math.min(previous, current.value);\n }\n\n }\n}", "function largestPrimeFactor(number) {\n let largestPrime = 1;\n let i = 2;\n while(i <= number) {\n if(number % i === 0) {\n number = number/i;\n } else {\n i++;\n }\n }\n return i;\n}", "function largestPrimeFactor(number) {\n // Good luck!\n let prime = 2,\n max = 1;\n while (prime <= number) {\n if (number % prime == 0) {\n max = prime;\n number = number / prime;\n } else prime++;\n }\n return max;\n}", "function digital_root(num) {\n while (Math.floor(num >= 10)) {\n num = Math.floor(num/10) +Math.floor(num % 10);\n }\n return num;\n}", "function getRemAndPrime(num) {\n if (num !== 1) { /*If Number Is One Thats A End Point Of Recursive*/\n let i = 1;\n while (++i) {\n if (isPrime(i)) {/*Check Prime*/\n let res = num / i;\n if (!isFloat(res)) {/*Result Should Be Whole number*/\n primeList.push(i);\n getRemAndPrime(res);\n break;\n }\n }\n }\n } else {\n console.log(JSON.stringify(primeList) + \"===\" + primeList.reduce((a, b) => { return a * b }, 1));\n }\n}", "function findMiddleDivisor(num, digitRestriction) {\n\tvar mNum = Math.sqrt(num);\n\tvar tNum = Math.ceil(mNum);\n\tvar bNum = Math.floor(mNum);\n\n\twhile(digitCount(tNum) == digitRestriction || digitCount(bNum) == digitRestriction) {\n\n\t\tif (digitCount(tNum) == digitRestriction && num % tNum == 0 && digitCount(num / tNum) == digitRestriction) return tNum;\n\t\tif (digitCount(bNum) == digitRestriction && num % bNum == 0 && digitCount(num / bNum) == digitRestriction) return bNum;\n\n\t\ttNum++;\n\t\tbNum--;\n\n\t}\n\n\treturn 0;\n}", "function GreatestCOmmonDivisor(a, b){\n var divisor = 2;\n greatestDivisor = 1;\n\n if (a < 2 || b < 2){\n return 1;\n }\n\n while(a >= divisor && b >= divisor){\n if (a % divisor == 0 && b% divisor == 0) {\n greatestDivisor = divisor;\n }\n divisor ++;\n }\n return greatestDivisor;\n}", "function greatestCommonDivisor(a, b) {\n if (b === 0) {\n return a;\n }\n return greatestCommonDivisor(b, a % b);\n}", "function solution(digits) {\n let max = 0;\n for (let i = 0; i < digits.length; i++) {\n let num = digits.slice(i, i+5);\n if (num > max) max = num;\n }\n return +max;\n}", "function largestFactor(n) {\n let factor = n - 1;\n while(n % factor !== 0){\n factor--;\n }\n return factor;\n}", "function gcd_more_than_two_numbers(input) {\n if (toString.call(input) !== \"[object Array]\") \n return false; \n var len, a, b;\n len = input.length;\n if ( !len ) {\n return null;\n }\n a = input[ 0 ];\n for ( var i = 1; i < len; i++ ) {\n b = input[ i ];\n a = gcd_two_numbers( a, b );\n }\n return a;\n }", "function largestNumber(numbers) {\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 mostSignificantDigit(num){\n\n}", "function numberMax(n1, n2) {\n // bit problem\n}", "function lcm(num1, num2){\n var sumNum = num1 * num2;\n// console.log(sumNum);\n //Using Math.min() returns the lowest number:\n if(sumNum % num1 !== 0 && sumNum % num2 !== 0){\n // console.log(Math.min(num1, num2));\n return Math.min(sumNum);\n }\n }", "function solution(N) {\n // write your code in JavaScript (Node.js 0.12)\n var limit = Math.sqrt(N); \n var min = 10*N; \n for(var i = 1; i<=limit; i++){\n \n if(N/i === Math.floor(N/i)){\n var P = 2*((N/i) + i); \n if(P<min){\n min = P; \n }\n }\n \n }\n return min; \n}", "function gcdTwoNum(m, n){\n var result = [];\n var limit = Math.max(Math.min(m, n), Math.floor(Math.max(m, n)/2));\n for (var i=1; i<=limit; i++ ){\n if(m % i === 0 && n % i === 0){\n result.push(i);\n }\n }\n return Math.max.apply(null, result);\n}", "function subtracktOddNumber(num) {\n var sum = 0;\n var sum1 = 0;\n for (var i = 1; i <= num; i++) {\n if (i % 2 === 0) {\n sum += i;\n } else if (i % 2 !== 2 && i <= num / 2) {\n sum1 += i;\n }\n\n }\n\n return (sum - sum1) * 12.5;\n}", "function solution_1 (isBadVersion) {\r\n return function (n) {\r\n let low = 1;\r\n let high = n;\r\n while (true) {\r\n const middle = Math.floor((high - low) / 2 + low);\r\n if (!isBadVersion(middle)) {\r\n low = middle + 1;\r\n } else if (middle === low || !isBadVersion(middle - 1)) { // condition `middle === low` is needed because then you wouldn't search `middle - 1`\r\n return middle\r\n } else {\r\n high = middle - 1;\r\n }\r\n }\r\n }\r\n}", "function highToLow(num){ \n\tvar arr = Array.from(num.toString()).map(Number);\n\tvar max=0\n\tvar newArr = []\n\tvar len = arr.length\n\twhile (newArr.length<len){\n\t\tfor (var i=0; i<arr.length; i++){\t\n\t\t\tif (max<arr[i]){\n\t\t\t\tmax = arr[i]\t\n\t\t\t}\n\t\t}\n\t\tnewArr.push(max)\n\t\tvar inx = arr.indexOf(max)\n\t\tarr.splice(inx, 1)\n\t\tmax = arr[0]\n\t}\n\tvar newNum = newArr.join(\"\")\n\treturn parseInt(newNum)\n}", "function findNb(m) {\n var sum = 0;\n var i = 1;\n while (sum <m) {\n sum = sum + Math.pow(i, 3);\n i++;\n }\n if (sum === m) {\n return (i-1);\n } else {\n return -1;\n }\n}", "function maximizeMoney(){\n n = 15; \n k = 1000;\n\n if(n%2==0){ //If number of house is even\n maxAmt = (n/2)*k;\n return maxAmt;\n }\n else(n%2!==0) //If number of house is odd\n maxAmt = (((n-1)/2)+1)*k;\n return maxAmt;\n }", "function smallestMult(n) {\n\n // start number from the biggest\n let result = n - 1;\n\n let found;\n let counter = 0;\n\n // increase the result by one until the number is not fully divisible by the numbers\n do {\n result++;\n\n // check if number is divisible by all numbers or not\n found = true;\n for (let i = 2; i <= n; i++) {\n if (result % i !== 0) {\n found = false;\n break;\n }\n counter++;\n }\n\n } while (!found);\n\n console.log(`Iterations: ${counter}`);\n return result;\n\n}", "findMyNumber(number) {\n \tlet temp = this.root;\n \twhile (temp.data !== number) { \n if(number > temp.data && temp.right !== null) {\n \ttemp = temp.right;\n }\n else if (number < temp.data && temp.left !== null) {\n \ttemp = temp.left;\n }\n else return console.log('number not found!')\n }\n return console.log(`${number} exists!`);\n }", "function getMaxPrimeFactor(num){\n let maxPrime=2;\n while (maxPrime<=num){\n if (num%maxPrime == 0){\n num/=maxPrime; \n } \n else {\n maxPrime++;\n }\n }\n $(\"#primeResult\").append(number + \" is number: \" + maxPrime);\n }", "function largerNum(a,b) {\n if (a>b) \n return a;\n else\n return b;\n}", "function teste2 (num){\n if (num > 8); {\n console.log(num);\n }\n }", "function maxOf2(largerNum, smallerNum) {\n if (largerNum > smallerNum) {\n return largerNum; \n }\n else{\n return \"equal\";\n }\n }", "function gcd(num1, num2) {\n var commonDivisor = [ ];\n let highNum = num1;\n if(num1 < num2){\n highNum = num2;\n \n }\n \n for (let i = 1; i <= highNum; i++) {\n if(num1 % i === 0 && num2 % i === 0){\n commonDivisor.push(i);\n }\n } \n const returnNum = Math.max(...commonDivisor);\n return returnNum; \n \n}", "function binary(arr, num){\n if(!isArrayLike(arr)){\n return -1;\n }\n var i = 0, \n j = arr.length-1, \n k, half; \n while(i <= j){\n k = Math.floor((i + j)/2);\n half = arr[k]\n if(half == num){\n return k;\n }\n num < half? j = k-1: i = k+1;\n }\n return -1; \n }", "function problem3(num){\n for(var x = 2; x<=num; x++){\n if(isPrime(x) !== true){\n }\n else if (num%x===0){\n num = num/x;\n }\n else if (isPrime(num) == true)\n return num;\n }\n}", "function sqrRoot(num, min = 1, max = num) {\n if (min > max) return;\n const mid = Math.floor((min + max) / 2);\n const sqr = mid * mid;\n if (sqr === num) return mid;\n if (sqr < num) {\n return sqrRoot(num, mid + 1, max);\n } else {\n return sqrRoot(num, min, mid - 1);\n }\n}", "getClosestStep(num) {\n num = this.bound(num);\n if (this.step) {\n const step = Math.round(num / this.step) * this.step;\n num = this.bound(step);\n }\n return num;\n }", "function solve(n, p){\n // Complete this function\n var front = (Math.floor(p / 2));\n var back = (Math.floor(n / 2) - front);\n if (front > back){\n return back\n } else {\n return front\n }\n}", "function gcf(num1, num2){\n if (num1 > num2){ //this ensures num1 is the smaller number\n var temp = num1; // 1...\n num1 = num2;\n num2 = temp;\n }\n for (var i = num1; i > 1; i--){ // n - dictated by size of num1\n if (num1 % i === 0 && num2 % i === 0){ // 2\n return i;\n }\n }\n return 1;\n}", "function primefactor(max) {\n for (var i = max; i > 0; i--) {\n if (i % max == 0) {\n console.log(i)\n for (var j = 2; j <= i; j++) {\n if (j == i) {\n return i\n }\n if (i % j == 0) {\n break\n }\n }\n }\n }\n}" ]
[ "0.6730373", "0.66105", "0.6608684", "0.63724303", "0.6371496", "0.6321737", "0.6297459", "0.6284052", "0.6275032", "0.62392884", "0.621486", "0.6196732", "0.61922294", "0.61634904", "0.61601347", "0.6152286", "0.61352134", "0.61269116", "0.6124017", "0.6110064", "0.6101486", "0.6095083", "0.609284", "0.6061593", "0.605179", "0.60468644", "0.6038568", "0.6038026", "0.6008869", "0.5983844", "0.5973802", "0.5971146", "0.5967296", "0.59460145", "0.5942162", "0.5927504", "0.5920021", "0.5910072", "0.59043175", "0.58967894", "0.5893194", "0.58910704", "0.58891356", "0.5856112", "0.5848949", "0.58388186", "0.58370495", "0.5827449", "0.5819597", "0.5818615", "0.5817984", "0.58058316", "0.58000517", "0.5798012", "0.5796115", "0.57939386", "0.5793061", "0.57880706", "0.5784783", "0.5784675", "0.5781126", "0.57747716", "0.57697755", "0.57662374", "0.5760446", "0.575396", "0.57538056", "0.5751628", "0.5748519", "0.5728554", "0.5727559", "0.57269186", "0.5723966", "0.5723364", "0.5722727", "0.57222044", "0.5721111", "0.5718348", "0.571319", "0.5712913", "0.5711449", "0.57114387", "0.57018685", "0.56996864", "0.5690941", "0.5684598", "0.5681359", "0.5679215", "0.5673468", "0.5669729", "0.565995", "0.5659943", "0.5656353", "0.5652375", "0.56496626", "0.5649253", "0.56482023", "0.56439227", "0.56417197", "0.563679", "0.5636021" ]
0.0
-1
Does not render the description unless it is not empty. So, each item in the list will have a different height, depending on whether or not the item has a description.
render () { return (<View key={this.props.id} onLayout={this.handleOnLayout} style={this.props.style}> <Text style={styles.item}>{this.props.name}</Text> {this.props.desc && <Text style={styles.item}>{this.props.desc}</Text> } </View>); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Description(props) {\n if (clothing.desc) {\n return (<div> <SubHeading> <div> Description</div></SubHeading>\n <Desc> {clothing.desc} </Desc></div>\n\n\n );\n } else {\n return (<div></div>);\n }\n }", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()('description', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(ItemDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_1_lodash_isNil___default()(children) ? content : children\n );\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('description', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(ItemDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"p\" /* getElementType */])(ItemDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ItemDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ItemDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ItemDescription(props) {\n\t var children = props.children,\n\t className = props.className,\n\t content = props.content;\n\n\t var classes = (0, _classnames2.default)(className, 'description');\n\t var rest = (0, _lib.getUnhandledProps)(ItemDescription, props);\n\t var ElementType = (0, _lib.getElementType)(ItemDescription, props);\n\n\t return _react2.default.createElement(\n\t ElementType,\n\t _extends({}, rest, { className: classes }),\n\t children || content\n\t );\n\t}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()('description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ItemDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ItemDescription, props);\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(ElementType, __WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_extends___default()({}, rest, {\n className: classes\n }), __WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* childrenUtils */].isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()('description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ItemDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ItemDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()('description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ItemDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ItemDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = Object(clsx__WEBPACK_IMPORTED_MODULE_1__[\"default\"])('description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ItemDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ItemDescription, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)('description', className);\n var rest = (0, _lib.getUnhandledProps)(ItemDescription, props);\n var ElementType = (0, _lib.getElementType)(ItemDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)('description', className);\n var rest = (0, _lib.getUnhandledProps)(ItemDescription, props);\n var ElementType = (0, _lib.getElementType)(ItemDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function ItemDescription(props) {\n return <div>{props.descr}</div>\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(className, 'description');\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(ListDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_1_lodash_isNil___default()(children) ? content : children\n );\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()(className, 'description');\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ListDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ListDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()(className, 'description');\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ListDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ListDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(className, 'description');\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(ListDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(className, 'description');\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"p\" /* getElementType */])(ListDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = Object(clsx__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(className, 'description');\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ListDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ListDescription, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(className, 'description');\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ListDescription, props);\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(ElementType, __WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_extends___default()({}, rest, {\n className: classes\n }), __WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* childrenUtils */].isNil(children) ? content : children);\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(className, 'description');\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ListDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_1_classnames___default()(className, 'description');\n var rest = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"r\" /* getUnhandledProps */])(ListDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_4__lib__[\"q\" /* getElementType */])(ListDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_4__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = (0,clsx__WEBPACK_IMPORTED_MODULE_1__.default)(className, 'description');\n var rest = (0,_lib__WEBPACK_IMPORTED_MODULE_4__.default)(ListDescription, props);\n var ElementType = (0,_lib__WEBPACK_IMPORTED_MODULE_5__.default)(ListDescription, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3__.createElement(ElementType, (0,_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_6__.isNil(children) ? content : children);\n}", "renderDescription () {\n if (!this.state.showDescription) {\n return (\n <div className='listing-description'>\n <p>{this.props.listing.tagline}</p>\n <Button onClick={()=> this.setState({showDescription: true})}>{`Read more about the space`}</Button>\n </div>\n );\n } else {\n return (\n <div className='listing-description'>\n <p>{this.props.listing.description}</p>\n <Button onClick={()=> this.setState({showDescription: false})}>Hide</Button>\n </div>\n );\n }\n }", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)(className, 'description');\n var rest = (0, _lib.getUnhandledProps)(ListDescription, props);\n var ElementType = (0, _lib.getElementType)(ListDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function ListDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)(className, 'description');\n var rest = (0, _lib.getUnhandledProps)(ListDescription, props);\n var ElementType = (0, _lib.getElementType)(ListDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "constructor(props) {\n super(props);\n let hasDescription, descriptionShown;\n if (this.props.item.description === \"\") {\n hasDescription = false;\n } else {\n hasDescription = true;\n }\n this.state = {\n hasDescription: hasDescription,\n descriptionShown: descriptionShown\n };\n }", "renderDescView() {\n const { data } = this.state;\n return (\n <View\n key=\"desc\"\n style={styles.descViewContainer}\n >\n <View style={styles.descTopContainer} />\n <View style={styles.descMainContainer}>\n <DescView\n style={styles.descTextContainer}\n numberOfLines={5}\n textAlign='left'\n showMoreItem={this.renderShowLessMoreButton(true)}\n showLessItem={this.renderShowLessMoreButton(false)}\n >\n <Text style={styles.descText}>{data.description}</Text>\n </DescView>\n {this.renderViewOnEcoWebsiteButton()}\n </View>\n </View >\n );\n }", "function Description(props) {\n var children = props.children;\n return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\",\n style: {\n padding: '16px'\n }\n }, children);\n}", "async descriptionHeightWorkaround(allowSyncReflows = false) {\n if (!this.node.hasAttribute(\"descriptionheightworkaround\")) {\n // This view does not require the workaround.\n return;\n }\n\n // We batch DOM changes together in order to reduce synchronous layouts.\n // First we reset any change we may have made previously. The first time\n // this is called, and in the best case scenario, this has no effect.\n let items = [];\n let collectItems = () => {\n // Non-hidden <label> or <description> elements that also aren't empty\n // and also don't have a value attribute can be multiline (if their\n // text content is long enough).\n let isMultiline = \":not([hidden],[value],:empty)\";\n let selector = [\n \"description\" + isMultiline,\n \"label\" + isMultiline,\n \"toolbarbutton[wrap]:not([hidden])\",\n ].join(\",\");\n for (let element of this.node.querySelectorAll(selector)) {\n // Ignore items in hidden containers.\n if (element.closest(\"[hidden]\")) {\n continue;\n }\n\n // Ignore content inside a <toolbarbutton>\n if (\n element.tagName != \"toolbarbutton\" &&\n element.closest(\"toolbarbutton\")\n ) {\n continue;\n }\n\n // Take the label for toolbarbuttons; it only exists on those elements.\n element = element.multilineLabel || element;\n\n let bounds = element.getBoundingClientRect();\n let previous = gMultiLineElementsMap.get(element);\n // We don't need to (re-)apply the workaround for invisible elements or\n // on elements we've seen before and haven't changed in the meantime.\n if (\n !bounds.width ||\n !bounds.height ||\n (previous &&\n element.textContent == previous.textContent &&\n bounds.width == previous.bounds.width)\n ) {\n continue;\n }\n\n items.push({ element });\n }\n };\n if (allowSyncReflows) {\n collectItems();\n } else {\n await this.window.promiseDocumentFlushed(collectItems);\n // Bail out if the panel was closed in the meantime.\n if (!this.node.panelMultiView) {\n return;\n }\n }\n\n // Removing the 'height' property will only cause a layout flush in the next\n // loop below if it was set.\n for (let item of items) {\n item.element.style.removeProperty(\"height\");\n }\n\n // We now read the computed style to store the height of any element that\n // may contain wrapping text.\n let measureItems = () => {\n for (let item of items) {\n item.bounds = item.element.getBoundingClientRect();\n }\n };\n if (allowSyncReflows) {\n measureItems();\n } else {\n await this.window.promiseDocumentFlushed(measureItems);\n // Bail out if the panel was closed in the meantime.\n if (!this.node.panelMultiView) {\n return;\n }\n }\n\n // Now we can make all the necessary DOM changes at once.\n for (let { element, bounds } of items) {\n gMultiLineElementsMap.set(element, {\n bounds,\n textContent: element.textContent,\n });\n element.style.height = bounds.height + \"px\";\n }\n }", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(className, 'description');\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"b\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__lib__[\"c\" /* getElementType */])(CardDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_1_lodash_isNil___default()(children) ? content : children\n );\n}", "function toggleDescriptionText() {\n\n\tvar default_height = parseInt(jQuery('.item-description.has-toggle').css('max-height')),//112,//150,//400;\n\t\titem_description = jQuery('.js-item-description'),\n\t\titem_description_toggle = jQuery('.js-item-description-toggle');\n\n\t//console.log(default_height);\n\t//console.log(item_description.height());\n\n\tif(item_description.height() < default_height) {\n\t\titem_description.removeClass('has-toggle');\n\t\titem_description_toggle.addClass('hide').removeClass('is-hidden');\n\t} else {\n\t\titem_description.addClass('has-toggle');\n\t\titem_description_toggle.removeClass('hide').addClass('is-hidden');\n\n\t\t/*var wordArray = item_description.get(0).innerHTML.split(' ');\n\t\twhile(item_description.get(0).scrollHeight > item_description.get(0).offsetHeight) {\n\t\t\twordArray.pop();\n\t\t\titem_description.get(0).innerHTML = wordArray.join(' ') + '...';\n\t\t}*/\n\t}\n\n\titem_description_toggle.on('click', function(e) {\n\t\te.preventDefault();\n\t\tif(item_description.is('.has-toggle')){\n\t\t\tjQuery('html, body').stop(true).animate({\n\t\t\t\tscrollTop: jQuery('.siteWidth').offset().top - jQuery('header').height()\n\t\t\t}, 750);\n\t\t}\n\t\titem_description.toggleClass('has-toggle');\n\t\titem_description.toggleClass('is-expanded');\n\t\titem_description_toggle.toggleClass('is-expanded');\n\t});\n}", "setHeight () {\n if (!this.props.list.length || !this.refs.item0) {\n return;\n }\n\n const node = ReactDom.findDOMNode(this);\n const computedStyle = getComputedStyle(node);\n const itemHeight = ReactDom.findDOMNode(this.refs.item0).offsetHeight;\n const height = ACList.heightAddenums.reduce((heightParts, prop) => {\n return heightParts + parseInt(computedStyle[prop], 10);\n }, itemHeight * this.props.itemsCount);\n\n node.style.maxHeight = height + 'px';\n }", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"D\" /* useTextAlignProp */])(textAlign), 'description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"r\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"q\" /* getElementType */])(CardDescription, props);\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(ElementType, __WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_extends___default()({}, rest, {\n className: classes\n }), __WEBPACK_IMPORTED_MODULE_5__lib__[\"c\" /* childrenUtils */].isNil(children) ? content : children);\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = classnames_default()(useTextAlignProp(textAlign), 'description', className);\n var rest = lib_getUnhandledProps(CardDescription, props);\n var ElementType = lib_getElementType(CardDescription, props);\n return react_default.a.createElement(ElementType, extends_default()({}, rest, {\n className: classes\n }), childrenUtils_namespaceObject.isNil(children) ? content : children);\n}", "function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);\n }\n return term;\n }", "function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);\n }\n return term;\n }", "function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);\n }\n return term;\n }", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"E\" /* useTextAlignProp */])(textAlign), 'description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"r\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"q\" /* getElementType */])(CardDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_5__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"E\" /* useTextAlignProp */])(textAlign), 'description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"r\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"q\" /* getElementType */])(CardDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_5__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function CardDescription(props) {\n\t var children = props.children,\n\t className = props.className,\n\t content = props.content;\n\n\t var classes = (0, _classnames2.default)(className, 'description');\n\t var rest = (0, _lib.getUnhandledProps)(CardDescription, props);\n\t var ElementType = (0, _lib.getElementType)(CardDescription, props);\n\n\t return _react2.default.createElement(\n\t ElementType,\n\t _extends({}, rest, { className: classes }),\n\t children || content\n\t );\n\t}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"C\" /* useTextAlignProp */])(textAlign), 'description', className);\n var rest = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"q\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = Object(__WEBPACK_IMPORTED_MODULE_5__lib__[\"p\" /* getElementType */])(CardDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_5__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n\n var classes = __WEBPACK_IMPORTED_MODULE_2_classnames___default()(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__lib__[\"o\" /* useTextAlignProp */])(textAlign), 'description', className);\n var rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__lib__[\"b\" /* getUnhandledProps */])(CardDescription, props);\n var ElementType = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__lib__[\"c\" /* getElementType */])(CardDescription, props);\n\n return __WEBPACK_IMPORTED_MODULE_4_react___default.a.createElement(\n ElementType,\n __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, rest, { className: classes }),\n __WEBPACK_IMPORTED_MODULE_5__lib__[\"d\" /* childrenUtils */].isNil(children) ? content : children\n );\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = Object(clsx__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"useTextAlignProp\"])(textAlign), 'description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getUnhandledProps\"])(CardDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getElementType\"])(CardDescription, props);\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(ElementType, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_5__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_2___default()(Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"useTextAlignProp\"])(textAlign), 'description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getUnhandledProps\"])(CardDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getElementType\"])(CardDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_5__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_2___default()(Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"useTextAlignProp\"])(textAlign), 'description', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getUnhandledProps\"])(CardDescription, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_5__[\"getElementType\"])(CardDescription, props);\n return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_5__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function descriptionCheck() {\n\t\tlet desc;\n\t\tif (detail.description === null) {\n\t\t\treturn desc = \"No description given\"\n\t\t}\n\t\telse {\n\t\t\treturn desc = detail.description\n\t\t}\n\t}", "getDescription() {\n return this.props.descriptionArray.map((description, index) => {\n return (\n <p key={index} className=\"confirmation-modal__description\">\n {description}\n </p>\n );\n });\n }", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)(className, 'description');\n var rest = (0, _lib.getUnhandledProps)(CardDescription, props);\n var ElementType = (0, _lib.getElementType)(CardDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "function foldedItemHeight() {\n return settings.nav_summaryLines * ITEM_LINE_HEIGHT + FOLDED_ITEM_OUTER_HEIGHT_EXTRAS;\n}", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n var classes = (0, _classnames[\"default\"])((0, _lib.useTextAlignProp)(textAlign), 'description', className);\n var rest = (0, _lib.getUnhandledProps)(CardDescription, props);\n var ElementType = (0, _lib.getElementType)(CardDescription, props);\n return _react[\"default\"].createElement(ElementType, (0, _extends2[\"default\"])({}, rest, {\n className: classes\n }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "get htmlDescription(){\n var desc = \"\";\n if(Object.keys(this.inventory).length == 0){\n return '<p>! Gather Resources !</p>';\n }\n else{\n for(var key in this.inventory){\n var value = this.inventory[key];\n desc += \"<p class='resource'>\" + key + \": \" + value + \"</p>\";\n }\n return desc;\n }\n }", "function CardDescription(props) {\n var children = props.children,\n className = props.className,\n content = props.content,\n textAlign = props.textAlign;\n\n var classes = (0, _classnames2.default)((0, _lib.useTextAlignProp)(textAlign), 'description', className);\n var rest = (0, _lib.getUnhandledProps)(CardDescription, props);\n var ElementType = (0, _lib.getElementType)(CardDescription, props);\n\n return _react2.default.createElement(ElementType, (0, _extends3.default)({}, rest, { className: classes }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "updateDescriptionBox_() {\n const descText = this.clonedLightboxableElements_[this.currentElementId_]\n .descriptionText;\n this.descriptionTextArea_.textContent = descText;\n if (!descText) {\n this.descriptionBox_.classList.add('hide');\n }\n }", "getDescription(descriptionObj) {\n // Uncomment to view inconsistencies\n // const descStart = descriptionObj.lastIndexOf('<p>');\n // const description = descriptionObj.slice(descStart + 3, descriptionObj.length - 4);\n\n const description = 'A dummy description of the Flickr image, please view FlickrImage.js to see reasoning for using this here.'\n return description;\n }", "description() {\n if (this._description) {\n return this._description;\n }\n for (let i = 0; i < this.sections.length; i++) {\n const section = this.sections[i];\n if (!section.doc) {\n continue;\n }\n const desc = this.extractDescription(section.markedDoc());\n if (desc) {\n this._description = desc;\n return desc;\n }\n }\n return '';\n }", "function displayDescription(idNum){\r\n\tfor (var i=0;i<descCount;i++){\r\n\t\tif (i===idNum){\r\n\t\t\t$(\"#desc\"+i).css(\"display\",\"inline-block\");\r\n\t\t}\r\n\t\telse{\r\n\t\t\t$(\"#desc\"+i).css(\"display\",\"none\");\r\n\t\t}\r\n\t}\r\n}", "function renderDescription(){\n let shortText = JSON.stringify(text).substr(1, 21);\n return <p className=\"card-text\">{ shortText }...</p>\n }", "function descriptionRequired() {\n let description = this.description\n return typeof description === 'string' ? false : true\n}", "buildDescription () {\n let sampleInput = this.props.description.sample_input !== undefined && this.props.description.sample_input.length >= 1 ? (\n <div className='io-format'>\n <h3>Sample Input</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.sample_input)}} />\n </div>\n ) : (<div />)\n let sampleOutput = this.props.description.sample_output !== undefined && this.props.description.sample_output.length >= 1 ? (\n <div className='io-format'>\n <h3>Sample Output:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.sample_output)}} />\n </div>\n ) : (<div />)\n\n let explanation = this.props.description.explanation !== undefined && this.props.description.explanation.length >= 1 ? (\n <div className='challenge-desc-explanation'>\n <h3>Explanation:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.explanation)}} />\n </div>\n ) : (<div />)\n\n return (\n <div className='challenge-description'>\n <div className='challenge-desc-content'>\n <h3>Description:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.content)}} />\n </div>\n <div className='challenge-desc-input-format'>\n <h3>Input Format:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.input_format)}} />\n </div>\n <div className='challenge-desc-output-format'>\n <h3>Output Format:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.output_format)}} />\n </div>\n <div className='challenge-desc-constraints'>\n <h3>Constraints:</h3>\n <div dangerouslySetInnerHTML={{__html: this.parseTextIntoHTML(this.props.description.constraints)}} />\n </div>\n {sampleInput}\n {sampleOutput}\n {explanation}\n </div>\n )\n }", "get description() {\n var _this$props$get;\n\n const value = (_this$props$get = this.props.get('description')) === null || _this$props$get === void 0 ? void 0 : _this$props$get.value;\n if (!value) return '';\n return value;\n }", "function toggleDescription() {\n self.showingDescription = !self.showingDescription;\n }", "render() {\r\n if (Object.keys(this.props.listItems).length === 0) {\r\n\r\n // return placeholder for empty list\r\n return (<ListPlaceholder\r\n emptyMessage=\"You have nothing to do at the moment. Why don't you put your feet up?\"\r\n filteredTotal={0}\r\n unfilteredTotal={0}/>)\r\n } else {\r\n\r\n // create actual list\r\n return (\r\n <List>\r\n {this\r\n .getKeys()\r\n .map(key => <MyTodoItem\r\n index={key}\r\n toggleDone={this.props.toggleDone}\r\n removeListItem={this.props.removeListItem}\r\n todoItem={this.props.listItems[key]}\r\n key={key}>{key}</MyTodoItem>)}\r\n </List>\r\n )\r\n }\r\n }", "render() {\n const {items } = this.state;\n return (\n <>\n {\n items.length > 0 ? items.map(item => {\n const {content} = item;\n return (\n\n <div className=\"berita_content\">\n <p>{content}</p>\n </div>\n );\n }) : null\n }\n </>\n );\n \n }", "descriptionAbbreviation(){\r\n if(this.props.data.description.length < 400){\r\n return this.props.data.description;\r\n }\r\n else return this.props.data.description.slice(0,400).concat(\"...\");\r\n }", "function description() {\n //check if not exist data description\n if(!book.volumeInfo.description){\n //return default description\n return 'No description available for this book, contact API administrator to add one :)'\n } else return book.volumeInfo.description\n }", "render() {\n return (\n <div data-testid=\"description_txt\" key=\"des\" className=\"Mode-Description\">\n {this.props.description}\n </div>\n );\n }", "function vpb_display_description_hidden()\n{\n\t$('.vpb_description').slideUp('fast');\n\t$('.vpb_description_hidden').slideDown('slow');\n}", "get description() {\n return this.getStringAttribute('description');\n }", "get description() {\n return this.getStringAttribute('description');\n }", "get description() {\n return this.getStringAttribute('description');\n }", "function renderList(items, list, cat) {\n if (list === 'noneList') {\n let output = `<div id=\"noneTitle\" class=\"container list-title-bar\"><h2>To Decide</h2><ul id='noneList' class=\"list-of-items\"></ul></div>`;\n $('#noneHolder').prepend(output);\n } else {\n let output = `<div id=\"catdTitle\" class=\"container list-title-bar\"><h2>${titles[cat]}</h2><ul id='catdList' class=\"list-of-items\"></ul></div>`;\n $('#catdHolder').prepend(output);\n }\n items.forEach(function (item) {\n createItem(item, list, cat);\n });\n}", "get description() {\n return this.catalogItemObj.itemData.description;\n }", "function setHeight(obj) {\n $(mainBlock).height(function () {\n return (obj.descriptionHeight + obj.menuListBlock) + 100;\n });\n }", "function getDescription(element) {\n if (Number.isInteger(parseInt(element.val()))) {\n $.getJSON('/markaspotshstweak/' + element.val() + '/' + element.data('shs-last-child'), function (data) {\n element.parent().siblings('.taxonomy-description').html(data.data);\n }).fail(function (jqXHR) {\n setDescription(element, '');\n })\n }\n else {\n setDescription(element, '');\n }\n }", "get _itemHeight() {\n return this._list.selectedItem.clientHeight;\n }", "function updateDescriptions() {\n descriptionNumber = imageNumber;\n artTitleElement.textContent = 'Title: ' + titleDescriptions[descriptionNumber];\n classificationElement.textContent = 'Classification: ' + classificationDescriptions[descriptionNumber];\n dateElement.textContent = 'Date: ' + dateDescriptions[descriptionNumber];\n workTypesElement.textContent = 'Work Types: ' + workTypesDescriptions[descriptionNumber];\n creationPlaceElement.textContent = 'Creation Place: ' + creationPlaceDescriptions[descriptionNumber];\n mediumElement.textContent = 'Medium: ' + mediumDescriptions[descriptionNumber];\n dimensionsElement.textContent = 'Dimensions: ' + dimensionsDescriptions[descriptionNumber]\n divInfoColumn.append(artTitleElement, classificationElement, dateElement, workTypesElement, mediumElement, dimensionsElement, creationPlaceElement);\n}", "function productDescriptionDisplay() {\n let description = document.createElement('p');\n description.innerHTML = product.description;\n productDetails.appendChild(description);\n}", "render (h) {\n return h(ItemList, { props: {title}})\n }", "render() {\n return html`\n <h1 class=\"title__list\">${this.title}</h1>\n ${this.items.length === 0\n ? html`<p class=\"list__state\">${this.loading}</p>`\n : this.showList(this.items)}\n `;\n }", "_handleDefaultInnerHTML() {\n const that = this;\n\n if (that.dataSource && that.dataSource.length > 0) {\n return;\n }\n\n if (that.$.itemsContainer.innerHTML.indexOf('<ul') >= 0) {\n const firstUl = that.$.itemsContainer.getElementsByTagName('ul')[0],\n items = firstUl.getElementsByTagName('li');\n\n for (let i = 0; i < items.length; i++) {\n const slide = { HTMLcontent: items[i].innerHTML };\n\n that.dataSource.push(slide);\n }\n }\n }", "function isEmptyList() {\n if (completedList.hasChildNodes() == true) {\n completedTitle.style.display = \"inline\";\n } else {\n completedTitle.style.display = \"none\";\n }\n}", "function heightses(){\n\t\t$('.page__catalog .catalog-products-list__title').height('auto').equalHeights();\n\t}", "function ListItemLabel(props) {\n if (props.sublist) {\n return _react.default.createElement(_index.Paragraph2, null, props.children);\n }\n\n return _react.default.createElement(\"div\", null, _react.default.createElement(_index.Label2, null, props.children), props.description && _react.default.createElement(_index.Paragraph3, {\n $style: {\n marginTop: 0,\n marginBottom: 0\n }\n }, props.description));\n}", "function displayDescriptions(descriptions, choose) {\n\t\tvar descriptionList;\n\t\tif (choose) descriptionList = slaveDescriptionList;\n\t\telse descriptionList = masterDescriptionList;\n\n\t\tif (descriptions) descriptionList.show();\n\t\telse return;\n\t\tdescriptionList.html('');\n\t\tfor (var i = 0; i < descriptions.length; i++) {\n\t\t\tvar listItem = $('<li></li>');\n\t\t\tvar descriptionText = $('<span class=\"description-text\"></span>');\n\t\t\tdescriptionText.append(descriptions[i].text);\n\t\t\tlistItem.append(descriptionText);\n\t\t\t// Only show author when master list is shown\n\t\t\tif (!choose) {\n\t\t\t\tlistItem.append(' eftir ');\n\t\t\t\tvar playerName = $('<span class=\"description-player\"></span>');\n\t\t\t\tplayerName.append(descriptions[i].player);\n\t\t\t\tlistItem.append(playerName);\n\t\t\t}\n\t\t\tif (choose) {\n\t\t\t\tvar chooseLink = $('<a href=\"#\" class=\"chooser\">Velja</a>');\n\t\t\t\tchooseLink.attr('data-description', descriptions[i].text);\n\t\t\t\tchooseLink.attr('data-player', descriptions[i].player);\n\t\t\t\tchooseLink.click(chooseDescription);\n\t\t\t\tlistItem.append(chooseLink);\n\t\t\t}\n\t\t\tdescriptionList.append(listItem);\n\t\t}\n\t}", "function hideDescription(time = 500, callback){\n\t\t\t\tli.find(\".itemDescription\").slideUp(time,callback);\n\t\t\t\texpandButton.text(\"\\u25bc\");\n\t\t\t\tdelete self.state.expansion[dataset.toDoList[i].id];\n\t\t\t\tconsole.log(\"hide\");\n\t\t\t}", "get description() {\n return this._data.description;\n }", "renderTagsConditionally() {\n let tagLength = this.state.tags.length;\n return tagLength === 0 ? (\n <p>No tags</p>\n ) : (\n <div>\n <p>The tags are :</p>\n <span style={this.styles} className={this.getBadgeClasses()}>\n {this.formatCount()}\n </span>\n <ul>{this.renderList()}</ul>\n </div>\n );\n }", "function showDescription(){\n\t$(this).find('.description').toggle();\n}", "render(){\n return(\n <div className='definition-list'> \n <dl>First header definition list\n <dt>first element sub list</dt>\n <dd>first subelement sublist</dd>\n \n <dt>second element second sub list</dt>\n <dd>second subelement second sublist</dd>\n \n <dt className='no-visibility'>third element second sub list</dt>\n <dd className='no-visibility'>third subelement second sublist</dd>\n \n </dl> \n </div> \n );\n }", "getDescription() { \n let description = ''\n let pageConfig = Config.pages[this.page] || {}\n \n if( this.isBlogPost) {\n description = this.post.frontmatter.description || this.post.excerpt\n }\n else {\n description = pageConfig.description || Config.description\n }\n \n return description\n }", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}", "get description () {\n\t\treturn this._description;\n\t}" ]
[ "0.66724217", "0.6530175", "0.6507974", "0.65043104", "0.64899737", "0.64899737", "0.64856285", "0.647921", "0.6452029", "0.6452029", "0.6410688", "0.6345662", "0.6345662", "0.6256617", "0.6251506", "0.6226316", "0.6226316", "0.6223395", "0.6216989", "0.6216294", "0.6212008", "0.62085855", "0.62085855", "0.6185301", "0.61846983", "0.6177667", "0.6177667", "0.60767454", "0.5917335", "0.59167343", "0.58764493", "0.58690226", "0.5806629", "0.58063674", "0.57514995", "0.5739441", "0.57366043", "0.57366043", "0.57366043", "0.57343745", "0.57343745", "0.57319826", "0.5727658", "0.5719762", "0.5717997", "0.5717314", "0.5717314", "0.5712686", "0.5682928", "0.5662567", "0.5623161", "0.5607278", "0.55967873", "0.5591035", "0.55688584", "0.55144334", "0.54714006", "0.54630476", "0.5455769", "0.54516125", "0.5444722", "0.5395532", "0.5387265", "0.53790504", "0.5366244", "0.5365254", "0.5359778", "0.53587574", "0.5348879", "0.5337053", "0.5337053", "0.5337053", "0.53275424", "0.53199977", "0.53144854", "0.5312907", "0.53055817", "0.53010625", "0.5295124", "0.5280488", "0.5265962", "0.5264288", "0.5250833", "0.5243419", "0.52387035", "0.52295125", "0.5223193", "0.52222824", "0.5214877", "0.51906556", "0.51814026", "0.5180276", "0.5170412", "0.5170412", "0.5170412", "0.5170412", "0.5170412", "0.5170412", "0.5170412", "0.5170412" ]
0.61509806
27
Find nearest cell to that coordinates via minimum of Euclidean distances.
function getNearestCell(x, y, cells) { var min = Infinity; var result; $.each(cells, function(index, cell) { var d = distance(x, y, cell.center_x, cell.center_y); // Update minimum. if (d < min) { min = d; result = cell; } }); return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function nearest(from) {\n\tvar to = indexOfMin(distances[from]);\n\tif (distances[from][to] < infinDist) {\n\t\tdistances[from][to] = distances[to][from]= infinDist;\n\t\treturn to;\n\t}\n\treturn -1;\n}", "function getNeighbor(current, all) {\n 'use strict';\n var closest = -1,\n minDistance = Infinity,\n col = Infinity, row = Infinity;\n for (var i = 0; i < all.length; i += 1) {\n var d = getDistance(current, all[i]);\n if (d < minDistance && d !== 0) {\n if ((minDistance !== d) ||\n (minDistance === d && all[i][0] < row) ||\n (minDistance === d && all[i][0] === row && all[i][1] < col)) {\n closest = i;\n minDistance = d;\n col = all[i][1];\n row = all[i][0];\n }\n }\n }\n return closest;\n}", "closest(points) {\n if (points.length === 1) {\n return Point.create(points[0]);\n }\n let ret = null;\n let min = Infinity;\n points.forEach((p) => {\n const dist = this.squaredDistance(p);\n if (dist < min) {\n ret = p;\n min = dist;\n }\n });\n return ret ? Point.create(ret) : null;\n }", "function GetMinDistance(targetRow, targetCol) {\n return Math.abs(exitRow - targetRow) + Math.abs((exitCol - targetCol));\n}", "function nearest(ctx) {\n var _a = ctx.structure, _b = _a.min, minX = _b[0], minY = _b[1], minZ = _b[2], _c = _a.size, sX = _c[0], sY = _c[1], sZ = _c[2], bucketOffset = _a.bucketOffset, bucketCounts = _a.bucketCounts, bucketArray = _a.bucketArray, grid = _a.grid, positions = _a.positions;\n var r = ctx.radius, rSq = ctx.radiusSq, _d = ctx.pivot, x = _d[0], y = _d[1], z = _d[2];\n var loX = Math.max(0, (x - r - minX) >> 3 /* Exp */);\n var loY = Math.max(0, (y - r - minY) >> 3 /* Exp */);\n var loZ = Math.max(0, (z - r - minZ) >> 3 /* Exp */);\n var hiX = Math.min(sX, (x + r - minX) >> 3 /* Exp */);\n var hiY = Math.min(sY, (y + r - minY) >> 3 /* Exp */);\n var hiZ = Math.min(sZ, (z + r - minZ) >> 3 /* Exp */);\n for (var ix = loX; ix <= hiX; ix++) {\n for (var iy = loY; iy <= hiY; iy++) {\n for (var iz = loZ; iz <= hiZ; iz++) {\n var idx = (((ix * sY) + iy) * sZ) + iz;\n var bucketIdx = grid[idx];\n if (bucketIdx > 0) {\n var k = bucketIdx - 1;\n var offset = bucketOffset[k];\n var count = bucketCounts[k];\n var end = offset + count;\n for (var i = offset; i < end; i++) {\n var idx_1 = bucketArray[i];\n var dx = positions[3 * idx_1 + 0] - x;\n var dy = positions[3 * idx_1 + 1] - y;\n var dz = positions[3 * idx_1 + 2] - z;\n var distSq = dx * dx + dy * dy + dz * dz;\n if (distSq <= rSq) {\n Query3D.QueryContext.add(ctx, distSq, idx_1);\n }\n }\n }\n }\n }\n }\n }", "function closest(node, cNodes) {\n\tnearNodes = [];\n let closest = window.innerWidth\n let toSend = false\n\tfor (let i = 0; i < cNodes.length; i++) {\n\t\tif (cNodes[i] != node) {\n\t\t\tlet distY = (parseInt(node.style.top)-parseInt(cNodes[i].style.top))*(parseInt(node.style.top)-parseInt(cNodes[i].style.top));\n\t\t\tlet distX = (parseInt(node.style.left)-parseInt(cNodes[i].style.left))*(parseInt(node.style.left)-parseInt(cNodes[i].style.left));\n\t\t\tlet dist = Math.sqrt(distY+distX);\n\t\t\tif (dist < closest) {\n closest = dist\n\t\t\t\ttoSend = cNodes[i]\n\t\t\t}\n\t\t}\n\t}\t\n return toSend;\n}", "function nearestCalc() {\n\tvar table = document.getElementById(\"markertable\");\n\t//Compare each marker to other markers if there are two or more markers\n\tif (Object.keys(markerDict).length > 1) {\n\t\tfor (var [key, marker] of Object.entries(markerDict)) {\n\t\t\tvar distList = []; //Helper array for selecting lowest distance\n\t\t\tvar smallest = 50000000; //Initialized with 50 000 km (more than max distance between two points on Earth)\n\t\t\tvar nearestMarker;\n\t\t\tfor (var [key2, marker2] of Object.entries(markerDict)) {\n\t\t\t\tif (markerDict[key] != markerDict[key2]) {\n\t\t\t\t\tvar dist = markerDict[key].getLatLng().distanceTo(markerDict[key2].getLatLng());\n\t\t\t\t\tdistList.push(dist); //All distances between markers to helper array\n\t\t\t\t\tif (dist < smallest) {\n\t\t\t\t\t\tvar smallest = dist;\n\t\t\t\t\t\tnearestMarker = key2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar minDist = Math.min(...distList); //Find the minimum value\n\t\t\t //current marker's coordinate string\n\t\t\tvar locationString = markerDict[key].getLatLng().lat.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ ', '\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ markerDict[key].getLatLng().lng.toString();\n\t\t\t//nearest marker's coordinate string\n\t\t\tvar neighbourString = markerDict[nearestMarker].getLatLng().lat.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ ', '\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ markerDict[nearestMarker].getLatLng().lng.toString();\n\t\t\tvar neighbourName;\n\t\t\t//Find nearest neighbour's name\n\t\t\tfor (var r = 1, i = table.rows.length; r < i; r++) {\n\t\t\t\tfor (var c = 0, j = table.rows[r].cells.length; c < j; c++) {\n\t\t\t\t\tif (table.rows[r].cells[c].innerHTML == neighbourString) {\n\t\t\t\t\t\tneighbourName = table.rows[r].cells[1].innerText;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Write distance and neighbourName to correct row\n\t\t\tfor (var r = 1, i = table.rows.length; r < i; r++) {\n for (var c = 0, j = table.rows[r].cells.length; c < j; c++) {\n\t\t\t\t\tif(table.rows[r].cells[c].innerHTML == locationString) {\n\t\t\t\t\t\ttable.rows[r].cells[4].innerHTML = neighbourName + \" / \" + minDist.toFixed(0) + \"m\"; //Removes decimals. toFixed(N) leaves N decimals in place.\n\t\t\t\t\t}\n }\n\t }\n\t\t}\n\t}\n}", "function closest_neighbor() {\n\t// Calculate neighbor for each shape\n\tshapes.forEach(function (item, index, arr) {\n\t//console.log(item);\n\t\n\t\tvar distances = []; // between on point an the rest\n\n\t\t// calculating distances\n\t\tfor (var i = 0; i < shapes.length ; i++) {\n\t\t\tlet delta_x = item.x - shapes[i].x;\n\t\t\tlet delta_y = item.y - shapes[i].y;\n\n\t\t\t//console.log(\"delta_x = item.x - shapes[i+1].x = \" + item.x + \" - \" + shapes[i+1].x + \" = \" + delta_x);\n\t\t\t//console.log(\"delta_y = item.y - shapes[i+1].y = \" + item.y + \" - \" + shapes[i+1].y + \" = \" + delta_y);\n\n\t\t\tdistances[i] = Math.sqrt( delta_x*delta_x + delta_y*delta_y);\n\n\t\t\t//var next_shape_idx = i+1;\n\t\t\t//console.log(\"distance [\"+ index +\" to \"+ next_shape_idx + \"] = \" + distances[i]);\n\t\t}\n\n\t\t// Look for smallest distance and assign it as neighbor\n\t\tshapes[index].neighbor = index_of_min(distances, 0);\n\t});\n}", "function nearestCentroidIndex(d) {\n\t\tvar minIndex = getCentroidIndex(focusCentroids[0]);\n\t\tvar minDistance = euclideanDistance(d.x, d.y, focusCentroids[0].x, focusCentroids[0].y);\n\n\t\tfocusCentroids.forEach(function(c, i) {\n\t\t\t// Calculate the distance to each centroid and return the closest\n\t\t\tdistance = euclideanDistance(d.x, d.y, c.x, c.y);\n\t\t\tif (distance < minDistance) {\n\t\t\t\tminDistance = distance;\n\t\t\t\tminIndex = getCentroidIndex(c);\n\t\t\t}\n\t\t});\n\t\treturn minIndex;\n\t}", "function findSmallestDistance(){\n\tvar minimum=100000;\n\tvar node=-1;\n\tunvisited.forEach(function(item){\n\t\tif(distance[item]<=minimum){\n\t\t\tminimum=distance[item];\n\t\t\tnode=item;\n\t\t}\n\t})\n\tif(node==-1){\n\t\tconsole.log(\"this should never happen\");\n\t}\n\treturn node;\n}", "findCell(x, y) {\n // `Number >> 4` effectively does an integer division by 16\n // and `Number << 4` multiplies by 16 this notation is used to avoid floats\n x = (x >> 4) << 4; // x = Math.floor((x / this.root.min) * this.root.min)\n y = (y >> 4) << 4; // y = Math.floor((y / this.root.min) * this.root.min)\n\n return this._findCell(x, y, this.root);\n }", "function closestCentroid(point, centroids, distance) {\n var min = Infinity,\n index = 0;\n for (var i = 0; i < centroids.length; i++) {\n var dist = distance(point, centroids[i]);\n if (dist < min) {\n min = dist;\n index = i;\n }\n }\n return index;\n}", "function findBestPointInCell2(idx) {\n var r = idxToRow(idx);\n var c = idxToCol(idx);\n var perSide = 4;\n var maxDist = 0;\n var dist, p, bestPoint;\n for (var i=0; i<perSide; i++) {\n for (var j=0; j<perSide; j++) {\n p = getGridPointInCell(c, r, i, j, perSide);\n dist = findDistanceFromNearbyFeatures(maxDist, p, c, r);\n if (dist > maxDist) {\n maxDist = dist;\n bestPoint = p;\n }\n }\n }\n bestPoints[idx] = bestPoint;\n return maxDist;\n }", "function heuristic(a, b) {\n return dist(a.row, a.col, b.row, b.col);;\n}", "getMinL1(pos, dir, target){\n \n let adjascent = this.getAdjascent(pos, dir);\n \n // Sort from smallest L1 norm to largest. We will prioritize the\n // smallest one.\n adjascent.sort((a, b) => {\n \n return this.normL1(a, target) > this.normL1(b, target);\n \n });\n \n \n // Loop through the adjascent cells and take the first one that it can\n let move = adjascent.shift();\n while(move){\n \n if(this.map.canMoveTo(move)){\n \n return move;\n \n }\n \n move = adjascent.shift();\n \n }\n \n }", "function nearest(rel_x) {\n var x_date = timescale.invert(rel_x),\n min_dist = Number.MAX_VALUE,\n nearest_row = 0;\n // find nearest date\n column.each(function(date, i) {\n var dist = Math.abs(date.getTime() - x_date.getTime());\n if (dist < min_dist) {\n min_dist = dist;\n nearest_row = i;\n }\n });\n return nearest_row;\n }", "function nearest(x,y,obj,n) {\n let all_distance = [] \n if (obj.length > 1 && n<=obj.length) {\n for (let i = 0; i < obj.length; i++) {\n all_distance[i] = distance(x,y,obj[i].x,obj[i].y) \n }\n all_distance = sort(all_distance);\n for (let i = 0; i < obj.length; i++) {\n if (distance(x,y,obj[i].x,obj[i].y)==all_distance[n]) return obj[i] \n }\n }\n}", "function getNeighborhood(userLat, userLong, evictionPts) {\n var d = 0.5,\n temp;\n var nearest;\n\n for (var i = 0; i < evictionPts.length; i++) {\n evLat = parseFloat(evictionPts[i]['lat']);\n evLong = parseFloat(evictionPts[i]['long']);\n\n temp = calculateDist(userLat, userLong, evLat, evLong);\n\n if (temp < d) {\n d = temp;\n nearest = evictionPts[i];\n }\n\n }\n //console.log(d);\n return nearest;\n}", "function cell() {\n //Pontos com coordenadas normalizadas (0 a 1)\n const pts = []\n pts.push(new Vector2(.25, .25));\n pts.push(new Vector2(.75, .25));\n pts.push(new Vector2(.75, .75));\n pts.push(new Vector2(.25, .75));\n pts.push(new Vector2(.5, .5));\n\n for (let i = 0; i < X; i++) {\n for(let j = 0; j < Y; j++) {\n\n var min_dist = Infinity;\n\n pts.forEach(e => {\n min_dist = Math.min(e.distance(new Vector2(i/X, j/Y)), min_dist);\n \n });\n canvasBefore[idx(i, j)].add(min_dist);\n }\n }\n}", "function getClosestCells(_currPos, gridDiv, gridW, gridH)\n{\n var neighbors = [];\n var boxWidth = gridW / gridDiv;\n var boxHeight = gridH / gridDiv;\n var _startX = 0.0;\n var _startY = 0.0;\n var _endX = 0.0;\n var _endY = 0.0;\n\n //establish current grid cell boundaries of agent\n for(var i = 0; i < gridW; i += boxWidth)\n {\n if(_currPos.x >= i && _currPos.x <= i + boxWidth)\n {\n _startX = i;\n _endX = i + boxWidth;\n }\n }\n\n for(var j = 0; j < gridH; j += boxHeight)\n {\n if(_currPos.z >= j && _currPos.z <= j + boxHeight)\n {\n _startY = j;\n _endY = j + boxHeight;\n }\n }\n\n //boundary cases\n if(_startX == 0)\n {\n _startX += boxWidth;\n }\n if(_startX == 20)\n {\n _startX -= boxWidth;\n }\n\n if(_startY == 0)\n {\n _startY += boxHeight;\n }\n if(_startY == 20)\n {\n _startY -= boxHeight;\n }\n\n if(_endX == 20)\n {\n _endX -= boxWidth;\n }\n if(_endY == 20)\n {\n _endY -= boxHeight;\n }\n\n //either multiply the values in if cases by 2 or subtract and add boxWidth and boxHeight here\n neighbors.push({startX: _startX - boxWidth, startY: _startY - boxHeight, endX: _endX + boxWidth, endY: _endY + boxHeight});\n\n return neighbors;\n}", "function nearestPoint(candidatePoints, points) {\n\n}", "searchSimpler(pos, dist) {\n const dist2 = dist * dist;\n // ideal search bounds:\n const bl = pos[0] - dist;\n const br = pos[0] + dist;\n const bt = pos[1] - dist;\n const bb = pos[1] + dist;\n // limited cell search bounds:\n const rCellSize = 1 / this.cellSize;\n const cellH = Math.max(~~(bl * rCellSize), 0);\n const cellH2 = Math.min(~~(br * rCellSize), this.numCellsH - 1);\n const cellV = Math.max(~~(bt * rCellSize), 0);\n const cellV2 = Math.min(~~(bb * rCellSize), this.numCellsV - 1);\n // apparently faster to name variables outside the loops\n let v, h, cell, l, n, npos, relx, rely, d2;\n let res = [];\n // might be able to speed this up by caching the set of cell offests to search for a given radius\n // (which, if arranged as a spiral, could also do a pseudo distance sort for free)\n for (v = cellV; v <= cellV2; v++) {\n for (h = cellH; h <= cellH2; h++) {\n cell = this.cells[v * this.numCellsH + h];\n l = cell.length;\n for (n = 0; n < l; n++) {\n npos = cell[n].pos;\n (relx = npos[0] - pos[0]), (rely = npos[1] - pos[1]);\n d2 = relx * relx + rely * rely;\n if (d2 <= dist2) {\n res.push(cell[n]);\n }\n }\n }\n }\n return res;\n }", "function NearestPoint(thePoint, theGrid) {\n //default x,y values\n this.x = 32;\n this.y = 32;\n\n var answer = this.findNearestPoint(thePoint, theGrid);\n this.x = answer[0];\n this.y = answer[1];\n\n}", "function getNearestThing(device, minDistance, callback) {\n\tvar nearest = null;\n\tvar nearestDistance = -1;\n\n\tflaredb.Thing.find({environment:device.environment}, function (err, things) {\n\n\t\tfor (var i = 0; i < things.length; i++) {\n\t\t\tvar thing = things[i];\n\t\t\tvar distance = distanceBetween(device.position, thing.position);\n\t\t\n\t\t\tif (distance != -1 && distance < minDistance && \n\t\t\t\t(nearestDistance == -1 || distance < nearestDistance)) \n\t\t\t{\n\t\t\t\tnearestDistance = distance;\n\t\t\t\tnearest = thing;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcallback(nearest);\n\t});\n}", "function findClosestLoc(x, y, arr, grid) {\n var shortestPath = Math.abs(arr[0][0] - x) + Math.abs(arr[0][1] - y);\n closestPoint = \"\";\n\n for (var i = 0; i < arr.length; i++) {\n var dist = Math.abs(arr[i][0] - x) + Math.abs(arr[i][1] - y);\n if (dist < shortestPath) {\n shortestPath = dist;\n closestPoint = grid[arr[i][0]][arr[i][1]];\n } else if (dist === shortestPath) {\n closestPoint = \".\";\n }\n }\n\n\n // console.log(shortestPath + \" to \" + closestPoint);\n return closestPoint;\n}", "function calc_dist(first_cell, second_cell) {\n // Distance formula = sqrt((x2 - x1)^2 + (y2-y1)^2)\n let h_cost_estimation = (Math.sqrt(Math.pow((second_cell.x_pos - first_cell.x_pos), 2) + \n Math.pow((second_cell.y_pos - first_cell.y_pos), 2))) * 10;\n return Math.floor(h_cost_estimation);\n}", "get_nearest_node(ignore_id=-1) {\n let min_dist = 1000000000;\n let best_id = -1;\n for(let i = 0; i < this.nodes.length; i++) {\n let n = this.nodes[i];\n let dist = (mouse.x-n.x)*(mouse.x-n.x)+(mouse.y-n.y)*(mouse.y-n.y);\n if(dist < min_dist && ignore_id != i) {\n min_dist = dist;\n best_id = i;\n }\n }\n return best_id;\n }", "distance(cell1, cell2) {\n return Math.sqrt(\n (\n Math.pow(cell2.x - cell1.x, 2) +\n Math.pow(cell2.y - cell1.y, 2)\n )\n );\n }", "function calcNewPosNearestNeighbour(position, positions) {\n if (positions.size() === 0) {\n return 0.0;\n }\n\n let j; // int\n let lowest_dist= (positions[0].first - position.first ) * (positions[0].first - position.first ) + (positions[0].second - position.second) * (positions[0].second - position.second),\n distance = 0.0;\n\n for (j = 1; j < positions.size(); ++j) {\n distance = (positions[j].first - position.first ) * (positions[j].first - position.first ) + (positions[j].second - position.second) * (positions[j].second - position.second);\n if(lowest_dist>distance) {\n lowest_dist = distance;\n }\n }\n return lowest_dist;\n}", "function minDistance(square, goal) {\n var horizDiff = Math.abs(goal.x - square.x);\n var vertDiff = Math.abs(goal.y - square.y);\n return Math.min(horizDiff, vertDiff);\n}", "function getClosestCellID(X, Y) {\r\n //$('#hackstatus').html('searching for cell id near mouse ' + X + ',' + Y);\r\n var cells = unsafeWindow.allCells;\r\n //console.log(cells);\r\n // Loop through all the cells and extract JUST the players\r\n var playerCells = [];\r\n apc=[];\r\n for (var i in cells) {\r\n var playerCell = cells[i];\r\n // Ignore food pellets & tiny cells\r\n if (playerCell.isFood || playerCell.size < 35) {\r\n continue;\r\n }\r\n // F is old agarplus obfuscated isVirus flag\r\n if (playerCell.f || playerCell.isVirus) {\r\n continue;\r\n }\r\n console.log(playerCell);\r\n // Calculate the x and y distances\r\n var distx = playerCell.x - X;\r\n var disty = playerCell.y - Y;\r\n // calculates distance between two X,Y points\r\n var distance = Math.sqrt( Math.pow(distx, 2) + Math.pow(disty, 2) );\r\n // save our player cell info\r\n var razorCell = {};\r\n razorCell.id = i;\r\n razorCell.name = playerCell.name;\r\n razorCell.distance = distance;\r\n razorCell.size = playerCell.size;\r\n razorCell.x = playerCell.x;\r\n razorCell.y = playerCell.y;\r\n razorCell.uid=playerCell.extra.uid;\r\n razorCell.skinUrl=playerCell.extra.skinUrl;\r\n //console.log(playerCell.name+\"\\'s teamHash: \"+playerCell.extra.teamHash);\r\n razorCell.team=playerCell.extra.teamHash;\r\n razorCell.pid=playerCell.extra.pid;\r\n playerCells.push(razorCell);\r\n\r\n if (apc.length<1){\r\n apc.push(razorCell);\r\n }\r\n var found=false;\r\n for (var cell in apc){\r\n var c=apc[cell];\r\n //compare if the cell belongs to same player or if it's a coin\r\n if (razorCell.pid==c.pid){\r\n found=true;\r\n break;\r\n }\r\n }\r\n if(!found){\r\n apc.push(razorCell);\r\n }\r\n\r\n }\r\n allcb=[];\r\n $('#pannel').html(\"\");\r\n //console.log(apc);\r\n apc.sort(function (a, b) { return a.distance - b.distance; });\r\n for (var a in apc){\r\n var b=apc[a];\r\n var pd=document.createElement(\"LI\");\r\n var img = document.createElement(\"img\");\r\n img.style=\"height:50px; width:50px;\";\r\n img.setAttribute('src', b.skinUrl);\r\n var cb = document.createElement(\"INPUT\");\r\n cb.setAttribute(\"type\", \"checkbox\");\r\n cb.value=b.pid;\r\n allcb.push(cb);\r\n pd.append(cb);\r\n pd.append(img);\r\n pd.append(b.name);\r\n $('#pannel').append(pd);\r\n }\r\n //console.log(playerCells);\r\n // Sort the cells by distance ascending\r\n playerCells.sort(function (a, b) { return a.distance - b.distance; });\r\n //console.log('closest player identified: ');\r\n //console.table(playerCells.slice(0, 1));\r\n if (playerCells.length) {\r\n return playerCells[0].id;\r\n } else {\r\n return 0;\r\n }\r\n}", "function calcPoint(currentPoint) {\n var distances = new Array(); // make array for the distances\n for(let point of points){\n\n // call distance function\n var distance = getDistance(point[2], point[3], Number(currentPoint[2]), Number(currentPoint[3]));\n\n // put the distance from the boat to the point in an array\n var location = new Array();\n location[0] = point[0];\n location[1] = Number(distance)*1000; // *1000 to get meters instead of km's \n location[2] = point[2];\n location[3] = point[3];\n distances.push(location); // add current position and distance to boat to distances array\n }\n\n distances.sort(compareSecondColumn); // sort the array by the distances\n\n var closestPoint = distances[0]; // take the lowest distance\n\n distances.shift(); // 2.2 remove the used point from the distances\n points = distances; // and replace the points array with the remaining items of the distances array\n\n return closestPoint; // return the closest point\n}", "function findBestPointInSubCell(c, r, c1, r1, z) {\n // using a 3x3 grid instead of 2x2 ... testing showed that 2x2 was more\n // likely to misidentify the sub-cell with the optimal point\n var q = 3;\n var perSide = Math.pow(q, z); // number of cell divisions per axis at this z\n var maxDist = 0;\n var c2, r2, p, best, dist;\n for (var i=0; i<q; i++) {\n for (var j=0; j<q; j++) {\n p = getGridPointInCell(c, r, c1 + i, r1 + j, perSide);\n dist = findDistanceFromNearbyFeatures(maxDist, p, c, r);\n if (dist > maxDist) {\n maxDist = dist;\n best = p;\n c2 = i;\n r2 = j;\n }\n }\n }\n if (z == 2) { // stop subdividing the cell at this level\n best.push(maxDist); // return distance as third element\n return best;\n } else {\n return findBestPointInSubCell(c, r, (c1 + c2)*q, (r1 + r2)*q, z + 1);\n }\n }", "function nearest_vertex(vertexes, point){\n var nearest = 0;\n var diffx = parseInt(vertexes[nearest]['x']) - parseInt(point['x']);\n var diffy = parseInt(vertexes[nearest]['y']) - parseInt(point['y']);\n var nearest_dist = Math.sqrt((diffx*diffx) + (diffy*diffy));\n var dist;\n for(i=1; i<vertexes.length; i++){\n diffx = parseInt(vertexes[i]['x']) - parseInt(point['x']);\n diffy = parseInt(vertexes[i]['y']) - parseInt(point['y']);\n dist = Math.sqrt((diffx*diffx) + (diffy*diffy));\n if(dist<nearest_dist){\n nearest = i;\n nearest_dist = dist;\n }\n }\n return nearest;\n}", "function bestStat(coord, data) {\n var best;\n var minDist = Number.POSITIVE_INFINITY;\n for (key in data) {\n var currVal = euclideanDist(coord, data[key]);\n if (currVal < minDist) {\n minDist = currVal;\n best = key;\n }\n }\n return best;\n}", "getLowestDistanceNode(unsettledNodes) {\n let lowest = null\n let lowestDistance = Number.MAX_SAFE_INTEGER\n for (let i = 0; i < unsettledNodes.length; i++) {\n let nodeDistance = unsettledNodes[i].distance\n if (nodeDistance < lowestDistance) {\n lowestDistance = nodeDistance\n lowest = unsettledNodes[i]\n }\n }\n\n return lowest;\n }", "function calculateNearestCity(latitude, longitude) {\n // Convert Degrees to Radians\n function Deg2Rad(deg) {\n return deg * Math.PI / 180;\n }\n function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {\n lat1 = Deg2Rad(lat1);\n lat2 = Deg2Rad(lat2);\n lon1 = Deg2Rad(lon1);\n lon2 = Deg2Rad(lon2);\n var R = 6371; // km\n var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);\n var y = lat2 - lat1;\n var d = Math.sqrt(x * x + y * y) * R;\n return d;\n }\n var minDif = 99999;\n var closest = locationsList.default;\n\n // loop through each location, matching a close city then the next closest and so on\n for (var key in locationsList) {\n /* eslint-disable no-prototype-builtins */\n if (locationsList.hasOwnProperty(key)) {\n /* eslint-enable no-prototype-builtins */\n if (key != \"default\") {\n var evalutedLocation = locationsList[key];\n var dif = PythagorasEquirectangular(latitude, longitude, evalutedLocation.latlon.split(\", \")[0], evalutedLocation.latlon.split(\", \")[1]);\n if (dif < minDif) {\n closest = evalutedLocation;\n closest.id = key;\n minDif = dif;\n }\n }\n }\n }\n return closest;\n }", "function shortestCellPath(grid, sr, sc, tr, tc) {\n\t/**\n\t@param grid: integer[][]\n\t@param sr: integer\n\t@param sc: integer\n\t@param tr: integer\n\t@param tc: integer\n\t@return: integer\n\t*/\n const nr = grid.length\n const nc = grid[0].length\n const queue = []\n\n grid[sr][sc] = -1\n\n queue.push({coords: [sr, sc], distance: 0})\n\n\n while (queue.length) {\n let current = queue.shift()\n let cr = current.coords[0]\n let cc = current.coords[1]\n let distance = current.distance\n\n let directions = [[cr, cc+1], [cr+1, cc], [cr, cc-1], [cr-1, cc]]\n\n for (const dir of directions) {\n const r = dir[0]\n const c = dir[1]\n\n if (r === tr && c === tc) {\n return distance + 1\n }\n\n if (isInBounds(r, c, nr, nc) && grid[r][c] === 1) {\n const newDistance = distance + 1\n\n grid[r][c] = -1\n queue.push({coords: [r, c], distance: newDistance})\n }\n }\n }\n\n return -1\n}", "static _getClosest(dungeon, openSpaces){\n var bestValue = Infinity;\n var bestIndex = -1;\n for (var i = 0; i < openSpaces.length; i++) {\n var test = Utils.coordinateHypo(openSpaces[i], dungeon.hero.location);\n if (test < bestValue){\n bestValue = test;\n bestIndex = i;\n }\n }\n return openSpaces[bestIndex];\n }", "function findNearest(elements, position) {\n var maxDistance = 30; // Defines the maximal distance of the cursor when the menu is displayed\n var nearestItem = null;\n var nearestDistance = maxDistance;\n var posX = position.x + ___WEBPACK_IMPORTED_MODULE_0__[\"QuickE\"].win.scrollLeft();\n var posY = position.y + ___WEBPACK_IMPORTED_MODULE_0__[\"QuickE\"].win.scrollTop();\n // Find nearest element\n elements.each(function () {\n var e = Positioning.get(Object(_interfaces_sxc_controller_in_page__WEBPACK_IMPORTED_MODULE_1__[\"$jq\"])(this));\n // First check x coordinates - must be within container\n if (posX < e.x || posX > e.x + e.w)\n return;\n // Check if y coordinates are within boundaries\n var distance = Math.abs(posY - e.yh);\n if (distance < maxDistance && distance < nearestDistance) {\n nearestItem = e;\n nearestDistance = distance;\n }\n });\n return nearestItem;\n}", "findNeighbourCells(cell, distance) {\n let { resolution } = this.canvas;\n\n let neighbourCells = [];\n\n // Iterates through all surounding directions.\n for (let i = -1; i <= 1; i++) {\n for (let j = -1; j <= 1; j++) {\n // Only accepts indexes between the bounds of the bidimensional array.\n if (\n cell.x + i >= 0 &&\n cell.x + i < resolution &&\n cell.y + j >= 0 &&\n cell.y + j < resolution\n ) {\n // Excludes diagonal neighbours.\n if (Math.abs(i) ^ Math.abs(j)) {\n neighbourCells.push(\n this.cells[cell.x + i * distance][cell.y + j * distance]\n );\n }\n }\n }\n }\n\n return neighbourCells;\n }", "function heuristic(x, y) {\n // Chebyshev/Octile distance - best suited for 8-way movement, also consistent\n // return Math.max(Math.abs(x - tileColumnCount - 1), Math.abs(y - tileRowCount - 1));\n // Euclidean distance - not monotone or consistent (h(x) <= d(x,y) + h(y))\n // return Math.sqrt((x - tileColumnCount - 1)**2 + (y - tileRowCount - 1)**2);\n // Manhattan distance - not consistent\n return (Math.abs(x - tileColumnCount - 1) + Math.abs(y - tileRowCount - 1));\n}", "function findClosestInSuggestedPath(x,y){\n var closest = 0;\n\n var mdist = 2000;\n\n var dist_x = 0;\n var dist_y = 0;\n\n for (var i = 0; i < suggestedPathPoints.length; i++) {\n dist_x = Math.abs(suggestedPathPoints[i].x - x);\n dist_y = Math.abs(suggestedPathPoints[i].y - y);\n\n if(dist_x + dist_y < mdist){\n mdist= dist_x + dist_y;\n closest = i;\n }\n }\n\n return closest;\n}", "function miniMapDistance(x, y)\n{\n\treturn Math.sqrt(Math.pow(x - 0, 2) + Math.pow(y - 0, 2));\n}", "querywrap(x, y, r)\n {\n if (r > this.maxRadius) r = this.maxRadius;\n\n // Squared distance\n let rsq = r * r;\n\n // Which cell are we in?\n let cellcentrex = (x - (this.mod(x, this.xcellsize))) / this.xcellsize;\n let cellcentrey = (y - (this.mod(y, this.ycellsize))) / this.ycellsize;\n\n // Use diagonal extent to find the cell range to search\n let cellminx = ((x - r) - (this.mod((x - r), this.xcellsize))) / this.xcellsize;\n let cellminy = ((y - r) - (this.mod((y - r), this.ycellsize))) / this.ycellsize;\n let cellmaxx = ((x + r) - (this.mod((x + r), this.xcellsize))) / this.xcellsize;\n let cellmaxy = ((y + r) - (this.mod((y + r), this.ycellsize))) / this.ycellsize;\n\n // console.log(`Checking numcells ${cellmaxx - cellminx}, ${cellmaxy - cellminy}`);\n\n let objs = [];\n\n if ((cellmaxy - cellminy) >= this.numcells) cellmaxy = cellminy + this.numcells - 1;\n if ((cellmaxx - cellminx) >= this.numcells) cellmaxx = cellminx + this.numcells - 1;\n\n for (let cy=cellminy; cy<=cellmaxy; cy++)\n {\n for (let cx=cellminx; cx<=cellmaxx; cx++)\n {\n let wx = this.wrap(cx), wy = this.wrap(cy);\n\n // if (once[wy][wx]) continue;\n // once[wy][wx] = 1;\n\n let cell = this.grid[wy][wx]\n if (!cell) continue;\n\n for (let t=0; t<cell.length; t++)\n {\n let item = cell[t];\n let pos = item;\n if (this.prop) pos = item[this.prop]\n let d = this.distsq(pos.x, pos.y, x, y);\n if (d <= rsq) objs.push(item);\n }\n }\n }\n\n return objs;\n }", "function NearestCity(latitude, longitude) {\r\n var mindif = 99999;\r\n var closest;\r\n /*for (index = 0; index < positions.length; ++index) {\r\n var dif = PythagorasEquirectangular(latitude, longitude, positions[index][0], positions[index][1]);\r\n if (dif < mindif) {\r\n closest = index;\r\n mindif = dif;\r\n }\r\n }*/\r\n jQuery.each(positions, function(i, val) {\r\n var dif = PythagorasEquirectangular(latitude, longitude, val.lat, val.long);\r\n if (dif < mindif) {\r\n closest = i;\r\n mindif = dif;\r\n }\r\n });\r\n // echo the nearest city\r\n //console.log($(\".r27_map[data-index='\" + closest + \"']\").closest('.contact-detail'), closest);\r\n //$(\".r27_map[data-index='\" + closest + \"']\").closest('.contact-detail').insertAfter($(\".location-list\"));\r\n }", "function shortestDistance(a, b, c) {\n return Math.min(\n Math.sqrt(a ** 2 + (b + c) * (b + c)),\n Math.sqrt(b ** 2 + (a + c) * (a + c)),\n Math.sqrt(c ** 2 + (a + b) * (a + b))\n );\n}", "function findMines() {\n for (let i = 0; i < numSquaresY; i++) {\n for (let j = 0; j < numSquaresX; j++) {\n board[i][j].calculateAdjacentMines();\n }\n }\n}", "function getMin(distances) {\n let vertex = null;\n let min = -1;\n for (let key in distances) {\n let value = distances[key];\n if (min == -1) {\n min = value;\n vertex = key;\n }\n else if(min > value) {\n min = value;\n vertex = key;\n }\n }\n delete distances[vertex];\n return Number(vertex);\n}", "function FindMinPath( seeds, sIndex, eIndex, tollerance ){\n\n const noValue =-1; // and invalid index\n const length = (u,v) => dist(seeds[u],seeds[v]);\n\n let path = []; // indexes for which we found the min path\n let front=[sIndex]; // point for which we just found the min path. We need to analyze their connections.\n let ends = seeds.map((v,i)=>i); // indexes of all the element which which don't have the min path\n let prev = seeds.map((v)=>noValue); // for the indexes in 'path' the index which connets them. It is used to determine teh actual path. See below.\n\n while( front.length > 0 && !path.includes(eIndex)){\n ends = ends.filter((i)=>!front.includes(i)); // remove the element of the path from the ends.\n // for each element in end, find the nearest element in the `front` set\n let nearest= ends.map((e)=>{\n let dsts =front.map((p)=>length(e,p));\n let minDst = Math.min(...dsts);\n let minIdx = dsts.indexOf(minDst);\n return minDst < tollerance ? front[minIdx] : noValue;\n }\n )\n // add the path on front to the actual path\n path = path.concat(front);\n // clen up the front indexes\n front = [];\n // for each point in nearest add to path and prev\n nearest.forEach((v,i)=>{\n if( v!= noValue){\n prev[ends[i]] = v;\n front.push(ends[i]);\n }\n });\n }\n\n let pathIndexes = null;\n if( path.includes(eIndex) ){\n pathIndexes = [];\n let p = eIndex;\n while( p!= sIndex ){\n p=prev[p];\n pathIndexes.push(p);\n }\n pathIndexes.reverse(); // so we start with sIndex and finish with eIndex\n }\n return pathIndexes;\n}", "function findNearestGridlineValue(position) {\n\tif ((position % gridlineSpacing) > gridlineSpacing / 2) {\n\t\treturn position - (position % gridlineSpacing) + gridlineSpacing\n\t} else {\n\t\treturn position - (position % gridlineSpacing)\n\t}\n}", "function nearestToilet(latitude, longitude) {\r\n var mindif = 99999;\r\n var closest;\r\n\r\n for (index = 0; index < cities.length; ++index) {\r\n var dif = pythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);\r\n if (dif < mindif) {\r\n closest = index;\r\n mindif = dif;\r\n }\r\n }\r\n // echo the nearest city\r\n alert(cities[closest]);\r\n}", "function findNearestVirus(cell, blobArray){\n var nearestVirus = _.min(_.filter(blobArray, \"isVirus\", true), function(element) {\n return lineDistance(cell, element);\n });\n\n if( Infinity == nearestVirus){\n //console.log(\"No nearby viruses\");\n return -1;\n }\n return nearestVirus;\n }", "function minDistance(origin, destinations) {\n return destinations.reduce(\n (min, dest) => Math.min(min, distance(origin, dest)),\n 20000 // slightly larger than greatest distance possible between two coordinates\n );\n}", "function findClosestSampledPoint() {\n var i,\n distSquared,\n smallestDist,\n xDelta, yDelta,\n indexOfSmallest;\n \n for (i = 0; i < numSamples; i++) {\n \n if (!(GSP.math.isFiniteScalar(samples[i*2]) && GSP.math.isFiniteScalar(samples[i*2+1]))) {\n continue;\n }\n \n xDelta = samples[i*2] - iPosition.x;\n yDelta = samples[i*2+1] - iPosition.y;\n\n distSquared = xDelta * xDelta + yDelta * yDelta;\n\n if ((smallestDist === undefined) || \n (distSquared < smallestDist)) {\n smallestDist = distSquared;\n indexOfSmallest = i;\n }\n }\n\n return {\n \"point\": GSP.GeometricPoint(samples[indexOfSmallest*2],\n samples[indexOfSmallest*2+1]),\n \"index\": indexOfSmallest};\n }", "function minDistance(Q, dist) {\n\tvar minValue = 1000000000000000;\n\tvar index = null;\n\tfor (var i = 0; i < dist.length; i++) {\n\t\tif (dist[i] < minValue) {\n\t\t\tminValue = dist[i];\n\t\t\tindex = i;\n\t\t}\n\t}\n\treturn Q[index];\n}", "findClosestDistance(arr) {\n var minDist = -1;\n var object = null;\n for (var i = 0; i < arr.length; i++) {\n var distance = this.findDistance(arr[i]);\n if (object === null || distance < minDist) {\n minDist = distance;\n object = arr[i];\n }\n }\n return minDist;\n }", "updateNearest() {\n this._sources = this._sources.sort((a, b) => {\n return ( this.p.dist(this.pos.x, this.pos.y, a.pos.x, a.pos.y) - this.p.dist(this.pos.x, this.pos.y, b.pos.x, b.pos.y));\n });\n \n if (this.nearest != this._sources[0]) {\n this.nearest = this._sources[0];\n }\n }", "function nearestIndex(xpos) {\r\n var begin = 0;\r\n var fin = g_linedata.length - 1;\r\n var middle;\r\n while (begin < fin) {\r\n middle = Math.floor((begin + fin) / 2);\r\n if (g_linedata[middle][0] < xpos) begin = middle + 1;\r\n else fin = middle;\r\n }\r\n var nearest = 0;\r\n if (fin != 0) nearest = xpos - g_linedata[fin - 1][0] < g_linedata[fin][0] - xpos ? fin - 1 : fin;\r\n return nearest;\r\n }", "getNearestDiamond(x, y, diamondPos) {\n\n /** If the diamonds array is empty, do not calculate the position*/\n if(diamondPos.length<=0) {\n return null;\n }\n\n let tempTotal = 0;\n let shorttestTotal = this.xMax + this.yMax;\n let shortestPos = {};\n let dx;\n let dy;\n\n for (let z = 0; z < diamondPos.length; z++) { \n dx = Number(diamondPos[z].split(\",\")[1]);\n dy = Number(diamondPos[z].split(\",\")[0]);\n tempTotal = Math.abs(dx - x) + Math.abs(dy - y);\n\t\t\tif (tempTotal < shorttestTotal) {\n shorttestTotal = tempTotal;\n shortestPos.x = dx;\n shortestPos.y = dy; \n\t\t\t}\n }\n return shortestPos;\n }", "function getIndexOfMinDistance(waypoints){\n\tindex = 0;\n\tminDistance = 0;\n\tfor(var i = 0; i < waypoints.length; i++){\n\t\tif(i == 0 || waypoints[i].distance < minDistance){\n\t\t\tminDistance = waypoints[i].distance;\n\t\t\tindex = i;\n\t\t}\n\t}\n\treturn index;\n}", "function getFirstFillPoint() {\n var p;\n if (!shuffledIds) {\n shuffledIds = utils.range(cells);\n utils.shuffle(shuffledIds);\n }\n while (++cellId < cells) {\n p = getRandomPointInCell(shuffledIds[cellId]);\n if (pointIsUsable(p)) {\n return p;\n }\n }\n }", "function euclidian_distance(row, col, dest) {\n return Math.sqrt(\n (row - dest.first) * (row - dest.first) +\n (col - dest.second) * (col - dest.second)\n );\n}", "function nearestVertex(vertex, size_x, size_y) {\n return Vertex(Math.min(size_x, Math.max(-size_x, vertex.x)),\n Math.min(size_y, Math.max(-size_y, vertex.y)));\n}", "function getClosestWrench(bot, wrenches) {\n var minDist = maxInt;\n var minI = -1;\n //var distances = [];\n for (var i = 0; i < wrenches.length; i++) {\n dist = getDistance(bot.x, bot.y, wrenches[i].x, wrenches[i].y);\n if (dist < minDist) {\n minDist = dist;\n minI = i;\n }\n //distances.push(dist);\n }\n \n //console.log(distances);\n return {i: minI, dist: minDist}\n}", "function gridDistances() {\n for (var row = 1; row < grid.height + 1; row++) {\n for (var col = 1; col < grid.width + 1; col++) {\n\n var id = row + \".\" + col;\n\n var cell = document.getElementById(id);\n var d = distanceToTarget(id);\n\n cell.innerHTML = d;\n\n }\n }\n}", "function getSnapPoint() {\n // Store each difference between current position and each snap point.\n var currentDiff;\n\n // Store the current best difference.\n var minimumDiff;\n\n // Best snap position.\n var snapIndex;\n\n // Loop through each snap location\n // and work out which is closest to the current position.\n var i = 0;\n for(; i < snapPoints.length; i++) {\n // Calculate the difference.\n currentDiff = Math.abs(positionX - snapPoints[i]);\n \n // Works out if this difference is the closest yet.\n if(minimumDiff === undefined || currentDiff < minimumDiff) {\n minimumDiff = currentDiff;\n snapIndex = i;\n }\n }\n return snapIndex;\n }", "function closestStraightCity(c, x, y, q) {\n // Write your code here\n let result = [];\n\n for (let i = 0; i < c.length; i++) {\n let city = c[i];\n let x_coord = x[i];\n let y_coord = y[i];\n let x_dist = Math.max.apply(null, x);\n let nearest_x_idx = null;\n\n for (let j = 0; j < y.length; j++) {\n if (j !== i && y_coord === y[j]) {\n let tempDistX = Math.abs(x[i] - x[j]);\n if (tempDistX !== 0 && x_dist >= tempDistX) {\n if (x_dist > tempDistX) {\n x_dist = tempDistX;\n nearest_x_idx = j;\n } else if (x_dist === tempDistX) {\n if (q[j] > q[nearest_x_idx]) {\n x_dist = tempDistX;\n nearest_x_idx = j;\n } else {\n continue;\n }\n }\n }\n }\n }\n\n let x_result = c[nearest_x_idx] ? c[nearest_x_idx] : null;\n\n let y_dist = Math.max.apply(null, y);\n let nearest_y_idx = null;\n\n for (let k = 0; k < x.length; k++) {\n if (k !== i && x_coord === x[k]) {\n let tempDistY = Math.abs(y[i] - y[k]);\n if (tempDistY !== 0 && y_dist >= tempDistY) {\n if (y_dist > tempDistY) {\n y_dist = tempDistY;\n nearest_y_idx = k;\n } else if (y_dist === tempDistY) {\n if (q[k] > q[nearest_y_idx]) {\n y_dist = tempDistY;\n nearest_y_idx = k;\n } else {\n continue;\n }\n }\n }\n }\n }\n\n let y_result = c[nearest_y_idx] ? c[nearest_y_idx] : null;\n\n if (x_result) {\n result.push(x_result);\n } else if (y_result) {\n result.push(y_result);\n } else {\n result.push(\"NONE\");\n }\n }\n\n return result;\n}", "query(item, r)\n {\n if (r > this.maxRadius) r = this.maxRadius;\n\n let pos = item;\n if (this.prop)\n pos = item[this.prop];\n\n // Squared distance\n let rsq = r * r;\n\n // Use diagonal extent to find the cell range to search\n let cellminx = ((pos.x - r) - (this.mod((pos.x - r), this.xcellsize))) / this.xcellsize;\n let cellminy = ((pos.y - r) - (this.mod((pos.y - r), this.ycellsize))) / this.ycellsize;\n let cellminz = ((pos.z - r) - (this.mod((pos.z - r), this.zcellsize))) / this.zcellsize;\n\n let cellmaxx = ((pos.x + r) - (this.mod((pos.x + r), this.xcellsize))) / this.xcellsize;\n let cellmaxy = ((pos.y + r) - (this.mod((pos.y + r), this.ycellsize))) / this.ycellsize;\n let cellmaxz = ((pos.z + r) - (this.mod((pos.z + r), this.zcellsize))) / this.zcellsize;\n\n if (cellminx < 0) cellminx = 0;\n if (cellmaxx >= this.numcells) cellmaxx = this.numcells-1;\n\n if (cellminy < 0) cellminy = 0;\n if (cellmaxy >= this.numcells) cellmaxy = this.numcells - 1;\n\n if (cellminz < 0) cellminz = 0;\n if (cellmaxz >= this.numcells) cellmaxz = this.numcells - 1;\n\n let objs = [];\n\n for (let cz=cellminz; cz<=cellmaxz; cz++)\n {\n for (let cy=cellminy; cy<=cellmaxy; cy++)\n {\n for (let cx=cellminx; cx<=cellmaxx; cx++)\n {\n let cell = this.grid[cz][cy][cx];\n\n if (!cell) continue;\n\n for (let t=0; t<cell.length; t++)\n {\n let neighbour = cell[t];\n\n if (neighbour == item)\n continue;\n\n // Handle xy position stored in a child property of item\n let npos = neighbour;\n if (this.prop) npos = neighbour[this.prop];\n\n let d = this.distsq(npos.x, npos.y, npos.z, pos.x, pos.y, pos.z);\n\n if (d <= rsq)\n objs.push(neighbour);\n }\n }\n }\n }\n\n return objs;\n }", "function nearest(value, min, max)\n {\n if((value-min)>(max-value))\n {\n return max;\n }\n else\n {\n return min;\n }\n }", "findClosestInRange(e,range){ // O(N^2)\n\t\tlet ents = util.findInRange(e,range);\n\t\tif(ents.length < 1){return null;}\n\t\tlet min = util.distance(ents[0],e);\n\t\tlet ent = ents[0];\n\n\t\tif(min < 0) min = -min;\n\n\t\tfor(let i=1;i<ents.length;i++){\n\t\t\tlet dist = util.distance(ents[i],e);\n\t\t\tif(dist < 0) dist = -dist;\n\n\t\t\tif(min > dist){\n\t\t\t\tmin = dist;\n\t\t\t\tent = ents[i];\n\t\t\t}\n\t\t}\n\n\t\treturn ent;\n\t}", "function steeringBehaviourLowestCost(agent) {\r\n\r\n\t//Do nothing if the agent isn't moving\r\n\tif (agent.velocity.magnitude() == 0) {\r\n\t\treturn zeroVector;\r\n\t}\r\n\tvar floor = agent.floor(); //Coordinate of the top left square centre out of the 4\r\n\tvar x = floor.x;\r\n\tvar y = floor.y;\r\n\r\n\t//Find our 4 closest neighbours and get their distance value\r\n\tvar f00 = Number.MAX_VALUE;\r\n\tvar f01 = Number.MAX_VALUE;\r\n\tvar f10 = Number.MAX_VALUE;\r\n\tvar f11 = Number.MAX_VALUE;\r\n\r\n\tif (isValid(x, y)) {\r\n\t\tf00 = grid[x][y].distance;\r\n\t};\r\n\tif (isValid(x, y + 1)) {\r\n\t\tf01 = grid[x][y + 1].distance;\r\n\t}\r\n\tif (isValid(x + 1, y)) {\r\n\t\tf10 = grid[x +1][y].distance; \r\n\t}\r\n\tif (isValid(x + 1, y + 1)) {\r\n\t\tf11 = grid[x + 1][y + 1].distance;\r\n\t}\r\n\r\n\t//Find the position(s) of the lowest, there may be multiple\r\n\tvar minVal = Math.min(f00, f01, f10, f11);\r\n\tvar minCoord = [];\r\n\r\n\tif (f00 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(0, 0)));\r\n\t}\r\n\tif (f01 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(0, 1)));\r\n\t}\r\n\tif (f10 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(1, 0)));\r\n\t}\r\n\tif (f11 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(1, 1)));\r\n\t} \r\n\r\n\r\n\t//Tie-break by choosing the one we are most aligned with\r\n\tvar currentDirection = agent.velocity.norm();\r\n\tvar desiredDirection = zeroVector;\r\n\tminVal = Number.MAX_VALUE;\r\n\tfor (var i = 0; i < minCoord.length; i++) {\r\n\t\t//the direction to the coord from the agent\r\n\t\tvar directionTo = minCoord[i].minus(agent).norm();\r\n\t\t//the magnitude of difference from the current vector to direction of the coord from the agent\r\n\t\tvar magnitude = directionTo.minus(currentDirection).magnitude();\r\n\t\t//if it's the smallest magnitude, set it as the desiredDirection\r\n\t\tif (magnitude < minVal) {\r\n\t\t\tminVal = magnitude;\r\n\t\t\tdesiredDirection = directionTo;\r\n\t\t}\r\n\t}\r\n\r\n\t//Convert to a force\r\n\tvar force = desiredDirection.mul(agent.maxForce / agent.maxSpeed);\r\n\treturn force;\r\n}", "function findClosestCentroid(point)\n {\n var closest = {\n i: -1,\n distance: width * 2\n };\n centroids.forEach(function(d, i)\n {\n var distance = getEuclidianDistance(d, point);\n // Only update when the centroid is closer\n if (distance < closest.distance)\n {\n closest.i = i;\n closest.distance = distance;\n }\n });\n return (centroids[closest.i]);\n }", "function nearest(node, radius, hits) {\n return ellipseNearest(node, radius, radius, 0, hits);\n}", "function getNearestEvents(x,y,events) {\nlet distances=[];\n//Calculate manhattan distance for each event, also get the minimum ticket IF tickets are available(since tickets can be 0)\nevents.forEach( e => distances.push( { eventNum:e.eventNum,\n coords:[e.x,e.y],\n distance:calcManhattanDistance(x,e.x,y,e.y),\n minTicket: e.tickets.length === 0 ? 'Tickets unavailable': Math.min(...e.tickets) +'$'\n })\n );\n//Sort distances and return.\ndistances.sort( (a,b) => a.distance - b.distance );\nreturn distances;\n\n}", "function closestPointOnPath_Cartesian( place, path, cb ) {\n var min = Number.MAX_VALUE;\n var closestPoint = null;\n for( var i=0; i<path.length-1; i++ ) {\n var v = { x: path[i].lng(), y: path[i].lat() };\n var w = { x: path[i+1].lng(), y: path[i+1].lat() };\n var p1 = { x: place.geometry.location.lng(), y: place.geometry.location.lat() };\n var p2 = getClosestPoint( p1, v, w );\n var d2 = dist2( p1, p2 );\n if( d2 < min ) {\n min = d2;\n closestPoint = new google.maps.LatLng( p2.y, p2.x );\n }\n }\n cb( closestPoint, min );\n }", "function nearestSq(n) {\n let x = Math.round(Math.sqrt(n));\n return x * x;\n}", "function prepareMines(mines, clicked) {\n return mines.map(cell => {\n const distance = Math.hypot(cell.x - clicked.x, cell.y - clicked.y);\n\n return {\n distance, cell\n };\n }).sort((a, b) => a.distance - b.distance);\n}", "function findClosestIntersection(grid, gridCenter) {\n let closestIntersectionManhattan;\n let closestIntersectionSteps = 0;\n let xDist;\n let yDist;\n\n for (var i = 0; i < grid.length; i++) {\n for (var j = 0; j < grid.length; j++) {\n if (grid[i][j] !== '' && grid[i][j].intersection) {\n if (i < gridCenter) {\n xDist = gridCenter - i;\n } else {\n xDist = i - gridCenter;\n }\n\n if (j < gridCenter) {\n yDist = gridCenter - j;\n } else {\n yDist = j - gridCenter;\n }\n let manhattanDistance = xDist + yDist;\n\n if (\n !closestIntersectionManhattan ||\n manhattanDistance < closestIntersectionManhattan\n )\n closestIntersectionManhattan = manhattanDistance;\n\n if (\n closestIntersectionSteps == 0 ||\n grid[i][j].steps < closestIntersectionSteps\n ) {\n closestIntersectionSteps = grid[i][j].steps;\n }\n }\n }\n }\n return {\n closestIntersectionManhattan: closestIntersectionManhattan,\n closestIntersectionSteps: closestIntersectionSteps\n };\n}", "closestIntersectionWith(wire)\n {\n const manhattan = (y, x) => Math.abs(y) + Math.abs(x);\n return this.intersectionsWith(wire).reduce((min, i) => Math.min(min, manhattan(i.y, i.x)), Number.MAX_SAFE_INTEGER);\n }", "closestNextRange(path, row, column) {\n let i;\n let candidate = [];\n let min;\n let min_index;\n\n for (i = 0; i < this.FocusView.length; i++) {\n if (this.FocusView[i].path === path) {\n if (this.FocusView[i].range.start.line > row) {\n let travel = this.FocusView[i].range.start.line - row;\n candidate.push({\n distance: travel,\n index: i\n });\n } else if (this.FocusView[i].range.start.line === row) {\n if (this.FocusView[i].range.start.character > column) {\n let travel =\n (this.FocusView[i].range.start.character - column) / 10;\n candidate.push({\n distance: travel,\n index: i\n });\n }\n }\n }\n }\n\n if (candidate.length > 0) {\n min = candidate[0].distance;\n min_index = candidate[0].index;\n for (i = 1; i < candidate.length; i++) {\n if (candidate[i].distance < min) {\n min = candidate[i].distance;\n min_index = candidate[i].index;\n }\n }\n return this.FocusView[min_index].range.end;\n }\n\n return null;\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 nearNeigh(matrix, start)\r\n{\r\n\tvar visited = [];\r\n\tvar solution = [];\r\n\tvar current = start;\r\n\t//update list of visited cities with the start city\r\n\tvisited.push(current);\r\n\t//update solution with start city and distance 0\r\n\tsolution.push([current,0]);\r\n\t//loop while # of visited cities is less than \r\n\t//total number of cities\r\n\twhile (visited.length<matrix.length)\r\n\t{\r\n\t\t//initialize minimum to infinity\r\n\t\tvar min = Infinity;\r\n\t\t//initialize minIndex to current city \r\n\t\t//- just a random choice could be anything\r\n\t\tvar minIndex = current;\r\n\t\t//loop over all cities current\r\n\t\tfor (var i = 0; i<matrix.length; i++)\r\n\t\t{\r\n\t\t\t//if distance to city i is less than min and i has not\r\n\t\t\t//been visited then update min distance from current\r\n\t\t\tif (matrix[current][i]<min && visited.indexOf(i)==-1)\r\n\t\t\t{\r\n\t\t\t\tmin = matrix[current][i];\r\n\t\t\t\tminIndex = i;\r\n\t\t\t\t//console.log(\"min: \",min, \"\\t\\tminIndex: \",minIndex);\r\n\t\t\t}\r\n\t\t}\r\n\t\t//update current to the closest city to previous current that \r\n\t\t//hadn't been visited as found by previous loop\r\n\t\tcurrent = minIndex;\r\n\t\t//put min city index and min distance into array next\r\n\t\tvar next = [minIndex,min];\r\n\t\t//push this pair onto solution\r\n\t\tsolution.push(next);\r\n\t\t//push min city index onto list of visited cities\r\n\t\tvisited.push(minIndex);\r\n\t}\r\n\treturn(solution);\r\n}", "function closest(list, x) {\n\t\tvar chosen = 0;\n\t for (var i in list) {\n\t\tvar miin = Math.abs(list[chosen] - x);\n\t\tif (Math.abs(list[i] - x) < miin) {\n\t\t chosen = i;}\n\t\t}\n\t return chosen;\n\t}", "function nearestIntersectedSnapObj(){\n\t\n\tgetIntersectedSnapObjs();\n\tif ( snapObjsIntersectedByRay.length > 0 ){ \n\t\treturn snapObjsIntersectedByRay[ 0 ]; \n\t}\t\t\n}", "function findClosestCentroid(point, centroids) {\n var minDist;\n var newDist;\n var closestCentroid;\n for (var c=0; c<centroids.length; c++) {\n newDist = calculateCentroidDistance(point, centroids[c]);\n if (minDist == undefined || minDist > newDist) {\n minDist = newDist;\n closestCentroid = c;\n }\n }\n return closestCentroid;\n }", "static closest(num, arr) {\n let curr = null;\n let diff = Infinity;\n arr.forEach((elem) => {\n let rect = elem.getBoundingClientRect();\n let val = rect.right - (rect.width / 2);\n let newdiff = Math.abs(num - val);\n if (newdiff < diff) {\n diff = newdiff;\n curr = elem;\n }\n });\n return curr;\n }", "function findTheNearestDiamond (diamondPositionObj) {\n let distanceArr = arrayOfDiamonds.map((item, index, arr) => {\n return parseInt(Math.sqrt(Math.pow((item.cellPositionLeft - diamondPositionObj.cellPositionLeft), 2) +\n Math.pow((item.cellPositionTop - diamondPositionObj.cellPositionTop), 2)))\n })\n return distanceArr\n }", "function findClosestPointInHeatmap(origin, layer) {\n var distanceBetween = google.maps.geometry.spherical.computeDistanceBetween; // shortcut\n var toReturn = layer.data.getAt(0).location, // initialize; if nothing else is smaller, first will be returned\n minDistance = google.maps.geometry.spherical.computeDistanceBetween(layer.data.getAt(0).location, origin);\n layer.data.forEach(function(point) {\n currentDistance = distanceBetween(origin, point.location);\n if (currentDistance < minDistance) {\n minDistance = currentDistance;\n toReturn = point;\n }\n });\n return { point: toReturn, distance: minDistance };\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function findCell(cells, c) {\n var lo = 0\n , hi = cells.length-1\n , r = -1\n while (lo <= hi) {\n var mid = (lo + hi) >> 1\n , s = compareCells(cells[mid], c)\n if(s <= 0) {\n if(s === 0) {\n r = mid\n }\n lo = mid + 1\n } else if(s > 0) {\n hi = mid - 1\n }\n }\n return r\n}", "function bugFood(x, y){\n var nearestFood = 0;\n var prevDist = distanceCalc(x,y,foods[nearestFood]);\n\n for(var i = 1; i < foods.length; i++){\n var newDist = distanceCalc(x,y, foods[i]);\n if (newDist < prevDist){\n nearestFood = i;\n prevDist = newDist;\n }\n }\n return nearestFood;\n}", "function find_closest_asset_address(player_enter_x, player_enter_z) {\n var closest_distance = 9999999;\n\n var closet_coor = null;\n\n // for each coordinate our coordinate map\n for (var i = 0; i < coordinate_map.length; i++) {\n var coor = coordinate_map[i]\n\n // determine the distance from that coordinate to the player enter position\n var distance = find_distance(player_enter_x, player_enter_z, coor.x, coor.z)\n\n // if this coordinate is closer set it as our closest\n if (distance < closest_distance) {\n closest_distance = distance\n closet_coor = coor;\n }\n }\n\n // return the address of the closest coordinate\n if (closet_coor != null) {\n return closet_coor.address\n } else {\n return \"\";\n }\n}", "function best(distances, visited) {\n let bestIndex = -1;\n let minDistance = Infinity;\n\n for (const [x, distance] of distances.entries()) {\n if (!visited[x] && distance < minDistance) {\n bestIndex = x;\n minDistance = distance;\n }\n }\n\n return bestIndex;\n}" ]
[ "0.685125", "0.67425996", "0.6669267", "0.6649439", "0.6381675", "0.63721305", "0.6362173", "0.6355284", "0.6316656", "0.6240928", "0.6228612", "0.62226576", "0.6206366", "0.6205011", "0.61719936", "0.61674714", "0.6155445", "0.6140501", "0.61386454", "0.61174345", "0.6116153", "0.6103563", "0.6097802", "0.6096708", "0.60947496", "0.6066316", "0.60582083", "0.605626", "0.60095775", "0.6004921", "0.59958035", "0.59922135", "0.59910476", "0.59669346", "0.5954159", "0.59411234", "0.5926831", "0.5925565", "0.59007365", "0.589292", "0.5876103", "0.5855427", "0.58537686", "0.58425725", "0.5841546", "0.58356994", "0.5822738", "0.5818061", "0.5805735", "0.5800893", "0.5776879", "0.5764188", "0.5757045", "0.5749905", "0.57421726", "0.5736307", "0.5726965", "0.57255274", "0.5719201", "0.5717447", "0.5704782", "0.57012886", "0.5687908", "0.568207", "0.56596595", "0.56467724", "0.5644313", "0.5634625", "0.5632192", "0.56271577", "0.56159884", "0.5612222", "0.560689", "0.5605111", "0.5603311", "0.5594218", "0.55896825", "0.5580126", "0.55764186", "0.5573543", "0.5568754", "0.5559462", "0.5551995", "0.5538786", "0.55234385", "0.55232143", "0.55149186", "0.5509092", "0.54933256", "0.5490665", "0.5490665", "0.5490665", "0.5490665", "0.5490665", "0.5490665", "0.5490665", "0.5490665", "0.5485233", "0.5478279", "0.5468456" ]
0.82347417
0
Returns true if client is actively mining new blocks.
_mining(){ return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "isOnline(lastUsed) {\n return utils.xSecondsAgoUTC(12) < lastUsed ? true : false\n }", "canBlock()\n {\n if(this.blocks < game.settings.maxBlocks)\n {\n return true;\n }\n\n return false;\n\n }", "isAvailable () {\n const lessThanOneHourAgo = (date) => {\n const HOUR = 1000 * 60 * 60;\n const anHourAgo = Date.now() - HOUR;\n\n return date > anHourAgo;\n }\n\n return this.socket !== null || (this.lastSeen !== null && lessThanOneHourAgo(this.lastSeen))\n }", "blocker(program, state) {\n return false;\n }", "isOnline() {\n return this.onLine;\n }", "hasRelevantContext(block) {\n return this.profile.madeChanges;\n }", "is_available() {\n return this._time_until_arrival === 0;\n }", "function online() {\n\t\t\treturn serverStatus === \"online\";\n\t\t}", "function botIsAlone() {\r\n let currentChannel = backend.getCurrentChannel();\r\n let clients = currentChannel ? currentChannel.getClientCount() : 0;\r\n return (clients <= 1) \r\n }", "async checkForNewBlock() {\n try {\n const blockHeight = await this.polkadotAPI.getBlockHeight()\n\n // if we get a newer block then expected query for all the outstanding blocks\n while (blockHeight > this.height) {\n this.height = this.height ? this.height++ : blockHeight\n this.newBlockHandler(this.height)\n\n // we are safe, that the chain produced a block so it didn't hang up\n if (this.chainHangup) clearTimeout(this.chainHangup)\n }\n } catch (error) {\n console.error('Failed to check for a new block', error)\n Sentry.captureException(error)\n }\n }", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "function canApplyUpdates() {\n return module.hot.status() === 'idle';\n}", "isGenesisBlock() {\n return !this.prevBlockHash;\n }", "function checkAttend(client) {\n if (client.mesa) return true\n return false\n }", "arePeersReady() {\n return this._readyState === true && this._remoteIsReady === true;\n }", "function block() {\n blocked++;\n }", "get isMine () {\n return false;\n }", "async canPowBeDone() {\n await this.iotaMultiNode.findPowServer();\n var powServer = this.iotaMultiNode.selectPowServers();\n if (!powServer[0]) {\n this.emitError(codes.NO_POW_SERVER_AVAILABLE)\n return false;\n }\n return true;\n }", "function startMining() {\n\tconsole.log('Started mining')\n\tisMining = true\n}", "_canFetch() {\n let now = Date.now();\n let elapsed = Math.floor( ( now - this.last ) / 1000 );\n let delay = this._options.fetchDelay | 0;\n\n if ( this.fetching || this.last >= now ) return false; // busy, wait\n if ( delay && elapsed < delay ) return false; // too soon, wait\n return true; // looks good\n }", "function isConnected(remote) {\n if (!remote) {\n return false;\n }\n\n var server = remote._getServer();\n if (!server) {\n return false;\n }\n\n return (Date.now() - server._lastLedgerClose <= 1000 * 20);\n}", "isChallengeLive() {\n return !this.challenge.isEnded && (Math.ceil(Date.now()/1000) >= this.challenge.startsAt.timestamp);\n }", "function checkNumberOfBlocksInserted() {\n if (currentBlocks < maximumBlocks) {\n currentBlocks++;\n return true;\n }else{\n $('#counter_blocks').html('<p>'+'You can add only 10 blocks</p>');\n return false;\n }\n}", "shouldBeRecycled() {\n\t\tif (this.memory.role === Creep.role.builder) {\n\t\t\treturn this.room.getConstructionSiteCount() < 1;\n\t\t} else if (this.memory.role === Creep.role.roadWorker) {\n\t\t\treturn !this.room.hasDamagedRoads();\n\t\t}\n\t\treturn false;\n\t}", "function startMine(user){\n user.mining = true;\n user.mineID = window.setInterval(mine, 3000, user);\n snackbar(\"User: \"+user.name+\" begins mining\");\n // updateUser(user);\n}", "isReady() {\n // We're only ready for a new refresh if the required milliseconds have passed.\n return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh);\n }", "isReady() {\n // We're only ready for a new refresh if the required milliseconds have passed.\n return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh);\n }", "mine() {\n //method that determines which transactions are valid\n const validTransactions = this.transactionPool.validTransactions();\n\n //include a reward for the miner\n validTransactions.push(\n Transaction.rewardTransaction(this.wallet, Wallet.blockchainWallet())\n );\n\n //create a block consisting of the valid transactions\n const block = this.blockchain.addBlock(validTransactions);\n\n //synchronize the chains in the p2p server\n this.p2pServer.syncChains();\n\n //clear transaction pool (local)\n this.transactionPool.clear();\n this.p2pServer.broadcastClearTransactions();\n\n //broadcast to every miner to clear their transaction pools\n //want other classes to access the block generated from this class\n return block;\n }", "get is_idle() {\n\t\treturn this.req_queue.length == 0 && Object.keys(this.req_map).length == 0;\n\t}", "function is_market_locked() {\n return (marketLockedForPlayer != null);\n}", "isReady()\n {\n //if a regulator is instantiated with a zero freq then it goes into\n //stealth mode (doesn't regulate)\n if (0 == this.m_dUpdatePeriod) return true;\n\n //if the regulator is instantiated with a negative freq then it will\n //never allow the code to flow\n if (this.m_dUpdatePeriod < 0) return false;\n\n var d = new Date();\n var CurrentTime = d.getTime();\n\n //the number of milliseconds the update period can vary per required\n //update-step. This is here to make sure any multiple clients of this class\n //have their updates spread evenly\n var UpdatePeriodVariator = 10.0;\n\n if (CurrentTime >= this.m_dwNextUpdateTime)\n {\n this.m_dwNextUpdateTime = (CurrentTime + this.m_dUpdatePeriod + getRandomArbitrary(-UpdatePeriodVariator, UpdatePeriodVariator));\n\n return true;\n }\n\n return false;\n }", "async checkForLatestBlock () {\n await this._updateLatestBlock()\n return await this.getLatestBlock()\n }", "function isOnline() {\n var xhr = new ( window.ActiveXObject || XMLHttpRequest )( \"Microsoft.XMLHTTP\" );\n var status;\n xhr.open( \"GET\", window.location.origin + window.location.pathname + \"/ping\",false);\n try {\n xhr.send();\n return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );\n } catch (error) {\n return false;\n }\n }", "isBlocked() {\r\n if(this.block > 0) {\r\n this.block--;\r\n return 1;\r\n }\r\n else return 0;\r\n }", "function _isBlocked() {\r\n var isblock = $.blockUI.IsPageBlocked();\r\n return isblock == null ? false : true;\r\n }", "checkWaitingPlayers() {\n if (DISABLE_BLOCKCHAIN) return;\n\n console.log(\"finding the best game to connect to\");\n if (this.processor !== null) {\n this.processor.stop();\n }\n if (this.gameRequestBlocks.length > 0) {\n var waitingPlayers = [];\n //Finds the most recent game request from each player, which was created\n //less than 5 minutes ago\n for (var i = this.gameRequestBlocks.length - 1; i >= 0; --i) {\n //TODO check that the user is not the same as the current person once testing is complete\n var iBlock = this.gameRequestBlocks[i];\n if (!waitingPlayers.includes(iBlock.data.username) &&\n (Date.now() - iBlock.data.time) < maxWaitingTime) {\n waitingPlayers.push(iBlock);\n }\n }\n //Removes games where the player already connected to someone else\n for (var j = this.closeRequestBlocks.length - 1; j >= 0; --j) {\n var jBlock = this.closeRequestBlocks[j];\n var playerIndex = waitingPlayers.indexOf(jBlock.username);\n if (playerIndex >= 0) {\n var possibleClosedGame = waitingPlayers[playerIndex];\n if (jBlock.time === possibleClosedGame.time) {\n waitingPlayers.splice(playerIndex, 1);\n }\n }\n }\n if (waitingPlayers.length > 0) {\n return waitingPlayers[0];\n }\n }\n }", "_onlineExpiring() {\n logger.info('OnlineStateManager: Online State Expiring; pinging to verify');\n this._isOnlineExpiring = true;\n this.checkOnlineStatus((result) => {\n if (!result && this._isOnlineExpiring) this._onlineExpired();\n this._isOnlineExpiring = false;\n });\n }", "finished() {\n return this.currentPoolSize === 0;\n }", "isInactive() {\n return this.workStatus == 0;\n }", "function isXmbcAlive(callback) {\n // Send JSONRPC ping request.\n xbmcRpc('JSONRPC.Ping',\n function (result) {\n callback(true);\n },\n function (error) {\n callback(false);\n });\n }", "function uptodate( user ){\n var age_collected = now - user.time_friends_collected;\n return age_collected < 3 * 24 * 3600 * 1000;\n }", "isAlive() {\n return this._lives > 0;\n }", "function BLOCKIND() {return true;}", "function checkBlock() {\n\t\n\t// get/update block time and duration in seconds\n\tvar count = JSON.parse(localStorage[\"blockCount\"]);\n\tcount += UPDATE_SECONDS;\n\t\n\tvar blockDur = localStorage[\"blockDuration\"];\n\tblockDur = blockDur * 3600;\n\tconsole.log(count + \" seconds of \" + blockDur + \" second sentence served\");\n\t// remove block if duration exceeded\n\tif (count >= blockDur) {\n \tlocalStorage[\"blockVar\"] = \"false\";\n \tlocalStorage[\"target\"] = 0;\n \tlocalStorage[\"blockCount\"] = 0;\n \t\tconsole.log(\"you did great. the block is coming down\");\n\t}\n\telse {\n\t\tlocalStorage[\"blockCount\"] = count;\n\t}\n}", "function hasPlayerWon() {\r\n if(gFlagsRemaining != 0) {\r\n return false;\r\n }\r\n return mBoard.allMinesFlagged();\r\n}", "requestBlocksUpdate () {\n this.emit(Runtime.BLOCKS_NEED_UPDATE);\n }", "function work_available(client, data) {\n if(client.type === \"worker\") {\n console.log(\"worker \"+client.worker+\" asked if work is available\");\n }\n}", "async checkFreeAccountRequestsLimit() {\n const from = +this.userTokens.property('сounting_requests_from');\n const counter = +this.userTokens.property('request_counter');\n if (this.now >= (from + 3600000)) { // Обновим метку отсчета (запросов в час)\n await this.extendRequestCounting();\n }\n else if (counter >= config.requests_per_hour_for_free_account) { // Превышено\n this.exceededRequestsLimit();\n return false;\n }\n else { // Накрутить счетчик запросов\n await this.increaseRequestsCount(counter + 1);\n }\n return true;\n }", "mineBlock(difficulty){\n\n var t0 = performance.now();\n\n while(this.hash.substring(0 , difficulty) !== Array(difficulty + 1).join(\"0\")){\n this.nonce++;\n this.hash = this.calculateHash();\n }\n\n console.log(\"Block Mined: \"+ this.hash);\n\n var t1 = performance.now();\n console.log(\"Mining block transaction took \" + (t1 - t0)/1000 + \" seconds.\"); \n }", "function checkEveryoneIsReady(players) {\n return (countReadyPlayers(players) > 5) ? true : false\n}", "async existGenesisBlock() {\n let exist = false;\n await this.getBlock(0)\n .then(() => {\n exist = true;\n })\n .catch((err) => {\n console.log('Genesis Block not found. Err: ' + err);\n });\n return exist;\n }", "function updateCurrentMinHop(newHops){\n var currentHop = context.get('sinkHops');\n var isUpdated = false;\n if(currentHop === -1){\n isUpdated = true;\n context.set('sinkHops', newHops);\n }else if(newHops < currentHop){\n isUpdated = true;\n context.set('sinkHops', newHops);\n }\n return isUpdated;\n}", "isLastMessageMine() {\r\n if (!this.props.thread.messages.length) {\r\n return false;\r\n }\r\n const message = this.props.thread.messages[this.props.thread.messages.length - 1];\r\n const from = StanzaHelper_1.StanzaHelper.getJid(message);\r\n return from.toLowerCase() === this.props.user.jid.toLowerCase();\r\n }", "_shouldCheckForUpdateOnStart() {\n const isColdStart = !localStorage.getItem('reloaderWasRefreshed');\n return isColdStart &&\n (\n this._options.check === 'everyStart' ||\n (\n this._options.check === 'firstStart' &&\n !localStorage.getItem('reloaderLastStart')\n )\n );\n }", "clientsUpdate() {\n for (var name in this.players) {\n this.getPlayerFromName(name).updateClientStateFromRoomState(this);\n }\n return true;\n }", "anyOneAlive (excludeNode, aliveTime) {\n const nowTime = new Date().getTime();\n for (const [key, value] of this.metrics.entries()) {\n if (key !== excludeNode) {\n const lastSeenAgo = nowTime - value.timestamp;\n if (lastSeenAgo < aliveTime) {\n debug('metrics', `${key} is alive.`);\n return true;\n }\n }\n }\n return false;\n }", "function isOnline() {\n var online = true;\n\n if (typeof window !== 'undefined' && 'navigator' in window && window.navigator.onLine === false) {\n online = false;\n }\n\n return online;\n}", "function isOnline() {\n var online = true;\n if (typeof window !== 'undefined' && 'navigator' in window // eslint-disable-line no-undef\n && window.navigator.onLine === false) {\n // eslint-disable-line no-undef\n online = false;\n }\n return online;\n }", "isAlive() {\n return this.currentHitPoints > 0 && !this.completed && !this.removeMe\n }", "get canReserve() {\n return (!this.api.isRequesting && this.selectedTime != '00:00:00');\n }", "function isConnected(client) {\n return db.getData(\"/clients/\" + client + \"/\").connected == \"true\"\n}", "checkMaster() {\n let isMaster = true;\n const ourId = this.id;\n for (const id in this._seenWCs) {\n if (id < ourId) {\n isMaster = false;\n }\n }\n this.set('isMaster', isMaster);\n }", "function checkPulse(){\n var heartbeat = this.node.heartbeat();\n var stale = Date.now() - this.timeout > heartbeat;\n if (stale) this.emit('change', 'candidate');\n}", "get isJoinable() { return !this.hasEnded && Now > this.startTime.plus(minutes(30)) }", "isAlive() {\n if (this.hp > 0) {\n return true;\n } else {\n this.state = LOSER;\n return false;\n }\n }", "function checkClientAlreadyConnected(request)\n { \n if (all_players_list[request.sessionID] != null)\n {\n request.session.player = all_players_list[request.sessionID];\n request.session.player['ref_count']++;\n console.log(\"This session (client \" + request.session.player.player_tag + \") is already connected. Increasing refcount to \" + request.session.player['ref_count']);\n return true;\n }\n return false;\n }", "function client_is_observer()\n{\n return client.conn['observer'] || observing;\n}", "function checkUpdate() {\n\tsync.net.getVersion(function(serverVersion) {\n\t\tif (serverVersion != version) {\n\t\t\tconsole.log(\"New update is available\");\n\t\t}\n\t});\n}", "blockUpdate() {\n this.updateManuallyBlocked = true;\n }", "function isCachedRequestMoreAccurateThanServerRequest(newCell, newWifiList)\n{\n gDebugCacheReasoning = \"\";\n let isNetworkRequestCacheEnabled = true;\n try {\n // Mochitest needs this pref to simulate request failure\n isNetworkRequestCacheEnabled = Services.prefs.getBoolPref(\"geo.wifi.debug.requestCache.enabled\");\n if (!isNetworkRequestCacheEnabled) {\n gCachedRequest = null;\n }\n } catch (e) {}\n\n if (!gCachedRequest || !isNetworkRequestCacheEnabled) {\n gDebugCacheReasoning = \"No cached data\";\n return false;\n }\n\n if (!newCell && !newWifiList) {\n gDebugCacheReasoning = \"New req. is GeoIP.\";\n return true;\n }\n\n if (newCell && newWifiList && (gCachedRequest.isCellOnly() || gCachedRequest.isWifiOnly())) {\n gDebugCacheReasoning = \"New req. is cell+wifi, cache only cell or wifi.\";\n return false;\n }\n\n if (newCell && gCachedRequest.isWifiOnly()) {\n // In order to know if a cell-only request should trump a wifi-only request\n // need to know if wifi is low accuracy. >5km would be VERY low accuracy,\n // it is worth trying the cell\n var isHighAccuracyWifi = gCachedRequest.location.coords.accuracy < 5000;\n gDebugCacheReasoning = \"Req. is cell, cache is wifi, isHigh:\" + isHighAccuracyWifi;\n return isHighAccuracyWifi;\n }\n\n let hasEqualCells = false;\n if (newCell) {\n hasEqualCells = gCachedRequest.isCellEqual(newCell);\n }\n\n let hasEqualWifis = false;\n if (newWifiList) {\n hasEqualWifis = gCachedRequest.isWifiApproxEqual(newWifiList);\n }\n\n gDebugCacheReasoning = \"EqualCells:\" + hasEqualCells + \" EqualWifis:\" + hasEqualWifis;\n\n if (gCachedRequest.isCellOnly()) {\n gDebugCacheReasoning += \", Cell only.\";\n if (hasEqualCells) {\n return true;\n }\n } else if (gCachedRequest.isWifiOnly() && hasEqualWifis) {\n gDebugCacheReasoning +=\", Wifi only.\"\n return true;\n } else if (gCachedRequest.isCellAndWifi()) {\n gDebugCacheReasoning += \", Cache has Cell+Wifi.\";\n if ((hasEqualCells && hasEqualWifis) ||\n (!newWifiList && hasEqualCells) ||\n (!newCell && hasEqualWifis))\n {\n return true;\n }\n }\n\n return false;\n}", "function validateLiveUpdates() {\n const current = new Date();\n const currentDate = current.toISOString().slice(0, 10);\n\n if (formData[\"liveUpdating\"]\n && currentDate > formData[\"enddatetime\"]) {\n return false;\n }\n\n return true;\n }", "minePendingTransactions(miningRewardAddress){\n let block = new Block(Date.now(), this.pendingTransactions, this.getLatestBlock().hash);\n block.mineBlock(this.difficulty);\n\n console.log(\"Block Successfully Mined!\");\n this.chain.push(block);\n\n //Added a transaction to reward the miner\n this.pendingTransactions = [\n new Transaction(null, miningRewardAddress, this.miningReward)\n ];\n }", "get hasNewMessages()\n\t{\n\t\treturn true;\n\t}", "shouldSendReminderUpdate() {\n const d = new Date();\n const revisedOffset = d.valueOf() - this.updatedAt.valueOf();\n if (revisedOffset < 183 * 24 * 3600 * 1000) { // if not revised during 6 months\n return false;\n }\n if (this.remindedUpdate) {\n const remindedOffset = d.valueOf() - this.remindedUpdate.valueOf();\n if (remindedOffset < 183 * 24 * 3600 * 1000) {\n return false;\n }\n }\n return true;\n }", "mineBlock(difficulty){\n while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join(\"0\")){\n this.nonce++;\n this.hash = this.calculateHash();\n }\n console.log(\"BLOCK MINED: \" + this.hash);\n \n }", "get idle ()\n {\n return this.waiting === this.entities.length;\n }", "function isConnected() {\n if (client === undefined) {\n return false;\n }\n return client.isConnected();\n }", "mineBlock(difficulty){\n while(this.hash.substring(0,difficulty)!==Array(difficulty + 1).join(\"0\")){\n this.nonce++;\n this.hash = this.calculateHash(); \n }\n console.log(\"BLOCK MINED:\"+this.hash);\n }", "function observeLatestBlocks(){\n\n // get the latest block immediately\n chain3.mc.getBlock('latest', function(e, block){\n if(!e) {\n updateBlock(block);\n }\n });\n\n // GET the latest blockchain information\n filter = chain3.mc.filter('latest').watch(checkLatestBlocks);\n\n}", "_shouldMakeMine() {\n return Math.random() < this.mineiness;\n }", "static isValid(creep) {\n\n //Need energy to transfer and spawn must not be full\n var spawn = creep.pos.findClosestByRange(FIND_MY_SPAWNS);\n if (spawn) {\n if (creep.carry.energy > 0 && spawn.energy < spawn.energyCapacity) {\n return true;\n }\n }\n return false;\n }", "isOnline() {\n return new Promise((resolve, reject) => {\n send(this.ip, [0], (data, err) => {\n resolve(!!!err);\n })\n })\n }", "function mineBlock() {\n\tif(unprocessedTransactions.length >= config.blockSize) {\n\t\tlet block = []\n\t\tconst blockNumber = blocks.length\n\t\tunprocessedTransactions.sort((a, b) => {\n\t\t\treturn b - a\n\t\t})\n\t\tconsole.log('Sorted array', unprocessedTransactions)\n\t\t// Take the block of 20 transactions\n\t\tblock = unprocessedTransactions.slice(0, config.blockSize)\n\t\t// Add the miner to each transaction\n\t\tfor(let i = 0; i < block.length; i++) {\n\t\t\tblock[i].minedBy = config.miner\n\t\t\tblock[i].blockNumber = blockNumber\n\t\t}\n\t\tunprocessedTransactions.splice(0, config.blockSize)\n\t\tblocks.push(block)\n\t\tconsole.log('Mined block number', blockNumber)\n\t}\n}", "function isIdle(request) {\n return request.kind === \"idle\";\n}", "get isBlocked() {\n\n }", "mineBlock(difficulty){\n\t\t\n\t\t/*\n\t\tThe hash is a string.\n\t\tCheck the first few characters in the hash (the substring determined by difficulty) to see if they have the corresponding number of zeros as difficulty.\n\t\tE.g. If difficulty is 5, then check if the first 5 characters of the hash is equal to '00000'.\n\t\t\n\t\tWhile the first few characters of the hash is not the corresponding number of zeros, then increment the nonce and recalculate the hash.\n\t\t*/\n\t\twhile(this.hash.substring(0, difficulty) !== Array(difficulty+1).join(\"0\")){\n\t\t\tthis.nonce++;\n\t\t\tthis.hash = this.calculateHash();\n\t\t}\n\t\t\n\t\t//Print it out to the console just to make sure that it is working\n\t\tconsole.log('Block mined: ' + this.hash);\n\t}", "function isConnect() {\n return !needWait;\n }", "function Wait_IsWaiting()\n{\n\t//check the counter\n\treturn this.cCounter > 0;\n}", "function _gcBlocksCache() {\n 'use strict';\n\n logger.info('cache info: ', JSON.stringify(_activeBlocksCache));\n for (var no = 0; no < _activeBlocksCache.length; no++){\n if (_activeBlocksCache[no] && (_activeBlocksCache[no].online === true)){\n if (_activeBlocksCache[no].flag === false) {\n _activeBlocksCache[no].offlinecount++;\n if (_activeBlocksCache[no].offlinecount >= OFFLINECOUNT){\n _activeBlocksCache[no].online = false;\n event.emit(events.BLOCKLIST,getActiveBlocks());\n var name = _activeBlocksCache[no].name;\n var idx = getBlockIdx(name,no);\n var state = 'disconnected';\n var count = getSameTypeBlockCount(name);\n event.emit(events.BLOCKCONNECTION,{name: name, idx: idx, state: state});\n event.emit(events.BLOCKCONUT,{type: name, count: count});\n }\n } else {\n _activeBlocksCache[no].flag = false;\n }\n }\n }\n}", "function isNotifiedRecently() {\n var seconds = (new Date().getTime() - lastNotified.getTime()) / 1000;\n return seconds <= notifyInterval;\n}", "isRunning() {\n return this.feedStartTime !== null;\n }", "get gettingNewMessages() {\n\t\treturn true;\n\t}", "function isCurrent(fetchTime: number, ttl: number): boolean {\n return fetchTime + ttl >= Date.now();\n}", "isUpdateAvailable(token) {\n return this.fetchScheduleFromNetwork(token).then(response => {\n return this.hash_ !== stringHash(response);\n });\n }" ]
[ "0.5999326", "0.59735894", "0.5895674", "0.5672302", "0.5659759", "0.5626051", "0.56140405", "0.56121016", "0.5603506", "0.55044883", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54964226", "0.54897654", "0.54766136", "0.5454589", "0.5437961", "0.5419861", "0.54096323", "0.5404736", "0.5383674", "0.5352875", "0.5344025", "0.5306213", "0.5297499", "0.529707", "0.5296309", "0.5296309", "0.5294366", "0.52939963", "0.52796274", "0.5274862", "0.526074", "0.5255988", "0.52404356", "0.5238897", "0.52177536", "0.5214999", "0.5208719", "0.5206261", "0.5203706", "0.51884973", "0.5188083", "0.5180642", "0.51795274", "0.51769847", "0.5176527", "0.51591593", "0.5124373", "0.5121206", "0.5101298", "0.5088886", "0.5076241", "0.5073174", "0.5071206", "0.5065723", "0.5053732", "0.50511557", "0.5042948", "0.503553", "0.5033737", "0.50282663", "0.50217235", "0.50097346", "0.50088394", "0.5004185", "0.49985084", "0.49920854", "0.4991038", "0.49859664", "0.49817473", "0.49719623", "0.496994", "0.49637607", "0.4954691", "0.4951276", "0.49495885", "0.49281362", "0.492735", "0.49228364", "0.4922406", "0.49213442", "0.49206376", "0.4914005", "0.49098554", "0.49080098", "0.4900782", "0.48999912", "0.48910612", "0.4885943", "0.48810357", "0.48798898", "0.487844", "0.48736045", "0.48697028" ]
0.0
-1
set up the event listener for a card. If a card is clicked: display the card's symbol (put this functionality in another function that you call from this one) add the card to a list of "open" cards (put this functionality in another function that you call from this one) if the list already has another card, check to see if the two cards match + if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one) + if the cards do not match, remove the cards from the list and hide the card's symbol (put this functionality in another function that you call from this one) + increment the move counter and display it on the page (put this functionality in another function that you call from this one) + if all cards have matched, display a message with the final score (put this functionality in another function that you call from this one) shuffle cards in deck array to create new deck
function shuffledDeck() { let shuffledDeck = shuffle(deck); $('.deck').empty(); for(let card = 0; card < shuffledDeck.length; card++) { $('.deck').append($('<li class="card"><i class="fa fa-' + shuffledDeck[card] + '"></i></li>')) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function clickCard(event) {\n // discard clicks on already matched or open cards\n if (event.target.nodeName === 'LI'\n && !(event.target.classList.contains(\"match\"))\n && !(event.target.classList.contains(\"open\")) ) {\n\n clickCounter += 1;\n\n if(clickCounter == 1) {\n startTimer();\n }\n\n //increase moveCounter every second click (one move = turning two cards)\n if(clickCounter % 2 == 0) {\n countMoves();\n\n // remove stars after 12 moves and then again every two moves\n // if(numberOfMoves > 0) { // for testing\n if(numberOfMoves >= 12 && numberOfMoves % 4 == 0) {\n removeStar();\n }\n }\n\n turnCard(event); // show the hidden side of the card\n\n openCardCounter += 1; // that many cards are turned over right now\n\n\n // if this is the 3rd card that has been clicked, turn first two cards over again and set openCardCounter to one\n if(openCardCounter == 3) {\n thirdCard();\n openCardCounter = 1;\n }\n\n // if it is the 1st or 2nd card that has been clicked, push the event targets and symbols in arrays\n // (if it had been the 3rd card, it will now be the 1st, as the arrays and counter have been reset\n cardArray.push(event.target);\n symbolArray.push(event.target.firstElementChild.classList[1])\n\n // if two cards are open, compare them\n if (openCardCounter == 2) {\n compareCards(event);\n }\n\n // if all cards have been matched, end the game\n // if (matchList == 4) { // for testing\n if(matchList == cards.length) {\n gameEnd();\n }\n }\n}", "function cardClick(){\n\tthis.classList.add('show', 'open');\n\tclickedCards.push(event.target);\n\tif(clickedCards.length === 2){\n\t\tmoves++;\n\t\tif(moves === 1){\n\t\t\ttimerStart();\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Move</span>`;\n\t\t} else if(moves >= 2 && moves <= 20) {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Moves</span>`;\n\t\t} else if(moves >= 21 && moves <= 29){\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves gold\">${moves} Moves</span>`;\n\t\t} else {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves red\">${moves} Moves</span>`;\n\t\t}\n\t\tif(clickedCards[0].innerHTML === clickedCards[1].innerHTML){\n\t\t\tmatching();\n\t\t\twinCheck();\n\t\t} else {\n\t\t\tnotMatching();\n\t\t}\n\t}\n\tcheckRating(moves);\n}", "function click(card) {\n card.addEventListener(\"click\", function() {\n if (switchTimer) {\n Timer = setInterval(setTimer, 1000);;\n switchTimer = false;\n }\n //Compare cards, and toggle each card's class depending on status\n card.classList.add(\"open\", \"show\", \"disabled\");\n openedCards.push(this);\n if (openedCards.length === 2) {\n moves++;\n numberMoves.innerHTML = moves;\n //Cards matched\n if (openedCards[0].innerHTML === openedCards[1].innerHTML) {\n openedCards[0].classList.add(\"match\", \"disabled\");\n openedCards[1].classList.add(\"match\", \"disabled\");\n matchedCards.push(openedCards[0], openedCards[1]);\n openedCards = [];\n //Cards unmatched\n } else {\n openedCards[0].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards[1].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards = [];\n }\n }\n\n //Star ratings determined\n if (moves < 15) {\n starNumber = 3;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\n <li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n } else if (moves < 25) {\n starNumber = 2;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n\n } else {\n starNumber = 1;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`\n\n }\n gameOver();\n\n\n });\n }", "function onCardClicked() {\n //get the card that was clicked\n let selectedId = $(this).attr('id').replace('card-','');\n let selectedCard = cards[selectedId];\n\n if (selectedCard.isDisplayed() || openCards.length >= 2) {\n return;\n } else {\n //increment click counter\n moveCount++;\n $('.moves').text(moveCount);\n\n //check move count and decrement stars if needed.\n if (moveCount == 20) {\n $('#star-3').removeClass('fa-star');\n $('#star-3').addClass('fa-star-o');\n } else if (moveCount == 30) {\n $('#star-2').removeClass('fa-star');\n $('#star-2').addClass('fa-star-o');\n }\n\n //display the card.\n selectedCard.flip();\n\n //after short delay, check if there is a match.\n //this is done so that the cards do not immediately flip back\n //preventing you from seeing the 2nd card.\n setTimeout(function() {\n if (!findCardMatch(selectedCard)) {\n //add selected card to list of open cards\n openCards.push(selectedCard);\n\n if (openCards.length == 2) {\n //hide both cards\n openCards[0].flip();\n openCards[1].flip();\n openCards = [];\n }\n }\n }, 800);\n }\n}", "function clickOnCard(e) {\n // if the target isn't a card, stop the function\n if (!e.target.classList.contains('card')) return;\n // if the user click the first time on a card (-->that is flip the first card) the timer starts\n if(isFirstCardclicked) {\n startTimer();\n isFirstCardclicked=false;\n }\n if (openCards.length<2) {\n let cardClicked = e.target;\n console.log(\"clicked \"+e.target.querySelector('i').classList);\n // show the card\n showSymbol(cardClicked);\n // save the card clicked\n addOpenCard(cardClicked);\n }\n if (openCards.length == 2) {\n // to stop from further clicking on cards until animation is finished\n deck.removeEventListener('click', clickOnCard);\n checkMatch(openCards[0], openCards[1]);\n updateMovesCounter();\n updateRating();\n }\n}", "function toggleAndAddCard() {\n const targetEvent = event.target;\n if (targetEvent.classList.contains('card') && openCards.length < 2 && !targetEvent.classList.contains('show')) {\n // console.log(\"A card was clicked.\")\n counter++;\n //This counter is to ensure that the timer only starts at the first card being clicked\n // console.log(counter);\n if (counter === 1) {\n startTimer();\n }\n displaySymbol(targetEvent);\n addCardToOpenCards(targetEvent);\n // If there are two open cards, it will check if they match\n // console.log(openCards);\n if (openCards.length === 2) {\n checkMatch();\n }\n }\n}", "function clickCard() {\n $(\".card\").click(function() {\n // Return the function if the card is open\n if ($(this).hasClass(\"open show\")) {\n return;\n }\n // Return if there are 2 opened cards\n if (openCards.length === 2) {\n return;\n }\n // Display the card symbol and add the card to openCards list\n $(this).addClass(\"open show\");\n openCards.push($(this));\n // Start runner if this is the first move\n if (moves === 0) {\n startRunner();\n }\n // Check if the cards match\n if (openCards.length === 2) {\n if (openCards[0][0].firstChild.className === openCards[1][0].firstChild.className) {\n setTimeout(addMatch,300);\n } else {\n setTimeout(removeClasses,1300);\n }\n // Increase moves after checking\n incrementMoves();\n }\n });\n }", "function processClick(card) {\n //if card is not open/matched: open/flip it\n if (!card.classList.contains(\"card-open\") && !card.classList.contains(\"card-matched\")) {\n toggleCard(card);\n openCards.push(card);\n ++moves;\n displayMoves();\n dispStars();\n }\n //if two consecutive open cards do not match: flip them back over/close them\n if (openCards.length === 2 && !card.classList.contains(\"card-matched\")) {\n setTimeout(function() {\n for (let card = 0; card < openCards.length; card++) {\n toggleCard(openCards[card]);\n }\n openCards = [];\n }, 650);\n }\n //check if two open cards match: mark them as matched\n if (checkMatch(openCards[0], openCards[1])) {\n addClass(openCards[0], \"card-matched\");\n addClass(openCards[1], \"card-matched\");\n numMatchedCards += 2;\n openCards = [];\n //check if all cards have been matched: show modal if true\n if (numMatchedCards === 16) {\n setTimeout(function() {\n stopTimer();\n displayModal();\n }, 500);\n }\n } else { //display unmatched cards effects\n addClass(openCards[0], \"card-unmatched\");\n addClass(openCards[1], \"card-unmatched\");\n unmatchedCards = document.querySelectorAll('.card-unmatched');\n setTimeout(function() {\n for (let card = 0; card < unmatchedCards.length; card++) {\n removeClass(unmatchedCards[card], \"card-unmatched\");\n }\n }, 500);\n }\n}", "function cardClicked(event) {\n openCardsList.push(this);\n this.classList.add('open', 'show', 'disable');\n if (openCardsList.length === 2 && openCardsList[0].innerHTML === openCardsList[1].innerHTML) {\n match();\n addMoves();\n }\n if (openCardsList.length === 2 && openCardsList[0].innerHTML != openCardsList[1].innerHTML) {\n noMatch();\n addMoves();\n }\n if (!watch.isOn) {\n watch.start();\n }\n}", "function cardClick() {\n\tif (clickedCards.length === 2 || matchedCards.includes(this.id)) {\n\t\treturn;\n\t}\n\tif(clickedCards.length === 0 || this.id != clickedCards[0].id){\n\n\t\tif(timeTrigger){\n\t\t\ttimerStart();\n\t\t\ttimeTrigger = false;\n\t\t}\n\t\tthis.classList.add('show', 'open');\n\t\tclickedCards.push(event.target);\n\t\tdetermineAction();\n\t}\n\telse {\n\t\treturn;\n\t}\n\tsetRating(moves);\n}", "function cardOpen(){\n if (event.target.className === 'card'){ //prevents anything except for unturned cards to be clicked\n event.target.className = 'card open';\n opened.push(event.target); //pushed card to 'opened' array\n count ++; //increases move counter for every click\n moves.innerHTML = count; //updates move counter\n gameRating(count); //updates star rating based on amount of moves\n }\n if (opened.length === 2){ //if statement to execute match function if 'opened' array has two cards\n container.removeEventListener('click', cardOpen); //prevents additional cards from being opened\n isCardEqual(opened);\n }\n}", "function playGame(){\n let cardDeck = document.getElementById(\"cardDeck\");\n\n cardDeck.addEventListener(\"click\", function(event){\n let activeCard = event.target;\n if (event.target && event.target.classList.contains(\"card\")){\n console.log(\"Card was clicked!\");\n openCardCtr++;\n\n if(openCardCtr==1){\n startTimer();\n };\n if (openCardList.length<2){\n if (activeCard.classList.contains(\"open\")){\n console.log(\"card is already open!!\");\n } else {\n activeCard.classList.add(\"open\",\"show\");\n openCardList.push(activeCard);\n if (openCardList.length==2) {\n console.log(\"2 cards are already open! Check if match...\");\n checkMatch();\n };\n };\n };// if opencards.length<2*/\n }; //if evt.target && contains \"class\"\n });//cardDeck addEventListener\n}", "function clickCards(){\r\n let allCards = document.querySelectorAll('.card');\r\n let i, cardName;\r\n for (i = 0; i < allCards.length; i++) {\r\n allCards[i].setAttribute(cardName, deckOfCards[i]);\r\n }\r\n // To Read the card name use\r\n // allCards[i].getAttribute(cardName);\r\n let openCards = [];\r\n let initialClick = 0;\r\n\r\n // Add an event listener to each element of allCards\r\n // The function in forEach takes two parameters: the refernce to the value\r\n // stored in allCards[i] and the index i\r\n allCards.forEach(function(htmlText, arrayIndex){\r\n // The value sent from allCards[i] has an event listener to it that is\r\n // activated by clikcing. Clicking the card represented by htmlText will\r\n // write the index value to openCards, which will later be used to compare\r\n // if two selected cards are a match.\r\n console.log(\"forEach method called.\")\r\n\r\n allCards[arrayIndex].addEventListener(\"click\", function() {\r\n // If its the first card click, activate timer functionality\r\n\r\n if (initialClick == 0) {\r\n initialClick = 1;\r\n setTimer();\r\n }\r\n\r\n // Make sure the same card isn't being clicked twice\r\n if(arrayIndex == openCards[0]) return;\r\n console.log(\"arrayIndex = \", arrayIndex);\r\n\r\n // Add array number for card that has been clicked in openCards\r\n openCards.push(arrayIndex);\r\n\r\n // Check if there are too many cards open (timeout isn't over)\r\n if(openCards.length > 2) return;\r\n\r\n allCards[arrayIndex].classList.add('open', 'show');\r\n\r\n // clicked to compare cards.\r\n if(openCards.length >= 2) {\r\n moveCounter++;\r\n setMoves();\r\n setStars();\r\n\r\n // If two cards are open, compare their values. If they're a match,\r\n // update the CSS coresponding to their class 'match' and 'show'\r\n if(allCards[openCards[0]].firstChild.className == allCards[openCards[1]].firstChild.className) {\r\n\r\n // Match found\r\n\r\n allCards[openCards[0]].classList.remove('open');\r\n allCards[openCards[1]].classList.remove('open');\r\n allCards[openCards[0]].classList.add('match');\r\n allCards[openCards[1]].classList.add('match');\r\n // add to matimetchedCards for winning the game\r\n matchedCards++;\r\n\r\n // Clear the openCards array\r\n openCards = [];\r\n } else {\r\n // No match found. Reset the cards\r\n setTimeout(function() {\r\n allCards[openCards[0]].classList.remove('open','show');\r\n allCards[openCards[1]].classList.remove('open','show');\r\n\r\n // Clear the openCards array\r\n openCards = [];\r\n //seconds allowed for open cards\r\n },475);\r\n }\r\n }\r\n })\r\n });\r\n}", "function clickOnCards(card){\n\n//Create card click event\ncard.addEventListener(\"click\", function(){\t\n\n//Add an if statement so that we can't open more than two cards at the same time\n\tif (openedCards.length === 0 || openedCards.length === 1){\n\tsecondCard = this;\n\tfirstCard = openedCards[0];\n\n\t//We have opened card\n\tif(openedCards.length === 1){\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n\n\t//We invoke the function to compare two cards\n\tcheck(secondCard, firstCard);\n\n\t}else {\n //We don't have opened cards\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n }\n\t}\n});\n}", "function clickedCard(event){\n if(event.target && event.target.nodeName == \"LI\") {\n event.target.addEventListener(\"click\", clickedCard);\n // Turning the cards is just changing the background color to reveal the hidden text\n event.target.style.backgroundColor= \"#00d37e\";\n const cardClass = event.target.className;\n const cardId = event.target.id;\n\n /* If no other card in cardId has the same id as the event.target,\n we add event.target's id to the array.\n Also, if a card has a match, we take from it the possibility of being played again. */\n if (cardsId.includes(cardId) || event.target.classList.length === 3){\n true;\n } else {\n // Add the click to the moves counter\n addMoves();\n // Check for potential matches\n cardsTurned.push(cardClass);\n cardsId.push(cardId);\n checkingTurned();\n }\n }\n}", "function handleCardClick(event) {\n event.preventDefault();\n\n if (!timerInterval) {\n startTimer();\n }\n\n // Check if card has been matched previously\n if (this.classList.contains('.matched') || chosen.length === 2) {\n return;\n }\n // If the card has not already been selected...\n if (!chosen.includes(this)) {\n chosen.push(this);\n // Flip the Card\n this.classList.replace('hidden', 'open');\n }\n \n // Check if 2 cards are flipped\n if (chosen.length === 2) {\n // Record the move\n movesCount();\n // Check to see if the 2 flipped cards match\n if (chosen[0].dataset.icon === chosen[1].dataset.icon) {\n // Add matched class to both cards if they do match\n chosen[0].classList.add('matched');\n chosen[1].classList.add('matched');\n // add the card to the matched array\n matched.push(this);\n // Reset the chosen array\n chosen = []\n } else {\n // return cards to normal state after a short delay\n setTimeout(function () {\n chosen[0].classList.replace('open', 'hidden');\n chosen[1].classList.replace('open', 'hidden');\n // Reset the chosen array\n chosen = []\n }, 1000);\n }\n // Call to check if number of moves affect the accomplishment meter\n levelCounter();\n // Regenerate the levelDisplay based on No. of moves\n generateLevelDisplay();\n winGame();\n }\n}", "function handleCardClick(event) {\n if(isCardShown(event.target) || tempFaceUp.length >= CARDS_TO_MATCH){\n return;\n }\n\n tempFaceUp.push(event.target);\n showCard(event.target);\n\n\n\n if(tempFaceUp.length >= CARDS_TO_MATCH){\n\n if(hasFoundMatch()){\n tempFaceUp = [];\n\n if(gameIsWon()){\n endGame();\n }\n \n }\n else{\n score ++;\n document.querySelector(\"#score\").innerText = score;\n\n setTimeout(() => {\n shown = 0;\n tempFaceUp.forEach( card => {\n hideCard(card);\n });\n tempFaceUp = [];\n }, 1000);\n }\n }\n}", "function handleCardClick (event) {\n\tif (\n\t\tevent.target !== firstCard &&\n\t\tevent.target !== secondCard &&\n\t\tevent.target.classList.contains('clicked') === false &&\n\t\tarrayOfClicked.length < 2\n\t) {\n\t\t// you can use event.target to see which element was clicked\n\t\tif (arrayOfClicked.length <= 1) {\n\t\t\tlet card = event.target;\n\n\t\t\tcard.classList.add('clicked');\n\t\t\tcard.style.backgroundColor = card.style.color;\n\t\t\tarrayOfClicked.push(card);\n\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\tif (i === 0 && arrayOfClicked.length === 1) {\n\t\t\t\t\tfirstCard = arrayOfClicked[i];\n\t\t\t\t} else if (i === 1 && arrayOfClicked.length === 2) {\n\t\t\t\t\tsecondCard = arrayOfClicked[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (firstCard === secondCard) {\n\t\t\tarrayOfClicked.splice(arrayOfClicked.indexOf(secondCard), 1);\n\t\t} else if (arrayOfClicked.length === 2) {\n\t\t\tnumAttempts++;\n\t\t\tscore = document.querySelector('#score');\n\t\t\tscore.innerText = '' + numAttempts;\n\t\t\tsetTimeout(function () {\n\t\t\t\tif (firstCard.style.color !== secondCard.style.color) {\n\t\t\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\t\t\tlet thisCard = arrayOfClicked[i];\n\t\t\t\t\t\tthisCard.style.backgroundColor = '';\n\t\t\t\t\t\tthisCard.classList.remove('clicked');\n\t\t\t\t\t}\n\t\t\t\t\tfirstCard = null;\n\t\t\t\t\tsecondCard = null;\n\t\t\t\t} else {\n\t\t\t\t\tnumMatched += 2;\n\t\t\t\t\tfirstCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tsecondCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tarrayOfMatched.push(firstCard);\n\t\t\t\t\tarrayOfMatched.push(secondCard);\n\t\t\t\t}\n\t\t\t\tarrayOfClicked = [];\n\t\t\t\tif (numMatched === numCards) {\n\t\t\t\t\tclearTimeout();\n\t\t\t\t\tscoreCounter.className = 'new-high-score';\n\t\t\t\t\tlet prevHighScore;\n\t\t\t\t\tlet newHighScore;\n\n\t\t\t\t\tif (numCards === 10 && localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 10) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 20 && localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 20) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 30 && localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 30) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Easy\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Medium\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Hard\"]').remove();\n\t\t\t\t\tresetEasyButton = document.createElement('input');\n\t\t\t\t\tresetEasyButton.type = 'button';\n\t\t\t\t\tresetEasyButton.value = 'Reset Easy';\n\t\t\t\t\tresetEasyButton.className = 'reset-button-class';\n\t\t\t\t\tresetEasyButton.id = 'reset-easy-button';\n\t\t\t\t\tresetMediumButton = document.createElement('input');\n\t\t\t\t\tresetMediumButton.type = 'button';\n\t\t\t\t\tresetMediumButton.value = 'Reset Medium';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-class';\n\t\t\t\t\tresetMediumButton.id = 'reset-medium-button';\n\t\t\t\t\tresetHardButton = document.createElement('input');\n\t\t\t\t\tresetHardButton.type = 'button';\n\t\t\t\t\tresetHardButton.value = 'Reset Hard';\n\t\t\t\t\tresetHardButton.className = 'reset-button-class';\n\t\t\t\t\tresetHardButton.id = 'reset-hard-button';\n\t\t\t\t\tgameContainer.append(resetEasyButton);\n\t\t\t\t\tgameContainer.append(resetMediumButton);\n\t\t\t\t\tgameContainer.append(resetHardButton);\n\t\t\t\t\tresetEasyButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetHardButton.className = 'reset-button-end-class';\n\t\t\t\t}\n\t\t\t}, 1000);\n\t\t}\n\t}\n}", "function manipulateCard(event) {\n\t// Check if there is any card already clicked\n\tif (firstClickedElement === null){\n\n\t\t// No card clicked yet => store its value (class) into firstCard variable\n\t\tfirstCard = event.target.lastElementChild.getAttribute('class');\n\n\t\t// Show the card\n\t\tshowCard(event);\n\n\t\t// Get the element of the first clicked card\n\t\tfirstClickedElement = document.querySelector('.clicked');\n\n\t} else if (firstCard === event.target.lastElementChild.getAttribute('class')) {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Since 2nd card matches the first one => change cards status to \"card match\" (both cards remain with their face up) -> with a short delay\n\t\tchangeCardsStatus(event, 'card match');\n\n\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\tother2Cards();\n\t\t\n\t\t// Increase number of matched cards\n\t\tcellNo = cellNo + 2;\n\n\t} else {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Set the 2 clicked cards attributes to wrong class -> with a short delay\n\t\tchangeCardsStatus(event, 'card open show wrong');\n\n\t\t// Set the 2 clicked cards attributes to its defaults -> with a short delay\n\t\tsetTimeout(function(){\n\t\t\tchangeCardsStatus(event, 'card');\n\n\t\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\t\tother2Cards();\n\t\t}, 300);\n\t}\n}", "function click (card) {\n card.addEventListener(\"click\", function() {\n if(initialClick) {\n clock();\n initialClick = false;\n }\n\n const currentCard = this;\n const previousCard = openCards[0];\n\n //open cards and compare them\n if(openCards.length === 1) {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n // card comparison conditional\n comparison(currentCard, previousCard);\n increaseMove();\n } else {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n\n }\n });\n}", "function handleCardClick(event) {\n event.target.classList.toggle(\"hide\"); // hides color. Turns card to white\n event.target.classList.add(\"clicked\"); // adds class of 'clicked' to cards\n openCards.push(event.target); // push cards to array\n if (openCards.length === 2) {\n // if array = 2 cards\n if (\n // if both cards in array are the same color\n openCards[0].getAttribute(\"data-color\") ===\n openCards[1].getAttribute(\"data-color\")\n ) {\n counter++; // add click to counter if both cards are the same color\n setTimeout(function () {\n if (counter === 5) {\n // counter = 5 clicks (all same cards are clicked)\n alert(\"You won the game!\"); // module alert saying you won\n }\n }, 500); // do the above after .5 seconds so all code executes\n\n openCards[0].style.pointerEvents = \"none\"; //disable click on each open card\n openCards[1].style.pointerEvents = \"none\"; // since they match\n } else {\n //disable click\n let firstUnmatched = openCards[0]; // 1st card in array if they dont match\n let secondUnmatched = openCards[1]; // 2nd card in array if they dont match\n firstUnmatched.classList.remove(\"clicked\"); // remove class on 1st card\n secondUnmatched.classList.remove(\"clicked\"); // remove class on 2nd card\n gameContainer.style.pointerEvents = \"none\"; // disable click\n setTimeout(function () {\n // unmatched = white\n firstUnmatched.classList.toggle(\"hide\"); // hide toggle between color/white\n secondUnmatched.classList.toggle(\"hide\"); // hide toggle between color/white\n gameContainer.style.pointerEvents = \"auto\"; //enable click...\n }, 1000); // ...after 1 second so player can click again\n }\n openCards = []; // reset array to take in new cards\n }\n}", "function createCards() {\n for (i = 0; i < icons.length; i++) {\n const card = document.createElement(\"li\");\n card.classList.add(\"card\");\n card.innerHTML = `<i class=\"${icons[i]}\"></i>`;\n deck.appendChild(card);\n //Add click event to each card to add interactivity feature\n click(card);\n };\n\n /*\n * When a card is clicked, toggle timer on.\n * Then, Toggle switch to false to prevent timer\n * running at irregular intervals as a result of every click\n */\n function click(card) {\n card.addEventListener(\"click\", function() {\n if (switchTimer) {\n Timer = setInterval(setTimer, 1000);;\n switchTimer = false;\n }\n //Compare cards, and toggle each card's class depending on status\n card.classList.add(\"open\", \"show\", \"disabled\");\n openedCards.push(this);\n if (openedCards.length === 2) {\n moves++;\n numberMoves.innerHTML = moves;\n //Cards matched\n if (openedCards[0].innerHTML === openedCards[1].innerHTML) {\n openedCards[0].classList.add(\"match\", \"disabled\");\n openedCards[1].classList.add(\"match\", \"disabled\");\n matchedCards.push(openedCards[0], openedCards[1]);\n openedCards = [];\n //Cards unmatched\n } else {\n openedCards[0].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards[1].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards = [];\n }\n }\n\n //Star ratings determined\n if (moves < 15) {\n starNumber = 3;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\n <li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n } else if (moves < 25) {\n starNumber = 2;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n\n } else {\n starNumber = 1;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`\n\n }\n gameOver();\n\n\n });\n }\n}", "function clickCards(){\nlet allCards=document.querySelectorAll('.card');\n//click cards\nallCards.forEach(function(card){\n card.addEventListener('click',function(evt){\n //start timer at the first click\n if(newStart){\n newStart=false;\n startTimer();\n }\n //check if cards already clicked first and can't click more than two cards\n if(!card.classList.contains('open')&&!card.classList.contains('show')&&!card.classList.contains('match')&&openCards.length<2){\n openCards.push(card);\n card.classList.add('open','show');\n if (openCards.length==2){\n //count Moves\n countMoves();\n //remove stars\n removeStar();\n //match Cards\n if(openCards[0].dataset.card===openCards[1].dataset.card){\n matched();\n //finshi game if all cards are matched\n finishGame();\n } else {\n unmatched();\n }\n }}\n });\n});\n}", "function initGame() {\n document.querySelector('.overlay').style.display = 'none';\n document.querySelector('.deck').innerHTML = '';\n shuffle(possibleCards);\n opened = [];\n numStars = 3;\n numMoves = 0;\n numMatch = 0;\n resetTimer();\n runTimer();\n printStars();\n printMoves();\n\n\n for(i=0;i<numCards;i++) {\n document.querySelector('.deck').innerHTML += `<li class=\"card\"><img src=\"img/animal/${possibleCards[i]}.svg\"/></li>`;\n };\n\n\n\n// ============================================\n// Set up event listener\n// 1. Click a card, if it's already shown, quit function\n// 2. If it's not shown, show the card, add it to opened array. \n// 3. If there's already an item in the opened array, check if it's match. \n// 4. run match or unmatch function, clear opened array for the next match check.\n// 5. Calculate the stars for each move.\n// 6. If reach maximum pairs, end the game, show congrats message\n// ============================================\n\n document.querySelectorAll(\".card\").forEach((card) => {\n card.addEventListener(\"click\", function () {\n\n if (card.classList.contains('show')){\n return; // exit function if the card is already opened.\n }\n\n card.classList.add('show','animated','flipInY');\n\n let currentCard = card.innerHTML;\n opened.push(currentCard);\n\n\n if(opened.length > 1) {\n if(currentCard === opened[0]) {\n match();\n }else {\n unmatch();\n }\n };\n \n starCount(); \n printMoves();\n\n\n if(numMatch === maxMatch ) {\n stopTimer();\n congrats();\n }\n\n })\n });\n\n}", "function clickFunction() {\r\n\r\n let moveCounter = document.querySelector('.moves');\r\n let moves = 0;\r\n moveCounter.innerText = moves;\r\n\r\n let allCards = document.querySelectorAll('.card');\r\n let openCards = []; // saves opened cards in an array\r\n\r\n let movesText = document.querySelector('.moves_text');\r\n let stars = document.querySelector('.stars');\r\n\r\n const item = document.getElementsByTagName('li');\r\n\r\n allCards.forEach(function(card) {\r\n card.addEventListener('click', function() {\r\n\r\n if (!card.classList.contains(\"open\") && !card.classList.contains(\"show\") && !card.classList.contains(\"match\") && openCards.length < 2) {\r\n openCards.push(card);\r\n card.classList.add(\"open\", \"show\");\r\n\r\n if (openCards.length == 2) {\r\n if (openCards[0].dataset.card == openCards[1].dataset.card) {\r\n\r\n openCards[0].classList.add(\"match\", \"open\", \"show\");\r\n openCards[1].classList.add(\"match\", \"open\", \"show\");\r\n\r\n openCards = [];\r\n\r\n } else {\r\n\r\n function closeCards() {\r\n openCards.forEach(function(card) {\r\n card.classList.remove(\"open\", \"show\");\r\n });\r\n openCards = [];\r\n }\r\n setTimeout(closeCards, 1000);\r\n\r\n } // end of else\r\n\r\n moves += 1;\r\n moveCounter.innerText = moves;\r\n\r\n item[1].innerHTML = `With ${moves} moves`;\r\n\r\n /* if 1 - \"Move\", if more than 1 - \"Moves\" */\r\n if (moves == 1) {\r\n movesText.innerHTML = \"Move\";\r\n } else {\r\n movesText.innerHTML = \"Moves\";\r\n }\r\n\r\n /* stars - game rating */\r\n function hideStar() {\r\n const starList = document.querySelectorAll('.stars li');\r\n for (star of starList) {\r\n if (star.style.display !== 'none') {\r\n star.style.display = 'none';\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (moves == 11) {\r\n hideStar();\r\n } else if (moves == 15) {\r\n hideStar();\r\n }\r\n\r\n }\r\n }\r\n });\r\n });\r\n\r\n }", "function clickCards() {\n let openCards = [];\n let allCards = document.querySelectorAll('.card');\n\n allCards.forEach(function (card) {\n\n card.addEventListener('click', function (event) {\n\n if (!(card.classList.contains('open')) && !(card.classList.contains('show'))) {\n if (openCards.length + 1 > 2) {\n return;\n }\n openCards.push(card);\n card.classList.add('open', 'show');\n console.log(\"Card no: \", openCards.length)\n\n\n // Close if 2 cards open simultaneously \n if (openCards.length === 2) {\n\n moves++;\n if(moves>20 && moves<50 && minusOne){\n // Remove a star\n for (let i = 2; i < stars.length; i++) {\n stars[i].classList.remove('outline');\n stars[i].classList.add('fa-inverse');\n }\n starCount--;\n minusOne=false;\n }\n else if(moves>=50 && minusTwo){\n // Remove 2 stars\n for(let i=1;i<stars.length;i++){\n stars[i].classList.remove('outline');\n stars[i].classList.add('fa-inverse');\n }\n starCount--;\n minusTwo=false;\n }\n movesSpan.innerText = moves;\n // Check if there is a match\n let firstCard = openCards[0].dataset.card;\n let secondCard = openCards[1].dataset.card;\n if (firstCard == secondCard) {\n // console.log('It is a match');\n openCards.forEach(function (card) {\n card.classList.remove('open', 'show');\n card.classList.add('match', 'animated', 'bounce');\n })\n openCards = [];\n totalMatch++;\n if(totalMatch==8){\n // Get time\n clearInterval(timerVar);\n let time=document.getElementById(\"timer\").innerHTML;\n let timeArray=time.split(':')\n console.log(starCount);\n swal(`Congrats you finished the game in ${timeArray[0]} hours ${timeArray[1]} minutes ${timeArray[2]} seconds and ${moves} moves with ${starCount}/3 stars \\n Do you want to continue`, {\n buttons: {\n Yes:{\n text:\"Yes\",\n value:\"Yes\"\n },\n No: {\n text: \"No\",\n value: \"No\",\n },\n },\n })\n .then((value) => {\n switch (value) {\n \n case \"Yes\":\n swal(\"Restarting the game\");\n gameStart();\n break;\n \n case \"No\":\n swal(\"See you again\");\n break;\n }\n });\n // alert(`Congrats you have completed the game in ${time} time and ${moves} moves`);\n // setTimeout(() => {\n // gameStart();\n // }, 4000);\n }\n }\n // Remove/hide\n else {\n setTimeout(() => {\n openCards.forEach(function (card) {\n card.classList.remove('open', 'show');\n })\n openCards = [];\n }, 1000);\n }\n }\n }\n\n })\n })\n}", "function init() {\n shuffle(cards);\n const deck = document.getElementById(\"card-deck\");\n deck.innerHTML = \"\"\n for (var i = 0; i < cards.length; i++) {\n let card = cards[i];\n const div = document.createElement(\"div\");\n div.appendChild(card)\n deck.innerHTML += div.innerHTML\n }\n cards = [...document.getElementsByClassName(\"card\")];\n\n for (var i = 0; i < cards.length; i++) {\n let card = cards[i];\n card.addEventListener(\"click\", function() {\n if (! timerHandle) {\n resetTimer()\n timerHandle = setInterval(banana, 3000)\n }\n\n displayCard(this);\n\n if (firstCard === null) {\n firstCard = this\n return;\n }\n\n // Add New Move\n addMove();\n \n var currentCard = this;\n\n if (! compare(currentCard, firstCard)) {\n // Wait 600ms then, do this!\n setTimeout(function () {\n currentCard.classList.remove(\"open\", \"show\", \"disable\");\n firstCard.classList.remove(\"open\", \"show\", \"disable\");\n firstCard = null; \n }, 600);\n\n return;\n }\n\n // Matched\n currentCard.classList.add(\"match\");\n firstCard.classList.add(\"match\");\n \n matchedCards.push(currentCard, firstCard);\n \n firstCard = null;\n \n // Check if the game is over!\n if (isGameOver()) {\n endGame();\n // resetTimer();\n }\n });\n };\n}", "function clickedCard() {\n if (event.target.classList.contains('card')) {\n event.target.classList.add('open', 'show', 'temp');\n tempArray.push(event.target);\n if (tempArray.length == 2) {\n if (tempArray[0] != tempArray[1]) {\n move++;\n moves.innerHTML = move;\n checkMatch();\n if (move === 15) {\n stars.children[2].classList.add('hide');\n starsArray.pop();\n } else if (move === 19) {\n stars.children[1].classList.add('hide');\n starsArray.pop();\n }\n } else {\n tempArray.splice(1);\n }\n }\n }\n}", "function cardClicked(event) {\n if (event.target.className === 'card' && clickedCards.length <2) {\n event.target.classList.add('open', 'show');\n addCardsToClickedCards(event);\n doCardsMatch(event);\n }\n}", "function selectCard(e) {\n let cardNode = e.target;\n let match;\n\n // only activate if card is clicked (not the deck)\n if (cardNode.getAttribute('class') === 'card') {\n\n // determin whether this is the first card selected\n if (cardSelected === false) {\n // show icon of card\n card1 = cardNode;\n flipCard(card1);\n\n // indicate that the first card has been selected\n cardSelected = true;\n } else {\n // show icon of card\n card2 = cardNode;\n flipCard(card2);\n\n // update the turn counter\n turns++;\n updateTurns(turns);\n\n // check whether the star need to be reduced\n reduceStars();\n\n // prevent other cards from being selected\n cardNode.parentNode.removeEventListener('click', selectCard);\n\n // check if selected cards are a match\n match = checkMatch(card1, card2);\n if (match) {\n // reinstate ability to select cards\n cardNode.parentNode.addEventListener('click', selectCard);\n\n // indicate that a pair has been found\n cardsMatched=cardsMatched+2;\n\n // determine if cards\n if (cardsMatched == CARDS) {\n // show congratulations panel and end game\n endGame();\n }\n } else {\n window.setTimeout(function(){\n flipCard(card1, 'reverse');\n flipCard(card2, 'reverse');\n // reinstate ability to select cards (after cards have been flipped)\n cardNode.parentNode.addEventListener('click', selectCard);\n }, 500);\n }\n\n // reset so that new card pairs can be selected\n cardSelected = false;\n }\n }\n}", "function toggleCard() {\n // Show cards when clicked\n $(\".card\").on(\"click\", function() {\n if ($(this).hasClass(\"open show\")) { return; }\n $(this).toggleClass(\"flipInY open show\");\n openCard.push($(this));\n startGame = true; {\n if (startGame = true){ //when clicked timer starts\n timer.start(); }\n else (startGame === false) \n \t }\n //If cards open check match\n if (openCard.length === 2) {\n if (openCard[0][0].classList[2] === openCard[1][0].classList[2]) {\n openCard[0][0].classList.add(\"bounceIn\", \"match\");\n openCard[1][0].classList.add(\"bounceIn\", \"match\");\n $(openCard[0]).off('click');\n $(openCard[1]).off('click');\n matchFound += 1;\n moves++;\n removeOpenCards();\n findWinner();\n } else {\n // If classes are not mathcing adds \"noMatch\" class\n openCard[0][0].classList.add(\"shake\", \"noMatch\");\n openCard[1][0].classList.add(\"shake\", \"noMatch\");\n \n // Removes \"show\" and \"open\" class\n setTimeout(removeClasses, 1100);\n // if classes are not mathcing resets openCard.length to 0\n setTimeout(removeOpenCards, 1100);\n moves++;\n }\n }\n updateMoves();\n })\n}", "function cardClickHandler(event) {\n $(this).attr('class','open card show click'); /* Card shows open when clicked */\n let cardcount = $('ul').find('.click').length; /*Keep count of cards that have been clicked*/\n\n//Array to check class of cards that are open once two are picked and turn them a color\n if (cardcount == 2) {\n $('.card').off('click', cardClickHandler); /*this ensures that only two cards can be seen*/\n//Setup array and specific class for each card selected to see if they match\n let openClass = $('.click').find('i');\n let classone = openClass[0].className;\n let classtwo = openClass[1].className;\n\n//increment the moves variable and update the count in html so user can see the moves as they happen\n moves++;\n document.getElementById(\"moves\").innerHTML = moves;\n\n//Remove one star after 13 moves, but before 19 moves\n if (moves > 13 && moves < 19) {\n $('.stars').find('#twostar').attr('class','star');\n }\n\n //Remove two stars after 19 moves\n if (moves >= 19) {\n $('.stars').find('#twostar').attr('class','star');\n $('.stars').find('#onestar').attr('class','star');\n }\n\n //If function when the two cards are a match\n if (classone == classtwo){\n $('.click').attr('class','open card show match'); /*new class to show the card green if it matches*/\n $('.card').on('click', cardClickHandler); /*turn the click handler back on so new cards can be selected*/\n $('.match').off('click', cardClickHandler); /*turn click handler off for cards that have the class match so they aren't selected*/\n\n //If statement to fire the modal when 16 cards have been matched\n if (($('.match').length)==16) {\n modalfire ();\n }\n return moves;\n }\n\n//Else function if the cards do not match\n else {\n $('.click').attr('class','open card show miss click'); /*show the cards as red cards*/\n\n //function to have the cards turn back over in just under 1 second.\n setTimeout(function() {\n $('.click').attr('class','card'); /*change the class back to a card to flip it back over*/\n $('.card').on('click', cardClickHandler);/*turn the click handler back on so new cards can be selected*/\n $('.match').off('click', cardClickHandler); /*ensure matched cards still aren't able to be selected after a miss*/\n }, 999);\n return moves;\n }\n }\n}", "function clickCard() {\n deck.addEventListener('click', function(event) {\n if (event.target.classList.contains('card')) {\n cardClicks++;\n if (cardClicks === 1 || cardClicks === 2) {\n clickedCard();\n } else {\n resetTurn();\n }\n }\n })\n}", "function cardClicked(clickEvent) {\n\n //This will create a reference to the actual card clicked on.\n const cardElementClicked = clickEvent.currentTarget;\n\n //That event is passed to this function which accesses the \n //currentTarget to get element that is clicked during the event.\n const cardClicked = cardElementClicked.dataset.cardtype;\n\n //Adds flip class to the clicked card.\n cardElementClicked.classList.add('flip');\n\n //sets the current card to cardClicked if cardClicked is null\n if (currentCard) {\n\n //matchFound will be set to true if cardClicked is equal to \n //currentCard.\n const matchFound = cardClicked === currentCard;\n\n //Adds matched cards to array of cardsMatched\n if (matchFound) {\n cardsMatched.push(cardClicked);\n //If cardsMatched is equal to cardsLength the array is complete and \n //the game is over.\n if (cardsMatched.length === cards.length) {\n\n setTimeout(gameWon, 500);\n }\n\n // Reset.\n currentCard = null;\n } else {\n //setTimeout is used to delay the function for 500 milliseconds\n // so the user can process the image.\n setTimeout(() => {\n\n document\n .querySelectorAll(`[data-cardType=\"${currentCard}\"]`)\n .forEach(card => card.classList.remove('flip'));\n\n //Remove flip class from the card that was just clicked.\n cardElementClicked.classList.remove('flip');\n\n // Reset.\n currentCard = null;\n }, 500);\n }\n //Reset. \n } else {\n currentCard = cardClicked;\n }\n}", "function activateCards() {\n allCards.forEach(function(card) {\n card.addEventListener('click', function(e) {\n console.log(\"A card was clicked!\"); \n if (!card.classList.contains('open') && !card.classList.contains('show') && !card.classList.contains('match')) {\n openCards.push(card);\n if (openCards.length < 3) {\n card.classList.add('open', 'show');\n // If cards match, show!\n if (openCards.length == 2) {\n if (openCards[0].dataset.card == openCards[1].dataset.card) {\n openCards[0].classList.add('match');\n openCards[0].classList.add('open');\n openCards[0].classList.add('show');\n\n openCards[1].classList.add('match');\n openCards[1].classList.add('open');\n openCards[1].classList.add('show');\n\n openCards = [];\n matched++;\n } else { \n // If they do not match, hide\n setTimeout(function(){\n openCards.forEach(function(card) {\n card.classList.remove('open', 'show');\n });\n\n openCards = [];\n }, 800);\n }\n addMove();\n checkScore();\n checkForGameOver();\n }\n }\n }\n });\n }); \n}", "function click(card) {\n // Create Click Event for card\n card.addEventListener(\"click\", function() {\n if(firstClick) {\n // Call Start the timer function\n startTimer();\n // Change the First Click value\n firstClick = false;\n }\n const secondCard = this;\n const firstCard = openedCards[0];\n // Opened card\n if(openedCards.length === 1) {\n card.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n // Call the Compare function\n compare(secondCard, firstCard);\n } else {\n secondCard.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n }\n });\n}", "function whenClicked(card){ \r\n \r\n card.addEventListener(\"click\", function(){\r\n \r\n \r\n if (openedCards.length===1){\r\n \r\n \r\n const currentCard=this;\r\n const previousCard=openedCards[0];\r\n\r\n \r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n\r\n compare(currentCard,previousCard);\r\n\r\n \r\n }else{\r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n }\r\n }\r\n\r\n );\r\n\r\n}", "function handleCardClick(event) {\n\tlet clickedCard = event.target;\n\t// check whether card has been clicked\n\tfor (let card of allClickedCards) {\n\t\tif (card === clickedCard) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t// handle the first of the two clicks\n\tif (clicked.length === 0) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\t// handle the second of the two clicks\n\t} else if (clicked.length === 1) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\tresult = checkMatch(clicked[0].style.backgroundImage, clicked[1].style.backgroundImage);\n\t\tif (result === true) {\n\t\t\t// start the counter over\n\t\t\tfor (card of clicked) {\n\t\t\t\tcard.classList.add('glow');\n\t\t\t}\n\t\t\tclicked = [];\n\t\t\tupdateGuesses();\n\t\t\t// keep from re-clicking the card, take it out of the running\n\t\t} else {\n\t\t\tsetTimeout(function() {\n\t\t\t\tflipCards(clicked);\n\t\t\t\tclicked = [];\n\t\t\t}, 1000);\n\t\t\tallClickedCards.pop();\n\t\t\tallClickedCards.pop();\n\t\t\tupdateGuesses();\n\t\t}\n\t}\n\n\tif (allClickedCards.length === COLORS.length) {\n\t\tsetTimeout(function() {\n\t\t\tgameOver();\n\t\t}, 100);\n\t}\n}", "function playGame(event) {\r\n // Game status update and all 5 stars added to score panel\r\n gameStatus.textContent = \"GAME ON!\";\r\n stars.innerHTML = star.repeat(5);\r\n let cardInPlay = event.target;\r\n // Check that card is not already turned over, then continue.\r\n if (cardInPlay.classList.contains('show')) {\r\n nodeElement = 0;\r\n } else {\r\n nodeElement = cardInPlay.tagName;\r\n }\r\n\r\n if (nodeElement === \"LI\") {\r\n /* If click is a card (\"LI\") then number of moves and star counter both activated.\r\n Also, card added to flipped cards array for checking match */\r\n moves++;\r\n starCounter(moves);\r\n let flippedCard = cardInPlay.dataset.card;\r\n movesCounter.textContent = moves;\r\n flippedCards.push(flippedCard);\r\n cardsInPlay.push(cardInPlay);\r\n }\r\n // Process for checking if cards match or not using switch\r\n switch (cardsInPlay.length) {\r\n\r\n case 1: cardsInPlay[0].classList.add('open', 'show'); break;\r\n\r\n case 2: cardsInPlay[1].classList.add('open', 'show');\r\n\r\n switch (true) {\r\n\r\n case flippedCards[0] == flippedCards[1]:\r\n setTimeout(function cardsMatch() {\r\n cardsInPlay[0].classList.add('match');\r\n cardsInPlay[1].classList.add('match');\r\n matchedCards.push(flippedCards[0], flippedCards[1]);\r\n cardsInPlay = [];\r\n flippedCards = [];\r\n // End game check after each successful match \r\n endGame(matchedCards);\r\n }, 1000);\r\n break;\r\n\r\n case flippedCards[0] === flippedCards[1]:\r\n setTimeout(function cardsNotMatch() {\r\n cardsInPlay[0].classList.remove('open', 'show');\r\n cardsInPlay[1].classList.remove('open', 'show');\r\n cardsInPlay = [];\r\n flippedCards = [];\r\n }, 1000);\r\n break;\r\n\r\n case flippedCards[0] != flippedCards[1]:\r\n setTimeout(function cardsNotMatch() {\r\n cardsInPlay[0].classList.remove('open', 'show');\r\n cardsInPlay[1].classList.remove('open', 'show');\r\n cardsInPlay = [];\r\n flippedCards = [];\r\n }, 1000);\r\n }\r\n }\r\n}", "function clicked(card) {\n card.addEventListener(\"click\",function(){\n \tcard.classList.add(\"show\", \"open\");\n\t stack.push(card);\n\t move();\n\t //when user open two card, compare them\n\t if(stack.length == 2){\n\t \t//same \n if(stack[0].innerHTML== stack[1].innerHTML){\n \t\tstack[0].classList.add(\"match\");\n \t\tstack[1].classList.add(\"match\");\n \t \tstack[1].removeEventListener(\"click\", this);\n \t \tstack.pop();\n \tstack.pop();\n \tnoOpenCard=noOpenCard+2;\n }\n //difference \n else{\n \tsetTimeout(function(){\n \tstack[0].classList.remove(\"show\",\"open\");\n \tstack[1].classList.remove(\"show\",\"open\");\n \tstack.pop();\n \tstack.pop();\n \t\t}, 300); \n }\n\t }\n result();\n })\n }", "function checkCard(card) {\n addMovement();\n\n currCards.push(card);\n\n let symbol = card.firstElementChild.className;\n openedCards.push(symbol);\n\n //check if a matched card is already opened\n if (openedCards.filter(openCard => openCard == symbol).length > 1) {\n lockCard();\n }\n //check if 2 cards are opened but not matched\n else if (openedCards.filter(openCard => openCard == symbol).length == 1 && currCards.length == 2) {\n for (let card of currCards) {\n card.className = 'card shake';\n }\n\n //hide unmatched cards after 0.5 second\n setTimeout(hideCard, 500);\n }\n}", "function bindClickEvent() {\n cardDeck.cards.forEach(card => {\n card.node.addEventListener(\"click\", (e) => {\n if (isClosingCard || card.isOpened() || card.isMatched()) {\n return;\n }\n \n card.open();\n \n if (state.isMatching) {\n if (state.matchingCard.getValue() === card.getValue()) {\n \n card.match()\n state.matchingCard.match();\n \n if (cardDeck.cards.filter(x => x.isMatched()).length === cardDeck.cards.length) {\n state.isGameOver = true;\n saveState();\n updateScreenMode(true);\n return;\n }\n \n state.isMatching = false;\n state.matchingCard = null;\n increaseMoveCounter();\n saveState();\n } else {\n isClosingCard = true;\n window.setTimeout(function() {\n card.closeCard()\n if (state.matchingCard !== null) {\n state.matchingCard.closeCard()\n }\n \n increaseMoveCounter();\n \n state.isMatching = false;\n state.matchingCard = null;\n saveState();\n isClosingCard = false;\n }, 500);\n }\n } else {\n state.isMatching = true;\n state.matchingCard = card;\n saveState();\n }\n }, false);\n });\n }", "function checkCard() {\n if (timerRunning === false) {\n timer();\n timerRunning = true;\n var music = document.getElementById(\"music\");\n music.currentTime = 180.175;\n }\n//The card is either cardOne...\n if (!cardOne) {\n cardOne = this;\n cardOne.removeEventListener('click', checkCard);\n cardOne.style.backgroundImage = cardOne.cover;\n cardOne.classList.add('open');\n cardOne.classList.add('show');\n return false;\n//...or cardTwo.\n } else if (!cardTwo) {\n cardTwo = this;\n cardTwo.removeEventListener('click', checkCard);\n cardTwo.style.backgroundImage = cardTwo.cover;\n cardTwo.classList.add('open');\n cardTwo.classList.add('show');\n moveCount += 1;\n console.log('Total moves ' + moveCount);\n document.getElementsByTagName('span')[0].innerHTML = moveCount;\n//Denumerates number of stars the moves you make.\n if (moveCount > 8 && moveCount < 13) {\n document.getElementsByClassName('fa fa-star')[4].style.visibility = 'hidden';\n starCount = 4;\n } else if (moveCount > 12 && moveCount < 17) {\n document.getElementsByClassName('fa fa-star')[3].style.visibility = 'hidden';\n starCount = 3;\n } else if (moveCount > 16 && moveCount < 21) {\n document.getElementsByClassName('fa fa-star')[2].style.visibility = 'hidden';\n starCount = 2;\n } else if (moveCount > 20) {\n document.getElementsByClassName('fa fa-star')[1].style.visibility = 'hidden';\n starCount = 1;\n }\n//If there is a match...\n if (cardOne.firstChild.className === cardTwo.firstChild.className) {\n cardTwo.classList.add('match');\n cardTwo.classList.remove('open');\n cardTwo.classList.remove('show');\n cardOne.classList.add('match');\n cardOne.classList.remove('open');\n cardOne.classList.remove('show');\n cardOne = null;\n cardTwo = null;\n matchedCount += 1;\n//Defines the conditions for the win.\n if (matchedCount === 8) {\n clearTimeout(t);\n for (let s = 0; s < starCount; s++) {\n const modalStar = document.createElement('i');\n modalStar.classList.add('fa', 'fa-star');\n document.getElementsByClassName('modal-stars')[0].appendChild(modalStar);\n }\n document.getElementsByClassName('modal-moves')[0].innerHTML = moveCount;\n document.getElementsByClassName('modal-time')[0].innerHTML = h2.textContent;\n //document.getElementsByClassName('modal-stars')[0].innerHTML = modalStar;\n $('#No1modal').modal('show');\n var music = document.getElementById(\"music\");\n music.currentTime = 395.5;\n console.log(starCount)\n }\n console.log('Total matches ' + matchedCount)\n } else {\n setTimeout(function() {\n cardTwo.addEventListener('click', checkCard);\n cardTwo.classList.remove('open');\n cardTwo.classList.remove('show');\n cardTwo.style.backgroundImage = 'none';\n cardOne.addEventListener('click', checkCard);\n cardOne.classList.remove('open');\n cardOne.classList.remove('show');\n cardOne.style.backgroundImage = 'none';\n cardOne = null;\n cardTwo = null;\n }, 2000);\n }\n }\n}", "function flipCard(evt) {\n\tif (evt.target !== evt.currentTarget) {\n\t\tconst clickedCard = evt.target;\n\t\tclickedCard.classList.add('show', 'open');\n\t\tflippedCard.push(clickedCard);\n\t\t\t\t\n\t\t\t//if the list already has another card, check to see if the two cards match\n\t\tif (flippedCard > 2){\n\t\t\tfirstCard.classList.remove('show', 'open');\n\t\t\tsecondCard.classList.remove('show', 'open');\n\t\t}\n\t\tconst firstCard = flippedCard[0];\n\t\tconst secondCard = flippedCard[1];\n\n\n\t\tif (firstCard && secondCard) {\n\t\t\tcardMoves +=1 ;\n\t\t\tnumMoves.innerHTML = cardMoves;\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tif (flippedCard.length === 2 && firstCard.innerHTML == flippedCard[1].innerHTML && \n\t\t\tfirstCard.innerHTML === flippedCard[1].innerHTML){\n\t\t\t//if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one)\n\n\t\t\tclickedCard.classList.add('match');\n\t\t\tfirstCard.classList.add('match')\n\t\t\tconsole.log('match!!');\t\n\t\t\tflippedCard = [];\n\t\t\tmatchedCard.push(firstCard, secondCard);\n\t\t\tgameWon();\n\n\t\t}else if (flippedCard.length === 2 && firstCard.innerHTML != flippedCard[1].innerHTML){\n\t\t\tconsole.log('no match');\n\n\t\t\tsetTimeout(wait, 1000);\n\t\t\tfunction wait(){\n\t\t\t\tfirstCard.classList.remove('show', 'open');\t\t\t\n\t\t\t\tsecondCard.classList.remove('show', 'open')\n\t\t\t\t\n\t\t\t}\n\t\t\tflippedCard = [];\n\t\t}else {\n\t\t\tconsole.log('select another');\n\t\t}\n\t}\n\n\tevt.stopPropagation();\n}", "function flip(){\n for(let i = 0; i < MyDeck.length; i++){\n allCards[i].addEventListener('click', function(evt){\n let targetClass = evt.target.className;\n if(targetClass == \"card\" && HowManyTimes != 2){\n allCards[i].className = ('class', 'card open show');\n movesCounter += 1;\n moves.innerHTML = movesCounter;\n if(firstCard == false ){\n firstCard = evt.target.firstElementChild.className;\n firstParentCard = evt.target;\n HowManyTimes += 1;\n } else {\n secondCard = evt.target.firstElementChild.className;\n secondParentCard = evt.target;\n HowManyTimes += 1;\n }\n\n // Comparing the Cards\n function doTheyMatch(){\n if(HowManyTimes === 2){\n if(secondCard == firstCard){\n matchingCards += 2;\n }\n } setTimeout(() => {\n if(HowManyTimes === 2){\n if(secondCard == firstCard){\n firstParentCard.className = 'card open match';\n secondParentCard.className = 'card open match';\n HowManyTimes *= 0;\n firstCard = '';\n secondCard = '';\n firstParentCard = '';\n secondParentCard = '';\n } else {\n firstParentCard.className = 'card';\n secondParentCard.className = 'card';\n HowManyTimes = 0;\n firstCard = '';\n secondCard = '';\n firstParentCard = '';\n secondParentCard = '';\n }\n };\n }, 1000);\n }\n doTheyMatch();\n }\n });\n allCards[i].onclick = (function(){\n Rating();\n const recieveTime = document.querySelector('.timer');\n if(movesCounter == 1){\n if(recieveTime.innerText === \"00:00\"){\n timerStart();\n timer();\n }\n }\n winGame();\n });\n };\n}", "function handleClicks() {\n\tlet cards = document.querySelectorAll('.card');\n\t// Removing event listener from the clicked card\n\tthis.removeEventListener('click', handleClicks);\n\tcountMoves();\n\tscore();\n\tdisplayCard(this);\n\tstoreClickedCard(this);\n\t\n\tif (clickedCard.length == 2) {\n\t\tcards.forEach( function(card) {\n\t\t\t// Removing event listener from all the cards\n\t\t\tcard.removeEventListener('click', handleClicks);\n\t\t});\t\n\n\t\tcheckMatching(clickedCard);\n\n\t\tif (cardMatch == true) {\n\t\t\topenCard(clickedCard);\n\t\t} else {\n\t\t\tsetTimeout(function() {\n\t\t\t\thideCard(clickedCard);\n\t\t\t}, 500);\n\t\t}\n\n\t\tsetTimeout(function() {\n\t\t\t// Adding event listener back to all cards\n\t\t\tcards.forEach( function(card) {\n\t\t\t\tcard.addEventListener('click', handleClicks);\n\t\t\t});\n\t\t\t// Removing event listener from the matched cards\n\t\t\tmatchedCards.forEach( function(card) {\n\t\t\t\tcard.removeEventListener('click', handleClicks);\n\t\t\t});\n\t\t},500);\n\t}\n\tif (matchedCards.length == 16) {\n\t\tendGame();\t\t\n\t}\n}", "function clickCard() {\n\n // add open class\n this.classList.add('open');\n\n // add class to open array\n openCards.push(this.id);\n\n // check if total items in open array is 2\n if (openCards.length === 2) {\n\n // get the unique items in this array\n let unique = openCards.filter(onlyUnique);\n\n // if total is equal to 1, a match was found, add to matched array.\n if (unique.length === 1) {\n matchedCards.push(this.id);\n }\n\n // if total matched cards is total cards, reset game by removing all matched cards\n if (matchedCards.length === cards.length / 2) {\n\n // game finshed.\n\n window.setTimeout(() => {\n victory();\n matchedCards = [];\n }, 500);\n }\n\n // reset cards, with a short delay\n window.setTimeout(() => {\n resetCards();\n }, 500);\n }\n}", "function matchCards() {\n\n // Show cards \n $(\".card\").on(\"click\", function() {\n if ($(this).hasClass(\"open show\")) {\n return\n }\n $(this).toggleClass(\" flipInY open show\");\n cardOpen.push($(this));\n\n // Check cards if they matched or not\n if (cardOpen.length === 2) {\n if (cardOpen[0][0].classList[2] === cardOpen[1][0].classList[2]) {\n cardOpen[0][0].classList.add(\"flash\", \"match\");\n cardOpen[1][0].classList.add(\"flash\", \"match\");\n $(cardOpen[0]).off('click');\n $(cardOpen[1]).off('click');\n matchFound += 1;\n moves++;\n removeOpenCards();\n endOfGame();\n } else {\n // If classes don't match, add \"wobble\" class\n cardOpen[0][0].classList.add(\"wobble\", \"wrong\");\n cardOpen[1][0].classList.add(\"wobble\", \"wrong\");\n // Timeout to remove cards\n setTimeout(removeClasses, 800);\n setTimeout(removeOpenCards, 800);\n moves++;\n }\n }\n\n UpdateMoves();\n });\n\n}", "function loadCard(card) {\n currentOpenCards.push(card);\n if (duplicates()) {\n currentOpenCards.pop();\n deck.addEventListener('click', flipCard);\n } else if (currentOpenCards.length === 1) {\n card.classList.add('open', 'show');\n } else if (currentOpenCards.length === 2) {\n card.classList.add('open', 'show');\n deck.removeEventListener('click', flipCard);\n checkForMatch(card);\n }\n}", "function compareCards(newCard) {\n const firstCardValue = previousCard.dataset.value;\n const secondCardValue = newCard.dataset.value;\n\n if (firstCardValue !== secondCardValue) {\n previousCard.addEventListener('click', dispalyCard);\n previousCard.classList.remove('open');\n newCard.classList.remove('open');\n }\n else {\n //if two cards were the same\n previousCard.removeEventListener('click', dispalyCard);\n newCard.removeEventListener('click', dispalyCard);\n matchCard.push(previousCard);\n matchCard.push(newCard);\n if (matchCard.length === 16){\n document.getElementById('pop-up').style.display= 'block';\n }\n }\n \n // empty the game memory\n previousCard = null;\n\n}", "function clickedCard() {\n$('li.card').on('click', function() {\n\tlet openCard = $(this);\n\ttoggleOpenShow(openCard);\n\tif(openCard.hasClass('open show disabled')\n\t\t&& allOpenedCards.length < 2) {\n\t\tallOpenedCards.push(openCard);\t\t\n\t}\t\t\n\tmatchedCard();\n\t});\n}", "function clickCard(event) {\n\n\tif (interval === null) {\n\t\tsetTime();\n\t}\n\n\t//Check there's not more than 2 cards clicked\n\tif (counter < 2) {\n\t\tvar element = event.target;\n\n\t\t//Show the card\n\t\telement.style.backgroundImage = cards[ids.indexOf(element.id)];\n\n\t\t//Check it's not the same card clicked twice\n\t\tif (previousCard !== element.id) {\n\t\t\t//Count a click\n\t\t\tcounter++;\n\n\t\t\t//Check if it's the 2nd card\n\t\t\tif (previousCard !== null) {\n\t\t\t\tcurrentCard = element.id;\n\n\t\t\t\t//Restart images\n\t\t\t\tvar currentPicture = document.getElementById(currentCard).style.backgroundImage;\n\t\t\t\tvar previousPicture = document.getElementById(previousCard).style.backgroundImage;\n\n\t\t\t\t//Check if both images are the same\n\t\t\t\tif (currentPicture === previousPicture) {\n\t\t\t\t\t//Initialices a temporizer to execute correct action\n\t\t\t\t\tsetTimeout(removeCards, 1000);\n\t\t\t\t\n\n\t\t\t\t//If they're different \n\t\t\t\t} else {\n\t\t\t\t\t//Substract the score\n\t\t\t\t\tscore += -5;\n\t\t\t\t\tshowScore();\n\t\t\t\t\t//Initialices a temporizer to execute wrong action\n\t\t\t\t\tsetTimeout(hideCards, 1000);\n\t\t\t\t}\n\t\t\t\n\t\t\t} else {\n\t\t\t\t//If it's the first, store the card for the next click\n\t\t\t\tpreviousCard = element.id;\n\t\t\t}\n\t\t}\n\t}\n}", "function openCard(card) {\n\n //start timer on the pick of the very first card\n if (movesCounter === 0 && openCardsList.length === 0) {\n startTimer();\n }\n\n // if two card are already opened do not pick any more\n if (openCardsList.length >= 2) {\n return;\n }\n\n //pick the card and proceed to check the current conditions\n pickCard(card);\n\n //if no cards opened alredy, open card and add to the list of open cards\n if (openCardsList.length === 0) {\n addToOpenCardsList(card);\n }\n //if one card already opened - open card and add to the list of open cards\n //then check if the card match\n else if (openCardsList.length === 1) {\n\n //opening two cards caounts as a one move\n movesCounter++;\n //update moves counter on page\n movesElement.innerText = movesCounter;\n //check star rating\n starRating = calculateStarRating(movesCounter);\n //update star rating on page (display correct number of stars)\n setStarRating(starRating)\n\n addToOpenCardsList(card);\n\n //if cards match - mark them\n setTimeout(function() {\n if (cardsMatch(openCardsList[0], openCardsList[1])) {\n\n setMatchedCards(openCardsList[0], openCardsList[1]);\n\n matchedCounter++;\n //Check if it was last pair of cards (game over)\n if (gameOver()) {\n stopTimer();\n setTimeout(function() {\n modalText.innerText = 'You made it in ' + movesCounter + ' moves ! It took ' + timer + ' of time! Your Star Rating is: ' + starRating;\n modal.classList.toggle(\"opened\");\n }, 500);\n }\n\n } else {\n setNotMatchedCards(openCardsList[0], openCardsList[1]);\n closeCards(openCardsList[0], openCardsList[1]);\n }\n resetOpenCardsList();\n }, 800);\n }\n}", "function cardOpen() {\n openedCards.push(this);\n openedCards[0].classList.add(\"disabled\");\n var length = openedCards.length;\n if (length === 2) {\n moveFunction();\n if (openedCards[0].dataset.name === openedCards[1].dataset.name) {\n scoreFunction();\n matched();\n } else {\n unmatched();\n }\n }\n}", "function handleCardClick(event) {\n // you can use event.target to see which element was clicked\n console.log(\"you just clicked\", event.target);\n if (faceUpPair.length < 2) {\n if (!event.target.style.backgroundColor){\n // reveal card\n event.target.style.backgroundColor = event.target.getAttribute('data-color');\n if (!faceUpLock){\n // synchronize on write\n faceUpLock = true;\n faceUpPair.push(event.target); // add card to array\n faceUpLock = false;\n }\n // increment score\n score++;\n currScore.innerText = score;\n //console.log(faceUpPair);\n }\n }\n if (faceUpPair.length == 2) {\n //console.log(faceUpPair);\n if (faceUpPair[0].style.backgroundColor !== faceUpPair[1].style.backgroundColor) {\n if (!faceUpLock){\n // lock faceUpPair until after timeout\n faceUpLock = true;\n setTimeout(() => {\n // hide cards\n for (let card of faceUpPair){\n card.style.backgroundColor = \"\";\n }\n faceUpPair = [];\n faceUpLock = false;\n }, 1000);\n }\n } else {\n if (!faceUpLock){\n // synchronize on write\n faceUpLock = true;\n faceUpPair = [];\n faceUpLock = false;\n }\n }\n }\n //console.log(\"Game Over: \", isGameOver());\n // show restart button if game over\n if (isGameOver() && !gameSetup.querySelector(\"#restart\")){\n if (localStorage.bestScore){\n const lowestScore = score < localStorage.bestScore ? score : localStorage.bestScore;\n localStorage.setItem(\"bestScore\", lowestScore);\n }\n else {\n localStorage.setItem(\"bestScore\", score);\n }\n bestScore.innerText = localStorage.bestScore; // update display\n gameSetup.querySelector('#setup-restart').appendChild(createRestartBtn());\n }\n}", "function matchCards() {\r\n\r\n // Function Call to flip 'this' particular Card\r\n flipCard(this);\r\n\r\n // Storing Id and Src of Clicked Cards\r\n id = $(this).attr('id');\r\n src = $($($(this).children()[1]).children()[0]).attr(\"src\");\r\n\r\n // Counting Number of Moves\r\n count += 1;\r\n if (count % 2 == 0) {\r\n moves = count / 2;\r\n $(\"#moves\").html(moves);\r\n // Function call to set stars as number of moves changes\r\n setRating();\r\n }\r\n\r\n // Pushing values in Array if less than 2 Cards are open\r\n if (hasSrc.length < 2 && hasId.length < 2) {\r\n hasSrc.push(src);\r\n hasId.push(id);\r\n\r\n // Turning off Click on first Card\r\n if (hasId.length == 1)\r\n $(this).off('click');\r\n }\r\n\r\n // Matching the two opened Cards\r\n if (hasSrc.length == 2 && hasId.length == 2) {\r\n if (hasSrc[0] == hasSrc[1] && hasId[0] != hasId[1]) {\r\n // Counting Pairs\r\n pair += 1;\r\n\r\n // Turning off Click on matched Cards\r\n $.each(hasId, function(index) {\r\n $('#' + hasId[index] + '').off(\"click\");\r\n });\r\n\r\n } else {\r\n // Flipping back unmatched Cards with a bit of delay\r\n $.each(hasId, function(index, open) {\r\n setTimeout(function() {\r\n flipCard('#' + open + '');\r\n }, 600);\r\n });\r\n\r\n // Turing on Click on first unmatched Card\r\n $('#' + hasId[0] + '').on(\"click\", matchCards);\r\n }\r\n\r\n // Emptying the Arrays \r\n hasSrc = [];\r\n hasId = [];\r\n }\r\n\r\n // Checking if all Cards are matched\r\n if (pair == 8) {\r\n endGame();\r\n }\r\n\r\n }", "function openCard() {\n let clickedCard = event.target;\n\n //Prevents from openning a new card while it's still checking the current pair \n if (!finishChecking) {\n return;\n };\n\n if (arrayOfClickedCards.length >= 2) {\n //To make sure it will not open more then 2 cards at the same time\n return;\n };\n\n if (clickedCard.nodeName === 'LI' && !clickedCard.classList.contains(CSS_OPEN_CARD_CLASS)) {\n clickedCard.classList.add(CSS_OPEN_CARD_CLASS);\n\n if (clickedCard.classList.contains(CSS_DONT_MATCH_CLASS)) {\n clickedCard.classList.remove(CSS_DONT_MATCH_CLASS);\n };\n \n countMoves();\n moveCounter === 1 && manageTimer(true);\n addOpenCardsToList(clickedCard.innerHTML);\n };\n}", "function appear(card){\n //OPEN first card or second card & compare between them\n function addCard() {\n // match timer start with first click\n const viewCard = this;\n const previousCard = openedCards[0];\n\n if (openedCards.length === 1) {\n card.classList.add('open', 'show', 'remove');\n openedCards.push(this);\n moves++;\n moveNumber.textContent = moves;\n compare(viewCard, previousCard);\n stars();\n } else {\n card.classList.add('open', 'show', 'remove');\n openedCards.push(this);\n stars();\n }\n\n if (isFirstClick === true) {\n timer();\n isFirstClick = false;\n }\n }\n card.addEventListener('click', addCard);\n}", "function click(card) {\n //click a card\n card.addEventListener(\"click\", function() {\n //run the timer and set the isFirstClick to false to not refer to this statement again\n if (isFirstClick) {\n beginTime();\n isFirstClick = false;\n }\n //add cards to an open card array to prepare to compare them\n if(openCards.length === 1){\n //if one card has aready been clicked then ->\n const firstCard = openCards[0];\n const secondCard = this;\n //open the card up, show the icon and disable is being clicked again using the freeze class\n card.classList.add(\"open\", \"show\", \"freeze\");\n openCards.push(this);\n compareCards(firstCard, secondCard);\n\n } else if (openCards.length >= 2){\n //Do Nothing\n } else {\n //if this is the first card to be clicked then ->\n card.classList.add(\"open\", \"show\", \"freeze\");\n openCards.push(this);\n }\n });\n }", "function playCard(event) {\n /**\n * If the player clicked on the symbol, we send the click event to the li element.\n */\n if (event.target.localName === \"i\") {\n event.target.parentNode.click();\n return;\n }\n\n timer.start();\n\n if (showCard(event) === false) {\n return;\n }\n\n var iClasses = event.target.childNodes[0].className.split(' ');\n addToOpenCards(event.target.id, iClasses[1]);\n\n let isMatch = function() {\n let keys = Object.keys(openCards);\n if (keys.length!=2) {\n return;\n }\n if (openCards[keys[0]] === openCards[keys[1]]) {\n return true;\n }\n return false;\n }();\n\n if (isMatch===true) {\n makeMatch();\n incrementMatchCount();\n } else if (isMatch===false) {\n setTimeout(misMatch, 300);\n } else {}\n\n incrementMoves();\n checkWinner();\n}", "function click(card) {\n card.addEventListener('click', function() {\n const currentCard = this;\n const previousCard = openCards[0];\n\n //call startTimer function\n clearInterval(interval);\n interval = setInterval(startTimer, 1000)\n\n //check for an existing opened cards\n if (openCards.length === 1) {\n\n card.classList.add(\"open\", \"show\", \"disable\");\n openCards.push(this);\n\n //compare our two opened card\n compare(currentCard, previousCard);\n\n } else {\n //check for no existing opened cards\n currentCard.classList.add(\"open\", \"show\", \"disable\");\n openCards.push(this);\n }\n });\n}", "function cardsMatchControl(openCardsLength){\n if (openCardsLength==2) {\n moves++;\n moveCounter(moves);\n removeEventListeners();\n setTimeout(function(){\n for (let i=0; i < array.length; i++){\n card[i].addEventListener(\"click\",displayCard);\n }\n },1100);\n Element1= openCards[0];\n childElement1=Element1.firstChild;\n Element2= openCards[1];\n childElement2=Element2.firstChild;\n if (childElement1.className==childElement2.className){\n lockCards(childElement1.className);\n }else{\n Element1.setAttribute(\"class\",\"card show shake\")\n Element2.setAttribute(\"class\",\"card show shake\")\n setTimeout(function(){\n Element1.setAttribute(\"class\",\"card\");\n Element1.addEventListener(\"click\",displayCard);\n Element2.setAttribute(\"class\",\"card\");\n Element2.addEventListener(\"click\",displayCard);\n },1000);\n }\n removeCards(Element1,Element2);\n }\n \n}", "function flipCard() {\n //we need to lock the board to avoid two sets of cards being turned at the same time, otherwise the flipping will fail.\n if (lockBoard) return;\n //There is still the case where the player can click twice on the same card. The matching condition would evaluate to true, removing the event listener from that card.\n if(this === firstCard) return;\n this.classList = '';\n this.classList.add('card');\n if (!hasFlippedCard) {\n hasFlippedCard = true;\n firstCard = this;\n }else{\n hasFlippedCard = false;\n secondCard = this;\n \n\n // if statment for matching cards\n if (firstCard.dataset.num === secondCard.dataset.num){\n firstCard.removeEventListener('click', flipCard)\n secondCard.removeEventListener('click', flipCard)\n let scoreCounter = document.querySelector('.score');\n scoreCounter.innerHTML = `Pairs found: ${score} / 12`\n score++;\n console.log(score)\n let triesCounter = document.querySelector('.tries');\n triesCounter.innerHTML = `Tries: ${tries}`\n tries++;\n } else{\n //When the player clicks the second card, lockBoard will be set to true and the condition if (lockBoard) return; will prevent any card flipping before the cards are hidden or match\n lockBoard=true;\n setTimeout(function(){\n firstCard.classList.add('card-hidden')\n secondCard.classList.add('card-hidden')\n let triesCounter = document.querySelector('.tries');\n triesCounter.innerHTML = `Tries: ${tries}`\n tries++;\n lockBoard=false;\n }, 1000);\n }\n }\n // Shows an alert with numbers of tries, when completing the game \n if (score === 13) {\n setTimeout(function(){\n alert(`Congratulations! You completed the game with ${tries-1} tries`);\n }, 500);\n }\n }", "function start () {\n\n if(startGame === 0){\n startTimer()\n startGame++\n }\n\n let mainEvent = $(this).parent().attr('id')\n firstSecondparents.push(mainEvent)\n\n let sibling = $(this).siblings().attr('id')\n firstSecondPickId.push(sibling)\n\n let siblingInfo = document.getElementById(sibling).childNodes[0].innerHTML\n\n count++\n\n if (count === 1) {\n //pushes the sibling class name of the clicked element in an array\n let changeClasses = document.getElementById(mainEvent)\n changeClasses.setAttribute('class', 'styleColWrapperFlip')\n let siblingFirstInfo = document.getElementById(sibling).childNodes[0].className\n firstSecondPick.push(siblingFirstInfo)\n\n }\n else if (count === 2) {\n /* pushes the sibling class name of the \n * clicked element in an array and checks if the element in the array are equal\n */\n let siblingSecondInfo = document.getElementById(sibling).childNodes[0].className\n firstSecondPick.push(siblingSecondInfo)\n\n let secondElement = firstSecondPick.pop()\n let booleanResult = firstSecondPick.includes(secondElement)\n\n if(!booleanResult){\n numberofClicks++\n \n if(numberofClickedCards.length === 0){\n numberofClickedCards.push(secondElement)\n numberofClickedCards.push(firstSecondPick[0])\n }\n else{\n \n if(numberofClickedCards.includes(secondElement) || numberofClickedCards.includes(firstSecondPick[0]))\n {\n numberofClickedSecondCards.push(secondElement)\n numberofClickedSecondCards.push(firstSecondPick[0])\n }\n else{ \n numberofClickedCards.push(secondElement)\n numberofClickedCards.push(firstSecondPick[0])\n }\n }\n\n }\n if(booleanResult){\n numberOfMoves++\n\n }else{\n if(numberofClickedSecondCards.includes(secondElement) || numberofClickedSecondCards.includes(firstSecondPick[0])){\n\n }else{\n\n numberOfMoves++\n }\n\n }\n\n \n /*checks if the number of times you open a card , either wrong or right and ahows the stars \n * stars are determined based on if the number of open cards fall in those ranges below\n */\n if(numberofClicks <= 12){\n numberOfStars = 3\n }\n else if(numberofClicks <= 22){\n document.getElementById('full-rating1').style.display='none'\n document.getElementById('star1').style.display=''\n numberOfStars = 2\n }\n else if(numberofClicks >= 28){\n document.getElementById('full-rating1').style.display='none'\n document.getElementById('full-rating2').style.display='none'\n document.getElementById('star1').style.display=''\n document.getElementById('star2').style.display=''\n numberOfStars = 1\n }\n document.getElementById(\"move\").innerHTML = numberOfMoves\n\n if (booleanResult) {\n\n firstSecondPickId.forEach(theId => {\n document.getElementById(`${theId}`).style.background = 'linear-gradient(#506d71, #e86722, #8b5338)'\n })\n\n firstSecondparents.forEach(theParents => {\n let changeParentClasses = document.getElementById(theParents)\n changeParentClasses.setAttribute('class', 'styleColWrapperFlip')\n })\n\n while (firstSecondPickId.length > 0 || firstSecondPick > 0 || firstSecondparents > 0) {\n firstSecondPickId.pop()\n firstSecondPick.pop()\n firstSecondparents.pop()\n }\n count = 0\n numberOfOpenCards++\n \n /* checks the the number of open cards equals 8 \n * and call the function that ends the game \n */\n if( maxNumberOfOpenCards === numberOfOpenCards ){\n \n endOfGame()\n completeGame()\n numberofClickedCards = []\n numberofClickedSecondCards = []\n numberofClicks = 0 \n }\n }\n else {\n\n let changeSecondParent = document.getElementById(firstSecondparents[1])\n changeSecondParent.setAttribute('class', 'styleColWrapperFlipError')\n\n firstSecondPickId.forEach(theId => {\n document.getElementById(`${theId}`).style.background = 'linear-gradient(red, grey)'\n let animatedMove = document.getElementById(`${theId}`)\n\n })\n\n function timer() {\n \n setTimeout(function () {\n let changeSecondParentFlip = document.getElementById(firstSecondparents[1])\n changeSecondParentFlip.setAttribute('class', 'styleColWrapperFlip2')\n\n let changeFirstParent = document.getElementById(firstSecondparents[0])\n changeFirstParent.setAttribute('class', 'styleColWrapperFlip2')\n\n while (firstSecondPickId.length > 0 || firstSecondPick > 0 || firstSecondparents > 0 ) {\n firstSecondPickId.pop()\n firstSecondPick.pop()\n firstSecondparents.pop()\n }\n },\n 20)\n }\n\n timer()\n\n count = 0\n }\n }\n}", "function select (cards) {\n cards.addEventListener(\"click\", (e) => {\n if (clickReset === 0) {\n stopWatch ();\n clickReset = 1;\n }\n console.log(cards.innerHTML);\n // put the first click and the second click into variables that can be used\n const firstCard = e.target;\n const secondCard = clickedCards[0];\n\n\n // This will record if we have a currently opened card,\n // I use the ignore css class to make sure we are not matching the same card, this is utlising css pointer-events\n\n if (clickedCards.length === 1) {\n cards.classList.add('open' , 'show', 'ignore');\n clickedCards.unshift(firstCard);\n\n // Comparision of cards for further use\n comparingCards(firstCard, secondCard);\n\n // This will record if we do not having an currently opened cards\n\n } else {\n firstCard.classList.add('open' , 'show', 'ignore');\n clickedCards.push(firstCard);\n }\n });\n}", "function cardClickHandler(e) {\n console.log('card clicked')\n const cardIsNotAlreadyChosen = e.target.parentNode != cardOneElement;\n if (!gameWon && e.target.classList.contains('card-face') && cardIsNotAlreadyChosen) {\n checkStats(e.target.parentNode);\n flipUp(e.target.parentNode);\n }\n}", "function clickOnCard(event)\n{\n // Voorbereiden van lokale variabelen\n var cellNumber = event.target.parentElement.parentElement.parentElement.cellIndex;\n var rowNumber = event.target.parentElement.parentElement.parentElement.parentElement.rowIndex;\n var cardNumber = (rowNumber * 4) + cellNumber;\n\n // Hieronder volgt de logica\n if(!maxCardsClicked()) {\n // Kaart omdraaien en tijdelijk klikken onmogelijk maken\n flipCard(cardNumber);\n toggleClickOnSingleCard(cardNumber, OFF);\n // Kaart toevoegen aan array\n addCardClicked(cardNumber);\n\n //Zijn de kaarten gelijk? Ja, dan punten toekennen\n // en beurt houden. Nee, dan kaarten terugdraaien en beurt naar\n // volgende speler\n if(maxCardsClicked()) {\n // Twee kaarten zijn gedraaid, dus nu heeft het pas zin\n // om te controleren of ze gelijk zijn\n if(areCardsEqual()) {\n // Kaarten zijn gelijk\n ronde_scores[huidige_speler] += 1; // Punt toevoegen\n if(huidige_speler === SPELER1)\n rondescore_speler_1.innerHTML = parseInt(rondescore_speler_1.innerHTML) + 1;\n else\n rondescore_speler_2.innerHTML = parseInt(rondescore_speler_2.innerHTML) + 1;\n //setClickOffOnClickedCards(); // Klikken is al uit\n resetCardsClicked();\n } else {\n // Kaarten zijn niet gelijk\n // Dus beide kaarten terug draaien en klikken weer mogelijk maken\n setTimeout( function() {\n flipCard(cards_clicked[FIRST_CARD_CLICKED]);\n flipCard(cards_clicked[LAST_CARD_CLICKED]);\n toggleClickOnSingleCard(cards_clicked[FIRST_CARD_CLICKED], ON);\n toggleClickOnSingleCard(cards_clicked[LAST_CARD_CLICKED], ON);\n \n // Beurt overgeven aan andere speler\n switchTurn();\n\n resetCardsClicked();\n }, 3000 );\n }\n }\n\n // Controleren of we alle kaarten al gedraaid hebben\n // want dan eindigt de ronde\n if(endOfRoundReached()) {\n endRound();\n }\n }\n}", "function checkCard() {\n if (openCards[0].firstChild.className === openCards[1].firstChild.className) {\n //openCards.push(card);\n openCards[0].classList.add(\"match\");\n openCards[1].classList.add(\"match\");\n openCards[0].classList.remove(\"open\", \"show\");\n openCards[1].classList.remove(\"open\", \"show\");\n removeOpenCards();\n updateMoves();\n checkWin();\n } else if (\n openCards[0].firstChild.className !== openCards[1].firstChild.className\n ) {\n openCards[0].classList.add(\"noMatch\");\n openCards[1].classList.add(\"noMatch\");\n setTimeout(hideCards, 800);\n updateMoves();\n } else {\n return;\n }\n}", "function respondToTheClick(evt) {\n\n\tshowCard(evt.target.classList);\n\n\taddCardtoStack(evt.target.innerHTML);\n\n\tif(timerOn==false) {\n\t\tconsole.log(\"starting timer\");\n\t\t// timerOn = showTimer();\n\t\ttimerOn = setTimeout(showTimer(), 1000);\n\t\ttimerOn = true;\n\t}\n\n\n\t//start fixing the same card shouldn't equal. Make sure the same card aren't being clicked\n\tconst nodes = Array.prototype.slice.call(document.querySelectorAll('ul')[1].children);\n\n\tconst nodeIndex = nodes.indexOf(evt.target);\n\n\tindexList.push(nodeIndex);\n\n\tif((indexList.filter(item => item == nodeIndex).length == 2)){\n\t\tconsole.log(\"diupliate cards\");\n\t\tindexList.pop();\n\t\tindexList.pop();\n\t\tconsole.log(\"index list after removing duplicates\");\n\t\tconsole.log(indexList);\n\t\tremoveCards();\n\t} \n\n\n\t//checking whether there are two cards in the list\n\tif (openCardsList.length>0 && openCardsList.length%2 == 0) {\n\t\t//if the two cards are equal\n\n\t\tif(openCardsList.filter(item => item == evt.target.innerHTML).length == 2) {\n\n\n\t\t\t//lock in the correct cards\n\t\t\tlockCorrectCards(evt.target.childNodes[1]);\n\n\t\t\tif (openCardsList.length == 16) {\n\t\t\t\t//If all 16 cards have been guessed, show the congratulations dialog. \n\t\t\t\tclearInterval(timerOn);\n\t\t\t\ttimerOn = false;\n\t\t\t\tshowDialog();\n\t\t\t}\n\t\t} \n\t\telse {\n\t\t\t//If the two cards aren't equal. remove the last two cards from the screen.\n\n\t\t\tsetTimeout(removeCards, 500);\n\t\t}\n\t} \n} //end respondtoClick", "function addingEventListner (){ \n ListOfCardNodes.forEach( function (openCard){\n openCard.addEventListener('click', function (){\n if (openCardsArray.length < 2 && openCard.classList.contains('open') == false && openCard.classList.contains('show')== false && openCard.classList.contains('match') == false){\n openCardsArray.push(openCard);\n openCard.classList.add('open', 'show'); \n if (openCardsArray.length == 2) {\n // when match, leave them open\n if (openCardsArray[0].dataset.card == openCardsArray[1].dataset.card){\n openCardsArray[0].classList.add('open', 'show', 'match');\n openCardsArray[1].classList.add('open', 'show', 'match');\n openCardsArray = [];\n numOfMatched ++; \n if (numOfMatched == 8){\n gameOver();\n }\n } else {\n //hiding cards\n openCardsArray.forEach(function (openCard) { \n setTimeout(function() {\n openCard.classList.remove('open', 'show');\n openCardsArray = []; \n }, 1000);\n }); \n } \n } \n numOfMoves++; //adding moves\n numOfMovesNode.innerText = numOfMoves;\n if (numOfMoves < 30){\n starsNode.innerHTML = addingStarsHTML + addingStarsHTML + addingStarsHTML;\n numOfStars = 3;\n }else if (numOfMoves < 50) {\n starsNode.innerHTML = addingStarsHTML + addingStarsHTML;\n numOfStars = 2;\n }else {\n starsNode.innerHTML = addingStarsHTML;\n numOfStars = 1;\n }\n\n }\n });\n\n });\n}", "function cardEventListener(event) {\n const addClasses = this.classList;\n addClasses.add(\"open\", \"show\");\n\n // setting intervals for timer\n if (isTimerSet != true) {\n clearInterval(Interval);\n Interval = setInterval(startTimer, 1000);\n isTimerSet = true;\n startTimer();\n }\n isMatch();\n}", "function cardClick() {\n if (event.target.nodeName == \"LI\") {\n // Card area is clicked\n cardClicked = event.target;\n } else if (event.target.nodeName == \"I\") {\n // card icon is clicked\n cardClicked = event.target.parentElement;\n } else {\n return; // Empty deck area clicked\n }\n if (cardClicked === openCards[0]) {\n return;\n }\n}", "function initGame() {\n //set initial timer value\n timer.innerHTML = '0 mins 0 secs';\n //set initial star rating\n for (let i = 0; i < stars.length; i++) {\n stars[i].style.color = \"#FFD700\";\n stars[i].style.visibility = \"visible\";\n }\n\n //deck selection and populating with generated card\n let deck = document.querySelector('.deck');\n let cardHTML = shuffle(cards).map(function(card) {\n return generatedCard(card);\n });\n deck.innerHTML = cardHTML.join('');\n allCards = document.querySelectorAll('.card');\n //card function\n allCards.forEach(function(card) {\n card.addEventListener('click', function(e) {\n openCards.push(card);\n card.classList.add('open', 'show', 'disabled');\n //initiating the timer function\n if (!timerActive) {\n startTimer()\n timerActive = true\n }\n // setting move counter and matched/unmatched cards based on open cards length\n if (openCards.length === 2) {\n movesCounter();\n if (openCards[0].dataset.card === openCards[1].dataset.card) {\n matched();\n allMatched();\n } else {\n unmatched();\n }\n }\n })\n });\n}", "function checkCard(){\n \n if(!this.flipped){ // check if the clicked card is not flipped yet\n\n this.classList.toggle(\"flipped\"); // flip the card\n this.flipped = true; // set the flipped state\n choices.push(this.dataset.value, this.id); // push the card ids into the array \n flips++; \n }\n\n if(flips == 2){ \n\n if(choices[0] == choices[2]){ // check if card values are equal\n pairs++; \n if(pairs == 8){alert(\"Gewonnen\");} // check if the end of the game is reached \n choices = []; // empty the card array\n flips = 0; \n tries++; \n moves.innerHTML = tries + \" Züge\"; // update the move counter\n }\n\n else{\n setTimeout(() => {\n for(let i = 1; i < choices.length; i+=2){ \n let remove = document.getElementById(choices[i]); // select flipped cards in last move \n remove.classList.toggle(\"flipped\"); // unflip cards\n remove.flipped = false; // remove flipped state\n }\n choices = []; // empty the card array\n flips = 0; \n tries++;\n moves.innerHTML = tries + \" Züge\";\n }, 700);\n }\n }\n\n }", "function turnCard(){\n\tif (this.classList.contains('open')) { //to avoid double click on the opened card...\n\t\n\t} else {\n\t\tif (animationFinished == false) { //to avoid to click on the third card before finishing matchCheck...\n\t\t} else {\n\t\t\tthis.classList.add('open', 'show');\n\t\t\tclickedCount ++;\n\t\t\tmoves.textContent = clickedCount;\n\t\t\topenedCard.push(this);\n\t\t\tif (openedCard.length === 2) {\n\t\t\t\tanimationFinished = false; \n\t\t\t\tmatchCheck(); \n\t\t\t} //once the second card was turned, call matchCheck...\n\t\t};\n\t};\n}", "function isTwoCards() {\n\n // add card to array of cards in play\n // 'this' hasn't been covered in this prework, but\n // for now, just know it gives you access to the card the user clicked on\n \n //have to fix reset on number of lives still\n \n \t\t\n\n var cardType = this.getAttribute('data-card');\n var cardId = this.getAttribute('id');\n\n\n if (lastCardClikedID==cardId){\n \talert('Naughty you clicked the same card twice');\n \tlastCardClikedID=cardId;\n }\t\n\n else {\n \n \t \tif (cardType==='king'){\n\tthis.innerHTML = '<img src=\"images/KDiamonds 12.png\" alt=\"King of Diamonds\" title =\"king\"/>';}\n\telse if (cardType==='queen')\n\t{\n\t\tthis.innerHTML = '<img src=\"images/QDiamonds 12.png\" alt=\"Queen of Diamonds\" title = \"queen\" />';\n\t}\n\n\n cardsInPlay.push(cardType);\n \n // if you have two cards in play check for a match\n\n\n\n if (cardsInPlay.length === 2) {\n\n // pass the cardsInPlay as an argument to isMatch function\n isMatch(cardsInPlay, numberOfClicks, numberOfCards);\n\n\n // clear cards in play array for next try\n cardsInPlay = [];\n \n\n\n }\n\n lastCardClikedID=cardId;\n numberOfClicks+=1;\n\n\n if(numberOfClicks>(numberOfCards*2)-1){\n \talert('Game Over');\n \tnumberOfClicks=0;\n \treStart();\n }\n\t\t\n }\n\n}", "function handleCardClick(event) {\n e = event;\n // you can use event.target to see which element was clicked\n // console.log(\"you just clicked\", event.target.className);\n // console.log(\"you just clicked\", event.target.getAttribute(DATACOLOR));\n\n // can only check covered cards & no sneaking in extra cards...\n if (event.target.getAttribute(CARDSTATE) === CARDCOVERED && cardFlips < 2){\n cardFlips++;\n totalFlips++;\n // display flips\n document.getElementById('flips').innerText = totalFlips;\n\n event.target.setAttribute(CARDSTATE, CARDFLIPPED);\n \n event.target.style.backgroundColor = event.target.getAttribute(DATACOLOR);\n // save the 1st flip\n if (cardFlips == 1){\n flippedElement = event.target;\n\n // 2nd flip, check for a match\n } else if (flippedElement.getAttribute(DATACOLOR) === event.target.getAttribute(DATACOLOR)) {\n event.target.setAttribute(CARDSTATE, CARDMATCHED);\n flippedElement.setAttribute(CARDSTATE, CARDMATCHED);\n cardFlips = 0;\n matchCnt += 2;\n console.log(\"matchCnt=\",matchCnt,\" cardCnt=\",cardCnt);\n if (matchCnt === cardCnt){\n gameWinner();\n }\n // alert(\"a match!!!!\")\n\n // if not a match reset everything flip cards back over \n } else { \n setTimeout(function(){\n event.target.style.backgroundColor = \"\";\n flippedElement.style.backgroundColor = \"\";\n cardFlips = 0;\n event.target.setAttribute(CARDSTATE, CARDCOVERED);\n flippedElement.setAttribute(CARDSTATE, CARDCOVERED);\n },1000);\n }\n }\n}", "function respondToTheClick(evt) {\n if(evt.target.className === 'card'){\n if(!timerIsOn){\n timer();\n }\n if (openCards.length < 2){\n displaySymbol(evt);\n addCardToList(evt);\n if(openCards.length >1){\n if (openCards[0].classList[1] === openCards[1].classList[1]){\n match();\n matchedCounter++;\n incrementMovesCounter();\n if (matchedCounter === 8){\n setTimeout(won, 400);\n }\n }else{\n missmatch();\n setTimeout(hide, 700);\n incrementMovesCounter();\n }\n }\n }\n }\n}", "function card_clicked() {\n if (board_clickable != true){\n return;\n }\n $(this).find('.back').hide();\n // $(this).find('.back').css({'transform' : \"perspective(600px) rotateY(180deg)\"});\n // $(this).find('.face').css({'transform' : \"perspective(600px) rotateY(0deg)\"});\n\n $(this).off('click');\n// check to find out if its the first card\n if (first_card_clicked === null) {\n first_card_clicked = this;\n console.log('first card clicked');\n //turns off first card click so you cant match same card\n var src = $(first_card_clicked).find('img').attr('src');\n cardInfo[src].onClick();\n return;\n }\n// Its the second card\n else {\n second_card_clicked = this;\n console.log('second card clicked');\n attempts++;\n display_stats();\n var first_card = $(first_card_clicked).find('img').attr('src');\n var second_card = $(second_card_clicked).find('img').attr('src');\n\n// compare the two cards\n //cards match\n if (first_card === second_card) {\n board_clickable = false;\n match_counter++;\n display_stats();\n console.log('card 1: ', first_card_clicked, 'card 2: ', second_card_clicked);\n console.log('first_card : ', first_card, 'second_card : ',second_card);\n setTimeout(function(){\n $(first_card_clicked).find('.front').hide();\n $(second_card_clicked).find('.front').hide();\n board_clickable = true;\n first_card_clicked = null;\n second_card_clicked = null;\n }, 1000);\n\n var src = $(second_card_clicked).find('img').attr('src');\n cardInfo[src].onMatch();\n\n if (match_counter == total_possible_matches) {\n mainTheme_song.volume = .7;\n mainTheme_song.play();\n $('#win').html(\"YOU WIN!!!\");\n $(\"#win\").show();\n $('#reset').show();\n pauseGameMusic();\n mainTheme_song.currentTime = 0;\n $('.music_on').show();\n }\n }\n //cards don't match\n else {\n board_clickable = false;\n resetCardsAfterNoMatch();\n }\n }\n}", "function openCard(e) {\n if (closed) {\n e.target.classList.toggle('open');\n e.target.classList.toggle('off');\n openCards.push(e.target.firstElementChild);\n let cardsInside = openCards.length;\n if (cardsInside === 2) {\n countMove();\n if (openCards[0].className === openCards[1].className) {\n matchList++;\n for (let i = 0; i < 2; i++) {\n openCards[i].parentElement.classList.add('match');\n }\n openCards = [];\n } else {\n failMatch();\n }\n }\n }\n winGame();\n}", "function makeMove(){\n\t$(\".card\").click(function(e){\n\t\tshowCardSymbol($(e.target));\n\t\taddToCardCheck($(e.target));\n\t\tif (cardCheck.length === 2) {\n\t\t\tcheckMatches();\n\t\t}\n\t\tcongratsMessage();\n\t});\n}", "function clickOnCard(evt) {\r\n let targetElement;\r\n if (evt.target.nodeName.toLowerCase() === 'li') {\r\n targetElement = evt.target;\r\n } else if (evt.target.nodeName.toLowerCase() === 'i') {\r\n targetElement = evt.target.parentNode;\r\n }\r\n if (targetElement) {\r\n let actionCard = memoryGame.playCard(targetElement.id);\r\n let secondElem;\r\n if (!memoryGame.isPlay) {\r\n targetElement.classList.add('open');\r\n targetElement.classList.add('show');\r\n }\r\n switch (actionCard[0]) {\r\n case 'activated':\r\n break;\r\n case 'matched':\r\n secondElem = document.getElementById(actionCard[1]);\r\n matchedCard(targetElement, secondElem);\r\n break;\r\n case 'deactivated':\r\n secondElem = document.getElementById(actionCard[1]);\r\n deactivatedCard(targetElement, secondElem);\r\n break;\r\n default:\r\n }\r\n updateScore();\r\n if (memoryGame.isEndGame()) {\r\n endGame();\r\n }\r\n }\r\n}", "function isCardEqual(opened){\n if (opened[0].innerHTML == opened[1].innerHTML){\n opened[0].className = 'card match';\n opened[1].className = 'card match';\n opened.length = 0; //resets 'opened' array to empty\n cardMatchCount ++; //update card match tracker\n if (cardMatchCount === 8){ //if statement used to display victory modal at end of game\n modal.style.display = 'block';\n document.querySelector('.time').innerHTML = time;\n document.querySelector('.star-count').innerHTML = starCount;\n clearInterval(gameTimer); //stop the timer once victory condition is met\n if (starCount === 1){\n document.querySelector('.singular-or-plural').innerHTML = 'star';\n }else{\n document.querySelector('.singular-or-plural').innerHTML = 'stars';\n }\n }\n if (opened.length === 0){ //if statement to add event listener back to 'click'\n container.addEventListener('click', cardOpen);\n }\n }else{ //timeout to prevent additional actions when two cards do not match\n opened[0].className = 'card nomatch';\n opened[1].className = 'card nomatch';\n setTimeout(function(){cardsNoMatch(opened)}, 1000);\n }\n}", "function flipCards(event) {\n // Check that we haven't clicked on any other nodes except the <li> or child <i>\n if (event.target.nodeName !== 'LI' && event.target.nodeName !== 'I') {\n return;\n }\n\n // Check that we have not more than 2 open unmatched cards before firing the click event\n if (openCards.length === 2) {\n return;\n }\n\n // If we clicked on <li>, check that the element is not an open or matched card\n if (event.target.className === 'card open' || event.target.className === 'card open match animated tada') {\n return;\n }\n\n // If we clicked on <i>, check that the parent element is not an open or matched card\n if (event.target.parentElement.className === 'card open' || event.target.parentElement.className === 'card open match animated tada') {\n return;\n }\n\n // Check if timer is equal to 0, then starts the game timer\n if (timer === 0) {\n timer = setInterval(startTimer, 1000);\n }\n\n var childCard = null;\n // Get the child of the card class that we clicked\n if (event.target.nodeName === 'LI') {\n // If we clicked on <li>, childCard is target children[0]\n childCard = event.target.children[0];\n } else {\n // If we clicked on <i>, childCard is just the target\n childCard = event.target;\n }\n\n // Flips the clicked card by adding the class open and then adds it to the openCards array\n childCard.parentElement.classList.add('open');\n openCards.push(childCard);\n\n if (openCards.length > 1) {\n compareCards(openCards);\n }\n}", "function openCards(){\n clickedCards.push(this);\n moves++;\n \n if(moves%2==0){\n\n document.querySelector(\".moves\").innerHTML=moves/2;\n\n document.getElementById(\"move\").innerHTML=moves/2;\n }\n if(moves===1){\n\n timing=setInterval(function(){\n document.querySelector(\".seconds\").innerHTML=seconds;\n document.querySelector(\".minutes\").innerHTML=minutes;\n \n seconds++;\n if(seconds===60){\n minutes++;\n seconds=0;}},1000);\n }\n if(clickedCards.length===2){\n\n\n if (moves > 10 && moves < 15){\n stars[2].style.visibility = \"collapse\";\n }\n else if (moves >=15 && moves < 20){\n stars[1].style.visibility = \"collapse\";\n }\n \n\n \n\n if(clickedCards[0].innerHTML===clickedCards[1].innerHTML){\n matchCount++;\n clickedCards[0].classList.toggle(\"match\");\n clickedCards[0].classList.remove(\"open\");\n clickedCards[0].classList.remove(\"show\");\n clickedCards[1].classList.toggle(\"match\");\n clickedCards[1].classList.remove(\"open\");\n clickedCards[1].classList.remove(\"show\");\n clickedCards=[];\n }\n else{\n\n clickedCards[0].classList.toggle(\"noMatch\");\n clickedCards[1].classList.toggle(\"noMatch\");\n\n setTimeout(function(){\n clickedCards[0].classList.remove(\"noMatch\");\n clickedCards[1].classList.remove(\"noMatch\");\n clickedCards[0].classList.remove(\"open\");\n clickedCards[0].classList.remove(\"show\");\n clickedCards[1].classList.remove(\"open\");\n clickedCards[1].classList.remove(\"show\");\n clickedCards[0].classList.remove(\"clicked\");\n clickedCards[1].classList.remove(\"clicked\");\n clickedCards=[];\n }, 1000);\n\n }}}", "function compare(e) {\n\n if (e.target.nodeName === \"LI\") { // If a list element is hit...\n\n cardArray.push(e.target); //Place current card into array...\n let total = cardArray.length;\n cards.removeEventListener(\"click\", tiktok, true); // Don't start timer again\n\n if (total < 2) {\n showCard(e); //show a card\n }\n\n if (total === 2) { // ...When 2 cards selected...\n\n showCard(e); //show a card again\n cards.removeEventListener(\"click\", showCard); // Show is disabled\n counter(); //Start counting moves\n\n if (cardArray[0].classList.value === cardArray[1].classList.value) { // ...compare the 2 cards...\n\n match(e);\n success +=1 ; // Increment successfull hits counter\n console.log(success);\n }\n\n else {\n setTimeout(close, 600); // if no match close them\n console.log(\"miss!!!\");\n }\n }\n\n if (success === 8) {\n console.log(\"You got it!!!\");\n openModal();\n pause();\n success = 0; // zero counter\n }\n }\n}", "function cardEvenClick(event){\n // check both opened or matched card\n let classes = $(this).attr(\"class\");\n if (classes.search('open') * classes.search('match') !== 1){\n // both should be -1\n return;\n }\n // start the game \n if (!gameStarted) {\n gameStarted = true;\n timeCount = 0;\n stopTime = setTimeout(startTimer, 1000);\n }\n // flipping to show the cards \n if (openCards.length < 2){\n $(this).toggleClass(\"open show\");\n openCards.push($(this));\n }\n // check openCards if they match or not\n if (openCards.length === 2){\n checkOpenCards();\n }\n}", "function cardOpen() {\n displayDeck.push(this);\n // this -> li.card.open.show.disabled\n // displayDeck -> array, length: 1,2\n let len = displayDeck.length;\n if(len === 2){\n counterMoves();\n if(displayDeck[0].type === displayDeck[1].type && displayDeck[0] !== displayDeck[1]){\n // type: \"bolt\"\n // type: \"leaf\"\n matched();\n } else {\n unmatched();\n }\n }\n}", "function handleCardClick(event) {\n // Make sure that you can not click too quickly and guess more than two cards at a time.\n if (noClicking) return;\n const currentCard = event.target\n const color = currentCard.classList[0];\n\n\n //as long as < 2 cards have been selected and card is not already face up, allow user to select a card\n if ((count < 2) && (!currentCard.classList.contains(\"faceUp\"))) {\n // increment guess count, mark card faceUp, assign card as guess1 or guess2\n count++;\n currentCard.classList.toggle(\"faceUp\")\n count === 1 ? guess1 = currentCard : guess2 = currentCard;\n }\n\n if (count === 2) {\n noClicking = true;\n // if the 2 cards selected match, add matched to classList and clear click event\n if (guess1.classList[0] === guess2.classList[0]) {\n console.log(\"match\")\n guess1.classList.add(\"matched\")\n guess2.classList.add(\"matched\")\n guess1.removeEventListener(\"click\", handleCardClick);\n guess1.removeEventListener(\"click\", handleCardClick);\n count = 0;\n cardsMatched += 2;\n\n setTimeout(function() {\n noClicking = false;\n }, 1000)\n\n } else {\n //otherwise, it's not a match, toggle faceUp and reset count\n console.log(\"not a match\");\n // When clicking two cards that are not a match, they should stay turned over for at least 1 second before they hide the color again. You should make sure to use a setTimeout so that you can execute code after one second.\n setTimeout(function() {\n guess1.classList.toggle(\"faceUp\")\n guess2.classList.toggle(\"faceUp\")\n noClicking = false;\n count = 0;\n faceUpCheck()\n }, 1000)\n\n // Run function to turn over any cards without class name of faceUp\n faceUpCheck()\n\n }\n };\n\n //Clicking a card should change the background color to be the color of the class it has.\n if (currentCard.classList.contains(\"faceUp\")) {\n currentCard.style.backgroundColor = color\n } else {\n currentCard.style.backgroundColor = \"white\";\n }\n\n // Let user know they have won if number of cards matched = the number of colors(or tiles)\nif (cardsMatched === COLORS.length) {\n alert(\"You've won!\")\n}\n\n}", "function check(secondCard, firstCard){\n\tif(secondCard.innerHTML === firstCard.innerHTML){\n\n\t\t//Cards match\n\t\tsecondCard.classList.add(\"match\");\n\t\tfirstCard.classList.add(\"match\");\n\t\tmatchedCards.push(secondCard,firstCard);\n\t\topenedCards = [];\n\n\t\t//If the game is over run the popup\n\t\tgameOver();\n\n\t} else {\n\t\t//Wait for 500 miliseconds before closing the cards\n\t\tsetTimeout(function(){\n\t\tsecondCard.classList.remove(\"open\", \"show\", \"disable\");\n\t\tfirstCard.classList.remove(\"open\", \"show\", \"disable\");\n\t\topenedCards = [];\n\t\t}, 500);\n\t}\t\n\t\n//Count moves\ncountMoves();\n\n//Run the rating function\nrating();\n}", "async function clickHandler(event) {\n const currentCard = getCard(event);\n if (!currentCard || currentCard.isFlipped()) return;\n\n if (!timer.isRunning()) {\n timer.start();\n }\n\n let allCardsMatched = false;\n\n clickedCards.push(currentCard);\n\n if (clickedCards.length == 2) {\n numberOfMoves++;\n updateScore();\n const previousCard = clickedCards[0];\n clickedCards = [];\n if (currentCard.id() === previousCard.id()) {\n numberOfMatched++;\n if (numberOfMatched === NUMBER_OF_CARDS) {\n timer.stop();\n allCardsMatched = true;\n }\n await currentCard.show();\n await Promise.all([\n currentCard.markAs('matched'),\n previousCard.markAs('matched')\n ]);\n if (allCardsMatched) {\n updateWinMessage(numberOfMoves);\n showModal('win');\n }\n } else {\n await currentCard.show();\n await Promise.all([\n currentCard.markAs('not-matched'),\n previousCard.markAs('not-matched')\n ]);\n currentCard.hide();\n previousCard.hide();\n }\n } else {\n currentCard.show();\n }\n }", "function openCard() {\n openedCards.push(this);\n\n const modal = document.querySelector('.overlay');\n\n if (openedCards.length == 2) {\n // Compare the 2 cards\n testMatching();\n movesCounter();\n }\n if (matchedCards.length === 16) {\n\n modal.classList.toggle('show');\n\n stopTimer();\n messageScore();\n\n }\n}", "function cardMatch(listOfCards) {\n $(\".open\").removeClass(\"noDuplicate\");\n let cardOne = $(listOfCards[0]).html();\n let cardTwo = $(listOfCards[1]).html();\n if (cardOne === cardTwo) {\n $(\".open\").addClass(\"match\");\n cardMatchCounter ++;\n gameFinishCheck(cardMatchCounter);\n } else {\n /** counts how many failed attempts have been made to match cards */\n numberOfMisses ++;\n moveCounter(numberOfMisses);\n /** if the cards do not match, remove the cards from the list and hide\n * the card's symbol (put this functionality in another function\n * that you call from this one) */\n allFaceDown();\n }\n}", "function openCard() {\n if (clockStatus == 0) {\n beginTimer();\n clockStatus = clockStatus + 1;\n }\n\n this.classList.add(\"card\");\n this.classList.add(\"open\");\n this.classList.add(\"show\");\n this.classList.add(\"disable\");\n cardMemory.push(this);\n if (cardMemory.length == 2) {\n moves = moves + 1;\n moveSection.innerHTML = moves;\n rating();\n if (cardMemory[0].children[0].classList.item(1) == cardMemory[1].children[0].classList.item(1)) {\n console.log(\"matched\");\n cardMemory[0].classList.add(\"match\", \"disable\");\n cardMemory[1].classList.add(\"match\", \"disable\");\n // all cards are matched the automatically stop the time here\n if (colliedCards.length == 16) {\n clearInterval(clock);\n Swal.fire({\n title: \"Completed\",\n html: 'you won two stars <strong style=\"color:#ff9f33; test-shadow:3px 3px 3px #000\">' + starNoof + '<i class=\"fa fa-star\"></i> </strong><br>you completed this game with the time of <br>' + sec + 'Seconds' + min + 'minutes' + hour + 'hour:',\n confirmButtonText: '<i class=\"fa fa-thumbs-up\"></i> PlayAgain',\n }).then(() => {\n document.location.reload();\n });\n }\n cardMemory = [];\n } else {\n console.log(\"notMatchd\");\n cardMemory[0].classList.add(\"unmatch\");\n cardMemory[1].classList.add(\"unmatch\");\n cardMemory.map((son) => {\n setTimeout(() => {\n son.classList.remove(\"unmatch\", \"open\", \"show\", \"disable\");\n }, 200)\n\n cardMemory = [];\n })\n }\n }\n}", "function flip(card) {\n\n // Cards click event\n card.addEventListener(\"click\", function() {\n\n // Prevent actions while flipping cards timeout active\n if (!cardTimeout) {\n // Check if this is the first card flipped\n if (gameStatus === false) {\n // Change game status\n gameStatus = true; \n \n // Start timer\n startTime = new Date().getTime();\n window.setTimeout(calculateTime, 1000);\n }\n\n // Define local variables\n let currentCard = this;\n let previousCard = openedCards[0];\n \n // Check if there is an existing opened card\n if (openedCards.length === 1) {\n\n currentCard.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n \n // Compare cards\n compareCards(currentCard, previousCard);\n \n } else {\n // If there is no opened card, add the current card to the opened cards array\n currentCard.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n }\n }\n });\n}", "function handleCardClick(event) {\n if ($(event.currentTarget).hasClass(\"isFlipped\") || twoCardsClicked) {\n return; // if a card is already flipped or there are two cards already clicked then clicks will be temporarily disabled\n }\n if (firstCardClicked === null) {\n firstCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n firstCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the first clicked card\n } else {\n secondCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n secondCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the second clicked card\n twoCardsClicked = true;\n if (firstCardClickedImageURL !== secondCardClickedImageURL) { // actions to take if the two clicked cards don't match\n misMatchedCardsAction();\n } else { // actions to take if the two clicked cards match\n matchedCardsAction();\n }\n }\n displayStats(); // calculate and show stats\n}", "function open() {\n cardSelected = $(event.target);\n cardSelected = cardSelected[0];\n cardSelected.setAttribute('class', 'card open show');\n openCards(cardSelected);\n startTimer();\n cardsEventListener();\n\n if (cardOpen.length === 2) {\n // delete all cardListener\n $('li').off();\n if (cardOpen[0].childNodes[1].className === cardOpen[1].childNodes[1].className) {\n lockCards();\n gameWon();\n } else {\n cardOpen[0].setAttribute('class', 'card open show wrong');\n cardOpen[1].setAttribute('class', 'card open show wrong');\n\n //the timeout function is needed to see the wrong cards for a short time\n setTimeout(function() {\n removeCards();\n }, 300);\n }\n }\n}", "function initGame() {\n startTimer();\n $(\".card\").on(\"click\", function (evt){\n /** asks if there is already one upturned card\n * display the card's symbol\n * (put this functionality in another function that you call from this one) */\n const hasClassShow = ($(listOfCards).hasClass(\"show\"));\n const hasTwoCardsOrMore = (listOfCards.length >= 2);\n const stopTurn = console.log('cards stop turning on click');\n hasClassShow ? (hasTwoCardsOrMore ? stopTurn : (showCard(this), cardMatch(listOfCards))): showCard(this);\n });\n}", "function Clicked(e){ // first I need to make sure that the user can't open > 2 cards in the same time\n if(OpCards.length<2){ // OpCards less than 2 then open it\n let pikedcard = e.target;\n if(pikedcard.classList.contains(\"card\")&& !pikedcard.classList.contains(\"open\",\"show\" , \"match\", \"notmatch\")){\n pikedcard.classList.add(\"open\" , \"show\");\n OpCards.push(pikedcard); //add it in OpCards array\n }\n \n if(OpCards.length == 2){ // to know if we have 2 cards in the array\n setTimeout(matchedCards, 1000);\n }}}", "function startGame() {\n /* shuffle the array listCards */\n let fullDeck = shuffle(listCards);\n /*empty array of open cards when clicked*/\n let openCards = [];\n /*variable for shuffled cards, declared later*/\n let newCards = '';\n /*initial value of matched cards*/\n matchedCards = 0;\n moves.textContent = 0;\n addMove = moves.textContent;\n /*adds yellow stars at beggining*/\n for (var i= 0; i < stars.length; i++){\n stars[i].style.color = \"#FFD700\";\n stars[i].style.visibility = \"visible\";\n }\n //reset the timer\n second = 0;\n minute = 0;\n hour = 0;\n let timer = document.querySelector(\".timer\");\n timer.innerHTML = \"0 min 0 sec\"; /*adds counter at beggining*/\n clearInterval(interval); /*stops the time per https://www.w3schools.com/jsref/met_win_clearinterval.asp*/\n deck.innerHTML = '';\n /*loop through the listcards*/\n for (let i = 0; i < fullDeck.length; i++) {\n /*append new li class*/\n newCards += '<li class=\"card\"><i class=\"' + fullDeck[i] + '\"></i></li>';\n deck.innerHTML = newCards;\n }\n /*adds cardListener at start to the DOM*/\n cardsListener();\n}", "function listener(e) {\n let card = e.target;\n moves++;\n //when moves = 1 -> start stopwatch\n if (moves === 1) {\n second++;\n stopWatch();\n }\n card.className = 'card open show disabled';\n //checking pairs of cards\n checkCardPairsArray(card);\n}" ]
[ "0.83509505", "0.8140722", "0.80919325", "0.80569696", "0.8001356", "0.79951125", "0.7924273", "0.7889374", "0.78789896", "0.7862501", "0.78373975", "0.77550113", "0.7748669", "0.7738757", "0.7725312", "0.7721494", "0.7714245", "0.7690667", "0.7676613", "0.7667446", "0.76514745", "0.7647446", "0.7639378", "0.7626563", "0.76172656", "0.76162577", "0.7592697", "0.75846434", "0.75840807", "0.7547648", "0.75262433", "0.7505937", "0.7505722", "0.75024223", "0.74976003", "0.749091", "0.748759", "0.7471737", "0.7467844", "0.74660414", "0.74629223", "0.74624646", "0.74539405", "0.74195373", "0.74161136", "0.7408265", "0.7400668", "0.73958355", "0.73933184", "0.7389419", "0.7379956", "0.7378879", "0.7374619", "0.7372394", "0.73598063", "0.73374534", "0.7333182", "0.73278695", "0.73219305", "0.7309273", "0.7303983", "0.7302473", "0.72950166", "0.7279805", "0.72781366", "0.72713447", "0.7260269", "0.72546667", "0.72466385", "0.7243812", "0.72427183", "0.7241033", "0.72369844", "0.7236328", "0.7235001", "0.72345597", "0.72262084", "0.7225876", "0.72206604", "0.72171724", "0.7214787", "0.7214512", "0.72123086", "0.7208306", "0.7203225", "0.71997195", "0.71951425", "0.71749043", "0.71714926", "0.71700066", "0.7166454", "0.7164761", "0.7158586", "0.71564883", "0.7154091", "0.714985", "0.71463346", "0.7143055", "0.7142764", "0.714268", "0.71391714" ]
0.0
-1
event handler for clicked card
function clickedCard() { $('li.card').on('click', function() { let openCard = $(this); toggleOpenShow(openCard); if(openCard.hasClass('open show disabled') && allOpenedCards.length < 2) { allOpenedCards.push(openCard); } matchedCard(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function cardClicked(e) {\n\n const clickedCard = e.target;\n if (clickedCard.classList.contains('card') && !clickedCard.classList.contains('show')) {\n clickedCard.classList.add('show');\n addToOpenCards(clickedCard);\n }\n }", "function apply_card_event_handlers(){\n $('.card').click(card_selected($(this)));\n }", "function cardClick() {\n\n}", "function cardClick() {\n if (event.target.nodeName == \"LI\") {\n // Card area is clicked\n cardClicked = event.target;\n } else if (event.target.nodeName == \"I\") {\n // card icon is clicked\n cardClicked = event.target.parentElement;\n } else {\n return; // Empty deck area clicked\n }\n if (cardClicked === openCards[0]) {\n return;\n }\n}", "function cardClicked(event) {\n if (event.target.className === 'card' && clickedCards.length <2) {\n event.target.classList.add('open', 'show');\n addCardsToClickedCards(event);\n doCardsMatch(event);\n }\n}", "function cardClick() {\n\tif (clickedCards.length === 2 || matchedCards.includes(this.id)) {\n\t\treturn;\n\t}\n\tif(clickedCards.length === 0 || this.id != clickedCards[0].id){\n\n\t\tif(timeTrigger){\n\t\t\ttimerStart();\n\t\t\ttimeTrigger = false;\n\t\t}\n\t\tthis.classList.add('show', 'open');\n\t\tclickedCards.push(event.target);\n\t\tdetermineAction();\n\t}\n\telse {\n\t\treturn;\n\t}\n\tsetRating(moves);\n}", "function clickOnCard(evt) {\r\n let targetElement;\r\n if (evt.target.nodeName.toLowerCase() === 'li') {\r\n targetElement = evt.target;\r\n } else if (evt.target.nodeName.toLowerCase() === 'i') {\r\n targetElement = evt.target.parentNode;\r\n }\r\n if (targetElement) {\r\n let actionCard = memoryGame.playCard(targetElement.id);\r\n let secondElem;\r\n if (!memoryGame.isPlay) {\r\n targetElement.classList.add('open');\r\n targetElement.classList.add('show');\r\n }\r\n switch (actionCard[0]) {\r\n case 'activated':\r\n break;\r\n case 'matched':\r\n secondElem = document.getElementById(actionCard[1]);\r\n matchedCard(targetElement, secondElem);\r\n break;\r\n case 'deactivated':\r\n secondElem = document.getElementById(actionCard[1]);\r\n deactivatedCard(targetElement, secondElem);\r\n break;\r\n default:\r\n }\r\n updateScore();\r\n if (memoryGame.isEndGame()) {\r\n endGame();\r\n }\r\n }\r\n}", "function cardClickHandler(e) {\n console.log('card clicked')\n const cardIsNotAlreadyChosen = e.target.parentNode != cardOneElement;\n if (!gameWon && e.target.classList.contains('card-face') && cardIsNotAlreadyChosen) {\n checkStats(e.target.parentNode);\n flipUp(e.target.parentNode);\n }\n}", "function selectCard(event) {\n let recipeCard = event.target.closest(\".recipe-card\")\n if (event.target.className === \"card-apple-icon\") {\n let cardId = parseInt(event.target.closest(\".recipe-card\").id)\n domUpdates.changeHeartImageSrc(cardId, user, event)\n } else if (event.target.className === \"card-mixer-icon\") {\n let cardId = parseInt(event.target.closest(\".recipe-card\").id)\n domUpdates.changeMixerImageSrc(cardId, user, event)\n } else if (event.target.id === \"exit-recipe-btn\") {\n exitRecipe(event);\n } else if (isDescendant(recipeCard, event.target)) {\n let recipeId = $(recipeCard).attr('id')\n openRecipeInfo(recipeId);\n }\n}", "handleClickEventOnCard(event) {\n if (!this.scoringHandler.isTimerStarted()) {\n this.scoringHandler.startTimer();\n }\n if (this.isNodeOfTypeLI(event) && this.isCardNotYetOpenOrMatched(event)) {\n this.openCard(event.target);\n }\n if (this.openCards.length === 2) {\n this.scoringHandler.increaseMovesByOne();\n if (this.openCardsDoMatch()) {\n this.markOpenCardsAsMatch();\n } else {\n this.coverOpenCards();\n }\n }\n }", "function clickedCard(event){\n if(event.target && event.target.nodeName == \"LI\") {\n event.target.addEventListener(\"click\", clickedCard);\n // Turning the cards is just changing the background color to reveal the hidden text\n event.target.style.backgroundColor= \"#00d37e\";\n const cardClass = event.target.className;\n const cardId = event.target.id;\n\n /* If no other card in cardId has the same id as the event.target,\n we add event.target's id to the array.\n Also, if a card has a match, we take from it the possibility of being played again. */\n if (cardsId.includes(cardId) || event.target.classList.length === 3){\n true;\n } else {\n // Add the click to the moves counter\n addMoves();\n // Check for potential matches\n cardsTurned.push(cardClass);\n cardsId.push(cardId);\n checkingTurned();\n }\n }\n}", "function onCardClick(_event) {\n // starten den Timer für die Zeitmessung\n if (setTheStartTime) {\n // Date() = Datums Klasse, man kann Anfragen bspw. zum loken Tag/Woche/Monat und Jahr || .getTime() = gibt die momentane Zeit in Millisek. aus\n startTime = new Date().getTime(); // https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute\n // muss gesetzt werden damit, diese if-Abfrage nicht nochmal ausgeführt wird --> wird nur bei der ersten Karte ausgeführt, die angegeklickt wird\n setTheStartTime = false;\n }\n // selectedCards = ein array in dem die ausgewählten Karten sind (am Anfang leeres array)\n if (selectedCards.length < 2) {\n // target = HTML Element was angeklickt wurde || target ist hier immer ein Bild, da diese Funktion nur HTMLImageElemente hinzugefügt wurde\n let cardImage = _event.target;\n // id der Karte ist die Position im cardPool array, der angeklickten Karte\n let cardPoolIndex = Number(cardImage.id);\n // url der angeklickten Karte wird in selectedCardUrl gespeichert\n let selectedCardUrl = cardPool[cardPoolIndex];\n // die url und das HTML Element wird in das Interface gegeben, damit dieses in das selectedCards array gespeichert wird\n let card = { url: selectedCardUrl, element: cardImage };\n // sagt ob das selectedCards array die angeklickte Karte bereits enthält || Anfangs wird ausgegangen, dass die geklickte Karte noch nicht in selectedCards[] drin ist\n let hasArraySelectedCard = false;\n // Falls selectedCards array leer ist, kann die angeklickte Karte direkt dem selectedCards array hinzugefügt werden\n if (selectedCards.length == 1) {\n let arrayZeroPos = Number(selectedCards[0].element.id);\n // wenn weimal die selbe Karte angeklickt wurde\n if (arrayZeroPos == cardPoolIndex) {\n // geklickte Karte wird auf true gesetzt, damit man weiß, dass die Karte im selectedCards[] enthalten ist\n hasArraySelectedCard = true;\n }\n }\n // wenn die Karte noch nicht vorhanden ist wird sie in selectedCards[] hinzugefügt (push())\n if (!hasArraySelectedCard) {\n selectedCards.push(card);\n }\n // cardPool[cardPoolIndex] = url der angeklickten Karte im cardPool[] --> wird angezeigt || .src = aus HTML (<img src=...)\n cardImage.src = cardPool[cardPoolIndex];\n // setTimeout() = wird gemacht damit beide Karten angezeigt bevor sie wieder umgedreht werden\n setTimeout(validateSelectedCards, 2000); // https://www.w3schools.com/jsref/met_win_settimeout.asp\n }\n }", "function cardClick(){\n\tthis.classList.add('show', 'open');\n\tclickedCards.push(event.target);\n\tif(clickedCards.length === 2){\n\t\tmoves++;\n\t\tif(moves === 1){\n\t\t\ttimerStart();\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Move</span>`;\n\t\t} else if(moves >= 2 && moves <= 20) {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Moves</span>`;\n\t\t} else if(moves >= 21 && moves <= 29){\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves gold\">${moves} Moves</span>`;\n\t\t} else {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves red\">${moves} Moves</span>`;\n\t\t}\n\t\tif(clickedCards[0].innerHTML === clickedCards[1].innerHTML){\n\t\t\tmatching();\n\t\t\twinCheck();\n\t\t} else {\n\t\t\tnotMatching();\n\t\t}\n\t}\n\tcheckRating(moves);\n}", "function clickOnCard(e) {\n // if the target isn't a card, stop the function\n if (!e.target.classList.contains('card')) return;\n // if the user click the first time on a card (-->that is flip the first card) the timer starts\n if(isFirstCardclicked) {\n startTimer();\n isFirstCardclicked=false;\n }\n if (openCards.length<2) {\n let cardClicked = e.target;\n console.log(\"clicked \"+e.target.querySelector('i').classList);\n // show the card\n showSymbol(cardClicked);\n // save the card clicked\n addOpenCard(cardClicked);\n }\n if (openCards.length == 2) {\n // to stop from further clicking on cards until animation is finished\n deck.removeEventListener('click', clickOnCard);\n checkMatch(openCards[0], openCards[1]);\n updateMovesCounter();\n updateRating();\n }\n}", "function displayCard(e){\n e.target.setAttribute(\"class\",\"card open show\");\n addToOpenCards(e.target);\n}", "function handleCardClick(event) {\n if ($(event.currentTarget).hasClass(\"isFlipped\") || twoCardsClicked) {\n return; // if a card is already flipped or there are two cards already clicked then clicks will be temporarily disabled\n }\n if (firstCardClicked === null) {\n firstCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n firstCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the first clicked card\n } else {\n secondCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n secondCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the second clicked card\n twoCardsClicked = true;\n if (firstCardClickedImageURL !== secondCardClickedImageURL) { // actions to take if the two clicked cards don't match\n misMatchedCardsAction();\n } else { // actions to take if the two clicked cards match\n matchedCardsAction();\n }\n }\n displayStats(); // calculate and show stats\n}", "function clickOn() {\n openedCards[0].click(cardToggle);\n}", "function cardClick() {\n $('button').on('click', function() {\n \n });\n}", "handleOnCardClicked(event) {\n const card = event.target;\n // skip and return if event target is not li or \n // if it is already open\n // if it is already matched\n if (card.nodeName.toLowerCase() !== 'li' ||\n this.mModel.mOpenCards.includes(card) ||\n this.mModel.mMatchedCards.includes(card)) {\n console.log('skipped click handling')\n return;\n }\n\n // add move, and then check resulting moves\n this.checkStars(this.mModel.addMove());\n\n // add card to the list of open cards\n this.mModel.addCardToOpenCards(card);\n }", "function turnClickHandlerOn() {\n $('.cards').on('click', handleClickCard);\n}", "static async onClick(event) {\n // filtering clicked html\n let currentCard = Board.instance.getSelectedCard(event.target);\n if (!currentCard)\n return;\n\n // ignoring some click events if matches some constraints \n if (!currentCard ||\n currentCard.isVisible() ||\n currentCard.isMatched() ||\n Board.instance.waitingAnimationFinish) {\n return;\n }\n\n // changing card state\n currentCard.toggle();\n Board.instance.selectedCards.push(currentCard);\n\n // updating moves\n Board.instance.movesCount++;\n document.querySelector('#moves').textContent = Board.instance.movesCount.toString();\n \n // removing stars from board(if any to remove)\n Board.instance.removeStars();\n\n // only one card was selected, nothing to handle \n if (Board.instance.selectedCards.length === 1)\n return;\n \n // checking if card pair is equal\n const previousCard = Board.instance.cardMap[Board.instance.selectedCards[0].getUid()];\n if (currentCard.getUid() == previousCard.getFkUid()) {\n // cards are equal!!! :D\n // checking if game finished\n await Board.instance.handleEqualCards(currentCard, previousCard);\n }\n else {\n // cards are different :(\n // animating different cards\n await Board.instance.handleDifferentCards(currentCard, previousCard);\n }\n\n // clear selectedCards\n Board.instance.selectedCards.splice(0, Board.instance.selectedCards.length);\n return;\n }", "function cardListener (data) {\n const cards = document.querySelectorAll('.card');\n for (let i = 0; i < cards.length; i += 1) {\n cards[i].addEventListener('click', (e) => displayModal(data, i))\n }\n}", "function mouseEvent(ev) {\n\t\tvar card = $(this).data('card');\n\t\tif (card.container) {\n\t\t\tvar handler = card.container._click;\n\t\t\tif (handler) {\n\t\t\t\thandler.func.call(handler.context||window, card, ev);\n\t\t\t}\n\t\t}\n\t}", "function clickEvent() {\n cards.forEach(card => {\n card.addEventListener('click', playFunc);\n })\n }", "function handleCardClick(e) {\n props.logClick(e, 3);\n }", "function cardClick() {\n cards = document.querySelectorAll('.card');\n for (let i = 0; i < cards.length; i++) {\n cards[i].addEventListener('click', () => createModal(people[i]));\n }\n}", "function cardClicked(event) {\n openCardsList.push(this);\n this.classList.add('open', 'show', 'disable');\n if (openCardsList.length === 2 && openCardsList[0].innerHTML === openCardsList[1].innerHTML) {\n match();\n addMoves();\n }\n if (openCardsList.length === 2 && openCardsList[0].innerHTML != openCardsList[1].innerHTML) {\n noMatch();\n addMoves();\n }\n if (!watch.isOn) {\n watch.start();\n }\n}", "function respondtoClick(event) {\n if (event.target.classList.contains('card') &&\n !event.target.classList.contains('match') &&\n !event.target.classList.contains('open') &&\n !event.target.classList.contains('show')) {\n showCard(event.target);\n moveCounter();\n starRating();\n cardMatchCheck(event.target);\n timeKeeper();\n }\n}", "function manipulateCard(event) {\n\t// Check if there is any card already clicked\n\tif (firstClickedElement === null){\n\n\t\t// No card clicked yet => store its value (class) into firstCard variable\n\t\tfirstCard = event.target.lastElementChild.getAttribute('class');\n\n\t\t// Show the card\n\t\tshowCard(event);\n\n\t\t// Get the element of the first clicked card\n\t\tfirstClickedElement = document.querySelector('.clicked');\n\n\t} else if (firstCard === event.target.lastElementChild.getAttribute('class')) {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Since 2nd card matches the first one => change cards status to \"card match\" (both cards remain with their face up) -> with a short delay\n\t\tchangeCardsStatus(event, 'card match');\n\n\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\tother2Cards();\n\t\t\n\t\t// Increase number of matched cards\n\t\tcellNo = cellNo + 2;\n\n\t} else {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Set the 2 clicked cards attributes to wrong class -> with a short delay\n\t\tchangeCardsStatus(event, 'card open show wrong');\n\n\t\t// Set the 2 clicked cards attributes to its defaults -> with a short delay\n\t\tsetTimeout(function(){\n\t\t\tchangeCardsStatus(event, 'card');\n\n\t\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\t\tother2Cards();\n\t\t}, 300);\n\t}\n}", "function onCardClick(card, i) {\n // set the current card\n currentCard = card;\n // add the 'clicked' class to the card, so it animates out\n currentCard.className += ' clicked';\n // animate the card 'cover' after a 500ms delay\n setTimeout(function() {animateCoverUp(currentCard)}, 500);\n // animate out the other cards\n animateOtherCards(currentCard, true);\n // add the open class to the page content\n openContent.className += ' open';\n}", "function onCardClicked() {\n //get the card that was clicked\n let selectedId = $(this).attr('id').replace('card-','');\n let selectedCard = cards[selectedId];\n\n if (selectedCard.isDisplayed() || openCards.length >= 2) {\n return;\n } else {\n //increment click counter\n moveCount++;\n $('.moves').text(moveCount);\n\n //check move count and decrement stars if needed.\n if (moveCount == 20) {\n $('#star-3').removeClass('fa-star');\n $('#star-3').addClass('fa-star-o');\n } else if (moveCount == 30) {\n $('#star-2').removeClass('fa-star');\n $('#star-2').addClass('fa-star-o');\n }\n\n //display the card.\n selectedCard.flip();\n\n //after short delay, check if there is a match.\n //this is done so that the cards do not immediately flip back\n //preventing you from seeing the 2nd card.\n setTimeout(function() {\n if (!findCardMatch(selectedCard)) {\n //add selected card to list of open cards\n openCards.push(selectedCard);\n\n if (openCards.length == 2) {\n //hide both cards\n openCards[0].flip();\n openCards[1].flip();\n openCards = [];\n }\n }\n }, 800);\n }\n}", "function newCardClick(event) {\n var dataSetId = event.target.dataset.id;\n\n // verify, that game is still running\n if (!gameCompleted) {\n // verify, that user clicked on img and that there is a id to identify the card index\n if (event.target.nodeName.toLowerCase() == \"img\" && dataSetId) {\n //if clicked card is not the same as the precedent and the card is not the dummy card ...\n if (dataSetId != oldId && cardArr[dataSetId].isClickable == true) {\n checkRating();\n checkCardClickChoice(dataSetId, event);\n }\n }\n }\n }", "function clickCard(event) {\n\n\tif (interval === null) {\n\t\tsetTime();\n\t}\n\n\t//Check there's not more than 2 cards clicked\n\tif (counter < 2) {\n\t\tvar element = event.target;\n\n\t\t//Show the card\n\t\telement.style.backgroundImage = cards[ids.indexOf(element.id)];\n\n\t\t//Check it's not the same card clicked twice\n\t\tif (previousCard !== element.id) {\n\t\t\t//Count a click\n\t\t\tcounter++;\n\n\t\t\t//Check if it's the 2nd card\n\t\t\tif (previousCard !== null) {\n\t\t\t\tcurrentCard = element.id;\n\n\t\t\t\t//Restart images\n\t\t\t\tvar currentPicture = document.getElementById(currentCard).style.backgroundImage;\n\t\t\t\tvar previousPicture = document.getElementById(previousCard).style.backgroundImage;\n\n\t\t\t\t//Check if both images are the same\n\t\t\t\tif (currentPicture === previousPicture) {\n\t\t\t\t\t//Initialices a temporizer to execute correct action\n\t\t\t\t\tsetTimeout(removeCards, 1000);\n\t\t\t\t\n\n\t\t\t\t//If they're different \n\t\t\t\t} else {\n\t\t\t\t\t//Substract the score\n\t\t\t\t\tscore += -5;\n\t\t\t\t\tshowScore();\n\t\t\t\t\t//Initialices a temporizer to execute wrong action\n\t\t\t\t\tsetTimeout(hideCards, 1000);\n\t\t\t\t}\n\t\t\t\n\t\t\t} else {\n\t\t\t\t//If it's the first, store the card for the next click\n\t\t\t\tpreviousCard = element.id;\n\t\t\t}\n\t\t}\n\t}\n}", "function evtListener() {\n debug(\"evtListener\");\n cards().forEach(function(node) {\n node.addEventListener('click', cardMagic);\n })\n }", "function handleCardClick(evt) {\n if (!gameLock){\n let currentCard = this;\n currentCard.classList.add(\"flipped\");\n currentCard.style.backgroundColor = currentCard.getAttribute(\"data-color\");\n flipCard(currentCard);\n }\n}", "function clickCard() {\n $(\".card\").click(function() {\n // Return the function if the card is open\n if ($(this).hasClass(\"open show\")) {\n return;\n }\n // Return if there are 2 opened cards\n if (openCards.length === 2) {\n return;\n }\n // Display the card symbol and add the card to openCards list\n $(this).addClass(\"open show\");\n openCards.push($(this));\n // Start runner if this is the first move\n if (moves === 0) {\n startRunner();\n }\n // Check if the cards match\n if (openCards.length === 2) {\n if (openCards[0][0].firstChild.className === openCards[1][0].firstChild.className) {\n setTimeout(addMatch,300);\n } else {\n setTimeout(removeClasses,1300);\n }\n // Increase moves after checking\n incrementMoves();\n }\n });\n }", "bindCardChoice(handler) {\n this.cardLinks = document.querySelectorAll('.pict1');\n this.cardLinks.forEach(element =>element.addEventListener('click', MemoryEvent => {\n handler(element.id-1);\n }));\n }", "function cardChanger(e) {\n\tdocument.getElementsByClassName('active-card')[0].classList.remove('active-card');\n\tdocument.getElementById(e.target.dataset.target).classList.add('active-card');\n}", "function clickCard(){\n //* define clickedCard as the element that received a click\n var clickedCard = $(this);\n // * call the function that will check for a match\n checkForMatch(clickedCard);\n}", "function onCardClick(event) {\n console.info(event);\n\n var message = \"\";\n var reason = event.action.parameters[0].value;\n\n if (event.action.actionMethodName == \"turnOnAutoResponder\") {\n turnOnAutoResponder(reason);\n message = \"Turned on vacation settings.\";\n } else if (event.action.actionMethodName == \"blockOutCalendar\") {\n blockOutCalendar(reason);\n message = \"Blocked out your calendar for the day.\";\n } else {\n message = \"I'm sorry; I'm not sure which button you clicked.\";\n }\n\n return { \"text\": message };\n}", "function clickCard() {\n deck.addEventListener('click', function(event) {\n if (event.target.classList.contains('card')) {\n cardClicks++;\n if (cardClicks === 1 || cardClicks === 2) {\n clickedCard();\n } else {\n resetTurn();\n }\n }\n })\n}", "function click (card) {\n card.addEventListener(\"click\", function() {\n if(initialClick) {\n clock();\n initialClick = false;\n }\n\n const currentCard = this;\n const previousCard = openCards[0];\n\n //open cards and compare them\n if(openCards.length === 1) {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n // card comparison conditional\n comparison(currentCard, previousCard);\n increaseMove();\n } else {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n\n }\n });\n}", "function handleClickCard(event) {\n $(event.currentTarget).find('.backOfCard').addClass('hidden');\n console.log(event.currentTarget);\n if (firstCardClicked === null) {\n firstCardClicked = $(event.currentTarget);\n } else {\n secondCardClicked = $(event.currentTarget);\n attempts++;\n var firstPick = firstCardClicked.find('.revealCard').css('background-image');\n var secondPick = secondCardClicked.find('.revealCard').css('background-image');\n turnClickHandlerOff();\n if (firstPick === secondPick) {\n console.log('The cards match!');\n matches++;\n firstCardClicked = null;\n secondCardClicked = null;\n turnClickHandlerOn();\n } else {\n setTimeout(function () {\n firstCardClicked.find('.backOfCard').removeClass('hidden');\n firstCardClicked = null;\n secondCardClicked.find('.backOfCard').removeClass('hidden');\n secondCardClicked = null;\n turnClickHandlerOn();\n }, 500);\n }\n displayStats();\n }\n}", "function showCard(clickedCard) {\n $(clickedCard).addClass('open show');\n}", "function dispalyCard(e) {\n const newCard = this;\n newCard.classList.toggle('open');\n\n if(previousCard != null) {\n setTimeout(function() { compareCards(newCard); }, 1000);\n }\n else {\n previousCard = newCard;\n newCard.removeEventListener('click', dispalyCard);\n }\n}", "function card_selected(card){\n $('.card').click(function(){\n $(this).toggleClass('selected');\n });\n }", "function addClickListeners() {\n var cardContainer = document.getElementById(\"card-container\");\n cardContainer.addEventListener('click', function(event) {\n var clickedId = event.target.id;\n // if name, display name\n if (clickedId == \"name-overlay\")\n displayNameFromCard(currentCard);\n // if mana cost, display mana_cost\n if (clickedId == \"mana-overlay\")\n displayManaFromCard(currentCard);\n // if creature type, display creature type\n if (clickedId == \"type-overlay\")\n displayTypeFromCard(currentCard);\n // if set symbol, display set symbol\n if (clickedId == \"set-symbol-overlay\")\n displaySetFromCard(currentCard);\n // if text box, display text box\n if (clickedId == \"text-box-overlay\")\n displayAbilitiesFromCard(currentCard);\n // if power/toughness, display power/toughness\n if (clickedId == \"power-toughness-overlay\")\n displayPTFromCard(currentCard);\n // if artist, display artist\n if (clickedId == \"artist-overlay\")\n displayArtistFromCard(currentCard);\n // if art is clicked, display artist\n if (clickedId == \"art-overlay\")\n displayArtistFromCard(currentCard);\n document.getElementById(\"card-exp\").scrollIntoView({block: \"end\", behaviour: \"smooth\"});\n });\n}", "function showCard(event){\n\tevent.target.setAttribute('class', 'card open show clicked');\n}", "function whenClicked(card){ \r\n \r\n card.addEventListener(\"click\", function(){\r\n \r\n \r\n if (openedCards.length===1){\r\n \r\n \r\n const currentCard=this;\r\n const previousCard=openedCards[0];\r\n\r\n \r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n\r\n compare(currentCard,previousCard);\r\n\r\n \r\n }else{\r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n }\r\n }\r\n\r\n );\r\n\r\n}", "function getCards() {\n const whichCard = document.querySelectorAll('.card');\n for (let i = 0; i < whichCard.length; i++){\n whichCard[i].addEventListener('click', function(e) {\n updateCards(e.target);\n })\n }\n}", "function clickCards() {\n\t$('.card').click(function() {\n\t\tdisplayCard(this);\n\t\taddCard(this);\n\t\tdoesCardMatch(openCards);\n\t\topenCards[0].addClass('open');\n\t\tif (openCards.length === 2) {\n\t\t\topenCards[0].removeClass('open');\n\t\t}\n\t});\n}", "function handleClick(d){\r\n fetchRecipeCard(d);\r\n }", "_cardSelectHandler(row, col) {\n\t\t\n\t\tconst card= this._grid[row][col];\n\n\t\t// If this is a fresh click,\n\t\t// set the card as current\n\t\tif(!this._currentCard)\n\t\t\treturn this._currentCard= card;\n\n\t\t// If its two clicks on the same card,\n\t\t// dont do shit\n\t\tif(this._currentCard == card)\n\t\t\treturn;\n\n\t\t// Delay before checking\n\t\tsetTimeout( () => {\n\n\t\t\t// If they have the same id, match them\n\t\t\t// Else, wrong match\n\t\t\tif(this._currentCard.id === card.id) {\n\n\t\t\t\t// Mark both cards as matched\n\t\t\t\tthis._currentCard.$elem.matchComplete();\n\t\t\t\tcard.$elem.matchComplete();\n\n\t\t\t\t// Add points\n\t\t\t\tthis._addScore(this.pointsIncr.CORRECT);\n\n\t\t\t\t// Two cards were matched i.e. one pair\n\t\t\t\tthis._matchedCards+= 2;\n\t\t\t\t\n\t\t\t\t// Check if the game is complete\n\t\t\t\tthis._checkIfComplete();\n\t\t\t} else {\n\n\t\t\t\t// Deduct points\n\t\t\t\tthis._addScore(this.pointsIncr.WRONG);\n\n\t\t\t\t// Hide both cards\n\t\t\t\tthis._currentCard.$elem.hide();\n\t\t\t\tcard.$elem.hide();\n\t\t\t}\n\t\t\t\n\t\t\t// No current card\n\t\t\tthis._currentCard= null;\n\n\t\t}, 500);\n\t}", "function toggleAndAddCard() {\n const targetEvent = event.target;\n if (targetEvent.classList.contains('card') && openCards.length < 2 && !targetEvent.classList.contains('show')) {\n // console.log(\"A card was clicked.\")\n counter++;\n //This counter is to ensure that the timer only starts at the first card being clicked\n // console.log(counter);\n if (counter === 1) {\n startTimer();\n }\n displaySymbol(targetEvent);\n addCardToOpenCards(targetEvent);\n // If there are two open cards, it will check if they match\n // console.log(openCards);\n if (openCards.length === 2) {\n checkMatch();\n }\n }\n}", "function showCard(event) {\n\n const thisCard = event.target.classList;\n\n if (thisCard.contains('card')) {\n if (!thisCard.contains('show') || !thisCard.contains('match')) {\n thisCard.add('open', 'show');\n addToOpen();\n countMoves();\n }\n } else {\n event.preventDefault(); //stop counting moves when an open or matched card is clicked\n }\n}", "function cardFunctionality() {\n document.getElementsByClassName(\"answerIsIncorrect\")[0].addEventListener(\"click\", function (e) {\n postResponse(data.round.roundid, actCard.cardid, false);\n view.cardContainer.firstChild.classList.add(\"nextCard\");\n buildCards();\n updateView();\n\n });\n document.getElementsByClassName(\"answerIsCorrect\")[0].addEventListener(\"click\", function (e) {\n postResponse(data.round.roundid, actCard.cardid, true);\n view.cardContainer.firstChild.classList.add(\"nextCard\");\n buildCards();\n updateView();\n });\n document.getElementsByClassName(\"specialCardButtonAllLearned\")[0].addEventListener('click', function (e) {\n postRound();\n document.body.classList.remove(\"showSpecialCardAllLearned\");\n document.body.classList.add(\"showLearnCard\");\n });\n }", "function clickedCards(card) {\n $(card).addClass('show open');\n}", "function mouseClick(event) {\n const id = event.target.id;\n\n // Check if click was made on the background\n if (id === \"background\")\n return;\n\n // Update selector if it wasn't over the clicked card \n // (mixed controls behaviour bug)\n if (mouseOver !== selectorOver)\n updateSelector(mouseOver);\n\n pickCard();\n}", "function select (cards) {\n cards.addEventListener(\"click\", (e) => {\n if (clickReset === 0) {\n stopWatch ();\n clickReset = 1;\n }\n console.log(cards.innerHTML);\n // put the first click and the second click into variables that can be used\n const firstCard = e.target;\n const secondCard = clickedCards[0];\n\n\n // This will record if we have a currently opened card,\n // I use the ignore css class to make sure we are not matching the same card, this is utlising css pointer-events\n\n if (clickedCards.length === 1) {\n cards.classList.add('open' , 'show', 'ignore');\n clickedCards.unshift(firstCard);\n\n // Comparision of cards for further use\n comparingCards(firstCard, secondCard);\n\n // This will record if we do not having an currently opened cards\n\n } else {\n firstCard.classList.add('open' , 'show', 'ignore');\n clickedCards.push(firstCard);\n }\n });\n}", "function clickOnCards(card){\n\n//Create card click event\ncard.addEventListener(\"click\", function(){\t\n\n//Add an if statement so that we can't open more than two cards at the same time\n\tif (openedCards.length === 0 || openedCards.length === 1){\n\tsecondCard = this;\n\tfirstCard = openedCards[0];\n\n\t//We have opened card\n\tif(openedCards.length === 1){\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n\n\t//We invoke the function to compare two cards\n\tcheck(secondCard, firstCard);\n\n\t}else {\n //We don't have opened cards\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n }\n\t}\n});\n}", "function click(card) {\n // Create Click Event for card\n card.addEventListener(\"click\", function() {\n if(firstClick) {\n // Call Start the timer function\n startTimer();\n // Change the First Click value\n firstClick = false;\n }\n const secondCard = this;\n const firstCard = openedCards[0];\n // Opened card\n if(openedCards.length === 1) {\n card.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n // Call the Compare function\n compare(secondCard, firstCard);\n } else {\n secondCard.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n }\n });\n}", "function handleCardClick(event) {\n if(isCardShown(event.target) || tempFaceUp.length >= CARDS_TO_MATCH){\n return;\n }\n\n tempFaceUp.push(event.target);\n showCard(event.target);\n\n\n\n if(tempFaceUp.length >= CARDS_TO_MATCH){\n\n if(hasFoundMatch()){\n tempFaceUp = [];\n\n if(gameIsWon()){\n endGame();\n }\n \n }\n else{\n score ++;\n document.querySelector(\"#score\").innerText = score;\n\n setTimeout(() => {\n shown = 0;\n tempFaceUp.forEach( card => {\n hideCard(card);\n });\n tempFaceUp = [];\n }, 1000);\n }\n }\n}", "function handleCardClick(event) {\n\t// you can use event.target to see which element was clicked\n\n\t// prevent selecting additional cards during no match delay\n\tif (selection1 !== 0 && selection2 !== 0) return;\n\n\t// console.log('you just clicked', event.target);\n\tconst cardClass = event.target.className;\n\n\tif (event.target.className === 'matched') {\n\t\tconsole.log('Cannot reselect this card!');\n\t\treturn;\n\t}\n\n\tattempts++;\n\tdisplayAttempts();\n\n\tevent.target.style.backgroundColor = `${colorMapObject[cardClass]}`;\n\n\tif (selection1 === 0) {\n\t\tselection1 = cardClass;\n\t\telement1 = event.target;\n\t} else if (selection2 === 0) {\n\t\tif (event.target === element1) return;\n\t\tselection2 = cardClass;\n\t\telement2 = event.target;\n\n\t\tif (selection1 === selection2) {\n\t\t\tmatch = true;\n\t\t\tselection1 = 0;\n\t\t\tselection2 = 0;\n\t\t\telement1.className = 'matched';\n\t\t\telement2.className = 'matched';\n\t\t\tmatches += 2;\n\t\t\tdisplayMatches();\n\t\t} else {\n\t\t\tmatch = false;\n\t\t\tlet noMatchTimeout = setTimeout(function() {\n\t\t\t\telement1.style.backgroundColor = defaultCardColor;\n\t\t\t\telement2.style.backgroundColor = defaultCardColor;\n\t\t\t\tselection1 = 0;\n\t\t\t\tselection2 = 0;\n\t\t\t}, noMatchDelay);\n\t\t}\n\t}\n}", "function addCardsToClickedCards(event) {\n clickedCards.push(event.target);\n}", "function nextCard(e){\n //console.log(\"In the function\");\n const cards = document.querySelectorAll(\".card\");\n if(position < userList.length-1){\n //console.log(\"In the statement\");\n closeModal();\n cards[position+1].click();\n }\n}", "function respondToTheClick(evt) {\n if(evt.target.className === 'card'){\n if(!timerIsOn){\n timer();\n }\n if (openCards.length < 2){\n displaySymbol(evt);\n addCardToList(evt);\n if(openCards.length >1){\n if (openCards[0].classList[1] === openCards[1].classList[1]){\n match();\n matchedCounter++;\n incrementMovesCounter();\n if (matchedCounter === 8){\n setTimeout(won, 400);\n }\n }else{\n missmatch();\n setTimeout(hide, 700);\n incrementMovesCounter();\n }\n }\n }\n }\n}", "function handleCardClick(event) {\n\tlet clickedCard = event.target;\n\t// check whether card has been clicked\n\tfor (let card of allClickedCards) {\n\t\tif (card === clickedCard) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t// handle the first of the two clicks\n\tif (clicked.length === 0) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\t// handle the second of the two clicks\n\t} else if (clicked.length === 1) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\tresult = checkMatch(clicked[0].style.backgroundImage, clicked[1].style.backgroundImage);\n\t\tif (result === true) {\n\t\t\t// start the counter over\n\t\t\tfor (card of clicked) {\n\t\t\t\tcard.classList.add('glow');\n\t\t\t}\n\t\t\tclicked = [];\n\t\t\tupdateGuesses();\n\t\t\t// keep from re-clicking the card, take it out of the running\n\t\t} else {\n\t\t\tsetTimeout(function() {\n\t\t\t\tflipCards(clicked);\n\t\t\t\tclicked = [];\n\t\t\t}, 1000);\n\t\t\tallClickedCards.pop();\n\t\t\tallClickedCards.pop();\n\t\t\tupdateGuesses();\n\t\t}\n\t}\n\n\tif (allClickedCards.length === COLORS.length) {\n\t\tsetTimeout(function() {\n\t\t\tgameOver();\n\t\t}, 100);\n\t}\n}", "connectedCallback () {\n this.addEventListener('click', this._cardClicked)\n }", "addCard(event) {\n if (event.target.closest('.carousel__button')) {\n let eventCastom = (new CustomEvent(\"product-add\", {\n detail: event.target.closest('.carousel__slide').dataset.id,\n bubbles: true\n }));\n event.target.dispatchEvent(eventCastom);\n }\n //krutim karusel esli est sosed po classu \"carousel__arrow_right\" togda sledujuschij\n if (event.target.closest('.carousel__arrow_right')) {\n this.next();\n }\n //krutim karusel esli est sosed po classu \"carousel__arrow_left\" prediduschij\n if (event.target.closest('.carousel__arrow_left')) {\n this.prev();\n } \n }", "function addCardHandler(e){\n e.preventDefault();\n const card = createCard(cardDueDate,cardTitle,cardMembers,cardDesc);\n props.addCard(card);\n \n }", "function click (card){\n card.addEventListener(\"click\",function(){\n const presentCard = this;\n const previousCard = openCard[0];\n if(openCard.length === 1){\n\n card.classList.add(\"open\",\"show\",\"disabled\");\n openCard.push(this);\n compare(presentCard,previousCard);\n }else{\n presentCard.classList.add('open','show','disabled');\n openCard.push(this);\n }\n }\n )\n\n }", "function cardClicked(clickEvent) {\n\n //This will create a reference to the actual card clicked on.\n const cardElementClicked = clickEvent.currentTarget;\n\n //That event is passed to this function which accesses the \n //currentTarget to get element that is clicked during the event.\n const cardClicked = cardElementClicked.dataset.cardtype;\n\n //Adds flip class to the clicked card.\n cardElementClicked.classList.add('flip');\n\n //sets the current card to cardClicked if cardClicked is null\n if (currentCard) {\n\n //matchFound will be set to true if cardClicked is equal to \n //currentCard.\n const matchFound = cardClicked === currentCard;\n\n //Adds matched cards to array of cardsMatched\n if (matchFound) {\n cardsMatched.push(cardClicked);\n //If cardsMatched is equal to cardsLength the array is complete and \n //the game is over.\n if (cardsMatched.length === cards.length) {\n\n setTimeout(gameWon, 500);\n }\n\n // Reset.\n currentCard = null;\n } else {\n //setTimeout is used to delay the function for 500 milliseconds\n // so the user can process the image.\n setTimeout(() => {\n\n document\n .querySelectorAll(`[data-cardType=\"${currentCard}\"]`)\n .forEach(card => card.classList.remove('flip'));\n\n //Remove flip class from the card that was just clicked.\n cardElementClicked.classList.remove('flip');\n\n // Reset.\n currentCard = null;\n }, 500);\n }\n //Reset. \n } else {\n currentCard = cardClicked;\n }\n}", "function selectCard(e) {\n let cardNode = e.target;\n let match;\n\n // only activate if card is clicked (not the deck)\n if (cardNode.getAttribute('class') === 'card') {\n\n // determin whether this is the first card selected\n if (cardSelected === false) {\n // show icon of card\n card1 = cardNode;\n flipCard(card1);\n\n // indicate that the first card has been selected\n cardSelected = true;\n } else {\n // show icon of card\n card2 = cardNode;\n flipCard(card2);\n\n // update the turn counter\n turns++;\n updateTurns(turns);\n\n // check whether the star need to be reduced\n reduceStars();\n\n // prevent other cards from being selected\n cardNode.parentNode.removeEventListener('click', selectCard);\n\n // check if selected cards are a match\n match = checkMatch(card1, card2);\n if (match) {\n // reinstate ability to select cards\n cardNode.parentNode.addEventListener('click', selectCard);\n\n // indicate that a pair has been found\n cardsMatched=cardsMatched+2;\n\n // determine if cards\n if (cardsMatched == CARDS) {\n // show congratulations panel and end game\n endGame();\n }\n } else {\n window.setTimeout(function(){\n flipCard(card1, 'reverse');\n flipCard(card2, 'reverse');\n // reinstate ability to select cards (after cards have been flipped)\n cardNode.parentNode.addEventListener('click', selectCard);\n }, 500);\n }\n\n // reset so that new card pairs can be selected\n cardSelected = false;\n }\n }\n}", "function clickOnCard(event)\n{\n // Voorbereiden van lokale variabelen\n var parentDiv = event.target.parentElement.parentElement;\n var card_back = event.target.parentElement.parentElement.children[0];\n var card_front = event.target.parentElement.parentElement.children[1];\n var cellNumber = event.target.parentElement.parentElement.parentElement.cellIndex;\n var rowNumber = event.target.parentElement.parentElement.parentElement.parentElement.rowIndex;\n var cardNumber = (rowNumber * 4) + cellNumber;\n\n /* Wat coderen we hieronder?\n - Als de speler die aan de beurt is (huidige_speler) nog niet\n het maximaal aantal kaarten heeft aangeklikt dan:\n - kaart die de speler heeft aangeklikt omdraaien\n - vastleggen in de array cards_clicked op welke kaart de speler\n heeft geklikt. Dit doen we door de index van de kaart in deze\n array te stoppen.\n - Als de huidige speler nu twee kaarten heeft aangeklikt dan:\n - Als de twee aangeklikte kaarten gelijk zijn dan:\n - ronde score van deze speler verhogen met 1 punt\n (ronde_scores[huidige_speler])\n - schakel de klik mogelijkheid op deze twee kaarten uit\n - reset de variabele cards_clicked, beide waarden\n in deze array weer terug zetten op NO_CARD_CLICKED\n - anders (de kaarten zijn niet gelijk) dan:\n - beide kaarten terug draaien\n - geven de beurt over aan de andere speler\n - reset de variabele cards_clicked\n\n - Als we het einde van de ronde hebben bereikt (alle kaarten zijn\n al gedraaid) dan:\n - De ronde beëindigen.\n > scores moeten bijgewerkt worden op het scherm\n > alle kaarten terugdraaien\n > de tekst op de knop terugzetten naar \"Start\"\n > Klikmogelijkheid van alle kaarten uitzetten\n > Tonen de bijgewerkte totaal score op het scherm\n @TODO: Alles samenvoegen om het spel te laten werken\n */\n\n\n}", "function handleCardClick (event) {\n\tif (\n\t\tevent.target !== firstCard &&\n\t\tevent.target !== secondCard &&\n\t\tevent.target.classList.contains('clicked') === false &&\n\t\tarrayOfClicked.length < 2\n\t) {\n\t\t// you can use event.target to see which element was clicked\n\t\tif (arrayOfClicked.length <= 1) {\n\t\t\tlet card = event.target;\n\n\t\t\tcard.classList.add('clicked');\n\t\t\tcard.style.backgroundColor = card.style.color;\n\t\t\tarrayOfClicked.push(card);\n\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\tif (i === 0 && arrayOfClicked.length === 1) {\n\t\t\t\t\tfirstCard = arrayOfClicked[i];\n\t\t\t\t} else if (i === 1 && arrayOfClicked.length === 2) {\n\t\t\t\t\tsecondCard = arrayOfClicked[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (firstCard === secondCard) {\n\t\t\tarrayOfClicked.splice(arrayOfClicked.indexOf(secondCard), 1);\n\t\t} else if (arrayOfClicked.length === 2) {\n\t\t\tnumAttempts++;\n\t\t\tscore = document.querySelector('#score');\n\t\t\tscore.innerText = '' + numAttempts;\n\t\t\tsetTimeout(function () {\n\t\t\t\tif (firstCard.style.color !== secondCard.style.color) {\n\t\t\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\t\t\tlet thisCard = arrayOfClicked[i];\n\t\t\t\t\t\tthisCard.style.backgroundColor = '';\n\t\t\t\t\t\tthisCard.classList.remove('clicked');\n\t\t\t\t\t}\n\t\t\t\t\tfirstCard = null;\n\t\t\t\t\tsecondCard = null;\n\t\t\t\t} else {\n\t\t\t\t\tnumMatched += 2;\n\t\t\t\t\tfirstCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tsecondCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tarrayOfMatched.push(firstCard);\n\t\t\t\t\tarrayOfMatched.push(secondCard);\n\t\t\t\t}\n\t\t\t\tarrayOfClicked = [];\n\t\t\t\tif (numMatched === numCards) {\n\t\t\t\t\tclearTimeout();\n\t\t\t\t\tscoreCounter.className = 'new-high-score';\n\t\t\t\t\tlet prevHighScore;\n\t\t\t\t\tlet newHighScore;\n\n\t\t\t\t\tif (numCards === 10 && localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 10) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 20 && localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 20) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 30 && localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 30) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Easy\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Medium\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Hard\"]').remove();\n\t\t\t\t\tresetEasyButton = document.createElement('input');\n\t\t\t\t\tresetEasyButton.type = 'button';\n\t\t\t\t\tresetEasyButton.value = 'Reset Easy';\n\t\t\t\t\tresetEasyButton.className = 'reset-button-class';\n\t\t\t\t\tresetEasyButton.id = 'reset-easy-button';\n\t\t\t\t\tresetMediumButton = document.createElement('input');\n\t\t\t\t\tresetMediumButton.type = 'button';\n\t\t\t\t\tresetMediumButton.value = 'Reset Medium';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-class';\n\t\t\t\t\tresetMediumButton.id = 'reset-medium-button';\n\t\t\t\t\tresetHardButton = document.createElement('input');\n\t\t\t\t\tresetHardButton.type = 'button';\n\t\t\t\t\tresetHardButton.value = 'Reset Hard';\n\t\t\t\t\tresetHardButton.className = 'reset-button-class';\n\t\t\t\t\tresetHardButton.id = 'reset-hard-button';\n\t\t\t\t\tgameContainer.append(resetEasyButton);\n\t\t\t\t\tgameContainer.append(resetMediumButton);\n\t\t\t\t\tgameContainer.append(resetHardButton);\n\t\t\t\t\tresetEasyButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetHardButton.className = 'reset-button-end-class';\n\t\t\t\t}\n\t\t\t}, 1000);\n\t\t}\n\t}\n}", "function handleCardClick(card) {\n if (clickable) {\n console.log(\"you just clicked\", card.target.className);\n if (lastClicked === \"\") {\n card.target.style.backgroundColor = card.target.className;\n lastClicked = card.target.className;\n card.target.setAttribute(\"id\", 'tempFlip');\n count++;\n document.querySelector('#count').innerText = count;\n clickable = true;\n } else if (card.target.getAttribute('id') !== 'tempFlip'){\n card.target.style.backgroundColor = card.target.className;\n const firstCard = document.querySelector('#tempFlip');\n firstCard.removeAttribute('id');\n if (lastClicked === card.target.className) {\n firstCard.classList.toggle('flipped');\n card.target.classList.toggle('flipped');\n if ((document.querySelectorAll('.flipped').length) === 10) {\n onWin();\n if (localStorage.getItem('record') === null) {\n localStorage.setItem('record', count + 1);\n } else if (count + 1 < localStorage.getItem('record')) {\n localStorage.setItem('record', count + 1);\n }\n }\n } else {\n clickable = false;\n setTimeout(function() {\n firstCard.removeAttribute('style');\n card.target.removeAttribute('style');\n clickable = true;\n }, 1000);\n }\n lastClicked = \"\";\n count++;\n document.querySelector('#count').innerText = count;\n }\n }\n}", "function Card1click(){\n console.log(\"card 1 clickt\");\n if(currentplayer)\n setcardstate(0, 0, 1);\n else\n setcardstate(0, 0, 2);\n}", "function cardClick(card, array) {\n \n var letter = array.slice();\n $(card).text(letter);\n lastCardId = $(card).attr(\"id\");\n}", "function openCard(event) {\n if (event.target.classList.contains('open', 'show') || event.target.classList.contains('fa') || event.target.classList.contains('deck')) {}\n else {\n countMoves();\n event.target.classList.add('open', 'show');\n addToOpenCards(event.target);\n }\n }", "function displayCard(cardClick) {\n\tcardClick.classList.toggle(\"open\");\n\tcardClick.classList.toggle(\"show\");\n}", "function click(card) {\n card.addEventListener(\"click\", function() {\n if (switchTimer) {\n Timer = setInterval(setTimer, 1000);;\n switchTimer = false;\n }\n //Compare cards, and toggle each card's class depending on status\n card.classList.add(\"open\", \"show\", \"disabled\");\n openedCards.push(this);\n if (openedCards.length === 2) {\n moves++;\n numberMoves.innerHTML = moves;\n //Cards matched\n if (openedCards[0].innerHTML === openedCards[1].innerHTML) {\n openedCards[0].classList.add(\"match\", \"disabled\");\n openedCards[1].classList.add(\"match\", \"disabled\");\n matchedCards.push(openedCards[0], openedCards[1]);\n openedCards = [];\n //Cards unmatched\n } else {\n openedCards[0].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards[1].classList.remove(\"open\", \"show\", \"disabled\");\n openedCards = [];\n }\n }\n\n //Star ratings determined\n if (moves < 15) {\n starNumber = 3;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\n <li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n } else if (moves < 25) {\n starNumber = 2;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`\n\n } else {\n starNumber = 1;\n numberStars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`\n\n }\n gameOver();\n\n\n });\n }", "function setClick () {\n const cards = document.querySelectorAll('.cards');\n for (let i=0; i<cards.length; i++) {\n cards[i].addEventListener('click', cardFlip)\n}\n}", "function selectCard(e) {\n\tselectedCard = e.target;\n\n\t// First Card\n\tif (\n\t\tselectedCard.className.includes('card') &&\n\t\tselectedCard.parentElement.classList != 'container' &&\n\t\tcards.firstCard === null\n\t) {\n\t\tselectedCard.parentElement.classList.toggle('flip');\n\t\tcards.firstCard = selectedCard;\n\n\t\t// Ensures the same Card Cannot be picked Twice\n\t} else if (\n\t\t(cards.firstCard != null && e.target === cards.firstCard.parentElement) ||\n\t\t(cards.firstCard != null && e.target === cards.firstCard)\n\t) {\n\t\treturn;\n\t}\n\n\t// Second Card\n\telse if (\n\t\tselectedCard.className.includes('card') &&\n\t\tselectedCard.parentElement.classList != 'container' &&\n\t\tcards.secondCard === null\n\t) {\n\t\tselectedCard.parentElement.classList.toggle('flip');\n\n\t\tcards.secondCard = selectedCard;\n\n\t\t// Compare Cards\n\t\tcomparisonCheck(cards.firstCard, cards.secondCard);\n\n\t\t// Moves Counter\n\t\tmoves.innerText++;\n\n\t\t// Reset Cards Value\n\t\tcards.firstCard = null;\n\t\tcards.secondCard = null;\n\t\treturn cards;\n\t}\n}", "function openCard(card) {\n myOpenedCards.push(card);\n card.classList.add('open');\n card.classList.add('show');\n card.style.pointerEvents = 'none';\n myLastTwoCards.push(card);\n}", "function byCourse(e) {\n e.preventDefault();\n //use delegation for access to the card that selected\n if (e.target.classList.contains(\"add-to-cart\")) {\n //access to the card div with parentElement\n const course = e.target.parentElement.parentElement;\n //read values\n getCourseInfo(course);\n }\n}", "function addCardToOpenCards(event) {\n if (event.classList.contains('open')) {\n openCards.push(event);\n }\n}", "function respondToTheClick(evt) {\n if (evt.target.classList.contains('card') && !evt.target.classList.contains('match') && matchedCards.length < 3 && !evt.target.classList.contains('open')) {\n if (matchedCards.length === 0) {\n toggleClass(evt.target);\n matchedCards.push(evt.target);\n } else if (matchedCards.length === 1) {\n toggleClass(evt.target);\n matchedCards.push(evt.target);\n matchedOrNot();\n }\n } if (timerOff) {\n startTimer();\n timerOff = false;\n } if (cards.length === openCards) {\n stopTimer(); \n writeStats(); \n toggleModal(); \n }\n}", "handleTwoCardsClickedEvent() {\n if (this.clicks == 2) {\n const cards = document.querySelectorAll('.card-image');\n // convert cards from nodelist to array\n const cardsArray = Array.from(cards);\n\n const clickedCards = cardsArray.filter(this.checkForClickClass);\n\n const [card1, card2] = clickedCards;\n this.cardsMatchHandler(card1, card2);\n\n this.resetClicks();\n }\n }", "function deleteCard(event) {\n const card = window.cardList[window.currentPage];\n console.log(\"i clicked\", card);\n\n deleteButton = document.getElementById(\"deleteButton\");\n\n deleteFetch(card.id);\n\n cardAlert(\"Deleted\");\n}", "function showCard(event) {\n\n\tevent.currentTarget.classList.toggle('card__turn');\n\tevent.currentTarget.removeEventListener('click', showCard);\n\n\tif (compareA === undefined) {\n\t\tDing.volume = 0.3;\n\t\tDing.currentTime = 0;\n\t\tDing.play();\n\t\tcompareA = event.currentTarget.getAttribute('data-pair');\n\t} else {\n\t\tcompareB = event.currentTarget.getAttribute('data-pair');\n\t\tcompareCards();\n\t}\n}", "_clickCard(e) {\n if (this.editMode) {\n // do not do default\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n }\n }", "function selectCard(evt) {\n console.log(\"select card\", evt);\n // retrieve .card element\n var card = $(evt.target);\n if(card.hasClass(\"symbol\")) {\n card = card.parent(\".card\");\n }\n // toggle selected state\n card.toggleClass(\"selected\");\n // if 3 selected cards: stop selection mode and send selection action\n var selection = $.map($(\".card.selected\"), function(e) {return Number.parseInt(e.id.substr(5))});\n if(selection.length == 3) {\n stopTrioSelection(\"Wait\", null);\n send({'type': 'select_trio', 'selection': selection});\n }\n}", "function previousCard(e){\n //console.log(\"In the function\");\n const cards = document.querySelectorAll(\".card\");\n if(position !=0){\n //console.log(\"In the statement\");\n closeModal();\n cards[position-1].click();\n }\n}", "function addCardToHand(card) {\n $('#hand').append('<img src=\"/assets/images/cards/' + card + '.png\" class=\"gamecard\">');\n $('#hand .gamecard:last').click(function() {\n if($(this).parent().is('#scrap') ) { // if in scrap, run scrap onclick, don't want to select this card\n $('#scrap').click();\n return; \n }\n // clicking on card toggles its active class, removes other actives if it's active\n if(! $(this).hasClass('active') )\n $('.gamecard').removeClass('active');\n $(this).toggleClass('active');\n });\n $('#hand .gamecard:last').dblclick(function() {\n //doubleclicking on card in lineup opens damage modal\n if($(this).parent().hasClass('lineup') ) {\n openDmgModal($(this) );\n }\n });\n}", "function clickSeriesCard(card) {\n\n //get series details\n let apiCall = 'https://api.themoviedb.org/3/tv/' + card.id + '?api_key=8d1a5ff2a48df63d8f152f0a36a15c7c&language=en-US';\n ajaxCall(\"GET\", apiCall, \"\", getSeriesSuccessCB, ErrorCB);\n\n //get msg for series\n getMsg(card.id);\n}", "function bindClickEvent() {\n cardDeck.cards.forEach(card => {\n card.node.addEventListener(\"click\", (e) => {\n if (isClosingCard || card.isOpened() || card.isMatched()) {\n return;\n }\n \n card.open();\n \n if (state.isMatching) {\n if (state.matchingCard.getValue() === card.getValue()) {\n \n card.match()\n state.matchingCard.match();\n \n if (cardDeck.cards.filter(x => x.isMatched()).length === cardDeck.cards.length) {\n state.isGameOver = true;\n saveState();\n updateScreenMode(true);\n return;\n }\n \n state.isMatching = false;\n state.matchingCard = null;\n increaseMoveCounter();\n saveState();\n } else {\n isClosingCard = true;\n window.setTimeout(function() {\n card.closeCard()\n if (state.matchingCard !== null) {\n state.matchingCard.closeCard()\n }\n \n increaseMoveCounter();\n \n state.isMatching = false;\n state.matchingCard = null;\n saveState();\n isClosingCard = false;\n }, 500);\n }\n } else {\n state.isMatching = true;\n state.matchingCard = card;\n saveState();\n }\n }, false);\n });\n }", "function listenSeriesEvents() {\r\n const cardElements = document.querySelectorAll(\".js-card\");\r\n for (const cardElement of cardElements) {\r\n cardElement.addEventListener(\"click\", handleCard);\r\n }\r\n}", "function cardEventListener(event) {\n const addClasses = this.classList;\n addClasses.add(\"open\", \"show\");\n\n // setting intervals for timer\n if (isTimerSet != true) {\n clearInterval(Interval);\n Interval = setInterval(startTimer, 1000);\n isTimerSet = true;\n startTimer();\n }\n isMatch();\n}", "function setActiveCard(e) {\n const cc = e.currentTarget;\n if (cc.dataset.active === 'false') {\n let section_id = cc.closest('section').id;\n document.querySelector('#' + section_id + ' .cards-container .cc[data-active=\"true\"]').dataset.active = 'false';\n cc.dataset.active = 'true';\n if (section_id === 'overview') updateTransactionList(cc);\n else updateInfo(cc);\n }\n}", "function handleCardClick(event) {\n\t// you can use event.target to see which element was clicked\n\tconsole.log('you just clicked', event.target);\n\n\tnumClicks++;\n\n\tconsole.log(numClicks);\n\tif (numClicks === 1) {\n\t\tfirstPick = event.target;\n\t\tfirstColor = firstPick.className;\n\t\tfirstPick.style.backgroundColor = firstPick.className;\n\t\tfirstPick.removeEventListener('click', handleCardClick);\n\t}\n\telse if (numClicks === 2) {\n\t\tsecondPick = event.target;\n\t\tsecondColor = secondPick.className;\n\t\tconsole.log(firstColor, secondColor);\n\t\tconsole.log(firstPick);\n\t\tsecondPick.style.backgroundColor = secondPick.className;\n\t\tnumClicks = 0;\n\t\t// firstPick.addEventListener('click', handleCardClick);\n\n\t\tconst allDivs = document.querySelectorAll('div div');\n\t\tconsole.log(allDivs);\n\t\tfor (let div of allDivs) {\n\t\t\tdiv.removeEventListener('click', handleCardClick);\n\t\t}\n\t\tsetTimeout(function() {\n\t\t\tfor (let div of allDivs) {\n\t\t\t\tdiv.addEventListener('click', handleCardClick);\n\t\t\t}\n\t\t}, 1000);\n\n\t\tif (firstColor !== secondColor) {\n\t\t\tsetTimeout(function() {\n\t\t\t\tfirstPick.style.backgroundColor = '';\n\t\t\t\tsecondPick.style.backgroundColor = '';\n\t\t\t}, 1000);\n\t\t}\n\t\telse numClicks = 0;\n\n\t\t// if it doesn't match, setTimeout\n\t}\n}" ]
[ "0.8312875", "0.81319517", "0.81228703", "0.80927646", "0.79460865", "0.7917277", "0.7762856", "0.7724018", "0.76542777", "0.76164526", "0.75316477", "0.7515705", "0.7494764", "0.74928045", "0.74820167", "0.7470019", "0.74594855", "0.74531555", "0.7408042", "0.7392202", "0.73884785", "0.7362011", "0.73577225", "0.73405415", "0.7335297", "0.7274839", "0.7257593", "0.7235199", "0.7229915", "0.72039205", "0.7197444", "0.71833366", "0.7165959", "0.7164253", "0.7154933", "0.7137902", "0.7092338", "0.7090863", "0.70857775", "0.7076193", "0.70757663", "0.7075731", "0.7072939", "0.7059789", "0.705796", "0.7028501", "0.70030993", "0.70001966", "0.6989683", "0.69774216", "0.6975154", "0.6972849", "0.6970933", "0.6961227", "0.69576496", "0.69510555", "0.69342893", "0.69314754", "0.6908971", "0.68962854", "0.6893097", "0.6888359", "0.68852067", "0.68808216", "0.6869049", "0.68650514", "0.6856222", "0.6846818", "0.6832957", "0.68104", "0.68086475", "0.6801531", "0.6789056", "0.6779816", "0.6778612", "0.6766891", "0.67666197", "0.6763932", "0.67635685", "0.67280024", "0.6726955", "0.6725932", "0.6720293", "0.67101496", "0.6706195", "0.6697655", "0.6695931", "0.6693472", "0.66860473", "0.6685103", "0.6680645", "0.66799897", "0.66792554", "0.6678834", "0.66788244", "0.66740865", "0.6658139", "0.66579705", "0.663482", "0.6621728" ]
0.7702436
8
toggling open and show class on clicked card
function toggleOpenShow(card) { card.addClass('open show disabled'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function openCard() {\n\t\tevent.target.classList.toggle('open');\n\t\tevent.target.classList.toggle('show');\n\t}", "function showCard(clickedCard) {\n $(clickedCard).addClass('open show');\n}", "function clickedCards(card) {\n $(card).addClass('show open');\n}", "function toggleCard() {\n\tthis.classList.toggle(\"open\");\n\tthis.classList.toggle(\"show\");\n}", "function openCard(card) {\n card.classList.add('show', 'open');\n}", "function openCard(card) {\n card.className = 'card open show';\n}", "function toggleCard(card) {\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function toggleCard(card) {\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function toggle(card){\n card.classList.toggle(\"open\");\n card.classList.toggle(\"show\");\n}", "function toggle(card){\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function toggleCardDisplay(clickedCard) {\n clickedCard.classList.add('show', 'open');\n}", "function showCard (evt) {\n evt.classList.add('show', 'open');\n}", "function displayCard (clickTarget) {\n clickTarget.classList.toggle(\"open\");\n clickTarget.classList.toggle(\"show\");\n}", "function showCard(event){\n\tevent.target.setAttribute('class', 'card open show clicked');\n}", "function toggleCard(clickTarget){\n clickTarget.classList.toggle('open');\n clickTarget.classList.toggle('show');\n}", "function showCard (target) {\n target.classList.add('open', 'show');\n}", "function showCard(event) {\n return event.target.classList.add('open', 'show');\n }", "function setopen(evt){\n evt.target.setAttribute('class','card'+' '+'open'+' '+ 'show');\n}", "function showCard(card) {\n card.classList.add(\"show\", \"open\");\n}", "function toggleCard(clickTarget) {\n clickTarget.classList.toggle('open');\n clickTarget.classList.toggle('show');\n}", "function displayCard(card) {\n\treturn $(card).toggleClass('open show animated');\n}", "function displayCard() {\n\tevent.target.classList.add('show', 'open');\n}", "function clicked(card) {\n if (card.classList.contains(\"show\") || card.classList.contains(\"open\")) {\n return true;\n }\n return false;\n}", "function turnCard(card) {\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function toggleCard(card) {\n openCards.push(card);\n card.classList.add(\"open\", \"show\");\n}", "function show(card) {\n\tcard.setAttribute(\"class\", \"card show open\");\n}", "function openCard() {\n $(this).addClass(\"open show\");\n checkMatch();\n}", "function displayCard(cardClick) {\n\tcardClick.classList.toggle(\"open\");\n\tcardClick.classList.toggle(\"show\");\n}", "function toggleCard(clickTarget) {\n\tclickTarget.classList.toggle('open');\n\tclickTarget.classList.toggle('show');\n}", "function openCard(event) {\n if (event.target.classList.contains('open', 'show') || event.target.classList.contains('fa') || event.target.classList.contains('deck')) {}\n else {\n countMoves();\n event.target.classList.add('open', 'show');\n addToOpenCards(event.target);\n }\n }", "function showCard(element) {\n element.addClass(\"open show\");\n}", "function displayer(card) {\n card.classList.add(\"open\");\n card.classList.add(\"show\");\n}", "function showCard() {\n if (openCards.length < 2) {\n this.classList.toggle(\"open\");\n this.classList.toggle(\"show\");\n this.classList.toggle(\"disable\");\n } else {\n return false;\n }\n }", "function openCard(query) {\n query.classList.add('open');\n}", "function showSymbol(card){\n card.classList.add('open', 'show');\n }", "function showCard(card)\n\t{\n\t\tcard.addClass('show open');\n\t\taddOpened(card);\n\t}", "function showSymbol(card) {\n card.classList.add('open', 'show');\n }", "function displayCard(e){\n e.target.setAttribute(\"class\",\"card open show\");\n addToOpenCards(e.target);\n}", "function keepCardsOpen(card) {\n card.classList.add('match');\n card.classList.remove('show', 'open');\n}", "function showCard(){\n\tif (parents.length == 1){\n\t\tparents[0].className = 'card open show';\n\t}\n\telse if (parents.length ==2){\n\t\tparents[0].className = 'card open show';\n\t\tparents[1].className = 'card open show';\n\t}\n}", "function cardClicked(e) {\n\n const clickedCard = e.target;\n if (clickedCard.classList.contains('card') && !clickedCard.classList.contains('show')) {\n clickedCard.classList.add('show');\n addToOpenCards(clickedCard);\n }\n }", "function flipCardOver (clickedCard) {\n clickedCard.classList.toggle('open');\n clickedCard.classList.toggle('show'); \n}", "function displayCard(currentCard) {\n currentCard.classList.toggle('open');\n currentCard.classList.toggle('show');\n }", "function isCardOpened(e) {\n if (e.target.className === 'card') {\n return e.target.classList.contains('open');\n }\n}", "function displayCard (target) {\n\ttarget.classList.remove('close');\n\ttarget.classList.add('open', 'show');\n}", "function card_onShown(){\n var $this = $(this);\n if ($this.children('.collapse.show').length)\n $this.addClass('show');\n }", "function updateDisplayOpen() {\n\tfor (const o of openCards) {\n\t\to.classList.add('show', 'open');\n\t}\n}", "function openTheCard(item){\n if (openCardList.length<2){\n item.classList.add(\"open\",\"show\");\n };\n }", "function showCard(event) {\n\n const thisCard = event.target.classList;\n\n if (thisCard.contains('card')) {\n if (!thisCard.contains('show') || !thisCard.contains('match')) {\n thisCard.add('open', 'show');\n addToOpen();\n countMoves();\n }\n } else {\n event.preventDefault(); //stop counting moves when an open or matched card is clicked\n }\n}", "function showCard(card) {\n timer.start();\n if (openCards.length === 0) {\n card.classList.add(\"open\", \"show\");\n openCards.push(card);\n } else if (openCards.length === 1) {\n card.classList.add(\"open\", \"show\");\n openCards.push(card);\n } else {\n openCards.push(card);\n }\n}", "function toggleCards() {\n if (typeof data === 'undefined') {\n loadData();\n }\n flashcards.removeClass(showing ? 'cards-show' : 'cards-hide');\n flashcards.addClass(showing ? 'cards-hide' : 'cards-show');\n showing = !showing;\n }", "function clickCards() {\n\t$('.card').click(function() {\n\t\tdisplayCard(this);\n\t\taddCard(this);\n\t\tdoesCardMatch(openCards);\n\t\topenCards[0].addClass('open');\n\t\tif (openCards.length === 2) {\n\t\t\topenCards[0].removeClass('open');\n\t\t}\n\t});\n}", "function flip(card) {\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function displayIcon(card){\n card.className +=\" \"+\"show open\"; \n}", "function showSymbol(card) {\n card.classList.add('open','show', 'disabled');\n}", "function displayCard(card) {\n card.setAttribute('class', 'card show open');\n openCards.push(card);\n}", "function cardShow(card) {\n if (card != null && card != undefined){\n card.classList.add(\"open\");\n setTimeout(function show(){\n card.classList.add(\"show\");\n }, 1000);\n }\n}", "function flipCards(clickTarget) {\n\tclickTarget.toggleClass('open');\n\tclickTarget.toggleClass('show');\n}", "function showCard(card) {\n if((card.className === 'card') && (cardsOpen.length<2)){\n card.classList.add('flip');\n moveCounter();\n openedCards(card);\n }\n}", "function flip(card){\r\ncard.target.classList.add(\"open\");\r\ncard.target.classList.add(\"show\");\r\n\r\n}", "function hideCard(card) {\n card.classList.remove('open','show');\n}", "function checkCard() {\n\t\tconst openList = document.querySelectorAll('.open.show:not(.match)');\n\n\t\tif (openList[0].innerHTML === openList[1].innerHTML) {\n\t\t\topenList[0].classList.toggle(\"match\");\n\t\t\topenList[1].classList.toggle(\"match\");\n\t\t}\n\t\telse {\n\n\t\t\topenList[0].className = 'card';\n\t\t\topenList[1].className = 'card';\n\t\t}\n\t}", "function toggleCard(card) {\n //if the icon element itself is clicked\n if (card.classList.contains(\"card-icon\")) {\n card.classList.toggle(\"card-icon-visible\");\n card.parentNode.classList.toggle(\"card-closed\");\n card.parentNode.classList.toggle(\"card-open\");\n } else { //if anywhere else in the card is clicked\n card.childNodes[0].classList.toggle(\"card-icon-visible\");\n card.classList.toggle(\"card-closed\");\n card.classList.toggle(\"card-open\");\n }\n}", "function card_selected(card){\n $('.card').click(function(){\n $(this).toggleClass('selected');\n });\n }", "function displayCard(card) {\n card.className = \"card open show disable\";\n}", "function view_change(next) {\n cards.forEach(card => {card.classList.remove('is-show');});\n next.classList.add('is-show');\n}", "function view_change(next) {\n cards.forEach(card => {card.classList.remove('is-show');});\n next.classList.add('is-show');\n}", "function toggleCards() {\n cardsWrapper.classList.toggle('hidden');\n}", "function view_change(next) {\n cards.forEach(card => {\n card.classList.remove('is-show');\n });\n next.classList.add('is-show');\n}", "function teamCardHelperClasses() {\r\n $('.team-card .btn-bio').on('click tap touch', function(e) {\r\n e.preventDefault();\r\n $(this).parentsUntil($('.elementor-widget-container'), '.team-card').toggleClass('open');\r\n })\r\n }", "function openCards (input) {\n var openCards = $(\".card.open.show\");\n var maxOpen = 2;\n if (openCards.length < maxOpen) {\n input.attr(\"class\",\"card open show\")\n input.addClass(\"animated flipInY\")\n return $(\".card.open.show\")\n } else {\n openCards.removeAttr('style')\n openCards.attr(\"class\",\"card\")\n }\n}", "function toggleCard(e) {\n\tdocument.getElementById(e.target.dataset.target).classList.toggle('active-card');\n\tresumeCardsContainer.classList.toggle('active-container');\n\tresumeEl.classList.toggle('visible');\n\t$(\".resume-btn\").toggleClass('translate');\n}", "function show(e) {\n\tif(openedCards.length >= 2 || e.target.classList.contains('open','show') || e.target.classList.contains('match')) {\n\t\treturn;\n\t}\n\n\te.target.classList.add('open','show','disable');\n\topenedCards.push(e.target);\n\tif(openedCards.length === 2) {\n\t\tmoveCounter++;\n\t\tmoves.textContent=moveCounter;\n\t\tmatchCard();\n\t\tratings();\n\t}\n}", "function open() {\n cardSelected = $(event.target);\n cardSelected = cardSelected[0];\n cardSelected.setAttribute('class', 'card open show');\n openCards(cardSelected);\n startTimer();\n cardsEventListener();\n\n if (cardOpen.length === 2) {\n // delete all cardListener\n $('li').off();\n if (cardOpen[0].childNodes[1].className === cardOpen[1].childNodes[1].className) {\n lockCards();\n gameWon();\n } else {\n cardOpen[0].setAttribute('class', 'card open show wrong');\n cardOpen[1].setAttribute('class', 'card open show wrong');\n\n //the timeout function is needed to see the wrong cards for a short time\n setTimeout(function() {\n removeCards();\n }, 300);\n }\n }\n}", "function openCard(card) {\n myOpenedCards.push(card);\n card.classList.add('open');\n card.classList.add('show');\n card.style.pointerEvents = 'none';\n myLastTwoCards.push(card);\n}", "function toggleOpen(){\n\t\tconsole.log('open')\n\t\tthis.toggleClass('open');\n\t}", "function cardClicked(event) {\n if (event.target.className === 'card' && clickedCards.length <2) {\n event.target.classList.add('open', 'show');\n addCardsToClickedCards(event);\n doCardsMatch(event);\n }\n}", "function openSwitch(){\n\t\tif(this.className===\"detailsClosed\"){\n\t\t\tthis.className=\"detailsOpen\";\n\t\t}else{\n\t\t\tthis.className=\"detailsClosed\";\n\t\t}\n\t}", "toggle(){\n // Measure heights and animate transition\n const {_details: details} = this;\n const initialHeight = getComputedStyle(details).height;\n const wasOpen = details.open;\n details.open= !details.open;\n const finalHeght = getComputedStyle(details).height;\n details.open= true; // Close after animation ends\n const keyframes = [\n {height: initialHeight},\n {height: finalHeght}\n ];\n const options = { duration: 150 };\n const animation = details.animate(keyframes, options);\n // This makes the animation consistent between states\n if(wasOpen){\n details.classList.remove(\"open\");\n animation.onfinish = () => {\n details.open = false;\n };\n }else\n details.classList.add(\"open\");\n }", "setShown(toShow) {\n this.currentlyShown = toShow;\n if (this.currentlyShown === true)\n $('#' + this.cardID).show();\n else\n $('#' + this.cardID).hide();\n }", "function flipOpenCards() {\r\n let toBeReflipped = Array.prototype.slice.call(toBeReflippedHC);\r\n toBeReflipped.forEach(function(card) {\r\n card.classList.remove('open', 'show', 'toBeReflipped');\r\n });\r\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\r\n if (openCardsArray.length>1) {\r\n openCardsArray.forEach(function(card) {\r\n card.classList.remove('open', 'show');\r\n });\r\n }\r\n}", "function cardOpen() {\n\tincrementCounter();\n\n\thandleStarRating();\n\n\taddOpenCard(this);\n\n\tdisableCard(this);\n\n\thandleOpenCards();\n}", "toggle() {\n if (this.isActive) {\n this.close();\n } else {\n this.open();\n }\n }", "function hideCard() {\n console.log('hideCard() is called');\n console.log(openCards);\n $(openCards[0]).removeClass('clicked open show');\n $(openCards[1]).removeClass('clicked open show');\n}", "function cardOpen() {\n openCards.push(this);\n if(openCards.length > 1){\n if(openCards[0].type === openCards[1].type){\n openCards[0].classList.toggle(\"match\", \"disabled\", \"show\", \"open\" );\n openCards[1].classList.toggle(\"match\", \"disabled\", \"show\", \"open\" );\n openCards = [];\n countMoves();\n starsCounter();\n numberMatch++;\n } else {\n openCards[0].classList.add(\"unmatch\", \"disabled\");\n openCards[1].classList.add(\"unmatch\", \"disabled\");\n setTimeout(function(){\n openCards[0].classList.remove(\"show\", \"open\", \"unmatch\", \"disabled\");\n openCards[1].classList.remove(\"show\", \"open\", \"unmatch\", \"disabled\");\n openCards = [];\n countMoves();\n starsCounter();\n },500);\n }\n }\n}", "function toggleOpen() {\n this.classList.toggle('open')\n}", "function closeCard(card) {\n card.classList.remove('show', 'open');\n}", "function addCardToOpenCards(event) {\n if (event.classList.contains('open')) {\n openCards.push(event);\n }\n}", "function flipOpenCards() {\n let toBeReflipped = Array.prototype.slice.call(toBeReflippedHC);\n toBeReflipped.forEach(function (card) {\n card.classList.remove('open', 'show', 'toBeReflipped');\n });\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\n if (openCardsArray.length > 1) {\n openCardsArray.forEach(function (card) {\n card.classList.remove('open', 'show');\n });\n }\n}", "toggleCardCollapsed() {\n this.card_collapsed = !this.card_collapsed;\n }", "function displayCardSymbol(card) {\n card.setAttribute('class', 'card open show');\n}", "function toggleOpen() {\n this.classList.toggle(\"open\"); // removes if there, adds if not\n}", "function match() {\n openCards[0].classList.toggle('match');\n openCards[1].classList.toggle('match');\n openCards = [];\n}", "toggleCartPreview()\r\n\t{\r\n\t\tlet opening = DOM.toggleClass(this.previewElement, 'opened', 'closed');\r\n\t\t\t\r\n\t\tif (opening) {\r\n\t\t\tthis.reloadCartPreview();\t\r\n\t\t}\r\n\t}", "function toggleOpen() {\n this.classList.toggle(\"open\");\n}", "function toggleAndAddCard() {\n const targetEvent = event.target;\n if (targetEvent.classList.contains('card') && openCards.length < 2 && !targetEvent.classList.contains('show')) {\n // console.log(\"A card was clicked.\")\n counter++;\n //This counter is to ensure that the timer only starts at the first card being clicked\n // console.log(counter);\n if (counter === 1) {\n startTimer();\n }\n displaySymbol(targetEvent);\n addCardToOpenCards(targetEvent);\n // If there are two open cards, it will check if they match\n // console.log(openCards);\n if (openCards.length === 2) {\n checkMatch();\n }\n }\n}", "toggle () {\n this.opened = !this.opened;\n }", "toggle () {\n this.opened = !this.opened;\n }", "function flipCards(target) {\n $(target).toggleClass('active');\n }", "function flipCard(self) {\r\n $(self).toggleClass('active');\r\n }" ]
[ "0.8499252", "0.8365504", "0.83585036", "0.82536286", "0.8201574", "0.81460655", "0.8103942", "0.8103942", "0.8098911", "0.809776", "0.80665207", "0.80101484", "0.7970789", "0.7960427", "0.79336786", "0.7920794", "0.78743166", "0.78577405", "0.78483397", "0.78322405", "0.78170556", "0.77873", "0.7762477", "0.7748154", "0.7744371", "0.7717288", "0.77136004", "0.7712319", "0.767847", "0.7674194", "0.7634373", "0.7610962", "0.75499904", "0.7513758", "0.7486993", "0.74762976", "0.7471441", "0.7458026", "0.7409277", "0.7343365", "0.73103637", "0.7297659", "0.729117", "0.72854394", "0.7281402", "0.7246505", "0.72364473", "0.7230821", "0.71694446", "0.7148228", "0.7119836", "0.7103894", "0.7099294", "0.70687103", "0.7047394", "0.7041713", "0.7032818", "0.70114636", "0.7004624", "0.70044166", "0.699105", "0.6980041", "0.69707865", "0.6961026", "0.69248563", "0.69247097", "0.69247097", "0.69164175", "0.69153315", "0.69097286", "0.68947154", "0.6893642", "0.68183774", "0.68087465", "0.68005645", "0.6796427", "0.6796297", "0.6784844", "0.67677295", "0.6767175", "0.6763105", "0.67612803", "0.676086", "0.6741302", "0.67314476", "0.67303383", "0.6724328", "0.6723109", "0.6718281", "0.67064345", "0.66888183", "0.6671183", "0.6657907", "0.6653941", "0.6648881", "0.6642529", "0.66359395", "0.66359395", "0.6609437", "0.6608056" ]
0.8375648
1
flip cards back over after modal display
function resetCards() { let cardsInDeck = $('.deck li') for(card of cardsInDeck) { card.className = 'card'; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function flipCardOver (clickedCard) {\n clickedCard.classList.toggle('open');\n clickedCard.classList.toggle('show'); \n}", "function flip(card){\r\ncard.target.classList.add(\"open\");\r\ncard.target.classList.add(\"show\");\r\n\r\n}", "function flip(card) {\n card.classList.toggle('open');\n card.classList.toggle('show');\n}", "function flipBack(openCards) {\n // Loop through each card and add new class/change style to indicate not match\n openCards.forEach(function(openCard) {\n openCard.parentElement.setAttribute('style', 'background-color: #ff0000');\n openCard.parentElement.classList.add('animated', 'wobble');\n });\n // Flip back open cards by removing added class and styles after a delay of 0.8 seconds\n setTimeout(function() {\n openCards.forEach(function(openCard) {\n openCard.parentElement.classList.remove('open', 'animated', 'wobble');\n openCard.parentElement.removeAttribute('style', 'background-color: #ff0000');\n });\n openCards.splice(0, 2);\n }, 800);\n moveCounter();\n starRating();\n}", "function flipDelay() {\n openedCards[1].toggleClass('open show').animateCss('flipInY');\n clearOpenCards();\n}", "function flip() {\n cardContainerRef.current.classList.toggle(style.is_flipped);\n }", "function flipBack() {\n $('.card').filter($('.open')).toggleClass('open');\n OpenCards = [];\n numOfmoves = numOfmoves + 1;\n $('.moves').text(numOfmoves);\n }", "cardFlip(card) {\n if (this.allowedToFlip(card)) {\n this.soundControl.flip();\n this.totalClicks++;\n this.ticktok.innerText = this.totalClicks;\n card.classList.add('visible');\n\n if(this.verifyCard) {\n this.checkForCardMatch(card);\n } else {\n this.verifyCard = card;\n }\n }\n }", "function flipCard(e) {\n\t\tlet chosen = e.target;\n\t\t// Checks if clicked element is a card, is not open, and if there are already 2 open cards\n\t\tif (chosen.nodeName === 'LI' && !chosen.classList.contains('open', 'show', 'match') && chosenCards.length !== 2) {\n\t\t\t\tchosen.classList.add('open');\n\t\t\t\taddChosenCard(chosen);\n\t\t\t\tif (timer === false && pairsRemain > 0) {\n\t\t\t\t\t\ttimerOn();\n\t\t\t\t}\n\t\t\t\tsetTimeout(showCard, 300, chosen);\n\t\t}\n}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCard) return;\n this.classList.add('flip');\n if (!hasFlippedCard) {\n //first card clicked\n hasFlippedCard = true;\n firstCard = this;\n return;\n }\n //second card clicked\n hasFlippedCard = false;\n secondCard = this;\n checkForMatch();\n\n if (checkWin()){\n stopCheck.stop(`/memory-solution-saver/${gameId}`);\n }\n\n\n }", "function flipOpenCards() {\r\n let toBeReflipped = Array.prototype.slice.call(toBeReflippedHC);\r\n toBeReflipped.forEach(function(card) {\r\n card.classList.remove('open', 'show', 'toBeReflipped');\r\n });\r\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\r\n if (openCardsArray.length>1) {\r\n openCardsArray.forEach(function(card) {\r\n card.classList.remove('open', 'show');\r\n });\r\n }\r\n}", "function flipCards() {\n if (wrongAnswer) {\n openCards[0].removeClass('open show fail bounce locked');\n openCards[1].removeClass('open show fail bounce locked');\n }\n}", "function flipOpenCards() {\n let toBeReflipped = Array.prototype.slice.call(toBeReflippedHC);\n toBeReflipped.forEach(function (card) {\n card.classList.remove('open', 'show', 'toBeReflipped');\n });\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\n if (openCardsArray.length > 1) {\n openCardsArray.forEach(function (card) {\n card.classList.remove('open', 'show');\n });\n }\n}", "flipCard(card) {\n if(this.canFlipCard(card)) {\n this.AudioFiles.flip();\n this.totalClicks++;\n this.ticker.innerText = this.totalClicks;\n card.classList.add('visible');\n\n if(this.cardToCheck) {\n this.checkForCardMatch(card);\n } else {\n this.cardToCheck = card;\n }\n }\n }", "function resetFlip() {\n if (event.target.matches(\".start_button\") || event.target.matches(\".playAgain_button\")) {\n return;\n }\n let resetInfo = document.querySelectorAll(\".card\");\n function flipUp() {\n resetInfo.forEach(function (card) {\n setTimeout(card.classList.add(\"selected\"), 3000);\n });\n }\n setTimeout(flipUp, 500);\n\n function flipDown() {\n resetInfo.forEach(function (card) {\n card.classList.remove(\"selected\");\n });\n }\n setTimeout(flipDown, 1000);\n }", "function flipCard() {\n if (app.lockBoard) return;\n if (event.target === document.getElementById('game-panel')) return;\n if (event.target === app.firstCard) return;\n event.target.classList.add(\"flip\");\n cardFlipSound();\n\n if (!app.hasFlippedCard) {\n app.hasFlippedCard = true;\n app.firstCard = event.target;\n return;\n }\n\n app.secondCard = event.target;\n moveCounter();\n checkMatch();\n}", "function flipFlashcard() {\n console.log(CURRENT_CARD);\n if (CURRENT_CARD.showingFront) return showBack();\n return showFront();\n}", "function playAgain(){\r\n\tmodal.classList.remove(\"show\");\r\n\tunflipAll();\r\n\tshuffleCards();\r\n}", "function flipCard() {\r\n //this - whatever card we have clicked \r\n //we're getting the card clicked id and store to the cardsArray arrayChosen but only the name \r\n let cardId = this.getAttribute('data-id')\r\n cardsChosen.push(cardsArray[cardId].name)\r\n cardsChosenIds.push(cardId)\r\n\r\n //flip the card when clicked\r\n this.setAttribute('src', cardsArray[cardId].img)\r\n\r\n //revert if two selected aren't the same\r\n if (cardsChosen.length === 2) {\r\n setTimeout(checkForMatch, 500)\r\n\r\n }\r\n\r\n }", "function reflipCards(){\n Array.from(cards).forEach(card => card.classList.remove('fadeOutDown'));\n Array.from(cards).forEach(card => card.addEventListener('click', flipCard));\n Array.from(cards).forEach(card => card.classList.remove('flip'));\n resetBoard(); \n shuffle();\n}", "function flipCard(self) {\r\n $(self).toggleClass('active');\r\n }", "function flipCard(item) {\n debug(\"flipCard\", item);\n item.setAttribute(\"class\", \"card open show\");\n }", "flipDown() {\n if (this.isActive && !this.isFaceDown) {\n // flip card face down\n this.queueVisualEffect(\n () => {\n this.el.classList.toggle('flip');\n },\n true\n );\n // make card clickable only when it is completely flipped face down\n this.queueVisualEffect(\n () => {\n this.isFaceDown = true;\n },\n false\n );\n }\n }", "function flip(event){\n\tvar element = event.currentTarget;\n\tif (element.className === \"flip-card\") {\n if(element.style.transform == \"rotateX(180deg)\") {\n element.style.transform = \"rotateX(0deg)\";\n }\n else {\n element.style.transform = \"rotateX(180deg)\";\n }\n }\n}", "function flipCards(clickTarget) {\n\tclickTarget.toggleClass('open');\n\tclickTarget.toggleClass('show');\n}", "function flipCard(element) {\r\n element.toggleClass(\"card-front card-back\");\r\n setTimeout(function(){\r\n if (element.hasClass(\"card-front\")) {\r\n element.attr(\"src\", images[element.attr(\"id\").slice(3)]);\r\n } else if (element.hasClass(\"card-back\")) {\r\n element.attr(\"src\", \"images/lotus.png\");\r\n }\r\n },200);\r\n}", "flipCard(card) {\n if (this.canFlipCard(card)) {\n this.totalClicks++;\n this.moveTicker.innerText = this.totalClicks;\n card.classList.add('visible');\n if (this.cardToCheck) {\n this.checkForCardMatch(card);\n } else {\n this.cardToCheck = card;\n };\n }\n }", "function flipCard(cardElem) {\n // Count flip\n data.flips += 1;\n\n cardElem.classList.add(FLIP);\n\n // Update aria label to symbol\n cardElem.setAttribute('aria-label', cardElem.dataset.symbol);\n }", "function unflipCards() {\n\tsetTimeout(() => {\n\n\t\tcount = 0;\n\t\tfirstCard.classList.remove('flip');\n\t\tsecondCard.classList.remove('flip');\n\t\tresetCards();\n\n\t}, 1300);\n}", "function flipCard(card) {\n card.style.backgroundColor = card.className;\n card.id = \"flipped\";\n card.removeEventListener(\"click\", handleCardClick);\n}", "function redoFlashCard(el) {\n // Copy the card and send it to the back\n let card = el.parentNode.parentNode.parentNode.parentNode;\n card.style.display = \"none\";\n card.querySelector(\".answer\").style.opacity = \"0\";\n\n document.getElementById(\"flashcard-modal-content\").insertBefore(card, null);\n\n // Show the next card\n let cards = document.querySelectorAll(\".flash-card\");\n\n cards[0].style.display = \"block\";\n}", "function flipCard(evt) {\r\n let flippedCard = evt.target;\r\n if (flippedCard.nodeName === 'LI') {\r\n if (!flippedCard.classList.contains('match') && !flippedCard.classList.contains('open')) {\r\n flippedCard.classList.add('open', 'show');\r\n }\r\n }\r\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\r\n if (openCardsArray.length ===2) {\r\n checkIfMatching();\r\n }\r\n if (openCardsArray.length >2) {\r\n flipOpenCards();\r\n }\r\n }", "function unFlipCard() {\n firstCard.style.backgroundColor = \"\";\n secondCard.style.backgroundColor = \"\";\n clearCardVars();\n}", "function flipCards(target) {\n $(target).toggleClass('active');\n }", "function addFlipCard() {\n var $card = $('.card');\n\n $card.bind('click', function() {\n $flippedCard = $(this).addClass('card open show');\n opened.push($flippedCard);\n comparedCard();\n })\n}", "function noMatchFlip() {\n setTimeout(function(){\n cardsOpen[0].classList.remove('no-match', 'no-match-shake');\n cardsOpen[1].classList.remove('no-match', 'no-match-shake');\n cardsOpen[0].lastChild.classList.remove('no-match', 'no-match-shake');\n cardsOpen[1].lastChild.classList.remove('no-match', 'no-match-shake');\n cardsOpen[0].firstChild.classList.remove('no-match', 'no-match-shake');\n cardsOpen[1].firstChild.classList.remove('no-match', 'no-match-shake');\n cardsOpen[0].classList.remove('flip');\n cardsOpen[1].classList.remove('flip');\n cardsOpen[0].addEventListener('click', clickResponse);\n cardsOpen[1].addEventListener('click', clickResponse);\n cardsOpen = [];\n }, 750);\n}", "function unflipCards() {\n app.lockBoard = true;\n setTimeout(() => {\n app.firstCard.classList.remove('flip');\n app.secondCard.classList.remove('flip');\n resetBoard();\n cardNoMatchSound();\n }, 1000);\n}", "function notAMatch() {\n //flip back over after half a second\n setTimeout(function() {\n openCards.forEach(function(card) {\n card.classList.remove('open', 'show');\n });\n //empty array\n openCards = [];\n }, 500);\n}", "function flipAllCards(){\n Array.from(cards).forEach(card => card.classList.remove('flip'));\n Array.from(cards).forEach(card => card.style.cursor = \"pointer\");\n}", "function flipCard(card_index) \n{\n if(speelveld[card_index].classList.contains('flipped')) {\n speelveld[card_index].classList.remove('flipped');\n speelveld[card_index].children[CARD_FRONT].innerHTML = \"\";\n } else {\n speelveld[card_index].children[CARD_FRONT].innerHTML = getCardImageTag(card_index);\n speelveld[card_index].classList.add('flipped');\n }\n}", "function animateCardFlip(card) {\n\tif (card.classList.contains('card--hovering-left')) {\n\t\tcard.classList.add('card--flipped');\n\t\tcard.classList.add('card--flipped-left');\n\t} else {\n\t\tcard.classList.add('card--flipped');\n\t\tcard.classList.add('card--flipped-right');\n\t}\n}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCardFlip) return;\n this.classList.add('flip');\n if (!cardHasFlipped) {\n cardHasFlipped = true;\n firstCardFlip = this;\n return;\n }\n secondCardFlip = this;\n\n checkForMatch();\n}", "function addFlipEffect () { \n var cardsFlip = document.querySelectorAll(\".card.effect__click\");\n for ( var i = 0; i < cardsFlip.length; i++ ) {\n var card = cardsFlip[i]; \n compareCards(card);\n }\n}", "function flipCardsBackDown(){\n setTimeout(function(){\n $(selectedCards[0]).toggleClass(\"flip\");\n $(selectedCards[1]).toggleClass(\"flip\");\n selectedCards = [];\n canSelectCard = true;\n }, 550);\n}", "function flipCard(evt) {\n let flippedCard = evt.target;\n if (flippedCard.nodeName === 'LI') {\n if (!flippedCard.classList.contains('match') && !flippedCard.classList.contains('open')) {\n flippedCard.classList.add('open', 'show');\n }\n }\n let openCardsArray = Array.prototype.slice.call(openCardsHC);\n if (openCardsArray.length === 2) {\n checkIfMatching();\n }\n if (openCardsArray.length > 2) {\n flipOpenCards();\n }\n}", "function flipCard() {\n if (cardsLocked) return;\n if (this === firstCard) return;\n this.classList.add('flip');\n if(!hasCardFlipped) {\n hasCardFlipped = true;\n firstCard = this;\n return;\n };\n secondCard = this;\n // hasCardFlipped = false;\n doCardsMatch(); \n}", "function showCard(card) {\n if((card.className === 'card') && (cardsOpen.length<2)){\n card.classList.add('flip');\n moveCounter();\n openedCards(card);\n }\n}", "function flipCards() {\n\tcardOne.removeEventListener('click', showCard);\n\tcardTwo.removeEventListener('click', showCard);\n\n\tcardOne.classList.add('shake');\n\tcardTwo.classList.add('shake');\n}", "function unflipCards() {\n stopClicks = true;\n setTimeout(() => {\n gsap.to(cardOne, { duration: 1, rotationY: 720 });\n gsap.to(cardOne, { duration: 0.5, color: \"transparent\" });\n gsap.to(cardTwo, { duration: 1, rotationY: 720 });\n gsap.to(cardTwo, { duration: 0.5, color: \"transparent\" });\n stopClicks = false;\n }, 1500);\n}", "function flipCard(card, flipDirection) {\n if(flipDirection != 'reverse') {\n card.setAttribute('class', 'card open show');\n } else {\n card.setAttribute('class', 'card');\n }\n}", "function flipCard(event) {\n\t// when the card is clicked it flips to the other side\n\t// have the definition side be hidden (toggle) and on click/flip hide the term\n\tterm.classList.toggle('hidden');\n\tdefinition.classList.toggle('hidden');\n}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCard) return;\n\n this.classList.add('flip');\n\n if (!hasFlippedCard) {\n hasFlippedCard = true;\n firstCard = this;\n\n return;\n }\n\n secondCard = this;\n checkForMatch();\n}", "function unFlipCards() {\n clearCardInPlay();\n freezePlay = true;\n setTimeout(() => {\n cardOne.classList.remove(\"flip\");\n cardTwo.classList.remove(\"flip\");\n clearDeck();\n }, 1700);\n }", "_flipCard () {\r\n // Don't flip if tile is hidden or inactive.\r\n if (this.hasAttribute('inactive') || this.hasAttribute('hidden')) {\r\n return\r\n }\r\n\r\n // Toggle the flip attribute.\r\n if (this.hasAttribute('flip')) {\r\n this.removeAttribute('flip')\r\n this._addFlippedEvent('back')\r\n } else {\r\n this.setAttribute('flip', '')\r\n this._addFlippedEvent('front')\r\n }\r\n }", "function card_flipback() {\n $(first_card_back).removeClass('flipped');\n $(second_card_back).removeClass('flipped');\n}", "function cardF () {\n dCard.classList.toggle('is-flipped')\n}", "function showOverlay() {\n cards = document.querySelectorAll('.card'); \n\n // shows adds corresponding HTML to modalDiv based on selected card index\n cards.forEach((card, index) => {\n card.addEventListener('click', (e) => {\n currentIndex = index;\n modalDiv.innerHTML = modalHTMLArray[currentIndex];\n modalDiv.style.display = 'block';\n })\n })\n\n // gives functionality to modal buttons\n modalDiv.addEventListener('click', (e) => {\n let next = currentIndex + 1;\n let prev = currentIndex - 1;\n // decreases currentIndex and changes modalDiv HTML\n if (e.target.id === 'modal-prev' || e.target.textContent === 'Prev') {\n if (currentIndex > 0){\n modalDiv.innerHTML = modalHTMLArray[prev];\n currentIndex = prev;\n } else {\n currentIndex = 0;\n }\n // increases currentIndex and changes modalDiv HTML\n } else if (e.target.id === 'modal-next' || e.target.textContent === 'Next') {\n if (currentIndex === cards.length - 1){\n currentIndex = cards.length - 1;\n } else if (currentIndex < cards.length) {\n modalDiv.innerHTML = modalHTMLArray[next];\n currentIndex = next;\n }\n } \n // closes modal\n else if( e.target.textContent === 'X' ) {\n modalDiv.style.display = 'none';\n }\n })\n}", "function flipCards(incomplete) {\n\tfor (var i = 1; i < 13; i++) {\n\t\tvar card = document.getElementById(\"card\" + i);\n\t\tif (card.className === \"card\") {\n\t\t\tcard.className = \"card flipped\";\n\t\t} else {\n\t\t\tcard.className = \"card\";\n\t\t}\n\n\t\tif (back) {\n\t\t\tdocument.getElementById(\"front\" + i).style.display = \"none\";\n\t\t\tdocument.getElementById(\"back\" + i).style.display = \"block\";\n\t\t\t\n\t\t\tdocument.getElementById(\"frontTable\" + i).style.visibility = \"hidden\";\n\t\t\tdocument.getElementById(\"backTable\" + i).style.visibility = \"visible\";\n\t\t\tdocument.getElementById(\"backTable\" + i).className = \"\";\n\t\t} else {\n\t\t\tdocument.getElementById(\"front\" + i).style.display = \"block\";\n\t\t\tdocument.getElementById(\"back\" + i).style.display = \"none\";\n\t\t\t\n\t\t\tdocument.getElementById(\"frontTable\" + i).style.visibility = \"visible\";\n\t\t\tdocument.getElementById(\"backTable\" + i).style.visibility = \"hidden\";\n\t\t\tdocument.getElementById(\"frontTable\" + i).className = \"\";\n\t\t}\n\t}\n\t\n\tif (incomplete < 12) {\n\t\thideOtherMatchingCards(incomplete);\n\t}\n}", "function flipCard(card) {\n //if there is no card clicked\n if(flippedCard === null){\n flippedCard = card;\n flippedCard.classList.toggle(\"active\");\n //if there is a card already clicked\n } else if(secondCardFlipped === null) {\n secondCardFlipped = card;\n secondCardFlipped.classList.toggle(\"active\");\n \n //if cards have different content:\n if(flippedCard.textContent.trim() !== secondCardFlipped.textContent.trim()) {\n setTimeout(\n function(){\n flippedCard.classList.remove(\"active\");\n secondCardFlipped.classList.remove(\"active\"); \n //Back to the original\n flippedCard = null;\n secondCardFlipped = null;\n }, 2000\n );\n } else {\n //if cards have the same content\n //Back to the original\n flippedCard = null;\n secondCardFlipped = null;\n }\n } \n}", "function flipCard(card_index)\n{\n if(speelveld[card_index].classList.contains('flipped')) {\t// Bevat de kaart al de css class flipped?\n /*\n Ja!\n Dan gaan de kaart weer terugdraaien door de css class flipped weer weg te halen\n */\n speelveld[card_index].classList.remove('flipped');\t\t\t// Hier halen we de css class flipped weg\n speelveld[card_index].children[CARD_FRONT].innerHTML = \"\";\t// We gaan de img-tag ook weer verwijderen\n } else {\n /*\n Nee!\n Dan draaien we de kaart om zodat de afbeelding zichtbaar wordt.\n Dit doen we door de css class flipped toe te voegen aan de kaart en de tweede div\n in de kaart te vullen met de img-tag van de echte afbeelding\n */\n speelveld[card_index].children[CARD_FRONT].innerHTML = getCardImageTag(card_index);\t// Toon de afbeelding\n speelveld[card_index].classList.add('flipped');\t\t\t\t\t\t\t\t\t\t// Voeg de css class flipped toe.\n }\n}", "function flipCard(evt) {\n\tif (evt.target !== evt.currentTarget) {\n\t\tconst clickedCard = evt.target;\n\t\tclickedCard.classList.add('show', 'open');\n\t\tflippedCard.push(clickedCard);\n\t\t\t\t\n\t\t\t//if the list already has another card, check to see if the two cards match\n\t\tif (flippedCard > 2){\n\t\t\tfirstCard.classList.remove('show', 'open');\n\t\t\tsecondCard.classList.remove('show', 'open');\n\t\t}\n\t\tconst firstCard = flippedCard[0];\n\t\tconst secondCard = flippedCard[1];\n\n\n\t\tif (firstCard && secondCard) {\n\t\t\tcardMoves +=1 ;\n\t\t\tnumMoves.innerHTML = cardMoves;\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tif (flippedCard.length === 2 && firstCard.innerHTML == flippedCard[1].innerHTML && \n\t\t\tfirstCard.innerHTML === flippedCard[1].innerHTML){\n\t\t\t//if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one)\n\n\t\t\tclickedCard.classList.add('match');\n\t\t\tfirstCard.classList.add('match')\n\t\t\tconsole.log('match!!');\t\n\t\t\tflippedCard = [];\n\t\t\tmatchedCard.push(firstCard, secondCard);\n\t\t\tgameWon();\n\n\t\t}else if (flippedCard.length === 2 && firstCard.innerHTML != flippedCard[1].innerHTML){\n\t\t\tconsole.log('no match');\n\n\t\t\tsetTimeout(wait, 1000);\n\t\t\tfunction wait(){\n\t\t\t\tfirstCard.classList.remove('show', 'open');\t\t\t\n\t\t\t\tsecondCard.classList.remove('show', 'open')\n\t\t\t\t\n\t\t\t}\n\t\t\tflippedCard = [];\n\t\t}else {\n\t\t\tconsole.log('select another');\n\t\t}\n\t}\n\n\tevt.stopPropagation();\n}", "function flip(e) {\n const vas = e.path[0];\n if (vas.classList == 'card') {\n e.target.classList.toggle('open');\n e.target.classList.toggle('show');\n } else if (vas.classList.contains('fa')) {\n if (vas.parentElement.classList == 'card') {\n vas.parentElement.classList.toggle('open');\n vas.parentElement.classList.toggle('show');\n\n }\n }\n}", "function unflipCards() {\n lockBoard = true;\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n resetBoard();\n }, 1500);\n\n }", "unflipCards() {\n this.lockBoard = true;\n\n setTimeout(() => {\n this.firstCard.classList.remove('flip');\n this.secondCard.classList.remove('flip');\n\n this.resetBoard();\n }, 1500);\n }", "function flipCardKeyboard(card) {\n\t\tif (!cards[card].classList.contains('open', 'show', 'match') && chosenCards.length !== 2) {\n\t\t\t\tcards[card].classList.add('open');\n\t\t\t\taddChosenCard(cards[card]);\n\t\t\t\tif (timer === false && pairsRemain > 0) {\n\t\t\t\t\t\ttimerOn();\n\t\t\t\t}\n\t\t\t\tsetTimeout(showCard, 300, cards[card]);\n\t\t}\n}", "function flipCard(elem) {\n elem.style = \"transform: rotateY(180deg);\";\n\n}", "function flipFlashCard(el) {\n el.parentNode.parentNode.querySelector(\".answer\").style.opacity = \"1\";\n el.parentNode.querySelector(\".correct-answer\").disabled = false;\n el.parentNode.querySelector(\".wrong-answer\").disabled = false;\n\n textToSpeech();\n}", "function unflipCards() {\n lockBoard = true;\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n resetBoard();\n }, 1000);\n }", "function flipOver(globals, id) {\n var cards = globals.cards;\n // Only do something if it was already revealed\n if (globals.cards[id].flipped) {\n globals.totFlip--;\n $('#' + id).css({\n backgroundImage:'url(' + cards[id].normalBack + ')'\n }); \n }\n\n cards[id].flipped = false;\n}", "function flipCard(index) {\n setOpenedCard((prevState) =>\n prevState.map((item, idx) => (idx === index ? !item : item))\n );\n // setOpenedCard((opened) => [...opened, index]);\n // cardFlipStatus[index] = !cardFlipStatus[index];\n // console.log(cardFlipStatus[index]);\n }", "function flipCard() { // flip card function, flips card on click, only applies when board not locked and flipping 1st or 2nd card\n if (lockBoard) return;\n if (this === firstCard) return;\n\n this.classList.add(\"flip\");\n\n if (!hasFlippedCard) {\n hasFlippedCard = true;\n firstCard = this;\n\n return;\n }\n\n secondCard = this;\n checkCards();\n}", "function cardFlip(theCard) {\n gameSound();\n addToFlips();\n cardSound();\n\n console.log(theCard)\n //adds or removes flip class to aCard class\n if (freezeScreen === true) return;\n $(theCard).toggleClass('flip')\n\n if (wasflipped === false) {\n //set card flipped to true\n wasflipped = true;\n //store card info in first card\n firstCard = theCard;\n }\n else {\n wasflipped = false;\n secondCard = theCard;\n // check if first card data attr matches 2nd card\n if (firstCard.getAttribute('data-cardatt') === secondCard.getAttribute('data-cardatt')) {\n addToMatches();\n cardsMatchedArray.push(firstCard, secondCard);\n $(firstCard).off('click');\n $(secondCard).off('click');\n }\n else {\n errorSound();\n freezeScreen = true;\n setTimeout(() => {\n //removes the flip class from the first and 2nd card and flips the cards back over\n $(firstCard).removeClass('flip');\n $(secondCard).removeClass('flip');\n freezeScreen = false;\n }, 1500);\n }\n\n }\n //check if cards match by checking attribute on card\n console.log($(firstCard));\n\n\n }", "function unflipCards() {\n lockBoard = true;\n\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n\n resetBoard();\n\n }, 1500);\n }", "function reset() {\n \n setTimeout(() => {\n [hasFlippedCard, gameBoard] = [false, false];\n [firstCard, secondCard] = [null, null];\n\n cards.forEach(cardBg => cardBg.classList.remove('bg_yes'));\n cards.forEach(cardBg => cardBg.classList.remove('bg_no'));\n\n cards.forEach(cards => cards.addEventListener('click', flipCard));\n }, 700); \n }", "function drawFlipCard(cards) {\n\n _.each(cards, function(card) {\n\n var $tmplFlipCard = $($(\"#templateFlipCard\").html());\n\n // Set the name of the card for Google Analytics\n $(\"#data-cardname\", $tmplFlipCard).html(card.name);\n\n // Set the question for the front of the card\n $(\".question\", $tmplFlipCard).html(card.question)\n\n // Set the back content of the card\n $(\".back1\", $tmplFlipCard).html(card.back1);\n $(\".back2\", $tmplFlipCard).html(card.back2);\n $(\".back3\", $tmplFlipCard).html(card.back3);\n $(\".back4\", $tmplFlipCard).html(card.back4);\n $(\".back5\", $tmplFlipCard).html(card.back5);\n\n\n\n\n $(\"img.background-image\", $tmplFlipCard).attr(\"src\", \"img/training/\" + card.image);\n\n // _NOW_ we add this template to the training page\n $(\"#flipCardList\").append($tmplFlipCard);\n\n });\n\n // Flip Cards Flipping Script\n // ====================================\n $('.flip').on('click', function(event) {\n $(event.target).parents('.card').toggleClass('flipped');\n });\n\n}", "function unFlipCard(card) {\n card.style.backgroundColor = \"white\";\n card.id = \"\";\n card.addEventListener(\"click\", handleCardClick);\n}", "function playAgain(){\r\n modal.classList.remove(\"show\");\r\n buildDeck();\r\n}", "function flipCard()\n\t{\n\t\tvar cardId = this.getAttribute('data-id');\n\t\tcardsInPlay.push(cards[cardId].rank);\n\t\t//console.log(\"User flipped \" + cards[cardId].rank+ \"\"+cards[cardId].cardImage);\n\t\tthis.setAttribute('src',cards[cardId].cardImage);\n\n\t\t//to check if two card are the same\n\t\tif(cardsInPlay.length===2)\t\n\t\tif (cardsInPlay[0] === cardsInPlay[1])\n\t\t { \n\t\t \t alert(\"You found a match!\"); \n\t\t //update score\n\t\t score = ++score; \n\t\t }\n\t\t // if user did not flip the same cards\n\t\telse \n\t\t {\n\t\t \talert(\"Sorry, try again.\");\n\n\t\t }\n\t}", "function flipCard(){\n if(cardSide == \"QuestionSide\"){\n cardSide = \"AnswerSide\";\n $(\".card-title-question\").hide();\n $(\".card-text-answer\").show();\n console.log(\"show Q\")\n }else{\n $(\".card-title-question\").show();\n $(\".card-text-answer\").hide();\n console.log(\"show A\");\n cardSide = \"QuestionSide\"\n }\n }", "function corduroyFlip(evt) {\n var cordPanel = document.querySelector(\"#corduroy .flapContainer\");\n\n if(cordPanel.style.transform ===\"none\") {\n cordPanel.style.transform = \"rotateY(180deg)\";\n cordPanel.zIndex = 1;\n } else {\n cordPanel.style.transform = \"none\";\n cordPanel.style.zIndex = 0;\n }\n \n evt.stopPropagation();\n}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCard) return;\n\n this.classList.add('flip');\n\n if (!hasFlippedCard) {\n// click 1 when the player selects the card the flip card function fires\n hasFlippedCard = true;\n firstCard = this;\n\n return;\n }\n\n// click 2 sets the second card as this\n secondCard = this;\n\n checkForMatch();\n}", "function unflipCards (){\n lockBoard = true;\n\n setTimeout(() => {\n firstCard.classList.remove (\"flip\");\n secondCard.classList.remove (\"flip\");\n\n resetBoard();\n }, 1200);\n }", "function openCard(event) {\n var btnCard = event.getAttribute(\"btnCard\");\n\n var elementCero = document.getElementsByClassName(`card-${btnCard}`)[0];\n var elementUno = document.getElementsByClassName(`card-${btnCard}`)[1];\n\n elementCero.style.transform = \"rotatey(360deg)\"\n elementUno.style.transform = \"rotatey(360deg)\"\n\n\n var rowCero = document.getElementsByClassName(`row-${btnCard}`)[0];\n var rowUno = document.getElementsByClassName(`row-${btnCard}`)[1];\n\n\n var rowCeroUno = document.getElementsByClassName(`row${btnCard}-${btnCard}`)[0];\n var rowUnoUno = document.getElementsByClassName(`row${btnCard}-${btnCard}`)[1];\n\n rowCero.style.opacity = \"0\";\n rowUno.style.opacity = \"0\";\n\n setTimeout(() => {\n rowCero.style.display = \"none\";\n rowUno.style.display = \"none\";\n }, 500);\n\n\n setTimeout(() => {\n rowCeroUno.style.display = \"flex\";\n rowUnoUno.style.display = \"flex\";\n }, 1000);\n\n\n\n}", "function flipCard(e) {\n if (e.target.nodeName === 'LI' || e.target.nodeName === 'I') {\n if (currentOpenCards.length % 2) {\n moves++;\n tally.textContent = moves;\n if (moves === 15 || moves === 20 || moves === 25 || moves === 30) {\n stars.firstElementChild.remove();\n }\n }\n }\n if (e.target.nodeName === 'LI') {\n const card = e.target;\n loadCard(card);\n } else if (e.target.nodeName === 'I') {\n const card = e.target.parentNode;\n loadCard(card);\n }\n}", "function flipCard(card) {\n // change background color to classname\n card.style.backgroundColor = card.className;\n}", "function flipCard(element, id) {\n // make flip sound\n myAudio.volume = 0.3;\n myAudio.play();\n\n element.parentElement.classList.add(\"open\");\n\n // in order to not show solution at first sight in the html code, the backside of card is\n // appended if user clicks on card\n var nodeBackDiv = document.createElement(\"div\");\n nodeBackDiv.classList.add(\"back\");\n\n var img = document.createElement(\"IMG\");\n img.src = \"assets/images/pool/1x/\" + cardArr[id][\"img\"] + \".png\";\n img.setAttribute(\"alt\", \"Train your Brain\");\n\n nodeBackDiv.appendChild(img);\n element.appendChild(nodeBackDiv);\n }", "function unflipCards() {\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n resetBoard();\n }, 1500);\n}", "flipCard(el) {\n if(this.blocked == false){\n if(this.removedCards.indexOf(el.target.id) != -1 || el.target.classList.contains(\"flipped\") ){ return; }\n el.target.classList.add(\"flipped\");\n const self = this;\n setTimeout(function(){\n el.target.style.backgroundImage=\"url(img/\"+pictures[self.randomizedCards[el.target.id]].img+\".png)\";\n }, 150);\n if(this.flippedCards.length != 0 && this.flippedCards.indexOf(pictures[this.randomizedCards[el.target.id]].type) == -1) {\n this.blocked = true;\n this.randomMessage(false);\n setTimeout(function() {\n self.unflipAllCards();\n }, 1400);\n }\n\n this.flippedCards.push(pictures[this.randomizedCards[el.target.id]].type);\n\n // Flips the cards and gives you 20 points if you get 4 cards of the same type\n if (this.flippedCards.length >= 4) {\n this.score += 20;\n for(let i=1;i<this.flippedCards.length;i++){\n if(this.flippedCards[i-1] == this.flippedCards[i]){\n continue;\n }\n this.randomMessage(false);\n this.unflipAllCards();\n return;\n }\n\n // to remove the chosen cards from the game\n while(document.getElementsByClassName(\"flipped\").length > 0) {\n this.removedCards.push(document.getElementsByClassName(\"flipped\")[0].getAttribute(\"id\"));\n document.getElementsByClassName(\"flipped\")[0].classList.add(\"invis\");\n document.getElementsByClassName(\"flipped\")[0].classList.remove(\"flipped\");\n }\n this.randomMessage(true);\n this.flippedCards = [];\n }\n\n if(this.removedCards.length >= 52){\n this.wonGame();\n }\n }\n }", "function flipped()\n{\n \n let flip = this.getAttribute(\"data-id\");\n pickedCard.push(cardsArr[flip].name);\n\n cardPickId.push(flip);\n //this.classList.replace(\"back\",\"front\");\n this.classList.add(\"flip\");\n this.setAttribute(\"src\",cardsArr[flip].img);\n \n \n if(pickedCard.length ===2){\n \n setTimeout(checkCard,500)\n }\n}", "function flipcard(i) {\r\n if ( newdeal ) // If it's the end of a hand, we can't flip, so just return\r\n {\r\n\t$(\"#deal\").effect('pulsate').effect( \"highlight\", {color:'lightgreen'}, 800 );\r\n return;\r\n }\r\n\r\n\tsetWait(true);\r\n if ( !flipped[i] ) { // Either flip card over...\r\n document.images[i+imgoffset].src = back.src;\r\n flipped[i] = 1;\r\n }\r\n else { // ...or flip it back\r\n document.images[i+imgoffset].src = cards[i].src;\r\n flipped[i] = 0;\r\n }\r\n setWait(false);\r\n}", "function reveal(globals, id) {\n if (globals.totFlip < globals.MAX_FLIP) {\n globals.cards[id].flipped = true;\n\t\tglobals.totFlip++;\n maxMem(globals);\n setNewMem(globals);\n $('#' + id).css({\n backgroundImage: 'url(' + globals.cards[id].frontFace + ')'\n });\n }\n}", "function flipCard(i) {\r\tcreateDrag(i,2);\r\t$('#card'+i).addClass('front');\r\t$('#card'+i).removeClass('back');\r}", "function enterflip(flip)\n{\n\tdocument.getElementById(flip).style.display = 'block';\n}", "function flipCard() {\n\tvar cardId = this.getAttribute('data-id');\n\tconsole.log(\"User flipped \" + cards[cardId].rank + \" of \" + cards[cardId].suit);\n\tconsole.log(cards[cardId].cardImage);\n\tconsole.log(cards[cardId].suit);\n\tthis.setAttribute('src',cards[cardId].cardImage);\n\tcardsInPlay.push(cards[cardId].rank);\n\tcheckForMatch();\n\t// remove eventListener for cards that have already been flipped\n\tthis.removeEventListener('click',flipCard);\n}", "function flipCard(card){ //flip card function\n\tcard.target.className = 'card open show';\n\tif(firstClick){\n\t\ttimerId = setInterval(startTimer, 1000); //id for clearInterval and sets interval to 1 second\n\t\tfirstClick = false; //have the game initialize with firstClick to be false so the game would start once a card has been clicked.\n\t}\n}", "function flipCard(card, cards_list){\n cardOpen.push(card)\n\n var crd = cards_list.filter(cards =>{\n return cards.id == card.id\n })\n\n card.src = crd[0].src\n\n if(cardOpen.length == 2){\n disable()\n check()\n count()\n }\n}", "function flipCard(){\n\n\tif(trackedCards.length < 2){\n\n\t\t$(this).addClass(\"flipped\");\n\t\tvar flippedCard = $(this).find(\"img\")[0];\n\t\tvar flippedCardId = flippedCard.id;\n\n\t\tif(flippedCardId != trackedCards[0]){\n\n\t\t\ttrackedCards.push(flippedCardId);\n\t\t\tcardsInPlay.push(cards[flippedCardId].value);\n\n\t\t\tif(cardsInPlay.length == 2){\n\n\t\t\t\tvar cardOne = cardsInPlay[0];\n\t\t\t\tvar cardTwo = cardsInPlay[1];\n\t\t\t\tif(cardOne == cardTwo){\n\n\t\t\t\t\tplayerScoreTracking();\n\n\t\t\t\t\toutOfPlay();\n\t\t\t\n\t\t\t\t} \t\n\n\t\t\t\telse { \n\n\t\t\t\t\tplayerSwitch();\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhoWon();\n\t}\n\n}", "function unflipCards() {\n lockBoard = true;\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n// There is a 60 second delay to see flipping animation\n resetBoard();\n }, 60);\n}", "function flipCard(){\n let cardId = this.getAttribute('data-id')\n cardChosen.push(cardArray[cardId].name)\n cardChosenId.push(cardId)\n this.setAttribute('src', cardArray[cardId].img)\n if(cardChosen.length ===2){\n setTimeout(checkForMatch, 500)\n }\n}", "function countdown_mtproc()\r\n\r\n{\r\n\r\n$(\"#mintentop\").flip({\r\n\r\ndirection:'tb',\r\n\r\ncolor: '#000000',\r\n\r\n\r\nonEnd: function(){\r\n$(\"#mintentop\").css(\"opacity\",\"0\");\r\n\t\t\r\n\t}\r\n\r\n})\r\n}", "function flipCard(event) {\n \n//counter for the moves\n moves++;\n counter.innerHTML= 'Moves '+ moves;\n\n if (!firstCard || !secondCard) {\n event.target.classList.toggle('front');\n //lock the bord \n if (lockBord) return; \n if (this === firstCard) return;\n\n if (!hasFlippedCard) {\n hasFlippedCard = true;\n firstCard = this; \n return; \n }\n secondCard = this;\n checkForMatch();\n }\n }" ]
[ "0.7347733", "0.7144152", "0.7125572", "0.7061022", "0.70547336", "0.7011751", "0.69605386", "0.69433624", "0.6926739", "0.6856992", "0.6850814", "0.68347245", "0.6827213", "0.68114984", "0.6804681", "0.6737662", "0.6736725", "0.6727424", "0.67223996", "0.67174643", "0.67071724", "0.67008376", "0.6694779", "0.6687766", "0.6677624", "0.6625409", "0.66228646", "0.66182315", "0.65953153", "0.657634", "0.6570483", "0.6568429", "0.65647227", "0.6560565", "0.65487295", "0.65478474", "0.6536925", "0.65245336", "0.65211713", "0.65061426", "0.64930326", "0.6483362", "0.6478127", "0.64721", "0.6471735", "0.6454927", "0.6442185", "0.64386797", "0.6437696", "0.64294606", "0.6427595", "0.642549", "0.64230156", "0.64203745", "0.64203155", "0.6410542", "0.6403558", "0.63957995", "0.63923943", "0.63894904", "0.6382207", "0.6377577", "0.6374626", "0.6373095", "0.63722247", "0.636959", "0.63631815", "0.63629544", "0.63580304", "0.63506716", "0.6347911", "0.6346654", "0.63461524", "0.63457084", "0.63434964", "0.63420224", "0.63379455", "0.6332769", "0.6332336", "0.63299984", "0.6325665", "0.63185257", "0.6313552", "0.6313075", "0.6311447", "0.63062406", "0.62865865", "0.6279996", "0.62773293", "0.6277078", "0.6275925", "0.6272017", "0.62612087", "0.626055", "0.6259403", "0.6258356", "0.62480325", "0.6244384", "0.6240895", "0.62394255", "0.623881" ]
0.0
-1
match first card clicked to second card clicked
function matchedCard() { let firstCard = allOpenedCards[0]; let secondCard = allOpenedCards[1]; if(allOpenedCards.length === 2) { moveCounter(); scoreCheck(); if(firstCard.children().attr('class') === secondCard.children().attr('class')) { firstCard.addClass('match'); secondCard.addClass('match'); allOpenedCards.length = 0; matchCount++; if(matchCount === matchedPairs) { gameOver(); } } else { setTimeout(function() { firstCard.removeClass('open show disabled'); secondCard.removeClass('open show disabled'); allOpenedCards.length = 0; }, 300); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function manipulateCard(event) {\n\t// Check if there is any card already clicked\n\tif (firstClickedElement === null){\n\n\t\t// No card clicked yet => store its value (class) into firstCard variable\n\t\tfirstCard = event.target.lastElementChild.getAttribute('class');\n\n\t\t// Show the card\n\t\tshowCard(event);\n\n\t\t// Get the element of the first clicked card\n\t\tfirstClickedElement = document.querySelector('.clicked');\n\n\t} else if (firstCard === event.target.lastElementChild.getAttribute('class')) {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Since 2nd card matches the first one => change cards status to \"card match\" (both cards remain with their face up) -> with a short delay\n\t\tchangeCardsStatus(event, 'card match');\n\n\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\tother2Cards();\n\t\t\n\t\t// Increase number of matched cards\n\t\tcellNo = cellNo + 2;\n\n\t} else {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Set the 2 clicked cards attributes to wrong class -> with a short delay\n\t\tchangeCardsStatus(event, 'card open show wrong');\n\n\t\t// Set the 2 clicked cards attributes to its defaults -> with a short delay\n\t\tsetTimeout(function(){\n\t\t\tchangeCardsStatus(event, 'card');\n\n\t\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\t\tother2Cards();\n\t\t}, 300);\n\t}\n}", "handleTwoCardsClickedEvent() {\n if (this.clicks == 2) {\n const cards = document.querySelectorAll('.card-image');\n // convert cards from nodelist to array\n const cardsArray = Array.from(cards);\n\n const clickedCards = cardsArray.filter(this.checkForClickClass);\n\n const [card1, card2] = clickedCards;\n this.cardsMatchHandler(card1, card2);\n\n this.resetClicks();\n }\n }", "function select (cards) {\n cards.addEventListener(\"click\", (e) => {\n if (clickReset === 0) {\n stopWatch ();\n clickReset = 1;\n }\n console.log(cards.innerHTML);\n // put the first click and the second click into variables that can be used\n const firstCard = e.target;\n const secondCard = clickedCards[0];\n\n\n // This will record if we have a currently opened card,\n // I use the ignore css class to make sure we are not matching the same card, this is utlising css pointer-events\n\n if (clickedCards.length === 1) {\n cards.classList.add('open' , 'show', 'ignore');\n clickedCards.unshift(firstCard);\n\n // Comparision of cards for further use\n comparingCards(firstCard, secondCard);\n\n // This will record if we do not having an currently opened cards\n\n } else {\n firstCard.classList.add('open' , 'show', 'ignore');\n clickedCards.push(firstCard);\n }\n });\n}", "function click ( e ) {\r\n \r\n //If a user click the next card while the timer is set, the two clicked cards will be judged right away\r\n if ( timer ) {\r\n clearTimeout( timer );\r\n judge();\r\n }\r\n \r\n let elm = e.target;//The clicked card\r\n elm.innerHTML = cards[ elm.index ];//Turn up the clicked card\r\n \r\n if ( !firstCard ) {\r\n //If a user didn't select any card yet, the clicked card is the first card.\r\n firstCard = elm;\r\n \r\n } else if ( firstCard.index == elm.index ) {\r\n //If a user selected the same card two times, exit if() loop\r\n return;\r\n \r\n } else {\r\n //If a user selected the different two cards\r\n secondCard = elm;//The second card is the newly clicked card\r\n timer = setTimeout( judge, 1000 );//Judge the clicked cards a second later\r\n \r\n }\r\n}", "function handleClickCard(event) {\n $(event.currentTarget).find('.backOfCard').addClass('hidden');\n console.log(event.currentTarget);\n if (firstCardClicked === null) {\n firstCardClicked = $(event.currentTarget);\n } else {\n secondCardClicked = $(event.currentTarget);\n attempts++;\n var firstPick = firstCardClicked.find('.revealCard').css('background-image');\n var secondPick = secondCardClicked.find('.revealCard').css('background-image');\n turnClickHandlerOff();\n if (firstPick === secondPick) {\n console.log('The cards match!');\n matches++;\n firstCardClicked = null;\n secondCardClicked = null;\n turnClickHandlerOn();\n } else {\n setTimeout(function () {\n firstCardClicked.find('.backOfCard').removeClass('hidden');\n firstCardClicked = null;\n secondCardClicked.find('.backOfCard').removeClass('hidden');\n secondCardClicked = null;\n turnClickHandlerOn();\n }, 500);\n }\n displayStats();\n }\n}", "function onCardClicked() {\n //get the card that was clicked\n let selectedId = $(this).attr('id').replace('card-','');\n let selectedCard = cards[selectedId];\n\n if (selectedCard.isDisplayed() || openCards.length >= 2) {\n return;\n } else {\n //increment click counter\n moveCount++;\n $('.moves').text(moveCount);\n\n //check move count and decrement stars if needed.\n if (moveCount == 20) {\n $('#star-3').removeClass('fa-star');\n $('#star-3').addClass('fa-star-o');\n } else if (moveCount == 30) {\n $('#star-2').removeClass('fa-star');\n $('#star-2').addClass('fa-star-o');\n }\n\n //display the card.\n selectedCard.flip();\n\n //after short delay, check if there is a match.\n //this is done so that the cards do not immediately flip back\n //preventing you from seeing the 2nd card.\n setTimeout(function() {\n if (!findCardMatch(selectedCard)) {\n //add selected card to list of open cards\n openCards.push(selectedCard);\n\n if (openCards.length == 2) {\n //hide both cards\n openCards[0].flip();\n openCards[1].flip();\n openCards = [];\n }\n }\n }, 800);\n }\n}", "function handleCardClick (event) {\n\tif (\n\t\tevent.target !== firstCard &&\n\t\tevent.target !== secondCard &&\n\t\tevent.target.classList.contains('clicked') === false &&\n\t\tarrayOfClicked.length < 2\n\t) {\n\t\t// you can use event.target to see which element was clicked\n\t\tif (arrayOfClicked.length <= 1) {\n\t\t\tlet card = event.target;\n\n\t\t\tcard.classList.add('clicked');\n\t\t\tcard.style.backgroundColor = card.style.color;\n\t\t\tarrayOfClicked.push(card);\n\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\tif (i === 0 && arrayOfClicked.length === 1) {\n\t\t\t\t\tfirstCard = arrayOfClicked[i];\n\t\t\t\t} else if (i === 1 && arrayOfClicked.length === 2) {\n\t\t\t\t\tsecondCard = arrayOfClicked[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (firstCard === secondCard) {\n\t\t\tarrayOfClicked.splice(arrayOfClicked.indexOf(secondCard), 1);\n\t\t} else if (arrayOfClicked.length === 2) {\n\t\t\tnumAttempts++;\n\t\t\tscore = document.querySelector('#score');\n\t\t\tscore.innerText = '' + numAttempts;\n\t\t\tsetTimeout(function () {\n\t\t\t\tif (firstCard.style.color !== secondCard.style.color) {\n\t\t\t\t\tfor (i = 0; i < arrayOfClicked.length; i++) {\n\t\t\t\t\t\tlet thisCard = arrayOfClicked[i];\n\t\t\t\t\t\tthisCard.style.backgroundColor = '';\n\t\t\t\t\t\tthisCard.classList.remove('clicked');\n\t\t\t\t\t}\n\t\t\t\t\tfirstCard = null;\n\t\t\t\t\tsecondCard = null;\n\t\t\t\t} else {\n\t\t\t\t\tnumMatched += 2;\n\t\t\t\t\tfirstCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tsecondCard.style.border = '2px solid lightgreen';\n\t\t\t\t\tarrayOfMatched.push(firstCard);\n\t\t\t\t\tarrayOfMatched.push(secondCard);\n\t\t\t\t}\n\t\t\t\tarrayOfClicked = [];\n\t\t\t\tif (numMatched === numCards) {\n\t\t\t\t\tclearTimeout();\n\t\t\t\t\tscoreCounter.className = 'new-high-score';\n\t\t\t\t\tlet prevHighScore;\n\t\t\t\t\tlet newHighScore;\n\n\t\t\t\t\tif (numCards === 10 && localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('easyHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 10) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('easyHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 20 && localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('medHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 20) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('medHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tif (numCards === 30 && localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\tif (numAttempts < localStorage.getItem('hardHighScore')) {\n\t\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\t\tgameContainer.appendChild(newHighScore);\n\t\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (numCards === 30) {\n\t\t\t\t\t\tnewHighScore = document.createElement('h2');\n\t\t\t\t\t\tnewHighScore.className = 'new-high-score';\n\t\t\t\t\t\tnewHighScore.innerText = 'NEW HIGH SCORE! ' + numAttempts;\n\t\t\t\t\t\tgameContainer.append(newHighScore);\n\t\t\t\t\t\tlocalStorage.setItem('hardHighScore', numAttempts);\n\t\t\t\t\t}\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Easy\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Medium\"]').remove();\n\t\t\t\t\tdocument.querySelector('input[value=\"Reset Hard\"]').remove();\n\t\t\t\t\tresetEasyButton = document.createElement('input');\n\t\t\t\t\tresetEasyButton.type = 'button';\n\t\t\t\t\tresetEasyButton.value = 'Reset Easy';\n\t\t\t\t\tresetEasyButton.className = 'reset-button-class';\n\t\t\t\t\tresetEasyButton.id = 'reset-easy-button';\n\t\t\t\t\tresetMediumButton = document.createElement('input');\n\t\t\t\t\tresetMediumButton.type = 'button';\n\t\t\t\t\tresetMediumButton.value = 'Reset Medium';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-class';\n\t\t\t\t\tresetMediumButton.id = 'reset-medium-button';\n\t\t\t\t\tresetHardButton = document.createElement('input');\n\t\t\t\t\tresetHardButton.type = 'button';\n\t\t\t\t\tresetHardButton.value = 'Reset Hard';\n\t\t\t\t\tresetHardButton.className = 'reset-button-class';\n\t\t\t\t\tresetHardButton.id = 'reset-hard-button';\n\t\t\t\t\tgameContainer.append(resetEasyButton);\n\t\t\t\t\tgameContainer.append(resetMediumButton);\n\t\t\t\t\tgameContainer.append(resetHardButton);\n\t\t\t\t\tresetEasyButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetMediumButton.className = 'reset-button-end-class';\n\t\t\t\t\tresetHardButton.className = 'reset-button-end-class';\n\t\t\t\t}\n\t\t\t}, 1000);\n\t\t}\n\t}\n}", "function filpCard() {\r\n if (lockBoard) return;\r\n if (this === firstCard) return;\r\n this.classList.add('flip');\r\n\r\n if (!hasFlippedCard) {\r\n //First card clicked\r\n hasFlippedCard = true;\r\n firstCard = this;\r\n return;\r\n }\r\n //Second card clicked\r\n secondCard = this;\r\n checkForMatch();\r\n}", "function handleCardClick(event) {\n if ($(event.currentTarget).hasClass(\"isFlipped\") || twoCardsClicked) {\n return; // if a card is already flipped or there are two cards already clicked then clicks will be temporarily disabled\n }\n if (firstCardClicked === null) {\n firstCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n firstCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the first clicked card\n } else {\n secondCardClicked = $(event.currentTarget).addClass(\"isFlipped\");\n secondCardClickedImageURL = event.currentTarget.children[2].style.backgroundImage; // image url of the second clicked card\n twoCardsClicked = true;\n if (firstCardClickedImageURL !== secondCardClickedImageURL) { // actions to take if the two clicked cards don't match\n misMatchedCardsAction();\n } else { // actions to take if the two clicked cards match\n matchedCardsAction();\n }\n }\n displayStats(); // calculate and show stats\n}", "function selectCard(e) {\n\tselectedCard = e.target;\n\n\t// First Card\n\tif (\n\t\tselectedCard.className.includes('card') &&\n\t\tselectedCard.parentElement.classList != 'container' &&\n\t\tcards.firstCard === null\n\t) {\n\t\tselectedCard.parentElement.classList.toggle('flip');\n\t\tcards.firstCard = selectedCard;\n\n\t\t// Ensures the same Card Cannot be picked Twice\n\t} else if (\n\t\t(cards.firstCard != null && e.target === cards.firstCard.parentElement) ||\n\t\t(cards.firstCard != null && e.target === cards.firstCard)\n\t) {\n\t\treturn;\n\t}\n\n\t// Second Card\n\telse if (\n\t\tselectedCard.className.includes('card') &&\n\t\tselectedCard.parentElement.classList != 'container' &&\n\t\tcards.secondCard === null\n\t) {\n\t\tselectedCard.parentElement.classList.toggle('flip');\n\n\t\tcards.secondCard = selectedCard;\n\n\t\t// Compare Cards\n\t\tcomparisonCheck(cards.firstCard, cards.secondCard);\n\n\t\t// Moves Counter\n\t\tmoves.innerText++;\n\n\t\t// Reset Cards Value\n\t\tcards.firstCard = null;\n\t\tcards.secondCard = null;\n\t\treturn cards;\n\t}\n}", "function matchOrNoMatch(card){\n let cardClassName = card.firstElementChild.className;\n if (openCards.length === 0) { // first card\n addToOpenCards(cardClassName);\n } else {\n if (openCards.indexOf(cardClassName) === -1) { // Not a match (either because just 1 card open or really no match)\n if (openCards.length % 2 !== 0) { // really not a match\n window.setTimeout(changeClass,3000,cardClassName,\"card\"); // Hide current card\n window.setTimeout(changeClass,3000,openCards.pop(),\"card\"); // Remove previous card from openCards, and hide it\n\n // disables all mouse events (to ensure no additional card can be picked while 2 are open)\n var allCards = document.getElementsByClassName(\"card\");\n for (var i = 0; i < allCards.length; i++) {\n allCards[i].style.pointerEvents = \"none\";\n }\n\n } else {\n addToOpenCards(cardClassName); // Add card always if opening the first of a pair of cards\n }\n } else { // yay, it's a match !!!\n addToOpenCards(cardClassName);\n changeClass(cardClassName,\"card match\");\n }\n }\n}", "function handleCardClick(event) {\n\t// you can use event.target to see which element was clicked\n\n\t// prevent selecting additional cards during no match delay\n\tif (selection1 !== 0 && selection2 !== 0) return;\n\n\t// console.log('you just clicked', event.target);\n\tconst cardClass = event.target.className;\n\n\tif (event.target.className === 'matched') {\n\t\tconsole.log('Cannot reselect this card!');\n\t\treturn;\n\t}\n\n\tattempts++;\n\tdisplayAttempts();\n\n\tevent.target.style.backgroundColor = `${colorMapObject[cardClass]}`;\n\n\tif (selection1 === 0) {\n\t\tselection1 = cardClass;\n\t\telement1 = event.target;\n\t} else if (selection2 === 0) {\n\t\tif (event.target === element1) return;\n\t\tselection2 = cardClass;\n\t\telement2 = event.target;\n\n\t\tif (selection1 === selection2) {\n\t\t\tmatch = true;\n\t\t\tselection1 = 0;\n\t\t\tselection2 = 0;\n\t\t\telement1.className = 'matched';\n\t\t\telement2.className = 'matched';\n\t\t\tmatches += 2;\n\t\t\tdisplayMatches();\n\t\t} else {\n\t\t\tmatch = false;\n\t\t\tlet noMatchTimeout = setTimeout(function() {\n\t\t\t\telement1.style.backgroundColor = defaultCardColor;\n\t\t\t\telement2.style.backgroundColor = defaultCardColor;\n\t\t\t\tselection1 = 0;\n\t\t\t\tselection2 = 0;\n\t\t\t}, noMatchDelay);\n\t\t}\n\t}\n}", "function clicktarget(evt){\n setopen(evt); //sets card to open state\n addcardtoList(evt);// adds card to list to be check for match\n removeclickevent(evt);// removes the click listener\n\n if (cardlist.length ==2){ //if 2 cards exists it will compare via Checkmatch()\n\n setTimeout(checkmatch,200); //delay so users can see the 2nd card clicked\n\n }\n else {\n\n }\n }", "function checkMatch(clickedCard) {\n if (openedCards[0].firstElementChild.HTMLImageElement.src === openedCards[1].firstElementChild.HTMLImageElement.src) {\n makeMatch(openedCards);\n } else {\n clearOpened(openedCards);\n };\n}", "function click(card) {\n // Create Click Event for card\n card.addEventListener(\"click\", function() {\n if(firstClick) {\n // Call Start the timer function\n startTimer();\n // Change the First Click value\n firstClick = false;\n }\n const secondCard = this;\n const firstCard = openedCards[0];\n // Opened card\n if(openedCards.length === 1) {\n card.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n // Call the Compare function\n compare(secondCard, firstCard);\n } else {\n secondCard.classList.add(\"open\", \"show\", \"disable\");\n openedCards.push(this);\n }\n });\n}", "function checkMatch() {\n // if firstCard equals secondCard then disable both cards click events else remove flip class.\n if (firstCard.dataset.card === secondCard.dataset.card){\n disableCards();\n } else {\n unflipCards();\n }\n}", "function doCardsMatch() {\n if(firstCard.dataset.icon === secondCard.dataset.icon) {\n cardArray.push(firstCard);\n cardArray.push(secondCard);\n disable();\n return;\n };\n unflippingCards(); \n}", "function clickOnCard(e) {\n // if the target isn't a card, stop the function\n if (!e.target.classList.contains('card')) return;\n // if the user click the first time on a card (-->that is flip the first card) the timer starts\n if(isFirstCardclicked) {\n startTimer();\n isFirstCardclicked=false;\n }\n if (openCards.length<2) {\n let cardClicked = e.target;\n console.log(\"clicked \"+e.target.querySelector('i').classList);\n // show the card\n showSymbol(cardClicked);\n // save the card clicked\n addOpenCard(cardClicked);\n }\n if (openCards.length == 2) {\n // to stop from further clicking on cards until animation is finished\n deck.removeEventListener('click', clickOnCard);\n checkMatch(openCards[0], openCards[1]);\n updateMovesCounter();\n updateRating();\n }\n}", "function cardClick() {\n\tif (clickedCards.length === 2 || matchedCards.includes(this.id)) {\n\t\treturn;\n\t}\n\tif(clickedCards.length === 0 || this.id != clickedCards[0].id){\n\n\t\tif(timeTrigger){\n\t\t\ttimerStart();\n\t\t\ttimeTrigger = false;\n\t\t}\n\t\tthis.classList.add('show', 'open');\n\t\tclickedCards.push(event.target);\n\t\tdetermineAction();\n\t}\n\telse {\n\t\treturn;\n\t}\n\tsetRating(moves);\n}", "function clickCard(){\n //* define clickedCard as the element that received a click\n var clickedCard = $(this);\n // * call the function that will check for a match\n checkForMatch(clickedCard);\n}", "function flipCard() {\r\n //this - whatever card we have clicked \r\n //we're getting the card clicked id and store to the cardsArray arrayChosen but only the name \r\n let cardId = this.getAttribute('data-id')\r\n cardsChosen.push(cardsArray[cardId].name)\r\n cardsChosenIds.push(cardId)\r\n\r\n //flip the card when clicked\r\n this.setAttribute('src', cardsArray[cardId].img)\r\n\r\n //revert if two selected aren't the same\r\n if (cardsChosen.length === 2) {\r\n setTimeout(checkForMatch, 500)\r\n\r\n }\r\n\r\n }", "function other2Cards(){\n\tfirstClickedElement = null;\n\tfirstCard = null;\n}", "function cardClicked(event) {\n if (event.target.className === 'card' && clickedCards.length <2) {\n event.target.classList.add('open', 'show');\n addCardsToClickedCards(event);\n doCardsMatch(event);\n }\n}", "function areCardsEqual()\n{\n if(cards[cards_clicked[FIRST_CARD_CLICKED]] === cards[cards_clicked[LAST_CARD_CLICKED]])\n return YES;\n\n return NO;\n}", "function compareCards(e) {\n //track number of clicks\n ++clickCount;\n //limit click count to 2\n while (clickCount > 2) {\n clickCount = 0;\n ++clickCount;\n }\n\n //flag checks if game has started\n if (flag === true) {\n\n //sets the first selected card to variable\n if (clickCount === 1) {\n console.log(e);\n cardOne = e.currentTarget.children[1].firstElementChild.attributes[1].nodeValue;\n console.log(cardOne);\n selectedCardOne = e.delegateTarget.offsetParent;\n //sets the second selected card to variable\n\n } else {\n cardTwo = e.currentTarget.children[1].firstElementChild.attributes[1].nodeValue;\n\n selectedCardTwo = e.delegateTarget.offsetParent;\n // selectedCardTwoAccurate = e.delegateTarget .offsetParent.className;\n\n }\n //checks cards for match, mismatch, or duplicate selection\n if (clickCount === 2) {\n if (selectedCardOne != selectedCardTwo) { \n if (cardOne === cardTwo) {\n cardsMatched++;\n //Replace gifs with chekcs on match - LightSide\n if(cardOne === \"yoda.gif\"){\n $(\".yodagif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"hangif.gif\"){\n $(\".hangif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"leia-gif.gif\"){\n $(\".leiagif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"lightsaber.gif\"){\n $(\".lightsabergif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"obi.gif\") {\n $(\".obigif\").attr(\"src\", \"check.jpg\");\n }\n //Replace gifs with checks on match - Darkside\n if(cardOne === \"forseen.webp\"){\n $(\".forseengif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"trooper.gif\") {\n $(\".troopergif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"darthvader.gif\"){\n $(\".vadergif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"force.gif\"){\n $(\".forcegif\").attr(\"src\", \"check.jpg\");\n }\n if(cardOne === \"starship.gif\"){\n $(\".starshipgif\").attr(\"src\", \"check.jpg\");\n }\n\n } else {\n //flips cards back to hidden after 1 second delay\n setTimeout(() => {\n flipCards(selectedCardOne);\n flipCards(selectedCardTwo);\n }, 1000);\n }\n } else {\n alert(`Can't select the same card!`);\n }\n }\n\n } else {\n console.log(`game has not started`);\n }\n //Check to see if the user has won the game\n if (cardsMatched === 5) {\n gameWon = true;\n console.log(\"You won the game!\");\n displayEndVideo();\n }\n }", "function clickedCard() {\n$('li.card').on('click', function() {\n\tlet openCard = $(this);\n\ttoggleOpenShow(openCard);\n\tif(openCard.hasClass('open show disabled')\n\t\t&& allOpenedCards.length < 2) {\n\t\tallOpenedCards.push(openCard);\t\t\n\t}\t\t\n\tmatchedCard();\n\t});\n}", "function cardClick(){\n\tthis.classList.add('show', 'open');\n\tclickedCards.push(event.target);\n\tif(clickedCards.length === 2){\n\t\tmoves++;\n\t\tif(moves === 1){\n\t\t\ttimerStart();\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Move</span>`;\n\t\t} else if(moves >= 2 && moves <= 20) {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves green\">${moves} Moves</span>`;\n\t\t} else if(moves >= 21 && moves <= 29){\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves gold\">${moves} Moves</span>`;\n\t\t} else {\n\t\t\tmovesCounter.innerHTML = `<span class=\"moves red\">${moves} Moves</span>`;\n\t\t}\n\t\tif(clickedCards[0].innerHTML === clickedCards[1].innerHTML){\n\t\t\tmatching();\n\t\t\twinCheck();\n\t\t} else {\n\t\t\tnotMatching();\n\t\t}\n\t}\n\tcheckRating(moves);\n}", "function cardClick() {\n if (event.target.nodeName == \"LI\") {\n // Card area is clicked\n cardClicked = event.target;\n } else if (event.target.nodeName == \"I\") {\n // card icon is clicked\n cardClicked = event.target.parentElement;\n } else {\n return; // Empty deck area clicked\n }\n if (cardClicked === openCards[0]) {\n return;\n }\n}", "function selectCard(e) {\n let cardNode = e.target;\n let match;\n\n // only activate if card is clicked (not the deck)\n if (cardNode.getAttribute('class') === 'card') {\n\n // determin whether this is the first card selected\n if (cardSelected === false) {\n // show icon of card\n card1 = cardNode;\n flipCard(card1);\n\n // indicate that the first card has been selected\n cardSelected = true;\n } else {\n // show icon of card\n card2 = cardNode;\n flipCard(card2);\n\n // update the turn counter\n turns++;\n updateTurns(turns);\n\n // check whether the star need to be reduced\n reduceStars();\n\n // prevent other cards from being selected\n cardNode.parentNode.removeEventListener('click', selectCard);\n\n // check if selected cards are a match\n match = checkMatch(card1, card2);\n if (match) {\n // reinstate ability to select cards\n cardNode.parentNode.addEventListener('click', selectCard);\n\n // indicate that a pair has been found\n cardsMatched=cardsMatched+2;\n\n // determine if cards\n if (cardsMatched == CARDS) {\n // show congratulations panel and end game\n endGame();\n }\n } else {\n window.setTimeout(function(){\n flipCard(card1, 'reverse');\n flipCard(card2, 'reverse');\n // reinstate ability to select cards (after cards have been flipped)\n cardNode.parentNode.addEventListener('click', selectCard);\n }, 500);\n }\n\n // reset so that new card pairs can be selected\n cardSelected = false;\n }\n }\n}", "function clickCards(){\nlet allCards=document.querySelectorAll('.card');\n//click cards\nallCards.forEach(function(card){\n card.addEventListener('click',function(evt){\n //start timer at the first click\n if(newStart){\n newStart=false;\n startTimer();\n }\n //check if cards already clicked first and can't click more than two cards\n if(!card.classList.contains('open')&&!card.classList.contains('show')&&!card.classList.contains('match')&&openCards.length<2){\n openCards.push(card);\n card.classList.add('open','show');\n if (openCards.length==2){\n //count Moves\n countMoves();\n //remove stars\n removeStar();\n //match Cards\n if(openCards[0].dataset.card===openCards[1].dataset.card){\n matched();\n //finshi game if all cards are matched\n finishGame();\n } else {\n unmatched();\n }\n }}\n });\n});\n}", "Match() {\n // if there are two cards with the classes clicked\n if ($('.clicked').length === 2) {\n// Than seeing if they match\n if ($('.clicked').first().data('value') == $('.clicked').last().data('value')){\n $('.clicked').each(function() {\n $(this).css({\"background-color\": \"green\",}).animate({ opacity: 0 }).removeClass('unmatched');\n });\n $('.clicked').each(function() {\n $(this).removeClass('clicked');\n });\n\n game.checkWin();\n // using a time out function to make the to flip the cards back \n } else {\n setTimeout(function() {\n $('.clicked').each(function() {\n $(this).html('').removeClass('clicked');\n \n });\n }, 1000);\n }\n }\n }", "function clickCard() {\n deck.addEventListener('click', function(event) {\n if (event.target.classList.contains('card')) {\n cardClicks++;\n if (cardClicks === 1 || cardClicks === 2) {\n clickedCard();\n } else {\n resetTurn();\n }\n }\n })\n}", "function clickCard() {\n $(\".card\").click(function() {\n // Return the function if the card is open\n if ($(this).hasClass(\"open show\")) {\n return;\n }\n // Return if there are 2 opened cards\n if (openCards.length === 2) {\n return;\n }\n // Display the card symbol and add the card to openCards list\n $(this).addClass(\"open show\");\n openCards.push($(this));\n // Start runner if this is the first move\n if (moves === 0) {\n startRunner();\n }\n // Check if the cards match\n if (openCards.length === 2) {\n if (openCards[0][0].firstChild.className === openCards[1][0].firstChild.className) {\n setTimeout(addMatch,300);\n } else {\n setTimeout(removeClasses,1300);\n }\n // Increase moves after checking\n incrementMoves();\n }\n });\n }", "function matchCards() {\r\n\r\n // Function Call to flip 'this' particular Card\r\n flipCard(this);\r\n\r\n // Storing Id and Src of Clicked Cards\r\n id = $(this).attr('id');\r\n src = $($($(this).children()[1]).children()[0]).attr(\"src\");\r\n\r\n // Counting Number of Moves\r\n count += 1;\r\n if (count % 2 == 0) {\r\n moves = count / 2;\r\n $(\"#moves\").html(moves);\r\n // Function call to set stars as number of moves changes\r\n setRating();\r\n }\r\n\r\n // Pushing values in Array if less than 2 Cards are open\r\n if (hasSrc.length < 2 && hasId.length < 2) {\r\n hasSrc.push(src);\r\n hasId.push(id);\r\n\r\n // Turning off Click on first Card\r\n if (hasId.length == 1)\r\n $(this).off('click');\r\n }\r\n\r\n // Matching the two opened Cards\r\n if (hasSrc.length == 2 && hasId.length == 2) {\r\n if (hasSrc[0] == hasSrc[1] && hasId[0] != hasId[1]) {\r\n // Counting Pairs\r\n pair += 1;\r\n\r\n // Turning off Click on matched Cards\r\n $.each(hasId, function(index) {\r\n $('#' + hasId[index] + '').off(\"click\");\r\n });\r\n\r\n } else {\r\n // Flipping back unmatched Cards with a bit of delay\r\n $.each(hasId, function(index, open) {\r\n setTimeout(function() {\r\n flipCard('#' + open + '');\r\n }, 600);\r\n });\r\n\r\n // Turing on Click on first unmatched Card\r\n $('#' + hasId[0] + '').on(\"click\", matchCards);\r\n }\r\n\r\n // Emptying the Arrays \r\n hasSrc = [];\r\n hasId = [];\r\n }\r\n\r\n // Checking if all Cards are matched\r\n if (pair == 8) {\r\n endGame();\r\n }\r\n\r\n }", "function clickOnCard(evt) {\r\n let targetElement;\r\n if (evt.target.nodeName.toLowerCase() === 'li') {\r\n targetElement = evt.target;\r\n } else if (evt.target.nodeName.toLowerCase() === 'i') {\r\n targetElement = evt.target.parentNode;\r\n }\r\n if (targetElement) {\r\n let actionCard = memoryGame.playCard(targetElement.id);\r\n let secondElem;\r\n if (!memoryGame.isPlay) {\r\n targetElement.classList.add('open');\r\n targetElement.classList.add('show');\r\n }\r\n switch (actionCard[0]) {\r\n case 'activated':\r\n break;\r\n case 'matched':\r\n secondElem = document.getElementById(actionCard[1]);\r\n matchedCard(targetElement, secondElem);\r\n break;\r\n case 'deactivated':\r\n secondElem = document.getElementById(actionCard[1]);\r\n deactivatedCard(targetElement, secondElem);\r\n break;\r\n default:\r\n }\r\n updateScore();\r\n if (memoryGame.isEndGame()) {\r\n endGame();\r\n }\r\n }\r\n}", "function clicked(card) {\n card.addEventListener(\"click\",function(){\n \tcard.classList.add(\"show\", \"open\");\n\t stack.push(card);\n\t move();\n\t //when user open two card, compare them\n\t if(stack.length == 2){\n\t \t//same \n if(stack[0].innerHTML== stack[1].innerHTML){\n \t\tstack[0].classList.add(\"match\");\n \t\tstack[1].classList.add(\"match\");\n \t \tstack[1].removeEventListener(\"click\", this);\n \t \tstack.pop();\n \tstack.pop();\n \tnoOpenCard=noOpenCard+2;\n }\n //difference \n else{\n \tsetTimeout(function(){\n \tstack[0].classList.remove(\"show\",\"open\");\n \tstack[1].classList.remove(\"show\",\"open\");\n \tstack.pop();\n \tstack.pop();\n \t\t}, 300); \n }\n\t }\n result();\n })\n }", "function doCardsMatch(){\n if (firstCard === secondCard) {\n console.log(\"they match\");\n //create function\n firstCard = \"\";\n secondCard = \"\";\n firstCardIndex = 0;\n secondCardIndex = 0;\n } else {\n //create function\n $($(\"img\")[firstCardIndex]).css({\"height\": \"100%\", \"width\": \"100%\"});\n $($(\"p\")[firstCardIndex]).css(\"visibility\", \"hidden\");\n $($(\"img\")[secondCardIndex]).css({\"height\": \"100%\", \"width\": \"100%\"});\n $($(\"p\")[secondCardIndex]).css(\"visibility\", \"hidden\");\n firstCard = \"\";\n secondCard = \"\";\n firstCardIndex = 0;\n secondCardIndex = 0;\n }\n }", "function click (card) {\n card.addEventListener(\"click\", function() {\n if(initialClick) {\n clock();\n initialClick = false;\n }\n\n const currentCard = this;\n const previousCard = openCards[0];\n\n //open cards and compare them\n if(openCards.length === 1) {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n // card comparison conditional\n comparison(currentCard, previousCard);\n increaseMove();\n } else {\n\n card.classList.add(\"open\", \"show\", \"endclick\");\n openCards.push(this);\n\n }\n });\n}", "function matcher(card) {\n if (clicked(card)) {\n return;\n }\n displayer(card);\n opened(card);\n}", "function card_clicked() {\n if (board_clickable != true){\n return;\n }\n $(this).find('.back').hide();\n // $(this).find('.back').css({'transform' : \"perspective(600px) rotateY(180deg)\"});\n // $(this).find('.face').css({'transform' : \"perspective(600px) rotateY(0deg)\"});\n\n $(this).off('click');\n// check to find out if its the first card\n if (first_card_clicked === null) {\n first_card_clicked = this;\n console.log('first card clicked');\n //turns off first card click so you cant match same card\n var src = $(first_card_clicked).find('img').attr('src');\n cardInfo[src].onClick();\n return;\n }\n// Its the second card\n else {\n second_card_clicked = this;\n console.log('second card clicked');\n attempts++;\n display_stats();\n var first_card = $(first_card_clicked).find('img').attr('src');\n var second_card = $(second_card_clicked).find('img').attr('src');\n\n// compare the two cards\n //cards match\n if (first_card === second_card) {\n board_clickable = false;\n match_counter++;\n display_stats();\n console.log('card 1: ', first_card_clicked, 'card 2: ', second_card_clicked);\n console.log('first_card : ', first_card, 'second_card : ',second_card);\n setTimeout(function(){\n $(first_card_clicked).find('.front').hide();\n $(second_card_clicked).find('.front').hide();\n board_clickable = true;\n first_card_clicked = null;\n second_card_clicked = null;\n }, 1000);\n\n var src = $(second_card_clicked).find('img').attr('src');\n cardInfo[src].onMatch();\n\n if (match_counter == total_possible_matches) {\n mainTheme_song.volume = .7;\n mainTheme_song.play();\n $('#win').html(\"YOU WIN!!!\");\n $(\"#win\").show();\n $('#reset').show();\n pauseGameMusic();\n mainTheme_song.currentTime = 0;\n $('.music_on').show();\n }\n }\n //cards don't match\n else {\n board_clickable = false;\n resetCardsAfterNoMatch();\n }\n }\n}", "function handleCardClick(event) {\n\tlet clickedCard = event.target;\n\t// check whether card has been clicked\n\tfor (let card of allClickedCards) {\n\t\tif (card === clickedCard) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t// handle the first of the two clicks\n\tif (clicked.length === 0) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\t// handle the second of the two clicks\n\t} else if (clicked.length === 1) {\n\t\tclicked.push(clickedCard);\n\t\tallClickedCards.push(clickedCard);\n\t\tclickedCard.style.backgroundImage = `url(${clickedCard.classList[0]})`;\n\t\tresult = checkMatch(clicked[0].style.backgroundImage, clicked[1].style.backgroundImage);\n\t\tif (result === true) {\n\t\t\t// start the counter over\n\t\t\tfor (card of clicked) {\n\t\t\t\tcard.classList.add('glow');\n\t\t\t}\n\t\t\tclicked = [];\n\t\t\tupdateGuesses();\n\t\t\t// keep from re-clicking the card, take it out of the running\n\t\t} else {\n\t\t\tsetTimeout(function() {\n\t\t\t\tflipCards(clicked);\n\t\t\t\tclicked = [];\n\t\t\t}, 1000);\n\t\t\tallClickedCards.pop();\n\t\t\tallClickedCards.pop();\n\t\t\tupdateGuesses();\n\t\t}\n\t}\n\n\tif (allClickedCards.length === COLORS.length) {\n\t\tsetTimeout(function() {\n\t\t\tgameOver();\n\t\t}, 100);\n\t}\n}", "function openCards(card) {\n tempCards.push($(card).children()[0].className.slice(6));\n if (tempCards.length === 2){\n compareCards();\n }\n}", "function flipCard() {\n // Prevent the second click in the same card because if second click in the same card the matching will be true\n if (this === firstCard) return; // it's mean false || stop the Function here\n // To prevent the user to unflip the 3rd card if it already flip 2 cards\n // If true stop the Function\n if (stopEvents) return; // it's mean false || stop the Function here\n // Give the targeted card the class flip\n this.classList.add('flip');\n\n // if there's no cards has class flip when user click one\n if(!hasFlipped) {\n // Thin Change the hasFlipped boolean a value of true\n hasFlipped = true;\n // And Change the firstCard variable the value of 'this' (Clicked Card)\n firstCard = this;\n return; // And stop the Function here\n }\n\n // And if the last condition is false that mean there's a card has flipped, so the clicked card must be the second one\n // So Change the secondCard variable the value of 'this' (Clicked Card)\n secondCard = this;\n // And Change the hasFlipped boolean a value of true\n hasFlipped = false;\n\n // And now call the isMatch() Function to check if the 2 cards matched or not!\n isMatch();\n}", "function cardClicked(clickEvent) {\n\n //This will create a reference to the actual card clicked on.\n const cardElementClicked = clickEvent.currentTarget;\n\n //That event is passed to this function which accesses the \n //currentTarget to get element that is clicked during the event.\n const cardClicked = cardElementClicked.dataset.cardtype;\n\n //Adds flip class to the clicked card.\n cardElementClicked.classList.add('flip');\n\n //sets the current card to cardClicked if cardClicked is null\n if (currentCard) {\n\n //matchFound will be set to true if cardClicked is equal to \n //currentCard.\n const matchFound = cardClicked === currentCard;\n\n //Adds matched cards to array of cardsMatched\n if (matchFound) {\n cardsMatched.push(cardClicked);\n //If cardsMatched is equal to cardsLength the array is complete and \n //the game is over.\n if (cardsMatched.length === cards.length) {\n\n setTimeout(gameWon, 500);\n }\n\n // Reset.\n currentCard = null;\n } else {\n //setTimeout is used to delay the function for 500 milliseconds\n // so the user can process the image.\n setTimeout(() => {\n\n document\n .querySelectorAll(`[data-cardType=\"${currentCard}\"]`)\n .forEach(card => card.classList.remove('flip'));\n\n //Remove flip class from the card that was just clicked.\n cardElementClicked.classList.remove('flip');\n\n // Reset.\n currentCard = null;\n }, 500);\n }\n //Reset. \n } else {\n currentCard = cardClicked;\n }\n}", "function click(card) {\n //click a card\n card.addEventListener(\"click\", function() {\n //run the timer and set the isFirstClick to false to not refer to this statement again\n if (isFirstClick) {\n beginTime();\n isFirstClick = false;\n }\n //add cards to an open card array to prepare to compare them\n if(openCards.length === 1){\n //if one card has aready been clicked then ->\n const firstCard = openCards[0];\n const secondCard = this;\n //open the card up, show the icon and disable is being clicked again using the freeze class\n card.classList.add(\"open\", \"show\", \"freeze\");\n openCards.push(this);\n compareCards(firstCard, secondCard);\n\n } else if (openCards.length >= 2){\n //Do Nothing\n } else {\n //if this is the first card to be clicked then ->\n card.classList.add(\"open\", \"show\", \"freeze\");\n openCards.push(this);\n }\n });\n }", "handleClicksInCard (e) {\n const isPerson = getParent(e.target, 'span[data-person]')\n const isArea = getParent(e.target, 'span[data-place]')\n const isNotion = getParent(e.target, 'span[data-notion]')\n const isLink = getParent(e.target, 'span[data-link]')\n const isSource = getParent(e.target, 'span[data-source]')\n if (!isPerson && !isArea && !isNotion && !isLink && !isSource) return\n if (isSource) {\n const sourceId = parseInt(isSource.getAttribute('data-source'), 10) - 1\n return this.activateSource(sourceId)\n } else if (isPerson) {\n // const type = 'persons'\n // const value = isPerson.getAttribute('data-person')\n // return this.props.setFilter(type, value)\n } else if (isArea) {\n // const type = 'areas'\n // const value = isArea.getAttribute('data-place')\n // return this.props.setFilter(type, value)\n } else if (isNotion) {\n // const type = 'notions'\n // const value = isNotion.getAttribute('data-notion')\n // return this.props.setFilter(type, value)\n } else if (isLink) {\n const id = parseInt(isLink.getAttribute('data-link'), 10)\n return this.props.activatePlace(id, { smooth: true })\n }\n }", "function clickCard(event) {\n\n\tif (interval === null) {\n\t\tsetTime();\n\t}\n\n\t//Check there's not more than 2 cards clicked\n\tif (counter < 2) {\n\t\tvar element = event.target;\n\n\t\t//Show the card\n\t\telement.style.backgroundImage = cards[ids.indexOf(element.id)];\n\n\t\t//Check it's not the same card clicked twice\n\t\tif (previousCard !== element.id) {\n\t\t\t//Count a click\n\t\t\tcounter++;\n\n\t\t\t//Check if it's the 2nd card\n\t\t\tif (previousCard !== null) {\n\t\t\t\tcurrentCard = element.id;\n\n\t\t\t\t//Restart images\n\t\t\t\tvar currentPicture = document.getElementById(currentCard).style.backgroundImage;\n\t\t\t\tvar previousPicture = document.getElementById(previousCard).style.backgroundImage;\n\n\t\t\t\t//Check if both images are the same\n\t\t\t\tif (currentPicture === previousPicture) {\n\t\t\t\t\t//Initialices a temporizer to execute correct action\n\t\t\t\t\tsetTimeout(removeCards, 1000);\n\t\t\t\t\n\n\t\t\t\t//If they're different \n\t\t\t\t} else {\n\t\t\t\t\t//Substract the score\n\t\t\t\t\tscore += -5;\n\t\t\t\t\tshowScore();\n\t\t\t\t\t//Initialices a temporizer to execute wrong action\n\t\t\t\t\tsetTimeout(hideCards, 1000);\n\t\t\t\t}\n\t\t\t\n\t\t\t} else {\n\t\t\t\t//If it's the first, store the card for the next click\n\t\t\t\tpreviousCard = element.id;\n\t\t\t}\n\t\t}\n\t}\n}", "function Card1click(){\n console.log(\"card 1 clickt\");\n if(currentplayer)\n setcardstate(0, 0, 1);\n else\n setcardstate(0, 0, 2);\n}", "function compareCards(event) {\n if (symbolArray[0] == symbolArray[1]) {\n cardArray[0].classList.add('match');\n cardArray[1].classList.add('match');\n\n matchList += 2;\n }\n}", "function processClick(card) {\n //if card is not open/matched: open/flip it\n if (!card.classList.contains(\"card-open\") && !card.classList.contains(\"card-matched\")) {\n toggleCard(card);\n openCards.push(card);\n ++moves;\n displayMoves();\n dispStars();\n }\n //if two consecutive open cards do not match: flip them back over/close them\n if (openCards.length === 2 && !card.classList.contains(\"card-matched\")) {\n setTimeout(function() {\n for (let card = 0; card < openCards.length; card++) {\n toggleCard(openCards[card]);\n }\n openCards = [];\n }, 650);\n }\n //check if two open cards match: mark them as matched\n if (checkMatch(openCards[0], openCards[1])) {\n addClass(openCards[0], \"card-matched\");\n addClass(openCards[1], \"card-matched\");\n numMatchedCards += 2;\n openCards = [];\n //check if all cards have been matched: show modal if true\n if (numMatchedCards === 16) {\n setTimeout(function() {\n stopTimer();\n displayModal();\n }, 500);\n }\n } else { //display unmatched cards effects\n addClass(openCards[0], \"card-unmatched\");\n addClass(openCards[1], \"card-unmatched\");\n unmatchedCards = document.querySelectorAll('.card-unmatched');\n setTimeout(function() {\n for (let card = 0; card < unmatchedCards.length; card++) {\n removeClass(unmatchedCards[card], \"card-unmatched\");\n }\n }, 500);\n }\n}", "function turnCard(){\n\tif (this.classList.contains('open')) { //to avoid double click on the opened card...\n\t\n\t} else {\n\t\tif (animationFinished == false) { //to avoid to click on the third card before finishing matchCheck...\n\t\t} else {\n\t\t\tthis.classList.add('open', 'show');\n\t\t\tclickedCount ++;\n\t\t\tmoves.textContent = clickedCount;\n\t\t\topenedCard.push(this);\n\t\t\tif (openedCard.length === 2) {\n\t\t\t\tanimationFinished = false; \n\t\t\t\tmatchCheck(); \n\t\t\t} //once the second card was turned, call matchCheck...\n\t\t};\n\t};\n}", "function checkCardClickChoice(currentCardId, event) {\n var currentElement = event.target.parentElement.parentElement;\n\n if (goToSecondMove == true) {\n showCardClickCounter.innerText = cardClickCounter++ + 1;\n // if it is the second card which is openend ...\n clickDisabled = true;\n\n flipCard(currentElement, currentCardId);\n\n if (cardArr[oldId].matchingPair == cardArr[currentCardId].matchingPair) {\n setTimeout(function () {\n // cards matching is passed, set to both cards on matched status\n cardArr[oldId].isMatching = true;\n cardArr[currentCardId].isMatching = true;\n\n // search for opened cards, remove class open and set it to matching\n var matchingPair = document.querySelectorAll(\".open\");\n for (var i = 0; i < matchingPair.length; i++) {\n matchingPair[i].classList.remove(\"open\");\n matchingPair[i].classList.add(\"matching\");\n }\n oldId = 999;\n clickDisabled = false;\n }, 1000);\n\n // pairmatching was passed, next move is again the first of two cards to open\n goToSecondMove = false;\n checkIfCompleted();\n } else {\n setTimeout(function () {\n if (oldId != 999) {\n cardArr[oldId].isOpen = false;\n }\n cardArr[currentCardId].isOpen = false;\n\n // card wasn't matching, remove the class open from both opened cards\n var pairs = document.querySelectorAll(\".open\");\n for (var i = 0; i < pairs.length; i++) {\n pairs[i].classList.remove(\"open\");\n }\n oldId = 999;\n clickDisabled = false;\n }, 1500);\n\n // pairmatching was not passed, next move is again the first of two cards to open\n goToSecondMove = false;\n }\n } else {\n // if it is the first card of two which is openen .....\n //\n // set status of current card to open\n cardArr[currentCardId].isOpen = true;\n\n flipCard(currentElement, currentCardId);\n\n // store current Id in oldId\n oldId = currentCardId;\n\n // allow next time to go to test of pairmatching\n goToSecondMove = true;\n }\n }", "function isCardMatched(e) {\n if (e.target.className === 'card') {\n return e.target.classList.contains('match');\n }\n}", "checkMatch() {\n let firstUrl;\n\n $('.card-unmatched').on('click', (e) => {\n $(e.target).css('opacity', 1);\n $(e.target).removeClass('card-unmatched');\n $(e.target).addClass('selected');\n console.log(e.target.src);\n if ($('.selected').length === 1) {\n firstUrl = e.target.src;\n // console.log('first url is: ', firstUrl);\n }\n if ($('.selected').length === 2) {\n // console.log('second url is: ', e.target.src);\n if (e.target.src === firstUrl) {\n // console.log(`it's a match`);\n firstUrl = '';\n\n setTimeout(function () {\n $(e.target).css('opacity', 0);\n $(e.target).parent().css('opacity', 0);\n $('.selected')\n .css('display', 'none')\n .removeClass('selected')\n .toggleClass('card-back')\n .parent()\n .css('opacity', 0);\n }, 500);\n\n this.startCombo++;\n this.increaseScore();\n this.displayStats();\n this.checkWin();\n } else {\n setTimeout(function () {\n $(e.target).addClass('card-unmatched');\n $('.selected')\n .addClass('card-unmatched')\n .removeClass('selected')\n .css('opacity', 0);\n }, 400);\n\n this.checkLose();\n this.resetCombo();\n this.minusHP();\n this.displayStats();\n }\n }\n });\n }", "function compare(viewCard, previousCard) {\n // when 2 cards matched\n if(viewCard.innerHTML === previousCard.innerHTML){\n viewCard.classList.add('match');\n previousCard.classList.add('match');\n matchedCards.push(viewCard, previousCard);\n openedCards = [];\n // when all cards match\n completeCards();\n // when 2 cards not matched\n } else {\n // show the second card for a 900s\n setTimeout(function () {\n viewCard.classList.add('unmatch');\n viewCard.classList.remove('open');\n previousCard.classList.add('unmatch');\n previousCard.classList.remove('open');\n setTimeout(function() {\n viewCard.classList.remove('unmatch', 'show', 'remove');\n previousCard.classList.remove('unmatch', 'show', 'remove');\n }, 500);\n }, 500);\n openedCards = [];\n }\n}", "function secondChosen(event, info1) {\n\n\tif (event.target.className === \"flip-card-front\" || event.target.className === \"flip-cardm-front\") {\n\n\t\tconst chosenIndex2 = chosenCard.indexOf(event.target);\n\t\tconsole.log(chosenIndex2);\n\t\tchosenCardInner[chosenIndex2].classList.add(\"chosen\");\n\n\t\tconst chosenImgSecond = chosenImg[chosenIndex2];\n\t\tconsole.log(chosenImgSecond);\n\n\n\t\tconst chosenImgFirst = info1.chosenImgFirst;\n\t\tconst chosenIndex = info1.chosenIndex;\n\n\t\tconst infoAll = { chosenImgFirst, chosenIndex, chosenImgSecond, chosenIndex2 };\n\t\tconsole.log(infoAll);\n\n\t\tsetTimeout(compare, 1500, infoAll);\n\n\t} else {\n\t\tboard.forEach(item => {\n\t\t\titem.addEventListener(\"click\", (event) => { secondChosen(event, info1) }, { once: true });\n\t\t});\n\t};\n}", "function flipCard() {\n //get data-id attribute of card clicked and store in var cardId\n let cardId = this.getAttribute('data-id');\n console.log(\"User flipped \"+cards[cardId].rank);\n console.log(cards[cardId].cardImage);\n console.log(cards[cardId].suit);\n cardsInPlay.push(cards[cardId].rank);\n //update src attribute to image of card that was just clicked\n this.setAttribute('src', cards[cardId].cardImage);\n //checking if player picked two cards\n if (cardsInPlay.length === 2) {\n checkForMatch();\n }\n}", "handleClick(cardVal) {\n let state1 = deepcopy(this.state);\n state1.clicks += 1;\n\n let lastClicked = state1.lastClicked;\n\n //the first val of lastClicked is either the first val or a new Object\n lastClicked[0] = lastClicked[0] || {};\n //the second val of lastClicked is either the second val or a new Object\n lastClicked[1] = lastClicked[1] || {};\n // in js, false values include: false, null, 0, \"\", and undefined\n\n //first click\n if (lastClicked[0] == null) {\n lastClicked[0] = cardVal;\n return;\n }\n else { //second click\n if (lastClicked[0].value == lastClicked[1].value) {\n //it's a match, so change all the cards with that value in the board to matched = true\n for (let ii = 0; ii < state1.board.length; ++ii) {\n let c = state1.board[ii];\n if (c.value == cardVal) {\n c.matched = true;\n }\n }\n //reset the last clicked to both be null.\n lastClicked[0] = null;\n lastClicked[1] = null;\n }\n else {\n //not a match, reset lastClicked array\n //TODO set some sort of time out before flipping cards?\n lastClicked[0] = null;\n lastClicked[1] = null;\n }\n }\n\n this.setState(state1);\n }", "function isTwoCards() {\n\n // add card to array of cards in play\n // 'this' hasn't been covered in this prework, but\n // for now, just know it gives you access to the card the user clicked on\n \n //have to fix reset on number of lives still\n \n \t\t\n\n var cardType = this.getAttribute('data-card');\n var cardId = this.getAttribute('id');\n\n\n if (lastCardClikedID==cardId){\n \talert('Naughty you clicked the same card twice');\n \tlastCardClikedID=cardId;\n }\t\n\n else {\n \n \t \tif (cardType==='king'){\n\tthis.innerHTML = '<img src=\"images/KDiamonds 12.png\" alt=\"King of Diamonds\" title =\"king\"/>';}\n\telse if (cardType==='queen')\n\t{\n\t\tthis.innerHTML = '<img src=\"images/QDiamonds 12.png\" alt=\"Queen of Diamonds\" title = \"queen\" />';\n\t}\n\n\n cardsInPlay.push(cardType);\n \n // if you have two cards in play check for a match\n\n\n\n if (cardsInPlay.length === 2) {\n\n // pass the cardsInPlay as an argument to isMatch function\n isMatch(cardsInPlay, numberOfClicks, numberOfCards);\n\n\n // clear cards in play array for next try\n cardsInPlay = [];\n \n\n\n }\n\n lastCardClikedID=cardId;\n numberOfClicks+=1;\n\n\n if(numberOfClicks>(numberOfCards*2)-1){\n \talert('Game Over');\n \tnumberOfClicks=0;\n \treStart();\n }\n\t\t\n }\n\n}", "function clickedCard() {\n if (event.target.classList.contains('card')) {\n event.target.classList.add('open', 'show', 'temp');\n tempArray.push(event.target);\n if (tempArray.length == 2) {\n if (tempArray[0] != tempArray[1]) {\n move++;\n moves.innerHTML = move;\n checkMatch();\n if (move === 15) {\n stars.children[2].classList.add('hide');\n starsArray.pop();\n } else if (move === 19) {\n stars.children[1].classList.add('hide');\n starsArray.pop();\n }\n } else {\n tempArray.splice(1);\n }\n }\n }\n}", "function isTwoCards() {\n\tcardsInPlay.push(this.getAttribute('data-card')); //add clicked card's data to cardsInPlay\n\tthis.firstChild.setAttribute('style', 'display: block;'); //allow img to be displayed\n\t\n\tif (cardsInPlay.length === 2) {\n\t\tisMatch(cardsInPlay);\n\t\tcardsInPlay = [];\n\t}\n}", "function click (card){\n card.addEventListener(\"click\",function(){\n const presentCard = this;\n const previousCard = openCard[0];\n if(openCard.length === 1){\n\n card.classList.add(\"open\",\"show\",\"disabled\");\n openCard.push(this);\n compare(presentCard,previousCard);\n }else{\n presentCard.classList.add('open','show','disabled');\n openCard.push(this);\n }\n }\n )\n\n }", "function handleCardClick(e) {\n var elem = findCard(e.target);\n if (clickCount === 1 && !traversedArr.includes(elem.getAttribute(\"name\"))) {\n\n if (elem != chosenArr[0]) {\n var cardColor = elem.getAttribute(\"name\");\n elem.id = \"chosen-two\";\n console.log('SECOND card choice -->', cardColor, elem.id);\n chosenArr.push(elem);\n flipCard(elem);\n clickCount++\n console.log('click count', clickCount);\n }\n else {\n console.log('Same Box Chosen')\n }\n }\n\n if (clickCount === 0 && !traversedArr.includes(elem.getAttribute(\"name\"))) {\n elem.id = \"chosen-one\";\n var cardColor = elem.getAttribute(\"name\");\n console.log('FIRST card choice -->', cardColor, elem.id);\n chosenArr.push(elem);\n flipCard(elem);\n clickCount++\n console.log('click count', clickCount);\n\n }\n if (clickCount === 2) {\n if (chosenArr[0].getAttribute(\"name\") === chosenArr[1].getAttribute(\"name\")) {\n for (let elem of chosenArr) {\n elem.id = \"\";\n traversedArr.push(elem.getAttribute(\"name\"));\n }\n console.log('MATCH FOUND');\n\n chosenArr = [];\n clickCount = 0;\n console.log('clickCount reset to', clickCount);\n if (traversedArr.length === 10) {\n setTimeout(function () { displayWin() }, 1000);\n console.log('game won!');\n }\n }\n\n else {\n console.log('NO MATCH', chosenArr[0].getAttribute(\"name\"), chosenArr[1].getAttribute(\"name\"))\n setTimeout(function () { unFlipCard() }, 1000);\n\n console.log('clickCount reset to', clickCount);\n chosenArr = [];\n }\n }\n e.preventDefault;\n // ... you need to write this ...\n}", "function flipCard(evt) {\n\tif (evt.target !== evt.currentTarget) {\n\t\tconst clickedCard = evt.target;\n\t\tclickedCard.classList.add('show', 'open');\n\t\tflippedCard.push(clickedCard);\n\t\t\t\t\n\t\t\t//if the list already has another card, check to see if the two cards match\n\t\tif (flippedCard > 2){\n\t\t\tfirstCard.classList.remove('show', 'open');\n\t\t\tsecondCard.classList.remove('show', 'open');\n\t\t}\n\t\tconst firstCard = flippedCard[0];\n\t\tconst secondCard = flippedCard[1];\n\n\n\t\tif (firstCard && secondCard) {\n\t\t\tcardMoves +=1 ;\n\t\t\tnumMoves.innerHTML = cardMoves;\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tif (flippedCard.length === 2 && firstCard.innerHTML == flippedCard[1].innerHTML && \n\t\t\tfirstCard.innerHTML === flippedCard[1].innerHTML){\n\t\t\t//if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one)\n\n\t\t\tclickedCard.classList.add('match');\n\t\t\tfirstCard.classList.add('match')\n\t\t\tconsole.log('match!!');\t\n\t\t\tflippedCard = [];\n\t\t\tmatchedCard.push(firstCard, secondCard);\n\t\t\tgameWon();\n\n\t\t}else if (flippedCard.length === 2 && firstCard.innerHTML != flippedCard[1].innerHTML){\n\t\t\tconsole.log('no match');\n\n\t\t\tsetTimeout(wait, 1000);\n\t\t\tfunction wait(){\n\t\t\t\tfirstCard.classList.remove('show', 'open');\t\t\t\n\t\t\t\tsecondCard.classList.remove('show', 'open')\n\t\t\t\t\n\t\t\t}\n\t\t\tflippedCard = [];\n\t\t}else {\n\t\t\tconsole.log('select another');\n\t\t}\n\t}\n\n\tevt.stopPropagation();\n}", "function checkForMatch(){\n let itsMatch = firstCard.dataset.name === secondCard.dataset.name;\n itsMatch ? disableCards() : unflipCards();\n}", "function matchCards(previousCard, currentCard) {\n previousCard.status = \"match\";\n $(previousCard.dom).toggleClass(\"open match squash-card\");\n $(currentCard.dom).toggleClass(\"open match squash-card\");\n\n setTimeout(function () {\n $(previousCard.dom).toggleClass(\"squash-card\");\n $(currentCard.dom).toggleClass(\"squash-card\");\n previousCard.dom = null;\n }, 500);\n}", "function whenClicked(card){ \r\n \r\n card.addEventListener(\"click\", function(){\r\n \r\n \r\n if (openedCards.length===1){\r\n \r\n \r\n const currentCard=this;\r\n const previousCard=openedCards[0];\r\n\r\n \r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n\r\n compare(currentCard,previousCard);\r\n\r\n \r\n }else{\r\n card.classList.add(\"open\", \"show\", \"disable\");\r\n openedCards.push(this);\r\n }\r\n }\r\n\r\n );\r\n\r\n}", "cardsMatchHandler(card1, card2) {\n if (card1.alt == card2.alt) {\n this.executeMatchActions(card1, card2);\n } else {\n this.executeMismatchActions(card1, card2);\n }\n this.removeClickClasss(card1, card2);\n }", "function clickOnCards(card){\n\n//Create card click event\ncard.addEventListener(\"click\", function(){\t\n\n//Add an if statement so that we can't open more than two cards at the same time\n\tif (openedCards.length === 0 || openedCards.length === 1){\n\tsecondCard = this;\n\tfirstCard = openedCards[0];\n\n\t//We have opened card\n\tif(openedCards.length === 1){\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n\n\t//We invoke the function to compare two cards\n\tcheck(secondCard, firstCard);\n\n\t}else {\n //We don't have opened cards\n\tcard.classList.add(\"open\",\"show\",\"disable\");\n\topenedCards.push(this);\n }\n\t}\n});\n}", "function appear(card){\n //OPEN first card or second card & compare between them\n function addCard() {\n // match timer start with first click\n const viewCard = this;\n const previousCard = openedCards[0];\n\n if (openedCards.length === 1) {\n card.classList.add('open', 'show', 'remove');\n openedCards.push(this);\n moves++;\n moveNumber.textContent = moves;\n compare(viewCard, previousCard);\n stars();\n } else {\n card.classList.add('open', 'show', 'remove');\n openedCards.push(this);\n stars();\n }\n\n if (isFirstClick === true) {\n timer();\n isFirstClick = false;\n }\n }\n card.addEventListener('click', addCard);\n}", "function handleCardClick(event) {\n\t// you can use event.target to see which element was clicked\n\tconsole.log('you just clicked', event.target);\n\tconst pick = event.target;\n\n\tif (card1 != '' && !pick.classList.contains('picked')) {\n\t\tif (numPick === 1) {\n\t\t\tnumPick++;\n\t\t\tcard2 = pick;\n\t\t\tconsole.log('card2');\n\t\t\tcard2.style.backgroundColor = card2.style.color;\n\t\t\tcard2.classList.add('picked');\n\t\t}\n\n\t\tif (numPick === 2 && card1.style.backgroundColor != card2.style.backgroundColor) {\n\t\t\tsetTimeout(function() {\n\t\t\t\tcard1.style.removeProperty('background-color');\n\t\t\t\tcard2.style.removeProperty('background-color');\n\t\t\t\tcard1.classList.remove('picked');\n\t\t\t\tcard2.classList.remove('picked');\n\t\t\t\tcard1 = '';\n\t\t\t\tcard2 = '';\n\t\t\t\tnumPick = 0;\n\t\t\t}, 1000);\n\t\t}\n\t\tif (numPick === 2 && card1.style.backgroundColor === card2.style.backgroundColor) {\n\t\t\tcard1.classList.add('matched');\n\t\t\tcard2.classList.add('matched');\n\t\t\tmatchedPairs++;\n\t\t\tconsole.log(matchedPairs);\n\t\t\tsetTimeout(function() {\n\t\t\t\tcard1 = '';\n\t\t\t\tcard2 = '';\n\t\t\t\tnumPick = 0;\n\t\t\t}, 1000);\n\t\t}\n\t}\n\tif (numPick === 0) {\n\t\tnumPick++;\n\t\tcard1 = pick;\n\t\tcard1.style.backgroundColor = card1.style.color;\n\t\tevent.target.classList.add('picked');\n\t\tconsole.log('card1');\n\t\tconsole.log(numPick);\n\t}\n\tlet allDivs = document.getElementsByClassName('back');\n\tif (matchedPairs === pushColorCounter) {\n\t\tsetTimeout(function() {\n\t\t\twhile (allDivs.length > 0) {\n\t\t\t\tallDivs[0].parentNode.removeChild(allDivs[0]);\n\t\t\t}\n\t\t\tCOLORS = [];\n\t\t\tpushColorCounter = 0;\n\t\t\tmatchedPairs = 0;\n\t\t\tnumPick = 0;\n\t\t\tcard1 = '';\n\t\t\tcard2 = '';\n\t\t}, 1000);\n\t}\n}", "function card_clicked() {\n card_flip(this);\n if (first_card_clicked === null) {\n first_card_clicked = this;\n first_card_back = first_card_clicked;\n first_card = $(this).find('.back').find('img').attr('src');\n attempts++;\n disable_flip(this);\n\n }\n else {\n second_card_clicked = this;\n second_card_back = second_card_clicked;\n second_card = $(this).find('.back').find('img').attr('src');\n disable_flip(this);\n\n // First and second card comparison\n if (first_card === second_card) {\n match_counter++;\n first_card_clicked = null;\n second_card_clicked = null;\n accuracy = ((match_counter / attempts) * 100).toFixed(0);\n\n // Match counter to win\n if (match_counter === total_possible_matches) {\n window.alert(\"You Win!\")\n }\n else {\n return \"Keep Going.\"\n }\n }\n // If cards do not match\n else {\n allow_flip(first_card_clicked, second_card_clicked);\n setTimeout(card_flipback, 700);\n first_card_clicked = null;\n second_card_clicked = null;\n }\n display_stats();\n }\n}", "function Clicked(e){ // first I need to make sure that the user can't open > 2 cards in the same time\n if(OpCards.length<2){ // OpCards less than 2 then open it\n let pikedcard = e.target;\n if(pikedcard.classList.contains(\"card\")&& !pikedcard.classList.contains(\"open\",\"show\" , \"match\", \"notmatch\")){\n pikedcard.classList.add(\"open\" , \"show\");\n OpCards.push(pikedcard); //add it in OpCards array\n }\n \n if(OpCards.length == 2){ // to know if we have 2 cards in the array\n setTimeout(matchedCards, 1000);\n }}}", "function flipCard() {\n if (lockBoard) return;\n if (this === firstCard) return;\n\n this.classList.add('flip');\n\n if (!hasFlippedCard) {\n// click 1 when the player selects the card the flip card function fires\n hasFlippedCard = true;\n firstCard = this;\n\n return;\n }\n\n// click 2 sets the second card as this\n secondCard = this;\n\n checkForMatch();\n}", "function flipCard(e) {\n if (lockBoard) return;\n if (e.target.classList.contains(\"card\")) {\n e.target.classList.toggle(\"flipper\");\n }\n if (!hasFlippedCard) {\n //first click\n hasFlippedCard = true;\n firstCard = this;\n } else {\n // second click\n hasFlippedCard = false;\n secondCard = this;\n function checkMatch() {\n let img1 = firstCard.lastChild.getAttribute(\"style\");\n let img2 = secondCard.lastChild.getAttribute(\"style\");\n\n if (img1 === img2) {\n matchedPairs++;\n function disableCards() {\n firstCard.classList.add(\"disappear\");\n secondCard.classList.add(\"disappear\");\n firstCard.removeEventListener(\"click\", flipCard);\n secondCard.removeEventListener(\"click\", flipCard);\n }\n disableCards();\n\n console.log(\"It's a match!\");\n } else {\n // not a match\n // function unflipCards() {\n lockBoard = true;\n setTimeout(() => {\n console.log(\"flip back\");\n firstCard.classList.add(\"flipper\");\n secondCard.classList.add(\"flipper\");\n lockBoard = false;\n }, 600);\n }\n }\n checkMatch();\n }\n\n console.log({ firstCard, secondCard });\n}", "function cardClicked(event) {\n openCardsList.push(this);\n this.classList.add('open', 'show', 'disable');\n if (openCardsList.length === 2 && openCardsList[0].innerHTML === openCardsList[1].innerHTML) {\n match();\n addMoves();\n }\n if (openCardsList.length === 2 && openCardsList[0].innerHTML != openCardsList[1].innerHTML) {\n noMatch();\n addMoves();\n }\n if (!watch.isOn) {\n watch.start();\n }\n}", "function compareCards(openCards) {\n if (openCards[0].className === openCards[1].className) {\n matched(openCards);\n } else {\n flipBack(openCards);\n }\n}", "function setState(card){\n if(clickedCard === undefined){\n clickedCard = card;\n } else if(otherClickedCard === undefined){\n otherClickedCard = card;\n } \n if(clickedCard !== undefined && otherClickedCard !== undefined){\n checkMatch(clickedCard, otherClickedCard);\n }\n}", "function checkForMatch() {\n let isMatch = (firstCard.dataset.name === secondCard.dataset.name); \n if (isMatch) {\n disableCards();\n matchCount += 2; \n } else {\n unFlipCards(); \n }\n}", "function toggleAndAddCard() {\n const targetEvent = event.target;\n if (targetEvent.classList.contains('card') && openCards.length < 2 && !targetEvent.classList.contains('show')) {\n // console.log(\"A card was clicked.\")\n counter++;\n //This counter is to ensure that the timer only starts at the first card being clicked\n // console.log(counter);\n if (counter === 1) {\n startTimer();\n }\n displaySymbol(targetEvent);\n addCardToOpenCards(targetEvent);\n // If there are two open cards, it will check if they match\n // console.log(openCards);\n if (openCards.length === 2) {\n checkMatch();\n }\n }\n}", "cardMatch(card1, card2) {\n this.matchedCards.push(card1);\n this.matchedCards.push(card2);\n card1.classList.add('matched');\n card2.classList.add('matched');\n this.AudioFiles.match();\n if(this.matchedCards.length === this.cardsArray.length)\n this.victory();\n }", "function doCardsMatch(event) {\n if (clickedCards.length === 2) {\n if (clickedCards[0].innerHTML === clickedCards[1].innerHTML) {\n clickedCards[0].classList.add('match');\n clickedCards[0].classList.remove('open', 'show');\n clickedCards[1].classList.add('match');\n clickedCards[1].classList.remove('open', 'show');\n matchedCards.push(clickedCards);\n clickedCards.length = 0;\n moveCounter();\n gameComplete();\n } else {\n setTimeout(function() {\n clickedCards[0].classList.remove('open', 'show');\n clickedCards[1].classList.remove('open', 'show');\n clickedCards.length = 0;\n moveCounter();\n }, 800);\n }\n }\n}", "function checkForMatch() { //use in the flipCard function\n //Cards match - using data attribute in HTML\n if (firstCard.dataset.type === secondCard.dataset.type) {\n //dataset.type: to access to the data attribute that I called type in the HTML\n disableCards();\n } else {\n unflipCards();\n }\n }", "function firstClick() {\n const clickArea = document.getElementById(\"card-click\");\n const card = document.getElementById(\"card1\");\n clickArea.addEventListener(\"click\", (e) => {\n card.classList.add(\"card1-hover\");\n });\n\n const attributes = document.querySelectorAll(\".atr-player-card\");\n attributes.forEach((value) => {\n value.addEventListener(\"click\", attributeSelection);\n });\n}", "function clickCards() {\n\t$('.card').click(function() {\n\t\tdisplayCard(this);\n\t\taddCard(this);\n\t\tdoesCardMatch(openCards);\n\t\topenCards[0].addClass('open');\n\t\tif (openCards.length === 2) {\n\t\t\topenCards[0].removeClass('open');\n\t\t}\n\t});\n}", "function isMatch() {\n // With the HTML 5 data atrribute if the 2 cards has the same Data name || value\n // if true call the keepFlipped() Function\n firstCard.dataset.ico === secondCard.dataset.ico ? keepFlipped() : recoverCards(); // And if false call the recoverCards() function\n}", "function checkCard(){\n let cards = document.querySelectorAll('img')\n let cardNum1 = clickedNum[0]\n let cardNum2 = clickedNum[1]\n \n\n if (clicked[0] === clicked[1]){\n cards[cardNum1].removeEventListener('click', cardImgDisplay)\n cards[cardNum2].removeEventListener('click', cardImgDisplay)\n \n matched.push(clicked)\n \n } else {\n \n cards[cardNum1].setAttribute('src','images/TheOffice.jpeg')\n cards[cardNum2].setAttribute('src','images/TheOffice.jpeg')\n \n \n \n } \n \n clicked = []\n clickedNum = []\n score.textContent = matched.length\n if(matched.length === arr.length/2){\n won.textContent = 'You Found All 6 Matches!!!'\n score.textContent = 'You won!!!'\n \n }\n \n \n }", "function firstChosen(event) {\n\tif (event.target.className === \"flip-card-front\" || event.target.className === \"flip-cardm-front\") {\n\n\t\tselectLevel.setAttribute(\"disabled\", \"disabled\");\n\t\tselectLevelDiv.style.display = \"none\";\n\t\t\n\t\tconst chosenIndex = chosenCard.indexOf(event.target);\n\t\tconsole.log(chosenIndex);\n\t\tchosenCardInner[chosenIndex].classList.add(\"chosen\");\n\n\t\tconst chosenImgFirst = chosenImg[chosenIndex];\n\t\tconsole.log(chosenImgFirst);\n\n\t\tif (selectLevel.value === \"game-small\") {\n\t\t\tmessageBox[0].textContent = \"בחרו קלף שני\";\n\t\t} else {\n\t\t\tmessageBox[1].textContent = \"בחרו קלף שני\";\n\t\t};\n\n\t\tconst info1 = { chosenImgFirst, chosenIndex };\n\n\t\tconsole.log(info1);\n\n\t\tboard.forEach(item => {\n\t\t\titem.removeEventListener(\"click\", firstChosen);\n\t\t\titem.addEventListener(\"click\", (event) => { secondChosen(event, info1) }, { once: true });\n\t\t});\n\n\t};\n}", "function checkForMatch(){\n let isMatch = firstCard.dataset.name === secondCard.dataset.name\n\n isMatch ? disableCards() : unflipCards();\n }", "function clickCards(){\r\n let allCards = document.querySelectorAll('.card');\r\n let i, cardName;\r\n for (i = 0; i < allCards.length; i++) {\r\n allCards[i].setAttribute(cardName, deckOfCards[i]);\r\n }\r\n // To Read the card name use\r\n // allCards[i].getAttribute(cardName);\r\n let openCards = [];\r\n let initialClick = 0;\r\n\r\n // Add an event listener to each element of allCards\r\n // The function in forEach takes two parameters: the refernce to the value\r\n // stored in allCards[i] and the index i\r\n allCards.forEach(function(htmlText, arrayIndex){\r\n // The value sent from allCards[i] has an event listener to it that is\r\n // activated by clikcing. Clicking the card represented by htmlText will\r\n // write the index value to openCards, which will later be used to compare\r\n // if two selected cards are a match.\r\n console.log(\"forEach method called.\")\r\n\r\n allCards[arrayIndex].addEventListener(\"click\", function() {\r\n // If its the first card click, activate timer functionality\r\n\r\n if (initialClick == 0) {\r\n initialClick = 1;\r\n setTimer();\r\n }\r\n\r\n // Make sure the same card isn't being clicked twice\r\n if(arrayIndex == openCards[0]) return;\r\n console.log(\"arrayIndex = \", arrayIndex);\r\n\r\n // Add array number for card that has been clicked in openCards\r\n openCards.push(arrayIndex);\r\n\r\n // Check if there are too many cards open (timeout isn't over)\r\n if(openCards.length > 2) return;\r\n\r\n allCards[arrayIndex].classList.add('open', 'show');\r\n\r\n // clicked to compare cards.\r\n if(openCards.length >= 2) {\r\n moveCounter++;\r\n setMoves();\r\n setStars();\r\n\r\n // If two cards are open, compare their values. If they're a match,\r\n // update the CSS coresponding to their class 'match' and 'show'\r\n if(allCards[openCards[0]].firstChild.className == allCards[openCards[1]].firstChild.className) {\r\n\r\n // Match found\r\n\r\n allCards[openCards[0]].classList.remove('open');\r\n allCards[openCards[1]].classList.remove('open');\r\n allCards[openCards[0]].classList.add('match');\r\n allCards[openCards[1]].classList.add('match');\r\n // add to matimetchedCards for winning the game\r\n matchedCards++;\r\n\r\n // Clear the openCards array\r\n openCards = [];\r\n } else {\r\n // No match found. Reset the cards\r\n setTimeout(function() {\r\n allCards[openCards[0]].classList.remove('open','show');\r\n allCards[openCards[1]].classList.remove('open','show');\r\n\r\n // Clear the openCards array\r\n openCards = [];\r\n //seconds allowed for open cards\r\n },475);\r\n }\r\n }\r\n })\r\n });\r\n}", "function cardMatch(card1, card2)\n\t{\n\t\tcard1.addClass('match');\n\t\tcard2.addClass('match');\n\t\tpreviousCard = null;\n\t}", "function cardMatch () {\n if (cardsShow[0].querySelector('i').classList.value == cardsShow[1].querySelector('i').classList.value) {\n cardsShow[0].classList.add('match');\n cardsShow[1].classList.add('match');\n cardsShow[0].classList.remove('show', 'open');\n cardsShow[1].classList.remove('show', 'open');\n cardsMatched.push(cardsShow[0].innerHTML);\n cardsMatched.push(cardsShow[1].innerHTML);\n }\n}", "function matchCards() {\r\n if (cardOneVal === cardTwoVal) { // if the values of the data-card attribute are the same add class match.\r\n console.log('they match');\r\n cardOne.className += ' match';\r\n cardTwo.className += ' match';\r\n cardOne, cardTwo = undefined;\r\n } else if (cardOneVal != cardTwoVal && cardTwoVal != undefined) {\r\n console.log(\"they don't match\");\r\n cardOneVal = undefined;\r\n cardTwoVal = undefined;\r\n\r\n setTimeout(function() { //add a slight timer for the cards to be shown before they are flipped back when they don't match\r\n if (cardOneVal == undefined && cardTwoVal == undefined) {\r\n setTimeout(function() {\r\n cardTwo.classList.remove('show');\r\n cardOne.classList.remove('show');\r\n }, 250);\r\n\r\n setTimeout(function() {\r\n // console.log(\"card one: \" + cardOne + \" cardTwo: \" + cardTwo);\r\n cardOne.classList.remove('open');\r\n cardTwo.classList.remove('open');\r\n }, 600);\r\n }\r\n }, 600);\r\n }\r\n }", "function cardEvenClick(event){\n // check both opened or matched card\n let classes = $(this).attr(\"class\");\n if (classes.search('open') * classes.search('match') !== 1){\n // both should be -1\n return;\n }\n // start the game \n if (!gameStarted) {\n gameStarted = true;\n timeCount = 0;\n stopTime = setTimeout(startTimer, 1000);\n }\n // flipping to show the cards \n if (openCards.length < 2){\n $(this).toggleClass(\"open show\");\n openCards.push($(this));\n }\n // check openCards if they match or not\n if (openCards.length === 2){\n checkOpenCards();\n }\n}", "function findMatch() {\n // Show cards on click\n $(\".card\").on(\"click\", function() {\n \tif ($(this).hasClass(\"open show\")) { return; };\n \t// Animate clicked card in case it isn't opened yet\n \t$(this).toggleClass(\"open show animated pulse\");\n \t// Send card to array to open cards for future use\n \topenCard.push($(this));\n \tclicks += 1;\n \tmoves();\n \tstartTimer();\n \tlet first = openCard[0];\n \tlet second = openCard[1];\n \t// Check if cards have same symbol based on the class of the <i> element\n \tif (openCard.length === 2 && first.children().hasClass(second.children().attr(\"class\"))) {\n \t\tfirst.toggleClass(\"match pulse flash\");\n \t\tsecond.toggleClass(\"match pulse flash\");\n \t\topenCard.pop(second);\n \t\topenCard.pop(first);\n \t\tmatchedCard.push(second);\n \t\tmatchedCard.push(first);\n \t\t// Check if all cards have been matched already\n \t\tpopup();\n \t// In case cards don't match, add animation and then remove it\n \t} else if (openCard.length === 2 && !first.children().hasClass(second.children().attr(\"class\"))) {\n \t\tsetTimeout(function() {\n \t\t\tfirst.toggleClass(\"open show pulse shake\")\n \t\t}, 1000);\n \t\tsetTimeout(function() {\n \t\t\tsecond.toggleClass(\"open show pulse shake\")\n \t\t}, 1000);\n \t\tsetTimeout(function() {\n \t\t\tfirst.toggleClass(\"animated shake\")\n \t\t}, 1500);\n \t\tsetTimeout(function() {\n \t\t\tsecond.toggleClass(\"animated shake\")\n \t\t}, 1500);\n \t\t// Drop cards from array of open cards\n \t\topenCard.pop(second);\n \topenCard.pop(first);\n \t}\n })\n}", "async function clickHandler(event) {\n const currentCard = getCard(event);\n if (!currentCard || currentCard.isFlipped()) return;\n\n if (!timer.isRunning()) {\n timer.start();\n }\n\n let allCardsMatched = false;\n\n clickedCards.push(currentCard);\n\n if (clickedCards.length == 2) {\n numberOfMoves++;\n updateScore();\n const previousCard = clickedCards[0];\n clickedCards = [];\n if (currentCard.id() === previousCard.id()) {\n numberOfMatched++;\n if (numberOfMatched === NUMBER_OF_CARDS) {\n timer.stop();\n allCardsMatched = true;\n }\n await currentCard.show();\n await Promise.all([\n currentCard.markAs('matched'),\n previousCard.markAs('matched')\n ]);\n if (allCardsMatched) {\n updateWinMessage(numberOfMoves);\n showModal('win');\n }\n } else {\n await currentCard.show();\n await Promise.all([\n currentCard.markAs('not-matched'),\n previousCard.markAs('not-matched')\n ]);\n currentCard.hide();\n previousCard.hide();\n }\n } else {\n currentCard.show();\n }\n }", "function addCardClicked(card_number)\n{\n if(cards_clicked[FIRST_CARD_CLICKED] === NO_CARD_CLICKED) {\n cards_clicked[FIRST_CARD_CLICKED] = card_number;\n } else if(cards_clicked[LAST_CARD_CLICKED] === NO_CARD_CLICKED) {\n cards_clicked[LAST_CARD_CLICKED] = card_number;\n }\n}", "cardMatch(card1, card2) {\n this.matchedCards.push(card1);\n this.matchedCards.push(card2);\n card1.classList.add('matched');\n card2.classList.add('matched');\n this.calculateScore();\n if (this.matchedCards.length === this.cardArray.length)\n this.victory();\n }", "function cardClick() {\n console.log(\"you clicked this: \" + this.id);\n\n if (lastCardId === '') {\n lastCardId = this.id;\n console.log(this.id);\n //show card by putting letter in it.\n this.innerHTML = letters[this.id]; //move to jquery\n guessCounter = guessCounter + 1;\n scorediv = $(\"#score\");\n scorediv.html(guessCounter);\n\n } else if (letters[this.id] === letters[lastCardId]) {\n console.log(\"CORRECT SIR!\");\n //turn this and the one before to found\n me = $(this);\n me.addClass(\"found\");\n me.html(letters[this.id]);\n \n you = $(\"#\"+lastCardId);\n you.addClass(\"found\");\n you.html(letters[lastCardId]);\n lastCardId = '';\n\n guessCounter = guessCounter + 1;\n scorediv = $(\"#score\");\n scorediv.html(guessCounter);\n\n } else {\n console.log(\"you chose unwisely\");\n console.log(letters[this.id] + \" \" + letters[lastCardId]);\n console.log(this.id + \" \" + lastCardId);\n \n\n you = $(\"#\"+lastCardId);\n you.html(\" \");\n\n me = $(this);\n me.html(letters[this.id]);\n \n lastCardId = this.id;\n \n guessCounter = guessCounter + 1;\n scorediv = $(\"#score\");\n scorediv.html(guessCounter);\n }\n\n\n}", "function cardClicked(e) {\n\n const clickedCard = e.target;\n if (clickedCard.classList.contains('card') && !clickedCard.classList.contains('show')) {\n clickedCard.classList.add('show');\n addToOpenCards(clickedCard);\n }\n }" ]
[ "0.77947104", "0.7635646", "0.7528747", "0.7339774", "0.73222744", "0.7298105", "0.7261481", "0.72083944", "0.70965254", "0.70963365", "0.70742667", "0.70650405", "0.70599145", "0.70543504", "0.7036428", "0.70251215", "0.7016041", "0.7015723", "0.70014864", "0.6997069", "0.6950127", "0.6950089", "0.694943", "0.6937803", "0.6916311", "0.69127893", "0.68991315", "0.68927246", "0.6890467", "0.68685615", "0.6866778", "0.68638563", "0.6862041", "0.6853685", "0.6842006", "0.68390805", "0.683277", "0.68312854", "0.68310577", "0.6799016", "0.6791518", "0.6790785", "0.6790045", "0.67898506", "0.678428", "0.6782443", "0.6781849", "0.67817533", "0.6779539", "0.6775936", "0.67700905", "0.6768835", "0.6767984", "0.6767712", "0.67608035", "0.6751096", "0.67349565", "0.6721776", "0.67038846", "0.66779584", "0.6677362", "0.6676633", "0.6664294", "0.66613114", "0.6659466", "0.6655675", "0.6653586", "0.6652889", "0.664973", "0.66467035", "0.66460663", "0.6639642", "0.6632706", "0.66316533", "0.6614724", "0.6613854", "0.66099375", "0.6609878", "0.66094947", "0.66061884", "0.6603627", "0.6599009", "0.65982103", "0.65959907", "0.65955925", "0.6586016", "0.6585708", "0.6582449", "0.6576845", "0.6574828", "0.6565788", "0.65628046", "0.65496856", "0.65490556", "0.65486735", "0.65482515", "0.6546692", "0.65403014", "0.6539657", "0.6535082" ]
0.6707762
58
count moves user make and update to screen
function moveCounter() { moveCount++; $('.moves').text(moveCount); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function increaseMoveCounter() {\n state.totalMoves++;\n document.querySelector('.moves').textContent = state.totalMoves;\n }", "function updateMoves() {\n moves++;\n movesCounter.textContent = moves;\n}", "function moveCounter () {\n moves += 1;\n document.querySelector('.moves').textContent = moves;\n}", "function trackMoves(moveCount) {\n //moveCount++;\n let movesText = document.querySelector('.moves');\n movesText.innerHTML = moveCount;\n}", "function countMoves() {\n moves++;\n if (moves === 1) {\n movesCounter.innerHTML = `1 movimento`;\n } else {\n movesCounter.innerHTML = `${moves} movimentos`;\n }\n}", "function countMoves() {\n\tmovesCounter++;\n\tlet move = Math.floor(movesCounter/2);\n\n\t// Starting the timer\n\tif (movesCounter == 1) {\n\t\ttime();\n\t}\n\n\tif (move == 1) {\n\t\tmoves.textContent = move + ' Move';\n\t} else if (movesCounter > 1) {\n\t\tmoves.textContent = move + ' Moves';\n\t}\n}", "function calcMoves() {\n moves++;\n movesSpan.innerText = moves;\n updateStars();\n }", "function movesCount() {\n moves++;\n moveCounter.innerHTML = moves;\n}", "function countMoves() {\n moves++;\n if (moves === 1) {\n counter.textContent = `${moves} move`;\n } else {\n counter.textContent = `${moves} moves`;\n }\n}", "function movesCounter(){\n //increment counter by one each time\n counter++;\n //Updates moves inner html with the counter data\n moves.innerHTML = `Moves Made: ${counter}`;\n //updateStars function when the counter increments to a certain value\n updateStars();\n}", "function incrementCounter()\n\t{\n\t\tmovesCounter ++;\n\t\t$('#moves_id').html(movesCounter + \" Move(s)\");\n\t}", "function moveCounter() {\n app.moves++;\n app.counter.innerHTML = app.moves;\n if (app.moves == 1) {\n app.second = 0;\n app.minute = 0;\n app.hour = 0;\n startTimer();\n }\n}", "function updateMovesCounter() {\n\tmovesCounter += 1;\n\tmovesCounterElement.textContent = movesCounter;\n\tupdateStarRating(movesCounter);\n}", "function incrementMoveCounter() {\n ++scorePanel.moveCounter;\n $(\".moves\").text(scorePanel.moveCounter.toString().padStart(3, \"0\").concat(\" moves\"));\n}", "function moves(){\n document.getElementById(\"moves\").innerHTML=\"No. of moves made: \"+move;\n }", "function countMoves() {\n moves++;\n const displayMoves = document.querySelector(\"#moves\");\n displayMoves.innerHTML = moves + \" Moves\";\n}", "function numMoves(){\n\tcountMoves +=1;\n\tdocument.querySelector('.moves').textContent=countMoves;\n}", "function countingMoves() {\n countMoves += 1;\n moves.textContent = countMoves;\n starRating();\n}", "function countMoves () {\n textMove.innerHTML = `Moves: ${moves}`\n}", "function moveCounter() {\n moves++;\n movesPanel.innerHTML = moves.toString();\n}", "function moveCount () {\n var moves = parseInt($(\".moves\").text())\n moves += 1\n $(\".moves\").text(moves)\n stars( moves )\n}", "function incrementMoves() {\n moves ++;\n $(\".score-panel .moves\").text(moves);\n if (moves === 13) {\n decrementStars();\n }\n else if (moves === 21) {\n decrementStars();\n }\n }", "function updateMovesCounter() {\n numMoves++;\n if (numMoves == 1){\n moves.textContent = numMoves + \" Move\";\n }\n else {\n moves.textContent = numMoves + \" Moves\";\n }\n}", "function initializeMoveCounter() {\n clickCounter = 0;\n numberOfMoves = 0;\n countMoves();\n}", "function moves() {\n moveCount++;\n moveText.innerHTML = moveCount; \n}", "function incrementNoOfMoves() {\n let noOfMoves = parseInt(document.querySelector('.moves').textContent);\n noOfMoves++;\n manageStars(noOfMoves);\n document.querySelector('.moves').textContent = noOfMoves;\n}", "function doCounter()\n{\n\tcounters[playerLocation]++;\n\tcounterMoves++;\n}", "function moveCount(){\n moves++;\n const allMoves=document.querySelector('.moves');\n allMoves.innerHTML=moves+ ' Moves';\n starRating(moves);\n if(moves===1){\n startCount();\n }\n}", "function toCountMoves() {\n\tmoveCounter++;\n\tdocument.getElementById(\"item-moves\").innerHTML = moveCounter;\n}", "function incrementCounter() {\n numberOfMoves++;\n moveCounter.innerHTML = numberOfMoves;\n}", "function moveCounter() {\n if (clickedCards.length === 0) {\n moves++;\n moveNumber.innerHTML = moves;\n starRating(moves);\n }\n}", "function moveCount () {\n moves++;\n moveCounter.innerHTML = moves;\n if (moves == 1) {\n timer();\n }\n}", "function MoveCounter(){\n moves++;\n counter.innerHTML = moves;\n}", "function clickTracker() {\n totalClicks += 1;\n moves.innerHTML = `${totalClicks} Moves`;\n}", "function incrementCounter(){\n\tnumberOfMoves++;\n\tconsole.log(`total moves ${numberOfMoves}`);\n\tcounterForMoves.innerHTML = numberOfMoves;\n\tif(numberOfMoves == 1){\n\t\tstartTimer();\n\t}\n}", "function countMoves() {\n moveCount++;\n moves.textContent = (moveCount === 1) ? `${moveCount} Move` : `${moveCount} Moves`;\n}", "function countMoves(){\n movesNumber+= 1;\n moves.innerHTML=movesNumber;\n}", "function movesCounter(){\n count = count + 1;// count moves\n if(count ===1){startclockTime();}//once first card clicked times function invoked\n $('.moves').html(count);\n if(count === 16 || count === 24 || count === 30){\n starDrop(count)\n }\n}", "function countMoves() {\n numberOfMoves = clickCounter/2;\n moveCounter.innerHTML = '<span>' + numberOfMoves + ' Moves</span>';\n}", "function updateScoreBoard() {\n totalMoves++;\n $('#moves-counter').text(totalMoves);\n if (totalMoves > 15 && totalMoves <= 20) {\n setStars(2);\n } else if (totalMoves > 20) {\n setStars(1);\n }\n}", "function moveCounter() {\n cardMoves++;\n let counter = document.querySelector('.moves');\n counter.innerHTML = cardMoves;\n }", "function resetMoveCount() {\n\tmoveCount = 0;\n\t$('.moves').text(moveCount);\n}", "function moveCount() {\n debug(\"moveCount\");\n let count = parseInt(document.querySelector('.moves').innerHTML, 10);\n let x = count + 1;\n \n document.querySelector('.moves').innerHTML = x;\n if (x > 29 && x < 40) {\n document.querySelector('.stars').childNodes[2].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n if (x >= 40 && x < 49) {\n document.querySelector('.stars').childNodes[1].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n }", "function moveCounter() {\n amountOfMoves++;\n movesID.innerHTML = amountOfMoves;\n}", "function updateMoveCounter(moveNumber) {\n moves.textContent = moveCounter;\n}", "function trackMovesAndScore () {\n\tgameData.moves++;\n\t$('.moves').text(gameData.moves);\n\n\tif (gameData.moves > 15 && gameData.moves < 20) {\n\t\t$('.stars').html(gameData.starsHTML + gameData.starsHTML);\n\t} else if (gameData.moves >= 20) {\n\t\t$('.stars').html(gameData.starsHTML);\n\t}\n}", "function countMoves() {\n moves++;\n moveCounter.innerHTML = moves;\n\n if (moves === 1) {\n seconds = 60;\n countDown();\n }\n\n starsEarned();\n}", "function countMoves() {\n moves++; //moves the counter up one after each 2 cards are clicked//\n movesCounter.innerHTML = moves; //displays the values of moves on the page//\n if (moves === 1) {\n seconds = 0;\n minutes = 0;\n startTimer(); //go to startTimer function//\n }\n }", "function numberSteps() {\n\tlet countPlay = numMove + 1; \n\tnumMove = document.getElementById('moveCount').innerHTML = countPlay;\n}", "function countMoves() {\n\n num++;\n moves.textContent = num;\n\n if (num === 1) {\n //start the stopwatch on the first move\n startTimer();\n } else if (num > 1) {\n //reduce the number of stars based on number of moves\n if (num > 49) {\n endGame(); //moves limit for game\n } else if (num > 18) {\n stars[1].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n } else if (num > 12) {\n stars[2].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n }\n }\n}", "function countMove(numOfMoves) {\n let MoveShow = document.getElementById(\"moves\");\n MoveShow.textContent = numOfMoves + \" Moves\";\n }", "function addMove() {\n moves++;\n movesCount.innerHTML = moves;\n // start timer after first move\n if (moves == 1) {\n startTimer();\n }\n\n // Set rating after each move\n rating();\n }", "function moveCount() {\n const moveCount = document.querySelector('.moveCount');\n const moveCountModal = document.querySelector('.moves');\n\n moveCountNum++;\n moveCount.innerHTML = moveCountNum;\n //Increment the moves on the modal at the end\n moveCountModal.innerHTML = \"Moves: \" + moveCountNum;\n}", "updateCounter () {\n\t\tthis.model.incrementUserMovements();\n\t\t$writeInnerHTML( this.view.$counter, this.model.userMovements );\n\t}", "function updateMoves() {\n moves += 1;\n $('#moves').html(`${moves} Moves`);\n if (moves === 24) {\n addBlankStar();\n }\n else if (moves === 16) {\n addBlankStar();\n }\n}", "function addMove () {\n moves++;\n var movesCounter = document.querySelector('.moves');\n movesCounter.innerHTML = moves;\n}", "function incrementMovesNumber() {\n movesNumber++;\n MOVES_NUMBER_DISPLAY.textContent = movesNumber;\n}", "function addMove(){\n moves++;\n movesCounter.textContent = moves;\n //Set Rating:\n rating();\n}", "function addCount() {\n game.count++;\n $(\"#count\").text(game.count);\n $(\"#count\").addClass('animated bounce');\n setTimeout(() => {\n $('#count').removeClass('animated bounce');\n }, 800);\n newMove();\n }", "function incrementMoves(){\n movesCounter++;\n moves.innerHTML = movesCounter;\n //start the timer when the players clicks the first time\n if(movesCounter == 1){\n second = 0;\n minute = 0;\n hour = 0;\n startTimer();\n }\n\n if (moves.innerHTML > 25) {\n //adds one star if the moves are greator than 25\n addStars(1);\n }\n else if (moves.innerHTML > 15 && moves.innerHTML <=25){\n //adds two star if the moves are greator than 15 and equals to and smaller than 25\n addStars(2);\n }\n else {\n addStars(3);\n }\n }", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n textMoves();\n\n /*\n * Check to determine the player's rating after\n * certain number of moves have been exceeded\n */\n if (moves > 12 && moves < 19) {\n starsArray.forEach(function(star, i) {\n if (i > 1) {\n star.style.visibility = 'collapse';\n }\n });\n } else if (moves > 20) {\n starsArray.forEach(function(star, i) {\n if (i > 0) {\n star.style.visibility = 'collapse';\n }\n });\n }\n}", "function incrementMovesNumber() {\r\n movesNumber++;\r\n MOVES_NUMBER_DISPLAY.textContent = movesNumber;\r\n}", "function displayMoves() {\n\tmoves += 1;\n\t$('.moves').text(moves);\n\tif (moves === 1) {\n\t\t$('.mov').text('Move');\n\t\tstartTimer();\n\t} else {\n\t\t$('.mov').text('Moves');\n\t}\n\tif (moves === 20 || moves === 40) {\n\t\tremoveStar();\n\t}\n}", "function addMoves(){\n tareMoves++;\n let countMoves = document.querySelector(\".moves\");\n countMoves.innerHTML = tareMoves;\n}", "function countMove() {\n moves++;\n count.innerHTML = moves;\n if (moves < 20 && moves > 12) {\n starCount[1].style.display = 'none';\n } else if (moves > 20) {\n starCount[2].style.display = 'none';\n }\n}", "function displayMovesCounter() {\n const movesHTML = document.querySelector('.moves');\n movesHTML.innerHTML = moves;\n}", "function attemptedMoves() {\n moves++;\n numberofMoves.innerHTML = moves;\n finishedMoves.innerHTML = moves;\n}", "function updateMovement()\r\n{\r\n if(moved)\r\n {\r\n moveCount++;\r\n updateMoveCounter();\r\n addNewNumber();\r\n updateTable();\r\n moved=false;\r\n\r\n if(isWin())\r\n gameWon();\r\n }\r\n else if(isGameOver())\r\n {\r\n gameOver();\r\n }\r\n}", "function countMoves() {\n clicksCount++;\n movesCount.innerHTML = clicksCount;\n\n // when game starts, get initial time\n if (clicksCount == 1) {\n gameTimer();\n }\n\n // hide stars if clicks go beyond a certain value\n if (clicksCount > 25 && clicksCount < 35) {\n starRating[0].style.display = 'none';\n starRatingModal[0].style.display = 'none';\n } else if (clicksCount >= 35) {\n starRating[0].style.display = 'none';\n starRating[1].style.display = 'none';\n starRatingModal[0].style.display = 'none';\n starRatingModal[1].style.display = 'none';\n }\n}", "function movesConter() {\n console.log('function movesConter active');\n numberMoves += 1;\n moves.innerHTML = numberMoves + ' Move(s)';\n if (numberMoves === 1) {\n Timer();\n }\n starRating();\n}", "function updateMoves() {\n moves += 1;\n const move = document.querySelector(\".moves\");\n move.innerHTML = moves;\n if (moves === 16) {\n removeStar();\n starRating = 2;\n } else if (moves === 25) {\n removeStar();\n starRating = 1;\n }\n}", "function incrementMovement() {\n movements++;\n let movesSelected = document.querySelector(\".moves\");\n movesSelected.innerHTML = (movements);\n setStars();\n}", "function addMove() {\n\tmoves++;\n\tconst movesText = document.querySelector('.moves')\n\tmovesText.innerHTML = moves;\n}", "function moveCount() {\r\n moveMade += 1;\r\n\r\n move.innerText = moveMade;\r\n if (moveMade > 1) {\r\n\r\n wordMove.innerText = 'Moves';\r\n }\r\n\r\n}", "function newGameCounter(){\n moves = 0\n var movesReset = document.querySelector('.moves');\n movesReset.innerHTML = moves;\n}", "function IncrementMoves(moves){\n let shownMoves = document.querySelector('.moves');\n shownMoves.textContent = moves;\n}", "function addMove() {\n\tmoves++;\n\tconst movesText = document.querySelector('.moves');\n\tmovesText.innerHTML = moves;\n}", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n //start timer on first click\n if (moves == 1) {\n second = 0;\n minute = 0;\n hour = 0;\n startTimer();\n }\n // setting rates based on moves\n if (moves > 8 && moves < 12) {\n for (i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n else if (moves > 13) {\n for (i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "function moveCounter(){\n moves++;\n movesCounter.innerHTML = moves;\n\n if(moves === 1) {\n timeCounter();\n }\n\n if (moves === 10) {\n scorePanel.lastElementChild.style.visibility = 'hidden';\n } else if (moves === 20) {\n scorePanel.lastElementChild.previousElementSibling.style.visibility = 'hidden';\n }\n}", "function resetCounter() {\n numberOfMoves = 0;\n moveCounter.innerHTML = numberOfMoves;\n}", "function setMoves() {\r\nlet movesDOM = document.querySelector('.moves');\r\n if (moveCounter == 1) {\r\n movesDOM.innerHTML = `${moveCounter} Move`;\r\n } else {\r\n movesDOM.innerHTML = `${moveCounter} Moves`;\r\n }\r\n}", "function getMoveCount() {\n document.querySelector(\".moves\").innerText = moveCount;\n}", "function updateActionCounter() {\n actionCount += 1;\n document.querySelector('.moves').textContent = actionCount;\n //TODO: change to fa-star-o class\n if (actionCount == 27) {\n starPanel[0].classList.add('hidden-star');\n } else if (actionCount == 33) {\n starPanel[1].classList.add('hidden-star');\n }\n}", "function updateWinMessage(numberOfMoves) {\n $finalMoves.textContent = numberOfMoves.toString();\n $finalStars.textContent = starsFromMoves(numberOfMoves).toString();\n $finalTime.textContent = timer.value().toString();\n }", "function incrementMoves() {\n moves++;\n document.querySelector(\".moves\").innerText = moves;\n if (moves === 1) {\n document.querySelector(\".moves-text\").innerText = \"Move\";\n } else {\n document.querySelector(\".moves-text\").innerText = \"Moves\";\n }\n decreaseStars();\n}", "function incrementMove() {\n move++;\n let movesSpan = document.querySelector('.moves');\n movesSpan.innerHTML = move + \" Moves\";\n}", "function addMoves(){\n moves.innerText = movesCounter();\n}", "function updateMoves(){\n --moves;\n document.getElementById(\"Moves\").innerHTML = `Moves Left: ${moves}`;\n \n if(moves === 0){\n alert(\"You lose.\");\n movementButtons();\n }\n}", "updateNumberOfMoves(){\n this.nbMovesDone++\n const action = {type : 'newMovePlayed', value : this.nbMovesDone}\n\n // send changes to the redux store\n this.props.dispatch(action)\n }", "function movesCounterDisplay(counter){\n let mc = document.getElementsByClassName(\"moves\")[0];\n mc.textContent = counter;\n}", "function resetCounter() {\n\tmoveCounter = 0;\n\tdocument.getElementById(\"item-moves\").innerHTML = moveCounter;\n}", "function resetCounter(){\n turnCounter = 0;\n const moveCount = document.querySelector(\".moves\");\n moveCount.textContent = turnCounter;\n\n}", "function moveCount(){\ncounter ++;\ncounterDisplay.innerHTML = counter;\n}", "function resetMoves() {\n debug(\"resetMoves\");\n count = document.querySelector('.moves');\n\n count.innerHTML = \"0\";\n }", "function logClickCounter() {\n\tmovesMade.innerText = Number(movesMade.innerText) + 1;\n}", "function addMove(){\n gameMoves++;\n const movesText = document.querySelector('.moves');\n movesText.innerHTML = gameMoves;\n}", "function addMove() {\n moves++;\n movesLabel.innerText = moves;\n}", "function incrementMoves() {\n\tmoves++;\n\tdocument.querySelector('.moves').textContent = moves;\n\tif (moves === twoStar) {\n\t\tdocument.querySelector('.star-3').style.display = 'none';\n\t} else if (moves === oneStar) {\n\t\tdocument.querySelector('.star-2').style.display = 'none';\n\t}\n}", "function addMoves() {\n 'use strict'; // turn on Strict Mode\n moves++;\n movesCounter.innerHTML = moves;\n rating();\n //Starting timer when user makes its first click on the cards\n if (moves == 1) {\n second = 0;\n minute = 0;\n hour = 0;\n startTimer();\n }\n}", "function addMove(){\n moves += 1;\n $(\"#moves\").html(moves);\n if (moves === 14 || moves === 20){\n finalRating();\n }\n}" ]
[ "0.7853812", "0.7808541", "0.76460904", "0.7616671", "0.7587451", "0.75746083", "0.7565361", "0.7546887", "0.75449276", "0.7528779", "0.7520808", "0.7499674", "0.7475477", "0.7448939", "0.74280125", "0.7410912", "0.7370721", "0.7339002", "0.73389035", "0.73168457", "0.73129195", "0.7300581", "0.7267499", "0.7255796", "0.72491336", "0.724521", "0.72401893", "0.7235551", "0.72271574", "0.7221814", "0.72184986", "0.72064984", "0.7198466", "0.7174237", "0.7160588", "0.7158369", "0.7156424", "0.71493644", "0.7138798", "0.70906717", "0.7078046", "0.70775455", "0.70721686", "0.70648247", "0.7050356", "0.704472", "0.7022452", "0.7021411", "0.7000711", "0.7000042", "0.6997153", "0.6997148", "0.6989227", "0.69780624", "0.69687706", "0.69602066", "0.69282037", "0.6919141", "0.6913482", "0.69002104", "0.68997127", "0.6894717", "0.6892961", "0.68719536", "0.6868791", "0.6838362", "0.6837737", "0.6836234", "0.68339705", "0.6756216", "0.675008", "0.6744978", "0.67368454", "0.67361414", "0.6728463", "0.6722059", "0.6721508", "0.669683", "0.66657925", "0.66638273", "0.66552705", "0.66443366", "0.6641401", "0.6640628", "0.6628504", "0.66144544", "0.6601786", "0.6597025", "0.6574286", "0.6563577", "0.6558242", "0.6543829", "0.65347767", "0.6534355", "0.65297717", "0.6523189", "0.6519592", "0.65089506", "0.64978755", "0.6482753" ]
0.76627684
2
remove stars based on how many moves user make
function scoreCheck() { if(moveCount === 8 || moveCount === 16 || moveCount === 24) { removeStar(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function starCounter(moves) {\r\n if (moves >= 20 && moves <= 30) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(4);\r\n } else if (moves >= 31 && moves <= 40) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(3);\r\n } else if (moves >= 41 && moves <= 50) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(2);\r\n } else if (moves >= 51) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(1);\r\n } else {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(5);\r\n\r\n }\r\n}", "function adjustStarRating(moves) {\n if (moves === 16) {\n stars.children[0].remove();\n }\n else if (moves === 22) {\n stars.children[0].remove();\n }\n else if (moves === 32) {\n stars.children[0].remove();\n }\n else if (moves === 42) {\n stars.children[0].remove();\n }\n}", "function reduceMoves () {\n moves--;\n $('.moves').text(moves);\n if (moves === 6 || moves === 3) {\n $('.stars').find('li:last').remove();\n }\n}", "function manageStars(noOfMoves) {\n if (noOfMoves > 16 && noOfMoves <= 32) {\n let fifthStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[4];\n if (fifthStar != null)\n fifthStar.remove();\n }\n if (noOfMoves > 32 && noOfMoves <= 48) {\n let fourthStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[3];\n if (fourthStar != null)\n fourthStar.remove();\n }\n if (noOfMoves > 48 && noOfMoves <= 64) {\n let thirdStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[2];\n if (thirdStar != null)\n thirdStar.remove();\n }\n if (noOfMoves > 64 && noOfMoves <= 80) {\n let secondStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[1];\n if (secondStar != null)\n secondStar.remove();\n }\n if (noOfMoves > 80) {\n let firstStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[0];\n if (firstStar != null)\n firstStar.remove();\n }\n}", "function starCount() {\n if (moveCountNum === 20 || moveCountNum === 35) {\n removeStar();\n }\n}", "function reduceStars() {\n let starList = document.querySelectorAll('.fa-star');\n\n // determine whether star should be removed\n if(turns % STAR_REDUCTION === 0 && stars!== 1) {\n // change the rightmost star to an empty star\n let starLost = starList[starList.length-1];\n starLost.setAttribute('class', 'fa fa-star-o');\n stars--;\n }\n}", "function removeStars() {\n moves.innerHTML++;\n if (moves.innerHTML == 15) {\n starsChildren[2].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n if (moves.innerHTML == 20) {\n starsChildren[1].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n}", "function starRatings() {\n if (moves === 12) {\n const star1 = stars.firstElementChild;\n stars.removeChild(star1);\n result = stars.innerHTML;\n } else if (moves === 16) {\n const star2 = stars.firstElementChild;\n stars.removeChild(star2);\n result = stars.innerHTML;\n }\n}", "function removeStar() {\n const stars = Array.from(document.querySelectorAll('.fa-star'));\n if (moves === 12 || moves === 15 || moves === 18) {\n for (star of stars){\n if (star.style.display !== 'none'){\n star.style.display = 'none';\n numberOfStarts--;\n break;\n }\n }\n }\n}", "function removeStar() {\n if (moves <= 15) {\n starNum = 3;\n }\n if (moves > 15) {\n document.querySelector('.three').innerHTML = '<i></i>';\n starNum = 2;\n };\n if (moves > 30) {\n document.querySelector('.two').innerHTML = '<i></i>';\n starNum = 1;\n };\n}", "function recalcStars() {\n const stars = document.querySelector(\".stars\");\n if ((countStars===3 && countMoves === 11) || (countStars===2 && countMoves === 17) ) {\n stars.children[countStars-1].firstElementChild.classList.replace('fa-star','fa-star-half-o');\n countStars -= 0.5;\n }\n if ((parseInt(countStars)===2 && countMoves === 14) || (parseInt(countStars)===1 && countMoves === 20)) {\n countStars -= 0.5;\n stars.children[countStars].firstElementChild.classList.replace('fa-star-half-o','fa-star-o');\n }\n}", "function starRemoval(){\n\tstars = document.querySelectorAll('.fa-star');\n\tstarCount = countMoves;\n\tswitch (starCount) {\n\t\tcase 10:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}", "function updateStarCount()\n\t{\n\t\tif ( previousCard == null )\n\t\t{\n\t\t\tif ( movesCounter == 20 || movesCounter == 30 )\n\t\t\t{\n\t\t\t\t$('ul.stars li').first().remove();\n\t\t\t}\n\t\t}\t\t\t\t\n\t}", "function rating (){\n let stars = document.querySelector('.stars');\n let movesNumber = movesContainer.textContent;\n if((movesNumber == 16 && stars.firstChild) || (movesNumber == 24 && stars.firstChild)){\n stars.removeChild(stars.firstChild);\n } \n}", "function adjustRating() {\n const oneStar = document.querySelector(\".fa-star\").parentNode;\n if (moveCount == 28) {\n oneStar.parentNode.removeChild(oneStar);\n } else if (moveCount == 38) {\n oneStar.parentNode.removeChild(oneStar);\n }\n}", "function stars() {\n starsNumber = 3;\n if (moves >= 10 && moves < 18) {\n thirdStar.classList.remove('fa-star', 'starColor');\n thirdStar.classList.add('fa-star-o');\n starsNumber = 2;\n } else if (moves >= 18) {\n secondStar.classList.remove('fa-star', 'starColor');\n secondStar.classList.add('fa-star-o');\n starsNumber = 1;\n }\n}", "function countMoves() {\n move++;\n moves.innerHTML = move;\n\n //Removes stars after a number of moves\n if (move > 15 && move < 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n } else if (move > 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "function starsRating() {\n if (moves === 14 || moves === 17 || moves === 24 || moves === 28\n ) { hideStar();\n }\n}", "function updateMoves() {\n moves += 1;\n const move = document.querySelector(\".moves\");\n move.innerHTML = moves;\n if (moves === 16) {\n removeStar();\n starRating = 2;\n } else if (moves === 25) {\n removeStar();\n starRating = 1;\n }\n}", "function removeStar() {\n if (remainingStars >= 2) {\n remainingStars -=1;\n stars.removeChild(stars.firstElementChild);\n }\n}", "function starCount() {\r\n if (moveCounter === 15) { // when the move counter reaches 10 remove the star\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop one star');\r\n } else if (moveCounter === 30) {\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop second star');\r\n }\r\n}", "function starRemove() {\n\tif (numMove > 16) {\n\t\testrelas[2].style.display = 'none';\n\t\tcontStars = 2;\n\t} if (numMove > 20) {\n\t\testrelas[1].style.display = 'none';\n\t}\n}", "function starColor(){\n\tif(numOfMoves === 8){\n\t\t--numOfStars;\n\t\tstars[2].classList.remove(\"staryellow\");\n\t}\n\telse if(numOfMoves === 12){\n\t\t--numOfStars;\n\t\tstars[1].classList.remove(\"staryellow\");\n\t}\n\telse if(counterMacth === 18){\n\t\tstars[0].classList.remove(\"staryellow\");\n\t}\n}", "function scoreStar() {\n if (moveCounter === 18) {\n stars1 = 2 // 2 estrelas\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 22) {\n stars1 = 1 // 1 estrela\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 29) {\n stars1 = 0 // 0 estrelas\n $('.fa-star').remove()\n }\n return\n}", "function starRating () {\n if ( moveCount === 20 || moveCount === 30 ) {\n decrementStar();\n }\n}", "function updateStarCounter() {\n\t// when moves counter reaches 20, one star is removed\n\tif (Number(movesMade.innerText) === 20) {\n\t\tlet star = document.querySelector('#star-one').classList.add('none');\n\t}\n\t// when moves counter reaches 29, two stars are removed\n\tif (Number(movesMade.innerText) === 29) {\n\t\tlet star = document.querySelector('#star-two').classList.add('none');\n\t}\n\t//when moves counter is zero, all stars should be shown\n\tif (Number(movesMade.innerText) === 0) {\n\t\tdocument.querySelector('#star-one').classList.remove('none');\n\t\tdocument.querySelector('#star-two').classList.remove('none');\n\t\tdocument.querySelector('#star-three').classList.remove('none');\n\t}\n}", "function starRating() {\n if (moves > 13 && moves < 16) {\n starCounter = 3;\n } else if (moves > 17 && moves < 27) {\n starCounter = 2;\n } else if (moves > 28) {\n starCounter = 1;\n }\n showStars(starCounter);\n }", "function subtractStars(moves) {\n if (moves === 26 || moves === 34 || moves === 42) {\n const elem = document.querySelector('.stars li');\n elem.parentNode.removeChild(elem);\n }\n }", "function starCount() {\n if (moves == 22 || moves == 27 || moves == 32) {\n hideStar();\n }\n}", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector(\".moves\").innerText = moves;\n\tdocument.querySelector(\".moves-text\").innerText = \"Moves\";\n\n\tlet stars = document.querySelector(\".stars\");\n\tvar lis = stars.children.length;\n\twhile (lis < 3) {\n\t\tvar star = stars.lastElementChild.cloneNode(true);\n\t\tstars.appendChild(star);\n\t\tlis = stars.children.length;\n\t}\n}", "function incMoves() {\n moveCounter += 1;\n moves.innerText = moveCounter;\n //set star score\n if (moveCounter > 12 && moveCounter <= 18) {\n //if player uses more than 18 moves, but less than 24, deduct one star\n for (i = 0; i < starsList.length; i++) {\n if (i > 1) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 1;\n }\n }\n } else if (moveCounter > 18 && moveCounter <= 24) {\n //if player uses more than 24 moves, but less than 32, deduct another star\n for (i = 0; i < starsList.length; i++) {\n if (i > 0) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 2;\n }\n }\n }\n}", "function incrementMoves() {\n\tmoves++;\n\tdocument.querySelector('.moves').textContent = moves;\n\tif (moves === twoStar) {\n\t\tdocument.querySelector('.star-3').style.display = 'none';\n\t} else if (moves === oneStar) {\n\t\tdocument.querySelector('.star-2').style.display = 'none';\n\t}\n}", "function rating() {\n 'use strict'; // turn on Strict Mode\n if (moves > 10 && moves < 19) {\n stars[2].classList.remove('fa-star');\n stars[2].classList.add('fa-star-o');\n starsRating = 2;\n } else if (moves > 20) {\n stars[1].classList.remove('fa-star');\n stars[1].classList.add('fa-star-o');\n starsRating = 1;\n }\n}", "function UpdateMoves() {\n\n $(\"#moves\").text(moves.toString());\n // Update star's number\n if (moves >= 0 && moves <= 8) {\n starNumber = '3';\n // Remove 1st Star\n } else if (moves >= 9 && moves <= 18) {\n $(\"#starOne\").removeClass(\"fa-star\");\n starNumber = '2';\n // Remove 2nd Star \n } else if (moves >= 19 && moves <= 25) {\n $(\"#starTwo\").removeClass(\"fa-star\");\n starNumber = '1';\n }\n}", "function star(numOfMove){\n\t noMoves = numOfMove; \n\t let stars = document.querySelector(\".stars\");\n\t if(numOfMove>50){\n\t \tnoStar=1;\n stars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else if (numOfMove>30){\n\t \tnoStar=2;\n\t \tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else{\n\t \tnoStar=3;\n\t\tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n}", "function rating(numOfMistakes) {\n if ((numOfMistakes === 9)||(numOfMistakes === 12)) {\n stars.removeChild(stars.lastChild);\n starCount -= 1;\n }\n }", "function loseStar(event) {\n\tlet counterMoves = Number (moves.textContent);\n\tif((counterMoves - numOfMatched) % 10 === 0 && counterStars != 1){//decrease stars after balance between counterMoves and numOfMatched with 10\n\t\tnumOfStars.children[counterStars-1].firstElementChild.className = 'fa fa-star-o';\n\t\tcounterStars--;\n\t}else{\n\t\t// alert('You are Lose!')\n\t\t// deck.removeEventListener('click', displayCard);\n\t}\n}", "function ratings() {\n\tif(moveCounter > 12 && moveCounter <= 16) {\n\t\tsStar[0].style.cssText = 'opacity: 0';\n\t\tcStar[0].style.cssText = 'display: none';\n\t}\n\tif(moveCounter > 16) {\n\t\tsStar[1].style.cssText = 'opacity: 0';\n\t\tcStar[1].style.cssText = 'display: none';\t\n\t}\n}", "function countStars() {\n\n if (moves <= 20) {\n stars = 3;\n } else if (moves <= 25) {\n stars = 2;\n } else {\n stars = 1;\n }\n\n displayStars();\n}", "function showStars() {\n let count;\n if (moveCount < 16) {\n count = 3;\n score = 60;\n } else if (moveCount < 32) {\n count = 2;\n score = 40;\n } else {\n count = 1;\n score = 10;\n }\n for (let i = 0; i < (stars.length - count); i++) {\n stars[i].setAttribute('style', 'display: none');\n }\n}", "function updateStars() {\n // if moves <=12 with 3 starts\n if (moves <= 12) {\n $('.stars .fa').addClass(\"fa-star\");\n stars = 3;\n } else if(moves >= 13 && moves <= 14){\n $('.stars li:last-child .fa').removeClass(\"fa-star\");\n $('.stars li:last-child .fa').addClass(\"fa-star-o\");\n stars = 2;\n } else if (moves >= 15 && moves <20){\n $('.stars li:nth-child(2) .fa').removeClass(\"fa-star\");\n $('.stars li:nth-child(2) .fa').addClass(\"fa-star-o\");\n stars = 1;\n } else if (moves >=20){\n $('.stars li .fa').removeClass(\"fa-star\");\n $('.stars li .fa').addClass(\"fa-star-o\");\n stars = 0;\n }\n $('.win-container .stars-number').text(stars);\n\n}", "function setStars() {\n /*Grabs the section in the html that has the moves count and updates it based on moves variable. */\n document.getElementById(\"moves\").textContent = moves;\n /*Conditional used to determine what stars to display depending on the number of moves/2clicks occur. */\n if (moves <= 10){\n starsRating = 3;\n return;\n } \n /*Grabs stars elements so that later the classes can be manipulated to display clear starts instead of full stars. */\n let stars = document.getElementById(\"stars\").children;\n /*If the user has taken over 10 moves/2 clicks, then one star is replaced with a star outline. */\n stars[2].firstElementChild.classList.remove(\"fa-star\");\n stars[2].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 20){\n starsRating = 2;\n return;\n } \n /*If the user has taken over 20 moves/2 clicks, then an addional star is repalced with a star outline. */\n stars[1].firstElementChild.classList.remove(\"fa-star\");\n stars[1].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 30) {\n starsRating = 1;\n return;\n } \n}", "function starCount() {\n\n if(numMoves < 16) {\n numStars = 3;\n }else if (numMoves >= 16 && numMoves < 25) {\n numStars = 2;\n }else {\n numStars = 1;\n };\n\n printStars();\n}", "function updateMoves() {\n if (moves === 1) {\n $(\"#movesText\").text(\" Move\");\n } else {\n $(\"#movesText\").text(\" Moves\");\n }\n $(\"#moves\").text(moves.toString());\n\n if (moves > 0 && moves < 16) { // gives star rating according the no of moves ,removes the class\n starRating = starRating;\n } else if (moves >= 16 && moves <= 20) {\n $(\"#starOne\").removeClass(\"fa-star\");\n starRating = \"2\";\n } else if (moves > 20) {\n $(\"#starTwo\").removeClass(\"fa-star\");\n starRating = \"1\";\n }\n}", "function starsEarned() {\n if (moves > 8 && moves < 12) {\n for (i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"hidden\";\n }\n }\n } else if (moves > 13) {\n for (i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"hidden\";\n }\n }\n }\n}", "function starScore () {\n if (moves >= 12) {\n stars[3].setAttribute('style', 'visibility: hidden');\n finalStarScore = 3;\n } \n if (moves >= 18) {\n stars[2].setAttribute('style', 'visibility: hidden');\n finalStarScore = 2;\n }\n if (moves >= 25) {\n stars[1].setAttribute('style', 'visibility: hidden');\n finalStarScore = 1;\n }\n}", "removeStar() {\n if (this.mStars != 0) {\n this.mStars--;\n }\n this.notifyStarsObservers(this.mStars);\n }", "function starRating() {\n if (moves === 15) {\n starChanger[0].classList.add('hide');\n starChanger[3].classList.add('hide');\n starChanger[1].classList.add('silver');\n starChanger[4].classList.add('silver');\n starChanger[2].classList.add('silver');\n starChanger[5].classList.add('silver');\n\n } if (moves === 20) {\n starChanger[1].classList.add('hide');\n starChanger[4].classList.add('hide');\n starChanger[2].classList.add('bronze');\n starChanger[5].classList.add('bronze');\n }\n}", "function updateScore() {\n $('.moves').text(movesCounter);\n if (movesCounter > 10 && movesCounter <= 15 ) {\n $('#thirdStar').removeClass('fa fa-star');\n $('#thirdStar').addClass('fa fa-star-o');\n starsCounter = 2;\n }\n else if (movesCounter > 15) {\n $('#secondStar').removeClass('fa fa-star');\n $('#secondStar').addClass('fa fa-star-o');\n starsCounter = 1;\n }\n // you should have at least 1 star\n}", "function starRating() {\n var starsTracker = starsPanel.getElementsByTagName('i');\n\n // If game finished in 11 moves or less, return and star rating remains at 3\n if (moves <= 11) {\n return;\n // If finished between 11 to 16 moves, 3rd colored star is replaced with empty star class\n } else if (moves > 11 && moves <= 16) {\n starsTracker.item(2).className = 'fa fa-star-o';\n // If finished with more than 16 moves, 2nd colored star is replaced with empty star class\n } else {\n starsTracker.item(1).className = 'fa fa-star-o';\n }\n\n // Update stars variable by counting length of remaining colored star elements\n stars = document.querySelectorAll('.fa-star').length;\n}", "function moveCounter() {\n moves += 1;\n moveField = document.getElementsByClassName(\"moves\");\n moveField[0].innerHTML = moves;\n\n if (moves === 16) {\n let starList = document.querySelectorAll('.fa-star');\n let star1 = starList[2];\n star1.style.color = \"black\";\n stars--\n } else if (moves === 24) {\n let starList = document.querySelectorAll('.fa-star');\n let star2 = starList[1];\n star2.style.color = \"black\";\n stars--\n }\n}", "function updateStars() {\n if (moves > 10 && moves < 20) {\n starsList[4].setAttribute('class', 'fa fa-star-o');\n stars = 4;\n }\n if (moves >= 20 && moves < 30) {\n starsList[3].setAttribute('class', 'fa fa-star-o');\n stars = 3;\n }\n if (moves >= 30 && moves < 40) {\n starsList[2].setAttribute('class', 'fa fa-star-o');\n stars = 2;\n }\n if (moves >= 40) {\n starsList[1].setAttribute('class', 'fa fa-star-o');\n stars = 1;\n }\n }", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n textMoves();\n\n /*\n * Check to determine the player's rating after\n * certain number of moves have been exceeded\n */\n if (moves > 12 && moves < 19) {\n starsArray.forEach(function(star, i) {\n if (i > 1) {\n star.style.visibility = 'collapse';\n }\n });\n } else if (moves > 20) {\n starsArray.forEach(function(star, i) {\n if (i > 0) {\n star.style.visibility = 'collapse';\n }\n });\n }\n}", "function starFilterRemover(power) {\n let newStar = '../stars/star-hollow.png';\n if(power === 'top-star-5') {\n } if(power === 'top-star-4') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n } if(power === 'top-star-3') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n } if(power === 'top-star-2') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n document.getElementById('top-star-3').classList.remove('live-star');\n document.getElementById('top-star-3').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n $(document.getElementById('top-star-3')).attr('src', newStar);\n } if(power === 'top-star-1') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n document.getElementById('top-star-3').classList.remove('live-star');\n document.getElementById('top-star-3').classList.add('star-filter','dead-star');\n document.getElementById('top-star-2').classList.remove('live-star');\n document.getElementById('top-star-2').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n $(document.getElementById('top-star-3')).attr('src', newStar);\n $(document.getElementById('top-star-2')).attr('src', newStar);\n };\n filterSetting(power);\n}", "function points() {\n if (totalClicks === 25) {\n removeLastStar();\n } else if (totalClicks === 40) {\n removeLastStar();\n }\n}", "function addAMove(){\n moves++;\n moveCounter.innerHTML = moves;\n //game displays a star rating from 1 to at least 3 stars - after some number of moves, star rating lowers\n if (moves > 8 && moves < 12) {\n numStars = 4;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 12 && moves < 20) {\n numStars = 3;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 20 && moves < 30) {\n numStars = 2;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves > 30) {\n numStars = 1;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n}", "function rating() {\n\tconst star1 = document.getElementById(\"one-star\");\n\tconst star2 = document.getElementById(\"two-star\");\n\tconst star3 = document.getElementById(\"three-star\");\n\t// change stars style depending on number of moves\n\tif (moveCounter == 18) {\n\t\tstar1.classList.remove(\"fas\");\n\t\tstar1.classList.add(\"far\");\n\t} else if (moveCounter == 16){\n\t\tstar2.classList.remove(\"fas\");\n\t\tstar2.classList.add(\"far\");\n\t} else if (moveCounter == 14) {\n\t\tstar3.classList.remove(\"fas\");\n\t\tstar3.classList.add(\"far\");\n\t} else {\n\t\t\n\t}\n}", "function starRating(moves) {\n if (moves >= 12 && moves < 18) {\n starCount.childNodes[5].childNodes[0].className = 'fa fa-star-o';\n } else if (moves >= 18) {\n starCount.childNodes[3].childNodes[0].className = 'fa fa-star-o';\n }\n return starCount;\n}", "function decrementStars() {\n $(\".stars i.fa-star\").first()\n .removeClass(\"fa-star\")\n .addClass(\"fa-star-o\");\n stars -= 1;\n }", "function stars() {\n\tconst starar = star.getElementsByTagName('i');\n\tfor (i = 0; i < starar.length; i++) {\n\t\tif (moves > 14 && moves <= 19) {\n\t\t\tstarar[2].className = 'fa fa-star-o';\n\t\t\tstarnum = 2;\n\t\t} else if (moves > 19) {\n\t\t\tstarar[1].className = 'fa fa-star-o';\n\t\t\tstarnum = 1;\n//\t\t} else if (moves > 24) {\n//\t\t\tstarar[0].className = 'fa fa-star-o';\n//\t\t\tstarnum = 0;\n\t\t} else {\n\t\t\tstarar[0].className = 'fa fa-star';\n\t\t\tstarar[1].className = 'fa fa-star';\n\t\t\tstarar[2].className = 'fa fa-star';\n\t\t\tstarnum = 3;\n\t\t}\n\t}\n}", "function rateTheStars(moves){\n if (moves > 24) {\n console.log(\"1 star\");\n starRating = 1;\n } else if (moves > 20) {\n console.log(\"2 stars\");\n starRating = 2;\n } else if (moves > 16){\n console.log(\"3 stars\");\n starRating = 3;\n } else if (moves > 12){\n console.log(\"4 stars\");\n starRating = 4;\n } else {\n starRating=5;\n }\n starColors(starRating);\n }", "function updateRating() {\n //Rating game based on move count\n if (numMoves == (moves_to_two_stars)) {\n stars[2].classList.remove(\"fa-star\");\n stars[2].classList.add(\"fa-star-o\");\n rating = 2;\n }\n else if (numMoves == (moves_to_one_star)) {\n stars[1].classList.remove(\"fa-star\");\n stars[1].classList.add(\"fa-star-o\");\n rating = 1;\n }\n}", "function rating(){\n //// TODO: Bug has been fixed\n if (!cardCouple[0].classList.contains('match') && !cardCouple[1].classList.contains('match')){\n moves.innerText++;\n }\n if (moves.innerText > 14){\n document.querySelector('.stars li:nth-child(1)').classList.add('starDown');\n }\n else if (moves.innerText > 20){\n document.querySelector('.stars li:nth-child(2)').classList.add('starDown');\n }\n}", "function calculateRemainingStars() {\n if (state.totalMoves >= 0 && state.totalMoves < 15) {\n return 3;\n }\n \n if (state.totalMoves >= 15 && state.totalMoves < 25) {\n return 2;\n }\n \n if (state.totalMoves >= 25) {\n return 1;\n }\n \n throw 'Unable to calculate remaining stars';\n }", "function setStars() {\r\nlet starsDOM = document.querySelector('.stars');\r\n if (moveCounter == 0) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 3;\r\n } else if (moveCounter == 14) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 2;\r\n } else if (moveCounter == 22) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 1;\r\n } else if (moveCounter == 30) {\r\n starsDOM.innerHTML = ``;\r\n starCounter = 0;\r\n }\r\n}", "function howManyStars() {\n\tif (Number(movesMade.innerText) < 20) {\n\t\treturn \"3 stars\";\n\t}\n\tif (Number(movesMade.innerText) > 19 && Number(movesMade.innerText) < 29) {\n\t\treturn \"2 stars\";\n\t}\n\tif (Number(movesMade.innerText) > 28) {\n\t\treturn \"1 star\";\n\t}\n}", "function removeStar() {\n for(star of allStars) {\n if(star.style.display !== 'none') {\n star.style.display = 'none';\n break;\n }\n }\n}", "function checkScore() {\n if (moves === 10 || moves === 20) {\n removeStar();\n }\n}", "function updateStarsDisplay(counter){\n let stars = document.getElementsByClassName(\"fa-star\");\n\n // for every 16 moves (or number of cards), remove a star\n if (counter > 0 && stars.length > 0){\n let penaltyLimit = cards.length + 1; \n let z = counter % penaltyLimit;\n if (z == 0){\n stars[0].classList.add(\"fa-star-o\");\n stars[0].classList.remove(\"fa-star\");\n }\n }\n return stars.length;\n}", "function moveCounter() {\n moveCount ++;\n moves.textContent = moveCount;\n // star Rating:\n let starRating = document.getElementsByClassName(\"stars\")[0];\n if (moveCount > 20) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li> <li><i class=\\\"fa fa-star\\\"></i></li>\";\n } else if (moveCount > 30) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li>\";\n }\n}", "function countMove() {\n moves++;\n count.innerHTML = moves;\n if (moves < 20 && moves > 12) {\n starCount[1].style.display = 'none';\n } else if (moves > 20) {\n starCount[2].style.display = 'none';\n }\n}", "function rating(moves) {\n let rating = 3;\n if (moves > stars3 && moves < stars2) {\n $rating.eq(3).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > stars2 && moves < star1) {\n $rating.eq(2).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > star1) {\n $rating.eq(1).removeClass('fa-star').addClass('fa-star-o');\n rating = 1;\n }\n return { score: rating };\n}", "function reSet(){\n count = 0;\n $('.moves').html('');\n $('.stars li').each( function(i){\n this.style.display = '';\n });\n stopClock();\n time = 0;\n check = 0;\n}", "function setStars() {\n if (movements === 0) {\n totalStars = 3;\n let fStar = document.querySelector(\"#firstStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star\";\n newStar.id=\"firstStar\";\n starsUl.appendChild(newStar);\n let sStar = document.querySelector(\"#secondStar\");\n sStar.remove();\n let starsUl2 = document.querySelector(\".stars\");\n let newStar2 = document.createElement(\"li\");\n newStar2.className = \"fa fa-star\";\n newStar2.id=\"secondStar\";\n starsUl.appendChild(newStar2);\n let tStar = document.querySelector(\"#thirdStar\");\n tStar.remove();\n let starsUl3 = document.querySelector(\".stars\");\n let newStar3 = document.createElement(\"li\");\n newStar3.className = \"fa fa-star\";\n newStar3.id=\"thirdStar\";\n starsUl.appendChild(newStar3);}\n else if (movements === 14) {\n totalStars = 2;\n let fStar = document.querySelector(\"#firstStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"firstStar\";\n starsUl.appendChild(newStar);\n } else if (movements === 21) {\n totalStars = 1;\n let fStar = document.querySelector(\"#secondStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"secondStar\";\n starsUl.appendChild(newStar);\n } else if (movements === 24) {\n totalStars = 0;\n let fStar = document.querySelector(\"#thirdStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"thirdStar\";\n starsUl.appendChild(newStar);\n }\n}", "function resetStars() {\n /*Grabs the children of the section of the html with the stars ID and assigns them to the stars variable. */\n let stars = document.getElementById(\"stars\").children;\n /*Enters 0 for the text content next to moves in the html, to indicate the user hasn't taken any moves in the new game yet. */\n document.getElementById(\"moves\").textContent = 0;\n /*Iterates over the stars in the stars variable and returns them all to stars and not star outlines. */\n for (let star of stars) {\n star.firstElementChild.classList.remove(\"fa-star-o\");\n star.firstElementChild.classList.add(\"fa-star\");\n }\n}", "function stars() {\n if (numberOfMoves === 14) {\n star[2].style.color = '#ccc';\n }\n if (numberOfMoves === 22) {\n star[1].style.color = '#ccc';\n }\n}", "function stars() {\n if (numberOfMoves === 14) {\n star[2].style.color = '#ccc';\n }\n if (numberOfMoves === 22) {\n star[1].style.color = '#ccc';\n }\n}", "function updateStarRating() {\n const numCards = deckConfig.numberOfcards;\n\n if (scorePanel.moveCounter === 0) {\n scorePanel.starCounter = 3;\n $(\".star-disabled\").toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === Math.trunc(numCards / 2 + numCards / 4)) {\n scorePanel.starCounter = 2;\n $($(\".stars\").children()[0]).toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === (numCards)) {\n scorePanel.starCounter = 1;\n $($(\".stars\").children()[1]).toggleClass(\"star-enabled star-disabled\");\n }\n}", "function clearStars() {\n starCount();\n let stars = document.querySelectorAll('.stars li i');\n stars[0].classList.remove('hide');\n stars[1].classList.remove('hide');\n stars[2].classList.remove('hide');\n starCounter = 0;\n }", "function removeStar() {\n $('.fa-star').last().attr('class', 'fa fa-star-o');\n numStars--;\n}", "function awardStars() {\n if (moves > 8 && moves < 14) {\n for (i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n } else if (moves > 15) {\n for (i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "function resetStars() {\n countStars = 3;\n for (star of stars) {\n star.style.display = 'inline';\n }\n}", "function updateMoves() {\n moves += 1;\n $('#moves').html(`${moves} Moves`);\n if (moves === 24) {\n addBlankStar();\n }\n else if (moves === 16) {\n addBlankStar();\n }\n}", "function starRating() {\n let lastStar;\n let lastModalStar;\n const deckStars = document.querySelectorAll('.stars .fa-star')\n const modalStars = document.querySelectorAll('.winStars .fa-star')\n if (moves === 33) {\n lastStar = deckStars[2];\n lastModalStar = modalStars[2];\n } else if (moves === 45) {\n lastStar = deckStars[1];\n lastModalStar = modalStars[1];\n } else if (moves === 52) {\n lastStar = deckStars[0];\n lastModalStar = modalStars[0];\n }\n if (lastStar !== undefined) {\n lastStar.classList.replace('fa-star', 'fa-star-o');\n lastModalStar.classList.replace('fa-star', 'fa-star-o');\n }\n}", "function removeStar() {\n\tlet stars = document.querySelectorAll(\".fa-star\");\n\tif (stars.length === 1) {\n\t\treturn;\n\t}\n\tfor (let star of stars) {\n\t star.parentNode.remove();\n\t return;\n \t}\n}", "function starlevel() {\n\tif (movesCount >= 14 && movesCount <= 20) {\n\t\tstarCount = 2;\n\t\tstarSection[2].style.display = \"none\";\n\t}\n\tif (movesCount > 20) {\n\t\tstarCount = 1;\n\t\tstarSection[1].style.display = \"none\";\n\t}\n}", "function removeStar() {\n const stars = document.querySelectorAll('.fa-star');\n for (let i = 0; i < stars.length; i++) {\n if (stars[i].style.display !== 'none') {\n stars[i].style.display = 'none';\n break;\n }\n }\n}", "function setRating() {\r\n // Assigning Stars according to number of moves\r\n if (moves <= 12) {\r\n var stars = '<i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star\" aria-hidden=\"true\"></i>';\r\n } else if (moves <= 14) {\r\n var stars = '<i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-half-o\" aria-hidden=\"true\"></i>';\r\n } else if (moves <= 16) {\r\n var stars = '<i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i>';\r\n } else if (moves <= 18) {\r\n var stars = '<i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-half-o\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i>';\r\n } else if (moves <= 20) {\r\n var stars = '<i class=\"fa fa-star\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i>';\r\n } else {\r\n var stars = '<i class=\"fa fa-star-half-o\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i> <i class=\"fa fa-star-o\" aria-hidden=\"true\"></i>';\r\n }\r\n // Appending Stars\r\n $('.starsB').html(stars);\r\n }", "function moveCount() {\n debug(\"moveCount\");\n let count = parseInt(document.querySelector('.moves').innerHTML, 10);\n let x = count + 1;\n \n document.querySelector('.moves').innerHTML = x;\n if (x > 29 && x < 40) {\n document.querySelector('.stars').childNodes[2].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n if (x >= 40 && x < 49) {\n document.querySelector('.stars').childNodes[1].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n }", "function addMove() {\n moves ++;\n moveCount.innerHTML = moves;\n if(moves === 10) {\n hideStar();\n } else if(moves === 20) {\n hideStar();\n }\n}", "function handleStarRating(){\n\t// setting the rates based on moves\n if (numberOfMoves > 30){\n stars[1].style.visibility = \"collapse\";\n } else if (numberOfMoves > 25){\n stars[2].style.visibility = \"collapse\";\n } else if (numberOfMoves > 20){\n stars[3].style.visibility = \"collapse\";\n } else if (numberOfMoves > 16){\n stars[4].style.visibility = \"collapse\";\n }\n}", "function starRating() {\n if(moveCounter <= 25) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'inline-block';\n starsList[2].style.display = 'inline-block';\n moves.style.color = \"green\";\n }\n else if(moveCounter > 25 && moveCounter <=65) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'inline-block';\n starsList[2].style.display = 'none';\n moves.style.color = \"orange\";\n }\n else if(moveCounter > 65) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'none';\n starsList[2].style.display = 'none';\n moves.style.color = \"red\";\n }\n}", "function updateStarRating(moves) {\n\tswitch (moves) {\n\t\tcase 10:\n\t\t\tstarRatingElements[2].classList.add('star--disabled');\n\t\t\tstarCount = 2;\n\t\tbreak;\n\t\tcase 15:\n\t\t\tstarRatingElements[1].classList.add('star--disabled');\n\t\t\tstarCount = 1;\n\t\tbreak;\n\t}\n}", "function rating(moves) {\n // \n let rating = 3;\n\n // Scoring system from 1 to 3 stars\n let stars3 = 10,\n stars2 = 16,\n star1 = 20;\n\n if (moves > stars3 && moves < stars2) {\n $stars.eq(3).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > stars2 && moves < star1) {\n $stars.eq(2).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > star1) {\n $stars.eq(1).removeClass('fa-star').addClass('fa-star-o');\n rating = 1;\n }\n return {\n score: rating\n };\n}", "function checkMovesNumber() {\n const STAR_1 = document.getElementById('star1');\n const STAR_2 = document.getElementById('star2');\n const STAR_3 = document.getElementById('star3');\n if (movesNumber > 14 && movesNumber <= 18) {\n starRating = 2.5;\n STAR_3.classList.remove('fa-star');\n STAR_3.classList.add('fa-star-half-o');\n } else if (movesNumber > 18 && movesNumber <= 22) {\n starRating = 2;\n STAR_3.classList.remove('fa-star-half-o');\n STAR_3.classList.add('fa-star-o');\n } else if (movesNumber > 22 && movesNumber <= 26) {\n starRating = 1.5;\n STAR_2.classList.remove('fa-star');\n STAR_2.classList.add('fa-star-half-o');\n } else if (movesNumber > 26 && movesNumber <= 30) {\n starRating = 1;\n STAR_2.classList.remove('fa-star-half-o');\n STAR_2.classList.add('fa-star-o');\n } else if (movesNumber > 30 && movesNumber <= 34) {\n starRating = 0.5;\n STAR_1.classList.remove('fa-star');\n STAR_1.classList.add('fa-star-half-o');\n } else if (movesNumber > 34) {\n starRating = 0;\n STAR_1.classList.remove('fa-star-half-o');\n STAR_1.classList.add('fa-star-o');\n alert('Game over! Du hattest zu viele Züge! Versuche es erneut!\\nAnzahl Züge: ' + movesNumber + '\\nVergangene Zeit: ' + sec + ' Sekunden' + '\\nDeine Bewertung: ' + starRating + ' Sterne');\n clearInterval(timer);\n } else {\n return;\n }\n}", "function starRating(){\r\n \r\n for (let i=0; i<starsContainer.length; i++){\r\n\r\n \r\n \r\n\r\n\r\n if (moves>= 0 && moves<=13){\r\n starsContainer[i].innerHTML=\r\n `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n\r\n }\r\n \r\n else if (moves>13 && moves <= 17){\r\n starsContainer[i].innerHTML=\r\n `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n }\r\n else if (moves>16 && moves <= 21){\r\n starsContainer[i].innerHTML=\r\n `<li><i class=\"fa fa-star\"></i></li>`;\r\n }else {\r\n starsContainer[i].innerHTML=\"\";\r\n }\r\n}\r\nif (moves===1 ){\r\n \r\n startTimer();\r\n }\r\n \r\n}", "function countMoves() {\n\n num++;\n moves.textContent = num;\n\n if (num === 1) {\n //start the stopwatch on the first move\n startTimer();\n } else if (num > 1) {\n //reduce the number of stars based on number of moves\n if (num > 49) {\n endGame(); //moves limit for game\n } else if (num > 18) {\n stars[1].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n } else if (num > 12) {\n stars[2].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n }\n }\n}", "function countStars() {\n if (moves <= 30) { //star count will be initial value of 3 stars\n document.getElementById(\"oneStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"twoStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"threeStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"oneStar\").style.color = 'green'; //star colour is green//\n document.getElementById(\"twoStar\").style.color = 'green'; //star colour is green//\n document.getElementById(\"threeStar\").style.color = 'green'; //star colour is green//\n } else if (moves > 30 && moves < 50) {\n document.getElementById(\"threeStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"oneStar\").style.color = 'yellow'; //star colour is yellow//\n document.getElementById(\"twoStar\").style.color = 'yellow'; //star colour is yellow//\n stars = 2; //star count will be 2 stars//\n } else if (moves > 50) {\n document.getElementById(\"twoStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"threeStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"oneStar\").style.color = 'red'; //star colour is red//\n stars = 1; //star count will be 1 star//\n }\n }", "function resetStarRating() {\n stars[1].classList.remove(\"fa-star-o\");\n stars[1].classList.add(\"fa-star\");\n stars[2].classList.remove(\"fa-star-o\");\n stars[2].classList.add(\"fa-star\");\n rating = 3;\n}", "function moveCount () {\n var moves = parseInt($(\".moves\").text())\n moves += 1\n $(\".moves\").text(moves)\n stars( moves )\n}" ]
[ "0.7903617", "0.78775245", "0.7817392", "0.78047484", "0.77238584", "0.76920605", "0.76788247", "0.7649155", "0.7590312", "0.7540466", "0.7526105", "0.74457574", "0.7412945", "0.73602223", "0.7320222", "0.731811", "0.73134935", "0.7310747", "0.7249409", "0.7239241", "0.72301507", "0.7215649", "0.71877015", "0.7168381", "0.7100064", "0.7095725", "0.7094026", "0.70724475", "0.7029947", "0.6977689", "0.6927555", "0.6927344", "0.69235504", "0.69212747", "0.69018024", "0.6900803", "0.6867345", "0.68110615", "0.680495", "0.6801083", "0.67991537", "0.6772237", "0.67720133", "0.6763422", "0.67441744", "0.6708214", "0.6694408", "0.6694263", "0.666682", "0.66649735", "0.66323733", "0.6627192", "0.6604433", "0.658801", "0.65800655", "0.6575321", "0.6574374", "0.6562775", "0.65547264", "0.6538024", "0.6520775", "0.6520006", "0.65167344", "0.6503617", "0.6500818", "0.64960957", "0.6477662", "0.6464609", "0.64599955", "0.644742", "0.6438085", "0.6430643", "0.64236337", "0.6417813", "0.641158", "0.6399541", "0.6399541", "0.63975805", "0.63859206", "0.6381788", "0.63711506", "0.63616455", "0.6360802", "0.6358204", "0.635783", "0.63566476", "0.6351645", "0.63472074", "0.63422424", "0.63309175", "0.63305265", "0.63226163", "0.63211805", "0.6300791", "0.6295318", "0.6293121", "0.6286641", "0.6277634", "0.6271985", "0.626609" ]
0.68883044
36
reset move count back to zero
function resetMoveCount() { moveCount = 0; $('.moves').text(moveCount); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function resetMoves() {\n debug(\"resetMoves\");\n count = document.querySelector('.moves');\n\n count.innerHTML = \"0\";\n }", "resetState() {\n this._movements = 0;\n }", "function resetCounter() {\n numberOfMoves = 0;\n moveCounter.innerHTML = numberOfMoves;\n}", "function resetMoves() {\n app.moves = 0;\n app.counter.innerHTML = \"0\";\n}", "function initializeMoveCounter() {\n clickCounter = 0;\n numberOfMoves = 0;\n countMoves();\n}", "function resetMoves() {\n moveCount = 0;\n moveText.innerHTML = moveCount;\n}", "resetCount() {\n this.count = this.initialCount;\n }", "function resetCounter() {\n\tmoveCounter = 0;\n\tdocument.getElementById(\"item-moves\").innerHTML = moveCounter;\n}", "function reset() {\n state.moves = [];\n state.turnCount = 0;\n state.playbackSpeed = 700;\n chooseMove();\n }", "reset() {\n this.steps = 0;\n }", "function resetCounter(){\n turnCounter = 0;\n const moveCount = document.querySelector(\".moves\");\n moveCount.textContent = turnCounter;\n\n}", "function resetMoves() {\n moves = 0;\n document.querySelector(\"#moves\").innerHTML = moves;\n}", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector('.moves').innerHTML = moves;\n}", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector('.moves').innerHTML = moves;\n}", "function resetMoves() {\n moves = 0;\n document.querySelector('.moves').innerHTML = moves;\n}", "function resetMoves() {\n numMoves = 0;\n moves.innerText = 0 +\" Moves\";\n}", "Reset()\n {\n this._position = 0;\n }", "clearSpace(move) {\r\n this.state[move] = 0; \r\n }", "_reset_poke() {\n\t\tthis.level = 1\n\t\tthis.moves = []\n\t}", "reset(){\n //set position x and y back to 100\n this._posX = 100;\n this._posY = 100;\n //set score back to 0\n this._score = 0;\n }", "resetNumberOfMoves(){\n this.nbMovesDone = 0\n const action = {type : 'resetMovesPlayed', value : this.nbMovesDone}\n\n // send changes to the redux store\n this.props.dispatch(action)\n }", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector(\".moves\").innerText = moves;\n\tdocument.querySelector(\".moves-text\").innerText = \"Moves\";\n\n\tlet stars = document.querySelector(\".stars\");\n\tvar lis = stars.children.length;\n\twhile (lis < 3) {\n\t\tvar star = stars.lastElementChild.cloneNode(true);\n\t\tstars.appendChild(star);\n\t\tlis = stars.children.length;\n\t}\n}", "function fullReset() {\n reset();\n score.DROITE = 0;\n score.GAUCHE = 0;\n }", "function reset() {\n started = false;\n count = 0;\n return;\n}", "function resetCards() {\n moveCount = 0;\n getMoveCount();\n cards.forEach(function(card) {\n card.classList.remove(\"open\", \"show\", \"match\");\n });\n shuffleCards();\n resetTimer();\n setStars(3);\n}", "function resetPositions() {\r\n\tcurrentRow = startingRow;\r\n\tcurrentColl = startingColl;\r\n\tlastRow = startingRow;\r\n\tlastColl = startingColl;\r\n\tnextRow = startingRow + 1;\r\n\tnextColl = startingColl;\r\n}", "function moveCounter() {\n app.moves++;\n app.counter.innerHTML = app.moves;\n if (app.moves == 1) {\n app.second = 0;\n app.minute = 0;\n app.hour = 0;\n startTimer();\n }\n}", "prev() {\n --this.move_index; //decrease move count\n this.draw_everything();\n }", "function reset() {\n\tstarted = false; count = 0;\n\treturn;\n}", "function clearCards() {\n matchCount = 0;\n cardSelections = [];\n cardMoves = 0;\n let counter = document.querySelector('.moves');\n counter.innerHTML = cardMoves;\n }", "_resetPendingCount() {\n count = updateCount = 0;\n }", "reset() {\r\n\t\tlet me = this;\r\n\t\tif (me.up > 50 && me.down >= me.up) {\r\n\t\t\tme.up = 0;\r\n\t\t\tme.down = 0;\r\n\t\t}\r\n\t}", "function increaseMoveCounter() {\n state.totalMoves++;\n document.querySelector('.moves').textContent = state.totalMoves;\n }", "function countMoves() {\n\tmovesCounter++;\n\tlet move = Math.floor(movesCounter/2);\n\n\t// Starting the timer\n\tif (movesCounter == 1) {\n\t\ttime();\n\t}\n\n\tif (move == 1) {\n\t\tmoves.textContent = move + ' Move';\n\t} else if (movesCounter > 1) {\n\t\tmoves.textContent = move + ' Moves';\n\t}\n}", "function moveCounter() {\n moveCount++;\n\t$('.moves').text(moveCount);\n}", "function reset(){\n animate = false;\n if ((cur === 0 || cur === n - beforeN)) {\n cur = beforeN;\n $(element).css({\"margin-left\": -cur * w});\n }\n o.endChange(log);\n }", "function moveCounter() {\n if (clickedCards.length === 0) {\n moves++;\n moveNumber.innerHTML = moves;\n starRating(moves);\n }\n}", "function roundReset () {\n userSequence = [];\n count = 0;\n currentPlayerNum += 1;\n updatePlayer();\n }", "function reset() {\n cardsArray.forEach(function(card) {\n card.classList.remove('match', 'unmatched', 'selected', 'disabled');\n });\n starsArray.forEach(function(star) {\n star.style.visibility = 'visible';\n });\n\n // Resets moves\n count = 0;\n moves = 0;\n counter.innerHTML = moves;\n\n // Resets timer\n clearInterval(interval);\n seconds = 0;\n minutes = 0;\n hours = 0;\n timer.innerHTML = minutes + ' min(s) ' + seconds + ' secs(s)';\n\n // Shuffles the cards\n shuffleCards();\n}", "reset() {\n\n for (let i = 0; i < this.tail.length; i++) {\n this.tail[i].classList.remove('snake');\n }\n\n this.tail.length = 0;\n this.direction = 'up';\n this.nextDirection = 'up';\n this.speed = 160;\n this.moving = false;\n\n this.init();\n }", "reset() {\n this.x=200;\n this.y=400;\n this.steps=0;\n }", "function reset (){\n $(\".card\").removeClass(\"match\").removeClass(\"open\").removeClass(\"show\");\n document.getElementById(\"numberMoves\").innerText = 0;\n $(container).addClass(\"fa fa-star\");\n list_cards = shuffle(list_cards);\n shuffle_cards(list_cards);\n match_list = [];\n document.getElementById(\"minutes\").innerHTML='00';\n document.getElementById(\"seconds\").innerHTML='00';\n click = false;\n clearInterval(countDown);\n}", "function resetGame() {\n counter = 0;\n }", "function moveCount(){\ncounter ++;\ncounterDisplay.innerHTML = counter;\n}", "function countMoves() {\n moves++;\n if (moves === 1) {\n counter.textContent = `${moves} move`;\n } else {\n counter.textContent = `${moves} moves`;\n }\n}", "resetCounters() {\n this.fired = this.handled = 0\n }", "resetClicks() {\n this.clicks = 0;\n }", "function reset()\n {\n _pos = {};\n _first = false;\n _fingers = 0;\n _distance = 0;\n _angle = 0;\n _gesture = null;\n }", "function moveCounter () {\n moves += 1;\n document.querySelector('.moves').textContent = moves;\n}", "resetScore() {\n this.score = INITIAL_SCORE;\n }", "resetSwipe(){ \n\tthis.direction = 0;\n\tthis.startX = 0;\n\tthis.startY = 0;\n }", "function reset() {\n\t\t\treturn go(0);\n\t\t}", "reset() {\n this.x = 200;\n this.y = 485;\n this.score = 0;\n scoreIncrease.innerHTML = 0;\n this.lives = 3;\n livesTracker.innerHTML = 3;\n }", "function handleReset(click) {\n turnCount = 0;\n init();\n}", "resetRound() {\n this.moves = 0;\n this.emptyBoard();\n this.result = {status: 'waiting'};\n this.turn = '';\n }", "reset(){\r\n \tconsole.log(\"reset\");\r\n \tthis.score=0;\r\n }", "function reset() {\n indexClicked = 0;\n trackClicked = 0;\n}", "function updateMoves() {\n moves++;\n movesCounter.textContent = moves;\n}", "function moveCount () {\n moves++;\n moveCounter.innerHTML = moves;\n if (moves == 1) {\n timer();\n }\n}", "function incrementNoOfMoves() {\n let noOfMoves = parseInt(document.querySelector('.moves').textContent);\n noOfMoves++;\n manageStars(noOfMoves);\n document.querySelector('.moves').textContent = noOfMoves;\n}", "function incrementMoveCounter() {\n ++scorePanel.moveCounter;\n $(\".moves\").text(scorePanel.moveCounter.toString().padStart(3, \"0\").concat(\" moves\"));\n}", "reset(){\n this.live = 3;\n this.score = 0;\n this.init();\n }", "function counterUp() {\n counter += 1;\n }", "reset() {\n this._index = 0;\n }", "reset() {\n this._index = 0;\n }", "function calcMoves() {\n moves++;\n movesSpan.innerText = moves;\n updateStars();\n }", "function reset () {\n\t\tfillZero(xs,9);\n\t\tfillZero(os,9);\n\t\tremoveSelected(circles);\n\t\tcurrent = null;\n\t\tcounter = null;\n\t\twin = false;\n\t\tdisplay.textContent = \"tic tac toe\";\n\t}", "function MoveCounter(){\n moves++;\n counter.innerHTML = moves;\n}", "function resetBoard(){\n\t// For loop cointing down available spaces\n\t// QUESTION - Should I have come up with counting down more easily? How so? \n\tfor (var i = boxes.length - 1; i >= 0; i--) {\n\t\t// Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element. \n\t\t// QUESTION - so this sets boxes back to empty, right? \n\t\tboxes[i].innerHTML=\"\"; \n\t\tboxes[i].setAttribute(\"class\",\"clear\"); \n\t}\n\t// Redefine oMoves array to empty\n\toMoves = []; \n\t// Redefine xMoves array to empty\n\txMoves = []; \n\t// Redefine winCounter to 0 \n\twinCounter=0;\n\t// Redefine counter to 1 \n\tcounter = 1;\n\t// Redefine text in turnText \n\tturnText.innerHTML = \"It is X's turn\";\n}", "resetGame() {\r\n this.scrollingBG.tilePosition = ({x: 0, y: 0});\r\n this.distance = BOUND_LEFT;\r\n this.completed = 0;\r\n this.gameActive = true;\r\n\r\n // Reset the houses\r\n this.houses.removeChildren();\r\n this.houseArray = [];\r\n this.addHouses(this.goal);\r\n }", "static resetStepArray() {\n steps.length = 0;\n count = 0;\n }", "resetIfOver(minCount, minPosition) {\n if (minCount === this.durationInMins && minPosition === 0) {\n this.frameCount = 0;\n this.activeVisitors = [];\n this.waitingVisitors = this.data.slice();\n }\n }", "_moveToStart() {\n // moveCount can disturb the method logic.\n const initialMoveCount = this._settings.moveCount;\n this._settings.moveCount = 1;\n\n for (let pos = 1; pos < this._settings.startPosition; pos++) {\n this._rightMoveHandler();\n }\n this._settings.moveCount = initialMoveCount;\n }", "function prev() {\n --move_index; //decrease move count\n draw_everything();\n}", "function incrementCounter() {\n numberOfMoves++;\n moveCounter.innerHTML = numberOfMoves;\n}", "function reSet(){\n count = 0;\n $('.moves').html('');\n $('.stars li').each( function(i){\n this.style.display = '';\n });\n stopClock();\n time = 0;\n check = 0;\n}", "function reset() {\n setPieces(round);\n }", "function moveCounter() {\n cardMoves++;\n let counter = document.querySelector('.moves');\n counter.innerHTML = cardMoves;\n }", "function numberSteps() {\n\tlet countPlay = numMove + 1; \n\tnumMove = document.getElementById('moveCount').innerHTML = countPlay;\n}", "reset() {\n this.setState({\n count: 0\n });\n }", "resetForNextDest() {\n this.setHintIndex(0);\n this.setPhotoIndex(0);\n this.setReviewIndex(0);\n this.setPhotos([]);\n this.setReviews([]);\n this.setPlaceID(-1);\n }", "resetActions(){\n console.log('called character.resetActions()');\n this.props.actions.forEach( eachAction => {\n eachAction.turn_used = 0\n })\n }", "function countMoves() {\n moveCount++;\n moves.textContent = (moveCount === 1) ? `${moveCount} Move` : `${moveCount} Moves`;\n}", "function trackMoves(moveCount) {\n //moveCount++;\n let movesText = document.querySelector('.moves');\n movesText.innerHTML = moveCount;\n}", "resetResources()\n {\n this.slaps = 0;\n this.blocks = 0;\n }", "function clear() {\n lastPos = null;\n delta = 0;\n }", "reset(){\n this.setState({\n count: 0\n })\n }", "function Reset() {\n boxesTaken = 0;\n won = false;\n displayMessage = false;\n twoNoMovesInARow = 0;\n initializeBoard();\n}", "function movesCount() {\n moves++;\n moveCounter.innerHTML = moves;\n}", "function updateMovesCounter() {\n\tmovesCounter += 1;\n\tmovesCounterElement.textContent = movesCounter;\n\tupdateStarRating(movesCounter);\n}", "function movesIncrement(counter) {\n counter++;\n return counter;\n}", "backUp(n) { this.pos -= n; }", "function reset() {\n time = 0;\n totalScore = 0;\n lives = 5;\n speed = 10;\n points.innerText = \"00\";\n totalImmunity = 0;\n blocks = document.querySelectorAll(\".collidable\");\n blocks.forEach(block => {\n block.remove()\n });\n }", "function moveCounter() {\n counter.innerHTML ++;\n}", "resetPos(){\n this.addX(this.getX());\n this.addY(this.getY());\n }", "getMoveCount() {\n return this.moveCount;\n }", "reset() {\n this.rndIndex = 0;\n }", "reset() {\n this.rndIndex = 0;\n }", "function incrementCounter()\n\t{\n\t\tmovesCounter ++;\n\t\t$('#moves_id').html(movesCounter + \" Move(s)\");\n\t}", "function resetLifes() {\r\n moveMade = 0;\r\n move.innerText = moveMade;\r\n wordMove.innerText = 'Move';\r\n}" ]
[ "0.7635513", "0.7538035", "0.7435507", "0.74042773", "0.7306319", "0.7157502", "0.71389836", "0.7016031", "0.7010484", "0.6892859", "0.685494", "0.67444164", "0.67438745", "0.67438745", "0.67194545", "0.6632518", "0.65582544", "0.65319884", "0.6526455", "0.65249395", "0.64984876", "0.64798284", "0.64652526", "0.6431954", "0.64298046", "0.6419939", "0.64186573", "0.63653755", "0.63636005", "0.63553447", "0.634446", "0.6328558", "0.63244027", "0.6323309", "0.6322526", "0.63048553", "0.62995774", "0.62942386", "0.6275013", "0.62086284", "0.62005526", "0.61985743", "0.61967963", "0.6193723", "0.618646", "0.61753505", "0.617291", "0.61638427", "0.6161507", "0.6159526", "0.61581385", "0.61533237", "0.615326", "0.61450356", "0.6141162", "0.6132944", "0.6128106", "0.6124235", "0.6099585", "0.6093915", "0.60862327", "0.6079616", "0.60670435", "0.605949", "0.605949", "0.6057424", "0.6054721", "0.6044996", "0.6039784", "0.60286975", "0.60252935", "0.6020588", "0.6003943", "0.60004437", "0.59988743", "0.5994662", "0.59881186", "0.5986045", "0.5984989", "0.5982244", "0.5979109", "0.5971632", "0.5970817", "0.59681743", "0.59579366", "0.59527165", "0.59416884", "0.5941236", "0.5938737", "0.59380573", "0.59341353", "0.5931355", "0.5929648", "0.59193677", "0.5910707", "0.5907876", "0.5907714", "0.5907714", "0.59051216", "0.59029716" ]
0.7834286
0
remove star based on how many moves user make
function removeStar() { for(star of allStars) { if(star.style.display !== 'none') { star.style.display = 'none'; break; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function starCount() {\n if (moveCountNum === 20 || moveCountNum === 35) {\n removeStar();\n }\n}", "function removeStar() {\n const stars = Array.from(document.querySelectorAll('.fa-star'));\n if (moves === 12 || moves === 15 || moves === 18) {\n for (star of stars){\n if (star.style.display !== 'none'){\n star.style.display = 'none';\n numberOfStarts--;\n break;\n }\n }\n }\n}", "function starCounter(moves) {\r\n if (moves >= 20 && moves <= 30) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(4);\r\n } else if (moves >= 31 && moves <= 40) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(3);\r\n } else if (moves >= 41 && moves <= 50) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(2);\r\n } else if (moves >= 51) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(1);\r\n } else {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(5);\r\n\r\n }\r\n}", "function removeStar() {\n if (moves <= 15) {\n starNum = 3;\n }\n if (moves > 15) {\n document.querySelector('.three').innerHTML = '<i></i>';\n starNum = 2;\n };\n if (moves > 30) {\n document.querySelector('.two').innerHTML = '<i></i>';\n starNum = 1;\n };\n}", "function reduceMoves () {\n moves--;\n $('.moves').text(moves);\n if (moves === 6 || moves === 3) {\n $('.stars').find('li:last').remove();\n }\n}", "function adjustStarRating(moves) {\n if (moves === 16) {\n stars.children[0].remove();\n }\n else if (moves === 22) {\n stars.children[0].remove();\n }\n else if (moves === 32) {\n stars.children[0].remove();\n }\n else if (moves === 42) {\n stars.children[0].remove();\n }\n}", "function removeStars() {\n moves.innerHTML++;\n if (moves.innerHTML == 15) {\n starsChildren[2].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n if (moves.innerHTML == 20) {\n starsChildren[1].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n}", "function manageStars(noOfMoves) {\n if (noOfMoves > 16 && noOfMoves <= 32) {\n let fifthStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[4];\n if (fifthStar != null)\n fifthStar.remove();\n }\n if (noOfMoves > 32 && noOfMoves <= 48) {\n let fourthStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[3];\n if (fourthStar != null)\n fourthStar.remove();\n }\n if (noOfMoves > 48 && noOfMoves <= 64) {\n let thirdStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[2];\n if (thirdStar != null)\n thirdStar.remove();\n }\n if (noOfMoves > 64 && noOfMoves <= 80) {\n let secondStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[1];\n if (secondStar != null)\n secondStar.remove();\n }\n if (noOfMoves > 80) {\n let firstStar = document.getElementsByClassName('stars')[0]\n .getElementsByTagName('li')[0];\n if (firstStar != null)\n firstStar.remove();\n }\n}", "function starRemove() {\n\tif (numMove > 16) {\n\t\testrelas[2].style.display = 'none';\n\t\tcontStars = 2;\n\t} if (numMove > 20) {\n\t\testrelas[1].style.display = 'none';\n\t}\n}", "function reduceStars() {\n let starList = document.querySelectorAll('.fa-star');\n\n // determine whether star should be removed\n if(turns % STAR_REDUCTION === 0 && stars!== 1) {\n // change the rightmost star to an empty star\n let starLost = starList[starList.length-1];\n starLost.setAttribute('class', 'fa fa-star-o');\n stars--;\n }\n}", "function starRemoval(){\n\tstars = document.querySelectorAll('.fa-star');\n\tstarCount = countMoves;\n\tswitch (starCount) {\n\t\tcase 10:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}", "function starRatings() {\n if (moves === 12) {\n const star1 = stars.firstElementChild;\n stars.removeChild(star1);\n result = stars.innerHTML;\n } else if (moves === 16) {\n const star2 = stars.firstElementChild;\n stars.removeChild(star2);\n result = stars.innerHTML;\n }\n}", "function starCount() {\r\n if (moveCounter === 15) { // when the move counter reaches 10 remove the star\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop one star');\r\n } else if (moveCounter === 30) {\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop second star');\r\n }\r\n}", "function removeStar() {\n if (remainingStars >= 2) {\n remainingStars -=1;\n stars.removeChild(stars.firstElementChild);\n }\n}", "function starColor(){\n\tif(numOfMoves === 8){\n\t\t--numOfStars;\n\t\tstars[2].classList.remove(\"staryellow\");\n\t}\n\telse if(numOfMoves === 12){\n\t\t--numOfStars;\n\t\tstars[1].classList.remove(\"staryellow\");\n\t}\n\telse if(counterMacth === 18){\n\t\tstars[0].classList.remove(\"staryellow\");\n\t}\n}", "function updateStarCount()\n\t{\n\t\tif ( previousCard == null )\n\t\t{\n\t\t\tif ( movesCounter == 20 || movesCounter == 30 )\n\t\t\t{\n\t\t\t\t$('ul.stars li').first().remove();\n\t\t\t}\n\t\t}\t\t\t\t\n\t}", "function recalcStars() {\n const stars = document.querySelector(\".stars\");\n if ((countStars===3 && countMoves === 11) || (countStars===2 && countMoves === 17) ) {\n stars.children[countStars-1].firstElementChild.classList.replace('fa-star','fa-star-half-o');\n countStars -= 0.5;\n }\n if ((parseInt(countStars)===2 && countMoves === 14) || (parseInt(countStars)===1 && countMoves === 20)) {\n countStars -= 0.5;\n stars.children[countStars].firstElementChild.classList.replace('fa-star-half-o','fa-star-o');\n }\n}", "function rating (){\n let stars = document.querySelector('.stars');\n let movesNumber = movesContainer.textContent;\n if((movesNumber == 16 && stars.firstChild) || (movesNumber == 24 && stars.firstChild)){\n stars.removeChild(stars.firstChild);\n } \n}", "function subtractStars(moves) {\n if (moves === 26 || moves === 34 || moves === 42) {\n const elem = document.querySelector('.stars li');\n elem.parentNode.removeChild(elem);\n }\n }", "function stars() {\n starsNumber = 3;\n if (moves >= 10 && moves < 18) {\n thirdStar.classList.remove('fa-star', 'starColor');\n thirdStar.classList.add('fa-star-o');\n starsNumber = 2;\n } else if (moves >= 18) {\n secondStar.classList.remove('fa-star', 'starColor');\n secondStar.classList.add('fa-star-o');\n starsNumber = 1;\n }\n}", "function adjustRating() {\n const oneStar = document.querySelector(\".fa-star\").parentNode;\n if (moveCount == 28) {\n oneStar.parentNode.removeChild(oneStar);\n } else if (moveCount == 38) {\n oneStar.parentNode.removeChild(oneStar);\n }\n}", "function scoreCheck() {\n if(moveCount === 8 || moveCount === 16 || moveCount === 24) {\n removeStar();\n }\n}", "function scoreStar() {\n if (moveCounter === 18) {\n stars1 = 2 // 2 estrelas\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 22) {\n stars1 = 1 // 1 estrela\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 29) {\n stars1 = 0 // 0 estrelas\n $('.fa-star').remove()\n }\n return\n}", "function starsRating() {\n if (moves === 14 || moves === 17 || moves === 24 || moves === 28\n ) { hideStar();\n }\n}", "function starCount() {\n if (moves == 22 || moves == 27 || moves == 32) {\n hideStar();\n }\n}", "function updateMoves() {\n moves += 1;\n const move = document.querySelector(\".moves\");\n move.innerHTML = moves;\n if (moves === 16) {\n removeStar();\n starRating = 2;\n } else if (moves === 25) {\n removeStar();\n starRating = 1;\n }\n}", "function starRating () {\n if ( moveCount === 20 || moveCount === 30 ) {\n decrementStar();\n }\n}", "function loseStar(event) {\n\tlet counterMoves = Number (moves.textContent);\n\tif((counterMoves - numOfMatched) % 10 === 0 && counterStars != 1){//decrease stars after balance between counterMoves and numOfMatched with 10\n\t\tnumOfStars.children[counterStars-1].firstElementChild.className = 'fa fa-star-o';\n\t\tcounterStars--;\n\t}else{\n\t\t// alert('You are Lose!')\n\t\t// deck.removeEventListener('click', displayCard);\n\t}\n}", "function countMoves() {\n move++;\n moves.innerHTML = move;\n\n //Removes stars after a number of moves\n if (move > 15 && move < 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n } else if (move > 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "removeStar() {\n if (this.mStars != 0) {\n this.mStars--;\n }\n this.notifyStarsObservers(this.mStars);\n }", "function incrementMoves() {\n\tmoves++;\n\tdocument.querySelector('.moves').textContent = moves;\n\tif (moves === twoStar) {\n\t\tdocument.querySelector('.star-3').style.display = 'none';\n\t} else if (moves === oneStar) {\n\t\tdocument.querySelector('.star-2').style.display = 'none';\n\t}\n}", "function updateStarCounter() {\n\t// when moves counter reaches 20, one star is removed\n\tif (Number(movesMade.innerText) === 20) {\n\t\tlet star = document.querySelector('#star-one').classList.add('none');\n\t}\n\t// when moves counter reaches 29, two stars are removed\n\tif (Number(movesMade.innerText) === 29) {\n\t\tlet star = document.querySelector('#star-two').classList.add('none');\n\t}\n\t//when moves counter is zero, all stars should be shown\n\tif (Number(movesMade.innerText) === 0) {\n\t\tdocument.querySelector('#star-one').classList.remove('none');\n\t\tdocument.querySelector('#star-two').classList.remove('none');\n\t\tdocument.querySelector('#star-three').classList.remove('none');\n\t}\n}", "function UpdateMoves() {\n\n $(\"#moves\").text(moves.toString());\n // Update star's number\n if (moves >= 0 && moves <= 8) {\n starNumber = '3';\n // Remove 1st Star\n } else if (moves >= 9 && moves <= 18) {\n $(\"#starOne\").removeClass(\"fa-star\");\n starNumber = '2';\n // Remove 2nd Star \n } else if (moves >= 19 && moves <= 25) {\n $(\"#starTwo\").removeClass(\"fa-star\");\n starNumber = '1';\n }\n}", "function star(numOfMove){\n\t noMoves = numOfMove; \n\t let stars = document.querySelector(\".stars\");\n\t if(numOfMove>50){\n\t \tnoStar=1;\n stars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else if (numOfMove>30){\n\t \tnoStar=2;\n\t \tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else{\n\t \tnoStar=3;\n\t\tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n}", "function rating(numOfMistakes) {\n if ((numOfMistakes === 9)||(numOfMistakes === 12)) {\n stars.removeChild(stars.lastChild);\n starCount -= 1;\n }\n }", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector(\".moves\").innerText = moves;\n\tdocument.querySelector(\".moves-text\").innerText = \"Moves\";\n\n\tlet stars = document.querySelector(\".stars\");\n\tvar lis = stars.children.length;\n\twhile (lis < 3) {\n\t\tvar star = stars.lastElementChild.cloneNode(true);\n\t\tstars.appendChild(star);\n\t\tlis = stars.children.length;\n\t}\n}", "function starRating() {\n if (moves > 13 && moves < 16) {\n starCounter = 3;\n } else if (moves > 17 && moves < 27) {\n starCounter = 2;\n } else if (moves > 28) {\n starCounter = 1;\n }\n showStars(starCounter);\n }", "function incMoves() {\n moveCounter += 1;\n moves.innerText = moveCounter;\n //set star score\n if (moveCounter > 12 && moveCounter <= 18) {\n //if player uses more than 18 moves, but less than 24, deduct one star\n for (i = 0; i < starsList.length; i++) {\n if (i > 1) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 1;\n }\n }\n } else if (moveCounter > 18 && moveCounter <= 24) {\n //if player uses more than 24 moves, but less than 32, deduct another star\n for (i = 0; i < starsList.length; i++) {\n if (i > 0) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 2;\n }\n }\n }\n}", "function points() {\n if (totalClicks === 25) {\n removeLastStar();\n } else if (totalClicks === 40) {\n removeLastStar();\n }\n}", "function checkScore() {\n if (moves === 10 || moves === 20) {\n removeStar();\n }\n}", "function starFilterRemover(power) {\n let newStar = '../stars/star-hollow.png';\n if(power === 'top-star-5') {\n } if(power === 'top-star-4') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n } if(power === 'top-star-3') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n } if(power === 'top-star-2') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n document.getElementById('top-star-3').classList.remove('live-star');\n document.getElementById('top-star-3').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n $(document.getElementById('top-star-3')).attr('src', newStar);\n } if(power === 'top-star-1') {\n document.getElementById('top-star-5').classList.remove('live-star');\n document.getElementById('top-star-5').classList.add('star-filter','dead-star');\n document.getElementById('top-star-4').classList.remove('live-star');\n document.getElementById('top-star-4').classList.add('star-filter','dead-star');\n document.getElementById('top-star-3').classList.remove('live-star');\n document.getElementById('top-star-3').classList.add('star-filter','dead-star');\n document.getElementById('top-star-2').classList.remove('live-star');\n document.getElementById('top-star-2').classList.add('star-filter','dead-star');\n $(document.getElementById('top-star-5')).attr('src', newStar);\n $(document.getElementById('top-star-4')).attr('src', newStar);\n $(document.getElementById('top-star-3')).attr('src', newStar);\n $(document.getElementById('top-star-2')).attr('src', newStar);\n };\n filterSetting(power);\n}", "function removeStar() {\n\tlet stars = document.querySelectorAll(\".fa-star\");\n\tif (stars.length === 1) {\n\t\treturn;\n\t}\n\tfor (let star of stars) {\n\t star.parentNode.remove();\n\t return;\n \t}\n}", "function starCount() {\n\n if(numMoves < 16) {\n numStars = 3;\n }else if (numMoves >= 16 && numMoves < 25) {\n numStars = 2;\n }else {\n numStars = 1;\n };\n\n printStars();\n}", "function rating() {\n 'use strict'; // turn on Strict Mode\n if (moves > 10 && moves < 19) {\n stars[2].classList.remove('fa-star');\n stars[2].classList.add('fa-star-o');\n starsRating = 2;\n } else if (moves > 20) {\n stars[1].classList.remove('fa-star');\n stars[1].classList.add('fa-star-o');\n starsRating = 1;\n }\n}", "function removeStar() {\n $('.fa-star').last().attr('class', 'fa fa-star-o');\n numStars--;\n}", "function showStars() {\n let count;\n if (moveCount < 16) {\n count = 3;\n score = 60;\n } else if (moveCount < 32) {\n count = 2;\n score = 40;\n } else {\n count = 1;\n score = 10;\n }\n for (let i = 0; i < (stars.length - count); i++) {\n stars[i].setAttribute('style', 'display: none');\n }\n}", "function clearNextMovesMarkers() {\n mapSquares(square => square.canBeNextMove = false);\n}", "function updateStars() {\n // if moves <=12 with 3 starts\n if (moves <= 12) {\n $('.stars .fa').addClass(\"fa-star\");\n stars = 3;\n } else if(moves >= 13 && moves <= 14){\n $('.stars li:last-child .fa').removeClass(\"fa-star\");\n $('.stars li:last-child .fa').addClass(\"fa-star-o\");\n stars = 2;\n } else if (moves >= 15 && moves <20){\n $('.stars li:nth-child(2) .fa').removeClass(\"fa-star\");\n $('.stars li:nth-child(2) .fa').addClass(\"fa-star-o\");\n stars = 1;\n } else if (moves >=20){\n $('.stars li .fa').removeClass(\"fa-star\");\n $('.stars li .fa').addClass(\"fa-star-o\");\n stars = 0;\n }\n $('.win-container .stars-number').text(stars);\n\n}", "function starsEarned() {\n if (moves > 8 && moves < 12) {\n for (i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"hidden\";\n }\n }\n } else if (moves > 13) {\n for (i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"hidden\";\n }\n }\n }\n}", "function moveCounter() {\n moves += 1;\n moveField = document.getElementsByClassName(\"moves\");\n moveField[0].innerHTML = moves;\n\n if (moves === 16) {\n let starList = document.querySelectorAll('.fa-star');\n let star1 = starList[2];\n star1.style.color = \"black\";\n stars--\n } else if (moves === 24) {\n let starList = document.querySelectorAll('.fa-star');\n let star2 = starList[1];\n star2.style.color = \"black\";\n stars--\n }\n}", "function updateMoves() {\n if (moves === 1) {\n $(\"#movesText\").text(\" Move\");\n } else {\n $(\"#movesText\").text(\" Moves\");\n }\n $(\"#moves\").text(moves.toString());\n\n if (moves > 0 && moves < 16) { // gives star rating according the no of moves ,removes the class\n starRating = starRating;\n } else if (moves >= 16 && moves <= 20) {\n $(\"#starOne\").removeClass(\"fa-star\");\n starRating = \"2\";\n } else if (moves > 20) {\n $(\"#starTwo\").removeClass(\"fa-star\");\n starRating = \"1\";\n }\n}", "function starScore () {\n if (moves >= 12) {\n stars[3].setAttribute('style', 'visibility: hidden');\n finalStarScore = 3;\n } \n if (moves >= 18) {\n stars[2].setAttribute('style', 'visibility: hidden');\n finalStarScore = 2;\n }\n if (moves >= 25) {\n stars[1].setAttribute('style', 'visibility: hidden');\n finalStarScore = 1;\n }\n}", "function starRating() {\n var starsTracker = starsPanel.getElementsByTagName('i');\n\n // If game finished in 11 moves or less, return and star rating remains at 3\n if (moves <= 11) {\n return;\n // If finished between 11 to 16 moves, 3rd colored star is replaced with empty star class\n } else if (moves > 11 && moves <= 16) {\n starsTracker.item(2).className = 'fa fa-star-o';\n // If finished with more than 16 moves, 2nd colored star is replaced with empty star class\n } else {\n starsTracker.item(1).className = 'fa fa-star-o';\n }\n\n // Update stars variable by counting length of remaining colored star elements\n stars = document.querySelectorAll('.fa-star').length;\n}", "function setStars() {\n /*Grabs the section in the html that has the moves count and updates it based on moves variable. */\n document.getElementById(\"moves\").textContent = moves;\n /*Conditional used to determine what stars to display depending on the number of moves/2clicks occur. */\n if (moves <= 10){\n starsRating = 3;\n return;\n } \n /*Grabs stars elements so that later the classes can be manipulated to display clear starts instead of full stars. */\n let stars = document.getElementById(\"stars\").children;\n /*If the user has taken over 10 moves/2 clicks, then one star is replaced with a star outline. */\n stars[2].firstElementChild.classList.remove(\"fa-star\");\n stars[2].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 20){\n starsRating = 2;\n return;\n } \n /*If the user has taken over 20 moves/2 clicks, then an addional star is repalced with a star outline. */\n stars[1].firstElementChild.classList.remove(\"fa-star\");\n stars[1].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 30) {\n starsRating = 1;\n return;\n } \n}", "function removeLastStar() {\n let lastStar = totalStars.length - 1;\n removedStarsArray.push(totalStars[lastStar]);\n totalStars[lastStar].classList.add(\"remove-star\");\n totalStars[lastStar].classList.remove(\"star-img\");\n}", "function ratings() {\n\tif(moveCounter > 12 && moveCounter <= 16) {\n\t\tsStar[0].style.cssText = 'opacity: 0';\n\t\tcStar[0].style.cssText = 'display: none';\n\t}\n\tif(moveCounter > 16) {\n\t\tsStar[1].style.cssText = 'opacity: 0';\n\t\tcStar[1].style.cssText = 'display: none';\t\n\t}\n}", "function starRating() {\n if (moves === 15) {\n starChanger[0].classList.add('hide');\n starChanger[3].classList.add('hide');\n starChanger[1].classList.add('silver');\n starChanger[4].classList.add('silver');\n starChanger[2].classList.add('silver');\n starChanger[5].classList.add('silver');\n\n } if (moves === 20) {\n starChanger[1].classList.add('hide');\n starChanger[4].classList.add('hide');\n starChanger[2].classList.add('bronze');\n starChanger[5].classList.add('bronze');\n }\n}", "function starRating(moves) {\n if (moves >= 12 && moves < 18) {\n starCount.childNodes[5].childNodes[0].className = 'fa fa-star-o';\n } else if (moves >= 18) {\n starCount.childNodes[3].childNodes[0].className = 'fa fa-star-o';\n }\n return starCount;\n}", "function updateScore() {\n $('.moves').text(movesCounter);\n if (movesCounter > 10 && movesCounter <= 15 ) {\n $('#thirdStar').removeClass('fa fa-star');\n $('#thirdStar').addClass('fa fa-star-o');\n starsCounter = 2;\n }\n else if (movesCounter > 15) {\n $('#secondStar').removeClass('fa fa-star');\n $('#secondStar').addClass('fa fa-star-o');\n starsCounter = 1;\n }\n // you should have at least 1 star\n}", "function addAMove(){\n moves++;\n moveCounter.innerHTML = moves;\n //game displays a star rating from 1 to at least 3 stars - after some number of moves, star rating lowers\n if (moves > 8 && moves < 12) {\n numStars = 4;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 12 && moves < 20) {\n numStars = 3;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 20 && moves < 30) {\n numStars = 2;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves > 30) {\n numStars = 1;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n}", "function countStars() {\n\n if (moves <= 20) {\n stars = 3;\n } else if (moves <= 25) {\n stars = 2;\n } else {\n stars = 1;\n }\n\n displayStars();\n}", "function decrementStars() {\n $(\".stars i.fa-star\").first()\n .removeClass(\"fa-star\")\n .addClass(\"fa-star-o\");\n stars -= 1;\n }", "function countMove() {\n moves++;\n count.innerHTML = moves;\n if (moves < 20 && moves > 12) {\n starCount[1].style.display = 'none';\n } else if (moves > 20) {\n starCount[2].style.display = 'none';\n }\n}", "function removeStar() {\n const stars = document.querySelectorAll('.fa-star');\n for (let i = 0; i < stars.length; i++) {\n if (stars[i].style.display !== 'none') {\n stars[i].style.display = 'none';\n break;\n }\n }\n}", "function addMove() {\n moves ++;\n moveCount.innerHTML = moves;\n if(moves === 10) {\n hideStar();\n } else if(moves === 20) {\n hideStar();\n }\n}", "function collectStar(player, star) {\n star.kill();\n score += 10;\n scoreText.text = 'Score: ' + score;\n }", "function stars() {\n\tconst starar = star.getElementsByTagName('i');\n\tfor (i = 0; i < starar.length; i++) {\n\t\tif (moves > 14 && moves <= 19) {\n\t\t\tstarar[2].className = 'fa fa-star-o';\n\t\t\tstarnum = 2;\n\t\t} else if (moves > 19) {\n\t\t\tstarar[1].className = 'fa fa-star-o';\n\t\t\tstarnum = 1;\n//\t\t} else if (moves > 24) {\n//\t\t\tstarar[0].className = 'fa fa-star-o';\n//\t\t\tstarnum = 0;\n\t\t} else {\n\t\t\tstarar[0].className = 'fa fa-star';\n\t\t\tstarar[1].className = 'fa fa-star';\n\t\t\tstarar[2].className = 'fa fa-star';\n\t\t\tstarnum = 3;\n\t\t}\n\t}\n}", "function removeStar() {\n const star = document.querySelector(\".stars\");\n const starChild = star.firstElementChild;\n star.removeChild(starChild);\n}", "function starlevel() {\n\tif (movesCount >= 14 && movesCount <= 20) {\n\t\tstarCount = 2;\n\t\tstarSection[2].style.display = \"none\";\n\t}\n\tif (movesCount > 20) {\n\t\tstarCount = 1;\n\t\tstarSection[1].style.display = \"none\";\n\t}\n}", "cleanMovePossible(){\n for(let i = this.placementsPossibles.length - 1; i >= 0; i--){\n if(i < this.placementsPossibles.length){\n let td = this.placementsPossibles[i]; \n let x = parseInt(td.id.charAt(4));\n let y = parseInt(td.id.charAt(5));\n let j = getPion(x,y);\n if(j != undefined){\n if(pions[j].color == this.color){\n this.placementsPossibles.splice(i, 1);\n }\n }\n }\n }\n }", "function calculateRemainingStars() {\n if (state.totalMoves >= 0 && state.totalMoves < 15) {\n return 3;\n }\n \n if (state.totalMoves >= 15 && state.totalMoves < 25) {\n return 2;\n }\n \n if (state.totalMoves >= 25) {\n return 1;\n }\n \n throw 'Unable to calculate remaining stars';\n }", "function setStars() {\n if (movements === 0) {\n totalStars = 3;\n let fStar = document.querySelector(\"#firstStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star\";\n newStar.id=\"firstStar\";\n starsUl.appendChild(newStar);\n let sStar = document.querySelector(\"#secondStar\");\n sStar.remove();\n let starsUl2 = document.querySelector(\".stars\");\n let newStar2 = document.createElement(\"li\");\n newStar2.className = \"fa fa-star\";\n newStar2.id=\"secondStar\";\n starsUl.appendChild(newStar2);\n let tStar = document.querySelector(\"#thirdStar\");\n tStar.remove();\n let starsUl3 = document.querySelector(\".stars\");\n let newStar3 = document.createElement(\"li\");\n newStar3.className = \"fa fa-star\";\n newStar3.id=\"thirdStar\";\n starsUl.appendChild(newStar3);}\n else if (movements === 14) {\n totalStars = 2;\n let fStar = document.querySelector(\"#firstStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"firstStar\";\n starsUl.appendChild(newStar);\n } else if (movements === 21) {\n totalStars = 1;\n let fStar = document.querySelector(\"#secondStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"secondStar\";\n starsUl.appendChild(newStar);\n } else if (movements === 24) {\n totalStars = 0;\n let fStar = document.querySelector(\"#thirdStar\");\n fStar.remove();\n let starsUl = document.querySelector(\".stars\");\n let newStar = document.createElement(\"li\");\n newStar.className = \"fa fa-star-o\";\n newStar.id=\"thirdStar\";\n starsUl.appendChild(newStar);\n }\n}", "function resetStars() {\n /*Grabs the children of the section of the html with the stars ID and assigns them to the stars variable. */\n let stars = document.getElementById(\"stars\").children;\n /*Enters 0 for the text content next to moves in the html, to indicate the user hasn't taken any moves in the new game yet. */\n document.getElementById(\"moves\").textContent = 0;\n /*Iterates over the stars in the stars variable and returns them all to stars and not star outlines. */\n for (let star of stars) {\n star.firstElementChild.classList.remove(\"fa-star-o\");\n star.firstElementChild.classList.add(\"fa-star\");\n }\n}", "function rating() {\n\tconst star1 = document.getElementById(\"one-star\");\n\tconst star2 = document.getElementById(\"two-star\");\n\tconst star3 = document.getElementById(\"three-star\");\n\t// change stars style depending on number of moves\n\tif (moveCounter == 18) {\n\t\tstar1.classList.remove(\"fas\");\n\t\tstar1.classList.add(\"far\");\n\t} else if (moveCounter == 16){\n\t\tstar2.classList.remove(\"fas\");\n\t\tstar2.classList.add(\"far\");\n\t} else if (moveCounter == 14) {\n\t\tstar3.classList.remove(\"fas\");\n\t\tstar3.classList.add(\"far\");\n\t} else {\n\t\t\n\t}\n}", "function starRating(){\n if (moves === 14 || moves === 24) {\n deathStar()\n }\n}", "function moves1(){\n if (document.getElementById(\"numberMoves\").innerText ==16){\n $(container[2]).removeClass(\"fa fa-star\") ;\n }\n else if (document.getElementById(\"numberMoves\").innerText ==32) {\n $(container[1]).removeClass(\"fa fa-star\");\n }\n\n\n}", "function make_stars() {\n var i, vb;\n vb = SVG.viewBox.baseVal;\n while (STARS.firstChild) {\n STARS.removeChild(STARS.firstChild);\n }\n for (i = 0; i < N_STARS; i += 1) {\n make_star(vb, STARS);\n }\n }", "function reSet(){\n count = 0;\n $('.moves').html('');\n $('.stars li').each( function(i){\n this.style.display = '';\n });\n stopClock();\n time = 0;\n check = 0;\n}", "function rating(){\n //// TODO: Bug has been fixed\n if (!cardCouple[0].classList.contains('match') && !cardCouple[1].classList.contains('match')){\n moves.innerText++;\n }\n if (moves.innerText > 14){\n document.querySelector('.stars li:nth-child(1)').classList.add('starDown');\n }\n else if (moves.innerText > 20){\n document.querySelector('.stars li:nth-child(2)').classList.add('starDown');\n }\n}", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n textMoves();\n\n /*\n * Check to determine the player's rating after\n * certain number of moves have been exceeded\n */\n if (moves > 12 && moves < 19) {\n starsArray.forEach(function(star, i) {\n if (i > 1) {\n star.style.visibility = 'collapse';\n }\n });\n } else if (moves > 20) {\n starsArray.forEach(function(star, i) {\n if (i > 0) {\n star.style.visibility = 'collapse';\n }\n });\n }\n}", "function stars() {\n if (numberOfMoves === 14) {\n star[2].style.color = '#ccc';\n }\n if (numberOfMoves === 22) {\n star[1].style.color = '#ccc';\n }\n}", "function stars() {\n if (numberOfMoves === 14) {\n star[2].style.color = '#ccc';\n }\n if (numberOfMoves === 22) {\n star[1].style.color = '#ccc';\n }\n}", "function updateStars() {\n if (moves > 10 && moves < 20) {\n starsList[4].setAttribute('class', 'fa fa-star-o');\n stars = 4;\n }\n if (moves >= 20 && moves < 30) {\n starsList[3].setAttribute('class', 'fa fa-star-o');\n stars = 3;\n }\n if (moves >= 30 && moves < 40) {\n starsList[2].setAttribute('class', 'fa fa-star-o');\n stars = 2;\n }\n if (moves >= 40) {\n starsList[1].setAttribute('class', 'fa fa-star-o');\n stars = 1;\n }\n }", "function checkMovesNumber() {\n const STAR_1 = document.getElementById('star1');\n const STAR_2 = document.getElementById('star2');\n const STAR_3 = document.getElementById('star3');\n if (movesNumber > 14 && movesNumber <= 18) {\n starRating = 2.5;\n STAR_3.classList.remove('fa-star');\n STAR_3.classList.add('fa-star-half-o');\n } else if (movesNumber > 18 && movesNumber <= 22) {\n starRating = 2;\n STAR_3.classList.remove('fa-star-half-o');\n STAR_3.classList.add('fa-star-o');\n } else if (movesNumber > 22 && movesNumber <= 26) {\n starRating = 1.5;\n STAR_2.classList.remove('fa-star');\n STAR_2.classList.add('fa-star-half-o');\n } else if (movesNumber > 26 && movesNumber <= 30) {\n starRating = 1;\n STAR_2.classList.remove('fa-star-half-o');\n STAR_2.classList.add('fa-star-o');\n } else if (movesNumber > 30 && movesNumber <= 34) {\n starRating = 0.5;\n STAR_1.classList.remove('fa-star');\n STAR_1.classList.add('fa-star-half-o');\n } else if (movesNumber > 34) {\n starRating = 0;\n STAR_1.classList.remove('fa-star-half-o');\n STAR_1.classList.add('fa-star-o');\n alert('Game over! Du hattest zu viele Züge! Versuche es erneut!\\nAnzahl Züge: ' + movesNumber + '\\nVergangene Zeit: ' + sec + ' Sekunden' + '\\nDeine Bewertung: ' + starRating + ' Sterne');\n clearInterval(timer);\n } else {\n return;\n }\n}", "function setStars() {\r\nlet starsDOM = document.querySelector('.stars');\r\n if (moveCounter == 0) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 3;\r\n } else if (moveCounter == 14) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 2;\r\n } else if (moveCounter == 22) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 1;\r\n } else if (moveCounter == 30) {\r\n starsDOM.innerHTML = ``;\r\n starCounter = 0;\r\n }\r\n}", "function incrementMovesCounter(){\n movesCounter++;\n document.querySelector('.moves').textContent = movesCounter;\n if(movesCounter === 16){\n document.querySelectorAll('.fa-star')[2].className = \"fa fa-star-o\";\n }else if (movesCounter === 24) {\n document.querySelectorAll('.fa-star')[1].className = \"fa fa-star-o\";\n }\n}", "function rating(moves) {\n let rating = 3;\n if (moves > stars3 && moves < stars2) {\n $rating.eq(3).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > stars2 && moves < star1) {\n $rating.eq(2).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > star1) {\n $rating.eq(1).removeClass('fa-star').addClass('fa-star-o');\n rating = 1;\n }\n return { score: rating };\n}", "function moveCount() {\n debug(\"moveCount\");\n let count = parseInt(document.querySelector('.moves').innerHTML, 10);\n let x = count + 1;\n \n document.querySelector('.moves').innerHTML = x;\n if (x > 29 && x < 40) {\n document.querySelector('.stars').childNodes[2].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n if (x >= 40 && x < 49) {\n document.querySelector('.stars').childNodes[1].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n }", "function clearStars() {\n starCount();\n let stars = document.querySelectorAll('.stars li i');\n stars[0].classList.remove('hide');\n stars[1].classList.remove('hide');\n stars[2].classList.remove('hide');\n starCounter = 0;\n }", "function updateMoves() {\n moves += 1;\n $('#moves').html(`${moves} Moves`);\n if (moves === 24) {\n addBlankStar();\n }\n else if (moves === 16) {\n addBlankStar();\n }\n}", "function countMoves() {\n\n num++;\n moves.textContent = num;\n\n if (num === 1) {\n //start the stopwatch on the first move\n startTimer();\n } else if (num > 1) {\n //reduce the number of stars based on number of moves\n if (num > 49) {\n endGame(); //moves limit for game\n } else if (num > 18) {\n stars[1].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n } else if (num > 12) {\n stars[2].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n }\n }\n}", "function updateStarsDisplay(counter){\n let stars = document.getElementsByClassName(\"fa-star\");\n\n // for every 16 moves (or number of cards), remove a star\n if (counter > 0 && stars.length > 0){\n let penaltyLimit = cards.length + 1; \n let z = counter % penaltyLimit;\n if (z == 0){\n stars[0].classList.add(\"fa-star-o\");\n stars[0].classList.remove(\"fa-star\");\n }\n }\n return stars.length;\n}", "function removeStar() {\n\t$('#star1').last().remove();\n\t$('#star2').last().remove();\n\t$('#stars1').append('<li><i class=\"fa fa-star-o\" id=\"star1\"></i></li>');\n\t$('#stars2').append('<li><i class=\"fa fa-star-o\" id=\"star2\"></i></li>');\n\n}", "function starRating() {\n let lastStar;\n let lastModalStar;\n const deckStars = document.querySelectorAll('.stars .fa-star')\n const modalStars = document.querySelectorAll('.winStars .fa-star')\n if (moves === 33) {\n lastStar = deckStars[2];\n lastModalStar = modalStars[2];\n } else if (moves === 45) {\n lastStar = deckStars[1];\n lastModalStar = modalStars[1];\n } else if (moves === 52) {\n lastStar = deckStars[0];\n lastModalStar = modalStars[0];\n }\n if (lastStar !== undefined) {\n lastStar.classList.replace('fa-star', 'fa-star-o');\n lastModalStar.classList.replace('fa-star', 'fa-star-o');\n }\n}", "function updateRating() {\n //Rating game based on move count\n if (numMoves == (moves_to_two_stars)) {\n stars[2].classList.remove(\"fa-star\");\n stars[2].classList.add(\"fa-star-o\");\n rating = 2;\n }\n else if (numMoves == (moves_to_one_star)) {\n stars[1].classList.remove(\"fa-star\");\n stars[1].classList.add(\"fa-star-o\");\n rating = 1;\n }\n}", "function rateTheStars(moves){\n if (moves > 24) {\n console.log(\"1 star\");\n starRating = 1;\n } else if (moves > 20) {\n console.log(\"2 stars\");\n starRating = 2;\n } else if (moves > 16){\n console.log(\"3 stars\");\n starRating = 3;\n } else if (moves > 12){\n console.log(\"4 stars\");\n starRating = 4;\n } else {\n starRating=5;\n }\n starColors(starRating);\n }", "function countUpTimer() {\n seconds = 0;\n var el = document.getElementById('timer');\n var decFactor = 3;\n function incrementSeconds() {\n seconds += 1;\n el.innerText = seconds;\n if (seconds * totalMoves > 600 && seconds * totalMoves < 1200) {\n if (decFactor === 3) {\n decFactor = 2;\n let starsElement = document.getElementsByClassName('stars')[0];\n starsElement.removeChild(document.getElementsByTagName('li')[0]);\n } else {\n\n }\n } else if (seconds * totalMoves > 1200 && seconds * totalMoves < 1800) {\n if (decFactor === 2) {\n decFactor = 1;\n let starsElement = document.getElementsByClassName('stars')[0];\n starsElement.removeChild(document.getElementsByTagName('li')[0]);\n } else {\n\n }\n }\n }\n cancel = setInterval(incrementSeconds, 1000);\n}", "function moveCounter() {\n moveCount ++;\n moves.textContent = moveCount;\n // star Rating:\n let starRating = document.getElementsByClassName(\"stars\")[0];\n if (moveCount > 20) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li> <li><i class=\\\"fa fa-star\\\"></i></li>\";\n } else if (moveCount > 30) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li>\";\n }\n}", "function starRestart() {\n starChanger[0].classList.remove('hide');\n starChanger[3].classList.remove('hide');\n starChanger[1].classList.remove('hide');\n starChanger[4].classList.remove('hide');\n starChanger[1].classList.remove('silver');\n starChanger[4].classList.remove('silver');\n starChanger[2].classList.remove('silver');\n starChanger[5].classList.remove('silver');\n starChanger[2].classList.remove('bronze');\n starChanger[5].classList.remove('bronze');\n}", "function resetStars(){\n $('#star-10').attr('src','images/star.png');\n $('#star-20').attr('src','images/star.png');\n $('#star-30').attr('src','images/star.png');\n endingStarBonus += startingStars;\n startingStars = 3;\n incorrectGuesses = 0;\n}" ]
[ "0.76538664", "0.76076657", "0.7605075", "0.758455", "0.75703126", "0.75592345", "0.7516247", "0.74422425", "0.74289495", "0.7418153", "0.7416017", "0.74063593", "0.7231626", "0.7148592", "0.7124285", "0.7105445", "0.70814943", "0.702841", "0.7028299", "0.700433", "0.6989616", "0.69488275", "0.6892232", "0.686902", "0.6861472", "0.6822686", "0.6795103", "0.6773213", "0.6759909", "0.67473215", "0.67143255", "0.6705548", "0.667576", "0.6611714", "0.6610787", "0.66093713", "0.6562591", "0.6523178", "0.6476537", "0.6467844", "0.6446436", "0.6403019", "0.639314", "0.6384497", "0.63683987", "0.6346586", "0.6338526", "0.6329994", "0.6327898", "0.6326657", "0.63246703", "0.6313756", "0.6297628", "0.6277568", "0.6270362", "0.6264057", "0.62567234", "0.6256029", "0.62417626", "0.62404335", "0.62398094", "0.6234523", "0.6211425", "0.6202973", "0.62003887", "0.61952746", "0.61769104", "0.617379", "0.6166975", "0.61645544", "0.61408705", "0.6129986", "0.6128636", "0.61275727", "0.6120364", "0.609532", "0.6082562", "0.60702556", "0.6069884", "0.60648507", "0.60579395", "0.60579395", "0.6055113", "0.6039811", "0.60283536", "0.60216", "0.6018557", "0.5989954", "0.59760755", "0.59533346", "0.5939969", "0.5934379", "0.5930157", "0.5924739", "0.5922742", "0.59154695", "0.5912015", "0.5910449", "0.5909557", "0.59079736" ]
0.64332324
41
count how many stars left to display based on how many moves user make
function updateStar() { let starCount = 0; for(star of allStars) { if(star.hidden === false) { starCount++; } } return starCount; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function moveCount () {\n var moves = parseInt($(\".moves\").text())\n moves += 1\n $(\".moves\").text(moves)\n stars( moves )\n}", "function countStars() {\n\n if (moves <= 20) {\n stars = 3;\n } else if (moves <= 25) {\n stars = 2;\n } else {\n stars = 1;\n }\n\n displayStars();\n}", "function starCount() {\n\n if(numMoves < 16) {\n numStars = 3;\n }else if (numMoves >= 16 && numMoves < 25) {\n numStars = 2;\n }else {\n numStars = 1;\n };\n\n printStars();\n}", "function starRating() {\n if (moves > 13 && moves < 16) {\n starCounter = 3;\n } else if (moves > 17 && moves < 27) {\n starCounter = 2;\n } else if (moves > 28) {\n starCounter = 1;\n }\n showStars(starCounter);\n }", "function starCount() {\n if (moves == 22 || moves == 27 || moves == 32) {\n hideStar();\n }\n}", "function moveCount() {\n debug(\"moveCount\");\n let count = parseInt(document.querySelector('.moves').innerHTML, 10);\n let x = count + 1;\n \n document.querySelector('.moves').innerHTML = x;\n if (x > 29 && x < 40) {\n document.querySelector('.stars').childNodes[2].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n if (x >= 40 && x < 49) {\n document.querySelector('.stars').childNodes[1].lastChild.setAttribute(\"class\", \"fa fa-star-o\");\n }\n }", "function countMoves() {\n move++;\n moves.innerHTML = move;\n\n //Removes stars after a number of moves\n if (move > 15 && move < 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n } else if (move > 20) {\n for (let i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "function calculateRemainingStars() {\n if (state.totalMoves >= 0 && state.totalMoves < 15) {\n return 3;\n }\n \n if (state.totalMoves >= 15 && state.totalMoves < 25) {\n return 2;\n }\n \n if (state.totalMoves >= 25) {\n return 1;\n }\n \n throw 'Unable to calculate remaining stars';\n }", "function howManyStars() {\n\tif (Number(movesMade.innerText) < 20) {\n\t\treturn \"3 stars\";\n\t}\n\tif (Number(movesMade.innerText) > 19 && Number(movesMade.innerText) < 29) {\n\t\treturn \"2 stars\";\n\t}\n\tif (Number(movesMade.innerText) > 28) {\n\t\treturn \"1 star\";\n\t}\n}", "function moveCounter() {\n moves += 1;\n moveField = document.getElementsByClassName(\"moves\");\n moveField[0].innerHTML = moves;\n\n if (moves === 16) {\n let starList = document.querySelectorAll('.fa-star');\n let star1 = starList[2];\n star1.style.color = \"black\";\n stars--\n } else if (moves === 24) {\n let starList = document.querySelectorAll('.fa-star');\n let star2 = starList[1];\n star2.style.color = \"black\";\n stars--\n }\n}", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n textMoves();\n\n /*\n * Check to determine the player's rating after\n * certain number of moves have been exceeded\n */\n if (moves > 12 && moves < 19) {\n starsArray.forEach(function(star, i) {\n if (i > 1) {\n star.style.visibility = 'collapse';\n }\n });\n } else if (moves > 20) {\n starsArray.forEach(function(star, i) {\n if (i > 0) {\n star.style.visibility = 'collapse';\n }\n });\n }\n}", "function countStars() {\n if (moves <= 30) { //star count will be initial value of 3 stars\n document.getElementById(\"oneStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"twoStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"threeStar\").style.visibility = 'visible'; //star is visible//\n document.getElementById(\"oneStar\").style.color = 'green'; //star colour is green//\n document.getElementById(\"twoStar\").style.color = 'green'; //star colour is green//\n document.getElementById(\"threeStar\").style.color = 'green'; //star colour is green//\n } else if (moves > 30 && moves < 50) {\n document.getElementById(\"threeStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"oneStar\").style.color = 'yellow'; //star colour is yellow//\n document.getElementById(\"twoStar\").style.color = 'yellow'; //star colour is yellow//\n stars = 2; //star count will be 2 stars//\n } else if (moves > 50) {\n document.getElementById(\"twoStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"threeStar\").style.visibility = 'hidden'; //star is hidden\n document.getElementById(\"oneStar\").style.color = 'red'; //star colour is red//\n stars = 1; //star count will be 1 star//\n }\n }", "function starCounter(moves) {\r\n if (moves >= 20 && moves <= 30) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(4);\r\n } else if (moves >= 31 && moves <= 40) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(3);\r\n } else if (moves >= 41 && moves <= 50) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(2);\r\n } else if (moves >= 51) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(1);\r\n } else {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(5);\r\n\r\n }\r\n}", "function recalcStars() {\n const stars = document.querySelector(\".stars\");\n if ((countStars===3 && countMoves === 11) || (countStars===2 && countMoves === 17) ) {\n stars.children[countStars-1].firstElementChild.classList.replace('fa-star','fa-star-half-o');\n countStars -= 0.5;\n }\n if ((parseInt(countStars)===2 && countMoves === 14) || (parseInt(countStars)===1 && countMoves === 20)) {\n countStars -= 0.5;\n stars.children[countStars].firstElementChild.classList.replace('fa-star-half-o','fa-star-o');\n }\n}", "function starCount() {\n if (moveCountNum === 20 || moveCountNum === 35) {\n removeStar();\n }\n}", "function countingMoves() {\n countMoves += 1;\n moves.textContent = countMoves;\n starRating();\n}", "function countMove() {\n moves++;\n count.innerHTML = moves;\n if (moves < 20 && moves > 12) {\n starCount[1].style.display = 'none';\n } else if (moves > 20) {\n starCount[2].style.display = 'none';\n }\n}", "function moveCount(){\n moves++;\n const allMoves=document.querySelector('.moves');\n allMoves.innerHTML=moves+ ' Moves';\n starRating(moves);\n if(moves===1){\n startCount();\n }\n}", "function updateScore() {\n $('.moves').text(movesCounter);\n if (movesCounter > 10 && movesCounter <= 15 ) {\n $('#thirdStar').removeClass('fa fa-star');\n $('#thirdStar').addClass('fa fa-star-o');\n starsCounter = 2;\n }\n else if (movesCounter > 15) {\n $('#secondStar').removeClass('fa fa-star');\n $('#secondStar').addClass('fa fa-star-o');\n starsCounter = 1;\n }\n // you should have at least 1 star\n}", "function moveCounter() {\n moveCount ++;\n moves.textContent = moveCount;\n // star Rating:\n let starRating = document.getElementsByClassName(\"stars\")[0];\n if (moveCount > 20) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li> <li><i class=\\\"fa fa-star\\\"></i></li>\";\n } else if (moveCount > 30) {\n starRating.innerHTML = \"<li><i class=\\\"fa fa-star\\\"></i></li>\";\n }\n}", "function starCount() {\n let stars = document.querySelectorAll('.stars li i');\n\n switch (true) {\n case ( cardMoves >= 24):\n stars[2].classList.add('hide');\n starCounter = 0;\n break;\n case (cardMoves >= 18):\n stars[1].classList.add('hide');\n starCounter = 1;\n break;\n case (cardMoves >= 9):\n stars[0].classList.add('hide');\n starCounter = 2;\n break;\n default:\n starCounter = 3;\n }\n }", "function moveCounter() {\n if (clickedCards.length === 0) {\n moves++;\n moveNumber.innerHTML = moves;\n starRating(moves);\n }\n}", "function updateStarCounter() {\n\t// when moves counter reaches 20, one star is removed\n\tif (Number(movesMade.innerText) === 20) {\n\t\tlet star = document.querySelector('#star-one').classList.add('none');\n\t}\n\t// when moves counter reaches 29, two stars are removed\n\tif (Number(movesMade.innerText) === 29) {\n\t\tlet star = document.querySelector('#star-two').classList.add('none');\n\t}\n\t//when moves counter is zero, all stars should be shown\n\tif (Number(movesMade.innerText) === 0) {\n\t\tdocument.querySelector('#star-one').classList.remove('none');\n\t\tdocument.querySelector('#star-two').classList.remove('none');\n\t\tdocument.querySelector('#star-three').classList.remove('none');\n\t}\n}", "function incMoves() {\n moveCounter += 1;\n moves.innerText = moveCounter;\n //set star score\n if (moveCounter > 12 && moveCounter <= 18) {\n //if player uses more than 18 moves, but less than 24, deduct one star\n for (i = 0; i < starsList.length; i++) {\n if (i > 1) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 1;\n }\n }\n } else if (moveCounter > 18 && moveCounter <= 24) {\n //if player uses more than 24 moves, but less than 32, deduct another star\n for (i = 0; i < starsList.length; i++) {\n if (i > 0) {\n starsList[i].style.visibility = \"collapse\";\n score = starsList.length - 2;\n }\n }\n }\n}", "function countMoves() {\n\n num++;\n moves.textContent = num;\n\n if (num === 1) {\n //start the stopwatch on the first move\n startTimer();\n } else if (num > 1) {\n //reduce the number of stars based on number of moves\n if (num > 49) {\n endGame(); //moves limit for game\n } else if (num > 18) {\n stars[1].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n } else if (num > 12) {\n stars[2].innerHTML = '<i class=\"fa fa-star-o\"></i>';\n }\n }\n}", "function incrementMoves() {\n\tmoves++;\n\tdocument.querySelector('.moves').textContent = moves;\n\tif (moves === twoStar) {\n\t\tdocument.querySelector('.star-3').style.display = 'none';\n\t} else if (moves === oneStar) {\n\t\tdocument.querySelector('.star-2').style.display = 'none';\n\t}\n}", "function updateStarCount()\n\t{\n\t\tif ( previousCard == null )\n\t\t{\n\t\t\tif ( movesCounter == 20 || movesCounter == 30 )\n\t\t\t{\n\t\t\t\t$('ul.stars li').first().remove();\n\t\t\t}\n\t\t}\t\t\t\t\n\t}", "function movesCounter(){\n count = count + 1;// count moves\n if(count ===1){startclockTime();}//once first card clicked times function invoked\n $('.moves').html(count);\n if(count === 16 || count === 24 || count === 30){\n starDrop(count)\n }\n}", "function incrementNoOfMoves() {\n let noOfMoves = parseInt(document.querySelector('.moves').textContent);\n noOfMoves++;\n manageStars(noOfMoves);\n document.querySelector('.moves').textContent = noOfMoves;\n}", "function countMoves() {\n clicksCount++;\n movesCount.innerHTML = clicksCount;\n\n // when game starts, get initial time\n if (clicksCount == 1) {\n gameTimer();\n }\n\n // hide stars if clicks go beyond a certain value\n if (clicksCount > 25 && clicksCount < 35) {\n starRating[0].style.display = 'none';\n starRatingModal[0].style.display = 'none';\n } else if (clicksCount >= 35) {\n starRating[0].style.display = 'none';\n starRating[1].style.display = 'none';\n starRatingModal[0].style.display = 'none';\n starRatingModal[1].style.display = 'none';\n }\n}", "function calcMoves() {\n moves++;\n movesSpan.innerText = moves;\n updateStars();\n }", "function stars() {\n starsNumber = 3;\n if (moves >= 10 && moves < 18) {\n thirdStar.classList.remove('fa-star', 'starColor');\n thirdStar.classList.add('fa-star-o');\n starsNumber = 2;\n } else if (moves >= 18) {\n secondStar.classList.remove('fa-star', 'starColor');\n secondStar.classList.add('fa-star-o');\n starsNumber = 1;\n }\n}", "function addAMove(){\n moves++;\n moveCounter.innerHTML = moves;\n //game displays a star rating from 1 to at least 3 stars - after some number of moves, star rating lowers\n if (moves > 8 && moves < 12) {\n numStars = 4;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 12 && moves < 20) {\n numStars = 3;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves >= 20 && moves < 30) {\n numStars = 2;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li><li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n if (moves > 30) {\n numStars = 1;\n stars.innerHTML = `<li class=\"star\"><i class=\"fa fa-star\"></i></li>`;\n }\n}", "function scoreStar() {\n if (moveCounter === 18) {\n stars1 = 2 // 2 estrelas\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 22) {\n stars1 = 1 // 1 estrela\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 29) {\n stars1 = 0 // 0 estrelas\n $('.fa-star').remove()\n }\n return\n}", "function updateStarsDisplay(counter){\n let stars = document.getElementsByClassName(\"fa-star\");\n\n // for every 16 moves (or number of cards), remove a star\n if (counter > 0 && stars.length > 0){\n let penaltyLimit = cards.length + 1; \n let z = counter % penaltyLimit;\n if (z == 0){\n stars[0].classList.add(\"fa-star-o\");\n stars[0].classList.remove(\"fa-star\");\n }\n }\n return stars.length;\n}", "function updateStars() {\n // if moves <=12 with 3 starts\n if (moves <= 12) {\n $('.stars .fa').addClass(\"fa-star\");\n stars = 3;\n } else if(moves >= 13 && moves <= 14){\n $('.stars li:last-child .fa').removeClass(\"fa-star\");\n $('.stars li:last-child .fa').addClass(\"fa-star-o\");\n stars = 2;\n } else if (moves >= 15 && moves <20){\n $('.stars li:nth-child(2) .fa').removeClass(\"fa-star\");\n $('.stars li:nth-child(2) .fa').addClass(\"fa-star-o\");\n stars = 1;\n } else if (moves >=20){\n $('.stars li .fa').removeClass(\"fa-star\");\n $('.stars li .fa').addClass(\"fa-star-o\");\n stars = 0;\n }\n $('.win-container .stars-number').text(stars);\n\n}", "function updateScoreBoard() {\n totalMoves++;\n $('#moves-counter').text(totalMoves);\n if (totalMoves > 15 && totalMoves <= 20) {\n setStars(2);\n } else if (totalMoves > 20) {\n setStars(1);\n }\n}", "function starRating () {\n if ( moveCount === 20 || moveCount === 30 ) {\n decrementStar();\n }\n}", "function updateScore() {\n moveCounter += 1;\n document.getElementsByClassName('moves')[0].textContent = moveCounter;\n const stars = document.getElementsByClassName('stars')[0];\n switch (moveCounter) {\n case 16:\n setStarEmpty(stars.children[2].children[0]);\n starCounter = 2;\n break;\n case 24:\n setStarEmpty(stars.children[1].children[0]);\n starCounter = 1;\n break;\n }\n}", "function updateMoves() {\n moves += 1;\n const move = document.querySelector(\".moves\");\n move.innerHTML = moves;\n if (moves === 16) {\n removeStar();\n starRating = 2;\n } else if (moves === 25) {\n removeStar();\n starRating = 1;\n }\n}", "function incrementMovesCounter(){\n movesCounter++;\n document.querySelector('.moves').textContent = movesCounter;\n if(movesCounter === 16){\n document.querySelectorAll('.fa-star')[2].className = \"fa fa-star-o\";\n }else if (movesCounter === 24) {\n document.querySelectorAll('.fa-star')[1].className = \"fa fa-star-o\";\n }\n}", "function starCount() {\n if (moveCount >= starChart4 && moveCount < starChart3) {\n $('.star4').hide();\n starResult = 3;\n\t}\n else if (moveCount >= starChart3 && moveCount < starChart2) {\n $('.star3').hide();\n starResult = 2;\n }\n else if (moveCount >= starChart2) {\n $('.star2').hide();\n starResult = 1;\n }\n}", "function rateTheStars(moves){\n if (moves > 24) {\n console.log(\"1 star\");\n starRating = 1;\n } else if (moves > 20) {\n console.log(\"2 stars\");\n starRating = 2;\n } else if (moves > 16){\n console.log(\"3 stars\");\n starRating = 3;\n } else if (moves > 12){\n console.log(\"4 stars\");\n starRating = 4;\n } else {\n starRating=5;\n }\n starColors(starRating);\n }", "showStarCounter() {\n const currentBoard = Boards.findOne(Session.get('currentBoard'));\n return currentBoard && currentBoard.stars >= 2;\n }", "function rating(){\n //// TODO: Bug has been fixed\n if (!cardCouple[0].classList.contains('match') && !cardCouple[1].classList.contains('match')){\n moves.innerText++;\n }\n if (moves.innerText > 14){\n document.querySelector('.stars li:nth-child(1)').classList.add('starDown');\n }\n else if (moves.innerText > 20){\n document.querySelector('.stars li:nth-child(2)').classList.add('starDown');\n }\n}", "function starRating(moves) {\n if (moves >= 12 && moves < 18) {\n starCount.childNodes[5].childNodes[0].className = 'fa fa-star-o';\n } else if (moves >= 18) {\n starCount.childNodes[3].childNodes[0].className = 'fa fa-star-o';\n }\n return starCount;\n}", "function trackMovesAndScore () {\n\tgameData.moves++;\n\t$('.moves').text(gameData.moves);\n\n\tif (gameData.moves > 15 && gameData.moves < 20) {\n\t\t$('.stars').html(gameData.starsHTML + gameData.starsHTML);\n\t} else if (gameData.moves >= 20) {\n\t\t$('.stars').html(gameData.starsHTML);\n\t}\n}", "function updateActionCounter() {\n actionCount += 1;\n document.querySelector('.moves').textContent = actionCount;\n //TODO: change to fa-star-o class\n if (actionCount == 27) {\n starPanel[0].classList.add('hidden-star');\n } else if (actionCount == 33) {\n starPanel[1].classList.add('hidden-star');\n }\n}", "function starRating() {\n var starsTracker = starsPanel.getElementsByTagName('i');\n\n // If game finished in 11 moves or less, return and star rating remains at 3\n if (moves <= 11) {\n return;\n // If finished between 11 to 16 moves, 3rd colored star is replaced with empty star class\n } else if (moves > 11 && moves <= 16) {\n starsTracker.item(2).className = 'fa fa-star-o';\n // If finished with more than 16 moves, 2nd colored star is replaced with empty star class\n } else {\n starsTracker.item(1).className = 'fa fa-star-o';\n }\n\n // Update stars variable by counting length of remaining colored star elements\n stars = document.querySelectorAll('.fa-star').length;\n}", "function countMoves() {\n moves++;\n if (moves === 1) {\n counter.textContent = `${moves} move`;\n } else {\n counter.textContent = `${moves} moves`;\n }\n}", "function addMove() {\n moves ++;\n moveCount.innerHTML = moves;\n if(moves === 10) {\n hideStar();\n } else if(moves === 20) {\n hideStar();\n }\n}", "function starCount () {\n if (counter.textContent == 17) {\n starDown();\n } else if (counter.textContent == 21) {\n starDown();\n } \n}", "function star(numOfMove){\n\t noMoves = numOfMove; \n\t let stars = document.querySelector(\".stars\");\n\t if(numOfMove>50){\n\t \tnoStar=1;\n stars.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else if (numOfMove>30){\n\t \tnoStar=2;\n\t \tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n\t else{\n\t \tnoStar=3;\n\t\tstars.innerHTML = `<li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li><li><i class=\"fa fa-star\"></i></li>`;\n\t }\n}", "function countMoves() {\n moves++;\n if (moves === 1) {\n movesCounter.innerHTML = `1 movimento`;\n } else {\n movesCounter.innerHTML = `${moves} movimentos`;\n }\n}", "function movesHandler() {\n movesCounter++;\n if (movesCounter === 1) {\n document.querySelector(\".checker\").innerHTML = \"Move\";\n document.querySelector(\".moves\").innerHTML = movesCounter;\n } else {\n document.querySelector(\".moves\").innerHTML = movesCounter;\n document.querySelector(\".checker\").innerHTML = \"Moves\";\n }\n if (movesCounter > 30 && movesCounter < 32) {\n for (var i = 0; i < 3; i++) {\n if (i > 1) {\n rating[i].style.visibility = \"hidden\";\n }\n }\n numberOfStars = 2;\n } else if (movesCounter > 40) {\n for (var x = 0; x < 3; x++) {\n if (x > 0) {\n rating[x].style.visibility = \"hidden\";\n }\n }\n numberOfStars = 1;\n }\n}", "function moveCounter(moves){\n document.querySelector(\".moves\").textContent=moves.toString()+\" Moves\";\n \n if (moves==12){\n let star = document.querySelector(\"#star4\");\n star.setAttribute(\"class\",\"fa fa-star-o\");\n starRating =3;\n // $('#myModal').modal('show')\n }else if (moves==15){\n let star = document.querySelector(\"#star3\");\n star.setAttribute(\"class\",\"fa fa-star-o\");\n starRating =2;\n }else if (moves==20){\n let star = document.querySelector(\"#star2\");\n star.setAttribute(\"class\",\"fa fa-star-o\");\n starRating =1;\n }\n\n}", "function updateMoves() {\n moves += 1;\n $('#moves').html(`${moves} Moves`);\n if (moves === 24) {\n addBlankStar();\n }\n else if (moves === 16) {\n addBlankStar();\n }\n}", "function showStars() {\n let count;\n if (moveCount < 16) {\n count = 3;\n score = 60;\n } else if (moveCount < 32) {\n count = 2;\n score = 40;\n } else {\n count = 1;\n score = 10;\n }\n for (let i = 0; i < (stars.length - count); i++) {\n stars[i].setAttribute('style', 'display: none');\n }\n}", "function starCount() {\n\twhile(starArea.childNodes.length > 0) {\n\t\tstarScore.appendChild(starArea.childNodes[0]);\n\t}\n}", "function starCount() {\r\n if (moveCounter === 15) { // when the move counter reaches 10 remove the star\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop one star');\r\n } else if (moveCounter === 30) {\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop second star');\r\n }\r\n}", "function setStars() {\n /*Grabs the section in the html that has the moves count and updates it based on moves variable. */\n document.getElementById(\"moves\").textContent = moves;\n /*Conditional used to determine what stars to display depending on the number of moves/2clicks occur. */\n if (moves <= 10){\n starsRating = 3;\n return;\n } \n /*Grabs stars elements so that later the classes can be manipulated to display clear starts instead of full stars. */\n let stars = document.getElementById(\"stars\").children;\n /*If the user has taken over 10 moves/2 clicks, then one star is replaced with a star outline. */\n stars[2].firstElementChild.classList.remove(\"fa-star\");\n stars[2].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 20){\n starsRating = 2;\n return;\n } \n /*If the user has taken over 20 moves/2 clicks, then an addional star is repalced with a star outline. */\n stars[1].firstElementChild.classList.remove(\"fa-star\");\n stars[1].firstElementChild.classList.add(\"fa-star-o\");\n if (moves <= 30) {\n starsRating = 1;\n return;\n } \n}", "function updateStarRating() {\n const numCards = deckConfig.numberOfcards;\n\n if (scorePanel.moveCounter === 0) {\n scorePanel.starCounter = 3;\n $(\".star-disabled\").toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === Math.trunc(numCards / 2 + numCards / 4)) {\n scorePanel.starCounter = 2;\n $($(\".stars\").children()[0]).toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === (numCards)) {\n scorePanel.starCounter = 1;\n $($(\".stars\").children()[1]).toggleClass(\"star-enabled star-disabled\");\n }\n}", "function calculateStarRating(moves) {\n if (moves < threeStars) {\n return 3;\n } else if (moves >= threeStars && moves < twoStars) {\n return 2;\n } else if (moves >= twoStars && moves < oneStar) {\n return 1;\n } else {\n return 0;\n }\n}", "function starScore () {\n if (moves >= 12) {\n stars[3].setAttribute('style', 'visibility: hidden');\n finalStarScore = 3;\n } \n if (moves >= 18) {\n stars[2].setAttribute('style', 'visibility: hidden');\n finalStarScore = 2;\n }\n if (moves >= 25) {\n stars[1].setAttribute('style', 'visibility: hidden');\n finalStarScore = 1;\n }\n}", "function reduceStars() {\n let starList = document.querySelectorAll('.fa-star');\n\n // determine whether star should be removed\n if(turns % STAR_REDUCTION === 0 && stars!== 1) {\n // change the rightmost star to an empty star\n let starLost = starList[starList.length-1];\n starLost.setAttribute('class', 'fa fa-star-o');\n stars--;\n }\n}", "function rating() {\n 'use strict'; // turn on Strict Mode\n if (moves > 10 && moves < 19) {\n stars[2].classList.remove('fa-star');\n stars[2].classList.add('fa-star-o');\n starsRating = 2;\n } else if (moves > 20) {\n stars[1].classList.remove('fa-star');\n stars[1].classList.add('fa-star-o');\n starsRating = 1;\n }\n}", "function countMoves() {\n moveCount++;\n moves.textContent = (moveCount === 1) ? `${moveCount} Move` : `${moveCount} Moves`;\n}", "function setStars() {\r\nlet starsDOM = document.querySelector('.stars');\r\n if (moveCounter == 0) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 3;\r\n } else if (moveCounter == 14) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>\r\n <li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 2;\r\n } else if (moveCounter == 22) {\r\n starsDOM.innerHTML = `<li><i class=\"fa fa-star\"></i></li>`;\r\n starCounter = 1;\r\n } else if (moveCounter == 30) {\r\n starsDOM.innerHTML = ``;\r\n starCounter = 0;\r\n }\r\n}", "function clickCounter() {\n let matchedCards = document.querySelectorAll('.match');\n\n /* checks moves to remove stars and checks if all cards are matched */\n if (matchedCards.length === 16) {\n countStars();\n wingame()\n } else if (clicks === 7) {\n stars.innerHTML += openStar;\n stars.removeChild(stars.firstElementChild);\n clicks += 1;\n moves.innerHTML = clicks\n } else if (clicks === 10) {\n stars.innerHTML += openStar;\n stars.removeChild(stars.firstElementChild);\n clicks += 1;\n moves.innerHTML = clicks\n } else if (clicks === 15) {\n stars.innerHTML += openStar;\n stars.removeChild(stars.firstElementChild);\n clicks += 1;\n moves.innerHTML = clicks\n } else {\n clicks += 1;\n moves.innerHTML = clicks\n }\n}", "function updateMovesCounter() {\n\tmovesCounter += 1;\n\tmovesCounterElement.textContent = movesCounter;\n\tupdateStarRating(movesCounter);\n}", "function rating(moves) {\n // \n let rating = 3;\n\n // Scoring system from 1 to 3 stars\n let stars3 = 10,\n stars2 = 16,\n star1 = 20;\n\n if (moves > stars3 && moves < stars2) {\n $stars.eq(3).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > stars2 && moves < star1) {\n $stars.eq(2).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > star1) {\n $stars.eq(1).removeClass('fa-star').addClass('fa-star-o');\n rating = 1;\n }\n return {\n score: rating\n };\n}", "function starsRating() {\n if (moves === 14 || moves === 17 || moves === 24 || moves === 28\n ) { hideStar();\n }\n}", "updateStarRating() {\n const { numberOfMoves, numberOfStars } = this.state;\n if(numberOfMoves < 12) {\n this.setState({\n numberOfStars: 3\n });\n } else if (numberOfMoves >= 12 && numberOfMoves < 18) {\n this.setState({\n numberOfStars: 2\n });\n } else {\n this.setState({\n numberOfStars: 1\n });\n }\n }", "function movesCounter(){\n //increment counter by one each time\n counter++;\n //Updates moves inner html with the counter data\n moves.innerHTML = `Moves Made: ${counter}`;\n //updateStars function when the counter increments to a certain value\n updateStars();\n}", "function displayMovesAndRating() {\n\tmoves = 0; rating = 3;\n\tmoveElement.innerText = `${moves} Move`;\n\n\tratingElement.children[2].classList.remove('fa-star-o');\n\tratingElement.children[2].classList.add('fa-star');\n\n\tratingElement.children[1].classList.remove('fa-star-o');\n\tratingElement.children[1].classList.add('fa-star');\n}", "function getStars() {\r\n stars = document.querySelectorAll('.stars li');\r\n starCount = 3;\r\n for (star of stars) {\r\n if (star.style.display == 'none') {\r\n --starCount;\r\n }\r\n }\r\n return starCount;\r\n }", "function Rating(myMoves){\r\n let score = 3;\r\n if(myMoves <= 20) {\r\n theStarsRating.eq(3).removeClass(\"fa-star\").addClass(\"fa-star-o\");\r\n score=3;\r\n } else if (myMoves > 20 && myMoves <= 30) {\r\n theStarsRating.eq(2).removeClass(\"fa-star\").addClass(\"fa-star-o\");\r\n score=2;\r\n } else if (myMoves > 30) {\r\n theStarsRating.eq(1).removeClass(\"fa-star\").addClass(\"fa-star-o\");\r\n score=1;\r\n }\r\n return score;\r\n}", "function updateRating() {\n //Rating game based on move count\n if (numMoves == (moves_to_two_stars)) {\n stars[2].classList.remove(\"fa-star\");\n stars[2].classList.add(\"fa-star-o\");\n rating = 2;\n }\n else if (numMoves == (moves_to_one_star)) {\n stars[1].classList.remove(\"fa-star\");\n stars[1].classList.add(\"fa-star-o\");\n rating = 1;\n }\n}", "function rating(moves) {\n let rating = 3;\n if (moves > stars3 && moves < stars2) {\n $rating.eq(3).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > stars2 && moves < star1) {\n $rating.eq(2).removeClass('fa-star').addClass('fa-star-o');\n } else if (moves > star1) {\n $rating.eq(1).removeClass('fa-star').addClass('fa-star-o');\n rating = 1;\n }\n return { score: rating };\n}", "function removeStars() {\n moves.innerHTML++;\n if (moves.innerHTML == 15) {\n starsChildren[2].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n if (moves.innerHTML == 20) {\n starsChildren[1].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n}", "function incrementMoves() {\n moves ++;\n $(\".score-panel .moves\").text(moves);\n if (moves === 13) {\n decrementStars();\n }\n else if (moves === 21) {\n decrementStars();\n }\n }", "function rating() {\n\tconst star1 = document.getElementById(\"one-star\");\n\tconst star2 = document.getElementById(\"two-star\");\n\tconst star3 = document.getElementById(\"three-star\");\n\t// change stars style depending on number of moves\n\tif (moveCounter == 18) {\n\t\tstar1.classList.remove(\"fas\");\n\t\tstar1.classList.add(\"far\");\n\t} else if (moveCounter == 16){\n\t\tstar2.classList.remove(\"fas\");\n\t\tstar2.classList.add(\"far\");\n\t} else if (moveCounter == 14) {\n\t\tstar3.classList.remove(\"fas\");\n\t\tstar3.classList.add(\"far\");\n\t} else {\n\t\t\n\t}\n}", "function updateMoves() {\n if (moves === 1) {\n $(\"#movesText\").text(\" Move\");\n } else {\n $(\"#movesText\").text(\" Moves\");\n }\n $(\"#moves\").text(moves.toString());\n\n if (moves > 0 && moves < 16) { // gives star rating according the no of moves ,removes the class\n starRating = starRating;\n } else if (moves >= 16 && moves <= 20) {\n $(\"#starOne\").removeClass(\"fa-star\");\n starRating = \"2\";\n } else if (moves > 20) {\n $(\"#starTwo\").removeClass(\"fa-star\");\n starRating = \"1\";\n }\n}", "function countMoves() {\n numberOfMoves = clickCounter/2;\n moveCounter.innerHTML = '<span>' + numberOfMoves + ' Moves</span>';\n}", "function countMoves() {\n moves++;\n moveCounter.innerHTML = moves;\n\n if (moves === 1) {\n seconds = 60;\n countDown();\n }\n\n starsEarned();\n}", "function listMinesLeft(){ //reducing board to a single variable(count)\r\n const markedTilesCount = board.reduce((count,row)=> {\r\n return count + row.filter(tile => tile.status === TILE_STATUS.MARKED).length;\r\n // default at 0 (count starts at 0 for each game)\r\n },0)\r\n\r\n //substract number of mines marked by the number of mines that were started with will equal \r\n //the current mine count\r\n MinesleftOutput.textContent = numberOfMines - markedTilesCount;\r\n \r\n}", "function loseStar(event) {\n\tlet counterMoves = Number (moves.textContent);\n\tif((counterMoves - numOfMatched) % 10 === 0 && counterStars != 1){//decrease stars after balance between counterMoves and numOfMatched with 10\n\t\tnumOfStars.children[counterStars-1].firstElementChild.className = 'fa fa-star-o';\n\t\tcounterStars--;\n\t}else{\n\t\t// alert('You are Lose!')\n\t\t// deck.removeEventListener('click', displayCard);\n\t}\n}", "function updateStars() {\n\t{\n\t\t$(\".fa-star\").last().attr(\"class\", \"fa fa-star-o\");\n\t\tif (numStars > 0)\n\t\t{\n\t\t\tnumStars--;\n\t\t}\n\t\t$(\".numStars\").text(numStars);\n\t}\n}", "function reduceMoves () {\n moves--;\n $('.moves').text(moves);\n if (moves === 6 || moves === 3) {\n $('.stars').find('li:last').remove();\n }\n}", "function countMoves() {\n moves++;\n const displayMoves = document.querySelector(\"#moves\");\n displayMoves.innerHTML = moves + \" Moves\";\n}", "function updateStars() {\n if (moves > 10 && moves < 20) {\n starsList[4].setAttribute('class', 'fa fa-star-o');\n stars = 4;\n }\n if (moves >= 20 && moves < 30) {\n starsList[3].setAttribute('class', 'fa fa-star-o');\n stars = 3;\n }\n if (moves >= 30 && moves < 40) {\n starsList[2].setAttribute('class', 'fa fa-star-o');\n stars = 2;\n }\n if (moves >= 40) {\n starsList[1].setAttribute('class', 'fa fa-star-o');\n stars = 1;\n }\n }", "function countStars() {\n const closedStar = `<i class=\"fa fa-star\"></i>`;\n const hollowStar = `<i class=\"fa fa-star-o\"></i>`;\n starCount = [];\n\n /* puts stars in an array and removes their li tag */\n for (let i = 0; i <= 2; i++) {\n starCount.push(hollowStar)\n };\n\n /* checks if a closed star is present */\n if (stars.querySelectorAll('.fa-star').length !== 0) {\n for (let i = 0; i <= stars.querySelectorAll('.fa-star').length - 1; i++) {\n starCount.splice(i, 1, closedStar)\n }\n }\n}", "function starRating() {\n if(moveCounter <= 25) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'inline-block';\n starsList[2].style.display = 'inline-block';\n moves.style.color = \"green\";\n }\n else if(moveCounter > 25 && moveCounter <=65) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'inline-block';\n starsList[2].style.display = 'none';\n moves.style.color = \"orange\";\n }\n else if(moveCounter > 65) {\n starsList[0].style.display = 'inline-block';\n starsList[1].style.display = 'none';\n starsList[2].style.display = 'none';\n moves.style.color = \"red\";\n }\n}", "function incrementMoves(){\n movesCounter++;\n moves.innerHTML = movesCounter;\n //start the timer when the players clicks the first time\n if(movesCounter == 1){\n second = 0;\n minute = 0;\n hour = 0;\n startTimer();\n }\n\n if (moves.innerHTML > 25) {\n //adds one star if the moves are greator than 25\n addStars(1);\n }\n else if (moves.innerHTML > 15 && moves.innerHTML <=25){\n //adds two star if the moves are greator than 15 and equals to and smaller than 25\n addStars(2);\n }\n else {\n addStars(3);\n }\n }", "function getStars() {\n\tstars = document.querySelectorAll('.stars li');\n\tstarCount = 0;\n\tfor (star of stars) {\n\t\tif (star.style.display !== 'none') {\n\t\t\tstarCount++;\n\t\t}\n\t}\n\treturn starCount;\n}", "function stars() {\n\tconst starar = star.getElementsByTagName('i');\n\tfor (i = 0; i < starar.length; i++) {\n\t\tif (moves > 14 && moves <= 19) {\n\t\t\tstarar[2].className = 'fa fa-star-o';\n\t\t\tstarnum = 2;\n\t\t} else if (moves > 19) {\n\t\t\tstarar[1].className = 'fa fa-star-o';\n\t\t\tstarnum = 1;\n//\t\t} else if (moves > 24) {\n//\t\t\tstarar[0].className = 'fa fa-star-o';\n//\t\t\tstarnum = 0;\n\t\t} else {\n\t\t\tstarar[0].className = 'fa fa-star';\n\t\t\tstarar[1].className = 'fa fa-star';\n\t\t\tstarar[2].className = 'fa fa-star';\n\t\t\tstarnum = 3;\n\t\t}\n\t}\n}", "function numMoves(){\n\tcountMoves +=1;\n\tdocument.querySelector('.moves').textContent=countMoves;\n}", "function moveCounter() {\n moves++;\n counter.innerHTML = moves;\n //start timer on first click\n if (moves == 1) {\n second = 0;\n minute = 0;\n hour = 0;\n startTimer();\n }\n // setting rates based on moves\n if (moves > 8 && moves < 12) {\n for (i = 0; i < 3; i++) {\n if (i > 1) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n else if (moves > 13) {\n for (i = 0; i < 3; i++) {\n if (i > 0) {\n stars[i].style.visibility = \"collapse\";\n }\n }\n }\n}", "function clickCounter() {\n\t$(\".card\").click(function(){\n\t\tnumberClicks++;\n\t\tif(numberClicks % 2 === 0) {\n\t\t\t$(\".moves\").html(numberClicks / 2);\n\t\t}\n\t\tstarRating(); // Star rating function below -- rating and star elements are based on number of clicks\n\t});\n}", "function movesCount() {\n moves++;\n moveCounter.innerHTML = moves;\n}" ]
[ "0.7933151", "0.79283005", "0.7891076", "0.7783046", "0.77191734", "0.76528335", "0.7643846", "0.7593916", "0.7527442", "0.7516414", "0.75119305", "0.7493098", "0.7484972", "0.74546975", "0.7440623", "0.7417278", "0.7394762", "0.7394098", "0.73380494", "0.73275435", "0.72849655", "0.72721475", "0.72617894", "0.7259873", "0.7208826", "0.7193162", "0.71384597", "0.7127152", "0.7096435", "0.7084204", "0.7079424", "0.70576036", "0.69893676", "0.69877416", "0.6984933", "0.69758624", "0.69602734", "0.6958561", "0.6953525", "0.69525945", "0.6949992", "0.6912597", "0.69111514", "0.6909542", "0.6909223", "0.6902072", "0.68917775", "0.6883941", "0.68808246", "0.6863543", "0.6848399", "0.68331945", "0.68316025", "0.68084484", "0.67965025", "0.6782335", "0.67818385", "0.6780401", "0.67795026", "0.6770612", "0.6754726", "0.6743201", "0.6734892", "0.67249906", "0.670518", "0.67011404", "0.66919243", "0.66848683", "0.6674396", "0.6674089", "0.6668202", "0.6660328", "0.6654574", "0.6651315", "0.6651224", "0.66441375", "0.6635195", "0.66335726", "0.66335595", "0.6632745", "0.6631128", "0.6630242", "0.66255873", "0.6623538", "0.66230726", "0.6614828", "0.66141635", "0.6613686", "0.65934587", "0.65802026", "0.6553502", "0.655106", "0.65495193", "0.65345514", "0.6533316", "0.65290177", "0.6527276", "0.65266687", "0.65223056", "0.6520354" ]
0.6901675
46
restore stars count to default
function resetStar() { for(star of allStars) { star.style.display = 'inline'; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function resetStarRating() {\n stars[1].classList.remove(\"fa-star-o\");\n stars[1].classList.add(\"fa-star\");\n stars[2].classList.remove(\"fa-star-o\");\n stars[2].classList.add(\"fa-star\");\n rating = 3;\n}", "function resetStarColors() {\n $('.star-rate').css('color', 'black');\n }", "function resetStars() {\n countStars = 3;\n for (star of stars) {\n star.style.display = 'inline';\n }\n}", "function resetStarRating() {\n //loop through all the stars and set the icon\n for (let i = 0; i < stars.length; i++) {\n let s = stars[i].firstChild;\n s.classList.remove('fa-star-o');\n s.classList.add('fa-star');\n }\n}", "function decrementStars() {\n $(\".stars i.fa-star\").first()\n .removeClass(\"fa-star\")\n .addClass(\"fa-star-o\");\n stars -= 1;\n }", "resetStars() {\n this.mStars = this.DEFAULT_NUM_STARS;\n this.notifyStarsObservers(this.mStars);\n }", "function resetStars() {\n\tstars = 0;\n\tconst starList = document.querySelectorAll('.stars li');\n\tfor (star of starList) {\n\t\tstar.style.display = 'inline';\n\t}\n}", "function resetStars(){\n\tmanipulateStarClassesFromBackToFront(0, 'fa fa-star', panelStars, modalStars);\n}", "function resetRating() {\n mismatches = 0;\n rating = 3;\n ratingLabel.innerHTML = \"\";\n for (let i = 3; i > 0; i--) {\n const i = document.createElement('i');\n i.classList.add('fa', 'fa-star');\n ratingLabel.appendChild(i);\n }\n}", "function resetStars(){\n $('#star-10').attr('src','images/star.png');\n $('#star-20').attr('src','images/star.png');\n $('#star-30').attr('src','images/star.png');\n endingStarBonus += startingStars;\n startingStars = 3;\n incorrectGuesses = 0;\n}", "function reduceStars() {\n let starList = document.querySelectorAll('.fa-star');\n\n // determine whether star should be removed\n if(turns % STAR_REDUCTION === 0 && stars!== 1) {\n // change the rightmost star to an empty star\n let starLost = starList[starList.length-1];\n starLost.setAttribute('class', 'fa fa-star-o');\n stars--;\n }\n}", "function updateStarCount()\n\t{\n\t\tif ( previousCard == null )\n\t\t{\n\t\t\tif ( movesCounter == 20 || movesCounter == 30 )\n\t\t\t{\n\t\t\t\t$('ul.stars li').first().remove();\n\t\t\t}\n\t\t}\t\t\t\t\n\t}", "function resetRating(){\n document.querySelector('.stars li:nth-child(1)').classList.remove('starDown');\n document.querySelector('.stars li:nth-child(2)').classList.remove('starDown');\n }", "function resetStars() {\n stars = 0;\n const starList = document.querySelectorAll('.stars li');\n for (star of starList) {\n star.style.display = 'inline';\n }\n}", "function resetStar() {\n\tsStar.forEach(function(star) {\n\t\tstar.style.cssText = '';\n\t});\n\tcStar.forEach(function(star) {\n\t\tstar.style.cssText = '';\n\t});\n}", "function resetStars() {\n\tstars = 0;\n\tconst starList = document.querySelectorAll('.stars li');\n\tfor (star of starList) {\n\t star.style.display = 'inline';\t\n\t}\n}", "function resetStars(e) {\n //if the user has selected a rating, we do not do the animation\n if (rating != 0) {\n return;\n }\n for (let i = 0; i < 5; i++) {\n stars[i].innerText = \"\\u2606\";\n }\n ratingText.innerText = \"\";\n}", "function recalcStars() {\n const stars = document.querySelector(\".stars\");\n if ((countStars===3 && countMoves === 11) || (countStars===2 && countMoves === 17) ) {\n stars.children[countStars-1].firstElementChild.classList.replace('fa-star','fa-star-half-o');\n countStars -= 0.5;\n }\n if ((parseInt(countStars)===2 && countMoves === 14) || (parseInt(countStars)===1 && countMoves === 20)) {\n countStars -= 0.5;\n stars.children[countStars].firstElementChild.classList.replace('fa-star-half-o','fa-star-o');\n }\n}", "function setRating() {\n // make sure rating doesn't go below 1 star\n if (mismatches > 7) return;\n\n // decrease rating every 3 mismatches\n if ( (mismatches % 3) === 0 ) {\n rating--;\n ratingLabel.removeChild(ratingLabel.lastElementChild);\n }\n}", "function updateStars() {\n\t{\n\t\t$(\".fa-star\").last().attr(\"class\", \"fa fa-star-o\");\n\t\tif (numStars > 0)\n\t\t{\n\t\t\tnumStars--;\n\t\t}\n\t\t$(\".numStars\").text(numStars);\n\t}\n}", "function resetRatingStars(parent)\r\n{\r\n for (var i = 0; i < parent.children.length; i++) {\r\n parent.children[i].src = unfilledStar;\r\n }\r\n \r\n parent.value = null;\r\n}", "function adjustRating() {\n const oneStar = document.querySelector(\".fa-star\").parentNode;\n if (moveCount == 28) {\n oneStar.parentNode.removeChild(oneStar);\n } else if (moveCount == 38) {\n oneStar.parentNode.removeChild(oneStar);\n }\n}", "function clearStars() {\n starCount();\n let stars = document.querySelectorAll('.stars li i');\n stars[0].classList.remove('hide');\n stars[1].classList.remove('hide');\n stars[2].classList.remove('hide');\n starCounter = 0;\n }", "function initStars() {\n stars = 3;\n $('.stars i').removeClass(\"fa-star-o\");\n $('.stars i').addClass(\"fa-star\");\n updateStars();\n}", "function resetStars() {\n for (let i = 1; i < 3; i++) {\n starsChildren[i].firstElementChild.className = 'fa fa-star';\n }\n}", "function resetRating() {\n\tconst rateItem = document.querySelectorAll(\"#item-rating i\");\n\tfor (let i =0; i < rateItem.length; i++) {\n\t\trateItem[i].classList.remove(\"far\");\n\t\trateItem[i].classList.add(\"fas\");\n\t}\n}", "function resetStarsHandler(){\n let stars = $(\".star\");\n for(let i=0; i<stars.length; i++){\n $(stars[i]).removeClass(\"fas selected-star\");\n $(stars[i]).addClass(\"far\");\n }\n}", "function starRating() {\n if (moves > 13 && moves < 16) {\n starCounter = 3;\n } else if (moves > 17 && moves < 27) {\n starCounter = 2;\n } else if (moves > 28) {\n starCounter = 1;\n }\n showStars(starCounter);\n }", "function starRemoval(){\n\tstars = document.querySelectorAll('.fa-star');\n\tstarCount = countMoves;\n\tswitch (starCount) {\n\t\tcase 10:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\tstars[stars.length-1].className='fa fa-star-o';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}", "function starsReset() {\n\tif (pub.clickedBody == -1 && !pub.starsResetDone) {\n\t\tvar allDone = true;\n\t\tfor (var i = 0; i < pub.origCoords.length; i++) {\n\t\t\tif (! easing(pub.origCoords, i)) allDone = false;\n\t\t}\n\n\t\tif (allDone == true) pub.starsResetDone = true;\n\t}\n}", "function resetStars() {\n\tconst stars = document.querySelector('.stars');\n\tstars.innerHTML = \"<li><i class='fa fa-star'></i></li><li><i class='fa fa-star'></i></li><li><i class='fa fa-star'></i></li><li><i class='fa fa-star'></i></li><li><i class='fa fa-star'></i></li>\";\n}", "function setNumStars() {\n N = num_stars_input.value();\n num_stars_input.value('');\n createStarInputInterface();\n}", "function removeStar() {\n $('.fa-star').last().attr('class', 'fa fa-star-o');\n numStars--;\n}", "function resetStarsDisplay() {\n let stars = document.getElementsByClassName(\"stars\")[0];\n starsCounter = stars.getElementsByTagName(\"li\").length;\n stars.innerHTML = \"\";\n for(let s=0; s<starsCounter; ++s){\n let listElement = document.createElement(\"li\");\n let starElement = document.createElement(\"i\");\n starElement.classList.add(\"fa\");\n starElement.classList.add(\"fa-star\");\n listElement.appendChild(starElement);\n stars.appendChild(listElement);\n }\n}", "function rating(numOfMistakes) {\n if ((numOfMistakes === 9)||(numOfMistakes === 12)) {\n stars.removeChild(stars.lastChild);\n starCount -= 1;\n }\n }", "resetCount() {\n this.count = this.initialCount;\n }", "function starCount() {\n if (moveCountNum === 20 || moveCountNum === 35) {\n removeStar();\n }\n}", "function resetRatingValues(playlistID){\n $('#favicon'+playlistID).css(\"color\",\"#676a6c\");\n console.log(\"resetting value for id =\"+playlistID);\n //startArr=[$star_ratingA,$star_ratingV,$star_ratingC];\n starAbyIDString='#audioRating'+playlistID+' .fa';\n starVbyIDString='#videoRating'+playlistID+' .fa';\n starCbyIDString='#contentRating'+playlistID+' .fa';\n $starAbyID=$(starAbyIDString);\n $starVbyID=$(starVbyIDString);\n $starCbyID=$(starCbyIDString);\n starArr=[$starAbyID,$starVbyID,$starCbyID];\n\n for(i=0;i<starArr.length;i++) {\n item = starArr[i];\n item.each(function () {\n $(this).removeClass('fa-star');\n $(this).addClass('fa-star-o');\n })\n }\n }", "function stars() {\n starsNumber = 3;\n if (moves >= 10 && moves < 18) {\n thirdStar.classList.remove('fa-star', 'starColor');\n thirdStar.classList.add('fa-star-o');\n starsNumber = 2;\n } else if (moves >= 18) {\n secondStar.classList.remove('fa-star', 'starColor');\n secondStar.classList.add('fa-star-o');\n starsNumber = 1;\n }\n}", "function reset() {\n 'use strict'; // turn on Strict Mode\n //Resetting timer\n timerCounter.innerHTML = \"0 Minute 0 Second\";\n clearInterval(timerInterval);\n\n //Resetting moves\n moves = 0;\n movesCounter.innerHTML = moves;\n\n //Reseting stars\n stars[1].classList.add(\"fa-star\");\n stars[1].classList.remove(\"fa-star-o\");\n stars[2].classList.add(\"fa-star\");\n stars[2].classList.remove(\"fa-star-o\");\n\n}", "function reSet(){\n count = 0;\n $('.moves').html('');\n $('.stars li').each( function(i){\n this.style.display = '';\n });\n stopClock();\n time = 0;\n check = 0;\n}", "function starColor(){\n\tif(numOfMoves === 8){\n\t\t--numOfStars;\n\t\tstars[2].classList.remove(\"staryellow\");\n\t}\n\telse if(numOfMoves === 12){\n\t\t--numOfStars;\n\t\tstars[1].classList.remove(\"staryellow\");\n\t}\n\telse if(counterMacth === 18){\n\t\tstars[0].classList.remove(\"staryellow\");\n\t}\n}", "updateStarCount(questionElement, nbStart) {\n questionElement.getElementsByClassName('star-count')[0].textContent = nbStart;\n }", "function removeStar() {\n if (remainingStars >= 2) {\n remainingStars -=1;\n stars.removeChild(stars.firstElementChild);\n }\n}", "function resetStars () {\n const starList = document.querySelectorAll(\".stars li\");\n for (star of starList) {\n star.style.display = 'inline';\n }\n}", "function resetMoves() {\n\tmoves = 0;\n\tdocument.querySelector(\".moves\").innerText = moves;\n\tdocument.querySelector(\".moves-text\").innerText = \"Moves\";\n\n\tlet stars = document.querySelector(\".stars\");\n\tvar lis = stars.children.length;\n\twhile (lis < 3) {\n\t\tvar star = stars.lastElementChild.cloneNode(true);\n\t\tstars.appendChild(star);\n\t\tlis = stars.children.length;\n\t}\n}", "removeStar() {\n if (this.mStars != 0) {\n this.mStars--;\n }\n this.notifyStarsObservers(this.mStars);\n }", "function resetStars() {\n /*Grabs the children of the section of the html with the stars ID and assigns them to the stars variable. */\n let stars = document.getElementById(\"stars\").children;\n /*Enters 0 for the text content next to moves in the html, to indicate the user hasn't taken any moves in the new game yet. */\n document.getElementById(\"moves\").textContent = 0;\n /*Iterates over the stars in the stars variable and returns them all to stars and not star outlines. */\n for (let star of stars) {\n star.firstElementChild.classList.remove(\"fa-star-o\");\n star.firstElementChild.classList.add(\"fa-star\");\n }\n}", "function adjustStarRating(moves) {\n if (moves === 16) {\n stars.children[0].remove();\n }\n else if (moves === 22) {\n stars.children[0].remove();\n }\n else if (moves === 32) {\n stars.children[0].remove();\n }\n else if (moves === 42) {\n stars.children[0].remove();\n }\n}", "function starCount() {\n\n if(numMoves < 16) {\n numStars = 3;\n }else if (numMoves >= 16 && numMoves < 25) {\n numStars = 2;\n }else {\n numStars = 1;\n };\n\n printStars();\n}", "function setStarRating(starsNumber) {\n if (starsNumber === 2) {\n stars[2].firstChild.classList.remove('fa-star');\n stars[2].firstChild.classList.add('fa-star-o');\n } else if (starsNumber === 1) {\n stars[1].firstChild.classList.remove('fa-star');\n stars[1].firstChild.classList.add('fa-star-o');\n } else if (starsNumber === 0) {\n stars[0].firstChild.classList.remove('fa-star');\n stars[0].firstChild.classList.add('fa-star-o');\n }\n}", "function updateStarRating() {\n const numCards = deckConfig.numberOfcards;\n\n if (scorePanel.moveCounter === 0) {\n scorePanel.starCounter = 3;\n $(\".star-disabled\").toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === Math.trunc(numCards / 2 + numCards / 4)) {\n scorePanel.starCounter = 2;\n $($(\".stars\").children()[0]).toggleClass(\"star-enabled star-disabled\");\n } else if (scorePanel.moveCounter === (numCards)) {\n scorePanel.starCounter = 1;\n $($(\".stars\").children()[1]).toggleClass(\"star-enabled star-disabled\");\n }\n}", "resetScore() {\n this.score = INITIAL_SCORE;\n }", "function updateStarCounter() {\n\t// when moves counter reaches 20, one star is removed\n\tif (Number(movesMade.innerText) === 20) {\n\t\tlet star = document.querySelector('#star-one').classList.add('none');\n\t}\n\t// when moves counter reaches 29, two stars are removed\n\tif (Number(movesMade.innerText) === 29) {\n\t\tlet star = document.querySelector('#star-two').classList.add('none');\n\t}\n\t//when moves counter is zero, all stars should be shown\n\tif (Number(movesMade.innerText) === 0) {\n\t\tdocument.querySelector('#star-one').classList.remove('none');\n\t\tdocument.querySelector('#star-two').classList.remove('none');\n\t\tdocument.querySelector('#star-three').classList.remove('none');\n\t}\n}", "changeStarOut() {\n const { rating } = this.state;\n this.changeStar(rating);\n }", "function starCounter(moves) {\r\n if (moves >= 20 && moves <= 30) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(4);\r\n } else if (moves >= 31 && moves <= 40) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(3);\r\n } else if (moves >= 41 && moves <= 50) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(2);\r\n } else if (moves >= 51) {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(1);\r\n } else {\r\n // stars.innerHTML.remove();\r\n stars.innerHTML = star.repeat(5);\r\n\r\n }\r\n}", "function starRating () {\n if ( moveCount === 20 || moveCount === 30 ) {\n decrementStar();\n }\n}", "function turnOffStars(e) {\r\n var stars = document.querySelectorAll(\"span#stars img\");\r\n for (var i = 0; i < stars.length; i++) {\r\n stars[i].src = \"bw_star.png\";\r\n document.getElementById(\"rating\").value = \"\";\r\n }\r\n}", "function starCount() {\r\n if (moveCounter === 15) { // when the move counter reaches 10 remove the star\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop one star');\r\n } else if (moveCounter === 30) {\r\n document.querySelector('.fa-star:last-of-type').classList.remove('fa-star');\r\n console.log('drop second star');\r\n }\r\n}", "function fullReset() {\n reset();\n score.DROITE = 0;\n score.GAUCHE = 0;\n }", "function reset(){\n\t\trandomScore();\n\t\trandomVal();\n\t\tmainScore = 0;\n\t\t$('.score').text('Score: ' + mainScore);\n\n\t}", "function resetBoard() {\n $(\".card\").attr(\"class\",\"card\");\n $(\".card\").removeAttr(\"style\")\n $(\".moves\").text(0);\n $(\".stars li i\").attr(\"class\",\"fa fa-star\");\n $(\".container\").removeAttr(\"style\");\n}", "resetGhostEatenScoring() {\n this.ghostEatenScore = 100;\n }", "function scoreStar() {\n if (moveCounter === 18) {\n stars1 = 2 // 2 estrelas\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 22) {\n stars1 = 1 // 1 estrela\n $('.fa-star').remove()\n $('.stars').append('<li><i class=\"fa fa-star\"></i></li>')\n } else if (moveCounter === 29) {\n stars1 = 0 // 0 estrelas\n $('.fa-star').remove()\n }\n return\n}", "function updateStar() {\n\tlet starCount = 0;\n\tfor(star of allStars) {\n\t\tif(star.hidden === false) {\n\t\t\tstarCount++;\n\t\t}\n\t}\n\treturn starCount;\n}", "function removeStars() {\n moves.innerHTML++;\n if (moves.innerHTML == 15) {\n starsChildren[2].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n if (moves.innerHTML == 20) {\n starsChildren[1].firstElementChild.className = 'fa fa-star-o';\n userStars.innerHTML--;\n }\n}", "function resetStaggering() {\n Object.keys(staggering).forEach(function (key) {\n staggering[key].value = 0;\n });\n}", "function reset_stars_select_classes() {\n grid_stars_select_stars_0_anchor.removeClass(\"stars_selected_star\");\n grid_stars_select_stars_1_anchor.removeClass(\"stars_selected_star\");\n grid_stars_select_stars_2_anchor.removeClass(\"stars_selected_star\");\n grid_stars_select_stars_3_anchor.removeClass(\"stars_selected_star\");\n grid_stars_select_stars_4_anchor.removeClass(\"stars_selected_star\");\n grid_stars_select_stars_5_anchor.removeClass(\"stars_selected_star\");\n \n grid_stars_select_stars_0_anchor.removeClass(\"stars_unselected_star\");\n grid_stars_select_stars_1_anchor.removeClass(\"stars_unselected_star\");\n grid_stars_select_stars_2_anchor.removeClass(\"stars_unselected_star\");\n grid_stars_select_stars_3_anchor.removeClass(\"stars_unselected_star\");\n grid_stars_select_stars_4_anchor.removeClass(\"stars_unselected_star\");\n grid_stars_select_stars_5_anchor.removeClass(\"stars_unselected_star\");\n \n if(meal.rating >= 1) {\n grid_stars_select_stars_1_anchor.attr('class', 'stars_selected_star');\n }\n else {\n grid_stars_select_stars_1_anchor.attr('class', 'stars_unselected_star');\n }\n \n if(meal.rating >= 2) {\n grid_stars_select_stars_2_anchor.attr('class', 'stars_selected_star');\n }\n else {\n grid_stars_select_stars_2_anchor.attr('class', 'stars_unselected_star');\n }\n \n if(meal.rating >= 3) {\n grid_stars_select_stars_3_anchor.attr('class', 'stars_selected_star');\n }\n else {\n grid_stars_select_stars_3_anchor.attr('class', 'stars_unselected_star');\n }\n if(meal.rating >= 4) {\n grid_stars_select_stars_4_anchor.attr('class', 'stars_selected_star');\n }\n else {\n grid_stars_select_stars_4_anchor.attr('class', 'stars_unselected_star');\n }\n if(meal.rating >= 5) {\n grid_stars_select_stars_5_anchor.attr('class', 'stars_selected_star');\n }\n else {\n grid_stars_select_stars_5_anchor.attr('class', 'stars_unselected_star');\n }\n }", "function gameRating(count){\n if (count === 29){\n starCount --;\n document.querySelector('.rating.second').className = 'rating second hidden';\n }else if (count === 39){\n starCount --;\n document.querySelector('.rating.first').className = 'rating first hidden';\n }\n}", "function updateStarsDisplay(counter){\n let stars = document.getElementsByClassName(\"fa-star\");\n\n // for every 16 moves (or number of cards), remove a star\n if (counter > 0 && stars.length > 0){\n let penaltyLimit = cards.length + 1; \n let z = counter % penaltyLimit;\n if (z == 0){\n stars[0].classList.add(\"fa-star-o\");\n stars[0].classList.remove(\"fa-star\");\n }\n }\n return stars.length;\n}", "function setupStars(){\n //Selected ensures that the rating does not reset after a mouseclick\n let selected = false;\n let stars = document.getElementById(\"stars\");\n let rating = 0;\n //On hover, selected is reset, the hovered star and its previous siblings are highlighted as well\n stars.addEventListener('mouseover', function (e) {\n selected = false;\n rating = e.target.alt;\n if (e.target.nodeName.toLowerCase() == 'img') {\n e.target.src = \"./bw_star2.png\"\n //Acquire the previous element image\n let previousStar = e.target.previousElementSibling;\n //If more preceding stars exist, the loop will continue\n for(let i = e.target.alt; i>1;i--){\n previousStar.src = \"./bw_star2.png\";\n previousStar = previousStar.previousElementSibling;\n }\n }\n if(rating){\n document.getElementById(\"rating\").value = \"\" + rating + \" stars\";\n }\n \n });\n //On mouseout, the stars are reset to their original color if no rating was selected\n stars.addEventListener('mouseout', function (e) {\n if (selected == false && e.target.nodeName.toLowerCase() == 'img') {\n e.target.src = \"./bw_star.png\"\n let previousStar = e.target.previousElementSibling;\n for(let i = e.target.alt; i>1;i--){\n previousStar.src = \"./bw_star.png\";\n previousStar = previousStar.previousElementSibling;\n }\n rating = 0;\n }\n });\n //On mouseclick, set the selected boolean to true, preventing a color reset\n stars.addEventListener('click', function (e) {\n if (e.target.nodeName.toLowerCase() == 'img') {\n selected = true;\n rating = e.target.alt;\n }\n });\n}", "function starCount() {\n let stars = document.querySelectorAll('.stars li i');\n\n switch (true) {\n case ( cardMoves >= 24):\n stars[2].classList.add('hide');\n starCounter = 0;\n break;\n case (cardMoves >= 18):\n stars[1].classList.add('hide');\n starCounter = 1;\n break;\n case (cardMoves >= 9):\n stars[0].classList.add('hide');\n starCounter = 2;\n break;\n default:\n starCounter = 3;\n }\n }", "function resetFruitTally() {\n grapes = 0;\n bananas = 0;\n oranges = 0;\n cherries = 0;\n bars = 0;\n bells = 0;\n sevens = 0;\n blanks = 0;\n }", "function updateStarCount(postElement, nbStart) {\n postElement.getElementsByClassName('star-count')[0].innerText = nbStart;\n}", "function setStars(numStars){\n let count = 0;\n let indexRating = global.ratingPara.indexOf(\":\") + 2;\n let ratingNum = parseFloat(global.ratingPara.slice(indexRating));\n\n for (let i=0; i < numStars; i++){\n let star = document.createElement(\"span\");\n\n // sets constants representing the minimum and maximum ratings\n const FIVE_STARS = 5;\n const ZERO_STARS = 0;\n\n if(ratingNum == FIVE_STARS){\n star.textContent = \"\\u2605\";\n }\n else if (ratingNum == ZERO_STARS){\n star.textContent = \"\\u2606\";\n }\n else{\n // ensures that ratings with decimals do not count as an extra star. Ex: Rating 2.9 --> 2 stars.\n let difference = ratingNum - count;\n if (count <= ratingNum && difference >= 1){\n star.textContent = \"\\u2605\";\n count++;\n }\n else{\n star.textContent = \"\\u2606\";\n }\n }\n displayStars(star);\n }\n}", "function setStars() {\n let starList = $stars;\n\n // determine whether stars need to be added or reset\n if (starList.childNodes.length == 0) {\n\n // add the stars to the board\n for(let i=0; i<stars; i++) {\n let starItem = document.createElement('li');\n starItem.innerHTML = '<i class=\"fa fa-star\"></i>';\n starList.appendChild(starItem);\n }\n } else {\n // reset stars that alredy exist\n for(let i=0;i<stars; i++){\n starList.childNodes[i].innerHTML = '<i class=\"fa fa-star\"></i>';\n }\n }\n}", "function countStars() {\n\n if (moves <= 20) {\n stars = 3;\n } else if (moves <= 25) {\n stars = 2;\n } else {\n stars = 1;\n }\n\n displayStars();\n}", "function reset() {\n totScore = 0;\n $(\"#totScore\").text(totScore);\n }", "function updateStars(){\n if (incorrectGuesses === 10) {\n $('#star-10').attr('src','images/black-star.png');\n startingStars -= 1;\n }\n else if (incorrectGuesses === 20) {\n $('#star-20').attr('src','images/black-star.png');\n startingStars -= 1;\n }\n else if (incorrectGuesses === 30) {\n $('#star-30').attr('src','images/black-star.png');\n startingStars -= 1;\n }\n}", "createStarsEmpty(rating) {\n let vote = Math.ceil(rating / 2);\n const stars = [];\n for (let i = vote; i < 5; i++) {\n stars.push(1)\n }\n return stars;\n\n }", "function removeStar() {\n const stars = Array.from(document.querySelectorAll('.fa-star'));\n if (moves === 12 || moves === 15 || moves === 18) {\n for (star of stars){\n if (star.style.display !== 'none'){\n star.style.display = 'none';\n numberOfStarts--;\n break;\n }\n }\n }\n}", "reset() {\n heartRate.value.avg = null\n count = 0\n }", "function rating (){\n let stars = document.querySelector('.stars');\n let movesNumber = movesContainer.textContent;\n if((movesNumber == 16 && stars.firstChild) || (movesNumber == 24 && stars.firstChild)){\n stars.removeChild(stars.firstChild);\n } \n}", "function loseStar(event) {\n\tlet counterMoves = Number (moves.textContent);\n\tif((counterMoves - numOfMatched) % 10 === 0 && counterStars != 1){//decrease stars after balance between counterMoves and numOfMatched with 10\n\t\tnumOfStars.children[counterStars-1].firstElementChild.className = 'fa fa-star-o';\n\t\tcounterStars--;\n\t}else{\n\t\t// alert('You are Lose!')\n\t\t// deck.removeEventListener('click', displayCard);\n\t}\n}", "function resetFruitTally() {\n grapes = 0;\n bananas = 0;\n oranges = 0;\n cherries = 0;\n bars = 0;\n bells = 0;\n sevens = 0;\n blanks = 0;\n}", "function resetFruitTally() {\n grapes = 0;\n bananas = 0;\n oranges = 0;\n cherries = 0;\n bars = 0;\n bells = 0;\n sevens = 0;\n blanks = 0;\n}", "function addOnetoCounter(){\n counterint++;\n counter.innerHTML=counterint;\n let scores= document.querySelector('.stars')\n if (counterint == 18){\n\n let firstStar = scores.firstElementChild;\n scores.removeChild(firstStar);\n }\n if (counterint == 28){\n let firstStar = scores.firstElementChild;\n scores.removeChild(firstStar);\n }\n}", "function updateScore() {\n $('.moves').text(movesCounter);\n if (movesCounter > 10 && movesCounter <= 15 ) {\n $('#thirdStar').removeClass('fa fa-star');\n $('#thirdStar').addClass('fa fa-star-o');\n starsCounter = 2;\n }\n else if (movesCounter > 15) {\n $('#secondStar').removeClass('fa fa-star');\n $('#secondStar').addClass('fa fa-star-o');\n starsCounter = 1;\n }\n // you should have at least 1 star\n}", "function updateScore() {\n moveCounter += 1;\n document.getElementsByClassName('moves')[0].textContent = moveCounter;\n const stars = document.getElementsByClassName('stars')[0];\n switch (moveCounter) {\n case 16:\n setStarEmpty(stars.children[2].children[0]);\n starCounter = 2;\n break;\n case 24:\n setStarEmpty(stars.children[1].children[0]);\n starCounter = 1;\n break;\n }\n}", "function reset_stars_select_classes_hover() {\n grid_stars_select_stars_0_anchor.removeClass(\"stars_unselected_star_hover\");\n grid_stars_select_stars_1_anchor.removeClass(\"stars_unselected_star_hover\");\n grid_stars_select_stars_2_anchor.removeClass(\"stars_unselected_star_hover\");\n grid_stars_select_stars_3_anchor.removeClass(\"stars_unselected_star_hover\");\n grid_stars_select_stars_4_anchor.removeClass(\"stars_unselected_star_hover\");\n grid_stars_select_stars_5_anchor.removeClass(\"stars_unselected_star_hover\");\n \n grid_stars_select_stars_0_anchor.removeClass(\"stars_selected_star_hover\");\n grid_stars_select_stars_1_anchor.removeClass(\"stars_selected_star_hover\");\n grid_stars_select_stars_2_anchor.removeClass(\"stars_selected_star_hover\");\n grid_stars_select_stars_3_anchor.removeClass(\"stars_selected_star_hover\");\n grid_stars_select_stars_4_anchor.removeClass(\"stars_selected_star_hover\");\n grid_stars_select_stars_5_anchor.removeClass(\"stars_selected_star_hover\");\n }", "function starRating() {\n var starsTracker = starsPanel.getElementsByTagName('i');\n\n // If game finished in 11 moves or less, return and star rating remains at 3\n if (moves <= 11) {\n return;\n // If finished between 11 to 16 moves, 3rd colored star is replaced with empty star class\n } else if (moves > 11 && moves <= 16) {\n starsTracker.item(2).className = 'fa fa-star-o';\n // If finished with more than 16 moves, 2nd colored star is replaced with empty star class\n } else {\n starsTracker.item(1).className = 'fa fa-star-o';\n }\n\n // Update stars variable by counting length of remaining colored star elements\n stars = document.querySelectorAll('.fa-star').length;\n}", "function ratings() {\n\tif(moveCounter > 12 && moveCounter <= 16) {\n\t\tsStar[0].style.cssText = 'opacity: 0';\n\t\tcStar[0].style.cssText = 'display: none';\n\t}\n\tif(moveCounter > 16) {\n\t\tsStar[1].style.cssText = 'opacity: 0';\n\t\tcStar[1].style.cssText = 'display: none';\t\n\t}\n}", "function getStars() {\r\n stars = document.querySelectorAll('.stars li');\r\n starCount = 3;\r\n for (star of stars) {\r\n if (star.style.display == 'none') {\r\n --starCount;\r\n }\r\n }\r\n return starCount;\r\n }", "function finalRating(){\n let stars = $(\".fa-star\");\n $(stars[stars.length-1]).toggleClass(\"fa-star fa-star-o\");\n}", "function scoreReset() {\n guessesRemaining = 9;\n guesses = [];\n}", "function off(me){\n\tif(!rated){\n\t\tif(!preSet){\t\n\t\t\tfor(i=1; i<=sMax; i++){\t\t\n\t\t\t\tdocument.getElementById(\"_\"+i).className = \"\";\n\t\t\t\tdocument.getElementById(\"rateStatus\").innerHTML = me.parentNode.title;\n\t\t\t}\n\t\t}else{\n\t\t\trating(preSet);\n\t\t\tdocument.getElementById(\"rateStatus\").innerHTML = document.getElementById(\"ratingSaved\").innerHTML;\n\t\t}\n\t}\n}", "function updateStars() {\n if (moves > 10 && moves < 20) {\n starsList[4].setAttribute('class', 'fa fa-star-o');\n stars = 4;\n }\n if (moves >= 20 && moves < 30) {\n starsList[3].setAttribute('class', 'fa fa-star-o');\n stars = 3;\n }\n if (moves >= 30 && moves < 40) {\n starsList[2].setAttribute('class', 'fa fa-star-o');\n stars = 2;\n }\n if (moves >= 40) {\n starsList[1].setAttribute('class', 'fa fa-star-o');\n stars = 1;\n }\n }", "function starRatings() {\n if (moves === 12) {\n const star1 = stars.firstElementChild;\n stars.removeChild(star1);\n result = stars.innerHTML;\n } else if (moves === 16) {\n const star2 = stars.firstElementChild;\n stars.removeChild(star2);\n result = stars.innerHTML;\n }\n}", "function resetScores () {\n STORE.questionNumber = 0;\n STORE.score = 0;\n}", "function resetScore() {\n currentScore = 0;\n questionNum = 0;\n $(\".score\").text(0);\n $(\".questionNumber\").text(0);\n}" ]
[ "0.7508352", "0.7249987", "0.72125965", "0.7198685", "0.71526194", "0.71423477", "0.71411514", "0.7135055", "0.71320564", "0.70547706", "0.7045222", "0.70349437", "0.6987225", "0.69333035", "0.69304264", "0.69177014", "0.6892717", "0.68557566", "0.68507874", "0.6833608", "0.6817725", "0.68167245", "0.6765189", "0.6732407", "0.6680308", "0.66518915", "0.66088676", "0.65507084", "0.654441", "0.6529393", "0.6520756", "0.6502926", "0.6495951", "0.64807916", "0.6469058", "0.64599216", "0.6455794", "0.64226466", "0.64196384", "0.64093405", "0.638346", "0.6352589", "0.6351296", "0.6344791", "0.63270164", "0.6325216", "0.6314314", "0.6298893", "0.6281569", "0.62608594", "0.6241662", "0.6235273", "0.6235115", "0.6225168", "0.62230915", "0.6196058", "0.61935246", "0.61804175", "0.61429936", "0.6139869", "0.613517", "0.6125256", "0.61251426", "0.61198187", "0.611606", "0.6112813", "0.610214", "0.60975605", "0.60971797", "0.6074906", "0.60726804", "0.6072562", "0.60489213", "0.60350126", "0.6034291", "0.602583", "0.6018623", "0.5999944", "0.5989482", "0.59844744", "0.59823346", "0.5980884", "0.5970411", "0.59538084", "0.59533465", "0.59533465", "0.5952644", "0.59526175", "0.5934596", "0.59268653", "0.59249324", "0.59143776", "0.59073997", "0.5901457", "0.58941644", "0.58936006", "0.58899325", "0.58886296", "0.58885634", "0.58852524" ]
0.6861697
17
start a timer once the game loads
function startTimer() { time = 0; countUp = setInterval(function () { time++; displayTimer(); }, 1000); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function startTimer() {\n\tgameData.timer = setInterval(timerData.timeCounter, 1000);\n}", "function start(data) {\n startGameTimer();\n}", "function startGame() {\n timerStat = true;\n showGamePanel();\n runTimer();\n displayImage();\n}", "function gameStart(){\n\t\t\tshuffleCards();\n\t\t\ttime = 0;\n\t\t\tstarttime = Date.now();\n\t\t\ttimer = setInterval(function(){\n\t\t\t\ttime++;\n\t\t\t\t$(\".info .timer .sec\").text(time);\n\t\t\t}, 1000);\n\t\t}", "function TimerStart()\n{\n\ttimer = window.setInterval(TimerTick, Game.interval);\n}", "function startGame() {\n\t\tvar game = document.getElementById(\"game-area\");\n\t\ttimeStart();\t\t\t\t\n\t}", "function startTime() {\n if (!gameInProgress) {\n intervalId = setInterval(countdown, 1000);\n gameInProgress = true;\n };\n}", "function loadTimer() {\n currentTimerType = PEvents.nextTimer(currentTimerType);\n \n switch (currentTimerType) {\n case PEvents.Timers.pomodoro:\n minutes = 25;\n seconds = 0;\n break;\n \n case PEvents.Timers.short_break:\n minutes = 5;\n seconds = 0;\n break;\n\n case PEvents.Timers.long_break:\n minutes = 25;\n seconds = 0;\n break;\n }\n\n render();\n }", "function startGame(){\n hideContent();\n unhideContent();\n assignButtonColours();\n generateDiffuseOrder();\n clearInterval(interval);\n setlevel();\n countdown(localStorage.getItem(\"theTime\"));\n listeningForClick();\n}", "function startTimer() {\n setTimeout(function () {\n //when game is stopped timer from previous game shouldn't infere\n if (!pausedGame) timerDone = true;\n }, 10000);\n}", "function handleStartGame() {\n console.log(\"Start Game clicked...!\");\n\n //------- Timer ------- //\n\n // Start Timer\n startTimer(0);\n}", "function timerola (){\n\tsetInterval(startGame,1000/60);\n}", "function startGameTimer() {\n clearInterval(gameClock);\n gameClock = setInterval(gameTimer, 1000);\n}", "start() {\n this.isRunning = true;\n this.secondsChecker = new SecondsChecker(Date.now(), Date.now() + 60);\n\n if (typeof this.onGameStart === 'function') {\n this.onGameStart();\n }\n }", "function on_load()\n{\n\tgame.start();\n}", "function startGameTimer(){\n var timer = setInterval(() => {\n console.log(GMvariables.timerSecs);\n $(\"#timer\").text(GMvariables.timerSecs);\n if(GMvariables.timerSecs == 0){\n $(\"#timer\").text(\"Go\");\n clearInterval(timer);\n setTimeout(() => {\n $(\"#timer\").css(\"display\", \"none\");\n reset();\n changePositionOfElement();\n headerUpdater();\n }, 1000);\n }\n GMvariables.timerSecs -= 1;\n }, 1000);\n \n}", "startCountdown() {\n this.setGameValues();\n this.timerStart = new Date().getTime();\n this.countdownInterval = setInterval(this.updateTime, 1000);\n }", "function startTimer(){\n gameTimer= setInterval(countUpTimer, 1000);\n}", "function timer() {\n footballCrowd();\n timerId = setInterval(() => {\n time--;\n $timer.html(time);\n\n if(time === 0) {\n restart();\n lastPage();\n }\n }, 1000);\n highlightTiles();\n }", "function startGame() {\n timer = setInterval(start, timerCd) \n}", "function startGame() {\n hitCount = 0\n\n if (isSettingsInitialized) {\n console.log('Settings initialized')\n loadSettings()\n }\n\n togglePanel(panel.PREGAME)\n generateLayout()\n\n maxSpawns = Math.floor(maxTime / spawnRate)\n remainingSpawns = maxSpawns\n\n for (let s = 0; s < maxSpawns; s++) {\n spawnTimeouts.push(setTimeout(spawnYagoo, spawnRate * s))\n }\n\n startTimer(msToSec(maxTime), document.getElementById('timer-text'))\n}", "function timerStart(){\n\t\n\t\t\n\t}", "function timeStart() {\n\ttime = setInterval(buildTime, 1000);\n}", "_startTimer() {\n let interval = this.config[\"appear\"][\"interval\"]\n let variation = this.config[\"appear\"][\"interval_variation\"]\n let seconds = interval + Math.round(Math.random() * variation)\n\n util.log(\"power-up\", \"next in \" + seconds + \" seconds\")\n this.timer = this.game.time.events.add(Phaser.Timer.SECOND * seconds, this._addPowerup, this);\n }", "function startTime() {\n setTimer();\n}", "function startGameTimer() {\r\n var mspf = 15;\r\n\r\n function timer() {\r\n gameLoop();\r\n window.setTimeout(timer, mspf);\r\n }\r\n\r\n window.setTimeout(timer, mspf);\r\n}", "function startTimer(){\n $scope.timeRemaining = $scope.levels.timeDuration;\n $scope.timerId = $interval(function() {\n if ($scope.timeRemaining > 0) {\n updateTilesRemaining(); // update remaining tiles\n $scope.timeRemaining = $scope.timeRemaining - 1000;\n if($scope.tilesRemaining.length == 0){\n $scope.stopGame(\"win\");\n }\n } else {\n $scope.stopGame(\"loose\");\n }\n }, 1000);\n }", "function countDownStart() {\n if (timer == 0) {\n that.gameLoop = setInterval(that.update, interval);\n that.status = State.RUN;\n }\n else {\n drawElements();\n that.gameArea.paintTimer(that.contex, timer);\n timer--;\n setTimeout(countDownStart, 1500);\n }\n \n }", "function timerStart() {\n timer = setInterval(function tick(){\n timeInSeconds++;\n updateTimerDisplay(timeInSeconds);\n }, 1000);\n}", "start() {\n timer.start();\n }", "function setTime() {\n //increments timer\n ++totalSeconds;\n //temporarily stops timer at 5 seconds for my sanity\n if (totalSeconds === 59) {\n totalMinutes += 1;\n totalSeconds = 0;\n }\n\n //stops timer when game is won\n if (gameWon === true) {\n return;\n }\n //calls function to display timer in DOM\n domTimer();\n }", "function startTimer() {\n if (stoptime) {\n stoptime = false;\n runClock();\n }\n}", "function startTimer() {\n if (timeLeft == 0) {\n gameEnded();\n } else {\n gameOn = true;\n setTimeout(printTime, 1000);\n }\n}", "function startGame() {\r\n countUp = 0;\r\n setTimeout(endGame, 120000);\r\n startTimer();\r\n cancelTimer = false;\r\n triggerCrime();\r\n}", "function startNewGame() {\n // Possible speeds\n var speeds = {\n 0: 60,\n 200: 77,\n 500: 120,\n 800: 300\n };\n\n // Getting speed based on difficulty\n var speed = difficulty.options[difficulty.selectedIndex].value;\n\n var moleTimer = new Timer({\n seconds: speeds[speed],\n speed: speed,\n onTime: function() {\n if (!gameEnded) {\n renderMole();\n }\n }\n });\n\n // Start timer.\n gameTimer.start();\n moleTimer.start();\n\n // New game\n gameEnded = false;\n }", "function startTimer() {\n if(started == false ){\n started = true;\n myp5.background(200, 200, 200, 0);\n startTime = Date.now();\n }\n}", "function timer() {\r\n count ++;\r\n if(count === 31){ //restart Game at the 31st second\r\n context.clearRect(0, 0, canvas.width, canvas.height);\r\n end_screen();\r\n clearInterval(startCounterIntv);\r\n gameStarted = false;\r\n }\r\n }", "function startGame() {\n const interval = setInterval(() => {\n console.log(\"run interval\", timer);\n setTimer((prevTimer) => {\n if (prevTimer > 0) {\n return prevTimer - 1;\n } else{\n clearInterval(interval);\n return 0;\n }\n });\n }, 1000);\n // refTimer.current = interval;\n setDisabled(true);\n }", "function startTimer() {\n setTime();\n if (totalSeconds > 0) {\n setInterval(function() {\n secondsElapsed++;\n renderTime();\n }, 1000);\n } \n }", "function turnOnGame() {\r\n if (!gameIsStarted) {\r\n gameIsStarted = true;\r\n ticking = setInterval(timeStart, 17.5);\r\n }\r\n}", "function startTimer() {\n saveItemInLocalStorage('start',true);\n timer= setInterval(showTimer,1000 );\n}", "function startGame(){\n countStartGame = 30;\n correctAnswers = 0;\n wrongAnswers = 0;\n unanswered = 0;\n\n if (!timerRunning){ \n intervalId = setInterval(timer, 1000);\n timerRunning = true;\n }\n timer();\n console.log(\"game startiiing\");\n \n}", "function startTimer() {\n site.stTime = new Date().getTime();\n}", "function startTimer() {\n\n var timeInterval = setInterval(function () {\n timerEl.textContent = \"Time: \" + timeLeft;\n timeLeft--;\n\n if (timeLeft === -1) {\n clearInterval(timeInterval);\n gameOver();\n }\n\n }, 1000);\n\n initialize();\n}", "start() {\n this.trace.info(() => '========== game engine started ==========');\n this.initWorld();\n\n // create the default timer\n this.timer = new Timer();\n this.timer.play();\n this.on('postStep', (step, isReenact) => {\n if (!isReenact) this.timer.tick();\n });\n\n this.emit('start', { timestamp: (new Date()).getTime() });\n }", "function start(time) {\n if (time <= 0) {\n clearTimeout(timeKeep);\n World.clear(engine.world, {keepStatic: true});\n checkscore();\n }\n else {\n timeKeep = setTimeout(function() {\n time = time - .01;\n timeClock[0].innerText = time.toFixed(2);\n start(time);\n }, 10);\n }\n\n}", "function starttimer()\n{\n\tvar seconds = 1;\n\tthis.timer = setInterval(function(){\n\t\t$('#time').text(`Score: ${seconds}`);\n\t\tseconds++;\n\t},1000);\n}", "function onInit()\n{\n\tscene.setTimer(\"clock\", 1);\n\t\n scenes.scene_1.objects.txTime.text = \"Time: \" + minutes + \":\" + seconds;\n\n}", "function startGame() {\n\tinitGame();\n\tsetInterval(updateGame, 90);\n}", "function startGame() {\r\n console.log(\"in startgame\");\r\n myTimer = setInterval(gameLoop, 16);\r\n}", "function startGame(){\n if(!gameStarted){\n gameStarted = true;\n startGame1 = true;\n $scoreP1.text(0);\n timeUp = false;\n p1Score = 0;\n highlight();\n countdown();\n setTimeout(() => {\n timeUp = true;\n $player1PopUp.css('display', 'block');\n $p1ScoreDisplay.text(p1Score);\n },15000);\n }\n }", "function startGame() {\n\n initializeGlobalVariables();\n setStars(3);\n $('#deck').empty();\n $('#moves-counter').text(0);\n\n shuffle(cardList);\n renderCards();\n $('.card').click(onClickEvent);\n\n try {\n timer.start();\n } catch (error) {\n if (error.message.includes(\"Timer already running\")) {\n timer.stop();\n timer.start();\n }\n }\n $('#timer').html(\"00:00:00\");\n}", "function startGame()\n{\n \nbuttonStart.disabled = 'disabled';\nisPlaying = true;\nrenderScore();\n\ntimer = setInterval(clock,1000);// 1000 duration counting time\n}", "start() {\n this.trace.info(() => '========== game engine started ==========');\n this.initWorld();\n\n // create the default timer\n this.timer = new Timer();\n this.timer.play();\n this.on('postStep', (step, isReenact) => {\n if (!isReenact) this.timer.tick();\n });\n\n this.emit('start', { timestamp: (new Date()).getTime() });\n }", "function timeOn(){\n\tgameTime = setInterval(function(){\n\t\tt++;\n\t\t$(\"#time\").html(t);\n\t},1000);\n}", "function startTimer(){\n setTimeout(setIntervals, 300);\n setTimeout(rail_lights, 3000);\n setTimeout(getAudio, 3300);\n setTimeout(empty_window, 9000);\n}", "function startTimer() {\n currentTime = 0;\n timeoutStore = setInterval(updateTimer, timeIncrementInMs);\n }", "function startTimer() {\n const microseconds = 2000 // 2 seconds\n window.setTimeout(fetchCurrentDef, microseconds)\n}", "function startTimer() {\n if (totalSeconds > 0) {\n interval = setInterval(function() {\n secondsElapsed++;\n renderTime();\n }, 1000);\n } else {\n endGame();\n }\n}", "function startTimer() {\n status = 1;\n timer();\n }", "function timerStart(){\n heatGenerate();\n dsec++;\n totalTime++;\n if(dsec == 10) {\n dsec = 0;\n sec++;\n if(sec == 60) {\n sec = 0;\n min++;\n }\n }\n \n if(totalTime % GAME_SPAWN_TIME == 0) {\n spawnRandomGame();\n }\n \n if(difficulty < MAX_DIFFICULTY && totalTime % DIFF_INCREASE == 0) {\n difficulty++;\n }\n \n timer.innerHTML = pad(min) + \" : \" + pad(sec) + \" : \" + dsec;\n\n\n if(min == TIME_GOAL){\n ironManAction();\n }\n}", "function timer() {\r\n\ttimerId = window.setInterval(\"updateTime()\", 1000);\r\n}", "function setGameTime(ms) {\n if (timerRep.value.state === 'stopped') {\n livesplit_core_1.default.TimeSpan.fromSeconds(0).with(function (t) { return timer.setLoadingTimes(t); });\n timer.initializeGameTime();\n }\n livesplit_core_1.default.TimeSpan.fromSeconds(ms / 1000).with(function (t) { return timer.setGameTime(t); });\n nodecg.log.debug(\"[Timer] Game time set to \" + ms);\n}", "function startGameClock() {\n if (gameStart == 0) {\n gameStart = 1;\n gameClock(); \n }\n}", "function startTimer() {\n timeCounter = setTimeout(addTime, 1000);\n timerStatus = true;\n }", "function timerSetup() {\n // MINIGAME 1: 35sec\n if (minigame1) {\n timer = 35;\n }\n // MINIGAME 2: 5sec\n else if (minigame2) {\n timer = 5;\n }\n}", "function startTimer() {\n runTime = setInterval(() => {\n displayTime();\n time++;\n }, 1000);\n\n}", "start(time) {\n this.drawWelcomeMessage();\n\n clearInterval(this._ballInterval);\n\n var self = this;\n this._ballInterval = setInterval(function () {\n //check if any key was pressed to start the game initially\n if (startGameKeyPressed) {\n self.draw();\n }\n }, time);\n }", "function timer(){\r\n\tdocument.getElementById(\"myTimer\").innerHTML = \"Time: \" + time;\r\n\ttime++;\r\n\tif (time == 60){\r\n\t\tgame_win();\r\n\t}\r\n}", "function tick() {\n\tif (gameStart == true) {\n\t\tvar secs = timeInSecs;\n\t\tif (secs > 0) {\n\t\t\ttimeInSecs--;\n\t\t} else {\n\t\t\tgameover();\n\t\t}\n\t\tdocument.getElementById(\"timeScreen\").innerHTML = secs;\n\t} else {\n\t\tclearInterval(ticker);\n\t}\n}", "function start() {\n\t\ttimer--;\n\t\t$('#timer').text(\"Time Remaining: \" + timer + \" Seconds\");\n\n\t\tif (timer == 0) {\n\t\t\tclearInterval(countdown);\n\t\t\ttimer = 0;\n\t\t\t$('#timer').text(\"Time Remaining: \" + timer + \" Seconds\");\n\n\t\t\tscore();\n\t\t\t\n\t\t}\n\t}", "function loadGame(){\n myGameArea.start();\n}", "function GameTimer(){\n document.getElementById(\"pause\").style.visibility = \"visible\";\n if (!loadGame) {\n \t nextshape = Math.floor(Math.random() * 72);\n \t SpawnBlock();\n }\n else {\n \t loadGame = false;\n }\n function run(){\n\t BlockDrop();\n\t updateLevel();\n\t timer = setTimeout(function() {run()}, timeBetweenDrops);\n }\n run();\n}", "function startUpdatePlaytime() {\n stopUpdatePlaytime();\n if( !currentEmulator || !currentSystem || !currentGame ) return;\n updatePlaytime();\n currentPlaytimeInterval = setInterval( updatePlaytime, UPDATE_PLAYTIME_INTERVAL );\n}", "function startIntevall() {\r\n start = setInterval(function () {\r\n timer();\r\n }, 1000);\r\n }", "function start(){\n\tinit();\n\ttimer=setInterval('run()', 100);\n}", "function startTimer(duration, display) {\n let timer = duration, minutes, seconds;\n\n let start=setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n if (foodeaten){\n foodeaten=false;\n timer=seconds=seconds+10;\n }\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n if (--timer < 0 ||checkdead) {\n storeScore(score);\n showScreen(3);\n timeattack = 0;\n clearInterval(start);\n display.textContent=\"starting..\";\n dead.play();\n }\n }, 1000);\n\n }", "function startTimer() {\n p.timeOut1 = setTimeout(() => {\n p.ready = true;\n p.timeOfStart = p.millis();\n p.timeOut2 = setTimeout(() => {\n p.ready = false;\n p.timeOfEnd = p.millis();\n const success = false;\n const time = ((p.timeOfEnd - p.timeOfStart) / 1000).toFixed(3);\n p.props.generateResult(success, time);\n }, p.props.gameTime * 1000);\n }, p.props.startTime * 1000);\n }", "function startGame() {\n\t\tstatus.show();\n\t\tinsertStatusLife();\n\t\tsetLife(100);\n\t\tsetDayPast(1);\n\t}", "function startTimer(_timer){\n _timer.start({\n countdown: true,\n startValues: {\n seconds: 30\n }\n });\n }", "function setGameTime() {\r\n if (test) { console.log(\"--- setGameTime ---\"); }\r\n if (test) { console.log(\"gameDuration \" + gameDuration); }\r\n clearInterval(gameInterval);\r\n gameSeconds = gameDuration;\r\n}", "function startTimer() {\n // Set time remaining based on selection\n if (id(\"time-3\").checked) {\n timeLeft = 180;\n } else if (id(\"time-5\").checked) {\n timeLeft = 300;\n } else {\n timeLeft = 600;\n }\n // Set the timer for first second\n id(\"timer\").textContent = timeConvert(timeLeft);\n // Timer to update every second\n timer = setInterval(function() {\n timeLeft --;\n // If time runs out, end the game\n if (timeLeft === 0) {\n gameOver();\n }\n id(\"timer\").textContent = timeConvert(timeLeft);\n }, 1000); // function runs every 1000 ms\n}", "function startGame() {\n\t\n\t// fill the question div with new random question\n\tgenerateQuestion();\n\t\n\t// start the timer\n\tmoveProgressBar();\n}", "function startTimer() {\n\t\tlet timer = localStorage.getItem('Timer') * 60; // turn minutes into seconds\n\t\tlet minutes;\n\t\tlet seconds;\n\t\tconst countdown = document.getElementById('timer');\n\t\tconst overlayEnd = document.getElementById('endgame-overlay');\n\n\t\tsetInterval(() => {\n\t\t\tminutes = parseInt(timer / 60, 10);\n\t\t\tseconds = parseInt(timer % 60, 10);\n\n\t\t\tminutes = minutes < 10 ? `0${minutes}` : minutes;\n\t\t\tseconds = seconds < 10 ? `0${seconds}` : seconds;\n\n\t\t\tlocalStorage.setItem('TimerMinutes', minutes);\n\t\t\tlocalStorage.setItem('TimerSeconds', seconds);\n\n\t\t\tconst xminutes = localStorage.getItem('TimerMinutes');\n\t\t\tconst xseconds = localStorage.getItem('TimerSeconds');\n\n\t\t\tif (xminutes && xseconds) {\n\t\t\t\t// putting timer in html\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\tcountdown.textContent = `${xminutes}:${xseconds}`;\n\t\t\t} else {\n\t\t\t\tcountdown.textContent = '00:00';\n\t\t\t}\n\n\t\t\t// when the timer has stopped\n\t\t\tif (--timer < 0) {\n\t\t\t\tcountdown.textContent = 'Game over';\n\t\t\t\toverlayEnd.style.display = 'flex';\n\t\t\t\tdeleteTimer();\n\t\t\t}\n\t\t}, 1000);\n\t\t// function to show progress bar\n\t\tstartBar();\n\t}", "gameStart() {\n this._model.resetState();\n result.stats.percent = false;\n\n this._stopFn = timer(this._model.maxTime, this._goToResults);\n document.body.addEventListener('timer-tick', this._tick, false);\n\n this._timer.classList.remove('invisible');\n this._switchToNext(0, this._questions);\n }", "function startTimer() {\n resetTimers(); \n game_timer = setTimeout ( \"endTimer()\", maximum_time);\n update_timer = setInterval(\"updateTimerBox(1000)\", 1000); //update every 1 second\n}", "function startGame() {\n // console.log('Clicked')\n var startTime = new Date(),\n endTime = new Date(),\n seconds = (endTime - startTime) / 1000\n console.log() \n }", "function startTimer() {\r\n gTime1 = Date.now();\r\n gMyTime = setInterval(timeCycle, 1);\r\n}", "function startTimer(){\n\n // ParseInt to only get whole number\n const seconds = parseInt(this.dataset.time);\n timer(seconds);\n}", "function startTime() {\n //Runs function every 0.01 seconds if timer is on\n if (timerOn == false) {\n milliControl = setInterval(addMillis, 10);\n timerOn = true;\n //does nothing if timer is already on\n } else {\n\n }\n}", "start() {\n var time = new Date;\n var _this = this;\n\n if (this.fps == 60) {\n this.runLoop = displayBind(function tick() {\n _this.onTick(new Date - time);\n _this.runLoop = displayBind(tick);\n time = new Date;\n });\n } else {\n this.runLoop = setTimeout(function tick() {\n _this.onTick(new Date - time);\n _this.runLoop = setTimeout(tick, 1000 / _this.fps);\n time = new Date;\n }, 1000 / this.fps);\n }\n }", "function init() {\n\n\t// initial global variables\n\ttime = 0;\n\ttotalPlay = 0;\n\tplayed = [];\n\tstop = false;\n\tstarted = true;\n\tnumLife = 3;\n\n\t// set contents and start the timer\n\tsetScenario();\n\ttimer.text(time);\n\tlife.text(numLife);\n\tcountTime();\n}", "function startTimer() {\n timeLeft = startingTime;\n \n timeInterval = setInterval(function() {\n timerBox.textContent = Math.floor(timeLeft/60)+\":\"+ formatTime(timeLeft%60);\n timeLeft--;\n \n if (timeLeft === 0) {\n timerBox.textContent = \"\";\n loadEnd();\n clearInterval(timeInterval);\n }\n \n }, 1000);\n }", "function setTimer() {\n\ttimer = setInterval(playStrings, 200);\n}", "function timer()\r\n {\r\n console.log(\"running...\");\r\n }", "function startTimer() {\n /* The \"interval\" variable here using \"setInterval()\" begins the recurring increment of the\n secondsElapsed variable which is used to check if the time is up */\n interval = setInterval(function () {\n secondsElapsed--;\n // So renderTime() is called here once every second.\n renderTime();\n }, 1000);\n}", "function startGame() {\n\tinitGlobals();\n\n\t//set the game to call the 'update' method on each tick\n\t_intervalId = setInterval(update, 1000 / fps);\n}", "function doTimer()\n\t{\n\tinit();\n\tif (!timer_is_on)\n\t {\n\t \ttimer_is_on=1;\n\t \tisStopped = 0;\t\t \n\t }\n\t animate();\n\t}", "function startTimer() {\n timerId = setInterval(() => {\n time++;\n displayTime();\n }, 1000);\n}", "function initGame() {\r\n\tinitFE();\r\n\tinitGP();\r\n\tsetTimeout(startLoader, 250);\r\n}", "function startTimer() {\n //stop old timer\n window.clearInterval(timer);\n $('#elapsedSeconds').text('Time: ' + 0 + ' seconds');\n\n //start new timer\n var startTime = _.now();\n\n //increment timer, also updates score which is dependant on time\n timer = window.setInterval(function() {\n var elapsedSeconds = Math.floor((_.now() - startTime) / 1000);\n $('#elapsedSeconds').text('Time: ' + elapsedSeconds + ' seconds');\n\n updateScore(elapsedSeconds);\n }, 1000);\n }" ]
[ "0.78974557", "0.7727225", "0.76524043", "0.7542344", "0.7488791", "0.7340845", "0.732516", "0.73242277", "0.73122287", "0.73114747", "0.7294211", "0.7273359", "0.7237607", "0.7219074", "0.7194123", "0.71939105", "0.71915674", "0.71911687", "0.71771586", "0.71349347", "0.7090798", "0.7056174", "0.70561373", "0.7050957", "0.7039181", "0.70220196", "0.7008156", "0.69938385", "0.69801426", "0.6979917", "0.6964928", "0.69615376", "0.6961248", "0.69608325", "0.695602", "0.69413835", "0.69304323", "0.6926914", "0.6885435", "0.68837273", "0.6854801", "0.68499297", "0.6820683", "0.68203306", "0.6814402", "0.681229", "0.6809962", "0.68061936", "0.67998105", "0.6796322", "0.67700064", "0.67644435", "0.6762523", "0.6755605", "0.67549735", "0.6747905", "0.67397076", "0.6736342", "0.67343456", "0.673001", "0.67287886", "0.6724991", "0.6721319", "0.67197627", "0.6719514", "0.67027235", "0.66985554", "0.6694703", "0.66844785", "0.6672849", "0.6670872", "0.6670533", "0.6662744", "0.6659867", "0.66488975", "0.6647451", "0.66433096", "0.66408205", "0.6640238", "0.66397923", "0.6639775", "0.6634369", "0.66325647", "0.6629842", "0.66297126", "0.6625817", "0.662379", "0.66159123", "0.6615726", "0.6613383", "0.6610565", "0.6605612", "0.65977204", "0.65969217", "0.6589572", "0.6579244", "0.65764016", "0.65727615", "0.656808", "0.6564804", "0.65600294" ]
0.0
-1
stop timer when user win
function stopTimer() { clearInterval(countUp); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function stopTimer() {\n if (!stoptime) {\n stoptime = true;\n }\n}", "function stopTimer() {\n // check timer is on or off\n if (stopTime == false) {\n stopTime = true;\n }\n }", "function stopTimer(){ clearInterval(interval)}", "function breakTimer() {}", "function stopTimer() {clearTimeout(startTimer)}", "function stopTimer() {\n window.clearInterval(timeinterval);\n}", "function stopTimer(){\r\n clearInterval(timer);\r\n }", "setTimer() {\n time=30;\n const timer = setInterval( ()=> {\n time--\n $('h3').text(time);\n if (time===0) {\n clearInterval(timer);\n checkForWin();\n }\n }, 1000);\n }", "function stopTimer(){\n clearInterval(timer);\n }", "function stopOpponentCheckTimer() {\n clearInterval(nIntervId);\n }", "function stopTimer () {\n\t\tif (time) {\n\t\t\twindow.clearTimeout(time);\n\t\t}\n\t\ttime = 0;\n\t}", "function timeStop(){\n\tgameTime = clearInterval();\n\t//save score\n\tvar response = confirm(\"YOU WIN, CONGRATS!\\nYour game time was \" + t + \" seconds\\nDo you want to save your score?\");\n\tif(response == true)\n\t\tsaveScore();\n}", "function time_stop(){\n\t\t\t\tclearInterval(timeinterval);\n\t\t\t}", "function stopTime ()\t{\n\t\t\tclearInterval (time);\n\t\t}", "function stopGame(){\r\n\ttoggleGameTimer(false);\r\n}", "function timer(){\n countStartGame -= 1;\n console.log(countStartGame);\n if (countStartGame === 0){\n console.log (\"time's up\");\n //need to clear interval - add stop\n }\n}", "function stopTimer() {\n clearTimeout(timeCounter);\n }", "function stopTimer(){\n clearInterval(gameTimer);\n}", "_stopTimer() {\n this.game.time.events.remove(this.timer)\n }", "function stopTimer() {\n clearInterval(timer);\n }", "function stopTimer(){\n clearInterval(timer); // stops interval.\n } // end stopTimer.", "function stop () {\n clearInterval(timerHandle)\n }", "function stopTimer()\n {\n clearInterval(timer);\n }", "function stopTimer() {\n clearInterval(move)\n }", "function stops(){\n window.clearInterval(timer);\n}", "function winGame() {\n stopTimer();\n toggleModal();\n}", "function stopTimer() {\n clearTimeout(timeFunc);\n }", "function stopTimer(){\n clearInterval(timer);\n}", "function stopClock() {\n clearInterval(timer); \n }", "function stopTimer(){\n clearTimeout(setCountdownTimer);\n}", "function checkForWin() {\r\n // If the score reaches 273:\r\n if (score === 273) {\r\n // Then we stop the ghosts:\r\n ghosts.forEach(ghost => clearInterval(ghost.timerId))\r\n // We remove the event listener from the control function:\r\n document.removeEventListener('keyup', control)\r\n // And we display a win message:\r\n scoreDisplay.innerHTML = 'You WON'\r\n }\r\n}", "function stop_the_game(){\n clearInterval(the_game);\n game_over = true;\n restart_btn.slideDown();\n }", "function removeTime() {\r\n onlyOnce = false;\r\n setScreen();\r\n $(window).unbind('mousewheel keydown');\r\n setTimeout(function() {\r\n $('#close-gate').click();\r\n }, 10 * 1000);\r\n }", "function timerStop() {\n clearInterval(timer);\n}", "function stopTimer() {\n\tclearInterval(clock);\n}", "function stop() {\n clearInterval(interval);\n able_start_button();\n $.post(\n '/server/index.php',\n { action : 'timer_pause', seconds : seconds }\n );\n }", "function stopTimer() {\n clearInterval(timer)\n}", "function stop() {\n timer.stop();\n}", "function stopTimer(){\n clearTimeout(t);\n}", "stopTimer() {\n\t\t\tclearInterval(this.timer);\n\t}", "function stopTimer() {\n clearInterval(timer);\n}", "function TimerStop()\n{\n\twindow.clearInterval(timer);\n}", "handleTimer() {\n this.setTimerInterrupt(true);\n }", "function timer(){\n let minutes = 1;\n let seconds = 30;\n setInterval(function(){\n seconds--;\n if(seconds < 0 && minutes == 1){\n seconds = 59;\n minutes = 0;\n }\n if(seconds < 10){\n seconds = \"0\"+ seconds;\n }\n $('#timerDisplay').text(minutes + \":\" + seconds);\n\n if(minutes == 0 && seconds == 00){\n looseWindow()\n }\n },1000)\n }", "function stopTimer() {\r\n\r\n timerControl = false;\r\n stopTime = getCurrTime();\r\n totalPassedTime += calcPassedTime(initTime, stopTime);\r\n localStorage[\"timer\"] = JSON.stringify(totalPassedTime);\r\n lapInitialTimer = 0;\r\n \r\n initTime = stopTime;\r\n btnReset.classList.remove(\"inactive\");\r\n btnLap.classList.add(\"inactive\");\r\n}", "function decreaseTimer() {\n\n timer--;\n //if time is up..\n if (timer == 0) {\n\n //check if game was beaten\n if (gameScore < scoreToWin) {\n //set state variable to lost. will affect draw loop\n state = STATES.LOSE;\n //wait 5 seconds and restart game\n setTimeout(restartGame, 5000);\n }\n else {\n //set state variable to won. will affect draw loop\n state = STATES.WIN;\n //wait 15 seconds so users can scan QR and restart game\n setTimeout(restartGame, 15000);\n }\n\n }\n\n}", "function stopTimer()\n{\n isStarted = false;\n clearInterval(intervalId);\n}", "function countDown()\n{\n //Reduce the time\n if (timer > 0)\n {\n timer--;\n document.getElementById('timer').innerHTML = timer;\n }\n //End the turn when time runs out\n else if (timer == 0)\n {\n window.dispatchEvent(thisPlayerEndTurn);\n }\n}", "function stopTimer (){\n if(currentPlayer == player1) {\n player1.time = seconds;\n $('#player1Time').text(seconds);\n switchTurns();\n } else {\n player2.time = seconds\n $('#player2Time').text(seconds);\n checkScore();\n switchTurns();\n }\n //return seconds = 0;\n clearInterval(timer);\n seconds=0;\n snitch.addEventListener('click', startTimer);\n}", "function stopClock() {\r\n clearInterval(timeClock);\r\n timerRunning = false;\r\n}", "function stopCountdownTimer(isByTimer){\n countdownTimer.stop();\n room.roomStatus = 'initial';\n io.emit('breakTimeEnded', room.roomStatus, isByTimer);\n console.info('stopCountdownTimer', countdownTimer.status);\n}", "function stopTime() {\n clearInterval(currentTimer);\n}", "function stopTimer() {\n\n // stop the countdown\n clearInterval(time);\n // removes the timer from the html\n $(\"#timer\").empty();\n // call the check answers function\n checkAnswers();\n }", "function stopTimer() {\n flagTimer = false;\n clearInterval(timerInterval);\n }", "function stopTimer() {\n flagTimer = false;\n clearInterval(timerInterval);\n }", "function stopTimer() {\n clearInterval(interval);\n }", "function stopTime(){\n clearInterval(start);\n }", "function stopTimer(){\n\tclearInterval(interval);\n}", "function stopGame() {\n\twindow.clearInterval(controlPlay);\n\tcontrolPlay = false; \n\n\t//show lightbox with score\n\tlet message1 = \"Tie Game\";\n\tlet message2 = \"Close to continue.\";\n\n\tif (score2 > score1) {\n\t\tmessage1 = \"Player 2 wins with \" + score2 + \" points!\";\n\t\tmessage2 = \"Player 1 had \" + score1 + \" points.\";\n\t} else if (score1 > score2) {\n\t\tmessage1 = \"Player 1 wins with \" + score1 + \" points!\";\n\t\tmessage2 = \"Player 2 had \" + score2 + \" points.\";\n\t} //else\n\n\tshowLightBox(message1, message2);\n\n\thidePowerups();\n\treset();\n}", "function stopTimer(){\n clearInterval(intervalId);\n }", "function overEnd(){\n\tif(game_state === false){\n\t\tdocument.getElementById(\"status\").innerHTML = \"you wON!!! in \"+ Math.round(10*totaltime)/10 + \" seconds .... congrats\";\n\t\tclearInterval(stopclock);\n\t\tstopclock = null;\n\t\ttotaltime = 0;\n\t\tgame_state = null;\n\t}\n}", "stopTimer() {\n clearInterval(this.timer);\n }", "function stopTimer() {\n\n /*HERE CHECKING THE STATE OF TIMER IS RUNN TO STOP TIMER */\n if (Runningtime == true) {\n\n /*CLEAR THE COUNTING TO RESET THE TIMER TO ZERO*/\n clearInterval(startTimeout);\n startTimeout = null;\n\n hr = 0;\n sec = 0;\n mint = 0;\n milsec = 0;\n\n Timer.innerHTML = \"00:00:00.000\";\n\n } else\n alert(\"colock doesnot work\");\n}", "function stopwatch() {\n\tgameTime++;\n\titemTimer.innerText = gameTime /100;\n\t//statement to stop the game when time is too long\n\tif (gameTime == 9999) { // set max. time value (100 = 1 [s])\n\t\ttoStopWatch();\n\t\tmodalToLong();\n\t} else {\n\t\t\n\t}\n}", "function onTimer(){\r\n\tif (turn == OPPONENT) return;\r\n\tupdate_handler({time:timer});\r\n\ttimer--;\r\n\tif (timer < 0){\r\n\t\tmissStep();\r\n }\r\n}", "function clearTimersAndAllowSleep() {\n if (window.plugins) {\n window.plugins.insomnia.allowSleepAgain();\n }\n $interval.cancel(timer);\n $interval.cancel(countdownTimer);\n vm.running = false;\n $scope.$broadcast('pauseMode');\n }", "function stopTimer() {\n secondsElapsed = 0;\n setTime();\n renderTime();\n}", "function stopTimer() {\n\tclearInterval(timer.timer);\n\t$(\"#final-time\").html($(\"#time\").html());\n}", "function stopTimer() {\n timerRunning = false\n clearInterval(intervalId)\n }", "function stopTime() {\n clearInterval(timeId);\n timeId = true;\n}", "function stopTimer() {\n clearInterval(intervalId);\n }", "function stopTimer() {\n clearInterval(intervalId);\n }", "function stop() {\n isGameActive = false;\n }", "function timer() {\n\tif(TIMER_STOPPED == false) {\n\t\tTIMER--;\n\t\tif (TIMER < 0) {\n\t\t\t// clearInterval(counter);\n\t\t\t//counter ended, do something here\n\n\t\t\t$('#start_timer').show();\n\t\t\t$('#stop_timer').hide();\n\t\t\tdisableButtons(false);\n\t\t\tsetDefault();\n\n\t\t\treturn;\n\t\t}\n\n\t\tsetTimer(TIMER);\n\t}\n}", "function loseGame() {\n stopGame();\n stopTimer();\n alert(\"Game Over! You lost!\");\n}", "function stopTimer(){\n\t\tif(clock.inProgress == false){\n\t\t\taddInProgressRow();\n\t\t}\n\n\t\tclock.stopped = !clock.stopped;\n\t\tif(clock.stopped == false){\n\t\t\tclock.clockInterval = window.setInterval(addSecond, 1000);\n\t\t\tstop_btn.innerText= \"Stop\";\n\t\t\tstop_btn.style.backgroundColor = \"#96838F\";\n isTaskActive = true;\n\t\t} else{\n\t\t\tclearInterval(clock.clockInterval);\n\t\t\tstop_btn.innerText= \"Start\";\n\t\t\tstop_btn.style.backgroundColor = \"#53b56d\";\n isTaskActive = false;\n\t\t}\n\t}", "function win() {\n if (squares[4].classList.contains('frog')) {\n result.innerHTML = 'YOU WON';\n //this one line breaks the code find out why\n \n clearInterval(timerId);\n document.removeEventListener('keyup', moveFrog);\n }\n }", "function stopTimer(){\n if (angular.isDefined($scope.timerId)) {\n $interval.cancel($scope.timerId);\n $scope.timerId = undefined;\n }\n if (angular.isDefined($scope.timerIdGameStop)) {\n $timeout.cancel($scope.timerIdGameStop);\n $scope.timerIdGameStop = undefined;\n }\n }", "function stopTime() {\n // Clear the timer\n clearInterval(countDown);\n}", "stopTiming () {\n this.gameTimer.stopGameTimer()\n if (this.timerOneIsOn) {\n this.gameTimer.stopTimerOne()\n }\n }", "chronoStop(){\n clearTimeout(this.timerID);\n }", "function timer(time){\n var display = document.querySelector('#time');\n var timer = time;\n //Prevents the spamming of Start game\n clearInterval(interval)\n interval = setInterval(function() {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10);\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n //Checks pause status every second\n if (!pause){\n --timer;\n //Game lost\n if (timer < 0) {\n var x = document.getElementsByClassName(\"time-box\");\n x[0].style.background = \"#F2403F\";\n gameStatus(\"lose\")\n disableGame();\n clearInterval(interval);\n on();\n clearInterval(interval);\n }\n }\n }, 1000);\n}", "function stopPlay () {\n\t\tremoveWeenie();\n \tclearInterval(interval1);\n \tclearInterval(interval2);\n \tclearInterval(countdown);\n\t}", "function stopTimer() {\n if (timer == null)\n return;\n clearTimeout(timer);\n timer = null;\n unUnload();\n }", "function verde() {\n let interval=setInterval(()=>{\n if(object.time.className==\"red\" && object.start==null){\n object.time.className=\"green\"\n window.removeEventListener(\"keypress\", red)\n window.addEventListener('keyup', start)\n }\n else if(object.time.className==\"red\" && object.start==2){\n object.time.className=\"green\"\n window.removeEventListener(\"keypress\", red)\n window.addEventListener('keyup', reset)\n }\n },1000);\n \nwindow.addEventListener('keyup', ()=>clearInterval(interval))\n}", "function stopTimer() {\n clearInterval(runTime);\n timer.innerHTML = '0:00';\n}", "function pauseTimer() {\r\n clearInterval(setCountdown)\r\n}", "function stopTimer() {\n clearTimeout(interval);\n }", "function abortTimer() {\n clearInterval(tid);\n}", "function stopTimer() {\r\n clearInterval(gMyTime);\r\n //document.querySelector('.stop').innerText;\r\n}", "function stopRound() {\n if (game.state === state.START || game.state === state.RUN) {\n game.state = state.STOP;\n unloadRound();\n window.onkeydown = function(event) {\n if (event.key === game.keys.stop) {\n stopRound();\n }\n };\n } else if (game.state === state.STOP) {\n window.onkeydown = null;\n loadRound(false);\n game.state = state.RUN;\n }\n\n}", "function endGame()\n{\n stopTimer();\n $('#timer').text(\"\");\n $('#timer').css('width','0%');\n backgroundMusic.pause();\n disableUnflipped();\n gameOverPopup();\n return;\n}", "function stop() {\n\n clearInterval(intervalId);\n timerRunning = false;\n \n }", "function stopclock()\n{\n\tif(timerRunning)\n\t\tclearTimeout(timerID);\n\ttimerRunning = false;\n}", "function checkIfHandedOff(){\n if (tagpro.players[currentlyScoring].dead){\n timer = clearInterval(timer);\n timer = setInterval(searchForScorer,10);\n }\n}", "function countDown() {\n seconds -= 1;\n\n if (seconds < 0 && minutes > 0) {\n seconds += 60;\n minutes -= 1;\n }\n else if (seconds === -1 && minutes === 0) {\n // Timer is done. Call relevant functions\n stopTimer();\n PEvents.timerDone(currentTimerType);\n loadTimer();\n }\n \n render();\n }", "stopGame() {\n if (this.state.isOn) {\n this.addScore();\n }\n this.setState({isOn: false, time: 0});\n clearInterval(this.timer);\n clearInterval(this.timerColor);\n }", "function stopTimer() {\n clearInterval(interval);\n}", "_stopTimer() {\n this._tock.end();\n }", "function stopTimer() {\n clearInterval(timerID);\n}" ]
[ "0.73457396", "0.72465724", "0.72084236", "0.7204068", "0.7135043", "0.70913154", "0.7090592", "0.70748055", "0.7052787", "0.7048408", "0.7041365", "0.70258296", "0.69861686", "0.6981033", "0.6980792", "0.6971905", "0.69695824", "0.69453716", "0.6935854", "0.69013435", "0.6895623", "0.6888754", "0.68830824", "0.68828887", "0.68789715", "0.6870707", "0.68549484", "0.68482524", "0.68458784", "0.6820197", "0.6807035", "0.67992973", "0.6799291", "0.67945313", "0.67929584", "0.67876077", "0.6786003", "0.6774874", "0.6768421", "0.6767503", "0.67630905", "0.67579496", "0.6757573", "0.6751398", "0.675073", "0.67399734", "0.6736841", "0.67182714", "0.67057854", "0.6700062", "0.6691853", "0.6685498", "0.6674079", "0.6670226", "0.6670226", "0.6659564", "0.6658689", "0.66469216", "0.6646037", "0.66441035", "0.66388625", "0.66348743", "0.6624925", "0.6619427", "0.6617187", "0.6612832", "0.66111016", "0.6608734", "0.6601594", "0.6599538", "0.6594372", "0.6594372", "0.6591479", "0.6590578", "0.6590208", "0.6584681", "0.65772676", "0.6577187", "0.65766686", "0.657247", "0.6569357", "0.6568561", "0.65680593", "0.6561246", "0.65592825", "0.6553048", "0.6553008", "0.6553001", "0.65496165", "0.6549532", "0.6545273", "0.65420574", "0.65404", "0.65343416", "0.6533142", "0.6519926", "0.6518474", "0.6518418", "0.6510534", "0.6508971" ]
0.6921759
19
displaying timer with live update
function displayTimer() { let clock = $('.timer').text(time); let mins = Math.floor(time / 60); let secs = time % 60; if(secs < 10) { clock.text(`${mins}:0${secs}`); } else { clock.text(`${mins}:${secs}`); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateTimerDisplay(){\n // Update current time text display.\n $('#current-time').text(formatTime( player.getCurrentTime() ));\n $('#duration').text(formatTime( player.getDuration() ));\n }", "function updateTimerDisplay(){\n // Update current time text display.\n $('#current-time').text(formatTime( r.getCurrentTime() ));\n $('#duration').text(formatTime( r.getDuration() ));\n}", "function updateTimerDisplay() {\n // Update current time text display.\n //$('#current-time').text(formatTime(player.getCurrentTime()))\n //$('#duration').text(formatTime(player.getDuration()))\n}", "updateTimer() {\n\t\tlet timer = parseInt((Date.now() - this.gameStartTimestamp)/1000);\n\t\tthis.gameinfoElement.childNodes[1].innerHTML = \"<h1>Time: \" + timer + \" s</h1>\";\n\t}", "function updateTimer() {\n\t\t\tvar timeString = formatTime(currentTime);\n\t\t\t$stopwatch.html(timeString);\n\t\t\tcurrentTime += incrementTime;\n\t\t}", "display(){\n $('#timer').text(timer.hours + \":\" + timer.minutes + \":\"+ timer.secondes);\n }", "function updateTimerDisplay(){\n // Update current time text display.\n $('#current-time').text(formatTime(player.getCurrentTime() ));\n $('#duration').text(formatTime( player.getDuration() ));\n}", "function updateTimer() {\n var t = addTimer();\n $('#days').html(t.days);\n $('#hours').html(t.hours);\n $('#minutes').html(t.minutes);\n $('#seconds').html(t.seconds);\n}", "_updateTime() {\r\n // Determine what to append to time text content, and update time if required\r\n let append = \"\";\r\n if (this.levelNum <= MAX_LEVEL && !this.paused) {\r\n this.accumulatedTime += Date.now() - this.lastDate;\r\n }\r\n this.lastDate = Date.now();\r\n\r\n // Update the time value in the div\r\n let nowDate = new Date(this.accumulatedTime);\r\n let twoDigitFormat = new Intl.NumberFormat('en-US', {minimumIntegerDigits: 2});\r\n if (nowDate.getHours() - this.startHours > 0) {\r\n this.timerDisplay.textContent = `Time: ${nowDate.getHours() - this.startHours}:`+\r\n `${twoDigitFormat.format(nowDate.getMinutes())}:` +\r\n `${twoDigitFormat.format(nowDate.getSeconds())}${append}`;\r\n }\r\n else {\r\n this.timerDisplay.textContent = `Time: ${twoDigitFormat.format(nowDate.getMinutes())}:` +\r\n `${twoDigitFormat.format(nowDate.getSeconds())}${append}`;\r\n }\r\n }", "function updateTimeDisplay(newTime) {\n $(\".timer\").text(time);\n time = newTime;\n}", "function updateTimer() {\n //console.log(currentTime);\n formatTimeDuration(currentTime);\n var timeString = formatTime(currentTime);\n $stopwatch.html(timeString);\n currentTime += incrementTime;\n }", "function updateTime(){\n setTimeContent(\"timer\");\n}", "function updateTime() {\n seconds += 1;\n document.querySelector(\"#timer\").innerText = \"Time elapsed: \" + seconds;\n}", "function updateTimer() {\n counter++;\n timer.innerHTML = \"<div>timer: \" + counter + \"</div>\";\n }", "displayTimer(){\n this.final_timer = `${this.year}-${this.month}-${this.date} Time : ${this.hours}:${this.mins}:${this.seconds}`;\n }", "function updateTimeDisplay()\n{\n // Get the current time in seconds and then get the difference from the stop seconds.\n var diff = globalStopSeconds - currentSeconds();\n\n // Set the time on the screen.\n $(\"#timer-display\").text( secondsToMinutes( diff));\n\n // Update the sand column graph. \n sandColumnUpdate( diff);\n\n}", "function updateTimer(newVal, oldVal) {\r\n\t\t// Change class on the timer to change the colour if needed.\r\n\t\t// See the common.css file for more information.\r\n\t\tif (oldVal) timerElem.toggleClass('timer_'+oldVal.state, false);\r\n\t\ttimerElem.toggleClass('timer_'+newVal.state, true);\r\n\t\t\r\n\t\ttimerElem.html(newVal.time); // timer.html\r\n\t}", "function domTimer() {\n $(`.timer`).text(`Timer: ${totalMinutes}:${totalSeconds}`);\n }", "function updateTimer() {\n var timerStr;\n var tempSeconds = seconds;\n var tempMinutes = Math.floor(seconds / 60) % 60;\n tempSeconds -= tempMinutes * 60;\n\n // formatTimer() defined after updateTimer()\n timerStr = formatTimer(tempMinutes, tempSeconds);\n timer.innerHTML = timerStr;\n }", "function timer() {\r\n\ttimerId = window.setInterval(\"updateTime()\", 1000);\r\n}", "function printTimer() {\n var timeDisplay = $(\"<h3>\").text(\n \"Time Remaining: \" + timeRemaining + \" Seconds\"\n );\n timeDisplay.attr({ id: \"time-display\", class: \"animated flipInX\" });\n $(\"#timer-section\").append(timeDisplay);\n intervalId = setInterval(count, 1000);\n }", "function updateTimer(elapsedSeconds) {\n let seconds = elapsedSeconds % 60;\n let minutes = Math.floor(elapsedSeconds / 60);\n let displayedTime = `${minutes.pad(2)}:${seconds.pad(2)}`;\n timer.innerHTML = displayedTime;\n}", "function runTimer() {\n var displayText = runCounters(true)\n document.getElementById('timer-window').innerHTML = displayText\n}", "function timerStart() {\n timer = setInterval(function tick(){\n timeInSeconds++;\n updateTimerDisplay(timeInSeconds);\n }, 1000);\n}", "function displayTimer(){\n\t\tif(!timerOn){\n\t\t\treturn;\n\t\t}\n\t\tdocument.getElementById(\"numeric\").innerHTML=\"<h1>\"+count+\"</h1>\";\n\t\tdocument.bgColor = window.location.hash.substring(1) === 'fullbg' ? 'darkred' : '';\n\t\tif(count==0){\n\t\t\tstartT=(new Date()).getTime();\n\t\t}\n\t\tcount +=100;\n\t\tif(count>maxResponseTime){\n\t\t\tresetDisplayTimer();\n\t\t\treturn;\n\t\t}\n\t\tt=setTimeout(\"displayTimer()\", 100);\n\t}", "function updateTimer(now){\n timer_field.text(Math.round((timer - now)/1000));\n}", "function timer() {\n difference = Math.round(milliseconds - (Date.now() - now) / 1000);\n if (difference < 0) {\n return;\n }\n // eslint-disable-next-line no-use-before-define\n const { minutes, seconds } = displayTimer(difference);\n\n // eslint-disable-next-line\n displayElement.textContent = `${minutes}:${seconds}`;\n document.title = `${minutes}:${seconds}`;\n }", "function displayTimer() {\n\tif(sec < 10)\n\t\tsecHTML.innerHTML = '0' + sec;\n\telse\n\t\tsecHTML.innerHTML = sec;\n\n\tif(min < 10)\n\t\tminHTML.innerHTML = '0' + min;\n\telse\n\t\tminHTML.innerHTML = min;\n}", "function dispTime() {\n setInterval(function() {\n time = calcTime(numSeconds);\n document.querySelector('.timer').innerHTML = time;\n }, 1000);\n}", "function stopwatchUpdate(){\n rawTime += intervalRate\n stopwatchTime.innerHTML = formatTime(rawTime)\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 displayTimer() {\n milliseconds += 10;\n\n if (milliseconds == 1000) {\n milliseconds = 0;\n seconds++;\n if (seconds == 60) {\n seconds = 0;\n minutes++;\n if (minutes == 60) {\n minutes = 0;\n hours++;\n }\n }\n }\n\n // convert integer into text to display\n // if number is single digit then add 0\n let h = hours < 10 ? \"0\" + hours : hours;\n let m = minutes < 10 ? \"0\" + minutes : minutes;\n let s = seconds < 10 ? \"0\" + seconds : seconds;\n let ms =\n milliseconds < 10\n ? \"00\" + milliseconds\n : milliseconds < 100\n ? \"0\" + milliseconds\n : milliseconds;\n\n // update timer details\n msDisplay.innerHTML = ms;\n secondsDisplay.innerHTML = s;\n minutesDisplay.innerHTML = m;\n hoursDisplay.innerHTML = h;\n}", "function timer() {\n\t\t//get elapsed time, comes as milliseconds\n\t\tlet timeElapsed = Date.now() - timerStart;\n\n\t\tif (timeElapsed >= QUIZDURATION) {\n\t\t\tendQuiz();\n\t\t\treturn;\n\t\t}\n\t\t//convert to seconds\n\t\tlet remaining = (QUIZDURATION - timeElapsed) / 1000;\n\t\tlet h = parseInt(remaining / 3600); //divide to get hours\n\t\tlet m = parseInt( (remaining % 3600) / 60); //divide remainder to get minutes\n\t\tlet s = parseInt( (remaining % 3600) % 60); //divide that remainder to get seconds\n\n\t\t//put on page\n\t\tlet textString = padTimer(h) + \":\" + padTimer(m) + \":\" + padTimer(s);\n\t\ttimeDisplay.innerText = textString;\n\t}", "function t_updateTime() {\n var display = document.getElementById(\"t_time\");\n t_seconds--;\n if (t_seconds==-1) {\n t_seconds = 59;\n t_mins--; \n }\n if (t_mins<0) {\n display.innerHTML = \"Time is up!\";\n } else {\n if (t_mins<10&&t_seconds<10) {\n display.innerHTML = \"0\"+t_mins+\":0\"+t_seconds; \n } else if (t_mins<10) {\n display.innerHTML = \"0\"+t_mins+\":\"+t_seconds; \n } else if (t_seconds<10) {\n display.innerHTML = t_mins+\":0\"+t_seconds; \n } else {\n display.innerHTML = t_mins+\":\"+t_seconds; \n }\n t_timer = setTimeout(\"t_updateTime()\",1000);\n }\n \n}", "function statusChanged(){\n resetTimer();\n renderTimer();\n}", "function startTimer() { // Timer begins incrementing 1 second after the user clicks?\n liveTimer = setInterval(function() {\n timer.innerHTML = `${minute} min ${second} sec`;\n second++;\n if (second == 60) {\n minute++;\n second= 0 ;\n }\n if (minute == 60) {\n hour++;\n minute= 0 ;\n }\n }, 1000);\n }", "function updateTime() {\r\n const date = new Date();\r\n const hour = formatTime(date.getHours());\r\n const minutes = formatTime(date.getMinutes());\r\n const seconds = formatTime(date.getSeconds());\r\n\r\n display.innerText=`${hour} : ${minutes} : ${seconds}`\r\n}", "function timerTick() {\r\n\t\ttime++;\r\n\t\ttimerDiv.html(time);\r\n\t}", "function showTime() {\n var elTimer = document.querySelector('.timer');\n gGame.secsPassed = parseInt((Date.now() - gStartTime) / 1000);\n elTimer.innerHTML = `${gGame.secsPassed}s`\n}", "function updateTime() {\n if (counter >= 0) {\n timer.innerHTML = counter;\n --counter;\n setTimeout(updateTime, 1000);\n }\n if (counter <= 0) {\n $('#over').modal('show')\n }\n }", "function timer(){\r\n const now = new Date();\r\n const hours = now.getHours();\r\n const minutes = now.getMinutes();\r\n const seconds = now.getSeconds();\r\n \r\n timerDisplay.textContent = `${hours}:${minutes < 10 ? '0': ''}${minutes}:${seconds < 10 ? '0': ''}${seconds}`;\r\n \r\n}", "function update_counter() {\n let time = remaining_time(); //get the time object\n\n //adds zero in front of the time measure unit if it displays less than 2 symbols\n function add_zero(measure_unit) {\n let unit; //variable needed to store different data from the time object depending on function argument\n\n if (measure_unit == hours){\n unit = time.hours; //stores the hours\n } else if (measure_unit == minutes) {\n unit = time.minutes; //stores the minutes\n } else if (measure_unit == seconds) {\n unit = time.seconds; //stores the seconds\n }\n\n //function returns additional zero symbol if 'unit' variable value are less than 10\n return (unit < 10) ? measure_unit.innerText = '0' + unit : measure_unit.innerText = unit;\n }\n\n //if delta time is over stops update function and display zero to every time measure unit\n if (time.total < 0) {\n clearInterval(update_time);\n time.hours = time.minutes = time.seconds = 0;\n }\n\n //adding zero to every displayed measure unit\n add_zero(hours);\n add_zero(minutes);\n add_zero(seconds);\n }", "function updateTimerText() {\n $(\".timer\").html(`<h3>Time Remaining ${time} Seconds</h3>`);\n}", "function stopwatchUpdate() {\r\n rawTime += intervalRate;\r\n stopwatchTime.innerHTML = formatTime(rawTime);\r\n}", "function refreshClock() {\n $('#timer').html(CustomTime.getTime);\n}", "function updateTimer() {\n //if the timer reaches 0, end the quiz and stop the timer\n if (timer < 0.1) {\n clearInterval(interval);\n endQuiz();\n return;\n }\n //otherwise increment time and change DOM\n timer -= 0.1;\n $timer.text(\"Timer: \" + timer.toFixed(1));\n }", "function displayTimer() {\n\tif (numMousePressed > 0) {\n\t\ttextSize(50);\n\t\tfill(0);\n\t\ttext(speedTimerMinutes + \":\" + speedTimerSeconds, width / 2, 40);\n\t\tif (frameCount % 60 === 0 && stopTimer != true) {\n\t\t\tspeedTimerSeconds++;\n\t\t\tif (speedTimerSeconds > 59) { // moves onto minutes if game runs more than 59 seconds\n\t\t\t\tspeedTimerMinutes += 1;\n\t\t\t\tspeedTimerSeconds = 0;\n\t\t\t}\n\t\t}\n\t}\n}", "updateTimer() {\n var currentTime = new Date();\n var timeDifference = this.startTime.getTime() - currentTime.getTime();\n\n this.timeElapsed = Math.abs(timeDifference / 1000);\n\n var timeRemaining = this.totalTime - this.timeElapsed;\n\n var seconds = Math.floor(timeRemaining);\n\n var result = (seconds < 10) ? \"\" + seconds : \"\" + seconds;\n\n if (result >= 0){\n this.timeLabel.text = result;\n }\n }", "function startTime(){\n clearInterval(timer);\n timer = setInterval(displayTime, 1000);\n }", "function displayTime() {\n var timerInterval = setInterval(function() {\n var currentTime = moment().format('MMMM Do YYYY, h:mm:ss a');\n $(\"#current\").text(currentTime);\n secondsLeft--;\n \n if (secondsLeft === 0) {\n clearInterval(timerInterval);\n displayTime();\n }\n }, 1000); \n }", "function updateTime() {\n scorePanel.playTime = Math.trunc((performance.now() - scorePanel.startTime) / 1000);\n $(\".time\").text(scorePanel.playTime.toString().padStart(3, \"0\").concat(\" seconds\"));\n}", "function startTimer() {\n timerId = setInterval(() => {\n time++;\n displayTime();\n }, 1000);\n}", "function showTimer() {\n changeTimer();\n}", "function timer(){\r\n secondsTimer++ //Increment the seconds when timer is called each 1second\r\n\r\n //increment minutes and hours in timer display\r\n if(secondsTimer == 60){\r\n secondsTimer = 0\r\n minutesTimer++\r\n if(minutesTimer == 60){\r\n minutesTimer = 0\r\n hourTimer++\r\n }\r\n }\r\n\r\n //Mechanism to format the time in timer\r\n if(secondsTimer<10){\r\n secondsNewTimer = \"0\"+secondsTimer\r\n }else{\r\n secondsNewTimer = secondsTimer\r\n }\r\n if(minutesTimer<10){\r\n minutesNewTimer = \"0\"+minutesTimer\r\n }else{\r\n minutesNewTimer = minutesTimer\r\n }\r\n if(hourTimer < 10){\r\n hourNewTimer = \"0\"+hourTimer\r\n }else{\r\n hourNewTimer = hourTimer\r\n }\r\n\r\n //Format the time in timer and apply this time in web page\r\n var format = hourNewTimer+\":\"+minutesNewTimer+\":\"+secondsNewTimer\r\n document.getElementById(\"timer\").innerHTML = format\r\n}", "function updateClock() {\n newDate = new Date();\n newStamp = newDate.getTime();\n var diff = Math.round((newStamp-startStamp)/1000);\n\n var d = Math.floor(diff/(24*60*60));\n diff = diff-(d*24*60*60);\n var h = Math.floor(diff/(60*60));\n diff = diff-(h*60*60);\n var m = Math.floor(diff/(60));\n diff = diff-(m*60);\n var s = diff;\n\n document.getElementById(item.id).innerHTML = d+\" day(s), \"+h+\" hour(s), \"+m+\" minute(s), \"+s+\" second(s) active\";\n }", "function timer() {\n\tseconds++;\n\tif(seconds === 60){\n\t\tminutes++;\n\t\tseconds = 0;\n\t}\n\ttimerContent.innerHTML = `<span class=\"time\">Time: ${minutes}&nbsp;:&nbsp;${seconds}</span>`;\n}", "function updateTimer(){\n if (secondsLeft < totalSeconds){\n liveTimeValue.textContent = totalSeconds - secondsLeft; \n } else {\n liveTimeValue.textContent = 0;\n } \n}", "function updateTimerDisplay(totalSeconds){\n let hours = 0;\n if (totalSeconds >= 3600) {\n hours = Math.floor(totalSeconds / 3600);\n totalSeconds %= 3600;\n }\n let minutes = 0;\n if (totalSeconds >= 60){\n minutes = Math.floor(totalSeconds / 60);\n }\n let seconds = totalSeconds % 60;\n // pad with leading zeroes\n let timerElement = document.getElementById(\"timer\");\n timerElement.textContent = String(hours).padStart(2, \"0\") + \":\" +\n String(minutes).padStart(2, \"0\") + \":\" +\n String(seconds).padStart(2, \"0\");\n}", "function startTimer() {\n runTime = setInterval(() => {\n displayTime();\n time++;\n }, 1000);\n\n}", "function startTimer() {\n $timer.show().text(\"Timer: \" + timer.toFixed(1));\n interval = setInterval(updateTimer, 100);\n }", "function updateTime(){\n timer.count += 1000\n $('#timer').text(new Date(timer.count).toLocaleTimeString(undefined, {\n minute: '2-digit',\n second: '2-digit'\n }))\n}", "function initTime() {\n nowTime = setInterval(function () {\n $timer.text(`${second}`)\n second = second + 1\n }, 1000);\n}", "function timerUpdate() {\n var currentTime = new Date();\n var diffTime = currentTime.getTime() - firstClickTime.getTime();\n\n diffHours = Math.floor(diffTime / (1000 * 60 * 60));\n diffTime -= diffHours * (1000 * 60 * 60);\n\n diffMin = Math.floor(diffTime / (1000 * 60));\n diffTime -= diffMin * 1000 * 60;\n\n diffSec = Math.floor(diffTime / 1000);\n\n showCardTimer.innerText = digitFormat(diffHours) + \":\" + digitFormat(diffMin) + \":\" + digitFormat(diffSec);\n }", "function updateTime() {\n time++;\n $('#timer').text('Game time: ' + time);\n}", "function timeUpdate() {\n (setInterval(function () {\n currentTime = moment().format('HH');\n updatePlanner()\n }, 1000))\n}", "displayTime() {\n if(app === 1){\n this.d1.value = this.twoDigitNum(stopwatch.t1);\n this.d2.value = this.twoDigitNum(stopwatch.t2);\n this.d3.value = this.twoDigitNum(stopwatch.t3);\n }\n else{\n this.d1.value = this.twoDigitNum(timer.t1);\n this.d2.value = this.twoDigitNum(timer.t2);\n this.d3.value = this.twoDigitNum(timer.t3);\n }\n }", "function updateTime() {\n var time = 0;\n if (global.startTime != null) {\n time = (new Date()).getTime() - global.startTime;\n time = (time/1000)|0;\n }\n var timeDiv = document.getElementById(\"timeDisplay\");\n timeDiv.innerHTML = formatTime(time);\n}", "function startTime() {\n timer = setInterval(function() {\n seconds ++;\n displayTime();\n }, 1000)\n}", "function timer(){\n\t\tsetInterval(function(){\n\t\t\tvar sec_curr = Math.floor(vid.currentTime);\n\t\t\tvar zero_curr = \"\";\n\t\t\tif((sec_curr % 60) < 10){\n\t\t\t\tzero_curr = \"0\";\n\t\t\t} else{\n\t\t\t\tzero_curr = \"\";\n\t\t\t}\n\t\t\tvar current_time = Math.floor(sec_curr / 60) + \":\" + zero_curr + (sec_curr % 60);\n\t\t\t$('#curr_time').text(current_time);\n\t\t\t$('progress').attr('value', sec_curr);\n\t\t}, 1000);\n\t}", "function timerUpdate() {\n if (timerOn) {\n // Timer logic\n if (timerHours > 0 && timerMinutes == 0) {\n timerHours--;\n timerMinutes = 60;\n }\n\n if (timerSeconds == 0) {\n timerMinutes--;\n timerSeconds = 60;\n }\n\n timerSeconds--;\n\n // Formatting for timer display\n var timeString = timerHours + \":\";\n if (timerMinutes < 10)\n timeString += \"0\"\n timeString += timerMinutes + \":\";\n\n if (timerSeconds < 10)\n timeString += \"0\"\n timeString += timerSeconds;\n\n // Update timer display\n $(\"#timer\").text(timeString);\n $(\"title\").text(\"Clocky (\" + timeString + \")\");\n\n // Timer Ends\n if (timerHours == 0 && timerMinutes == 0 && timerSeconds == 0) {\n timerOn = false;\n alert.play();\n }\n }\n}", "function displayCurrentTime() {\n\tsetInterval(function(){\n\t\t$('#current-time').html(moment().format('hh:mm A'))\n\t }, 1000);\n\t}", "function updateTime() {\n time -= 1000;\n showTime(); \n}", "function timeElapsed() {\n timer.textContent = `Timer: ${seconds}`;\n seconds++;\n }", "function startTimer() {\n liveTimer = setInterval(function() {\n totalSeconds++;\n timerContainer.innerHTML = totalSeconds;\n },1000);\n}", "function updateTime() {\n let date = getToday();\n let hours = date.getHours();\n let minutes = date.getMinutes();\n let seconds = date.getSeconds();\n\n hours = addZero(hours);\n minutes = addZero(minutes);\n seconds = addZero(seconds);\n\n document.querySelector(\".date .time\").innerText = hours + \":\" + minutes + \":\" + seconds;\n // $('.date .time').text(`${hours}:${minutes}:${seconds}`);\n update = setTimeout(function () { updateTime() }, 500)\n}", "function updateTimer(){\r\n timer--\r\n $('.timer').text(`Time: ${timer}`)\r\n if(timer <= 0){\r\n endGame()\r\n }\r\n}", "function initTime() {\n currentTimer = setInterval(function() {\n $timer.text(`${second}`)\n second = second + 1\n }, 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 displayCurrentTime() {\n setInterval(function(){\n $('#current-time').html(moment().format('HH:mm'))\n }, 1000);\n }", "function setTime()\n {\n ++totalSeconds;\n $('#timer > #seconds').html(pad(totalSeconds%60));\n $('#timer > #minutes').html(pad(parseInt(totalSeconds/60)));\n }", "function startTimer(){\r\n startedTimer = true;\r\n time++;\r\n var out = formatTime();\r\n document.getElementById(\"counter\").innerHTML = out;\r\n \r\n var interval = setTimeout(startTimer, 1000);\r\n \r\n }", "function counter() {\n interval = setInterval(function() {\n seconds ++;\n compute_display();\n }, 1 );\n }", "function timer() {\n sec += 1;\n if (sec === 60) {\n min += 1;\n sec = 0;\n }\n\n for (let i = 0; i < timeEl.length; i++) {\n timeEl[i].innerText = min.pad(2) + \":\" + sec.pad(2);\n }\n }", "function runTimer () {\n CLOCK.innerHTML = Clock.printClock();\n millisecondsCounter += 10; //interval runs every 10 milliseconds\n secondsCounter = millisecondsCounter / 1000;\n Clock.updateTime();\n}", "function timeInterval() {\n interval = setInterval(displayTime, 1000);\n}", "function updateClock() {\r\n\tvar date = new Date();\r\n\tvar timer = document.getElementById(\"currTimer\");\r\n\ttimer.textContent = msToTime(date.getTime() - state.starting_time);\r\n}", "function startTimer() {\n app.interval = setInterval(function () {\n app.timer.innerHTML = app.minute + ':' + app.second;\n app.second++;\n if (app.second == 60) {\n app.minute++;\n app.second = 0;\n }\n if (app.minute == 60) {\n app.hour++;\n app.minute = 0;\n }\n if (app.second < 10) {\n app.second = '0' + app.second;\n }\n }, 1000);\n}", "function dynamicTime() {\n var currentTime = moment().format('HH:mm:ss');\n $('#dynamic-time').text(currentTime);\n setInterval(dynamicTime, 1000);\n }", "function updateTimer()\n{\n\tconsole.log(\"timer going! \");\n\tif(gametime == 0) // if game is done.\n\t{\n\t\t$(\"#announcements\").html(\"Game over! Reload the page to try again.\");\n\t\tstopTimer();\n\t}\n\telse\n\t{\n\t\tgametime--;\n\t\tvar min = Math.floor(gametime / 60);\n\t\tvar sec = gametime % 60;\n\t\tvar s = pad(min,2) + \":\" + pad(sec,2);\n\t\t$(\"#gametimerscreen\").val(s);\n\t}\n}", "function displayTimer(){\n push();\n textFont(`Blenny`);\n fill(breadFill.r, breadFill.g, breadFill.b);\n textSize(24);\n text(`${timer} seconds left`, 1050, 190);\n if (frameCount % 60 == 0 && timer > 0) {\n timer --;\n }\n // if (timer == 0) {\n // text(\"GAME OVER\", width, height);\n // }\n pop();\n }", "function setTimer() {\n document.getElementById(\"timer\").textContent = timer;\n }", "function updateTimer(){\n if (pomo.isPaused) return;\n\n seconds -= 1;\n pomo.timerDisplay.innerHTML = makeSecondsReadable(seconds);\n\n if(seconds<=0) { //if timer is done then 'ding' and set timer to next interval\n console.log(\"play()\")\n pomo.isWork()? document.querySelector(\".tom\").play() : document.querySelector(\".tink\").play();\n setTimer() ;\n }\n }", "function runTimer(event){\n\tlet start = new Date().getTime();\n\ttimer = window.setInterval(function(){\n\t\t\t\t\tlet time = new Date().getTime()-start,\n\t\t\t\t\t\tseconds = Math.floor(time/1000)%60%10,\n\t\t\t\t\t\ttensSecs = Math.floor(time/10000)%6,\n\t\t\t\t\t\tminutes = Math.floor(time/60000)%60%10,\n\t\t\t\t\t\ttensMins = Math.floor(time/600000)%6\n\t\t\t\t\t\thours = Math.floor(time/3600000);\n\n\t\t\t\t\t\tdocument.getElementById('time').innerText = hours + ':' + tensMins + minutes + ':' + tensSecs + seconds;\n\t\t\t\t\t},\n\t\t\t\t100);\n}", "refreshTime() {\n if (this._game.isRun()) {\n this._view.setValue(\"time\", this._game.timeElapsed);\n }\n }", "function timeCounting(){\n\t\ttimer = setInterval(function(){\n\t\t\tsec +=1;\n\t\t\tif(sec <60){\n\t\t\t\t$(\".seconds\").text(sec + \"s\");\n\t\t\t} else if(sec ===60){\n\t\t\t\tmin += 1;\n\t\t\t\tsec = 0;\n\t\t\t\t$(\".minutes\").css('visibility', 'visible');\n\t $(\".colon-two\").css('visibility', 'visible');\n\t $(\".seconds\").text(sec + \"s\");\n\t $(\".minutes\").text(min + \"m\");\n\t sec += 1;\n\t\t\t}\t\n\t\t\t// console.log(sec);\n\t\t},1000)\n\t\t\t\n\t}", "function timer() {\n seconds++; // increase seconds (current)\n saveSeconds++; // save the seconds (total)\n\n if(seconds / 60 == true) {seconds = 0; minutes++} // after 60 sec increase minutes\n if(minutes / 60 == true) {minutes = 0; hours++} // after 60 min increase hours\n\n // beautify the output for human reading\n secondsOutput = (seconds >= 10) ? seconds : '0' + seconds;\n minutesOutput = (minutes >= 10) ? minutes : '0' + minutes;\n hoursOutput = (hours >= 10) ? hours : '0' + hours;\n\n // show hours only when reach hours\n if(hours == true) {\n // update the title\n document.title = hoursOutput + ':' + minutesOutput + ':' + secondsOutput;\n } else {\n // update the title\n document.title = minutesOutput + ':' + secondsOutput;\n } // end if - else\n} // end timer()", "function countDown() {\r\n tick();\r\n var countDownString = numToString(min) + \" : \" +\r\n numToString(sec);\r\n const printTimer = document.getElementById(\"timer\");\r\n timer.innerText = countDownString;\r\n}", "function updatetime() {\n time.innerHTML = new Date;\n \n}", "function updateTimer(seconds) {\n var minutes = Math.floor(seconds / 60);\n var seconds = seconds % 60;\n\n // zero pads minutes and seconds if < 10\n var time = ((minutes < 10) ? \"0\" + minutes : minutes) + \":\" + ((seconds < 10) ? \"0\" + seconds : seconds);\n $timer.html(time);\n }", "function updateUI(){\n\t\n\t$('elapsed').innerText = timeElapsed();\n\t$('timer').innerText = countdown;\n\t$('shots').innerText = min_elapsed;\n\t$('bottles').innerText = toBottles(min_elapsed);\n\t$('ml').innerText = toMl(min_elapsed);\n\t$('oz').innerText = toOz(min_elapsed);\n\tif(paused){\n\t\t$('status').innerText = 'Play!';\n\t\t$('status').setStyle('color', '#'+Math.floor(Math.random()*16777215).toString(16));\n\t}\n\telse{\n\t\t$('status').innerText = 'Pause.';\n\t}\n\t$('interval').innerText = 'Game interval is ' + interval + ' seconds. Click to change.';\n}" ]
[ "0.8108987", "0.8053087", "0.79875094", "0.78876555", "0.7877026", "0.7836753", "0.77575207", "0.76473975", "0.76145405", "0.75946945", "0.75683683", "0.7521375", "0.7513487", "0.7442374", "0.740356", "0.73958313", "0.7374653", "0.7365908", "0.7354137", "0.7297008", "0.7289488", "0.72590536", "0.7251007", "0.72047484", "0.7203797", "0.7199478", "0.7195678", "0.7167597", "0.7163178", "0.7160631", "0.71513605", "0.7150671", "0.71110976", "0.7106755", "0.7102133", "0.70892197", "0.70733017", "0.70702034", "0.705356", "0.7050438", "0.7036365", "0.70340484", "0.70313156", "0.70261914", "0.7024083", "0.7023153", "0.7020238", "0.7005551", "0.7004864", "0.6990708", "0.6986057", "0.69835454", "0.6983323", "0.69826204", "0.69774604", "0.6974627", "0.6966602", "0.6964143", "0.69635296", "0.6957544", "0.69529504", "0.6944001", "0.69319195", "0.6924361", "0.6923085", "0.69168925", "0.6915167", "0.6913583", "0.6907669", "0.69023997", "0.6900626", "0.68933105", "0.6889483", "0.68867356", "0.68748397", "0.6872061", "0.6863531", "0.68608147", "0.68607044", "0.68481046", "0.68473125", "0.6840387", "0.68389934", "0.68385", "0.6833206", "0.6830495", "0.682772", "0.68180215", "0.6816533", "0.6812877", "0.6809421", "0.68090737", "0.6807834", "0.68065935", "0.6802838", "0.679302", "0.67928886", "0.6791662", "0.6791602", "0.6791073" ]
0.6841012
81
reset the timer to start counting time from the beginning
function resetTimer() { stopTimer(); timeStart = true; time = 0; displayTimer(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "resetTimer() {\n this.timeSelected = 0;\n this.completeElapsed = 0;\n this.complete = false;\n }", "reset() {\n this.stop();\n $(this._timerElemjQuery).text(\"00\");\n this._start = null;\n this._duration = 0;\n }", "reset() {\n this.stop();\n $(this._timerElemjQuery).text(\"00\");\n this._start = null;\n this._duration = 0;\n }", "function resetTimer() {\n stepCount = 0;\n startTime = (new Date()).getTime();\n}", "function resetTimer(){\n\n time = 31;\n }", "resetTimer() {\n clearInterval(this._timer);\n this._seconds = 0;\n this._setTimerContext();\n this.startTimer();\n }", "function resetTime () {\nstopClock();\ntimerOff = true;\ntime = 0;\ncountTime();\n}", "function reset(){\n clearTimeout(stopper);\n stopper = setInterval(timer, 10000);\n }", "function resetTimer() {\r\n clearInterval(timer.clearTime);\r\n timer.seconds = 0;\r\n timer.minutes = 0;\r\n $(\".timer\").text(\"0:00\");\r\n\r\n timer.clearTime = setInterval(startTimer, 1000);\r\n}", "function reset() {\n setSeconds(duration);\n setRunning(false);\n }", "function resetTimer(){\n const timerValue = document.querySelector(\".timerCount\");\n time = 0;\n timerValue.textContent = time;\n paused=false;\n //setTimeout(timer,1000);\n}", "reset() {\n this.timer = 500;\n this.interval = 0;\n }", "resetTimer(){\r\n this.timerRunning = false;\r\n this.remainingTime = 1500;\r\n TimerUI.updateTimeDisplay(this.remainingTime);\r\n }", "function startTimer (){\n clear = setInterval(timer, 1000)\n }", "function resetTimer() {\n // set the time value for zero\n $timer.value = 0;\n // set the DOM text for a empty string\n $text.innerHTML = '';\n stopTimer();\n }", "function startTimer() {\n\tif (timerSeconds.innerHTML === '00') {\n\t\tcountUp = setInterval(setTime, 1000); //allows us to call clearInerval on this variable later.\n\t}\n}", "function resetTimer() {\n app.second = 0;\n app.minute = 0;\n app.hour = 0;\n clearInterval(app.interval);\n app.timer.innerHTML = \"0:00\";\n}", "function resetTimer() {\r\n \r\n if(!timerControl) {\r\n initTime = 0;\r\n stopTime = 0;\r\n totalPassedTime = 0;\r\n lapInitialTimer = 0;\r\n stopwatch.innerText = formatTimer(totalPassedTime);\r\n resetLapsHistory();\r\n \r\n // clear local storage\r\n localStorage.clear();\r\n }\r\n}", "function timerReset() {\n clearInterval(timercycle);\n minutes = seconds = 0;\n $(\".timer\").text(\"00:00\");\n timercycle = setInterval(timerUpdate, 1000);\n}", "function reset() {\n started = false;\n count = 0;\n return;\n}", "function resetTimer(){\n clearInterval(tInterval);\n difference = 0;\n}", "reset() {\n this.timer = 5000;\n this.interval = 0;\n }", "function reset() {\n setSeconds(0);\n setIsActive(false);\n }", "function startTimer() {\n // Sets timer\n timer = setInterval(function() {\n timerCount--;\n timerElement.textContent = timerCount;\n if (timerCount === 0) {\n // Clears interval\n clearInterval(timer);\n nextQuestion();\n }\n }, 1000);\n }", "resetTimer() {\n this.stopTimer();\n console.log(\"resetTimer() called, timer instance restarts from 0.\");\n this.mElapsedTime = 0;\n this.notifyTimerObservers(this.mElapsedTime);\n const handler = function () {\n this.mElapsedTime++;\n this.notifyTimerObservers(this.mElapsedTime);\n }\n this.mElapsedTime = 0;\n mTimerIntervalId = window.setInterval(handler.bind(this), 1000);\n }", "function clearTimer() {\n stopTimer();\n seconds = 0; \n minutes = 0;\n timerStatus = false;\n let resetTime = document.querySelector('.timer');\n resetTime.innerHTML = '00:00';\n }", "function resetTimer() {\n $(\"#timer\").html = '00:00';\n stoptime = true;\n sec = 0;\n min = 0;\n}", "reset() {\n\t\tthis.stop();\n\n\t\tthis.ticks = 0;\n\t\tthis.interval = 0;\n\t\tthis.node.innerText = \"00:00:00\";\n\t}", "function resetTimer() {\n clearInterval(interval);\n THETIMER.innerHTML = \"0\";\n timer = 0;\n timerRunning = false;\n}", "reset() {\n this.running = false;\n window.cancelAnimationFrame(this.frameReq);\n clearTimeout(this.timeout);\n this.els.seconds.textContent = this.duration / 1000;\n this.els.ticker.style.height = null;\n this.els.definition.textContent = ''; \n this.els.rhymes.textContent = ''; \n this.element.classList.remove('countdown--ended');\n }", "function setupTimer() {\n timeCount = setInterval(function () {\n timer--;\n var timeReset = timeElement.textContent = \"Time:\" + \" \" + timer;\n timer = timer;\n if (timer <= 0) { \n clearInterval(timeCount);\n \n timeElement.textContent = timeReset;\n \n }\n }, 1000)\n}", "function reset() {\n clearInterval(interval);\n able_start_button();\n able_stop_button();\n $.post(\n '/server/index.php',\n { action : 'timer_reset' }\n );\n sedonds = 0;\n ss.html('00');\n mm.html('00');\n hh.html('00');\n }", "function startTimer() {\n currentTime = 0;\n timeoutStore = setInterval(updateTimer, timeIncrementInMs);\n }", "function reset() {\n if (currentTimer == \"Session\") {\n sessionSeconds = tempoarySessionSeconds;\n seconds_left = sessionSeconds;\n } else if (currentTimer == \"Long Break\") {\n longBreakSeconds = tempoaryLongBreakSeconds;\n seconds_left = longBreakSeconds;\n } else {\n shortBreakSeconds = tempoaryShortBreakSeconds;\n seconds_left = shortBreakSeconds;\n }\n seconds_left += 1;\n clearInterval(interval);\n intervalManager(true, doTheInterval); // for setInterval\n\n\n}", "function reset(){\n window.clearInterval(timer)\n count = 0; // reinicia desde 0 esta fuera del contador principal \n chronometre.innerHTML = count; \n}", "function resetHandler() {\n count = 0,\n minutes = 0,\n seconds = 0,\n mseconds = 0;\n }", "function reset() {\n\tstarted = false; count = 0;\n\treturn;\n}", "function resetTimer(){\r\n clearInterval(timeInterval);\r\n playBtn.style.display='block';\r\n pauseBtn.style.display='none';\r\n clear(timeFace, '00:00:00');\r\n elapsedTime = 0;\r\n}", "function resetTimer() {\n\tclearTimeout(timer);\n\tdocument.querySelector('.timer').innerText = secondsElapsed;\n}", "function stp() {\n clearInterval(timerId); //reset and stop all timer\n for_count.innerHTML = \"00:00:00\";//output of clicking button clear\n for_msec.innerHTML = \"0\"; // output of clicking button clear\n go = false; // to start counting from zero\n count = 0; //reset counter\n start.removeAttribute('value');\n start.setAttribute('value', 'start');\n}", "function resetTimer() {\n clearInterval(liveTimer);\n }", "function reset(){\n setTimeout(get_count,checkInterval)\n }", "function reset () {\n stopTimerAndResetCounters();\n setParamsAndStartTimer(currentParams);\n dispatchEvent('reset', eventData);\n }", "function setTimer() {\n counter = 11;\n clearInterval(timer);\n timer = setInterval (countDown, 1000);\n }", "function reset() {\n time = 30;\n // DONE: Change the \"display\" div to \"00:00.\"\n $(\".timer\").text(\"00:00\");\n }", "function reset (){\n \n clearInterval(interval); // making sure there is no interval running in the background\n interval = null; // clear resource\n timer=[0,0,0,0];\n timerRunning=false; //allows us to start timer again\n textBox.value=\"\";\n theTimer.innerHTML = \"00:00:00\";\n textBoder.style.borderColor = \"gray\";\n \n \n \n }", "reset() {\n this.elapsedTime = 0;\n }", "resetTimer() {\n // reset to initial state\n this.toggleButton.classList.remove(`running`);\n this.toggleButton.classList.remove(`paused`);\n this.toggleButton.classList.add(`initial-state`);\n\n // reset time variables\n this.startTime = 0;\n this.timeElapsed = 0;\n this.pausedTime = 0;\n this.unpausedTime = 0;\n this.pauseIncrement = 0;\n this.totalPausedTimeArray.length = 0;\n this.totalPausedTime = 0;\n this.seconds = 0;\n this.minutes = 0;\n\n // reset ui content\n this.toggleButton.textContent = `Start`;\n this.content = `0:00.00`;\n }", "function resetTimer(){\n clearInterval(timerInterval);\n timerInterval = null;\n startButton.attr('disabled', false);\n minutes.text('00');\n seconds.text('08');\n itsTimeFor.text('Time to do some work!');\n }", "function resetTimer () {\n timerRunning = false;\n clearInterval(clockInterval);\n clearInterval(wpmInterval);\n}", "function resetTimer() {\n if (timer_is_on) {\n clearTimeout(timer);\n timer_is_on = false;\n }\n}", "resetTimer_() {\n clearTimeout(this.timer);\n this.timer = 0;\n }", "function reset() {\n timerDone = false;\n newPoints.textContent = 0;\n}", "function stopwatchReset() {\r\n if (stopwatchStatus === 'started' || stopwatchStatus === 'paused') {\r\n window.clearInterval(interval)\r\n seconds = 0\r\n minutes = 0\r\n hours = 0\r\n\r\n document.querySelector('#counter').innerHTML = '00:00:00'\r\n stopwatchStatus = 'paused'\r\n }\r\n}", "function startTimer() {\n timer = setInterval(decrementTimer, 1000);\n remainingTime = 61;\n }", "function resetTimer() {\r\n stopTimer();\r\n resetUI();\r\n timerTime = 0;\r\n seconds.innerText = '00';\r\n minutes.innerText = '00';\r\n}", "function resetTimer() {\n inactiveTime = 0;\n}", "function resetTimer(){\n clearInterval(interval);\n intervalTimer();\n}", "function reset() {\n time = 120;\n gameRun = false;\n }", "function countDownStart() {\n if (timer == 0) {\n that.gameLoop = setInterval(that.update, interval);\n that.status = State.RUN;\n }\n else {\n drawElements();\n that.gameArea.paintTimer(that.contex, timer);\n timer--;\n setTimeout(countDownStart, 1500);\n }\n \n }", "function reset_start(){\n timer = Date.now() + 50000;\n playing = true;\n score = 0;\n menu.addClass(\"hidden\");\n moles.forEach(mole => {\n mole.position.y = -6;\n mole.nextEvent = getStartUpTime();\n mole.nextDown = null;\n });\n updateScore();\n run();\n}", "function resetTimer() {\n timeLeft = 15;\n $(\"#timer\").html(\"<h2>Time Left: \" + timeLeft + \"</h2>\");\n countDown();\n }", "function resetTimers() {\n startTime = new Date;\n startTime.setHours(0);\n startTime.setMinutes(0);\n startTime.setSeconds(0);\n startTime.setMilliseconds(0);\n \n stopTime = new Date;\n stopTime.setHours(config.timer.hour);\n stopTime.setMinutes(config.timer.minute);\n stopTime.setSeconds(0);\n stopTime.setMilliseconds(0);\n }", "function clearTimer() {\n clearInterval(currentTime);\n $('.current-time').html('00:00');\n $('.current-song').html('Stopped');\n elapsedSeconds = 0;\n }", "function clearTimer() {\n timer_p.textContent = \"00:00:00\";\n seconds = 0; minutes = 0; hours = 0;\n}", "function resetTimer () {\n window.clearInterval(timerIntervalId);\n timerIntervalId = null;\n window.clearInterval(pageTitleIntervallId);\n pageTitleIntervallId = null;\n timerStartFinishTimestamp = null;\n timerPauseTimestamp = null;\n timeobject = {\n hours: '00',\n minutes: '00',\n seconds: '00',\n milliseconds: '00'\n };\n printTimedisplayFromTimestamp(0);\n startPauseButton.innerHTML = 'Start';\n if (getActiveMode() == 'countdown') {\n startPauseButton.setAttribute('onclick', 'startCountdown();');\n dialpad.classList.remove('hide');\n updatePageTitle('Countdown');\n } else if (getActiveMode() == 'stopwatch') {\n startPauseButton.setAttribute('onclick', 'startStopwatch();');\n lapContainer.classList.add('hide');\n updatePageTitle('Stopwatch');\n lapLog.innerHTML = \"\";\n };\n}", "function resetTimer() {\n timeLeft = 10;\n}", "function timer() {\r\n count ++;\r\n if(count === 31){ //restart Game at the 31st second\r\n context.clearRect(0, 0, canvas.width, canvas.height);\r\n end_screen();\r\n clearInterval(startCounterIntv);\r\n gameStarted = false;\r\n }\r\n }", "function resetTimer() {\n clearInterval(timerInterval);\n timePassed = 0;\n timeLeft = TIME_LIMIT;\n document.getElementById(\"base-timer-label\").innerHTML = formatTime(TIME_LIMIT);\n}", "function countDown() {\n counter--;\n $(\"#time\").html(\"Timer: \" + counter);\n\n if (counter === 0) {\n timeReset();\n \n \n\n\n }\n}", "reset() {\n this.interval = 1000;\n }", "function reset() {\n clearInterval(myCounter);\n $(\".label\").html(getMessage());\n if (isSession) {\n color = \"#5cb85c\";\n totalTime = $(\"#session\").children(\".value\").html() * 60;\n } else {\n color = \"red\";\n totalTime = $(\"#break\").children(\".value\").html() * 60;\n }\n $(\".timer\").css({\n \"background-color\": color,\n \"border\": \"1px solid \" + color\n });\n count = totalTime;\n timeRemaining = totalTime;\n updateTimer(totalTime);\n updatePie(0);\n}", "_clearTimer() {\n\t\tconst timer = this.get('_timer');\n\n\t\tif (timer) {\n\t\t\tcancel(timer);\n\n\t\t\tthis.set('_timer');\n\t\t}\n\n\t\tthis.set('_nextDelay');\n\t\tthis.set('_times', 0);\n\t\tthis.set('_timestamp');\n\t}", "function startTimer() {\n status = 1;\n timer();\n }", "function startTimer() {\n if (!timerFlag) {\n timerInterval = setInterval(decrement, 1000);\n }\n }", "function startTimer() {\n if (!timerFlag) {\n timerInterval = setInterval(decrement, 1000);\n }\n }", "function timer(){\n countStartGame -= 1;\n console.log(countStartGame);\n if (countStartGame === 0){\n console.log (\"time's up\");\n //need to clear interval - add stop\n }\n}", "function resetTimer() {\n window.clearInterval(intervalId);\n time = 15;\n $(\".timer\").append(time);\n intervalId = window.setInterval(onTimeChange, 1000);\n}", "function reset() {\n // Stops the clock\n clearInterval(timerInterval);\n\n // Resets the timeRemaining\n timeRemaining = questions.length * 15;\n\n // Sets the timer\n timer.text(timeRemaining);\n\n // Resets the questionIndex\n questionIndex = -1;\n }", "function resetTimer () {\n if (isMarch == true) {\n clearInterval(control);\n isMarch = false;\n }\n acumularTime = 0;\n timer.innerHTML = \"00 : 00 : 00\";\n}", "function slideResetTimer()\n{\n\ttimer_start = timer_elapsed;\n\tupdateTimer();\n}", "function startTimer() {\n totalSeconds = quizObj.length * 10;\n clearInterval(interval); \n setTime();\n}", "function resetTimer(){\n currentTime = startingTime;\n \n \n if(statusStart){\n timerFunc(currentTime);\n }\n else{\n displayTimeFormat(currentTime);\n }\n}", "reset() {\n this.setState({\n count: 0,\n milliseconds: 0,\n seconds: 0,\n minutes: 0,\n });\n }", "function resetIt() {\n clearInterval(timeInterval);\n clearInterval(timeIntervalBreak);\n timerLength = 25;\n breakLength = 5;\n msConvert = timerLength * 60000;\n msConvertBreak = breakLength * 60000;\n $(\".timer-length\").text(timerLength);\n $(\".break-length\").text(breakLength);\n $(\".countdown\").text(\"25:00\");\n $( \"#start-stop\" ).removeClass( \"stop\" ).addClass( \"start\" );\n $(\"#start-stop\").text(\"start\");\n $(\"#start-stop-cd\").removeClass(\"stop-countdown\");\n startStop = false;\n $(\".break-countdown\").hide();\n $(\".start-countdown\").show();\n $(\".minus2\").show();\n $(\".plus2\").show();\n }", "function startTimer() {\n clockRunning = true;\n\n // Reset clock\n clearInterval(countdownTimer);\n countdownTimer = setInterval(decrement, 1000);\n seconds = 20;\n timer.html(seconds);\n }", "function reset(){\n timerStarted = false;\n sessionInProgress = true;\n minutes = sessionMinutes;\n seconds = sessionSeconds;\n document.getElementById(\"start-button\").innerHTML = \"Start\";\n writeTime();\n \n}", "function reset() {\n document.querySelector(\".infinity-type-area\").disabled = true;\n document.querySelector(\".start\").disabled = false;\n document.querySelector(\".start\").style.backgroundColor =\n \"var(--primary-color)\";\n document.querySelector(\".start\").style.cursor = \"pointer\";\n document.querySelector(\".infinity-type-area\").style.borderColor = \"#A1A1AA\";\n clearInterval(clocking);\n document.querySelector(\".infinity-min\").innerText = \"00\";\n document.querySelector(\".infinity-sec\").innerText = \"00\";\n min = 0;\n sec = 0;\n document.querySelector(\".infinity-type-area\").value = \"\";\n document.querySelector(\"#timer-wpm-inf\").innerText = \"0\";\n document.querySelector(\"#timer-cpm-inf\").innerText = \"0\";\n document.querySelector(\"#timer-accuracy-inf\").innerText = \"0\";\n document.querySelector(\".infinity-user-type\").innerText = samples[random];\n}", "function resetClockAndTime() {\n stopTimer();\n clockOff = true;\n hour = 0;\n minutes = 0;\n seconds = 0;\n displayTime();\n}", "function Timer() {\n\tthis.startTime = 0; // the time that this timer was started\n\t\n\tthis.Reset(); // initially reset our timer\n}", "function reset() {\n\t$win = true;\n\t$last = 'hi';\n\t$i = 0;\n\tcurrent_val = reset_current_val;\n\t$seq = 0;\n\t$t_win = 0;\n\t$t_los = 0;\n\t$seq_count = 0;\n\tif($interval != null)\n\tclearInterval($interval);\n}", "function resetTimer() {\n if( cancelTimer ) {\n cancelTimer();\n cancelTimer = null;\n }\n if( start && Date.now() - start > maxWait ) {\n if(!runScheduledForNextTick){\n runScheduledForNextTick = true;\n utils.compile(runNow);\n }\n }\n else {\n if( !start ) { start = Date.now(); }\n cancelTimer = utils.wait(runNow, wait);\n }\n }", "function resetTimer() {\n if( cancelTimer ) {\n cancelTimer();\n cancelTimer = null;\n }\n if( start && Date.now() - start > maxWait ) {\n if(!runScheduledForNextTick){\n runScheduledForNextTick = true;\n utils.compile(runNow);\n }\n }\n else {\n if( !start ) { start = Date.now(); }\n cancelTimer = utils.wait(runNow, wait);\n }\n }", "function startTimer(){\n timeRemain = setInterval(timeCount, 1000); \n}", "function startTimer() {\n \n intervalId = setInterval(function () { \n timerCnt--;\n if (timerCnt >= 0) {\n $(\"#counter\").text(timerCnt);\n } else {\n clearInterval(intervalId);\n missedTimer();\n }\n }, 1000);\n\n } //ends startTimer", "function timerStart()\n {\n clearInterval(intervalId);\n intervalId = setInterval(decrement, 1000);\n }", "function resetTimer(timer) {\n if (timer) {\n clearInterval(timer);\n }\n}", "function reset() {\n clearInterval(timeId);\n timeId = true;\n let newTime = parseInt(document.getElementsByClassName(\"time active\")[0].textContent) * 60;\n document.querySelector(\"#timer\").textContent = secondToStringConversion(newTime);\n let currentStatus = document.querySelector(\".inProgress\");\n currentStatus.style.cssText = 'background-color: rgb(214, 214, 214)';\n}", "function startCountdown() {\r\n\r\n stopCountdown();\r\n\r\n resumeTimer = Object.assign({}, timers);\r\n resumeTimer.secs = toSecs(resumeTimer.sessionTime);\r\n\r\n setCountDown(getMins(resumeTimer.secs), getSecs(resumeTimer.secs));\r\n countdown(resumeTimer);\r\n}", "function timeReset() {\n clearInterval(timer);\n lost++;\n nextQuestion();\n}" ]
[ "0.8165589", "0.8099327", "0.8099327", "0.7967145", "0.7961562", "0.79461545", "0.79386926", "0.7879661", "0.78262764", "0.7717204", "0.7717105", "0.7710925", "0.7660638", "0.76589066", "0.76543236", "0.75742245", "0.75660044", "0.7560766", "0.75526357", "0.7541143", "0.7527697", "0.7525762", "0.74975026", "0.7465004", "0.7430475", "0.74106747", "0.7396433", "0.7392651", "0.7392095", "0.737543", "0.7371196", "0.73583025", "0.734348", "0.73252296", "0.73006535", "0.7299806", "0.72956777", "0.7284982", "0.7276443", "0.72673965", "0.72517496", "0.7245714", "0.723092", "0.72273326", "0.72226226", "0.7222177", "0.72193086", "0.72085065", "0.71891296", "0.7175886", "0.71744823", "0.71714383", "0.7158641", "0.71561515", "0.71450657", "0.71394044", "0.7134898", "0.7131424", "0.7129617", "0.71233404", "0.71208346", "0.71117514", "0.71021223", "0.71014583", "0.7091488", "0.7066499", "0.7066183", "0.70655316", "0.7062227", "0.7056303", "0.705122", "0.7034764", "0.7032661", "0.70267326", "0.7012797", "0.7012797", "0.7008848", "0.7007078", "0.69856733", "0.6970872", "0.69672346", "0.69574296", "0.6954523", "0.6952182", "0.6949634", "0.6941793", "0.6936157", "0.692643", "0.6919971", "0.691198", "0.689338", "0.6889204", "0.6889204", "0.688768", "0.6887369", "0.68839544", "0.68813336", "0.68716544", "0.686438", "0.68508124" ]
0.79940706
3
toggle modal on or off
function toggleModal() { $('.modal-results').toggleClass('show-modal'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function toggle() {\r\n setModal(!modal)\r\n }", "toggleModal () {\n\t\tthis.model.toggleModalState();\n\t\tthis.view.toggleModal( this.model.isModalOpen )\n\t}", "toggle() {\n this.setState({\n modal: !this.state.modal\n });\n }", "toggle() {\n this.setState({\n modal: !this.state.modal\n });\n }", "toggle() {\n this.setState({\n modal: !this.state.modal\n });\n }", "toggle(){\n this.setState({\n modal: !this.state.modal\n });\n }", "toggle() {\n this.setState({ modal: !this.state.modal });\n }", "toggle() {\n this.setState({ showModal : !this.state.showModal });\n }", "toggleModal() {\n\n this.colorChanged = false\n\n if(this.modal.hasAttribute('active')) {\n this.modal.removeAttribute('active') \n }\n else {\n this.modal.setAttribute('active', '')\n }\n }", "function toggleModal() {\n modal.classList.toggle(\"show-modal\");\n }", "toggle() {\n this.setState(prevState => ({\n modal: !prevState.modal\n }));\n }", "toggle() {\n this.setState(prevState => ({\n modal: !prevState.modal\n }));\n }", "function setModal() {\n if ($('#modal').iziModal('getState') == 'closed') {\n $('#modal').iziModal('open');\n }\n}", "handleModalToggle() {\n this.setState({\n showModal: !this.state.showModal\n });\n }", "function attShowModal() {\n setShowModal(!showModal);\n }", "handleToggleModal() {\n this.setState({ showModal: !this.state.showModal });\n }", "function toggleModal(modal) {\n var state = modal.getAttribute('data-state');\n if (state === 'open') {\n modal.setAttribute('data-state', 'closed');\n } else {\n modal.setAttribute('data-state', 'open');\n }\n }", "toggleModal() {\n this.setState({displayModal: !this.state.displayModal});\n }", "showModal() {\n this.isModalOpen = true;\n }", "toggleModal() {\n if(this.modal.hasAttribute('active')) {\n this.modal.removeAttribute('active') \n }\n else {\n this.modal.setAttribute('active', '')\n }\n }", "toggleModal() {\n if(this.modal.hasAttribute('active')) {\n this.modal.removeAttribute('active') \n }\n else {\n this.modal.setAttribute('active', '')\n }\n }", "toggleSettingsModal() {\n this.setState({\n showModal: !this.state.showModal\n })\n }", "toggle() {\n this.setState(prevState => ({\n modal: !prevState.modal,\n }));\n }", "function toggleModalOn(){\n var modalWindow = document.querySelector('.modal')\n modalWindow.style.display = 'inherit'\n modalMovesStats();\n modalStarsStats();\n modalTimerStats();\n }", "toggle() {\n this.setState(prevState => ({\n modal: !prevState.modal\n }));\n }", "toggle() {\n this.setState(prevState => ({\n modal: !prevState.modal\n }));\n }", "function toggleModal() {\n\n let form = document.getElementById('editModal');\n if (form.style.display === 'none') form.style.display = 'block';\n else form.style.display = 'none';\n}", "function toggleModalOff(){\n var modalWindow = document.querySelector('.modal')\n modalWindow.style.display = 'none';\n }", "toggleModal() {\n this.setState({\n isModalOpen: !this.state.isModalOpen\n });\n }", "setModalShowOrHide() {\r\n this.setState({\r\n showModal: !this.state.showModal\r\n })\r\n }", "function modalOnOff() {\n btnModal\n .classList\n .toggle(\"hide\") \n \n todoList\n .classList\n .toggle(\"hide\")\n}", "function show_modal(modal) {\n modal.classList.toggle('inactive');\n}", "toggleModal1() {\n this.setState({\n modal1: !this.state.modal1\n });\n }", "openModal() { \n this.bShowModal = true;\n }", "function openModal() {\n setQuesFlag(false);\n setIsModalVisible(true); \n }", "toggleModalGeneralConditions(){\n this.showModalConfirmCart = !this.showModalConfirmCart;\n }", "toggleModal({commit}, show) {\n commit(\"toggleModal\", show);\n }", "function loginSignUpModalToggle(bool) {\n if(bool){\n $('#signUpModal')\n .on('shown.bs.modal', function () {\n $('#email').trigger('focus');\n })\n .modal('show');\n $('#loginModal').modal('hide');\n }\n else {\n $('#loginModal')\n .on('shown.bs.modal', function () {\n $('#username').trigger('focus');\n })\n .modal('show');\n $('#signUpModal').modal('hide');\n }\n}", "toggleModal() {\n this.setState(state => ({ showModal: !state.showModal }));\n }", "function toggleModal() {\n $('body').classList.toggle('modalOpen');\n //Force video to stop playing when modal is closed - we could do this in a nicer way if we used the youtube API.\n $('modalTrailer').setAttribute('src', '');\n //Inverse modalHiddenState\n modalHiddenState = !modalHiddenState;\n $('modalTrailer').setAttribute('aria-hidden', modalHiddenState);\n}", "function openModal() {\n setIsModalOpen((isModalOpen) => !isModalOpen);\n }", "togglePopup() {\n const { modal } = this.state;\n\n if (modal) {\n this.setState(({\n modal: !modal\n }));\n } else {\n this.setState(({\n modal: !modal\n }));\n }\n }", "mostrarModal() {\n this.mostrarmodal = !this.mostrarmodal\n \n }", "function toggleModal() {\n modal.classList.toggle(\"show-modal\");\n}", "function toggleModal() {\n modal.classList.toggle(\"show-modal\");\n}", "toggleModalLeaveAMessage(){\n this.showModalLeaveMsg = !this.showModalLeaveMsg;\n }", "function onShowBsModal() {\n isModalInTransitionToShow = true;\n isModalVisible = true;\n }", "toggle() {\n return (\n this.modalPanel.isVisible() ?\n this.quit() :\n this.warn()\n );\n }", "changeModal() {\n this.setState({\n openModal: !this.state.openModal\n });\n }", "showModal() {\n this.open = true;\n }", "function togglePrefect() {\n // the long version of the toggle:\n /* if (student.prefect === true) {\n student.prefect = false;\n } else {\n student.prefect = true;\n } */\n // the short version of the code above\n activeModalStudent.prefect = !activeModalStudent.prefect;\n // refresh the modal\n openModal();\n}", "function showModal() {\n if (this.getAttribute(\"id\") === \"settings-btn\") {\n document.getElementById('settings-modal').style.display = 'block';\n }\n if (this.getAttribute(\"id\") === \"how-btn\") {\n document.getElementById('how-modal').style.display = 'block';\n }\n}", "function openModal() {\n setIsOpen(true);\n }", "function toggleModal() {\n if (isModalDisplayed) {\n // set as display None and update the variable\n modal.style.display = \"none\"\n } else {\n // set display to initial\n modal.style.display = \"flex\" //display modal\n const modalTimeElement = document.getElementById('timeAnchor')\n const modalScoreElement = document.getElementById('finalScore')\n\n modalTimeElement.innerHTML = prettyPrintTime()\n modalScoreElement.innerHTML = cardsWon.length\n }\n isModalDisplayed = !isModalDisplayed //update isModalDisplayed variable\n\n\n }", "function toggleModalOff() {\n const modal = document.querySelector('.modal-background');\n modal.classList.add('hide');\n }", "function changeModal(id){\n\t\tif(!$(id).is(':visible')){\n\t\t\t$('[data-role=\"modal_page\"]').hide();\n\t\t\t$(id).fadeIn();\n\t\t}\t\t\n\t}", "function changeVisibleModal(bool) {\n props.visibleModalChange(bool)\n \n }", "activateModal() {\n\t\tdocument.getElementById('logout').style.display = 'none';\n\t\tdocument.querySelector('#login-modal').style.display = 'block';\n\t}", "toggle_edit_modal() {\n this.clearState()\n var value = this.state.edit_modal\n this.setState({ edit_modal: !value })\n }", "toggleSignIn(state) {\n state.modalsStatus.signIn = !state.modalsStatus.signIn;\n }", "toggle() {\n this.setState({\n modal: !this.state.modal,\n description: \"\",\n time: \"10:30\",\n title: \"\",\n blocking: false,\n selectedUsers: this.props.currentUser.uid\n });\n }", "onToggleModal() {\n this.setState({\n isDone: !this.state.isDone\n })\n }", "toggleCreateEvent() {\n this.toggleModal(true, createEventComponent);\n }", "toggle() {\n // console.log( \",this.state.sRefreshSokcet = \",this.state.RefreshSokcet);\n this.setState(prevState => ({\n modal: !prevState.modal, \n }));\n }", "alteraModal(visibilidade){\n this.setState({modalVisible: visibilidade});\n }", "toggle() {\n if (this.isActive) {\n this.close();\n } else {\n this.open();\n }\n }", "toggle_label_ready_modal() {\n var value = this.state.label_ready_modal\n this.setState({ label_ready_modal: !value })\n }", "function showModal()\n{\n\tdocument.getElementById('modal-backdrop').classList.toggle('hidden');\n\tif(document.getElementById('leave-comment-modal')) {\n\t\tdocument.getElementById('leave-comment-modal').classList.toggle('hidden');\n\t}\n\tif(document.getElementById('create-location-modal')) {\n\t\tdocument.getElementById('create-location-modal').classList.toggle('hidden');\n\t}\n}", "function openModal() {\n setOpen(true);\n }", "function toggleModal() {\n\tconst modal = document.querySelector('.modal__background');\n\tmodal.classList.toggle('hide');\n}", "toggle() {\n this.setState({\n addEmployeeModal: !this.state.addEmployeeModal\n })\n }", "function openModal() {\r\n document.getElementById(\"modal\").classList.toggle(\"modal-active\");\r\n}", "function toggleModal(){\n // Get the modal dialog from this image div's data\n let $dialog = $(this).data('modal');\n // Open it\n $dialog.dialog('open');\n} // end of toggleModal", "toggleAddAlert(){\n this.setState({\n modal: !this.state.modal\n });\n }", "function setModal() {\n $('.overlay').fadeIn('slow');\n $('.modal').slideDown('slow');\n }", "toggleEditProductModal() {\n this.setState({\n editProductModal: ! this.state.editProductModal\n });\n }", "function toggleModal() {\n const modal = document.querySelector('.modal');\n modal.classList.toggle('hide');\n}", "function toggleModal(selector)\n{\n var that = $(selector);\n if( that.hasClass('shown') )\n {\n $('html').removeClass('stop-scrolling')\n that.fadeOut(500, function(){that.toggleClass('shown')} );\n\n }else{\n $('html').addClass('stop-scrolling')\n that.toggleClass('shown').fadeIn(500);\n }\n}", "function toggleModal() {\n\tconst modal = document.querySelector('.modal_background');\n\tmodal.classList.toggle('hide');\n}", "function toggleModalOn() {\n const modal = document.querySelector('.modal-background');\n modal.classList.remove('hide');\n }", "function modalOpen() {\n modal.style.display = 'block';\n}", "function toggleModal(e) {\n if (modal.style.display === '') {\n modal.style.display = 'block';\n document.body.style.overflowY = 'hidden';\n } else if (\n e.target.className === 'projects__modal' ||\n e.target.className === 'projects__modal-btn'\n ) {\n modal.style.display = '';\n document.body.style.overflowY = 'visible';\n }\n}", "function btnEmployeeSign() {\n $(\"#modalMatch\").modal(\"toggle\");\n }", "toggle () {\n if (this.closed) {\n this.open();\n } else {\n if (this.state === 'initial') {\n this.showChooseOrSignIn();\n } else {\n this.close();\n }\n }\n }", "eventToggleModal(event) {\n event.preventDefault();\n this.toggleModal();\n }", "toggle () {\n this.opened = !this.opened;\n }", "toggle () {\n this.opened = !this.opened;\n }", "function openModal() { \n modal.style.display = 'block';\n }", "function toggleWindow() {\n $(\"#alertWindow\").modal(\"toggle\");\n }", "function openModal() {\n modal.style.display = 'block';\n }", "function openModal() {\n modal.style.display = 'block';\n }", "toggle()\n {\n if (this.showing)\n {\n this.close();\n }\n else\n {\n this.open();\n }\n }", "closeModal(){\n this.showModal = false\n }", "function openModal(){\r\n modal.style.display = 'block';\r\n }", "function openModal(e) {\n\tmodal.style.display = 'block'\n}", "handleToggleLoginModal() {\n console.log(\"Toggling Modal State\");\n this.setState(state => ({\n modalToggle: !state.modalToggle\n }));\n }", "function toggleLoginRegister() {\n $(\".loginModal\").toggleClass(\"showLoginRegister\");\n $(\".registerModal\").toggleClass(\"showLoginRegister\");\n }", "toggleModal() {\n if (this.modal == true) {\n customerService.getCustomerSearch(result => {\n this.temporaryOptions = [];\n result.map(e => {\n this.temporaryOptions.push({ value: e.c_id, label: e.fullname });\n });\n this.searchbarOptions = this.temporaryOptions;\n });\n }\n this.modal ? (this.modal = false) : (this.modal = true);\n }", "function toggleModal(event) {\n modal.classList.toggle(\"show_modal\");\n body.classList.toggle(\"hide_scroll\")\n}", "function openModal () {\n modal.style.display = 'block';\n }" ]
[ "0.8614924", "0.78581", "0.7577401", "0.7509253", "0.7509253", "0.7470424", "0.7466745", "0.74192214", "0.74085176", "0.73702323", "0.732111", "0.732111", "0.72533655", "0.7232697", "0.72234124", "0.72224724", "0.7196147", "0.7166964", "0.7128359", "0.7122359", "0.7122359", "0.71209407", "0.7114154", "0.70861816", "0.7083215", "0.7083215", "0.7075001", "0.7073273", "0.70612484", "0.7049742", "0.7045869", "0.7041464", "0.7028636", "0.69949245", "0.69888294", "0.6987859", "0.69802934", "0.697765", "0.6955684", "0.69525063", "0.69508845", "0.6944405", "0.6885376", "0.6836545", "0.6836545", "0.68189836", "0.68005776", "0.6767248", "0.6765436", "0.6740515", "0.6732685", "0.67201746", "0.67177886", "0.6705726", "0.6694494", "0.66823995", "0.6682331", "0.6676373", "0.6672759", "0.66677606", "0.66660476", "0.6638416", "0.66287506", "0.6626588", "0.66094726", "0.66046166", "0.65909785", "0.65742654", "0.65675807", "0.65663356", "0.65556717", "0.6550073", "0.6549547", "0.65460676", "0.65380645", "0.6534039", "0.65340364", "0.65130043", "0.65064937", "0.649835", "0.6494711", "0.6484065", "0.64828956", "0.6469633", "0.64643294", "0.6456022", "0.6456022", "0.6455306", "0.64538", "0.6451478", "0.6451478", "0.6450842", "0.64503276", "0.644887", "0.6446111", "0.6435962", "0.6435631", "0.64303833", "0.64288026", "0.6420525" ]
0.7193635
17
update modal with results
function updateModal() { let newTime = $('.timer').text(); let newStars = updateStar(); $('.modal-time').text(`Time: ${newTime}`); $('.modal-moves').text(`Moves: ${moveCount}`); $('.modal-stars').text(`Stars: ${newStars}`); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function view_update_modal(id_table, url) {\n $(`#${id_table} tbody`).on('click', '.btn-info', function() {\n const id = $(this).data('id');\n const response = get(`${url}${id}`);\n response.then((res) => {\n load_preloader_container(res.form.id, 10);\n $('#modal_update').modal('show');\n set_data_in_form(res.form.id, res.data);\n stop_preloader(res.form.id, 1000);\n update_data(res.form.id, res.form.rules, res.form.confirm, res.form.url);\n }).catch((err) => {\n toastr.error(err.message);\n });\n });\n}", "function successUpdate() {\n updateForm.style.display = \"none\";\n updateSuccessView.style.display = \"block\";\n setTimeout(closeUpdateModal, 1500);\n }", "function updateVote(result, status) {\n console.log(result);\n $('p.votes').text(result.voted); // update the current display value\n current_popup.find('p.votes').text(result.voted); // update the saved display value\n}", "function updateModal(e) {\n var articleDoi = $('.schedule-cancel-btn[data-article-id=\"' + schedule.articleId + '\"]').attr('data-article-doi');\n $('.article-cancel-info', '#schedule-modal').html(articleDoi);\n validateForm();\n }", "function upcoming_tours_update_modal(offer_id)\n{\n\t $.post( \n \"upcoming_tours_update_modal.php\",\n { offer_id : offer_id },\n function(data) { \n $('#div_upcoming_tours_update_modal').html(data);\n });\n}", "function displayModal() {\n\t\t\t\t$(\"#user-name\").text(newPerson.name);\n\t\t\t\t$(\"#match-name\").text(matchName);\n\t\t\t\t$(\"#match-img\").attr(\"src\", matchImage);\n\t\t\t\t$(\"#myModal\").modal();\n\t\t\t}", "async function createInvAdminModal() {\n const modal = await modalController.create({\n component: \"inv-admin-modal\",\n cssClass: \"invAdminModal\",\n });\n\n var settings = {\n \"url\": `http://localhost:8080/api/admin/inventory/detail/${storedButtonID}`,\n \"method\": \"GET\",\n \"timeout\": 0,\n };\n \n $.ajax(settings).done(function (response) {\n var dataArray2 = JSON.parse(response);\n console.log(dataArray2);\n\n document.getElementById(\"adminInvDonorName\").innerHTML = dataArray2[0].donor_name + \" | \" + dataArray2[0].donor_id;\n document.getElementById(\"adminInvItemName\").innerHTML = dataArray2[0].item_name + \" | \" + dataArray2[0].item_id;\n document.getElementById(\"adminInvLocation\").innerHTML = dataArray2[0].item_location;\n document.getElementById(\"adminInvRepairFre\").innerHTML = dataArray2[0].repair_frequency;\n document.getElementById(\"adminInvRepairSta\").innerHTML = dataArray2[0].repair_status;\n document.getElementById(\"adminInvRepairType\").innerHTML = dataArray2[0].repair_type;\n document.getElementById(\"adminInvStatus\").innerHTML = dataArray2[0].item_status;\n\n for (var i = 0; i < dataArray2.length; i++){\n document.getElementById(\"adminInvStaHist\").append(dataArray2[i].item_status+\", \");\n document.getElementById(\"adminInvLocHist\").append(dataArray2[i].item_location+\", \");\n document.getElementById(\"adminInvDateHist\").append(dataArray2[i].item_date+\", \");\n \n }\n\n });\n\n \n await modal.present();\n currentModal = modal;\n}", "function update_load_data()\n{\n\t$(function(){\n\t$(\".update_object\").on(\"click\",function(e)\n\t{\n\t\tvar id=$(this).attr(\"update_id\");\n\t\te.preventDefault();\n\t\t$.ajax({\n\t\t\turl:\"member_update_load.php\",\n\t\t\tdata:{id:id},\n\t\t\tmethod:\"POST\",\n\t\t\tsuccess:function(response)\n\t\t\t{\n\t\t\t\t$(\".update_modal_body\").html(response);\n\t\t\t $(\"#UpdateMember\").modal(\"show\");\n\t\t\t}\n\t\t});\n\t})\n\t});\n}", "function updateClientModal() {\n $(\"#clientNameValue\").val(selectedClient.name);\n $(\"#clientCreditValue\").val(selectedClient.credit);\n $(\"#clientLastLessonDateValue\").val(selectedClient.lastLessonDate);\n}", "function updateAboutModal() {\r\n /**\r\n * we fetch the metrics\r\n */\r\n $.ajax({\r\n type: 'GET',\r\n url: 'ajax/fetch_about_modal_metrics.php',\r\n dataType: 'json',\r\n success: function (json) {\r\n $('#span_controller_url').html(json.controller_url);\r\n $('#span_controller_user').html(json.controller_user);\r\n $('#span_controller_version').html(json.controller_version);\r\n $('#span_memory_used').html(json.memory_used);\r\n },\r\n error: function(jqXHR, textStatus, errorThrown) {\r\n console.log(jqXHR);\r\n }\r\n });\r\n}", "function response_in_modal(response) {\n $(\".modal-title\").html(response);\n $(\"#empModal\").modal(\"show\");\n}", "function showModalUpdate(id, autor,fecha,tnovedad,estado,detalle,idTabla,button,fila){\n showModalRegister(id, autor,fecha,tnovedad,estado,detalle,idTabla);\n var $d = $(button).parent(\"td\");\n var Grid_Table = document.getElementById(idTabla); \n $('#Autor').val(Grid_Table.rows[fila].cells[1].textContent);\n $('#selectTnovedad').val(Grid_Table.rows[fila].cells[3].textContent);\n $('#titulonovedad').val(Grid_Table.rows[fila].cells[5].textContent);\n $('#detallenovedad').val(Grid_Table.rows[fila].cells[6].textContent); \n }", "async function presentEditFeedModal( $item, langs_data ) {\n // create the modal with the `modal-page` component\n $doc.trigger('open-modal', [\n await modalController.create({\n component: 'modal-update-feed',\n componentProps: {\n 'langs' : langs_data,\n 'lang' : $item.data('lang'),\n 'id' : $item.data('id'),\n 'url' : $item.data('url'),\n 'title' : $item.find('ion-label h3 span').text(),\n 'allow_duplicates' : $item.data('allow-duplicates'),\n },\n }),\n function() {\n setTimeout(function() {\n $('#feed_title')[0].setFocus();\n }, 500);\n }\n ]);\n }", "addUpdateListener() {\n this.updateBtn.click(() => {\n if (this.text !== $('#modalText').val()) {\n $.ajax({\n type: \"PUT\",\n url: `/api/chirps/${this.id}`,\n data: JSON.stringify({ user: this.author, text: $('#modalText').val() }),\n contentType: 'application/json',\n success: () => {\n console.log(\"successful update, id: \" + '/api/chirps/' + this.id);\n }\n });\n displayAllChirps();\n }\n $('#exampleModalCenter').modal('toggle');\n\n });\n }", "async function createCWInvModal() {\n const modal = await modalController.create({\n component: \"inv-cw-modal\",\n cssClass: \"CWInvModal\",\n });\n\n var settings = {\n \"url\": `http://localhost:8080/api/caseworker/inventory/detail/${storedButtonID}`,\n \"method\": \"GET\",\n \"timeout\": 0,\n };\n \n $.ajax(settings).done(function (response) {\n var dataArray2 = JSON.parse(response);\n console.log(dataArray2);\n\n document.getElementById(\"cwInvDonorName\").innerHTML = dataArray2[0].donor_name + \" | \" + dataArray2[0].donor_id;\n document.getElementById(\"cwInvItemName\").innerHTML = dataArray2[0].item_name + \" | \" + dataArray2[0].item_id;\n document.getElementById(\"cwInvItemLocation\").innerHTML = dataArray2[0].item_location;\n document.getElementById(\"cwInvRepairFre\").innerHTML = dataArray2[0].repair_frequency;\n document.getElementById(\"cwInvRepairSta\").innerHTML = dataArray2[0].repair_status;\n document.getElementById(\"cwInvRepairType\").innerHTML = dataArray2[0].repair_type;\n document.getElementById(\"cwInvItemStatus\").innerHTML = dataArray2[0].item_status;\n\n for (var i = 0; i < dataArray2.length; i++){\n document.getElementById(\"cwInvStaHist\").append(dataArray2[i].item_status+\", \");\n document.getElementById(\"cwInvLocHist\").append(dataArray2[i].item_location+\", \");\n document.getElementById(\"cwInvDateHist\").append(dataArray2[i].item_date+\", \");\n \n }\n\n });\n\n await modal.present();\n currentModal = modal;\n}", "function updateInfo() {\n const updatedInfoModal = document.getElementById('updatedInfoModal');\n\n updatedInfoModal.style.display = \"block\";\n\n $(\".okay\").on(\"click\", function () {\n updatedInfoModal.style.display = \"none\";\n })\n}", "function updateModal(title, body) {\n modal.querySelector(\".modal-title\").innerHTML = title\n modal.querySelector(\".modal-body\").innerHTML = body\n}", "function btnUpdate_click(dep) {\n const title = document.getElementById(\"mdCreateTitle\");\n title.textContent = \"Atualizar curso\";\n\n document.getElementById(\"txtName\").value = dep.name;\n actualId = dep.id;\n $(\"#modalCreate\").modal();\n}", "function successModal(message1,message2) {\n $(\"#modalsave\").hide();\n $(\"#sure .modal-title\").text(message1);\n $(\"#sure .modal-body\").html(message2);\n $(\"#sure\").modal('show');\n $(\"#sure\").modal('handleUpdate'); \n }", "function setUpdateEvent(data){\n\t\tvar theID = '#' + data.doc._rev;\n\t\t$(theID).click(function(){\n\t\t\t$.each(jsonData.rows,function(i){\n\t\t\t\tif(jsonData.rows[i].doc._rev == data.doc._rev){\n\t\t\t\t\tmodal.style.display = \"block\";\n\t\t\t\t\tlocalStorage.setItem(\"currentQuestion\",data.doc._rev);\n\t\t\t\t\tdocument.getElementById('english-question').value=data.doc[\"english-question\"];\n\t\t\t\t\tdocument.getElementById('english-answer').value=data.doc[\"english-answer\"];\n\t\t\t\t\tdocument.getElementById('arabic-question').value=data.doc[\"arabic-question\"];\n\t\t\t\t\tdocument.getElementById('arabic-answer').value=data.doc[\"arabic-answer\"];\n\t\t\t\t\tdocument.getElementById('playing-frequency').value=data.doc[\"playing frequency\"];\n\t\t\t\t\tdocument.getElementById('video-type').value=data.doc[\"video-type\"];\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t})\n\t\t});\n}", "function updateData(nr) {\n let item = users[nr];\n\n $(\".modal-img\").attr(\"src\", `${item.picture.large}`);\n $(\".modal-name\").html(\n `${item.name.title} ${item.name.first} ${item.name.last}`\n );\n $(\".modal-text\")\n .eq(0)\n .html(`${item.email}`);\n $(\".modal-text\")\n .eq(1)\n .html(`${item.location.city}`);\n $(\".modal-text\")\n .eq(2)\n .html(`${item.cell}`);\n $(\".modal-text\")\n .eq(3)\n .html(\n `${item.location.street}, ${item.location.city}, ${item.location.state} ${\n item.location.postcode\n }`\n );\n $(\".modal-text\")\n .eq(4)\n .html(`Birthday: ${item.dob.date.split(\"T\")[0]}`); // Split TS to only get Date\n}", "function updateProfileModal() {\n $.ajax({\n url: _BASEURLJSONSERVER + '/' + supervisorList,\n data: {\n \"id\": empid\n },\n success: function(data) {\n fillAndShowUpdateProfileModal(data,'supervisor');\n },\n error: function() {\n alert('unable to get data from server');\n }\n\n });\n }", "function showEditDialog(row_id) {\n $(\"#ServiceModal h4\").text(\"Edit Service \"+row_id);\n /*\n * Get info about service from server\n * perform an ajax POST\n */\n $.ajax( { \n url: $SCRIPT_ROOT +\"/get_row\",\n contentType: \"application/json; charset=utf-8\",\n method: \"GET\",\n dataType: \"json\",\n data: { \"row_id\": row_id },\n success: function ( json ) {\n if (json.status == 'OK'){\n $.each( json, function( key, val ) {\n // pre-populate the fields\n $('input[name=\"'+key+'\"]').val(val);\n $('textarea[name=\"'+key+'\"]').val(val);\n });\n }\n else{\n alert(json.status);\n }\n },\n error: function ( req, reqStatus, reqObj ) {\n alert(\"ERROR! Server returned error from ajax submit, try again\");\n }\n\n });\n\n $(\"#ServiceModal\").modal(\"show\");\n }", "function updateSuccess(itemsdata) {\n tbl.clear();\n redrawTable(tbl, itemsdata);\n buttonEvents();\n $(\"#editDiv\").hide();\n swal(\"עודכן בהצלחה!\", \"הפעולה בוצעה\", \"success\");\n mode = \"\";\n }", "function showModal() {\n\n $('#myModal').modal(\"show\");\n $(\".modal-title\") .text(data.name)\n $(\".modal-li-1\") .text(\"Accuracy: \" + data.accuracy)\n $(\".modal-li-2\").text(\"PP: \" + data.pp)\n $(\".modal-li-3\").text(\"Power: \" + data.power)\n $(\".modal-li-4\").text(\"Type: \" + data.type.name)\n $(\".modal-li-5\").text(\"Priority: \" + data.priority)\n \n }", "function showLastRunDetails() {\n $('#modal-container').html(last_run_details_template(runResults))\n $('#modal-container').modal()\n}", "function updateView(result) {\n showScheduleButton();\n showResultMessage(result.message);\n loadTasks();\n}", "function updateCallbackOk(result) {\n $(\"#mdlAlert\").modal(\"hide\");\n $(\"#tblAlerts\").bootstrapTable(\"updateRow\", {\n index: TableUtil.getTableIndexById(\"#tblAlerts\", $(\"#txtAlertId\").val()),\n row: {\n Id: $(\"#txtAlertId\").val(),\n Name: $(\"#txtAlertName\").val(),\n Description: $(\"#txtAlertDescription\").val(),\n DueDate: DateUtil.formatDateTime($(\"#txtAlertDueDate\")\n .data(\"DateTimePicker\").date())\n }\n });\n }", "function openModal(data) {\n\n\t//change beginning and end inputs to date objects\n\t// Split timestamp into [ Y, M, D, h, m, s ]\n\tvar d = data[0]['date_debut'].split(/[- :]/);\n\tvar f = data[0]['date_fin'].split(/[- :]/);\n\n\t// Apply each element to the Date function\n\tvar debut = new Date(Date.UTC(d[0], d[1]-1, d[2], d[3], d[4], d[5]));\n\tvar fin = new Date(Date.UTC(f[0], f[1]-1, f[2], f[3], f[4], f[5]));\n\n\t//fill modal with correct data\n\t$('#updateServiceId').val(data[0]['fk_service']);\n\t$('#updatePromoServiceId').val(data[0]['pk_promotion_service']);\n\tdocument.getElementById(\"debut\").valueAsDate = debut;\n\tdocument.getElementById(\"fin\").valueAsDate = fin;\n\t$('#updateCodePromo').val(data[0]['code']);\n\t$('#updatePromoName').val(data[0]['fk_promotion']);\n\t\n\t//change percentage of box based on chosen promotion\n\tvar e = document.getElementById('updatePromoName');\n var promo = e.children[e.selectedIndex];\n var percent = promo.getAttribute(\"data-percent\");\n document.getElementById('updatePromoNb').innerHTML = percent * 100 + \"%\";\n\t\n modal.style.display = \"block\";\n}", "function Editclick(obj) {\n var rowID = $(obj).attr('id');\n $.ajax({\n url: `https://localhost:44397/api/patients/ ${rowID}`,\n type: 'GET',\n success: function (response) {\n $.ajax({\n type: \"GET\",\n url: '/Home/CreateorUpdate',\n cache: false,\n data:response,\n dataType: \"html\",\n success: function (responseText) {\n $('#editor-content-container').html(responseText);\n console.log(responseText);\n $('#editor-container').modal('show');\n }\n });\n },\n });\n}", "function updateResults() {\n const resultLink = $(\"#resultlink\").serialize();\n $.ajax({\n method: \"GET\",\n url: \"/update\",\n data: resultLink,\n dataType: \"json\",\n success: function (result) {\n console.log(\"it was success \", result);\n },\n error: function (err) {\n console.log(\"we are in an error\", err);\n }\n })\n\n }", "function InitUpdateModal(detailUser) {\n $(\"#name\").val(detailUser.name);\n $(\"#phone\").val(detailUser.phone);\n}", "function showModal() {\n\n $('#myModal').modal(\"show\");\n $(\".modal-title\").text(data.name)\n $(\".modal-li-1\").text(\"Generation: \" + data.generation.name)\n $(\".modal-li-2\").text(\"Effect: \" + data.effect_changes[0].effect_entries[1].effect)\n $(\".modal-li-3\").text(\"Chance: \" + data.effect_entries[1].effect)\n $(\".modal-li-4\").text(\"Bonus Effect: \" + data.flavor_text_entries[0].flavor_text)\n }", "function modalCommentary(id)\n{\n $.ajax({\n url: apiCatalogo + 'get',\n type: 'post',\n data:{\n idProducto: id\n },\n datatype: 'json'\n })\n .done(function(response){\n //Se verifica si la respuesta de la API es una cadena JSON, sino se muestra el resultado en consola\n if (isJSONString(response)) {\n const result = JSON.parse(response);\n //Se comprueba si el resultado es satisfactorio para mostrar los valores en el formulario, sino se muestra la excepción\n if (result.status) {\n $('#form-comentario')[0].reset();\n $('#idProducto').val(result.dataset.idProducto); \n M.updateTextFields();\n $('#modalComentario').modal('open');\n } else {\n sweetAlert(2, result.exception, null);\n }\n } else {\n console.log(response);\n }\n })\n .fail(function(jqXHR){\n //Se muestran en consola los posibles errores de la solicitud AJAX\n console.log('Error: ' + jqXHR.status + ' ' + jqXHR.statusText);\n });\n}", "function updateRelease() {\n const relId = document.getElementById(\"modal-id\").value.substring(3);\n const nom = document.getElementById(\"modal-name\").value;\n const date = document.getElementById(\"modal-date\").value;\n const description = document.getElementById(\"modal-description\").value;\n const link = document.getElementById(\"modal-src_link\").value;\n const sprint = document.getElementById(\"modal-sprint\").value;\n\n let jsonData = {\n \"name\": nom,\n \"release_date\": formatDate(date, false),\n \"description\": description,\n \"src_link\": link,\n \"sprint\": sprint\n };\n\n sendAjax(\"/api/release/\" + relId, 'PUT', JSON.stringify(jsonData)).then(res => {\n $(\"#rel\" + res.id + \"-name\").empty().append(res.name);\n $(\"#rel\" + res.id + \"-description\").empty().append(res.description);\n $(\"#rel\" + res.id + \"-releaseDate\").empty().append(formatDate(res.releaseDate));\n $(\"#rel\" + res.id + \"-src_link\").empty().append(res.srcLink);\n $(\"#rel\" + res.id + \"-sprint\").empty().append(\"<span id='sprint-id-rel-\" + res.id + \"' class='hidden'>\" + res.sprint.id + \"</span>\" +\n \"Du \" + formatDate(res.sprint.startDate) + \" au \" + formatDate(res.sprint.endDate));\n $(\"#modal-release\").modal(\"hide\");\n })\n}", "function adminModif(id){\n console.log(id)\n biblio = biblioteca[id]\n document.querySelector(\"#titleModal\").innerText = biblio.titulo\n document.querySelector(\"#authorModal\").value = biblio.autor\n document.querySelector(\"#demogModal\").value = biblio.demografia\n document.querySelector(\"#categModal\").value = biblio.categoria\n document.querySelector(\"#añoModal\").value = biblio.año\n document.querySelector(\"#ediModal\").value = biblio.editorial\n document.querySelector(\"#tomoModal\").value = biblio.tomo\n document.querySelector(\"#imgModal\").value = biblio.imagen\n document.querySelector(\"#descripModal\").value = biblio.descripcion\n \n $('#adminModif').modal('show')\n \n}", "function onUpdateSuccess(data) {\n console.log(\"update success!\");\n console.log(data);\n var jsonData = $.parseJSON(data);\n var results = $('<h2>');\n results.html(\"Created Video ID: \" + jsonData.result.id);\n $('#results').append(results); \n $('#results').css('backgroundColor', '#AFFFB4');\n}", "function displayResults() {\n modalMoves.innerHTML = movesCounter.innerHTML;\n modalTime.innerHTML = timerDisplay.innerHTML;\n modal.style.display = 'block';\n}", "showEditDeleteModal(rowData) {\n $(\"#rid\").val(rowData.id);\n $(\"#rdescription\").val(rowData.description);\n $(\"#rprice\").val(rowData.price);\n $(\"#rrooms\").val(rowData.rooms);\n $(\"#rmail\").val(rowData.mail);\n $(\"#rname\").val(rowData.name);\n $(\"#rphoneNr\").val(rowData.phoneNr);\n $(\"#editDeleteModal\").modal('show');\n }", "function onEditCallSuccess (json) {\n var listingToEdit = json;\n $modal = $('#updateListingModal');\n // $imgUrlField = $modal.find('#updateListingImgUrl');\n\n //$zipField = $modal.find('#updateListingZip');\n $titleField = $modal.find('#updateListingTitle');\n $rentField = $modal.find('#updateListingRent');\n\n //$imgUrlField.val(listingToEdit.imgUrl);\n //$streetField.val(listingToEdit.street);\n //$cityField.val(listingToEdit.city);\n //$stateField.val(listingToEdit.state);\n //$zipField.val(listingToEdit.zip);\n $titleField.val(listingToEdit.title);\n $rentField.val(listingToEdit.rent);\n\n $('#updateListing').on('click', handleUpdateListing);\n\n}", "function editRecg(questionId){\n $.ajax({\n url : 'recognition.php',\n method: 'post',\n dataType: 'json',\n data:{\n key: 'getRecg',\n questionId: questionId\n },\n \n success: function(response){\n $('#editRecgId').val(questionId);\n $('#question_number').val(response.question_number);\n $('#survey_question').val(response.survey_question);\n $('#agree').val(response.agree);\n $('#disagree').val(response.disagree);\n $('#prefer_not_to_say').val(response.prefer_not_to_say);\n $('#recgModal').modal('show');\n\n /**\n * change the value of input to update and the button style whilst\n * updating the row with the updated data\n */\n $('#updateRecg').attr('value', 'Update').attr('class', \"btn btn-dark\").attr('onclick', \"manageData('updateRecg')\")\n alert(response)\n }\n })\n}", "function updateCallbackOk(result) {\n $(\"#mdlTask\").modal(\"hide\");\n $(\"#tblTasks\").bootstrapTable(\"updateRow\", {\n index: TableUtil.getTableIndexById(\"#tblTasks\", $(\"#txtTaskId\").val()),\n row: {\n Id: $(\"#txtTaskId\").val(),\n Name: $(\"#txtTaskName\").val(),\n Description: $(\"#txtTaskDescription\").val(),\n Order: $(\"#txtTaskOrder\").val(),\n Status: $(\"#ddlTaskStatus option:selected\").text()\n }\n });\n }", "function updateModal(bill, noOfPeople, totalPPS) {\n $('#billPara').html('€' + bill);\n $('#peoplePara').html(noOfPeople);\n\n switch (tipPercentMultiplier) {\n case '1.05':\n percentage = 5;\n break;\n case '1.10':\n percentage = 10;\n break;\n case '1.15':\n percentage = 15;\n break;\n case '1.20':\n percentage = 20;\n break;\n case '1.25':\n percentage = 25;\n break;\n default:\n percentage = 0;\n }\n\n $('#percentagePara').html(percentage + '%');\n $('#totalPerPersonPara').html('€' + totalPPS);\n}", "function Mostrar(id) {\n$(\"#hidden_usuario_id\").val(id);\n$.post(\"../../model/users/unique_info.php\", {\nid: id\n},\nfunction (data, status) {\nvar dato = JSON.parse(data);\n$(\"#nick2\").val(dato.nick);\n$(\"#nombre2\").val(dato.nombre_usuario);\n$(\"#correo2\").val(dato.correo_usuario);\n$(\"#nivel2\").val(dato.nivel);\n}\n);\n$(\"#modaluserupdate\").modal(\"show\");\n}", "function top_track_moda (tracks){\n var id_modal = \"#modal_track\";\n $(id_modal+ \" h4\").text(\"Track\");\n var result='<table class=\"table\">'+\n '<thead>'+\n '<tr>'+\n '<th colspan=\"5\" class=\"text-center\"><h2>'+tracks.track_name+'</h2></th>'+\n '</tr>'+\n '</thead>'+\n '<tbody>'+\n '<tr>'+\n '<th class=\"text-center\">Disc Number</th><th class=\"text-center\">Track Number</th><th class=\"text-center\">Album Name</th><th class=\"text-center\">Duration</th><th class=\"text-center\">Preview</th>'+\n '</tr>'+ \n '<tr>'+\n '<td class=\"text-center\">'+tracks.disc_number+'</td>'+\n '<td class=\"text-center\">'+tracks.track_number+'</td>'+\n '<td id=\"'+tracks.album_id+'\" class=\"text-center\">'+tracks.album_name+'</td>'+\n '<td class=\"text-center\">'+millisToMinutesAndSeconds(tracks.duration_ms)+'</td>'+\n '<td class=\"text-center\"><a target=\"_blank\" href=\"'+tracks.preview_url+'\"><span class=\"glyphicon glyphicon-music\"></span></a></td>'+\n '</tr>'; \n \n '</tbody>'+\n '</table>';\n // $(\"#tracklist_list\").empty();\n //$(\"#tracklist_list\").append(result);\n $(id_modal+\" .modal-body\").empty();\n $(id_modal+\" .modal-body\").append(result);\n $(id_modal+\" td:nth-child(3)\").click(function (){\n var id_album =$(this).attr(\"id\");\n var url = \"https://api.spotify.com/v1/albums/\" + id_album + \"/tracks\";\n request(url,\"load_tracks\",tracks.album_name);\n });\n \n \n $(id_modal).modal('show'); \n}", "function results(){\n totalMoves = moves.innerHTML;\n totalTime = timerDiv.innerHTML;\n\n let modalStars = document.querySelector('.total-stars');\n let modalTimer = document.querySelector('.total-time');\n let modalMoves = document.querySelector('.total-moves');\n\n modalMoves.innerHTML = totalMoves;\n modalTimer.innerHTML = totalTime;\n modalStars.innerHTML = `Stars remaining: ${totalStars}`\n}", "function modalSearch(){\n\t$('#lbl_title').text('Search Data Infaq');\n\t$('#m_search').modal('show');\n}", "function modalEditOnShown(dialogRef) {\r\n\t\t\tvar rowData = dt.row('.selected').data(),\r\n\t\t\t\tmodalBody = dialogRef.getModalBody(),\r\n\t\t\t\r\n\t\t\t// For checking active licenses\r\n\t\t\tparams = { \r\n\t\t\t\tlicense_status: 1,\r\n\t\t\t\tclientLicenseId: rowData.client_id \r\n\t\t\t};\r\n\t\t\t\t\r\n\t\t\t// Check if client have active licenses\r\n\t\t\t$.post(WS_LIST_LICENSES, params)\r\n\t\t\t\t.done(function (results, status) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Remove elements for status\r\n\t\t\t\t\tmodalBody.find('select[data-field=\"status\"]').selectpicker('destroy');\r\n\t\t\t\t\tmodalBody.find('select[data-field=\"status\"]').remove();\r\n\t\t\t\t\tmodalBody.find('input[data-field=\"status\"]').remove();\r\n\t\t\t\t\tmodalBody.find('input[data-value=\"status\"]').remove();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Append input (readonly) \r\n\t\t\t\t\tif (results.response.type === 'SUCCESS') {\t\t\t\t\t\t\r\n\t\t\t\t\t\tmodalBody.find('#status-box').append(\r\n\t\t\t\t\t\t\t'<input type=\"hidden\" data-field=\"status\" value=\"1\">' +\r\n\t\t\t\t\t\t\t'<input type=\"text\" class=\"form-control\" data-value=\"status\" value=\"Active\" readonly>'\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t// Append select\r\n\t\t\t\t\t} else {\t\t\t\t\t\r\n\t\t\t\t\t\tmodalBody.find('#status-box').append(\r\n\t\t\t\t\t\t\t'<select class=\"form-control\" data-field=\"status\">' +\r\n\t\t\t\t\t\t\t\t'<option value=\"1\">Active</option>' +\r\n\t\t\t\t\t\t\t\t'<option value=\"0\">Inactive</option>' +\r\n\t\t\t\t\t\t\t'</select>'\r\n\t\t\t\t\t\t);\t\t\t\t\t\t\r\n\t\t\t\t\t}\t\r\n\r\n\t\t\t\t\t// Load form values\r\n\t\t\t\t\t$.each(rowData, function (name, value) {\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (name === 'status') {\r\n\t\t\t\t\t\t\tmodalBody.find('select[data-field=\"status\"]').val(value === 'Active' ? '1' : '0')\r\n\t\t\t\t\t\t\tmodalBody.find('select[data-field=\"status\"]').selectpicker();\r\n\t\t\t\t\t\t}\telse {\r\n\t\t\t\t\t\t\tmodalBody.find('input[data-field=\"' + name + '\"]').val(value);\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\t\t\t\t\r\n\t\t\t\t\t});\t\t\t\t\t\t\r\n\t\t\t\t})\r\n\t\t\t\t\r\n\t\t\t\t// Show WS Error\r\n\t\t\t\t.fail(function () {\r\n\t\t\t\t\tSTIC.ShowWSError({ formId: params.formId });\r\n\t\t\t\t});\r\n\t\t}", "function update() {\n axios.post('../../api/controller.php', {\n action: \"update-disciplina\",\n values: [\n $(\"#editar_disciplina\").val(),\n $(\"#id_disciplina\").val()\n ]\n }).then(function (response) {\n if (response.data) {\n $('#modal_update_disciplinas').modal('hide')\n $(\"#editar_disciplina\").val(\"\")\n Swal.fire(\n 'Sucesso',\n 'Disciplina Editada com sucesso',\n 'success'\n );\n $(\"#table\").DataTable().destroy()\n getDisciplinas()\n\n\n } else {\n Swal.fire(\n 'Ops :(',\n 'Não foi possivel editar essa disciplina',\n 'error'\n );\n $(\"#table\").DataTable().destroy()\n getDisciplinas()\n }\n })\n}", "function actualizar_oi(){\n $('#confirmar_actualizar_oi').modal('show');\n}", "function showEditPromotionModal(productSku, productName, productModel, carePakSku, carePakType, carePakPeriod, startDate, endDate, registrationPeriod) {\n // Rest form of previous values\n $(\"#editPromotionInfo\")[0].reset();\n // Assign the json values to the fields\n $(\"#productSku\").val(productSku);\n $(\"#productName\").val(productName);\n $(\"#productModel\").val(productModel);\n $(\"#carePakSku\").val(carePakSku);\n $(\"#carePakType\").val(carePakType);\n $(\"#carePakPeriod\").val(carePakPeriod);\n $(\"#startDate\").val(startDate);\n $(\"#endDate\").val(endDate);\n $(\"#registrationPeriod\").val(registrationPeriod);\n\n // Show the overlay\n $(\".overlay\").css('display', 'block');\n $(\"#editPromotionModal\").css('display', 'block');\n}", "function successReload(option) {\n visitas.closeModal(option); //Aquí cerramos el modal, llamamos al JS que se llama visitas y ejecutamos el metodo closeModal\n //alert(\"Todo bien\");\n alertUpdate(); //metodo hub\n }", "function updateService() { //add to onlick\n $.ajax({'success': function (html) {\n\t\t$('#modalServiceGroupsBody').html(html);\n\t\t$('#modalServiceGroups').modal('show');\n\t\t$('#Paid_Services_price').inputmask(\"9{2,9}.9{2}\");\n\t},\n\t\t\t'url': $(this).attr('href')\n });\n return false;\n}", "function uncoretModal(){\n $(\"#uncoretModal .modal-body\").html(\"Yakin kembalikan \"+currentProfile.tec_regno+\" (\"+currentProfile.name+\") ?\")\n $('#uncoretModal').modal('show');\n}", "function modal_edit_refaccion(refaccion) \r\n{\r\n /*Recuperar el id de la garantia que se desea actualizar*/\r\n var refaccion_id = refaccion;\r\n $('#modal_edit_refaccion').modal('toggle');\r\n search_refaccion(refaccion);//Buscar las refacciones\r\n\r\n return false;\r\n}", "toggleModal() {\n if (this.modal == true) {\n customerService.getCustomerSearch(result => {\n this.temporaryOptions = [];\n result.map(e => {\n this.temporaryOptions.push({ value: e.c_id, label: e.fullname });\n });\n this.searchbarOptions = this.temporaryOptions;\n });\n }\n this.modal ? (this.modal = false) : (this.modal = true);\n }", "function mostrarFechasResultantes (infoFechaInmunidad, infoFechaRevacunacion){\n //levanto el modal donde están las cajas de mensaje donde\n //cargo la información de las fechas\n $('#modalInfo').modal();\n //asigno la información de las fechas a las cajas de texto\n const infoFechaInmune = document.getElementById(\"fInmune\");\n infoFechaInmune.innerHTML = `${infoFechaInmunidad}`;\n const infoFechaRevacunar = document.getElementById(\"fRevacunacion\");\n infoFechaRevacunar.innerHTML = `${infoFechaRevacunacion}`;\n\n\n}", "update() {\n this.scoreHTML.innerText = this.score;\n // show modal if you score 12\n if(this.score == 12){\n this.win();\n }\n }", "function setModal(id, json){\r\n for(var i = 0; i < json['products'].length; i++){\r\n var data = json['products'][i]\r\n if(data['id'] == id){\r\n $(\"#modal-shop-title\").html(data['name']);\r\n $(\"#modal-shop-price\").html(data['price']+\"€\");\r\n $(\"#modal-shop-description\").html(data['description']);\r\n\r\n UIkit.modal(\"#modal-shop\").show();\r\n }\r\n }\r\n}", "function show_modal_response( data ){\n //debugger\n if(data){\n j('#response').html( S(data) );\n j('#fancybox_trigger').trigger('click');\n }\n }", "function showModel(TSID, task) {\n var jsonAction = JSON.parse(list.filter(o => o.treansactionID_FK == currentVacationId)[0].actions).filter(o => o.TSID == TSID)[0];\n $.ajax({\n url: \"/TicketsApprovment/forTickets/\" + currentVacationId,\n typr: \"GET\",\n contentType: \"application/json;charset=UTF-8\",\n dataType: \"json\",\n success: function (Data) {\n tickets = JSON.parse(Data.Data);\n if (Data.Code === 200) { \n var result = myUserControl(jsonAction, task, Data.Data);\n $(\"#userControl\").css(\"margin-top\", \"7%\");\n $(\"#userControl .modal-title\").html(result[0]);\n $(\"#userControl .modal-body\").html(result[1]);\n $(\"#userControl .modal-footer\").html(result[2]);\n $(\"#userControl .modal-dialog\").width(result[2] + '%');\n\n\n\n $(\"#userControl\").modal('show');\n }\n },\n error: function (errormessage) {\n console.log(errormessage.responseText);\n }\n\n });\n\n\n \n\n}", "function showEditContactModal(data) { \n var jdata = arcGetJson(data);\n $(\"#contactname\").val(jdata.name);\n $(\"#contacttitle\").val(jdata.title);\n $(\"#contactemail\").val(jdata.email);\n $(\"#contactphone\").val(jdata.phone);\n $(\"#contactid\").val(jdata.id);\n $(\"#editContactModal\").modal(\"show\");\n}", "function modalDisplay(chosenRest) {\n // in case no restaurant fits the criteria\n if (chosenRest === undefined) {\n $(\"#no-results-modal\").removeClass(\"modal_hidden\");\n $(\"#load\").addClass(\"hidden\");\n return;\n }\n $(\"#res-name\").text(chosenRest.name);\n $(\"#res-icon\").attr(\"src\", chosenRest.icon);\n $(\"#address\").text(chosenRest.vicinity);\n $(\"#res-rate\").text(\"Rating: \" + chosenRest.rating);\n\n $(\"#res-modal\").removeClass(\"modal_hidden\");\n }", "function openModalMaaltijdfilterUpdate(htmlColumn) {\n\tsetModalMaaltijdfilterModus(false);\n\trow = htmlColumn.closest(\"tr\");\n\tid = getColumnValue(row, 'id');\n\tproductgroepId = getColumnValue(row, 'productgroep-id');\n\tmaaltijdtypeId = getColumnValue(row, 'maaltijdtype-id');\n\tmaaltijdsubtypeId = getColumnValue(row, 'maaltijdsubtype-id');\n\ttooltip = getColumnValue(row, 'tooltip');\n\t// Set the id for the row so it can be identified for a text update.\n\trow.attr('id', 'fltr_' + id);\n\tsetModalMaaltijdfilterModus(false);\n\tsetModalMaaltijdfilterValue('id',id, false);\n\tsetModalMaaltijdfilterValue('productgroep-id',productgroepId, false, 'select');\n\tsetModalMaaltijdfilterValue('maaltijdtype-id',maaltijdtypeId, false, 'select');\n\tsetModalMaaltijdfilterValue('maaltijdsubtype-id',maaltijdsubtypeId, false, 'select');\n\tsetModalMaaltijdfilterValue('tooltip',tooltip, false, 'textarea');\n\t$(\"#modal-maaltijdfilter\").modal('show');\n}", "function updateViewEmployeeModal() {\n var image_url = $('#baseUrl').val();\n $('#viewEmployeeDataModal').find('.emp_name').html(current_employee.name);\n $('#viewEmployeeDataModal').find('.emp_address').html(current_employee.address);\n\n if (current_employee.image && current_employee.image != null) {\n $('#viewEmployeeDataModal').find('.emp_image').attr('src', (image_url + current_employee.image));\n }\n updateViewMapLoc(current_employee.lat, current_employee.lng);\n}", "function okOnGet(data, postFun){\r\n $(\"#\"+modal+\" .modal-body\").html(data.content);\r\n registerForm(postFun);\r\n $(\"#\"+modal).modal(\"show\");\r\n //mymodal.open();\r\n }", "function showModal() {\n\n $('#myModal').modal(\"show\");\n $(\".modal-title\").text(data.name)\n $(\".modal-img\").attr('src', data.sprites.other['official-artwork'].front_default);\n $(\".modal-li-1\").text(\"Type: \" + data.types[0].type.name)\n $(\".modal-li-2\").text(\"Abilities: \" + data.abilities[0].ability.name + \"/\" + data.abilities[1].ability.name)\n $(\".modal-li-3\").text(\"Stats: \" + \"HP: \" + data.stats[0].base_stat + \" ATK: \" + data.stats[1].base_stat + \" DEF: \" + data.stats[2].base_stat + \" SP. ATK: \" + data.stats[3].base_stat + \" SP. DEF: \" + data.stats[4].base_stat + \" SPD: \" + data.stats[5].base_stat)\n $(\".modal-li-4\").text(\"Base XP: \" + data.base_experience);\n $(\".modal-li-5\").text(\"Height: \" + data.height + \" ft \" + \"Weight: \" + data.weight + \" lbs\")\n }", "function editCategoryModal(id) {\n $.ajax({\n url: '../Category/categoryApi.php', // url where to submit the request\n type: \"POST\", // type of action POST || GET\n data: {getUpdate: id}, // post data || get data\n success: function (data) {\n console.log(data);\n var obj = JSON.parse(data);\n $('#id').val(obj.category_id);\n $('#name').val(obj.category_name);\n $('#des').val(obj.category_des);\n $('#editCate').modal(\"show\");\n },\n error: function (result) {\n showNotification('top', 'right', 'This Category can\\'t be edit', '2');\n console.log(result);\n\n }\n });\n}", "function modalViewOnShown(dialogRef) {\r\n\t\t\tvar rowData = dt.row('.selected').data(),\r\n\t\t\t\tmodalBody = dialogRef.getModalBody();\r\n\t\t\t$.each(rowData, function (name, value) {\r\n\t\t\t\tmodalBody.find('td[data-cell=\"' + name + '\"]').text(value);\r\n\t\t\t});\r\n\t\t}", "function modal(data) {\n // Set modal title\n $('.modal-title').html(data.title);\n // Clear buttons except Cancel\n $('.modal-footer button:not(\".btn-default\")').remove();\n // Set input values\n $('#title').val(data.event ? data.event.title : '');\n $('#description').val(data.event ? data.event.description : '');\n $('#color').val(data.event ? data.event.color : '#3a87ad');\n // Create Butttons\n $.each(data.buttons, function(index, button){\n $('.modal-footer').prepend('<button type=\"button\" id=\"' + button.id + '\" class=\"btn ' + button.css + '\">' + button.label + '</button>')\n })\n //Show Modal\n $('.modal').modal('show');\n }", "function modal(data) {\n // Set modal title\n $('.modal-title').html(data.title);\n // Clear buttons except Cancel\n $('.modal-footer button:not(\".btn-default\")').remove();\n // Set input values\n $('#title').val(data.event ? data.event.title : ''); \n $('#description').val(data.event ? data.event.description : '');\n $('#color').val(data.event ? data.event.color : '#3a87ad');\n // Create Butttons\n $.each(data.buttons, function(index, button){\n $('.modal-footer').prepend('<button type=\"button\" id=\"' + button.id + '\" class=\"btn ' + button.css + '\">' + button.label + '</button>')\n })\n //Show Modal\n $('.modal').modal('show');\n }", "function InsertDataIntoCourseUpdateModal(id){\r\n\t$.ajax({\r\n\t\ttype: 'GET',\r\n\t\tcontentType: 'application/json; charset=utf-8',\r\n\t\turl: 'http://localhost:8000/Course/'+id+'/',\r\n\t\tdataType: 'json',\r\n\t}).then(function(data){\r\n\t\tconsole.log(data);\r\n\t\t$('#uCourseId').val(data.id);\r\n\t\t$('#uCourseName').val(data.courseName);\r\n\t\t$('#uMajor').val(data.major);\r\n\t});\r\n}", "function update_form_data(res) {\n $(\"#promo_id\").val(res.id);\n $(\"#promo_name\").val(res.name);\n $(\"#promo_type\").val(res.promo_type);\n $(\"#promo_value\").val(res.value);\n $(\"#promo_start_date\").val(res.start_date);\n $(\"#promo_end_date\").val(res.end_date);\n $(\"#promo_detail\").val(res.detail);\n }", "async function createConsumablesCWModal() {\n const modal = await modalController.create({\n component: \"consume-cw-modal\",\n cssClass: \"consumeCWModal\",\n });\n\n var settings = {\n \"url\": `http://localhost:8080/api/caseworker/consumables/detail/${storedButtonID}`,\n \"method\": \"GET\",\n \"timeout\": 0,\n };\n \n $.ajax(settings).done(function (response) {\n var dataArray2 = JSON.parse(response);\n console.log(dataArray2);\n\n var comments;\n\n if(dataArray2[0].cons_comment = \"undefined\"){\n comments = \" - \";\n }else{\n comments = dataArray2[0].cons_comment;\n }\n\n document.getElementById(\"cwConsName\").innerHTML = dataArray2[0].cons_name;\n document.getElementById(\"cwConsID\").innerHTML = dataArray2[0].cons_id;\n document.getElementById(\"cwConsLabel\").innerHTML = dataArray2[0].cons_label;\n document.getElementById(\"cwConsStatus\").innerHTML = dataArray2[0].cons_status;\n document.getElementById(\"cwConsComments\").innerHTML = comments;\n \n });\n\n await modal.present();\n currentModal = modal;\n}", "function showModal(title, body) {\n updateModal(title, body)\n $(modal).modal('show')\n}", "function modalResult() {\n\tlet href = \"#modal-result\";\n\twindow.open(href, \"_self\");\n}", "function openUpdatePromo(promoId) {\n\tjQuery.ajax({\n\t url: \"service.php\",\n\t type: \"GET\",\n\t data: {updatePromoId:promoId},\n\t success: function(json_data)\n\t\t{\n\t\t\t//fills data\n\t\t\tvar data_array = $.parseJSON(json_data);\n\t\t\t\n\t\t\tconsole.log(data_array);\n\t\t\t\n\t\t\topenModal(data_array);\t\t\t\t\n\t\t},\n\t\terror: function (jqXHR, textStatus, errorThrown)\n\t\t{\n\t\t\tconsole.log(errorThrown);//)\n\t\t}\n\t});\n}", "function showSerialManageModal(data)\r\n{\r\n //you can do anything with data, or pass more data to this function. i set this data to modal header for example\r\n\t $('.serialManageDeleteByAdmin').attr('href','/serialManageDeleteByAdmin?id='+data);\r\n\t$(\"#mySerialManageModal .serialManageDeleteByAdminId\").html(data)\r\n $(\"#mySerialManageModal\").modal();\r\n}", "async function createPayAdminModal() {\n const modal = await modalController.create({\n component: \"pay-admin-modal\",\n cssClass: \"payAdminModal\",\n });\n\n var settings = {\n \"url\": `http://localhost:8080/api/admin/payment/${storedButtonID}`,\n \"method\": \"GET\",\n \"timeout\": 0,\n };\n \n $.ajax(settings).done(function (response) {\n var dataArray = JSON.parse(response);\n console.log(dataArray);\n\n var paymentNotes;\n\n if(dataArray[0].paymentNote = \"undefined\"){\n paymentNotes = \" - \";\n }\n else{\n paymentNotes = dataArray[0].paymentNote;\n }\n\n document.getElementById(\"paymentTenantID\").innerHTML = dataArray[0].tenant_id;\n document.getElementById(\"paymentAmount\").innerHTML = \"$\" + dataArray[0].amount_owe;\n document.getElementById(\"paymentDeduction\").innerHTML = \"$\" + dataArray[0].deposit_deduction;\n document.getElementById(\"paymentCategory\").innerHTML = dataArray[0].payment_cat;\n document.getElementById(\"paymentCharges\").innerHTML = \"$\" + dataArray[0].negligence_charge;\n document.getElementById(\"paymentNotes\").innerHTML =paymentNotes;\n });\n\n await modal.present();\n currentModal = modal;\n}", "function setSearchResults(response, endpoint, searchParam) {\n searchContent.empty();\n searchContentUl.empty();\n if(response.count) {\n searchContent.append(searchContentUl);\n delete response.results[0].created;\n delete response.results[0].edited;\n delete response.results[0].url;\n $.each(response.results[0], function(index,value) {\n if(!Array.isArray(value)) {\n searchContentUl.append($(\"<li>\" + index + \": \" + value + \"</li>\"));\n }\n });\n } else {\n //Creating modal and triggering on empty SWAPI response.results object.\n let modal = $(\"<div id='modal-close-outside' uk-modal>\");\n modal.empty();\n let modalBody = $(\"<div class='uk-modal-dialog uk-modal-body'>\");\n let modalBtn = $(\"<button class='uk-modal-close-outside' type='button' uk-close></button>\");\n let modalTitle = $(\"<h2 class='uk-modal-title'>Force Disturbance</h2>\");\n let modalGif = $(\"<img src='./assets/img/jedi-mind-trick.gif'/>\");\n switch (endpoint) {\n case \"planets\":\n endpoint = \"planet\";\n break;\n case \"people\":\n endpoint = \"person\";\n break;\n case \"starships\":\n endpoint = \"starship\";\n break;\n case \"species\":\n endpoint = \"species\";\n break; \n default:\n endpoint = \"film\";\n break;\n }\n let modalP = $(\"<p>This is not the \" + endpoint + \" you are looking for. \" + searchParam.charAt(0).toUpperCase() + searchParam.slice(1) + \" is not a \" + endpoint + \" in a galaxy far, far away.</p>\");\n modal.append(modalBody);\n modalBody.append(modalBtn,modalTitle,modalGif,modalP);\n console.log(modal);\n UIkit.modal(modal).show();\n };\n}", "async function updateModal(req, res) {\n \n console.log('UPD Modal Item')\n\n try {\n const modal = await findByID(req.params.id, 'modal_items')\n \n if (!modal) {\n res.status(404).json({message : `Modal Not Found ${req.params.id}`})\n } else {\n const data = await getPostData(req)\n \n const { name, addInfo, price } = JSON.parse(data)\n\n const modalData = {\n name: name || modal.name,\n addInfo: addInfo || modal.addInfo,\n price: price || modal.price,\n }\n \n const updatedModal = await update(req.params.id, modalData, 'modal_items')\n\n res.status(200).json(updatedModal)\n }\n } catch (error) {\n console.log(error);\n }\n}", "function modal(data) {\n // Set modal title\n $('.modal-title').html(data.title);\n // Clear buttons except Cancel\n $('.modal-footer button:not(\".btn-default\")').remove();\n // Set input values\n $('#title').val(data.event ? data.event.title : '');\n if( ! data.event) {\n // When adding set timepicker to current time\n var now = new Date();\n var time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes());\n } else {\n // When editing set timepicker to event's time\n var time = data.event.date.split(' ')[1].slice(0, -3);\n time = time.charAt(0) === '0' ? time.slice(1) : time;\n }\n $('#time').val(time);\n $('#description').val(data.event ? data.event.description : '');\n $(\"#id_sala option:selected\").val(data.event ? data.event.id_sala : '');\n $('#color').val(data.event ? data.event.color : '#3a87ad');\n // Create Butttons\n $.each(data.buttons, function(index, button){\n $('.modal-footer').prepend('<button type=\"button\" id=\"' + button.id + '\" class=\"btn ' + button.css + '\">' + button.label + '</button>')\n });\n //Show Modal\n $('.modal').modal('show');\n }", "function populateModal(response) {\n let year;\n let month;\n let day;\n let types = [];\n\n title.text(response.nom + ' ' + response.prenom)\n\n $('#nom').val(response.nom);\n $('#prenom').val(response.prenom);\n\n arrayDate = response.birth_date.split('-');\n year = arrayDate[0];\n month = arrayDate[1];\n day = arrayDate[2].substring(0, 2);\n $('#birth_date').datepicker('setDate', day + '/' + month + '/' + year);\n\n response.types.forEach(type => {\n types.push(type.id);\n });\n select.multipleSelect('setSelects', types);\n \n $('#weight').val(response.weight);\n $('#adress').val(response.adress);\n $('#phone').val(response.phone);\n $('#boxer_id').val(response.id)\n $('#parent_name').val(response.parent_name);\n $('#parent_phone').val(response.parent_phone);\n }", "function actualizarMostrar(id,cedula,nombre,apellido1,apellido2,telefono,correo,productoid){\n$(\"#idActualizar\").val(id);\n$(\"#cedulaM\").val(cedula);\n$(\"#nombreM\").val(nombre);\n$(\"#apellido1M\").val(apellido1);\n$(\"#apellido2M\").val(apellido2);\n$(\"#telefonoM\").val(telefono);\n$(\"#correoM\").val(correo);\n$(\"#productoM\").val(productoid);\n\n document.getElementById(\"modalModificar\").style.display = \"block\";\n}", "function updateMelons(results) {\n if (results.code === \"OK\") {\n $('#order-status').html(\"<p>\" + results.msg + \"</p>\");\n }\n else {\n $('#order-status').addCtygtglass(\"order-error\");\n $('#order-status').html(\"<p><b>\" + results.msg + \"</b></p>\");\n }\n}", "function place(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tdocument.getElementById('submitButton').style.opacity=0.3;\n\t\t\t\tcheckoutID=document.getElementById('checkoutID').value;\n\t\t\t\tid=sessionStorage.shopID;\n\t\t\t\tverifyCheckoutID(id,checkoutID)\n\t\t\t\t.then(function(){\n\t\t\t\t\tupdate(id,checkoutID)\n\t\t\t\t\t.then(function(){\n\t\t\t\t\t\tconsole.log('updated');\n\t\t\t\t\t})\n\t\t\t\t\t.catch(function(){\n\n\t\t\t\t\t})\n\t\t\t\t\tlocation.reload();\n\t\t\t\t})\n\t\t\t\t.catch(function(){\n\t\t\t\t\tdocument.getElementById('submitButton').setAttribute(\"data-toggle\",\"modal\");\n\t\t\t\t\t$(\"#myModal\").modal(\"show\");\n\t\t\t\t});\n\t\t\t\tdocument.getElementById('submitButton').style.opacity=1;\n\n\t\t\t}", "function modal_souvenir(id)\n {\n document.getElementById('mg_title').innerHTML=\"Souvenir Information\";\n console.log(server+'_data_souvenir_1.php?cari='+id);\n $.ajax({url: server+'_data_souvenir_1.php?cari='+id, data: \"\", dataType: 'json', success: function(rows){ \n for (var i in rows.data){ \n var row = rows.data[i];\n var id = row.id;\n var name = row.name;\n var owner = row.owner;\n var cp = row.cp;\n var address = row.address;\n var employee = row.employee;\n var type_souvenir = row.type_souvenir;\n var lat=row.lat;\n var lng = row.lng;\n console.log(name);\n document.getElementById('mg_body').innerHTML=\"<h2>\"+name+\"</h2><br><div style='margin-left:20px'>Address: \"+address+\"<br>Contact Person: \"+cp+\"<br>Owner: \"+owner+\"<br>Employee: \"+employee+\"<br>Type: \"+type_souvenir+\"</div>\";\n }//end for\n\n $('#modal_gallery').modal('show');\n }});//end ajax \n }", "function getShowById(id) {\n $(\"#title\").text(\"Show Detail\")\n $.ajax({\n url: '/Show/GetShowById/' + id,\n type: 'GET',\n datatype: 'json',\n success: function (data) {\n $(\"#Id\").val(data.Id);\n $(\"#Name\").val(data.Name);\n $(\"#Price\").val(data.Price);\n isUpdate = true;\n $(\"#showModal\").modal('show');\n },\n error: function (err) {\n alert(\"Error\" + err.ResponseText);\n }\n });\n}", "function showAnswerActions(answers) {\n answers.forEach(function (answer) {\n var id = 'actions_' + answer.answer_id;\n var html = \"<button class='btn btn-primary' id='myBtn\" + answer.answer_id + \"' data-toggle='modal' data-target='#myModal\" + answer.answer_id + \"'>Edit</button>\";\n document.getElementById(id).innerHTML = html;\n });\n var models = [];\n answers.forEach(function (answer) {\n var html = \"<div id='myModal\" + answer.answer_id + \"' class='modal'>\"\n + \"<div class='modal-content'>\"\n + \" <span class='close' data-dismiss='modal'>&times;</span>\"\n + \"<textarea class='textarea' id='newAnswer\" + answer.answer_id + \"'>\" + answer.answer_body + \"</textarea><br>\"\n + \"<button class='btn btn-primary' id='updateBtn' onclick='updateUserAnswer(\" + JSON.stringify(answer) + \");'>Update</button>\"\n + \"</div>\"\n + \"</div>\";\n models.push(html);\n });\n document.getElementById('includes').innerHTML = models.join(\"\");\n}", "function success() {\n\n Modal.success({\n okText:\"Done\",\n title: 'Submit successful!',\n // content: 'View your requests to see your new entry.',\n onOk() {\n doneRedirect();\n }\n });\n }", "function mostrarModalEditContacto(idContacto, idAgencia){\n //alert(idContacto+\" \"+idAgencia);\n $.ajax({\n type: 'POST',\n url: 'getContactos.php',\n dataType: 'json',\n data: {\n idContacto: idContacto,\n idAgencia: idAgencia,\n flagContacto: 'getContacto'\n }\n })\n .done(function(resultado){\n if(resultado.error == false){\n $('#modalEditContact').modal('show');\n $('#editIdContacto').val(idContacto);\n $('#editNombreContacto').val(resultado.nombreContacto);\n $('#editPuestoContacto').val(resultado.puestoContacto);\n $('#editSkypeContacto').val(resultado.skypeContacto);\n $('#editTelefonoContacto').val(resultado.telefonoContacto);\n }\n })\n \n}", "function showData() {\n GetUser().then((res) => {\n for (const key in res) {\n addModalBox(res[key]);\n }\n });\n}", "function openFormEditKienNghi() {\n showLoadingOverlay(modalIdKienNghi + \" .modal-content\");\n $.ajax({\n type: \"GET\",\n url: editKienNghiUrl,\n data: {\n id: HoSoVuAnID\n },\n success: function (response) {\n $(modalIdKienNghi + \" .modal-content\").html(response);\n\n hideLoadingOverlay(modalIdKienNghi + \" .modal-content\");\n }\n });\n }", "function inicioEditar(idEmpresa){\n $.post(\"/censocc/viewcontroller/getAllDataEncuesta.php\", {idEmpresa : idEmpresa}, function(allDataEditar){\n var dataEdit = allDataEditar[0];\n $.post(\"editarencuesta.php\",function(data){\n //console.log(data);\n var $miModal = $(\"#myModalFormEdit\");\n $(\"#modalContentFormBody\").html(data);\n vaciarDatos(allDataEditar,$miModal);\n });\n });\n}", "async function ModalUpdate(index) {\n const response = await api.get('analises');\n let contar = 0;\n const analisesBanco = response.data;\n\n analisesBanco.map(async analise => {\n const ObjAnalise = {\n id: analise.id,\n nomeAnalise: analise.analise,\n };\n contar += 1;\n setSelectAnalises(state => [...state, ObjAnalise]);\n if (analise.id === relatorioCacp[index].analiseId) {\n setIndex3(new IndexPath(contar));\n }\n // console.log(index3);\n });\n const item = {\n tipo_item_id: 1,\n };\n const response2 = await api.get('piscinas', { params: item });\n let contar1 = 0;\n const piscinasBanco = response2.data;\n\n piscinasBanco.map(async piscina => {\n const ObjPiscina = {\n id: piscina.id,\n nomePiscina: piscina.piscina,\n };\n contar1 += 1;\n setSelectPiscinas(state => [...state, ObjPiscina]);\n if (piscina.id === relatorioCacp[index].piscinaId) {\n setIndex(new IndexPath(contar1));\n }\n });\n\n setVisible(true);\n setRelatorioCacpId(relatorioCacp[index].id);\n setCloro(relatorioCacp[index].cloro.toString());\n setQualidadeAgua(relatorioCacp[index].qualidade_agua.toString());\n setTemperatura(relatorioCacp[index].temperatura.toString());\n setHidrogeron(relatorioCacp[index].hidrogeron.toString());\n setTemperaturaAmbiente(\n relatorioCacp[index].temperatura_ambiente.toString()\n );\n\n setTemperaturaRio(relatorioCacp[index].temperatura_rio.toString());\n setPh(relatorioCacp[index].ph.toString());\n\n setChecked(relatorioCacp[index].status_id === 1);\n }", "function changeStatus() {\n // Grab id and new status from button\n // Attribute data-new-status holds \"true\" for save button and \"false\" for remove button\n const mongoId = $(this).attr('data-id');\n const newStatus = $(this).attr('data-new-status');\n // AJAX call to update article by ID\n $.ajax({\n method: 'PUT',\n url: `/articles/${mongoId}`,\n data: {\n saved: newStatus\n }\n })\n .then(function(data) {\n // If save was successfull, notify user\n if (data.saved === true) {\n // modal here\n console.log('saved');\n } else {\n // error message here\n console.log('something went wrong.');\n }\n // reload page\n location.reload();\n });\n }", "function setNShowStatus(data) {\r\n $('.likesmodel').html(data);\r\n $('.likesmodel').modal('show')\r\n }", "function modificarAuditoria()\n{\n var id = $(\"#idAuditoria\").val()\n console.log(\"id\",id_auditoria)\n sel_normas = \"\";\n $(\"#sel_normas option:selected\").each(function() {\n sel_normas = $(\"#sel_normas\").val();\n });\n\n // VALIDAMOS EL FORMUALARIO\n var res = validarAuditoria()\n //console.log(\"res\",res)\n\n if(result)\n {\n // ABRIMOS MODAL CONFIRMAR CAMBIOS EN AUDITORIA\n $('#modalConfirmarCambiosAuditoria').modal('show')\n // CERRAMOS MODAL MODIFICAR AUDITORIA\n $('#modificarAuditoriaModal').modal('hide');\n }\n else{ swal(\"Error\",\"Ingrese todos los datos\",\"error\") }\n\n}//*/", "function showRulesModal(data)\r\n{\r\n //you can do anything with data, or pass more data to this function. i set this data to modal header for example\r\n\t $('.rulesDeleteByAdmin').attr('href','/rulesDeleteByAdmin?id='+data);\r\n\t$(\"#myRulesModal .rulesDeleteByAdminId\").html(data)\r\n $(\"#myRulesModal\").modal();\r\n}", "function updateStaff(id){\r\n id = $('#modal_id').val();\r\n name = $('#modal_name').val();\r\n gender = $('#modal_gender').val();\r\n uni = $('#modal_uni').val();\r\n room = $('#modal_room').val();\r\n $.post(\"update.act\",{\r\n id:id,\r\n name:name,\r\n gender:gender,\r\n uni:uni,\r\n room:room,\r\n },function(data){\r\n clearChild();\r\n getList();\r\n swal({ type: \"success\", title: \"Update Successfully!\", timer: 1000, showConfirmButton: false });\r\n });\r\n}" ]
[ "0.70432013", "0.67155415", "0.6565725", "0.6510939", "0.64728963", "0.6413299", "0.63912356", "0.6362877", "0.63580984", "0.6355751", "0.6333586", "0.6310187", "0.6285229", "0.62677604", "0.6260749", "0.62368536", "0.62367016", "0.6213442", "0.61973274", "0.6185287", "0.61645913", "0.6160022", "0.61457914", "0.61433524", "0.6137182", "0.61290705", "0.6127737", "0.6116959", "0.6111435", "0.61026794", "0.6093947", "0.60898036", "0.60808086", "0.60502595", "0.60485494", "0.60464066", "0.60417473", "0.60378814", "0.6012714", "0.6007784", "0.6002946", "0.59901685", "0.5987796", "0.59773463", "0.59663653", "0.59659696", "0.59638965", "0.59623396", "0.59606534", "0.59595656", "0.5958163", "0.5953495", "0.59496903", "0.59402364", "0.5938254", "0.59374577", "0.5930026", "0.5927235", "0.5914126", "0.59108084", "0.590761", "0.59059453", "0.5891434", "0.5886481", "0.5881078", "0.5875473", "0.58741385", "0.5873608", "0.58656085", "0.58611286", "0.58606166", "0.58578557", "0.5857141", "0.58475906", "0.58409435", "0.5839602", "0.5835967", "0.5834035", "0.583171", "0.5829915", "0.58296585", "0.58264583", "0.58232486", "0.581376", "0.5809675", "0.5809487", "0.58045846", "0.5802001", "0.5795484", "0.5785773", "0.57853377", "0.57751775", "0.57728636", "0.5772538", "0.577135", "0.5768161", "0.57674265", "0.57667714", "0.57640725", "0.576386" ]
0.65053934
4
function to reset game
function restartGame() { allOpenedCards.length = 0; resetTimer(); resetMoveCount(); resetStar(); resetCards(); toggleModal(); init(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function resetGame() {\n resetClockAndTime();\n resetMoves(); \n resetRatings();\n startGame();\n}", "function resetGame() {\n resetClockAndTime();\n resetMoves();\n resetStars();\n initGame();\n activateCards();\n startGame();\n}", "function reset() {\n //Reset the game\n channelResetGame();\n }", "function resetGame() {\n clearGameCards();\n resetMoves();\n resetTimer();\n}", "function resetGame() {\n resetTimer();\n resetMoves();\n resetStars();\n shuffleDeck();\n resetCards();\n}", "function reset() {\n timesPlayed = -1;\n right = 0;\n wrong = 0;\n startGame ();\n }", "function reset() {\n time = 120;\n gameRun = false;\n }", "function resetGame() {\n counter = 0;\n }", "function resetGame() {\n gBoard = buildBoard();\n gGame.shownCount = 0;\n gGame.isOn = false;\n gLivesCount = 3;\n}", "function resetGame(){\n game_mode='';\n player_sequence=[];\n game_sequence=[];\n player_clicks = 0;\n createGame();\n}", "function resetGame() {\n matched = 0;\n resetTimer();\n resetMoves();\n resetStars();\n resetCards();\n shuffleDeck();\n}", "function resetGame() {\n stopGoodTones();\n stopErrTone();\n clearScore();\n game.genSeq = [];\n game.playerSeq = [];\n game.err = false;\n }", "function resetGame() {\n\tresetClockAndTime();\n\tresetMoves();\n\tresetStars();\n\tshuffleDeck();\n\tresetCards();\n\tmatched = 0;\n\ttoggledCards = [];\n}", "function resetCurrentGame() {\n clearGameCards();\n resetMoves();\n resetTimer();\n startGame();\n resetGameSound();\n}", "function reset(){\n\n theme.play();\n\n gameState = PLAY;\n gameOver.visible = false;\n restart.visible = false;\n \n monsterGroup.destroyEach();\n \n Mario.changeAnimation(\"running\",MarioRunning);\n\n score=0;\n\n monsterGroup.destroyEach();\n\n \n}", "function resetGame() {\n cardShuffle();\n resetBoard();\n cardsInPlay = [];\n cardInPlayId = -1;\n}", "function reset() {\n\t\t/**\n\t\t * TODO: create initial game start page and additional\n\t\t * \tinteractivity when game resets once understand more about\n\t\t * animation\n\t\t */\n\t}", "function resetGame() {\n counter = 0;\n correctCounter = 0;\n incorrectCounter = 0;\n unansweredCounter = 0;\n timer = 30;\n startGame();\n timerHolder();\n }", "function reset(){\r\n gameState = PLAY;\r\n gameOver.visible = false;\r\n // restart.visible = false;\r\n enemiesGroup.destroyEach();\r\n blockGroup.destroyEach();\r\n stars1Group.destroyEach();\r\n stars2Group.destroyEach();\r\n candyGirl.addAnimation(\"running\", candygirl_running);\r\n score = 0;\r\n}", "function gameReset(){\n\t\t\tshowAction(\"RESET!\");\n\t\t\tif(timer) gameEnd();\n\t\t\t$(\".info .timer .sec\").text(0);\n\t\t\t$(\".info .timer .sectext\").hide();\n\t\t\ttime = null;\n\t\t\tcardsleft = settings.cardcnt;\n\t\t\t$(\"#wrap-gameboard li.flip\").removeClass(\"found selected flip\");\n\t\t\t$(\"#wrap-gameboard li.hover\").removeClass(\"hover\");\n\t\t}", "function resetGame() {\n stopPongGame();\n\n // reset positions\n\n // reset scores\n\n // start game again\n}", "function resetGame () { \n\t\t\t\t\t\t\tblueNum = 0;\n\t\t\t\t\t\t greenNum = 0;\n\t\t\t\t\t\t\tredNum = 0;\n\t\t\t\t\t\t\tyellowNum = 0;\n\t\t\t\t\t\t scoreResult=0;\n\t\t\t\t\t\t\ttargetScore = 0;\n\t\t\t\t\t\t\tgetNumber(); // Restart the game and assigns new traget number\n\t\t\t\t\t\t\tscoreBoard(); // Update the score board with new values.\n\t\t}", "function resetGame() {\n \n // reset varaibles\n wrong = 0;\n correct = 0;\n index = -1;\n \n // Update HTML\n clearContent();\n\n // Restart game\n loadQuestion();\n }", "function gameReset() {\n totalScore = 0;\n setupGame();\n }", "function resetGame() {\n account.score = 0;\n account.lines = 0;\n account.level = 0;\n board.reset();\n time = { start: 0, elapsed: 0, level: LEVEL[account.level] };\n}", "function resetGame () {\n resetBricks ();\n store.commit ('setScore', 0);\n store.commit ('setLives', 3);\n resetBoard ();\n draw ();\n}", "function resetGame() {\n userScore = 0;\n computerScore = 0;\n gameSwitch(winningScore);\n}", "function resetGame() {\n window.cancelAnimationFrame(anim_id);\n playing = false;\n score = 0;\n level = 1;\n new_game = true;\n speed = init_speed\n direction = ''\n snake.reset(init_speed);\n fruit.reset();\n }", "resetGame() {\n\t\t//stop game\n\t\tthis.running = false\n\t\tclearInterval(this.loop);\n\n\t\t//set original values\n\t\tthis.aliens = [1, 3, 5, 7, 9, 23, 25, 27, 29, 31];\n\t\tthis.direction = 1;\n\t\tthis.ship = [104, 114, 115, 116];\n\t\tthis.missiles = [];\n\t\tthis.level = 1;\n\t\tthis.currentLevel = 1;\n\t\tthis.speed = 512;\n\t\tthis.score = 0;\n\n\t\tconsole.log(\"Game reset.\");\n\t}", "function resetGame() {\n generateTarget();\n generateNumbers();\n distributeNumbers();\n}", "function gameReset() {\n\t//maybe add gameOverStatus\n\t//initial gameStatus\n\tcounter = 100;\n\tgameOverStatus = false;\n\twindow.location.hash = \"#game-board\";\n\tmessageBoard.innerText = \"Game Start!\\n\" + \"Current Score: \" + counter + \" points\";\n\tshuffleCards();\n}", "function reset() {\n generateLevel(0);\n Resources.setGameOver(false);\n paused = false;\n score = 0;\n lives = 3;\n level = 1;\n changeRows = false;\n pressedKeys = {\n left: false,\n right: false,\n up: false,\n down: false\n };\n }", "function reset() {\n x = 20;\n y = 35;\n level = 1;\n lost = false;\n won =false;\n game = false;\n loseColor =0;\n winColor=1;\n}", "function restart(){\n myGameArea.reset();\n}", "function resetGame() {\n timer.stop();\n startGame();\n}", "function NewGameReset(){\n\t\tconsole.log(\"Game Reset\");\n\n\t\t\n\t\t//Clear Score value and color\n\t\tUtil.one(\"#score\").innerHTML = 0;\n\t\tUtil.one(\"#points\").setAttribute(\"class\", \"grey_background\");\n\t\tUtil.one(\"#score\").setAttribute(\"class\", \"grey_background\");\n\t\tUtil.one(\"#point_text\").setAttribute(\"class\", \"grey_background\");\n\t\t\n\t\t\n\t\t//Reset all event flags\n\t\tcrushing_in_progress = false;\n\t\tshowing_hint = true;\n\t\tlastmove = new Date().getTime();\n\t\t\n\t\t\n}", "function resetGame() {\n newSquares = Array(9).fill(null);\n setSquares(newSquares);\n setXTurn(true);\n }", "function resetGame() {\n\t// Repopulate card deck\n\tcardDeck = masterDeck.map(function(card) { return card }); \n\t// Empty all containers of their elements\n\t$('#game-board').html('')\n\t$('#p1-hand').html(''); \n\t$('#p2-hand').html('');\n\t$('#p1-points').html('');\n\t$('#p2-points').html('');\n\t$('#turn-count').html('');\n\t// Reset board array\n\tgameBoard = [0, 1, 2, 3, 4, 5, 6, 7, 8]; \n\t// Reset turn count\n\tturnCount = 0;\n\t// Reset points\n\tplayer1.points = 5; \n\tplayer2.points = 5;\n}", "function resetGame() {\n gameStart();\n stopTimer();\n resetStars();\n resetCards();\n moves = 0;\n movesText.innerHTML = '0';\n second = 0;\n minute = 0;\n hour = 0;\n clock.innerHTML = '0:00';\n}", "function resetGame() {\n // Position of prey and player will reset\n setupPrey();\n setupPlayer();\n // movement and speed of prey will reset\n movePrey();\n // sound will replay\n nightSound.play();\n // Size and color of player will reset\n playerRadius = 20;\n firegreen = 0;\n // score will reset\n preyEaten = 0;\n // prey speed will reset\n preyMaxSpeed = 4\n // All of this when game is over\n gameOver = false;\n}", "function resetGame() {\n\n gameOver = false;\n state = `menu`;\n\n scoreMoney = 0;\n score = 0;\n\n setup();\n\n // clearInterval of mouse \n if (minigame1) {\n clearInterval(mousePosInterval);\n }\n // Resets the fishies\n if (minigame2) {\n for (let i = 0; i < NUM_FISHIES; i++) {\n let fish = fishies[i];\n fish.reset();\n }\n }\n}", "function resetGame() {\n game.correctAnswers = 0;\n game.incorrectAnswers = 0;\n game.unanswered = 0;\n game.time = 0;\n game.questionIndex = 0;\n clearInterval(game.intervalId);\n clearTimeout(game.timeoutID);\n}", "function resetGame() {\n localStorage.setItem('Game.State', null);\n document.querySelector('.moves').textContent = \"0\";\n \n if (cardDeck) {\n cardDeck.clear();\n }\n \n cardDeck = new CarDeck();\n cardDeck.shuffle();\n bindClickEvent();\n \n cardDeck.cards.forEach(card => {\n card.closeCard()\n card.unmatch()\n });\n \n state = {\n matchingCard: null,\n isMatching: false,\n totalMoves: 0,\n elapsedSeconds: 0,\n isGameOver: false\n }\n \n updateScreenMode(true)\n }", "function resetGame(){\n setWinner(undefined)\n setPlayerBoard(()=> GameBoard('player'))\n setAiBoard(()=> GameBoard('ai'))\n setAI(() => Player('ai'))\n setIsPlayerTurn(true)\n setUpGame()\n }", "function resetGame() {\r\n shuffle(deck);\r\n gameStart();\r\n dealerarea.innerHTML = \"\";\r\n playerarea.innerHTML = \"\";\r\n winnerarea.innerHTML = \"\";\r\n playerHand.firsttotal = 0;\r\n dealerHand.firsttotal = 0;\r\n playerHand.secondtotal = 0;\r\n dealerHand.secondtotal = 0;\r\n }", "function resetGame() {\n if (dinoStegosaurus.foodEaten + dinoTriceratops.foodEaten >= 20) {\n tornado.reset();\n }\n if (dinoStegosaurus.foodEaten + dinoTriceratops.foodEaten >= 30) {\n fire.reset();\n }\n if (dinoStegosaurus.foodEaten + dinoTriceratops.foodEaten >= 40) {\n meteor.reset();\n }\n foodLeaves.reset();\n foodBerries.reset();\n foodPlant.reset();\n dinoStegosaurus.reset();\n dinoTriceratops.reset();\n gameOverScreen = false;\n titleScreen = true;\n instructionsScreen = false;\n gameWon = false;\n}", "function resetGame() {\n\n\t// show it (when page loads the bugs are hidden)\n\t$(\".bug-bg\").css({\n\t\t\"display\": \"block\"\n\t});\n\n\t// reset state vars\n\tcurrentHighestIndex = 0;\n\tnumberErrors = 0;\n\n\tplaySound('#resetSound');\n\n\t// reset visuals\n\t$(\"#currentHighestIndex\").html(currentHighestIndex);\n\t$(\"#numberErrors\").html(numberErrors);\n\t// remove all boxes\n\t$(\".hidden-btn\").removeClass(\"correct\").removeClass(\"incorrect\");\n}", "function reset(){\n score=0;\n gameTime=0;\n updateScore();\n}", "function gameReset() {\n\t\tquestionCounter = 0;\n\t\tcorrectGuesses = 0;\n\t\tincorrectGuesses = 0;\n\t}", "function gameReset() {\n\t\tquestionCounter = 0;\n\t\tcorrectGuesses = 0;\n\t\tincorrectGuesses = 0;\n\t}", "function gameReset() {\n\t\tquestionCounter = 0;\n\t\tcorrectGuesses = 0;\n\t\tincorrectGuesses = 0;\n\t}", "function gameReset() {\n\t\tquestionCounter = 0;\n\t\tcorrectGuesses = 0;\n\t\tincorrectGuesses = 0;\n\t}", "function resetGame() {\n location.reload();\n }", "function resetGame () {\n clearBoard();\n window.location.reload();\n}", "function resetGameState() {\n\t\tgameOngoing = true;\n\t\tcurrentPlayer = player1;\n\t}", "function reset() {\n resetGame(gameId);\n updateCharList([]);\n updateChar(\"\");\n }", "function reset() {\n clear();\n initialize(gameData);\n }", "function resetGame() {\n clearGame();\n levelSpace.innerHTML = \"Press Start/Stop to Begin\";\n}", "function resetGame() {\n\tquestionCounter = 0;\n\tcorrectTally = 0;\n\tincorrectTally = 0;\n\tunansweredTally = 0;\n\tcounter = 30;\n\tgenerateHTML();\n\ttimerWrapper();\n}", "function gameReset() {\n hideWinPanel();\n timerStop();\n timeInSeconds = 0;\n hours = 0;\n minutes = 0;\n updateTimerDisplay(0);\n movesCounter = 0;\n movesCounterDisplay(movesCounter);\n cardsMatched = 0;\n shuffle(cards);\n setupCardDeckDisplay(deckElement, cards);\n resetStarsDisplay();\n cardElements = deckElement.getElementsByClassName('card');\n cardDeckFlashDisplay(cardElements);\n timerStart();\n}", "function reset() {\n\t$snake.off(\"keydown\");\n\tdeleteSnake();\n\t\n\tmakeSnake();\n\tupdateScores();\n\tassignKeys();\n\tplayGame();\n}", "function resetGame(){\n console.log(gamePaused);\n gamePaused=false;\n console.log(gamePaused);\n if(!gamePaused && !stopGame){\n removeModal(); \n playGame();\n } else{\n removeModal();\n addCirclesToHoverBar();\n //clearing all dots of game board\n clearGameBoard();\n clearMessageBoard(); \n changeMessageBoardBG(\"none\"); \n stopGame=false;\n count=30;\n startGame();\n } \n}", "function resetGame() {\n // reset the global variables\n cardsCollected = [];\n DeckOfCards = [];\n cardOneElement = null;\n cardTwoElement = null;\n startTime = null;\n currentTurn = 0;\n gameWon = false;\n seconds = 0;\n moves = 0;\n stars = 3;\n}", "function resetGame() {\r\n\t\r\n\t\tfor(var i=0; i<board.length; i++) {\r\n\t\t\tboard[i].innerHTML = \" \";\r\n\t\t\tboard[i].style.color = 'navy';\r\n\t\t\tboard[i].style.backgroundColor = 'transparent';\r\n\t\t}\r\n\t\tgameOver = false;\r\n\t\tempty = 9;\r\n\t\tsetMessage(player + \" gets to start.\");\r\n\t\tsetMessage2(\"Go!\");\r\n\t\tconsole.log(\"visited resetGame\");\r\n\t}", "function resetGame() {\n moves = 0;\n match_found = 0;\n $('#deck').empty();\n $('#stars').empty();\n $('#game-deck')[0].style.display = \"\";\n $('#sucess-result')[0].style.display = \"none\";\n game_started = false;\n timer.stop();\n $('#timer').html(\"00:00:00\");\n playGame();\n}", "function resetGame() {\n game.player1.gameScore = 0;\n game.player2.gameScore = 0;\n gameScoreIndex++;\n pointScoreIndex = 0; //for after looking at matchStats\n // gameScoreIndex = 0;\n // game.gameScoreCollection.push(pushArr);\n if (game.startSer === 'player1') {\n swal(game.player2.name + \" serves first\");\n game.startSer = 'player2';\n game.player1.curSer = false;\n game.player2.curSer = true;\n }else if (game.startSer === 'player2'){\n swal(game.player1.name + \" serves first\");\n game.startSer = 'player1';\n game.player1.curSer = true;\n game.player2.curSer = false;\n }\n }", "function resetGame() {\n\t$(\"#gameOver\").fadeOut();\n\ttotal = 0;\n\tupdateTotal(0);\n\ttotalEmptyCells = 16;\n\tgrid = getGrid();\n\tgridSpans = getSpanGrid();\n\t$(gridSpans).each(function(i,r) { $(r).each(function(i,c) { $(c).parent().css(\"background-color\", \"#D1E3EB\"); $(c).text(\"\"); }); });\n\tsetRandCell(get2or4());\n\tsetRandCell(get2or4());\n}", "function resetGame(){\n startingLevel = 1;\n startingScore = 0;\n startingLives = 5;\n\n changeScore(startingLevel, startingScore);\n changeLevel(startingLevel);\n}", "function reset() {\n // make a new game object\n myGame = new Game('X');\n // update the view\n updateView();\n document.getElementById(\"status\").innerHTML = \"Start Game!\";\n document.getElementById(\"reset-btn\").innerHTML = \"Reset Game\";\n}", "function reset() {\n status.gameArr = [];\n status.level = 0;\n topLeft.off();\n topRight.off();\n bottomLeft.off();\n bottomRight.off();\n status.running = false;\n level.html(\"0\").css(\"color\", 'red');\n start.html('<i class=\"fa fa-play\"></i>').css('color', 'red');\n}", "function resetGame() {\n\tcards = [];\n\tcardsDisplayed = 0;\n\tclearTimeout(timer);\n\ttoggleNumbers();\n\t$('#timer').html('30');\n\t$('.card').each(function() {\n\t\t$(this).html('&nbsp;');\n\t\t\n\t}); // end each\n\t$('#total').html('&nbsp;');\n\t$('#answer').text('');\n\t$('.card').each(function() {\n\t\tif ($(this).hasClass('disabled')) {\n\t\t\t$(this).removeClass('disabled');\n\t\t}\n\t\tif ($(this).hasClass('pause')) {\n\t\t\t$(this).removeClass('pause');\n\t\t}\n\t}); // end each\n\t$('#variables').html('');\n\tuserVariables = [];\n\t$('#notice').fadeOut();\n\t\n}", "function resetme(){\n\tinitiateBoard();\n\tmode=0;\n\tdisplay(0);\n}", "function resetGame() {\n randomizer();\n attempt = 0;\n $(\".showTarget\").text(target);\n $(\".showAttempt\").text(attempt);\n $(\".showWins\").text(wins);\n $(\".showLosses\").text(losses);\n }", "function resetGame() {\n // reset game by going through buttons\n for (var i=0; i < buttons.length; i++) {\n buttons[i].style.backgroundColor = ''; // change color back to original\n buttons[i].innerHTML = ''; // delete x's and o's\n }\n gameover = false;\n }", "function resetGame() {\n // Clear the main boxes and the minimap boxes\n for(var rIndex = 0; rIndex < NUM_ROWS; rIndex++) {\n for(var cIndex = 0; cIndex < NUM_COLS; cIndex++) {\n // Clear main boxes\n boxes[rIndex][cIndex].classList.remove(xClass, oClass);\n boxes[rIndex][cIndex].textContent = \"\";\n // Clear minimap boxes\n miniboxes[rIndex][cIndex].classList.remove(xClass, oClass);\n miniboxes[rIndex][cIndex].textContent = \"\";\n }\n }\n\n // Hide end game text\n $(victoryText).hide();\n\n // Reset number of filled boxes\n boxCount = 0;\n\n // Start the game again\n gameOver = false;\n }", "resetGame() {\n // clear game seeds\n this.gameSeed = '';\n this.currentString = '';\n\n if (this.gameStarted) {\n this.toggleGameStarted();\n this.flashCount();\n document.getElementById('simon-points').innerHTML = '--';\n // delayed set to default in-case point flashing causes issues\n setTimeout(() => { document.getElementById('simon-points').innerHTML = '--'; }, 525);\n this.flashTimer = setInterval(() => { this.flashCount(); }, 1000);\n }\n }", "function resetGame(){\t\t\n\thasStarted=false;\n\tinput=-1;\n\tsequence=[];\n\tlevel=0;\n\tdisplay(\"--\");\n\tsetTimeout(function(){\n\t\t\t$(\"#board div\").removeClass(\"clickable\");\n\t\t},500);\t\n}", "function resetGame() {\n\tusedQuestions = [];\n\ttime = 20;\n\tscore = 0;\n\twrongAnswers = 0;\n\tnoAnswer = 0;\n\t$(\"#results\").empty();\n\tsetGame();\n}", "function actionOnResetClick () {\n gameRestart();\n }", "function gameReset() {\n questionCounter = 0;\n correctGuesses = 0;\n incorrectGuesses = 0;\n }", "function gameReset() {\n questionCounter = 0;\n correctGuesses = 0;\n incorrectGuesses = 0;\n }", "function resetGame() {\n history = [];\n guessesCount = -1;\n level = 0;\n $('.level').text(level);\n }", "function gameReset() {\n questionCounter = 0;\n correctGuesses = 0;\n incorrectGuesses = 0;\n }", "function resetGame() {\n deck.innerHTML = '';\n openCards = [];\n matchedCards = [];\n moves = 0;\n clickCounter = 0;\n clearInterval(timer);\n seconds = 0;\n minutes = 0;\n timer = 0;\n time.textContent = '00:00';\n generateStar(starsLost);\n starsLost = 0;\n initGame();\n}", "function gameReset() {\r\n\tgameState.score = 0;\r\n\t$(\"#score\").html(\"Points: <br>\"+gameState.score);\r\n\t$(\"#wins\").html(\"Wins: \"+gameState.wins);\r\n\t$(\"#losses\").html(\"Losses: \"+gameState.losses);\r\n\tgameState.match = getRandom(19,120);\r\n\t$(\"#randomNum\").html(\"Match: <br>\"+gameState.match);\r\n\tgameInit()\r\n}", "resetGame() {\n this.initGrid();\n this.setDefaultSeeds();\n this.iteration = 0;\n }", "function resetGame() {\n location.reload()\n}", "resetGame() {\n this.winner = null;\n this.grid.resetGrid();\n }", "function resetGame(){\n if (!win || win){\n clearWinOrLoseScreen()\n }\n BGM.currentTime = 0\n BGM.play()\n // BGM.volume = 0.2\n win = null\n cells[enemyA.position].classList.remove('enemy1')\n cells[enemyB.position].classList.remove('enemy2')\n cells[enemyC.position].classList.remove('enemy3')\n cells[enemyD.position].classList.remove('enemy4')\n clearInterval(gametimer)\n clearInterval(berryTimer)\n gameOver = false\n playerScore = 0\n scoreboard.innerHTML = playerScore\n createMaze()\n startTimer()\n startBerryTimer()\n cookiesRemaining = 212\n playerPosition = 487\n cells[playerPosition].classList.add('sprite')\n enemyA.position = 337\n cells[enemyA.position].classList.add('enemy1')\n enemyB.position = 335\n cells[enemyB.position].classList.add('enemy2')\n enemyC.position = 339\n cells[enemyC.position].classList.add('enemy3')\n enemyD.position = 338\n cells[enemyD.position].classList.add('enemy4')\n\n }", "function resetGameState() {\r\n\r\n // Reset difficulty and enemy speed.\r\n increaseDifficulty.difficulty = \"start\";\r\n Enemy.v = 4;\r\n toggleEnemySpawner.spawnRate = 2000;\r\n\r\n // Clear the list of game objects.\r\n observers = [];\r\n\r\n // Reset player.\r\n player = new Player();\r\n\r\n // Reset game state data.\r\n time = 90;\r\n document.getElementById(\"time-numeric\").innerHTML = time;\r\n Player.score = 100;\r\n document.getElementById(\"score-numeric\").innerHTML = Player.score;\r\n timeAt100 = 0;\r\n}", "function gameReset () {\n questionCounter = 0;\n correctGuesses = 0;\n incorrectGuesses = 0;\n }", "resetGame() {\n\t\tthis.App.setGetters.setGameProperty('timer', this.App.game.settings.gameLength);\n\t\tthis.App.setGetters.setPlayersProperty('correct', false);\t\t\n\t\tthis.App.setGetters.setGameStoreProperty('paths', {});\n\t\tthis.App.setGetters.setGameStoreProperty('chatLog', {});\n\t\tthis.App.clientComms.emitToAllSockets('reset');\n\t\tthis.App.clientComms.emitToAllSockets('puzzle', []);\n\t}", "function resetGame() {\n toggleMenu(Menu.MAIN);\n $('#statsOutput').hide();\n $('#ammoBarsContainer').hide();\n scene.stopMusic();\n renderer.clear(false, true, true);\n scene = new TheScene(renderer.domElement);\n}", "function resetGame() {\n for (let i = 0; i < kids.length; i++) {\n kids[i].reset();\n player.reset();\n isGameOver = false;\n }\n}", "function resetGame(){\n\t\n\tlocation.reload(); \n\t\n}", "function resetGame() {\n\t\ttokbox.forceUnpublish();\n\t\tfor(x = 1; x < 21; x++) {\n\t\t\t$(\"#score_\"+x).css(\"background-color\", \"transparent\");\n\t\t\tif(x < 5) {\n\t\t\t\t$(\"#solution_\"+ (x - 1) + \"_right\").html(\"\");\n\t\t\t\t$(\"#solution_\" + (x - 1) + \"_container\").css(\"background-color\", \"#BFBB11\").css(\"border-color\", \"#730046\").css(\"color\", \"black\");\n\t\t\t}\n\t\t\t$(\"#help_container_computer_normal\").fadeIn('slow');\n\t\t\t$(\"#help_container_audience_normal\").fadeIn('slow');\n\t\t\t$(\"#help_container_phone_normal\").fadeIn('slow');\n\t\t\tif(user_type == 'host') {\n\t\t\t\t$(\"#correct_answer\").html(\"\");\n\t\t\t}\n\t\t\tif(user_type == 'user') {\n\t\t\t\t$(\".question_holder\").unbind('click');\n\t\t\t\t$(\"#help_container_phone_normal\").unbind('click');\n\t\t\t\t$(\"#help_container_audience_normal\").unbind('click');\n\t\t\t\t$(\"#help_container_computer_normal\").unbind('click');\n\t\t\t\tuser_type = \"viewer\";\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif(user_type == 'host') {\n\t\t\tquestion_counter = 0;\n\t\t\ttrivia_questions = [];\n\t\t\tdisplay_question = [];\n\t\t\tloadQuestions(MAX_QUESTIONS);\n\t\t}\n\t\t$(\"#actual_question\").html(\"\");\n\t\t$(\"#game_recap_container\").fadeOut('slow');\n\t}", "function reset() {\n gameMode = modeSelector.options[ modeSelector.selectedIndex ].value;\n gameDifficulty = difficultySelector.options[ difficultySelector.selectedIndex ].value;\n if ( gameDifficulty === \"Easy\" ) {\n playGame( 3 );\n } else {\n playGame( 6 );\n }\n}", "function resetGame(){\n\t\t\n\t\tguessesLeft = 10;\n\t\tguessesMade = [];\n\n\t}//END resetGame()", "function resetGame() {\n\t$('.box').removeClass('played');\n\t$('.box').removeClass('U-turn');\n\t$('.box').removeClass('I-turn');\n\t$('.box').html('');\n\t$('.box').addClass('free');\n\tisPlayerOne = true;\n\tisPlayerTwo = false;\n\n}", "function resetGame() {\n rights = 0;\n wrongs = 0;\n timeLeft = 11;\n questionIndex = undefined;\n currentQ = undefined;\n correctOption = undefined;\n gameInProgress = false;\n intervalId = undefined;\n questionsArray = [];\n pauseTime();\n $(\"#questionText\").empty();\n $(\"#answerOptions\").empty();\n $(\"#video\").empty();\n $(\"#gameResults\").empty();\n $(\"#gameResults\").css(\"display\", \"none\");\n $(\"#resetGame\").css(\"display\", \"none\");\n $(\"#bonusQ\").css(\"display\", \"none\");\n $(\"#gameElements\").css(\"display\", \"none\");\n $(\"#startGame\").css(\"display\", \"block\");\n}", "function resetGame() {\n deck.innerHTML = '';\n tally.textContent = 0;\n seconds = 0;\n minutes = 0;\n moves = 0;\n stars.innerHTML = '';\n pairedCards = [];\n setupDeck();\n modal.style.display = 'none';\n}" ]
[ "0.8925137", "0.8868678", "0.8839611", "0.88265324", "0.87974507", "0.87514013", "0.8715469", "0.8713044", "0.8680245", "0.8623561", "0.8620319", "0.8616942", "0.85936975", "0.8580226", "0.8546222", "0.85140723", "0.85026693", "0.84723043", "0.84667", "0.8462359", "0.8455414", "0.8451833", "0.8442891", "0.8424668", "0.84143925", "0.8388871", "0.83775264", "0.83762723", "0.83579504", "0.8341541", "0.83314526", "0.8324106", "0.8315676", "0.83126473", "0.8303249", "0.830314", "0.82950765", "0.8291193", "0.8289443", "0.82878953", "0.82870626", "0.82855386", "0.82538867", "0.8250463", "0.82480896", "0.8247941", "0.82466596", "0.8240372", "0.8229444", "0.8229444", "0.8229444", "0.8229444", "0.82265186", "0.82251513", "0.82157415", "0.82132614", "0.8193146", "0.81906617", "0.8189592", "0.8185963", "0.8183939", "0.8181182", "0.8166817", "0.81579626", "0.81529856", "0.8146057", "0.8141091", "0.8136706", "0.813504", "0.8134281", "0.81328386", "0.8132477", "0.8131344", "0.8129234", "0.8127255", "0.81235284", "0.8121095", "0.81193054", "0.81135315", "0.81115264", "0.81115264", "0.81084144", "0.81035", "0.809848", "0.8096778", "0.8093534", "0.8093221", "0.8089283", "0.808705", "0.8084159", "0.8077102", "0.80747557", "0.80616146", "0.8061053", "0.8056562", "0.80477357", "0.80476534", "0.8042496", "0.8040736", "0.80404156", "0.8036304" ]
0.0
-1
function to stop the game once the user win and toggle the modal to show result
function gameOver() { stopTimer(); updateModal(); toggleModal(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function winGame() {\n stopTimer();\n toggleModal();\n}", "function continueGame() {\n // clear modal\n $(\".modal\").removeClass(\"bg-modal\");\n $(\".modal-inner\").removeClass(\"modal-content\").html(\"\");\n // has endgame condition been reached\n if (selectedGlyphs.length === numQuestionsPerGame) {\n endCondition_gameOver();\n } else {\n selectGlyph();\n }\n }", "function wonGame(){\n stopClock();\n modalData();\n $('.modal_background').removeClass('hide');\n}", "function gameWonMessage() {\n $('.play-again').click(gameStart);\n $('#gameWon').modal(\"show\");\n}", "checkIfWon() {\n let func = () => {\n this.reset();\n }\n if (this.y < 0) {\n this.gameWon = true;\n document.querySelector('.modal').style.display = 'block';\n document.querySelector('.modal-wnd').style.display = 'block';\n document.getElementById('replay-btn').addEventListener('click', function() {\n document.querySelector('.modal').style.display = 'none';\n document.querySelector('.modal-wnd').style.display = 'none';\n func();\n });\n }\n }", "function restartGameFromModal() {\n modal.style.display = \"none\";\n newGame();\n}", "function gameStatus() {\n\tpairsToGuess--;\n\tif (pairsToGuess == 0) {\n\t\ttoStopWatch(); //stop the stopwatch\n\t\tsetTimeout(function() { //display result popup\n\t\t\tdisplayResult(); //to put results to the modal\n \t\tmodalResult(); // to show modal with results\n \t\t}, 500); \n\t} else {\n\t\t\n\t}\n}", "function triggerModal () {\n modal.style.display = 'block';\n\n if (turn !== 1) {\n winner.innerHTML = 'Player 1 Wins!';\n console.log ('Player 1 Wins!');\n }\n if (turn === 1) {\n winner.innerHTML = 'Player 2 Wins!';\n console.log ('Player 2 Wins!');\n }\n }", "function endGame() {\n stopMusic();\n win.play();\n modal.style.display = \"block\";\n modalContent.innerHTML = `<h1 class=\"centered\">Congratulation!</h1><h3 class=\"centered\">You have completed the game!</h3><h3 class=\"centered\">Points scored: ${player.score}</h3><h3 class=\"centered\">Lives saved: ${player.lives}</h3><h3 class=\"centered\">Final Score: ${player.score*player.lives}</h3><button class=\"restart button centered\">RESTART!</button>`;\n}", "function gameDraw(){\n $(\"#winMsg\").html(\"Game is a draw!! Play Again!\");\n $(\"#winModal\").modal(\"show\");\n }", "function checkStatus() {\n if (matchPairCounter == 8) {\n timer.timer('pause');\n $('#totalscore').text(`You finished the game in ${timer.data('seconds')} seconds with ${movesCounter} moves and ${starsCounter} star(s)`);\n $('#myModal').modal({backdrop: 'static', keyboard: false});\n \n }\n}", "function continueGame() {\n\tGAME_COMPLETE = false;\n\tGAME_OVER = false;\n\tGAME_CONTINUE = true;\n\t$('#winner').hide();\n}", "function checkForWin() {\n if (score > score2){\n $('#player1WinModal').show();\n $('#player1WinModalClose').click(function(){\n $('#player1WinModal').hide();\n });\n } else if (score < score2){\n $('#player2WinModal').show();\n $('#player2WinModalClose').click(function(){\n $('#player2WinModal').hide();\n });\n } else if (score = score2) {\n $('#drawModal').show();\n $('#drawModalClose').click(function(){\n $('#drawModal').hide();\n });\n }\n }", "function winGame() {\n if (matched.length === 8) { \n stopTimer();\n toggleModal();\n } \n}", "checkIfWin() {\n if (this.score === 10) {\n this.started = false;\n allEnemies = [];\n showWinModal();\n }\n }", "function showGameResult () {\n if ($( \".flippable\" ).length === 2 && $('.show').length === 12) { // we pop up a winner modal\n $('.modal-body').html(\n `\n <div class=\"score-item\">Your Time: ${$('.Timer').text()}</div>\n <div class=\"score-item\">Your Score: ${$('.stars').html()}<div>\n `\n );\n $('#endGameModalLabel').text('You Win!');\n $('#endGameModal').modal('show');\n clearInterval(timer);\n resetBoard();\n } else if (moves === 0) { // else we pop up a loser modal\n $('.modal-body').html(\n `\n <div class=\"score-item\">Your Time: ${$('.Timer').text()}</div>\n `\n );\n $('#endGameModalLabel').text('You Lose!');\n $('#endGameModal').modal('show');\n clearInterval(timer);\n resetBoard();\n } else { // not the end of the game!\n return;\n }\n}", "function endGame() {\n\t$(\"#lossModal\").modal({backdrop: 'static', keyboard: false});\n\t$(\"#lossModal\").modal('show');\n\t$(\"#name-loss\").text(playerName);\n\t$(\"#poke-number-caught\").text(winCount);\n\t$(\"#score-span\").text(score);\n}", "function gameOver() {\n stopMusic();\n loose.play();\n modal.style.display = \"block\";\n modalContent.innerHTML = `<h1 class=\"centered\">Game Over!</h1><h3 class=\"centered\">You have lost all lives and collected ${player.score} points!</h3><button class=\"restart button centered\">RESTART!</button>`;\n}", "function checkWin() {\n\t\tif (pairsRemain === 0) {\n\t\t\t\ttimerOff();\n\t\t\t\topenModal();\n\t\t};\n}", "function winOrLose (result) {\n const overlayTitle = document.querySelector('.title');\n const startButton = document.querySelector('.btn__reset');\n\n overlay.style.display = '';\n overlay.className = result;\n overlayTitle.innerHTML = `you ${result} the game`;\n startButton.innerHTML = 'Start New Game'\n\n // Reset the game after win or lose\n resetGame();\n}", "function gameOver() {\n stopClock();\n writeModalStats();\n toggleModal();\n}", "function modalStart(e) {\n e.preventDefault();\n document.querySelector('p.numbers span').textContent = game.numbers = 0;\n document.querySelector('p.wins span').textContent = game.wins = 0;\n document.querySelector('p.losses span').textContent = game.losses = 0;\n document.querySelector('p.draws span').textContent = game.draws = 0;\n document.querySelector('[data-summary=\"who-win\"]').textContent = '';\n document.querySelector('[data-summary=\"your-choice\"]').textContent = '';\n document.querySelector('[data-summary=\"ai-choice\"]').textContent = '';\n if (!isNaN(params.playerName = document.querySelector('input[name=\"firstname\"]').value)){\n return alert('You Have To Give Your Name!!!')\n };\n params.numberRounds = document.querySelector('input[name=\"rounds\"]').value;\n infoRounds.innerHTML = `${params.numberRounds} Rounds to the End of the Game`\n params.play = true;\n document.querySelector('#modal-overlay').classList.remove('show');\n choice.innerHTML = params.playerName.toUpperCase();\n}", "function winGame() {\n if (matchList === 8) {\n pause();\n openModal();\n timerModal.innerText = `Final time is: ${min}:${zeroPlaceholder}${second}`;\n playTimer.style.display = 'none';\n gameStarted = false;\n }\n if (moves < 20 && moves > 12) {\n starCount[5].style.display = 'none';\n } else if (moves > 20) {\n starCount[4].style.display = 'none';\n }\n countModal.innerHTML = moves;\n}", "function gameWon() {\n modal();\n const playAgain = document.querySelector('.button');\n playAgain.addEventListener('click', function() {\n restart();\n const modal = document.getElementById('endGame');\n modal.classList.remove('appear');\n \n }); \n \n}", "function win() {\n if (cardList.length === liMatch.length) {\n stopTimer();\n displayModal();\n }\n}", "function replayGame() {\n resetGame();\n toggleModal();\n}", "function replayGame() {\n resetGame();\n toggleModal();\n}", "function winOrLoseScreen(){\n if (!win){\n GameOverGraphic()\n BGM.pause()\n } else {\n youWinGraphic()\n BGM.pause()\n }\n }", "function winner(){\n gameMode = false;\n $('.pop-up').html(curPlayer + \" is victorious! <br><br> Press 'New Game' to play again\");\n $('.pop-up').css(\"visibility\", \"visible\");\n}", "function victoryModal(typeOfVictory) {\r\n if (typeOfVictory === \"draw\") {\r\n $(\"#game\").css(\"display\", \"none\");\r\n $(\"#draw\").css(\"display\", \"block\");\r\n let counter = 5;\r\n let int3 = setInterval(() => {\r\n if (counter === 1) {\r\n\r\n $(\"#draw\").fadeOut(\"slow\", () => {\r\n $(\"#modal\").css(\"display\", \"block\");\r\n $(\"#draw\").css(\"display\", \"none\");\r\n });\r\n }\r\n else if (counter === 0) {\r\n clearInterval(int3);\r\n }\r\n $(\"#countdown\").text(counter);\r\n counter--;\r\n }, 1000);\r\n }\r\n else if (typeOfVictory === \"win\") {\r\n $(\"#displayWinner\").text(\"Winner is: \" + winner);\r\n $(\"#currentPlayer\").css(\"display\", \"none\");\r\n $(\"#game\").css(\"margin-top\", \"35px\");\r\n\r\n let counter = 5;\r\n let int4 = setInterval(() => {\r\n if (counter === 1) {\r\n $(\"#game\").fadeOut(\"slow\", () => {\r\n $(\"#modal\").css(\"display\", \"block\");\r\n $(\"#game\").css(\"display\", \"none\");\r\n });\r\n }\r\n else if (counter === 0) {\r\n clearInterval(int4);\r\n }\r\n $(\"#restartCounter\").css(\"display\", \"block\");\r\n $(\"#restartCounter\").text(\"Restarting in : \" + counter);\r\n counter--;\r\n }, 1000);\r\n }\r\n }", "function playAgain() {\n modal.classList.remove(\"show\");\n restartGame();\n}", "restartGame() {\n score=5;\n $('#restart-button').on('click', () => {\n $('.modal').hide();\n $('.game-container').css('display', 'block');\n $('.mushroom-container').css('display', 'block');\n setUpRound();\n $('#restart-button').off();\n });\n }", "function endScreen(){\n toggleModalOn();\n var newGameSelector = document.getElementById('modal-new-game');\n var modalCancel = document.getElementById('modal-cancel');\n \n newGameSelector.addEventListener('click', event=>{\n toggleModalOff();\n newGame();\n })\n \n modalCancel.addEventListener('click', event =>{\n toggleModalOff();\n })\n \n}", "function youWon() {\n //stop the timer\n clearInterval(interval);\n //elaborate the score\n score();\n const modal = document.querySelector('.modal');\n //show the score\n modal.style.display = 'block';\n tryAgain.addEventListener('click', function () {\n restart();\n modal.style.display = 'none';\n });\n}", "function playAgain(){\n modal.classList.remove(\"show\");\n resetGame();\n}", "function UserContinue() {\n //close window\n Modal.closeLevelCompleteWindow();\n //exit current level\n continueGame();\n}", "function showModal(){\n gamePaused=true;\n let container=$QS('.gameDisplayDiv');\n let modal=$CESC('div', 'msg-modal');\n \n let h2=$CESC('h2', 'modal-heading');\n h2.innerText='pause';\n //continue game , restart, quit game\n let continueBtn=$CESC('button', 'modal-btn continue-btn');\n continueBtn.innerText='continue game';\n continueBtn.onclick=continueGame;\n\n let resetBtn=$CESC('button', 'modal-btn reset-btn');\n resetBtn.innerText='Restart';\n resetBtn.onclick=resetGame;\n\n let quitBtn=$CESC('button', 'modal-btn quit-btn');\n quitBtn.innerText='quit btn';\n quitBtn.onclick=goToHomePage;\n \n $ACP(modal, h2);\n $ACP(modal, continueBtn);\n $ACP(modal, resetBtn);\n $ACP(modal, quitBtn);\n\n $ACP(container, modal);\n}", "showGameWonModal() {\n let modalView = document.getElementById(\"modal-container-view\");\n let modalCloseBtn = document.getElementById(\"modal-close-btn\");\n modalView.style.display = \"flex\";\n\n // Allows user to dimiss the modal message\n modalCloseBtn.onclick = function () {\n modalView.style.display = \"none\";\n }\n\n // When the user clicks anywhere outside of the modal, close it\n window.onclick = function (event) {\n if (event.target == modalView) {\n modalView.style.display = \"none\";\n }\n }\n console.log(\"game won!\");\n }", "function continueGame(){\n removeModal();\n\n if(stopGame){\n addCirclesToHoverBar();\n //clearing all dots of game board\n clearGameBoard();\n clearMessageBoard(); \n changeMessageBoardBG(\"none\"); \n stopGame=false;\n count=30;\n startGame();\n }\n\n if(gamePaused){\n gamePaused=false;\n playGame();\n }\n}", "toggleDialog() {\n document.getElementById('gameOver').classList.toggle('is-visible');\n stopInterval();\n }", "function gameOver() {\n clearInterval(timer);\n getTimeClock();\n setTimeout(function () {\n $(\"#winModal\").toggleClass(\"hidden animated bounceIn\");\n }, 500);\n }", "function gameOver() {\n\tstopClock();\n\twriteModalStats();\n\ttoggleModal();\n}", "function displayWinner(name) {\n const winnerModal = document.getElementById(\"winnerModal\");\n const restartGame = document.getElementById(\"restartGame\");\n document.getElementById('winner').innerHTML = name;\n gameStarted = false;\n winnerModal.style.display = \"block\";\n restartGame.onclick = (e) => {\n e.preventDefault();\n player1.score = 0;\n player2.score = 0;\n newGame();\n }\n}", "function gameWinPopup(){\n var modalGameWin = document.getElementById('modalGameWin');\n var rePlay = document.getElementById(\"replayBtnWin\");\n var img = document.querySelectorAll(\"img\")[0];\n\n modalGameWin.style.display = \"block\";\n $(\"#scoreWin\").html(\"Final score: \" + finalScore);\n // When the user clicks button replay, close it\n rePlay.onclick = function() {\n window.location.assign(\"../start.html\");\n }\n }", "function gameOver() {\n stopTimer();\n toggleModal();\n writeModalStats();\n}", "function replayGame() {\n\tresetGame();\n\ttoggleModal();\n}", "function replayGame() {\n\tresetGame();\n\ttoggleModal();\n}", "function showModal(modalForWin) {\n var elModal = document.querySelector(\".modal\");\n elModal.style.display = 'block'\n var resString = (modalForWin) ? `Well Done ` : 'Try again..'\n elModal.innerHTML = `${resString} <button onclick=\"init()\">Play again</button>`\n}", "function nameModuleClose() {\n winnerDeclared = document.querySelector('.declaredWinner');\n pvpModal.style.cssText = \"display: none;\";\n let numOne = first.value;\n let numTwo = second.value;\n firstPlayer.winner(numOne);\n computer.winner(numTwo);\n \n // determines which parts of code run\n GBModule.power('on');\n firstPlayer.power('on');\n computer.power('on');\n AIGame.switch('off');\n winnerDeclared.style.cssText = \"display: none;\";\n\n }", "function show_win(){\n alert(' You Win !!');\n game_end();\n}", "function gameOver() {\n\tstopClock();\n\twriteModalStats();\n\ttoggleModal();\n\tmatched=0;\n}", "function isGameOver() {\n if (matchedCards.length === symbols.length) {\n //stop timer\n clearInterval(interval);\n \n //popup congratulation message\n const modal = document.querySelector('.modal');\n const playAgain = document.querySelector('.play-again');\n modal.style.display = \"block\";\n playAgain.addEventListener(\"click\", function() {\n modal.style.display = \"none\";\n\n //call restartGame function\n restartGame();\n }); \n }\n}", "function checkWin() {\n if (matchFound === 8) {\n $(\"#runner\").css(\"display\",\"none\")\n $(\".win-modal\").css(\"display\",\"block\");\n $(\".win-modal .stars\").text(stars);\n $(\".win-modal .moves\").text(moves);\n $(\".win-modal .runner\").text(minute + \":\" + second);\n }\n }", "function winCheck() {\n\tif(matches === 8){\n\t\ttimerEnd();\n\t\taddRating(moves);\n\t\tpopUpModal();\n\t\tpopUp.classList.remove('display-none');\n\t}\n}", "function showEndModal(showType) {\n // CREDIT - Code for showing modal was taken from W3 Schools and adapted to fit this project\n let modal = document.getElementsByClassName(\"end-modal-background\")[0];\n let closeSpan = document.getElementsByClassName(\"end-close\")[0];\n modal.style.display = \"flex\";\n\n closeSpan.onclick = function() {\n modal.style.display = \"none\";\n\n if (showType === \"end\") {\n endGame();\n }\n };\n\n window.onclick = function(event) {\n if (event.target === modal) {\n modal.style.display = \"none\";\n\n if (showType === \"end\") {\n endGame();\n }\n }\n };\n\n if (showType === \"quit\") {\n document.getElementsByClassName(\"end-game\")[0].style.display = \"none\";\n document.getElementsByClassName(\"quit-game\")[0].style.display = \"block\";\n } else if (showType === \"end\") {\n document.getElementsByClassName(\"quit-game\")[0].style.display = \"none\";\n document.getElementsByClassName(\"end-game\")[0].style.display = \"block\";\n\n if (previousWinner === \"player\") {\n document.getElementById(\"end-lose\").style.display = \"none\";\n document.getElementById(\"end-win\").style.display = \"block\";\n let endScore = document.getElementById(\"end-score-win\");\n endScore.textContent = `${playerScore.textContent} - ${computerScore.textContent}`;\n } else if (previousWinner === \"computer\") {\n document.getElementById(\"end-win\").style.display = \"none\";\n document.getElementById(\"end-lose\").style.display = \"block\";\n let endScore = document.getElementById(\"end-score-lose\");\n endScore.textContent = `${playerScore.textContent} - ${computerScore.textContent}`;\n }\n }\n}", "function findWinner() {\n \n if (matchFound === 8) {\n timer.pause();\n\n var modal = document.getElementById(\"winner-popup\");\n var span = document.getElementsByClassName(\"close\")[0];\n\n $(\"#total-moves\").text(moves);\n $(\"#total-stars\").text(starRating);\n $(\".minutes\").text(timer.getTimeValues().minutes);\n $(\".seconds\").text(timer.getTimeValues().seconds);\n \n modal.style.display = \"block\";\n \n // When the user clicks on <span> (x), close the modal\n span.onclick = function() {\n modal.style.display = \"none\";\n }\n\n $(\"#play-again\").on(\"click\", function() {\n location.reload()\n });\n \n clearInterval(timer);\n }\n}", "function endGame() {\n // console.log(matchNum);\n starModalCount();\n openModal();\n}", "function lost(){\r\n let failureMessage = document.querySelector('.failure-message');\r\n modal.classList.remove('hidden');\r\n failureMessage.classList.remove('hidden');\r\n let againBtn = document.querySelector('.again');\r\n againBtn.onclick = function(){\r\n modal.classList.add('hidden');\r\n failureMessage.classList.add('hidden');\r\n player.x = 350;\r\n player.y = 430;\r\n resetGame();\r\n };\r\n}", "function playAgain(){\r\n modal.classList.remove(\"show\");\r\n buildDeck();\r\n}", "function checkWinningPlayer(player){\n if(player.score === 3){\n document.getElementById('main-content').style.display = 'none'\n let gameOverModal = document.getElementById('gameOverModal')\n gameOverModal.style.display = 'block'\n document.getElementById('winner-container').innerText = `${player.name} won the game!`\n document.getElementById('restart-button').addEventListener('click', restartGame)\n return true\n }\n return false\n}", "modalShow() {\n\t\tlet modal = document.getElementById(\"myModal\");\n\t\tlet restartBtn = document.getElementsByClassName(\"close\")[0];\n\n\t\tthis.scene.pause(); // pause timer & game When colliding with a bomb\n\t\tmodal.style.display = \"block\"; // show modal\n\n\t\trestartBtn.addEventListener(\"click\", (e) => {\n\t\t\te.preventDefault();\n\t\t\tmodal.style.display = \"none\"; // hide modal on clicking 'RESTART' button\n\n\t\t\t// restart after clicking 'restart' - clear all events & set game in initial point\n\t\t\tthis.restartGame();\n\t\t});\n\t}", "function makeDecision() {\n //set up modal\n $(\"#modalLine1\").removeClass('redAlert')\n $(\"#loader\").removeClass(\"active\")\n $(\"#modalBtn\").text(\"Play Again\")\n $(\"#modalBtn\").removeClass('quit')\n $(\"#modalBtn\").addClass('playA')\n\n //if you are player one\n if (whoAreYou === 'Player1') {\n\n //call whoWon function to determine winner,\n //change text to you won, you lost, or you tied\n if (whoWon(p1, p2) === 'p1') {\n $(\"#modalTop\").text(\"You won!\")\n }\n if (whoWon(p1, p2) === 'p2') {\n $(\"#modalTop\").text(\"You lost!\")\n }\n if (whoWon(p1, p2) === 'Tied') {\n $(\"#modalTop\").text(\"You tied!\")\n }\n $(\"#modalLine1\").text('You choose ' + p1)\n $(\"#modalLine2\").text('Your opponent choose ' + p2)\n callModal()\n }\n\n //if you are player 2\n if (whoAreYou === 'Player2') {\n\n //call whoWon function to determine winner,\n //change text to you won, you lost, or you tied\n if (whoWon(p1, p2) === 'p1') {\n $(\"#modalTop\").text(\"You lost!\")\n }\n if (whoWon(p1, p2) === 'p2') {\n $(\"#modalTop\").text(\"You won!\")\n }\n if (whoWon(p1, p2) === 'Tied') {\n $(\"#modalTop\").text(\"You tied!\")\n }\n $(\"#modalLine1\").text('You choose ' + p2)\n $(\"#modalLine2\").text('Your opponent choose ' + p1)\n callModal()\n }\n //wait one second and call reset function\n setTimeout(reset, 1000)\n}", "function gameIsOver() {\n \n // Append the message in the modal dialog respectively\n if(player1 > player2)\n {\n $(\"#winner\").text(\"Winner!!Player1 catched more Pokemons\");\n }\n if(player2 > player1){\n $(\"#winner\").text(\"Winner!!Player2 catched more Pokemons\");\n }\n if(player1 === player2)\n {\n $(\"#winner\").text(\"Both players catched equal Pokemons\");\n }\n // show modal dialog \n $(\"#myModal\").modal('show');\n\n}", "function closeWinModalAndReset() {\n $(document).click(function(event) {\n if ($(event.target).hasClass(\"resetGame\")) {\n if (!$(\".lockedLevelModal\").hasClass(\"showModal\")) {\n closeModal();\n changeMusic();\n resetGame(); \n }\n }\n });\n}", "function winGame() {\n if(matchedCards.length === 8) {\n swal({\n closeOnClickOutside: false,\n closeOnEsc: false,\n title: \"You win!\",\n text: \"You matched all 8 pairs in \" + seconds + \" seconds, \" + moveCount + \" moves, and with \" + starResult + \" stars remaining.\",\n icon: \"success\",\n button: \"Play again!\"\n }).then(function(isConfirm) {\n if (isConfirm) {\n $('.deck, .moves').empty();\n reset();\n }\n });\n clearInterval(countSeconds);\n }\n}", "function endGameModal() {\n $('#endGameModal').modal(\"show\");\n\n}", "function gameOver() {\n if (gameState == \"win\") {\n console.log(\"You win!!\");\n $(\"#gameOverDialog\").dialog(\"open\");\n $(\"#gameOverDialog\").text(\"You win. You successfully avoided too much harmful content.\");\n } else if (gameState == \"lose\") {\n console.log(\"You lose!!\");\n $(\"#gameOverDialog\").dialog(\"open\");\n $(\"#gameOverDialog\").text(\"You lose. You were unable to avoid harmful content.\");\n }\n}", "function won() {\n stopTimer();\n let rating = document.getElementById(\"stars\").innerHTML;\n let ratingModal = document.getElementById(\"stars-modal\");\n ratingModal.innerHTML = rating;\n let time = document.getElementById(\"timerLabel\").textContent;\n let timeModal = document.getElementById(\"time-modal\");\n timeModal.textContent = \"Time: \" + time;\n // I can break it to min sec and ms later\n modal.style.display = \"block\";\n\n let replay = document.getElementById('replay');\n\n replay.addEventListener('click', function() {\n modal.style.display = \"none\";\n restartGame();\n });\n\n // When the user clicks on <span> (x), close the modal\n closeModal.onclick = function() {\n modal.style.display = \"none\";\n }\n\n // When the user clicks anywhere outside of the modal, close it\n window.onclick = function(event) {\n if (event.target == modal) {\n modal.style.display = \"none\";\n }\n }\n\n }", "function winOrLose(winCounter, lives) {\n if (winCounter == randomWord.length) {\n $('.theWord').text(randomWord.toUpperCase());\n $('#winModal').modal('show');\n gamesWon++;\n $('#smart')[0].play();\n newGame();\n } else if (lives === 0) {\n $('.theWord').text(randomWord.toUpperCase());\n $('#doh')[0].play();\n $('#loseModal').modal('show');\n newGame();\n }\n}", "function modalShow(){\n let modal = document.querySelector(\".modal\");\n modal.classList.add(\"modalShow\");\n //set the moves\n let endMoves = document.querySelector(\".endMoves\"); \n endMoves.textContent = turnCounter;\n //set the timer\n paused = true;\n let endTime= document.querySelector(\".endTime\"); \n endTime.textContent = time;\n //display the final star rating\n const two = document.querySelector(\".endTwo\");\n const three = document.querySelector(\".endThree\");\n //display the star rating in the modal\n if(turnCounter >= 20){\n two.classList.add(\"hidden\");\n three.classList.add(\"hidden\");\n }else if(turnCounter > 13 && turnCounter <20){\n three.classList.add(\"hidden\");\n }\n //make the reset button do actually reset the application\n let button = document.querySelector(\".button\");\n button.addEventListener(\"click\",resetClicked);\n}", "function winner() {\n\twinPage.classList.remove('hidden');\n\twinPage.style.display = 'block';\n\tgamePage.classList.add('hidden');\n\tplayAgainBtn.classList.remove('hidden');\n\tclearInterval(setTimer);\n}", "function endgame(){\n $('#guess-box').prop('disabled', true)\n $('span.element').show();\n $('#element-list').show();\n $('.cell').not('.success').addClass('fail').removeClass('s d p f');\n }", "win() {\n modal.style.display = 'block';\n playAgainButton.focus();\n this.clear();\n }", "function result () {\n gameWindow.classList.add('hide')\n welcomeWindow.classList.add('hide')\n scoreWindow.classList.remove('hide')\n getScore()\n}", "function finishGame(isVictory) {\n if (isVictory) {\n highestScore(gLevel.type, gGame.secsPassed);\n renderSmiley(true);\n winningAudio.play();\n // alert('You Win!');\n openModal('You Won!');\n gGame.isOn = false;\n } else {\n gGame.isOn = false;\n losingAudio.play();\n openModal('You Lost :(');\n revealMines();\n }\n clearInterval(gTimerInterval);\n}", "function closeModal() {\n modal.classList.remove(\"show\");\n restartGame();\n}", "function finishedGame() {\n timer.pause();\n let pText = document.querySelector(\"#resultFinished\");\n let iStars = parseInt(countStars);\n let middle = countStars > iStars ? 'and a half' : '';\n pText.innerHTML = `You won with ${countMoves} moves and ${iStars} ${middle} stars in ${timer.getTimeValues().toString()}.`;\n $('#myModal').modal();\n}", "function continueGame() {\n game.updateDisplay();\n if (game.getState() == \"playing\") {\n $(\"#startButton\").toggleClass(\"hidden\");\n } else {\n $(\"#resetButton\").toggleClass(\"hidden\");\n }\n saveGame();\n}", "function checkEndGame() {\r\n if (cardMatches == 8) {\r\n console.log(\"gameEnd\");\r\n // stop the clock\r\n clearInterval(ticking);\r\n // open end game modal\r\n openModal();\r\n }\r\n}", "function winnerResult() {\n if (gameScoreWon === 3 || gameScoreLost === 3) {\n document.getElementById('games-won').style.display = \"none\";\n document.getElementById('game-con').style.display = \"none\";\n document.getElementById('final-result').style.display = \"block\";\n document.getElementById('rules-btn').disabled = true;\n document.getElementById('play').disabled = true;\n \n }\n if (gameScoreWon === 3) {\n document.getElementById('winner').style.display = \"block\";\n document.getElementById('loser').style.display = \"none\";\n document.getElementById('result-msg').innerText = \"Awesome - You won the Game!\";\n } else if (gameScoreLost === 3) {\n document.getElementById('loser').style.display = \"block\";\n document.getElementById('winner').style.display = \"none\";\n document.getElementById('result-msg').innerText = \"Better luck next time!\";\n }\n}", "function gameOver() {\n // Clear the interval\n clearInterval(info.timeout);\n // Display the modal\n divs.modal_div.style.display = \"block\";\n // Update the final score element\n divs.final_score.innerText = \"Your final score is: \" + info.score;\n}", "function winner() {\n winnerPrompt.classList.remove('hidden-winner');\n resetPlayAgain.classList.remove('hidden');\n hide1.classList.add('hide-all');\n hide2.classList.add('hide-all');\n resetSpan.textContent = 'Play Again?';\n }", "function openModal() {\npaused = true;\nmyModal.style.display = 'block';\nendScore.innerHTML = score;\ndocument.getElementsByClassName('play-again')[0].addEventListener('click', reset);\ndocument.getElementsByClassName('quit')[0].addEventListener('click', clearModal);\n}", "function openModal() {\n modal.style.display = \"block\";\n passTheScore();\n}", "checkForGameEnd() {\n const { numberOfLockedCards, shuffledCards } = this.state;\n if(numberOfLockedCards === shuffledCards.length) {\n // Show modal and hide the main content\n this.setState({\n modalVisible: true,\n timer: clearInterval(this.state.timer)\n });\n }\n }", "function celebration(){\n\t // if all cards = is solved then display (animation? and final photo) \n\t //in raw html/css first so image is on the page display none in css\n\t //show it with a slow fade in\n\t $(\"#group-silly\").fadeIn(\"slow\");\n\t // stop timer using variable \n\t clearTimeout(myVar);\n\t $(\".start-button\").html(\"Play Again\");\n\t $(\".start-button\").click(restartGame);\n\t // call restartGame function\n}", "function gameWin(player){\n var playerColor = player.toUpperCase();\n $(\"#winMsg\").html(playerColor + \" WINS!!!\");\n $(\"#winModal\").modal(\"show\");\n if(player == \"red\"){\n redWins++;\n $(\".redWins\").html(redWins);\n turn = \"red\";\n }else{\n blackWins++;\n $(\".blackWins\").html(blackWins);\n turn = \"black\";\n }\n }", "function toggleScoreModal() {\n stopTimer();\n finalScore();\n let modal = document.querySelector('#score-modal');\n modal.classList.toggle('modal-hide');\n}", "async win (){\n if(this.state.turn){\n await this.setState({winner: this.state.player1Name});\n this.updateMineFieldChange();\n //Alert who has won and suggestion of restarting the game\n if(window.confirm(this.state.player1Name + ' has won the game, do you wish to restart it?')){\n }\n }\n else{\n await this.setState({winner: this.state.player2Name});\n this.updateMineFieldChange();\n //Alert who has won and suggestion of restarting the game\n if(window.confirm(this.state.player2Name + ' has won the game, do you wish to restart it?')){\n }\n }\n return;\n }", "function win () { \n style = { font: \"65px Arial\", fill: \"#fff\", align: \"center\" };\n game.add.text(game.camera.x+325, game.camera.y+150, \"You Win!\", style);\n button = game.add.button(game.camera.x+275, game.camera.y+250, 'reset-button', actionOnResetClick, this);\n button = game.add.button(game.camera.x+475, game.camera.y+250, 'contact-button', actionOnContactClick, this); \n // The following lines kill the players movement before disabling keyboard inputs\n player.body.velocity.x = 0;\n setTimeout(game.input.keyboard.disabled = true, 1000); \n // Plays the victory song \n victory.play('');\n // When the Reset button is clicked, it calls this function, which in turn calls the game to be reloaded.\n // Here we display the contact and replay button options, calling either respective function\n function actionOnResetClick () {\n gameRestart();\n }\n\n // When the contact button is clicked it redirects through to contact form\n function actionOnContactClick () {\n\n window.location = (\"/contacts/\" + lastName)\n \n } \n }", "function endGame(status) {\n let // Select Popuo Element\n popup = document.querySelector(\".popup\"),\n // Select Player Status Element\n playerStatus = popup.querySelector(\".player-status\"),\n // Select Player Status Span\n playerStatusSpan = playerStatus.querySelector(\"span\"),\n // Select Wrong Attempts Span\n wrongAttemptsSpan = popup.querySelector(\".wrong-attempts span\"),\n // Select Play Again Button\n playAgainBtn = popup.querySelector(\".play-again\");\n\n // Show Popup Element\n popup.style.display = \"block\";\n\n // Set Player Status [Win Or Fail]\n playerStatusSpan.textContent = status;\n\n // Set Wrong Attempts Number\n wrongAttemptsSpan.textContent = wrongAttempts;\n\n // Check If The Player [Win Or Fail]\n if (status === \"Win\") {\n playerStatus.classList.add(\"win\");\n\n if (playerStatus.classList.contains(\"fail\")) {\n playerStatus.classList.remove(\"fail\");\n }\n } else {\n playerStatus.classList.add(\"fail\");\n\n if (playerStatus.classList.contains(\"win\")) {\n playerStatus.classList.remove(\"win\");\n }\n }\n\n // Play Again\n playAgainBtn.onclick = function () {\n // Hid Popup Element\n popup.style.display = \"none\";\n\n // Reset [wrongAttempts] & [rightChoose] Value\n wrongAttempts = 0;\n rightChoose = 0;\n\n // Empty Letters Container\n lettersContainer.innerHTML = \"\";\n\n // Remove Finished Class From Letters Container\n if (lettersContainer.classList.contains(\"finished\")) {\n lettersContainer.classList.remove(\"finished\");\n }\n\n // Trigger Generate Letters Function\n generateLetters();\n\n // Trigger Get Word Functuin\n getWord();\n\n // Empty Letters Guess Contianer\n lettersGuessContainer.innerHTML = \"\";\n\n // Trigger Guess Function\n guess();\n\n // Remove Wrong Class From Hangman Draw\n for (let i = 1; i <= 8; i++) {\n if (theDraw.classList.contains(`wrong-${i}`)) {\n theDraw.classList.remove(`wrong-${i}`);\n }\n }\n\n gameMacanism();\n };\n}", "function gameOver() {\n $('#winnerText').text(`Your final score is ${score}`);\n $('#winnerModal').modal('toggle');\n}", "function finish(){\n\n // sound-effect\n playIncorrect()\n // Disable buttons, because we don't need them.\n elements.correctButton.disabled = true\n elements.incorrectButton.disabled = true\n window.setTimeout(displayGameOver,1500)\n}", "function gameWon() {\n //This element will hide the game section\n document.getElementById('main').style.display = 'none';\n\n //This element will hide the victory-screen section.\n document.getElementById('victory-screen').style.display = 'flex';\n\n //Setting the event listener for the play again button.\n document.getElementById('play-again-button').addEventListener('click', resetGame);\n}", "function win() {\n if (squares[4].classList.contains('man')) {\n result.innerHTML = 'I am Inevitable 😍'\n squares[index].classList.remove('man')\n clearInterval(timerId)\n document.removeEventListener('keyup', moveman)\n }\n }", "function isFinished(){\n if(counter === 10){\n counter = 0;\n result.textContent = \"Play again!\";\n result.className = \"\";\n reset = true;\n showConclusionModal();\n }\n}", "function checkWin() {\n\tif (towerC.childElementCount === 3) {\n\t\tmodal.style.display = 'inline';\n\t\tplayerMessage.innerHTML = '';\n\t\tmodalContent.innerHTML = 'YOU WON!!!! LFG';\n\t\tclearInterval(countUp); //stops the timer.\n\t}\n}", "function closeModal() {\n close.click(function(e) {\n gameEnd.removeClass('show');\n start();\n });\n}", "function endOfGame() {\n\n if (matchFound === 8) {\n window.clearInterval(timer);\n var modal = document.getElementById('message');\n var span = document.getElementsByClassName(\"close\")[0];\n\n $(\"#total-moves\").text(moves);\n $(\"#total-stars\").text(starNumber);\n\n modal.style.display = \"block\";\n\n\n span.onclick = function() {\n modal.style.display = \"none\";\n };\n // Play again button\n $(\"#play-again-btn\").on(\"click\", function() {\n location.reload()\n });\n\n clearInterval(timer);\n }\n}", "function gameOverPopup(){\n var modalGameOver = document.getElementById('modalGameOver');\n var rePlay = document.getElementById(\"replayBtn\");\n var img = document.querySelectorAll(\"img\")[0];\n\n modalGameOver.style.display = \"block\";\n $(\"#score\").html(\"Final score: \" + finalScore);\n // When the user clicks button replay, close it\n rePlay.onclick = function() {\n window.location.assign(\"../start.html\");\n }\n }" ]
[ "0.79958755", "0.7674914", "0.7590692", "0.7562863", "0.75202096", "0.7463216", "0.74332577", "0.7370642", "0.736813", "0.73266023", "0.7278763", "0.7268241", "0.7261297", "0.72610885", "0.7241172", "0.72255564", "0.72160333", "0.72023773", "0.7202213", "0.7199982", "0.71915716", "0.7189895", "0.71889216", "0.7187446", "0.71789646", "0.7166189", "0.7166189", "0.7162732", "0.71512085", "0.7146162", "0.71250755", "0.7124917", "0.7122165", "0.71140504", "0.71050334", "0.70826083", "0.7081608", "0.70704484", "0.7067574", "0.70663816", "0.7055887", "0.7045389", "0.7043902", "0.7025624", "0.70068204", "0.70002407", "0.70002407", "0.6988729", "0.6957064", "0.69469076", "0.69355595", "0.692904", "0.69118965", "0.6911346", "0.6910631", "0.6909339", "0.69085497", "0.690487", "0.68827564", "0.6878053", "0.68715584", "0.68586427", "0.6853054", "0.6847448", "0.6838475", "0.6828403", "0.6825362", "0.682418", "0.68124145", "0.6811421", "0.6806929", "0.68059486", "0.6802486", "0.6784522", "0.6781022", "0.678078", "0.6779199", "0.6778522", "0.67784894", "0.6778383", "0.6775107", "0.6774229", "0.6773439", "0.6769036", "0.6757667", "0.6753235", "0.67517793", "0.6746199", "0.67455566", "0.6739178", "0.67263985", "0.6721057", "0.6720466", "0.6708937", "0.67064357", "0.6698592", "0.66912633", "0.668426", "0.6682957", "0.6677367" ]
0.73718977
7
TODO: Clean this crap up
async reAuthorize(user, pass, options) { return new Promise((resolve, reject) => { puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']}).then(async browser => { try { const page = await browser.newPage(); try { console.log(`[cbs api] - navigate to ${CbsAPI.login.page}`); await page.goto(`${CbsAPI.login.page}?${CbsAPI.login.params}`); await page.type(CbsAPI.login.userSelector, user); await page.type(CbsAPI.login.passwordSelector, pass); console.log('[cbs api] - submit login form') await page.$eval(CbsAPI.login.form, form => form.submit()); await page.waitForNavigation(); console.log(`[cbs api] - Login Complete. Get access_tokens`); await page.waitForSelector(CbsAPI.teams.waitSelector); const tokens = await this.getAllTokens(page, options); console.log(`[cbs api] - ${tokens.length} valid leagues`); resolve(new CbsProfile(user, tokens)); } catch (err) { console.log(err); reject(error); } } finally { console.log('[cbs api] - close browser'); await browser.close(); } }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private internal function m248() {}", "private public function m246() {}", "protected internal function m252() {}", "transient private protected internal function m182() {}", "static private internal function m121() {}", "transient protected internal function m189() {}", "static final private internal function m106() {}", "transient private internal function m185() {}", "transient final protected internal function m174() {}", "static private protected internal function m118() {}", "static transient final private internal function m43() {}", "static transient final protected internal function m47() {}", "static transient private protected internal function m55() {}", "transient private protected public internal function m181() {}", "transient final private protected internal function m167() {}", "obtain(){}", "transient final private internal function m170() {}", "static transient final protected public internal function m46() {}", "static transient final private protected internal function m40() {}", "__previnit(){}", "function _____SHARED_functions_____(){}", "static transient private protected public internal function m54() {}", "static protected internal function m125() {}", "static final private protected internal function m103() {}", "static transient private internal function m58() {}", "static private protected public internal function m117() {}", "function DWRUtil() { }", "transient private public function m183() {}", "static transient private public function m56() {}", "function AeUtil() {}", "prepare() {}", "static transient final protected function m44() {}", "transient final private protected public internal function m166() {}", "static transient final private protected public internal function m39() {}", "static final private public function m104() {}", "static final protected internal function m110() {}", "function PathSearchResultCollector() {\n\n}", "static final private protected public internal function m102() {}", "static transient final private public function m41() {}", "_firstRendered() { }", "apply () {}", "lastUsed() { }", "function findCanonicalReferences() {\n\n }", "function TMP() {\n return;\n }", "static private public function m119() {}", "static transient final private protected public function m38() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "function Utils() {}", "function Utils() {}", "resolution() { }", "init () {\n\t\treturn null;\n\t}", "function fm(){}", "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 }", "getResult() {}", "function SeleneseMapper() {\n}", "function StupidBug() {}", "static transient protected internal function m62() {}", "function o0(o1)\n{\n var o2 = -1;\n try {\nfor (var o259 = 0; o3 < o1.length; function (o502, name, o38, o781, o782, o837, o585, o838, o549) {\n try {\no839.o468();\n}catch(e){}\n // TODO we should allow people to just pass in a complete filename instead\n // of parent and name being that we just join them anyways\n var o840 = name ? o591.resolve(o591.o592(o502, name)) : o502;\n\n function o841(o842) {\n function o843(o842) {\n try {\nif (!o838) {\n try {\no474.o800(o502, name, o842, o781, o782, o549);\n}catch(e){}\n }\n}catch(e){}\n try {\nif (o837) try {\no837();\n}catch(e){}\n}catch(e){}\n try {\no334('cp ' + o840);\n}catch(e){}\n }\n var o844 = false;\n try {\nModule['preloadPlugins'].forEach(function (o845) {\n try {\nif (o844) try {\nreturn;\n}catch(e){}\n}catch(e){}\n try {\nif (o845['canHandle'](o840)) {\n try {\no845['handle'](o842, o840, o843, function () {\n try {\nif (o585) try {\no585();\n}catch(e){}\n}catch(e){}\n try {\no334('cp ' + o840);\n}catch(e){}\n });\n}catch(e){}\n try {\no844 = true;\n}catch(e){}\n }\n}catch(e){}\n });\n}catch(e){}\n try {\nif (!o844) try {\no843(o842);\n}catch(e){}\n}catch(e){}\n }\n try {\no332('cp ' + o840);\n}catch(e){}\n try {\nif (typeof o38 == 'string') {\n try {\no839.o846(o38, function (o842) {\n try {\no841(o842);\n}catch(e){}\n }, o585);\n}catch(e){}\n } else {\n try {\no841(o38);\n}catch(e){}\n }\n}catch(e){}\n })\n {\n try {\nif (o1[o3] == undefined)\n {\n try {\nif (o2 == -1)\n {\n try {\no2 = o3;\n}catch(e){}\n }\n}catch(e){}\n }\n else\n {\n try {\nif (o2 != -1)\n {\n try {\no4.o5(o2 + \"-\" + (o3-1) + \" = undefined\");\n}catch(e){}\n try {\no2 = -1;\n}catch(e){}\n }\n}catch(e){}\n try {\no4.o5(o3 + \" = \" + o1[o3]);\n}catch(e){}\n }\n}catch(e){}\n }\n}catch(e){}\n}", "transient final private public function m168() {}", "constructor () {\r\n\t\t\r\n\t}" ]
[ "0.6629856", "0.64722884", "0.6315378", "0.59493625", "0.58367836", "0.58133566", "0.5773609", "0.57577735", "0.5658787", "0.5511058", "0.5473137", "0.54320234", "0.5384917", "0.53504694", "0.53492665", "0.53312796", "0.5299023", "0.52425486", "0.5214896", "0.5134584", "0.5102485", "0.5073686", "0.50611746", "0.50600356", "0.50535417", "0.50495934", "0.5047122", "0.49607447", "0.48987287", "0.48795825", "0.4870619", "0.4867342", "0.48294634", "0.48215133", "0.4786205", "0.47728947", "0.47662288", "0.4764877", "0.4725948", "0.47178438", "0.47054914", "0.46974608", "0.46955356", "0.46919054", "0.4690006", "0.46631268", "0.46493202", "0.46493202", "0.46493202", "0.46493202", "0.46493202", "0.46493202", "0.46421102", "0.46421102", "0.46340513", "0.46312746", "0.4625699", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.4624448", "0.46160704", "0.45969164", "0.45964774", "0.4582676", "0.45813", "0.4571879", "0.45672163" ]
0.0
-1
TODO: OBJECT FOR MAPPING OWNERS TO TEAM
mapTeamData(team, ownersList) { const owners = ownersList.filter(owner => owner.team.id == team.id).map(ownerObj => { const owner = Object.assign({}, ownerObj); const name = owner.name.split(' '); owner.isLeagueManager = owner.commissioner == 1; owner.displayName = owner.name; owner.firstName = name.length > 0 ? name[0] : ''; owner.lastName = name.length > 1 ? name[1] : ''; delete owner.name; delete owner.team; delete owner.commissioner; delete owner.logged_in_owner; return owner; }); const roster = team.players.map(player => { return { id: parseInt(player.id), firstName: player.firstname, lastName: player.lastname, fullName: player.fullname } }); team.owners = owners; team.roster = roster; team.id = parseInt(team.id); team.abbrev = team.abbr; delete team.abbr; delete team.projected_points; delete team.lineup_status; delete team.players; delete team.warning; delete team.point; delete team.long_abbr; delete team.short_name; delete team.division; return team; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get owners() {\r\n return new Owners(this);\r\n }", "function getProjectMembersOrTenderers() {\n $scope.membersList = $rootScope.getProjectMembers(people);\n $scope.tags = [];\n _.each($rootScope.currentTeam.fileTags, function(tag) {\n $scope.tags.push({name: tag, select: false});\n });\n \n // get unique member \n $scope.membersList = _.uniq($scope.membersList, \"_id\");\n\n // filter members list again\n _.each(file.members, function(member) {\n _.remove($scope.membersList, {_id: member._id});\n });\n\n // remove current user from the members list\n _.remove($scope.membersList, {_id: $rootScope.currentUser._id});\n\n // remove the file owner from available assignees\n _.remove($scope.membersList, {_id: $scope.file.owner._id})\n\n // get invitees for related item\n $scope.invitees = angular.copy($scope.file.members);\n _.each($scope.file.notMembers, function(member) {\n $scope.invitees.push({email: member});\n });\n $scope.invitees.push($scope.file.owner);\n $scope.invitees = _.uniq($scope.invitees, \"email\");\n _.remove($scope.invitees, {_id: $rootScope.currentUser._id});\n }", "function getUserTeam() {\n API.getTeam(user.email)\n .then(res => {\n if (res.data != null) {\n setTeam(res.data)\n setTeamPlayers(res.data.players);\n }\n })\n .catch(err => console.log(err))\n setTeam({ ...team, owner: user.email })\n }", "getOwners() {\n return this.owners;\n }", "get owner() { return this.ownerIn; }", "function Company(obj) {\n return obj.team && Team(obj.team);\n}", "getMultiOwnerInfo() {\n if (this._payingUsers.length <= 1) { return null; }\n const info = [];\n this._payingUsers.forEach((payerObj) => {\n const portionOfTipOwed = (payerObj.percentage / 100) * (this.tip || 0);\n const portionOfInvoiceOwed = (payerObj.percentage / 100) * this.addServiceFee(this.amount);\n const totalPaidAmt = (portionOfTipOwed + portionOfInvoiceOwed).toFixed(2);\n const ownerInfo = {\n name: payerObj._user.name,\n percentage: payerObj.percentage,\n paidAmount: totalPaidAmt,\n };\n info.push(ownerInfo);\n });\n return info;\n }", "function Players(name, age, goals, cards) {\n this.team = 'Barcelona';\n this.name = name;\n this.age = age;\n this.goals = goals;\n this.yellowCards = cards;\n}", "function Players(name, age, goals, cards) {\n this.team = 'Barcelona';\n this.name = name;\n this.age = age;\n this.goals = goals;\n this.yellowCards = cards;\n}", "get team() {\r\n return new Team(this);\r\n }", "function footballTeam (player){\n\tvar teamobj = {}\n\tteamobj.player = player;\n\tteamobj.addInfo =addInfo;\n\tteamobj.arrayOfPlayers= [];\n\tteamobj.increaseLevel=increaseLevel;\n\tteamobj.isAvailable=isAvailable;\n\tteamobj.decrease=decrease;\n\tteamobj.sortPalyerBy=sortPalyerBy;\n\treturn teamobj\n}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "function OwnerID() {}", "findOwners() {\n return this._getRelationship('owner', 'from');\n }", "function setOwnership(country, selectedPlayer){\n\tcountry.owner = selectedPlayer;\n\tcountry.style.border = \"5px solid \" + selectedPlayer.colour;\n}", "function ownedByLuke(pet) {\n return pet.ownerName == \"Luke\";\n}", "static revive(projectObject)\n {\n let realProject = new Project();\n realProject.name = projectObject.name;\n realProject.team = projectObject.team;\n realProject.tasks = projectObject.tasks;\n\n for(let i = 0;i < realProject.team.length; i++)\n {\n let memberObject = realProject.team[i];\n let realMember = new Member(memberObject.color, memberObject.name);\n realProject.team[i] = realMember;\n }\n\n for(let i = 0;i < realProject.tasks.length; i++)\n {\n let taskObject= realProject.tasks[i];\n let realTask = new Task();\n\n realTask.name = taskObject.name;\n realTask.from = new Date(taskObject.from);\n realTask.to = new Date(taskObject.to);\n realTask.finished = taskObject.finished;\n realTask.workingOn = taskObject.workingOn;\n if(taskObject.inCharge !== undefined)\n {\n realTask.inCharge = getMember(realProject.team, taskObject.inCharge.name, taskObject.inCharge.color);\n }\n\n for(let j = 0;j < realTask.workingOn.length; j++)\n {\n let memberObject = realTask.workingOn[j];\n let realMember = getMember(realProject.team, memberObject.name, memberObject.color);\n realTask.workingOn[j] = realMember;\n }\n\n realProject.tasks[i] = realTask;\n }\n\n return realProject;\n }", "joinTeam(team) {\n team.members.push(this)\n }", "function teamObj(id, teamMembers, teamName, currentStanding){\n\t\tthis.teamId = id;\n\t\tthis.teamMembers = teamMembers;\n\t\tthis.teamName = teamName;\n\t\tthis.currentStanding = currentStanding;\n\t\tthis.totalDrinks = 0;\n\t\tthis.playersPlaced = 0;\n\t\tthis.disableDrinks = \"\";\n\t\tthis.drank = false;\n\t}", "function OwnerID() { }", "function getOwner(){\n return owner;\n }", "async function getTeamInfo() {\n try{\n let myData = await fetch('https://fantasy.premierleague.com/api/me/', {});\n let myDataJSON = await myData.json();\n\n let teamId = myDataJSON.player.entry;\n let myTeam = await fetch(`https://fantasy.premierleague.com/api/my-team/${teamId}/`, {});\n let myTeamJSON = await myTeam.json();\n\n myTeamJSON.teamId = teamId;\n //console.log(myTeamJSON);\n return myTeamJSON;\n } catch (e) {\n return {};\n }\n}", "function joinTeam(input) { }", "function Team(client){\n\tthis.client = client;\n\tthis.myTanks = {};\n\tthis.init();\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 }" ]
[ "0.6072791", "0.60671264", "0.5977277", "0.58441657", "0.5806571", "0.572325", "0.57117057", "0.57033056", "0.57033056", "0.56819993", "0.56730604", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5668324", "0.5665458", "0.5664456", "0.56610847", "0.56477314", "0.56461716", "0.5636138", "0.5625381", "0.561756", "0.5613478", "0.5573967", "0.55531096", "0.5547978" ]
0.6414082
0
P R I V A T E
async getAllTokens(page, options) { const tokens = []; let teamsList = await page.$$(`${CbsAPI.teams.prefixSelector}${options.sport}${CbsAPI.teams.suffixSelector}`); console.log(`[cbs api] - found ${teamsList.length} team(s)`); const hrefs = []; for (let i = 0; i < teamsList.length; i++) { const prop = await teamsList[i].getProperty('href'); const href = await prop.jsonValue(); hrefs.push(href); } for (let i = 0; i <hrefs.length; i++) { console.log(`[cbs api] - navigate to ${hrefs[i]} to get check league type and access_token`); const token = await this.getAccessToken(page, hrefs[i]); tokens.push(token); } return tokens.filter(token => CbsAPI.allowedTypes.includes(token.leagueType)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "protected internal function m252() {}", "transient private internal function m185() {}", "transient protected internal function m189() {}", "static private internal function m121() {}", "transient private protected internal function m182() {}", "obtain(){}", "function _p(t,e){0}", "static transient final private internal function m43() {}", "static transient final protected internal function m47() {}", "transient final protected internal function m174() {}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}" ]
[ "0.6497584", "0.6456844", "0.60105735", "0.6008095", "0.5982573", "0.59378886", "0.5866038", "0.5724313", "0.5679906", "0.564659", "0.5587861", "0.55853236", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935", "0.55626935" ]
0.0
-1
Function plots cartesian coordiate system
function plotCartesian(x,y,z, target){ let hoverlabel = ["X: "+x[0]+", Y: "+y[0]+", Z: "+z[0],"X: "+x[1]+", Y: "+y[1]+", Z: "+z[1]]; var data = [{ type: 'scatter3d', mode: 'lines', x: x, y: y, z: z, hoverinfo: 'text', hovertext: hoverlabel, opacity: 1, line: { width: 6, color: "rgb(0,0,0)" } }] var layout = { scene: { xaxis:{title: 'X AXIS'}, yaxis:{title: 'Y AXIS'}, zaxis:{title: 'Z AXIS'}, } } Plotly.plot(target, data, layout); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function drawCartesianOverlay() {\n \"use strict\";\n //Draw heavier black lines for grid\n ctx.beginPath();\n ctx.moveTo(0.5, 300.5);\n ctx.lineTo(800.5, 300.5);\n ctx.moveTo(400.5, 0.5);\n ctx.lineTo(400.5, 600.5);\n ctx.strokeStyle = 'black';\n ctx.lineWidth = 1.0;\n ctx.stroke();\n //-x arrow for line\n ctx.beginPath();\n ctx.moveTo(5.5, 295.5);\n ctx.lineTo(0.5, 300.5);\n ctx.lineTo(5.5, 305.5);\n //+x arrow for line\n ctx.moveTo(795.5, 295.5);\n ctx.lineTo(800.5, 300.5);\n ctx.lineTo(795.5, 305.5);\n //+y arrow for line\n ctx.moveTo(395.5, 5.0);\n ctx.lineTo(400.5, 0.5);\n ctx.lineTo(405.5, 5.0);\n //-y arrow for line\n ctx.moveTo(395.5, 595.5);\n ctx.lineTo(400.5, 600.5);\n ctx.lineTo(405.5, 595.5);\n ctx.strokeStyle = 'black';\n ctx.lineWidth = 1.0;\n ctx.stroke();\n //Label Graphs\n ctx.font = \"9px Georgia\";\n ctx.fillText(\"-x\", 1, 288);\n ctx.fillText(\"+\", 790, 288);\n ctx.fillText(\"x\", 795, 288);\n ctx.fillText(\"-y\", 382, 597);\n ctx.fillText(\"+\", 381, 8);\n ctx.fillText(\"y\", 386, 8);\n}", "function plotGrid() {\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[i].length; j++) {\n plotRectangle(i, j);\n }\n }\n }", "axisPlot() {\n this.ctx = this.canvas.getContext(\"2d\");\n\n /**\n * Grid grid\n */\n if (this.grid.grid) {\n this.ctx.beginPath();\n this.ctx.font = 'italic 18pt Calibri';\n this.ctx.strokeStyle = '#979797';\n this.ctx.lineWidth = 1;\n this.ctx.setLineDash([10, 15]);\n for (let i = 30; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldY(i)*1000)/1000, 0, i);\n this.ctx.moveTo(0, i);\n this.ctx.lineTo(this.field.width, i);\n }\n for (let i = 100; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldX(i)*1000)/1000, i, this.field.height);\n this.ctx.moveTo(i, 0);\n this.ctx.lineTo(i, this.field.height);\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n /**\n * Grid axiss\n */\n if (this.grid.axiss) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#b10009';\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n this.ctx.moveTo(this.center.x, 0);\n this.ctx.lineTo(this.center.x, this.field.height);\n\n this.ctx.moveTo(0, this.center.y);\n this.ctx.lineTo(this.field.width, this.center.y);\n\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n if (this.grid.serifs) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#058600';\n this.ctx.fillStyle = '#888888'\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n let start = 0;\n if (!this.grid.serifsStep){\n return;\n }\n\n let s = Math.abs(\n this.ScreenToWorldY(0) -\n this.ScreenToWorldY(this.grid.serifsSize)\n );\n\n /**\n * To right & to left\n */\n if ((this.center.y > 0) && (this.center.y < this.field.height)) {\n\n let finish = this.ScreenToWorldX(this.field.width);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo(i+this.grid.serifsStep/2,(s/2));\n this.lineTo(i+this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(i+this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i+this.grid.serifsStep,s);\n this.lineTo(i+this.grid.serifsStep,-s);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(i+this.grid.serifsStep), this.WorldToScreenY(s));\n }\n\n finish = this.ScreenToWorldX(0);\n\n for (let i = start; i > finish; i-=this.grid.serifsStep) {\n this.moveTo(i-this.grid.serifsStep/2,(s/2));\n this.lineTo(i-this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i-this.grid.serifsStep/2, this.WorldToScreenX(i-this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i-this.grid.serifsStep,s);\n this.lineTo(i-this.grid.serifsStep,-s);\n this.ctx.fillText(i-this.grid.serifsStep, this.WorldToScreenX(i-this.grid.serifsStep), this.WorldToScreenY(s));\n }\n }\n\n /**\n * To top & to bot\n */\n if ((this.center.x > 0) && (this.center.x < this.field.width)) {\n\n start = 0;\n let finish = this.ScreenToWorldY(0);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo(-s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n\n finish = this.ScreenToWorldY(this.field.width);\n\n for (let i = start; i > finish-this.grid.serifsStep; i-=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo( -s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n }", "function plotGraph() {\n if (houses.data.length > 0) {\n for (let i = 0; i < houses.data.length; i++) {\n xs[i] = map(houses.data[i].inputs[0], 0, zoom, 0, wnx);\n ys[i] = map(houses.data[i].inputs[1], 0, zoom, wny, 200);\n cs[i] = houses.data[i].inputs[8];\n ps[i] = houses.data[i].target[0];\n }\n }\n}", "function cartesian(coordinates) {\n const lambda = coordinates[0] * radians,\n phi = coordinates[1] * radians,\n cosphi = cos(phi);\n return [cosphi * cos(lambda), cosphi * sin(lambda), sin(phi)];\n}", "function plotPoints(coords) {\n ctx.fillStyle = 'green';\n console.log(coords);\n ctx.fillRect(coords.y, coords.x, 5, 5);\n}", "function plot() {\n \n }", "plotCyclists() {\n for (let c of this.mapCyclists) {\n if (c.cyclist.id.id == \"0_ghost\" || c.cyclist.id.id == \"ghost\") {\n c.plotGhost(this.map);\n } else {\n c.plotMarker(this.map);\n }\n }\n }", "function displayCoord(a) {\r\n\t\tc.beginPath();\r\n\t\tc.moveTo(parseInt(a[0],10)-3,output(parseInt(a[1],10)-3));\r\n\t\tc.lineTo(parseInt(a[0],10)+3,output(parseInt(a[1],10)+3));\r\n\t\tc.stroke();\r\n\t\tc.beginPath();\r\n\t\tc.moveTo(parseInt(a[0],10)-3,output(parseInt(a[1],10)+3));\r\n\t\tc.lineTo(parseInt(a[0],10)+3,output(parseInt(a[1],10)-3));\r\n\t\tc.stroke();\r\n\t\tif (showCoordsCheck) c.fillText(\"(\"+a[0]+\",\"+a[1]+\")\",parseInt(a[0],10)+10,output(parseInt(a[1],10)+10));\r\n\t}", "function cartesian(coordinates) {\n var lambda = coordinates[0] * __WEBPACK_IMPORTED_MODULE_1__math__[\"v\" /* radians */],\n phi = coordinates[1] * __WEBPACK_IMPORTED_MODULE_1__math__[\"v\" /* radians */],\n cosphi = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(phi);\n return [cosphi * Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(lambda), cosphi * Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(lambda), Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(phi)];\n}", "show() {\n fill(255);\n noStroke();\n let sx = map(this.x/this.z, 0, 1, 0, width);\n let sy = map(this.y/this.z, 0, 1, 0, height);\n let r = map(this.z, 0, width, 8, 0);\n //ellipse(sx, sy, r, r);\n stroke(255);\n let px = map(this.x/this.pz, 0, 1, 0, width);\n let py = map(this.y/this.pz, 0, 1, 0, height);\n line(px,py, sx, sy);\n this.pz = this.z;\n }", "plot() {\n return \"Cute alien takes over the earth\";\n }", "function cartesian$1(coordinates) {\n var lambda = coordinates[0] * radians,\n phi = coordinates[1] * radians,\n cosphi = cos(phi);\n return [\n cosphi * cos(lambda),\n cosphi * sin(lambda),\n sin(phi)\n ];\n}", "function cartesian(coordinates) {\n var lambda = coordinates[0] * __WEBPACK_IMPORTED_MODULE_1__math__[\"v\" /* radians */],\n phi = coordinates[1] * __WEBPACK_IMPORTED_MODULE_1__math__[\"v\" /* radians */],\n cosphi = Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(phi);\n return [\n cosphi * Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"h\" /* cos */])(lambda),\n cosphi * Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(lambda),\n Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"y\" /* sin */])(phi)\n ];\n}", "function plot(rows = 36, cols = 64) {\n\n /* 'c' will contain the whole generated html rect tags string to change innerhtml of enclosing div */\n /* 'y' will denote the 'y' coordinate where the next grid must be placed */\n let c = \"\", y = 0;\n\n /* Looping for each row */\n for (let i = 0; i < rows; i++) {\n\n /* 'x' is a coordinate denoting where the next grid must be placed */\n var x = 0;\n\n /* For each row we will loop for each column present in the Grid */\n for (let j = 0; j < cols; j++) {\n\n /* 'colr' will store the rest grid color which is dark gray currently */\n let colr = grid_color;\n\n /* If the Rectange present in the grid is on the border side then change the color in order to highlight borders */\n if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1){\n colr = border_color;\n }\n\n /* Creating a rect tag that is appending in 'c' for now and will be updated to innerhtml of enclosing div */\n /* I know you will be wondering about the id given to each rect :-\n * Each rect must be provided with id in order to do anything with the corresponding rect.\n * Operations like coloring the grid as well saving saving any number in corresponding matrix needs an id of the rect.\n * Hence id is important to allot to each rect to make further changes in matrix on which whole algo is based.\n * In order to assing every rect id i decided to allot their corresponding row_number + : + col_number to be as id\n * As with this scenario it is easy to remember and will be unique for every rect tag. \n */\n c += `<rect id=${i + \":\" + j} x=\"${x}\" y=\"${y}\" width=\"30\" height=\"30\" fill=\"${colr}\" r=\"0\" rx=\"0\" ry=\"0\" stroke=\"#000\" style=\"-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 0.2;\" stroke-opacity=\"0.2\"></rect>`;\n\n /* Incrementing the 'x' coordinate as we have width of 30px and hence 'x' coordinate for next rect will be +30 from current pos. */\n x += 30;\n }\n\n /* Incrementing the 'y' coordinate as we have placed sufficient rect in 1 row now need to advance 'y' as height of each rect \n is 30px hence for every rect in next column the y coordinate will be +30*/\n y += 30;\n }\n\n /* At last after creating rect tags using loops, now update innerHtml of enclosing div with id='container'[grid.html] */\n document.getElementById(\"container\").innerHTML = c;\n\n /* I wanted to preplace the Source - coordinate so at rect with id='src_crd' will be coloured green */\n document.getElementById(src_crd).style.fill = \"rgb(0, 255, 0)\";\n matrix[split(src_crd, 0)][split(src_crd, 1)] = 1; /* Update the pos as '1' to denote source location */\n\n /* I wanted to preplace the Destination - coordinate so at rect with id='dst_crd' will be coloured Red */\n document.getElementById(dst_crd).style.fill = \"rgb(255, 0, 0)\";\n matrix[split(dst_crd, 0)][split(dst_crd, 1)] = 2; /* Update the pos as '2' to denote Destination location */\n\n }", "function main(){\n // Same functions used in class for moveTo and lineTo\n function moveToTx(x,y,z,Tx) {\n var loc = [x,y,z];\n var locTx = m4.transformPoint(Tx,loc);\n context.moveTo(locTx[0],locTx[1]);\n }\n function lineToTx(x,y,z,Tx) {\n var loc = [x,y,z];\n var locTx = m4.transformPoint(Tx,loc);\n context.lineTo(locTx[0], locTx[1]);\n }\n function drawAxes(Tx){\n context.beginPath();\n moveToTx(-50, 0, 0, Tx);\n lineToTx(50, 0, 0, Tx);\n context.stroke(); // x-axis\n moveToTx(0, -50, 0, Tx);\n lineToTx(0, 50, 0, Tx);\n context.stroke(); // y-axis\n moveToTx(0, 0, -50, Tx);\n lineToTx(0, 0, 50, Tx);\n context.stroke(); // z-axis\n }\n /**\n Itterates through the 2d array of points (x,y,z), drawing a line\n between each. Points have already been transformed to exist in the world\n coordinate system from the point at which they were added.\n **/\n function drawPicture(Tx, vectArray, toMouse){\n context.beginPath();\n vectArray.forEach(function(point,i){\n if(i === 0){\n moveToTx(point[0],point[1],point[2],Tx);\n }else{\n lineToTx(point[0],point[1],point[2],Tx);\n }\n context.stroke();\n });\n if(toMouse){\n lineToTx(currMousePos[0],currMousePos[1],0,m4.identity());\n }\n context.stroke();\n }\n /**\n Draws a grid on the y=0 plane\n **/\n function drawGrid(Tx){\n context.beginPath();\n var dim = 10;\n var length = 500;\n // Draw from the negative width to pos\n for(var i=-(dim/2); i<=(dim/2); i++){\n iScaled = i * 50;\n moveToTx(iScaled, 0, -length/2, Tx); lineToTx(iScaled, 0, length/2, Tx);\n moveToTx(-length/2, 0, iScaled, Tx); lineToTx(length/2, 0, iScaled, Tx);\n }\n context.stroke();\n }\n // Animation loop\n function draw(){\n // Quick clear for re-draw as well as resize in event of window change\n canvas.width = window.innerWidth; canvas.height = window.innerHeight;\n context.strokeStyle = PRIMARY_TEXT_COLOR;\n\n // Transforms\n var TrotX = m4.rotationX(thetaXSpindle*Math.PI); // Spindle spins independantly of the world.\n var TrotY = m4.rotationY(thetaYSpindle*Math.PI);\n var Ttrans = m4.translation([spindleX,0,spindleZ]);\n Tspindle = m4.multiply(TrotX, TrotY);\n Tspindle = m4.multiply(Tspindle, Ttrans);\n\n var eye = [Math.sin(theta*Math.PI)*radius, camPosY, Math.cos(theta*Math.PI)*radius];\n var target = [0,0,0];\n var up = [0,1,0];\n var TlookAt = m4.lookAt(eye, target, up);\n var Tcamera = m4.inverse(TlookAt);\n Tcamera = m4.multiply(Tcamera, m4.scaling([1,-1,1])); // flip to point Y up\n Tcamera = m4.multiply(Tcamera, m4.translation([canvas.width/2, canvas.height/2, 0]));\n\n context.strokeStyle = 'rgba(255, 255, 255, .15)';\n drawGrid(Tcamera);\n context.strokeStyle = \"lightblue\";\n commits.forEach(function(curr){\n curr.draw(Tcamera);\n });\n // Animation transforms\n thetaYSpindle += rotSpeedY;\n thetaXSpindle += rotSpeedX;\n TspindleMod = m4.multiply(Tspindle, Tcamera);\n // Update the global variable\n mouseToWorld = m4.inverse(TspindleMod);\n\n context.strokeStyle = \"white\";\n drawAxes(TspindleMod);\n context.strokeStyle = \"lightblue\";\n drawPicture(TspindleMod, vectArray, true);\n context.translate(canvas.width/2, canvas.height/2); // Move orgin for UI\n ui.showManual();\n ui.showStats(rotSpeedX, rotSpeedY, spindleX, spindleZ);\n window.requestAnimationFrame(draw);\n }\n draw();\n\n\n // EVENT LISTENERS\n document.onmousemove = function(e){\n currMousePos = [e.pageX, e.pageY, 0];\n }\n document.onmousedown = function(event){\n if(currPos){\n prevPos = currPos\n }\n currPos = [event.clientX, event.clientY, 0];\n currPos = m4.transformPoint(mouseToWorld, currPos);\n vectArray.push(currPos);\n }\n document.addEventListener('keydown', (event) => {\n const keyName = event.key;\n if(keyName === \"c\"){\n // Store drawing\n var drawing = new Drawing(Tspindle, vectArray);\n drawing.rotSpeedY = rotSpeedY;\n drawing.rotSpeedX = rotSpeedX;\n commits.push(drawing);\n // Clear drawing\n vectArray = [];\n currPos = null;\n }\n if(keyName === \"x\"){\n // pop last commit\n commits.pop();\n // Clear drawing\n vectArray = [];\n currPos = null;\n }\n // Controll axis'\n if(keyName === \"ArrowUp\"){\n event.preventDefault();\n rotSpeedX += stepSize;\n }\n if(keyName === \"ArrowDown\"){\n event.preventDefault();\n rotSpeedX -= stepSize;\n }\n if(keyName === \"ArrowLeft\"){\n event.preventDefault();\n rotSpeedY -= stepSize;\n }\n if(keyName === \"ArrowRight\"){\n event.preventDefault();\n rotSpeedY += stepSize;\n }\n if(keyName === \"w\"){\n event.preventDefault();\n camPosY += 1;\n }\n if(keyName === \"s\"){\n event.preventDefault();\n camPosY -= 1;\n }\n if(keyName === \"d\"){\n event.preventDefault();\n theta += .05;\n }\n if(keyName === \"a\"){\n event.preventDefault();\n theta -= .05;\n }\n if(keyName === \"l\"){\n event.preventDefault();\n spindleX += 5;\n }\n if(keyName === \"j\"){\n event.preventDefault();\n spindleX -= 5;\n }\n if(keyName === \"i\"){\n event.preventDefault();\n spindleZ += 5;\n }\n if(keyName === \"k\"){\n event.preventDefault();\n spindleZ -= 5;\n }\n });\n /** Drawing **/\n function Drawing(Tmod, array){\n this.Tmod = Tmod;\n this.array = array;\n // Animation transforms\n this.rotSpeedY;\n this.rotSpeedX;\n // Drawing\n this.draw = function(Tcamera){\n var rot = m4.rotationX(Math.PI*this.rotSpeedX);\n this.Tmod = m4.multiply(rot,this.Tmod);\n rot = m4.rotationY(Math.PI*this.rotSpeedY);\n this.Tmod = m4.multiply(rot, this.Tmod);\n var Tx = m4.multiply(this.Tmod, Tcamera);\n drawPicture(Tx, this.array, false);\n }\n }\n}", "function canvasToCartesianAxisCoords(pos) {\n // return an object with x/y corresponding to all used axes\n var res = {},\n i, axis;\n for (i = 0; i < xaxes.length; ++i) {\n axis = xaxes[i];\n if (axis && axis.used) {\n res[\"x\" + axis.n] = axis.c2p(pos.left);\n }\n }\n\n for (i = 0; i < yaxes.length; ++i) {\n axis = yaxes[i];\n if (axis && axis.used) {\n res[\"y\" + axis.n] = axis.c2p(pos.top);\n }\n }\n\n if (res.x1 !== undefined) {\n res.x = res.x1;\n }\n\n if (res.y1 !== undefined) {\n res.y = res.y1;\n }\n\n return res;\n }", "function plot() {\n\n}", "function CartesianChart(config)\n{\n CartesianChart.superclass.constructor.apply(this, arguments);\n}", "function axis(ctx, color, axisx, axisy, px, d1,py, d2) {\n var w = ctx.canvas.width;\n var h = ctx.canvas.height;\n\n ctx.strokeStyle = color;\n\n //if axis function is below grid function\n // and grid is dotted this removes the axis from\n // dotted back to normal line\n ctx.setLineDash([0, 0]);\n\n //if the axis is undefined in both direction creates it at the far left corner like a normal graph\n if (axisy == undefined && axisx == undefined) {\n lines(ctx, 1, h - 1, w - 1, h - 1, 1);\n lines(ctx, 1, 1, 1, h - 1, 1);\n }\n\n //the same as above\n else if (axisx == w && axisy == h) {\n lines(ctx, 1, axisy - 1, axisx - 1, axisy - 1, 1);\n lines(ctx, 1, 1, 1, axisy - 1, 1);\n }\n\n //if axisx and axis y are numbers the axis will be created inwards to the number that has been created.\n else if (typeof axisx == \"number\" && typeof axisy == \"number\") {\n lines(ctx, 0, axisy, w, axisy, 3);\n lines(ctx, axisx, 0, axisx, h, 3);\n }\n\n // if axisy and axisx are inputed as middle the x and y axis will be created in the center of the canvas\n else if (axisx == \"middle\" && axisy == \"middle\") {\n axisx = w / 2;\n axisy = h / 2;\n\n lines(ctx, h / 2, w, h / 2, 2);\n\n lines(ctx, w / 2, w / 2, h, 2);\n }\n\n // creates the x for the creation of axis points as pf now only at the positive x axis\n if (px == \"px\" && py == \"py\") {\n let i = axisx;\n let j = 0;\n let k = 0;\n let l = 0;\n\n //creates positive x axis points\n for (i = axisx; i <= w; i += d1) {\n lines(ctx, i, axisy, i, axisy + 10, 1);\n }\n\n //create negative y axis points\n for (l = axisy; l >= 0; l -= d2) {\n lines(ctx, axisx, l, axisx - 10, l, 1);\n }\n\n //creates positive y axis points\n for (j = axisy; j <= h; j += d2) {\n lines(ctx, axisx - 10, j, axisx, j, 1);\n }\n //creates negative x axis points\n for (k = axisx; k >= 0; k -= d1) {\n lines(ctx, k, axisy, k, axisy + 10, 1);\n }\n }\n\n else if(px =='px' && py == undefined){\n let i = 0;\n let k = 0;\n //creates positive x axis points\n for (i = axisx; i <= w; i += d1) {\n lines(ctx, i, axisy, i, axisy + 10, 1);\n }\n\n //creates negative x axis points\n for (k = axisx; k >= 0; k -= d1) {\n lines(ctx, k, axisy, k, axisy + 10, 1);\n }\n }\n}", "function createCoords(svgid,parameters) {\r\n\tthis.svgid = svgid;\r\n\tthis.id = svgid+'_coords';\r\n\tthis.svg = document.getElementById(svgid);\r\n\tthis.fontSize = parseFloat(getComputedStyle(this.svg).fontSize);\r\n\tlet rem = this.fontSize;\r\n\tlet re = new RegExp(\"rem\");\r\n\t\r\n\t\t// MARGINS\r\n\tlet margin = new Array();\r\n\tlet marginTop,marginRight,marginBottom,marginLeft;\t\r\n\tif( parameters['margin'] != undefined ) { margin = parameters['margin']; }\t\r\n\tmarginTop = re.test(margin[0]) ? parseFloat(margin[0])*rem : parseFloat(margin[0]);\r\n\tmarginRight = re.test(margin[1]) ? parseFloat(margin[1])*rem : parseFloat(margin[1]);\r\n\tmarginBottom = re.test(margin[2]) ? parseFloat(margin[2])*rem : parseFloat(margin[2]);\r\n\tmarginLeft = re.test(margin[3]) ? parseFloat(margin[3])*rem : parseFloat(margin[3]);\r\n\tmargin = [marginTop,marginRight,marginBottom,marginLeft];\r\n\tthis.margin = margin;\r\n\tthis.marginTop = marginTop; this.marginRight = marginRight; this.marginBottom = marginBottom; this.marginLeft = marginLeft;\r\n\t\r\n\t\t// svg area [min-u,max-v,width,height] of the plotBox\t\t\r\n\tthis.plotBox = [marginLeft,marginTop,this.svg.clientWidth-(marginRight+marginLeft),this.svg.clientHeight-(marginTop+marginBottom)];\r\n\t\t// svg coordinate Range\r\n\tthis.uMin = this.plotBox[0];\r\n\tthis.uMax = this.plotBox[0]+this.plotBox[2];\r\n\tthis.vMin = this.plotBox[1];\r\n\tthis.vMax = this.plotBox[1]+this.plotBox[3];\t\r\n \r\n\tthis.defineCoords(parameters);\r\n\t\r\n\t // define two special groups for this coordinate system\r\n var g1 = document.createElementNS('http://www.w3.org/2000/svg', 'g');\r\n var g2 = document.createElementNS('http://www.w3.org/2000/svg', 'g');\r\n\t\r\n /* this.g1.id = this.id+'_g1'; this.g2.id = this.id+'_g2'; */\r\n this.svg.g1 = g1; // default for plots\r\n this.svg.g2 = g2; // default for axes\r\n this.svg.appendChild(g2);\r\n this.svg.appendChild(g1);\r\n\t\r\n\tif( parameters['clip'] == true ) { this.plotObject('clip',{'x1':this.xMin,'x2':this.xMax,'y1':this.yMin,'y2':this.yMax}); }\r\n} // END function createCoords()", "function generatePositions() {\n rows = [];\n columns = [];\n if (gridOption.enableRow) {\n //use coordinate.y to generate rows\n if (coordinate.y && coordinate.y.model.rotate == 90) {\n coordinate.y.forEach(function(i,length){\n rows.push(coordinate.y.model.beginY-length)\n });\n gridOption._x = coordinate.x.model.beginX;\n } else if (coordinate.x && coordinate.x.model.rotate == 90) {\n coordinate.x.forEach(function (i, length) {\n rows.push(coordinate.x.model.beginY - length)\n });\n\n gridOption._x = coordinate.y.model.beginX;\n }\n gridOption.width = coordinate.size().width || 0;\n gridOption.rows = rows;\n }\n if (gridOption.enableColumn) {\n if (coordinate.y && coordinate.y.model.rotate == 0) {\n coordinate.y.forEach(function(i,length){\n columns.push(coordinate.y.model.beginX+length)\n });\n gridOption._y = coordinate.x.model.beginY;\n } else if (coordinate.x && coordinate.x.model.rotate == 0) {\n coordinate.x.forEach(function (i, length) {\n columns.push(coordinate.x.model.beginX + length)\n });\n gridOption._y = coordinate.y.model.beginY;\n }\n gridOption.height = coordinate.size().height || 0;\n gridOption.columns = columns;\n }\n\n }", "plotJourneys() {\n for (let j of this.mapJourneys) {\n //plot ghost Session\n j.plotSessions(this);\n }\n }", "function drawPCGraph() {\r\n\r\n\tvar x = d3.scale.ordinal().rangePoints([0, 480], 1),\r\n y= {};\r\n \r\n for (var dim in cars[0]) {\r\n\t if (dim != \"name\") {\r\n\t\t y[dim] = d3.scale.linear()\r\n\t\t\t .domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])\r\n\t\t .range([height,0]);\r\n\t }\r\n }\r\n \r\n//sets the x domain dimensions\r\n x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != \"name\";}));\r\n\r\n//draws the polylines\r\n for (var i=1; i< cars.length; i++) { //for each car\r\n\r\n//prepare the coordinates for a polyline\r\n\t var lineData = []; //initialize an array for coordinates of a polyline\r\n\t for (var prop in cars[0]) { \r\n\t if (prop != \"name\" ) {\r\n\t var point = {}; \r\n\t var val = cars[i][prop];\r\n\t\t point['x'] = x(prop); \r\n\t point['y'] = y[prop](val);\r\n\t lineData.push(point);\r\n\t }\r\n\t }\r\n\r\n//draws a polyline based on the coordindates \r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"polyline\")\r\n\t .append(\"path\")\r\n\t\t .attr(\"d\", line(lineData))\r\n\t\r\n//Changes stroke red when mouseover\r\n\t.on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t.style(\"stroke\",\"red\")\r\n\t })\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.style(\"stroke\",null)\r\n\t\t\r\n})\r\n }\r\n\r\n var g = chart.selectAll(\".dimension\")\r\n\t .data(dimensions)\r\n\t .enter().append(\"g\")\r\n\t .attr(\"class\", \"dimension\")\r\n\t .attr(\"transform\", function(d) { return \"translate(\" + x(d) + \")\"; }) //translate each axis\r\n\r\n g.append(\"g\")\r\n\t .attr(\"class\", \"axis\")\r\n\t .each(function(d) { d3.select(this).call(axis.scale(y[d])); })\r\n\t .append(\"text\")\r\n\t .style(\"text-anchor\", \"middle\")\r\n\t .attr(\"y\", -4)\r\n\t .text(function(d) { return d; });\r\n\t \r\n \r\n}", "function pricesGraph() {\n for (let i = 0; i < houses.data.length; i++) {\n\n // Map colors\n let color = mapColor(ps[i]);\n\n // Render\n fill(color.r, color.g, color.b, 255);\n noStroke();\n ellipse(xs[i] + xoff, ys[i] + yoff, 2, 2);\n }\n}", "function Cartesian2D(name) {\n Cartesian.call(this, name);\n}", "function Cartesian2D(name) {\n Cartesian.call(this, name);\n}", "function Cartesian2D(name) {\n Cartesian.call(this, name);\n}", "function Cartesian2D(name) {\n Cartesian.call(this, name);\n}", "function Cartesian2D(name) {\n Cartesian.call(this, name);\n}", "function render() {\n dots\n .attr(\"cx\", function (d) {\n return project(d).x;\n })\n .attr(\"cy\", function (d) {\n return project(d).y;\n });\n }", "function draw() {\n \n // background(237, 34, 93);\n for(let i = 0; i < h; i += 10) {\n for(let j = 0; j < w; j+= 10) {\n // if(i == cx[counting] && j == cy[counting]) {\n point_color = 222;\n strokeWeight(1);\n stroke(point_color);\n point(cx[counting],cy[counting])\n counting++;\n // } \n } \n // line(i, 0, i, h)\n counting = 0;\n }\n\n \n}", "function drawGraph(xArray, yArray) {\n var xMax = Math.max(...xArray);\n var xMin = Math.min(...xArray);\n //var yMax = Math.max(...yArray);\n //var yMin = Math.min(...yArray);\n\n var yMax = nParticles * 1.13;\n var yMin = 0;\n\n // Conversion between the screen coordiantes and the axis coordiantes\n function xScreen(x) {\n return (x - xMin) / (xMax - xMin) * canvasGraph.width + 5;\n }\n function yScreen(y) {\n return canvasGraph.height - (y - yMin) / (yMax - yMin) * canvasGraph.height - 5;\n }\n\n var x = xArray[0];\n var y = yArray[0];\n ctxGraph.moveTo(xScreen(x), yScreen(y));\n for (var i = 1; i <= xArray.length; i++) {\n x = xArray[i];\n y = yArray[i];\n ctxGraph.lineTo(xScreen(x), yScreen(y));\n }\n}", "drawcrosshairs() {\n \n if (this.internal.volume===null) \n return;\n \n for (var i=0;i<=2;i++) \n this.internal.slices[i].drawcrosshairs(this.internal.slicecoord);\n \n // Update Dat.GUI\n if (this.internal.datgui.gui !== null) {\n this.internal.datgui.data.xcoord = this.internal.slicecoord[0];\n this.internal.datgui.data.ycoord = this.internal.slicecoord[1];\n this.internal.datgui.data.zcoord = this.internal.slicecoord[2];\n this.internal.datgui.data.tcoord = this.internal.slicecoord[3];\n this.updateDatGUIControllers();\n }\n this.drawtext();\n this.informToRender(); \n //this.drawcolorscale();\n }", "function equilatGrid(L,R,dx,dy){\n let yVals = [];\n let ytip = 70;\n let xtip = 300;\n let yChange = dy/10;\n let xChange = 2*dx/10\n for(let i = 0; i < 9; i++){\n yVals.push((ytip+dy)-yChange*(i+1));\n }\n push();\n let x1, x2, y1, y2;\n // Carrier grid\n stroke(255,100,0,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-L[1])/L[0];\n y2 = ytip + dy;\n x2 = (xtip-dx) + xChange*(i+1);\n line(x1,y1,x2,y2);\n }\n \n // Solvent grid\n stroke(128,0,128,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-R[1])/R[0];\n y2 = ytip + dy;\n x2 = (xtip+dx) - xChange*(i+1);\n line(x1,y1,x2,y2);\n }\n // Solute grid\n stroke(0,0,255,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-L[1])/L[0];\n y2 = y1;\n x2 = (y2-R[1])/R[0];\n line(x1,y1,x2,y2);\n }\n pop();\n}", "display(){\n fill (0);\n ellipse(this.x, this.y, 4, 4);\n }", "draw_axes(gfx) {\n // Drawing in white\n gfx.noFill();\n gfx.stroke(255);\n\n // Draw the unit circle (width and height 2)\n gfx.ellipse(0, 0, 2, 2);\n\n // Draw x- and y-axes\n gfx.line(-10, 0, 10, 0);\n gfx.line(0, -10, 0, 10);\n }", "function apskritimoPlotas(spindulys) {\n console.log('Apskritimo plotas');\n return Math.PI * (spindulys ** 2);\n}", "plotRoutes() {\n for (let r of this.mapRoutes) {\n r.plotPath(this.map);\n }\n }", "function plotAll() {\n d3.select(\"#scatter-macro-1 svg\").remove()\n d3.select(\"#scatter-macro-2 svg\").remove()\n d3.select(\"#scatter-micro-1 svg\").remove()\n d3.select(\"#scatter-micro-2 svg\").remove()\n doPlot(\"scatter-macro-1\", voltageArr, \"Voltage\", maxLinearVelocityArr, \"Max. Linear Velocity\");\n doPlot(\"scatter-macro-2\", currentArr, \"Current\", accelerationArr, \"Acceleration\");\n doPlot(\"scatter-micro-1\", voltageArr, \"Voltage\", maxAngularVelocityArr, \"Max. Angular Velocity\");\n doPlot(\"scatter-micro-2\", currentArr, \"Current\", torqueArr, \"Torque\");\n}", "show() {\n fill(0, 10, 100);\n noStroke();\n\n ellipse(this.x, this.y, this.mainSize, this.mainSize);\n ellipse(this.x - 18, this.y + 20, this.subSize, this.subSize);\n ellipse(this.x - 6, this.y + 20, this.subSize, this.subSize);\n ellipse(this.x + 6, this.y + 20, this.subSize, this.subSize);\n ellipse(this.x + 18, this.y + 20, this.subSize, this.subSize);\n }", "function zoom_arc_plot(v_chr, v_start, v_end) {\n // chosen chromosome for zoom\n var xScale_zoomed_chrom,\n // all other chromosomes\n xScale_unzoomed_chrom;\n\n // margin for the zoom function of the arc plot\n var margin = {\n top: 1,\n right: 1,\n bottom: 20,\n left: 10\n };\n\n // padding between the chromosomes\n var padding = 2;\n // width and height of the plot\n var w = 800 - margin.left - margin.right - (24 * padding);\n var h = 600 - margin.top - margin.bottom; \n // chromosome length without the chosen chromosome\n var chrom_scale_compare = chrom_length - chromLength[(v_chr -1)];\n\n //for loop to create the length of the chromosomes\n var chromLength_scaled = [];\n for (var i = 0;i < chromLength.length; i++) {\n var temp;\n if ((v_chr - 1) == i) {\n chromLength_scaled.push(w/2);\n } else {\n temp = ((w/2) / chrom_scale_compare) * chromLength[i];\n chromLength_scaled.push(temp);\n }\n }\n\n //for loop to calculate the x position\n var chrom_x_position = [0];\n var Scaled_abs_xposition = 0;\n for (var i = 0; i < chrom_abs_length.length ; i++) {\n Scaled_abs_xposition = Scaled_abs_xposition + chromLength_scaled[i] + padding;\n chrom_x_position.push(Scaled_abs_xposition);\n }\n\n // var for the chromsome length of the chosen area\n var selected_chrom_area = v_end - v_start;\n // array for the ticks\n var ticks_chrom_chosen = [];\n // for loop to create the ticks for the chosen chromosome\n for (var i = 0; i< 20 ; i++) {\n var temp_x,\n temp_label,\n temp_range,\n temp_range_label,\n temp;\n if(selected_chrom_area == 0) {\n temp_x = chrom_x_position[(v_chr - 1)] + (chromLength_scaled[(v_chr - 1)] / 20) * i;\n temp_label = Math.round(((chromLength[(v_chr - 1)] / 20) / 1000000) * i) + \"MB\";\n } else {\n temp_x = chrom_x_position[(v_chr - 1)] + (chromLength_scaled[(v_chr - 1)] / 20) * i;\n temp = Math.round(v_start + (selected_chrom_area / 20)* i);\n if(temp < 50000) {\n temp_range = 1;\n temp_range_label = \"\";\n } else if(temp < 50000000) {\n temp_range = 1000;\n temp_range_label = \"Kb\";\n } else {\n temp_range = 1000000;\n temp_range_label = \"Mb\";\n }\n temp_label = Math.round((temp / temp_range)) + temp_range_label; \n }\n var obj = {};\n obj[\"x\"] = temp_x;\n obj[\"label\"] = temp_label;\n ticks_chrom_chosen.push(obj);\n }\n\n // array to store all nodes and all links which should not be displayed in the zoom function\n zoom_allNodes = [];\n zoom_links = [];\n links.forEach( function(d) {\n if((allNodes[d.source].chrom == v_chr \n && allNodes[d.source].bp_position >= v_start \n && allNodes[d.source].bp_position <= v_end) ||\n (allNodes[d.source].chrom == v_chr && selected_chrom_area == 0) ||\n (allNodes[d.target].chrom == v_chr && \n allNodes[d.target].bp_position >= v_start && \n allNodes[d.target].bp_position <= v_end) ||\n (allNodes[d.target].chrom == v_chr && selected_chrom_area == 0)) {\n\n zoom_allNodes.push(allNodes[d.source]);\n zoom_allNodes.push(allNodes[d.target]);\n zoom_links.push(d);\n }\n });\n \n // add nodes with degree zero\n allNodes.forEach( function (d) {\n var in_zoomed_chrom = (d.chrom == v_chr && d.degree == 0);\n var in_zoomed_region = (d.bp_position >= v_start && d.bp_position <= v_end);\n\n if(in_zoomed_chrom && in_zoomed_region) {\n zoom_allNodes.push(d);\n }\n });\n \n // sort and make the zoom_allnodes function unique\n var temp_zoomnodes = [];\n\n zoom_allNodes.forEach( function (d) {\n temp_zoomnodes.push(d.id);\n });\n\n temp_zoomnodes = sort_unique(temp_zoomnodes);\n\n zoom_allNodes = [];\n\n temp_zoomnodes.forEach( function (d) {\n zoom_allNodes.push(allNodes[d]);\n });\n \n \n // create SVG for the plot\n var svg = d3.select(\"#chart\")\n .append(\"svg\")\n .attr(\"id\", \"mainplot\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n d3.select('#ld_container').selectAll('svg').remove();\n\n var chromosome_container = svg.selectAll(\"g.group\")\n .data(chromLength)\n .enter().append(\"svg:g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(\" + chrom_x_position[i] + \",\" + height_chrom_bar + \")\"; \n })\n // scales the width of chromosomes\n .attr(\"width\", function(d, i) {\n create_ld_plot(i+1, chromLength_scaled[i], chrom_x_position[i], padding, v_chr, v_start, v_end); \n return chromLength_scaled[i]; \n })\n .attr(\"height\", 40)\n .attr(\"class\", function (d,i) {\n return \"chrom\" + (i+1);\n });\n\n var id_chrom_zoom = \"g.chrom\" + (v_chr);\n // store the the new startpoint\n var startzoom = 0;\n if (v_start == 0 && v_end == 0) {\n var x_scale_zoom = d3.scale.linear()\n .domain([0, chromLength[(v_chr -1)]])\n .range([0, chromLength_scaled[(v_chr -1)]]);\n } else {\n var x_scale_zoom = d3.scale.linear()\n .domain([v_start, v_end])\n .range([0, chromLength_scaled[(v_chr -1)]]);\n }\n \n //function to zoom with the mouse\n var brush = svg.select(id_chrom_zoom)\n .append(\"g\")\n .attr(\"class\", \"brush\")\n .call(d3.svg.brush().x(x_scale_zoom)\n .on(\"brushstart\", brushstart)\n .on(\"brush\", brushmove)\n .on(\"brushend\", brushend))\n .selectAll(\"rect\")\n .attr(\"height\", 40) \n .style(\"stroke\", \"blue\")\n .style(\"fill\", \"blue\")\n .style(\"opacity\" , 0.7);\n\n function brushstart() { \n brush.classed(\"selecting\", true);\n }\n\n function brushmove() {\n var r = d3.event.target.extent(); \n document.getElementById(\"texzs\").value = Math.round(r[0]);\n document.getElementById(\"texze\").value = Math.round(r[1]);\n }\n\n function brushend() { \n brush.classed(\"selecting\", !d3.event.target.empty());\n }\n\n // create rectangle in the g container\n var chrom_bar = chromosome_container.append(\"rect\")\n .attr(\"transform\", \"translate(\" + 0 + \",\" + 0 + \")\")\n .attr(\"class\", \"rect\")\n // scales the width of chromosomes\n .attr(\"width\", function(d, i) {\n return chromLength_scaled[i]; \n })\n .attr(\"height\", 20)\n .style(\"fill\", function(d, i) {\n return chromcolour[i];\n })\n .style(\"stroke\", function(d, i) {\n return chromcolour[i];\n });\n\n //create ticks for the chrom_bar\n svg.selectAll(\"line\")\n .data(ticks_chrom_chosen)\n .enter().append(\"line\")\n .attr(\"class\", \"tickchromosome\")\n .attr(\"x1\", function(d) {\n return + d.x;\n })\n .attr(\"y1\", height_nodes + 25)\n .attr(\"x2\", function (d) {\n return + d.x;\n })\n .attr(\"y2\", height_nodes + 30)\n .style(\"stroke\", \"#000\")\n\n svg.selectAll(\"text\")\n .data(ticks_chrom_chosen)\n .enter().append(\"text\")\n .attr(\"class\", \"label\")\n .attr(\"dy\", \".35em\")\n .attr(\"transform\", function (d) {\n return \"translate(\"+ d.x + \",\" + (height_nodes + 38) + \")\" + \"rotate(90)\"; \n })\n .attr(\"font-size\", \"10\")\n .text(function (d) {\n return d.label; \n });\n\n // create the label for the chromosomes\n chromosome_container.append(\"svg:text\")\n .attr(\"class\", \"chromosom_number\")\n // 2* padding for double digits chromosome numbers\n .attr(\"transform\", function (d, i) {\n if (i == (v_chr-1)) {\n return \"translate(\" + (8 * padding) + \",\" + 15 + \")\";\n } else {\n return \"translate(\" + (4 * padding) + \",\" + 35 + \")\"; \n }\n })\n .append(\"svg:textPath\")\n .text(function(d, i) {\n return i + 1;\n })\n .attr(\"font-size\", function (d, i) {\n if (i == (v_chr-1)) {\n return \"14px\";\n } else {\n return \"9px\";\n }\n })\n .attr(\"text-anchor\", \"end\")\n .style(\"fill\", function(d, i) {\n if (i == (v_chr - 1)) {\n return \"#000\";\n } else {\n return chromcolour[i];\n }\n })\n .style(\"stroke\", function(d, i) {\n if (i == (v_chr - 1)) {\n return \"#000\";\n } else {\n return chromcolour[i];\n }\n });\n\n // object to store the position of the zoomed chromosomes\n var id_chosen = [];\n // create circles for the location of the interacting SNPs \n svg.selectAll(\"circle.vertex\")\n .data(zoom_allNodes)\n .enter().append(\"circle\")\n .attr(\"class\", \"circle_zoom\")\n .style(\"fill\", function(d) {\n return graphColor(d.probe_group);\n })\n .style(\"stroke\", function(d) {\n return graphColor(d.probe_group);\n })\n // positioning the SNPs\n .attr(\"cx\", function(d) {\n if(d.chrom == v_chr && selected_chrom_area == 0) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1 )] + \n ((w/2) / chromLength[(d.chrom - 1)]) * d.bp_position; \n return id_chosen[d.id];\n\n } else if (d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position >= v_start && \n d.bp_position <= v_end) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1)] + \n ((w/2) / selected_chrom_area) * (d.bp_position - v_start);\n return id_chosen[d.id];\n\n } else if(d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position < v_start ) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1)];\n return id_chosen[d.id];\n\n } else if (d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position > v_end) {\n id_chosen[d.id] = chrom_x_position[(d.chrom - 1)] + (w/2);\n return id_chosen[d.id];\n\n } else if(d.chrom != v_chr) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1 )] +\n ((w/2) / chrom_scale_compare) * d.bp_position; \n return id_chosen[d.id];\n\n } else {\n return id_chosen[d.id] = \"NaN\" ;\n }\n })\n .attr(\"cy\", height_nodes)\n .attr(\"r\", function(d) {\n if(id_chosen[d.id] == \"NaN\" && d.chrom == v_chr ) {\n return 0;\n } else {\n return 2;\n }\n })\n // to get information about the SNPs from different sources, if you click on a circle\n .on(\"click\", function (d,i) { externalLink(d, i); });\n\n // show degree as tooltip - title\n svg.selectAll(\"g .circle_zoom\") \n .append(\"title\")\n .text(function(d) {\n return \"degree: \" + two_dec(d.degree) + \"\\nSNP: \" + d.rs + \"\\nid: \" + d.id + \n \"\\nposition: \" + d.bp_position\n });\n\n // draw the edges between linked SNP's nodes\n var arcs = svg.selectAll(\"path.link\")\n .data(zoom_links)\n .enter().append(\"path\")\n .attr(\"class\", \"link\")\n .style(\"stroke\", function(d) {\n return graphColor(d.probe_group);\n })\n .style(\"stroke\", 1)\n .style(\"stroke-width\", 2.5)\n .style(\"opacity\", 3.7)\n .style(\"fill\", \"none\")\n // function to create the arc for the links\n .attr(\"d\", function (d) {\n // to ensure that the path is drawn correct \n if(d.source > d.target) {\n var temp;\n temp = d.source;\n d.source = d.target;\n d.target = temp;\n } \n\n if (allNodes[d.source].chrom == v_chr || allNodes[d.target].chrom == v_chr) {\n var start_position_x = id_chosen[d.source],\n start_position_y = height_nodes ;\n\n var end_position_x = id_chosen[d.target],\n end_position_y = height_nodes ;\n } else {\n var start_position_x = \"NaN\",\n start_position_y = height_nodes ;\n\n var end_position_x = \"NaN\",\n end_position_y = height_nodes ;\n }\n\n // to ensure that the arc links are drawn on the correct side \n if (end_position_x < start_position_x) {\n var temp; \n temp = end_position_x; \n end_position_x = start_position_x;\n start_position_x = temp; \n }\n\n var radius = (end_position_x - start_position_x) / 2 ;\n\n var c1x = start_position_x,\n c1y = start_position_y - radius,\n c2x = end_position_x,\n c2y = end_position_y - radius ;\n\n return \"M\" + start_position_x + \",\" + start_position_y + \" C\" + c1x +\n \",\" + c1y + \",\" + c2x + \",\" + c2y + \" \" + \n end_position_x + \",\" + end_position_y ; \n })\n .on(\"click\" , function(d,i) { return highlight_snp_pairs(d, i);});\n\n // creates the colour scale indicator for the ld plot\n createColourScale_ldplot();\n}", "function plotGraph(){\n createAxis();\n // zoom.x(x).y(y);\n // console.log('setting scales');\n // console.log(x);\n // console.log(y);\n updateBoundaryGraph.setScales(x,y);\n }", "function drawLocs(){\n\tfor (var i = 0; i <= loc.length; i++){\n fill(0, 200);\n ellipse(locX[i], locY[i], locSize, locSize);\n fill(255);\n text(loc[i],locX[i], locY[i]);\n }\n}", "coordinatesByAxes(coordinates, repetitions) {\n const {\n repetitionsAlongLatticeVectorA,\n repetitionsAlongLatticeVectorB,\n repetitionsAlongLatticeVectorC,\n } = repetitions;\n const maxNumberOfRepetitions = Math.max(\n repetitionsAlongLatticeVectorA,\n repetitionsAlongLatticeVectorB,\n repetitionsAlongLatticeVectorC,\n );\n\n if (\n !repetitionsAlongLatticeVectorA &&\n !repetitionsAlongLatticeVectorB &&\n !repetitionsAlongLatticeVectorC\n )\n return coordinates;\n\n let columns = coordinates.reduce((res, item, index) => {\n if (index % maxNumberOfRepetitions === 0) {\n res[res.length] = [item];\n } else {\n res[res.length - 1].push(item);\n }\n return res;\n }, []);\n\n if (repetitionsAlongLatticeVectorA < maxNumberOfRepetitions) {\n columns = columns.slice(0, maxNumberOfRepetitions * repetitionsAlongLatticeVectorA);\n }\n if (repetitionsAlongLatticeVectorB < maxNumberOfRepetitions) {\n columns = columns.filter(\n (item, index) =>\n index % maxNumberOfRepetitions < repetitionsAlongLatticeVectorB,\n );\n }\n if (repetitionsAlongLatticeVectorC < maxNumberOfRepetitions) {\n columns = columns.map((arr) =>\n arr.filter((item, index) => index < repetitionsAlongLatticeVectorC),\n );\n }\n return columns.reduce((res, item) => {\n res.push(...item);\n return res;\n }, []);\n }", "function drawScatterMatrix(trips){\n\n\tspeed = [];\n\tdistance =[];\n\tduration=[];\n\tfor (var i =0;i<trips.length;i++)\n\t{\n\t speed[i]=trips[i].avspeed;\n\t\t distance[i]=trips[i].distance;\n\t\t duration[i]=trips[i].duration;\n\t}\n\n\tgoogle.charts.load('current', {'packages':['corechart']}); \n google.charts.setOnLoadCallback(drawScatterMatrixCallBack(speed,distance,duration)); \n}", "function drawXY(){\r\n//setting the x and y domains\r\n x.domain([d3.min(cars, function(d) { return d.year; }), d3.max(cars, function(d) { return d.year; })]);\r\n y.domain([d3.min(cars, function(d) { return d.power; }), d3.max(cars, function(d) { return d.power; })]);\r\n\r\n//setting the yPosition \r\n var yPos = height -20;\r\n//creating the x-Axis\r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"xaxis\")\r\n\t .attr(\"transform\", \"translate(0,\" + yPos + \")\")\r\n\t .call(xAxis);\r\n//creating the Y-axis\r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"yaxis\")\r\n\t .attr(\"transform\", \"translate(480,0)\")\r\n\t .call(yAxis);\r\n\r\n \r\n//selecting ths dot \r\n//adding attributes\t\r\n chart.selectAll(\".dot\")\r\n\t .data(cars)\r\n\t .enter().append(\"circle\")\r\n\t .attr(\"class\", \"dot\")\r\n\t .attr(\"cx\", function(d) { return x(d.year); })\r\n\t .attr(\"cy\", function(d) { return y(d.power); })\r\n\t .attr(\"r\", 3)\r\n\t \r\n//the mouseover function that fills the dots red when the mouse is over them\r\n\t .on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t\t.attr(\"fill\", \"red\")\r\n\t })\r\n//the mouseout function that changes the dots back to normal color\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.attr(\"fill\", \"black\")\r\n\t\t\r\n})\r\n\t\r\n \r\n}", "function draw_axis(c){\n\n let yplot = 40;\n let d =0;\n\n c.beginPath();\n c.strokeStyle = \"blue\";\n \n c.moveTo(count_block(5),count_block(5));\n c.lineTo(count_block(5), count_block(40));\n c.lineTo(count_block(80), count_block(40));\n\n c.moveTo(count_block(5), count_block(40));\n \n \n\n //loop for the y-axix labels\n for(let i = 1 ;i<=10;i++ ){\n c.strokeText(d, count_block(2), count_block(yplot));\n yplot-=5;\n d+=500;\n }\n c.stroke();\n\n}", "show() {\n fill(\"white\");\n ellipse(this.x, this.y, 30, 30);\n }", "function draw_axis(c){\n\n let yplot = 40;\n let d =0;\n\n c.beginPath();\n c.strokeStyle = \"black\";\n \n c.moveTo(count_block(5),count_block(5));\n c.lineTo(count_block(5), count_block(40));\n c.lineTo(count_block(80), count_block(40));\n\n c.moveTo(count_block(5), count_block(40));\n \n \n\n //loop for the y-axix labels\n for(let i = 1 ;i<=10;i++ ){\n c.strokeText(d, count_block(2), count_block(yplot));\n yplot-=5;\n d+=500;\n }\n c.stroke();\n\n}", "show() {\n fill(\"red\");\n ellipse(this.pos.x, this.pos.y, 15, 15)\n\n }", "display(){\r\n point(this.x,this.y);\r\n }", "display() {\n fill(127);\n stroke(200);\n strokeWeight(2);\n ellipse(this.x, this.y, this.r * 2, this.r * 2);\n }", "plot() {\n if (this.plot === 'Cumulative frequency plot' ||\n this.plot === 'Dot plot') {\n this.createPlot();\n }\n }", "plotRoutesCornerPoints() {\n for (let r of this.mapRoutes) {\n r.plotRouteCornerPoints(this.map);\n }\n }", "function render() {\n renderPlots1D();\n renderPlots2D();\n}", "display() {\n fill(127);\n stroke(200);\n strokeWeight(2);\n ellipse(this.x, this.y, this.radius * 2, this.radius * 2);\n }", "display() {\n fill(this.color, 100, 100);\n ellipse(this.x, this.y, this.diameter)\n }", "function plotDot(){\n\t for (var i = 0; i<data_dot.dot.length;i++) {\n ctx.beginPath();\n ctx.arc(data_dot.dot[i].x,data_dot.dot[i].y,7,0,2*Math.PI);\n ctx.fillStyle =\"#000\";\n ctx.fill();\n\t}\n}", "plot(){\n /* plot the X and Y axis of the graph */\n super.plotXAxis();\n super.plotYAxis();\n\n /* (re)draw the points, grouped in a single graphics element */\n let canvas = d3.select('svg#canvas_bioActivity > g#graph');\n canvas.selectAll('#points').remove();\n canvas.append('g')\n .attr('id', 'points')\n .attr('transform', 'translate('+this._margin.left+', 0)')\n ;\n /* Each data point will be d3 symbol (represented using svg paths) */\n let pts = d3.select('#points').selectAll('g')\n .data(this._data)\n /* each point belongs to the 'data-point' class its positioned in the graph\n * according to the associated (x,y) coordinates and its drawn using its\n * color and shape */\n let point = pts.enter().append('path')\n .attr('class', 'data-point')\n .attr('transform', d => 'translate('+d.x+' '+d.y+')')\n .attr('fill', d => d.color )\n .attr('d', function(d){\n let s = ['Circle','Cross','Diamond','Square','Star','Triangle','Wye']\n let symbol = d3.symbol()\n .size(50)\n .type(d3.symbols[s.indexOf(d.shape)])\n ;\n return symbol();\n })\n ;\n /* each point will also have an associated svg title (tooltip) */\n point.append('svg:title')\n .text((d) => {\n return 'Organism: '+d['Organism Name']+\n '\\nGene: '+d['Gene Symbol']+\n '\\nConcentation: '+d['Activity Concentration']+'nM';\n })\n ;\n }", "addCoords(coords) {\n var point = {\n x: this.xScale.invert(coords[0]),\n y: this.yScale.invert(coords[1]),\n c: currentClass\n };\n this.addPoint(point);\n }", "function init_xy(){\n\n\t\t\tg.append(\"line\")\n\t\t\t\t.attr(\"class\", \"xy\")\n\t\t\t\t.attr(\"x1\", 0)\n\t\t\t\t.attr(\"x2\", inner_w )\n\t\t\t\t.attr(\"y1\", h + 20)\n\t\t\t\t.attr(\"y2\", h + 20)\n\t\t\t\t.style(\"stroke\", \"#CCC\")\n\t\t\t\t.style(\"stroke-width\", \"1px\")\n\t\t\t\t.style(\"stroke-dasharray\", \"5 3\");\n\n\t\t}", "function renderGraphics(coords) {\n // Get the selected RGB combo vis params.\n var visParams = RGB_PARAMS[rgbSelect.getValue()];\n \n // Get the clicked point and buffer it.\n var point = ee.Geometry.Point(coords);\n var aoiCircle = point.buffer(45);\n var aoiBox = point.buffer(regionWidthSlider.getValue()*1000/2);\n \n // Clear previous point from the Map.\n map.layers().forEach(function(el) {\n map.layers().remove(el);\n });\n\n // Add new point to the Map.\n map.addLayer(aoiCircle, {color: AOI_COLOR});\n map.centerObject(aoiCircle, 14);\n \n // Build annual time series collection.\n LCB_PROPS['aoi'] = aoiBox;\n LCB_PROPS['startDate'] = startDayBox.getValue();\n LCB_PROPS['endDate'] = endDayBox.getValue();\n lcb.props = lcb.setProps(LCB_PROPS);\n \n // Define annual collection year range as ee.List.\n var years = ee.List.sequence(lcb.props.startYear, lcb.props.endYear);\n var col = ee.ImageCollection.fromImages(years.map(imgColPlan));\n\n // Display the image chip time series. \n displayBrowseImg(col, aoiBox, aoiCircle);\n\n OPTIONAL_PARAMS['chartParams']['vAxis']['title'] = indexSelect.getValue();\n\n // Render the time series chart.\n rgbTs.rgbTimeSeriesChart(col, aoiCircle, indexSelect.getValue(), visParams,\n chartPanel, OPTIONAL_PARAMS);\n}", "function draw(){\n\n drawGrid();\n var seriesIndex;\n\n if(!graph.hasData) {\n return;\n }\n\n if(graph.options.axes.x1.show){\n if(!graph.options.axes.x1.labels || graph.options.axes.x1.labels.length === 0) {\n seriesIndex = graph.options.axes.x1.seriesIndex;\n graph.options.axes.x1.labels= getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);\n }\n drawXLabels(graph.options.axes.x1);\n }\n if(graph.options.axes.x2.show && graph.hasData){\n if (!graph.options.axes.x2.labels || graph.options.axes.x2.labels.length === 0) {\n seriesIndex = graph.options.axes.x2.seriesIndex;\n graph.options.axes.x2.labels = getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);\n }\n drawXLabels(graph.options.axes.x2);\n }\n\n if (graph.options.axes.y1.show) {\n drawYLabels(graph.maxVals[graph.options.axes.y1.seriesIndex], graph.minVals[graph.options.axes.y1.seriesIndex], graph.options.axes.y1);\n }\n if (graph.options.axes.y2.show) {\n drawYLabels(graph.maxVals[graph.options.axes.y2.seriesIndex], graph.minVals[graph.options.axes.y2.seriesIndex], graph.options.axes.y2);\n }\n }", "display() {\n fill(0, 0, 0, 30)\n noStroke()\n ellipse(this.position.x, this.position.y, 4, 4)\n }", "createAxes () {\n }", "function plot(x) { \n var canvas = document.getElementById(\"canvas\"); \n var c = canvas.getContext(\"2d\"); \n var canvasStyle = window.getComputedStyle(canvas, null); \n var width = parseInt(canvasStyle.width);\n var height= parseInt(canvasStyle.height); \n var offset = (1 / (x.length - 1)) * width;\n var maxX = x.reduce(function(a, b) { return Math.max(a, b);});\n var minX = x.reduce(function(a, b) { return Math.min(a, b);});\n // scale the input values to be plotted\n function drawToScale(input) {\n return height - ( (input-minX)*height) / (maxX-minX); \n } \n // remove the previuous lines\n c.clearRect(0, 0, width, height) \n // plot the new ones\n c.beginPath();\n c.moveTo(0, drawToScale(x[0]));\n for (var i = 1; i < x.length; i++) {\n c.lineTo(i * offset, drawToScale(x[i]) );\n }\n c.stroke();\n }", "function drawCoords(currentLat, currentLon) {\n html += \"Latitude: \" + currentLat;\n html += \"<br>Longitude: \" + currentLon;\n $(\".longLat\").html(html);\n }", "display(){\n\n fill(255)\n ellipse(this.pos.x, this.pos.y, this.size);\n }", "function drawPoints(){\n\tfor (var i=0; i<p.length; i+=1){\n\t\tp[i].pplot(1);\n\t}\n}", "function cartesianAxisToCanvasCoords(pos) {\n // get canvas coords from the first pair of x/y found in pos\n var res = {},\n i, axis, key;\n\n for (i = 0; i < xaxes.length; ++i) {\n axis = xaxes[i];\n if (axis && axis.used) {\n key = \"x\" + axis.n;\n if (pos[key] == null && axis.n === 1) {\n key = \"x\";\n }\n\n if (pos[key] != null) {\n res.left = axis.p2c(pos[key]);\n break;\n }\n }\n }\n\n for (i = 0; i < yaxes.length; ++i) {\n axis = yaxes[i];\n if (axis && axis.used) {\n key = \"y\" + axis.n;\n if (pos[key] == null && axis.n === 1) {\n key = \"y\";\n }\n\n if (pos[key] != null) {\n res.top = axis.p2c(pos[key]);\n break;\n }\n }\n }\n\n return res;\n }", "display(){\n noStroke();\n fill(0,0,0);\n ellipse(this.location.x, this.location.y, this.mass * 5, this.mass * 5)\n noFill();\n stroke(255,255,255);\n ellipse(this.location.x, this.location.y, 200, 200);\n }", "function showGrid(ctx, axis, color = '#000000') {\n\tif (!axis.displayGrid) /* do not show grid */\n\t\treturn;\n\tif (!axis.set) { /* haven't set axis */\n\t\talert('You must set AXIS first!');\n\t\treturn;\n\t}\n\tlet lineSize = 1;\n\tlet i = 0;\n\tfor (; i < axis.xDivision.length; ++i) {\n\t\tx = axis.xDivision[i];\n\t\tdrawLine(ctx, x, axis.yLeftRange, x, axis.yRightRange,\n\t\t\tcolor, lineSize);\n\t}\n\t/* yLeft is pos and yRight is neg */\n\tfor (i = 0; i < axis.yDivision.length; ++i) {\n\t\ty = axis.yDivision[i];\n\t\tdrawLine(ctx, axis.xLeftRange, y, axis.xRightRange, y,\n\t\t\tcolor, lineSize);\n\t}\n}", "function Coords($map) {\n var that = this;\n\n this.x = $map.data('x');\n this.y = $map.data('y');\n this.iconTitle = '[' + this.x + ',' + this.y + ']';\n\n var $a = $map.find('a');\n if ($a.length) {\n $map.find('sup').unwrap();\n }\n\n var $markers = $map.find('.map-marker');\n\n this.initMap($map, false, $markers, true);\n\n that.createMapPopupTooltip();\n }", "show() {\r\n fill(255);\r\n ellipse(this.x, this.y, this.r*2);\r\n }", "function drawAxes() {\n canvas.select(\"#layer1\").append(\"g\")\n .attr(\"class\", \"grid\")\n .attr(\"transform\", \"translate(0,\" + h + \")\")\n .call(xAxis);\n canvas.select(\"#layer1\").append(\"g\")\n .attr(\"class\", \"grid\")\n .call(yAxis);\n}", "display() {\n\t\tfill(this.col);\n\t\tstroke(255);\n\t\t// for (var i = 1; i < meter - 1; i++) {\n\t\t// \tline(0,0, width, 0);\n\t\t// }\n\t\tnoStroke();\n\t\tellipseMode(CENTER);\n\t\tellipse(this.x, this.y, this.size, this.size);\n\t}", "function drawPrices(x,y,price){\r\n fill(244,24,100);\r\n text(price + \" gp\",x+200,35+(y*50));\r\n }", "function Grid( )\n{\n\tthis.lowerLeft = [37.74027582404923, -122.51225523839999];\n\tthis.upperRight = [37.81323020595205, -122.38651514053345];\n\tthis.latStep = 0.004053 / 3;\n\tthis.lngStep = 0.006287 / 4;\n\tthis.widthN = (this.upperRight[1] - this.lowerLeft[1]) / this.lngStep;\n\tthis.heightN = (this.upperRight[0] - this.lowerLeft[0]) / this.latStep;\n\t\n\tthis.plotGrid = function( bbox, row, column ) {\n\t\tvar grid = drawRegion_bbox( bbox );\n\t\tgrid.row = row;\n\t\tgrid.column = column;\n\t\tgrid.id = row * this.widthN + column;\n\t\t\n\t\tgoogle.maps.event.addListener(grid, 'mouseover', function(event) {\n\t\t\tmessage('Grid row ' + this.row + ' column ' + this.column + ' id ' + this.id);\n\t\t});\n\t\t\n\t\tgoogle.maps.event.addListener(grid, 'mouseout', function(event) {\n\t\t\tmessage('');\n\t\t});\n\t\t\n\t\treturn grid;\n\t};\n\t\n\tthis.plotAllGrids= function() {\n\t\tfor (var row = 0; row < this.heightN; row ++)\n\t\t{\n\t\t\tfor (var column = 0; column < this.widthN; column ++)\n\t\t\t{\n\t\t\t\tbbox = [ this.lowerLeft[0] + this.latStep * (this.heightN - row -1), \n\t\t\t\t\t\tthis.lowerLeft[1] + this.lngStep * column,\n\t\t\t\t\t\tthis.upperRight[0] - this.latStep * row, \n\t\t\t\t\t\tthis.upperRight[1] - this.lngStep * (this.widthN - 1 - column)];\n\t\t\t\t\n\t\t\t\tthis.plotGrid( bbox, row, column );\n\t\t\t}\n\t\t}\n\t};\n\t\n\t\n\tthis.plotByID = function( id ) {\n\t\tvar row = Math.floor(id / this.widthN);\n\t\tvar column = id % this.widthN;\n\t\tvar bbox = [ this.lowerLeft[0] + this.latStep * (this.heightN - row -1), \n\t\t\t\t\t\tthis.lowerLeft[1] + this.lngStep * column,\n\t\t\t\t\t\tthis.upperRight[0] - this.latStep * row, \n\t\t\t\t\t\tthis.upperRight[1] - this.lngStep * (this.widthN - 1 - column)];\n\t\treturn this.plotGrid( bbox, row, column );\n\t};\n}", "display(){\n noStroke();\n fill(245,172,114);\n ellipse(this.location.x, this.location.y, this.mass * 5, this.mass * 5)\n }", "function showCars(){\n for(let i = 0; i < carImage.length; i++){\n image(carImage[i],xCars[i], yCars[i],carWidth,carHeigth); \n print(yCars[i], xCars[i]);\n }\n}", "function drawGridCentre(x,y,s,rot){\r\n ctx.save();\r\n ctx.translate(x,y);\r\n ctx.rotate(rot*Math.PI/180);\r\n drawCircle(0,0,20, colArray[0], colArray[0], 2, false, true);\r\n for(j = 0; j<7 ; j++){\r\n for(var i = 0 ; i<7 ; i++){\r\n drawRectangle(0-s/2+i*s/7,0-s/2+j*s/7, s/7,s/7,colArray[3], colArray[4],0.5, false, true);\r\n }\r\n }\r\n ctx.restore();\r\n}", "function PolarCoordinates() {\r\n}", "function calc_graph(args) {\n\n //calculate the distances between each screen pixel\n var x_step = (args.xmax - args.xmin) / args.width;\n var y_step = (args.ymax - args.ymin) / args.height;\n\n //current complex number\n var x = args.xmin;\n var y = args.ymin;\n\n\n for (var scaleX = 0; scaleX < args.width; scaleX++) {\n y = args.ymin;\n for (var scaleY = 0; scaleY < args.height; scaleY++) {\n var c = new Complex(x,y);\n if(is_mandelbrot_member(c)) {\n postMessage({ x: scaleX, y: scaleY });\n }\n y += y_step;\n }\n x += x_step;\n }\n}", "function drawPol(xCor, yCor, N, side) {\n paper.circle(xCor, yCor, 3).attr(\"fill\", \"black\");\n\n var path = \"\", n, temp_x, temp_y, angle;\n\n for (n = 0; n <= N; n += 1) {\n // angulo en radianes parte del circulo a dibujar\n angle = n / N * 2 * Math.PI;\n\n // ajustar valor de x de acuerdo al angulo\n temp_x = xCor + Math.cos(angle) * side;\n // ajustar valor de y de acuerdo al angulo\n temp_y = yCor + Math.sin(angle) * side;\n\n //Empezar a escribir el path\n // Si es el primer punto, se usa M (starting point) si no utilizar L en el formato del path\n //Dato especificado por raphael\n path += (n === 0 ? \"M\" : \"L\") + temp_x + \",\" + temp_y;\n }\n return path;\n}", "display() {\n push();\n fill(255, 255, 0);\n let angle = TWO_PI / this.points;\n let halfAngle = angle / 2.0;\n beginShape();\n for (let a = 0; a < TWO_PI; a += angle) {\n let sx = this.x + cos(a) * this.outerRadius;\n let sy = this.y + sin(a) * this.outerRadius;\n vertex(sx, sy);\n sx = this.x + cos(a + halfAngle) * this.innerRadius;\n sy = this.y + sin(a + halfAngle) * this.innerRadius;\n vertex(sx, sy);\n }\n endShape(CLOSE);\n pop();\n }", "function genIterDiagram(f, xstar, axis) {\n\n var w = 900\n var h = 300\n var totalIters = 150\n var state_beta = 0.0\n var state_alpha = 0.001\n var num_contours = 15\n var onDrag = function() {}\n var w0 =[-1.21, 0.853]\n //var w0 = [0,0]\n\n function renderIterates(div) {\n\n // Render the other stuff\n var intDiv = div.style(\"width\", w + \"px\")\n .style(\"height\", h + \"px\")\n .style(\"box-shadow\",\"0px 3px 10px rgba(0, 0, 0, 0.4)\")\n .style(\"border\", \"solid black 1px\")\n\n // Render Contours \n var plotCon = contour_plot.ContourPlot(w,h)\n .f(function(x,y) { return f([x,y])[0] })\n .drawAxis(false)\n .xDomain(axis[0])\n .yDomain(axis[1])\n .contourCount(num_contours)\n .minima([{x:xstar[0], y:xstar[1]}]);\n\n var elements = plotCon(intDiv);\n\n var svg = intDiv.append(\"div\")\n .append(\"svg\")\n .style(\"position\", 'absolute')\n .style(\"left\", 0)\n .style(\"top\", 0)\n .style(\"width\", w)\n .style(\"height\", h)\n .style(\"z-index\", 2) \n\n\n // var X = d3.scaleLinear().domain([0,1]).range(axis[0])\n // var Y = d3.scaleLinear().domain([0,1]).range(axis[1])\n\n var X = d3.scaleLinear().domain(axis[0]).range([0, w])\n var Y = d3.scaleLinear().domain(axis[1]).range([0, h])\n \n // Rendeer Draggable dot\n var circ = svg.append(\"circle\")\n .attr(\"cx\", X(w0[0])) \n .attr(\"cy\", Y(w0[1]) )\n .attr(\"r\", 4)\n .style(\"cursor\", \"pointer\")\n .attr(\"fill\", colorbrewer.OrRd[3][1])\n .attr(\"opacity\", 0.8)\n .attr(\"stroke-width\", 1)\n .attr(\"stroke\", colorbrewer.OrRd[3][2])\n .call(d3.drag().on(\"drag\", function() {\n var pt = d3.mouse(this)\n var x = X.invert(pt[0])\n var y = Y.invert(pt[1])\n this.setAttribute(\"cx\", pt[0])\n this.setAttribute(\"cy\", pt[1])\n w0 = [x,y]\n onDrag(w0)\n iter(state_alpha, state_beta, w0);\n }))\n\n var iterColor = d3.scaleLinear().domain([0, totalIters]).range([\"black\", \"black\"])\n\n var update2D = plot2dGen(X, Y, iterColor)(svg)\n\n // Append x^star\n svg.append(\"path\")\n .attr(\"transform\", \"translate(\" + X(xstar[0]) + \",\" + Y(xstar[1]) + \")\")\n .attr(\"d\", \"M 0.000 2.000 L 2.939 4.045 L 1.902 0.618 L 4.755 -1.545 L 1.176 -1.618 L 0.000 -5.000 L -1.176 -1.618 L -4.755 -1.545 L -1.902 0.618 L -2.939 4.045 L 0.000 2.000\")\n .style(\"fill\", \"white\")\n .style(\"stroke-width\",1)\n\n \n function iter(alpha, beta, w0) {\n\n // Update Internal state of alpha and beta\n state_alpha = alpha\n state_beta = beta\n\n // Generate iterates \n var OW = runMomentum(f, w0, alpha, beta, totalIters)\n var W = OW[1]\n\n update2D(W)\n\n circ.attr(\"cx\", X(w0[0]) ).attr(\"cy\", Y(w0[1]) )\n circ.moveToFront()\n\n }\n\n iter(state_alpha, state_beta, w0);\n \n return { control:iter, \n w0:function() { return w0 }, \n alpha:function() { return state_alpha }, \n beta:function() {return state_beta} }\n\n }\n\n renderIterates.width = function (_) {\n w = _; return renderIterates;\n }\n\n renderIterates.height = function (_) {\n h = _; return renderIterates;\n }\n\n renderIterates.iters = function (_) {\n totalIters = _; return renderIterates;\n }\n\n renderIterates.drag = function (_) {\n onDrag = _; return renderIterates;\n }\n\n renderIterates.init = function (_) {\n w0 = _; return renderIterates;\n }\n\n renderIterates.alpha = function (_) {\n state_alpha = _; return renderIterates;\n }\n\n renderIterates.beta = function (_) {\n state_beta = _; return renderIterates;\n }\n\n return renderIterates\n\n}", "function plot_function(npoints) {\n data = [...Array(npoints).keys()].map(Math.random);\n\n //yScale for position\n yScale = d3.scaleLinear()\n .domain([d3.min(data), d3.max(data)])\n .range([d3.select(\"#chart\").style(\"height\").replace(\"px\",\"\")-20, 10]);\n\n //This range of continous scales can be colours!\n color = d3.scaleLog()\n .domain([d3.min(data), d3.mean(data), d3.max(data)])\n .range([1,0]);\n\n //Quantized colors can be used to.\n color = d3.scaleQuantize()\n .domain([d3.min(data), d3.max(data)])\n .range(d3.schemeCategory10);\n\n xScale = d3.scaleLinear()\n .domain([0,npoints])\n .range([0,700]);\n\n markers = d3.select(\"#axisbox\")\n .attr(\"transform\", \"translate(80,-20)\")\n .selectAll(\"circle\")\n .data(data)\n .enter()\n .append(\"circle\")\n .attr(\"r\", 2)\n .attr(\"cx\", function(d,i) {return xScale(i);})\n .attr(\"cy\", function(d,i) {return yScale(d);})\n .attr(\"fill\", function(d,i) {return color(d);});\n\n laxis = d3.axisLeft(yScale)\n .ticks(10, 'f');\n\n baxis = d3.axisBottom(xScale)\n .ticks(10);\n\n d3.select(\"#axisbox\")\n .append(\"g\")\n .call(laxis);\n\n d3.select(\"#axisbox\")\n .append(\"g\")\n .attr(\"transform\", \"translate(0,620)\")\n .call(baxis)\n .select(\".domain\")\n}", "function plot(x,y,color){\n ctx.fillStyle = color;\n ctx.fillRect(x,y,1,1);\n }", "function setGraphCoordinates(canvasSize) {\n let xCoordinate = 0;\n let yCoordinate = 1000;\n const decimalIncrement = 0.1;\n let coordinatesArray = []\n while(yCoordinate > 0) {\n\n let orderedPair = generateOrderedPair(xCoordinate);\n yCoordinate =orderedPair[1] \n coordinatesArray.push(orderedPair);\n xCoordinate +=decimalIncrement;\n }\n return coordinatesArray\n}", "function drawChords (matrix, mmap) {\n var w = 980, h = 750, r1 = h / 2, r0 = r1 - 110, duration=5000;\n\n var fill = d3.scale.ordinal()\n // .range(['#c7b570','#c6cdc7','#335c64','#768935','#507282','#5c4a56','#aa7455','#574109','#837722','#73342d','#0a5564','#9c8f57','#7895a4','#4a5456','#b0a690','#0a3542',]);\n //.range(['#E54E45', \"#DBC390\", \"#13A3A5\", \"#403833\", \"#334D5C\", \"#C0748D\", \"#EFC94C\", \"#E27A3F\", \"#DF4949\", \"#7B3722\", \"#8F831F\", \"#F0900D\", \"#10325C\"]);\n .range(['#A9A18C', '#855723', '#4E6172', '#DBCA69', '#A3ADB8', '#668D3C', '#493829']);\n\n var chord = d3.layout.chord()\n .padding(.02)\n .sortSubgroups(d3.descending)\n .sortChords(d3.descending);\n\n var arc = d3.svg.arc()\n .innerRadius(r0)\n .outerRadius(r0 + 20);\n\n var svg = d3.select(\"#ext-chart\").append(\"svg:svg\")\n .attr(\"width\", w)\n .attr(\"height\", h)\n .append(\"svg:g\")\n .attr(\"id\", \"circle\")\n .attr(\"transform\", \"translate(\" + w / 2 + \",\" + h / 2 + \")\");\n\n svg.append(\"circle\")\n .attr(\"r\", r0 + 20);\n\n var rdr = chordRdr(matrix, mmap);\n chord.matrix(matrix);\n\n var g = svg.selectAll(\"g.group\")\n .data(chord.groups())\n .enter().append(\"svg:g\")\n .attr(\"class\", \"group\")\n .on(\"mouseover\", mouseover)\n .on(\"mouseout\", function (d) { d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") });\n\n g.append(\"svg:path\")\n .style(\"stroke\", \"black\")\n .style(\"fill\", function(d) { return fill(rdr(d).gname); })\n .attr(\"d\", arc);\n\n g.append(\"svg:text\")\n .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })\n .attr(\"dy\", \".35em\")\n .style(\"font-family\", \"helvetica, arial, sans-serif\")\n .style(\"font-size\", \"12px\")\n .attr(\"text-anchor\", function(d) { return d.angle > Math.PI ? \"end\" : null; })\n .attr(\"transform\", function(d) {\n return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n + \"translate(\" + (r0 + 26) + \")\"\n + (d.angle > Math.PI ? \"rotate(180)\" : \"\");\n })\n .text(function(d) { return rdr(d).gname; });\n\n var chordPaths = svg.selectAll(\"path.chord\")\n .data(chord.chords())\n .enter().append(\"svg:path\")\n .attr(\"class\", \"chord\")\n .style(\"stroke\", function(d) { return d3.rgb(fill(rdr(d).sname)).darker(); })\n .style(\"fill\", function(d) { return fill(rdr(d).sname); })\n .attr(\"d\", d3.svg.chord().radius(r0))\n .on(\"mouseover\", function (d) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .html(chordTip(rdr(d)))\n .style(\"font\", \"12px sans-serif\")\n .style(\"top\", function () { return (d3.event.pageY - 170)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 100)+\"px\";})\n })\n .on(\"mouseout\", function (d) { d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") });\n\n function chordTip (d) {\n var q = d3.format(\",.1f\")\n return \"Flow Info:<br/><br>\"\n + d.sname + \" flow from \" + d.tname\n + \": \" + q(d.svalue) + \"T<br/>\"\n + \"<br/>\"\n + d.tname + \" flow from \" + d.sname\n + \": \" + q(d.tvalue) + \"T<br/>\";\n }\n\n function groupTip (d) {\n var p = d3.format(\".1%\"), q = d3.format(\",.2f\")\n return \"Influx Info:<br/><br/>\"\n + d.gname + \" : \" + q(d.gvalue) + \"T\"\n }\n\n function mouseover(d, i) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .html(groupTip(rdr(d)))\n .style(\"top\", function () { return (d3.event.pageY - 80)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 130)+\"px\";})\n\n chordPaths.classed(\"fade\", function(p) {\n return p.source.index != i\n && p.target.index != i;\n });\n }\n\n /* for brush slider */\n var margin = {top: 0, right: 50, bottom: 10, left: 50},\n width = w - margin.left - margin.right,\n height = 50 - margin.bottom - margin.top;\n\n var x = d3.scale.linear()\n .domain([10, 22])\n .range([0, width])\n .clamp(true);\n\n var brush = d3.svg.brush()\n .x(x)\n .extent([0, 0])\n .on(\"brush\", brushed);\n\n var svg = d3.select(\"#brush-slider\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height / 2 + \")\")\n .call(d3.svg.axis()\n .scale(x)\n .orient(\"bottom\")\n .tickFormat(function(d) { return d + \":00\"; })\n .tickSize(0)\n .tickPadding(12))\n .select(\".domain\")\n .select(function() { return this.parentNode.appendChild(this.cloneNode(true)); })\n .attr(\"class\", \"halo\");\n\n var slider = svg.append(\"g\")\n .attr(\"class\", \"slider\")\n .call(brush);\n\n slider.selectAll(\".extent,.resize\")\n .remove();\n\n slider.select(\".background\")\n .attr(\"height\", height);\n\n var handle = slider.append(\"circle\")\n .attr(\"class\", \"handle\")\n .attr(\"transform\", \"translate(0,\" + height / 2 + \")\")\n .attr(\"r\", 9);\n\n slider\n .call(brush.event)\n .transition() // gratuitous intro!\n .duration(750)\n .call(brush.extent([16, 16]))\n .call(brush.event);\n\n function brushed() {\n var value = brush.extent()[0];\n\n if (d3.event.sourceEvent) { // not a programmatic event\n value = x.invert(d3.mouse(this)[0]);\n brush.extent([value, value]);\n }\n\n handle.attr(\"cx\", x(value));\n } \n }", "function position(dot) {\n dot .attr(\"cx\", function(d) { \n // console.log(\"cx is \" + xScale(x(d)) );\n // return xScale(x(d)); \n return xScale(d.engineers_num);\n } )\n .attr(\"cy\", function(d) { return yScale(d.employees_num) })\n .attr(\"r\", 10\n // function(d) {\n // console.log( radiusScale(radius(d)) );\n // return radiusScale(radius(d)); \n // }\n );\n }", "function axialCoords(q, r) {\r\n\tthis.q = q;\r\n\tthis.r = r;\r\n}", "function drawGrid(Tx){\n context.beginPath();\n var dim = 10;\n var length = 500;\n // Draw from the negative width to pos\n for(var i=-(dim/2); i<=(dim/2); i++){\n iScaled = i * 50;\n moveToTx(iScaled, 0, -length/2, Tx); lineToTx(iScaled, 0, length/2, Tx);\n moveToTx(-length/2, 0, iScaled, Tx); lineToTx(length/2, 0, iScaled, Tx);\n }\n context.stroke();\n }", "function render () {\n\n\t\tfunction pushMatrix (fn) {\n\t\t\tp.push();\n\t\t\tfn();\n\t\t\tp.pop();\n\t\t}\n\n\t\t// Draw Horizontal Lines\n\t\tpushMatrix(function () {\n\t\t\tp.strokeCap(p.ROUND);\n\t\t\tp.stroke(121, 192, 242);\t\t\t\t// Light Blue\n\t\t\tp.translate(p.width/2, p.height/2);\t\t// Translate to center\n\n\t\t\t// Set strokeweight to decrease proportionally to the stretch factor\n\t\t\tvar base_stroke_weight = 2;\n\t\t\tvar stroke_weight = base_stroke_weight - (a_l_de.value * base_stroke_weight);\n\t\t\tp.strokeWeight(stroke_weight);\n\n\t\t\tvar spacing = 60;\t\t\t\t\t\t// Set space around Es\n\t\t\t// Mult by -1 for left line\n\t\t\tvar displacement_start = a_l_ds.value * (p.width / 2) + spacing;\n\t\t\tvar displacement_end = a_l_de.value * (p.width / 2) + spacing;\n\n\t\t\tp.line(-displacement_end, 0, -displacement_start, 0);\t\t// Left Line\n\t\t\tp.line(displacement_end, 0, displacement_start, 0);\t\t// Right Line\n\t\t});\n\n\t\t// Assemble Logo!\n\n\t\t// Rotate E\n\t\tpushMatrix(function () {\n\n\t\t\tp.tint(255, 255); // Opacity (255)\n\t\t\t\n\t\t\tp.translate(p.width / 2, p.height / 2);\n\t\t\tp.rotate(p.radians(a_ed_r.value));\t\t// All rotations must occur here!!!\n\t\t\tp.scale(0.75, 0.75);\n\n\t\t\t// For Dots\n\t\t\tpushMatrix(function () {\n\n\t\t\t\tp.translate(-41.25,-42.65); \t\t// Center offset\n\t\t\t\tp.scale(0.15,0.15);\n\n\t\t\t\t// Polar Coordinates\n\t\t\t\tvar r = a_d_d.value;\t\t\t\t// Origin Offset \t{start: 300, end: 265}\n\t\t\t\tvar angle = p.radians(a_d_r.value);\t\t// Angle Offset\t\t{start: 0, end: 77}\n\t\t\t\tvar x = p.cos(angle) * r;\t\t\t\t// Multiply r * -1 for other Dot\n\t\t\t\tvar y = p.sin(angle) * r;\n\n\t\t\t\t// Top Dot\n\t\t\t\tpushMatrix(function () {\n\t\t\t\t\tp.scale(1, 1);\n\t\t\t\t\t\n\t\t\t\t\tp.translate(x,y);\n\t\t\t\t\tp.translate(276,283); \t\t// Center on Es\n\t\t\t\t\tp.scale(a_d_s.value, a_d_s.value); \t// Each scale <-- Parametric\n\t\t\t\t\tp.image(dot, -50, -50); \t// Center around origin\n\t\t\t\t});\n\n\t\t\t\t// Bottom Dot\n\t\t\t\tpushMatrix(function () {\n\t\t\t\t\tp.scale(1, 1);\n\t\t\t\t\t\n\t\t\t\t\tp.translate(-x,-y);\n\t\t\t\t\tp.translate(276, 283); \t\t// Center on Es, experimentally determined\n\t\t\t\t\tp.scale(a_d_s.value, a_d_s.value); \t// Each scale <-- Parametric\n\t\t\t\t\tp.image(dot2, -50, -50); \t// Center around origin\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t// For Es\n\t\t\tpushMatrix(function () {\n\t\t\t\tp.scale(a_e_s.value, a_e_s.value); \t// Global scale\n\t\t\t\tp.translate(-41.25,-42.65); \t\t// Center offset, experimentally determined\n\t\t\t\tp.scale(0.15,0.15);\n\t\t\t\t\n\t\t\t\t// Bottom E\n\t\t\t\tp.image(E, 100, 100);\n\n\t\t\t\t// Top E\n\t\t\t\tpushMatrix(function () {\n\t\t\t\t\tp.translate(200, 0);\n\t\t\t\t\tp.image(E2, 0, 0);\n\t\t\t\t});\n\t\t\t});\n\n\t\t});\n\n\t\tpushMatrix(function () {\n\t\t\tp.fill(255);\n\t\t\tp.noStroke();\n\t\t\tp.translate(p.width/2, p.height/2);\n\t\t});\n\n\t\tif (global_animator.value >= 1) {\n\t\t\tp.noLoop();\n\t\t}\n\t}", "show() {\n\t\tfill(255);\n ellipse(this.x, this.y, this.r*2)\n\t}", "function showCoords(c)\r\n {\r\n $('#x1').val(c.x);\r\n $('#y1').val(c.y);\r\n $('#x2').val(c.x2);\r\n $('#y2').val(c.y2);\r\n $('#w').val(c.w);\r\n $('#h').val(c.h);\r\n }", "function allDotsDraw(positions) {\n // Loop through each dot and draw\n for (i = 0; i < positions.length; i++){\n dotDrawer(positions[i])\n }\n}", "function drawPC() {\r\n\t\r\n//setting the x and y scale \r\n\tvar x = d3.scale.ordinal().rangePoints([0, 480], 1),\r\n y= {};\r\n \r\n// Extract the list of dimensions and create a scale for each.\r\n for (var dim in cars[0]) {\r\n\t if (dim != \"name\") {\r\n\t\t y[dim] = d3.scale.linear()\r\n\t\t\t .domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])\r\n\t\t .range([height,0]);\r\n\t }\r\n }\r\n \r\n//setting the x domain dimensions\r\n x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != \"name\";}));\r\n\r\n//draw polylines\r\n for (var i=1; i< cars.length; i++) { \r\n\r\n//prepare the coordinates for a polyline\r\n\t var lineData = []; //initialize an array for coordinates of a polyline\r\n\t for (var prop in cars[0]) { //get each dimension\r\n\t if (prop != \"name\" ) { //skip the name dimension\r\n\t var point = {}; //initialize a coordinate object\r\n\t var val = cars[i][prop]; //obtain the value of a car in a dimension\r\n\t\t point['x'] = x(prop); //x value: mapping the dimension \r\n\t point['y'] = y[prop](val);//y value: mapping the value in that dimension\r\n\t lineData.push(point); //add the object into the array \r\n\t }\r\n\t }\r\n\r\n//draw a polyline based on the coordindates \r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"polyline\")\r\n\t .append(\"path\") // a path shape\r\n\t\t .attr(\"d\", line(lineData)) //line() is a function to turn coordinates into SVG commands\r\n\t\r\n//the mouseover function that changes the strokes to red when the mouse is over them\r\n\t.on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t.style(\"stroke\",\"red\")\r\n\t })\r\n//the mouseout function that changes the strokes back to their original color\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.style(\"stroke\",null)\r\n\t\t\r\n})\r\n }\r\n\r\n//draw individual dimension lines\r\n//position dimension lines \r\n var g = chart.selectAll(\".dimension\")\r\n\t .data(dimensions)\r\n\t .enter().append(\"g\")\r\n\t .attr(\"class\", \"dimension\")\r\n\t .attr(\"transform\", function(d) { return \"translate(\" + x(d) + \")\"; }) //translate each axis\r\n\r\n\t\r\n// Add an axis and title.\r\n g.append(\"g\")\r\n\t .attr(\"class\", \"axis\")\r\n\t .each(function(d) { d3.select(this).call(axis.scale(y[d])); })\r\n\t .append(\"text\")\r\n\t .style(\"text-anchor\", \"middle\")\r\n\t .attr(\"y\", -4)\r\n\t .text(function(d) { return d; });\r\n\t \r\n \r\n}", "show() {\n fill(this.fill, this.alpha);\n strokeWeight(4);\n stroke(255);\n ellipse(this.x, this.y, (this.r * 2));\n }" ]
[ "0.606524", "0.58996356", "0.5816983", "0.5802485", "0.5684464", "0.56714755", "0.5637831", "0.5623183", "0.55911744", "0.55853385", "0.5572179", "0.55446523", "0.553017", "0.5528281", "0.5513845", "0.5494181", "0.54765886", "0.5468272", "0.5444749", "0.5409388", "0.54050297", "0.5395914", "0.53905684", "0.5358139", "0.53568447", "0.532887", "0.532887", "0.532887", "0.532887", "0.532887", "0.53257716", "0.5300905", "0.5295992", "0.5292185", "0.52795315", "0.5271068", "0.52670676", "0.5236764", "0.52175516", "0.5215454", "0.51955086", "0.51848817", "0.51627237", "0.51625776", "0.5161895", "0.5158863", "0.5158799", "0.51501846", "0.51463616", "0.514113", "0.5139577", "0.5137731", "0.5132567", "0.51304746", "0.5130238", "0.5114844", "0.5090193", "0.50843906", "0.5080542", "0.50802016", "0.50799865", "0.50774837", "0.50752324", "0.50729203", "0.50669867", "0.50567275", "0.50500333", "0.5047022", "0.503867", "0.5038485", "0.5036975", "0.5033208", "0.5028407", "0.5023549", "0.5022242", "0.5011926", "0.5006844", "0.5005144", "0.49989474", "0.49845433", "0.4974301", "0.49738157", "0.4968948", "0.49688894", "0.496795", "0.49653587", "0.49645236", "0.4957469", "0.49547073", "0.49536672", "0.49477163", "0.49464875", "0.4945217", "0.49392927", "0.49376544", "0.49371412", "0.49365854", "0.4932834", "0.4932218", "0.49270192" ]
0.5585903
9
Function plots Cylindrical coordiate system
function plotCylindrical(r,theta,z, target){ console.log(r,theta,z,target); let hoverlabel = ["R: "+r[0]+", Θ: "+theta[0]+", Z: "+z[0],"R: "+r[1]+", Θ: "+theta[1]+", Z: "+z[1]]; var data = [{ type: 'scatter3d', mode: 'lines', x: r, y: theta, z: z, hoverinfo: 'text', hovertext: hoverlabel, opacity: 1, line: { width: 6, color: "rgb(0,0,0)", reversescale: false } }] var layout = { scene: { xaxis:{title: 'R'}, yaxis:{title: 'THETA'}, zaxis:{title: 'Z'}, } } Plotly.plot(target, data, layout); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "plotCyclists() {\n for (let c of this.mapCyclists) {\n if (c.cyclist.id.id == \"0_ghost\" || c.cyclist.id.id == \"ghost\") {\n c.plotGhost(this.map);\n } else {\n c.plotMarker(this.map);\n }\n }\n }", "axisPlot() {\n this.ctx = this.canvas.getContext(\"2d\");\n\n /**\n * Grid grid\n */\n if (this.grid.grid) {\n this.ctx.beginPath();\n this.ctx.font = 'italic 18pt Calibri';\n this.ctx.strokeStyle = '#979797';\n this.ctx.lineWidth = 1;\n this.ctx.setLineDash([10, 15]);\n for (let i = 30; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldY(i)*1000)/1000, 0, i);\n this.ctx.moveTo(0, i);\n this.ctx.lineTo(this.field.width, i);\n }\n for (let i = 100; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldX(i)*1000)/1000, i, this.field.height);\n this.ctx.moveTo(i, 0);\n this.ctx.lineTo(i, this.field.height);\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n /**\n * Grid axiss\n */\n if (this.grid.axiss) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#b10009';\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n this.ctx.moveTo(this.center.x, 0);\n this.ctx.lineTo(this.center.x, this.field.height);\n\n this.ctx.moveTo(0, this.center.y);\n this.ctx.lineTo(this.field.width, this.center.y);\n\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n if (this.grid.serifs) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#058600';\n this.ctx.fillStyle = '#888888'\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n let start = 0;\n if (!this.grid.serifsStep){\n return;\n }\n\n let s = Math.abs(\n this.ScreenToWorldY(0) -\n this.ScreenToWorldY(this.grid.serifsSize)\n );\n\n /**\n * To right & to left\n */\n if ((this.center.y > 0) && (this.center.y < this.field.height)) {\n\n let finish = this.ScreenToWorldX(this.field.width);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo(i+this.grid.serifsStep/2,(s/2));\n this.lineTo(i+this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(i+this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i+this.grid.serifsStep,s);\n this.lineTo(i+this.grid.serifsStep,-s);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(i+this.grid.serifsStep), this.WorldToScreenY(s));\n }\n\n finish = this.ScreenToWorldX(0);\n\n for (let i = start; i > finish; i-=this.grid.serifsStep) {\n this.moveTo(i-this.grid.serifsStep/2,(s/2));\n this.lineTo(i-this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i-this.grid.serifsStep/2, this.WorldToScreenX(i-this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i-this.grid.serifsStep,s);\n this.lineTo(i-this.grid.serifsStep,-s);\n this.ctx.fillText(i-this.grid.serifsStep, this.WorldToScreenX(i-this.grid.serifsStep), this.WorldToScreenY(s));\n }\n }\n\n /**\n * To top & to bot\n */\n if ((this.center.x > 0) && (this.center.x < this.field.width)) {\n\n start = 0;\n let finish = this.ScreenToWorldY(0);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo(-s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n\n finish = this.ScreenToWorldY(this.field.width);\n\n for (let i = start; i > finish-this.grid.serifsStep; i-=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo( -s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n }", "function plot() {\n \n }", "plot() {\n return \"Cute alien takes over the earth\";\n }", "function plotGraph() {\n if (houses.data.length > 0) {\n for (let i = 0; i < houses.data.length; i++) {\n xs[i] = map(houses.data[i].inputs[0], 0, zoom, 0, wnx);\n ys[i] = map(houses.data[i].inputs[1], 0, zoom, wny, 200);\n cs[i] = houses.data[i].inputs[8];\n ps[i] = houses.data[i].target[0];\n }\n }\n}", "function tick(){\n\n d3.selectAll('.circ')\n .attr('cx', function(d){return d.x})\n .attr('cy', function(d){return d.y})\n\n }", "function concentric() {\n let n = 12\n let res = [WIDTH/2, WIDTH/2]\n for (let r = 100; r < 360; r+=60) {\n for (let i=0; i<n; i++) {\n let x = WIDTH/2 + r * Math.cos(360 * 0.0174533 * i/n)\n let y = WIDTH/2 + r * Math.sin(360 * 0.0174533 * i/n)\n res.push(x, y)\n }\n }\n return res\n}", "function Cylindrical( radius, theta, y ) {\n\n\tthis.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane\n\tthis.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis\n\tthis.y = ( y !== undefined ) ? y : 0; // height above the x-z plane\n\n\treturn this;\n\n}", "function Cylindrical( radius, theta, y ) {\n\n\tthis.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane\n\tthis.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis\n\tthis.y = ( y !== undefined ) ? y : 0; // height above the x-z plane\n\n\treturn this;\n\n}", "function plot() {\n\n}", "function draw_cos(){\n\tvar x_increments = parseFloat(document.getElementById('x_inc').value)\n\tvar y_increments = parseFloat(document.getElementById('y_inc').value)\n\n if (loopcounter !=0){\n\n\t\tif((x_increments != last_x_inc) || (y_increments != last_y_inc)){\n\t\t\tclear();\n\t\t\tdraw_axis();\n\t\t\tdraw_ticks();\n\t\t}\n\tdraw_adjusted_cos_fn()\n\tlast_x_inc = x_increments\n\tlast_y_inc = y_increments\n\t}\n\n\tif (loopcounter == 0){\n\n\t\tdraw_adjusted_cos_fn()\n\t\tlast_x_inc = x_increments\n\t\tlast_y_inc = y_increments\n\t\tloopcounter+=1\n\t}\n\n}", "function plotPoints(coords) {\n ctx.fillStyle = 'green';\n console.log(coords);\n ctx.fillRect(coords.y, coords.x, 5, 5);\n}", "function drawCartesianOverlay() {\n \"use strict\";\n //Draw heavier black lines for grid\n ctx.beginPath();\n ctx.moveTo(0.5, 300.5);\n ctx.lineTo(800.5, 300.5);\n ctx.moveTo(400.5, 0.5);\n ctx.lineTo(400.5, 600.5);\n ctx.strokeStyle = 'black';\n ctx.lineWidth = 1.0;\n ctx.stroke();\n //-x arrow for line\n ctx.beginPath();\n ctx.moveTo(5.5, 295.5);\n ctx.lineTo(0.5, 300.5);\n ctx.lineTo(5.5, 305.5);\n //+x arrow for line\n ctx.moveTo(795.5, 295.5);\n ctx.lineTo(800.5, 300.5);\n ctx.lineTo(795.5, 305.5);\n //+y arrow for line\n ctx.moveTo(395.5, 5.0);\n ctx.lineTo(400.5, 0.5);\n ctx.lineTo(405.5, 5.0);\n //-y arrow for line\n ctx.moveTo(395.5, 595.5);\n ctx.lineTo(400.5, 600.5);\n ctx.lineTo(405.5, 595.5);\n ctx.strokeStyle = 'black';\n ctx.lineWidth = 1.0;\n ctx.stroke();\n //Label Graphs\n ctx.font = \"9px Georgia\";\n ctx.fillText(\"-x\", 1, 288);\n ctx.fillText(\"+\", 790, 288);\n ctx.fillText(\"x\", 795, 288);\n ctx.fillText(\"-y\", 382, 597);\n ctx.fillText(\"+\", 381, 8);\n ctx.fillText(\"y\", 386, 8);\n}", "function trC(coord){\n\treturn -95 + coord*10;\n}", "function Courbe(Y){\t\n\t// Remise à zero de la courbe : \n\tvar svg = d3.select(\"#graph\");\n\n\t// scaleY\n\tvar scaleY = d3.scaleLinear();\n\t// J'inverse min et max car pour Y c'est inversé\n\tscaleY.domain([1,0]);\n\tscaleY.range([0,500]);\n\n\t// Axe Y\n\tvar yAxis = d3.axisLeft(scaleY);\n\tvar gyAxis = svg.select(\"#axisX\");\n\tgyAxis.call(yAxis);\n\tgyAxis.attr(\"font-size\",28);\n\tgyAxis.attr(\"transform\",\"translate(50,50)\");\n\t\n\t// scaleX\n\tvar scaleX = d3.scaleLinear();\n\tscaleX.domain([0,24]);\n\tscaleX.range([0,800]);\n\t\n\t// Axe X\n\tvar xAxis = d3.axisBottom(scaleX);\n\tvar gxAxis = svg.select(\"#axisY\");\n\tgxAxis.call(xAxis.ticks(24));\n\tgxAxis.attr(\"font-size\",28);\n\tgxAxis.attr(\"transform\",\"translate(50,550)\");\n\t\n\t// Ajout titres des axes\n\tvar tmp =\"\";\n\ttmp +='<text x=\"450\" y=\"620\" font-size=\"28\" fill=\"black\" style=\"text-anchor: middle\" >Heure</text>';\n\ttmp += ' <text x=\"100\" y=\"0\" font-size=\"28\" fill=\"black\" style=\"text-anchor: middle\" >Flux de sève (mm/h)</text>';\n\tvar titre_axes = document.getElementById(\"texte\");\n\ttitre_axes.innerHTML = tmp;\t\n\n\t// line\n\tvar lValues = d3.line();\n\tlValues.x(function(d,i) { return scaleX(i/2) });\n\tlValues.y(function(d) { return scaleY(d)});\n\tvar gLine = svg.select(\".courbe\")\n\t.attr(\"transform\", \"translate(50,50)\")\n\t.attr(\"stroke\", \"green\")\n\t.attr(\"stroke-width\",2 )\n\t.attr(\"fill\", \"none\")\n\t.transition()\n\t.duration(500)\n\t.on(\"start\", function(d){\n\t\tvar gPoints = document.getElementById(\"points\");\n\t\tgPoints.innerHTML = \"\" ;\t\n\t})\n\t.on(\"end\", function(d){\n\t\t// Ajout des points\n\t\tcir =\"\";\n\t\tfor (j=0;j<Y.length;j++) {\n\t\t\tcir +=' <circle transform = \"translate(50,50)\" onmouseover=\"drawInfoBox('+Y[j]+','+j+','+scaleX(j)+','+scaleY(Y[j])+')\" onmouseleave=\"removeInfoBox()\" \tcx=\"'+scaleX(j/2)+'\" cy=\"'+scaleY(Y[j])+'\" r=\"5\" fill=\"green\" />' ;\n\t\t}\n\t\tvar gPoints = document.getElementById(\"points\");\n\t\tgPoints.innerHTML = cir ;\t\t\n\t})\n\t.attr(\"d\", lValues(Y));\t\t\n}", "function drawcylinder(gl,canvas,a_Position,r,s,x1,y1,x2,y2,numpolyline){\r\n Acolor = 1 - (numpolyline/255) \r\n // ** DRAW CYLINDERS **\r\n //\r\n // multiply degrees by convert to get value in radians \r\n // a circle is 360 degrees, rotate by (360 / s) degrees for every side, where n is number of sides!\r\n let convert = Math.PI/180 \r\n let numsides = 360/s\r\n\r\n // get the angle that the line segment forms\r\n let deltaX = x2-x1\r\n let deltaY = y2-y1 \r\n let degreeToRotate = Math.atan2(deltaY,deltaX)\r\n degreeToRotate = ((2* Math.PI)-degreeToRotate)\r\n \r\n // first we'll draw a circle by rotating around the x axis, then use a transformation matrix to rotate it\r\n // by the angle we found previously so the circle fits around the axis formed by the line segment\r\n let unrotated = []\r\n\r\n for (var i=0 ; i <=360; i+=numsides){ \r\n unrotated.push(0)\r\n unrotated.push((Math.cos(convert*i))*r)\r\n unrotated.push(Math.sin(convert*i)*r)\r\n } \r\n let cylinder_points = [] \r\n let indices = []\r\n let colors = []\r\n let normie = []\r\n //first circle\r\n for (var i = 0 ; i < unrotated.length; i+=3){\r\n cylinder_points.push((unrotated[i] * Math.cos(degreeToRotate)) + (unrotated[i+1] * Math.sin(degreeToRotate)) + x1) \r\n cylinder_points.push((unrotated[i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[i+1] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[i+2])\r\n }\r\n\r\n // second circle\r\n for (var i = 0 ; i < unrotated.length; i+=3){\r\n cylinder_points.push((unrotated[i] * Math.cos(degreeToRotate)) + (unrotated[i+1] * Math.sin(degreeToRotate)) + x2) \r\n cylinder_points.push((unrotated[i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[i+1] * Math.cos(degreeToRotate)) + y2)\r\n cylinder_points.push(unrotated[i+2])\r\n }\r\n\r\n \r\n //calculate face normals from cylinder points \r\n let cylindernormals = calcnormals(gl,canvas,a_Position,r,s,x1,y1,x2,y2,cylinder_points) \r\n // n+1th normal (the point that comes after the last point is the same as the first point) \r\n cylindernormals.push(cylindernormals[0])\r\n cylindernormals.push(cylindernormals[1])\r\n cylindernormals.push(cylindernormals[2])\r\n cylinder_points = []\r\n colors = []\r\n \r\n cylinder_points.push((unrotated[0] * Math.cos(degreeToRotate)) + (unrotated[1] * Math.sin(degreeToRotate)) + x1) \r\n cylinder_points.push((unrotated[0] * (-1 * Math.sin(degreeToRotate))) + (unrotated[1] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[2])\r\n normie.push((cylindernormals[0]+cylindernormals[27]) / 2)\r\n normie.push((cylindernormals[1]+cylindernormals[28]) / 2)\r\n normie.push((cylindernormals[2]+cylindernormals[29]) / 2)\r\n colors.push(Rcolor)\r\n colors.push(Gcolor)\r\n colors.push(Bcolor)\r\n colors.push(Acolor)\r\n\r\n\r\n for (var i = 1 ; i < s+1; i++){\r\n cylinder_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x1) \r\n cylinder_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[3*i+2])\r\n normie.push((cylindernormals[3*i]+cylindernormals[3*(i-1)])/2) \r\n normie.push((cylindernormals[3*i+1]+cylindernormals[3*(i-1)+1])/2) \r\n normie.push((cylindernormals[3*i+2]+cylindernormals[3*(i-1)+2])/2) \r\n colors.push(Rcolor)\r\n colors.push(Gcolor)\r\n colors.push(Bcolor)\r\n colors.push(Acolor)\r\n }\r\n // second circle\r\n cylinder_points.push((unrotated[0] * Math.cos(degreeToRotate)) + (unrotated[1] * Math.sin(degreeToRotate)) + x2) \r\n cylinder_points.push((unrotated[0] * (-1 * Math.sin(degreeToRotate))) + (unrotated[1] * Math.cos(degreeToRotate)) + y2)\r\n cylinder_points.push(unrotated[2])\r\n normie.push((cylindernormals[0]+cylindernormals[27]) / 2)\r\n normie.push((cylindernormals[1]+cylindernormals[28]) / 2)\r\n normie.push((cylindernormals[2]+cylindernormals[29]) / 2)\r\n colors.push(Rcolor)\r\n colors.push(Gcolor)\r\n colors.push(Bcolor)\r\n colors.push(Acolor)\r\n for (var i = 1 ; i < s+1; i++){\r\n cylinder_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n cylinder_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n cylinder_points.push(unrotated[3*i+2])\r\n normie.push((cylindernormals[3*i]+cylindernormals[3*(i-1)])/2) \r\n normie.push((cylindernormals[3*i+1]+cylindernormals[3*(i-1)+1])/2) \r\n normie.push((cylindernormals[3*i+2]+cylindernormals[3*(i-1)+2])/2) \r\n colors.push(Rcolor)\r\n colors.push(Gcolor)\r\n colors.push(Bcolor)\r\n colors.push(Acolor)\r\n }\r\n\r\n // 2 points to represent the center\r\n cylinder_points.push(x2) \r\n cylinder_points.push(y2)\r\n cylinder_points.push(0)\r\n colors.push(Rcolor)\r\n colors.push(Gcolor)\r\n colors.push(Bcolor)\r\n colors.push(Acolor)\r\n\r\n let len = cylinder_points.length/6\r\n // cool traiangles\r\n for (var i=0 ; i < s; i++){\r\n indices.push(i)\r\n indices.push(i+1) \r\n indices.push(len+i)\r\n indices.push(i)\r\n \r\n indices.push(i+1)\r\n indices.push(i)\r\n indices.push(len+i+1)\r\n indices.push(i+1)\r\n\r\n indices.push(len+i+1)\r\n indices.push(len+i) \r\n indices.push(i+1)\r\n indices.push(len+i+1)\r\n }\r\n\r\n var n = initVertexBuffers(gl,cylinder_points,colors,normie,indices)\r\n if (n<0){\r\n console.log('failed to set vert info')\r\n return\r\n }\r\n // Set the clear color and enable the depth test\r\n gl.enable(gl.DEPTH_TEST);\r\n initAttrib(gl,canvas,numpolyline)\r\n\r\n //draw the cylinder!\r\n gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);\r\n \r\n\r\n // ** DRAW CAP **\r\n // (FOR SMOOTH EDGES) \r\n let cap_points = []\r\n if (previousFace.length < 1){\r\n // second circle\r\n for (var i = 0 ; i < s+1 ; i++){\r\n previousFace.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n previousFace.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+2])\r\n }\r\n return\r\n } \r\n for (var j=0 ; j < previousFace.length ;j++){\r\n cap_points.push(previousFace[j]) \r\n }\r\n previousFace = []\r\n for (var i = 0 ; i < s+1 ; i++){\r\n cap_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x1) \r\n cap_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y1)\r\n cap_points.push(unrotated[3*i+2])\r\n }\r\n for (var i = 0 ; i < s+1 ; i++){\r\n previousFace.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n previousFace.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+2])\r\n }\r\n var capvertices = new Float32Array(cap_points)\r\n let caplen = capvertices.length/14;\r\n if (caplen === 0)\r\n return\r\n var n = initVertexBuffers(gl,capvertices,colors,normie,indices)\r\n if (n<0){\r\n console.log('failed to set vert info')\r\n return\r\n }\r\n // Set the clear color and enable the depth test\r\n gl.enable(gl.DEPTH_TEST);\r\n initAttrib(gl,canvas,numpolyline)\r\n //draw the cylinder!\r\n gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);\r\n}", "function plotGrid() {\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[i].length; j++) {\n plotRectangle(i, j);\n }\n }\n }", "function draw_axis(c){\n\n let yplot = 40;\n let d =0;\n\n c.beginPath();\n c.strokeStyle = \"blue\";\n \n c.moveTo(count_block(5),count_block(5));\n c.lineTo(count_block(5), count_block(40));\n c.lineTo(count_block(80), count_block(40));\n\n c.moveTo(count_block(5), count_block(40));\n \n \n\n //loop for the y-axix labels\n for(let i = 1 ;i<=10;i++ ){\n c.strokeText(d, count_block(2), count_block(yplot));\n yplot-=5;\n d+=500;\n }\n c.stroke();\n\n}", "function draw_axis(c){\n\n let yplot = 40;\n let d =0;\n\n c.beginPath();\n c.strokeStyle = \"black\";\n \n c.moveTo(count_block(5),count_block(5));\n c.lineTo(count_block(5), count_block(40));\n c.lineTo(count_block(80), count_block(40));\n\n c.moveTo(count_block(5), count_block(40));\n \n \n\n //loop for the y-axix labels\n for(let i = 1 ;i<=10;i++ ){\n c.strokeText(d, count_block(2), count_block(yplot));\n yplot-=5;\n d+=500;\n }\n c.stroke();\n\n}", "circumcenter(ax, ay, bx, by, cx, cy) \n {\n bx -= ax;\n by -= ay;\n cx -= ax;\n cy -= ay;\n\n var bl = bx * bx + by * by;\n var cl = cx * cx + cy * cy;\n\n var d = bx * cy - by * cx;\n\n var x = (cy * bl - by * cl) * 0.5 / d;\n var y = (bx * cl - cx * bl) * 0.5 / d;\n\n return {\n x: ax + x,\n y: ay + y\n };\n }", "function draw() {\n \n // background(237, 34, 93);\n for(let i = 0; i < h; i += 10) {\n for(let j = 0; j < w; j+= 10) {\n // if(i == cx[counting] && j == cy[counting]) {\n point_color = 222;\n strokeWeight(1);\n stroke(point_color);\n point(cx[counting],cy[counting])\n counting++;\n // } \n } \n // line(i, 0, i, h)\n counting = 0;\n }\n\n \n}", "function drawcylinder(gl,canvas,a_Position,r,s,x1,y1,x2,y2){\r\n\r\n // ** DRAW CYLINDERS **\r\n //\r\n\r\n // multiply degrees by convert to get value in radians \r\n // a circle is 360 degrees, rotate by (360 / s) degrees for every side, where n is number of sides!\r\n const convert = Math.PI/180 \r\n const numsides = 360/s\r\n\r\n // get the angle that the line segment forms\r\n const deltaX = x2-x1\r\n const deltaY = y2-y1 \r\n let degreeToRotate = Math.atan2(deltaY,deltaX)\r\n degreeToRotate = ((2*Math.PI)-degreeToRotate)\r\n \r\n // first we'll draw a circle by rotating around the x axis, then use a transformation matrix to rotate it\r\n // by the angle we found previously so the circle fits around the axis formed by the line segment\r\n let unrotated = []\r\n\r\n for (var i=0 ; i <=360; i+=numsides){ \r\n unrotated.push(0)\r\n unrotated.push((Math.cos(convert*i))*r)\r\n unrotated.push(Math.sin(convert*i)*r)\r\n } \r\n for (var i=0 ; i <=360; i+=numsides){ \r\n unrotated.push(0)\r\n unrotated.push((Math.cos(convert*i))*r)\r\n unrotated.push(Math.sin(convert*i)*r)\r\n } \r\n\r\n // OUR ROTATIONAL MATRIX (Rotating around the Z axis):\r\n // cos sin (0)\r\n // -sin cos (0)\r\n // 0 0 1 \r\n \r\n // first circle\r\n for (var i = 0 ; i < unrotated.length/2 ; i+=3){\r\n cylinder_points.push((unrotated[i] * Math.cos(degreeToRotate)) + (unrotated[i+1] * Math.sin(degreeToRotate)) + x1) \r\n cylinder_points.push((unrotated[i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[i+1] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[i+2])\r\n cylinder_points.push(Rcolor)\r\n cylinder_points.push(Gcolor)\r\n cylinder_points.push(Bcolor)\r\n cylinder_points.push(Acolor)\r\n }\r\n // second circle\r\n for (var i = unrotated.length/2; i < unrotated.length; i+=3){\r\n cylinder_points.push((unrotated[i] * Math.cos(degreeToRotate)) + (unrotated[i+1] * Math.sin(degreeToRotate)) +x2) \r\n cylinder_points.push((unrotated[i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[i+1] * Math.cos(degreeToRotate)) +y2)\r\n cylinder_points.push(unrotated[i+2])\r\n cylinder_points.push(Rcolor)\r\n cylinder_points.push(Gcolor)\r\n cylinder_points.push(Bcolor)\r\n cylinder_points.push(Acolor)\r\n }\r\n let cylindernormals = calcnormals(gl,canvas,a_Position,r,s,x1,y1,x2,y2,cylinder_points) \r\n console.log(cylindernormals)\r\n // actually apply shading after calculating surface normals\r\n let colors = []\r\n // Lambertan Shading Ld = kD * I * Max(0,n dot vl)\r\n light1V = normalize(light1V)\r\n light2V = normalize(light2V)\r\n // now both the light and surface normal are length 1 \r\n \r\n let currentsurfacecolor = findsurfacecolor(light1C,defaultcolor)\r\n if (whiteLightBox.checked){\r\n colors = calculateColors(cylindernormals,light1V,currentsurfacecolor) \r\n }\r\n\r\n if (redLightBox.checked){ \r\n if (whiteLightBox.checked){\r\n currentsurfacecolor = findsurfacecolor (light2C,currentsurfacecolor)\r\n colors = calculateColors(cylindernormals,light2V,currentsurfacecolor) \r\n }\r\n else{\r\n currentsurfacecolor = findsurfacecolor (light2C,defaultcolor)\r\n colors = calculateColors(cylindernormals,light2V,currentsurfacecolor) \r\n }\r\n }\r\n cylinder_points = []\r\n if (colors.length == 0){\r\n console.log (\"Try Turning on a light!\")\r\n return\r\n }\r\n colors.push(colors[0]) \r\n\r\n for (var i = 0 ; i < s ; i++){\r\n cylinder_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x1) \r\n cylinder_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[3*i+2])\r\n cylinder_points.push(colors[i][0])\r\n cylinder_points.push(colors[i][1])\r\n cylinder_points.push(colors[i][2])\r\n cylinder_points.push(colors[i][3])\r\n cylinder_points.push((unrotated[3*i+3] * Math.cos(degreeToRotate)) + (unrotated[3*i+4] * Math.sin(degreeToRotate)) + x1)\r\n cylinder_points.push((unrotated[3*i+3] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+4] * Math.cos(degreeToRotate)) + y1)\r\n cylinder_points.push(unrotated[3*i+5])\r\n cylinder_points.push(colors[i][0])\r\n cylinder_points.push(colors[i][1])\r\n cylinder_points.push(colors[i][2])\r\n cylinder_points.push(colors[i][3])\r\n }\r\n // second circle\r\n for (var i = 0 ; i < s ; i++){\r\n cylinder_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n cylinder_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n cylinder_points.push(unrotated[3*i+2])\r\n cylinder_points.push(colors[i][0])\r\n cylinder_points.push(colors[i][1])\r\n cylinder_points.push(colors[i][2])\r\n cylinder_points.push(colors[i][3])\r\n cylinder_points.push((unrotated[3*i+3] * Math.cos(degreeToRotate)) + (unrotated[3*i+4] * Math.sin(degreeToRotate)) + x2)\r\n cylinder_points.push((unrotated[3*i+3] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+4] * Math.cos(degreeToRotate)) + y2)\r\n cylinder_points.push(unrotated[3*i+5])\r\n cylinder_points.push(colors[i][0])\r\n cylinder_points.push(colors[i][1])\r\n cylinder_points.push(colors[i][2])\r\n cylinder_points.push(colors[i][3])\r\n }\r\n\r\n let len = cylinder_points.length/14;\r\n let indices = []\r\n // cool traiangles\r\n for (var i=0 ; i < s; i++){\r\n\r\n indices.push(i)\r\n indices.push(i+1) \r\n indices.push(len+i)\r\n indices.push(i)\r\n \r\n indices.push(i+1)\r\n indices.push(i)\r\n indices.push(len+i+1)\r\n indices.push(i+1)\r\n\r\n indices.push(len+i+1)\r\n indices.push(len+i) \r\n indices.push(i+1)\r\n indices.push(len+i+1)\r\n\r\n\r\n }\r\n\r\n var vertices = new Float32Array(cylinder_points)\r\n setVertexBuffer(gl, new Float32Array(vertices))\r\n setIndexBuffer(gl, new Uint16Array(indices))\r\n // draw cylinder\r\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0) \r\n //draw normal vectors ! (if applicable)\r\n calcnormals(gl,canvas,a_Position,r,s,x1,y1,x2,y2,cylinder_points) \r\n cylinder_points = []\r\n\r\n\r\n\r\n // ** DRAW CAP **\r\n // (FOR SMOOTH EDGES) \r\n\r\n let cap_points = []\r\n if (previousFace.length < 1){\r\n // second circle\r\n for (var i = 0 ; i < s ; i++){\r\n previousFace.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n previousFace.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+2])\r\n previousFace.push(colors[i][0])\r\n previousFace.push(colors[i][1])\r\n previousFace.push(colors[i][2])\r\n previousFace.push(colors[i][3])\r\n previousFace.push((unrotated[3*i+3] * Math.cos(degreeToRotate)) + (unrotated[3*i+4] * Math.sin(degreeToRotate)) + x2)\r\n previousFace.push((unrotated[3*i+3] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+4] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+5])\r\n previousFace.push(colors[i][0])\r\n previousFace.push(colors[i][1])\r\n previousFace.push(colors[i][2])\r\n previousFace.push(colors[i][3])\r\n }\r\n return\r\n } \r\n for (var j=0 ; j < previousFace.length ;j++){\r\n cap_points.push(previousFace[j]) \r\n }\r\n\r\n previousFace = []\r\n for (var i = 0 ; i < s ; i++){\r\n cap_points.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x1) \r\n cap_points.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y1)\r\n cap_points.push(unrotated[3*i+2])\r\n cap_points.push(colors[i][0])\r\n cap_points.push(colors[i][1])\r\n cap_points.push(colors[i][2])\r\n cap_points.push(colors[i][3])\r\n cap_points.push((unrotated[3*i+3] * Math.cos(degreeToRotate)) + (unrotated[3*i+4] * Math.sin(degreeToRotate)) + x1)\r\n cap_points.push((unrotated[3*i+3] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+4] * Math.cos(degreeToRotate)) + y1)\r\n cap_points.push(unrotated[3*i+5])\r\n cap_points.push(colors[i][0])\r\n cap_points.push(colors[i][1])\r\n cap_points.push(colors[i][2])\r\n cap_points.push(colors[i][3])\r\n }\r\n for (var i = 0 ; i < s ; i++){\r\n previousFace.push((unrotated[3*i] * Math.cos(degreeToRotate)) + (unrotated[3*i+1] * Math.sin(degreeToRotate)) + x2) \r\n previousFace.push((unrotated[3*i] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+1] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+2])\r\n previousFace.push(colors[i][0])\r\n previousFace.push(colors[i][1])\r\n previousFace.push(colors[i][2])\r\n previousFace.push(colors[i][3])\r\n previousFace.push((unrotated[3*i+3] * Math.cos(degreeToRotate)) + (unrotated[3*i+4] * Math.sin(degreeToRotate)) + x2)\r\n previousFace.push((unrotated[3*i+3] * (-1 * Math.sin(degreeToRotate))) + (unrotated[3*i+4] * Math.cos(degreeToRotate)) + y2)\r\n previousFace.push(unrotated[3*i+5])\r\n previousFace.push(colors[i][0])\r\n previousFace.push(colors[i][1])\r\n previousFace.push(colors[i][2])\r\n previousFace.push(colors[i][3])\r\n }\r\n var capvertices = new Float32Array(cap_points)\r\n let caplen = capvertices.length/14;\r\n if (caplen === 0)\r\n return\r\n setVertexBuffer(gl, new Float32Array(cap_points))\r\n setIndexBuffer(gl, new Uint16Array(indices))\r\n // draw caps \r\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0)\r\n}", "function displayCoord(a) {\r\n\t\tc.beginPath();\r\n\t\tc.moveTo(parseInt(a[0],10)-3,output(parseInt(a[1],10)-3));\r\n\t\tc.lineTo(parseInt(a[0],10)+3,output(parseInt(a[1],10)+3));\r\n\t\tc.stroke();\r\n\t\tc.beginPath();\r\n\t\tc.moveTo(parseInt(a[0],10)-3,output(parseInt(a[1],10)+3));\r\n\t\tc.lineTo(parseInt(a[0],10)+3,output(parseInt(a[1],10)-3));\r\n\t\tc.stroke();\r\n\t\tif (showCoordsCheck) c.fillText(\"(\"+a[0]+\",\"+a[1]+\")\",parseInt(a[0],10)+10,output(parseInt(a[1],10)+10));\r\n\t}", "function equilatGrid(L,R,dx,dy){\n let yVals = [];\n let ytip = 70;\n let xtip = 300;\n let yChange = dy/10;\n let xChange = 2*dx/10\n for(let i = 0; i < 9; i++){\n yVals.push((ytip+dy)-yChange*(i+1));\n }\n push();\n let x1, x2, y1, y2;\n // Carrier grid\n stroke(255,100,0,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-L[1])/L[0];\n y2 = ytip + dy;\n x2 = (xtip-dx) + xChange*(i+1);\n line(x1,y1,x2,y2);\n }\n \n // Solvent grid\n stroke(128,0,128,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-R[1])/R[0];\n y2 = ytip + dy;\n x2 = (xtip+dx) - xChange*(i+1);\n line(x1,y1,x2,y2);\n }\n // Solute grid\n stroke(0,0,255,80);\n for(let i = 0; i < yVals.length; i++){\n y1 = yVals[i];\n x1 = (y1-L[1])/L[0];\n y2 = y1;\n x2 = (y2-R[1])/R[0];\n line(x1,y1,x2,y2);\n }\n pop();\n}", "function plot(rows = 36, cols = 64) {\n\n /* 'c' will contain the whole generated html rect tags string to change innerhtml of enclosing div */\n /* 'y' will denote the 'y' coordinate where the next grid must be placed */\n let c = \"\", y = 0;\n\n /* Looping for each row */\n for (let i = 0; i < rows; i++) {\n\n /* 'x' is a coordinate denoting where the next grid must be placed */\n var x = 0;\n\n /* For each row we will loop for each column present in the Grid */\n for (let j = 0; j < cols; j++) {\n\n /* 'colr' will store the rest grid color which is dark gray currently */\n let colr = grid_color;\n\n /* If the Rectange present in the grid is on the border side then change the color in order to highlight borders */\n if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1){\n colr = border_color;\n }\n\n /* Creating a rect tag that is appending in 'c' for now and will be updated to innerhtml of enclosing div */\n /* I know you will be wondering about the id given to each rect :-\n * Each rect must be provided with id in order to do anything with the corresponding rect.\n * Operations like coloring the grid as well saving saving any number in corresponding matrix needs an id of the rect.\n * Hence id is important to allot to each rect to make further changes in matrix on which whole algo is based.\n * In order to assing every rect id i decided to allot their corresponding row_number + : + col_number to be as id\n * As with this scenario it is easy to remember and will be unique for every rect tag. \n */\n c += `<rect id=${i + \":\" + j} x=\"${x}\" y=\"${y}\" width=\"30\" height=\"30\" fill=\"${colr}\" r=\"0\" rx=\"0\" ry=\"0\" stroke=\"#000\" style=\"-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 0.2;\" stroke-opacity=\"0.2\"></rect>`;\n\n /* Incrementing the 'x' coordinate as we have width of 30px and hence 'x' coordinate for next rect will be +30 from current pos. */\n x += 30;\n }\n\n /* Incrementing the 'y' coordinate as we have placed sufficient rect in 1 row now need to advance 'y' as height of each rect \n is 30px hence for every rect in next column the y coordinate will be +30*/\n y += 30;\n }\n\n /* At last after creating rect tags using loops, now update innerHtml of enclosing div with id='container'[grid.html] */\n document.getElementById(\"container\").innerHTML = c;\n\n /* I wanted to preplace the Source - coordinate so at rect with id='src_crd' will be coloured green */\n document.getElementById(src_crd).style.fill = \"rgb(0, 255, 0)\";\n matrix[split(src_crd, 0)][split(src_crd, 1)] = 1; /* Update the pos as '1' to denote source location */\n\n /* I wanted to preplace the Destination - coordinate so at rect with id='dst_crd' will be coloured Red */\n document.getElementById(dst_crd).style.fill = \"rgb(255, 0, 0)\";\n matrix[split(dst_crd, 0)][split(dst_crd, 1)] = 2; /* Update the pos as '2' to denote Destination location */\n\n }", "draw_axes(gfx) {\n // Drawing in white\n gfx.noFill();\n gfx.stroke(255);\n\n // Draw the unit circle (width and height 2)\n gfx.ellipse(0, 0, 2, 2);\n\n // Draw x- and y-axes\n gfx.line(-10, 0, 10, 0);\n gfx.line(0, -10, 0, 10);\n }", "constructor(x1, y1, x2, y2, c)\n {\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n this.c = c;\n }", "show() {\n fill(255);\n noStroke();\n let sx = map(this.x/this.z, 0, 1, 0, width);\n let sy = map(this.y/this.z, 0, 1, 0, height);\n let r = map(this.z, 0, width, 8, 0);\n //ellipse(sx, sy, r, r);\n stroke(255);\n let px = map(this.x/this.pz, 0, 1, 0, width);\n let py = map(this.y/this.pz, 0, 1, 0, height);\n line(px,py, sx, sy);\n this.pz = this.z;\n }", "function ColorPlot(canvasId) {\n\tif(typeof(canvasId) === 'undefined' ) \n\t\tcanvasId = \"plotcanvas\";\n\n\tthis.canvasId = canvasId; \n\t\t\n\tthis.minX = 0;\n\tthis.maxX = 10;\n\tthis.scaleX = 1;\n\tthis.scaleY = 1;\n\tthis.minY = 0;\n\tthis.maxY = 1.5;\t\n\tthis.minZ = 0;\n\tthis.maxZ = 1;\n\t\t \n\tthis.x = new Array();\n\tthis.y= new Array();\n\tthis.z= new Array();\n\t\n\tthis.cmap = this.colormap();\n\t\n\tvar canvas = document.getElementById(this.canvasId);\n\tthis.buffer = document.createElement('canvas');\n\tthis.buffer.width = canvas.width;\n\tthis.buffer.height = canvas.height;\n\t\n\tthis.viewX = 0;\n\tthis.viewY = 0;\n\n}", "function drawPCGraph() {\r\n\r\n\tvar x = d3.scale.ordinal().rangePoints([0, 480], 1),\r\n y= {};\r\n \r\n for (var dim in cars[0]) {\r\n\t if (dim != \"name\") {\r\n\t\t y[dim] = d3.scale.linear()\r\n\t\t\t .domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])\r\n\t\t .range([height,0]);\r\n\t }\r\n }\r\n \r\n//sets the x domain dimensions\r\n x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != \"name\";}));\r\n\r\n//draws the polylines\r\n for (var i=1; i< cars.length; i++) { //for each car\r\n\r\n//prepare the coordinates for a polyline\r\n\t var lineData = []; //initialize an array for coordinates of a polyline\r\n\t for (var prop in cars[0]) { \r\n\t if (prop != \"name\" ) {\r\n\t var point = {}; \r\n\t var val = cars[i][prop];\r\n\t\t point['x'] = x(prop); \r\n\t point['y'] = y[prop](val);\r\n\t lineData.push(point);\r\n\t }\r\n\t }\r\n\r\n//draws a polyline based on the coordindates \r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"polyline\")\r\n\t .append(\"path\")\r\n\t\t .attr(\"d\", line(lineData))\r\n\t\r\n//Changes stroke red when mouseover\r\n\t.on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t.style(\"stroke\",\"red\")\r\n\t })\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.style(\"stroke\",null)\r\n\t\t\r\n})\r\n }\r\n\r\n var g = chart.selectAll(\".dimension\")\r\n\t .data(dimensions)\r\n\t .enter().append(\"g\")\r\n\t .attr(\"class\", \"dimension\")\r\n\t .attr(\"transform\", function(d) { return \"translate(\" + x(d) + \")\"; }) //translate each axis\r\n\r\n g.append(\"g\")\r\n\t .attr(\"class\", \"axis\")\r\n\t .each(function(d) { d3.select(this).call(axis.scale(y[d])); })\r\n\t .append(\"text\")\r\n\t .style(\"text-anchor\", \"middle\")\r\n\t .attr(\"y\", -4)\r\n\t .text(function(d) { return d; });\r\n\t \r\n \r\n}", "function show(c, r, l) {\n var col = l.rgb();\n var str = '(' + col.r + ', ' + col.g + ', ' + col.b + ')';\n\n document.getElementById('xcoord').innerHTML = c[0];\n document.getElementById('ycoord').innerHTML = c[1];\n document.getElementById('radius').innerHTML = r;\n document.getElementById('current-color').innerHTML = l.hex();\n document.getElementById('rgb-color').innerHTML = str;\n}", "function plot(x) { \n var canvas = document.getElementById(\"canvas\"); \n var c = canvas.getContext(\"2d\"); \n var canvasStyle = window.getComputedStyle(canvas, null); \n var width = parseInt(canvasStyle.width);\n var height= parseInt(canvasStyle.height); \n var offset = (1 / (x.length - 1)) * width;\n var maxX = x.reduce(function(a, b) { return Math.max(a, b);});\n var minX = x.reduce(function(a, b) { return Math.min(a, b);});\n // scale the input values to be plotted\n function drawToScale(input) {\n return height - ( (input-minX)*height) / (maxX-minX); \n } \n // remove the previuous lines\n c.clearRect(0, 0, width, height) \n // plot the new ones\n c.beginPath();\n c.moveTo(0, drawToScale(x[0]));\n for (var i = 1; i < x.length; i++) {\n c.lineTo(i * offset, drawToScale(x[i]) );\n }\n c.stroke();\n }", "function Circular() {\n\tvar D = document.getElementById(\"D\").value;\n\tvar Area, Cx, Cy, Ixx, Iyy;\n\tif (D == undefined) {\n\t\talert: \"Please Enter a Valid input\";\n\t}\n\tArea = 3.14 * D * D / 4;\n\tCx = 0;\n\tCy = 0;\n\tIxx = (3.14 / 64) * Math.pow(D,4);\n\tIyy = Ixx;\n\tdocument.getElementById(\"area\").innerHTML = Area + \" m^2\";\n\tdocument.getElementById(\"cog-x\").innerHTML = Cx + \" m\";\n\tdocument.getElementById(\"cog-y\").innerHTML = Cy + \" m\";\n\tdocument.getElementById(\"moi-xx\").innerHTML = Ixx + \" m^4\";\n\tdocument.getElementById(\"moi-yy\").innerHTML = Iyy + \" m^4\";\n}", "function drawGridCentre(x,y,s,rot){\r\n ctx.save();\r\n ctx.translate(x,y);\r\n ctx.rotate(rot*Math.PI/180);\r\n drawCircle(0,0,20, colArray[0], colArray[0], 2, false, true);\r\n for(j = 0; j<7 ; j++){\r\n for(var i = 0 ; i<7 ; i++){\r\n drawRectangle(0-s/2+i*s/7,0-s/2+j*s/7, s/7,s/7,colArray[3], colArray[4],0.5, false, true);\r\n }\r\n }\r\n ctx.restore();\r\n}", "function plot(x,y,color){\n ctx.fillStyle = color;\n ctx.fillRect(x,y,1,1);\n }", "function plot(data) {\r\n\tconvertData(data);\r\n\tcreateScales(data);\r\n\taddAxes();\r\n\taddGridlines();\r\n\tgroupDataByMainLifts(data);\r\n\tgroupDataByBw(data);\r\n\tdrawLines(mainLiftData);\r\n\tdrawLineLabels(mainLiftData);\r\n\tdrawBwLine(bwData)\r\n\tdrawCircles(data);\r\n\tdrawReps(data);\r\n\tconsole.log((bwData))\r\n}", "plot() {\n if (this.plot === 'Cumulative frequency plot' ||\n this.plot === 'Dot plot') {\n this.createPlot();\n }\n }", "function drawCircleGrid() {\n\t\tfor (var i = 180; i <= 1100; i+=100) {\n\t\t\tfor (var j = 50; j <= 1100; j+=100) {\n\t\t\t\tvar myCircle = new Path.Circle(new Point(i, j), 10);\n\t\t\t\tmyCircle.fillColor = hue();\n\t\t\t}\n\t\t}\n\t}", "function CubicPoly() {\n\n\t \t}", "function drawCanyon(t_canyon)\n{\n\tfor(var i = 0; i < canyons.length; i++)\n\t{\n\t\tfill(184, 134, 11);\n\t\trect(t_canyon.x_pos,432,t_canyon.width,150);\n\t\tnoStroke();\n\t\tfill(255);\n\t}\n}", "function init_xy(){\n\n\t\t\tg.append(\"line\")\n\t\t\t\t.attr(\"class\", \"xy\")\n\t\t\t\t.attr(\"x1\", 0)\n\t\t\t\t.attr(\"x2\", inner_w )\n\t\t\t\t.attr(\"y1\", h + 20)\n\t\t\t\t.attr(\"y2\", h + 20)\n\t\t\t\t.style(\"stroke\", \"#CCC\")\n\t\t\t\t.style(\"stroke-width\", \"1px\")\n\t\t\t\t.style(\"stroke-dasharray\", \"5 3\");\n\n\t\t}", "function drawCanyon(t_canyon) {\n {\n fill(101, 33, 67)\n noStroke();\n rect(t_canyon.canyonPos_x, t_canyon.canyonPos_y, t_canyon.width, t_canyon.height)\n }\n\n}", "function _via_draw_control_point(cx, cy) {\n _via_reg_ctx.beginPath();\n _via_reg_ctx.arc(cx, cy, VIA_REGION_POINT_RADIUS, 0, 2*Math.PI, false);\n _via_reg_ctx.closePath();\n\n _via_reg_ctx.fillStyle = \"white\";\n _via_reg_ctx.fill();\n}", "function plotGraph(){\n createAxis();\n // zoom.x(x).y(y);\n // console.log('setting scales');\n // console.log(x);\n // console.log(y);\n updateBoundaryGraph.setScales(x,y);\n }", "function CubicPoly() {\r\n\r\n\t\t}", "circb(x0, y0, r, c) {\n // evaluate runtime errors\n this.colorRangeError(c);\n let x = 0;\n let y = r;\n let p = 3 - 2 * r;\n this.circbPixGroup(x0, y0, x, y, c);\n while (x < y) {\n x++;\n if (p < 0) {\n p = p + 4 * x + 6;\n }\n else {\n y--;\n p = p + 4 * (x - y) + 10;\n }\n this.circbPixGroup(x0, y0, x, y, c);\n }\n }", "circPixGroup(x0, y0, x, y, c) {\n this.line(x0 + x, y0 + y, x0 - x, y0 + y, c);\n this.line(x0 + x, y0 - y, x0 - x, y0 - y, c);\n this.line(x0 + y, y0 + x, x0 - y, y0 + x, c);\n this.line(x0 + y, y0 - x, x0 - y, y0 - x, c);\n }", "function drawContour (obj)\n {\n // set the axis right\n obj.y.domain(range(obj.data.contour.yy));\n obj.x.domain(range(obj.data.contour.xx));\n\n // draw the target density\n var line = d3.svg.line()\n .x(function(d, i) { return obj.x(d.x); })\n .y(function(d, i) { return obj.y(d.y); });\n\n\t// obj.data.contour.points is array where element is an array corresponding to each contour line\n var lines = obj.plot.selectAll(\"path.contour\")\n .data(obj.data.contour.points);\n \n // This draws the path for the contour plot\n // Note that input is line, which array with each element corresponding to a curve on the contour plot\n lines.enter().append(\"path\")\n .attr(\"class\", \"contour\")\n .attr(\"d\", line)\n\n // draw the point at which the Metropolis algorithm is at\n var poi = {x : obj.data.metropolis.x.val, y : obj.data.metropolis.y.val};\n\n var point = obj.plot.selectAll(\"circle\")\n .data([poi]);\n\n point.enter().append(\"circle\")\n .attr(\"class\", \"currentValue\")\n .attr(\"cx\", function (d, i) { return obj.x(d.x); })\n .attr(\"cy\", function (d, i) { return obj.y(d.y); })\n .attr(\"r\", 7)\n .each( function (d)\n { this._current = Object(); this._current.d = d;\n this._current.name = 'contour'; this._current.obj = obj; return 0; });\n\n\n\t// draw previous points (the entire array of sampled points, including current point) \n\t// create pairs of points\n\t var prevPoi = makePoints(data.metropolis.x.vals,data.metropolis.y.vals)\n\t// create circles of class \"prev\" and pass data\n var prevPoints = obj.plot.selectAll(\"circle.prev\")\n .data(prevPoi);\n\t// plot points\n prevPoints.enter().append(\"circle\")\n .attr(\"class\", \"prev\")\n .attr(\"cx\", function (d, i) { return obj.x(d.x); })\n .attr(\"cy\", function (d, i) { return obj.y(d.y); })\n .attr(\"r\", 4)\n\n\n // create object that will hold lines connecting sampled points; plot lines\n var connectLines = []\n if(data.metropolis.currentIteration > 0){\n \t\tfor(var ii=1; ii < prevPoi.length; ii++){\n \tconnectLines.push({'x1':prevPoi[ii-1].x,'y1':prevPoi[ii-1].y,'x2':prevPoi[ii].x,'y2':prevPoi[ii].y})\n \t}\n }\n\n var lines = obj.plot.selectAll(\"line\")\n .data(connectLines);\n \n lines.enter().append(\"line\")\n .attr('class', 'connect')\n .attr(\"x1\", function (d, i) { return obj.x(d.x1); })\n .attr(\"y1\", function (d, i) { return obj.y(d.y1); })\n .attr(\"x2\", function (d, i) { return obj.x(d.x2); })\n .attr(\"y2\", function (d, i) { return obj.y(d.y2); })\n .style(\"opacity\", 0.85)\n .style(\"stroke\", \"red\")\n .attr(\"stroke-dasharray\", \"5, 5\");\n \n \n\n\t// Calculate acceptance rate of Metropolis algorithm (only if at least 1 iteration...)\n\tif(data.metropolis.accepted.length!=0)\n\t{\n\t\tvar sumAccept = data.metropolis.accepted.reduce(function(a, b) { return a + b });\n\t\tvar percAccept = sumAccept/data.metropolis.accepted.length;\n\t\tvar acceptRate = d3.selectAll(\".acceptRate\");\n\t\tacceptRate.html(\"Acceptance Rate of Proposals: \" + d3.round(100 * percAccept, 2)+\"%\");;\n\t}\n\n\n // handle the transitions (this is necessary to reset plot when hit \"Refresh\")\n var tr = obj.svg.transition().duration(500);\n // rescale axes\n tr.select(\".y.axis\").call(obj.yAxis);\n tr.select(\".x.axis\").call(obj.xAxis);\n // Redraw current point in Metropolis algorithm + path leading to it\n tr.select(\"circle\").attr(\"cx\", function(d){return obj.x(d.x);})\n .attr(\"cy\",function(d){return obj.y(d.y);});\n // Redraw contour plot\n tr.selectAll(\"path.contour\").attr('d', function (d)\n { return line(d) } );\n \n // transitions for lines\n tr.selectAll(\"line.connect\")\n .attr(\"x1\", function (d, i) { return obj.x(d.x1); })\n .attr(\"y1\", function (d, i) { return obj.y(d.y1); })\n .attr(\"x2\", function (d, i) { return obj.x(d.x2); })\n .attr(\"y2\", function (d, i) { return obj.y(d.y2); })\n .style(\"opacity\", 0.85)\n .style(\"stroke\", \"red\")\n .attr(\"stroke-dasharray\", \"5, 5\");\n \n // remove all previous points and lines connecting them from plot when hit \"refresh\"\n prevPoints.exit().remove();\n lines.exit().remove();\n return 0;\n }", "function ChannelPlotChannel(imyPlot) {\n this.myPlot = imyPlot;\n this.FixedSizeY = -1; //negative value= flexible\n\n //Draws a vertical scale in the left panel of the channel\n this.DrawVertScale = function(DrawInfo, minvl, maxvl) {\n var jumps = GetScaleJump((maxvl - minvl) / 15);\n\n DrawInfo.LeftContext.fillStyle = \"black\";\n DrawInfo.LeftContext.font = '10px sans-serif';\n DrawInfo.LeftContext.textBaseline = 'bottom';\n DrawInfo.LeftContext.textAlign = 'right';\n\n DrawInfo.LeftContext.strokeStyle = \"black\";\n DrawInfo.CenterContext.strokeStyle = \"black\";\n DrawInfo.LeftContext.globalAlpha = 0.6;\n DrawInfo.CenterContext.globalAlpha = 0.2;\n for (j = Math.ceil(minvl / jumps.Jump1); j <= Math.floor(maxvl / jumps.Jump1); j++) {\n vl = j * jumps.Jump1;\n yp = Math.round(DrawInfo.PosY - DrawInfo.SizeY * 0.1 - (vl - minvl) / (maxvl - minvl) * DrawInfo.SizeY * 0.8) - 0.5;\n if (j % jumps.JumpReduc == 0) {\n DrawInfo.LeftContext.beginPath();\n DrawInfo.LeftContext.moveTo(DrawInfo.LeftSizeX - 8, yp);\n DrawInfo.LeftContext.lineTo(DrawInfo.LeftSizeX, yp);\n DrawInfo.LeftContext.stroke();\n DrawInfo.LeftContext.fillText(vl, DrawInfo.LeftSizeX - 12, yp + 5);\n DrawInfo.CenterContext.beginPath();\n DrawInfo.CenterContext.moveTo(0, yp);\n DrawInfo.CenterContext.lineTo(DrawInfo.SizeX, yp);\n DrawInfo.CenterContext.stroke();\n }\n else {\n DrawInfo.LeftContext.beginPath();\n DrawInfo.LeftContext.moveTo(DrawInfo.LeftSizeX - 4, yp);\n DrawInfo.LeftContext.lineTo(DrawInfo.LeftSizeX, yp);\n DrawInfo.LeftContext.stroke();\n }\n }\n DrawInfo.LeftContext.globalAlpha = 1;\n DrawInfo.CenterContext.globalAlpha = 1;\n\n }\n\n\n //Draws a message in the center panel of the channel\n this.DrawMessage = function (DrawInfo, txt) {\n DrawInfo.CenterContext.fillStyle = \"black\";\n DrawInfo.CenterContext.globalAlpha = 0.2;\n DrawInfo.CenterContext.fillRect(0, DrawInfo.PosY - DrawInfo.SizeY, DrawInfo.SizeX, DrawInfo.SizeY);\n DrawInfo.CenterContext.globalAlpha = 1.0;\n\n DrawInfo.LeftContext.fillStyle = \"black\";\n DrawInfo.LeftContext.globalAlpha = 0.2;\n DrawInfo.LeftContext.fillRect(0, DrawInfo.PosY - DrawInfo.SizeY, DrawInfo.LeftSizeX, DrawInfo.SizeY);\n DrawInfo.LeftContext.globalAlpha = 1.0;\n\n DrawInfo.CenterContext.fillStyle = \"black\";\n DrawInfo.CenterContext.font = '25px sans-serif';\n DrawInfo.CenterContext.textBaseline = 'bottom';\n DrawInfo.CenterContext.textAlign = 'center';\n DrawInfo.CenterContext.globalAlpha = 0.6;\n DrawInfo.CenterContext.fillText(txt, DrawInfo.SizeX / 2, DrawInfo.PosY - DrawInfo.SizeY / 2 + 12);\n DrawInfo.CenterContext.globalAlpha = 1.0;\n }\n\n //Draws a title in the left panel of the channel\n this.DrawTitle = function (DrawInfo) {\n DrawInfo.LeftContext.save();\n DrawInfo.LeftContext.translate(0, DrawInfo.PosY - DrawInfo.SizeY / 2);\n DrawInfo.LeftContext.rotate(-Math.PI / 2);\n DrawInfo.LeftContext.textBaseline = 'top';\n DrawInfo.LeftContext.textAlign = \"center\";\n DrawInfo.LeftContext.font = '14px sans-serif';\n DrawInfo.LeftContext.fillStyle = \"black\";\n if (\"Title\" in this)\n DrawInfo.LeftContext.fillText(this.Title, 0, 5);\n if (\"SubTitle\" in this) {\n DrawInfo.LeftContext.font = '12px sans-serif';\n DrawInfo.LeftContext.fillStyle = \"rgb(100,100,100)\";\n DrawInfo.LeftContext.fillText(this.SubTitle, 0, 25);\n }\n DrawInfo.LeftContext.restore();\n }\n\n //Get tooltip info at a specific point in screen coordinates in the channel\n //Default behaviour: return null. This function can be overriden by a specific implementation of a channel\n //Note that the return object will be digested by the function DrawChannelToolTip\n this.GetToolTipInfo = function (xp, yp) {\n return null;\n }\n\n //Handle a click event inside a channel\n //Default behaviour: do nothing. This function can be overriden by a specific implementation of a channel\n this.OnClick = function (xp, yp) {\n }\n\n\n}", "constructor(x, y, t, r, n, c) {\n\t\tsuper(x, y);\n\t\tthis.theta = t;\t//in degrees\n\t\tthis.circumRad = r;\n\t\tthis.vertexNum = n;\n\t\tthis.color = c;\n\t}", "function plotGrid() {\n let equalParts = (maxValue/5).toPrecision(2);\n lenAxis = equalParts*6;\n let ticks = [equalParts, equalParts*2, equalParts*3, equalParts*4, equalParts*5, lenAxis];\n \n // griglie\n let circle = svg.selectAll(\".grid\")\n .data(ticks);\n\n circle.exit().remove(); // exit\n\n circle.enter() // enter\n .append(\"circle\")\n .attr(\"class\", \"grid\")\n .attr(\"cx\", cx)\n .attr(\"cy\", cy)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"gray\")\n .transition().duration(1000)\n .attr(\"r\", t=>rScale(t));\n\n // scritte\n let txt = svg.selectAll(\".tick\")\n .data(ticks);\n \n txt.exit().remove(); //exit\n\n txt.enter() //enter\n .append(\"text\")\n .attr(\"class\", \"tick\")\n .attr(\"x\", cx+5)\n .attr(\"y\", t=>cy-rScale(t)-1)\n .transition().duration(1000).delay(1000)\n .attr(\"opacity\", 1)\n .text(t=>t.toString());\n}", "function CubicPoly() {\r\n\r\n\t}", "function CubicPoly() {\n\n\t}", "function CubicPoly() {\n\n\t}", "function render() {\n dots\n .attr(\"cx\", function (d) {\n return project(d).x;\n })\n .attr(\"cy\", function (d) {\n return project(d).y;\n });\n }", "function drawCirc(){\n for(y = 0; y < shapePosY.length; y++){\n for(i = 0; i < shapePosX.length; i++){\n noStroke();\n fill(colors.reverse()[i]);\n circle(shapePosX[i], shapePosY[y], 20);\n }\n }\n}", "constructor(name, x, y) {\n this.name = name;\n this.x = x;\n this.y = y;\n this.w = 50;\n this.h = 50;\n this.ax = x;\n this.ay = y;\n }", "function plot (x,y,val){\n\tdocument.getElementById(\"c\"+x+\".\"+y).style.backgroundColor = colors[val]; //on prend l'id cx.y et on lui attribue la valeur du tableau colors, val = indice couleur//\n document.getElementById(\"c\"+x+\".\"+y).value = val; //On dit que la valeur de cette case est val, c'est pour ça qu'on peut la retourner avec la fonction get//\n}", "function drawPC() {\r\n\t\r\n//setting the x and y scale \r\n\tvar x = d3.scale.ordinal().rangePoints([0, 480], 1),\r\n y= {};\r\n \r\n// Extract the list of dimensions and create a scale for each.\r\n for (var dim in cars[0]) {\r\n\t if (dim != \"name\") {\r\n\t\t y[dim] = d3.scale.linear()\r\n\t\t\t .domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])\r\n\t\t .range([height,0]);\r\n\t }\r\n }\r\n \r\n//setting the x domain dimensions\r\n x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != \"name\";}));\r\n\r\n//draw polylines\r\n for (var i=1; i< cars.length; i++) { \r\n\r\n//prepare the coordinates for a polyline\r\n\t var lineData = []; //initialize an array for coordinates of a polyline\r\n\t for (var prop in cars[0]) { //get each dimension\r\n\t if (prop != \"name\" ) { //skip the name dimension\r\n\t var point = {}; //initialize a coordinate object\r\n\t var val = cars[i][prop]; //obtain the value of a car in a dimension\r\n\t\t point['x'] = x(prop); //x value: mapping the dimension \r\n\t point['y'] = y[prop](val);//y value: mapping the value in that dimension\r\n\t lineData.push(point); //add the object into the array \r\n\t }\r\n\t }\r\n\r\n//draw a polyline based on the coordindates \r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"polyline\")\r\n\t .append(\"path\") // a path shape\r\n\t\t .attr(\"d\", line(lineData)) //line() is a function to turn coordinates into SVG commands\r\n\t\r\n//the mouseover function that changes the strokes to red when the mouse is over them\r\n\t.on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t.style(\"stroke\",\"red\")\r\n\t })\r\n//the mouseout function that changes the strokes back to their original color\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.style(\"stroke\",null)\r\n\t\t\r\n})\r\n }\r\n\r\n//draw individual dimension lines\r\n//position dimension lines \r\n var g = chart.selectAll(\".dimension\")\r\n\t .data(dimensions)\r\n\t .enter().append(\"g\")\r\n\t .attr(\"class\", \"dimension\")\r\n\t .attr(\"transform\", function(d) { return \"translate(\" + x(d) + \")\"; }) //translate each axis\r\n\r\n\t\r\n// Add an axis and title.\r\n g.append(\"g\")\r\n\t .attr(\"class\", \"axis\")\r\n\t .each(function(d) { d3.select(this).call(axis.scale(y[d])); })\r\n\t .append(\"text\")\r\n\t .style(\"text-anchor\", \"middle\")\r\n\t .attr(\"y\", -4)\r\n\t .text(function(d) { return d; });\r\n\t \r\n \r\n}", "function drawPoleZeroPlot() {\n\n zPlaneContext.clearRect(0, 0, 275, 280);\n zPlaneContext.font = '12px Arial';\n\n // This helper function returns the pixel coordinates inside the $z$-plane canvas\n // for a complex number `z`.\n var coordinatesFromComplexNumber = function(z) {\n return {\n x: unitCircle.x + z.real * unitCircle.radius,\n y: unitCircle.y - z.imaginary * unitCircle.radius\n };\n };\n\n // This helper function is used to determine the multiplicity of poles or\n // zeros.\n var countMultiplicity = function(result, z) {\n var w = _.find(result, _.compose(_.partial(Complex.areEqual, z), function(w) { return w.z; }));\n if (w !== undefined) {\n w.multiplicity++;\n }\n else {\n result.push( { z: z, multiplicity: 1 });\n }\n return result;\n };\n\n // Draw a circle at each zero.\n var zerosToRender = _.reduce(filter.zeros, countMultiplicity, []);\n _.each(zerosToRender, function(zero) {\n zPlaneContext.beginPath();\n var p = coordinatesFromComplexNumber(zero.z);\n var radius = Complex.areEqual(zero.z, selection) ? 4.5 : 4.0;\n zPlaneContext.arc(p.x, p.y, radius, 0, 2 * Math.PI, false);\n zPlaneContext.strokeStyle = Complex.areEqual(zero.z, hover) ? '#00677e' : '#00374e';\n zPlaneContext.lineWidth = Complex.areEqual(zero.z, selection) ? 3.0 : 2.0;\n zPlaneContext.stroke();\n if (zero.multiplicity > 1) {\n zPlaneContext.fillText(zero.multiplicity, p.x + 5, p.y - 5);\n }\n });\n\n // Draw a cross at each pole.\n var polesToRender = _.reduce(filter.poles, countMultiplicity, []);\n _.each(polesToRender, function(pole) {\n zPlaneContext.beginPath();\n var p = coordinatesFromComplexNumber(pole.z);\n var radius = Complex.areEqual(pole.z, selection) ? 4.5 : 4.0;\n zPlaneContext.moveTo(p.x - radius, p.y + radius);\n zPlaneContext.lineTo(p.x + radius, p.y - radius);\n zPlaneContext.moveTo(p.x - radius, p.y - radius);\n zPlaneContext.lineTo(p.x + radius, p.y + radius);\n zPlaneContext.strokeStyle = Complex.areEqual(pole.z, hover) ? '#00677e' : '#00374e';\n zPlaneContext.lineWidth = Complex.areEqual(pole.z, selection) ? 3.0 : 2.0;\n zPlaneContext.stroke();\n if (pole.multiplicity > 1) {\n zPlaneContext.fillText(pole.multiplicity, p.x + 5, p.y - 5);\n }\n });\n }", "createAxes () {\n }", "function axis(ctx, color, axisx, axisy, px, d1,py, d2) {\n var w = ctx.canvas.width;\n var h = ctx.canvas.height;\n\n ctx.strokeStyle = color;\n\n //if axis function is below grid function\n // and grid is dotted this removes the axis from\n // dotted back to normal line\n ctx.setLineDash([0, 0]);\n\n //if the axis is undefined in both direction creates it at the far left corner like a normal graph\n if (axisy == undefined && axisx == undefined) {\n lines(ctx, 1, h - 1, w - 1, h - 1, 1);\n lines(ctx, 1, 1, 1, h - 1, 1);\n }\n\n //the same as above\n else if (axisx == w && axisy == h) {\n lines(ctx, 1, axisy - 1, axisx - 1, axisy - 1, 1);\n lines(ctx, 1, 1, 1, axisy - 1, 1);\n }\n\n //if axisx and axis y are numbers the axis will be created inwards to the number that has been created.\n else if (typeof axisx == \"number\" && typeof axisy == \"number\") {\n lines(ctx, 0, axisy, w, axisy, 3);\n lines(ctx, axisx, 0, axisx, h, 3);\n }\n\n // if axisy and axisx are inputed as middle the x and y axis will be created in the center of the canvas\n else if (axisx == \"middle\" && axisy == \"middle\") {\n axisx = w / 2;\n axisy = h / 2;\n\n lines(ctx, h / 2, w, h / 2, 2);\n\n lines(ctx, w / 2, w / 2, h, 2);\n }\n\n // creates the x for the creation of axis points as pf now only at the positive x axis\n if (px == \"px\" && py == \"py\") {\n let i = axisx;\n let j = 0;\n let k = 0;\n let l = 0;\n\n //creates positive x axis points\n for (i = axisx; i <= w; i += d1) {\n lines(ctx, i, axisy, i, axisy + 10, 1);\n }\n\n //create negative y axis points\n for (l = axisy; l >= 0; l -= d2) {\n lines(ctx, axisx, l, axisx - 10, l, 1);\n }\n\n //creates positive y axis points\n for (j = axisy; j <= h; j += d2) {\n lines(ctx, axisx - 10, j, axisx, j, 1);\n }\n //creates negative x axis points\n for (k = axisx; k >= 0; k -= d1) {\n lines(ctx, k, axisy, k, axisy + 10, 1);\n }\n }\n\n else if(px =='px' && py == undefined){\n let i = 0;\n let k = 0;\n //creates positive x axis points\n for (i = axisx; i <= w; i += d1) {\n lines(ctx, i, axisy, i, axisy + 10, 1);\n }\n\n //creates negative x axis points\n for (k = axisx; k >= 0; k -= d1) {\n lines(ctx, k, axisy, k, axisy + 10, 1);\n }\n }\n}", "function cs_geocentric_to_geodetic (cs, p) {\n\n var X =p.x;\n var Y = p.y;\n var Z = p.z;\n var Longitude;\n var Latitude;\n var Height;\n\n var W; /* distance from Z axis */\n var W2; /* square of distance from Z axis */\n var T0; /* initial estimate of vertical component */\n var T1; /* corrected estimate of vertical component */\n var S0; /* initial estimate of horizontal component */\n var S1; /* corrected estimate of horizontal component */\n var Sin_B0; /* Math.sin(B0), B0 is estimate of Bowring aux variable */\n var Sin3_B0; /* cube of Math.sin(B0) */\n var Cos_B0; /* Math.cos(B0) */\n var Sin_p1; /* Math.sin(phi1), phi1 is estimated latitude */\n var Cos_p1; /* Math.cos(phi1) */\n var Rn; /* Earth radius at location */\n var Sum; /* numerator of Math.cos(phi1) */\n var At_Pole; /* indicates location is in polar region */\n\n X = parseFloat(X); // cast from string to float\n Y = parseFloat(Y);\n Z = parseFloat(Z);\n\n At_Pole = false;\n if (X != 0.0)\n {\n Longitude = Math.atan2(Y,X);\n }\n else\n {\n if (Y > 0)\n {\n Longitude = HALF_PI;\n }\n else if (Y < 0)\n {\n Longitude = -HALF_PI;\n }\n else\n {\n At_Pole = true;\n Longitude = 0.0;\n if (Z > 0.0)\n { /* north pole */\n Latitude = HALF_PI;\n }\n else if (Z < 0.0)\n { /* south pole */\n Latitude = -HALF_PI;\n }\n else\n { /* center of earth */\n Latitude = HALF_PI;\n Height = -cs.b;\n return;\n }\n }\n }\n W2 = X*X + Y*Y;\n W = Math.sqrt(W2);\n T0 = Z * AD_C;\n S0 = Math.sqrt(T0 * T0 + W2);\n Sin_B0 = T0 / S0;\n Cos_B0 = W / S0;\n Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;\n T1 = Z + cs.b * cs.ep2 * Sin3_B0;\n Sum = W - cs.a * cs.es * Cos_B0 * Cos_B0 * Cos_B0;\n S1 = Math.sqrt(T1*T1 + Sum * Sum);\n Sin_p1 = T1 / S1;\n Cos_p1 = Sum / S1;\n Rn = cs.a / Math.sqrt(1.0 - cs.es * Sin_p1 * Sin_p1);\n if (Cos_p1 >= COS_67P5)\n {\n Height = W / Cos_p1 - Rn;\n }\n else if (Cos_p1 <= -COS_67P5)\n {\n Height = W / -Cos_p1 - Rn;\n }\n else\n {\n Height = Z / Sin_p1 + Rn * (cs.es - 1.0);\n }\n if (At_Pole == false)\n {\n Latitude = Math.atan(Sin_p1 / Cos_p1);\n }\n\n p.x = Longitude;\n p.y =Latitude;\n p.z = Height;\n return 0;\n}", "function drawCylinder() {\n setMV();\n Cylinder.draw();\n}", "function drawCylinder() {\n setMV();\n Cylinder.draw();\n}", "function makecncsvgexport()\n{\n var c,d,x,y,x0,y0,pts,txt=\"\";\n getdefaults();\n var sfx=cutterwidth/(xmax-xmin);\n var sfy=cutterheight/(ymax-ymin);\n switch(originpos)\n {\n case 0: originx=0; originy=0; break; // Bottom left\n case 1: originx=0; originy=cutterheight; break; // Top left\n case 2: originx=cutterwidth; originy=0; break; // Bottom right\n case 3: originx=cutterwidth; originy=cutterheight; break; // Top right\n case 4: originx=cutterwidth/2; originy=cutterheight/2; break; // Middle\n }\n txt+='<?xml version=\"1.0\" encoding=\"utf-8\"?>\\r\\n';\n txt+='<svg id=\"gcodercncsvg\" width=\"'+cutterwidth+'px\" height=\"'+cutterheight+'px\" style=\"background-color:#FFFFFF\" version=\"1.1\" ';\n txt+='xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" ';\n txt+=makedefaultsparams()+' ';\n txt+='>\\r\\n';\n for(c=0;c<commands.length;c++)\n {\n if(commands[c][0]==='L')\n {\n pts=commands[c][1];\n pts=scaletoolpath(pts,sfx,sfy,cutterheight);\n pts=simplifytoolpath(pts,arcdist);\n txt+=' <path id=\"'+commands[c][12]+'\" d=\"M ';\n for(d=0;d<pts.length;d++)\n {\n x=pts[d][0]-originx;\n y=(cutterheight-pts[d][1])-originy;\n if(d===0)\n {\n x0=x;\n y0=y;\n }\n if(d===pts.length-1 && commands[c][11]===1) txt+=\"Z\";\n else txt+=x.toFixed(3)+\",\"+y.toFixed(3)+\" \";\n }\n txt+='\" opacity=\"1\" stroke=\"#000000\" stroke-opacity=\"1\" stroke-width=\"1\" stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-dasharray=\"none\" fill-opacity=\"0\" ';\n txt+=makepathparams(c)+' ';\n txt+='/>\\r\\n';\n }\n }\n txt+='</svg>\\r\\n';\n return txt;\n}", "function drawScatterMatrix(trips){\n\n\tspeed = [];\n\tdistance =[];\n\tduration=[];\n\tfor (var i =0;i<trips.length;i++)\n\t{\n\t speed[i]=trips[i].avspeed;\n\t\t distance[i]=trips[i].distance;\n\t\t duration[i]=trips[i].duration;\n\t}\n\n\tgoogle.charts.load('current', {'packages':['corechart']}); \n google.charts.setOnLoadCallback(drawScatterMatrixCallBack(speed,distance,duration)); \n}", "function plotCrossHair(bestI) {\n\n // get data from window\n dataList = window.data;\n\n var x = dataList[0][bestI];\n var yMin = dataList[1][bestI];\n var yMax = dataList[2][bestI];\n\n // Draw the cross hair\n ctx.lineWidth = 2;\n var r = 5;\n\n // circles\n ctx.beginPath();\n ctx.arc(x, yMin, r, 0, 2 * Math.PI);\n ctx.stroke();\n ctx.beginPath();\n ctx.arc(x, yMax, r, 0, 2 * Math.PI);\n ctx.stroke();\n\n // vertical line\n ctx.moveTo(x, GRAPH_BOTTOM);\n ctx.lineTo(x, yMin + r);\n ctx.moveTo(x, yMin - r);\n ctx.lineTo(x, yMax + r);\n ctx.moveTo(x, yMax - r);\n ctx.lineTo(x, GRAPH_TOP);\n\n // horizontal line\n ctx.moveTo(GRAPH_LEFT, yMin);\n ctx.lineTo(x - r, yMin);\n ctx.moveTo(x + r, yMin);\n ctx.lineTo(GRAPH_RIGHT, yMin);\n ctx.moveTo(GRAPH_LEFT, yMax);\n ctx.lineTo(x - r, yMax);\n ctx.moveTo(x + r, yMax);\n ctx.lineTo(GRAPH_RIGHT, yMax);\n ctx.stroke();\n\n // draw the x and y data next to the lines\n var date = window.data[4][bestI].toString();\n for (var i = 0; i < date.length; i++) {\n var year = date[0] + date[1] + date[2] + date[3];\n var month = date[4] + date[5];\n var day = date[6] + date[7];\n }\n var dateString = year + '/' + month + '/' + day\n var tempMin = window.data[5][bestI] / 10;\n var tempMax = window.data[6][bestI] / 10;\n\n // type selected data\n ctx.font = \"bold 25px sans-serif\";\n ctx.fillText(dateString + \": Min = \" + tempMin +\n \", Max = \" + tempMax, GRAPH_LEFT + 20, GRAPH_BOTTOM + 60);\n ctx.stroke();\n}", "function plotCorr(id) {\n let data = dictMetrics[id];\n dictAbs = dictAbsGlobal[id];\n $(\"#correlation_bar_graph\").html(\"\");\n $(\"#actualPredicted\").html(\"\");\n updatePlot(1997);\n draw_correlation_bar_graph(data);\n}", "function CubicPoly() {}", "function CubicPoly() {}", "function CubicPoly() {}", "function CubicPoly() {}", "function CubicPoly() {}", "function doPlot(id, xArr, xLabel, yArr, yLabel) {\n\n var margin = { top: 10, right: 10, bottom: 50, left: 50 },\n // outerWidth = 350,\n // outerHeight = 300,\n outerWidth = getWidth() / 5,\n outerHeight = getHeight() / 3,\n width = outerWidth - margin.left - margin.right,\n height = outerHeight - margin.top - margin.bottom;\n\n var x = d3.scale.linear()\n .range([0, width]).nice();\n\n var y = d3.scale.linear()\n .range([height, 0]).nice();\n\n // var xLabel = \"Voltage\",\n // yLabel = \"Current\",\n // colorCat = \"Manufacturer\";\n\n // d3.csv(\"http://rohin.me/dev/mettletest/cerial.csv\", function(data) {\n // data.forEach(function(d) {\n // d.Voltage = +d.Voltage;\n // d.Current = +d.Current;\n // });\n\n data = [];\n\n if (xArr.length == 0 || yArr.length == 0) {\n data.push([0, 0]);\n } else {\n data = xArr.map(function (_, i) {\n return [xArr[i], yArr[i], i];\n });\n }\n\n dataLength = data.length\n // data = [];\n // data.push([1, 1]);\n // data.push([2, 2]);\n // data.push([3, 3]);\n // data.push([4, 4]);\n // data.push([5, 5]);\n // console.log(data);\n\n let xMax = d3.max(data, function (d) { return d[0]; }) * 1.05;\n let xMin = d3.min(data, function (d) { return d[0]; });\n\n let yMax = d3.max(data, function (d) { return d[1]; }) * 1.05;\n let yMin = d3.min(data, function (d) { return d[1]; });\n\n yMin = yMin > 0 ? 0 : yMin;\n xMin = xMin > 0 ? 0 : xMin,\n\n x.domain([xMin, xMax]);\n y.domain([yMin, yMax]);\n\n var xAxis = d3.svg.axis()\n .scale(x)\n .orient(\"bottom\")\n .tickSize(-height);\n\n var yAxis = d3.svg.axis()\n .scale(y)\n .orient(\"left\")\n .tickSize(-width);\n\n var color = d3.scale.category10();\n\n var tip = d3.tip()\n .attr(\"class\", \"d3-tip\")\n .offset([-10, 0])\n .html(function (d) {\n $log('graph', 'hover', {\n id: xLabel +\" vs \" + yLabel,\n values: \"(\" + d[0] + \",\" + d[1] + \")\"\n })\n return xLabel + \": \" + d[0] + \"<br>\" + yLabel + \": \" + d[1];\n });\n\n var zoomBeh = d3.behavior.zoom()\n .x(x)\n .y(y)\n .scaleExtent([0, 500])\n .on(\"zoom\", zoom);\n\n var svg = d3.select(\"#\" + id)\n .append(\"svg\")\n .attr(\"width\", outerWidth)\n .attr(\"height\", outerHeight)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\")\n .call(zoomBeh);\n\n svg.call(tip);\n\n svg.append(\"rect\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n\n svg.append(\"g\")\n .classed(\"x axis\", true)\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis)\n .append(\"text\")\n .classed(\"label\", true)\n .attr(\"x\", width)\n .attr(\"y\", margin.bottom - 10)\n .style(\"text-anchor\", \"end\")\n .text(xLabel).style(\"font-size\", 20).style(\"font-weight\", \"600\");\n\n svg.append(\"g\")\n .classed(\"y axis\", true)\n .call(yAxis)\n .append(\"text\")\n .classed(\"label\", true)\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", -margin.left)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(yLabel).style(\"font-size\", 20).style(\"font-weight\", \"600\");;\n\n var objects = svg.append(\"svg\")\n .classed(\"objects\", true)\n .attr(\"width\", width)\n .attr(\"height\", height);\n\n objects.append(\"svg:line\")\n .classed(\"axisLine hAxisLine\", true)\n .attr(\"x1\", 0)\n .attr(\"y1\", 0)\n .attr(\"x2\", width)\n .attr(\"y2\", 0)\n .attr(\"transform\", \"translate(0,\" + height + \")\");\n\n objects.append(\"svg:line\")\n .classed(\"axisLine vAxisLine\", true)\n .attr(\"x1\", 0)\n .attr(\"y1\", 0)\n .attr(\"x2\", 0)\n .attr(\"y2\", height);\n\n objects.selectAll(\".dot\")\n .data(data)\n .enter().append(\"circle\")\n .classed(\"dot\", true)\n .attr(\"r\", function (d) { /*console.log(d);*/ return 4; /*Math.sqrt(d[rCat] / Math.PI);*/ })\n .attr(\"transform\", transform)\n .style(\"fill\",\n function (d) {\n if (d[2] == dataLength - 1) {\n return \"#FFC107\"\n } else {\n // console.log(\"MotorID\" + motorIDArr[d[2]]);\n var motorID = motorIDArr[d[2]];\n return motorSpecs[motorID ? motorID : 0][4];\n // TODO:very hacky\n }\n })\n .on(\"mouseover\", tip.show)\n .on(\"mouseout\", tip.hide);\n\n var legend = svg.selectAll(\".legend\")\n .data(color.domain())\n .enter().append(\"g\")\n .classed(\"legend\", true)\n .attr(\"transform\", function (d, i) { return \"translate(0,\" + i * 20 + \")\"; });\n\n legend.append(\"circle\")\n .attr(\"r\", 3.5)\n .attr(\"cx\", width + 20)\n .attr(\"fill\", color);\n\n legend.append(\"text\")\n .attr(\"x\", width + 26)\n .attr(\"dy\", \".35em\")\n .text(function (d) { return d; });\n\n // d3.select(\"input\").on(\"click\", change);\n\n // function change() {\n // // xLabel = \"Carbs\";\n // xMax = d3.max(data, function(d) { return d[xLabel]; });\n // xMin = d3.min(data, function(d) { return d[xLabel]; });\n // yMax = d3.max(data, function(d) { return d[yLabel]; });\n // yMin = d3.min(data, function(d) { return d[yLabel]; });\n\n // zoomBeh.x(x.domain([xMin, xMax])).y(y.domain([yMin, yMax]));\n\n // var svg = d3.select(\"#scatter\").transition();\n\n // svg.select(\".x.axis\").duration(750).call(xAxis).select(\".label\").text(xLabel);\n\n // objects.selectAll(\".dot\").transition().duration(1000).attr(\"transform\", transform);\n // }\n\n // hanldes zoom event on graph\n function zoom() {\n svg.select(\".x.axis\").call(xAxis);\n svg.select(\".y.axis\").call(yAxis);\n\n svg.selectAll(\".dot\")\n .attr(\"transform\", transform);\n }\n\n function transform(d) {\n return \"translate(\" + x(d[0]) + \",\" + y(d[1]) + \")\";\n }\n // });\n}", "function showConjugates () {\n\n pointsTable = lens.pointsTable.getData(); \n pointsList = Optics.calculatePointToPoint(renderableLens.total, pointsTable);\n totalLens = renderableLens.total;\n\n if (pointsList.length > 0) {\n pointsList.forEach( elem => {\n console.log(\"showing .... conjugate pair id = \" + elem.id);\n drawConjugates(elem, displayOptions);\n } );\n }\n }", "function FunctionPlotter(options) {\n let axisTickCounts,\n functions,\n gridBoolean,\n group,\n hasTransitioned,\n plotArea,\n plotter,\n range,\n width,\n where,\n x,\n y;\n\n plotter = this;\n\n init(options);\n\n return plotter;\n\n /* INITIALIZE */\n function init(options) {\n let curtain;\n\n _required(options);\n _defaults(options);\n\n\n curtain = addCurtain();\n plotter.scales = defineScales();\n plotter.axisTitles = {};\n group = addGroup();\n plotArea = addPlotArea();\n plotter.layers = addLayers();\n plotter.grid = addGrid();\n plotter.axes = addAxes();\n plotter.lines = addLines(functions);\n plotter.hotspot = addHotspot();\n\n plotter.hasTransitioned = false;\n\n // valueCircle = false;\n\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n axisTickCounts = options.axisTicks ? options.axisTicks : {\"x\":1,\"y\":1};\n functions = options.functions ? options.functions : [];\n plotter.height = options.height ? options.height : 400;\n plotter.width = options.width ? options.width : 800;\n plotter.domain = options.domain ? options.domain : [0,10];\n plotter.range = options.range ? options.range : [0,10];\n plotter.margins = options.margins ? options.margins : defaultMargins();\n //TODO: THIS IS SLOPPY. GRID SHOULD BE CLEARER\n gridBoolean = options.hideGrid ? false : true;\n x = options.x ? options.x : 0;\n y = options.y ? options.y : 0;\n plotter.coordinates = options.coordinates ? options.coordinates : {\"x\":x,\"y\":y};\n plotter.fontFamily = options.fontFamily ? options.fontFamily : \"\";\n\n }\n\n function _required(options) {\n\n hasTransitioned = false;\n where = options.where;\n\n }\n\n\n /* PRIVATE METHODS */\n function addAxes() {\n let axes;\n\n axes = {};\n\n axes.x = addXAxis();\n axes.y = addYAxis();\n\n return axes;\n }\n\n function addCurtain() {\n let clipPath,\n rect;\n\n clipPath = where\n .select(\"defs\")\n .append(\"clipPath\")\n .attr(\"id\",\"plotterClipPath\");\n\n rect = clipPath\n .append(\"rect\")\n .attr(\"x\",-1)\n .attr(\"y\",-1)\n .attr(\"width\",width - plotter.margins.left - plotter.margins.right + 1)\n .attr(\"height\",plotter.height - plotter.margins.top - plotter.margins.bottom + 1);\n\n return clipPath;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\"where\":options.where})\n .attr(\"transform\",\"translate(\"+plotter.coordinates.x+\",\"+plotter.coordinates.y+\")\");\n\n return group;\n }\n\n function addGrid() {\n let grid;\n\n if(gridBoolean) {\n grid = new FunctionPlotterGrid({\n \"axisTickCounts\":axisTickCounts,\n \"domain\":plotter.domain,\n \"range\":range,\n \"scales\":plotter.scales,\n \"where\":plotter.layers.grid,\n \"tickEvery\":1\n });\n }\n\n return grid;\n }\n\n function addHotspot() {\n let hotspot;\n\n hotspot = group\n .append(\"rect\")\n .attr(\"x\",plotter.margins.left)\n .attr(\"y\",plotter.margins.top)\n .attr(\"width\",plotter.width - plotter.margins.left - plotter.margins.right)\n .attr(\"height\",plotter.height - plotter.margins.top - plotter.margins.bottom)\n .attr(\"fill\",\"rgba(0,0,0,0)\");\n\n return hotspot;\n }\n\n function addPlotArea() {\n let plotGroup;\n\n plotGroup = explorableGroup({\n \"where\":group\n })\n .attr(\"transform\",\"translate(\"+plotter.margins.left+\",\"+plotter.margins.top+\")\");\n\n return plotGroup;\n }\n\n function addLayers() {\n let layers;\n\n layers = {};\n layers.plot = explorableGroup({\"where\":group})\n .attr(\"transform\",\"translate(\"+plotter.margins.left+\",\"+plotter.margins.top+\")\");\n\n layers.grid = explorableGroup({\"where\":layers.plot})\n .attr(\"clip-path\",\"url(#plotterClipPath)\");\n\n layers.axes = explorableGroup({\"where\":layers.plot});\n layers.lines = explorableGroup({\"where\":layers.plot});\n\n\n layers.indicators = explorableGroup({\"where\":group});\n layers.tooltip = explorableGroup({\"where\":group});\n\n return layers;\n }\n\n\n function addLines(functions) {\n let lines;\n\n if(functions.length == 0) {\n lines = [];\n\n return lines;\n }\n\n functions.forEach((aFunction) => {\n let line = new FunctionPlotterLine({\n \"function\":aFunction,\n \"where\":plotter.layers.lines,\n \"domain\":plotter.domain,\n \"scales\":plotter.scales,\n });\n\n lines.push(line);\n });\n\n return lines;\n }\n\n function addXAxis() {\n let axis;\n\n axis = new FunctionPlotterAxis({\n \"axisType\":\"bottom\",\n \"scales\":plotter.scales,\n \"tickCount\":axisTickCounts.x,\n \"where\":plotter.layers.axes\n });\n\n return axis;\n }\n\n function addYAxis() {\n let axis;\n\n axis = new FunctionPlotterAxis({\n \"axisType\":\"left\",\n \"scales\":plotter.scales,\n \"tickCount\":axisTickCounts.y,\n \"where\":plotter.layers.axes\n });\n\n return axis;\n }\n\n function defaultMargins() {\n return {\n \"left\":100,\n \"right\":10,\n \"top\":30,\n \"bottom\":50\n };\n }\n\n function defineScale(inputDomain,outputRange) {\n let scale;\n\n scale = d3.scaleLinear()\n .domain(inputDomain)\n .range(outputRange);\n\n return scale;\n }\n\n function defineScales() {\n let scales;\n\n scales = {};\n scales.x = defineScale(plotter.domain,[0,plotter.width - plotter.margins.right - plotter.margins.left]);\n scales.y = defineScale(plotter.range,[plotter.height - plotter.margins.bottom - plotter.margins.top,0]);\n\n return scales;\n }\n\n\n}", "function initCola() {\n\t\t\t\t// set up the axes\n\t\t\t\tvar x = d3.scale.linear().domain([0, 350]).range([0, 10]),\n\t\t\t\t y = d3.scale.linear().domain([0, 350]).range([0, 10]),\n\t\t\t\t z = d3.scale.linear().domain([0, 350]).range([0, 10]);\n\n\t\t\t\t//.on(\"tick\", function(e) {\n\t\t\t\tfor (var key in nodes) {\n\t\t\t\t\tspheres[key].position.set(x(nodes[key].x) * 40 - 40, y(nodes[key].y) * 40 - 40, z(nodes[key].z) * 40 - 40);\n\t\t\t\t\tlabels[key].position.set(x(nodes[key].x) * 40 - 40, y(nodes[key].y) * 40 - 40, z(nodes[key].z) * 40 - 40);\n\n\t\t\t\t\tfor (var j = 0; j < three_links.length; j++) {\n\t\t\t\t\t\tvar arrow = three_links[j];\n\t\t\t\t\t\tvar vi = null;\n\t\t\t\t\t\tif (arrow.userData.source === key) {\n\t\t\t\t\t\t\tvi = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (arrow.userData.target === key) {\n\t\t\t\t\t\t\tvi = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (vi >= 0) {\n\t\t\t\t\t\t\tif (vi == 0) {\n\t\t\t\t\t\t\t\tvar vectOrigin = new THREE.Vector3(spheres[key].position.x, spheres[key].position.y, spheres[key].position.z);\n\t\t\t\t\t\t\t\tsetArrowOrigin(arrow, vectOrigin);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (vi == 1) {\n\t\t\t\t\t\t\t\tvar vectTarget = new THREE.Vector3(spheres[key].position.x, spheres[key].position.y, spheres[key].position.z);\n\t\t\t\t\t\t\t\tsetArrowTarget(arrow, vectTarget);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\trenderer.render(scene, camera);\n\t\t\t}", "function DrawCtrChart()\n{\n // create/delete rows \n if (ctrTable.getNumberOfRows() < contDataPoints.length)\n { \n var numRows = contDataPoints.length - ctrTable.getNumberOfRows();\n ctrTable.addRows(numRows);\n } else {\n for(var i=(ctrTable.getNumberOfRows()-1); i > contDataPoints.length; i--)\n {\n ctrTable.removeRow(i); \n }\n }\n\n // Populate data table with time/cost data points. \n for(var i=0; i < ctrTable.getNumberOfRows(); i++)\n {\n ctrTable.setCell(i, 0, new Date(parseInt(contDataPoints[i].timestamp)));\n ctrTable.setCell(i, 1, (parseInt(contDataPoints[i].clicks)/parseInt(contDataPoints[i].impressions))*100);\n }\n\n // Draw line chart.\n chartOptions.title = 'Ctr Chart';\n ctrChart.draw(ctrView, chartOptions); \n}", "function draw(){\n\n drawGrid();\n var seriesIndex;\n\n if(!graph.hasData) {\n return;\n }\n\n if(graph.options.axes.x1.show){\n if(!graph.options.axes.x1.labels || graph.options.axes.x1.labels.length === 0) {\n seriesIndex = graph.options.axes.x1.seriesIndex;\n graph.options.axes.x1.labels= getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);\n }\n drawXLabels(graph.options.axes.x1);\n }\n if(graph.options.axes.x2.show && graph.hasData){\n if (!graph.options.axes.x2.labels || graph.options.axes.x2.labels.length === 0) {\n seriesIndex = graph.options.axes.x2.seriesIndex;\n graph.options.axes.x2.labels = getXLabels(graph.allSeries[seriesIndex].series[0], graph.options.labelDateFormat);\n }\n drawXLabels(graph.options.axes.x2);\n }\n\n if (graph.options.axes.y1.show) {\n drawYLabels(graph.maxVals[graph.options.axes.y1.seriesIndex], graph.minVals[graph.options.axes.y1.seriesIndex], graph.options.axes.y1);\n }\n if (graph.options.axes.y2.show) {\n drawYLabels(graph.maxVals[graph.options.axes.y2.seriesIndex], graph.minVals[graph.options.axes.y2.seriesIndex], graph.options.axes.y2);\n }\n }", "function zoom_arc_plot(v_chr, v_start, v_end) {\n // chosen chromosome for zoom\n var xScale_zoomed_chrom,\n // all other chromosomes\n xScale_unzoomed_chrom;\n\n // margin for the zoom function of the arc plot\n var margin = {\n top: 1,\n right: 1,\n bottom: 20,\n left: 10\n };\n\n // padding between the chromosomes\n var padding = 2;\n // width and height of the plot\n var w = 800 - margin.left - margin.right - (24 * padding);\n var h = 600 - margin.top - margin.bottom; \n // chromosome length without the chosen chromosome\n var chrom_scale_compare = chrom_length - chromLength[(v_chr -1)];\n\n //for loop to create the length of the chromosomes\n var chromLength_scaled = [];\n for (var i = 0;i < chromLength.length; i++) {\n var temp;\n if ((v_chr - 1) == i) {\n chromLength_scaled.push(w/2);\n } else {\n temp = ((w/2) / chrom_scale_compare) * chromLength[i];\n chromLength_scaled.push(temp);\n }\n }\n\n //for loop to calculate the x position\n var chrom_x_position = [0];\n var Scaled_abs_xposition = 0;\n for (var i = 0; i < chrom_abs_length.length ; i++) {\n Scaled_abs_xposition = Scaled_abs_xposition + chromLength_scaled[i] + padding;\n chrom_x_position.push(Scaled_abs_xposition);\n }\n\n // var for the chromsome length of the chosen area\n var selected_chrom_area = v_end - v_start;\n // array for the ticks\n var ticks_chrom_chosen = [];\n // for loop to create the ticks for the chosen chromosome\n for (var i = 0; i< 20 ; i++) {\n var temp_x,\n temp_label,\n temp_range,\n temp_range_label,\n temp;\n if(selected_chrom_area == 0) {\n temp_x = chrom_x_position[(v_chr - 1)] + (chromLength_scaled[(v_chr - 1)] / 20) * i;\n temp_label = Math.round(((chromLength[(v_chr - 1)] / 20) / 1000000) * i) + \"MB\";\n } else {\n temp_x = chrom_x_position[(v_chr - 1)] + (chromLength_scaled[(v_chr - 1)] / 20) * i;\n temp = Math.round(v_start + (selected_chrom_area / 20)* i);\n if(temp < 50000) {\n temp_range = 1;\n temp_range_label = \"\";\n } else if(temp < 50000000) {\n temp_range = 1000;\n temp_range_label = \"Kb\";\n } else {\n temp_range = 1000000;\n temp_range_label = \"Mb\";\n }\n temp_label = Math.round((temp / temp_range)) + temp_range_label; \n }\n var obj = {};\n obj[\"x\"] = temp_x;\n obj[\"label\"] = temp_label;\n ticks_chrom_chosen.push(obj);\n }\n\n // array to store all nodes and all links which should not be displayed in the zoom function\n zoom_allNodes = [];\n zoom_links = [];\n links.forEach( function(d) {\n if((allNodes[d.source].chrom == v_chr \n && allNodes[d.source].bp_position >= v_start \n && allNodes[d.source].bp_position <= v_end) ||\n (allNodes[d.source].chrom == v_chr && selected_chrom_area == 0) ||\n (allNodes[d.target].chrom == v_chr && \n allNodes[d.target].bp_position >= v_start && \n allNodes[d.target].bp_position <= v_end) ||\n (allNodes[d.target].chrom == v_chr && selected_chrom_area == 0)) {\n\n zoom_allNodes.push(allNodes[d.source]);\n zoom_allNodes.push(allNodes[d.target]);\n zoom_links.push(d);\n }\n });\n \n // add nodes with degree zero\n allNodes.forEach( function (d) {\n var in_zoomed_chrom = (d.chrom == v_chr && d.degree == 0);\n var in_zoomed_region = (d.bp_position >= v_start && d.bp_position <= v_end);\n\n if(in_zoomed_chrom && in_zoomed_region) {\n zoom_allNodes.push(d);\n }\n });\n \n // sort and make the zoom_allnodes function unique\n var temp_zoomnodes = [];\n\n zoom_allNodes.forEach( function (d) {\n temp_zoomnodes.push(d.id);\n });\n\n temp_zoomnodes = sort_unique(temp_zoomnodes);\n\n zoom_allNodes = [];\n\n temp_zoomnodes.forEach( function (d) {\n zoom_allNodes.push(allNodes[d]);\n });\n \n \n // create SVG for the plot\n var svg = d3.select(\"#chart\")\n .append(\"svg\")\n .attr(\"id\", \"mainplot\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n d3.select('#ld_container').selectAll('svg').remove();\n\n var chromosome_container = svg.selectAll(\"g.group\")\n .data(chromLength)\n .enter().append(\"svg:g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(\" + chrom_x_position[i] + \",\" + height_chrom_bar + \")\"; \n })\n // scales the width of chromosomes\n .attr(\"width\", function(d, i) {\n create_ld_plot(i+1, chromLength_scaled[i], chrom_x_position[i], padding, v_chr, v_start, v_end); \n return chromLength_scaled[i]; \n })\n .attr(\"height\", 40)\n .attr(\"class\", function (d,i) {\n return \"chrom\" + (i+1);\n });\n\n var id_chrom_zoom = \"g.chrom\" + (v_chr);\n // store the the new startpoint\n var startzoom = 0;\n if (v_start == 0 && v_end == 0) {\n var x_scale_zoom = d3.scale.linear()\n .domain([0, chromLength[(v_chr -1)]])\n .range([0, chromLength_scaled[(v_chr -1)]]);\n } else {\n var x_scale_zoom = d3.scale.linear()\n .domain([v_start, v_end])\n .range([0, chromLength_scaled[(v_chr -1)]]);\n }\n \n //function to zoom with the mouse\n var brush = svg.select(id_chrom_zoom)\n .append(\"g\")\n .attr(\"class\", \"brush\")\n .call(d3.svg.brush().x(x_scale_zoom)\n .on(\"brushstart\", brushstart)\n .on(\"brush\", brushmove)\n .on(\"brushend\", brushend))\n .selectAll(\"rect\")\n .attr(\"height\", 40) \n .style(\"stroke\", \"blue\")\n .style(\"fill\", \"blue\")\n .style(\"opacity\" , 0.7);\n\n function brushstart() { \n brush.classed(\"selecting\", true);\n }\n\n function brushmove() {\n var r = d3.event.target.extent(); \n document.getElementById(\"texzs\").value = Math.round(r[0]);\n document.getElementById(\"texze\").value = Math.round(r[1]);\n }\n\n function brushend() { \n brush.classed(\"selecting\", !d3.event.target.empty());\n }\n\n // create rectangle in the g container\n var chrom_bar = chromosome_container.append(\"rect\")\n .attr(\"transform\", \"translate(\" + 0 + \",\" + 0 + \")\")\n .attr(\"class\", \"rect\")\n // scales the width of chromosomes\n .attr(\"width\", function(d, i) {\n return chromLength_scaled[i]; \n })\n .attr(\"height\", 20)\n .style(\"fill\", function(d, i) {\n return chromcolour[i];\n })\n .style(\"stroke\", function(d, i) {\n return chromcolour[i];\n });\n\n //create ticks for the chrom_bar\n svg.selectAll(\"line\")\n .data(ticks_chrom_chosen)\n .enter().append(\"line\")\n .attr(\"class\", \"tickchromosome\")\n .attr(\"x1\", function(d) {\n return + d.x;\n })\n .attr(\"y1\", height_nodes + 25)\n .attr(\"x2\", function (d) {\n return + d.x;\n })\n .attr(\"y2\", height_nodes + 30)\n .style(\"stroke\", \"#000\")\n\n svg.selectAll(\"text\")\n .data(ticks_chrom_chosen)\n .enter().append(\"text\")\n .attr(\"class\", \"label\")\n .attr(\"dy\", \".35em\")\n .attr(\"transform\", function (d) {\n return \"translate(\"+ d.x + \",\" + (height_nodes + 38) + \")\" + \"rotate(90)\"; \n })\n .attr(\"font-size\", \"10\")\n .text(function (d) {\n return d.label; \n });\n\n // create the label for the chromosomes\n chromosome_container.append(\"svg:text\")\n .attr(\"class\", \"chromosom_number\")\n // 2* padding for double digits chromosome numbers\n .attr(\"transform\", function (d, i) {\n if (i == (v_chr-1)) {\n return \"translate(\" + (8 * padding) + \",\" + 15 + \")\";\n } else {\n return \"translate(\" + (4 * padding) + \",\" + 35 + \")\"; \n }\n })\n .append(\"svg:textPath\")\n .text(function(d, i) {\n return i + 1;\n })\n .attr(\"font-size\", function (d, i) {\n if (i == (v_chr-1)) {\n return \"14px\";\n } else {\n return \"9px\";\n }\n })\n .attr(\"text-anchor\", \"end\")\n .style(\"fill\", function(d, i) {\n if (i == (v_chr - 1)) {\n return \"#000\";\n } else {\n return chromcolour[i];\n }\n })\n .style(\"stroke\", function(d, i) {\n if (i == (v_chr - 1)) {\n return \"#000\";\n } else {\n return chromcolour[i];\n }\n });\n\n // object to store the position of the zoomed chromosomes\n var id_chosen = [];\n // create circles for the location of the interacting SNPs \n svg.selectAll(\"circle.vertex\")\n .data(zoom_allNodes)\n .enter().append(\"circle\")\n .attr(\"class\", \"circle_zoom\")\n .style(\"fill\", function(d) {\n return graphColor(d.probe_group);\n })\n .style(\"stroke\", function(d) {\n return graphColor(d.probe_group);\n })\n // positioning the SNPs\n .attr(\"cx\", function(d) {\n if(d.chrom == v_chr && selected_chrom_area == 0) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1 )] + \n ((w/2) / chromLength[(d.chrom - 1)]) * d.bp_position; \n return id_chosen[d.id];\n\n } else if (d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position >= v_start && \n d.bp_position <= v_end) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1)] + \n ((w/2) / selected_chrom_area) * (d.bp_position - v_start);\n return id_chosen[d.id];\n\n } else if(d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position < v_start ) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1)];\n return id_chosen[d.id];\n\n } else if (d.chrom == v_chr && selected_chrom_area > 0 && d.bp_position > v_end) {\n id_chosen[d.id] = chrom_x_position[(d.chrom - 1)] + (w/2);\n return id_chosen[d.id];\n\n } else if(d.chrom != v_chr) {\n id_chosen[d.id] = chrom_x_position[(d.chrom -1 )] +\n ((w/2) / chrom_scale_compare) * d.bp_position; \n return id_chosen[d.id];\n\n } else {\n return id_chosen[d.id] = \"NaN\" ;\n }\n })\n .attr(\"cy\", height_nodes)\n .attr(\"r\", function(d) {\n if(id_chosen[d.id] == \"NaN\" && d.chrom == v_chr ) {\n return 0;\n } else {\n return 2;\n }\n })\n // to get information about the SNPs from different sources, if you click on a circle\n .on(\"click\", function (d,i) { externalLink(d, i); });\n\n // show degree as tooltip - title\n svg.selectAll(\"g .circle_zoom\") \n .append(\"title\")\n .text(function(d) {\n return \"degree: \" + two_dec(d.degree) + \"\\nSNP: \" + d.rs + \"\\nid: \" + d.id + \n \"\\nposition: \" + d.bp_position\n });\n\n // draw the edges between linked SNP's nodes\n var arcs = svg.selectAll(\"path.link\")\n .data(zoom_links)\n .enter().append(\"path\")\n .attr(\"class\", \"link\")\n .style(\"stroke\", function(d) {\n return graphColor(d.probe_group);\n })\n .style(\"stroke\", 1)\n .style(\"stroke-width\", 2.5)\n .style(\"opacity\", 3.7)\n .style(\"fill\", \"none\")\n // function to create the arc for the links\n .attr(\"d\", function (d) {\n // to ensure that the path is drawn correct \n if(d.source > d.target) {\n var temp;\n temp = d.source;\n d.source = d.target;\n d.target = temp;\n } \n\n if (allNodes[d.source].chrom == v_chr || allNodes[d.target].chrom == v_chr) {\n var start_position_x = id_chosen[d.source],\n start_position_y = height_nodes ;\n\n var end_position_x = id_chosen[d.target],\n end_position_y = height_nodes ;\n } else {\n var start_position_x = \"NaN\",\n start_position_y = height_nodes ;\n\n var end_position_x = \"NaN\",\n end_position_y = height_nodes ;\n }\n\n // to ensure that the arc links are drawn on the correct side \n if (end_position_x < start_position_x) {\n var temp; \n temp = end_position_x; \n end_position_x = start_position_x;\n start_position_x = temp; \n }\n\n var radius = (end_position_x - start_position_x) / 2 ;\n\n var c1x = start_position_x,\n c1y = start_position_y - radius,\n c2x = end_position_x,\n c2y = end_position_y - radius ;\n\n return \"M\" + start_position_x + \",\" + start_position_y + \" C\" + c1x +\n \",\" + c1y + \",\" + c2x + \",\" + c2y + \" \" + \n end_position_x + \",\" + end_position_y ; \n })\n .on(\"click\" , function(d,i) { return highlight_snp_pairs(d, i);});\n\n // creates the colour scale indicator for the ld plot\n createColourScale_ldplot();\n}", "constructor(x, y) {\n\t\tthis.chadX = 1000;\n\t\tthis.chadY = 10;\n\t\tthis.chadW = 10;\n\t\tthis.chadDy = 5;\n this.color = \"Red\";\n }", "function drawXY(){\r\n//setting the x and y domains\r\n x.domain([d3.min(cars, function(d) { return d.year; }), d3.max(cars, function(d) { return d.year; })]);\r\n y.domain([d3.min(cars, function(d) { return d.power; }), d3.max(cars, function(d) { return d.power; })]);\r\n\r\n//setting the yPosition \r\n var yPos = height -20;\r\n//creating the x-Axis\r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"xaxis\")\r\n\t .attr(\"transform\", \"translate(0,\" + yPos + \")\")\r\n\t .call(xAxis);\r\n//creating the Y-axis\r\n chart.append(\"g\")\r\n\t .attr(\"class\", \"yaxis\")\r\n\t .attr(\"transform\", \"translate(480,0)\")\r\n\t .call(yAxis);\r\n\r\n \r\n//selecting ths dot \r\n//adding attributes\t\r\n chart.selectAll(\".dot\")\r\n\t .data(cars)\r\n\t .enter().append(\"circle\")\r\n\t .attr(\"class\", \"dot\")\r\n\t .attr(\"cx\", function(d) { return x(d.year); })\r\n\t .attr(\"cy\", function(d) { return y(d.power); })\r\n\t .attr(\"r\", 3)\r\n\t \r\n//the mouseover function that fills the dots red when the mouse is over them\r\n\t .on(\"mouseover\", function(){\r\n\t\t\td3.select(this)\r\n\t\t\t.attr(\"fill\", \"red\")\r\n\t })\r\n//the mouseout function that changes the dots back to normal color\r\n\t.on(\"mouseout\", function(){\r\n\t\td3.select(this)\r\n\t\t.attr(\"fill\", \"black\")\r\n\t\t\r\n})\r\n\t\r\n \r\n}", "function plotTrajectory(trajectoryData, color) {\n console.log(trajectoryData);\n \n \n \n \n \n}", "circ(x0, y0, r, c) {\n // evaluate runtime errors\n this.colorRangeError(c);\n // draw filled circle\n let x = 0;\n let y = r;\n let p = 3 - 2 * r;\n this.circPixGroup(x0, y0, x, y, c);\n while (x < y) {\n x++;\n if (p < 0) {\n p = p + 4 * x + 6;\n }\n else {\n y--;\n p = p + 4 * (x - y) + 10;\n }\n this.circPixGroup(x0, y0, x, y, c);\n }\n }", "function drawCanyon(t_canyon)\n{\n noStroke();\n\tfill(100, 155, 255);\n\trect(t_canyon.x_pos, t_canyon.y_pos, t_canyon.width, 200);\n}", "function render_scatterOnrust() {\n var plotS = hgiScatter().mapping(['uw_eigen_factor', 'onrust']).addLOESS(true).xLabel('Uw eigen factor').yLabel('Onrust').xTicks(5).yTicks(5);\n d3.select('#scatterOnrust').datum(data).call(plotS);\n}", "function sheetContour(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: \"contour\"\r\n }\r\n ];\r\n var layout = {\r\n title: \"Contour\"\r\n };\r\n // Display plot\r\n Plotly.newPlot(\"contourPlot\", data, layout);\r\n}", "addAxes () {\n }", "function plotAll() {\n d3.select(\"#scatter-macro-1 svg\").remove()\n d3.select(\"#scatter-macro-2 svg\").remove()\n d3.select(\"#scatter-micro-1 svg\").remove()\n d3.select(\"#scatter-micro-2 svg\").remove()\n doPlot(\"scatter-macro-1\", voltageArr, \"Voltage\", maxLinearVelocityArr, \"Max. Linear Velocity\");\n doPlot(\"scatter-macro-2\", currentArr, \"Current\", accelerationArr, \"Acceleration\");\n doPlot(\"scatter-micro-1\", voltageArr, \"Voltage\", maxAngularVelocityArr, \"Max. Angular Velocity\");\n doPlot(\"scatter-micro-2\", currentArr, \"Current\", torqueArr, \"Torque\");\n}", "function DrawCircle(xc, yc, r){\n /**@todo */\n let x = 0;\n let y = r;\n let d = 3 - 2 * r;\n DrawEightPoints(xc,x,yc,y);\n while(y >= x) //While we're only looking at degrees from 45-90\n {\n x++;\n if(d > 0){\n y--;\n d += 4 * (x-y) + 10;\n }\n else{\n d += 4 * x + 6;\n }\n DrawEightPoints(xc,x,yc,y);\n }\n}", "function CalculMélangeRGB() {\n \n //valeurs des curseurs\n valCurseurR = document.querySelector(\"#curseurRouge\").getElementsByTagName('input')[0].value;\n valCurseurG = document.querySelector(\"#curseurVert\").getElementsByTagName('input')[0].value;\n valCurseurB = document.querySelector(\"#curseurBleu\").getElementsByTagName('input')[0].value;\n //valeurs des curseurs en %\n pCurseurR = valCurseurR / 100;\n pCurseurB = valCurseurB / 100;\n pCurseurG = valCurseurG / 100;\n\n //recuperer les valeurs X Y Z\n XBleu = data.XYZ.B.X;\n YBleu = data.XYZ.B.Y;\n ZBleu = data.XYZ.B.Z;\n //XYZ du Vert\n XVert = data.XYZ.G.X;\n YVert = data.XYZ.G.Y;\n ZVert = data.XYZ.G.Z;\n //XYZ du rouge\n XRouge = data.XYZ.R.X;\n YRouge = data.XYZ.R.Y;\n ZRouge = data.XYZ.R.Z;\n\n //calcul du X,Y,Z pour le mélange\n\n Xmelange = (XBleu * pCurseurB) + (XVert * pCurseurG) + (XRouge * pCurseurR);\n Ymelange = (YBleu * pCurseurB) + (YVert * pCurseurG) + (YRouge * pCurseurR);\n Zmelange = (ZBleu * pCurseurB) + (ZVert * pCurseurG) + (ZRouge * pCurseurR);\n\n //calcul du melange du x et y\n xMelange = Xmelange / (Xmelange + Ymelange + Zmelange);\n yMelange = Ymelange / (Xmelange + Ymelange + Zmelange);\n\n const cieChart = document.querySelector('cie-xy-chart'); // Tu récupère le premier diagramme de ton DOM (par exemple.)\n cieChart.inputs.xy.x.value = xMelange; // Tu définis la valeur du champ x.\n cieChart.inputs.xy.x.dispatchEvent(new InputEvent('input')); // Tu déclenches l'événement \"input\" correspondant à x.\n cieChart.inputs.xy.y.value = yMelange; // Tu définis la valeur du champ y.\n cieChart.inputs.xy.y.dispatchEvent(new InputEvent('input')); // Tu déclenches l'événement \"input\" correspondant à y.\n // Déclencher les événements input devrait rafraîchir le diagramme.\n \n}", "function plot() {\n\n // Skip some frames to avoid unnecessary workload\n counterGraph++\n if (counterGraph % skipRateGraph != 0) return\n\n // fill data arrays\n timeArray.push(time);\n susceptibleArray.push(nSusceptible);\n infectedArray.push(nInfected);\n immuneArray.push(nImmune);\n deathsArray.push(nDeaths);\n\n // Clear graph canvas\n ctxGraph.clearRect(0, 0, canvasGraph.width, canvasGraph.height);\n\n // draw the axes\n drawAxes()\n\n // draw the susceptible\n ctxGraph.beginPath();\n ctxGraph.strokeStyle = \"purple\";\n ctxGraph.lineWidth = 3;\n drawGraph(timeArray, susceptibleArray)\n ctxGraph.stroke();\n\n // draw the infected\n ctxGraph.beginPath();\n ctxGraph.strokeStyle = \"red\";\n ctxGraph.lineWidth = 3;\n drawGraph(timeArray, infectedArray)\n ctxGraph.stroke();\n\n // draw the immune\n ctxGraph.beginPath();\n ctxGraph.strokeStyle = \"green\";\n ctxGraph.lineWidth = 3;\n drawGraph(timeArray, immuneArray)\n ctxGraph.stroke();\n\n // draw the deaths\n ctxGraph.beginPath();\n ctxGraph.strokeStyle = \"black\";\n ctxGraph.lineWidth = 3;\n drawGraph(timeArray, deathsArray)\n ctxGraph.stroke();\n}", "drawCones(){\r\n // might be place where we add the x and y coords to the canvas to draw the cones\r\n for (let i = 0; i < this.numCones; i++)\r\n {\r\n cones[i].x = ((this.coneLoc[i].x));\r\n cones[i].y = (this.coneLoc[i].y);\r\n }\r\n }", "function CubicPoly(){}", "function bobaTick(nodes, strokeWidth, cupRadius, hyp2, w) {\n // console.log('tick');\n\n nodes.attr('cx', function (d) {\n return d.x = magicInternetFunction(d.rad, d.x, d.y, strokeWidth, cupRadius, hyp2, w);\n })\n .attr('cy', function (d) {\n return d.y = magicInternetFunction(d.rad, d.y, d.x, strokeWidth, cupRadius, hyp2, w);\n });\n }", "function draw() {\n ellipseMode(CENTER);\n drawTrack(h1Pat, whatY(1));\n drawTrack(h2Pat, whatY(2));\n drawTrack(snPat, whatY(3));\n drawTrack(shPat, whatY(4));\n drawTrack(k1Pat, whatY(5));\n drawTrack(k2Pat, whatY(6));\n getTrackCenters();\n}", "function drawCases(){\n clear();\n \n div.hide();\n let data = boundary[0].the_geom.coordinates[0];\n stroke(255);\n fill(100,100,100, 50);\n\tbeginShape();\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tlet lon = boundary[0].the_geom.coordinates[0][i][0];\n let lat = boundary[0].the_geom.coordinates[0][i][1];\n \n const p = myMap.latLngToPixel(lat, lon);\n\n\t\t\tlet x = map(lon, city_limit.xMin, city_limit.xMax, 0+padding, width-padding);\n\t\t\tlet y = map(lat,city_limit.yMin, city_limit.yMax, height-padding, 0+padding);\n\n\t\t\tvertex(p.x,p.y);\n\t\t}\n\tendShape(CLOSE);\n\n\n fill(109, 255, 0);\n stroke(100);\n for(var i = 0; i < Object.keys(covidData).length; i++)\n {\n\n const latitude = covidData[i][\"attributes\"][\"Y\"];\n const longitude = covidData[i][\"attributes\"][\"X\"];\n \n\n //if (myMap.map.getBounds().contains([latitude, longitude])) {\n // Transform lat/lng to pixel position\n const pos = myMap.latLngToPixel(latitude, longitude);\n \n //map(value, start1, stop1, start2, stop2)\n let size = covidData[i][\"attributes\"][\"Point_Count\"];\n size = map(size, 0, covidData[0][\"attributes\"][\"Point_Count\"], 1, 25) + myMap.zoom();\n ellipse(pos.x, pos.y, size, size); \n\n \n }\n\n }", "function colorwheel(a,theta,x){return a*(1+cos(theta+x))}", "function drawCylinder() {\t\r\n\t\t//TODO: update VBO positions based on 'factor' for cone-like effect\r\n\t\tmeshes.cylinder.drawMode = gl.LINE_LOOP;\r\n\t\t\r\n\t\t// Render\r\n\t\tmeshes.cylinder.setAttribLocs(attribs);\r\n\t\tmeshes.cylinder.render();\t\t\t\t\r\n\t}" ]
[ "0.5888707", "0.5736098", "0.56165415", "0.5589112", "0.55744106", "0.55394167", "0.5459294", "0.5414624", "0.5414624", "0.5370074", "0.53614116", "0.5356966", "0.53366965", "0.5328876", "0.5309544", "0.53041136", "0.5301971", "0.5296474", "0.5284543", "0.5255541", "0.5231733", "0.5223299", "0.52098805", "0.5204737", "0.5194695", "0.518084", "0.5169951", "0.5156523", "0.51543087", "0.5148458", "0.51468754", "0.5134001", "0.51329017", "0.5121668", "0.51201004", "0.5108403", "0.5108007", "0.51036286", "0.509853", "0.5095718", "0.508755", "0.5086827", "0.50782615", "0.50681853", "0.50588816", "0.5051154", "0.5048031", "0.5015852", "0.50120556", "0.5008874", "0.50085956", "0.50011784", "0.49959576", "0.49959576", "0.49950635", "0.49920264", "0.49878576", "0.49794656", "0.4969593", "0.49691632", "0.49660802", "0.49631706", "0.4948637", "0.49449918", "0.49449918", "0.49409166", "0.49398968", "0.49374905", "0.4933055", "0.49307865", "0.49307865", "0.49307865", "0.49307865", "0.49307865", "0.4924931", "0.49236783", "0.4923673", "0.4923485", "0.49216768", "0.49207845", "0.49185085", "0.49154055", "0.49130273", "0.49126133", "0.4909292", "0.49044555", "0.48974872", "0.489712", "0.4894673", "0.48875624", "0.4886608", "0.488419", "0.48815238", "0.48779947", "0.48776543", "0.48682335", "0.4861912", "0.48605984", "0.4853527", "0.48507434" ]
0.5288344
18
Function plots Spherical coordiate system
function plotSpherical(r, theta, phi, target){ let hoverlabel = ["R: "+r[0]+", Θ: "+theta[0]+", Φ: "+phi[0],"R: "+r[1]+", Θ: "+theta[1]+", Φ: "+phi[1]]; var data = [{ type: 'scatter3d', mode: 'lines', x: r, y: theta, z: phi, hoverinfo: 'text', hovertext: hoverlabel, opacity: 1, line: { width: 6, color: "rgb(0,0,0)", reversescale: false } }] var layout = { scene: { xaxis:{title: 'R'}, yaxis:{title: 'THETA'}, zaxis:{title: 'PHI'}, }, showticklabels: false } Plotly.plot(target, data, layout); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function drawSphere(gl) {\n\tdrawCircle(gl);\n\tdrawMarks(gl);\n}", "function drawSphere() {\n setMV();\n Sphere.draw();\n}", "function drawSphere() {\n setMV();\n Sphere.draw();\n}", "function spherical(cartesian) {\n return [Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"g\" /* atan2 */])(cartesian[1], cartesian[0]) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */], Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"e\" /* asin */])(Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"q\" /* max */])(-1, Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"r\" /* min */])(1, cartesian[2]))) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */]];\n}", "function spherical(cartesian) {\n return [\n Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"g\" /* atan2 */])(cartesian[1], cartesian[0]) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */],\n Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"e\" /* asin */])(Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"q\" /* max */])(-1, Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"r\" /* min */])(1, cartesian[2]))) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */]\n ];\n}", "function Sphere1 (long, lat) {\n\n\tthis.name = \"sphere1\";\n\n\t// vertices definition\n\t////////////////////////////////////////////////////////////\n\n\tthis.vertices = new Float32Array(3*((long-1)*(lat)+2));\n\n\tvar radius = 1.0;\n\tvar p;\n var t;\n var p_step = Math.PI / long;\n\tvar t_step = 6.283185307179586476925286766559 / lat;\n\n\tvar vertexoffset = 0;\n // bottom vertex\n this.vertices[vertexoffset] = 0.0;\n this.vertices[vertexoffset+1] = -1.0;\n this.vertices[vertexoffset+2] = 0.0;\n vertexoffset += 3;\n\n // middle sphere\n\tfor (var i = 1; i < long; i++) {\n p = p_step*i - Math.PI/2; //start from -pi/2 and go to pi/2 for longitude\n //console.log(p);\n for(var j = 0; j < lat; j++){\n t = t_step*j;\n //console.log(t);\n this.vertices[vertexoffset] = Math.cos(p) * Math.sin(t);\n //console.log(this.vertices[vertexoffset]);\n \t\tthis.vertices[vertexoffset+1] = Math.sin(p);\n //console.log(this.vertices[vertexoffset+1]);\n \t\tthis.vertices[vertexoffset+2] = Math.cos(p) * Math.cos(t);\n //console.log(this.vertices[vertexoffset+2]);\n \t\tvertexoffset += 3;\n }\n\t}\n\n // top vertex\n this.vertices[vertexoffset] = 0.0;\n this.vertices[vertexoffset+1] = 1.0;\n this.vertices[vertexoffset+2] = 0.0;\n vertexoffset += 3;\n\n var totalvertices = vertexoffset/3;\n\n\t// triangles definition\n\t////////////////////////////////////////////////////////////\n\n\tthis.triangleIndices = new Uint16Array(6*long*lat);\n\n\tvar triangleoffset = 0;\n // bottom of sphere\n\tfor (var i = 0; i < lat; i++)\n\t{\n\t\tthis.triangleIndices[triangleoffset] = 0; //bottom vertex\n\t\tthis.triangleIndices[triangleoffset+1] = i+1;//%totalvertices;\n\t\tthis.triangleIndices[triangleoffset+2] = (i+1)%lat + 1;//%totalvertices;\n\t\ttriangleoffset += 3;\n\t}\n\n //middle of sphere\n\tfor (var i = 0; i <= lat*(long-1); i++)\n\t{\n if(i <= (lat)*(long-2)){\n\t\t this.triangleIndices[triangleoffset] = i;\n\t\t this.triangleIndices[triangleoffset+1] = i+1;\n\t\t this.triangleIndices[triangleoffset+2] = i+lat;\n\t\t triangleoffset += 3;\n }\n\n if(i >= lat){\n\t\t this.triangleIndices[triangleoffset] = i;\n\t\t this.triangleIndices[triangleoffset+1] = i+1;\n\t\t this.triangleIndices[triangleoffset+2] = i+1-lat;\n\t\t triangleoffset += 3;\n }\n\t}\n\n for (var i = 0; i < lat; i++)\n\t{\n\t\tthis.triangleIndices[triangleoffset] = totalvertices-1; //bottom vertex\n\t\tthis.triangleIndices[triangleoffset+1] = i+(lat)*(long-2);//%totalvertices;\n\t\tthis.triangleIndices[triangleoffset+2] = i+1+(lat)*(long-2);//%totalvertices;\n\t\ttriangleoffset += 3;\n\t}\n\n\tthis.numVertices = this.vertices.length/3;\n\tthis.numTriangles = this.triangleIndices.length/3;\n}", "function spherical(cartesian) {\n return [\n atan2(cartesian[1], cartesian[0]) * degrees,\n asin(max(-1, min(1, cartesian[2]))) * degrees,\n ];\n}", "function phi() {\n\tvar xcoords = [];\n\tvar ycoords = [];\n\tvar turnFraction = (1 + Math.sqrt(5)) / 2;\n\tfor (var i = 0; i < maxIter; i++) {\n\t\tvar dist = i*i / (maxIter - 1);\n\t\tvar angle = 2 * Math.PI * turnFraction * i;\n\t\tvar x = dist * Math.cos(angle);\n\t\tvar y = dist * Math.sin(angle);\n\n\t\txcoords.push(x);\n\t\tycoords.push(y);\n\t}\n\tvar data = {\n\t\tx: xcoords,\n\t\ty: ycoords,\n\t\tmode: 'markers',\n\t\ttype: 'scatter'\n\t}\n\treturn data;\n}", "function generateSphere1(config) {\n var scale, lats, longs, generateUVs;\n scale = config.scale || 100;\n lats = config.lats || 20;\n longs = config.longs || 20;\n generateUVs = config.generateUVs || false;\n var points = [],\n edges = [],\n polys = [],\n uvs = [];\n for (let latNumber = 0; latNumber <= lats; ++latNumber) {\n for (let longNumber = 0; longNumber <= longs; ++longNumber) {\n var theta = latNumber * PI / lats;\n var phi = longNumber * TAU / longs;\n var sinTheta = sin(theta);\n var sinPhi = sin(phi);\n var cosTheta = cos(theta);\n var cosPhi = cos(phi);\n var x = cosPhi * sinTheta;\n var y = cosTheta;\n var z = sinPhi * sinTheta;\n if (generateUVs) {\n var u = longNumber / longs;\n var v = latNumber / lats;\n uvs.push({\n u: u,\n v: v\n })\n }\n points.push({\n x: scale * x,\n y: scale * y,\n z: scale * z\n })\n }\n }\n for (let latNumber = 0; latNumber < lats; ++latNumber) {\n for (let longNumber = 0; longNumber < longs; ++longNumber) {\n var first = (latNumber * (longs + 1)) + longNumber;\n var second = first + longs + 1;\n if (latNumber === 0) {\n var p = [first + 1, second + 1, second];\n if (generateUVs) {\n p.uvs = [uvs[first + 1].u, uvs[first + 1].v, uvs[second + 1].u, uvs[second + 1].v, uvs[second].u, uvs[second].v]\n }\n polys.push(p);\n edges.push({\n a: first,\n b: second\n })\n } else {\n if (latNumber === lats - 1) {\n let p = [first + 1, second, first];\n if (generateUVs) {\n p.uvs = [uvs[first + 1].u, uvs[first + 1].v, uvs[second].u, uvs[second].v, uvs[first].u, uvs[first].v]\n }\n polys.push(p);\n edges.push({\n a: first,\n b: second\n })\n } else {\n let p = [first + 1, second + 1, second, first];\n if (generateUVs) {\n p.uvs = [uvs[first + 1].u, uvs[first + 1].v, uvs[second + 1].u, uvs[second + 1].v, uvs[second].u, uvs[second].v, uvs[first].u, uvs[first].v]\n }\n polys.push(p);\n edges.push({\n a: first,\n b: second\n });\n edges.push({\n a: second,\n b: second + 1\n })\n }\n }\n }\n }\n return {\n points: points,\n edges: edges,\n polygons: polys\n }\n }", "function plotGraph() {\n if (houses.data.length > 0) {\n for (let i = 0; i < houses.data.length; i++) {\n xs[i] = map(houses.data[i].inputs[0], 0, zoom, 0, wnx);\n ys[i] = map(houses.data[i].inputs[1], 0, zoom, wny, 200);\n cs[i] = houses.data[i].inputs[8];\n ps[i] = houses.data[i].target[0];\n }\n }\n}", "function spherical$1(cartesian) {\n return [\n atan2(cartesian[1], cartesian[0]) * degrees,\n asin(max(-1, min(1, cartesian[2]))) * degrees\n ];\n}", "function apskritimoPlotas(spindulys) {\n console.log('Apskritimo plotas');\n return Math.PI * (spindulys ** 2);\n}", "function drawSpheres() {\n \"use strict\";\n var cuboids = new THREE.Group();\n\n var geometry = new THREE.SphereBufferGeometry(GRID_WIDTH / 2);\n geometry.addAttribute('lightPos', POINT_LIGHT_POSITIONS.GPUBuffer);\n var gridPosition = new GridPosition(0,0,0);\n SPHERES_POSITIONS.forEach(function(item) {\n var material;\n // The color attribute of the material must be assigned in the constructor parameters.\n switch (shadingMethod) {\n case GOURAUD_SHADING:\n material = new THREE.MeshLambertMaterial({color: getRandColor(), side: THREE.FrontSide});\n break;\n case PHONG_SHADING:\n material = chooseShading();\n break;\n }\n var cuboid = new THREE.Mesh(geometry, material);\n cuboid.position.copy(gridPosition.setPosition(item[0], item[1], item[2]).getVector3());\n cuboid.matrixAutoUpdate = true;\n cuboids.add(cuboid);\n });\n\n scene.add(cuboids);\n}", "function drawSphere(color) {\r\n mvMatrix = mult(mvMatrix, scalem(0.75, 0.75, 0.75)); // Scale the sphere since it is a little big\r\n gl.uniformMatrix4fv(modelView, false, flatten(mvMatrix));\r\n\tsetDiffuse(color);\r\n for (var i = cubePoints.length; i < cubePoints.length + spherePoints.length; i += 3) {\r\n gl.drawArrays(gl.TRIANGLES, i, 3);\r\n }\r\n}", "function sphere() {\n var c = 2 * asin(1 / sqrt(5)) * degrees;\n return {\n type: \"Polygon\",\n coordinates: [\n [[0, 90], [-180, -c + epsilon], [0, -90], [180, -c + epsilon], [0, 90]]\n ]\n };\n}", "function sinusoidalZoom(min, max) {\n delta = clock.getDelta();\n theta += delta * 0.2;\n //theta += 0.01;\n camera.position.z = Math.abs((max-min)*Math.sin(theta))+min;\n}", "function drawSphere (rex,yon) {\n\t\tconsole.log(\"call Me\");\n\t\t//debugger; \n var waxBall = new DoodleImage({\n src: \"elect.png\",\n left: rex,\n top: yon,\n width: 250,\n height: 50\n });\n draw(waxBall);\n\n }", "function OnDrawGizmos()\n{\n\tGizmos.color = Color.green;\n\tGizmos.DrawSphere(transform.position + laneStart, 0.2);\n\t\n\tGizmos.color = Color.red;\n\tGizmos.DrawSphere(transform.position + laneEnd, 0.2);\n}", "function Sphere(radius, colorMapURLs, specularMapURL, shininess, animation, lighting) {\n var bands = 30, \n vertices = [], \n normals = [], \n textureCoord = [];\n\n // latitudes\n for (var slice = 0; slice <= bands; slice++) {\n var theta = slice * Math.PI / bands,\n sinTheta = Math.sin(theta),\n cosTheta = Math.cos(theta);\n\n // longitudes\n for (var arc = 0; arc <= bands; arc++) {\n var phi = arc * 2 * Math.PI / bands,\n sinPhi = Math.sin(phi),\n cosPhi = Math.cos(phi);\n\n var x = cosPhi * sinTheta,\n y = cosTheta,\n z = sinPhi * sinTheta,\n u = 1 - (arc / bands),\n v = 1 - (slice / bands);\n\n vertices.push(radius * x, radius * y, radius * z);\n textureCoord.push(u, v);\n normals.push(x, y, z);\n }\n }\n\n var vertexIndices = [];\n for (var slice = 0; slice < bands; slice++) {\n for (var arc = 0; arc < bands; arc++) {\n var first = (slice * (bands + 1)) + arc,\n second = first + bands + 1;\n\n vertexIndices.push(first, second, first + 1, second, second + 1, first + 1);\n }\n }\n\n ItemElements.call(this, vertices, vertexIndices, normals, textureCoord, colorMapURLs, \n specularMapURL, shininess, animation, lighting);\n}", "plot() {\n return \"Cute alien takes over the earth\";\n }", "function hemisphere2PolarHemisphere(x, y, z) {\n // xy fisheye 直交座標系 + 高さ\b z で表された 半径 r の半球上の座標を lθ+z 半球極座標系へ変換する\n var l = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));\n var theta = Math.atan2(y, x);\n return { l: l, theta: theta, z: z };\n}", "function generateSphere(subdiv, color, array) {\n\n var step = (360.0 / subdiv) * (Math.PI / 180.0); //how much do we increase the angles by per triangle\n\n for (var lat = 0; lat <= Math.PI; lat += step) { //latitude\n for (var lon = 0; lon + step <= 2 * Math.PI; lon += step) { //longitude\n //triangle 1\n array.push(vec4(Math.sin(lat) * Math.cos(lon), Math.sin(lon) * Math.sin(lat), Math.cos(lat), 1.0)); //position\n array.push(color); //color\n array.push(vec4(Math.sin(lat) * Math.cos(lon), Math.sin(lon) * Math.sin(lat), Math.cos(lat), 0.0)); //normal\n array.push(vec4(Math.sin(lat) * Math.cos(lon + step), Math.sin(lat) * Math.sin(lon + step), Math.cos(lat), 1.0)); //position\n array.push(color); //color\n array.push(vec4(Math.sin(lat) * Math.cos(lon+step), Math.sin(lat) * Math.sin(lon+step), Math.cos(lat), 0.0)); //normal\n array.push(vec4(Math.sin(lat + step) * Math.cos(lon + step), Math.sin(lon + step) * Math.sin(lat + step), Math.cos(lat + step), 1.0)); //etc\n array.push(color); //color\n array.push(vec4(Math.sin(lat+step) * Math.cos(lon+step), Math.sin(lon+step) * Math.sin(lat+step), Math.cos(lat+step), 0.0));//normal\n\n //triangle 2\n array.push(vec4(Math.sin(lat + step) * Math.cos(lon + step), Math.sin(lon + step) * Math.sin(lat + step), Math.cos(lat + step), 1.0));\n array.push(color); //color\n array.push(vec4(Math.sin(lat+step) * Math.cos(lon+step), Math.sin(lon+step) * Math.sin(lat+step), Math.cos(lat+step), 0.0));//normal\n array.push(vec4(Math.sin(lat + step) * Math.cos(lon), Math.sin(lat + step) * Math.sin(lon), Math.cos(lat + step), 1.0));\n array.push(color); //color\n array.push(vec4(Math.sin(lat+step) * Math.cos(lon), Math.sin(lat+step) * Math.sin(lon), Math.cos(lat+step),0.0));//normal\n array.push(vec4(Math.sin (lat) * Math.cos(lon), Math.sin(lon) * Math.sin(lat), Math.cos(lat), 1.0));\n array.push(color); //color\n array.push(vec4(Math.sin(lat) * Math.cos(lon), Math.sin(lon) * Math.sin(lat), Math.cos(lat), 0.0));//normal\n\n if(array === cart) {\n cartVertices += 6;\n } else if (array === lightGlobe) {\n lightVerts += 6;\n } else if (array === alphaSpheres) {\n alphaSphereVertices += 6;\n }\n }\n }\n}", "function makeSphere(ctx, radius, lats, longs) {\n var geometryData = [];\n var normalData = [];\n var texCoordData = [];\n var indexData = [];\n var latNumber;\n var longNumber;\n for (latNumber = 0; latNumber <= lats; ++latNumber) {\n for (longNumber = 0; longNumber <= longs; ++longNumber) {\n var theta = latNumber * Math.PI / lats;\n var phi = longNumber * 2 * Math.PI / longs;\n var sinTheta = Math.sin(theta);\n var sinPhi = Math.sin(phi);\n var cosTheta = Math.cos(theta);\n var cosPhi = Math.cos(phi);\n var x = cosPhi * sinTheta;\n var y = cosTheta;\n var z = sinPhi * sinTheta;\n var u = 1 - (longNumber / longs);\n var v = latNumber / lats;\n normalData.push(x);\n normalData.push(y);\n normalData.push(z);\n texCoordData.push(u);\n texCoordData.push(v);\n geometryData.push(radius * x);\n geometryData.push(radius * y);\n geometryData.push(radius * z);\n }\n }\n for (latNumber = 0; latNumber < lats; ++latNumber) {\n for (longNumber = 0; longNumber < longs; ++longNumber) {\n var first = (latNumber * (longs + 1)) + longNumber;\n var second = first + longs + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n }\n }\n // FIXME: What I don't like about this is the coupling of the geometry to the WebGL buffering.\n var normalBuffer = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, normalBuffer);\n ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(normalData), ctx.STATIC_DRAW);\n var texCoordBuffer = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, texCoordBuffer);\n ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(texCoordData), ctx.STATIC_DRAW);\n var vertexBuffer = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, vertexBuffer);\n ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(geometryData), ctx.STATIC_DRAW);\n var numIndices = indexData.length;\n var indexBuffer = ctx.createBuffer();\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, indexBuffer);\n ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), ctx.STREAM_DRAW);\n var self = {\n get normalBuffer() {\n return normalBuffer;\n },\n get texCoordBuffer() {\n return texCoordBuffer;\n },\n get vertexBuffer() {\n return vertexBuffer;\n },\n get indexBuffer() {\n return indexBuffer;\n },\n get numIndices() {\n return numIndices;\n }\n };\n return self;\n }", "function sphericalToCartesian( r, a, e ) {\n var x = r * Math.cos(e) * Math.cos(a);\n var y = r * Math.sin(e);\n var z = r * Math.cos(e) * Math.sin(a);\n\n return [x,y,z];\n }", "show() {\n fill(255);\n noStroke();\n let sx = map(this.x/this.z, 0, 1, 0, width);\n let sy = map(this.y/this.z, 0, 1, 0, height);\n let r = map(this.z, 0, width, 8, 0);\n //ellipse(sx, sy, r, r);\n stroke(255);\n let px = map(this.x/this.pz, 0, 1, 0, width);\n let py = map(this.y/this.pz, 0, 1, 0, height);\n line(px,py, sx, sy);\n this.pz = this.z;\n }", "function _drawSphere(pos, r, color) {\n var p = new Primitive();\n p.color = toColor(color);\n\n // Decreasing these angles will increase complexity of sphere.\n var dtheta = 35; var dphi = 35;\n\n for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) {\n for (var phi = 0; phi <= (360 - dphi); phi += dphi) {\n p.vertices.push(new THREE.Vector3(\n pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),\n pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),\n pos.z + r * Math.sin(theta * DEG_TO_RAD)\n ));\n\n p.vertices.push(new THREE.Vector3(\n pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),\n pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),\n pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)\n ));\n\n p.vertices.push(new THREE.Vector3(\n pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),\n pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),\n pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)\n ));\n\n if ((theta > -90) && (theta < 90)) {\n p.vertices.push(new THREE.Vector3(\n pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),\n pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),\n pos.z + r * Math.sin(theta * DEG_TO_RAD)\n ));\n }\n }\n }\n\n renderer.addPrimitive(p);\n }", "function SphericalHarmonics(numBands, numSamples)\n{\n this.numBands = numBands;\n this.numSamplesSqrt = parseInt(math.sqrt(numSamples));\n this.numSamples = this.numSamplesSqrt * this.numSamplesSqrt;\n this.numCoeffs = numBands * numBands;\n this.samples = [];\n this.coeffs = [];\n for (var i = 0; i < this.numCoeffs; ++i) {\n this.coeffs.push([0, 0, 0]);\n }\n this.scaleMatrix = []; // used to scale the coefficients\n // store (l,m) values, useful for looping\n this.lmPairs = [];\n for(var l=0; l<this.numBands; ++l) {\n for(var m=-l; m<=l; ++m) {\n var ci = l * (l+1) + m; // coefficient index\n this.lmPairs[ci] = [l, m];\n }\n }\n this.setupSphericalSamples();\n}", "function d3f_geo_cartesian(spherical) {\n var λ = spherical[0],\n φ = spherical[1],\n cosφ = Math.cos(φ);\n return [\n cosφ * Math.cos(λ),\n cosφ * Math.sin(λ),\n Math.sin(φ)\n ];\n}", "function createSphere() {\n var geometry = new THREE.Geometry({\n colorsNeedUpdate : true\n }); // define a blank geometry\n var material = new THREE.MeshBasicMaterial(\n {\n transparency: true,\n opacity: 1.0,\n wireframeLinewidth: 0.5,\n color: 0x444444\n }\n );\n material.wireframe = true;\n\n sphere_radius_3D_S = 60; // test value\n sphere_wSegs_3D_S = 60; // test value 纬带数(纬线数+1)\n sphere_hSegs_3D_S = 60; // test value 经带数\n\n // 【生成所有顶点位置】 latNumber:纬线计数器\n var totalVertex = (sphere_wSegs_3D_S+1)*(sphere_hSegs_3D_S+1);\n for (var latNumber=0; latNumber<=sphere_wSegs_3D_S; latNumber++) {\n var theta = latNumber * Math.PI / sphere_wSegs_3D_S;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta);\n for (var longNumber=0; longNumber<=sphere_hSegs_3D_S; longNumber++) {\n var phi = longNumber * 2 * Math.PI / sphere_hSegs_3D_S;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n // 球坐标系映射到xyz\n var x = sphere_radius_3D_S * sinTheta * cosPhi;\n var y = sphere_radius_3D_S * sinTheta * sinPhi;\n var z = sphere_radius_3D_S * cosTheta;\n var p = new THREE.Vector3(x, y, z);\n geometry.vertices.push(p);\n }\n }\n // 为了把这些顶点缝合到一起,需要【建立三角面片索引列表】\n var indexData = [];\n for (var latNumber = 0; latNumber < sphere_wSegs_3D_S; latNumber++) {\n for (var longNumber = 0; longNumber < sphere_hSegs_3D_S; longNumber++) {\n var first = (latNumber * (sphere_hSegs_3D_S + 1)) + longNumber;\n var second = first + sphere_hSegs_3D_S + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n // 测试用:调整了顶点顺序\n // indexData.push(first + 1);\n // indexData.push(second);\n // indexData.push(second + 1);\n }\n }\n // create faces\n for (var vertexCounter = 0; vertexCounter<indexData.length; vertexCounter+=3) {\n // var face = new THREE.Face3(\n // indexData[vertexCounter],\n // indexData[vertexCounter+1],\n // indexData[vertexCounter+2]\n // );\n var index1 = indexData[vertexCounter];\n var index2 = indexData[vertexCounter+1];\n var index3 = indexData[vertexCounter+2];\n var face = new THREE.Face3(\n index1,\n index2,\n index3\n );\n\n //着色方案1:仅用三种颜色测试\n // var color1 = findColor2(index1);//顶点1颜色\n // var color2 = findColor2(index2);//顶点2颜色\n // var color3 = findColor2(index3);//顶点3颜色\n\n // 着色方案2:灰度→彩色映射\n // 尚未测试\n // var color1 = trans_R( gray_scale(index1,totalVertex) );\n // var color2 = trans_G( gray_scale(index2,totalVertex) );\n // var color3 = trans_B( gray_scale(index3,totalVertex) );\n\n // 着色方案3:随机颜色\n // var color1 = new THREE.Color(0xFFFFFF * Math.random());//顶点1颜色——红色\n // var color2 = new THREE.Color(0xFFFFFF * Math.random());//顶点2颜色——绿色\n // var color3 = new THREE.Color(0xFFFFFF * Math.random());//顶点3颜色——蓝色\n // var color1 = new THREE.Color(getColor());//顶点1颜色——红色 产生随机色の方法2\n // var color2 = new THREE.Color(getColor());//顶点2颜色——绿色\n // var color3 = new THREE.Color(getColor());//顶点3颜色——蓝色\n\n // 着色方案4:随顶点索引数规律变化\n var color1 = findColor(index1,totalVertex);//顶点1颜色——红色\n var color2 = findColor(index2,totalVertex);//顶点2颜色——绿色\n var color3 = findColor(index3,totalVertex);//顶点3颜色——蓝色\n\n face.vertexColors.push(color1, color2, color3);//定义三角面三个顶点的颜色\n geometry.faces.push(face);\n }\n\n sphmat_3D_S=new THREE.MeshBasicMaterial({\n vertexColors: THREE.VertexColors,//以顶点颜色为准\n //vertexColors: geometry.colors,//以顶点颜色为准\n side: THREE.DoubleSide,//两面可见\n transparent: true,\n opacity: 1.0\n });//材质对象\n\n // create sphere and add it to scene\n sphere_3D_S = new THREE.Mesh(geometry,sphmat_3D_S);//网格模型对象\n scene_3D_S.add(sphere_3D_S); //网格模型添加到场景中\n}", "function sphere(nameOrM,radius,_boundNum,c1,c_2) {\n var c2 = c_2|| c1;\n\n var transform = new Transform();\n if (nameOrM[0]) scene.new_Part(nameOrM[1]);\n else transform = nameOrM[1];\n var ts = transform.get_Trans();\n var tn = transform.get_Tnorm();\n var index = scene.get_Indexbase();\n\n for(var i=0;i<=_boundNum; i++){\n var lat = i*Math.PI/_boundNum-Math.PI/2;\n if(i==0) lat+=0.001; if(i==_boundNum) lat-=0.001;\n var col = MyGradient(c1,c2,i,_boundNum+1);\n\n for(var j=0;j<=_boundNum; j++){\n var lon = j*2*Math.PI/_boundNum-Math.PI;\n var x = radius*Math.cos(lat)*Math.cos(lon);\n var z = radius*Math.cos(lat)*Math.sin(lon);\n var y = radius*Math.sin(lat);\n var poi = [x,y,z];\n scene.append_VBuffer([m4.transformPoint(ts,poi), col, m4.transformPoint(tn,poi)]);\n }\n }\n for(var i=0;i<_boundNum; i++) {\n for (var j = 0; j < _boundNum; j++) {\n var lu = index + i * (_boundNum + 1) + j;\n var ld = lu + _boundNum + 1;\n scene.append_IBuffer([lu, ld + 1, lu + 1, lu, ld, ld + 1]);\n }\n }\n }", "function displaySymmetryDrawObjects(symop){\r\n\tvar symOffsetString = _file.symmetry.symOffset;\r\n\tsymOffsetString = symOffsetString.substring(1);\r\n\tvar symOffsetArray = symOffsetString.split(\",\");\r\n\tvar xOffsetValue = parseInt(symOffsetArray[0])+\"/1\";\r\n\tvar yOffsetValue = parseInt(symOffsetArray[1])+\"/1\";\r\n\tvar zOffsetValue = parseInt(symOffsetArray[2])+\"/1\";\r\n\tvar symopString = \"\"+symop+\"\";\r\n\tvar symopArray = symopString.split(\",\");\r\n\tconsole.log(symopArray)\r\n\tvar xSymopValue = symopArray[0];\r\n\tvar ySymopValue = symopArray[1];\r\n\tvar zSymopValue = symopArray[2];\r\n\tsymopWithOffset = xSymopValue+\"+\"+xOffsetValue+\",\"+ySymopValue+\"+\"+yOffsetValue+\",\"+zSymopValue+\"+\"+zOffsetValue\r\n\trunJmolScriptWait(\"draw symop '\"+symopWithOffset+\"'\");\r\n\taxisFactor = 3;\r\n\trunJmolScriptWait(\"drawCleanSymmetryAxisVectors(\"+axisFactor+\")\");\r\n}", "function new_sphere (x, y, z, radius, dr, dg, db, k_ambient, k_specular, specular_pow) {\r\n append(shapes, new Sphere(x, y, z, radius, dr, dg, db, k_ambient, k_specular, specular_pow));\r\n}", "function SphereSubdiv (s) {\r\n this.name = \"sphere\";\r\n\r\n var vertices = [\r\n 1.0, 0.0, 0.0,\r\n 0.0, 1.0, 0.0,\r\n -1.0, 0.0, 0.0,\r\n 0.0, -1.0, 0.0,\r\n 0.0, 0.0, 1.0,\r\n 0.0, 0.0, -1.0\r\n ];\r\n var indices = [\r\n /* 0, 1, 4,\r\n 0, 1, 5,\r\n 1, 2, 4,\r\n 1, 2, 5,\r\n 2, 3, 4,\r\n 2, 3, 5,\r\n 3, 0, 4,//*/\r\n 3, 0, 5\r\n ];\r\n\r\n for (var i = 0; i<s; i++){\r\n var newIndices = []\r\n\r\n let vertexCount = vertices.length/3;\r\n\r\n var midpoints = new Array(vertexCount).fill(0).map(row => new Array(vertexCount).fill(-1)); \r\n for (var face = 0; face<indices.length/3; face++){\r\n let f = face*3;\r\n let a = indices[f];\r\n let b = indices[f+1];\r\n let c = indices[f+2];\r\n let ax = vertices[a*3];\r\n let ay = vertices[a*3+1];\r\n let az = vertices[a*3+2];\r\n let bx = vertices[b*3];\r\n let by = vertices[b*3+1];\r\n let bz = vertices[b*3+2];\r\n let cx = vertices[c*3];\r\n let cy = vertices[c*3+1];\r\n let cz = vertices[c*3+2];\r\n\r\n // Find (mx, my, mz), (nx, ny, nz), (px, py, pz) -- centers of segments\r\n var m = midpoints[a][b];\r\n if(m==-1){\r\n var x = (ax+bx)/2;\r\n var y = (ay+by)/2;\r\n var z = (az+bz)/2;\r\n let l = Math.sqrt(x*x + y*y + z*z);\r\n x/=l;\r\n y/=l;\r\n z/=l;\r\n m = vertices.length/3; // The index of the new point\r\n vertices = vertices.concat([x, y, z]);\r\n midpoints[a][b] = m;\r\n midpoints[b][a] = m;\r\n }\r\n var n = midpoints[a][c];\r\n if(n==-1){\r\n var x = (ax+cx)/2;\r\n var y = (ay+cy)/2;\r\n var z = (az+cz)/2;\r\n let l = Math.sqrt(x*x + y*y + z*z);\r\n x/=l;\r\n y/=l;\r\n z/=l;\r\n n = vertices.length/3; // The index of the new point\r\n vertices = vertices.concat([x, y, z]);\r\n midpoints[a][c] = n;\r\n midpoints[c][a] = n;\r\n }\r\n var p = midpoints[c][b];\r\n if(p==-1){\r\n var x = (cx+bx)/2;\r\n var y = (cy+by)/2;\r\n var z = (cz+bz)/2;\r\n let l = Math.sqrt(x*x + y*y + z*z);\r\n x/=l;\r\n y/=l;\r\n z/=l;\r\n p = vertices.length/3; // The index of the new point\r\n vertices = vertices.concat([x, y, z]);\r\n midpoints[c][b] = p;\r\n midpoints[b][c] = p;\r\n }\r\n\r\n newIndices = newIndices.concat([\r\n m, a, n,\r\n m, b, p,\r\n n, c, p,\r\n m, n, p\r\n ]);\r\n }\r\n indices = newIndices;\r\n }\r\n\r\n // Mirror around x\r\n var mirrorStart = vertices.length;\r\n vertices = vertices.concat(vertices);\r\n for(var i = mirrorStart; i<vertices.length; i+=3){\r\n vertices[i] = -vertices[i];\r\n }\r\n var mirrorFacesStart = indices.length;\r\n indices = indices.concat(indices);\r\n for (var i = mirrorFacesStart; i<indices.length; i++){\r\n indices[i]+=mirrorStart/3;\r\n }\r\n // Mirror around y\r\n mirrorStart = vertices.length;\r\n vertices = vertices.concat(vertices);\r\n for(var i = mirrorStart+1; i<vertices.length; i+=3){\r\n vertices[i] = -vertices[i];\r\n }\r\n mirrorFacesStart = indices.length;\r\n indices = indices.concat(indices);\r\n for (var i = mirrorFacesStart; i<indices.length; i++){\r\n indices[i]+=mirrorStart/3;\r\n }\r\n // Mirror around z\r\n mirrorStart = vertices.length;\r\n vertices = vertices.concat(vertices);\r\n for(var i = mirrorStart+2; i<vertices.length; i+=3){\r\n vertices[i] = -vertices[i];\r\n }\r\n mirrorFacesStart = indices.length;\r\n indices = indices.concat(indices);\r\n for (var i = mirrorFacesStart; i<indices.length; i++){\r\n indices[i]+=mirrorStart/3;\r\n }\r\n this.vertices = new Float32Array(vertices);\r\n this.triangleIndices = new Uint16Array(indices);\r\n\r\n this.numVertices = this.vertices.length/3;\r\n this.numTriangles = this.triangleIndices.length/3;\r\n\r\n}", "function init$g() {\n //no-op\n if (!this.sphere) {\n this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));\n }\n}", "display() {\n push();\n fill(255, 255, 0);\n let angle = TWO_PI / this.points;\n let halfAngle = angle / 2.0;\n beginShape();\n for (let a = 0; a < TWO_PI; a += angle) {\n let sx = this.x + cos(a) * this.outerRadius;\n let sy = this.y + sin(a) * this.outerRadius;\n vertex(sx, sy);\n sx = this.x + cos(a + halfAngle) * this.innerRadius;\n sy = this.y + sin(a + halfAngle) * this.innerRadius;\n vertex(sx, sy);\n }\n endShape(CLOSE);\n pop();\n }", "function showCoords() {\n // TODO: Set the map center to the latitude / longitude position of your own home\n\n\n // TODO: Zoom the map close enough\n\n}", "function makeSphere(ctx, radius, lats, longs) {\n\tvar geometryData = [];\n\tvar normalData = [];\n\tvar texCoordData = [];\n\tvar indexData = [];\n\n\tfor (var latNumber = 0; latNumber <= lats; ++latNumber) {\n\t\tfor (var longNumber = 0; longNumber <= longs; ++longNumber) {\n\t\t\tvar theta = latNumber * Math.PI / lats;\n\t\t\tvar phi = longNumber * 2 * Math.PI / longs;\n\t\t\tvar sinTheta = Math.sin(theta);\n\t\t\tvar sinPhi = Math.sin(phi);\n\t\t\tvar cosTheta = Math.cos(theta);\n\t\t\tvar cosPhi = Math.cos(phi);\n\n\t\t\tvar x = cosPhi * sinTheta;\n\t\t\tvar y = cosTheta;\n\t\t\tvar z = sinPhi * sinTheta;\n\t\t\tvar u = 1 - (longNumber / longs);\n\t\t\tvar v = latNumber / lats;\n\n\t\t\tnormalData.push(x);\n\t\t\tnormalData.push(y);\n\t\t\tnormalData.push(z);\n\t\t\ttexCoordData.push(u);\n\t\t\ttexCoordData.push(v);\n\t\t\tgeometryData.push(radius * x);\n\t\t\tgeometryData.push(radius * y);\n\t\t\tgeometryData.push(radius * z);\n\t\t}\n\t}\n\n\tfor (var latNumber = 0; latNumber < lats; ++latNumber) {\n\t\tfor (var longNumber = 0; longNumber < longs; ++longNumber) {\n\t\t\tvar first = (latNumber * (longs + 1)) + longNumber;\n\t\t\tvar second = first + longs + 1;\n\t\t\tindexData.push(first);\n\t\t\tindexData.push(second);\n\t\t\tindexData.push(first + 1);\n\n\t\t\tindexData.push(second);\n\t\t\tindexData.push(second + 1);\n\t\t\tindexData.push(first + 1);\n\t\t}\n\t}\n\n\tvar retval = {};\n\n\tretval.normalObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(normalData), ctx.STATIC_DRAW);\n\n\tretval.texCoordObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(texCoordData), ctx.STATIC_DRAW);\n\n\tretval.vertexObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(geometryData), ctx.STATIC_DRAW);\n\n\tretval.numIndices = indexData.length;\n\tretval.indexObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);\n\tctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), ctx.STREAM_DRAW);\n\tretval.indexType = ctx.UNSIGNED_SHORT;\n\n\treturn retval;\n}", "function drawVectors() {\n gridPoints.forEach(function(pt, index) {\n translate(pt.x, pt.y);\n // --Basic field:--\n // var xDis = 20 * ((w/2) - pt.x) / w;\n // var yDis = 20 * ((w/2) - pt.y) / w;\n\n // Perfect, this makes it look more continuous and natural:\n var scale = 0.1;\n\n var noiseVal = noise(scale * pt.x/s, scale * pt.y/s);\n\n fullArray.push({\n x: pt.x,\n y: pt.y,\n val: noiseVal\n });\n\n var angle = noiseVal * 2 * Math.PI;\n rotate(angle);\n\n stroke(255);\n line(0, 0, 10, 0);\n\n rotate(-angle);\n\n // line(0, 0, xDis, yDis);\n // don't forget to translate back out -- could also use push and pop to achieve same effect:\n translate(-pt.x, -pt.y);\n });\n}", "function drawSphere(numberToSubdivide, useFlatShading, isSun) {\n divideTriangle(va, vb, vc, numberToSubdivide);\n divideTriangle(vd, vc, vb, numberToSubdivide);\n divideTriangle(va, vd, vb, numberToSubdivide);\n divideTriangle(va, vc, vd, numberToSubdivide);\n \n function triangle(a, b, c) {\n pointsArray.push(a, b, c);\n \n //push normal vectors \n if(useFlatShading){\n var t1 = subtract(c,b);\n var t2 = subtract(c,a);\n var normal = vec4(normalize(cross(t1,t2)));\n if(isSun){\n normal = subtract(vec4(0,0,0,0), normal);\n }\n normalsArray.push(normal, normal, normal);\n }\n else{\n normalsArray.push(a, b, c);\n } \n\n index += 3;\n }\n\n function divideTriangle(a, b, c, count) {\n if ( count <= 0 ) { \n triangle(a, b, c);\n }\n else{ \n var ab = mix( a, b, 0.5);\n var ac = mix( a, c, 0.5);\n var bc = mix( b, c, 0.5);\n \n ab = normalize(ab, true);\n ac = normalize(ac, true);\n bc = normalize(bc, true);\n \n divideTriangle( a, ab, ac, count - 1 );\n divideTriangle( ab, b, bc, count - 1 );\n divideTriangle( bc, c, ac, count - 1 );\n divideTriangle( ab, bc, ac, count - 1 );\n }\n }\n\n}", "function drawSphere() {\r\n // console.log(xindex + \" \" + yindex + \" \" +xthumb + \" \" + ythumb);\r\n //console.log(handMeshes[userId])\r\n var xs = xindex - xthumb;\r\n var ys = yindex - ythumb;\r\n var r = (Math.sqrt( xs*xs + ys*ys )-10);\r\n //console.log(r)\r\n var obj1 = new THREE.Object3D();\r\n \r\n var sfera = new THREE.SphereGeometry(r);\r\n var matsfe = new THREE.MeshNormalMaterial();\r\n var mesh1 = new THREE.Mesh(sfera, matsfe);\r\n \r\n obj1.position.x = xthumb;\r\n obj1.position.y = ythumb;\r\n \r\n obj1.add(mesh1);\r\n scene.add(obj1);\r\n }", "function makeSphere(numLongSteps) {\n \n try {\n if (numLongSteps % 2 != 0)\n throw \"in makeSphere: uneven number of longitude steps!\";\n else if (numLongSteps < 4)\n throw \"in makeSphere: number of longitude steps too small!\";\n else { // good number longitude steps\n \n // make vertices, normals and uvs -- repeat longitude seam\n const INVPI = 1/Math.PI, TWOPI = Math.PI+Math.PI, INV2PI = 1/TWOPI, epsilon=0.001*Math.PI;\n var sphereVertices = [0,-1,0]; // vertices to return, init to south pole\n var sphereUvs = [0.5,0]; // uvs to return, bottom texture row collapsed to one texel\n var angleIncr = TWOPI / numLongSteps; // angular increment \n var latLimitAngle = angleIncr * (Math.floor(numLongSteps*0.25)-1); // start/end lat angle\n var latRadius, latY, latV; // radius, Y and texture V at current latitude\n for (var latAngle=-latLimitAngle; latAngle<=latLimitAngle+epsilon; latAngle+=angleIncr) {\n latRadius = Math.cos(latAngle); // radius of current latitude\n latY = Math.sin(latAngle); // height at current latitude\n latV = latAngle*INVPI + 0.5; // texture v = (latAngle + 0.5*PI) / PI\n for (var longAngle=0; longAngle<=TWOPI+epsilon; longAngle+=angleIncr) { // for each long\n sphereVertices.push(-latRadius*Math.sin(longAngle),latY,latRadius*Math.cos(longAngle));\n sphereUvs.push(longAngle*INV2PI,latV); // texture u = (longAngle/2PI)\n } // end for each longitude\n } // end for each latitude\n sphereVertices.push(0,1,0); // add north pole\n sphereUvs.push(0.5,1); // top texture row collapsed to one texel\n var sphereNormals = sphereVertices.slice(); // for this sphere, vertices = normals; return these\n\n // make triangles, first poles then middle latitudes\n var sphereTriangles = []; // triangles to return\n var numVertices = Math.floor(sphereVertices.length/3); // number of vertices in sphere\n for (var whichLong=1; whichLong<=numLongSteps; whichLong++) { // poles\n sphereTriangles.push(0,whichLong,whichLong+1);\n sphereTriangles.push(numVertices-1,numVertices-whichLong-1,numVertices-whichLong-2);\n } // end for each long\n var llVertex; // lower left vertex in the current quad\n for (var whichLat=0; whichLat<(numLongSteps/2 - 2); whichLat++) { // middle lats\n for (var whichLong=0; whichLong<numLongSteps; whichLong++) {\n llVertex = whichLat*(numLongSteps+1) + whichLong + 1;\n sphereTriangles.push(llVertex,llVertex+numLongSteps+1,llVertex+numLongSteps+2);\n sphereTriangles.push(llVertex,llVertex+numLongSteps+2,llVertex+1);\n } // end for each longitude\n } // end for each latitude\n } // end if good number longitude steps\n return({vertices:sphereVertices, normals:sphereNormals, uvs:sphereUvs, triangles:sphereTriangles});\n } // end try\n \n catch(e) {\n console.log(e);\n } // end catch\n }", "function plot() {\n \n }", "function getSphereData(isEllipse, sphere) {\n\n sphere.vertices = [];\n if (!isEllipse) {\n sphere.texCoords = [];\n }\n for (var latNumber = 0; latNumber <= latBands; latNumber++) {\n var theta = latNumber * Math.PI / latBands;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta);\n\n for (var longNumber = 0; longNumber <= longBands; longNumber++) {\n var phi = longNumber * 2 * Math.PI / longBands;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n\n var x = cosPhi * sinTheta;\n var y = cosTheta;\n var z = sinPhi * sinTheta;\n if (!isEllipse) {\n sphere.texCoords.push(1 - (longNumber / longBands));\n sphere.texCoords.push(1 - (latNumber / latBands));\n }\n sphere.vertices.push(radius * x);\n if (isEllipse) {\n sphere.vertices.push(2 * radius * y);\n } else {\n sphere.vertices.push(radius * y);\n }\n sphere.vertices.push(radius * z);\n }\n }\n}", "function _Sphere(radius) {\n var __sphereData = null,\n __sphereVertexPositionBuffer = null,\n __sphereVertexIndexBuffer = null,\n __sphereVertexNormalBuffer = null,\n\n __colour = {r: 0.8, g: 0.8, b: 0.8, a: 1.0},\n __radius = radius || 1.0,\n __modelMatrix = mat4.create(),\n __rotationMatrix = mat4.create(),\n __translationMatrix = mat4.create(),\n __scaleMatrix = mat4.create(),\n __PVMMatrix = mat4.create(),\n __normalMatrix = mat3.create(),\n __shouldUpdateMatrices = true;\n\n function __init() {\n __sphereData = webGLDrawUtilities.createSphereVertexData(__radius);\n\n // create the buffer for vertex positions and assign it to that buffer to use for later\n __sphereVertexPositionBuffer = _gl.createBuffer();\n __sphereVertexPositionBuffer.itemSize = 3;\n __sphereVertexPositionBuffer.numItems = __sphereData.vertexPositionData.length / __sphereVertexPositionBuffer.itemSize;\n __sphereVertexPositionBuffer.items = new Float32Array(__sphereData.vertexPositionData);\n\n _gl.bindBuffer(_gl.ARRAY_BUFFER, __sphereVertexPositionBuffer);\n _gl.bufferData(_gl.ARRAY_BUFFER, __sphereVertexPositionBuffer.items, _gl.STATIC_DRAW);\n\n // create the buffer for vertex positions indexes and assign it to that buffer to use for later\n __sphereVertexIndexBuffer = _gl.createBuffer();\n __sphereVertexIndexBuffer.itemSize = 1;\n __sphereVertexIndexBuffer.numItems = __sphereData.vertexIndexData.length;\n __sphereVertexIndexBuffer.items = new Uint16Array(__sphereData.vertexIndexData);\n\n _gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, __sphereVertexIndexBuffer);\n _gl.bufferData(_gl.ELEMENT_ARRAY_BUFFER, __sphereVertexIndexBuffer.items, _gl.STATIC_DRAW);\n\n // create the buffer for vertex positions indexes and assign it to that buffer to use for later\n __sphereVertexNormalBuffer = _gl.createBuffer();\n __sphereVertexNormalBuffer.itemSize = 3;\n __sphereVertexNormalBuffer.numItems = __sphereData.vertexNormals.length / __sphereVertexNormalBuffer.itemSize;\n __sphereVertexNormalBuffer.items = new Float32Array(__sphereData.vertexNormals);\n\n _gl.bindBuffer(_gl.ARRAY_BUFFER, __sphereVertexNormalBuffer);\n _gl.bufferData(_gl.ARRAY_BUFFER, __sphereVertexNormalBuffer.items, _gl.STATIC_DRAW);\n\n }\n\n // draw itself\n function __draw() {\n\n mat4.multiply(__modelMatrix, __translationMatrix, __rotationMatrix);\n mat4.multiply(__modelMatrix, __modelMatrix, __scaleMatrix);\n\n // calculate the inverse, transpose of the model Matrix to make sure our surface normals are perpendicular to the surface again!!\n mat3.normalFromMat4(__normalMatrix, __modelMatrix);\n\n // View * Model\n mat4.multiply(__PVMMatrix, _glProgram.customAttribs.viewMatrix, __modelMatrix);\n\n // Perspective * (View * Model)\n mat4.multiply(__PVMMatrix, _glProgram.customAttribs.perspectiveMatrix, __PVMMatrix);\n\n // alright now assign the matrices back to the location of our vertex shader\n _gl.uniformMatrix3fv(_glProgram.customAttribs.u_NormalMatrixRef, false, __normalMatrix);\n _gl.uniformMatrix4fv(_glProgram.customAttribs.u_PVMMatrixRef, false, __PVMMatrix);\n\n // set the position buffer\n _gl.bindBuffer(_gl.ARRAY_BUFFER, __sphereVertexPositionBuffer);\n _gl.vertexAttribPointer(_glProgram.customAttribs.a_PositionRef, __sphereVertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, 0);\n _gl.enableVertexAttribArray(_glProgram.customAttribs.a_PositionRef);\n\n // set the index buffer\n _gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, __sphereVertexIndexBuffer);\n\n // bind the surface normal buffer\n _gl.bindBuffer(_gl.ARRAY_BUFFER, __sphereVertexNormalBuffer);\n _gl.vertexAttribPointer(_glProgram.customAttribs.a_VertexNormalRef, __sphereVertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, 0);\n _gl.enableVertexAttribArray(_glProgram.customAttribs.a_VertexNormalRef);\n\n // make sure the sphere is in the correct colour\n _gl.uniform4f(_glProgram.customAttribs.u_FragColourRef, __colour.r, __colour.g, __colour.b, __colour.a);\n\n // draw the elements!\n _gl.drawElements(_gl.TRIANGLES, __sphereVertexIndexBuffer.numItems, _gl.UNSIGNED_SHORT, 0);\n\n }\n\n // rotate the sphere by x, y, z degrees\n function __rotateOnAxisByDegrees(x, y, z) {\n\n if (typeof x === 'number') {\n mat4.rotateX(__rotationMatrix, __rotationMatrix, glMatrix.toRadian(x));\n }\n\n if (typeof y === 'number') {\n mat4.rotateY(__rotationMatrix, __rotationMatrix, glMatrix.toRadian(y));\n }\n\n if (typeof z === 'number') {\n mat4.rotateZ(__rotationMatrix, __rotationMatrix, glMatrix.toRadian(z));\n }\n\n __shouldUpdateMatrices = true;\n\n return this;\n\n }\n\n // scale the sphere by s units\n function __scale(s) {\n if (typeof s === 'number') {\n mat4.scale(__scaleMatrix, __scaleMatrix, vec3.fromValues(s, s, s));\n }\n\n __shouldUpdateMatrices = true;\n\n return this;\n }\n\n // translate the sphere by (x, y, z) units\n function __translate(x, y, z) {\n\n mat4.translate(__translationMatrix, __translationMatrix, vec3.fromValues(x, y, z));\n\n __shouldUpdateMatrices = true;\n\n return this;\n }\n\n __init();\n\n ////////////////////////////////////////////////////////\n // _Sphere public API\n ////////////////////////////////////////////////////////\n this.rotateOnAxisByDegrees = __rotateOnAxisByDegrees;\n\n this.draw = __draw;\n\n this.scale = __scale;\n\n this.translate = __translate;\n\n // sets the colour of the primitive\n this.setColour = function(r, g, b, a) {\n __colour.r = r;\n __colour.g = g;\n __colour.b = b;\n __colour.a = a;\n\n return this;\n };\n\n this.getRadius = function() {\n return __radius;\n };\n\n return this;\n }", "function makeSphere (slices, stacks) {\n // fill in your code here.\n\tvar triangles = [];\n\tvar origin = [0.0, 0.0, 0.0];\n\tconst radius = 0.5;\n\tconst longi_step = radians(360 / slices); // in radian\n\tconst lati_step = radians(180 / stacks); // in radian\n\n\tvar theta = 0.0;\n\t\n\n\tfor (var i=0; i<slices; i++){\n\n\t\tvar phi = 0.0;\n\t\tfor(var j=0; j<stacks; j++){\n\t\t\tvar v1 = [radius * Math.sin(theta) * Math.sin(phi), radius * Math.cos(phi), radius * Math.cos(theta) * Math.sin(phi)];\n\t\t\tvar v2 = [radius * Math.sin(theta + longi_step) * Math.sin(phi), radius * Math.cos(phi), radius * Math.cos(theta + longi_step) * Math.sin(phi)];\n\t\t\tvar v3 = [radius * Math.sin(theta) * Math.sin(phi + lati_step), radius * Math.cos(phi + lati_step), radius * Math.cos(theta) * Math.sin(phi + lati_step)];\n\t\t\tvar v4 = [radius * Math.sin(theta + longi_step) * Math.sin(phi + lati_step), radius * Math.cos(phi + lati_step), radius * Math.cos(theta + longi_step) * Math.sin(phi + lati_step)];\n\n\t\t\ttriangles.push([v1, v3, v2]);\n\t\t\ttriangles.push([v2, v3, v4]);\n\n\t\t\tphi += lati_step;\n\t\t}\n\n\t\ttheta += longi_step;\n\t}\n\n\tconsole.log(triangles.length);\n\n\tfor (tri of triangles){\n\t\taddTriangle(\n\t\t\ttri[0][0], tri[0][1], tri[0][2],\n\t\t\ttri[1][0], tri[1][1], tri[1][2],\n\t\t\ttri[2][0], tri[2][1], tri[2][2]\n\t\t\t);\n\t}\n\n\n}", "function makeSphere(numLongSteps) {\n \n try {\n if (numLongSteps % 2 != 0)\n throw \"in makeSphere: uneven number of longitude steps!\";\n else if (numLongSteps < 4)\n throw \"in makeSphere: number of longitude steps too small!\";\n else { // good number longitude steps\n \n// // make vertices and normals\n// \t\n// var sphereVertices = [0,-1,0]; // vertices to return, init to south pole\n// var sphereTextureCoords = [0.5,0];\n// var angleIncr = (Math.PI+Math.PI) / numLongSteps; // angular increment \n// var latLimitAngle = angleIncr * (Math.floor(numLongSteps/4)-1); // start/end lat angle\n// var latRadius, latY; // radius and Y at current latitude\n// for (var latAngle=-latLimitAngle; latAngle<=latLimitAngle; latAngle+=angleIncr) {\n// latRadius = Math.cos(latAngle); // radius of current latitude\n// latY = Math.sin(latAngle); // height at current latitude\n// for (var longAngle=0; longAngle<2*Math.PI; longAngle+=angleIncr){ // for each long\n// sphereVertices.push(latRadius*Math.sin(longAngle),latY,latRadius*Math.cos(longAngle));\n// sphereTextureCoords.push((latRadius*Math.sin(longAngle)+1)/2,(latY+1)/2);\n// }\n// } // end for each latitude\n// sphereVertices.push(0,1,0); // add north pole\n// sphereTextureCoords.push(0.5,1);\n// var sphereNormals = sphereVertices.slice(); // for this sphere, vertices = normals; return these\n// \n// // make triangles, from south pole to middle latitudes to north pole\n// var sphereTriangles = []; // triangles to return\n// for (var whichLong=1; whichLong<numLongSteps; whichLong++) // south pole\n// sphereTriangles.push(0,whichLong,whichLong+1);\n// sphereTriangles.push(0,numLongSteps,1); // longitude wrap tri\n// var llVertex; // lower left vertex in the current quad\n// for (var whichLat=0; whichLat<(numLongSteps/2 - 2); whichLat++) { // middle lats\n// for (var whichLong=0; whichLong<numLongSteps-1; whichLong++) {\n// llVertex = whichLat*numLongSteps + whichLong + 1;\n// sphereTriangles.push(llVertex,llVertex+numLongSteps,llVertex+numLongSteps+1);\n// sphereTriangles.push(llVertex,llVertex+numLongSteps+1,llVertex+1);\n// } // end for each longitude\n// sphereTriangles.push(llVertex+1,llVertex+numLongSteps+1,llVertex+2);\n// sphereTriangles.push(llVertex+1,llVertex+2,llVertex-numLongSteps+2);\n// } // end for each latitude\n// for (var whichLong=llVertex+2; whichLong<llVertex+numLongSteps+1; whichLong++) // north pole\n// sphereTriangles.push(whichLong,sphereVertices.length/3-1,whichLong+1);\n// sphereTriangles.push(sphereVertices.length/3-2,sphereVertices.length/3-1,sphereVertices.length/3-numLongSteps-1); // longitude wrap\n \t\n \t/**Using the sphere from the lesson: http://learningwebgl.com/blog/?p=1253*/\n \tvar vertexPositionData = [];\n var normalData = [];\n var textureCoordData = [];\n for (var latNumber = 0; latNumber <= numLongSteps; latNumber++) {\n var theta = latNumber * Math.PI / numLongSteps;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta);\n\n for (var longNumber = 0; longNumber <= numLongSteps; longNumber++) {\n var phi = longNumber * 2 * Math.PI / numLongSteps;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n\n var x = cosPhi * sinTheta;\n var y = cosTheta;\n var z = sinPhi * sinTheta;\n var u = 1 - (longNumber / numLongSteps);\n var v = 1 - (latNumber / numLongSteps);\n\n normalData.push(x);\n normalData.push(y);\n normalData.push(z);\n textureCoordData.push(u);\n textureCoordData.push(v);\n vertexPositionData.push(x);\n vertexPositionData.push(y);\n vertexPositionData.push(z);\n }\n }\n var indexData = [];\n for (var latNumber = 0; latNumber < numLongSteps; latNumber++) {\n for (var longNumber = 0; longNumber < numLongSteps; longNumber++) {\n var first = (latNumber * (numLongSteps + 1)) + longNumber;\n var second = first + numLongSteps + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n }\n }\n \t\n } // end if good number longitude steps\n// return({vertices:sphereVertices, normals:sphereNormals, triangles:sphereTriangles, texture:sphereTextureCoords});\n return({vertices:vertexPositionData, normals:normalData, triangles:indexData, texture:textureCoordData});\n } // end try\n \n catch(e) {\n console.log(e);\n } // end catch\n } // end make sphere", "function drawSphere(radius, widthSegments, heightSegments, opacity, color, position){\n\tvar geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments, 0, 2.*Math.PI, 0, Math.PI)\n\tvar material = new THREE.MeshPhongMaterial( { \n\t\tcolor: color, \n\t\tflatShading: false, \n\t\ttransparent:true,\n\t\topacity:opacity, \n\t\t//shininess:50,\n\t});\n\n\tsphere = new THREE.Mesh( geometry, material );\n\tsphere.position.set(position.x, position.y, position.z)\n\t//update the vertices of the plane geometry so that I can check for the intersection -- not needed (and also breaks the sparse view)\n\t//https://stackoverflow.com/questions/23990354/how-to-update-vertices-geometry-after-rotate-or-move-object\n\t// sphere.updateMatrix();\n\t// sphere.geometry.applyMatrix( sphere.matrix );\n\t// sphere.matrix.identity();\n\t// sphere.position.set( 0, 0, 0 );\n\t// sphere.rotation.set( 0, 0, 0 );\n\t// sphere.scale.set( 1, 1, 1 );\n\n\tparams.scene.add( sphere );\n\t\n\treturn sphere;\n\n}", "plotJourneys() {\n for (let j of this.mapJourneys) {\n //plot ghost Session\n j.plotSessions(this);\n }\n }", "function drawCircle () {\n\tvar resolution = 8;\n\tvar amplitude = 10;\n\tvar size = 360 / resolution;\n\n\tvar geometry = new THREE.Geometry();\n\tvar material = new THREE.MeshBasicMaterial( { color: 0xFFFFFF,\n\t\tside: THREE.DoubleSide,\n\t\twireframe: true} );\n\t// geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );\n\tfor(var i = 0; i <= resolution; i++) {\n\t var segment = ( i * size ) * Math.PI / 180;\n\t var segment2 = ( i * size + size * 0.5 ) * Math.PI / 180;\n\t geometry.vertices.push( new THREE.Vector3( Math.cos( segment ) * amplitude, Math.sin( segment ) * amplitude, 0 ) ); \n\t geometry.vertices.push( new THREE.Vector3( Math.cos( segment2 ) * (amplitude-2), Math.sin( segment2 ) * (amplitude -2), 0 ) ); \n\t}\n\n\tfor ( i = 0; i < geometry.vertices.length -2; i++) {\n\t\tgeometry.faces.push ( new THREE.Face3( i, i+1, i+2 ) );\n\t}\n\tconsole.log ('Vertices', geometry.faces);\n\tgeometry.computeBoundingSphere();\n\n\n\tvar ringMesh = new THREE.Mesh(geometry, material); \n ringMesh.position.set(-1.5, 0.0, -14.0); \n scene.add(ringMesh); \n}", "function S(e,t,n,i,r){var o=Math.cos(e),a=Math.sin(e),s=n/t*e,l=Math.cos(s);r.x=i*(2+l)*.5*o,r.y=i*(2+l)*a*.5,r.z=i*Math.sin(s)*.5}", "function makeSphere (slices, stacks) {\n // fill in your code here.\n var sliceDivision = radians(360) / slices;\n var stackDivision = radians(180) / stacks;\n var radius = 0.5;\n\n for (var longitude = 0; longitude < radians(360); longitude += sliceDivision) {\n for (var latitude = 0; latitude < radians(180); latitude += stackDivision) {\n addTriangle(radius * Math.cos(longitude) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision), \n radius * Math.cos(longitude) * Math.sin(latitude), radius * Math.sin(longitude) * Math.sin(latitude), radius * Math.cos(latitude), \n radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision));\n \n addTriangle(radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude + stackDivision), radius * Math.cos(latitude + stackDivision), \n radius * Math.cos(longitude) * Math.sin(latitude), radius * Math.sin(longitude) * Math.sin(latitude), radius * Math.cos(latitude), \n radius * Math.cos(longitude + sliceDivision) * Math.sin(latitude), radius * Math.sin(longitude + sliceDivision) * Math.sin(latitude), radius * Math.cos(latitude));\n\n }\n }\n}", "function drawSphere() {\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexPositionBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, sphereVertexPositionBuffer.itemSize,\r\n gl.FLOAT, false, 0, 0);\r\n\r\n // Bind normal buffer\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexNormalBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute,\r\n sphereVertexNormalBuffer.itemSize,\r\n gl.FLOAT, false, 0, 0);\r\n gl.drawArrays(gl.TRIANGLES, 0, sphereVertexPositionBuffer.numItems);\r\n}", "function drawSphere() {\n\n gl.useProgram(sphere.program);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(sphere.indexList), gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, verticesBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphere.vertices), gl.STATIC_DRAW);\n var vertexPosition = gl.getAttribLocation(sphere.program, \"vertexPosition\");\n gl.vertexAttribPointer(vertexPosition, sphere.vertDim, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(vertexPosition);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, normalsBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(flatten(sphere.normals)), gl.STATIC_DRAW);\n var nvPosition = gl.getAttribLocation(sphere.program, \"nv\");\n gl.vertexAttribPointer(nvPosition, sphere.vertDim, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(nvPosition);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, sphereTexture);\n gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphere.texCoords), gl.STATIC_DRAW);\n var texCoordLocation = gl.getAttribLocation(sphere.program, \"texCoord\");\n gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(texCoordLocation);\n\n var MLoc = gl.getUniformLocation(sphere.program, \"M\");\n gl.uniformMatrix4fv(MLoc, false, M);\n\n var SRotLoc = gl.getUniformLocation(sphere.program, \"SRot\");\n gl.uniformMatrix4fv(SRotLoc, false, flatten(sceneRotation));\n\n var MinvTransLoc = gl.getUniformLocation(sphere.program, \"MinvTrans\");\n gl.uniformMatrix4fv(MinvTransLoc, false, MinvTrans);\n\n var PLoc = gl.getUniformLocation(sphere.program, \"P\");\n gl.uniformMatrix4fv(PLoc, false, P);\n\n var thetaLoc = gl.getUniformLocation(sphere.program, \"theta\");\n gl.uniform1f(thetaLoc, sphere.theta);\n\n var scaleLoc = gl.getUniformLocation(sphere.program, \"s\");\n gl.uniform1f(scaleLoc, scale);\n\n var lightDirection1Loc = gl.getUniformLocation(sphere.program, \"lightDirection1\");\n gl.uniform3f(lightDirection1Loc, lightDirection1[0], lightDirection1[1], lightDirection1[2]);\n var directionColor1Loc = gl.getUniformLocation(sphere.program, \"directionColor1\");\n gl.uniform3f(directionColor1Loc, directionColor1[0], directionColor1[1], directionColor1[2]);\n var lightDirection2Loc = gl.getUniformLocation(sphere.program, \"lightDirection2\");\n gl.uniform3f(lightDirection2Loc, lightDirection2[0], lightDirection2[1], lightDirection2[2])\n var directionColor2Loc = gl.getUniformLocation(sphere.program, \"directionColor2\");\n gl.uniform3f(directionColor2Loc, directionColor2[0], directionColor2[1], directionColor2[2])\n\n gl.drawElements(gl.TRIANGLES, sphere.numElems, gl.UNSIGNED_SHORT, 0);\n}", "function sphere() {\n\n}", "function calculation () { \n var cos = Math.cos(phi), sin = Math.sin(phi);\n xB0 = xM0+R0*cos; yB0 = yM0-R0*sin; // Beobachtungsort (linke Skizze) \n xN0 = xB0-R1*sin; yN0 = yB0-R1*cos; // Norden (linke Skizze)\n xS0 = xB0+R1*sin; yS0 = yB0+R1*cos; // S�den (linke Skizze)\n xZ0 = xB0+R1*cos; yZ0 = yB0-R1*sin; // Zenit (linke Skizze)\n if (phi < 0) {cos = -cos; sin = -sin;} // Vorzeichenumkehr f�r S�dhalbkugel\n xP1 = xB1-R1*cos; yP1 = yB1-R1*sin; // Himmelspol (rechte Skizze) \n }", "function showPosition(position) {\n\tvar radlat1 = Math.PI * position.coords.latitude/180\n\tvar radlat2 = Math.PI * myLatitude/180\n\tvar theta = position.coords.longitude-myLongitude\n\tvar radtheta = Math.PI * theta/180\n\tvar dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);\n\tdist = Math.acos(dist)\n\tdist = dist * 180/Math.PI\n\tdist = dist * 60 * 1.1515 * 1.609344 * 1000 //convert to meters\n\tdocument.getElementById(myDistance).innerHTML = Math.round(dist) + \" meters\"; \t\n}", "function SphericalMercator(options) {\n options = options || {};\n this.size = options.size || 256;\n if (!cache[this.size]) {\n var size = this.size;\n var c = cache[this.size] = {};\n c.Bc = [];\n c.Cc = [];\n c.zc = [];\n c.Ac = [];\n for (var d = 0; d < 30; d++) {\n c.Bc.push(size / 360);\n c.Cc.push(size / (2 * Math.PI));\n c.zc.push(size / 2);\n c.Ac.push(size);\n size *= 2;\n }\n }\n this.Bc = cache[this.size].Bc;\n this.Cc = cache[this.size].Cc;\n this.zc = cache[this.size].zc;\n this.Ac = cache[this.size].Ac;\n}", "function OnDrawGizmosSelected() {\n\tvar camera = GetComponent.<Camera>();\n\tvar p = camera.ScreenToWorldPoint(new Vector3(100, 100, camera.nearClipPlane));\n\tGizmos.color = Color.yellow;\n\tGizmos.DrawSphere(p, 0.1F);\n}", "function showSphereLighted(model) {\n //code from http://learningwebgl.com/cookbook/index.php/How_to_draw_a_sphere & http://learningwebgl.com/blog/?p=1253\n const latitudeBands = 30;\n const longitudeBands = 30;\n const radius = 100;\n\n const vertexPositionData = [];\n const normalData = [];\n const textureCoordData = [];\n\n for (let latNumber = 0; latNumber <= latitudeBands; latNumber++) {\n const theta = latNumber * Math.PI / latitudeBands;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n\n for (let longNumber = 0; longNumber <= longitudeBands; longNumber++) {\n const phi = longNumber * 2 * Math.PI / longitudeBands;\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const x = cosPhi * sinTheta;\n const y = cosTheta;\n const z = sinPhi * sinTheta;\n const u = 1 - (longNumber / longitudeBands);\n const v = latNumber / latitudeBands;\n\n normalData.push(x);\n normalData.push(-y); //y-inversion\n normalData.push(z);\n\n textureCoordData.push(u);\n textureCoordData.push(1. - v); //y-inversion\n\n vertexPositionData.push(radius * x);\n vertexPositionData.push(- radius * y); //y-inversion\n vertexPositionData.push(radius * z);\n }\n }\n\n const indexData = [];\n\n for (let latNumber = 0; latNumber < latitudeBands; latNumber++) {\n for (let longNumber = 0; longNumber < longitudeBands; longNumber++) {\n const first = (latNumber * (longitudeBands + 1)) + longNumber;\n const second = first + longitudeBands + 1;\n\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n }\n }\n\n //setup model\n model.vertices(vertexPositionData);\n model.indices(indexData);\n model.normals(normalData);\n model.uvs(textureCoordData);\n\n const w = 2 * radius;\n const h = w;\n\n model.x(w).y(h);\n\n //texture (http://planetpixelemporium.com/earth.html)\n model.src(path.join(__dirname, 'sphere/moonmap1k.jpg'));\n //model.src(path.join(__dirname, 'sphere/earthmap1k.jpg'));\n\n //animate\n model.rx.anim().from(0).to(360).dur(5000).loop(-1).start();\n model.ry.anim().from(0).to(360).dur(5000).loop(-1).start();\n}", "function spindulioReiksme () {\n// let ivedimoLaukas = document.querySelector('div input');\n let r = document.querySelector('div input').value;\n let plotas= Math.PI*r*r\n\n// console.log(plotas);\ndocument.querySelector(\".apskritimo-plotas\").innerHTML = plotas;\n}", "function staciakampoPlotas(ilgis, aukstis) {\n return ilgis * aukstis;\n}", "function drawGridCentre(x,y,s,rot){\r\n ctx.save();\r\n ctx.translate(x,y);\r\n ctx.rotate(rot*Math.PI/180);\r\n drawCircle(0,0,20, colArray[0], colArray[0], 2, false, true);\r\n for(j = 0; j<7 ; j++){\r\n for(var i = 0 ; i<7 ; i++){\r\n drawRectangle(0-s/2+i*s/7,0-s/2+j*s/7, s/7,s/7,colArray[3], colArray[4],0.5, false, true);\r\n }\r\n }\r\n ctx.restore();\r\n}", "function pushCartesianFromSpherical(out, latDeg, lonDeg) {\n let latRad = (latDeg / 180.0) * Math.PI,\n lonRad = (lonDeg / 180.0) * Math.PI\n out.push(Math.cos(latRad) * Math.cos(lonRad), Math.cos(latRad) * Math.sin(lonRad), Math.sin(latRad))\n return out\n}", "function update_spheroid(path) {\n var i, n, d, dt, x0, y0, x1, y1, tx, ty, l, x2, y2, xa, ya, xb, yb;\n d = \"M{0},0\".fmt(path.heights[0]);\n for (i = 0, n = path.heights.length, dt = 2 * Math.PI / n; i < n; i += 1) {\n x0 = path.heights[(i + n - 1) % n] * Math.cos((i - 1) * dt);\n y0 = path.heights[(i + n - 1) % n] * Math.sin((i - 1) * dt);\n x1 = path.heights[i] * Math.cos(i * dt);\n y1 = path.heights[i] * Math.sin(i * dt);\n x2 = path.heights[(i + 1) % n] * Math.cos((i + 1) * dt);\n y2 = path.heights[(i + 1) % n] * Math.sin((i + 1) * dt);\n tx = x2 - x0;\n ty = y2 - y0;\n l = Math.sqrt(tx * tx + ty * ty);\n tx = tx / l;\n ty = ty / l;\n xa = x1 - SMOOTHING * tx * magnitude(x1 - x0, y1 - y0);\n ya = y1 - SMOOTHING * ty * magnitude(x1 - x0, y1 - y0);\n xb = x1 + SMOOTHING * tx * magnitude(x1 - x2, y1 - y2);\n yb = y1 + SMOOTHING * ty * magnitude(x1 - x2, y1 - y2);\n d += \"C{0},{1} {2},{3} {4},{5}\".fmt(xa, ya, x1, y1, xb, yb);\n }\n path.setAttribute(\"d\", d);\n }", "axisPlot() {\n this.ctx = this.canvas.getContext(\"2d\");\n\n /**\n * Grid grid\n */\n if (this.grid.grid) {\n this.ctx.beginPath();\n this.ctx.font = 'italic 18pt Calibri';\n this.ctx.strokeStyle = '#979797';\n this.ctx.lineWidth = 1;\n this.ctx.setLineDash([10, 15]);\n for (let i = 30; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldY(i)*1000)/1000, 0, i);\n this.ctx.moveTo(0, i);\n this.ctx.lineTo(this.field.width, i);\n }\n for (let i = 100; i < this.field.width; i+= 100) {\n this.ctx.fillText(Math.ceil(this.ScreenToWorldX(i)*1000)/1000, i, this.field.height);\n this.ctx.moveTo(i, 0);\n this.ctx.lineTo(i, this.field.height);\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n /**\n * Grid axiss\n */\n if (this.grid.axiss) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#b10009';\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n this.ctx.moveTo(this.center.x, 0);\n this.ctx.lineTo(this.center.x, this.field.height);\n\n this.ctx.moveTo(0, this.center.y);\n this.ctx.lineTo(this.field.width, this.center.y);\n\n this.ctx.stroke();\n this.ctx.closePath();\n }\n\n\n if (this.grid.serifs) {\n this.ctx.beginPath();\n this.ctx.strokeStyle = '#058600';\n this.ctx.fillStyle = '#888888'\n this.ctx.lineWidth = 2;\n this.ctx.setLineDash([]);\n\n let start = 0;\n if (!this.grid.serifsStep){\n return;\n }\n\n let s = Math.abs(\n this.ScreenToWorldY(0) -\n this.ScreenToWorldY(this.grid.serifsSize)\n );\n\n /**\n * To right & to left\n */\n if ((this.center.y > 0) && (this.center.y < this.field.height)) {\n\n let finish = this.ScreenToWorldX(this.field.width);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo(i+this.grid.serifsStep/2,(s/2));\n this.lineTo(i+this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(i+this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i+this.grid.serifsStep,s);\n this.lineTo(i+this.grid.serifsStep,-s);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(i+this.grid.serifsStep), this.WorldToScreenY(s));\n }\n\n finish = this.ScreenToWorldX(0);\n\n for (let i = start; i > finish; i-=this.grid.serifsStep) {\n this.moveTo(i-this.grid.serifsStep/2,(s/2));\n this.lineTo(i-this.grid.serifsStep/2,-(s/2));\n this.ctx.fillText(i-this.grid.serifsStep/2, this.WorldToScreenX(i-this.grid.serifsStep/2), this.WorldToScreenY(s/2));\n\n this.moveTo(i-this.grid.serifsStep,s);\n this.lineTo(i-this.grid.serifsStep,-s);\n this.ctx.fillText(i-this.grid.serifsStep, this.WorldToScreenX(i-this.grid.serifsStep), this.WorldToScreenY(s));\n }\n }\n\n /**\n * To top & to bot\n */\n if ((this.center.x > 0) && (this.center.x < this.field.width)) {\n\n start = 0;\n let finish = this.ScreenToWorldY(0);\n\n for (let i = start; i < finish; i+=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo(-s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n\n finish = this.ScreenToWorldY(this.field.width);\n\n for (let i = start; i > finish-this.grid.serifsStep; i-=this.grid.serifsStep) {\n this.moveTo((s/2),i+this.grid.serifsStep/2);\n this.lineTo(-(s/2),i+this.grid.serifsStep/2);\n this.ctx.fillText(i+this.grid.serifsStep/2, this.WorldToScreenX(s/2), this.WorldToScreenY(i+this.grid.serifsStep/2));\n\n this.moveTo(s, i+this.grid.serifsStep);\n this.lineTo( -s, i+this.grid.serifsStep);\n this.ctx.fillText(i+this.grid.serifsStep, this.WorldToScreenX(s), this.WorldToScreenY(i+this.grid.serifsStep));\n }\n }\n this.ctx.stroke();\n this.ctx.closePath();\n }\n }", "static astroToSpherical( dist, decl, ra, sph ) {\n\n\t\tsph = sph || new Spherical();\n\t\tsph.set( dist,\n\t\t\t\t Math.PI / 2 - Utils.radians( decl ),\n\t\t\t\t Utils.radians( ra ) - Math.PI / 2 );\n\t\treturn sph;\n\n\t}", "function sphericalDistance(a, b) {\n\t var x = lonToMeters(a[0] - b[0], (a[1] + b[1]) / 2),\n\t y = latToMeters(a[1] - b[1]);\n\t return Math.sqrt((x * x) + (y * y));\n\t}", "function plot() {\n\n}", "function Sphere(gl, position = [0, 0, 0]) {\n\n\t// Shader program\n\tif (Sphere.shaderProgram === undefined) {\n\t\tSphere.shaderProgram = initShaderProgram(gl, \"vertex-shader\", \"fragment-shader\");\n\t\tif (Sphere.shaderProgram === null) {\n\t\t\tthrow new Error('Creating the shader program failed.');\n\t\t}\n\t\tSphere.locations = {\n\t\t\tattribute: {\n\t\t\t\tvertPosition: gl.getAttribLocation(Sphere.shaderProgram, \"vertPosition\"),\n\t\t\t\tvertColor: gl.getAttribLocation(Sphere.shaderProgram, \"vertColor\"),\n\t\t\t\taNormal: gl.getAttribLocation(Sphere.shaderProgram, \"aNormal\"),\n\t\t\t},\n\t\t\tuniform: {\n\t\t\t\tmMatrix: gl.getUniformLocation(Sphere.shaderProgram, \"mMatrix\"),\n\t\t\t\twMatrix: gl.getUniformLocation(Sphere.shaderProgram, \"wMatrix\"),\n\t\t\t\tvMatrix: gl.getUniformLocation(Sphere.shaderProgram, \"vMatrix\"),\n\t\t\t\tmMatrixInv: gl.getUniformLocation(Sphere.shaderProgram, \"mMatrixInv\"),\n\t\t\t\tpMatrix: gl.getUniformLocation(Sphere.shaderProgram, \"pMatrix\"),\n\t\t\t\tpLight: gl.getUniformLocation(Sphere.shaderProgram, \"pLight\"),\n\t\t\t\tcamera: gl.getUniformLocation(Sphere.shaderProgram, \"camera\"),\n\t\t\t\tspecularEnabled: gl.getUniformLocation(Sphere.shaderProgram, \"specularEnabled\"),\n\t\t\t\tphong: gl.getUniformLocation(Sphere.shaderProgram, \"phong\")\n\t\t\t}\n\t\t};\n\t\tgl.enableVertexAttribArray(Sphere.locations.attribute.vertPosition);\n\t\tgl.enableVertexAttribArray(Sphere.locations.attribute.vertColor);\n\t\tgl.enableVertexAttribArray(Sphere.locations.attribute.aNormal);\n\t}\n\n\t// Buffers\n\tif (Sphere.buffers === undefined) {\n\t\t// Create a buffer with the vertex positions\n\t\t// 3 coordinates per vertex, 3 vertices per triangle\n\t\t// 2 triangles make up the ground plane, 4 triangles make up the sides\n\t\tconst pBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, pBuffer);\n\n\n\t\t// Position vertices\n\t\tlet limit = 33;\n\t\tlet i, hi, si, ci;\n\t\tlet j, hj, sj, cj;\n\t\tlet p1, p2;\n\n\t\tlet vertices = [];\n\t\tlet normals = [];\n\t\tfor (let j = 0; j <= limit; j++) {\n\t\t\thj = j * Math.PI / limit;\n\t\t\tsj = Math.sin(hj);\n\t\t\tcj = Math.cos(hj);\n\t\t\tfor (let i = 0; i <= limit; i++) {\n\t\t\t\thi = i * 2 * Math.PI / limit;\n\t\t\t\tsi = Math.sin(hi);\n\t\t\t\tci = Math.cos(hi);\n\n\t\t\t\t// 0.77 to minimize the sphere\n\t\t\t\tvertices.push(ci * sj * 0.77); // X\n\t\t\t\tvertices.push(cj * 0.77); // Y\n\t\t\t\tvertices.push(si * sj * 0.77); // Z\n\n\t\t\t\tnormals.push(ci*sj);\n\t\t\t\tnormals.push(cj);\n\t\t\t\tnormals.push(si*sj);\n\t\t\t}\n\t\t}\n\n\t\tgl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\t\tpBuffer.itemSize = 3;\n\t\tpBuffer.numItems = vertices.length;\n\n\n\t\t// Indices\n\t\tlet indices = []\n\t\tlet iBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iBuffer);\n\t\tfor (j = 0; j < limit; j++) {\n\t\t\tfor (i = 0; i < limit; i++) {\n\t\t\t\tp1 = j * (limit + 1) + i;\n\t\t\t\tp2 = p1 + (limit + 1);\n\n\t\t\t\tindices.push(p1);\n\t\t\t\tindices.push(p2);\n\t\t\t\tindices.push(p1 + 1);\n\n\t\t\t\tindices.push(p1 + 1);\n\t\t\t\tindices.push(p2);\n\t\t\t\tindices.push(p2 + 1);\n\t\t\t}\n\t\t}\n\n\t\tgl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\t\tiBuffer.itemSize = 3;\n\t\tiBuffer.numItems = indices.length;\n\n\n\t\t// Color\n\t\tlet cBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, cBuffer);\n\t\tlet colors = [];\n\n\t\tfor (let i = 0; i <= limit; i++) {\n\t\t\tfor (let j = 0; j <= limit; j++) {\n\t\t\t\tcolors.push(0);\n\t\t\t\tcolors.push(0);\n\t\t\t\tcolors.push(0.99);\n\t\t\t}\n\t\t}\n\t\tgl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\t\tcBuffer.itemSize = 3;\n\t\tcBuffer.numitems = colors.length;\n\n\n\t\t// Lines\n\t\tconst lBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, lBuffer);\n\n\t\tlet lineVertices = [\n\t\t\t0.0, 1.1, 0.0,\n\t\t\t0.0, -1.1, 0.0,\n\n\t\t\t1.1, 0.0, 0.0,\n\t\t\t-1.1, 0.0, 0.0,\n\n\t\t\t0.0, 0.0, 1.1,\n\t\t\t0.0, 0.0, -1.1\n\t\t];\n\t\tgl.bufferData(gl.ARRAY_BUFFER, new Float32Array(lineVertices), gl.STATIC_DRAW);\n\t\tlBuffer.itemSize = 3;\n\t\tlBuffer.numItems = 6;\n\n\n\t\tconst liBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, liBuffer);\n\n\t\tlet lineIndices = [\n\t\t\t0, 1,\n\t\t\t2, 3,\n\t\t\t4, 5\n\t\t];\n\t\tgl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(lineIndices), gl.STATIC_DRAW);\n\t\tliBuffer.itemSize = 1;\n\t\tliBuffer.numItems = 6;\n\n\t\tconst lcBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, lcBuffer);\n\n\t\tlet lineColors = [\n\t\t\t0.0, 1.0, 0.0, 1.0,\n\t\t\t0.0, 1.0, 0.0, 1.0,\n\n\t\t\t1.0, 0.0, 0.0, 1.0,\n\t\t\t1.0, 0.0, 0.0, 1.0,\n\n\t\t\t0.0, 0.0, 1.0, 1.0,\n\t\t\t0.0, 0.0, 1.0, 1.0\n\t\t];\n\t\tgl.bufferData(gl.ARRAY_BUFFER, new Float32Array(lineColors), gl.STATIC_DRAW);\n\t\tlcBuffer.itemSize = 4;\n\t\tlcBuffer.numItems = 6;\n\n\n\t\t//Create a buffer with the normals\n\t\tconst nBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, nBuffer);\n\t\tgl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);\n\n\n\t\tSphere.buffers = {\n\t\t\tpBuffer: pBuffer,\n\t\t\tcBuffer: cBuffer,\n\t\t\tnBuffer: nBuffer,\n\t\t\tlBuffer: lBuffer,\n\t\t\tiBuffer: iBuffer,\n\t\t\tliBuffer: liBuffer,\n\t\t\tlcBuffer: lcBuffer,\n\t\t\tpComponents: 3,\n\t\t\tcComponents: 3,\n\t\t\tnComponents: 3,\n\t\t};\n\t}\n\n\t// Object Variables\n\tthis.lcPosition = position;\n\tthis.scale = [1, 1, 1];\n\n\tthis.mMatrix = mat4.create();\n\tthis.lcMatrix = mat4.create();\n\tthis.mMatrixInv = mat3.create();\n\tthis.selected = false;\n\tthis.global = false;\n\n\t// Object draw function\n\tthis.draw = function (gl, pMatrix, vMatrix) {\n\t\tgl.useProgram(Sphere.shaderProgram);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.pMatrix, false, pMatrix);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.mMatrix, false, this.mMatrix);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.wMatrix, false, wMatrix);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.vMatrix, false, vMatrix);\n\t\tgl.uniformMatrix3fv(Sphere.locations.uniform.mMatrixInv, false, this.mMatrixInv);\n\t\tgl.uniform3fv(Sphere.locations.uniform.pLight, lightPosition);\n\t\tgl.uniform3fv(Sphere.locations.uniform.camera, [0, -10, 0]);\n\t\tgl.uniform1f(Sphere.locations.uniform.specularEnabled, specularEnabled);\n\t\tgl.uniform1f(Sphere.locations.uniform.phong, phong);\n\t\tgl.uniform4fv(Sphere.locations.uniform.uColor, [1.0, 0.0, 0.0, 1.0]);\n\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.pBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.vertPosition, Sphere.buffers.pComponents, gl.FLOAT, false, 0, 0);\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.cBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.vertColor, Sphere.buffers.cComponents, gl.FLOAT, false, 0, 0);\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.nBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.aNormal, Sphere.buffers.nComponents, gl.FLOAT, false, 0, 0);\n\n\t\tgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Sphere.buffers.iBuffer);\n\t\tgl.drawElements(gl.TRIANGLES, Sphere.buffers.iBuffer.numItems, gl.UNSIGNED_SHORT, 0);\n\n\t\tgl.drawArrays(gl.TRIANGLES, 0, 18);\n\t};\n\n\n\t// Object drawLines function which are displayed as local coordinates in colors R for x, G for y and B for z axis\n\tthis.drawLines = function (gl, pMatrix) {\n\t\tgl.useProgram(Sphere.shaderProgram);\n\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.lBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.vertPosition, Sphere.buffers.lBuffer.itemSize, gl.FLOAT, false, 0, 0);\n\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.lcBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.vertColor, Sphere.buffers.lcBuffer.itemSize, gl.FLOAT, false, 0, 0);\n\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, Sphere.buffers.nBuffer);\n\t\tgl.vertexAttribPointer(Sphere.locations.attribute.aNormal, Sphere.buffers.nComponents, gl.FLOAT, false, 0, 0);\n\n\n\t\tgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Sphere.buffers.liBuffer);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.pMatrix, false, pMatrix);\n\t\tgl.uniformMatrix4fv(Sphere.locations.uniform.mMatrix, false, this.lcMatrix);\n\n\t\tgl.drawElements(gl.LINES, Sphere.buffers.liBuffer.numItems, gl.UNSIGNED_SHORT, 0);\n\t};\n\n\tthis.start = function () {\n\t\tmat4.translate(this.mMatrix, this.mMatrix, this.lcPosition);\n\t\tmat4.translate(this.lcMatrix, this.lcMatrix, this.lcPosition);\n\t};\n\n\tthis.update = function (x, y, z, position = [0, 0, 0], scale = [1, 1, 1]) {\n\t\t// Global transformations\n\t\tif (this.global) {\n\t\t\t// Move the Object to the center\n\t\t\tmat4.identity(this.mMatrix);\n\t\t\t// Transform the object\n\t\t\tmat4.scale(this.mMatrix, this.mMatrix, scale);\n\t\t\tmat4.rotateX(this.mMatrix, this.mMatrix, x);\n\t\t\tmat4.rotateY(this.mMatrix, this.mMatrix, y);\n\t\t\tmat4.rotateZ(this.mMatrix, this.mMatrix, z);\n\t\t\tmat4.translate(this.mMatrix, this.mMatrix, position);\n\n\t\t\t// Multiply with Local Coordinates to get to the right position\n\t\t\tmat4.multiply(this.mMatrix, this.mMatrix, this.lcMatrix);\n\n\t\t\t// Move Local Coordinates where the object is\n\t\t\tmat4.identity(this.lcMatrix);\n\t\t\tmat4.multiply(this.lcMatrix, this.lcMatrix, this.mMatrix);\n\t\t}\n\t\t// Local transformations\n\t\telse {\n\t\t\t// Transform Object\n\t\t\tmat4.translate(this.mMatrix, this.mMatrix, position);\n\t\t\tmat4.rotateX(this.mMatrix, this.mMatrix, x);\n\t\t\tmat4.rotateZ(this.mMatrix, this.mMatrix, z);\n\t\t\tmat4.rotateY(this.mMatrix, this.mMatrix, y);\n\t\t\tmat4.scale(this.mMatrix, this.mMatrix, scale);\n\n\t\t\t// Transform Local Coordinates\n\t\t\tmat4.translate(this.lcMatrix, this.lcMatrix, position);\n\t\t\tmat4.rotateX(this.lcMatrix, this.lcMatrix, x);\n\t\t\tmat4.rotateZ(this.lcMatrix, this.lcMatrix, z);\n\t\t\tmat4.rotateY(this.lcMatrix, this.lcMatrix, y);\n\t\t\tmat4.scale(this.lcMatrix, this.lcMatrix, scale);\n\t\t}\n\t\tmat3.normalFromMat4(this.mMatrixInv, this.mMatrix);\n\t};\n}", "function drawScene(){\n\n\tvar radius = params.size*Math.sqrt(2)/4.\n\n\t//draw the full spheres (this should be from an input file)\n\t//corners\n\tvar p1 = new THREE.Vector3(0, \t\t\t\t0, \t\t\t\t0);\n\tvar p2 = new THREE.Vector3(params.size, \t0, \t\t\t\t0);\n\tvar p3 = new THREE.Vector3(0, \t\t\t\tparams.size, \t0);\n\tvar p4 = new THREE.Vector3(params.size, \tparams.size, \t0);\n\tvar p5 = new THREE.Vector3(0, \t\t\t\t0,\t\t\t\tparams.size);\n\tvar p6 = new THREE.Vector3(params.size, \t0, \t\t\t\tparams.size);\n\tvar p7 = new THREE.Vector3(0, \t\t\t\tparams.size, \tparams.size);\n\tvar p8 = new THREE.Vector3(params.size,\t\tparams.size, \tparams.size);\n\t//centers on planes\n\tvar p9 = new THREE.Vector3(0,\t\t\t\tparams.size/2.,\tparams.size/2.);\n\tvar p10 = new THREE.Vector3(params.size/2.,\t0,\t\t\t\tparams.size/2.);\n\tvar p11 = new THREE.Vector3(params.size/2.,\tparams.size/2.,\t0);\n\tvar p12 = new THREE.Vector3(params.size,\tparams.size/2.,\tparams.size/2.);\n\tvar p13 = new THREE.Vector3(params.size/2.,\tparams.size,\tparams.size/2.);\n\tvar p14 = new THREE.Vector3(params.size/2.,\tparams.size/2.,\tparams.size);\n\n\tvar allP = [p1,p2,p3,p4,p5,p6,p7,p8, p9,p10,p11,p12,p13,p14]\n\tallP.forEach(function(p){\n\t\tvar mesh = drawSphere(radius, params.sphereSegments, params.sphereSegments, params.defaultOuterOpacity, params.sphereColor, p);\n\t\tparams.spheres.push(mesh);\n\t})\n\t\n\t//half spheres\n\tvar r9 = new THREE.Vector3(0,\t\t\t\tMath.PI/2.,\t\t0);\n\tvar r10 = new THREE.Vector3(-Math.PI/2.,\t0,\t\t\t\t0);\n\tvar r11 = new THREE.Vector3(0, \t\t\t\t0,\t\t\t\t0);\n\tvar r12 = new THREE.Vector3(0, \t\t\t\t-Math.PI/2.,\t0);\n\tvar r13 = new THREE.Vector3(Math.PI/2., \t0, \t\t\t\t0);\n\tvar r14 = new THREE.Vector3(Math.PI,\t\t0,\t\t\t0);\n\n\tallP = [p9,p10,p11,p12,p13,p14]\n\tvar allR = [r9,r10,r11,r12,r13,r14]\n\tallP.forEach(function(p, i){\n\t\tvar mesh = drawHalfSphere(radius, params.sphereSegments, params.sphereSegments, params.defaultInnerOpacity, params.sphereColor, p, allR[i]);\n\t\tparams.hemiSpheres.push(mesh);\n\t})\n\n\n\tvar r1 = new THREE.Vector3(0,\t\t\t\tMath.PI/2.,\t\t0); \n\tvar r2 = new THREE.Vector3(0,\t\t\t\t0,\t\t\t\t0); \n\tvar r3 = new THREE.Vector3(Math.PI/2.,\t\tMath.PI/2.,\t\t0); \n\tvar r4 = new THREE.Vector3(Math.PI/2.,\t\t0,\t\t\t\t0);\n\tvar r5 = new THREE.Vector3(0,\t\t\t\tMath.PI/2.,\t\t-Math.PI/2.); \n\tvar r6 = new THREE.Vector3(0,\t\t\t\t-Math.PI/2.,\t0);\n\tvar r7 = new THREE.Vector3(Math.PI/2.,\t\t0,\t\t\t\tMath.PI); \n\tvar r8 = new THREE.Vector3(Math.PI,\t\t0,\t\t\t\t0); \n\tallP = [p1,p2,p3,p4,p5,p6,p7,p8]\n\tallR = [r1,r2,r3,r4,r5,r6,r7,r8]\n\tallP.forEach(function(p, i){\n\t\tvar mesh = drawQuarterSphere(radius, params.sphereSegments, params.sphereSegments, params.defaultInnerOpacity, params.sphereColor, p, allR[i]);\n\t\tparams.hemiSpheres.push(mesh);\n\t})\n\n\n\t//draw slice\n\tvar p = new THREE.Vector3(params.size,\tparams.size/2.,\tparams.size/2.); \n\tvar r = new THREE.Vector3(0,\t\t\tMath.PI/2.,\t\t0); \n\n\tvar slice = drawSlice(2.*params.size, p, r, params.sliceOpacity, params.sliceColor);\n\tparams.sliceMesh.push(slice.plane);\n\tparams.sliceMesh.push(slice.mesh);\n\n\n\t//draw the box\n\tdrawBox();\n\n\n\n\t//lights\n\taddLights()\n\n\n}", "function Sphere(center, radius, color, emission, reflectionType) {\n this.center = center;\n this.radius = radius;\n this.color = color;\n this.emission = emission;\n this.reflectionType = reflectionType; // DIFFUSE, SPECULAR, REFRACTIVE\n}", "plotRoutes() {\n for (let r of this.mapRoutes) {\n r.plotPath(this.map);\n }\n }", "function cs_geocentric_to_geodetic (cs, p) {\n\n var X =p.x;\n var Y = p.y;\n var Z = p.z;\n var Longitude;\n var Latitude;\n var Height;\n\n var W; /* distance from Z axis */\n var W2; /* square of distance from Z axis */\n var T0; /* initial estimate of vertical component */\n var T1; /* corrected estimate of vertical component */\n var S0; /* initial estimate of horizontal component */\n var S1; /* corrected estimate of horizontal component */\n var Sin_B0; /* Math.sin(B0), B0 is estimate of Bowring aux variable */\n var Sin3_B0; /* cube of Math.sin(B0) */\n var Cos_B0; /* Math.cos(B0) */\n var Sin_p1; /* Math.sin(phi1), phi1 is estimated latitude */\n var Cos_p1; /* Math.cos(phi1) */\n var Rn; /* Earth radius at location */\n var Sum; /* numerator of Math.cos(phi1) */\n var At_Pole; /* indicates location is in polar region */\n\n X = parseFloat(X); // cast from string to float\n Y = parseFloat(Y);\n Z = parseFloat(Z);\n\n At_Pole = false;\n if (X != 0.0)\n {\n Longitude = Math.atan2(Y,X);\n }\n else\n {\n if (Y > 0)\n {\n Longitude = HALF_PI;\n }\n else if (Y < 0)\n {\n Longitude = -HALF_PI;\n }\n else\n {\n At_Pole = true;\n Longitude = 0.0;\n if (Z > 0.0)\n { /* north pole */\n Latitude = HALF_PI;\n }\n else if (Z < 0.0)\n { /* south pole */\n Latitude = -HALF_PI;\n }\n else\n { /* center of earth */\n Latitude = HALF_PI;\n Height = -cs.b;\n return;\n }\n }\n }\n W2 = X*X + Y*Y;\n W = Math.sqrt(W2);\n T0 = Z * AD_C;\n S0 = Math.sqrt(T0 * T0 + W2);\n Sin_B0 = T0 / S0;\n Cos_B0 = W / S0;\n Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;\n T1 = Z + cs.b * cs.ep2 * Sin3_B0;\n Sum = W - cs.a * cs.es * Cos_B0 * Cos_B0 * Cos_B0;\n S1 = Math.sqrt(T1*T1 + Sum * Sum);\n Sin_p1 = T1 / S1;\n Cos_p1 = Sum / S1;\n Rn = cs.a / Math.sqrt(1.0 - cs.es * Sin_p1 * Sin_p1);\n if (Cos_p1 >= COS_67P5)\n {\n Height = W / Cos_p1 - Rn;\n }\n else if (Cos_p1 <= -COS_67P5)\n {\n Height = W / -Cos_p1 - Rn;\n }\n else\n {\n Height = Z / Sin_p1 + Rn * (cs.es - 1.0);\n }\n if (At_Pole == false)\n {\n Latitude = Math.atan(Sin_p1 / Cos_p1);\n }\n\n p.x = Longitude;\n p.y =Latitude;\n p.z = Height;\n return 0;\n}", "function\ntb_project_to_sphere(r, x, y)\n{\n var d, t, z;\n \n d = Math.sqrt(x*x + y*y);\n if (d < r * 0.70710678118654752440) { /* Inside sphere */\n z = Math.sqrt(r*r - d*d);\n } else { /* On hyperbola */\n t = r / 1.41421356237309504880;\n z = t*t / d;\n }\n return z;\n}", "function calcSpheric(coords, dt) {\n if (!dw.isTurnable()) return;\n var proj = dw.initProj();\n var rect = dw.viewsizeOf(),\n skyRadius = .32 * Math.sqrt((rect[2] - rect[0]) * (rect[2] - rect[0]) + (rect[3] - rect[1]) * (rect[3] - rect[1])),\n gmst = Starry.siderealTime(dt),\n skyRotationAngle = gmst / 12.0 * Math.PI;\n coords[0] /= skyRadius * Math.PI / 180;\n coords[1] /= skyRadius * Math.PI / 180;\n var cy = -proj.lat0 * 180 / Math.PI,\n cx = lat * 180 / Math.PI + skyRotationAngle * 180 / Math.PI;\n var skyproj = '+proj=ortho +units=m +a=' + proj.a + ' +b=' + proj.b + ' +lon_0=' + cx + ' +lat_0=' + cy;\n Proj4js.defs['SKY'] = skyproj;\n dw.projload['SKY'] = new Proj4js.Proj('SKY');\n var pt = dw.transformCoords('SKY', 'epsg:4326', coords);\n if (pt) {\n // backside\n pt[0] = MUtil.ang360(180 - (pt[0] - cx) + cx) * Math.PI / 180;\n pt[1] = pt[1] * Math.PI / 180;\n }\n return pt;\n}", "display() {\n strokeWeight(1);\n stroke(200);\n fill(200);\n beginShape();\n for (let i = 0; i < this.surface.length; i++) {\n let v = scaleToPixels(this.surface[i]);\n vertex(v.x, v.y);\n }\n vertex(width, height);\n vertex(0, height);\n endShape(CLOSE);\n }", "function createHemisphereGeometry(radius,dir,cu,cv) {\n let r = radius;\n\n var geom = new THREE.Geometry(); \n\n let points = [];\n\n let num_z_segments = 16;\n let num_xy_segments = 32;\n\n let uvs = [];\n let margin = 0.05;\n let ru = 0.25 * (1.0 - margin);\n let rv = 0.5 * (1.0 - margin);;\n\n let half_pi = Math.PI / 2.0;\n for(let s=0; s<num_z_segments; s++) {\n let zc = (s / num_z_segments) * half_pi;\n\n for(let t=0; t<num_xy_segments; t++) {\n\n // angle of rotation on xy plane in radians\n let xyc = (t / num_xy_segments) * (Math.PI * 2.0) * dir;\n\n let x = Math.cos(xyc) * Math.cos(zc) * r;\n let y = Math.sin(xyc) * Math.cos(zc) * r;\n let z = Math.sin(zc) * r * dir * (-1.0);\n\n geom.vertices.push(new THREE.Vector3(x,y,z));\n\n let u = cu + (Math.cos(xyc) * ru * (num_z_segments - s) / num_z_segments) * dir;\n let v = cv + Math.sin(xyc) * rv * (num_z_segments - s) / num_z_segments;\n uvs.push( new THREE.Vector2(u,v) );\n }\n }\n\n // Add the last one vertex to close the top of the dome\n geom.vertices.push(new THREE.Vector3(0,0,r * dir * (-1.0)));\n uvs.push( new THREE.Vector2(cu,cv) );\n\n // Faces (polygon indices)\n\n for(let s=0; s<num_z_segments-1; s++) {\n for(let t=0; t<num_xy_segments; t++) {\n //let i = ;\n let i0 = s * num_xy_segments + t;\n let i1 = s * num_xy_segments + (t+1) % num_xy_segments;\n let i2 = (s+1) * num_xy_segments + (t+1) % num_xy_segments;\n let i3 = (s+1) * num_xy_segments + t;\n geom.faces.push( new THREE.Face3(i0,i1,i2) );\n geom.faces.push( new THREE.Face3(i0,i2,i3) );\n\n geom.faceVertexUvs[0].push([ uvs[i0], uvs[i1], uvs[i2] ]);\n geom.faceVertexUvs[0].push([ uvs[i0], uvs[i2], uvs[i3] ]);\n }\n }\n\n // Close the hole\n let i2 = num_z_segments * num_xy_segments;\n for(let t=0; t<num_xy_segments; t++) {\n let i0 = (num_z_segments-1) * num_xy_segments + t;\n let i1 = (num_z_segments-1) * num_xy_segments + (t+1) % num_xy_segments;\n geom.faces.push( new THREE.Face3(i0,i1,i2) );\n geom.faceVertexUvs[0].push([ uvs[i0], uvs[i1], uvs[i2] ]);\n }\n\n return geom;\n}", "function createSphereVertices(radius,numRings,vertPerRing) {\n\tvar r = radius\n\tnumRings = numRings+1;\n\tvar phi = Math.PI/numRings;\n\tvar theta = 2*Math.PI/vertPerRing;\n\tvar vertices = []\n\tfor (var i = 0; i<numRings+1; i++) { //Should include \"ring\" for top/bot points\n\t\tvertices.push([])\n\t\t\tfor (var j = 0; j<vertPerRing; j++) {\n\t\t\t\tvar y = r*Math.cos(i*phi)\n\t\t\t\tvar x = r*Math.sin(i*phi)*Math.cos(j*theta);// + (i/2)*theta)\n\t\t\t\tvar z = r*Math.sin(i*phi)*Math.sin(j*theta);// + (i/2)*theta)\n\t\t\t\t\n\t\t\t\tvertices[i].push([x,y,z])\n\t\t\t}\n\t}\n\tvar triangle_strip = [];\n\tfor (var i = 0; i<numRings; i++) {\n\t\tvar li = vertices[i].length\n\t\tvar li1 = vertices[i+1].length\n\t\ttriangle_strip = triangle_strip.concat(vertices[i][li-1])\n\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][li1-1])\n\t\tfor (var j = 0; j<vertPerRing; j++) {\n\t\t\ttriangle_strip = triangle_strip.concat(vertices[i][j])\n\t\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][j])\n\t\t}\n\t\ttriangle_strip = triangle_strip.concat(vertices[i][0])\n\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][0])\n\t}\n\tvar numItems = triangle_strip.length/3\t//based on 3-vector\n\treturn [triangle_strip,numItems]\n}", "function Sphere(center, radius, mat) {\n this.center = vec3.create(center);\n this.radius = radius;\n this.mat = mat;\n this.id = ++SPHERE_NB;\n\n gl.useProgram(shaderProgram);\n this.centerLocation = gl.getUniformLocation(shaderProgram, \"sphere\"+this.id+\"_center\");\n this.radiusLocation = gl.getUniformLocation(shaderProgram, \"sphere\"+this.id+\"_radius\");\n this.mat.createUniform(this);\n this.updateUniform = function () {\n gl.uniform3f(this.centerLocation,this.center[0],this.center[1],this.center[2]);\n gl.uniform1f(this.radiusLocation,this.radius);\n this.mat.updateUniform();\n };\n this.updateUniform();\n\n this.move = function (direction){\n this.center[0] += direction[0];\n this.center[1] += direction[1];\n this.center[2] += direction[2];\n gl.uniform3f(this.centerLocation,this.center[0],this.center[1],this.center[2]);\n }\n}", "function draw3() {\n var a = 0.86,\n // b controls tightness and direction of spiral. b=0 is a circle \n // b->infinity the spiral approaches a straight line\n b = 0.3,\n //b = 0.5,\n rotations = 3.2,\n radius_max = DIAMETER,\n \n arms = 2,\n \n alpha = 0.5,\n beta = 1,\n \n x_0 = 0,\n sigma = 6;\n \n var theta_min = 0,\n theta_max = rotations * (Math.PI * 2);\n for (var j = 0; j < arms; j++) {\n \n \n for (var i = 0; i < PARTICLE_COUNT / arms; i++) {\n \n // Create a new star\n var star = Object.create(Star);\n \n // Create a random theta\n var theta = Math.random() * (theta_max - theta_min + 1) + theta_min\n \n // Adjust the b value based on which arm we are calculating.\n b2 = b + (0.5 * arms);\n \n // Now use the formula for the logarithmic spiral to get the radius\n var radius = Math.pow(a * Math.E, b2 * theta);\n \n // Use the quantile function (inverse cdf) of the Cauchy\n // distribution to spread the stars from the mainline\n var rad_mod = x_0 + sigma * Math.tan(Math.PI * (Math.random() - 0.5));\n //radius = radius + rad_mod;\n \n // Convert to cartesian\n star.x = (radius * Math.cos(theta)) + (DIAMETER / 2);\n star.y = (radius * Math.sin(theta)) + (DIAMETER / 2);\n \n galaxy.stars.push(star);\n \n //sys.puts(\" created star [\" + i + \"] at (\" + star.x + \",\" + star.y + \")\");\n }\n }\n \n}", "display() \n { \n this.scene.pushMatrix();\n this.semiSphere2.display();\n this.scene.popMatrix();\n }", "function plotGraph(){\n createAxis();\n // zoom.x(x).y(y);\n // console.log('setting scales');\n // console.log(x);\n // console.log(y);\n updateBoundaryGraph.setScales(x,y);\n }", "function drawDonut() {\n for (let i = 0; i <= 360; i += angleStep) {\n let x = width * sin(i);\n let y = height * cos(i);\n let z = 0;\n let center = { x, y, z };\n circlesVertices.push(createCircleVertices(center, i, 1));\n }\n drawVertices();\n}", "function zoomed() {\n\n\n \tprojection.scale(d3.event.scale);\n\n svgGroup.selectAll(\".land\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".boundary\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".saskatoon\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".saskatoonFOV\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".princegeorge\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".princegeorgeFOV\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".clyde\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".clydeFOV\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".rankin\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".rankinFOV\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".inuvik\")\n .attr(\"d\", path);\n svgGroup.selectAll(\".inuvikFOV\")\n .attr(\"d\", path);\n svgGroup.selectAll(\"#sphere\")\n .attr(\"d\", path);\n\n svgGroup.selectAll(\".circles\")\n\t\t.remove()\n\n\tdrawPoints(\"saskatoon\",\"green\");\n\tdrawPoints(\"rankin\",\"blue\");\n drawPoints(\"princegeorge\",\"red\");\n drawPoints(\"inuvik\",\"orange\");\n drawPoints(\"clyde\",\"purple\"); \n}", "show()\n{\n\t var theta = this.vel.heading() + radians(90);\n\t fill(100, 100);\n\t stroke(0);\n\t strokeWeight(1);\n\t push();\n\t translate(this.pos.x,this.pos.y);\n\t rotate(theta);\n\t beginShape();\n\t vertex(0, -this.r*2);\n\t vertex(-this.r, this.r*2);\n\t vertex(this.r, this.r*2);\n\t endShape(CLOSE);\n\t pop();\n}", "function Sphere(radius){\n return -1;\n }", "function drawShapes() {\n //reference methods: http://glmatrix.net/docs/module-mat4.html\n \n let teapotModelMatrix = glMatrix.mat4.create();\n let teapotColumnModelMatrix = glMatrix.mat4.create();\n let teapotTopModelMatrix = glMatrix.mat4.create();\n let teapotBaseModelMatrix = glMatrix.mat4.create();\n \n let sphereModelMatrix = glMatrix.mat4.create();\n let sphereColumnModelMatrix = glMatrix.mat4.create();\n let sphereTopModelMatrix = glMatrix.mat4.create();\n let sphereBaseModelMatrix = glMatrix.mat4.create();\n \n let coneModelMatrix = glMatrix.mat4.create();\n let coneColumnModelMatrix = glMatrix.mat4.create();\n let coneTopModelMatrix = glMatrix.mat4.create();\n let coneBaseModelMatrix = glMatrix.mat4.create();\n\n \n //*************************************************************************\n //Sphere-- change this orienation to influence the rest...\n transformMatrix(sphereModelMatrix, sphereModelMatrix, 't', 4, .8, 0, 0);\n transformMatrix(sphereModelMatrix, sphereModelMatrix, 's', 2, 2, 2, 0);\n transformMatrix(sphereModelMatrix, sphereModelMatrix, 'rx', 0, 0, 0, radians(-90) );\n gl.uniformMatrix4fv (program.uModelT, false, sphereModelMatrix);\n gl.bindVertexArray(mySphere.VAO);\n gl.drawElements(gl.TRIANGLES, mySphere.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Sphere Column\n transformMatrix( sphereModelMatrix, sphereColumnModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( sphereColumnModelMatrix, sphereColumnModelMatrix, 't', 0, 0, 1.5, 0 );\n transformMatrix( sphereColumnModelMatrix, sphereColumnModelMatrix, 's', 1, 1, 2.05, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, sphereColumnModelMatrix);\n gl.bindVertexArray(sphereColumn.VAO);\n gl.drawElements(gl.TRIANGLES, sphereColumn.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //sphere Column Top\n transformMatrix( sphereModelMatrix, sphereTopModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( sphereTopModelMatrix, sphereTopModelMatrix, 't', 0, 0, .5, 0 );\n transformMatrix( sphereTopModelMatrix, sphereTopModelMatrix, 's', 1.5, 1.5, .25, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, sphereTopModelMatrix);\n gl.bindVertexArray(sphereTop.VAO);\n gl.drawElements(gl.TRIANGLES, sphereTop.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //sphere Column Base\n transformMatrix( sphereModelMatrix, sphereBaseModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( sphereBaseModelMatrix, sphereBaseModelMatrix, 't', 0, 0, 2.65, 0 );\n transformMatrix( sphereBaseModelMatrix, sphereBaseModelMatrix, 's', 1.5, 1.5, .25, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, sphereBaseModelMatrix);\n gl.bindVertexArray(sphereBase.VAO);\n gl.drawElements(gl.TRIANGLES, sphereBase.indices.length, gl.UNSIGNED_SHORT, 0);\n //*************************************************************************\n \n \n //*************************************************************************\n //Teapot-- did not do anything remotely hierarchical, just eyeballed it\n transformMatrix( teapotModelMatrix, teapotModelMatrix, 'ry', 0, 0, 0, radians(180) );\n gl.uniformMatrix4fv (program.uModelT, false, teapotModelMatrix);\n gl.bindVertexArray(myTeapot.VAO);\n gl.drawElements(gl.TRIANGLES, myTeapot.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Teapot Column\n transformMatrix( teapotColumnModelMatrix, teapotColumnModelMatrix, 'rx', 0, 0, 0, radians(90) );\n transformMatrix( teapotColumnModelMatrix, teapotColumnModelMatrix, 't', 0, 0, 2.5, 0 );\n transformMatrix( teapotColumnModelMatrix, teapotColumnModelMatrix, 's', 2.2, 2.2, 4, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, teapotColumnModelMatrix);\n gl.bindVertexArray(teapotColumn.VAO);\n gl.drawElements(gl.TRIANGLES, teapotColumn.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Teapot Column Base\n transformMatrix( teapotBaseModelMatrix, teapotBaseModelMatrix, 't', 0, -4.5, 0, 0);\n transformMatrix( teapotBaseModelMatrix, teapotBaseModelMatrix, 's', 3, .5, 3, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, teapotBaseModelMatrix);\n gl.bindVertexArray(teapotBase.VAO);\n gl.drawElements(gl.TRIANGLES, teapotBase.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Teapot Column Top\n transformMatrix( teapotTopModelMatrix, teapotTopModelMatrix, 't', 0, -.25, 0, 0);\n transformMatrix( teapotTopModelMatrix, teapotTopModelMatrix, 's', 3, .5, 3, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, teapotTopModelMatrix);\n gl.bindVertexArray(teapotTop.VAO);\n gl.drawElements(gl.TRIANGLES, teapotTop.indices.length, gl.UNSIGNED_SHORT, 0);\n //*************************************************************************\n \n \n //*************************************************************************\n //Cone-- change this orienation to influence the rest...\n transformMatrix(coneModelMatrix, coneModelMatrix, 't', -4, .8, 0, 0);\n transformMatrix(coneModelMatrix, coneModelMatrix, 's', 2, 2, 2, 0);\n transformMatrix(coneModelMatrix, coneModelMatrix, 'rx', 0, 0, 0, radians(-90) );\n gl.uniformMatrix4fv (program.uModelT, false, coneModelMatrix);\n gl.bindVertexArray(myCone.VAO);\n gl.drawElements(gl.TRIANGLES, myCone.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Cone Column\n transformMatrix( coneModelMatrix, coneColumnModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( coneColumnModelMatrix, coneColumnModelMatrix, 't', 0, 0, 1.5, 0 );\n transformMatrix( coneColumnModelMatrix, coneColumnModelMatrix, 's', 1, 1, 2.05, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, coneColumnModelMatrix);\n gl.bindVertexArray(coneColumn.VAO);\n gl.drawElements(gl.TRIANGLES, coneColumn.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Cone Column Top\n transformMatrix( coneModelMatrix, coneTopModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( coneTopModelMatrix, coneTopModelMatrix, 't', 0, 0, .5, 0 );\n transformMatrix( coneTopModelMatrix, coneTopModelMatrix, 's', 1.5, 1.5, .25, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, coneTopModelMatrix);\n gl.bindVertexArray(coneTop.VAO);\n gl.drawElements(gl.TRIANGLES, coneTop.indices.length, gl.UNSIGNED_SHORT, 0);\n \n //Cone Column Base\n transformMatrix( coneModelMatrix, coneBaseModelMatrix, 'rx', 0, 0, 0, radians(180) );\n transformMatrix( coneBaseModelMatrix, coneBaseModelMatrix, 't', 0, 0, 2.65, 0 );\n transformMatrix( coneBaseModelMatrix, coneBaseModelMatrix, 's', 1.5, 1.5, .25, 0 );\n gl.uniformMatrix4fv (program.uModelT, false, coneBaseModelMatrix);\n gl.bindVertexArray(coneBase.VAO);\n gl.drawElements(gl.TRIANGLES, coneBase.indices.length, gl.UNSIGNED_SHORT, 0);\n //*************************************************************************\n \n}", "function init_latitude(gl) {\n let vertices = [];\n let color = [1, 0, 1];\n for (var i = 0; i <= 360; i += 10) {\n let j = (i * Math.PI) / 180;\n let vert = [0, R * Math.cos(j), R * Math.sin(j)]; // drawing a circle on the YZ plane\n vertices.push(vert[0], vert[1], vert[2]);\n vertices.push(color[0], color[1], color[2]);\n }\n\n let vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n let vbo = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, vbo);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // stride is 6, 3 for positions and 3 for the color\n gl.vertexAttribPointer(loc_aPosition, 3, gl.FLOAT, false, 4 * 6, 0); \n gl.enableVertexAttribArray(loc_aPosition);\n\n // stride is 6, offset in this case is 3 color elements are located after 3 position elements..\n gl.vertexAttribPointer(loc_aColor, 3, gl.FLOAT, false, 4 * 6, 4 * 3); \n gl.enableVertexAttribArray(loc_aColor);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n return { vao, n: vertices.length / 6 }; // since it has three coordinates and colors so devide by 6\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 drawPoleZeroPlot() {\n\n zPlaneContext.clearRect(0, 0, 275, 280);\n zPlaneContext.font = '12px Arial';\n\n // This helper function returns the pixel coordinates inside the $z$-plane canvas\n // for a complex number `z`.\n var coordinatesFromComplexNumber = function(z) {\n return {\n x: unitCircle.x + z.real * unitCircle.radius,\n y: unitCircle.y - z.imaginary * unitCircle.radius\n };\n };\n\n // This helper function is used to determine the multiplicity of poles or\n // zeros.\n var countMultiplicity = function(result, z) {\n var w = _.find(result, _.compose(_.partial(Complex.areEqual, z), function(w) { return w.z; }));\n if (w !== undefined) {\n w.multiplicity++;\n }\n else {\n result.push( { z: z, multiplicity: 1 });\n }\n return result;\n };\n\n // Draw a circle at each zero.\n var zerosToRender = _.reduce(filter.zeros, countMultiplicity, []);\n _.each(zerosToRender, function(zero) {\n zPlaneContext.beginPath();\n var p = coordinatesFromComplexNumber(zero.z);\n var radius = Complex.areEqual(zero.z, selection) ? 4.5 : 4.0;\n zPlaneContext.arc(p.x, p.y, radius, 0, 2 * Math.PI, false);\n zPlaneContext.strokeStyle = Complex.areEqual(zero.z, hover) ? '#00677e' : '#00374e';\n zPlaneContext.lineWidth = Complex.areEqual(zero.z, selection) ? 3.0 : 2.0;\n zPlaneContext.stroke();\n if (zero.multiplicity > 1) {\n zPlaneContext.fillText(zero.multiplicity, p.x + 5, p.y - 5);\n }\n });\n\n // Draw a cross at each pole.\n var polesToRender = _.reduce(filter.poles, countMultiplicity, []);\n _.each(polesToRender, function(pole) {\n zPlaneContext.beginPath();\n var p = coordinatesFromComplexNumber(pole.z);\n var radius = Complex.areEqual(pole.z, selection) ? 4.5 : 4.0;\n zPlaneContext.moveTo(p.x - radius, p.y + radius);\n zPlaneContext.lineTo(p.x + radius, p.y - radius);\n zPlaneContext.moveTo(p.x - radius, p.y - radius);\n zPlaneContext.lineTo(p.x + radius, p.y + radius);\n zPlaneContext.strokeStyle = Complex.areEqual(pole.z, hover) ? '#00677e' : '#00374e';\n zPlaneContext.lineWidth = Complex.areEqual(pole.z, selection) ? 3.0 : 2.0;\n zPlaneContext.stroke();\n if (pole.multiplicity > 1) {\n zPlaneContext.fillText(pole.multiplicity, p.x + 5, p.y - 5);\n }\n });\n }", "function ParaGeometry(parameter,scale)\n{\n var x = parameter.x*UnitOf(parameter.lunit)*scale; \n\tvar y = parameter.y*UnitOf(parameter.lunit)*scale; \n\tvar z = parameter.z*UnitOf(parameter.lunit)*scale; \n\tvar alpha = parameter.alpha*UnitOf(parameter.aunit)/UnitOf('deg');\n\tvar theta = parameter.theta*UnitOf(parameter.aunit)/UnitOf('deg');\n\tvar phi = parameter.phi*UnitOf(parameter.aunit)/UnitOf('deg'); \n\n var fDx = x/2;\n var fDy = y/2;\n var fDz = z/2;\n \n alpha=Math.min(alpha,360);\n alpha=Math.PI*alpha/180;\n\n theta=Math.min(theta,360);\n theta=Math.PI*theta/180;\n\n phi=Math.min(phi,180);\n phi=Math.PI*phi/180;\n\n var fTalpha = Math.tan(alpha);\n var fTthetaCphi = Math.tan(theta)*Math.cos(phi);\n var fTthetaSphi = Math.tan(theta)*Math.sin(phi);\n\n \tvar geometry = new THREE.Geometry();\n\n geometry.vertices.push( new THREE.Vector3(-fDz*fTthetaCphi-fDy*fTalpha-fDx, -fDz*fTthetaSphi-fDy, -fDz));\n geometry.vertices.push( new THREE.Vector3(-fDz*fTthetaCphi-fDy*fTalpha+fDx, -fDz*fTthetaSphi-fDy, -fDz));\n geometry.vertices.push( new THREE.Vector3(-fDz*fTthetaCphi+fDy*fTalpha-fDx, -fDz*fTthetaSphi+fDy, -fDz));\n geometry.vertices.push( new THREE.Vector3(-fDz*fTthetaCphi+fDy*fTalpha+fDx, -fDz*fTthetaSphi+fDy, -fDz));\n geometry.vertices.push( new THREE.Vector3(+fDz*fTthetaCphi-fDy*fTalpha-fDx, +fDz*fTthetaSphi-fDy, +fDz));\n geometry.vertices.push( new THREE.Vector3(+fDz*fTthetaCphi-fDy*fTalpha+fDx, +fDz*fTthetaSphi-fDy, +fDz));\n geometry.vertices.push( new THREE.Vector3(+fDz*fTthetaCphi+fDy*fTalpha-fDx, +fDz*fTthetaSphi+fDy, +fDz));\n geometry.vertices.push( new THREE.Vector3(+fDz*fTthetaCphi+fDy*fTalpha+fDx, +fDz*fTthetaSphi+fDy, +fDz));\n\n geometry.faces.push( new THREE.Face3(0,2,1) );\n geometry.faces.push( new THREE.Face3(2,3,1) );\n\n geometry.faces.push( new THREE.Face3(4,5,6) );\n geometry.faces.push( new THREE.Face3(5,7,6) );\n\n geometry.faces.push( new THREE.Face3(0,1,4) );\n geometry.faces.push( new THREE.Face3(1,5,4) );\n\n geometry.faces.push( new THREE.Face3(2,6,7) );\n geometry.faces.push( new THREE.Face3(7,3,2) );\n\n geometry.faces.push( new THREE.Face3(0,4,2) );\n geometry.faces.push( new THREE.Face3(4,6,2) );\n\n geometry.faces.push( new THREE.Face3(1,3,7) );\n geometry.faces.push( new THREE.Face3(7,5,1) );\n\n return geometry;\n\n}", "function testSphere(){\n \"use strict\";\n\n let testspheregeo = new THREE.SphereGeometry(1.0,24,24);\n let testspheremat = new THREE.MeshPhongMaterial( {color: new THREE.Color(0.1,0.3,0.1) } );\n let testsphere = new THREE.Mesh(testspheregeo, testspheremat);\n testsphere.position.set(2.0,3.0,5.0);\n testsphere.castShadow = true;\n scene.add(testsphere);\n\n testsphere.animate = function () { this.rotation.y -= 0.01; this.position.y+=0.01 * Math.sin(this.rotation.y); }\n animateobjects.push(testsphere);\n}", "function draw() {\n \n\tvar red = 0; // Color value defined\n\tvar green = 1;\n\tvar blue = 2;\n\tvar alpha = 3;\n\n\tvar iter = 81;\n\n\tif(os){ // if oscillation is set true by oscillate(), then do oscilation of \n\t\t\t\t\t\t\t\t\t\t// julia set by using sin(angle) to set real c and cos(angle) to set imaginary c.\n\t\tcx =0.7885*cos(angle);\n\t\tcy =0.7785*sin(angle);\n\t\tangle+= 0.04;\n\t}\n\n\tvar zy = 0.0;\n\tvar zx = 0.0;\n\n loadPixels(); \n\n\n // Interate through the window demision. 'width' and 'hieght' are the with and height of our window\n for (var y = 0; y < height; y++) {\n\n for (var x = 0; x < width; x++) {\n\n\t zy = map(y, 0, height, min_i , max_i); // use map() to scale the range so it will be from \n\t\tzx = map(x, 0, width, minReal, maxReal); // minReal to maxReal and min_i to max_i\n\t\t\n\t\tif(!os && !clicked){ // if neither of 'os' or 'clicked' is true, cy and cx (real and imaginary c) will be the scale of zy and zx.\n\t\t\tcy = zy;\n\t\t\tcx = zx;\n\t\t}\n\t\t\n var counter= 0;\n\n\t\t// calculate the mandelbrot / julia set using:\n\t\t// mandelbrot: f(z) = z^2 + c where c is changing\n\t\t// julia: f(z) = z^2 + c where c is constant\n\t\twhile ((zx * zx + (zy * zy) < 16.0) && counter < iter) {\n\n\t\t\tvar zx_temp = zx * zx - zy * zy +cx\n\n\t\t\tzy = 2.0 * zx * zy+cy;\n\t\t\tzx = zx_temp;\n\n\t\t\t++counter;\n\t\t}\n\t\t\n\t var color = 255;\n\n\t\tif(counter !=iter){\n\t\t\tcolor = counter;\n\t\t}\n\n var pix = (x + y * width) * 4;\n\n pixels[pix + red] = sin(color)%255; // set pixels\n pixels[pix + green] = color;\n pixels[pix + blue] = color;\n\n pixels[pix+alpha] = 255;\n }\n }\n\n updatePixels(); \n}", "render() {\n MapPlotter.setUpFilteringButtons();\n MapPlotter.readFiltersValues();\n\n MapPlotter.currentStateName = 'Texas';\n MapPlotter.drawRaceDoughnut();\n\n MapPlotter.drawMap();\n }", "function Figure() {\n geometry = new THREE.ParametricGeometry(figureShoeSurface, 100, 100);\n geometry.center();\n}", "function Figure() {\n geometry = new THREE.ParametricGeometry(figureShoeSurface, 100, 100);\n geometry.center();\n}", "function drawQuarterSphere(radius, widthSegments, heightSegments, opacity, color, position, rotation){\n\tvar sphere = new THREE.SphereGeometry(radius, widthSegments, heightSegments, 0, Math.PI/2., 0, Math.PI/2.)\n\tvar circle1 = new THREE.CircleGeometry(radius, widthSegments, 0., Math.PI/2.)\n\tvar circle2 = new THREE.CircleGeometry(radius, widthSegments, 0., Math.PI/2.)\n\tvar circle3 = new THREE.CircleGeometry(radius, widthSegments, 0., Math.PI/2.)\n\n\tvar sphereMesh = new THREE.Mesh(sphere);\n\n\tvar circle1Mesh = new THREE.Mesh(circle1);\n\tcircle1Mesh.rotation.set(0, 0, Math.PI/2.);\n\n\tvar circle2Mesh = new THREE.Mesh(circle2);\n\tcircle2Mesh.rotation.set(Math.PI/2., 0, Math.PI/2.);\n\n\tvar circle3Mesh = new THREE.Mesh(circle3);\n\tcircle3Mesh.rotation.set(Math.PI/2., Math.PI/2., 0);\n\n\tvar singleGeometry = new THREE.Geometry();\n\n\tsphereMesh.updateMatrix(); // as needed\n\tsingleGeometry.merge(sphereMesh.geometry, sphereMesh.matrix);\n\n\tcircle1Mesh.updateMatrix(); // as needed\n\tsingleGeometry.merge(circle1Mesh.geometry, circle1Mesh.matrix);\n\n\tcircle2Mesh.updateMatrix(); // as needed\n\tsingleGeometry.merge(circle2Mesh.geometry, circle2Mesh.matrix);\n\n\tcircle3Mesh.updateMatrix(); // as needed\n\tsingleGeometry.merge(circle3Mesh.geometry, circle3Mesh.matrix);\n\n\tvar material = new THREE.MeshPhongMaterial( { \n\t\tcolor: color, \n\t\tflatShading: false, \n\t\ttransparent:true,\n\t\t//shininess:50,\n\t\topacity:opacity, \n\t\tside:THREE.DoubleSide,\n\t});\n\n\tvar mesh = new THREE.Mesh(singleGeometry, material);\n\tmesh.position.set(position.x, position.y, position.z);\n\tmesh.rotation.set(rotation.x, rotation.y, rotation.z);\n\tmesh.renderOrder = -1;\n\tparams.scene.add(mesh);\n\treturn mesh;\n\n}", "function plotUlam(poses) {\n\t\t// Determine the bounds\n\t\tvar bounds = {\n\t\t\tx: {\n\t\t\t\tmin: 0,\n\t\t\t\tmax: 0\n\t\t\t},\n\t\t\ty: {\n\t\t\t\tmin: 0,\n\t\t\t\tmax: 0\n\t\t\t}\n\t\t};\n\t\t$$.each(poses, function(pos) {\n\t\t\tif (pos.x < bounds.x.min) {\n\t\t\t\tbounds.x.min = pos.x;\n\t\t\t}\n\t\t\tif (pos.x > bounds.x.max) {\n\t\t\t\tbounds.x.max = pos.x;\n\t\t\t}\n\t\t\tif (pos.y < bounds.y.min) {\n\t\t\t\tbounds.y.min = pos.y;\n\t\t\t}\n\t\t\tif (pos.y > bounds.y.max) {\n\t\t\t\tbounds.y.max = pos.y;\n\t\t\t}\n\t\t});\n\t\tvar matrix = $$.makeArray([bounds.y.max - bounds.y.min + 1, bounds.x.max - bounds.x.min + 1], \" \");\n\t\t$$.each(poses, function(pos) {\n\t\t\tvar x = pos.x - bounds.x.min,\n\t\t\t\ty = pos.y - bounds.y.min,\n\t\t\t\tstr = \"\" + pos.ix;\n\t\t\tif (matrix[y][x] != \" \") {\n\t\t\t\tthrow new Error(\"Over-writing something!\");\n\t\t\t}\n\t\t\tmatrix[y][x] = str.substr(str.length - 1);\n\t\t});\n\t\t$$.each(matrix, \"reverse\", function(line) {\n\t\t\tconsole.log(\" \" + line.join(\"\"));\n\t\t});\n\t}", "function renderPolarGrid() {\n /*\n * Polar initialization\n */\n var xRadialTickMax = Math.max( Math.abs( xTickMin), Math.abs( xTickMax)),\n yRadialTickMax = Math.max( Math.abs( yTickMin), Math.abs( yTickMax)),\n radialTickMin = 1,\n radialTickMax = xRadialTickMax + yRadialTickMax,\n radialTickMaxSquare = xRadialTickMax * xRadialTickMax +\n yRadialTickMax * yRadialTickMax,\n gridRatio = renderAttrs.gridSpacing.y / renderAttrs.gridSpacing.x,\n isOriginVisibleInX = (xTickMin * xTickMax <= 0),\n isOriginVisibleInY = (yTickMin * yTickMax <= 0);\n \n // Set maximum of radial tick range for rendering\n while( radialTickMax * radialTickMax > radialTickMaxSquare) {\n --radialTickMax;\n }\n ++radialTickMax;\n \n // Set minimum of radial tick range for rendering\n if( !isOriginVisibleInX || !isOriginVisibleInY) {\n var xRadialTickMin = Math.min( Math.abs( xTickMin), Math.abs( xTickMax)),\n yRadialTickMin = Math.min( Math.abs( yTickMin), Math.abs( yTickMax));\n if( isOriginVisibleInX) {\n radialTickMin = yRadialTickMin;\n }\n else if( isOriginVisibleInY) {\n radialTickMin = xRadialTickMin;\n }\n else {\n // Origin not in X or Y range. Set radialTickMin from closest corner.\n var radialTickMinSquare = xRadialTickMin * xRadialTickMin +\n yRadialTickMin * yRadialTickMin;\n while( radialTickMin * radialTickMin <= radialTickMinSquare) {\n ++radialTickMin;\n }\n --radialTickMin;\n }\n }\n \n /*\n * Polar annular rendering\n */\n \n /**\n Draws an annulus of dots at 15-deg intervals.\n Based on RenderPolarGrid() in render_axis.c.\n Uses several closure variables:\n renderAttrs.radius -- the radius of the rendered dots\n renderAttrs.color -- the color of the rendered dots\n @param {Object} ctx -- the canvas context\n @param {Object} iOrigin -- the center of the annulus\n @param {Number} iRadius -- the { x, y } radius of the annulus\n */\n function renderAnnularDots(ctx, iOrigin, iRadius) {\n var latticePt, // index of 15-deg polar line (0..23)\n relativePt = { x: 0, y: 0 }, //\n dotRadius = renderAttrs.radius,\n // Lookup table so RenderPolarGrid can avoid using trig functions.\n // Each pair gives {cos,sin} values for 15-deg increments in Quadrant I.\n kCosSin15Deg = [\n { cos: 1.0, sin: 0.0 }, // 0 deg\n { cos: 0.96592582628907, sin: 0.25881904510252 }, // 15 deg\n { cos: 0.86602540378444, sin: 0.5 }, // 30 deg\n { cos: 0.70710678118655, sin: 0.70710678118655 }, // 45 deg\n { cos: 0.5, sin: 0.86602540378444 }, // 60 deg\n { cos: 0.25881904510252, sin: 0.96592582628907 }, // 75 deg\n { cos: 0.0, sin: 1.0 } // 90 deg\n ];\n \n ctx.fillStyle = renderAttrs.color;\n for( latticePt = 0; latticePt < 7; ++latticePt) {\n \n relativePt.x = iRadius.x * kCosSin15Deg[latticePt].cos;\n relativePt.y = iRadius.y * kCosSin15Deg[latticePt].sin;\n\n // Quadrant I\n drawCircleFill(ctx, { x: iOrigin.x + relativePt.x,\n y: iOrigin.y - relativePt.y }, dotRadius);\n // Quadrant II\n if( (latticePt > 0) && (latticePt < 6)) { // skip for axes\n drawCircleFill(ctx, { x: iOrigin.x - relativePt.x,\n y: iOrigin.y - relativePt.y }, dotRadius);\n }\n // Quadrant III\n drawCircleFill(ctx, { x: iOrigin.x - relativePt.x,\n y: iOrigin.y + relativePt.y }, dotRadius);\n // Quadrant IV\n if( (latticePt > 0) && (latticePt < 6)) { // skip for axes\n drawCircleFill(ctx, { x: iOrigin.x + relativePt.x,\n y: iOrigin.y + relativePt.y }, dotRadius);\n }\n }\n }\n \n // Draw annular gridlines or dots\n var renderFn = renderAttrs.grid === 'dotted'\n ? renderAnnularDots\n : drawEllipseFrame,\n i;\n for( i = 1; i <= radialTickMax; ++i) {\n var radius = { x: i * renderAttrs.gridSpacing.x,\n y: i * renderAttrs.gridSpacing.y };\n renderFn( ctx, renderAttrs.origin, radius);\n }\n \n /*\n * Polar radial rendering\n */\n \n /**\n Utility function for determining if a given radial line is visible\n given the origin placement within the canvas.\n Based on RenderPolarGrid() in render_axis.c.\n @param {Number} iTheta -- angle of the radial in radians\n @param {Array of Points} iPts -- Array of two { x, y } points\n defining the endpoints of the radial\n @param {String} iProp -- 'x' or 'y' for the coordinate to be checked\n @param {Object} iRange -- { min, max } values for the coordinate\n @returns {Boolean} True if the radial is visible and should\n be rendered, false otherwise.\n */\n function isRadialInRange( iTheta, iPts, iProp, iRange) {\n if( iTheta === 0.0) {\n return (iRange.min <= iPts[0][iProp]) && (iPts[0][iProp] <= iRange.max);\n }\n else if( iTheta > 0.0) {\n return iPts[0][iProp] > iRange.max\n ? iPts[1][iProp] <= iRange.max\n : iPts[0][iProp] >= iRange.min;\n }\n else if( iTheta < 0.0) {\n return iPts[0][iProp] < iRange.min\n ? iPts[1][iProp] >= iRange.min\n : iPts[0][iProp] <= iRange.max;\n }\n }\n \n // Draw radial gridlines\n if( renderAttrs.grid === 'gridlines') {\n var deltaTheta = Math.PI / 12.0, // increment by 15 deg\n theta0 = - 2.0 * deltaTheta, // start at -30 deg\n p0 = { x: renderAttrs.origin.x, y: renderAttrs.origin.y },\n p1 = { x: renderAttrs.origin.x, y: renderAttrs.origin.y },\n rp = [ { x: p0.x, y: p0.y }, { x: p1.x, y: p1.y } ],\n theta, tangent;\n\n // Render the radials from -30 deg to 30 deg.\n // These radials are clipped horizontally.\n p0 = { x: renderXMin - renderAttrs.origin.x,\n y: renderAttrs.origin.y };\n rp[0].x = renderXMin;\n p1.x = renderXMax - renderAttrs.origin.x;\n rp[1].x = renderXMax;\n\n for( i = 0; i < 5; ++i) {\n theta = theta0 + i * deltaTheta;\n tangent = - Math.tan( theta) * gridRatio;\n rp[0].y = renderAttrs.origin.y + p0.x * tangent;\n rp[1].y = renderAttrs.origin.y + p1.x * tangent;\n if( isRadialInRange( theta, rp, 'y',\n { min: renderYMin, max: renderYMax })) {\n drawLine( ctx, rp[0], rp[1]);\n }\n }\n \n // Render the radials from 45 deg to 135 deg.\n // Let theta be the complement of the desired angle, so that\n // we can still use tan() without dividing to find cotan().\n // These radials are clipped vertically.\n gridRatio = 1.0 / gridRatio;\n p0.y = renderYMin - renderAttrs.origin.y;\n rp[0].y = renderYMin;\n p1.y = renderYMax - renderAttrs.origin.y;\n rp[1].y = renderYMax;\n \n theta0 = 3 * deltaTheta; // start at 45 deg\n for( i = 0; i < 7; ++i) {\n theta = theta0 - i * deltaTheta;\n tangent = - Math.tan( theta) * gridRatio;\n rp[0].x = renderAttrs.origin.x + p0.y * tangent;\n rp[1].x = renderAttrs.origin.x + p1.y * tangent;\n if( isRadialInRange( theta, rp, 'x',\n { min: renderXMin, max: renderXMax })) {\n drawLine( ctx, rp[0], rp[1]);\n }\n }\n }\n }", "function createSphere(radius, hlines, vlines, color) {\n var material = new THREE.MeshPhongMaterial();\n material.color = new THREE.Color(color);\n material.wireframe = false;\n material.shininess = 100;\n var geometry_sphere = new THREE.SphereGeometry(radius, hlines, vlines);\n var ball = new THREE.Mesh(geometry_sphere, material);\n return ball;\n}" ]
[ "0.64300853", "0.631371", "0.631371", "0.6163995", "0.60776424", "0.6008311", "0.59189767", "0.58383954", "0.58289444", "0.5808101", "0.5748349", "0.5744434", "0.56139386", "0.56059897", "0.5590826", "0.5570486", "0.55594295", "0.5548546", "0.5505314", "0.54518604", "0.54491204", "0.54481673", "0.54432285", "0.54424685", "0.5420934", "0.54164815", "0.54089534", "0.54077363", "0.53985053", "0.53601867", "0.53371674", "0.53319824", "0.5317635", "0.53171897", "0.5316604", "0.531189", "0.5293096", "0.528842", "0.5282282", "0.5274708", "0.5274197", "0.5260175", "0.52582973", "0.52454656", "0.52447397", "0.5243358", "0.52334344", "0.52299136", "0.5227786", "0.52213234", "0.5209146", "0.5193235", "0.5181709", "0.5174626", "0.5161564", "0.5155097", "0.51466775", "0.5135736", "0.5131913", "0.51256764", "0.51154673", "0.51107377", "0.51023734", "0.50868696", "0.50864506", "0.5084724", "0.5075592", "0.5072381", "0.50641465", "0.5063681", "0.5054613", "0.505234", "0.50480825", "0.5042818", "0.5040686", "0.5037962", "0.5031296", "0.50144124", "0.50076514", "0.50031185", "0.50027233", "0.5001403", "0.49958244", "0.4993925", "0.49812624", "0.49741936", "0.49706975", "0.49671176", "0.49443048", "0.49423853", "0.49387807", "0.49349663", "0.49264455", "0.49262333", "0.4923863", "0.4923863", "0.491693", "0.49166143", "0.49163544", "0.49131718" ]
0.6640652
0
\ ROUTE MAP /\
function checkDataForInsert(req, res, next) { let data = req.body if (!req.user.id || !data.topic_id || !data.msg) { res.resp(403, errmsg.MISSING_DATA) } else { if (data.msg.match(regex.string_blank)) { res.resp(403, errmsg.BLANK_STRING) } if (data.msg.length > global.limit.msg) { res.resp(403, errmsg.LONG_STRING) } } let topic = new Topic() topic.import(data.topic_id) .then((result) => { if(topic.status == 1 || topic.status == 3) { res.resp(423, errmsg.ARCHIVED_TOPIC) } else next() }) .catch((err) => { res.resp(404, errmsg.ID_NOT_FOUND) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function map() {\n\n}", "function MAP() {\n\n}", "function Map() {}", "function Map() {\n\t\n}", "function Map() {\n\t\n}", "function PathMapper() {\n\t}", "function PathMapper() {\n\t}", "function ParamMap() { }", "function ParamMap() { }", "function ParamMap() {}", "function ParamMap() {}", "function ParamMap(){}", "function route() {\n this.method = this.req.method.toLowerCase();\n var n = w.map[this.method];\n if (!n) {\n this.reply4xx(404, \"no route for method: \"+this.req.method);\n this.end();\n return\n } else {\n this.url = w.dep.url.parse(this.req.url, true);\n this.query = this.url.query || {};\n this.context = {};\n for (var e in this.query) { this.context[e] = this.query[e] }\n this.context._work = this;\n this.context._js = [];\n this.context._css = [];\n \n var p = this.url.pathname.split('/');\n console.log(this.req.url, \"route to ===============> \" + this.req.method.toUpperCase(), p);\n \n for (var i = 1; i < p.length; ++i) {\n var segment = p[i];\n if (n.branches[segment]) { n = n.branches[segment]; continue };\n if (n.branches[':']) { //varname\n this.context[n.varname] = segment;\n console.log(\"//varname: \" + n.varname + \" = \" + this.context[n.varname]);\n n = n.branches[':'];\n continue\n };\n if (n.branches['*']) { //wildcard\n this.context['_location'] = p.slice(i).join('/');\n console.log(\"//wildcard: \" + this.context['_location']);\n n = n.branches['*'];\n break\n };\n this.reply4xx(404, \"no route to: \"+this.req.method+' '+this.req.url);\n this.end();\n return\n };\n };\n \n if (n.handler) {\n this.mapnode = n;\n n.handler.call(this);\n this.end();\n return\n }\n\n this.reply5xx(500, \"no handler found for: \"+this.req.method+' '+this.req.url);\n this.end();\n return\n}", "function SeleneseMapper() {\n}", "static routes() {\n\n\t\tconst keys = ['all', 'delete', 'get', 'patch', 'post', 'put'];\n\n\t\treturn MapContainer.create(...keys);\n\t}", "function InvokeDefinitionMap() {\n this.map = [];\n this.lookup_table = {}; // Just for building dictionary\n}", "function addMapping(router, mapping) {\n for (let url in mapping) {\n\n if (url.startsWith('GET ')) {\n\n let path = url.substring(4);\n router.get(path, mapping[url]);\n\n } else if (url.startsWith('POST ')) {\n\n let path = url.substring(5);\n router.post(path, mapping[url]);\n\n } else if (url.startsWith('PUT ')) {\n\n let path = url.substring(4);\n router.put(path, mapping[url]);\n\n } else if (url.startsWith('DELETE ')) {\n\n let path = url.substring(7);\n router.delete(path, mapping[url]);\n\n } else {\n console.log(`invalid URL: ${url}`);\n }\n }\n}", "function addMapping(router, mapping) {\n for (var url in mapping) {\n if (url.startsWith('GET ')) {\n var path = url.substring(4);\n router.get(path, mapping[url]);\n console.log(`register URL mapping: GET ${path}`);\n } else if (url.startsWith('POST ')) {\n var path = url.substring(5);\n router.post(path, mapping[url]);\n console.log(`register URL mapping: POST ${path}`);\n } else if (url.startsWith('PUT ')) {\n var path = url.substring(4);\n router.put(path, mapping[url]);\n console.log(`register URL mapping: PUT ${path}`);\n } else if (url.startsWith('DELETE ')) {\n var path = url.substring(7);\n router.del(path, mapping[url]);\n console.log(`register URL mapping: DELETE ${path}`);\n } else {\n console.log(`invalid URL: ${url}`);\n }\n }\n}", "map(id, source) {}", "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 mapa1(){\n // Crea un arreglo con los nodos visitados hasta ahora.\n var nodes = [\n \n {id: 1, label: 'Brasil'},\n ];\n\n // Crea un arreglo con las conexiones entre los nodos.\n var edges = [\n\n ];\n // Crea un arreglo con los nodos activos.\n var activeNode = [ 1 ];\n mapa( nodes, edges, activeNode );\n }", "function Rn(){this.seq=[],this.map={}}// --- Utilities ---", "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}", "function addMapping(router, mapping) {\n for (let url in mapping.default) {\n if (url.startsWith('GET ')) {\n var path = url.substring(4);\n router.get(path, mapping[url]);\n console.log(`register URL mapping: GET ${path}`);\n\n } else if (url.startsWith('POST ')) {\n var path = url.substring(5);\n router.post(path, mapping[url]);\n console.log(`register URL mapping: POST ${path}`);\n\n } else if (url.startsWith('PUT ')) {\n var path = url.substring(4);\n router.put(path, mapping[url]);\n console.log(`register URL mapping: PUT ${path}`);\n\n } else if (url.startsWith('DELETE ')) {\n var path = url.substring(7);\n router.del(path, mapping[url]);\n console.log(`register URL mapping: DELETE ${path}`);\n\n } else {\n console.log(`invalid URL: ${url}`);\n }\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 */\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}", "static rmap(context) {\n return Pierce.dimap(context).call(Hask.id(context));\n }", "function map(n, d1, d2, r1, r2) {\r\n\tvar Rd = d2-d1;\r\n\tvar Rr = r2-r1;\r\n\treturn (Rr/Rd)*(n - d1) + r1;\r\n}", "function map(n, d1, d2, r1, r2) {\r\n\tvar Rd = d2-d1;\r\n\tvar Rr = r2-r1;\r\n\treturn (Rr/Rd)*(n - d1) + r1;\r\n}", "function mapTest() {\n return \"Hello\"\n}", "function mapa2(){\n // Crea un arreglo con los nodos visitados hasta ahora.\n var nodes = [\n \n {id: 1, label: 'Brasil'},\n {id: 2, label: 'Finlandia'},\n\n ];\n\n // Crea un arreglo con las conexiones entre los nodos.\n var edges = [\n {from: 1, to: 2},\n ];\n // Crea un arreglo con los nodos activos.\n var activeNode = [ 2 ];\n mapa( nodes, edges, activeNode );\n }", "get Mipmaps() {}", "function map(stats) {\n return stats.path;\n}", "handleMapLoad(map) {\n }", "function sc_map(proc, l1) {\n if (l1 === undefined)\n\treturn null;\n // else\n var nbApplyArgs = arguments.length - 1;\n var applyArgs = new Array(nbApplyArgs);\n var revres = null;\n while (l1 !== null) {\n\tfor (var i = 0; i < nbApplyArgs; i++) {\n\t applyArgs[i] = arguments[i + 1].car;\n\t arguments[i + 1] = arguments[i + 1].cdr;\n\t}\n\trevres = sc_cons(proc.apply(null, applyArgs), revres);\n }\n return sc_reverseAppendBang(revres, null);\n}", "map(route) {\r\n if (Array.isArray(route)) {\r\n route.forEach(r => this.map(r));\r\n return this;\r\n }\r\n return this.mapRoute(route);\r\n }", "function WoWMapProjection(){}", "function mapPath(i) {\n return pArr[i];\n }", "function i(e,t){return(0,u.default)(t).map(function(n){var r=t[n];return(0,l.default)(r)?{name:n,direction:e,fn:r}:(0,o.default)({name:n},r)})}", "function map$4(f, param) {\n return /* Dual */[_1(f, param[0])];\n }", "function routeMap(routePath) {\n return \"https://maps.googleapis.com/maps/api/staticmap?path=color:0x0000ff|weight:5\"+\n routePath + \"&size=400x400&key=AIzaSyAH-KSfz-462dVd84424pUVWa7vO2RgfAs\";\n}", "constructor(maps = [], mirror, from2 = 0, to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from2;\n this.to = to;\n }", "function elaborateRoute(map, legs, polyline, bounds, markers,\n contentStrings, totExcitement, alg){\n if(alg==0) return elaborateDH(map, legs, polyline, bounds,\n markers, contentStrings, totExcitement);\n else if(alg==1) return elaborateNumSections(map, legs,\n polyline, bounds, markers, contentStrings, totExcitement);\n}", "function main() {\n getRoutes();\n}", "map_system() {\n\t\t// First 8K of RAM\n\t\tthis.map_loram(0x00, 0x3F, 0x0000, 0x1FFF, 0);\n\t\t// PPU regs\n\t\tthis.map_kind(0x00, 0x3F, 0x2000, 0x3FFF, 0x2000, MAP_TI.PPU);\n\t\t// CPU regs\n\t\tthis.map_kind(0x00, 0x3F, 0x4000, 0x5FFF, 0x4000, MAP_TI.CPU);\n\t\t// All of this mirrored again at 0x80\n\t\tthis.map_loram(0x80, 0xBF, 0x00, 0x1FFF, 0);\n\t\tthis.map_kind(0x80, 0xBF, 0x2000, 0x3FFF, 0x2000, MAP_TI.PPU);\n\t\tthis.map_kind(0x80, 0xBF, 0x4000, 0x5FFF, 0x4000, MAP_TI.CPU);\n\t}", "static lmap(context) {\n return new Hask(function(sa) {\n return Pierce.dimap(context).call(sa).call(Hask.id(context));\n });\n }", "_map(inputStart, inputEnd, outputStart, outputEnd, input) {\n return outputStart + ((outputEnd - outputStart) / (inputEnd - inputStart)) * (input - inputStart);\n }", "set Mipmaps(value) {}", "function LangMap() {}", "function LangMap() {}", "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 }", "mapToPath() {\n Path.mapMin1 = this.params.mapMin1;\n Path.mapMax1 = this.params.mapMax1;\n Path.mapMin2 = this.params.mapMin2;\n Path.mapMax2 = this.params.mapMax2;\n }", "getRoutingNames() {\n\n }", "function map(a,b,c,d,e){return(a-b)/(c-b)*(e-d)+d}", "function z(a){function b(b,c){this.tgt=a.getTgt(b,c)}\n// Simple map declared as function\nreturn Z(a)&&(a={getTgt:a}),a.baseMap&&(a=j(j({},a.baseMap),a)),a.map=function(a,c){return new b(a,c)},a}", "function map(value,\n istart, istop,\n ostart, ostop) {\n return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));\n}", "function initMap() {\n}", "map(value, istart, istop, ostart, ostop) {\n\t\treturn ostart + (ostop - ostart) * ((value - istart) / (istop - istart));\n\t}", "function modify()\r{\r\tvar entry = getindex(arguments[0]);\r\tvar args = new Array();\r\tfor(var i=1; i<arguments.length; i++){\r\t\targs[i-1] = arguments[i];\r\t}\r\toutlet(0, \"script\", \"send\", \"mapping_object_alg_\"+entry, args);\r}", "function processRoute (data){\n console.log(\"reitti: \", data);\n var segments = data.routes[0].segments;\n segmentNames.length = 0;\n segmentKind.length = 0;\n\tsegmentDuration.length = 0;\n \n $.each(segments, function(index, value){\n processSegments(value);\n });\n printRoute();\n preparePolyline(data);\n initMap();\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}", "mapValue(value){\r\n var map={\r\n 8: 1, 7: 2, 6: 3, 5: 4, 4: 5, 3: 6, 2: 7, 1: 8,\r\n \"h\":\"a\", \"g\":\"b\", \"f\":\"c\", \"e\":\"d\", \"d\":\"e\", \"c\":\"f\", \"b\":\"g\", \"a\":\"h\"\r\n }\r\n return(map[value])\r\n }", "function goMap(map_num){\n \n var file_name;\n \n switch (map_num){\n \n //assign parameters for respective page\n \n case 0:\n file_name = 'signup2.html';\n var params = new Array(file_name);\n params[file_name] = new Array();\n params[file_name][0] = 'name';\n params[file_name][1] = 'email';\n params[file_name][2] = 'phone';\n params[file_name][3] = 'password';\n return params;\n \n case 1:\n file_name = 'credit_card.html';\n var params = new Array(file_name);\n params[file_name] = new Array();\n params[file_name][0] = 'address';\n params[file_name][1] = 'address2';\n params[file_name][2] = 'zip';\n return params;\n \n \n case 3:\n file_name = 'sign_in.html';\n var params = new Array(file_name);\n params[file_name] = new Array();\n params[file_name][0] = 'email';\n params[file_name][1] = 'password';\n return params;\n \n }\n \n}", "function summonCaptainPlanet() {\r\n\tconsole.log(map)\r\n}", "function getRaresMap() {\n var map = {};\n var lines = require('fs').readFileSync(__dirname+'/wallabee_rares.dat').toString().split(/\\r?\\n/);\n for (var i in lines) {\n var parts = lines[i].split(/\\|/);\n parts[1] = parseInt(parts[1]);\n map[parts[0]] = parts;\n }\n return map;\n}", "function myMap(arr, cb) {\n // enter your code here\n}", "function MapTable() {\r\n}", "static mapStops(direction) {\n const out = new Map();\n const stops =\n direction === \"North\"\n ? caltrainServiceData.northStops\n : caltrainServiceData.southStops;\n for (let i = 0; i < stops.length; i++) {\n out.set(stops[i], i);\n }\n return out;\n }", "function create_map(name, code) {\n var view = '\"' + name + '\": {' + '\\n';\n view += '\"map\": \"' + escape(code) + '\"}';\n return view;\n}", "function getUserRouteMap(canonicalRoutes) {\n return canonicalRoutes.reduce((mapping, route) => {\n switch (route) {\n case 'GS':\n case 'FS':\n case 'H': {\n const newMap = { [route]: 'S' }\n return Object.assign({}, mapping, newMap)\n }\n default: {\n const newMap = { [route]: route }\n return Object.assign({}, mapping, newMap)\n }\n }\n }, {})\n}", "function Mapping(){this.generatedLine=0;this.generatedColumn=0;this.source=null;this.originalLine=null;this.originalColumn=null;this.name=null;}", "function Routes(){\n\tthis.static = require('../../static/static')();\n\tthis.routes = new Map();\n}", "function getPosMapping() {\n\tvar NOU = 0;\n\tvar PRO = 1;\n\tvar ADJ = 2;\n\tvar VER = 3;\n\tvar ADV = 4;\n\tvar PRE = 5;\n\tvar CON = 6;\n\tvar INT = 7;\n\tvar DET = 8;\n\tvar NUL = 9;\n\tvar posDict = {\"CC\":CON, \"CD\": NUL, \"DT\": DET, \"EX\": NUL, \"FW\": NUL,\n\t\t\t\t\t\"IN\": PRE, \"JJ\": ADJ, \"JJR\": ADJ, \"JJS\":ADJ,\"LS\":NUL,\n\t\t\t\t\t\"MD\":NUL, \"NN\":NOU, \"NNS\":NOU, \"NNP\":NOU,\"NNPS\":NOU,\"PDT\":NUL,\"POS\":NUL,\"PRP\":PRO,\n\t\t\t\t\t\"PRP$\":PRO,\"RB\":ADV,\"RBR\":ADV,\"RBS\":ADV,\"RP\":PRE,\"SYM\":NUL,\"TO\":PRE,\"UH\":INT,\n\t\t\t\t\t\"VB\":VER,\"VBD\":VER,\"VBG\":VER,\"VBN\":VER,\"VBP\":VER,\"VBZ\":VER,\"WDT\":DET,\"WP\":PRE,\n\t\t\t\t\t\"WP$\":PRE,\"WRB\":ADV};\n\treturn posDict;\n}", "function mapa3(){\n // Crea un arreglo con los nodos visitados hasta ahora.\n var nodes = [\n \n {id: 1, label: 'Brasil'},\n {id: 2, label: 'Finlandia'},\n {id: 3, label: 'China'},\n ];\n\n // Crea un arreglo con las conexiones entre los nodos.\n var edges = [\n {from: 1, to: 2},\n {from: 2, to: 3},\n\n \n\n ];\n // Crea un arreglo con los nodos activos.\n var activeNode = [ 3 ];\n mapa( nodes, edges, activeNode );\n}", "function\nmap0$fopr_2343_(a5x1)\n{\nlet xtmp57;\n;\n{\nxtmp57 = a1x2(a5x1);\n}\n;\nreturn xtmp57;\n}", "constructor() {\n // _routes will contain a mapping of HTTP method name ('GET', etc.) to an\n // array of all the corresponding Route instances that are registered.\n this._routes = new Map();\n }", "function arpMapping(x, y, pageId) {\n\tconst coords = {\n\t\t// midi 10\n\t\t'200 50': {alias: 'rndarp_launchcontrol', chan: 7, cc_strict: 21, type: 'fader'},\n\n '25 50': {alias: 'gate_length', chan: 10, cc: 2, type: 'fader'},\n\t\t'400 50': {alias: 'gaterate', chan: 10, cc: 3, type: '8step'},\n\n '50 500': {alias: 'attack', chan: 10, cc: 4, type: 'fader'},\n '100 500': {alias: 'decay', chan: 10, cc: 5, type: 'fader'},\n '150 500': {alias: 'sustain', chan: 10, cc: 6, type: 'fader'},\n '200 500': {alias: 'release', chan: 10, cc: 7, type: 'fader'},\n '300 525': {alias: 'volume', chan: 10, cc: 8, type: 'fader'},\n\n\t\t// midi 11\n\t\t'0 250': {alias: 'pitchon', chan: 11, cc: 1, type: 'on_off'},\n\t\t'400 200': {alias: 'pitchrate', chan: 11, cc: 2, type: '8step'},\n\t\t'400 300': {alias: 'pitchsteps', chan: 11, cc: 3, type: '8step'},\n\t\t'25 225': {alias: 'pitchhold', chan: 11, cc: 4, type: 'fader'},\n\t\t'800 200': {alias: 'pitchdist', chan: 11, cc: 5, type: 'fader'},\n\t\t'900 50': {alias: 'rnd', chan: 11, cc: 6, type: 'fader'},\n\t\t'900 200': {alias: 'scale_scale', chan: 11, cc: 8, type: 'fader' },\n\t\t'950 200': {alias: 'scale_choice', chan: 11, cc: 7, type: 'fader' },\n\t\t'200 225': {alias: 'drop', chan: 11, cc: 9, type: 'fader'},\n\n\t\t// midi 12 + 13 as fallback\n\t\t'500 500': {alias: 'delay_left', chan: 12, cc: 1, type: '8-2step'},\n\t\t'500 600': {alias: 'delay_right', chan: 13, cc: 1, type: '8-2step'},\n\n\t\t'800 500': {alias: 'delayfb', chan: 12, cc: 2, type: 'fader'},\n\t\t'850 500': {alias: 'link', chan: 13, cc: 3, type: 'on_off'},\n\t\t'900 500': {alias: 'gain', chan: 13, cc: 2, type: 'fader'},\n\t\t'950 500': {alias: 'delaymix', chan: 12, cc: 3, type: 'fader'}\n\t};\n\treturn coords[`${x} ${y}`];\n}", "map(layout){\n\t\tvar map = new Mapping(layout);\n\t\treturn map.section();\n\t}", "function runRules(vmap, cmap, rmap, start, n) {\n\n var start_str = start;\n var result = \"\";\n\n for (var j = 0; j < n; j++) {\n for (var i = 0; i < start_str.length; i++) {\n // No rule found\n if (rmap[start_str[i]] == null) {\n result += start_str[i];\n } else {\n result += rmap[start_str[i]];\n }\n }\n start_str = result;\n result = \"\";\n }\n\n return start_str;\n}", "function render() {\n debugMap(map, 10, 20);\n }", "['fantasy-land/map'](f) {\n return this.map(f);\n }", "function MapIterator() {}", "function init(){\n basemap();\n}", "match(route) {\n //match route against dictionary of defined paths to their relevant attributes\n for (let [path, {pathRoute, handler, params}] of this.routes) {\n const match = pathRoute.exec(route);\n //each route will be associated with a handler\n //this handler will handle all of the rendering associated with a new change\n if (match !== null) {\n //remove the first / from the route\n //loop through values and add each value with its associated parameter\n const routeParams = match.slice(1).\n reduce((allParams, value, index) => {\n allParams[params[index]] = value;\n return allParams;\n }, {});\n //split parameters using the ?varName=varVal \n this.currentPath = path;\n //check if we have any query parameters to parse\n if (window.location.search) {\n this.getQueryParameters(window.location.search, routeParams);\n }\n handler(route, routeParams);\n //we don't want to execute more than route once we've matched one\n //if it can match multiple ones so we break\n break;\n }\n\n }\n }", "function generateSafeInternalRouteMap() {\n const map = new Map();\n for (const keyAsString in InternalRoute_1.default) {\n const key = parseInt(keyAsString, 10);\n // skipt enum literals, use only the numeric keys\n if (isNaN(key) || !isFinite(key) || typeof key !== 'number') {\n continue;\n }\n // generate a random hash for the URL and prepend a slash so the server can resolve it\n let hash;\n const ensureUnique = () => {\n hash = generateRandomHash();\n for (const value of map.values()) {\n if (hash === value) {\n ensureUnique();\n return;\n }\n }\n };\n ensureUnique();\n // actually update the hash\n map.set(key, hash);\n }\n return map;\n}", "function getMap() {\n showJourneyMap();\n}", "generateStops (routes, reRenderKey) {\n return routes.map((route) => {\n return route.stops.map((stop, i) => {\n if (route.display) {\n // const boundPress = this.props.fetchStopData.bind(this, stop.id, route.id)\n const key = Platform.OS === 'ios' ? `${stop.id}-${reRenderKey}`: `${stop.id}`\n return (\n <MapView.Circle center={{latitude: stop.lat, longitude: stop.lng}} radius={stop.radius ? stop.radius : 10} zIndex={stop.zindex ? stop.zindex : 1} fillColor={stop.fillColor ? stop.fillColor: 'black'} strokeColor={route.routeColor}/>\n ) \n }\n })\n })\n }", "function PhoneticMapper(map)\n{\n this.map = map;\n}", "function testFunction(req, res) {\n res.render('map-test');\n\n}", "function Mapping() {\n this.generatedLine = 0\n this.generatedColumn = 0\n this.source = null\n this.originalLine = null\n this.originalColumn = null\n this.name = null\n}", "static match(map) {\n let direct = Object.create(null);\n for (let prop in map)\n for (let name of prop.split(\" \"))\n direct[name] = map[prop];\n return (node) => {\n for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {\n let found = direct[i < 0 ? node.name : groups[i]];\n if (found)\n return found;\n }\n };\n }", "_generateMap() {\n // Generate all the empty tiles\n var width = this.display.getOptions().width;\n var height = this.display.getOptions().height;\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n let tile = new Tile(\"empty\", x, y);\n let key = tile.getPositionKey();\n this.map[key] = tile;\n }\n }\n\n // Next, use celluar automata to lay down the first layer of resources\n // but make sure they meet the minimum bar\n var sumIronTiles = 0;\n while (sumIronTiles <= config.map.resources.iron.minTiles) {\n var ironMap = new ROT.Map.Cellular(width, height, { connected: true});\n // % chance to be iron\n ironMap.randomize(config.map.resources.iron.baseChance);\n // iterations smooth out and connect live tiles\n for (let i = 0; i < config.map.resources.iron.generations; i++) {\n ironMap.create();\n }\n // Check to ensure that we have a minimum number of iron tiles\n sumIronTiles = ironMap._map.flat().reduce(doSum, 0);\n }\n\n // Go through the map and change the tiles we touch to type \"iron\"\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n if (ironMap._map[x][y] == 1) {\n let key = `${x},${y}`\n let tile = this.map[key];\n let resourceAmount = this._calculateResourceAmount(x, y, ironMap._map, \"iron\");\n tile.addResources(\"iron\", resourceAmount);\n }\n }\n }\n\n // Same for coal\n var sumCoalTiles = 0;\n while (sumCoalTiles <= config.map.resources.coal.minTiles) {\n var coalMap = new ROT.Map.Cellular(width, height, { connected: true });\n coalMap.randomize(config.map.resources.coal.baseChance);\n for (let i = 0; i< config.map.resources.coal.generations; i++) {\n coalMap.create();\n }\n sumCoalTiles = coalMap._map.flat().reduce(doSum, 0);\n }\n\n // Change tiles to \"coal\", but only if they're empty!\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n if (coalMap._map[x][y] == 1) {\n let key = `${x},${y}`\n let tile = this.map[key];\n if (tile.tileType == \"empty\") {\n let resourceAmount = this._calculateResourceAmount(x, y, coalMap._map, \"coal\");\n tile.addResources(\"coal\", resourceAmount);\n }\n }\n }\n }\n\n // Same for copper\n var sumCopperTiles = 0;\n while (sumCopperTiles <= config.map.resources.copper.minTiles) {\n var copperMap = new ROT.Map.Cellular(width, height, { connected: true });\n copperMap.randomize(config.map.resources.copper.baseChance);\n for (let i = 0; i< config.map.resources.copper.generations; i++) {\n copperMap.create();\n }\n sumCopperTiles = copperMap._map.flat().reduce(doSum, 0);\n }\n\n // Change tiles to \"copper\", but only if they're empty!\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n if (copperMap._map[x][y] == 1) {\n let key = `${x},${y}`\n let tile = this.map[key];\n if (tile.tileType == \"empty\") {\n let resourceAmount = this._calculateResourceAmount(x, y, copperMap._map, \"copper\");\n tile.addResources(\"copper\", resourceAmount);\n }\n }\n }\n }\n }", "function refreshMap() {\n\t\t$.each(routes, function(i,m) {\n\t\t\tshowRouteVehicles(m.tag);\n\t\t});\n\t}", "function getMapping(idx) {\n return mapping[idx]\n}", "__init25() {this.forceRenames = new Map()}", "get routes(){\n\t\treturn {\n\t\t\t'get /': [actionFilter, 'index'],\n\t\t\t'get /home/about': 'about'\n\t\t}\n\t}", "function Map(value, from1, to1, from2, to2) {\n return (value - from1) / (to1 - from1) * (to2 - from2) + from2;\n}", "exec() {\n return _map[MMU.rb(regPC[0]++)]();\n }", "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 initializeMap(){\n let brewery1 = state.body[0];\n initMap(brewery1);\n}" ]
[ "0.68645376", "0.6628688", "0.65455055", "0.6352502", "0.6352502", "0.6338502", "0.6338502", "0.63022685", "0.63022685", "0.62968117", "0.62968117", "0.61751074", "0.6137952", "0.6093293", "0.60596484", "0.6041014", "0.5973534", "0.59055483", "0.5819673", "0.5810476", "0.5810476", "0.5714253", "0.57025236", "0.56983805", "0.56983805", "0.5696133", "0.5681549", "0.5661081", "0.5634524", "0.5634524", "0.5614651", "0.55855685", "0.55671936", "0.5560953", "0.55517304", "0.55320966", "0.5524759", "0.5522271", "0.5508456", "0.55082893", "0.5492555", "0.54821557", "0.5464685", "0.54385996", "0.54352826", "0.543207", "0.54105306", "0.5375306", "0.53708696", "0.5368987", "0.5368987", "0.5367772", "0.53511477", "0.53491277", "0.53480566", "0.5344039", "0.5330519", "0.5320954", "0.5303524", "0.5295402", "0.52941567", "0.528932", "0.5273567", "0.5272712", "0.52666795", "0.5266564", "0.5260394", "0.5249588", "0.5248639", "0.5235252", "0.5226762", "0.52253836", "0.5221467", "0.52036005", "0.5203296", "0.5199588", "0.51964355", "0.51961356", "0.51819247", "0.51758987", "0.5175409", "0.51723695", "0.5170031", "0.5169641", "0.51620775", "0.515672", "0.51488316", "0.5145472", "0.5139013", "0.51231706", "0.510709", "0.5091593", "0.5085569", "0.5085388", "0.50843906", "0.5083146", "0.50823855", "0.5081064", "0.5078971", "0.50752914", "0.50723124" ]
0.0
-1
Getter for quantity If _value is an instance of Quantity, will return object with properties number and unit Otherwise return null;
get quantity() { if (this._observation.dataValue && this._observation.dataValue.value instanceof Quantity) { return { number: this._observation.dataValue.value.number.decimal, unit: this._observation.dataValue.value.units.coding.codeValue.value, }; } else { return null; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get valueQuantity () {\r\n\t\treturn this._valueQuantity;\r\n\t}", "get valueQuantity () {\r\n\t\treturn this.__valueQuantity;\r\n\t}", "get quantity() {\n\t\treturn this.__quantity;\n\t}", "get quantity() {\n\t\treturn this.__quantity;\n\t}", "get quantity() {\n\t\treturn this.__quantity;\n\t}", "function getQuantityValueAndUnit(ob) {\n if (typeof ob != 'undefined' &&\n typeof ob.valueQuantity != 'undefined' &&\n typeof ob.valueQuantity.value != 'undefined' &&\n typeof ob.valueQuantity.unit != 'undefined') {\n return Number(parseFloat((ob.valueQuantity.value)).toFixed(2)) + ' ' + ob.valueQuantity.unit;\n } else {\n return undefined;\n }\n}", "function getQuantityFieldValue() {\n\t\treturn parseInt(quantityField.getText(), 10);\n\t}", "function getQuantityValueAndUnit(ob) {\n if (typeof ob != 'undefined' &&\n typeof ob.valueQuantity != 'undefined' &&\n typeof ob.valueQuantity.value != 'undefined' &&\n typeof ob.valueQuantity.unit != 'undefined') {\n return Number(parseFloat((ob.valueQuantity.value)).toFixed(2)) + ' ' + ob.valueQuantity.unit;\n } else {\n return undefined;\n }\n}", "function getUnitValue(u) { return (u.value != undefined) ? u.value : u; }", "function getQuantityValueAndUnit(ob) {\n if (\n typeof ob != \"undefined\" &&\n typeof ob.valueQuantity != \"undefined\" &&\n typeof ob.valueQuantity.value != \"undefined\" &&\n typeof ob.valueQuantity.unit != \"undefined\"\n ) {\n return (\n Number(parseFloat(ob.valueQuantity.value).toFixed(2)) +\n \" \" +\n ob.valueQuantity.unit\n );\n } else {\n return undefined;\n }\n}", "get detailQuantity () {\n\t\treturn this._detailQuantity;\n\t}", "get detailQuantity() {\n\t\treturn this.__detailQuantity;\n\t}", "function getItemValue(price, quantity) {\n return currency(price)\n .multiply(quantity.toString())\n .format();\n}", "get defaultValueQuantity() {\n\t\treturn this.__defaultValueQuantity;\n\t}", "function ItemQuantity(item, quantity = 1) {\n this.item = item;\n this.quantity = quantity;\n}", "getStandardConversion(quantity) {\n\t\tswitch(this.unit.toLowerCase()){\n\t\t\tcase \"seconds\": return quantity;\n\t\t\tcase \"minutes\": return quantity * 60;\n\t\t\tcase \"hours\": return quantity * (60 * 60);\n\t\t\tcase \"days\": return quantity * (24 * 60 * 60);\n\t\t\tcase \"weeks\": return quantity * (7 * 24 * 60 * 60);\n\t\t\tdefault: return null;\n\t\t}\n\t}", "function getQuantityFromInputField()\n {\n return nanCheck($('.cr_current_quantity_class').val());\n }", "quantity(amount) {\n return assay.coerce(amount).quantity;\n }", "get units() {\n return this._units;\n }", "get specimenQuantity () {\n\t\treturn this._specimenQuantity;\n\t}", "setQuantity(quantity) {\n this.quantity = quantity;\n }", "get unit () {\n\t\treturn this._unit;\n\t}", "static get __resourceType() {\n\t\treturn 'Quantity';\n\t}", "function getVal(input, key) {\n for (var i=0; i < input.length ; ++i){\n if(input[i]['size'] == key){\n return input[i]['quantity'];\n }\n }\n }", "get unit() {\n\t\treturn this.__unit;\n\t}", "get value() {\n return this.amount;\n }", "getSignalQuantity()\n {\n return parseInt(this.quantity);\n }", "get unitPrice() {\n\t\treturn this.__unitPrice;\n\t}", "calculateQuantity() {\n console.log('Calculating quantity... ');\n const symbol = this.symbol.meta;\n const minQuantity = symbol.minQty;\n const maxQuantity = symbol.maxQty;\n const quantitySigFig = symbol.quantitySigFig;\n const stepSize = symbol.stepSize; //minimum quantity difference you can trade by\n const currentPrice = this.ticker.meta.bid;\n const budget = this.config.budget;\n\n let quantity = minQuantity;\n while (quantity * currentPrice <= budget) quantity += stepSize;\n if (quantity * currentPrice > budget) quantity -= stepSize;\n if (quantity === 0) quantity = minQuantity;\n\n assert(quantity >= minQuantity && quantity <= maxQuantity, 'invalid quantity');\n\n console.log('Quantity Calculated: ', quantity.toFixed(quantitySigFig));\n return quantity.toFixed(quantitySigFig);\n }", "function getUnits(quantity) {\n var db = getDatabase();\n var res=\"\";\n db.transaction(function(tx) {\n var rs = tx.executeSql('SELECT name FROM units WHERE quantity=?;', [quantity]);\n if (rs.rows.length > 0) {\n res = rs;\n } else {\n res = \"Unknown\";\n }\n })\n // The function returns “Unknown” if the setting was not found in the database\n // For more advanced projects, this should probably be handled through error codes\n return res\n}", "function quantity(val) {\n\t return Math.pow(10, quantityExponent(val));\n\t }", "toFormattedQuantityUnit(value) {\n if (value >= 1000000)\n return format('%.2fM', value / 1000000);\n else if (value >= 1000)\n return format('%.2fk', value / 1000);\n else\n return format('%.2f', value);\n }", "constructor(ticker, quantity, currentValue) {\n this.ticker = ticker;\n this.quantity = quantity == null ? null : quantity;\n this.currentPrice = null;\n this.high = null;\n this.low = null;\n this.currentValue = currentValue == null ? null : currentValue;\n }", "getTotalMilliseconds() {\n return this._quantity;\n }", "function getQuantity() {\n let quantity = 0;\n for (let i = 0; i < cart.length; i++) {\n quantity += cart[i].quantity;\n }\n\n return quantity;\n}", "function orderItem() {\n\t\t\tthis.id = null ;\n\t\t\tthis.name = null ;\n\t\t\tthis.unit_size = null ;\n\t\t\tthis.category = null ;\n\t\t\tthis.languages = [] ;\n\t\t\tthis.quantities = [] ;\n\t\t\tthis.limits = [];\n\t\t}", "get value() {\n return this.getNumberAttribute('value');\n }", "function getQuantity(qty) {\n\tvar num = document.getElementById(\"qty\").value;\n\tconsole.log(\"quantity ordered: \" + num)\n\treturn qty * num;\n}", "init() {\n this.quantity = 3;\n }", "function fruit(){\n this.name = \"apple\";\n this.color = \"red\";\n this.qty = 4;\n // this.getQty = function(){\n // return this.qty;\n // }\n}", "shelfSize()\n {\n return this.values.size * this.values.quantity;\n }", "getValorTotal(){\n return this._valorUnitario * this._quantidade;\n }", "function loadQuantity(){\n //console.log(\"loadQuantity\");\n var $inputs = $('.' + _input);\n for(var i = 0; i < $inputs.length; i++){\n var $input = $($inputs[i]);\n var datas = $input.data();\n if (datas && datas[_inputStructureId]) {\n var strId = datas[_inputStructureId];\n var jCookie = getJCookie(_cookieName);\n var jResource = jCookie[_jResources][strId];\n if (jResource && jResource[_jQuantity]) {\n $input.val(jResource[_jQuantity]);\n }\n }\n }\n }", "constructor() {\r\n super();\r\n this.quantity = 1;\r\n }", "get value() {\n if (!this._value) {\n this._value = 0;\n }\n return this._value;\n }", "function stockQuantity(id, quantity) {\n connection.query(\n \"SELECT stock_quantity, price FROM products WHERE id = \" + id,\n function(err, res) {\n if (err) throw err;\n purchase(res[0].stock_quantity, quantity, res[0].price, id);\n }\n );\n}", "minOrderQuantity(minValue) {\n return minValue;\n }", "getInteger() {\n return this.value ? this.value : null;\n }", "getPos() {\n return this.units;\n }", "function getQuantitySelected() {\n return parseInt(document.getElementById(\"productQuantity\").value);\n}", "getValorUnitario(){\n return this._valorUnitario;\n }", "get quaternionValue() {}", "function cartItem(detail, name, price, quantity) {\n this.detail = detail;\n this.name = name;\n this.price = price * 1;\n this.quantity = quantity * 1;\n}", "function cartItem(sku, name, price, quantity) {\r\n this.sku = sku;\r\n this.name = name;\r\n this.price = price * 1;\r\n this.quantity = quantity * 1;\r\n}", "static loadItem(id, quantity) {\n // TODO: Update with API call\n for(let i = 0; i < placeholderData.items.length; i++){\n if(id === placeholderData.items[i].id){\n const item = placeholderData.items[i];\n // Enrich data with quantity.\n item.quantity = quantity;\n return item;\n }\n }\n return null;\n }", "function changeQuantity() {\n var number = document.getElementById(\"quantityList\");\n var quantity = number.value;\n return quantity;\n } // end function", "function getQty(ID, qty) {\n var query = connection.query(\"SELECT Stock_QTY FROM products WHERE ID = ?;\",[ID] ,function(err, res) {\n if (err) throw err;\n stock = res[0].Stock_QTY;\n updateProducts(stock, ID, qty);\n });\n return stock;\n}", "get amount() {\n\t\t\treturn this.items\n\t\t\t\t.map(item => item.qty * item.price)\n\t\t\t\t.reduce((total, qty) => total += qty, 0);\n\t\t}", "function quantity(val) {\n return Math.pow(10, quantityExponent(val));\n}", "function CartItem(sku, type,name, slug, mrp, price, quantity, image, category, size, weight) {\r\n // console.log(size);\r\n this.sku = sku;\r\n this.type = type;\r\n this.name = name;\r\n this.slug = slug;\r\n this.image = image;\r\n this.category = category;\r\n this.size = size;\r\n this.mrp = mrp;\r\n this.price = price * 1;\r\n this.quantity = quantity * 1;\r\n this.weight = weight * 1;\r\n this.status = 0;\r\n}", "function QuantitySelector(_ref) {\n var name = _ref.name,\n classes = _ref.classes,\n addIcon = _ref.addIcon,\n addButtonProps = _ref.addButtonProps,\n subtractIcon = _ref.subtractIcon,\n subtractButtonProps = _ref.subtractButtonProps,\n value = _ref.value,\n minValue = _ref.minValue,\n maxValue = _ref.maxValue,\n onChange = _ref.onChange,\n inputProps = _ref.inputProps,\n ariaLabel = _ref.ariaLabel;\n classes = useStyles({\n classes: classes\n });\n var _classes = classes,\n quantitySelector = _classes.quantitySelector,\n icon = _classes.icon,\n button = _classes.button,\n inputClasses = (0, _objectWithoutProperties2[\"default\"])(_classes, [\"quantitySelector\", \"icon\", \"button\"]);\n if (!value) value = 1;\n\n function handleChange(value) {\n if (value >= minValue && value <= maxValue) {\n onChange(value);\n }\n }\n\n return /*#__PURE__*/_react[\"default\"].createElement(_react[\"default\"].Fragment, null, /*#__PURE__*/_react[\"default\"].createElement(_IconButton[\"default\"], (0, _extends2[\"default\"])({\n size: \"small\",\n classes: {\n root: button\n },\n className: classes.subtract,\n onClick: function onClick() {\n return handleChange(value - 1);\n },\n \"aria-label\": \"add one \".concat(ariaLabel)\n }, subtractButtonProps), subtractIcon || /*#__PURE__*/_react[\"default\"].createElement(_Remove[\"default\"], {\n classes: {\n root: icon\n }\n })), /*#__PURE__*/_react[\"default\"].createElement(\"input\", (0, _extends2[\"default\"])({\n onChange: handleChange,\n value: value,\n name: name\n }, {\n 'aria-label': ariaLabel\n }, {\n className: (0, _clsx[\"default\"])([classes.input, inputClasses])\n }, inputProps, {\n readOnly: true\n })), /*#__PURE__*/_react[\"default\"].createElement(_IconButton[\"default\"], (0, _extends2[\"default\"])({\n size: \"small\",\n classes: {\n root: button\n },\n className: classes.add,\n onClick: function onClick() {\n return handleChange(value + 1);\n },\n \"aria-label\": \"subtract one \".concat(ariaLabel)\n }, addButtonProps), addIcon || /*#__PURE__*/_react[\"default\"].createElement(_Add[\"default\"], {\n classes: {\n root: icon\n }\n })));\n}", "constructor(item, quantity) {\r\n this.item = item;\r\n this.quantity = quantity;\r\n this.children = {};\r\n }", "function cartItem(sku, name, price, quantity) {\n this.sku = sku;\n this.name = name;\n this.price = price * 1;\n this.quantity = quantity * 1;\n }", "valueOf() {\n return this.money;\n }", "get number() {\n return Number(this.view.value);\n }", "constructor() {\n this.order = null;\n this.desc = null;\n this.quantity = null;\n this.length = null;\n this.width = null;\n this.height = null;\n this.rotate = null;\n this.stack = null;\n this.group = null;\n }", "function getSubTotalByProductAmountAndQuantity()\n {\n return ((getQuantityFromInputField() * getProductAmountFromInputField()).toFixed(2));\n }", "get value() {}", "get value() {}", "get amount () {\n return Math.abs(this.raw) / this.scale\n }", "function getQuantityNumber (airClass) {\n const airClassInput = document.getElementById(airClass + '-quantity');\n const airClassQuantity = parseFloat(airClassInput.value);\n return airClassQuantity;\n}", "function quantity(pid, selections) {\n var up = function (ev) {\n event({\n __ctor: \"QuantityClick\",\n product: pid,\n action: \"up\"\n });\n };\n var down = function (ev) {\n event({\n __ctor: \"QuantityClick\",\n product: pid,\n action: \"down\"\n });\n };\n var q = selections.has(pid)\n ? selections.get(pid).quantity\n : 0;\n return maquette_1.h(\"div.row\", { key: \"quantity\" }, [\n maquette_1.h(\"div.col-sm\", { key: 1, onclick: down }, [\"(-)\"]),\n maquette_1.h(\"div.col-sm\", { key: 2 }, [q.toString()]),\n maquette_1.h(\"div.col-sm\", { key: 3, onclick: up }, [\"(+)\"])\n ]);\n}", "toString() { return `${this.value || '?'} ${this.unit}`.trim() }", "function getUnitFromInput() {\n\t\tvar unit_id = $(\"#units-select\").val();\n\t\treturn units[unit_id];\n\t}", "totalItemPrice(item) {\n if(undefined === item.price || undefined === item.quantity){\n return 0;\n }\n return item.price * item.quantity;\n }", "valueOfStock()\n {\n return this.numberofshare*this.shareprice\n }", "handleQuantity() {\n // dummy function which will invoke inside created().\n }", "quantity(fileName) {\n return this.stored.bag[fileName] || 0\n }", "get StockNum() {\n return this._stockNum;\n }", "function _setQuantity(xml) {\n var valueNode = Sdk.Xml.selectSingleNode(xml, \"//a:KeyValuePairOfstringanyType[b:key='Quantity']/b:value\");\n if (!Sdk.Xml.isNodeNull(valueNode)) {\n _quantity = parseInt(Sdk.Xml.getNodeText(valueNode), 10);\n }\n }", "getNormalizedValue() {\n return this.value === null ? null : normalize(this.unitList, this.value, options.type);\n }", "getValue() {\n return this.value;\n }", "get valueAsNumber() {\n return this.getInput().valueAsNumber;\n }", "getValue() {\n return this.value;\n }", "getValue() {\n return this.value;\n }", "getValue() {\n return this.value;\n }", "function getQuantityByProduct(itemNode) {\n var qtyNode = itemNode.querySelector(\".quantity-input\");\n var qty = qtyNode.value;\n return qty;\n}", "_getValue() {\n return this._value;\n }", "function Item (name, quantity, location) {\n this.name = name;\n this.quantity = quantity;\n this.location = location;\n}", "_get_value() {\n return this._has_value() ? this._value : undefined;\n }", "getValue()\n {\n return this.value;\n }", "function getQty(){\n let qty = 0;\n for(let i = 0; i < cart.length; i += 1){\n qty += cart[i].qty;\n }\n return qty\n}", "function get() {\n return _value;\n }", "get value() { return this._value; }", "get value() { return this._value; }", "get value() { return this._value; }", "get value() { return this._value; }", "get value() { return this._value; }", "get value() { return this._value; }", "get value() { return this._value; }" ]
[ "0.73006326", "0.7286378", "0.70620376", "0.70620376", "0.70620376", "0.6507041", "0.64678663", "0.6447228", "0.64377165", "0.6419223", "0.6379325", "0.63425386", "0.6100222", "0.6005071", "0.58844334", "0.5869871", "0.5835774", "0.583076", "0.58057064", "0.57182", "0.5714805", "0.57037574", "0.56409436", "0.55763", "0.5523546", "0.5497091", "0.5464132", "0.5444517", "0.5444067", "0.54053134", "0.5385414", "0.5373996", "0.53449875", "0.5273777", "0.52737665", "0.5270375", "0.52645326", "0.52591217", "0.52530664", "0.5227396", "0.52167296", "0.52146137", "0.52052295", "0.51983494", "0.5197908", "0.519709", "0.5196031", "0.519328", "0.51843405", "0.5179871", "0.5174384", "0.51677483", "0.5164473", "0.5138329", "0.51379335", "0.5136521", "0.50830436", "0.50819755", "0.5080884", "0.50771147", "0.5066792", "0.50667244", "0.50647134", "0.50604385", "0.50548697", "0.5048589", "0.5048423", "0.5044601", "0.5044601", "0.50398636", "0.5028527", "0.50263566", "0.50056404", "0.5003554", "0.5003099", "0.49879223", "0.49811682", "0.49804372", "0.49776748", "0.49734843", "0.49716595", "0.4971525", "0.4965383", "0.49619517", "0.49619517", "0.49619517", "0.49458006", "0.49434304", "0.49378595", "0.49367273", "0.4925654", "0.49253488", "0.49141017", "0.4906687", "0.4906687", "0.4906687", "0.4906687", "0.4906687", "0.4906687", "0.4906687" ]
0.8323964
0