query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Bins the generated timestamp into the same itnerval set with var timeGrouping | function binTimestamp(timestamp) {
timestamp = parseInt(timestamp);
var divVal = null
switch (timeGrouping) {
case 'minute':
divVal = 1000 * 60;
break;
case 'second':
divVal = 1000;
break;
case 'millisecond':
divVal = 1;
break;
default:
console.warn('Binning unsupported timestamp type', timeGrouping, timestamp);
break;
}
return parseInt(timestamp / divVal) * divVal;
} | [
"function bin_by_time(span) {\n return {\n func: function(datum) {\n let date = new Date(datum/1000);\n return Math.floor((date.getHours() + date.getMinutes()/60) / span);\n },\n count: 24/span\n };\n}",
"joinTimestamp(splitTimestamp) {\n let nl, ns;\n let out = null;\n if (\n splitTimestamp && splitTimestamp.large !== undefined &&\n splitTimestamp.small !== undefined\n ) {\n nl = new BN(splitTimestamp.large, 10);\n ns = new BN(splitTimestamp.small, 10);\n out = nl.shln(32).toNumber() + ns.toNumber();\n }\n return out;\n }",
"createReducedGranularityTimeseries(granularityMins, reduceFunction){\n // the new granularityMins value must be higher, we cannot upsample\n if (granularityMins <= this.binGranularityMins){\n console.error(`createReducedGranularityTimeseries(): cannot convert granularity from ${this.binGranularityMins} to ${granularityMins}`)\n }\n\n // downsample to new granularity:\n let binnedLists = {}; // => {1234:[234,3,65], 1235:[234,32], ...}\n for(let i = 0; i<this.timestampLogDataPoints; i++){\n datapoint = this.timestampLogDataPoints[i];\n if(!binnedLists[AbstractFeatureGenerator.getBinnedTimestampForGranularity(datapoint.timestamp)]){\n binnedLists[AbstractFeatureGenerator.getBinnedTimestampForGranularity(datapoint.timestamp)] = [];\n }\n binnedLists[AbstractFeatureGenerator.getBinnedTimestampForGranularity(datapoint.timestamp)].push(datapoint.value);\n }\n\n let accumulatedBins = [];\n Object.keys(binnedLists).forEach(aBinTimestamp => {\n accumulatedBins.push({timestamp: aBinTimestamp, value: binnedLists[aBinTimestamp].reduce(reduceFunction)});\n });\n\n accumulatedBins.sort((bin1,bin2) => {return bin1.timestamp-bin2.timestamp});\n\n return new TimestampLogTimeseries(accumulatedBins, granularityMins);\n }",
"function addEmpty(group, binSize) {\n var msIn1Min = 60 * 1000;\n return {\n all: function() {\n var prev = null;\n var groups = [];\n group.all().forEach(function(g) {\n // If the gap between data is more than <bucket size> + 1 minute,\n // insert a null data point to break line segment.\n if (prev && (g.key - prev) > binSize * 3 * msIn1Min + msIn1Min) {\n var newdate = new Date(prev.getTime() + binSize * 3 * msIn1Min);\n /*console.log(\"added empty group \" + newdate.toISOString()) +\n \" between \" + prev.toISOString() + \" and \" +\n g.key.toISOString());*/\n groups.push({\n key: newdate,\n value: {count: 0, total: null}\n });\n }\n groups.push(g);\n prev = g.key;\n });\n return groups;\n }\n };\n}",
"function buildTimeGroupby(type, parameters) {\n var aql = [];\n aql.push('for $t in dataset {0}'.format(TempDSName));\n if (type == \"time\") {\n aql.push('let $ts_start := datetime(\"{0}\")'.format(parameters['startdt']));\n aql.push('let $ts_end := datetime(\"{0}\")'.format(parameters['enddt']));\n aql.push('where $t.create_at >= $ts_start and $t.create_at < $ts_end');\n }\n aql.push('group by $c := print-datetime($t.create_at, \"YYYY-MM-DD hh\") with $t ');\n aql.push('let $count := count($t)');\n aql.push('order by $c ');\n aql.push('return {\"slice\":$c, \"count\" : $count };\\n');\n return aql.join('\\n');\n}",
"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}",
"function timeBinIntoInteractions (data, numBins = 20, type = 'CPV') {\r\n\r\n var timeExtent = [0, d3.max(data, function (d) {\r\n return +d.date\r\n })]\r\n\r\n var elapsedTime = timeExtent[1] - timeExtent[0]\r\n var interval = elapsedTime / numBins\r\n\r\n var initBins = []\r\n for (var i = 1; i <= numBins; i++) {\r\n initBins.push(\r\n data.filter(function (d) {\r\n return timeExtent[0] + interval * (i - 1) <= d.date &&\r\n d.date < timeExtent[0] + interval * i &&\r\n d.id !== 'mouseEnter' && d.id !== 'MouseEnter'\r\n })\r\n )\r\n }\r\n\r\n var bins = []\r\n for (var i = 0; i < initBins.length; i++) {\r\n if (type === 'CPV') {\r\n bins.push({\r\n 'startTime': timeExtent[0] + interval * i,\r\n 'endTime': timeExtent[0] + interval * (i + 1),\r\n 'officesCleared': 0,\r\n 'officeMouseEnter': 0,\r\n 'officeClicked': 0,\r\n 'sliderMoved': 0,\r\n 'accessTimeClicked': 0,\r\n 'histogramBrushStart': 0,\r\n 'histogramBrushEnd': 0,\r\n 'headerClicked': 0,\r\n 'rowClicked': 0,\r\n 'rowMouseOver': 0,\r\n 'tableToggleSelected': 0,\r\n 'pageChange': 0,\r\n 'histogramBarClick': 0,\r\n 'histogramBarMouseEnter': 0,\r\n 'graphNodeMouseEnter': 0,\r\n 'infoHover': 0,\r\n 'total': 0\r\n })\r\n } else {\r\n bins.push({\r\n 'startTime': timeExtent[0] + interval * i,\r\n 'endTime': timeExtent[0] + interval * (i + 1),\r\n 'yAxisChanged': 0,\r\n 'xAxisChanged': 0,\r\n 'AddedTypeFilter': 0,\r\n 'PokemonSelected': 0,\r\n 'AddedGenerationFilter': 0,\r\n 'total': 0\r\n })\r\n }\r\n\r\n for (var j = 0; j < initBins[i].length; j++) {\r\n var key = initBins[i][j].id\r\n bins[i][key] += 1\r\n bins[i].total += 1\r\n }\r\n }\r\n return bins\r\n}",
"function binData(data, binInterval) {\n\tvar binnedData = [];\n\tvar binCounts = [];\n\tvar minTime = null;\n\tvar maxTime = null;\t\n\t\t\n\tfor (var i=0; i<data.length; i++) {\n\t\tvar dataType = data[i].activity_type;\n\t\tvar skip = (i<data.length-1) && (dataType=='link') && (data[i+1].activity_type=='link_rating');\n\t\tif (skip) continue;\n\t\t\n\t\tif (dataType=='link_rating') {\n\t\t\tif (data[i].is_helpful) dataType='link_helpful';\n\t\t\telse dataType='link_unhelpful';\n\t\t}\n\t\tvar dataTime = getLocalTime(new Date(data[i].timestamp));\n\t\tif (minTime==null) {\n\t\t\tminTime = dataTime;\n\t\t\tmaxTime = new Date(minTime.getTime()+(binInterval*60*1000));\t\n\t\t}\n\n\t\tif (dataTime >= maxTime) {\n\t\t\t// save previous bin\n\t\t\tif (Object.keys(binCounts).length>0) {\n\t\t\t\tfor (var binType in binCounts) {\n\t\t\t\t\tbinnedData.push({activity_type:binType, timestamp:minTime, count:binCounts[binType]});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// initialize bin\n\t\t\tbinCounts = [];\n\t\t\tvar minTime = dataTime;\n\t\t\tvar maxTime = new Date(minTime.getTime()+(binInterval*60*1000));\t\n\t\t}\n\t\n\t\t// increment bin counts\n\t\tif (binCounts[dataType] == undefined) binCounts[dataType] = 1;\n\t\telse binCounts[dataType]++;\n\t}\n\t\n\t// save last bin\n\tif (Object.keys(binCounts).length>0) {\n\t\tfor (var binType in binCounts) {\n\t\t\tbinnedData.push({activity_type:binType, timestamp:minTime, count:binCounts[binType]});\n\t\t}\n\t}\n\t\n\treturn binnedData;\n}",
"splitTimingIntoIntervals(timing) {\n let startingBlock = Math.floor((timing.responseStart - this.epoch) / this.INTERVAL_DURATION);\n let endingBlock = Math.floor((timing.responseEnd - this.epoch) / this.INTERVAL_DURATION);\n let bytesPerBlock = timing.transferSize / ((endingBlock - startingBlock + 1));\n\n for (var i = startingBlock; i <= endingBlock; i++) {\n this.allIntervals[i] = (this.allIntervals[i] || 0) + bytesPerBlock;\n }\n }",
"getTimestampWorkingGroupId (timestamp) {\n let currentPeriodRunTime = (timestamp - this.circleStartTime) % this.periodTime\n let numGroupsAlreadyRun = Math.floor(currentPeriodRunTime / this.intervalTime)\n let currentWorkingGroup = (numGroupsAlreadyRun % this.numGroups) + this.minGroup\n return currentWorkingGroup\n }",
"function groupTimes() {\n\tvar groups = [];\n\tvar currentGroup = [];\n\n\tcurrentGroup.push(rawData[0]);\n\tfor (var i = 1; i < rawData.length; i++) {\n\n\t\tvar date = new Date(rawData[i-1].date);\n\t\tvar nextDate = new Date(rawData[i].date);\n\n\t\tif ((date.getDay() == nextDate.getDay()) && (nextDate.getHours() - date.getHours() <= 3)) {\n\t\t\tcurrentGroup.push(rawData[i]);\n\t\t} else if ((date.getHours() - nextDate.getHours() >= 21)) {\n\t\t\tcurrentGroup.push(rawData[i]);\n\t\t} else {\n\t\t\tgroups.push(currentGroup);\n\t\t\tcurrentGroup = [rawData[i]];\n\t\t}\n\t}\n\tgroups.push(currentGroup);\n\treturn groups;\n}",
"function getBinIndex(scale, curTimeStamp, startTimeStamp) {\n var curBin = scale._getRangeThreshold(),\n showPlotOverTick = scale.showPlotOverTick(),\n squareOff = showPlotOverTick ? Math.round : Math.floor,\n yearsInBetween,\n startTime = new Date(startTimeStamp),\n curTime = new Date(curTimeStamp),\n startMonth,\n curMonth,\n startYear,\n curYear,\n index,\n binLength = curBin[2];\n\n if (curBin[0].name() === 'year') {\n return squareOff(curBin[0].count(startTimeStamp, curTimeStamp) / curBin[1]);\n } else if (curBin[0].name() === 'month') {\n startYear = dateAPI(startTime, 'FullYear', scale.getType());\n curYear = dateAPI(curTime, 'FullYear', scale.getType());\n startMonth = dateAPI(startTime, 'Month', scale.getType());\n curMonth = dateAPI(curTime, 'Month', scale.getType());\n yearsInBetween = Math.max(0, curYear - startYear - 1);\n\n if (startYear === curYear) {\n index = Math.floor(curMonth / curBin[1]) - Math.floor(startMonth / curBin[1]);\n } else {\n index = yearsInBetween * 12 / curBin[1];\n index += 12 / curBin[1] - Math.floor(startMonth / curBin[1]);\n index += Math.floor(curMonth / curBin[1]);\n } // If plots are placed at starting of bin and mouse pointer is has crossed the mid point\n // of the bin, return the next bin as the active bin\n\n\n if (showPlotOverTick && curTime.getDate() > MONTH_MID) {\n index++;\n }\n\n return index;\n }\n\n return squareOff((curTimeStamp - startTimeStamp) / binLength);\n}",
"function fill_binned_data(data_map,time_bins,bin_size) {\n var time_map = new Map();\n data_map.forEach( function(data, location, data_map ) {\n // If location not checked don't include in time_map\n if( !document.getElementById(location).checked ) return;\n for( var i=0; i<data.length; i++) {\n // date for each entry in data array for each location is the first element for that entry\n var this_date = data[i][0];\n // time bins is list of bin centers\n // each date should then be either half a bin before or after the bin center\n var this_bin = find_nearest_date(time_bins,this_date,bin_size/2);\n if( this_bin < 0 ) {\n continue;\n }\n var this_data = data[i][1]; // this is [cmp,error]\n // map data to given location for next step\n // (need to know which locations went in to each bin)\n var this_data_map = new Map();\n this_data_map.set(location,this_data);\n if( time_map.has(this_bin) ) {\n time_map.get(this_bin).push(this_data_map);\n }\n else {\n var this_data_map_array = [];\n this_data_map_array.push(this_data_map);\n time_map.set(this_bin,this_data_map_array);\n }\n }\n });\n return time_map;\n}",
"function getBinTicks(chosenXAxis, histData){\n var min = d3.min(histData[chosenXAxis]);\n var max = d3.max(histData[chosenXAxis]);\n binTicks = [];\n bin_range = (max-min)/binNum;\n for (var i=0; i<binNum+1; i++){\n var t = (min+(bin_range*i)).toFixed(3);\n binTicks.push(t);\n }; \n return binTicks; \n}",
"splitTimestamp(timestamp) {\n let num;\n const out = { large: null, small: null };\n if (timestamp !== null && timestamp !== undefined) {\n num = new BN(timestamp, 10);\n out.small = num.and(new BN('FFFFFFFF', 16)).toNumber();\n out.large = num.shrn(32).toNumber();\n }\n return out;\n }",
"function encodeTimestamp(d, b, i) {\n\n encodeTime(d, b, i)\n var ms = d.getUTCMilliseconds()\n var ms1 = ms % 10\n b[i + 6] = (ms - ms1) / 10\n b[i + 7] = ms1 * 10 + (d.us100 || 0)\n }",
"function bucketize(spans, keyField, timeField, bucketDur, f) {\n var retval = {};\n var coeff = 1000 * bucketDur;\n\n for (var span of spans) {\n var roundedDate = new Date(Math.round(span[timeField] / (1000 * coeff)) * coeff);\n var bucket = retval[roundedDate];\n if (!bucket) {\n bucket = {};\n retval[roundedDate] = bucket;\n }\n var key = span[keyField];\n // bucket[key] = (bucket[key] || 0) + 1;\n bucket[key] = f(bucket[key] || 0, span);\n }\n\n return retval;\n}",
"function TimestampSamples(maxBuckets, granularity) {\n this.maxBuckets = maxBuckets;\n this.minMagnitude = Math.pow(10, granularity);\n\n // Note: this will initialize the rest of the object fields\n this.clear();\n}",
"function groupBy(interval, groupByCallback, datapoints) {\n var ms_interval = utils.parseInterval(interval);\n\n // Calculate frame timestamps\n var frames = _.groupBy(datapoints, function(point) {\n // Calculate time for group of points\n return Math.floor(point[1] / ms_interval) * ms_interval;\n });\n\n // frame: { '<unixtime>': [[<value>, <unixtime>], ...] }\n // return [{ '<unixtime>': <value> }, { '<unixtime>': <value> }, ...]\n var grouped = _.mapValues(frames, function(frame) {\n var points = _.map(frame, function(point) {\n return point[0];\n });\n return groupByCallback(points);\n });\n\n // Convert points to Grafana format\n return sortByTime(_.map(grouped, function(value, timestamp) {\n return [Number(value), Number(timestamp)];\n }));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
turns icon back to gray when you click outside of the search box | function revertIconColor() {
searchIcon.style.color = '#757575'
} | [
"function searchIconClick() {\n searchIcon.on(\"click\", function () {\n if (toggleSearch == false) {\n searchHeader.css({\"width\": \"96%\"});\n form.css({\"width\": \"100%\"});\n formGroup.css({\"width\": \"95%\"});\n searchInput.css({\"width\": \"100%\", \"opacity\": 1});\n headerUser.css({\"opacity\": 0, \"width\": 0});\n headerMenu.css({\"opacity\": 0, \"width\": 0});\n headerLogo.css({\"opacity\": 0, \"width\": 0});\n toggleSearch = true;\n } else{\n searchHeader.css({\"width\": \"unset\"});\n form.css({\"width\": \"unset\"});\n formGroup.css({\"width\": \"unset\"});\n searchInput.css({\"width\": \"0\", \"opacity\": 0});\n headerUser.css({\"opacity\": 1, \"width\": \"unset\"});\n headerMenu.css({\"opacity\": 1, \"width\": \"unset\"});\n headerLogo.css({\"opacity\": 1, \"width\": \"unset\"});\n toggleSearch = false;\n }\n \n });\n }",
"function updateSearchIcon(){\n\n const input = searchBar.value;\n\n if(input===''){\n searchIcon.src = './icons/lupa.svg';\n searchIcon.removeEventListener('click', clearSearchBar);\n searchIcon.classList.remove('clickeable-icon');\n\n }else{\n searchIcon.src = './icons/cancel.svg';\n searchIcon.addEventListener('click', clearSearchBar);\n searchIcon.classList.add('clickeable-icon');\n }\n}",
"function removeSearchIcon() {\n searchSection.style.background = \"none\";\n}",
"function onBlur() {\n // only focus out when there is no text inside search bar, else, dont focus out\n if (searchVal.current.value === \"\") {\n setSearchIconClick(false);\n }\n }",
"function addSearchIcon() {\n if (searchSection.value == \"\") {\n searchSection.style.background =\n \"url(../images/icons8-search-filled-30.png) no-repeat center\";\n } else if (searchSection.value != \"\") {\n searchSection.style.background = \"none\";\n }\n}",
"clickSearchIcon() {\n this.toggleProperty('isShowingResults');\n $('.sitemap-search-input').toggleClass('hidden');\n }",
"clickOnSearchIcon() {\n return elementUtil.doClick(this.searchIcon);\n }",
"function _searchClose() {\n if (_state.search) {\n _searchToggle();\n }\n }",
"function highlightMarkersearch(e){\n var layer = e.feature;\n var iconElem = L.DomUtil.get(e._icon);\n iconElem.style.border=\"4px #00ffff solid\";\n iconElem.style.height=\"38px\";\n iconElem.style.width=\"38px\";\n iconElem.style.marginTop=\"-19px\";\n iconElem.style.marginLeft=\"-19px\";\n iconElem.id=\"selectedIcon\";\n }",
"function searchFocusOut() {\n if (!mouseOnSearchOut) {\n displaySearch(false);\n }\n}",
"function searchAndClearSearchHandler(event){\n if(!event.target.classList.contains(\"search-button-icon\") && !event.target.classList.contains(\"clear-button-icon\")){\n return;\n }\n event.target.classList.contains(\"search-button-icon\") ? search(event) : clearSearch(event);\n}",
"function _siteMaskClickHandler() {\n _state.search && _searchToggle();\n }",
"function searchBarBlur() {\n $ctrl.showCancel = false;\n }",
"function disableCancelSearch () {\n CancelSearchInput.src = \"/icons/empty.png\";\n CancelSearchInput.disabled = true;\n sboxState = SBoxEmpty;\t// No active search\n SearchResult.hidden = true;\n}",
"function hideSearch(){\n $('#overlay, #search').hide()\n $('#overlay').unbind('click');\n $(window).unbind('keyup');\n }",
"_closeSearch() {\n const searchInputElement = this.shadowRoot.getElementById('search_input');\n if (searchInputElement?.classList.contains('opened')) {\n searchInputElement.value = '';\n\n searchInputElement.classList.remove('opened');\n searchInputElement.removeAttribute('style', 'width');\n\n this.shadowRoot.getElementById('close_button').style.zIndex = '-1';\n this.shadowRoot.getElementById('search_glass').style.backgroundColor = 'inherit';\n this.#hideAutoCompleteList();\n }\n }",
"function onClearSearch() {\n $('#search').val('');\n $('#types .btn-primary').removeClass('btn-primary').addClass('btn-light');\n $('#clear-filter').fadeOut();\n $('#items').children().fadeIn();\n $('#items').unmark();\n }",
"function hide() {\n $('#search-icon').css(\"visibility\", \"hidden\");\n}",
"function cancelSearch() {\r\n $('.highlight').each(function() {\r\n var par = $(this).parent();\r\n $(this).contents().unwrap();\r\n par[0].normalize();\r\n });\r\n $('.search-notfound').removeClass('search-notfound');\r\n $(\"#filter-count\").hide();\r\n $('#buttons_wrapper').hide();\r\n $('#search_ui').hide();\r\n\r\n// ///OOOOOOOOO\r\n// $(\"#filter-count_xs\").hide();\r\n// $('#buttons_wrapper_xs').hide();\r\n// $('#search_ui_xs').hide();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check the current role of the comment authors and save it to comments | function checkCurrentRoleOfAuthor(comments){
return new Promise((resolve, reject)=>{
comments.forEach((comment)=>{
User.findById(comment.author.id, (err, user)=>{
if(err){
req.flash('error', "unable to retrieve comment user");
res.redirect('back');
return;
} else {
comment.author.role = user.role;
comment.save();
}
});
});
resolve(comments);
});
} | [
"function checkCurrentRoleOfAuthor(blogs){\n return new Promise((resolve, reject)=>{\n blogs.forEach((blog)=>{\n User.findById(blog.author.id, (err, user)=>{\n if(err){\n req.flash('error', \"unable to retrieve blog author\");\n res.redirect('back');\n return; \n } else {\n blog.author.role = user.role;\n blog.save();\n }\n });\n });\n resolve(blogs);\n });\n }",
"function save_author() {\r\n\tif (req.data.deleteid != null) {\r\n\t\tvar user = app.getObjects(\"User\",{_id:req.data.deleteid})[0];\r\n\t\tthis.delete_user(user.username);\r\n\t\tres.redirect(this.getURI(\"manage_authors?deleted=true\"));\r\n\t\treturn;\r\n\t}\r\n\tvar data = {};\r\n\tif (req.data.editid != null) {\r\n\t\tdata.user_id = req.data.editid;\r\n\t\tif (req.data.username != null) {\r\n\t\t\tdata.username = req.data.username;\r\n\t\t}\r\n\t\tdata.email = req.data.email;\r\n\t\tdata.role = req.data.role;\r\n\t\tdata.fullname = req.data.fullname;\r\n\t\tif (req.data.password1 != \"\") {\r\n\t\t\tdata.password = req.data.password1;\r\n\t\t}\r\n\t\tthis.edit_user(data);\r\n\t\tres.redirect(this.getURI(\"manage_authors?saved=true\"));\r\n\t} else {\r\n\t\tdata.username = req.data.username;\r\n\t\tdata.email = req.data.email;\r\n\t\tdata.role = req.data.role;\r\n\t\tdata.fullname = req.data.fullname;\r\n\t\tdata.password = req.data.password1;\r\n\t\tdata.activated = false;\r\n\t\tvar random = new Date().valueOf() + data.username;\r\n\t\tdata.id = random.md5();\r\n\t\tvar user = this.create_user(data);\r\n\t\tuser.send_invite();\r\n\t\tres.redirect(this.getURI(\"manage_authors?saved=true\"));\r\n\t}\r\n}",
"function isCommentAuthor(author) {\n return divvy.currentUser == author;\n }",
"author(parent, args, ctx, info) {\n // 'Comment' Object data -> is present in 'parent' argument in author() method\n return USERS_DATA.find((user) => { // find return individual user object\n return user.id === parent.author\n });\n }",
"function ownByEditor(articleAuthor, req){\n\tif (articleAuthor._id.toString() != req.user._id.toString()){\n\t\treturn false;\n\t} else\n\t{\n\t\treturn true;\n\t} \n}",
"function checkOwnership(req, res, next) {\r\n if (req.isAuthenticated()) {\r\n Comment.findById(req.params.comment_id, function (err, foundComment) {\r\n if (err) {\r\n res.redirect(\"back\");\r\n } else {\r\n // console.log(foundCampground.author.id); mongoose object\r\n // console.log(req.user._id) string\r\n if (foundComment.author.id.equals(req.user._id) || req.user.isAdmin) {\r\n next();\r\n } else {\r\n req.flash(\"error\", \"You don't have the permission\");\r\n res.redirect(\"back\");\r\n }\r\n }\r\n });\r\n } else {\r\n req.flash(\"error\", \"You need to be logged in\");\r\n res.redirect(\"back\");\r\n }\r\n}",
"function userCanEdit(req, res) {\n return Comment.findById(req.params.id, (err, comment) => {\n if (err) return res.json(err);\n // For some reason I have to convert the values to string (or use \"==\"). If not this will never evaluate true\n return JSON.stringify(comment.author) === JSON.stringify(req.user.id);\n });\n}",
"function checkCommentOwnership(req,res,next){\n if(req.isAuthenticated){\n Comment.findById(req.params.comment_id,function(err,foundComment){\n if(err){\n console.log(\"Yoe something went wrong!!!\");\n console.log(err);\n }else{\n //checking the current user with idea user\n if(foundComment.author.id.equals(req.user._id)){\n next();\n }else{\n req.flash(\"commentPermission\",\"you dont have a permission to do that\");\n res.redirect(\"back\");\n }\n \n }\n });\n }else{\n res.redirect(\"back\");\n }\n}",
"function addHimselfAsAuthor () {\n\n //add himself to the list of authors\n if (!dbRootObj.authors || singleton.auth && !dbRootObj.authors[singleton.auth.uid]) {\n dbRootObj.authors = dbRootObj.authors || {};\n dbRootObj.authors[singleton.auth.uid] = true;\n }\n }",
"function checkCommentOwnership(req, res, next)\n{\n //is user logged in\n if(req.isAuthenticated())\n {\n Comment.findById(req.params.comment_id, function(err, foundComment)\n {\n if(err)\n {\n req.flash(\"error\", \"Error retrieving comment from the database\");\n res.redirect(\"back\");\n }\n else\n {\n //does user own the comment\n if(foundComment.author.id.equals(req.user._id)) // .equals() is a method that comes with mongoose that allows you to compare variables of different types\n {\n next();\n }\n else\n {\n req.flash(\"error\", \"You don't have permission to edit that comment\");\n res.redirect(\"back\");\n }\n }\n });\n }\n else\n { \n req.flash(\"error\", \"You need to be logged in to do that\");\n res.redirect(\"back\");\n }\n}",
"function checkCommentOwnership(req,res,next){\n\tif(req.isAuthenticated()){\n\t\tComment.findById(req.params.comment_id,function(err,foundComment){\n\t\t\tif(err){\n\t\t\t\tres.redirect(\"back\")\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(foundComment.author.id)\n\t\t\t\t\tconsole.log(req.params.id)\n\t\t\t\tif(foundComment.author.id.equals(req.user.id)){\n\t\t\t\t\tnext();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tres.send(\"You don't have permission to do that\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\telse{\n\t\tres.redirect(\"back\");\n\t}\n}",
"setAuthor(){\n this.state.newItem.author = this.idFromUsername(this.auth.getUsername());\n this.state.commentItem.author = this.idFromUsername(this.auth.getUsername());\n }",
"function checkCommentOwnership(req,res,next){\n\tif(req.isAuthenticated()){\n\t//does the user own the campground ?\n\t\tComment.findById(req.params.comment_id,function(err,foundComment){\n\t\tif(err){\n\t\t\tres.redirect(\"back\")\n\t\t}else {\n\t\t\tif(foundComment.author.id.equals(req.user._id)){\n\t\t\t\tnext()\n\t\t\t}else {\n\t\t\t\treq.flash(\"error\", \"You don't have permission to do that\");\n\t\t\t\tres.redirect(\"back\")\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t})\n\n\t\t}else{\n\t\t\treq.flash(\"error\", \"You need to be logged in to do that\");\n\t\t\tres.redirect(\"back\") //previous page\n\t\t}\n\t}",
"function checkCommentsOwnership(req,res,next){\n \n if(req.isAuthenticated()){\n Comment.findById(req.params.comments_id,function(err,foundComment){\n if(err){\n req.flash(\"error\",\"Not found\");\n res.redirect(\"back\");\n }\n else{\n // check whether user own comments or not\n if(foundComment.author.id.equals(req.user._id)){\n next();\n \n }\n else{\n req.flash(\"error\",\"Not have permission to do that\");\n res.redirect(\"back\");\n }\n }\n });\n \n \n }\n else{\n req.flash(\"error\", \"You need to be logged in\");\n res.redirect(\"back\");\n }\n \n}",
"function assignAuthor() {\n\tvar snippet = {\n\t\tquery: {id: \"-K_WonIe_j7iSm-WeyC8\", authorId: \"-K_W_cxqkjGVo8zEfLUc\"}\n\t}\n\trimer.post.assignAuthor(snippet, function(error, value) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t}\n\t\telse {\n\t\t\tconsole.log(value)\n\t\t}\n\t})\n}",
"function commentOwnershipAuthentication(req, res, next){\n\tif(req.isAuthenticated()){\n\t\tComment.findById(req.params.comment_id, function(err, foundComment){\n\t\t\tif(err){\n\t\t\t\tres.redirect(\"back\");\n\t\t\t} else {\n\t\t\t\tif(foundComment.author.id.equals(req.user._id)) {\n\t\t\t\t\tnext();\n\t\t\t\t} else {\n\t\t\t\t\tres.redirect(\"back\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} else {\n\t\tres.redirect(\"back\");\n\t}\n}",
"isEditable() {\n if (!this.user) {\n return false;\n }\n // If the comment has been deleted, it should only be editable\n // by site admins or the user who deleted it.\n if (this.activity.deleted_by) {\n return this.user.is_admin || this.activity.deleted_by === this.user.email;\n }\n // If the comment is not deleted, site admins or the author can edit.\n return this.user.email === this.activity.author || this.user.is_admin;\n }",
"function isEditor() {\n var user = Session.getActiveUser().getEmail();\n return EDITORS.indexOf(user) >= 0;\n}",
"function checkCommentOwnership(req, res, next){\n if (req.isAuthenticated()){\n Comment.findById(req.params.comment_id, (error, retComment)=>{\n if (error || !retComment){ // if no comment is found (due to wrong id), return empty retComment\n req.flash(\"error\", \"Sorry! That comment does not exist or something went wrong!\")\n console.log(\"Error in checkCommentOwnership(): \", error);\n return res.redirect(\"back\")\n } else {\n if (retComment.author.id.equals(req.user._id)) // does user own campgrounds?\n next()\n else{\n req.flash(\"error\", \"You don't have permission to access this comment!\")\n res.redirect(\"/destinations\") // take user back to previous page they were on\n }\n }\n })\n } else {\n res.redirect(\"/login\"); // take user back to previous page they were on\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The comment submit button action | function submitComment() {
submitCmt.click(function () {
$(".default-cmt__content__cmt-block__cmt-box").find('.messages').hide();
if (checkGuestFormValidate()) {
var cmtText = cmtBox.val();
if (cmtText.trim().length) {
$('.default-cmt_loading').show();
$(this).prop('disabled', true);
var ajaxRequest = ajaxCommentActions(cmtText, submitCmt);
ajaxRequest.done(function () {
cmtBox.val('');
$('.default-cmt_loading').hide();
$(this).prop('disabled', false);
}.bind(this));
} else {
$('.default-cmt__content__cmt-block__cmt-box__cmt-input').parent().append(messengerBox.cmt_warning);
}
}
});
} | [
"function submitComment(evt) {\n evt.preventDefault();\n\n const comment = $('#comment')\n\n $.post('/community', comment, (response) => {\n $('#d-flex flex-column comment-section').append(`${response.global_comment}`);\n } )\n console.log('posted')\n}",
"function submitComment(){\n\tcomment = this.parentNode.children[0].value\n\tisCommentValid(this, comment);\n\tthis.parentNode.reset(); \n}",
"function submitComment(event) {\n event.preventDefault();\n CommentModel.create({\n content: content,\n authorId: props.user[0].id,\n tweetId: props.id,\n }).then((json) => {\n if (json.status === 201) {\n console.log(json, \"user commented\");\n }\n });\n }",
"function commentSubmit(e){\n\t\t\n\t\tif (e.target.parentNode.childNodes[1].value == \"\"){\n\t\t\talert(\"The text box is currently empty! Type in your comment and I'll submit it for you.\");\n\t\t\te.preventDefault();\n\t\t}\n\t\telse {\n\t\t\tvar newCommentNum = updateCommentCounter();\n\t\t\tvar newString = newCommentString(newCommentNum);\n\t\t\te.target.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes[3].childNodes[1].childNodes[3].innerHTML = newString;\n\t\t\te.preventDefault();\n\t\t\tgetComment();\n\t\t\te.target.parentNode.reset();\n\t\t}\n\t}",
"function submitComment() {\r\n cccp_comment_dom.innerHTML = cccp_comment.value;\r\n mungeComment();\r\n comment.value = cccp_comment_dom.innerHTML;\r\n submit.click();\r\n}",
"function submitComment(e) {\n e.preventDefault();\n let newCommentData = { text: newComment, userId: user.id, postId: postId }\n console.log(newCommentData);\n\n API.Comment.createComment(newCommentData)\n .then(res => {\n console.log(\"Comment created!\");\n })\n .catch(err => console.log(err));\n\n\n setCommentSubmitStatus(!commentSubmitStatus);\n }",
"function submitComment(e) {\n e.preventDefault();\n let newCommentData = { text: newComment, userId: user.id, postId: postId }\n console.log(newCommentData);\n\n API.Comment.createComment(newCommentData)\n .then(res => {\n console.log(\"Comment created!\");\n loadPosts()\n })\n .catch(err => console.log(err));\n e.target.reset();\n }",
"static buttonClick(e) { \r\n\r\n Dom.injectCommentForm(e)\r\n // e.target.closest(\"[id^=prayer-box]\").append(Comment.formDisplay()\r\n }",
"function submitComment(comment) {\n $.post(\"/api/comments\", comment, function() {\n window.location.href = \"/comments\";\n });\n }",
"function submitUserComment() {\n $('body').on('click', '.js-add-comment-btn', function(event) {\n event.preventDefault();\n const id = STATE.currentStrain._id;\n const content = $('#add-comment').val();\n const author = sessionStorage.getItem('currentUser');\n\n if (content === '' || content === ' ') {\n $('.js-message').text('Comment is blank. Please add some content');\n $('.js-message').prop('hidden', false);\n return\n }\n\n addCommentToStrain(id, content, author);\n $('.js-message').prop('hidden', true);\n });\n}",
"function submitComment(e) {\n e.preventDefault();\n const postId = parseInt(e.target.getAttribute(\"id\"));\n const commentData = {\n comment: e.target.comments.value,\n };\n\n const options = {\n method: \"PATCH\",\n body: JSON.stringify(commentData),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n };\n\n fetch(`https://bloguefp.herokuapp.com/${postId}`, options)\n .then((r) => r.json())\n .catch(console.warn);\n\n commentsFunction(commentData, e.target);\n e.target.comments.value = \"\";\n}",
"function handleNewComment(){\n $(\"form[action$='comment']\").each(function(){\n $(this).submit(function(){\n refreshButtons();\n });\n\n $(this).keyup(function(ev){\n // This is the command key. Refresh every time because listening to the\n // full cmd+enter combo is impossible because of github's listeners.\n if(ev.keyCode == 91){\n setTimeout(refreshButtons,1000);\n }\n });\n });\n}",
"function handleFormSubmit(event) {\n event.preventDefault();\n // Wont submit the comment if we are missing a content or post\n if (!contentInput.val().trim() || !postSelect.val()) {\n return;\n }\n // Constructing a newComment object to hand to the database\n var newComment = {\n content: contentInput.val().trim(),\n PostId: postSelect.val()\n };\n\n // If we're updating a comment run updateComment to update a comment\n // Otherwise run submitComment to create a whole new comment\n if (updating) {\n newComment.id = commentId;\n updateComment(newComment);\n } else {\n submitComment(newComment);\n }\n }",
"function submitComment() {\n const comment = $('#comment').val();\n const itemId = getUrlParam('itemId');\n\n if (comment != '' && itemId != null) {\n $.post('/itempagedata', {comment: comment, itemId: itemId})\n .done(function() {\n window.location.reload();\n })\n .fail(function() {\n console.log('Failed to send form data');\n });\n }\n}",
"function submitComment(comment) {\n $.post(\"/api/comments\", comment, () => {\n window.location.reload();\n });\n }",
"function commentPost(postId){\n // When clicking the comment button, also show the present comments:\n // First, empty the comments container:\n document.querySelector(\"#commentContainer\" + postId).innerHTML = \"\";\n // Load the comments and display them:\n showComments(postId);\n // Display the comment field and set it empty:\n let newComment = document.querySelector('#commentField' + postId);\n //newComment.style.opacity = 1;\n newComment.disabled = false;\n newComment.value = \"\";\n newComment.style.display = \"block\";\n newComment.autofocus = true;\n\n // Change the text of the comment button and disable it:\n let commentButton = document.querySelector('#commentButton' + postId);\n commentButton.innerHTML = \"Save Comment\";\n commentButton.disabled = true;\n commentButton.onclick = function() {\n sendComment(postId);\n }\n // Display the cancel button:\n let commentCancelButton = document.querySelector('#commentCancel' + postId)\n commentCancelButton.style.display = \"block\";\n\n // If text is entered in the comment field, enable the save comment button:\n newComment.onkeyup = function(){\n if (newComment.value.length > 0){\n commentButton.disabled = false;\n } else {\n commentButton.disabled = true;\n }\n }\n}",
"function updateComment() {\n $(document).on(\"submit\", \".save-comment\", function(event) {\n event.preventDefault();\n var values = $(this).serialize();\n var url = $(this).attr('action');\n $.post(url, values, function(data) {\n var comment = new Comment(data);\n var id = \"#\" + comment.id;\n $(id + ' .comment-content').html(comment.content);\n }, \"json\");\n }); \n}",
"function submitWithEscapeCommentToPost ()\r\n{\r\n escapeChars(document.getElementsByClassName(\"commentToPostText\")[0]);\r\n}",
"function sendCommentButtonPressed() {\n\n // Extract comment parameters, currently displayed document is the reference document\n var refid = getCurrentDocId();\n var title = \"\";\n var tags = \"\";\n var text = document.getElementById('comment_text').value;\n\n // Submit comment as new document to the contract\n sendDocument(refid, title, tags, text);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get an identifier for a layer that can be used in a target= option (returns name if layer has a unique name, or a numerical id) | function getLayerTargetId(catalog, lyr) {
var nameCount = 0,
name = lyr.name,
id;
catalog.getLayers().forEach(function(o, i) {
if (lyr.name && o.layer.name == lyr.name) nameCount++;
if (lyr == o.layer) id = String(i + 1);
});
if (!id) error('Layer not found');
return nameCount == 1 ? lyr.name : id;
} | [
"function getID(layer)\n{\n\treturn layer.url ? layer.id : layer.id;\n}",
"function getID(layer)\n{\n\treturn layer.url ? layer.id : layer.featureCollection.layers[0].id;\n}",
"function getID(layer)\r\n\t\t\t{\r\n\t\t\t\treturn layer.url ? layer.id : layer.id;\r\n\t\t\t}",
"function getLayerIdFromAnchorName(name){\n id = \"#\"+settings.layerPrefix+name;\n if(!$(id).size())\n return \"\";\n return id;\n\t }",
"function layer_name(name) { return '#'.concat(name); }",
"function getIdentifier(target) {\n return getStateTreeNode(target).identifier;\n }",
"function getLayerID()\r{\r var ref = new ActionReference();\r ref.putEnumerated( charIDToTypeID('Lyr '),charIDToTypeID('Ordn'),charIDToTypeID('Trgt') );\r amID = executeActionGet(ref).getInteger(stringIDToTypeID( \"layerID\" ));\r return amID;\r}",
"function getIdentifier(target) {\n // check all arguments\n assertIsStateTreeNode(target, 1);\n return getStateTreeNode(target).identifier;\n}",
"function getLayerName(id) {\n var layerReference = new ActionReference();\n layerReference.putProperty(charIDToTypeID(\"Prpr\"), charIDToTypeID(\"Nm \"));\n layerReference.putIdentifier(charIDToTypeID(\"Lyr \"), id);\n var descriptor = executeActionGet(layerReference);\n return descriptor.getString(charIDToTypeID(\"Nm \"));\n}",
"static LayerToName() {}",
"selectedLayerId(state) {\n const selected = Object.keys(state.selected)\n if (selected.length === 1) {\n const id = selected[0]\n const part = state.parts[id]\n if (!part.children) {\n return id\n }\n }\n return null\n }",
"function buildLayerName(id){\n\tvar layername = \"\";\n\tswitch (id){\n\t\tcase \"montypemapbtn\":\n\t\t\tlayername = \"Monuments by Type: \" + buildParamString(id,\", \",false,0);\n\t\t\treturn layername;\n\t\tcase \"monperiodmapbtn\":\n\t\t\tlayername = \"Monuments by Period: \" + buildParamString(id,\", \",false,0);\n\t\t\treturn layername;\n\t\tcase \"objtypemapbtn\":\n\t\t\tlayername = \"Objects by Type: \" + buildParamString(id,\", \",false,0);\n\t\t\treturn layername;\n\t\tcase \"objperiodmapbtn\":\n\t\t\tlayername = \"Objects by Period: \" + buildParamString(id,\", \",false,0);\n\t\t\treturn layername;\n\t\tcase \"objmaterialmapbtn\":\n\t\t\tlayername = \"Objects by Material: \" + buildParamString(id,\", \",false,0);\n\t\t\treturn layername;\n\t}\t\t\n}",
"getActivationFromId(id){\r\n let activation = \"\";\r\n this._layers.forEach((layer) =>{\r\n if(layer.id == id){\r\n activation = layer.activation;\r\n }\r\n });\r\n return activation;\r\n }",
"function generateKeyForLayer(layer, stringsDict) {\n var key = layer.container.name + '-' + layer.index;\n var keyWithIndex = key;\n var index = 1;\n while (stringsDict[keyWithIndex]) {\n keyWithIndex = key + '-' + index;\n index = index + 1;\n }\n return keyWithIndex;\n}",
"function getIdentifier$$1(target) {\n // check all arguments\n if (true) {\n if (!isStateTreeNode$$1(target))\n fail(\"expected first argument to be a mobx-state-tree node, got \" + target + \" instead\");\n }\n return getStateTreeNode$$1(target).identifier;\n}",
"get id() {\n return `${this._layer.getID()}-${this._id}`\n }",
"deduplicateName( d ) {\n let target = d3.select( `#${ d.id }` );\n target.property('value', Hoot.layers.checkLayerName( target.property('value') ));\n }",
"function getSelectedParameterId(layer, strip) {\n const button0 = toButtonId(layer, 1, strip);\n const button1 = toButtonId(layer, 2, strip);\n\n const state0 = getButtonState(button0) ? 1 : 0;\n const state1 = getButtonState(button1) ? 1 : 0;\n\n // which register was choosed by button state\n const register = (state1 << 1) + state0;\n return toParameterId(layer, strip, register);\n}",
"function getLayerCode(layerCtrlId) {\n var layerCode = layerCtrlId.slice(layerCtrlId.lastIndexOf(\"$\") + 1); // slices the control name with '$' as identifier and gets the last element\n\n return layerCode;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the JSON Schema version number that corresponds to the Swagger/OpenAPI version number | function getJsonSchemaVersionNumber ({ swagger, openapi }) {
if (swagger && swagger.startsWith("2.0")) {
// Swagger 2.0 uses JSON Schema Draft 4
return "draft-04";
}
else if (openapi && openapi.startsWith("3.0")) {
// OpenAPI 3.0 uses JSON Schema Wright Draft 00 (a.k.a. Draft 5).
// This library doesn't officially support Draft 5, but it's nearly identical to Draft 4.
return "draft-04";
}
else if (openapi && openapi.startsWith("3.1")) {
// OpenAPI 3.1 uses JSON Schema 2019-09
return "2019-09";
}
else {
throw new Error(`Unknown Swagger/OpenAPI version: ${swagger || openapi}`);
}
} | [
"schemaVersion() {\r\n if (this.getType().indexOf(\":\") == -1)\r\n return 1;\r\n return 2;\r\n }",
"function getSchemaVersion (obs) {\n if (obs.schemaVersion) return obs.schemaVersion\n if (typeof obs.device_id === 'string' &&\n typeof obs.created === 'string' &&\n typeof obs.tags === 'undefined') return 1\n if (typeof obs.created_at === 'undefined' &&\n typeof obs.tags !== 'undefined' &&\n typeof obs.tags.created === 'string') return 2\n return null\n}",
"static version() {\n return SCHEMA_VERSION;\n }",
"get schemaVersion() {\n return this.getStringAttribute('schema_version');\n }",
"get schemaVersion() {\n this._ensureOpen();\n return this._connection.schemaVersion;\n }",
"static version() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require('../schema/cloud-assembly.version.json').version;\n }",
"function graphqlSchemaVersion (newSchema, oldSchema = null, oldVersion = DEFAULT_VERSION) {\n if (!oldSchema) { return oldVersion }\n\n const increment = diffSchema(new Pair(newSchema, oldSchema)\n .map(normalizeSchema)\n .map(buildClientSchema))\n if (increment === INCREMENT_NONE) { return oldVersion }\n if (increment < INCREMENT_MINOR) { return semver.inc(oldVersion, 'patch') }\n if (increment < INCREMENT_MAJOR) { return semver.inc(oldVersion, 'minor') }\n if (increment === INCREMENT_MAJOR) { return semver.inc(oldVersion, 'major') }\n}",
"get docVersionKeyName(){\n // mongoose's __v but name can change by changing schema.options.versionKey\n return this._schemaOptions['docVersionKeyName'];\n }",
"get schemaType() {\n const _schema = _namespaces.get(this);\n let _schemaData = null;\n [\"openapi\", \"swagger\"].forEach((type) => {\n if (_schema.model.schema.hasOwnProperty(type)) {\n _schemaData = {\n type: type,\n version: _schema.model.schema[type],\n };\n }\n });\n\n return _schemaData;\n }",
"function getVersion(req) {\n let version;\n if (req) {\n if (!req.version) {\n if (req.headers && req.headers['accept-version']) {\n version = req.headers['accept-version'];\n }\n } else {\n version = String(req.version);\n }\n }\n\n return version;\n}",
"function getVersion() {\n var packageJson = JSON.parse(fs.readFileSync(path.normalize(lazoPath + '/package.json'), 'utf8'));\n return packageJson.version;\n}",
"function GetVersion() {\r\n return exports.PACKAGE_JSON.version;\r\n}",
"getVersion() {\n return this.defn.info.version;\n }",
"function detectApiVersionMiddleware(req, res, next) {\n const version = parseInt(req.headers[\"n-api-version\"], 10) || parseInt(req.params.apiVersion, 10) || 0;\n req.apiVersion = res.apiVersion = version;\n\n next();\n}",
"apiVersion() {\n return this.options.apiVersion || 3;\n }",
"function getVersion() {\n return require(path.join(__dirname, 'package.json')).version;\n}",
"function getVersion(){\n return version\n }",
"versionNumber () {\n let release = this.release();\n if (release) {\n return release.versionNumber\n }\n }",
"getFhirVersion() {\n return (0, lib_1.fetchConformanceStatement)(this.state.serverUrl).then(metadata => metadata.fhirVersion);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handler to remove note from a group | function removeNoteFromGroup(userId, groupId, noteId, done) {
logger.info("Inside service method - remove note from a group");
groupsDao.removeNoteFromGroup(userId, groupId, noteId, done);
} | [
"function removeNote(){}",
"function removeNote(e) {\n div_id = e.path[2].id;\n if (div_id !== 'data') {\n // do not delete the entire data element accidentally due to html image glitches.\n document.getElementById(div_id).remove();\n save_notes();\n loadNotes();\n }\n }",
"handler(argv) {\n notes.removeNote(argv.title)\n // console.log('Removing the note')\n }",
"function removeNote(e) {\n var noteToRemove = e.path[1];\n for (var i = 0; i < notesArray.length; i++) {\n if (notesArray[i].id == noteToRemove.id) {\n styleControl(noteToRemove, \"opacity\", \"0\");\n setTimeout(function() {\n removeNoteFromDom(notesArray[i].id);\n notesArray.splice(i, 1);\n localStorage.setItem(\"mynotes\", JSON.stringify(notesArray));\n }, 1000);\n break;\n }\n }\n}",
"function removeNote(e) {\n var noteToRemove = e.path[1];\n for (var i = 0; i < notesArray.length; i++) {\n if (notesArray[i].id == noteToRemove.id) {\n styleControl(noteToRemove, \"opacity\", \"0\");\n setTimeout(function() {\n removeNoteFromDom(notesArray[i].id);\n notesArray.splice(i, 1);\n localStorage.setItem(\"notes\", JSON.stringify(notesArray));\n }, 1000);\n break;\n }\n }\n}",
"function removeNote(){\n\tthis.parentNode.remove();\n\tupdateNoteNumbers();\n}",
"function removeNote(e){\n \n if (e.target.classList.contains('remove-note')){\n e.target.parentElement.remove();\n }\n}",
"function deleteNote(note) {\n note.parentNode.removeChild(note);\n}",
"deleteNote(tick) {\n delete this.notes[tick];\n }",
"removeNote() {\n Api.put('note', {\n taskId: this.model.get('taskId'),\n noteId: this.model.get('_id'),\n isDeleted: true\n }).then(res => {\n if (res.flag === 202) {\n this.model.destroy();\n } else {\n new Noty({ text: res.message, type: 'error' }).show();\n }\n }, e => new Noty({ text: e.responseJSON.message, type: 'error' }).show());\n }",
"function removeNote(){\n\t$('.playerNotes .notesWrapper').each(function(index, element) {\n\t\tif($(this).attr('data-array')==curNote){\n\t\t\t$(this).remove();\n\t\t}\n });\n\tgenerateArray(false);\n\thighLightNote(false);\n\tstopGame();\n}",
"deleteNote() {\n this.actionBuffer.addAction('deleteNote');\n const measureSelections = this._undoTrackerMeasureSelections('delete note');\n this.tracker.selections.forEach((sel) => {\n const altSel = this._getEquivalentSelection(sel);\n\n // set the pitch to be a good position for the rest\n const pitch = JSON.parse(JSON.stringify(\n SmoMeasure.defaultPitchForClef[sel.measure.clef]));\n const altPitch = JSON.parse(JSON.stringify(\n SmoMeasure.defaultPitchForClef[altSel.measure.clef]));\n sel.note.pitches = [pitch];\n altSel.note.pitches = [altPitch];\n\n // If the note is a note, make it into a rest. If the note is a rest already,\n // make it invisible. If it is invisible already, make it back into a rest.\n if (sel.note.isRest() && !sel.note.hidden) {\n sel.note.makeHidden(true);\n altSel.note.makeHidden(true);\n } else {\n sel.note.makeRest();\n altSel.note.makeRest();\n sel.note.makeHidden(false);\n altSel.note.makeHidden(false);\n }\n });\n this._renderChangedMeasures(measureSelections);\n }",
"function handlenoteDelete() {\n var currentnote = $(this).parents(\".note-panel\").data(\"id\");\n deletenote(currentnote);\n }",
"removeGroup( groupName) {\r\n // Get the index of the group object in the list.\r\n const groupIndex = this.list.findIndex( item => {\r\n return item.name.toLowerCase() === groupName.toLowerCase();\r\n })\r\n // Delete 1 object from the list at index retrieved.\r\n this.list.splice(groupIndex, 1);\r\n }",
"function deleteGroup (group) {\n // Confirm that user wants to delete message if not return\n swal({\n title: 'Deleting Group',\n text: 'Are you sure you want to delete your Group?', \n icon: 'warning',\n buttons: ['Cancel', 'Yes'],\n dangerMode: true\n })\n .then(function (value) {\n if (value == null) { // Escape deletion \n return\n } else { // Proceed with deletion \n \n // Remove message from UI\n group.parentElement.removeChild(group);\n // Remove message from Initiative object \n let id = group.id.replace('group', ''); // remove ui tag from id \n //console.log(\"group object in delete:\", id)\n currentInitiative.groups.delete(id); \n // Send updates to main\n let ipcInit = currentInitiative.pack_for_ipc();\n ipc.send('save', currentInitiativeId, ipcInit); \n };\n });\n}",
"function removeNote(e) {\n let currentNote = e.target;\n let parent = currentNote.parentElement;\n if (currentNote.classList[0] === \"deleteButton\") {\n removeFromLocalStorage(parent.id);\n \n parent.remove(e);\n \n }\n \n \n}",
"function removeSelectedNote () {\n var path = curr_note_fn;\n deselectNote();\n client.remove(path, function (err, stat) {\n loadNoteList(refreshNoteList);\n });\n return false;\n}",
"function deleteButtonPressed(note) {\n removeFromDb(note);\n}",
"removeNote(noteId){\n console.log(noteId);\n // 29) to remove the note from our database, we have to tell it from what reference-- in this case we tell it to go to the key\n //we're grabbing that location in our database and saying to remove it \n //now move on to notesCard.js to allow us to edit our cards\n\n //63) we also need to grab the userID as well again\n // part 64 starts in our notesCard which is for editing \n const userId = firebase.auth().currentUser.uid;\n\n //62) we grabbed from 61) because we tiered it and have to drill down to where the note is\n const dbRef = firebase.database().ref(`users/${userId}/notes/${noteId}`);\n dbRef.remove();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Task 1 format a name and email address into the following String format: | function formatEmailAddress(name, email) {
return name + ' <' + email + '>';
} | [
"function buildEmailAddressString(address) {\r\n return address.displayName + \":\" + address.emailAddress + \";\";\r\n }",
"function buildEmailAddressString(address) {\n return address.displayName;\n }",
"function my_email(x,y){return x+\".\"+y+\"@evolveu.ca\"}",
"function buildEmailAddressString(address) {\n return address.displayName + \" <\" + address.emailAddress + \">\";\n }",
"function buildEmailAddressString(address) {\n return address.displayName + \" <\" + address.emailAddress + \">\";\n }",
"function inputAndFormatEmail() {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise(resolve => rl.question('Enter Email ', result => {\n rl.close();\n if (i.test(String(result).toLowerCase()) !== true) {\n console.log('Invalid Email');\n return null;\n } else {\n result = 'https://www.' + result.split('@')[1]\n resolve(result);\n }\n }))\n}",
"function format_name(name) {\n var name_array = name.split(',');\n var from = (name_array[1] && name_array[1].startsWith(\"from:\")) ? name_array[1] : \"from:nominatim\";\n return name_array[0];//+\"<br/>\"+from+\"<br/>\"\n}",
"function generateUserName(email) {\n let username, fname, lname, owner;\n\n username = email.split(\"@\");\n username = username[0].split(\".\");\n\n fname = username[0];\n lname = username[1];\n\n fname = fname.charAt(0).toUpperCase() + fname.slice(1);\n lname = lname.charAt(0).toUpperCase() + lname.slice(1);\n\n owner = fname + \" \" + lname;\n\n return owner;\n}",
"function generateRequestorNameFromEmail(stakeholder) {\n var tempEmail = stakeholder;\n var emailArray = tempEmail.split(\"@\");\n var names = emailArray[0].replace(\".\", \" \");\n var name = toTitleCase(names);\n return name;\n}",
"function getShortName (userInfo) {\n if (userInfo.fullname) {\n var parts = userInfo.fullname.split(\" \");\n var shortName = \"\";\n parts.forEach(function (part) {\n shortName += part.charAt(0).toUpperCase();\n })\n return shortName;\n }\n return userInfo.email.charAt(0).toUpperCase();\n }",
"function getUname(email) {\n var username = \"\";\n for(var i = 1; i < email.length; i++) {\n if (email[i] != \"@\") {\n username += email[i - 1]\n }\n else {\n username += email[i - 1]\n break;\n }\n }\n return username;\n }",
"function buildEmailAddressesString(addresses) {\n if (addresses && addresses.length > 0) {\n var returnString = \"\";\n \n for (var i = 0; i < addresses.length; i++) {\n if (i > 0) {\n returnString = returnString + \"<br/>\";\n }\n returnString = returnString + buildEmailAddressString(addresses[i]);\n }\n \n return returnString;\n }\n \n return \"None\";\n }",
"function buildEmailAddressesString(addresses) {\n if (addresses && addresses.length > 0) {\n var returnString = \"\";\n\n for (var i = 0; i < addresses.length; i++) {\n if (i > 0) {\n returnString = returnString + \"<br/>\";\n }\n returnString = returnString + buildEmailAddressString(addresses[i]);\n }\n\n return returnString;\n }\n\n return \"None\";\n }",
"function getFullName(name, surname) {\n return ('Your full name is ' + name + ' ' + surname);\n}",
"function getUname(email) {\n var username = \"\";\n for (var i = 1; i < email.length; i++) {\n if (email[i] != \"@\") {\n username += email[i - 1]\n } else {\n username += email[i - 1]\n break;\n }\n }\n return username;\n }",
"function make_name(email) {\n\t\t\tif (email && typeof email === 'string') {\n\t\t\t\tconst pos = email.indexOf('@');\n\t\t\t\tconst LIMIT = 20;\n\t\t\t\tif (pos !== -1) {\n\t\t\t\t\treturn email.substring(0, pos).substring(0, LIMIT);\t\t// cut string off after @ and limit length\n\t\t\t\t}\n\t\t\t\treturn email.substring(0, LIMIT);\n\t\t\t}\n\t\t\treturn null;\n\t\t}",
"function email() {\n return from(String).format(JsonFormatTypes.EMAIL);\n}",
"function getFullName (name, surname) {\n return 'Your full name is ' + name + ' ' + surname + '.'\n}",
"function getUserFullName(){\n if( this.firstname && this.lastname )\n return this.firstname + ' ' + this.lastname;\n else if( this.firstname )\n return this.firstname;\n else if( this.lastname )\n return this.lastname;\n else\n return this.email;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the PR info (labels and body) to the commit | async addPrInfoToCommit(commit) {
const modifiedCommit = Object.assign({}, commit);
if (!modifiedCommit.labels) {
modifiedCommit.labels = [];
}
if (modifiedCommit.pullRequest) {
const [err, info] = await await_to_js_1.default(this.git.getPr(modifiedCommit.pullRequest.number));
if (err || !info || !info.data) {
return modifiedCommit;
}
const labels = info ? info.data.labels.map((l) => l.name) : [];
modifiedCommit.labels = [
...new Set([...labels, ...modifiedCommit.labels]),
];
modifiedCommit.pullRequest.body = info.data.body;
modifiedCommit.subject = info.data.title || modifiedCommit.subject;
const hasPrOpener = modifiedCommit.authors.some((author) => author.username === info.data.user.login);
// If we can't find the use who opened the PR in authors attempt
// to add that user.
if (!hasPrOpener) {
const user = await this.git.getUserByUsername(info.data.user.login);
if (user) {
modifiedCommit.authors.push(Object.assign(Object.assign({}, user), { username: user.login }));
}
}
}
return modifiedCommit;
} | [
"async addPrInfoToCommit(commit) {\n const modifiedCommit = Object.assign({}, commit);\n if (!modifiedCommit.labels) {\n modifiedCommit.labels = [];\n }\n if (modifiedCommit.pullRequest) {\n const info = await this.git.getPr(modifiedCommit.pullRequest.number);\n if (!info || !info.data) {\n return modifiedCommit;\n }\n const labels = info ? info.data.labels.map(l => l.name) : [];\n modifiedCommit.labels = [\n ...new Set([...labels, ...modifiedCommit.labels])\n ];\n modifiedCommit.pullRequest.body = info.data.body;\n if (!modifiedCommit.authors.find(author => Boolean(author.username))) {\n const user = await this.git.getUserByUsername(info.data.user.login);\n if (user) {\n modifiedCommit.authors.push(Object.assign(Object.assign({}, user), { username: user.login }));\n }\n }\n }\n return modifiedCommit;\n }",
"function print_with_commit(base_body){\r\n var msg = \"Issue co maju commit: \";\r\n for(var i in base_body) {\r\n if (base_body[i].pull_request != undefined) {\r\n msg += \" \" + i;\r\n }\r\n }\r\n console.log(msg);\r\n}",
"async generateCommitNote(commit) {\n var _a;\n const subject = commit.subject\n ? commit.subject\n .split(\"\\n\")[0]\n .trim()\n .replace(\"[skip ci]\", \"\\\\[skip ci\\\\]\")\n : \"\";\n let pr = \"\";\n if ((_a = commit.pullRequest) === null || _a === void 0 ? void 0 : _a.number) {\n const prLink = url_join_1.default(this.options.baseUrl, \"pull\", commit.pullRequest.number.toString());\n pr = `[#${commit.pullRequest.number}](${prLink})`;\n }\n const user = await this.createUserLinkList(commit);\n return `- ${subject}${pr ? ` ${pr}` : \"\"}${user ? ` (${user})` : \"\"}`;\n }",
"async addLabelToPr(pr, label) {\n this.logger.verbose.info(`Creating \"${label}\" label to PR ${pr}`);\n const result = await this.github.issues.addLabels({\n issue_number: pr,\n owner: this.options.owner,\n repo: this.options.repo,\n labels: [label],\n });\n this.logger.veryVerbose.info(\"Got response from addLabels\\n\", result);\n this.logger.verbose.info(\"Added labels on Pull Request.\");\n return result;\n }",
"async function commitAndCreatePullRequest(moduleInfo) {\n const changelogBranchName = `${moduleInfo.nameWithDash}-release-${moduleInfo.version}`;\n await execShellCommand(\n `git checkout -b ${changelogBranchName} && git add . && git commit -m \"chore(${moduleInfo.nameWithDash}): update changelogs\" && git push --set-upstream origin ${changelogBranchName}`\n );\n await execShellCommand(\n `gh pr create --title \"${moduleInfo.nameWithSpace}: Updating changelogs\" --body \"This is an automated PR.\" --base master --head ${changelogBranchName}`\n );\n console.log(\"Created PR for changelog updates.\");\n}",
"async prBody(options) {\n const { message, pr, context = 'default', dryRun, delete: deleteFlag } = options;\n if (!this.git) {\n throw this.createErrorMessage();\n }\n this.logger.verbose.info(\"Using command: 'pr-body'\");\n const prNumber = this.getPrNumber('pr-body', pr);\n if (dryRun) {\n if (deleteFlag) {\n this.logger.log.info(`Would have deleted PR body on ${prNumber} under \"${context}\" context`);\n }\n else {\n this.logger.log.info(`Would have appended to PR body on ${prNumber} under \"${context}\" context:\\n\\n${message}`);\n }\n }\n else {\n if (deleteFlag) {\n await this.git.addToPrBody('', prNumber, context);\n }\n if (message) {\n await this.git.addToPrBody(message, prNumber, context);\n }\n this.logger.log.success(`Updated body on PR #${prNumber}`);\n }\n }",
"function formatNotes(data){\n\treturn data.map(commit =>\n\t\t`- [:information_source:](${commit.html_url}) - ${commit.commit.message} ${commit.author ? `- [${commit.author.login}](${commit.author.html_url})` : ''}`\n\t).join('\\n')\n}",
"function getPRInfo(body) {\n var prBody = body['pull_request'];\n var number = prBody.number;\n var name = prBody.head.repo.name;\n\n return {\n number: number,\n name: name\n };\n}",
"function addProposeChangesToolTips() {\n const steps = ['Edit File', 'Create Pull Request', 'Pull Request Opened'];\n\n addProgressBar(2, 3, '.repository-content', steps);\n\n $('#pull_request_body').attr(\n 'placeholder',\n 'You can add a more detailed description here if needed.'\n );\n\n try {\n var branchName = document.getElementsByClassName('branch-name')[0].innerText;\n } catch {\n var isComparingBranch = true;\n }\n\n let newHeaderText = `Finish the pull request submission below to allow others to accept the changes. These changes can be viewed later under the branch name: ' +\n ${branchName}`;\n\n if (isComparingBranch) {\n newHeaderText =\n 'Finish the pull request submission below to allow others to accept the changes';\n\n $('.gh-header-title').text('Create Pull Request');\n }\n\n $('.gh-header-meta').text(newHeaderText);\n\n let pullRequestTitle = document.getElementsByClassName('gh-header-title')[1];\n pullRequestTitle.innerHTML = 'Create pull request';\n\n const branchContainerText =\n 'This represents the origin and destination of your changes if you are not sure, leave it how it is, this is common for small changes.';\n\n const topRibbon = document.getElementsByClassName('js-range-editor')[0];\n topRibbon.style.width = '93%';\n topRibbon.style.display = 'inline-block';\n\n // ribbon above current current branch and new pull request branch\n const currentBranchIcon = new ToolTipIcon(\n 'H4',\n 'helpIcon',\n branchContainerText,\n '.js-range-editor'\n );\n\n currentBranchIcon.createIcon();\n\n $(currentBranchIcon.toolTipElement).insertAfter(currentBranchIcon.gitHubElement);\n\n // move button row to left side of editor\n const buttonRow = document.getElementsByClassName('d-flex flex-justify-end m-2')[0];\n buttonRow.classList.remove('flex-justify-end');\n buttonRow.classList.add('flex-justify-start');\n\n const confirmPullRequestText =\n 'By clicking this button you will create the pull request to allow others to view your changes and accept them into the repository.';\n\n const submitButtonClass = '.js-pull-request-button';\n\n // icon next to create pull request button\n const createPullRequestBtn = new ToolTipIcon(\n 'H4',\n 'helpIcon',\n confirmPullRequestText,\n submitButtonClass\n );\n\n createPullRequestBtn.createIcon();\n\n $(createPullRequestBtn.toolTipElement).insertAfter(createPullRequestBtn.gitHubElement);\n\n const summaryText =\n 'This shows the amount of commits in the pull request, the amount of files you changed in the pull request, how many comments were on the commits for the pull request and the ammount of people who worked together on this pull request.';\n\n const summaryClass = '.overall-summary';\n\n // override the container width and display to add icon\n const numbersSummaryContainer = document.getElementsByClassName('overall-summary')[0];\n numbersSummaryContainer.style.width = '93%';\n numbersSummaryContainer.style.display = 'inline-block';\n\n // icon above summary of changes and commits\n const requestSummaryIcon = new ToolTipIcon('H4', 'helpIcon', summaryText, summaryClass);\n\n requestSummaryIcon.createIcon();\n\n requestSummaryIcon.toolTipElement.style = 'float:right;';\n\n $(requestSummaryIcon.toolTipElement).insertAfter(requestSummaryIcon.gitHubElement);\n\n const comparisonClass = '.details-collapse';\n\n const changesText =\n 'This shows the changes between the orginal file and your version. Green(+) represents lines added. Red(-) represents removed lines';\n\n // icon above container for changes in current pull request\n const comparisonIcon = new ToolTipIcon('H4', 'helpIcon', changesText, comparisonClass);\n\n comparisonIcon.createIcon();\n\n const commitSummaryContainer = document.getElementsByClassName('details-collapse')[0];\n\n commitSummaryContainer.style.width = '93%';\n commitSummaryContainer.style.display = 'inline-block';\n\n $(comparisonIcon.toolTipElement).insertAfter(comparisonIcon.gitHubElement);\n}",
"pushChangesToForkAndCreatePullRequest(targetBranch, proposedForkBranchName, title, body) {\n return tslib.__awaiter(this, void 0, void 0, function* () {\n const repoSlug = `${this.git.remoteParams.owner}/${this.git.remoteParams.repo}`;\n const { fork, branchName } = yield this._pushHeadToFork(proposedForkBranchName, true);\n const { data } = yield this.git.github.pulls.create(Object.assign(Object.assign({}, this.git.remoteParams), { head: `${fork.owner}:${branchName}`, base: targetBranch, body,\n title }));\n // Add labels to the newly created PR if provided in the configuration.\n if (this.config.releasePrLabels !== undefined) {\n yield this.git.github.issues.addLabels(Object.assign(Object.assign({}, this.git.remoteParams), { issue_number: data.number, labels: this.config.releasePrLabels }));\n }\n info(green(` ✓ Created pull request #${data.number} in ${repoSlug}.`));\n return {\n id: data.number,\n url: data.html_url,\n fork,\n forkBranch: branchName,\n };\n });\n }",
"pushChangesToForkAndCreatePullRequest(targetBranch, proposedForkBranchName, title, body) {\n return __awaiter(this, void 0, void 0, function* () {\n const repoSlug = `${this.git.remoteParams.owner}/${this.git.remoteParams.repo}`;\n const { fork, branchName } = yield this._pushHeadToFork(proposedForkBranchName, true);\n const { data } = yield this.git.github.pulls.create(Object.assign(Object.assign({}, this.git.remoteParams), { head: `${fork.owner}:${branchName}`, base: targetBranch, body,\n title }));\n // Add labels to the newly created PR if provided in the configuration.\n if (this.config.releasePrLabels !== undefined) {\n yield this.git.github.issues.addLabels(Object.assign(Object.assign({}, this.git.remoteParams), { issue_number: data.number, labels: this.config.releasePrLabels }));\n }\n info(green(` ✓ Created pull request #${data.number} in ${repoSlug}.`));\n return {\n id: data.number,\n url: data.html_url,\n fork,\n forkBranch: branchName,\n };\n });\n }",
"function prMessage(data) {\n var pr = data.pull_request;\n var action = data.action;\n var attachments = [];\n var slackMessage;\n var text;\n\n // Repo and PR title\n var repo = '[' + data.repository.full_name + '] ';\n var prTitle = '#' + pr.number + ' ' + pr.title;\n\n // Linked Title and User\n var titleLinked = helper.hyperLink(prTitle, pr.html_url);\n var userLink = helper.hyperLink(pr.user.login, pr.user.html_url);\n\n // PR updated\n if (action === 'synchronize') {\n text = repo + 'Pull request updated: ' + titleLinked + ' by ' + userLink;\n }\n\n // PR closed\n if (action === 'closed') {\n text = repo + 'Pull request ' + action + ': ' + titleLinked + ' by ' + userLink;\n }\n\n // PR submitted\n if (action === 'opened') {\n text = repo + 'Pull request submitted by ' + userLink;\n attachments = [{\n title: prTitle,\n title_link: pr.html_url,\n text: pr.body,\n color: 'good'\n }];\n }\n\n slackMessage = {\n text: text,\n attachments: attachments\n };\n\n return slackMessage;\n}",
"async _addToGitHub(label) {\n let params = Util.commonParams();\n params.issue_number = this._prNum;\n params.labels = [];\n params.labels.push(label.name);\n\n await GH.addLabels(params);\n\n label.markAsAdded();\n }",
"async afterStatus({ data }) {\n if (data.state !== 'failure') {\n return;\n }\n\n const { user } = this.context.payload.pull_request;\n\n const comment = this.context.issue({\n body: `\nUh oh!\n\nLooks like this PR has some conflicts with the base branch, @${ user.login }.\n\nPlease bring your branch up to date as soon as you can.\n `,\n });\n\n await this.context.github.issues.createComment(comment);\n }",
"async function createPr(\n branchName,\n title,\n body,\n labels,\n useDefaultBranch,\n statusCheckVerify\n) {\n let base = useDefaultBranch ? config.defaultBranch : config.baseBranch;\n // istanbul ignore if\n if (config.mirrorMode && branchName === 'renovate/configure') {\n logger.debug('Using renovate-config as base branch for mirror config');\n base = 'renovate-config';\n }\n // Include the repository owner to handle forkMode and regular mode\n const head = `${config.repository.split('/')[0]}:${branchName}`;\n const options = {\n body: {\n title,\n head,\n base,\n body,\n },\n };\n // istanbul ignore if\n if (config.forkToken) {\n options.token = config.forkToken;\n }\n logger.debug({ title, head, base }, 'Creating PR');\n const pr = (await get.post(\n `repos/${config.parentRepo || config.repository}/pulls`,\n options\n )).body;\n pr.displayNumber = `Pull Request #${pr.number}`;\n pr.branchName = branchName;\n await addLabels(pr.number, labels);\n if (statusCheckVerify) {\n logger.debug('Setting statusCheckVerify');\n await setBranchStatus(\n branchName,\n 'renovate/verify',\n 'Renovate verified pull request',\n 'success',\n 'https://renovatebot.com'\n );\n }\n return pr;\n}",
"async createPullRequest(info) {\n const botUser = info.user\n const regArr = await this.sanitizeText(\n botUser,\n info.text,\n regexOptions.repoUserTitleBranch\n )\n const regObj = {\n repo: regArr[1],\n username: config.bit.username,\n title: regArr[2],\n branch: regArr[3],\n }\n const { repo, username, title, branch } = regObj\n this.bitbucketAuth()\n await bb.repositories.createPullRequest({\n repo_slug: repo,\n username: username,\n _body: { title: title, source: { branch: { name: branch } } },\n })\n }",
"async label({ pr } = {}) {\n if (!this.git) {\n throw this.createErrorMessage();\n }\n this.logger.verbose.info(\"Using command: 'label'\");\n let labels = [];\n if (pr) {\n labels = await this.git.getLabels(pr);\n }\n else {\n const pulls = await this.git.getPullRequests({\n state: 'closed'\n });\n const lastMerged = pulls\n .sort((a, b) => new Date(b.merged_at).getTime() - new Date(a.merged_at).getTime())\n .find(pull => pull.merged_at);\n if (lastMerged) {\n labels = lastMerged.labels.map(label => label.name);\n }\n }\n if (labels.length) {\n console.log(labels.join('\\n'));\n }\n }",
"function addReviewPullRequestTips() {\n const steps = ['Edit File', 'Confirm Pull Request', 'Pull Request Opened'];\n\n addProgressBar(3, 3, '.gh-header-show', steps);\n\n const titleTest = 'new'; // document.getElementsByClassName('js-issue-title')[0];\n\n const branchContainerText =\n 'This indicates that the pull request is open meaning someone will get to it soon.';\n\n const pullRequestStatusIcon = new ToolTipIcon(\n 'H4',\n 'helpIcon',\n branchContainerText,\n '.js-clipboard-copy'\n );\n\n pullRequestStatusIcon.createIcon();\n\n $(pullRequestStatusIcon.toolTipElement).insertAfter(pullRequestStatusIcon.gitHubElement);\n\n const requestButtonsText =\n 'This will close the pull request meaning people cannot view this! Do not click close unless the request was solved.';\n\n const requestButtonsClass = '.js-comment-and-button';\n\n const closePullRequestIcon = new ToolTipIcon(\n 'H4',\n 'helpIcon',\n requestButtonsText,\n requestButtonsClass\n );\n\n closePullRequestIcon.createIcon();\n\n $(closePullRequestIcon.toolTipElement).insertBefore(closePullRequestIcon.gitHubElement);\n\n closePullRequestIcon.toolTipElement.style.marginRight = '20px';\n\n /*\n var submitButtons = document.getElementsByClassName('d-flex flex-justify-end')[0];\n submitButtons.classList.remove('flex-justify-end');\n submitButtons.classList.add('flex-justify-start');*/\n\n $('.js-quick-submit-alternative').click((event) => {\n if (!Confirm(`Are you sure that you want to close the pull request: ${titleTest}?`)) {\n event.preventDefault();\n }\n });\n}",
"async addReviewerToPullRequest(info) {\n this.bitbucketAuth()\n let reviewers = await this.userLookup(info.team, info.individual)\n await bb.repositories.updatePullRequest({\n username: config.bit.username,\n repo_slug: info.repo,\n pull_request_id: info.pr_id,\n _body: {\n title: info.title,\n reviewers: [{ uuid: reviewers.uuid }],\n },\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apertura modal approvazione appunto e recupero codice argomento e appunto selezionati | function openModalApprovaAppunto(btn) {
idAppunto = parseInt($(btn).attr("id").split('_')[$(btn).attr("id").split('_').length - 1]);
idArgomento = parseInt($(btn).attr("id").split('_')[$(btn).attr("id").split('_').length - 2]);
$("#contModale").text("Sei sicuro di voler accettare questo allegato?");
$("#btnConfApprovAllegato").removeAttr("disabled");
$("#modalApprovAllegato").modal("show");
} | [
"function abrirModalPrato(tipo, prato, preco, quantPrato){\r\n\t\r\n\tmodalPratoTitle.innerText = tipo;\r\n\tlet html = \"<p>\"+prato+\"</p>\";\r\n\thtml += \"<p>R$ \"+preco+\"</p>\";\r\n\tmodalPratoInfo.innerHTML = html;\r\n\tquantidade.value = quantPrato;\r\n\tmodalPrato.modal('show');\r\n}",
"function openModalRifiutoArgomento(btn) {\n idAppunto = parseInt($(btn).attr(\"id\").split('_')[$(btn).attr(\"id\").split('_').length - 1]);\n $(\"#contModaleRifiuto\").text(\"Sei sicuro di voler rifiutare questo appunto?\");\n $(\"#btnConfRifiutoAllegato\").removeAttr(\"disabled\");\n $(\"#modalRifiutoAllegato\").modal(\"show\");\n}",
"function notificaRequest()\n{\n\t//imposta il contenuto del modal\n\t$('#modalHeader').html('Nuova richiesta di intervento');\n\t$('#modalBody').html('<p>Un utente richiede il tuo preventivo. Vuoi visualizzare la sua richiesta?</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//mostra il modal\n\t$('#panelNotifiche').modal('show');\n\t//spegne il bottone notifica\n\tspegniSeNotifica();\n}",
"function btnOKCertificadoHandler(){\r\n \r\n //se não é somente visualizacao.\r\n if($scope.viewStateFlags.inserindoNovaCertidao || $scope.viewStateFlags.alterandoCertidao){\r\n if($scope.viewStateFlags.inserindoNovaCertidao){\r\n inserirCertidao();\r\n }else{\r\n alterarCertidao();\r\n }\r\n }\r\n }",
"function carregaAgricultor(idClicado, opcao){\n// var Sessao = getSessao();\n var envio = {\n metodo: \"GET_POR_ID\",\n idpessoa: idClicado\n// usuario: Sessao.usuario,\n// sessao: Sessao.sessao\n };\n \n \n //chama a requisicao do servidor, o resultado é listado em uma tabela\n requisicao(true, \"agricultor/buscar\", envio, function(dadosRetorno) {\n if(dadosRetorno.sucesso){\n //testa qual opcao sera, editar ou mostrar\n if(opcao === \"modal\"){\n //carrega atributos no painel modal que sera exibido\n $(\"#modalTitulo\").text(\"Agricultor\");\n $(\"#itensModal\").append(\"<h3>\"+dadosRetorno.data.nome+\"</h3><h4> Sobrenome: \"+dadosRetorno.data.sobrenome+\"</h4><h4>Apelido: \"+dadosRetorno.data.apelido+\"</h4><h4> CPF: \"+dadosRetorno.data.cpf+\"</h4><h4> RG: \"+dadosRetorno.data.rg+\"</h4><h4> Data de nascimento: \"+dadosRetorno.data.datanascimento+\"</h4><h4> Sexo: \"+dadosRetorno.data.sexo+\"</h4><h4> Telefone1: \"+dadosRetorno.data.telefone1+\"</h4><h4>Telefone2\"+dadosRetorno.data.telefone2+\"</h4><h4>Email: \"+dadosRetorno.data.email+\"</h4><h4>Quantidade de crianças: \"+dadosRetorno.data.qtdcriancas+\"</h4><h4>Quantidade de integrantes: \"+dadosRetorno.data.qtdintegrantes+\"</h4><h4>Quantidade de grávidas: \"+dadosRetorno.data.qtdgravidas+\"</h4><h4>Estado civil: \"+dadosRetorno.data.estadocivil+\"</h4><h4>Escolaridade: \"+dadosRetorno.data.escolaridade+\"</h4>\");\n }else if(opcao === \"editar\"){\n $(\"#divItens\").empty().append('<h2 class=\"sub-header\">Editar agricultor</h2> <form data-toggle=\"validator\" role=\"form\" id=\"salvarEditAgri\" > <div class=\"form-group\"><label for=\"nomeAgricultor\" class=\"control-label\">Nome:</label><input type=\"text\" class=\"form-control\" id=\"nomeAgricultor\" placeholder=\"Digite o nome do agricultor...\" value=\"'+dadosRetorno.data.nome+'\" data-error=\"Por favor, informe o nome correto do agricultor.\" required ><div class=\"help-block with-errors\"></div></div><div class=\"form-group\"><label for=\"sobrenomeAgricultor\" class=\"control-label\">Sobrenome:</label><input type=\"text\" class=\"form-control\" id=\"sobrenomeAgricultor\" placeholder=\"Digite o sobrenome do agricultor...\" value=\"'+dadosRetorno.data.sobrenome+'\"></div><div class=\"form-group\"><label for=\"rgAgricultor\" class=\"control-label\">RG:</label><input type=\"text\" class=\"form-control\" id=\"rgAgricultor\" placeholder=\"Digite o rg do agricultor...\" value=\"'+dadosRetorno.data.rg+'\"></div><div class=\"form-group\"><label for=\"cpfAgricultor\" class=\"control-label\">CPF:</label><input type=\"text\" class=\"form-control\" id=\"cpfAgricultor\" placeholder=\"Digite o cpf do agricultor...\" value=\"'+dadosRetorno.data.cpf+'\" ></div><div class=\"form-group\"><label for=\"apelidoAgricultor\" class=\"control-label\">Apelido:</label><input type=\"text\" class=\"form-control\" id=\"apelidoAgricultor\" placeholder=\"Digite o apelido do agricultor...\" value=\"'+dadosRetorno.data.apelido+'\" ></div><div class=\"form-group\"><label for=\"dataNascAgricultor\" class=\"control-label\">Data de nascimento:</label><input type=\"text\" class=\"form-control\" id=\"dataNascAgricultor\" placeholder=\"Digite a data de nascimento do agricultor...\" value=\"'+dadosRetorno.data.datanascimento+'\" ></div><div class=\"form-group\" id=\"genero\"><input type=\"radio\" name=\"genero\" value=\"m\" checked> Masculino<br><input type=\"radio\" name=\"genero\" value=\"f\"> Feminino<br> <br></div><div class=\"form-group\"><label for=\"telefone1Agricultor\" class=\"control-label\">Telefone 1:</label><input type=\"text\" class=\"form-control\" id=\"telefone1Agricultor\" placeholder=\"(xx) xxxxx-xxxx\" value=\"'+dadosRetorno.data.telefone1+'\" ></div><div class=\"form-group\"><label for=\"telefone2Agricultor\" class=\"control-label\">Telefone 2:</label><input type=\"text\" class=\"form-control\" id=\"telefone2Agricultor\" placeholder=\"Digite o telefone 2 do agricultor...\" value=\"'+dadosRetorno.data.telefone2+'\" ></div><div class=\"form-group\"><label for=\"emailAgricultor\" class=\"control-label\">Email:</label><input type=\"text\" class=\"form-control\" id=\"emailAgricultor\" placeholder=\"Digite o email do agricultor...\" value=\"'+dadosRetorno.data.email+'\" ></div><div class=\"form-group\"><label for=\"escolaridadeAgricultor\" class=\"control-label\">Escolaridade:</label><select class=\"form-control \" id=\"escolaridadeAgricultor\" value=\"'+dadosRetorno.data.escolaridade+'\"><option>Ensino fundamental</option><option>Ensino fundamental incompleto</option><option>Ensino médio</option><option>Ensino médio incompleto</option><option>Ensino superior</option><option>Ensino superior incompleto</option><option>Pós-graduação</option><option>Pós-graduação incompleta</option><option>Sem escolaridade</option></select></div><div class=\"form-group\"><label for=\"estadocivilAgricultor\" class=\"control-label\">Estado civil:</label><select class=\"form-control \" id=\"estadocivilAgricultor\" value=\"'+dadosRetorno.data.estadocivil+'\"><option>Solteiro(a)</option><option>Casado(a)</option><option>Divorciado(a)</option><option>Viúvo(a)</option><option>Separado(a)</option><option>Companheiro(a)</option></select></div><hr><button type=\"submit\" class=\"btn btn-warning\">Salvar <span class=\"fa fa-save\" aria-hidden=\"true\"></span></button></form>');\n $('#salvarEditAgri').validator();\n }\n //retira o painel loading\n $(\".painelCarregando\").fadeOut(400);\n }else{\n //retira o painel loading\n $(\".painelCarregando\").fadeOut(400);\n alerta(\"Alerta!\", dadosRetorno.mensagem);\n }\n //atualiza a sessao\n updateSessao(dadosRetorno.sessao);\n });\n}",
"function carregaUnidade(idClicado, opcao){\n \n var envio = {\n metodo: \"GET_POR_ID\",\n idunidade: idClicado\n };\n \n //chama a requisicao do servidor, o resultado é listado em uma tabela\n requisicao(true, \"unidade/buscar\", envio, function(dadosRetorno) {\n if(dadosRetorno.sucesso){\n \n //testa qual opcao sera, editar ou mostrar\n if(opcao === \"modal\"){\n //carrega atributos no painel modal que sera exibido\n $(\"#modalTitulo\").text(\"Unidade\");\n// console.log(dadosRetorno.data);\n $(\"#itensModal\").append('<h3>'+dadosRetorno.data.nomeunidade+'</h3><h4> Cidade: '+dadosRetorno.data.nomecidade+'</h4><h4> Estado: '+dadosRetorno.data.nomeestado+'</h4><h4> País: '+dadosRetorno.data.nomepais+'</h4><h4> Telefone1: '+dadosRetorno.data.telefone1+'</h4><h4> Telefone2: '+dadosRetorno.data.telefone2+'</h4><h4> Email: '+dadosRetorno.data.email+'</h4><h4> Cnpj: '+dadosRetorno.data.cnpj+'</h4><h4> Razão social: '+dadosRetorno.data.razao_social+'</h4><h4> Nome fantasia: '+dadosRetorno.data.nome_fanta+'</h4><h4> Rua: '+dadosRetorno.data.rua+'</h4><h4> Bairro: '+dadosRetorno.data.bairro+'</h4><h4> Complemento: '+dadosRetorno.data.complemento+'</h4><h4> Latitude: '+dadosRetorno.data.gps_lat+'</h4><h4> Longitude: '+dadosRetorno.data.gps_long+'</h4>');\n }else if(opcao === \"editar\"){\n $(\"#divItens\").empty().append('<h2 class=\"sub-header\">Editar unidade</h2><form data-toggle=\"validator\" role=\"form\" id=\"salvarEditUnidade\"><div class=\"form-group\"><label for=\"nomeUnidade\" class=\"control-label\">Nome unidade:</label><input type=\"text\" class=\"form-control\" id=\"nomeUnidade\" placeholder=\"Digite o nome da unidade...\" value=\"'+dadosRetorno.data.nomeunidade+'\"></div><div class=\"form-group\"><label for=\"cnpj\" class=\"control-label\">CNPJ:</label><input type=\"text\" class=\"form-control\" id=\"cnpj\" placeholder=\"Digite o cnpj...\" value=\"'+dadosRetorno.data.cnpj+'\"></div><div class=\"form-group\"><label for=\"razaoSocial\" class=\"control-label\">Razão social:</label><input type=\"text\" class=\"form-control\" id=\"razaoSocial\" placeholder=\"Digite a razão social...\" value=\"'+dadosRetorno.data.razao_social+'\"></div><div class=\"form-group\"><label for=\"telefone1\" class=\"control-label\">Telefone 1:</label><input type=\"text\" class=\"form-control\" id=\"telefone1\" placeholder=\"Digite o telefone 1...\" value=\"'+dadosRetorno.data.telefone1+'\"></div><div class=\"form-group\"><label for=\"telefone2\" class=\"control-label\">Telefone 2:</label><input type=\"text\" class=\"form-control\" id=\"telefone2\" placeholder=\"Digite o telefone 2...\" value=\"'+dadosRetorno.data.telefone2+'\"></div><div class=\"form-group\"><label for=\"email\" class=\"control-label\">Email:</label><input type=\"text\" class=\"form-control\" id=\"email\" placeholder=\"Digite o email...\"value=\"'+dadosRetorno.data.email+'\"></div><div class=\"form-group\"><label for=\"rua\" class=\"control-label\">Rua:</label><input type=\"text\" class=\"form-control\" id=\"rua\" placeholder=\"Digite a rua...\" value=\"'+dadosRetorno.data.rua+'\"></div><div class=\"form-group\"><label for=\"bairro\" class=\"control-label\">Bairro:</label><input type=\"text\" class=\"form-control\" id=\"bairro\" placeholder=\"Digite o bairro...\" value=\"'+dadosRetorno.data.bairro+'\"></div><div class=\"form-group\"><label for=\"numero\" class=\"control-label\">Número:</label><input type=\"text\" class=\"form-control\" id=\"numero\" placeholder=\"Digite o número...\" value=\"'+dadosRetorno.data.numero+'\"></div><div class=\"form-group\"><label for=\"complemento\" class=\"control-label\">Complemento:</label><input type=\"text\" class=\"form-control\" id=\"complemento\" placeholder=\"Digite o complemento...\" value=\"'+dadosRetorno.data.complemento+'\"></div><div class=\"form-group\"><label for=\"gps_lat\" class=\"control-label\">Latitude:</label><input type=\"text\" class=\"form-control\" id=\"gps_lat\" placeholder=\"Digite a latitude...\" value=\"'+dadosRetorno.data.gps_lat+'\"></div><div class=\"form-group\"><label for=\"gps_long\" class=\"control-label\">Longitude:</label><input type=\"text\" class=\"form-control\" id=\"gps_long\" placeholder=\"Digite a longitude...\" value=\"'+dadosRetorno.data.gps_long+'\"></div><div class=\"form-group\"><label for=\"pais\" class=\"control-label\">País:</label><select class=\"form-control \" id=\"pais\" value=\"'+dadosRetorno.data.nomepais+'\"><option>Brasil</option></select></div><div class=\"form-group\"><label for=\"estado\" class=\"control-label\">Estado:</label><select class=\"form-control \" id=\"estado value=\"'+dadosRetorno.data.nomeestado+'\"\"><option>Paraná</option></select></div><div class=\"form-group\"><label for=\"cidade\" class=\"control-label\">Cidade:</label><select class=\"form-control \" id=\"cidade\" value=\"'+dadosRetorno.data.nomecidade+'\"><option>Cascavel</option></select></div><hr><button type=\"submit\" class=\"btn btn-warning\">Salvar <span class=\"fa fa-save\" aria-hidden=\"true\"></span></button></form>'); \n $('#salveEditUnidade').validator();\n }\n $(\".painelCarregando\").fadeOut(400);\n }else{\n //retira o painel loading\n $(\".painelCarregando\").fadeOut(400);\n alerta(\"Alerta!\", dadosRetorno.mensagem);\n }\n //atualiza a sessao\n updateSessao(dadosRetorno.sessao);\n });\n}",
"function ventanaModal()\n {\n \n }",
"function cambioClave(codigo) {\n noEmp = codigo;\n $('#modalCambioClave').modal('show');\n // $('#input-correo-editar').val(email);\n // $('#select-posicion').val(posicion).attr(\"selected\", \"selected\");\n}",
"function openModalApprovaModulo(btn) {\n idModulo = parseInt($(btn).attr(\"id\").split('_')[$(btn).attr(\"id\").split('_').length - 1]);\n idArgomento = parseInt($(btn).attr(\"id\").split('_')[$(btn).attr(\"id\").split('_').length - 2]);\n $(\"#contModaleApprovModulo\").text(\"Sei sicuro di voler accettare questo corso?\");\n $(\"#btnConfApprovModulo\").removeAttr(\"disabled\");\n $(\"#modalApprovModulo\").modal(\"show\");\n}",
"function viewModal(appoinID, auth, cell, cellID){\n\t$('.ui.mini.modal').modal({\n onShow: function(){\n //console.log('shown');\n },\n onApprove: function() {\n var reason = $('#mod_reason').val();\n\t\t\tif(reason ==\"\" || reason == \" \"){\n\t\t\t\t$(\"#canceAPPErr\").html(\" Please enter reason for appointment cancellation\");\t\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$(\"#canceAPPErr\").html(\"\");\n\t\t\t\tcancelAppointment(appoinID, auth, cell, cellID);\n\t\t\t}\n },\n\t\tonDeny: function(){\n\t\t\t$(\"#canceAPPErr\").html(\"\");\n\t\t}\n }).modal('show')\n\t.modal('refresh')\n\t.modal('refresh');\t\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}",
"function confermaCapitoliModale(){\n var listaCapitoli = capitoliModaleSelezionati.filter(filterOutUndefined).map(mapToObject);\n var obj = {listaCapitoloEntrataPrevisione: listaCapitoli};\n\n $.postJSON('inserisciConfigurazioneStampaDubbiaEsigibilita_confermaCapitoli.do', projectToString(obj))\n .then(function(data) {\n if (impostaDatiNegliAlert(data.errori, erroriModaleCapitolo)) {\n return;\n }\n capitoliModaleSelezionati = [];\n cleanDataTable($('#risultatiRicercaCapitolo'));\n popolaTabellaTempCapitoli(data.listaAccantonamentoFondiDubbiaEsigibilitaTemp);\n $('#divRisultatiRicercaCapitolo').addClass('hide');\n $('#modaleGuidaCapitolo').modal('hide');\n });\n }",
"function activer_controle_changer_horaire_seance(code_seance, id_modal, html_info_seance, html_info_partipations, html_mailto, debut_nouveau_creneau, fin_nouveau_creneau) {\r\n $(\"#\" + id_modal + \"_titre\").html(\"Changement horaire séance\");\r\n html_corps = '<div class=\"alert alert-warning\" role=\"alert\">Opération irréversible !<br />Ne pas oublier de prévenir les personnes intéressées.</div>';\r\n html_corps = html_corps + '<div class=\"card\"><div class=\"card-body\"><p>' + html_info_seance + '</p><p>' + html_info_partipations + '</p></div></div>';\r\n html_corps = html_corps + '<div><button type=\"button\" class=\"btn btn-outline-primary\"><a href=\"' + html_mailto + '\">Envoyez un mail aux participants</a></button></div>';\r\n html_corps = html_corps + '<div><button type=\"button\" class=\"btn btn-primary\" onclick=\"modifier_horaire_seance_activite(' + code_seance\r\n + ', \\'' + debut_nouveau_creneau\r\n + '\\', \\'' + fin_nouveau_creneau\r\n + '\\'); return false;\">Confirmer changement horaire</button></div>';\r\n $(\"#\" + id_modal + \"_corps\").html(\"<div>\" + html_corps + \"</div>\");\r\n \r\n $(\"#\" + id_modal + \"_btn\").html(\"Ne rien faire\");\r\n\r\n return true;\r\n}",
"function primario(mensaje) {\n $modal.attr(\"class\", \"modal fade\");\n $titulo.text(defaultsMensajes.titulo);\n $cuerpo.attr(\"class\", \"modal-body \" + defaultsMensajes.estilo.primario + \" text-center\");\n $cuerpo.html(!esNuloNoDefinido(mensaje) ? mensaje : defaultsMensajes.mensaje);\n $btnAceptar.show().html(defaultsMensajes.textoBotonAceptar);\n $btnCancelar.hide();\n defaults.callbackAceptar = null;\n defaults.callbackCancelar = null;\n return $modal.modal({\n keyboard: defaultsApp.modalKeyboard,\n backdrop: defaultsApp.modalBackdrop\n });\n }",
"function BarberoSeleccionado(idBarbero,nombres,apellidos){\n Materialize.toast(\"Barbero seleccionado:\"+nombres,4000);\n //debe estar oculta la información de codigo del servicio\n //obtener el codigo del servicio\n\n var IdCodigoServicio = $(\"#modalIdCodigoServicio\").val();\n var nombreServicio = $(\"#modalNombreServicio\").val();\n var precioServicio = $(\"#modalPrecioServicio\").val();\n //Cerrar el modal\n $('#modal_BarberoServicio').modal('close');\n //llamar AumentarCantidadServicio(codigoServicio,idBarbero);\n AumentarCantidadServicio(\n IdCodigoServicio,\n nombreServicio,\n precioServicio,\n idBarbero,\n nombres,\n apellidos);\n}",
"function _EnvioDatosyModal() {\n inputs = LSModule.LeerInputs();\n LSModule.GuardarInputs();\n console.log('enviodatos');\n $.post(url, inputs,\n function (data, textStatus, jqXHR) {\n console.log('Recibido');\n console.log(inputs);\n $('#modalmsg').html(\"Me gusta tu elección amigo<br>ZampApp's Actitude Always\");\n $('#modalfeedback').modal('show');\n setTimeout(_enlaceResultados, 4000);\n },\n )\n .fail(function () {\n ErrorEnvio()\n });\n // .fail(function (obj, textStatus, jqXHR) {\n // console.log('No Recibido');\n // $('#textModal').html(\"Parece que tenemos algún tipo de problema en la cocina<br>En unos segundos te redirigiremos a la página principal\");\n // $('#myModal').modal('show');\n // setTimeout(_enlaceHome, 4000);\n }",
"function activar_tipoAsignatura(pk, nombre){\n\tpk_tipoAsignatura = pk;\n\testado_tipoAsignatura =\"Activo\";\n\t$('#formAct').show();\n\t$('#formElim').hide();\n\t$('#formMod').hide();\n\t$('#formAgregar').hide();\n\t$(\"#confirmacion_activar\").text(\"¿Desea activar el tipo de asignatura \"+ nombre + \"?\");\n}",
"function ver(datos) {\r\n //console.log(datos);\r\n ventanaModal(); //abrir ventana modal\r\n getDatos(datos); //pasar los datos al formulario\r\n\r\n}",
"mostrarFormularioAsignacionPaciente() {\n\n let funcion = () => this.activarSeleccion(\"asignarPersonal\", botonAltaPaciente);\n crearFormulario([\"Nombre\"], \"asignarPersonal\", funcion);\n let botonAltaPaciente = document.getElementById(\"confirmacion\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read ARP Cache (/opt/net/arp) | readARP() {
try {
var content = fs.readFileSync(ARP_FILE, 'utf8');
return content
.split(os.EOL)
.map((line) => {
let ip = findPattern(IPV4, line);
if (!ip) return null;
let mac = findPattern(MAC, line);
if (!mac) return null;
return ( findPattern(INCOMLITE, line) ) ? null : {ip: ip, mac: mac};
}).filter((line) => line != null);
} catch (err) {
logger.error(err);
return [];
}
} | [
"function arpAll () {\n return cp.exec('arp -a').then(parseAll)\n}",
"function arpOne (address) {\n return cp.exec('arp -n ' + address).then(parseOne)\n}",
"getElementsFromArpTable() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const promise = new Promise((resolve, reject) => {\n let tbl = { mac_addresses: {} };\n arp1.table(function (err, entry) {\n if (!!err)\n return console.log('arp: ' + err.message);\n if (!entry)\n return;\n // if (entry.ifname == cfg.arp.interface) {\n if (entry && entry[cfg.arp.entry_interface] && entry[cfg.arp.entry_interface] == cfg.arp.interface) {\n if (tbl.mac_addresses[entry.mac]) {\n if (!tbl.mac_addresses[entry.mac].includes(entry.ip)) {\n tbl.mac_addresses[entry.mac].push(entry.ip);\n }\n }\n else {\n tbl.mac_addresses[entry.mac] = [entry.ip];\n }\n }\n resolve(tbl);\n });\n });\n return promise;\n }\n catch (error) {\n console.log(\"ERRR\", error);\n }\n });\n }",
"function getIpAdressOfPeer(){\n const arpCmd = \"arp-scan --interface=ap0 --localnet | grep 192 | awk '{print $1}'\";\n return getAsync(arpCmd);\n}",
"function arpOne (address, servers) {\n\tif (!ip.isV4Format(address) && !ip.isV6Format(address)) {\n\t\treturn Promise.reject(new Error('Invalid IP address provided.'))\n\t}\n\treturn new Promise((resolve, reject)=>{\n\t\tcp.exec('arp -a ' + address, options).then((data)=>{\n\t\t\tresolve(parseOne(data, servers));\n\t\t}).catch((err)=>{resolve(null);});\n\t});\n}",
"function parse_arp_table(arpt){\n\n var arp_arr = [];\n arpt = arpt.split('\\n');\n var x;\n for(x in arpt){\n var entry = arpt[x];\n var arp_obj = {};\n\n // Get the IP from the \"(1.2.3.4)\" fromat\n var ip_start = entry.indexOf('(');\n if(ip_start === -1)\n continue;\n var ip_end = entry.indexOf(')');\n var ip = entry.slice(ip_start + 1, ip_end);\n arp_obj['ip'] = ip;\n\n // Get the Corresponding MAC Addres by splitting\n var mac = entry.split(' ')[3];\n\n // make sure MAC addresses are in lowercase\n mac = mac.toLowerCase();\n\n // make sure octets have a leading zero\n var mac_splited = mac.split(\":\");\n for(var i in mac_splited) {\n if(mac_splited.hasOwnProperty(i)) {\n if(mac_splited[i].length == 1) {\n mac_splited[i] = \"0\" + mac_splited[i];\n }\n }\n }\n\n // join octets again\n mac = mac_splited.join(\":\");\n\n arp_obj['mac'] = mac;\n\n arp_arr.push(arp_obj);\n }\n\nreturn arp_arr;\n}",
"function arpOne (address, arpPath) {\n if (!ip.isV4Format(address) && !ip.isV6Format(address)) {\n return Promise.reject(new Error('Invalid IP address provided.'))\n }\n\n return cp.exec(`${arpPath} -n ${address}`, options).then(parseOne)\n}",
"function arpAll (skipNameResolution = false, arpPath) {\n const isWindows = process.platform.includes('win32')\n const cmd = (skipNameResolution && !isWindows) ? `${arpPath} -an` : `${arpPath} -a`\n return cp.exec(cmd, options).then(parseAll)\n}",
"function arp_table_parse (table) {\r\n /*]\r\n [|] Create arp table object to contain arp table information\r\n [*/\r\n const arp_table = {}\r\n /*]\r\n [|] Create empty lists to contain items from the arp table.\r\n [*/\r\n const ip_list = []\r\n const mac_list = []\r\n let item_buffer = []\r\n /*]\r\n [|] Split the arp table string into individual characters\r\n [*/\r\n const split_arr = table.split('')\r\n /*]\r\n [|]\r\n [*/\r\n const gateway_subnet = network_deets.gateway.slice(0, -2)\r\n /*]\r\n [|] Loop through every character in the arp table.\r\n [*/\r\n split_arr.forEach((n, i) => {\r\n if (n !== ' ') {\r\n item_buffer.push(n)\r\n } else {\r\n /*]\r\n [|] Check to see if item_buffer currently holds a value\r\n [*/\r\n if (item_buffer.length >= 1) {\r\n const joined = item_buffer.join('')\r\n /*]\r\n [|] Add item to ip address list, if determined to be an IP\r\n [*/\r\n if (joined.includes(gateway_subnet) === true){\r\n ip_list.push(joined)\r\n } else if (joined.match(mac_regexp()) !== null) {\r\n mac_list.push(joined)\r\n }\r\n /*]\r\n [|] Clear out the item_buffer / string buffer\r\n [*/\r\n item_buffer = []\r\n }\r\n }\r\n })\r\n /*]\r\n [|] Add the list of items to the appropriate property of the arp table object\r\n [*/\r\n arp_table.ip_addresses = ip_list\r\n arp_table.mac_addresses = mac_list \r\n /*]\r\n [|]\r\n [*/\r\n return arp_table\r\n}",
"load(reader, adr) {\r\n this.clock.inc()\r\n console.log('DEBUG ' + this.name + '.load(' + adr + ')')\r\n let tag = adr >> this.numberOfAddressBits;\r\n let index = adr & this.andMask\r\n let line = null\r\n console.log('DEBUG ' + this.name + ' tag=' + tag + \", index=\" + index)\r\n \r\n // check, if cache line is already in cache\r\n let lineNum = this.lineInCache(tag)\r\n console.log('DEBUG ' + this.name + ' lineInCache(' + tag + ') returns ' + lineNum)\r\n if(lineNum == null) {\r\n console.log('DEBUG ' + this.name + ' read cache miss :-(')\r\n lineNum = this.findInvalidLine()\r\n if(lineNum == null) {\r\n console.log('DEBUG ' + this.name + ' and cache is full :-( :-(')\r\n lineNum = this.evictOldestLine();\r\n } else {\r\n console.log('DEBUG ' + this.name + ' but cache is not full :-|')\r\n }\r\n this.setTag(lineNum, tag)\r\n\t let response = this.bus.placeReadMiss(this, tag, this.numberOfAddressBits)\r\n\t console.log('DEBUG ' + this.name + ' got response')\r\n\t /*\r\n\t for(var i = 0; i < response.values.length; i++) {\r\n\t\tconsole.log('DEBUG ' + this.name + ' response value[' + i + ']=' + response.values[i])\r\n\t }\r\n\t */\r\n\t this.setValues(lineNum, response.values)\r\n this.setState(lineNum, States.SHARED)\r\n } else {\r\n console.log('DEBUG ' + this.name + ' read cache hit. lineNum=' + lineNum + ' :-)')\r\n }\r\n return this.getValue(lineNum, index)\r\n }",
"function readCached() {\n\n redisOper.readCachedServers(saveServerInfo);\n}",
"function YCellular_get_apn()\n {\n var res; // string;\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_APN_INVALID;\n }\n }\n res = this._apn;\n return res;\n }",
"async function getClientMacAddress(accessPointId, ipAddress) {\n\tconst key = `${accessPointId}-${ipAddress}`\n\tif (macAddresses[key] && macAddresses[key].timestamp > Date.now() - macCacheTimeout && macAddresses[key].value) {\n\t\treturn macAddresses[key].value\n\t}\n\n\tconst ap = accessPoint(accessPointId)\n\tconst macAddress = \n\t\t\tawait ap.run('cat /proc/net/arp | grep ' + ipAddress + ' | awk \\'{printf $4}\\'').then(result => result.stdout) ||\n\t\t\tawait ap.run('chilli_query list | grep ' + ipAddress + ' | awk \\'{printf $1}\\' | sed s/-/:/g').then(result => result.stdout)\n\n\tmacAddresses[key] = {\n\t\tvalue: macAddress,\n\t\ttimestamp: Date.now()\n\t}\n\n\treturn macAddress\n}",
"readCache(query)\t{ return this._behavior('read cache', query); }",
"function scanAPs() {\n\t\t$.get('http://'+_root+'/wifi/scan', onScan);\n\t}",
"function refetchMacAddresses() {\n const table = document.getElementById('mac-address-table');\n const progress = document.getElementById('mac-address-table-progress-bar');\n const progressTask = document.querySelector('#mac-address-table-progress-bar .progress-task');\n const progressBar = document.querySelector('#mac-address-table-progress-bar .progress-bar');\n\n progress.style.display = 'block';\n progressTask.innerHTML = 'Requesting ping to network...';\n progressBar.value = 0;\n\n // Ping broadcast address and parse arp table.\n hack.getMacAddresses()\n // On ping start\n .on('ping', () => {\n progressTask.innerHTML = 'Pinging network...';\n progressBar.value = 33.3;\n })\n // On arp start\n .on('arp', () => {\n progressTask.innerHTML = 'Fetching ARP-table from kernel...';\n progressBar.value = 66.6;\n })\n // On data received\n .on('data', addresses => {\n progressTask.innerHTML = 'Received ARP-data.';\n progressBar.value = 100;\n progress.style.display = 'none';\n table.style.display = 'table';\n\n const tbody = table.querySelector('tbody');\n tbody.innerHTML = '';\n\n // Create table\n addresses.forEach((address) => {\n const row = document.createElement('tr');\n\n row.appendChild(utils.createCell(address.name));\n row.appendChild(utils.createCell(`<code>${address.address}</code>`));\n\n // Create 'steal'-button to be able to directly use that address.\n const button = document.createElement('button');\n button.className = 'button is-small';\n button.innerText = 'Steal Address';\n button.addEventListener('click', () => {\n if (confirm(\n 'Stealing addresses is not recommended!\\n' +\n 'It will most likely break the network or break your connection to it.\\n' +\n 'Are you sure you want to steal this address?'\n )) {\n setMacAddress(address.address);\n }\n });\n\n // Add button to row\n row.appendChild(utils.createCell(button));\n\n tbody.appendChild(row);\n });\n });\n}",
"function _get(key){\n\tvar ret = null;\n\n\n\t// Pull from cache or re-read from fs.\n\t//console.log('key: ' + key)\n\t//console.log('use_zcache_p: ' + use_zcache_p)\n\tif( use_zcache_p ){\n\t ret = zcache[key];\n\t\t// console.log('_get CACHED: ', key, ret.slice(0, 10));\n\t}else{\n\t ret = afs.read_file(path_cache[key]);\n\t\t// console.log('_get FILE: ', key, path_cache[key], ' Length: ', ret.length);\n\t}\n\n\treturn ret;\n }",
"async getRoutableIP(host_address) {\n const route = await execa('ip', ['route', 'get', host_address]);\n const route_elements = route.stdout.split(' ');\n const source_ip = route_elements[route_elements.indexOf('src')+1];\n\n return source_ip\n }",
"async loadPacFile() {\n debug2(\"Loading PAC file: %o\", this.uri);\n const rs = await (0, get_uri_1.getUri)(this.uri, { ...this.opts, cache: this.cache });\n debug2(\"Got `Readable` instance for URI\");\n this.cache = rs;\n const buf = await (0, agent_base_1.toBuffer)(rs);\n debug2(\"Read %o byte PAC file from URI\", buf.length);\n return buf.toString(\"utf8\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves standups to db | function saveStandUp(standUpDetails) {
repos.userStandupRepo.add(standUpDetails);
} | [
"saveStandup(standupDetails) {\n AppBootstrap.userStandupRepo.add(standupDetails);\n }",
"function saveToDatabase() {\n idb.add(dbKeys.stations, JSON.stringify(stationList));\n idb.add(dbKeys.lastFrequency, lastFrequency);\n }",
"function saveStandup(room, time) {\n var standups = getStandups();\n var newStandup = {\n time: time,\n room: room\n };\n standups.push(newStandup);\n updateBrain(standups);\n}",
"save () {}",
"function saveStandup(room, time, utc) {\n var standups = getStandups();\n\n var newStandup = {\n time: time,\n room: room,\n utc: utc\n };\n\n standups.push(newStandup);\n updateBrain(standups);\n }",
"function saveToDB() {\n\tdb.collection(\"cards\")\n\t\t.doc(currentExpansion)\n\t\t.set(cardList);\n}",
"function save() {\n\n if (wise4) {\n // this model is being used in WISE4\n\n if (wiseAPI != null) {\n // save the trial data to WISE\n wiseAPI.save(trialData);\n }\n } else if (wise5) {\n // this mode is being used in WISE5\n\n // create a component state\n var componentState = {};\n componentState.isAutoSave = false;\n componentState.isSubmit = false;\n componentState.studentData = trialData;\n\n // save the component state to WISE\n saveWISE5State(componentState);\n }\n}",
"saveAbuse() { }",
"function save() {\n Context.updateAttendance(student.value.id, name.value, color.value);\n}",
"async save() {\n const priv = privates.get(this);\n const tableName = priv.get(\"tableName\");\n if (tableName) {\n const formData = new FormData(this.form);\n if (formData.get(\"saveDetails\") !== \"on\") {\n return;\n }\n const dataToSave = Object.assign({}, this.data, this.toObject());\n if (!db.isOpen()) {\n await db.open();\n }\n await db[tableName].put(dataToSave);\n this.data = dataToSave;\n }\n }",
"function storeStooges() {\n self.log(self.oldStoogesFound);\n self.log(self.oldStoogesKilled);\n spec.integrationStore.putModel(self.moe, stoogeStored);\n spec.integrationStore.putModel(self.larry, stoogeStored);\n spec.integrationStore.putModel(self.shemp, stoogeStored);\n }",
"function saveData()\n{\n if(numberOfAchievements > 0 || hasStats)\n {\n gamesCollection.findOne({appid:Number(appId)}, function(e, docs){\n // Set the game name, since this field is often empty in the Steam API.\n gameSchemeJson.game.gameName = docs.name;\n // Add the appId, could be useful.\n gameSchemeJson.game.appid = Number(appId);\n\n // Save the completed game schema + global stats + name\n detailedGamesCollection.remove({appid:Number(appId)});\n detailedGamesCollection.insert(gameSchemeJson.game, {});\n detailedGamesCollection.index('appid', 1);\n\n console.log(\"Saved detailedgame data for \" +gameSchemeJson.game.gameName);\n\n updateGame();\n });\n }\n else {\n updateGame();\n }\n}",
"function saveMeasurementtable() {\n var rowid = document.getElementById('mgt_rowid').value;\n var date = document.getElementById('mgt_date').value;\n var weight = document.getElementById('mgt_weight').value.toString();\n var height = document.getElementById('mgt_height').value.toString();\n var neck = document.getElementById('mgt_neck').value.toString();\n var shoulder = document.getElementById('mgt_shoulder').value.toString();\n var midarm = document.getElementById('mgt_midarm').value.toString();\n var chest = document.getElementById('mgt_chest').value.toString();\n var waist = document.getElementById('mgt_waist').value.toString();\n var hips = document.getElementById('mgt_hips').value.toString();\n var details = [date, height, weight, neck, shoulder, midarm, chest, waist, hips, userid, rowid];\n var sql = `update measurement_table set mgt_date=?,mgt_height=?,mgt_weight=?,mgt_neck=?,mgt_sholder=?,mgt_midarm=?,mgt_chest=?,mgt_waist=?,mgt_hips=? where memberno=? and rowid=?`;\n database.updatePerson(sql, details);\n populateMeasurementTable(userid);\n}",
"function save() {\n \n if (wise4) {\n // this model is being used in WISE4\n \n if (wiseAPI != null) {\n // save the trial data to WISE\n wiseAPI.save(trialData);\n }\n } else if (wise5) {\n // this mode is being used in WISE5\n \n // create a component state\n var componentState = {};\n componentState.isAutoSave = false;\n componentState.isSubmit = false;\n componentState.studentData = trialData;\n \n // save the component state to WISE\n saveWISE5State(componentState);\n }\n}",
"save() {\n this.Dbinterface.saveMeasurements();\n }",
"function save() {\n\t\tinstrumentName = $('#instrument-name-form').val();\n\t\t\tpatch.synths.length = 0;\n\t\t\n\t\tsendDOMItemToJSONObj('input[id^=\"oscPitchOctave_\"]', patch.synth_octave_pitch_sliders, 'synth_slider_name', 'synth_slider_val');\t\n\t\tsendDOMItemToJSONObj('input[id^=\"oscNoteValueInput_\"]', patch.synth_note_pitch_sliders, 'synth_slider_name', 'synth_slider_val');\t\n\t\n\t\t\n\t\t\n\n\t\t\n\t\t$(\".synth\").each(function() { // finds all divs with class .synth and gets their individual ID and Left/Top CSS positional values\n\t\t\tvar temp = $(\"#\" + this.id);\n\t\t\tvar pos = $(temp).position();\n\t\t\tpatch.synths.push({\n\t\t\t\t'synth_name': this.id,\n\t\t\t\t'xpos': pos.left,\n\t\t\t\t'ypos': pos.top\n\t\t\t});\n\t\t});\n\t\t\n\t\t$('.patch-list').html(patch.name);\n\t\t\n\t\tpatch.patch_name = instrumentName; \n\t\t\n\t\t$.ajax({\n\t\t\ttype: 'POST',\n\t\t\turl: 'php/pdo/add.php',\n\t\t\tdata: { mydata: patch},\n\t\t\tsuccess: function() {\n\t\t\t\t$(\".patch-list\").empty();\n\t\t\t\t$.ajax({\n\t\t\t\t\turl: \"php/pdo/get.php\"\n\t\t\t\t}).done(function(html) {\n\t\t\t\t\t$(\".patch-list\").append(html)\n\t\t\t\t\tgetSynthsFromDatabase();\n\t\t\t\t\tsetPatchNameOrder();\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tinitRubberBandScript();\n\t}",
"save () { state.elders = state.adults; state.adults = {}; state.babies = {}; state.stiffs = {}; }",
"function MLINKSTUD_save() {\n console.log(\"===== MLINKSTUD_save =====\");\n\n if (permit_dict.permit_crud && permit_dict.requsr_same_school) {\n\n const url_str = urls.url_student_enter_exemptions;\n const upload_dict = {mode: \"enter\",\n table: \"student\"};\n UploadChanges(upload_dict, url_str);\n };\n\n $(\"#id_mod_link_students\").modal(\"hide\");\n\n }",
"async function presave_story() {\n await story.save();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pauses / resumes the game when "Escape" is pressed | function Update () {
if (Input.GetKeyUp(KeyCode.Escape)) {
if (paused == false) {
PauseGame();
} else {
ResumeGame();
}
}
} | [
"function Update () {\r\n\tif (Input.GetKeyUp(KeyCode.Escape)) {\r\n\t\tif (paused == false) {\r\n\t\t\tPauseGame();\r\n\t\t} else {\r\n\t\t\tResumeGame();\r\n\t\t}\r\n\t}\r\n}",
"function Update () {\n if (Input.GetKeyUp(KeyCode.Escape)){\n pause();\n }\n}",
"function pauseByESC() {\r\n window.onkeydown = (event) => {\r\n if (event.key === 'Escape') {\r\n if (gameStarted) {\r\n pauseGameMenuElem.classList.remove(\"hidden\"); // Show pause menu\r\n soundControlGame.classList.add(\"hidden\"); // Hide sound icon \r\n pauseGameBtn.classList.add(\"hidden\"); // Hide pause icon\r\n pauseTheGame();\r\n } else {\r\n pauseGameMenuElem.classList.add(\"hidden\"); // Hide pause menu \r\n soundControlGame.classList.remove(\"hidden\"); // Show sound icon\r\n pauseGameBtn.classList.remove(\"hidden\"); // Show pause icon \r\n resumeTheGame();\r\n }\r\n }\r\n };\r\n}",
"function quit( ev ) {\n\t// check what key is pressed\n\tvar code = ev.keyCode;\n\tif(code === 27) {\n\t\tgameOver(quit);\n\t}\n}",
"onKeyDown(event) {\n if (event.key === 'Escape') this.abort();\n }",
"function Update(){\n//quit game if escape key is pressed\n\tif (Input.GetKey(KeyCode.Escape)){\n\t\tApplication.Quit();\n\t}\t\n}",
"function onEscKey(event) {\n\t\tif(event.keyCode === 27) {\n\t\t\tdeactivate();\n\t\t}\n\t}",
"onEscapePress() {}",
"function pauseGame() {\n if (paused.state) {\n lock.current = false;\n lastKey.current = null;\n setPaused({ text: \"PAUSE\", state: false });\n } else {\n lock.current = true;\n setPaused({ text: \"RESUME\", state: true });\n }\n }",
"async pressEscape() {\n await this.client.keys(this.client.Keys.ESCAPE);\n }",
"function gamePause() {\n drawPauseState();\n resumeCountdown = 3;\n gameState = \"gamePaused\";\n}",
"function checkForEscape() {\n key = event.key\n if (key === \"Escape\" || key=== \"q\") {\n console.log(\"Escape was pressed\")\n clearAllTimeouts()\n cinderellaImgIdx = 0\n cinderellaRecordingHasStarted = false\n openNav()\n nav.hidden = false\n // unloadJS(exp.name)\n clearScreen()\n rec.stopRec()\n }\n}",
"function handleKeyDown(e) {\n if (e.key === 'Escape') {\n paused = !paused;\n // open / close menu\n // TODO: Build menu\n }\n sceneManager.handleKeyDown(e);\n}",
"function pause_resume() {\r\n if (gameState == \"run\") {\r\n gameLoop.stop();\r\n gameState = \"stop\";\r\n }\r\n else if (gameState == \"stop\") {\r\n gameLoop.start();\r\n gameState = \"run\";\r\n }\r\n}",
"function checkForEscape() {\n key = event.key\n if (key === \"Escape\" || key=== \"q\") {\n console.log(\"Escape was pressed\")\n openNav()\n nav.hidden = false\n // unloadJS(exp.name)\n clearScreen()\n resetVars()\n }\n}",
"function Start () {\n\t//esc_pressed = false;\n\n}",
"function detectarEsc (e) {\n if (e.key === \"Escape\"){\n closeModal();\n }\n}",
"function keyPressed(){\n this.stop = function (){\n if(keyCode === ESCAPE){\n noLoop();\n }\n }\n}",
"function keyReleased() {\n if (keyCode === ENTER) {\n restart();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the distances in AP from (from_x, from_y) to (places[i][1], places[i][2]) and put it into places[i][3] Then sort places by increasing distance | function sort_places(from_x, from_y, places) {
// {{{
function dist_sort(e1, e2) {
return e1[3] - e2[3];
}
for (var i = 0 ; i < places.length; ++i) {
places[i][3] = distance_AP(from_x, from_y, places[i][1], places[i][2]);
}
places.sort(dist_sort);
// }}}
} | [
"function sortByDistance()\n {\n Places.sort(function(a,b)\n {\n return a.distance-b.distance;\n });\n }",
"function orderedPlaces(places) {\n var arr = [];\n for (var i = 0; i < places.length; i++) {\n arr.push(places[i].object_form());\n }\n var ordArr = [];\n var pairs = [];\n for (var i = 0; i < arr.length; i++) {\n pairs.push({ name: arr[i].name, index: i, ischain: arr[i].ischain, duration: arr[i].duration, open: (arr[i].timeleft != \"Closed\") ? 1 : 0, notchain: (arr[i].ischain != \"true\") ? 1 : 0 })\n }\n pairs.sort(function (a, b) {\n return a.duration - b.duration;\n });\n pairs.sort(function (a, b) {\n return b.open - a.open;\n });\n pairs.sort(function (a, b) {\n return b.notchain - a.notchain;\n });\n for (var i = 0; i < pairs.length; i++) {\n //console.log(pairs[i])\n ordArr.push(arr[pairs[i].index])\n }\n return ordArr;\n}",
"addTofreePlaceArr() {\n //add element to array of free places\n this._field.getfreePlaceArr().push(this._data);\n //sort array by index of free place\n this._field.getfreePlaceArr().sort( (prEl, nextEl) => prEl[0] - nextEl[0] );\n\n let arr = [];\n\n //connect free places\n for (let i = 0; i < this._field.getfreePlaceArr().length; i++) {\n let currElement = this._field.getfreePlaceArr()[i];\n let nextElement = this._field.getfreePlaceArr()[i + 1];\n if (nextElement && currElement[0] + 1 == nextElement[0]) {\n let currIndex = currElement[0];\n while (nextElement && nextElement[0] - currIndex == 1) {\n i++;\n currIndex = nextElement[0];\n nextElement = this._field.getfreePlaceArr()[i + 1];\n if (nextElement) {\n currElement[1] += nextElement[1];\n }\n }\n }\n arr.push(currElement);\n }\n //end connect free places\n\n this._field.setfreePlaceArr(arr);\n\n //sort array by length value\n this._field.getfreePlaceArr().sort( (prEl, nextEl) => prEl[1] - nextEl[1] );\n return this;\n }",
"function getPlaceData() {\n $.ajax({\n url: newQueryURL,\n method: \"GET\",\n }).then(function (response) {\n let places = response.results;\n // console.log(places)\n // console.log(restaurantArray);\n let sortedRestaurantArray = places.sort(function (a, b) {\n if (a.rating > b.rating) {\n return -1;\n } else if (a.rating > b.rating) {\n return 1;\n } else {\n return 0;\n }\n })\n\n console.log(sortedRestaurantArray)\n\n for (var i = 0; i < places.length; i++) {\n\n // temporary variable declarations\n // they only need to be temp b/c the are reset \n // for each iteration\n // let photo = places[i].photos[0].photo_reference;\n let tempLat = places[i].geometry.location.lat;\n let tempLong = places[i].geometry.location.lng;\n let rating = places[i].rating;\n let name = places[i].name;\n // datapoints are in the only form that the heatmap layer api accepts\n let dataPoint = { location: new google.maps.LatLng(tempLat, tempLong), weight: rating };\n dataPointArray.push(dataPoint);\n\n }\n\n\n });\n}",
"function orderByPlace(array) {\n const results = [];\n array.forEach((element, index) => {\n element.place = parseInt(element.place);\n if (isNaN(element.place)) {\n element.place = \"-\";\n }\n results[index] = element;\n });\n return results;\n}",
"computeDistances(google, places){\n for(let i in places){\n places[i]['distance'] = google.maps.geometry.spherical.computeDistanceBetween(\n places[i].geometry.location, this.props.addresses[0].geometry.location\n )\n +\n google.maps.geometry.spherical.computeDistanceBetween(\n places[i].geometry.location, this.props.addresses[1].geometry.location\n )\n }\n }",
"function distToArr() {\n for (var i in data) {\n var dist = getDistance(lat1, lon1, data[i].lat, data[i].lon);\n data[i].distance = dist;\n distStart = Number(data[0].distance);\n }\n data.sort((a, b) => parseFloat(a.distance) - parseFloat(b.distance));\nvar story = document.getElementById(\"story\");\n}",
"function sortPlaces() {\n\t\t\tself.filterList().forEach(function(filter) {\n\t\t\t\trawPlacesList.forEach(function(place) {\n\t\t\t\t\tfor(var i = 0; i < filter.googleType.length; i++) {\n\t\t\t\t\t\tvar type = filter.googleType[i];\n\t\t\t\t\t\t\n\t\t\t\t\t\t//place has filter type and isn't a duplicate\n\t\t\t\t\t\tif(place.types.indexOf(type) > -1 && filter.list.indexOf(place) == -1) {\n\t\t\t\t\t\t\tfilter.list.push(place);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t//Sort each list by rating\n\t\t\t\tfilter.list.sort(function(a,b) {\t\t\t\t\t\n\t\t\t\t\tif(a.rating() > b.rating()) {\t\t\t\t\t\t\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t} else if(a.rating() == b.rating()) {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\t\t\n\t\t}",
"function calcDistanceWithOrder(points, order) {\n var totalDistance = 0;\n for (var i = 0; i < order.length-1; i++) {\n //p5js dist function calculates distance between two coordinates\n var cityA = points[order[i]];\n var cityB = points[order[i+1]];\n var distance = dist(cityA.x , cityA.y, cityB.x, cityB.y);\n totalDistance += distance;\n }\n return totalDistance;\n}",
"function sortArrayByDistance() {\n\n debugPrint(\"Inside sortArrayByDistance function\");\n\n var arrayToSort = mapListPageInfo.ArrayOfPOIData;\n var currentLat = mapListPageInfo.CurrentPosition_Lat;\n var currentLong = mapListPageInfo.CurrentPosition_Long;\n\n //Sort the array by distance from the user\n var sortedArray = arrayToSort.sort(\n function (a, b) {\n var distanceTo_A = CalculateDistanceInFeet(currentLat, currentLong,\n a.POI_Latitude, a.POI_Longitude);\n var distanceTo_B = CalculateDistanceInFeet(currentLat, currentLong,\n b.POI_Latitude, b.POI_Longitude);\n return distanceTo_A - distanceTo_B;\n });\n\n return sortedArray;\n}",
"function sortDistanceAsc(array)\n{\n\tvar temp;\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\ttemp = array[i];\n\t\tvar j = i - 1;\n\t\twhile (j >= 0 && Number(array[j].distance) > Number(temp.distance))\n\t\t{\n\t\t\tarray[j+1] = array[j];\n\t\t\tj--;\n\t\t}\n\t\tarray[j+1] = temp;\n\t}\n\t\n\t//Display data\n\tdisplayDataSearch(array);\n}",
"function sortAndCreateMarker() {\n let sortedPlaces = \n places.sort(function (a, b) {\n let nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();\n if (nameA < nameB)\n return -1;\n if (nameA > nameB)\n return 1;\n return 0;\n });\n\n for (let i = 0; i < sortedPlaces.length; i++) {\n let place = sortedPlaces[i];\n createMarker(place, i);\n }\n }",
"getDistances() {\n return this.grid.inputPoints\n .map(inputPoint => {\n return {\n inputPoint: inputPoint,\n distance: this.getManhattanDistanceTo(inputPoint)\n }\n })\n .sort((a, b) => a.distance - b.distance)\n }",
"function orderByProx (pickup, drivers) {\n let mapDrivers = drivers.map((driver) => {\n let dist2 = Math.pow(Math.abs(driver.atx - pickup[0]), 2) + Math.pow(Math.abs(driver.aty - pickup[1]), 2);\n let result = [driver, dist2];\n return result;\n })\n mapDrivers.sort(function(a,b) {\n if (a[1] <= b[1]) {\n return -1;\n } else {\n return 1;\n }\n })\n return mapDrivers;\n // this is an array of tuples with driver objects and their distance2 from pickup;\n}",
"function sortDistancesAscending(stations) {\n return stations.sort(function(a, b) {\n return (\n a.properties.distanceFromUserAddress -\n b.properties.distanceFromUserAddress\n )\n })\n }",
"function computeDistancesFromOrigin() {\n\n var originCoordinates = new google.maps.LatLng(LFL.origin.latitude, LFL.origin.longitude);\n var distInMeters = 0, distInKm = 0, distInMiles =0;\n var destinationCoordinates = null;\n var loopLen = LFL.locations.length, i;\n for (i = 0; i < loopLen; i++) {\n\n destinationCoordinates = new google.maps.LatLng(LFL.locations[i].latitude, LFL.locations[i].longitude);\n distInMeters = google.maps.geometry.spherical.computeDistanceBetween(originCoordinates, destinationCoordinates);\n //convert distance from meters to kilometers by dividing by 1000 (1000m = 1km)\n distInKm = distInMeters / 1000;\n // convert kms to miles by dividing by 1.6 (1.6km = 1 mile)\n distInMiles = distInKm / 1.6;\n\n /*\n adding distances in meters and kilometers as well to the object so that\n at a later time if we would like to switch the sort to one of these we can.\n \n we are rounding the numbers after conversion to minimize rounding error that\n might result if we do it before conversions.\n */\n\n LFL.locations[i].distInMeters = Math.round(distInMeters);\n LFL.locations[i].distInKm = Math.round(distInKm);\n LFL.locations[i].distInMiles = Math.round(distInMiles);\n }\n\n /*\n now sort the array by distance from origin in Miles by ascending order.\n To have it sorted in descending order, flip the operands for the subtraction.\n */\n LFL.locations.sort(function(a, b) {\n return a.distInMiles - b.distInMiles;\n });\n //console.log (LFL.locations);\n\n // call updateUI to redraw the list since the origin most likely changed.\n updateUI();\n}",
"function sortStations(stations, latLng) {\n stations.sort((a, b) => a.distance - b.distance);\n }",
"function sortByDistance(unvisitedCells, grid){\n return unvisitedCells.sort((cellA, cellB) => grid[cellA[0]][cellA[1]].distance - grid[cellB[0]][cellB[1]].distance);\n }",
"function sortItemsByDistance(coordinates, items){\n return _.sortBy(items, function(item){\n return geo.distance(coordinates, item.coordinates);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a function to be run before processing spans Conservatively, this function works even if called after MAJAX has completed loading and has already processed the spans once. | function majaxRunBeforeSpanProcessing(func) {
if (majax !== undefined && majax.loaded) {
func();
majaxProcessSpans();
} else {
majaxLoadHandlers.push(func);
}
} | [
"onStart(span, _) {\n span.setAttribute('service_name', span.resource.attributes['service.name']);\n span.setAttribute('honeycomb.trace_type', 'otel');\n otelTraceBase.SimpleSpanProcessor.prototype.onStart.call(this, span);\n }",
"function setBeforeStart(fn) {\n beforeStart = fn;\n }",
"function runBeforeBootstrap(func) {\n\tfuncsToRunBeforeBootstrap_ = funcsToRunBeforeBootstrap_ || [];\n\taddFunctionToList(func, funcsToRunBeforeBootstrap_);\n}",
"function addOnBeforeItemLoadCallback(fn) {\n onBeforeItemLoadCallbacks.push(fn);\n }",
"addOnBeforeItemLoadCallback(fn) {\r\n this.onBeforeItemLoadCallbacks.push(fn);\r\n }",
"function fathomInitWrapper(traineesAddedIn, pageManagerLoadedIn) {\n traineesAdded = traineesAddedIn;\n pageManagerLoaded = pageManagerLoadedIn;\n if (traineesAdded && pageManagerLoaded) {\n fathomInit();\n }\n }",
"function beforeStartWorkflow(callback/*:Function*/)/*:void*/ {\n callback();\n }",
"onTokenize(...functions) {\n this.tokenizeListeners.push(...functions);\n }",
"postProcess(fn) {\n this.taggers.push(fn)\n return this\n }",
"onStartSpan(span) {\n if (!this.active)\n return;\n if (!this.currentRootSpan ||\n this.currentRootSpan.traceId !== span.traceId) {\n this.logger.debug('currentRootSpan != root on notifyStart. Need more investigation.');\n }\n return super.onStartSpan(span);\n }",
"add(func) {\n\n let index = _.indexOf(this.funcs, func)\n\n if (index !== -1) return\n\n this.funcs.push(func);\n if (this.funcs.length > 0) {\n this.start();\n }\n }",
"setStartFunction (nodeType, fn) {\n this.startFunctions[nodeType] = fn\n }",
"process(container, level = 0) {\n // Initially, this method was supposed to just add the XML elements directly into\n // the document. However, this caused a lot of problems (e.g. title not working).\n // HTML does not work really well with custom elements, especially if they are of\n // another XML namespace.\n let query = ':not(span):not(svg):not(use):not(button)';\n let pending = container.querySelectorAll(query);\n // No more XML elements to expand\n if (pending.length === 0)\n return;\n // For each XML element currently in the container:\n // * Create a new span element for it\n // * Have the processors take data from the XML element, to populate the new one\n // * Replace the XML element with the new one\n pending.forEach(element => {\n let elementName = element.nodeName.toLowerCase();\n let newElement = document.createElement('span');\n let context = {\n xmlElement: element,\n newElement: newElement\n };\n newElement.dataset['type'] = elementName;\n // I wanted to use an index on ElementProcessors for this, but it caused every\n // processor to have an \"unused method\" warning.\n switch (elementName) {\n case 'coach':\n ElementProcessors.coach(context);\n break;\n case 'excuse':\n ElementProcessors.excuse(context);\n break;\n case 'integer':\n ElementProcessors.integer(context);\n break;\n case 'named':\n ElementProcessors.named(context);\n break;\n case 'phrase':\n ElementProcessors.phrase(context);\n break;\n case 'phraseset':\n ElementProcessors.phraseset(context);\n break;\n case 'platform':\n ElementProcessors.platform(context);\n break;\n case 'service':\n ElementProcessors.service(context);\n break;\n case 'station':\n ElementProcessors.station(context);\n break;\n case 'stationlist':\n ElementProcessors.stationlist(context);\n break;\n case 'time':\n ElementProcessors.time(context);\n break;\n case 'vox':\n ElementProcessors.vox(context);\n break;\n default:\n ElementProcessors.unknown(context);\n break;\n }\n element.parentElement.replaceChild(newElement, element);\n });\n // Recurse so that we can expand any new elements\n if (level < 20)\n this.process(container, level + 1);\n else\n throw Error(L.PHRASER_TOO_RECURSIVE);\n }",
"function lineagePreProcess(rData, callback) {\n\n\tcallback(rData);\n}",
"function process(\n MathJax: Object,\n script: HTMLScriptElement,\n callback: () => void\n) {\n pendingScripts.push(script)\n pendingCallbacks.push(callback)\n if (!needsProcess) {\n needsProcess = true\n setTimeout(() => doProcess(MathJax), 0)\n }\n}",
"onTagInjected () {\n this.counter++;\n\n if(this.counter === this.urls.length && typeof this.loadedCallback === \"function\") {\n this.loadedCallback();\n }\n }",
"function attachLocalSpans(doc, change, from, to) { // 7179\n var existing = change[\"spans_\" + doc.id], n = 0; // 7180\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { // 7181\n if (line.markedSpans) // 7182\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; // 7183\n ++n; // 7184\n }); // 7185\n } // 7186",
"function initializeSpans() {\r\n\tspanArray = pageDoc.getElementsByTagName(\"span\");\t\r\n\tfor (var i=0; i<spanArray.length; i++) {\r\n\t\tif (spanArray[i].className == \"siwa\") {\r\n\t\t\tvar currSpan = spanArray[i];\t\t\t\r\n\t\t\tcurrSpan.onclick = servRequest;\t\t\t\r\n\t\t}\r\n\t}\t\r\n}",
"beforeParse() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funzione per il controllo della selezione dell'abbonamento cena | function ControlloAbbonamentoCena() {
var i;
var AbbonamentoCena = document.getElementById("AbbonamentoCena");
var Iscrizione = document.getElementById("Iscrizione");
if (!Iscrizione.checked && AbbonamentoCena.checked) {
alert("Non è possibile registrare l'abbonamento alle cene senza l'iscrizione, almeno come ospite");
return false;
}
// chiedo conferma per la cancellazione dell'abbonamento
if (!AbbonamentoCena.checked) {
//if (!confirm("Attenzione! Sei sicuro di voler togliere all'iscritto l'abbonamento cene?")) {
//AbbonamentoCena.checked = true;
//}
} else {
//if (confirm("Attenzione! Impostando l'abbonamento cene verranno annullati tutti le cene singole\nVuoi proseguire?")) {
// annullo le cene singole se è impostato l'abbonamento
var Cene = document.getElementsByName("Cena[]");
var CeneGratis = document.getElementsByName("GratisCena[]");
for (i=0; i < Cene.length; i++) {
Cene[i].checked = false;
CeneGratis[i].checked = false;
}
//} else {
// AbbonamentoCena.checked = false;
//}
}
document.getElementById("CostoTotaleEuroCalcolato").value = CalcolaCostoTotale().toFixed(2).replace(".", ",");
return;
} // fine funzione controllo abbonamento cena | [
"function vendiCasa(){\n //verifico che il terreno esista e salvo il risultato in proprietà\n var n = EsisteTerreno(props.terreni, terreno);\n if(n === -1){\n setTestoVenditaEdifici('Controlla che il nome del terreno sia scritto in modo corretto');\n setOpenVenditaEdifici(true); \n return;\n }\n var proprietà = props.terreni[n];\n //verifico che il turnoGiocatore sia proprietario di proprietà\n if((proprietà.proprietario !== props.turnoGiocatore)){\n setTestoVenditaEdifici('Non puoi vendere gli edifici se il terreno che non è tuo');\n setOpenVenditaEdifici(true); \n return;\n }\n \n //Se sul terreno non ci sono case non ho nulla da vendere\n if(proprietà.case === 0){\n setTestoVenditaEdifici(\"Su questo terreno non ci sono case\");\n setOpenVenditaEdifici(true); \n return;\n }\n //modifico l'array terreni e l'array giocatori\n proprietà.case = proprietà.case - 1;\n var nuoviTerreni = props.terreni;\n nuoviTerreni[n] = proprietà;\n props.setTerreni(nuoviTerreni);\n\n var nuoviGiocatori = props.giocatori;\n var guadagno = proprietà.valore*3/8;\n nuoviGiocatori[props.turnoGiocatore].capitale = nuoviGiocatori[props.turnoGiocatore].capitale + guadagno;\n props.setGiocatori(nuoviGiocatori);\n\n var banca = Banca.getInstance();\n banca.incrementaCase();\n\n setTestoVenditaEdifici('La vendita della casa è andata a buon fine');\n setOpenVenditaEdifici(true); \n }",
"function etapaBuscaBanco(){\n //...\n }",
"function vendiAlbergo(){\n //verifico che il terreno esista e salvo il risultato in proprietà\n var n = EsisteTerreno(props.terreni, terreno);\n if(n === -1){\n setTestoVenditaEdifici('Controlla che il nome del terreno sia scritto in modo corretto');\n setOpenVenditaEdifici(true); \n return;\n }\n var proprietà = props.terreni[n];\n //verifico che il turnoGiocatore sia proprietario di proprietà\n if((proprietà.proprietario !== props.turnoGiocatore)){\n setTestoVenditaEdifici('Non puoi vendere gli edifici che non sono su un tuo terreno');\n setOpenVenditaEdifici(true); \n return;\n }\n //Verifico ceh sul terreno ci sia un albergo\n if((proprietà.alberghi !== 1)){\n setTestoVenditaEdifici(\"Su questo terreno non c'è un albergo\");\n setOpenVenditaEdifici(true); \n return;\n }\n \n //modifico l'array terreni e l'array giocatori\n //quando vendo un albergo alla banca ricevo in cambio metà del prezzo d'aquisto e 4 case\n proprietà.alberghi = 0;\n proprietà.case = 4;\n var nuoviTerreni = props.terreni;\n nuoviTerreni[n] = proprietà;\n props.setTerreni(nuoviTerreni);\n\n var nuoviGiocatori = props.giocatori;\n var guadagno = proprietà.valore*3/8;\n nuoviGiocatori[props.turnoGiocatore].capitale = nuoviGiocatori[props.turnoGiocatore].capitale + guadagno;\n props.setGiocatori(nuoviGiocatori);\n\n var banca = Banca.getInstance();\n banca.incrementaAlberghi();\n\n setTestoVenditaEdifici(\"La vendita dell'albergo è andata a buon fine\");\n setOpenVenditaEdifici(true); \n }",
"function principal() {\n choquecuerpo();\n choquepared();\n dibujar();\n movimiento();\n \n if(cabeza.choque (comida)){\n comida.colocar();\n cabeza.meter();\n } \n}",
"controlla() {\n\tfor(var j = 0; j < pallini.length; j++ ) { \n\tthis.urtoPallino(pallini[j]);\n\t}\n\tthis.urtoParete();\n\tif( new Date().getTime() - this.tempo > tempoguarigione && this.tempo > 0) {\n\tthis.stato = 2;\n\t}\n\t}",
"function ControlloAbbonamentoPranzo() {\r\n var i;\r\n\t\t\tvar AbbonamentoPranzo = document.getElementById(\"AbbonamentoPranzo\");\r\n\t\t\tvar Iscrizione = document.getElementById(\"Iscrizione\");\r\n\t\t\tif (!Iscrizione.checked && AbbonamentoPranzo.checked) {\r\n\t\t\t\talert(\"Non è possibile registrare l'abbonamento ai pranzi senza l'iscrizione, almeno come ospite\");\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t// chiedo conferma per la cancellazione dell'abbonamento\r\n\t\t\tif (!AbbonamentoPranzo.checked) {\r\n\t\t\t\t//if (!confirm(\"Attenzione! Sei sicuro di voler togliere all'iscritto l'abbonamento pranzi?\")) {\r\n\t\t\t\t\t//AbbonamentoPranzo.checked = true;\r\n\t\t\t\t//}\r\n\t\t\t} else {\r\n\t\t\t\t//if (confirm(\"Attenzione! Impostando l'abbonamento pranzi verranno annullati tutti i pranzi singoli\\nVuoi proseguire?\")) {\r\n\t\t\t\t\t// annullo i pranzi singoli se è impostato l'abbonamento\r\n\t\t\t\t\tvar Pranzi = document.getElementsByName(\"Pranzo[]\");\r\n\t\t var PranziGratis = document.getElementsByName(\"GratisPranzo[]\");\r\n\t\t\t\t\tfor (i=0; i < Pranzi.length; i++) {\r\n\t\t\t\t\t\tPranzi[i].checked = false;\r\n\t\t\t\t\t\tPranziGratis[i].checked = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t//} else {\r\n\t\t\t\t//\tAbbonamentoPranzo.checked = false;\r\n\t\t\t\t//}\r\n\t\t\t}\r\n\t\t\t// ricalcolo il totale\r\n\t\t\tdocument.getElementById(\"CostoTotaleEuroCalcolato\").value = CalcolaCostoTotale().toFixed(2).replace(\".\", \",\");\r\n\t\t\treturn; \r\n } // fine funzione controllo dell'abbonamento pranzo",
"function abrirBlancosCercanos(fila, columna, numeroFilas, numeroColumnas) {\n /*\n Se recorren en un ciclo for las 8 adyacencias (arriba, izq, der, etc etc)\n Por cada adyacencia: \n 1. Si es numero, marca destapado.\n 2. Si es un blanco y no esta destapado, marca destapado y llama a esta misma funcion\n */\n \n // Declarando variables para adyacencias\n var arribaIzq = null, arriba = null, arribaDer = null, izquierda = null;\n var abajoIzq = null, abajo = null, abajoDer = null, derecha = null;\n // Asignando Variables\n if (fila > 0 && columna > 0) {\n arribaIzq = filas[fila - 1][columna - 1];\n }\n if (columna > 0) {\n izquierda = filas[fila][columna - 1]\n if (fila < numeroFilas - 1) {\n abajoIzq = filas[fila + 1][columna - 1]\n }\n }\n if (fila > 0) {\n arriba = filas[fila - 1][columna]\n if (columna < numeroColumnas - 1) {\n arribaDer = filas[fila - 1][columna + 1]\n }\n }\n if (columna < numeroColumnas - 1) {\n derecha = filas[fila][columna + 1]\n }\n if (fila < numeroFilas - 1) {\n abajo = filas[fila + 1][columna]\n }\n if ((fila < numeroFilas - 1) && (columna < numeroColumnas - 1)) {\n abajoDer = filas[fila + 1][columna + 1]\n }\n // Verificando adyacencias\n if (arribaIzq != null) {\n if (arribaIzq.contenido == 'numero') {\n arribaIzq.estado = 'descubierto'\n }\n if (arribaIzq.contenido == 'blanco' && arribaIzq.estado != 'descubierto') {\n arribaIzq.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n if (arriba != null) {\n if (arriba.contenido == 'numero') {\n arriba.estado = 'descubierto'\n }\n if (arriba.contenido == 'blanco' && arriba.estado != 'descubierto') {\n arriba.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna, numeroFilas, numeroColumnas)\n }\n }\n if (arribaDer != null) {\n if (arribaDer.contenido == 'numero') {\n arribaDer.estado = 'descubierto'\n }\n if (arribaDer.contenido == 'blanco' && arribaDer.estado != 'descubierto') {\n arribaDer.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (derecha != null) {\n if (derecha.contenido == 'numero') {\n derecha.estado = 'descubierto'\n }\n if (derecha.contenido == 'blanco' && derecha.estado != 'descubierto') {\n derecha.estado = \"descubierto\";\n abrirBlancosCercanos(fila, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (abajoDer != null) {\n if (abajoDer.contenido == 'numero') {\n abajoDer.estado = 'descubierto'\n }\n if (abajoDer.contenido == 'blanco' && abajoDer.estado != 'descubierto') {\n abajoDer.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (abajo != null) {\n if (abajo.contenido == 'numero') {\n abajo.estado = 'descubierto'\n }\n if (abajo.contenido == 'blanco' && abajo.estado != 'descubierto') {\n abajo.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna, numeroFilas, numeroColumnas)\n }\n }\n if (abajoIzq != null) {\n if (abajoIzq.contenido == 'numero') {\n abajoIzq.estado = 'descubierto'\n }\n if (abajoIzq.contenido == 'blanco' && abajoIzq.estado != 'descubierto') {\n abajoIzq.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n if (izquierda != null) {\n if (izquierda.contenido == 'numero') {\n izquierda.estado = 'descubierto'\n }\n if (izquierda.contenido == 'blanco' && izquierda.estado != 'descubierto') {\n izquierda.estado = \"descubierto\";\n abrirBlancosCercanos(fila, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n}",
"function irComputadores() {\n // Eliminar la clase Activa de los enlaces y atajos\n eliminarClaseActivaEnlances(enlaces, 'activo');\n eliminarClaseActivaEnlances(atajosIcons, 'activo-i');\n // Añadimos la clase activa de la seccion de Coputadores en los enlaces y atajos\n añadirClaseActivoEnlaces(enlaceComputadores, 'activo');\n añadirClaseActivoEnlaces(atajoComputadores, 'activo-i');\n // Crear contenido de la Seccion\n crearContenidoSeccionComputadores();\n // Abrir la seccion \n abrirSecciones();\n}",
"function MetaCaixaInit() {\n //S'executa al carregar-se la pàgina, si hi ha metacaixes,\n // s'assignen els esdeveniments als botons\n //alert(\"MetaCaixaInit\");\n var i = 0 //Inicialitzem comptador de caixes\n for (i = 0; i <= 9; i++) {\n var vMc = document.getElementById(\"mc\" + i);\n if (!vMc) break;\n //alert(\"MetaCaixaInit, trobada Metacaixa mc\"+i);\n var j = 1 //Inicialitzem comptador de botons dins de la caixa\n var vPsIni = 0 //Pestanya visible inicial\n for (j = 1; j <= 9; j++) {\n var vBt = document.getElementById(\"mc\" + i + \"bt\" + j);\n if (!vBt) break;\n //alert(\"MetaCaixaInit, trobat botó mc\"+i+\"bt\"+j);\n vBt.onclick = MetaCaixaMostraPestanya; //A cada botó assignem l'esdeveniment onclick\n //alert (vBt.className);\n if (vBt.className == \"mcBotoSel\") vPsIni = j; //Si tenim un botó seleccionat, en guardem l'index\n }\n //alert (\"mc=\"+i+\", ps=\"+j+\", psini=\"+vPsIni );\n if (vPsIni == 0) { //Si no tenim cap botó seleccionat, n'agafem un aleatòriament\n vPsIni = 1 + Math.floor((j - 1) * Math.random());\n //alert (\"Activant Pestanya a l'atzar; _mc\"+i+\"bt\"+vPsIni +\"_\");\n document.getElementById(\"mc\" + i + \"ps\" + vPsIni).style.display = \"block\";\n document.getElementById(\"mc\" + i + \"ps\" + vPsIni).style.visibility = \"visible\";\n document.getElementById(\"mc\" + i + \"bt\" + vPsIni).className = \"mcBotoSel\";\n }\n }\n }",
"function ActCC()\n\t{\n\tvar x = document.getElementById('forpagos').value;\n\tvar y = x.split('[||]');\n\tvar cd = y[0]; // Código de Documento\n\tvar ds = y[1]; // Descripción\n\tvar cta = y[2]; // Cuenta Contable\n\tvar dp = y[3]; // Tipo de Pago\n\tvar cc = y[4]; // Centro de Costo\n\tvar td = y[5]; // Conciliacion\n\t\n\t/* Activa Centro de costo */\n\tif (cc=='S') { document.getElementById('ccosto').disabled=false; }\n\telse { document.getElementById('ccosto').disabled=true; }\n\n\t/* Si el pago es con Cheque a Fecha, Muestro zona oculta */\n\tif (cd=='CH') { document.getElementById('oculto').style.display='block'; }\n\telse { document.getElementById('oculto').style.display='none'; }\n\n\t/* Activa Conciliacion si TipoDocumentoConciliacion es Diferente a 00 */\n\tif (td!='00')\n\t\t{\n\t\tdocument.getElementById('tipdoccon').disabled=false;\n\t\tif ($.trim(td)!='')\n\t\t\t{\n\t\t\tdocument.getElementById('areanumdoccb').style.display='block';\n\t\t\t}\n\t\telse \n\t\t\t{\n\t\t\tdocument.getElementById('areanumdoccb').style.display='none';\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\tdocument.getElementById('tipdoccon').disabled=true;\n\t\tdocument.getElementById('areanumdoccb').style.display='none';\n\t\t}\n\t$('#cc').val(cc);\n\t$('#ctable').val(cta);\n\t}",
"activerConcert() {\n this.activeAccueil = false;\n this.activeSpotify = false;\n this.activeLyrics = false;\n this.activeInfos = false;\n this.activeConcert = true;\n this.activeContact = false;\n this.activeAPropos = false;\n this.changementAccueil.emit(\"concert\");\n }",
"function inviertePalabras(cad) {\r\n \r\n }",
"function controlloVincita()\n{\n\tvincita=true;\n\ti=0, n=0;\n\tfor (j=0; j<15;j++)\n\t{\n\t\tvar n=parseInt($(\"#mainTable\").children().eq(j).attr(\"id\"));\n\t\tn+=1;\n\t\tif ($(\"#mainTable\").children().eq(j).text()!=n)\n\t\t{\n\t\t\tvincita=false;\n\t\t}\n\t}\n\t//Se ho vinto fermo il cronometro e mostro i dettagli della partita\n\tif (vincita==true)\n\t{\n\t\tvittoria();\n\t\tswitchCronometro();\n\t}\n}",
"function seleccionCalculo(tipoCalculo) {\n if (tipoCalculo == \"inmueble\") {\n calculoActivo = \"inmueble\";\n botonActivo();\n }\n if (tipoCalculo == \"carro\") {\n calculoActivo = \"carro\";\n botonActivo();\n }\n if (tipoCalculo == \"honorarios\") {\n calculoActivo = \"honorarios\";\n botonActivo();\n }\n}",
"function HabilitarControlesAvanzar() {\n\n\n window.parent.App.gpOrdenEstimacion.setDisabled(false);\n window.parent.App.dfFechaEmision.setDisabled(false);\n window.parent.App.txtfObservaciones.setDisabled(false);\n window.parent.App.txtfObservaciones.setReadOnly(false);\n window.parent.App.imgbtnGuardar.setDisabled(false);\n window.parent.App.imgbtnBorrar.setDisabled(false);\n window.parent.App.imgbtnCancelar.setDisabled(true);\n window.parent.App.chkAtendido.setReadOnly(false);\n\n window.parent.App.IdCliente.setDisabled(false);\n window.parent.App.txtfSucursalCR.setDisabled(false);\n\n\n window.parent.App.dfFechaOrigen.setReadOnly(false);\n window.parent.App.dfFechaMaxima.setReadOnly(false);\n window.parent.App.nfDiasAtencion.setReadOnly(false);\n window.parent.App.nfDiasAtencion.setDisabled(false);\n window.parent.App.txtfReporta.setReadOnly(false);\n window.parent.App.txtfReporta.setDisabled(false);\n\n window.parent.App.txtfNoReporte.setReadOnly(false);\n\n window.parent.App.txtfTrabajoRequerido.setReadOnly(false);\n window.parent.App.txtfTrabajoRequerido.setDisabled(false);\n\n\n window.parent.App.txtfCodigoFalla.setDisabled(false);\n window.parent.App.txtfCodigoFalla.setReadOnly(false);\n\n window.parent.App.dfFechaLlegada.setReadOnly(false);\n window.parent.App.tfHoraLlegada.setReadOnly(false);\n window.parent.App.dfFechaFinActividad.setReadOnly(false);\n window.parent.App.tfHoraFinActividad.setReadOnly(false);\n window.parent.App.cmbCuadrilla.setReadOnly(false);\n window.parent.App.cmbCuadrilla.setDisabled(false);\n\n\n window.parent.App.tHoraOrigen.setReadOnly(false);\n window.parent.App.chkAtendido.setDisabled(false);\n window.parent.App.chkAtendido.setReadOnly(false);\n\n\n window.parent.App.cmbClasificacion.setReadOnly(false);\n window.parent.App.cmbDivision.setReadOnly(false);\n \n //6. Deshabilita los comandos del grid\n window.parent.App.ccFotos.commands[0].disabled = false;\n window.parent.App.ccFotos.commands[1].disabled = false;\n window.parent.App.ccCroquis.commands[0].disabled = false;\n window.parent.App.ccCroquis.commands[1].disabled = false;\n window.parent.App.ccFacturas.commands[0].disabled = false;\n window.parent.App.ccFacturas.commands[1].disabled = false;\n window.parent.App.ccConcepto.commands[0].disabled = false;\n window.parent.App.gpOrdenEstimacion.reconfigure();\n}",
"function annullaCapitolo() {\n\t\tvar varieUEB = $(\"#tabellaUEBTrovate\").dataTable().fnGetData();\n\t var clone = $.extend(true, {}, varieUEB);\n\t var oggettoDaInserire = {};\n\t var form = $('form');\n\t\n\t form.overlay('show');\n\t\n\t // Carico ogni UEB nella lista in sessione\n\t $.each(clone, function(index, value) {\n\t var qualifiedValue = qualify(value, \"specificaUEB.listaUEBDaAnnullare[\" + index + \"]\");\n\t $.extend(true, oggettoDaInserire, qualifiedValue);\n\t });\n\t\n\t $.postJSON(\n\t \"annullaCapitoli_importiUeb_aggiornamento.do\",\n\t oggettoDaInserire,\n\t function(data) {\n\t var errori = data.errori;\n\t var messaggi = data.messaggi;\n\t var informazioni = data.informazioni;\n\t // Alerts\n\t var alertErrori = $(\"#ERRORI\");\n\t var alertMessaggi = $(\"#MESSAGGI\");\n\t var alertInformazioni = $(\"#INFORMAZIONI\");\n\t\n\t // Controllo che non vi siano errori\n\t if(impostaDatiNegliAlert(errori, alertErrori)) {\n\t return;\n\t }\n\t if(impostaDatiNegliAlert(messaggi, alertMessaggi)) {\n\t return;\n\t }\n\t if(impostaDatiNegliAlert(informazioni, alertInformazioni)) {\n\t return;\n\t }\n\t\t\n\t leggiCapitoliNellaVariazione();\n\t \t\n\t $('#pulsanteApriRicercaCapitolo').trigger('click');\n\t }\n\t //).always(form.removeClass.bind(form, 'form-submitted'));\n\t ).always(form.overlay.bind(form, 'hide'));\n\t}",
"function menu2_carte(id){\n\t\tattaquante=rechercherCarteDsAtt(id.substring(1));\n\t\t\t\t\n\t\tsaisie= prompt(\"CA cibler adversaire | C1 cibler ADV.att1 |C2 cibler ADV.att2 | CC: cibler autres cartes ?\");\n\t\tif (saisie!=null){\n\t\t\tsaisie = saisie.toUpperCase();\n\t\t\tswitch (saisie){\n\t\t\t\tcase \"CA\": \n\t\t\t\t\t//infliger les dégats à l'adversaire\t\t\t\n\t\t\t\t\tpv_adv = pv_adv-attaquante.ATT;\n\t\t\t\t\t\n\t\t\t\t\t$(\"#vieadv\").html(pv_adv);\t//chnager couleur en fonction état J,orange,rouge ???\n\t\t\t\t\tif(pv_adv==0){\n\t\t\t\t\t\talert(\"BRAVO, vous avez gagné !!!\");\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase \"C1\":\n\t\t\t\tcase \"C2\":\n\t\t\t\t\t// @totest\n\t\t\t\t\tnoCible=parseInt(saisie.substring(1));\n\t\t\t\t\tcible = att_adv[noCible-1];\n\t\t\t\t\tif (cible!==\"undefined\"){\n\t\t\t\t\t\tcible.DEF = cible.DEF-attaquante.ATT;\n\t\t\t\t\t\t//SI def<0 => cimetiere\n\t\t\t\t\t\tif (cible.DEF<=0){\n\t\t\t\t\t\t\t//Placer la crétaure au cimetière\n\t\t\t\t\t\t\tcible.etat= ETAT_CIM;\n\t\t\t\t\t\t\tcible.def= cible.sauvdef;\n\t\t\t\t\t\t\tposerCarteDansCimetiere(cible);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//effacement carte\n\t\t\t\t\t\t\t$(\"#\"+cible.id).hide(2000);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//suppimer du tableau\n\t\t\t\t\t\t\tatt_adv[nocible-1]=\"undefined\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tseldef=\"#\"+cible.id+\" #def\";\n\t\t\t\t\t\t\t$(seldef).html(cible.DEF);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase \"CC\":\n\t\t\t\t\t//Faire saisir le no carte ciblée\n\t\t\t\t\tnoc= parseInt(prompt(\"Carte no: 1 |2 |3 | 4 ||0 pour sortir ?\"));\n\t\t\t\t\tif (noc>0){\n\t\t\t\t\t\tcible= jeu_adv[noc-1];\n\t\t\t\t\t\tafficherDetailsCarte(cible);\n\t\t\t\t\t\tif (cible!==\"undefined\"){\n\t\t\t\t\t\t\tcible.DEF-=attaquante.ATT;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (cible.DEF<=0){ //ATTENTION: du coup DEF=0 ds cimetière ???\n\t\t\t\t\t\t\t\t//Placer la créature au cimetière\n\t\t\t\t\t\t\t\tcible.etat= ETAT_CIM;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tcible.DEF=cible.sauvdef;\n\t\t\t\t\t\t\t\tconsole.log(\"APS cible.DEF=\"+cible.DEF);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tposerCarteDansCimetiere(cible);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//effacement carte\n\t\t\t\t\t\t\t\t$(\"#\"+cible.id).hide(2000);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//suppimer du tableau\n\t\t\t\t\t\t\t\tjeu_adv[noc-1]=\"undefined\";\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t//MAJ des cartes en jeu(DEF affichée)\n\t\t\t\t\t\t\t\tseldef=\"#\"+cible.id+\" #def\";\n\t\t\t\t\t\t\t\t$(seldef).html(cible.DEF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"function menu2_carte(id){\n\t\tattaquante=rechercherCarteDsAtt(id.substring(1));\n\t\tif(attaquante.etat != ETAT_ATT1 && attaquante.etat != ETAT_ATT2){\n\t\t\talert(\"Vous venez d'invoquer la carte, elle ne peut PAS attaquer déjà !\");\n\t\t}else {\t\t\n\t\t\tsaisie= prompt(\"CA cibler adversaire | C1 cibler ADV.att1 |C2 cibler ADV.att2 | CC: cibler autres cartes ?\");\n\t\t\tif (saisie!=null){\n\t\t\t\tsaisie = saisie.toUpperCase();\n\t\t\t\tswitch (saisie){\n\t\t\t\t\tcase \"CA\":\t\n\t\t\t\t\t my_logger(\"J'attaque \"+saisie);\n\t\t\t\t\t\tjeu_attaquerCA(true,attaquante);\n\t\t\t\t\t\tjeu_isFinJeu();\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"C1\":\n\t\t\t\t\tcase \"C2\":\n\t\t\t\t\t my_logger(\"J'attaque \"+saisie);\n\t\t\t\t\t\n\t\t\t\t\t\tnoCible=parseInt(saisie.substring(1));\n\t\t\t\t\t\tjeu_attaquerC(true,noCible,attaquante);\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"CC\":\n\t\t\t\t\t\t//Faire saisir le no carte ciblée\n\t\t\t\t\t\tnoc= parseInt(prompt(\"Carte no: 1 |2 |3 | 4 ||0 pour sortir ?\"));\n\t\t\t\t\t\tif (noc>0){\t\t\n\t\t\t\t\t\t\tmy_logger(\"J'attaque \"+saisie+noc);\n\t\t\t\t\t\t\tcible= jeu_adv[noc-1];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tjeu_attaquerCC(true,noc,cible,attaquante);\n\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function spectre(){//perte de tous les souvenirs et multi\n\t\tsouvenirs = 0;\n\t\tSouvenirs.innerHTML = souvenirs;\n\t\tauto = 0;\n\t\tif(compteur >1){\n\t\tcompteur = 1;\n\t\t}\n\t\t//Bonus_malus.innerHTML = compteur ;\n\t}//tres mechant----"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate peer identity keypair + transform to desired format + add to config. | function generateAndSetKeypair() {
var keys = peerId.create({
bits: opts.bits
});
config.Identity = {
PeerID: keys.toB58String(),
PrivKey: keys.privKey.bytes.toString('base64')
};
writeVersion();
} | [
"function generateAndSetKeypair () {\n var keys = peerId.create({\n bits: opts.bits\n })\n config.Identity = {\n PeerID: keys.toB58String(),\n PrivKey: keys.privKey.bytes.toString('base64')\n }\n\n writeVersion()\n }",
"function genKeyPair() {\n\n generateKeyPair('rsa', {\n modulusLength: 4096, // bits - standard for RSA keys\n //namedCurve: 'secp256k1', // Options \n publicKeyEncoding: {\n type: 'pkcs1',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs1',\n format: 'pem'\n }\n },\n (err, publicKey, privateKey) => { // Callback function \n if (!err) {\n // Create the public key file\n fs.writeFileSync(__dirname + '/id_rsa_pub.pem', publicKey);\n // Create the private key file\n fs.writeFileSync(__dirname + '/id_rsa_priv.pem', privateKey);\n }\n else {\n // Prints error \n console.log(\"Errr is: \", err);\n }\n });\n\n}",
"function generatePair(callback)\n{\n crypto.generateKeyPair('rsa',{\n modulusLength : 2048,\n publicExponenet : 0x10001,\n\n\n publicKeyEncoding:{\n type : 'pkcs1',\n format : 'pem'\n },\n\n privateKeyEncoding:{\n type: 'pkcs8',\n format : 'pem',\n cipher : 'aes-192-cbc',\n passphrase : 'pass'\n }}\n\n ,(err,publicKey,privateKey) => {\n if(err)\n console.log(err);\n else\n {\n callback(publicKey,privateKey);\n }\n }\n )}",
"function generateKeypair () {\n crypt = new JSEncrypt({default_key_size: 2056})\n privateKey = crypt.getPrivateKey()\n\n//Only return the public key, keep the private key hidden for obvious reasons\n return crypt.getPublicKey()\n}",
"generateKeyPair() {\n const keys = native_crypto.generateKeyPairSync(\"rsa\", this.config.keyPair)\n this.publicKeyString = keys.publicKey\n this.privateKeyString = keys.privateKey\n this.loadKeys()\n }",
"generateKeyPair() {\n this.keys = forge.pki.rsa.generateKeyPair(1024);\n }",
"function generateKeys() {\n const { publicKey, privateKey } = generateKeyPairSync('rsa', \n {\n modulusLength: 4096,\n namedCurve: 'secp256k1', \n publicKeyEncoding: {\n type: 'spki',\n format: 'pem' \n }, \n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: passphrase\n } \n });\n\n writeFileSync('private.pem', privateKey)\n writeFileSync('public.pem', publicKey)\n}",
"function deriveKeyPair(privateKeySeed) {\n const {publicKey, secretKey} = nacl.sign.keyPair.fromSeed(privateKeySeed);\n return {publicKey: nacl.util.encodeBase64(publicKey), privateKey: nacl.util.encodeBase64(secretKey)}\n}",
"function generateKeyPair(req, res, next){\n\n var comment = req.params.email;\n var keyName = req.params.keyName;\n var pair = keypair();\n var publicKey = forge.pki.publicKeyFromPem(pair.public);\n var publicKeySSH = forge.ssh.publicKeyToOpenSSH(publicKey, comment);\n\n //BUGFIX:if a key already exists with a key name a new one should not be generated.\n\n\n r.table('keys').insert([\n { \n username: req.params.username,\n password: req.params.password,\n baseKeyName: keyName,\n publicKeyName: keyName+'_public',\n privateKeyName: keyName+'_private',\n publicKeyValue: publicKeySSH,\n privateKeyValue: pair.private,\n component: req.params.component,\n timestamp: new Date()\n }\n ]).run(connection, function(err, result) {\n if (err) throw err;\n console.log(JSON.stringify(result, null, 2));\n res.send(200, pair.private);\n return next();\n }); \n}",
"function createKeyPair() {\n window.crypto.subtle.generateKey(\n {\n name: \"RSASSA-PKCS1-v1_5\",\n modulusLength: 2048,\n publicExponent: new Uint8Array([1, 0, 1]), // 65537\n hash: {name: \"SHA-256\"}\n },\n true,\n [\"sign\", \"verify\"]\n ).then(function(keyPair) {\n\n window.crypto.subtle.exportKey(\"spki\", keyPair.publicKey\n ).then(function(spkiBuffer) {\n var spkiBytes = new Uint8Array(spkiBuffer);\n var spkiString = byteArrayToBase64(spkiBytes);\n var spkiBox = document.getElementById(\"publickey\");\n spkiBox.value = spkiString;\n }).catch(function(err) {\n alert(\"Could not export public key: \" + err.message);\n });\n\n window.crypto.subtle.exportKey(\"pkcs8\", keyPair.privateKey\n ).then(function(pkcs8Buffer) {\n var pkcs8Bytes = new Uint8Array(pkcs8Buffer);\n var pkcs8String = byteArrayToBase64(pkcs8Bytes);\n var pkcs8Box = document.getElementById(\"privatekey\");\n pkcs8Box.value = pkcs8String;\n }).catch(function(err) {\n alert(\"Could not export private key: \" + err.message);\n });\n\n }).catch(function(err) {\n alert(\"Could not generate key pair: \" + err.message);\n });\n}",
"function createKeyPair() {\n\tfunction exportKey(buffer, type) {\n\t\tvar keyBytes = new Uint8Array(buffer);\n\t\tvar keyString = byteArrayToBase64(keyBytes);\n\t\tvar keyBox = document.getElementById(type);\n\t\tkeyBox.value = keyString;\n\t}\n\t// Replace this alert with the correct code\n\twindow.crypto.subtle.generateKey({\n\t\t\tname: 'RSASSA-PKCS1-v1_5',\n\t\t\tmodulusLength: 2048,\n\t\t\tpublicExponent: new Uint8Array([1, 0, 1]), // 65537\n\t\t\thash: {\n\t\t\t\tname: \"SHA-256\"\n\t\t\t}\n\n\t\t}, true, ['sign', 'verify']).then(function (keyPair) {\n\n\t\t\twindow.crypto.subtle.exportKey('spki', keyPair.publicKey)\n\t\t\t\t.then(function(spkiBuffer){exportKey(spkiBuffer, 'publickey')})\n\t\t\t\t.catch(function (err) {\n\t\t\t\t\talert(\"Could not export public key: \" + err.message);\n\t\t\t\t});\n\n\t\t\twindow.crypto.subtle.exportKey('pkcs8', keyPair.privateKey)\n\t\t\t\t.then(function(pkcs8buffer){exportKey(pkcs8buffer, 'privatekey')})\n\t\t\t\t.catch(function (err) {\n\t\t\t\t\talert(\"Could not export public key: \" + err.message);\n\t\t\t\t});\n\n\t\t})\n\t\t.catch(function (err) {\n\t\t\tthrow new Error(err.message);\n\t\t})\n}",
"function createKeyPair() {\n reporter.log('...Creating new Key Pair...');\n saveKey(ursa.generatePrivateKey());\n}",
"function generateKeyPair() {\r\n var key = new rsa().generateKeyPair(2048, 65537); // Generate 2048-bit key\r\n\r\n return {\r\n publicKey: key.exportKey('public'), // 'pkcs8-public-pem'\r\n privateKey: key.exportKey('private') // 'pkcs1-private-pem'\r\n };\r\n}",
"static async makeKeypair(seed) {\n await libsodium_wrappers_1.default.ready;\n const keypair = libsodium_wrappers_1.default.crypto_sign_seed_keypair(seed);\n return Ed25519Keypair.fromLibsodiumPrivkey(keypair.privateKey);\n }",
"async function main(){\n \n const bobChain = new KeyChain( )\n\n await bobChain.open()\n \n await bobChain.generateKey({\n email: 'bob@test.xyz',\n name: 'Bob bob',\n unattend: true,\n })\n\n const who = await bobChain.whoami()\n console.log('bob whoami',who)\n\n const bobPub = await bobChain.exportPublicKey(who[0])\n console.log(bobPub)\n\n const aliceChain = new KeyChain()\n\n await aliceChain.open()\n\n await aliceChain.generateKey({\n email: 'alice@test.xyz',\n name: 'Alice alice',\n unattend: true,\n })\n\n const imported = await aliceChain.importKey(bobPub)\n console.log('imported', imported)\n\n await aliceChain.trustKey(imported[0], '3')\n await aliceChain.signKey(imported[0])\n\n const secrets = await aliceChain.listSecretKeys(false)\n console.log('secrets', secrets)\n\n const other = await aliceChain.whoami()\n console.log('alice whoami',other)\n\n const alicePub = await aliceChain.exportPublicKey(other[0])\n\n const bobImported = await bobChain.importKey(alicePub)\n\n await bobChain.trustKey(bobImported[0], '3')\n await bobChain.signKey(bobImported[0])\n\n\n\n let toEmails = ['alice@test.xyz']\n\n\n const enc = await bobChain.encrypt('hello world', who.concat(toEmails), who[0])\n console.log('encrypt -', enc)\n\n const dec = await aliceChain.decrypt(enc, {from: 'bob@test.xyz'})\n console.log('decrypt -', dec.toString())\n\n return\n}",
"function generateRsaKeypair(){\n //generating an 2048 bit RSA keypair\n crypto.keys.generateKeyPair('RSA', 2048, async(err, keypair) => {\n if(err){\n console.log('error ', err);\n }\n else{\n console.log(\"\\nGenerated new RSA Keypair\\n\");\n createIpnsRecord(keypair);\n }\n });\n}",
"async function generateDidPeer() {\r\n\r\n // Ask browser to create a key pair with the p256 curve\r\n var keyPair = await crypto.subtle.generateKey(\r\n {\r\n name: \"ECDSA\",\r\n namedCurve: \"P-256\"\r\n },\r\n true,\r\n [\"sign\", \"verify\"]\r\n );\r\n\r\n // Export both keys to the JWK format (see spec for details)\r\n var privateKeyJWK = await crypto.subtle.exportKey(\"jwk\", keyPair.privateKey);\r\n var publicKeyJWK = await crypto.subtle.exportKey(\"jwk\", keyPair.publicKey);\r\n\r\n // Get the key fingerprint in Peer DID format\r\n let fingerprint = await keyPairFingerprint(keyPair);\r\n\r\n // Buid the DID string\r\n var did = `did:peer:${fingerprint}`;\r\n\r\n // Return an object with the DID and both keys\r\n return { did: did, privateKey: privateKeyJWK, publicKey: publicKeyJWK };\r\n\r\n}",
"async createPublicKeyFromPrivateKey(){\n if (this.privateKeyObj !== null){\n const jscu = getJscu();\n this.publicKeyObj = new jscu.Key('pem', await this.privateKeyObj.export('pem', {outputPublic: true}));\n }\n }",
"function generate() {\n let publicKey = rsa.getPublicKey();\n let publicKeySet = JSONWebKey.fromPEM(publicKey);\n console.log('Public key set ->', publicKeySet.toJSON());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get our information from the info sheet The only fields applicable are the api key, region, summoner name, season, summoner id, and check duoer | function getInfo(value) {
var s = SpreadsheetApp.getActiveSpreadsheet();
var sheet = s.getSheetByName('Configuration');
if(value == 'api_key') {
return sheet.getRange('B1').getValue();
}
if(value == 'region') {
return sheet.getRange('B2').getValue();
}
if(value == 'summoner_name') {
return sheet.getRange('B3').getValue();
}
if(value == 'season') {
return sheet.getRange('B6').getValue();
}
if(value == 'check_duoer') {
return sheet.getRange('B7').getValue();
}
if(value == 'correct_row') {
var row = sheet.getRange('B8').getValue();
if(row) {
return row;
}
else {
Browser.msgBox("Error, please enter a row number to be corrected when using this option")
return;
}
}
// summoner_id has a special case because it's populated the first time we run the script
if(value == 'summoner_id') {
val = sheet.getRange('B4').getValue();
if(!val) {
val = getSummonerId();
if(val == 'exit') {
return 'exit';
}
}
sheet.getRange('B4').setValue(val);
return val;
}
if(value == 'account_id') {
val = sheet.getRange('B5').getValue();
if(!val) {
val = getAccountId();
if(val == 'exit') {
return 'exit';
}
}
sheet.getRange('B5').setValue(val);
return val;
}
} | [
"async getAllInfoBySummonerName() {\n try {\n let temp = {};\n // First get basic summoner data by summoner name, update temp\n const summonerInfoByName = await this.getSummonerBySummonerName();\n temp = { ...temp, ...summonerInfoByName };\n\n // Then get that summoners league info by id\n this.payload.summonerId = temp.id;\n let summonerLeagueInfoById = await this.getLeagueBySummonerId();\n summonerLeagueInfoById = summonerLeagueInfoById[0];\n temp = { ...temp, ...summonerLeagueInfoById };\n\n // Then get the summoners last 20 match id's\n this.payload.puuid = temp.puuid;\n const TwentyMatchIds = await this.getMatchByPuuidAndCount();\n temp = { ...temp, matchIds: TwentyMatchIds };\n\n // Finally, get the match data for the last 20 matchs\n this.payload.matchIds = temp.matchIds;\n const lastTwentyMatchs = await this.getBatchOfMatchInfo();\n temp = { ...temp, allMatchInfo: lastTwentyMatchs }\n\n // Return data\n return temp;\n\n } catch(err) {\n throw new Error(err);\n }\n }",
"function getGameInfo() {\n limiter.request({\n url: `https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?champData=all&${api}`,\n method: 'GET',\n json: true,\n }, (error, response) => {\n if (!error && response.statusCode === 200) {\n champions = response.body.data;\n version = response.body.version;\n console.log(champions);\n }\n if (error) {\n throw new Error('Cannot connect to Riot API');\n }\n });\n}",
"function getMyLeagueStats() {\n var url = 'https://' + getInfo('region') + '.api.riotgames.com/lol/league/v3/leagues/by-summoner/' + getInfo('summoner_id') + '?api_key=' + getInfo('api_key');\n var s = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = s.getSheetByName('Data');\n var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});\n var status = checkStatusError(response);\n if(!status) {\n var json = response.getContentText();\n var data = JSON.parse(json);\n var stats = {};\n var division, lp, tier, promos;\n stats['tier'] = data[0]['tier'];\n for(i = 0; i < data[0]['entries'].length; i++) {\n if(data[0]['entries'][i]['playerOrTeamName'] == getInfo('summoner_name')) {\n stats['division'] = data[0]['entries'][i]['rank'];\n stats['lp'] = data[0]['entries'][i]['leaguePoints'];\n stats['promos'] = 'No';\n if(data[0]['entries'][i]['miniSeries']) {\n if(data[0]['entries'][i]['miniSeries']['progress'] != 'NNN') {\n stats['promos'] = 'Yes';\n }\n }\n //return [tier, division, lp, promos];\n return stats;\n }\n }\n }\n else if(status == 'exit') {\n return 'exit';\n }\n else if(typeof(status) == 'number') {\n Utilities.sleep(status);\n return getMyLeagueStats();\n }\n else { // default wait 10 seconds if we fail but don't know why \n Utilities.sleep(10000);\n return getMyLeagueStats();\n }\n}",
"async fetchTFTSummonerInfo(summonerName) {\n const url = `/tft/summoner/v1/summoners/by-name/${summonerName}`\n\n let response\n try {\n response = await axios.get(\n url,\n this.getHeaders({ baseURL: config.get('riot.baseURL') })\n )\n return this.transformSummonerInfo(response.data)\n } catch (err) {\n logger.error(\n `An error occurred attempting to fetch summoner info for ${summonerName}, ${err.message}`\n )\n throw err\n }\n }",
"function extractRelevantPlayerDataByName(players_info) {\r\n console.log(players_info);\r\n return players_info.map((player_info) => {\r\n console.log(player_info)\r\n const { fullname, image_path, position_id } = player_info;\r\n if ('team' in player_info){\r\n const { name } = player_info.team.data;\r\n return {\r\n name: fullname,\r\n image: image_path,\r\n position: position_id,\r\n team_name: name ,\r\n };\r\n }\r\n else{\r\n return {\r\n name: fullname,\r\n image: image_path,\r\n position: position_id,\r\n team_name: 'No Team' ,\r\n };\r\n }\r\n });\r\n}",
"async function getLeagueDetails() {\n // get league details\n const league = await axios.get(\n `https://soccer.sportmonks.com/api/v2.0/leagues/${LEAGUE_ID}`,\n {\n params: {\n include: \"season\",\n api_token: process.env.api_token,\n },\n }\n );\n let stage;\n let stage_name;\n // if there is non current stage in league\n if(league.data.data.current_stage_id != null){\n stage = await axios.get(\n `https://soccer.sportmonks.com/api/v2.0/stages/${league.data.data.current_stage_id}`,\n {\n params: {\n api_token: process.env.api_token,\n },\n }\n );\n stage_name = stage.data.data.name;\n }\n else{\n stage = null;\n stage_name = null;\n }\n // get the most near game that going to play\n let nextGameDeatails = await match_utils.getNextGameDetails(); \n\n return {\n league_name: league.data.data.name,\n current_season_name: league.data.data.season.data.name,\n current_stage_name: stage_name,\n nextGameDeatails: nextGameDeatails\n };\n}",
"async info() {\n return await this.api.querySheetInfo(this.sheetId);\n }",
"async function getLeagueDetails() {\r\n const league = await axios.get(\r\n `https://soccer.sportmonks.com/api/v2.0/leagues/${LEAGUE_ID}`,\r\n {\r\n params: {\r\n include: \"season\",\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n );\r\n if (league.data.data.current_stage_id == null){\r\n var stageName = \"No Stage on the momennt\";\r\n }\r\n else{\r\n const stage = await axios.get(\r\n `https://soccer.sportmonks.com/api/v2.0/stages/${league.data.data.current_stage_id}`,\r\n {\r\n params: {\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n );\r\n var stageName = stage.data.data.name;\r\n }\r\n\r\n const next_game = await DButils.execQuery(`SELECT TOP 1 * FROM dbo.Matches WHERE HomeGoals IS NULL ORDER BY Date asc`);\r\n\r\n return {\r\n league_name: league.data.data.name,\r\n current_season_name: league.data.data.season.data.name,\r\n current_stage_name: stageName,\r\n nextgame: next_game\r\n };\r\n}",
"function extractRelevantPlayerPageDataByID(players) {\r\n const player_info = players[0].data.data;\r\n const {player_id ,fullname, image_path, position_id, common_name, nationality, birthdate, birthcountry, height, weight } = player_info;\r\n \r\n if(player_info){ \r\n return {\r\n player_id: player_id,\r\n name: fullname,\r\n image: image_path,\r\n position: position_id,\r\n team_name: player_info.team? player_info.team.data.name : \"unkown\",\r\n common_name: common_name,\r\n nationality: nationality,\r\n birthdate: birthdate,\r\n birthcountry: birthcountry, \r\n height: height,\r\n weight: weight,\r\n }; \r\n } \r\n}",
"async function fetchSummoner() {\n if (typeof window.ethereum !== 'undefined') {\n const provider = new ethers.providers.Web3Provider(window.ethereum)\n const contract = new ethers.Contract(greeterAddress, Rarity.abi, provider)\n try {\n const data = await contract.()\n console.log('summoner: ', data)\n } catch (err) {\n console.log(\"Error: \", err)\n }\n } \n }",
"async function getPlayerDetails(player_id) {\r\n const Player = await axios.get(\r\n `https://soccer.sportmonks.com/api/v2.0/players/${player_id}`,\r\n {\r\n params: {\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n );\r\n\r\n const Team = await axios.get(\r\n `https://soccer.sportmonks.com/api/v2.0/teams/${Player.data.data.team_id}`,\r\n {\r\n params: {\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n );\r\n\r\n return{\r\n playerPreview: {\r\n player_id : Player.data.data.player_id,\r\n name: Player.data.data.fullname,\r\n image: Player.data.data.image_path,\r\n position: Player.data.data.position_id,\r\n team_name: Team.data.data.name,\r\n },\r\n common_name : Player.data.data.common_name,\r\n nationality : Player.data.data.nationality,\r\n birthdate : Player.data.data.birthdate,\r\n birthcountry : Player.data.data.birthcountry,\r\n height: Player.data.data.height,\r\n weight: Player.data.data.weight,\r\n }\r\n}",
"parseSummonerDataFromResponse(summoner) {\n var parsedSummoner = summoner;\n parsedSummoner.championMastery = (typeof summoner.championMastery == 'string' ? JSON.parse(summoner.championMastery) : summoner.championMastery);\n parsedSummoner.league = (typeof summoner.league == 'string' ? JSON.parse(summoner.league) : summoner.league);\n parsedSummoner.masteries = (typeof summoner.masteries == 'string' ? JSON.parse(summoner.masteries) : summoner.masteries);\n parsedSummoner.runes = (typeof summoner.runes == 'string' ? JSON.parse(summoner.runes) : summoner.runes);\n\n return parsedSummoner;\n }",
"async function getInfoAboutSpreadSheet() {\n try {\n return doc.getInfoAsync();\n } catch (e) {\n console.log(\"Get information error\", e);\n }\n}",
"async function getLeagueDetails() {\r\n const league = (await axios.get(\r\n `${api_domain}/leagues/${LEAGUE_ID}`, {\r\n params: {\r\n include: \"season\",\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n )).data.data;\r\n // In case current stage doesn't exist (summer break), pick the most early stage in Superliga.\r\n const current_stage = league.current_stage_id || 77453568\r\n const stage = (await axios.get(\r\n `${api_domain}/stages/${current_stage}`, {\r\n params: {\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n )).data.data;\r\n return {\r\n league_name: league.name,\r\n current_season_name: league.season.data.name,\r\n current_season_id: league.season.data.id,\r\n current_stage_name: stage.name,\r\n current_stage_id: stage.id\r\n };\r\n}",
"profile (region, summonerName) {\n region = RiotApi.getRegion(region);\n\n const summoner = RiotApi.get('https://{region}.api.pvp.net/api/lol/{region}/v1.4/summoner/by-name/{summonerNames}', {\n region,\n summonerNames: summonerName\n });\n\n if (!summoner)\n throw new Meteor.Error(403, 'There is no a summoner registered with that name');\n\n return summoner[summonerName];\n }",
"function getLeagueData(url, sheet, settingsSheet, notation){\n\n var season = retrieveSeason_(settingsSheet, notation);\n url = url.replace(\"####\", season);\n\n var json = retrieveJsonData_(url);\n var data = [];\n var dataDetails = [];\n \n //push columm headers onto the array\n dataDetails.push([\"Franchise ID\",\"Franchise Name\"]);\n \n for(var i=0; i<json.league.franchises.franchise.length; i++){\n \n //push columm values onto the array\n dataDetails.push([json.league.franchises.franchise[i].id, json.league.franchises.franchise[i].name]);\n \n }\n \n data = dataDetails;\n \n var sheet = SpreadsheetApp.getActive().getSheetByName(sheet);\n \n //clear the sheet before writing\n //sheet.clear({ formatOnly: false, contentsOnly: true });\n \n //setting range in sheet with sepecific coordinate because functions will be used in the sheet in other columns \n var range = sheet.getRange(1,1,data.length, data[0].length);\n sheet.setActiveRange(range).setValues(data);\n \n //hiding id column\n sheet.hideColumns(1);\n \n sheet.hideSheet();\n}",
"function getSummonerData(json, data) {\n\tjson.name = data.name;\n\tjson.id = data.id;\n\tjson.icon = data.profileIconId;\n}",
"async getBasicInfo() {\n const response = await this.fetchMainPage();\n const myName = scrape.myName(response.data);\n const balance = scrape.balance(response.data);\n const firstCardName = scrape.firstCardName(response.data);\n return { name: myName, balance: balance, firstCard: firstCardName };\n }",
"function getBeerData() {\n let data = FooBar.getData();\n beers = JSON.parse(data).beertypes;\n //This is for Section 5: \n beerInfo();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resizes a tab strip element. | _resize(event) {
const that = this;
if (!that._resizing) {
return;
}
const orientationSettings = that._orientationSettings,
sizeChange = event[orientationSettings.coordinate] - that._resizeFrom,
customElement = that._getCorrespondingCustomElement(that._tabToResize);
let oldSize;
if (customElement.labelSize === null) {
oldSize = that._tabToResize[orientationSettings.size];
}
else {
oldSize = customElement.labelSize;
}
const newSize = Math.max(10, oldSize + sizeChange);
if (newSize !== oldSize) {
customElement._preventPropertyChangedHandler = true;
customElement.labelSize = newSize;
that._tabToResize.style[orientationSettings.dimension] = parseInt(newSize, 10) + 'px';
}
that.$resizeToken.addClass('jqx-hidden');
that._applyTabOverflow();
that._resizing = false;
that.removeAttribute('resizing');
} | [
"function setElementsSize_hor() {\n\t\t\n\t\t// get strip height\n\t\tvar stripHeight = g_objStrip.getHeight();\n\t\tvar panelWidth = g_temp.panelWidth;\n\n\t\t// set buttons height\n\t\tif (g_objButtonNext) {\n\t\t\tg_objButtonPrev.height(stripHeight);\n\t\t\tg_objButtonNext.height(stripHeight);\n\n\t\t\t// arrange buttons tip\n\t\t\tvar prevTip = g_objButtonPrev.children(\".ug-strip-arrow-tip\");\n\t\t\tg_functions.placeElement(prevTip, \"center\", \"middle\");\n\n\t\t\tvar nextTip = g_objButtonNext.children(\".ug-strip-arrow-tip\");\n\t\t\tg_functions.placeElement(nextTip, \"center\", \"middle\");\n\t\t}\n\n\t\t// set panel height\n\t\tvar panelHeight = stripHeight + g_options.strippanel_padding_top\n\t\t\t\t+ g_options.strippanel_padding_bottom;\n\n\t\t// set panel size\n\t\tg_objPanel.width(panelWidth);\n\t\tg_objPanel.height(panelHeight);\n\n\t\tg_temp.panelHeight = panelHeight;\n\n\t\t// set strip size\n\t\tvar stripWidth = panelWidth - g_options.strippanel_padding_left\t- g_options.strippanel_padding_right;\n\n\t\tif (g_objButtonNext) {\n\t\t\tvar buttonWidth = g_objButtonNext.outerWidth();\n\t\t\tstripWidth = stripWidth - buttonWidth * 2 - g_options.strippanel_padding_buttons * 2;\n\t\t}\n\n\t\tg_objStrip.resize(stripWidth);\n\t}",
"function setElementsSize_vert() {\n\t\t\t\t\n\t\t// get strip width\n\t\tvar stripWidth = g_objStrip.getWidth();\n\t\tvar panelHeight = g_temp.panelHeight;\n\t\t\n\t\t// set buttons height\n\t\tif (g_objButtonNext) {\n\t\t\tg_objButtonPrev.width(stripWidth);\n\t\t\tg_objButtonNext.width(stripWidth);\n\n\t\t\t// arrange buttons tip\n\t\t\tvar prevTip = g_objButtonPrev.children(\".ug-strip-arrow-tip\");\n\t\t\tg_functions.placeElement(prevTip, \"center\", \"middle\");\n\n\t\t\tvar nextTip = g_objButtonNext.children(\".ug-strip-arrow-tip\");\n\t\t\tg_functions.placeElement(nextTip, \"center\", \"middle\");\n\t\t}\n\n\t\t// set panel width\n\t\tvar panelWidth = stripWidth + g_options.strippanel_padding_left\n\t\t\t\t+ g_options.strippanel_padding_right;\n\n\t\t// set panel size\n\t\tg_objPanel.width(panelWidth);\n\t\tg_objPanel.height(panelHeight);\n\n\t\tg_temp.panelWidth = panelWidth;\n\n\t\t// set strip size\n\t\tvar stripHeight = panelHeight - g_options.strippanel_padding_top\n\t\t\t\t- g_options.strippanel_padding_bottom;\n\n\t\tif (g_objButtonNext) {\n\t\t\tvar buttonHeight = g_objButtonNext.outerHeight();\n\t\t\tstripHeight = stripHeight - buttonHeight * 2\n\t\t\t\t\t- g_options.strippanel_padding_buttons * 2;\n\t\t}\n\n\t\tg_objStrip.resize(stripHeight);\n\t}",
"function resizeTabs() {\n\n // Get values for tab scaling BEFORE change\n var defaultTabWidth = 150;\n var numberOfTabs = pm.getNumberOfTabs(0);\n var paneWidth = $('.code-pane').width();\n var w = Math.floor(100 / numberOfTabs);\n var tabs = $('#code-pane-0 .code-tab');\n var tabText = $('#code-pane-0 .code-tab span');\n tabText.css(\"width\", \"auto\");\n var tabsWidth;\n var tabTextWidth;\n\n // If the tabs won't all fit...\n if((numberOfTabs * defaultTabWidth) >= paneWidth) {\n w = w.toString() + \"%\";\n tabs.css(\"width\", w);\n\n // Update values for tab scaling AFTER change\n tabs = $('#code-pane-0 .code-tab');\n tabText = $('#code-pane-0 .code-tab span');\n tabsWidth = tabs.outerWidth();\n tabTextWidth = tabsWidth - 55;\n tabText.css(\"width\", tabTextWidth);\n } else {\n tabs.css(\"width\", defaultTabWidth);\n }\n}",
"function _jsTabControl_draw() {\n\n\t//create string holder\n\tvar d = new jsDocument;\n\t\n\t//calculate tabs per strip\n\tthis.tabsPerStrip = parseInt((window.innerWidth - IMG_BTN_MORE.width - IMG_BTN_LESS.width) / this.tabWidth);\n\t\n\t//calculate number of strips needed\n\tvar numStrips = Math.ceil(this.tabs.length / this.tabsPerStrip);\n\t\n\t//need to create arrays for Netscape 4.x\n\tthis._strips = new Array;\n\tthis._tabs = new Array;\n\n\t//draw each strip\n\tfor (i=0; i < numStrips; i++)\n\t\tthis.createStrip(0 + (this.tabsPerStrip * i), this.tabsPerStrip + (this.tabsPerStrip * i));\n}",
"function setElementsSize() {\n\n\t\tif (g_options.strippanel_vertical_type == false)\n\t\t\tsetElementsSize_hor();\n\t\telse\n\t\t\tsetElementsSize_vert();\n\t}",
"_tabStripMoveHandler(event) {\n const that = this;\n\n if (that._dragStartDetails && !that._dragStartDetails.checked) {\n if (Date.now() - that._dragStartDetails.originalTime < 500) {\n that._endReordering(undefined, undefined);\n that._dragStartDetails.checked = true;\n }\n else {\n delete that._dragStartDetails;\n }\n }\n\n if (that._dragStartDetails &&\n (Math.abs(that._dragStartDetails.pageX - event.pageX) >= 5 ||\n Math.abs(that._dragStartDetails.pageY - event.pageY) >= 5)) {\n const orientationSettings = that._orientationSettings,\n difference = that._dragStartDetails[orientationSettings.coordinate] - event[orientationSettings.coordinate],\n oldScrollDirection = that.$.tabStrip[orientationSettings.scrollDirection];\n\n that.$.tabStrip[orientationSettings.scrollDirection] += difference;\n\n if (oldScrollDirection !== that.$.tabStrip[orientationSettings.scrollDirection]) {\n that._updateScrollButtonVisibility();\n }\n\n that._dragStartDetails = {\n startX: that._dragStartDetails.startX,\n startY: that._dragStartDetails.startY,\n pageX: event.pageX,\n pageY: event.pageY,\n startTime: that._dragStartDetails.startTime,\n originalTime: that._dragStartDetails.originalTime,\n target: event.originalEvent.target,\n checked: that._dragStartDetails.checked\n };\n that._swiping = true;\n\n return;\n }\n\n if (!that.resize || that._resizing || that._reordering || that.tabLayout === 'shrink') {\n return;\n }\n\n const orientationSettings = that._orientationSettings,\n currentCoordinate = event[orientationSettings.coordinate],\n tabCoordinates = that._tabCoordinates;\n let tabToResize;\n\n for (let i = 0; i < tabCoordinates.length; i++) {\n const currentTabCoordinate = tabCoordinates[i][orientationSettings.to];\n\n if (currentCoordinate >= currentTabCoordinate - 4 && currentCoordinate <= currentTabCoordinate + 4) {\n tabToResize = that._reorderItems[i];\n that._resizeFrom = currentCoordinate;\n break;\n }\n }\n\n if (tabToResize !== undefined) {\n that._tabToResize = tabToResize;\n that.setAttribute('resizing', '');\n }\n else {\n that._tabToResize = undefined;\n that.removeAttribute('resizing');\n }\n }",
"_containerTabStripResizeHandler(event) {\n const that = this,\n splitter = event.target.closest('smart-splitter');\n\n if (splitter === that.$.horizontalHiddenItemsContainer || splitter === that.$.verticalHiddenItemsContainer) {\n splitter._resizeEventHandler();\n that._setAutoHidePaddings();\n }\n }",
"function rerenderTabstrip () {\n empty(tabContainer)\n for (var i = 0; i < tabs.length; i++) {\n tabContainer.appendChild(createTabElement(tabs[i]))\n }\n}",
"_labelSizeChangeHandler(event) {\n const that = this,\n newSize = event.detail.size;\n let correspondingLabelContainer;\n\n if (that.tabLayout === 'shrink') {\n return;\n }\n\n if (event.target instanceof Smart.TabItem) {\n correspondingLabelContainer = event.target.tabLabelContainer;\n }\n else {\n correspondingLabelContainer = that._groupLabels[that._groups.indexOf(event.target.label)];\n }\n\n if (newSize !== null) {\n correspondingLabelContainer.style[that._orientationSettings.dimension] = parseInt(newSize, 10) + 'px';\n }\n else {\n correspondingLabelContainer.style.removeProperty(that._orientationSettings.dimension);\n }\n\n that._applyTabOverflow();\n }",
"function _jsTabControl_draw() {\n\n\t//create string holder\n\tvar d = new jsDocument;\n\t\n\t//calculate tabsperstrip\n\tthis.tabsPerStrip = parseInt((document.body.clientWidth - IMG_BTN_MORE.width - IMG_BTN_LESS.width) / this.tabWidth);\n\n\t//calculate number of strips needed\n\tvar numStrips = Math.ceil(this.tabs.length / this.tabsPerStrip);\n\n\t//draw each strip\n\tfor (i=0; i < numStrips; i++)\n\t\tthis.createStrip(d, 0 + (this.tabsPerStrip * i), this.tabsPerStrip + (this.tabsPerStrip * i));\n\n\t//draw to the frame\n\tdocument.body.insertAdjacentHTML(\"afterBegin\", d);\n}",
"function resizeIndicators(){\n\t\tfor(i = 0; tabs.length > i; i++){\n\t\t\tvar tab = tabs.item(i),\n\t\t\t\ttabSelect = tab.querySelector(\".n-tab-select-item\"),\n\t\t\t\ttabIndicator = tab.querySelector(\".n-tabs-indicator\");\n\n\t\t\tif(tabIndicator){\n\t\t\t\tvar translateX = getTranslateX(tabIndicator),\n\t\t\t\t\toffset = (translateX - tabSelect.clientWidth) * -1;\n\n\t\t\t\t// Give the indicator the new size\n\t\t\t\ttabIndicator.style.width = tabSelect.clientWidth + \"px\";\n\n\t\t\t\t// Reposition the indicator offset whenever it's offset is not in the first tab\n\t\t\t\tif(translateX != 0){\n\t\t\t\t\ttabIndicator.style.transform = `translateX(${tabSelect.clientWidth + offset}px)`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"_labelSizeChangeHandler(event) {\n const that = this,\n newSize = event.detail.size;\n let correspondingLabelContainer;\n\n if (that.tabLayout === 'shrink') {\n return;\n }\n\n if (event.target instanceof JQX.TabItem) {\n correspondingLabelContainer = event.target.tabLabelContainer;\n }\n else {\n correspondingLabelContainer = that._groupLabels[that._groups.indexOf(event.target.label)];\n }\n\n if (newSize !== null) {\n correspondingLabelContainer.style[that._orientationSettings.dimension] = parseInt(newSize, 10) + 'px';\n }\n else {\n correspondingLabelContainer.style.removeProperty(that._orientationSettings.dimension);\n }\n\n that._applyTabOverflow();\n }",
"function setTabWidth(){\r\nvar totalTabs = $('.ms-widget ul.x620').children().length;\r\nif(totalTabs >= 6){\r\n var tabWidth = Number((100/totalTabs).toString().match(/^\\d+(?:\\.\\d{0,2})?/));\r\n $('.ms-widget ul.x620 li').css('width',tabWidth+'%');\r\n $('.ms-widget ul.x620 li .selBg').css('width',tabWidth+'%');\r\n $('.ms-widget ul.x620 li .tabHead').css('width',tabWidth+'%'); \r\n}\r\n \r\n}",
"_removeInlineStyle() {\n const that = this,\n tabStrip = that.$.tabStrip;\n\n if (that._inlineStyleTabStripChildren) {\n const tabStripChildren = tabStrip.children;\n\n for (let i = 0; i < tabStripChildren.length; i++) {\n tabStripChildren[i].removeAttribute('style');\n tabStripChildren[i].firstElementChild.firstElementChild.classList.remove('smart-tab-label-text-container-full-height');\n }\n\n delete that._inlineStyleTabStripChildren;\n }\n\n if (that._inlineStyleTabStrip) {\n tabStrip.removeAttribute('style');\n delete that._inlineStyleTabStrip;\n }\n\n tabStrip.$.removeClass('shrink-tabs');\n tabStrip.$.removeClass('shrink-tabs-vertical');\n }",
"updateTabTitleStyle() {\n const tabTitles = this._tabTitlesEl.childNodes\n for (let i = 0; i < tabTitles.length; i++) {\n this._tabTitlesEl.childNodes.item(i).style.width = `${\n 100 / this._tabs.length}%`\n }\n }",
"function rerenderTabstrip() {\n say.c('rerenderTabstrip()', 'yellow')\n\n let selectedEl = document.querySelector('.selected')\n let selectedElId = ''\n let selectedElVal = ''\n if (selectedEl != null) {\n selectedElVal = selectedEl.querySelector('input').value\n selectedElId = selectedEl.getAttribute('data-tab')\n }\n\n empty(tabGroup)\n for (var i = 0; i < tabs.length; i++) {\n tabGroup.appendChild(createTabElement(tabs[i]))\n if (tabs[i].selected) {\n document.querySelectorAll('.tab-item')[i].classList.add('active')\n } else {\n document.querySelectorAll('.tab-item')[i].classList.remove('active')\n }\n if (selectedElId != '' && tabs[i].id == selectedElId) {\n document.querySelectorAll('.tab-item')[i].classList.add('selected')\n document.querySelectorAll('.tab-item')[i].querySelector('input').value = selectedElVal\n document.querySelectorAll('.tab-item')[i].querySelector('input').focus()\n } else {\n document.querySelectorAll('.tab-item')[i].classList.remove('selected')\n }\n }\n tabCount()\n}",
"_containerTabStripResizeHandler(event) {\n const that = this,\n splitter = event.target.closest('jqx-splitter');\n\n if (splitter === that.$.horizontalHiddenItemsContainer || splitter === that.$.verticalHiddenItemsContainer) {\n splitter._resizeEventHandler();\n that._setAutoHidePaddings();\n }\n }",
"getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden');\n\n // Append to parent so we get the \"real\" size\n tab.parentNode.appendChild(clone);\n\n // Get the sizes before we remove\n const width = clone.scrollWidth;\n const height = clone.scrollHeight;\n\n // Remove from the DOM\n removeElement(clone);\n return {\n width,\n height\n };\n }",
"_removeInlineStyle() {\n const that = this,\n tabStrip = that.$.tabStrip;\n\n if (that._inlineStyleTabStripChildren) {\n const tabStripChildren = tabStrip.children;\n\n for (let i = 0; i < tabStripChildren.length; i++) {\n tabStripChildren[i].removeAttribute('style');\n tabStripChildren[i].firstElementChild.firstElementChild.classList.remove('jqx-tab-label-text-container-full-height');\n }\n\n delete that._inlineStyleTabStripChildren;\n }\n\n if (that._inlineStyleTabStrip) {\n tabStrip.removeAttribute('style');\n delete that._inlineStyleTabStrip;\n }\n\n tabStrip.$.removeClass('shrink-tabs');\n tabStrip.$.removeClass('shrink-tabs-vertical');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getMode Returns the current editor's mode. | getMode() {
return this.mode;
} | [
"function mode() {\n var value = (attr.mdMode || \"\").trim();\n if ( value ) {\n switch(value) {\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n case MODE_BUFFER:\n case MODE_QUERY:\n break;\n default:\n value = undefined;\n break;\n }\n }\n return value;\n }",
"function mode() {\n var value = (attr.mdMode || \"\").trim();\n if (value) {\n switch (value) {\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n case MODE_BUFFER:\n case MODE_QUERY:\n break;\n default:\n value = MODE_INDETERMINATE;\n break;\n }\n }\n return value;\n }",
"get mode() {\n return this._.windowmode\n }",
"function mode() {\n var value = (attr.mdMode || \"\").trim();\n if ( value ) {\n switch(value) {\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n case MODE_BUFFER:\n case MODE_QUERY:\n break;\n default:\n value = MODE_INDETERMINATE;\n break;\n }\n }\n return value;\n }",
"function getDocumentMode() {\n var documentMode = editor.getDoc().documentMode;\n\n return documentMode ? documentMode : 6;\n }",
"function getMode(){\n\tvar mvp = presenter.getCurrentMVP();\n\treturn mvp.getMode();\n}",
"get _mode() {\n return this.currentMode;\n }",
"function getMode()\r\n\t{\r\n\t\treturn metaData.mode;\r\n\t}",
"get mode() { return this._mode; }",
"function getMode(){\n return mode;\n}",
"get mode() {\n return this.getAttribute('mode');\n }",
"function getDocumentMode() {\n\t\t\tvar documentMode = editor.getDoc().documentMode;\n\n\t\t\treturn documentMode ? documentMode : 6;\n\t\t}",
"function getMode(){\n\t...\n}",
"async getMode() {\n const modeAttr = (await this.host()).getAttribute('mode');\n return (await modeAttr);\n }",
"function editorMode(view) {\n var mode = \"xml\";\n\n if (extname(view.name) === \".js\") mode = \"javascript\";\n\n if (extname(view.name) === \".css\") mode = \"css\";\n\n if (extname(view.name) === \".txt\") mode = \"text\";\n\n return mode;\n}",
"getMode () {\n return this.state.mode;\n }",
"switchEditorMode(mode) {\n this.target.mode = mode;\n this.init();\n }",
"function _getCurrentFullEditor() {\n\n return EditorManger.getCurrentFullEditor();\n }",
"function getCurrentMode() {\n var src_iframe = $(\"iframe\").attr(\"src\");\n var mode = src_iframe.substring(37, 43);\n if (mode.substring(0,5) === 'place') {\n mode = 'place'\n }\n if (mode.substring(0,5) === 'searc') {\n mode = 'search'\n }\n return mode;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks Function to check if the active shape is at the bottom | checkBottom(y) {
return !(
y + this.activeshape[this.rotation][0].y >= this.canvasheight / this.blockSize ||
y + this.activeshape[this.rotation][1].y >= this.canvasheight / this.blockSize ||
y + this.activeshape[this.rotation][2].y >= this.canvasheight / this.blockSize ||
y + this.activeshape[this.rotation][3].y >= this.canvasheight / this.blockSize
);
} | [
"isAtViewBottom(){\n let body = document.getElementById(`sheet-${this.sheet.props.id}-body`);\n let bottomRow = body.lastChild;\n let cornerElement = bottomRow.lastChild;\n return this.selectionFrame.corner.y === parseInt(cornerElement.dataset[\"y\"]);\n }",
"function checkBaseline() {\n var isBottom = false;\n for (var i = 0; i < shape.length; i++) {\n if(shape[i].row === 39) {\n isBottom = true;\n return isBottom;\n }\n }\n }",
"function reachedBottom() {\n // If we go a little beyond the bottom\n if (this.y > this.height + this.r * 4) {\n return true;\n } else {\n return false;\n }\n }",
"isAtDataBottom(){\n return this.selectionFrame.corner.y === this.sheet.dataFrame.corner.y;\n }",
"function withinTopBottom(y) {\n\n // if y coordinate is smaller than canvas height minus radius of the circle\n // or y coordinate is larger than radius of the circle \n // then shape is within the height of the canvas, function returns true \n // otherwise function returns false\n if (y <= CANVAS_HEIGHT - 1 / 2 * circleSize && y >= 1 / 2 * circleSize) {\n return true;\n } else {\n return false;\n }\n\n}",
"isBottom(el, offset) {\n return el.getBoundingClientRect().bottom <= window.innerHeight + offset;\n }",
"isCloseToBottom({ layoutMeasurement, contentOffset, contentSize }) {\n return layoutMeasurement.height + contentOffset.y >= contentSize.height - 50;\n }",
"function checkBottomCollision() {\n var isBottomCollided = false;\n for (var i = shape.length-1; i >= 0; i--) {\n if(gameGrid[(shape[i].row) + 1][shape[i].col] === 1) {\n gameGrid[shape[i].row] = gameGrid[shape[i].row]\n isBottomCollided = true;\n return isBottomCollided;\n }\n }\n }",
"checkBottomEdge() {\n if (this.position > (p5.height - this.radius)) {\n // A little dampening when hitting the bottom\n this.velocity *= -0.9;\n this.position = (p5.height - this.radius);\n }\n }",
"isOpenBottom() {\r\n return openBottom\r\n }",
"outOfBounds() {\n const aboveTop = this.y < 0;\n const belowBottom = this.y + CONSTANTS.CAPY_HEIGHT > this.dimensions.height;\n return aboveTop || belowBottom;\n }",
"function checkBottom(){\n //initiallise 0\n total = 0\n //loop through each element in the bottom row of the array\n for (var i = 0; i < current.shape.length; i++) {\n //if there is anything then increase total to not equal 0\n total += current.shape[current.shape.length - 1][i]\n }\n //id nothing in bottom row return value 1\n if (total == 0){\n return 1\n }\n //otherwise return value 0, meaning bottom row is full\n else{\n return 0\n }\n\n}",
"function isBottom(){\n\t\tvar domLast = $(\".img-box\").last().get(0)\n\t\tvar lastHeight = domLast.offsetTop + Math.floor(domLast.offsetHeight/2)\n\t\tconsole.log(window.scrollY, window.innerHeight , lastHeight)\n\t\tif (window.scrollY +window.innerHeight > lastHeight){\n\t\t\treturn true\n\t\t} else{\n\t\t\treturn false\n\t\t}\n\t}",
"collisionBottom() {\n if (this.posY - this.canvasWidth * 0.05 >= this.canvasHeight) {\n return true;\n }\n }",
"cursorBelowView(){\n let body = document.getElementById(`sheet-${this.sheet.props.id}-body`);\n let bottomRow = body.lastChild;\n let cornerElement = bottomRow.lastChild;\n let y = this.selectionFrame.cursor.y;\n return y > parseInt(cornerElement.dataset[\"y\"]);\n \t}",
"function reachedTheBottom(bottomSquares) {\n var reachedTheBottom = false;\n for(var i = 0; i < bottomSquares.length; i++) {\n if (bottomSquares[i].y_coord == 14) {\n return true;\n }\n }\n return reachedTheBottom;\n}",
"function IsInBottomBorderRow(tree) {\n\n return +tree.getAttribute(\"data-y\") === TREE_COUNT_Y - 1;\n\n}",
"function isTopToBottom() {\n return scope.orientation == 'TB';\n }",
"isNearBottom() {\n return window.innerHeight + window.scrollY >= document.body.offsetHeight - 300;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a command has been restricted in that guild | function isRestrictedCommand(str_command, guild){
const specs = utils.getSpecifics(guild);
if (specs.restricted.indexOf(str_command) > -1){
return true;
}
return false;
} | [
"function restrictCommand(author, str_command, guild){\r\n\tlet specs = utils.getSpecifics(guild);\r\n\tif (!isRestrictedCommand(str_command, guild)){\r\n\t\tspecs.restricted.push(str_command);\r\n\t}\r\n\tutils.writeSpecifics(guild, specs);\r\n\treturn sendRestrictions(author, guild);\r\n}",
"function canControlGuilds(guilds) {\n return guilds.filter(g => {\n gp = new Discord.Permissions(null, g.permissions);\n return gp.has(\"MANAGE_GUILD\");\n });\n}",
"get guildOnly() { return this.guilds.length > 0 ? true : false; }",
"function hasPermissions(id, guild){\n return guild.owner.id === id;\n}",
"function canManageGuild(member) {\n return member.permissions.hasPermission('MANAGE_GUILD');\n}",
"async function isLenoxBotAndUserOn(req) {\n const islenoxbotNonPerm = [];\n if (req.user) {\n for (let i = 0; i < req.user.guilds.length; i += 1) {\n let result;\n await shardingManager.broadcastEval(`this.guilds.get('${req.user.guilds[i].id}')`).then((guildArray) => {\n result = guildArray.find((g) => g);\n });\n\n if (result && typeof result !== 'undefined') {\n req.user.guilds[i].lenoxbot = true;\n }\n else {\n req.user.guilds[i].lenoxbot = false;\n }\n\n if (req.user.guilds[i].lenoxbot === true) {\n islenoxbotNonPerm.push(req.user.guilds[i]);\n }\n }\n }\n return islenoxbotNonPerm;\n }",
"checkCommandAccess(command){\n let target = command.target;\n if (!target)\n return ;\n \n function check(condition, msg){\n if (!condition) {\n // TODO: add messages i18n\n throw new Error(msg || 'Access denied.');\n }\n }\n function containedIn(list, value){\n let result = false;\n for (let i = 0, len = list ? list.length : 0; !result && i < len; i++) {\n result = (list[i] == value);\n }\n return result;\n }\n let allow = false;\n let deny = false;\n \n let roles = target['.roles'] || {};\n let access = target['.access'] || {};\n let role = this.getRole(roles[this.userId]);\n\n let commandKeys = command.hierarchy;\n while (!allow && !deny && commandKeys.length){\n let commandKey = commandKeys.pop();\n\n let roleKeys = role.hierarchy;\n while (!allow && !deny && roleKeys.length){\n let roleKey = roleKeys.pop();\n\n let accessRules = access[roleKey];\n if (!accessRules)\n continue;\n allow = containedIn(accessRules.allow, commandKey);\n deny = containedIn(accessRules.deny, commandKey);\n }\n }\n\n // TODO: add messages i18n\n check(!deny, '[' + command.key + ']' + \n ' Access denied for the user \"' + this.userId + '\".');\n\n // TODO: add messages i18n\n check(!!allow, '[' + command.key + ']' + \n ' Access rules are not defined for the user \"' + this.userId + '\".');\n }",
"hasPermission(message) {\n if (message.channel.type === 'dm') {\n return true\n } else {\n return\n }\n }",
"function hasCommandPermission(command, message) {\n\t\tvar com_level = getCommandLevel(command, message);\n\n\t\treturn hasLevel(com_level, message);\n\t}",
"function isGuildInteraction(interaction) {\n return Reflect.has(interaction, 'guild_id');\n}",
"isAllowedToRun(commandName, runnersRoles, runnersGuild){\n // Decide if we need to check permissions or not based on config\n if(Settings.getSetting('restrict_commands')===false){\n return true;\n }\n if(runnersGuild && runnersRoles){\n // Find at least one role we have that is allowed to run\n let permissiveRole = this.getAllowedRoles(runnersGuild.id, commandName).some((role) => {\n return runnersRoles.has(role);\n });\n // If we found a role return true, false otherwise\n return permissiveRole ? true:false;\n }\n return false;\n }",
"function CheckPermission(msg){\r\n return !notAllowedToBrazil.includes(msg.author.id.toString()) && (msg.member.hasPermission(\"ADMINISTRATOR\") || specialAdmin.includes(msg.author.id.toString()) || msg.member.roles.cache.some(role => role.name.toLowerCase() === permissionRole[msg.guild]) || permissionRole[msg.guild] === \"\")\r\n}",
"function checkPermissions(who, command){\n\t// If who is undefined, meaning they aren't registered or authenticated with NickServ, we give them the lowest permission level.\n\tvar p = who != undefined && global.permissions[who.toLowerCase()] != undefined ? global.permissions[who.toLowerCase()] : 0;\n\tfor (var i = 0; i <= p; i++){\n\t\tif (global.commandPerms[i].indexOf(command) > -1) return true;\n\t}\n\treturn false;\n}",
"check({client, context}, serverStrictness = false) {\n\t\tif (this.isInherited) {\n\t\t\tif (this.binding.supercommand) {\n\t\t\t\treturn this.inherited.check({client, context});\n\t\t\t} else {\n\t\t\t\tthrow 'Permissions cannot be inherited from nothing.';\n\t\t\t} \n\t\t}\n\t\tif (this.isPublic || context.isDM || context.userID == client.ownerID) {\n\t\t\treturn Grant.granted();\n\t\t}\n\t\tif (this.isPrivate) {\n\t\t\treturn Grant.denied(Constants.STRINGS.PRIVATE);\n\t\t}\n\t\tif (this.isPrivileged) {\n\t\t\tif (context.server && context.member) {\n\t\t\t\tif (Permissions.memberHasPrivilege(context.server, context.member)) {\n\t\t\t\t\treturn Grant.granted();\n\t\t\t\t} else {\n\t\t\t\t\treturn Grant.denied(`${md.mention(context.user)} does not have ${Constants.PRIVILEGED_PERMISSION}.`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn Grant.denied(`This command may only be used in a server by users with ${Constants.PRIVILEGED_PERMISSION}.`);\n\t\t\t}\n\t\t}\n\t\tif (this.isDmOnly) {\n\t\t\treturn Grant.denied(Constants.STRINGS.DM_ONLY);\n\t\t}\n\t\tif (!(context.server.id in this.servers)) {\n\t\t\tif (serverStrictness) {\n\t\t\t\treturn Grant.denied(`Server is not permissed.`);\n\t\t\t} else {\n\t\t\t\treturn Grant.granted();\n\t\t\t}\n\t\t}\n\t\t\n\t\t// get permissions for the server\n\t\tvar sp = this.servers[context.server.id];\n\t\t\n\t\t// check users\n\t\tif (context.user && sp.users.length > 0) {\n\t\t\tvar hasUser = sp.users.includes(context.user.id);\n\t\t\tif (this.isExclusive && hasUser) {\n\t\t\t\treturn Grant.denied(`${md.mention(context.user)} is blacklisted from using that command.`);\n\t\t\t} else if (this.isInclusive && !hasUser) {\n\t\t\t\treturn Grant.denied(`${md.mention(context.user)} is not whitelisted to use that command.`);\n\t\t\t}\n\t\t}\n\t\t// check roles\n\t\tif (context.roles && sp.roles.length > 0) {\n\t\t\tvar hasRole = sp.roles.some(r => context.member.roles.some(role => role.id == r));\n\t\t\tif (this.isExclusive && hasRole) {\n\t\t\t\treturn Grant.denied(`One or more of ${md.mention(context.user)}'s roles is blacklisted: ${sp.getRoleNames(context.server)}`);\n\t\t\t} else if (this.isInclusive && !hasRole) {\n\t\t\t\treturn Grant.denied(`None of ${md.mention(context.user)}'s roles are whitelisted: ${sp.getRoleNames(context.server)}`);\n\t\t\t}\n\t\t}\n\t\t// check channels\n\t\tif (context.channel && sp.channels.length > 0) {\n\t\t\tvar hasChannel = sp.channels.includes(context.channel.id);\n\t\t\tif (this.isExclusive && hasChannel) {\n\t\t\t\treturn Grant.denied(`This channel is blacklisted: ${sp.channelsAsMarkdown}`);\n\t\t\t} else if (this.isInclusive && !hasChannel) {\n\t\t\t\treturn Grant.denied(`This channel is not whitelisted: ${sp.channelsAsMarkdown}`);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// granted full permission to use the command\n\t\treturn Grant.granted();\n\t}",
"function isnotroleperm() {\nif(!message.member.roles.some(r=>[botrole].includes(r.name)) ) {\n\n\tconst plaintext = \"<:warn_3:498277726604754946> Sorry, you don't have permissions to use this!\"\nconst embed = new RichEmbed() \n//.setTitle('Title') \n.setColor(0xCC0000) \n.setDescription('only user of role ' + botrole + ' may use this command')\n//.setAuthor(\"Header\")\n.setFooter(\"@\" + msgauthor)\n//.addField(\"Field\");\nmessage.channel.send(plaintext, embed);\n\nreturn true\n}\nelse\nreturn false;\n}",
"function checkCommandRights( tags, rights ) {\n\n\n\tif ( rights === \"0\" && tags.badges !== null ) {\n\n\t\tif ( tags.badges.broadcaster === \"1\" ) { // Streamer only\n\n\t\t\treturn true;\n\t\t}\n\n\t} else if ( rights === \"1\" && tags.badges !== null ) {\n\n\t\tif ( tags.badges.broadcaster === \"1\" || tags.badges.moderator === \"1\" ) { // Streamer or Moderator\n\n\t\t\treturn true;\n\n\t\t}\n\n\t} else if ( rights === \"2\" && tags.badges !== null ) {\n\n\t\tif ( tags.badges.broadcaster === \"1\" || tags.badges.moderator === \"1\" || tags.badges.vip === \"1\" ) { // Streamer or Moderator or VIP\n\n\t\t\treturn true;\n\n\t\t}\n\n\t} else if ( rights === \"3\" ) { // Everyone\n\n\t\treturn true;\n\t}\n\n\treturn false; // Noone (should not happen)\n}",
"function CheckServerOnlyCmd( )\r\n{\r\n EnterFunction( arguments );\r\n\r\n if( g_oVariables.fServerOnly == true )\r\n {\r\n return false;\r\n }\r\n g_oVariables.fServerOnly = true;\r\n return true;\r\n}",
"function userIsMember(guildId, user) {\r\n var credentials = user.uRole,\r\n where = credentials.indexOf(guildId);\r\n console.log(\"MEMBER? \"+guildId+\" \"+credentials);\r\n return (where > -1);\r\n }",
"function isGuildMember(m){\n var ret = false\n config.memberRoles.forEach((memberRole) => {\n if (m.roles.has(memberRole)){\n ret = true\n }\n })\n return ret\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method :: setServiceSteps Desc :: Sets components steps for stepzila to create and update service data | setServiceSteps() {
const steps = [
{
name: 'Create',
component: <MlServiceCardStep1 data={this.state.data} />,
icon: <span className="ml my-ml-add_tasks"></span>
},
{
name: 'Select Tasks',
component: <MlServiceCardStep2 data={this.state.data}
optionsBySelectService={this.optionsBySelectService}
profileId={this.props.profileId}
serviceId={this.props.serviceId} />,
icon: <span className="ml fa fa-users"></span>
},
{
name: 'Terms & Conditions',
component: <MlServiceCardStep3 data={this.state.data} />,
icon: <span className="ml ml-payments"></span>
},
{
name: 'Payment',
component: <MlServiceCardStep4 data={this.state.data}
checkChargeStatus={this.checkChargeStatus}
calculateCharges={this.calculateCharges}
saveServicePaymentDetails={this.saveServicePaymentDetails} />,
icon: <span className="ml ml-payments"></span>
}
];
return steps;
} | [
"setServiceSteps() {\n let canStatusChange = (this.state.serviceBasicInfo.isLive || this.state.serviceBasicInfo.isApproved ) && FlowRouter.getQueryParam(\"id\") ;\n const {\n serviceBasicInfo,\n daysRemaining,\n clusterCode,\n clusters,\n clusterName,\n serviceTermAndCondition,\n attachments,\n servicePayment,\n facilitationCharge,\n taxStatus,\n serviceTask,\n finalAmount,\n prevFinalAmount\n } = this.state;\n let steps = [\n {\n name: !this.props.viewMode ? 'Create' : 'View',\n component: <MlAppServiceBasicInfo data={serviceBasicInfo}\n clusterCode={clusterCode}\n clusterName={clusterName}\n clusters={clusters}\n activateComponent={this.activateComponent}\n getRedirectServiceList={this.getRedirectServiceList}\n clusterData={this.state.clusterData}\n daysRemaining={daysRemaining}\n optionsBySelectstates={this.optionsBySelectstates}\n optionsBySelectChapters={this.optionsBySelectChapters}\n optionsBySelectCommunities={this.optionsBySelectCommunities}\n getServiceDetails={this.getServiceDetails}\n options={this.options}\n checkBoxHandler={this.checkBoxHandler}\n validTill={this.validTill}\n viewMode={this.props.viewMode || (this.state.serviceBasicInfo && (this.state.serviceBasicInfo.isLive || this.state.serviceBasicInfo.isApproved || this.state.serviceBasicInfo.isReview ))}\n canStatusChange={ canStatusChange }\n setSessionFrequency={this.setSessionFrequency}\n onChangeFormField={this.onChangeFormField}\n setServiceExpiry={this.setServiceExpiry} />,\n\n icon: <span className=\"ml my-ml-add_tasks\"></span>\n },\n {\n name: !this.props.viewMode ? 'Select Tasks' : 'Tasks',\n component: <MlAppServiceSelectTask serviceTask={serviceTask}\n profileId={this.profileId}\n serviceId={this.serviceId}\n activateComponent={this.activateComponent}\n getRedirectServiceList={this.getRedirectServiceList}\n deleteSelectedTask={this.deleteSelectedTask}\n getServiceDetails={this.getServiceDetails}\n viewMode={this.props.viewMode || (this.state.serviceBasicInfo && (this.state.serviceBasicInfo.isLive || this.state.serviceBasicInfo.isApproved || this.state.serviceBasicInfo.isReview ))}\n saveService={this.saveService}\n selectedTaskId={serviceTask.selectedTaskId}\n optionsBySelectService={this.optionsBySelectService}\n updateSessionSequence={this.updateSessionSequence}\n />,\n icon: <span className=\"ml fa fa-users\"></span>\n },\n {\n name: 'Terms & Conditions',\n component: <MlAppServiceTermsAndConditions serviceTermAndCondition={serviceTermAndCondition}\n attachments={attachments}\n viewMode={this.props.viewMode || (this.state.serviceBasicInfo && (this.state.serviceBasicInfo.isLive || this.state.serviceBasicInfo.isApproved || this.state.serviceBasicInfo.isReview ))}\n activateComponent={this.activateComponent}\n getRedirectServiceList={this.getRedirectServiceList}\n onChangeCheckBox={this.onChangeCheckBox}\n onChangeValue={this.onChangeValue}\n getServiceDetails={this.getServiceDetails} />,\n icon: <span className=\"ml ml-payments\"></span>\n },\n {\n name: 'Payment',\n component: <MlAppServicePayment servicePayment={servicePayment}\n taxStatus={taxStatus} currencySymbol={this.state.currencySymbol}\n finalAmount={finalAmount} currencyType={this.currencyType.bind(this)}\n prevFinalAmount={prevFinalAmount} client={appClient}\n viewMode={this.props.viewMode || (this.state.serviceBasicInfo && (this.state.serviceBasicInfo.isLive || this.state.serviceBasicInfo.isReview ))}\n activateComponent={this.activateComponent}\n getRedirectServiceList={this.getRedirectServiceList}\n getServiceDetails={this.getServiceDetails}\n facilitationCharge={facilitationCharge}\n checkDiscountEligibility={this.checkDiscountEligibility}\n calculateDiscounts={this.calculateDiscounts}\n checkTaxStatus={this.checkTaxStatus}\n checkPromoStatus={this.checkPromoStatus}\n checkApprovalRequiredFromSeeker={this.checkApprovalRequiredFromSeeker}\n checkDiscountStatus={this.checkDiscountStatus}\n bookService={this.props.bookService}\n canStatusChange={ canStatusChange }\n serviceId={this.props.serviceId} />,\n\n icon: <span className=\"ml ml-payments\"></span>\n },\n\n ];\n return steps;\n }",
"function setupSteps()\n {\n vm.setCurrentStep(vm.currentStepNumber);\n }",
"SET_STEPS (state, steps) {\n state.steps = steps;\n }",
"function updateSteps(){\n StepsSrv.getSteps($scope.experimentId)\n .then(\n function(success){\n vm.steps = orderBy(success.data.steps, 'name', false);\n vm.selectedStep = vm.steps[0];\n },\n function(error){\n vm.error = error.data;\n });\n }",
"addStepsToTestCase(testCaseId, steps) {\n let requestBody = {\n \"mode\": \"OVERWRITE\",\n \"items\": steps\n }\n this._post(`testcases/${testCaseId}/teststeps`, requestBody)\n }",
"drawSteps(steps) {\n this.eraseSteps();\n steps.forEach(navStep => {\n // Create new steps\n this.leafletSteps[navStep.id] = this._createNewStep(navStep);\n // Register event listeners\n this.leafletSteps[navStep.id].map(\n this.stepOnClickListener.bind(this)\n );\n });\n }",
"static registerSteps(steps) {\n buildSteps = steps;\n }",
"function setDataStep1() {\n\n}",
"function setSteps() {\n scope.stepsToShow = scope.steps.filter(function (s) {\n return s.type === 'QUESTION';\n });\n\n setStepStyles();\n }",
"addSteps(steps) {\n let joyride = this.refs.joyride;\n\n if (!Array.isArray(steps)) {\n steps = [steps];\n }\n\n if (!steps.length) {\n return false;\n }\n\n this.setState(function(currentState) {\n currentState.steps = currentState.steps.concat(joyride.parseSteps(steps));\n return currentState;\n });\n }",
"managePresentStep( stepObj ){\n\tthis.debug( '\\nStep object:\\n', stepObj );\n\tconst serviceCode = stepObj.stepArgs.service.code;\n\tswitch ( serviceCode ){\n\tcase 'RESE': // rental services\n\t this.managePresentStepRentals( stepObj );\n\t break;\n\tcase 'SISE': // side services\n\t this.managePresentStepSides( stepObj );\n\t break;\n\tcase 'MASE': // maintenance services\n\t this.managePresentStepMaintenance( stepObj );\n\t break;\n\t}\n }",
"setStep(step) {\n this.step = step;\n }",
"function addStep() {\n vm.step.step_number = vm.detail.steps.length + 1;\n vm.detail.total_duration += vm.step.duration;\n $('.input-focus').focus();\n dataService.post(`${recipeUrl}steps/`, vm.step)\n .then(function(response) {\n // Update the steps array\n vm.detail.steps.push(response.data);\n\n // Show the Brew It button, hide the Add Steps button\n $(\".brew-it-button\").removeClass(\"hidden\");\n $(\".no-steps\").addClass(\"hidden\");\n });\n\n // Clear the step form data\n vm.step = {};\n }",
"function setDataStep2() {\n\n}",
"SET_SERVICE (state, services) {\n \tif (services.constructor !== Array) {\n\t services = [services]\n\t }\n\n\t\tservices.forEach((service) => {\n\t\t\tlet c = service.config\n\t\t\tstate.services[service.name] = {...c}\n\t\t\tstate.services[service.name].path = c.url + (c.port? ':' + c.port : '') + (c.apiVer? '/' + c.apiVer : '')\n\t\t})\n }",
"function setDataStep3() {\n\n}",
"updateLocalStorage(steps) {\n localStorage.setItem('step-data', steps);\n localStorage.setItem('date', this.getCurrentDateAndTime()[0]);\n }",
"updateStepsCache() {\n let out = execSync(this.getCmdListSteps()).toString();\n this.steps = this.parseSteps(out);\n }",
"get steps () { return this.data.steps }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all items of the DockingLayout that have been undocked | get undockedItems() {
const that = this;
if (!that.isReady) {
return;
}
const tabsWindows = document.getElementsByTagName('jqx-tabs-window');
let undockedWindows = [];
for (let i = 0; i < tabsWindows.length; i++) {
if (!tabsWindows[i].closest('jqx-docking-layout') && tabsWindows[i].layout === that) {
tabsWindows[i].undocked = true;
undockedWindows.push(tabsWindows[i]);
}
}
return undockedWindows;
} | [
"get undockedItems() {\n const that = this;\n\n if (!that.isReady) {\n return;\n }\n\n const tabsWindows = document.getElementsByTagName('smart-tabs-window');\n let undockedWindows = [];\n\n for (let i = 0; i < tabsWindows.length; i++) {\n if ((!tabsWindows[i].closest('smart-docking-layout') && !that._getClosestDockingLayout(tabsWindows[i])) && tabsWindows[i].layout === that) {\n tabsWindows[i].undocked = true;\n undockedWindows.push(tabsWindows[i]);\n }\n }\n\n return undockedWindows;\n }",
"get undockedItems() {\n\t\treturn this.nativeElement ? this.nativeElement.undockedItems : undefined;\n\t}",
"function clearDockItems() {\r\n\t\t\tfor (i = 0; i < dockTitles.length; i++) {\r\n\t\t\t\twindow.fluid.removeDockMenuItem(dockTitles[i]);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdockTitles = [];\r\n\t\t}",
"restoreItems() {\n if (this.outView) {\n this.outView = false;\n this.items = Array.from(this.itemsBackup || []);\n this.itemsBackup = undefined;\n this.renderer.setStyle(this.contentsEl, 'height', undefined);\n this.cdRef.detectChanges();\n }\n }",
"closeAll() {\n // Make a copy of all the widget in the dock panel (using `toArray()`)\n // before removing them because removing them while iterating through them\n // modifies the underlying data of the iterator.\n algorithm_1.toArray(this._dockPanel.widgets()).forEach(widget => widget.close());\n }",
"_correctItemOrder() {\n // Defer until after scrolling and animated transactions are complete\n if (this._isScrolling || this._transaction) {\n return;\n }\n\n for (let key of this._visibleLayoutInfos.keys()) {\n let view = this._visibleViews.get(key);\n\n this._children.delete(view);\n\n this._children.add(view);\n }\n }",
"closeAll() {\n // Make a copy of all the widget in the dock panel (using `toArray()`)\n // before removing them because removing them while iterating through them\n // modifies the underlying data of the iterator.\n toArray(this._dockPanel.widgets()).forEach(widget => widget.close());\n this._downPanel.stackedPanel.widgets.forEach(widget => widget.close());\n }",
"resetItems() {\n // Remove refs to current items.\n this._disposeItems(this.items);\n\n this.isInitialized = false; // Find new items in the DOM.\n\n this.items = this._getItems(); // Set initial styles on the new items.\n\n this._initItems(this.items);\n\n this.once(Shuffle.EventType.LAYOUT, () => {\n // Add transition to each item.\n this.setItemTransitions(this.items);\n this.isInitialized = true;\n }); // Lay out all items.\n\n this.filter(this.lastFilter);\n }",
"getUnusedWidgets(aWindowPalette) {\n return CustomizableUIInternal.getUnusedWidgets(aWindowPalette).map(\n CustomizableUIInternal.wrapWidget,\n CustomizableUIInternal\n );\n }",
"removeAllPanelItems() {\n for (const item of this.items_) {\n item.remove();\n }\n this.items_ = [];\n this.setAriaHidden_();\n this.updateSummaryPanel();\n }",
"_getCurrentViewItems(view) {\n const that = this;\n\n if (!that.grouped) {\n if (view === undefined) {\n return that.$.mainContainer.children;\n }\n else {\n return view.container.firstElementChild.children;\n }\n }\n else {\n if (view === undefined) {\n return that.$.view.querySelectorAll('.jqx-menu-main-container > jqx-menu-item, .jqx-menu-main-container > jqx-menu-items-group');\n }\n else {\n const allChildren = view.container.firstElementChild.children,\n items = [];\n\n for (let i = 0; i < allChildren.length; i++) {\n let currentItem = allChildren[i];\n\n if (currentItem instanceof JQX.MenuItem || currentItem instanceof JQX.MenuItemsGroup) {\n items.push(currentItem);\n }\n }\n\n return items;\n }\n }\n }",
"function unfoldAllItems() {\n if (displayMode != 'expanded') {\n error(\"unfoldAllItems: can only unfold in expanded mode\");\n return;\n }\n \n foreachItem(function($item) {\n unfoldItem({interactive: true, batch: true, animated: false}, $item);\n });\n\n updateContentPaneButtons();\n}",
"_getCurrentViewItems(view) {\n const that = this;\n\n if (!that.grouped) {\n if (view === undefined) {\n return that.$.mainContainer.children;\n }\n else {\n return view.container.firstElementChild.children;\n }\n }\n else {\n if (view === undefined) {\n return that.$.view.querySelectorAll('.smart-menu-main-container > smart-menu-item, .smart-menu-main-container > smart-menu-items-group');\n }\n else {\n const allChildren = view.container.firstElementChild.children,\n items = [];\n\n for (let i = 0; i < allChildren.length; i++) {\n let currentItem = allChildren[i];\n\n if (currentItem instanceof Smart.MenuItem || currentItem instanceof Smart.MenuItemsGroup) {\n items.push(currentItem);\n }\n }\n\n return items;\n }\n }\n }",
"function resetItems() {\n self.leftItem = undefined;\n self.rightItem = undefined;\n self.centerItem = undefined;\n }",
"function resetItems() {\n\n self.leftItem = undefined;\n self.rightItem = undefined;\n self.centerItem = undefined;\n }",
"undo() {\n this._changeItemsVisibility(!this.state)\n }",
"function getItemsDimensionFromDOM() {\n // not(.ng-leave) : we don't want to select elements that have been\n // removed but are still in the DOM\n elements = $document[0].querySelectorAll(\n '.dynamic-layout-item-parent:not(.ng-leave)'\n );\n items = [];\n for (var i = 0; i < elements.length; ++i) {\n // Note: we need to get the children element width because that's\n // where the style is applied\n var rect = elements[i].children[0].getBoundingClientRect();\n var width;\n var height;\n if (rect.width) {\n width = rect.width;\n height = rect.height;\n } else {\n width = rect.right - rect.left;\n height = rect.top - rect.bottom;\n }\n\n items.push({\n height: height +\n parseFloat($window.getComputedStyle(elements[i]).marginTop),\n width: width +\n parseFloat(\n $window.getComputedStyle(elements[i].children[0]).marginLeft\n )\n });\n }\n return items;\n }",
"removeDisabledWidgets() {\n this.layout.set(\n this.layout.get().filter(item => {\n return this.isWidgetEnabled(this.getWidget(item.i))\n })\n )\n }",
"function removeAllOverflowItems() {\n $('.overflow').each(function() {\n $(this).removeClass('overflow').addClass('showing').appendTo('.nav-item-container');\n });\n $('.evo-nav-overflow').addClass('hidden');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if search param contains RFE collection | function isRFE() {
var exists = false;
if ($location.search().kind) {
if ($location.search().kind.indexOf('RFE') > -1) {
exists = true;
}
}
return exists;
} | [
"containsSearchTermMatch (searchTerm) {\n let contains = false\n this.models.forEach((model) => {\n if (model.matchesSearchTerm(searchTerm)) {\n contains = true\n }\n })\n return contains\n }",
"function checkSearch(req) {\n\n\t\tlet searchParam = req.query.s\n\n\t\treturn searchParam != undefined\n\t}",
"isSearching() {\n const entriesType = this.getEntriesType();\n\n return this.props.state.entries[entriesType].isSearching || false;\n }",
"isResearch () {\n // Check catalogItemTypes json-ld vocab to see if itype's collectionTypes includes 'Research':\n let itype = this.objectId('nypl:catalogItemType')\n // Strip namespace from id:\n if (itype) itype = itype.split(':').pop()\n let itypeIsResearch = itype &&\n catalogItemTypeMapping[itype] &&\n catalogItemTypeMapping[itype].collectionType.indexOf('Research') >= 0\n\n return this.isPartner() || itypeIsResearch\n }",
"hasCollections(doc) {\n return (\n doc && doc.contextParameters && doc.contextParameters.collections && doc.contextParameters.collections.length > 0\n );\n }",
"function isRelevantToSearch(entry){\n\tvar query = searchText ? searchText.toLowerCase().trim() : null;\n\tif (!query)\n\t\treturn true;\n\n\t// Note: \"allAuthors\" should be included in order to support alternative name spellings\n\tvar keys = [\"id\", \"title\", \"venue\", \"year\", \"type\", \"url\", \"categories\"];\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tif (String(entry[keys[i]]).toLowerCase().indexOf(query) != -1) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Check the category descriptions as well\n\tfor (var i = 0; i < entry.categories.length; i++){\n\t\tif (categoriesMap[entry.categories[i]].description.toLowerCase().indexOf(query) != -1) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}",
"addableSearch() {\n let self = this;\n let query = self.addableQuery;\n\n if (query.length <= 1) {\n self.addableProductsList = [];\n } else {\n this.serverApi.getSearch(0, query, {}, r => self.addableProductsList = r.data.filter(alreadyAdded) );\n }\n var alreadyAdded = v => {\n for (var i = 0; i < self.pdfCatalogue.products.length; i++) {\n if (self.pdfCatalogue.products[i].id === v.id) return false;\n }\n return true;\n }\n }",
"function IsSearchBySubSection() {\n if (typeof(pg_bSearchBySubSection) !== \"undefined\" &&\n (pg_bSearchBySubSection === 1)) {\n return true;\n }\n return false;\n}",
"isMovie(object) {\n return this.search.movies.result.includes(object);\n }",
"areClientFiltersAvailable() {\n if (!this.props.isMyDataSetPage) {\n return Object.keys(this.state.activeFacets.filters).length > 0;\n }\n\n const localFilters = Object.assign({}, this.state.activeFacets.filters);\n if (Object.keys(localFilters).length > 0 &&\n localFilters.hasOwnProperty('Display type') &&\n localFilters['Display type'] === general.PUBLICATION_TYPE_DATA_COLLECTION) {\n delete localFilters['Display type'];\n\n // return true if there is any other filters in array\n return Object.keys(localFilters).length > 0;\n } else {\n // this shouldnt be reachable - if its a dataset page it should always have at least one filter\n return Object.keys(this.state.activeFacets.filters).length > 0;\n }\n }",
"hasFacet(doc, facet) {\n return doc && doc.facets && doc.facets.indexOf(facet) !== -1;\n }",
"validate() {\n if (\n this.additionalSearchParameters.queryBy.length === 0 &&\n Object.values(this.collectionSpecificSearchParameters).some((c) => (c.queryBy || \"\").length === 0)\n ) {\n throw new Error(\n \"Missing parameter: Either additionalSearchParameters.queryBy needs to be set, or all collectionSpecificSearchParameters need to have .queryBy set\"\n );\n }\n }",
"has_resource(arg_name) { return this.root.hasIn( ['resources', 'by_name', arg_name] ) }",
"isSearchBody(id) {\n return id === \"searchBody\";\n }",
"checkFacet(props) {\n if (props.query) {\n for (let filter of props.query) {\n if (props.data.facet.value == filter.value) {\n return true\n }\n }\n if (props.data.ancestorChecked) {\n return true\n }\n }\n return false\n }",
"checkSearchParam(search) {\n check(search, String);\n }",
"hasSuggestions() {\n return this.filteredAirports && Object.keys(this.filteredAirports).length > 1;\n }",
"hasSearchTerm(post, searchTerm) {\n // Iterate through each key of the post\n for (const key of Object.keys(post)) {\n // Get value contained in key\n var value = post[key];\n // Only compare valid keys\n if (key !== \"time\" &&\n key !== \"timeEdited\" &&\n key !== \"wanted\" &&\n key !== \"userId\") {\n if (String(value).includes(String(searchTerm))) {\n return true;\n }\n }\n }\n return false;\n }",
"hasFilters() {\n return Object.keys(this.filters).length > 0\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HELPER FUNCTIONS function that gets all questions for a given category, difficulty, startdate, and enddate | function getAllQuestions(category, difficulty, startDate, endDate, res) {
category = category.toLowerCase();
let questions = [];
let promises = [];
let categories = categoryCache.getCategories();
for (let i = 0; i < categories.length; i ++) {
let currCategory = categories[i].category.toLowerCase();
if (currCategory.includes(category)) {
promises.push(getQuestionsById(categories[i].categoryId, currCategory, difficulty, startDate, endDate));
}
}
Promise.all(promises)
.then(function(values) {
for (let i = 0; i < values.length; i ++) {
let questionArr = values[i];
for (let j = 0; j < questionArr.length; j ++) {
questions.push(questionArr[j]);
}
}
res.json({
questions: questions,
categories: categories.length
});
});
} | [
"async function getQuestionsById(id, category, difficulty, startDate, endDate) {\n\n return new Promise(resolve => {\n let questions = [];\n let url = \"http://jservice.io/api/category?id=\" + id;\n fetch(url)\n .then(response => response.json())\n .then(data => {\n let clues = data.clues;\n for (let i = 0; i < clues.length; i ++) {\n let answer = clues[i].answer;\n let question = clues[i].question;\n let value = clues[i].value;\n let airDate = new Date(clues[i].airdate);\n startDate.setHours(0, 0, 0);\n endDate.setHours(0, 0, 0);\n airDate.setHours(0, 0, 0);\n if (!(startDate <= airDate && airDate <= endDate)) continue;\n if (difficulty != value && difficulty != \"all\") continue;\n if (question.length == 0 || answer.length == 0) continue;\n questions.push({\n question: question,\n answer: answer,\n category: category,\n difficulty: value,\n airdate: airDate\n });\n }\n resolve(questions);\n });\n });\n}",
"static async getQuestionsOf(category) {\n try {\n const data = await database.select('*', 'questions', `WHERE category = ${category}`);\n return data;\n } catch (e) {\n throw e;\n }\n }",
"async getDBQuestions(numQuestions, category, difficulty) {\n const whereClause = {};\n if (category !== 'All') {\n whereClause.category = category;\n }\n if (difficulty !== 'all') {\n whereClause.difficulty = difficulty;\n }\n const dbQuestions = await Questions.findAll({\n where: whereClause,\n order: [['times_asked', 'ASC']],\n limit: numQuestions,\n });\n let questions = new Array()\n console.info('questionManager: Questions found in database: ' + dbQuestions.length + ' questions' + ' numQuestions: ' + numQuestions);\n if (dbQuestions.length == numQuestions) {\n console.info('questionManager: Found enough questions in database');\n for (let i = 0; i < numQuestions; i++) {\n questions[i] = new Question(this.client, dbQuestions[i], (i + 1), 'internal', dbQuestions[i].url );\n }\n } else {\n console.info('Not enough questions found in database, getting new questions');\n questions = await this.addQuestions(numQuestions, category, difficulty, null);\n this.reportNewQuestionsToDeveloperChannel(questions, category, difficulty);\n }\n return questions;\n }",
"static getAllQuestions(category, file) {\n return this.getData(category, file)\n .then(data => data.questions)\n .catch( err => console.error(err) )\n }",
"questions(dateStart, dateEnd, skip, limit, qtype, memberId, questionId, questionNo) {\n const localVarPath = this.basePath + '/questions';\n let queryParameters = {};\n let headerParams = Object.assign({}, this.defaultHeaders);\n let formParams = {};\n if (dateStart !== undefined) {\n queryParameters['date_start'] = dateStart;\n }\n if (dateEnd !== undefined) {\n queryParameters['date_end'] = dateEnd;\n }\n if (skip !== undefined) {\n queryParameters['skip'] = skip;\n }\n if (limit !== undefined) {\n queryParameters['limit'] = limit;\n }\n if (qtype !== undefined) {\n queryParameters['qtype'] = qtype;\n }\n if (memberId !== undefined) {\n queryParameters['member_id'] = memberId;\n }\n if (questionId !== undefined) {\n queryParameters['question_id'] = questionId;\n }\n if (questionNo !== undefined) {\n queryParameters['question_no'] = questionNo;\n }\n let useFormData = false;\n let requestOptions = {\n method: 'GET',\n qs: queryParameters,\n headers: headerParams,\n uri: localVarPath,\n useQuerystring: this._useQuerystring,\n json: true,\n };\n this.authentications.default.applyToRequest(requestOptions);\n if (Object.keys(formParams).length) {\n if (useFormData) {\n requestOptions.formData = formParams;\n }\n else {\n requestOptions.form = formParams;\n }\n }\n return new Promise((resolve, reject) => {\n request(requestOptions, (error, response, body) => {\n if (error) {\n reject(error);\n }\n else {\n if (response.statusCode >= 200 && response.statusCode <= 299) {\n resolve({ response: response, body: body });\n }\n else {\n reject({ response: response, body: body });\n }\n }\n });\n });\n }",
"function getQuizQuestions() {\n //Build the query url, if there is a selected currentCategory \n var queryURL = \"https://opentdb.com/api.php?amount=\" + numQuestions \n + (currentCategory ? \"&category=\" + currentCategory : '')\n + (currentDifficulty ? \"&difficulty=\" + currentDifficulty : '')\n\n //Actual ajax call\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n //Send the results to the questionArray\n questionArray = response.results;\n //Show the question\n showQuestion();\n })\n }",
"function getQuestionByCategory(request, response) {\n return __awaiter(this, void 0, void 0, function () {\n var categoryName, allQuestion, error_3, error_4;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 5, , 6]);\n categoryName = request.params.category;\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, questionSchema_1.questions.find({ category: new RegExp(categoryName, \"i\") })];\n case 2:\n allQuestion = _a.sent();\n return [2 /*return*/, response.status(200).send({ success: true, allQuestion: allQuestion })];\n case 3:\n error_3 = _a.sent();\n return [2 /*return*/, response.status(404).send({ success: false, message: \"Cannot find the Question\" })];\n case 4: return [3 /*break*/, 6];\n case 5:\n error_4 = _a.sent();\n return [2 /*return*/, response.status(404).send({ success: false, message: \"Something went wrong Please Try again\" })];\n case 6: return [2 /*return*/];\n }\n });\n });\n}",
"function requestQuestions(category) {\n // console.log('getting questions of category ' + category)\n $.ajax({\n method: 'GET',\n url: 'https://opentdb.com/api.php?amount=3&category='+ category,\n success: function(response) {\n // console.log('success in getting questions')\n // console.log(response)\n saveQuestions(response)\n if(questions.length === 12) {\n renderGameBoard()\n }\n },\n error: function (response) {\n console.log('error from api')\n console.log(response)\n }\n })\n }",
"function quizGet(amount, category, difficulty, answerType) {\n fetch(`https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=${answerType}`).then(function(res) {\n return res.json();\n }).then(function(result) {\n return result.results;\n }).then(function(questions) {\n this.setState({ready: true, questions: questions});\n \n return questions;\n });\n}",
"getQuestions(category, num) \n {\n let categories = \"{\" + category.join() + \"}\";\n return new Promise((resolve, reject) => {\n const client = new Client();\n console.log(categories);\n client.connect().then(() => {\n client.query(\"SELECT * FROM quiz WHERE category = ANY(\" + `'${categories}') limit ` + num, (err, rws) => {\n client.end();\n if (err) reject(err);\n resolve(rws);\n });\n });\n });\n\n }",
"async function getQuestions(tag) {\n //Current time in UNIX timestamp for filter\n var toDate = parseInt(new Date().getTime() / 1000, 10)\n\n //One week is 604800 seconds\n var fromDate = toDate - 604800\n\n //Filter to get top (highest voted) questions\n var filterTop = {\n pagesize: 10,\n sort: 'votes',\n order: 'desc',\n fromdate: fromDate,\n todate: toDate,\n tagged: tag,\n site: 'stackoverflow',\n filter: '!2A0j)MOzD3wIaLkC-MkJcgdAVxXrUZAn.(GA3LgB2zdb1.RCIYYIzL'\n }\n\n //Filter to get newest questions\n var filterNew = {\n pagesize: 10,\n sort: 'creation',\n order: 'desc',\n fromdate: fromDate,\n todate: toDate,\n tagged: tag,\n site: 'stackoverflow',\n filter: '!2A0j)MOzD3wIaLkC-MkJcgdAVxXrUZAn.(GA3LgB2zdb1.RCIYYIzL'\n }\n\n //Make 2 requests to stackexchange API with filters\n let newQuestions = await reqQuestions(filterNew)\n let topQuestions = await reqQuestions(filterTop)\n\n //Return questions and quota remaining\n var returnValues = {}\n returnValues.items = [...newQuestions.items, ...topQuestions.items].sort((a,b) => b.creation_date - a.creation_date)\n returnValues.quota = topQuestions.quota_remaining\n\n //Return list in desending order by creation date (newest first)\n return returnValues\n}",
"function filterCategoryQuestion(){\n\tsequence_arr = [];\n\tfor(n=0;n<question_arr.length;n++){\n\t\tsequence_arr.push(n);\n\t}\n\t\n\tif($.editor.enable){\n\t\treturn;\n\t}\n\t\n\t//do nothing if category page is off\n\tif(!categoryPage){\n\t\treturn;\n\t}\n\t\n\t//do nothing if category all is selected\n\tif(categoryAllOption && category_arr[categoryNum] == categoryAllText){\n\t\treturn;\n\t}\n\t\n\t//filter the category\n\tsequence_arr = [];\n\tfor(n=0;n<question_arr.length;n++){\n\t\tif(category_arr[categoryNum] == question_arr[n].category){\n\t\t\tsequence_arr.push(n);\n\t\t}\n\t}\n}",
"function getQuestions() {\n return Question.find({});\n}",
"getQuestionWithAnswers(category, difficulty, language) {\n\n return this.determineQuestion(category, difficulty).then((questionItem) => {\n\n if (this.isNewQuestion(questionItem.id)) {\n\n return this.getTranslatedQuestion(questionItem.id, language).then((translatedQuestion) => {\n\n return this.getTranslatedAnswers(questionItem.id, language).then((translatedAnswers) => {\n\n this.recursionSafetyCounter = 0;\n return Promise.resolve([questionItem, translatedQuestion, translatedAnswers]);\n });\n });\n }\n else if (this.recursionSafetyCounter > 50) {\n throw \"No appropriate questions left.\";\n }\n else {\n this.recursionSafetyCounter++;\n\n // For understanding recursion you first have to understand recursion.\n return Promise.resolve(this.getQuestionWithAnswers(category, difficulty, language));\n }\n }).catch(function (ex) {\n console.log(ex);\n return ex;\n });\n }",
"runQuery(q, begin_date, end_date) {\n const newYorkTimesAPI = \"defcdcfdde634a5d8c8bd2fd522eef32\";\n const formattedQuery = q.trim();\n const formattedBegin = begin_date.trim();\n const formattedEnd = end_date.trim()\n const apiResults = response.data.results;\n\n const queryURL = `https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=${newYorkTimesAPI}&${formmattedQuery}`\n\n console.log('PLEASE WORK QUERY PLEASE!');\n\n return axios.get(\"https://api.nytimes.com/svc/search/v2/articlesearch.json\", {\n params: {\n \"api-key\": newYorkTimesAPI,\n \"q\": formattedQuery,\n \"begin_date\": formattedBegin,\n \"end_date\": formattedEnd\n }\n }).then(function(results) {\n console.log(\"Axiiooooooooooooooooooooooooos\")\n console.log(results);\n return results;\n })\n }",
"function getQuestions() {\n let result = [];\n for ( i = 0; i < data.length; i++) {\n \n result.push(data[i].question);\n }\n return result;\n}",
"function filterQuestions(questions, containerId) {\r\n\tconst category = document.querySelector(`#${containerId} [name='category']`).value;\r\n\tconst description = document.querySelector(`#${containerId} [name='description']`).\r\n\t\tvalue.toLowerCase().trim();\r\n\tconst difficulty = document.querySelector(`#${containerId} [name='difficulty']`).value;\r\n\t//let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])\r\n\treturn questions.filter((question) => {\r\n\t\treturn (!category || question.category == category) &&\r\n\t\t\t(!description || question.description.toLowerCase().indexOf(description) != -1) &&\r\n\t\t\t(!difficulty || question.difficulty == difficulty)\r\n\r\n\t});\r\n}",
"static async getAllCategoriesAndQuestions() {\n categories = [];\n let categoryIds = await Category.getCategoryIds();\n for ( let categoryId of categoryIds ) {\n let fullCategory = await Category.getCategory(categoryId);\n categories.push(fullCategory);\n }\n return categories;\n }",
"function preparequestionCategoriesData () {\t\r\n\tvar tmpData = [];\r\n\tquestionCategoryList = KbygQAFlow.questionCategoryList;\r\n\tquestionCategoryCount = questionCategoryList.length;\r\n\r\n\tfor(index = 0; index < questionCategoryCount; index++){\r\n\t\tvar questionCategoryRow = {\r\n categoryName: questionCategoryList[index].category_name,\r\n sequenceNumber: questionCategoryList[index].sequence_number\r\n\t\t\t};\r\n\t\ttmpData.push(questionCategoryRow);\r\n\t}\r\n\treturn tmpData;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to check conditions of multiple ORs in one if condition Can be used to check even one OR Comparision is strongly typed Eg: if(task.taskType ===STRING_NORMAL || task.taskType === FULL_KIT || task.taskType === MILESTONE ) if(multipleORs(task.taskType,STRING_NORMAL,FULL_KIT,MILESTONE)) | function multipleORs(){
var args =arguments;
if(_.rest(args).indexOf(_.first(args)) !== -1)
return true;
else
return false;
} | [
"function testLogicalOr(val) {\n if (val < 10 || val > 20) {\n //|| = OR\n return \"outside\";\n }\n return \"inside\";\n}",
"function isAcceptedByConditionsJoinType(value, conditions, type) {\n\t\tvar condition;\n\n\t\tif (conditions && conditions.length) {\n\t\t\tfor (var i in conditions) {\n\t\t\t\tcondition = conditions[i];\n\t\t\t\tif (condition) {\n\t\t\t\t\tif ((type == \"or\") == !!value.match(new RegExp(condition))) {\n\t\t\t\t\t\treturn type == \"or\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn type != \"or\";\n\t}",
"function doOr() {\n doDoubleOp(\"OR\");\n}",
"function doOr() {\r\n // probably should get two numbers and do Or\r\n let num1 = $(\"#num1\").val();\r\n let num2 = $(\"#num2\").val();\r\n if (checkInput(\"OR\", num1, num2))\r\n send(\"OR\", num1, num2);\r\n}",
"function or(...args) {\n return args.reduce(orCode);\n }",
"isOr(node) {\n return typeof node === 'string' && /\\s*or\\s*/i.test(node)\n }",
"function testLogicalOr(num) {\n if (num === 20 || num === 25) {\n return \"Yes\";\n }\n return \"No\";\n}",
"function oneOfTwoTrue() {\nlet thing1 = \"\";\nlet thing2 = 'hello';\nif (thing1 && thing2) {\n return \"dont run\"\n}\n else if (thing1 || thing2) {\n return \"run\"\n}\n}",
"function testLogicalOr(val) {\n // Only change code below this line\n\n if (val<10||val>20) {\n return \"Outside\";\n }\n\n\n // Only change code above this line\n return \"Inside\";\n}",
"static oror(...args) {\n return Matcher.many(false, ...args);\n }",
"function handleConditionalRequirements(courses) { \n let result_OR = false\n for(let or = 0; or < courses.length; or++) {\n let result_AND = true\n for(let and = 0; and < courses[or].length; and++) {\n result_AND = result_AND && lookup.get(courses[or][and]).isSelected\n }\n result_OR = result_OR || result_AND \n }\n return result_OR\n }",
"function or(...predicates) {\n return (x) => {\n let result = false;\n for (const predicate of predicates) {\n result = result || checkedPredicate('argument of or', predicate)(x);\n }\n return result;\n };\n }",
"function testLogicalOr(val) {\n \n if (val <10 || val > 20) {\n return \"Outside\";\n }\n return \"Inside\";\n }",
"function or() {\n\t var predicates = Array.prototype.slice.call(arguments, 0);\n\t if (!predicates.length) {\n\t throw new Error('empty list of arguments to or');\n\t }\n\n\t return function orCheck() {\n\t var values = Array.prototype.slice.call(arguments, 0);\n\t return predicates.some(function (predicate) {\n\t try {\n\t return check.fn(predicate) ?\n\t predicate.apply(null, values) : Boolean(predicate);\n\t } catch (err) {\n\t // treat exceptions as false\n\t return false;\n\t }\n\t });\n\t };\n\t }",
"function testLogicalOr(val) {\n if (val > 20 || val <10) {\n return \"Outside\";\n }\n return \"Inside\";\n}",
"function eatLogicalOrExpression() {\n var expr = eatLogicalAndExpression();\n while (peekIdentifierToken('or') || peekTokenOne(_TokenKind.TokenKind.SYMBOLIC_OR)) {\n var token = nextToken(); //consume OR\n var rhExpr = eatLogicalAndExpression();\n checkOperands(token, expr, rhExpr);\n expr = _OpOr.OpOr.create(toPosToken(token), expr, rhExpr);\n }\n return expr;\n }",
"function testLogicalOr(val) {\n if (val <10 || val >20) {\n return \"Outside\";\n }\n return \"Inside\";\n}",
"codeLogicalOperator(recipe) {\n if (recipe.op == \"AND\" && (recipe.samePropertyOp == \"AND\" || recipe.conditions.length < 3)) return \"ALL\"\n if (recipe.op == \"OR\" && (recipe.samePropertyOp == \"OR\" || recipe.conditions.length < 3)) return \"ANY\"\n return \"SOME\"\n }",
"function or () {\n\t var predicates = Array.prototype.slice.call(arguments, 0);\n\t if (!predicates.length) {\n\t throw new Error('empty list of arguments to or')\n\t }\n\n\t return function orCheck () {\n\t var values = Array.prototype.slice.call(arguments, 0);\n\t return predicates.some(function (predicate) {\n\t try {\n\t return low.fn(predicate) ? predicate.apply(null, values) : Boolean(predicate)\n\t } catch (err) {\n\t // treat exceptions as false\n\t return false\n\t }\n\t })\n\t }\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set position y target object to center of window | function __setCenterY(target) {
target.position.y = __getCenterY(target);
return target;
} | [
"set TopCenter(value) {}",
"function setPosition() {\n\tconst bounds = mainTray.getBounds();\n\tconst { x, y } = bounds;\n\tmainWindow.setPosition(x - (mainWidth / 2), y - mainHeight);\n}",
"function centerViewportOn(Crafty, target, time) {\r\n\t\tvar worldTargetCenter = {\r\n\t\t\tx: target.x + target.w / 2,\r\n\t\t\ty: target.y + target.h / 2\r\n\t\t};\r\n\t\tvar screenTargetCenter = {\r\n\t\t\tx: worldTargetCenter.x + Crafty.viewport.x,\r\n\t\t\ty: worldTargetCenter.y + Crafty.viewport.y\r\n\t\t};\r\n\t\tvar screenCenter = {\r\n\t\t\tx: config.viewport.width / 2,\r\n\t\t\ty: config.viewport.height / 2,\r\n\t\t};\r\n\t\tCrafty.viewport.pan('reset');\r\n\t\tCrafty.viewport.pan('x', screenTargetCenter.x - screenCenter.x, time);\r\n\t\tCrafty.viewport.pan('y', screenTargetCenter.y - screenCenter.y, time);\r\n\t}",
"center() {\n this.translationX = this.canvas.width * 0.5\n this.translationY = this.canvas.height * 0.5\n }",
"function updateCenterPosition(obj) {\n obj.centerPosition.x = obj.position.x + obj.size.x / 2;\n obj.centerPosition.y = obj.position.y + obj.size.y / 2;\n}",
"set centerY(value) {\n this.pos.y = value - this.height / 2\n }",
"_updatePosFromCenter() {\n let half = this._size.$multiply(0.5);\n this._topLeft = this._center.$subtract(half);\n this._bottomRight = this._center.$add(half);\n }",
"centerAt(target) {\n\t\tthis.x = target.world.x + Math.round(target.width * 0.5);\n\t\tthis.y = target.world.y + Math.round(target.height * 0.5);\n\n\t\t// substract half the width and height of this sprite from x,y to finish centering it\n\t\tthis.x -= Math.round(this.width / 2);\n\t\tthis.y -= Math.round(this.height / 2);\n\t}",
"setCenter(x, y){\n this.equipment.setPosition([x - this.width() * .5, y - this.height() * .5]);\n }",
"set BottomCenter(value) {}",
"function initializeCenter() {\n setMousePosition(ox, oy);\n setBoardPosition(ox, oy);\n }",
"function moveToViewCenter() {\n if (visible) {\n ctx.translate((width / 2) - x(viewCenter.x), -y(viewCenter.y) + (height / 2));\n }\n }",
"setCenter() {\n this.center = createVector(this.x, this.y);\n }",
"set targetPosition(value) {}",
"function center($window, $obj){\n var top, left;\n var win_height = $window.height();\n var win_width = $window.width();\n var obj_height = $obj.height();\n var obj_width = $obj.width();\n \n //keep obj on screen\n if(win_height > obj_height)\n top = win_height/2 - obj_height/2;\n else\n top = 0;\n if(win_width > obj_width)\n left = win_width/2 - obj_width/2;\n else\n left = 0;\n \n //set to center\n $obj.css('top', top);\n $obj.css('left', left);\n}",
"centerScreen() {\n self.moveCenter(0,0);\n }",
"function moveDownCenter() {\n var x = 40;\n var y = hero.pos.y - 12;\n hero.moveXY(x, y);\n}",
"function moveWindow(){\n\twindoww.x = 60;\n\twindoww.y = 200;\n\n}",
"setPixelCenter() {\n let bodyPos = this.body.getPixelCoordinates();\n let angle = this.body.angle;\n let rotatedCenter = createVector(this.center.x, this.center.y);\n rotatedCenter.rotate(angle);\n let trueCenterPos = p5.Vector.add(bodyPos, rotatedCenter);\n this.pixelCenter = trueCenterPos;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a slug from the category name. Spaces are replaced by "+" to make the URL easier to read and other characters are encoded. | function getCategorySlug(name) {
const encodedName = name;
return encodedName
.split(' ')
.map(encodeURIComponent)
.join('+');
} | [
"function getCategorySlug(name) {\n return name.split(' ').map(encodeURIComponent).join('+');\n } // Returns a name from the category slug.",
"function getCategorySlug(name) {\n return name\n .split(' ')\n .map(encodeURIComponent)\n .join('+');\n }",
"function getCategorySlug(name) {\n const encodedName = decodedCategories[name] || name;\n\n return encodedName\n .split(' ')\n .map(encodeURIComponent)\n .join('+');\n}",
"function getCategoryName(slug) {\n return slug\n .split('+')\n .map(decodeURIComponent)\n .join(' ');\n}",
"function getCategoryName(slug) {\n return slug\n .split('+')\n .map(decodeURIComponent)\n .join(' ');\n }",
"function getCategoryName(slug) {\n const decodedSlug = slug;\n\n return decodedSlug\n .split('+')\n .map(decodeURIComponent)\n .join(' ');\n}",
"function getCategoryName(slug) {\n const decodedSlug = encodedCategories[slug] || slug;\n\n return decodedSlug\n .split('+')\n .map(decodeURIComponent)\n .join(' ');\n}",
"function createSlug(value){\n return value\n .replace(/[^a-z0-9_]+/gi, \"-\")\n .replace(/^-|-$/g, \"\")\n .toLowerCase();\n}",
"__toSlug(categoryId) {\n if (categoryId < 10) {\n return new String(categoryId);\n }\n\n let previous = 0;\n return new String(categoryId)\n .split('')\n .map((s) => parseInt(s))\n .map((i) => {\n previous = previous * 10 + i;\n return previous;\n })\n .join('/');\n }",
"function createSlug(value) {\n return value\n .replace(/[^a-z0-9_]+/gi, \"-\")\n .replace(/^-|-$/g, \"\")\n .toLowerCase();\n}",
"slugify() {\n\t\treturn str.trim().replace(/[^A-Za-z0-9]+/g, \"-\").toLowerCase();\n\t}",
"function urlSlug(title) {\n return title.split(/\\W/).filter( (e) => e != '').join('-').toLowerCase(); \n}",
"function makeSlug(string) {\n return string\n .toLowerCase()\n .replace(/[^\\w ]+/g,'')\n .replace(/ +/g,'-')\n ;\n}",
"function convertToSlug(text){\n\treturn text\n\t\t.toLowerCase()\n\t\t.replace(/ /g,'-')\n\t\t.replace(/[^\\w-]+/g,'');\n}",
"function matter_slug(title) {\n t = title.replace(new RegExp(small_words, \"gi\"), ''); // removes the small_words\n t = t.replace(/[^a-zA-Z0-9\\s]/g,\"\"); // removes anything that is not a number or letter (i think)\n t = t.toLowerCase(); // makes the title all lowercase\n t = t.replace(/\\s\\s+/g, ' '); // replaces multiple spaces with single spaces\n t = t.replace(/[ \\t]+$/g, ''); // removes trailing spaces from title\n var slug = t.replace(/\\s/g,'-'); // converts single spaces into dashes\n return slug;\n }",
"function matter_slug(title) {\n t = title.replace(new RegExp(small_words, \"gi\"), ''); // removes the small_words\n t = t.replace(/[^a-zA-Z0-9\\s]/g,\"\"); // removes anything that is not a number or letter (i think)\n t = t.toLowerCase(); // makes the title all lowercase\n t = t.replace(/\\s\\s+/g, ' '); // replaces multiple spaces with single spaces\n t = t.replace(/[ \\t]+$/g, ''); // removes trailing spaces from title\n var slug = t.replace(/\\s/g,'-'); // converts single spaces into dashes\n return slug;\n }",
"function convertToSlug(text){\n\treturn text\n\t\t.toLowerCase()\n\t\t.replace(/ /g,'-')\n\t\t.replace(/[^\\w-]+/g,'')\n\t\t;\n}",
"function urlSlug(title) {\n\n let toLower = title.toLowerCase();\n let sluggish = toLower.split(/\\W/);\n sluggish = sluggish.filter(ele => ele != \"\");\n sluggish = sluggish.join('-');\n return sluggish;\n\n}",
"slugify() {\n this.slug = slug(this.name);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
objCountry =============== Constructor function for country object Parameters in strName Country name instrValue Cookie value used for storing country instrRegion Region in which the country is a part of instrURL URL of Homepage specific for country/language Return value | function objCountry (strName, strValue, intRegion, strURL)
{
this.name = strName; // Country name
this.value = strValue; // Cookie value used for storing country
this.region = gobjRegionArray[intRegion]; // Region in which the country is a part of
this.language = new Array(); // Language array
this.language[0] = new objLanguage("DEFAULT", "DEFAULT", strURL);
} | [
"function objLanguage (strName, strValue, strURL)\r\n{\r\n\tthis.name = strName\t\t\t// Names of language used in country\r\n\tthis.value = strValue\t\t\t// Cookie value of language used in country\r\n\tthis.url = strURL\t\t\t// URL for language-specific homepage\r\n}",
"function Country(countryName, countryPopulation, countryFinName) {\r\n this.name = countryName;\r\n this.population = countryPopulation;\r\n this.finName = countryFinName; \r\n}",
"function country (region,president, flagColor, independenceDay, district, city){\n \n this.region = region\n this.president = president\n this.flagColor = flagColor\n this.independenceDay = independenceDay\n this.district= district\n this.city = city\n}",
"function country(countryName, population, size, continent, emblem, independence) {\r\n this.countryName = countryName\r\n this.population = population\r\n this.size = size \r\n this.continent = continent\r\n this.emblem = emblem \r\n this.independence = independence\r\n}",
"function Country()\n{\n this.name = new Object(); \n this.regions = new Array();\n this.numOfRegions = new Object();\n}",
"function country(population,currency,colonialMaster,independenceYear,president, continent){ \n //these properties are named using 'this'\n>>>>>>> 9923d8543a7d21169c2eadc0a1a13ac19505854c\n this.population=population\n this.currency=currency\n this.colonialMaster=colonialMaster\n this.independenceYear=independenceYear\n this.president=president\n<<<<<<< HEAD\n this.africa=africa\n}",
"function countryInfo(title, description) {\n this.title = title;\n this.description = description;\n}",
"function createCountry(_country,id){\n\n //create empty country object\n let country = {}\n\n //the following define and place properties that belong to the country object\n country.id = id+\"\" \n country.name = _country['name']['common']\n country.flag = _country['flag']\n //Checks if the the unMember value is \"true/false\" \n //returns a \"Yes\" if true\n country.UnMember = _country['unMember'] ? \"Yes\" : \"No\"\n country.capital = _country['capital']\n country.language = _country['languages']\n country.borders = _country['borders']\n country.currencies = _country['currencies']\n\n //Store (save) the created object into the local cache\n localCountryData.addCountry(country)\n\n}",
"function Country() {\n\t\t\t// Properties omitted from JSON by Angular due to `$$` prefix.\n\t\t\tthis.$$searchTextIso = null;\n\t\t\tthis.$$searchTextName = null;\n\t\t\tthis.$$selected = null;\n\t\t}",
"function country(name, healthiness, demonym, maleNames, femaleNames) {\n this.name = name;\n this.healthiness = healthiness;\n this.demonym = demonym;\n this.maleNames = maleNames;\n this.femaleNames = femaleNames;\n}",
"function objRegion (strName, strFile, strURL)\r\n{\r\n\tthis.name = strName\t\t\t// Name of region\r\n\tthis.file = strFile\t\t\t// Region filename containing office information\r\n\tthis.url = strURL\t\t\t// URL for region-specific homepage\r\n}",
"function getCountry() {\n return country_code;\n}",
"function Country(name, iso, capital, population) {\n \"use strict\";\n // TODO: Add the missing source code in the Country constructor\n}",
"function getCountry(name){\n return countryData[name]\n}",
"function initCountryObject(filename) {\n var dataURL = urlForDataFile(filename);\n console.log(\"dataURL: \" + dataURL);\n $.ajax({\n url: dataURL,\n async: false,\n dataType: 'json'\n }).done(function(response) {\n initCountry = response;\n $('#countryField').text(initCountry.name);\n // The value read from the UN data files is for a 5 year period, so rescale\n initCountry.netMigration = initCountry.netMigration/5;\n initSimState();\n }).fail(function() {\n tell(\"Oops! This page was called with a bad country file name: \" + filename, \"red\");\n });\n }",
"function Country(currency, exchange, numStadiums) {\n this.currency = currency;\n this.exchange = exchange;\n this.numStadiums = numStadiums;\n}",
"function getCountry(name) {\r\n var countryCode = getCountryCode(name);\r\n var countryElement = createCountryElement(countryCode);\r\n return countryElement;\r\n}",
"get country() {\n return privates.get(this).get(\"[[country]]\");\n }",
"function buildCountryRefObj() {\n var countries = {};\n for (var region in ein.regions) {\n if (Array.isArray(ein.regions[region])) { addCountries(ein.regions[region], region) \n } else {\n for (var subRegion in ein.regions[region]) {\n addCountries(ein.regions[region][subRegion], region)\n }\n }\n }\n return countries;\n\n function addCountries(cntryAry, region) {\n cntryAry.forEach(function(cntry){\n var cntryStr = cntry.split('[')[0].trim(); \n countries[cntryStr] = region; \n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get TreeNode props with Tree props. | function getTreeNodeProps(key, _ref3) {
var expandedKeysSet = _ref3.expandedKeysSet,
selectedKeysSet = _ref3.selectedKeysSet,
loadedKeysSet = _ref3.loadedKeysSet,
loadingKeysSet = _ref3.loadingKeysSet,
checkedKeysSet = _ref3.checkedKeysSet,
halfCheckedKeysSet = _ref3.halfCheckedKeysSet,
dragOverNodeKey = _ref3.dragOverNodeKey,
dropPosition = _ref3.dropPosition,
keyEntities = _ref3.keyEntities;
var entity = keyEntities[key];
var treeNodeProps = {
eventKey: key,
expanded: expandedKeysSet.has(key),
selected: selectedKeysSet.has(key),
loaded: loadedKeysSet.has(key),
loading: loadingKeysSet.has(key),
checked: checkedKeysSet.has(key),
halfChecked: halfCheckedKeysSet.has(key),
pos: String(entity ? entity.pos : ''),
parent: entity.parent,
// [Legacy] Drag props
// Since the interaction of drag is changed, the semantic of the props are
// not accuracy, I think it should be finally removed
dragOver: dragOverNodeKey === key && dropPosition === 0,
dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,
dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1
};
return treeNodeProps;
} | [
"function getTreeNodeProps(key, _ref3) {\n\t var expandedKeys = _ref3.expandedKeys,\n\t selectedKeys = _ref3.selectedKeys,\n\t loadedKeys = _ref3.loadedKeys,\n\t loadingKeys = _ref3.loadingKeys,\n\t checkedKeys = _ref3.checkedKeys,\n\t halfCheckedKeys = _ref3.halfCheckedKeys,\n\t dragOverNodeKey = _ref3.dragOverNodeKey,\n\t dropPosition = _ref3.dropPosition,\n\t keyEntities = _ref3.keyEntities;\n\t var entity = keyEntities[key];\n\t var treeNodeProps = {\n\t eventKey: key,\n\t expanded: expandedKeys.indexOf(key) !== -1,\n\t selected: selectedKeys.indexOf(key) !== -1,\n\t loaded: loadedKeys.indexOf(key) !== -1,\n\t loading: loadingKeys.indexOf(key) !== -1,\n\t checked: checkedKeys.indexOf(key) !== -1,\n\t halfChecked: halfCheckedKeys.indexOf(key) !== -1,\n\t pos: String(entity ? entity.pos : ''),\n\t // [Legacy] Drag props\n\t // Since the interaction of drag is changed, the semantic of the props are\n\t // not accuracy, I think it should be finally removed\n\t dragOver: dragOverNodeKey === key && dropPosition === 0,\n\t dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,\n\t dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1\n\t };\n\t return treeNodeProps;\n\t}",
"function getTreeNodeProps(key, _ref2) {\n var expandedKeys = _ref2.expandedKeys,\n selectedKeys = _ref2.selectedKeys,\n loadedKeys = _ref2.loadedKeys,\n loadingKeys = _ref2.loadingKeys,\n checkedKeys = _ref2.checkedKeys,\n halfCheckedKeys = _ref2.halfCheckedKeys,\n dragOverNodeKey = _ref2.dragOverNodeKey,\n dropPosition = _ref2.dropPosition,\n keyEntities = _ref2.keyEntities;\n var entity = keyEntities[key];\n var treeNodeProps = {\n eventKey: key,\n expanded: expandedKeys.indexOf(key) !== -1,\n selected: selectedKeys.indexOf(key) !== -1,\n loaded: loadedKeys.indexOf(key) !== -1,\n loading: loadingKeys.indexOf(key) !== -1,\n checked: checkedKeys.indexOf(key) !== -1,\n halfChecked: halfCheckedKeys.indexOf(key) !== -1,\n pos: String(entity ? entity.pos : ''),\n // [Legacy] Drag props\n // Since the interaction of drag is changed, the semantic of the props are\n // not accuracy, I think it should be finally removed\n dragOver: dragOverNodeKey === key && dropPosition === 0,\n dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,\n dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1\n };\n return treeNodeProps;\n}",
"get props() {\n\t\tconst { nodeType, nodeName, id, type } = this.actualNode;\n\n\t\treturn {\n\t\t\tnodeType,\n\t\t\tnodeName: nodeName.toLowerCase(),\n\t\t\tid,\n\t\t\ttype\n\t\t};\n\t}",
"function getNodeProps(node, key, opts, renderer) {\n\t var props = { key: key }, undef;\n\t\n\t // `sourcePos` is true if the user wants source information (line/column info from markdown source)\n\t if (opts.sourcePos && node.sourcepos) {\n\t props['data-sourcepos'] = flattenPosition(node.sourcepos);\n\t }\n\t\n\t var type = normalizeTypeName(node.type);\n\t\n\t switch (type) {\n\t case 'html_inline':\n\t case 'html_block':\n\t props.isBlock = type === 'html_block';\n\t props.escapeHtml = opts.escapeHtml;\n\t props.skipHtml = opts.skipHtml;\n\t break;\n\t case 'code_block':\n\t var codeInfo = node.info ? node.info.split(/ +/) : [];\n\t if (codeInfo.length > 0 && codeInfo[0].length > 0) {\n\t props.language = codeInfo[0];\n\t }\n\t break;\n\t case 'code':\n\t props.children = node.literal;\n\t props.inline = true;\n\t break;\n\t case 'heading':\n\t props.level = node.level;\n\t break;\n\t case 'softbreak':\n\t props.softBreak = opts.softBreak;\n\t break;\n\t case 'link':\n\t props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t break;\n\t case 'image':\n\t props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t\n\t // Commonmark treats image description as children. We just want the text\n\t props.alt = node.react.children.join('');\n\t node.react.children = undef;\n\t break;\n\t case 'list':\n\t props.start = node.listStart;\n\t props.type = node.listType;\n\t props.tight = node.listTight;\n\t break;\n\t default:\n\t }\n\t\n\t if (typeof renderer !== 'string') {\n\t props.literal = node.literal;\n\t }\n\t\n\t var children = props.children || (node.react && node.react.children);\n\t if (Array.isArray(children)) {\n\t props.children = children.reduce(reduceChildren, []) || null;\n\t }\n\t\n\t return props;\n\t}",
"function getNodeProps(node, key, opts, renderer) {\n\t var props = { key: key },\n\t undef;\n\t\n\t // `sourcePos` is true if the user wants source information (line/column info from markdown source)\n\t if (opts.sourcePos && node.sourcepos) {\n\t props['data-sourcepos'] = flattenPosition(node.sourcepos);\n\t }\n\t\n\t var type = normalizeTypeName(node.type);\n\t\n\t switch (type) {\n\t case 'html_inline':\n\t case 'html_block':\n\t props.isBlock = type === 'html_block';\n\t props.escapeHtml = opts.escapeHtml;\n\t props.skipHtml = opts.skipHtml;\n\t break;\n\t case 'code_block':\n\t var codeInfo = node.info ? node.info.split(/ +/) : [];\n\t if (codeInfo.length > 0 && codeInfo[0].length > 0) {\n\t props.language = codeInfo[0];\n\t }\n\t break;\n\t case 'code':\n\t props.children = node.literal;\n\t props.inline = true;\n\t break;\n\t case 'heading':\n\t props.level = node.level;\n\t break;\n\t case 'softbreak':\n\t props.softBreak = opts.softBreak;\n\t break;\n\t case 'link':\n\t props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t break;\n\t case 'image':\n\t props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t\n\t // Commonmark treats image description as children. We just want the text\n\t props.alt = node.react.children.join('');\n\t node.react.children = undef;\n\t break;\n\t case 'list':\n\t props.start = node.listStart;\n\t props.type = node.listType;\n\t props.tight = node.listTight;\n\t break;\n\t default:\n\t }\n\t\n\t if (typeof renderer !== 'string') {\n\t props.literal = node.literal;\n\t }\n\t\n\t var children = props.children || node.react && node.react.children;\n\t if (Array.isArray(children)) {\n\t props.children = children.reduce(reduceChildren, []) || null;\n\t }\n\t\n\t return props;\n\t}",
"function getNodeProps(node, key, opts, renderer) {\n\t var props = { key: key }, undef;\n\n\t // `sourcePos` is true if the user wants source information (line/column info from markdown source)\n\t if (opts.sourcePos && node.sourcepos) {\n\t props['data-sourcepos'] = flattenPosition(node.sourcepos);\n\t }\n\n\t var type = normalizeTypeName(node.type);\n\n\t switch (type) {\n\t case 'html_inline':\n\t case 'html_block':\n\t props.isBlock = type === 'html_block';\n\t props.escapeHtml = opts.escapeHtml;\n\t props.skipHtml = opts.skipHtml;\n\t break;\n\t case 'code_block':\n\t var codeInfo = node.info ? node.info.split(/ +/) : [];\n\t if (codeInfo.length > 0 && codeInfo[0].length > 0) {\n\t props.language = codeInfo[0];\n\t }\n\t break;\n\t case 'code':\n\t props.children = node.literal;\n\t props.inline = true;\n\t break;\n\t case 'heading':\n\t props.level = node.level;\n\t break;\n\t case 'softbreak':\n\t props.softBreak = opts.softBreak;\n\t break;\n\t case 'link':\n\t props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t if (opts.linkTarget) {\n\t props.target = opts.linkTarget;\n\t }\n\t break;\n\t case 'image':\n\t props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\n\t // Commonmark treats image description as children. We just want the text\n\t props.alt = node.react.children.join('');\n\t node.react.children = undef;\n\t break;\n\t case 'list':\n\t props.start = node.listStart;\n\t props.type = node.listType;\n\t props.tight = node.listTight;\n\t break;\n\t default:\n\t }\n\n\t if (typeof renderer !== 'string') {\n\t props.literal = node.literal;\n\t }\n\n\t var children = props.children || (node.react && node.react.children);\n\t if (Array.isArray(children)) {\n\t props.children = children.reduce(reduceChildren, []) || null;\n\t }\n\n\t return props;\n\t}",
"function _getPropertyTree() {\n\t\t// If not using the property tree then just return generic data.\n\t\tif(!_useTree)\n\t\t\treturn {\n\t\t\t\tcanSet: true,\n\t\t\t\ti: \t\t0,\n\t\t\t\tprop: \t_prop,\n\t\t\t\tscope: \t_scope\n\t\t\t};\n\t\t\n\t\t// Split the different props of the property tree.\n\t\tvar props = _prop.split(\".\"),\n\t\t// Store the _scope into the result to use for looping.\n\t\t\tresult = _scope,\n\t\t// Used to determine if can set the variable.\n\t\t\tcanSet = true;\n\t\t\n\t\t// Loops through attempting to find the correct scope that\n\t\t// the property lies in.\n\t\tfor(var i = 0; i < props.length - 1 && canSet; ++i)\n\t\t\tif(result[props[i]] !== undefined)\n\t\t\t\tresult = result[props[i]];\n\t\t\telse\n\t\t\t\tcanSet = false;\n\t\t\n\t\treturn {\n\t\t\tcanSet: canSet,\n\t\t\ti: \t\ti,\n\t\t\tprop: \tprops[i],\n\t\t\tscope: \tresult\n\t\t};\n\t}",
"prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }",
"tree() {\n return this.nodeTree;\n }",
"prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }",
"prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }",
"function retrieveNameFromProps( nodeDetails){\r\n\tvar props = nodeDetails.properties, nameNode;\r\n var display = $.grep(props, function(i, prop) {\r\n \t if(i.name == 'name') {\r\n \t\t nameNode = i.value;\r\n \t\t \t\t\t\t\t}\r\n })\r\n // display the name if exits or type of node \r\n if (nameNode ) { nodeDetails.cyDisplay = nameNode}\r\n else {nodeDetails.cyDisplay ='' + '(' + nodeDetails.type + ')' ;}\r\n\treturn nodeDetails;\r\n\t\r\n}",
"function formatTreeData(treeData, getLabelProp) {\n var warningTimes = 0;\n var valueSet = new Set();\n\n function dig(dataNodes) {\n return (dataNodes || []).map(function (node) {\n var key = node.key,\n value = node.value,\n children = node.children,\n rest = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__babel_runtime_helpers_esm_objectWithoutProperties__[\"a\" /* default */])(node, [\"key\", \"value\", \"children\"]);\n\n var mergedValue = 'value' in node ? value : key;\n\n var dataNode = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__babel_runtime_helpers_esm_objectSpread2__[\"a\" /* default */])(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__babel_runtime_helpers_esm_objectSpread2__[\"a\" /* default */])({}, rest), {}, {\n key: key !== null && key !== undefined ? key : mergedValue,\n value: mergedValue,\n title: getLabelProp(node)\n }); // Check `key` & `value` and warning user\n\n\n if (process.env.NODE_ENV !== 'production') {\n if (key !== null && key !== undefined && value !== undefined && String(key) !== String(value) && warningTimes < MAX_WARNING_TIMES) {\n warningTimes += 1;\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3_rc_util_es_warning__[\"a\" /* default */])(false, \"`key` or `value` with TreeNode must be the same or you can remove one of them. key: \".concat(key, \", value: \").concat(value, \".\"));\n }\n\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3_rc_util_es_warning__[\"a\" /* default */])(!valueSet.has(value), \"Same `value` exist in the tree: \".concat(value));\n valueSet.add(value);\n }\n\n if ('children' in node) {\n dataNode.children = dig(children);\n }\n\n return dataNode;\n });\n }\n\n return dig(treeData);\n}",
"function formatTreeData(treeData, getLabelProp) {\n var warningTimes = 0;\n var valueSet = new Set();\n\n function dig(dataNodes) {\n return (dataNodes || []).map(function (node) {\n var key = node.key,\n value = node.value,\n children = node.children,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(node, [\"key\", \"value\", \"children\"]);\n\n var mergedValue = 'value' in node ? value : key;\n\n var dataNode = _objectSpread(_objectSpread({}, rest), {}, {\n key: key !== null && key !== undefined ? key : mergedValue,\n value: mergedValue,\n title: getLabelProp(node)\n }); // Check `key` & `value` and warning user\n\n\n if (false) {}\n\n if ('children' in node) {\n dataNode.children = dig(children);\n }\n\n return dataNode;\n });\n }\n\n return dig(treeData);\n}",
"getTreePropertyString(treePropertyName) {\n return this.treePropertyFunctions[treePropertyName]();\n }",
"render() {\n return _react.default.createElement(TreeMenuLinkStyle, _extends({}, this.props, {\n selected: this.props.selected\n }), this.props.children);\n }",
"render() {\n let componentTree = [];\n\n return (\n <ul className=\"tree\">\n {this.renderTree(this.props.componentTreeObj)}\n </ul>\n );\n }",
"getTree() {\n return tree.getTree();\n }",
"extractProps(node) {\n if (Element.isAncestor(node)) {\n var properties = _objectWithoutProperties(node, _excluded$3);\n\n return properties;\n } else {\n var properties = _objectWithoutProperties(node, _excluded2$2);\n\n return properties;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the Param metadata. Use this decorator to compose your own decorator. | function ParamFn(fn) {
return (target, propertyKey, index) => {
if (core.decoratorTypeOf([target, propertyKey, index]) === core.DecoratorTypes.PARAM) {
fn(exports.ParamMetadata.get(target, propertyKey, index), [target, propertyKey, index]);
}
};
} | [
"function ctorParameterToMetadata(param, isCore) {\n // Parameters sometimes have a type that can be referenced. If so, then use it, otherwise\n // its type is undefined.\n var type = param.typeExpression !== null ? param.typeExpression : ts.createIdentifier('undefined');\n var properties = [\n ts.createPropertyAssignment('type', type),\n ];\n // If the parameter has decorators, include the ones from Angular.\n if (param.decorators !== null) {\n var ngDecorators = param.decorators.filter(function (dec) { return isAngularDecorator(dec, isCore); }).map(decoratorToMetadata);\n properties.push(ts.createPropertyAssignment('decorators', ts.createArrayLiteral(ngDecorators)));\n }\n return ts.createObjectLiteral(properties, true);\n }",
"function ctorParameterToMetadata(param, defaultImportRecorder, isCore) {\n // Parameters sometimes have a type that can be referenced. If so, then use it, otherwise\n // its type is undefined.\n const type = param.typeValueReference.kind !== 2 /* UNAVAILABLE */ ?\n valueReferenceToExpression(param.typeValueReference, defaultImportRecorder) :\n new LiteralExpr(undefined);\n const mapEntries = [\n { key: 'type', value: type, quoted: false },\n ];\n // If the parameter has decorators, include the ones from Angular.\n if (param.decorators !== null) {\n const ngDecorators = param.decorators.filter(dec => isAngularDecorator$1(dec, isCore))\n .map((decorator) => decoratorToMetadata(decorator));\n const value = new WrappedNodeExpr(ts.createArrayLiteral(ngDecorators));\n mapEntries.push({ key: 'decorators', value, quoted: false });\n }\n return literalMap(mapEntries);\n }",
"swaggerMetadata() {\n return swaggerMetadata(...args.slice(0, args.length - 1));\n }",
"function propertyMeta(context) {\n return (prop) => Reflect.getMetadata(prop, context);\n}",
"get parameterInfos() {\n const usageByTypeName = {};\n return this.parameterTypes.map((t) => getParameterInfo(t, usageByTypeName));\n }",
"function getDecoratorsOfParameters(node){var decorators;if(node){var parameters=node.parameters;var firstParameterIsThis=parameters.length>0&&ts.parameterIsThisKeyword(parameters[0]);var firstParameterOffset=firstParameterIsThis?1:0;var numParameters=firstParameterIsThis?parameters.length-1:parameters.length;for(var i=0;i<numParameters;i++){var parameter=parameters[i+firstParameterOffset];if(decorators||parameter.decorators){if(!decorators){decorators=new Array(numParameters);}decorators[i]=parameter.decorators;}}}return decorators;}",
"function createRouteParamDecorator(factory) {\n const paramtype = randomString() + randomString();\n return (data, ...pipes) => (target, key, index) => {\n const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target, key) || {};\n Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, assignCustomMetadata(args, paramtype, index, factory, data, ...pipes), target, key);\n };\n}",
"identifyingParams() {\n return this._identifyingParams();\n }",
"parameterNames() {\n\t\tconst params = [];\n\t\tif (this.parameterMetadata) {\n\t\t\tfor (const param of this.parameterMetadata.paramDefs) {\n\t\t\t\tparams.push(param.name);\n\t\t\t}\n\t\t}\n\t\treturn params;\n\t}",
"function transformDecoratorsOfParameter(decorators,parameterOffset){var expressions;if(decorators){expressions=[];for(var _i=0,decorators_1=decorators;_i<decorators_1.length;_i++){var decorator=decorators_1[_i];var helper=createParamHelper(context,transformDecorator(decorator),parameterOffset,/*location*/decorator.expression);ts.setEmitFlags(helper,1536/* NoComments */);expressions.push(helper);}}return expressions;}",
"function ParameterDecorator(target, methodName, parameterPosition) {\n console.log('Parameter Decorator!');\n console.log(target);\n console.log(methodName);\n console.log(parameterPosition);\n}",
"identifyingParams() {\n return this._identifyingParams();\n }",
"get metadata () {\n return {\n name: this.name,\n number: this.number,\n position: this._position,\n maxXPosition: this.maxXPosition\n }\n }",
"function getDecoratorsOfParameters(node) {\n var decorators;\n if (node) {\n var parameters = node.parameters;\n for (var i = 0; i < parameters.length; i++) {\n var parameter = parameters[i];\n if (decorators || parameter.decorators) {\n if (!decorators) {\n decorators = new Array(parameters.length);\n }\n decorators[i] = parameter.decorators;\n }\n }\n }\n return decorators;\n }",
"getParameters () { return this.parameters }",
"function getDecoratorsOfParameters(node) {\n var decorators;\n if (node) {\n var parameters = node.parameters;\n for (var i = 0; i < parameters.length; i++) {\n var parameter = parameters[i];\n if (decorators || parameter.decorators) {\n if (!decorators) {\n decorators = new Array(parameters.length);\n }\n decorators[i] = parameter.decorators;\n }\n }\n }\n return decorators;\n }",
"function visitParameter(node) {\n if (ts.parameterIsThisKeyword(node)) {\n return undefined;\n }\n var parameter = ts.createParameter(\n /*decorators*/ undefined, \n /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), \n /*questionToken*/ undefined, \n /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));\n // While we emit the source map for the node after skipping decorators and modifiers,\n // we need to emit the comments for the original range.\n ts.setOriginalNode(parameter, node);\n ts.setTextRange(parameter, ts.moveRangePastModifiers(node));\n ts.setCommentRange(parameter, node);\n ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));\n ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);\n return parameter;\n }",
"get parameters() {\n return this._parameters\n }",
"function getParamAccessor(id, params) {\n // easy access\n var paramGet = function (prop, alt, required) {\n if (arguments.length < 1) {\n throw (new Error('expected at least 1 argument'));\n }\n if (arguments.length < 2) {\n required = true;\n }\n if (params && hasOwnProp(params, prop)) {\n return params[prop];\n }\n if (required) {\n if (!params) {\n throw (new Error('no params supplied for: ' + id));\n }\n throw (new Error('missing param property: ' + prop + ' in: ' + id));\n }\n return alt;\n };\n paramGet.raw = params;\n return paramGet;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads all new posts from saved urls TODO: Download only pages that have not been fully downloaded yet. | function downloadPosts(){
chrome.storage.local.get("urls", function(result){
result = result["urls"];
result = (result === undefined ? {} : result);
//Variables to define:
let pageTotal = 0;
let loadingBar = document.getElementById("loadingBar");
let toDownload = {}; //Stores num to download in key-value pairs
let numDownloaded = 0;
//Iterator function
let currentURL = 0;
function getNextURL(){
let url = Object.values(result)[currentURL];
currentURL = currentURL + 1;
return url;
}
//Count Num Posts for each URL
function countNumPosts(callback){
let url = getNextURL();
if (!url)
{
currentURL = 0;
return callback();
}
let currentPage = (!url["currentPage"] ? 1 : url["currentPage"]); //Default page = 1;
getBeachNumPages(url["url"], function(numPages){
let numUnread = numPages - currentPage + 1; //+1 because we need to read the current page too
pageTotal = pageTotal + numUnread;
toDownload[url["url"]] = numUnread;
countNumPosts(callback);
})
}
//NOTE:
//YOU NEED TO QUEUE ALL PAGES SEQUENTIALLY, AND FIGURE OUT HOW TO FREE DATA
//ELSE, 40 PAGES WILL OPEN AT THE SAME TIME AND BREAK THE SYSTEM.
function downloadEachURL(callback){
let url = getNextURL();
console.log("URL Received");
if (!url)
{
console.log("End");
return callback();
}
console.log(url["type"]);
if (url["type"] == "pokebeach"){
let currentPage = (!url["currentPage"] ? 1 : url["currentPage"]); //Default page = 1;
let endPage = toDownload[url["url"]] + currentPage - 1;
function nextPage(){
let toReturn = currentPage;
currentPage++;
return toReturn;
}
function readPage(){
let pageNumber = nextPage();
console.log (pageNumber + " " + endPage);
if (pageNumber > endPage){
//callback
return downloadEachURL(callback);
}
console.log("Downloading " + url["url"]+"page-" + pageNumber);
let site = sequentialGetFile(url["url"]+"page-" + pageNumber, function(site){
let x = Array.from(site.getElementsByClassName("message"));
let y = Array.from(site.getElementsByClassName("deleted"));
let z = Array.from(site.getElementsByClassName("quickReply"));
x = x.filter(function(e){return this.indexOf(e)<0;},y);
x = x.filter(function(e){return this.indexOf(e)<0;},z);
let numToSave = x.length;
let numSaved = 0;
chrome.storage.local.get("posts", function(data){
data = data["posts"];
if (data === undefined) data = {};
x.forEach(function (item) {
let id = item.id;
data[id] = (data[id] === undefined ? packagePost(item, id, url["url"]) : data[id]);
});
result[url["url"]]["currentPage"] = pageNumber;
//Save the updated posts list
chrome.storage.local.set({"posts" : data}, function() {
//Save the act of reading the page
chrome.storage.local.set({"urls" : result}, function(){
console.log(result);
loadingBar.value = loadingBar.value + 1;
numDownloaded++;
document.getElementById("loadingTitle").innerHTML = "Downloaded " + numDownloaded + " of " + pageTotal;
readPage();
})
});
});
});
}
readPage();
}
else if (url["type"] == "qt")
{
console.log("Downloading " + url["url"]+"?m1=-1&mN=-1");
let site = sequentialGetFile(url["url"]+"?m1=-1&mN=-1", function(site){
let x = Array.from(site.getElementsByClassName("messagerow"));
let postsToDownload = x.length;
let postsDownloaded = 0;
let pathArray = url["url"].split( '/' );
let chatNumber = pathArray.slice(-1)[0];
chrome.storage.local.get("posts", function(data){
data = data["posts"];
if (data === undefined) data = {};
x.forEach(function (item) {
//Get ID
let id = undefined;
let messageNumber = item.getElementsByClassName("messagenumber")[0];
id = messageNumber.childNodes[0].getAttribute("name");
let postNumber = id;
id += "-" + chatNumber;
data[id] = (data[id] === undefined ? packageQTPost(item, id, url["url"], postNumber) : data[id]);
});
chrome.storage.local.set({"posts" : data}, function() {
loadingBar.value = loadingBar.value + 1;
numDownloaded++;
document.getElementById("loadingTitle").innerHTML = "Downloaded " + numDownloaded + " of " + pageTotal;
return downloadEachURL(callback);
});
});
});
}
}
document.getElementById("loadingPanel").style.display = "block";
document.getElementById("loadingButton").style.display = "none";
document.getElementById("loadingTitle").innerHTML = "Preparing Download";
countNumPosts(function(){
loadingBar.max = pageTotal;
loadingBar.value = 0;
document.getElementById("loadingTitle").innerHTML = "Downloaded 0 of " + pageTotal;
downloadEachURL(function() {
//Reset Loading Panel
document.getElementById("loadingPanel").style.display = "none";
loadingBar.max = "";
loadingBar.value = "";
document.getElementById("loadingButton").style.display = "inline";
outputPosts();
});
})
});
} | [
"function fetchPosts() {\n // Exit if postURLs haven't been loaded\n if (!postURLs) return;\n\n isFetchingPosts = true;\n\n // Load as many posts as there were present on the page when it loaded\n // After successfully loading a post, load the next one\n var loadedPosts = 0,\n postCount = $(\".posts-list article\").size(),\n callback = function() {\n loadedPosts++;\n var postIndex = postCount + loadedPosts;\n\n if (postIndex > postURLs.length-1) {\n disableFetching();\n return;\n }\n\n if (loadedPosts < postsToLoad) {\n fetchPostWithIndex(postIndex, callback);\n } else {\n isFetchingPosts = false;\n }\n };\n\n fetchPostWithIndex(postCount + loadedPosts, callback);\n }",
"function fetchPosts() {\n // Exit if postURLs haven't been loaded\n if (!postURLs) return;\n \n isFetchingPosts = true;\n \n // Load as many posts as there were present on the page when it loaded\n // After successfully loading a post, load the next one\n var loadedPosts = 0,\n postCount = $(\".content-box\").children().length,\n callback = function() {\n loadedPosts++;\n var postIndex = postCount + loadedPosts;\n \n if (postIndex > postURLs.length-1) {\n disableFetching();\n return;\n }\n \n if (loadedPosts < postsToLoad) {\n fetchPostWithIndex(postIndex, callback);\n } else {\n isFetchingPosts = false;\n }\n };\n\t\tconsole.log(\"post count: \", postCount)\n fetchPostWithIndex(postCount + loadedPosts, callback);\n }",
"function fetchPosts() {\n // Exit if postURLs haven't been loaded\n if (!postURLs) return;\n \n isFetchingPosts = true;\n \n // Load as many posts as there were present on the page when it loaded\n // After successfully loading a post, load the next one\n var loadedPosts = 0,\n postCount = $(\".post-list\").children().length,\n callback = function() {\n loadedPosts++;\n var postIndex = postCount + loadedPosts;\n \n if (postIndex > postURLs.length-1) {\n disableFetching();\n return;\n }\n \n if (loadedPosts < postsToLoad) {\n fetchPostWithIndex(postIndex, callback);\n } else {\n isFetchingPosts = false;\n }\n };\n\t\t\n fetchPostWithIndex(postCount + loadedPosts, callback);\n }",
"async download() {\n const posterURLs = this.getPosterURLs();\n const subtitlesURLs = this.getSubtitlesUrls();\n\n this.downloading = true;\n this.saveToCache([...posterURLs, ...subtitlesURLs]);\n this.runIDBDownloads();\n }",
"async function saveLastTenPosts(lastPostLink) {\n var postNumber = getPostNumber(lastPostLink);\n const baseLink = lastPostLink.substr(0, lastPostLink.indexOf('/post/') + 6);\n var iter = 0;\n\n while (postNumber > 0 && iter < 10) {\n const page = await axios.get(baseLink + postNumber--).catch(function(error) {\n if (error.response) {\n console.log('404: Post not found!');\n }\n }) || null;\n if (page) {\n savePostContent(cheerio.load(page.data), baseLink);\n iter++;\n }\n }\n}",
"function downloadNewFiles(website){\n\tretrieveFilesURLs(website,function(files,website){ \n\t\tvar inMain = false;\n\t\tif(document.getElementById(\"main\").style.visibility === \"visible\"){\n\t\t\tinMain = true;\n\t\t}\n\t\tweb = downloadFiles(files,website);\n\t\twebFilesListener(web);\n\t\tchrome.runtime.sendMessage({type: \"printURLs\"});\n\t\tif(inMain){\n\t\t\treturnToMain();\n\t\t}\n\t});\n}",
"crawlComplete() {\n // We are not downloading images, just add it.\n let links = this.settings.getImageLinks(),\n url = '',\n link = null,\n i = 0,\n page = null,\n pattern = null,\n valid = true,\n pages = [];\n\n for (url in links) {\n this.db.images[url] = links[url];\n }\n links = this.settings.getDocumentLinks();\n\n for (url in links) {\n link = links[url];\n let alias = this.generateAlias(link.url);\n // Link it to the page.\n for (i in this.db.pages) {\n if (this.db.pages[i].url.replace(/#.*/, '') == link.contextUrl) {\n this.db.pages[i].documents[link.url] = { url: link.url, id: link.url, alias: alias };\n\n break;\n }\n }\n\n // Remove the context url and add it to the global list.\n this.db.documents[url] = { url: link.url, id: link.url, alias: alias };\n }\n\n // Turn assets into arrays.\n this.db.images = _.values(this.db.images);\n this.db.imagesSkipped = _.values(this.db.imagesSkipped);\n this.db.documents = _.values(this.db.documents);\n this.db.forms = _.values(this.db.forms);\n for (i in this.db.pages) {\n this.db.pages[i].documents = _.values(this.db.pages[i].documents);\n }\n // Save db to JSON.\n if (this.db.pages.length > 0) {\n let duplicates = new Duplicates(),\n genericTitle = '',\n genericUrl = '';\n\n if (this.settings.removeDuplicates) {\n duplicates.removeDuplicates(this.db.pages);\n duplicates.removeDuplicateTitles(this.db.pages);\n }\n\n // OK - final cleaning things.\n // 1. Global string replacements on URLs and body text.\n for (i in this.db.pages) {\n page = this.db.pages[i];\n page.alias = this.generateAlias(page.url);\n valid = true;\n if (!genericTitle) {\n genericTitle = this.db.pages[i].title;\n genericUrl = this.settings.protocol + '//' + this.settings.domain;\n }\n\n let replacements = this.settings.searchReplace.split('\\n'),\n index = 0,\n replacement = [];\n\n for (index = 0; index < replacements.length; index++) {\n replacement = replacements[index].split('|');\n\n if (replacement.length > 1) {\n page.body = page.body.split(replacement[0]).join(replacement[1]);\n page.url = page.url.split(replacement[0]).join(replacement[1]);\n }\n }\n page.alias = this.generateAlias(page.url);\n\n // 2. Clean the URL parameters\n // Trailing slashes removed.\n page.url = page.url.replace(/\\/$/g, '');\n page.alias = this.generateAlias(page.url);\n\n // Query string removed.\n page.url = page.url.replace(/\\?.*$/g, '');\n page.alias = this.generateAlias(page.url);\n\n // Multiple slashes that is not a URL removed.\n page.url = page.url.replace(/([^:])\\/\\//, '$1/');\n page.alias = this.generateAlias(page.url);\n\n // 4. Clean nasty redirect scripts from URLs and body text.\n if (this.settings.redirectScript) {\n pattern = new RegExp(this.settings.redirectScript, 'g');\n if (pattern.test(page.url)) {\n // Nuke it.\n valid = false;\n }\n // Replace redirect links in the body.\n page.body = page.body.replace(pattern, function(match, p1) {\n return this.decodeEntities(p1);\n });\n }\n page.alias = this.generateAlias(page.url);\n\n // 5. Kill pages from a 404.\n if (page.title.toLowerCase().includes('page not found') ||\n page.title.toLowerCase().includes('page missing')) {\n valid = false;\n this.log('Page not found: ' + page.url);\n }\n // 6. Kill bogus file extensions from webpages and urls.\n let all = this.settings.scriptExtensions.split(','),\n extIndex;\n page.alias = this.generateAlias(page.url);\n\n for (extIndex in all) {\n if (all[extIndex]) {\n page.url = page.url.replace(new RegExp('.' + all[extIndex], 'g'), '');\n page.body = page.body.replace(new RegExp('.' + all[extIndex], 'g'), '');\n }\n }\n\n // 3. Generate Aliases\n // Generate a relative link from the URL.\n page.alias = this.generateAlias(page.url);\n\n // 7. Some pages have MULTIPLE h1s (really!?). We will take the last one if it happens.\n\n pattern = /<h1>([^<]*)<\\/h1>/g;\n // Not in node.\n if (page.body.matchAll) {\n let matches = page.body.matchAll(pattern);\n for (let match of matches) {\n page.title = match[1];\n }\n }\n\n // 8. Kill %20 invalid urls.\n page.alias = this.decodeEntities(page.alias);\n\n // 10. Generate Parents for the menu.\n\n let parentPage = page.alias;\n // Remove trailing slashes.\n parentPage = parentPage.replace(/\\/$/g, '');\n\n // Get path sections.\n parentPage = parentPage.split('/');\n // Remove the last one.\n parentPage.pop();\n // Build a string again.\n page.parent = parentPage.join('/');\n\n // 11. For pages with a generic title, make a new one from the alias.\n if (page.title == genericTitle && i > 0) {\n page.title = this.sanitiseTitle(page.alias);\n }\n if (this.settings.excludeTitleString) {\n page.title = page.title.replace(new RegExp(this.settings.excludeTitleString, 'gi'), '');\n }\n\n // 12. For listing pages, keep the first page content but add a comment.\n if (pages[page.alias]) {\n valid = false;\n pages[page.alias].body += '<!-- Listing page -->';\n }\n\n // 13. Decode entities in titles.\n page.title = this.decodeEntities(page.title);\n\n // 14. Remove titles from the body content.\n pattern = /<h1>([^<]*)<\\/h1>/g;\n page.body = page.body.replace(pattern, '');\n\n // All pages must have a title.\n if (page.title.trim() == '') {\n valid = false;\n }\n\n if (valid) {\n // No duplicate aliases.\n\n let j = 0;\n for (j = 0; j < i; j++) {\n // Non empty text that duplicates an existing page.\n if (this.db.pages[j].body == this.db.pages[i].body && this.db.pages[j].body.length > 256) {\n this.db.redirects.push({\n from: this.db.pages[i].alias.substr(1),\n to: 'internal:' + this.db.pages[j].alias\n });\n valid = false;\n j = i;\n }\n }\n\n if (valid) {\n pages[page.alias] = page;\n }\n }\n }\n\n let doitagain = true;\n let alias1 = '', alias2 = '', found = false;\n while (doitagain) {\n doitagain = false;\n\n for (alias1 in pages) {\n found = false;\n page = pages[alias1];\n\n for (alias2 in pages) {\n if (page.parent == pages[alias2].alias) {\n found = true;\n }\n }\n\n if (!found && page.parent) {\n let newpage = {};\n newpage.url = genericUrl + page.parent;\n newpage.alias = page.parent;\n newpage.images = [];\n newpage.documents = [];\n newpage.forms = [];\n newpage.body = '';\n newpage.mediaType = 'text/html';\n newpage.contentType = 'govcms_standard_page';\n newpage.fields = [];\n let parentPage = page.parent.split('/');\n let title = parentPage.pop();\n newpage.parent = parentPage.join('/');\n newpage.title = this.sanitiseTitle(title);\n pages[newpage.alias] = newpage;\n this.log('Generate parent for page: ' + newpage.alias);\n\n doitagain = true;\n }\n }\n }\n\n // 15. Generate blank intermediate pages for the menu that are missing.\n this.db.pages = _.values(pages);\n\n this.scorePages();\n\n this.saveDb();\n this.updateIndex();\n\n this.log('Crawl complete!', this.db.pages.length + ' pages', this.db.images.length + ' images',\n this.db.documents.length + ' documents', this.db.forms.length + ' forms');\n } else {\n this.log('Crawl failed! Could not download ' + this.settings.startUrl);\n this.completeHandler(false);\n }\n // Stop crawling.\n this.crawler.stop();\n }",
"async function getUnscrapedUrls(num){\n const docs = await webgraphDb.viewAsync('pages', 'unscraped', { limit: num });\n // Update the docs\n let updatedDocs = docs.rows.map((doc) => {\n doc.key.status = 'queued';\n return doc.key;\n });\n const bulkResults = await webgraphDb.bulkAsync({ docs: updatedDocs });\n // Review the update\n for(var b=bulkResults.length-1; b>=0; b--){\n const bulkResult = bulkResults[b];\n if(bulkResult.error){\n updatedDocs.splice(b, 1); // Remove any docs that couldn't be flagged as `queued` (likely due to conflicts)\n } else {\n updatedDocs[b]._rev = bulkResult.rev; // Update the _rev of those that could\n }\n }\n // Make sure the url is a property\n updatedDocs.forEach(function(doc){\n doc.url = doc._id;\n });\n // Return\n return updatedDocs;\n}",
"function fetchMorePosts()\n\t{\n\t\tsetTimeout(function(){\n\t\t\t\t$loaderbody.show();\n\t\t}, 3000)\n\n\t\tsetTimeout(function() {\n\n\t\t\tif($urlDeterminer)\n\t\t\t{\n\t\t\t\tgrabTypePosts();\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgrabFeedPosts();\n\t\t\t}\n\n\t\t}, 6000)\n\t}",
"function _fetchPosts() {\n var queries = [];\n\n // Builds each query to execute\n for (var i = 0; i * POSTS_PER_PAGE < POSTS_TO_FETCH; i++) {\n queries.push(_buildRequest(BASE_URL + i));\n }\n\n // Execute each query\n async.parallel(\n queries,\n function (err, results) {\n // Flatten results\n var posts = [].concat.apply([], results);\n\n console.log('Done. %s posts fetched.', posts.length);\n console.log('Storing posts...');\n\n StoreHelper.storePosts(posts, function () {\n console.log('Done.');\n\n MongoHelper.finalize();\n process.exit();\n });\n }\n );\n}",
"function downloadByInternalLinks() {\n\tvar url = \"\";\n\tvar links = data.getInternal();\n\tfor (var i=0; i < links.length; i++) {\n\t\turl = links[i];\n\t\tchrome.tabs.create({url: url, active: false}, function(tab) {\n\t\t\tdonwloadTabIds.push(tab.id);\n\t\t});\n\t}\n}",
"function loadFeedPages() {\r\n\tif (!feedPanels[newsMode].feedPagesLoaded) {\r\n\t\t//httpRequest(\"POST\", feedsUrl, false, \"loadFeedPages_callback\", \"mode=\" + newsMode);\r\n\t\tsendRequest(feedsUrl, \"mode=\" + newsMode, 2, \"loadFeedPages_callback\", false);\r\n\t\tfeedPanels[newsMode].feedPagesLoaded = true;\r\n\t}\r\n}",
"function loadedPosts(e) {\n //don't clear if the url's got a timestamp marker in it, indicating \"load more posts\"\n if (e.target.responseURL.search(\"&before=\") < 0) postgrid.innerHTML = \"\";\n //console.log(e.target.response);\n let json = JSON.parse(e.target.response);\n let postdelay = 0;\n for (const post of json.response) {\n switch (post.type) {\n case \"photo\":\n //console.log(\"creating photo post\");\n createPhotoPost(post, postdelay);\n break;\n case \"text\":\n //console.log(\"creating text post\");\n createTextPost(post, postdelay);\n break;\n default:\n //console.log(String.toString(post));\n break;\n }\n postdelay += 0.1;\n pagetimestamp = post.timestamp;\n }\n removeErrors();\n loaderbutton.style.display = \"block\";\n}",
"function load(){\n //set start n end post nos, and update counter\n const start = counter;\n const end=start+qty-1\n counter=end+1\n\n //get new posts and add posts\n fetch(`posts?start=${start}&end=${end}`)\n .then(response=>response.json())\n .then(data=>{\n data.posts.forEach(add_post);\n })\n}",
"function loadBatch() {\n var MAX_COUNT = 4,\n count = 0;\n var $filteredPosts = $posts.filter(':visible:not(.loaded)');\n\n $filteredPosts.each(function() {\n var $post = $(this),\n url = '';\n\n url = $post.data('url');\n\n if (postIsAvailable($post)) {\n count++;\n loadPostData($post, url);\n }\n\n if (count >= MAX_COUNT) {\n loadRunning = false;\n return false;\n }\n });\n }",
"function getAllPagesURL() {\n pagesRange = [];\n var pagesRangeText = ehDownloadRange.querySelector('input').value.replace(/,/g, ',').trim();\n var retryCount = 0;\n\n if (pagesRangeText) { // if pages range is defined\n console.log('[EHD] Pages Range >', pagesRangeText);\n if (!ehDownloadRegex.pagesRange.test(pagesRangeText)) return alert('The format of Pages Range is incorrect.');\n\n var rangeRegex = /(?:(\\d*)-(\\d*))(?:\\/(\\d+))?|(\\d+)/g;\n var matches;\n while (matches = rangeRegex.exec(pagesRangeText)) {\n var single = Number(matches[4]);\n if (!isNaN(single)) {\n pagesRange.push(single);\n continue;\n }\n\n var begin = Number(matches[1]) || 1;\n var end = Number(matches[2]) || getFileSizeAndLength().page;\n if (begin > end) {\n var tmp = begin;\n begin = end;\n end = tmp;\n }\n var mod = Number(matches[3]) || 1;\n\n for (var i = begin; i <= end; i += mod) {\n pagesRange.push(i);\n }\n }\n\n pagesRange.sort(function(a, b){ return a - b; });\n pagesRange = pagesRange.filter(function(e, i, arr) { return i == 0 || e != arr[i - 1] });\n }\n\n ehDownloadDialog.style.display = 'block';\n if (!getAllPagesURLFin) {\n pageURLsList = [];\n var pagesLength;\n try { // in case pages has been modified like #56\n pagesLength = [].reduce.call(document.querySelectorAll('.ptt td'), function(x, y){\n var i = Number(y.textContent);\n if (!isNaN(i)) return x > i ? x : i;\n else return x;\n });\n }\n catch (error) {}\n var curPage = 0;\n retryCount = 0;\n\n var xhr = fetchPagesXHR;\n xhr.onload = function(){\n if (xhr.status !== 200 || !xhr.responseText) {\n if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {\n pushDialog('Failed! Retrying... ');\n retryCount++;\n xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);\n xhr.timeout = 30000;\n xhr.send();\n }\n else {\n pushDialog('Failed!\\nFetch Pages\\' URL failed, Please try again later.');\n isDownloading = false;\n alert('Fetch Pages\\' URL failed, Please try again later.');\n }\n return;\n }\n\n var pagesURL = xhr.responseText.split('<div id=\"gdt\">')[1].split('<div class=\"c\">')[0].match(ehDownloadRegex.pagesURL);\n if (!pagesURL) {\n console.error('[EHD] Response content is incorrect!');\n if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {\n pushDialog('Failed! Retrying... ');\n retryCount++;\n xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);\n xhr.timeout = 30000;\n xhr.send();\n }\n else {\n pushDialog('Failed!\\nCan\\'t get pages URL from response content.');\n isDownloading = false;\n //alert('We can\\'t get request content from response content. It\\'s possible that E-Hentai changes source code format so that we can\\'t find them, or your ISP modifies (or say hijacks) the page content. If it\\'s sure that you can access to any pages of E-Hentai, including current page: ' + location.origin + location.pathname + '?p=' + curPage + ' , please report a bug.');\n }\n return;\n }\n\n if (pagesURL[0].indexOf('/mpv/') >= 0) {\n console.log('[EHD] Page 1 URL > ' + pagesURL[0] + ' , use MPV fetch');\n pushDialog('Pages URL is MPV link\\n');\n\n getPagesURLFromMPV();\n return;\n }\n\n for (var i = 0; i < pagesURL.length; i++) {\n pageURLsList.push(pagesURL[i].split('\"')[1].replaceHTMLEntites());\n }\n pushDialog('Succeed!');\n\n curPage++;\n\n if (!pagesLength) { // can't get pagesLength correctly before\n pagesLength = xhr.responseText.match(ehDownloadRegex.pagesLength)[1] - 0;\n }\n\n if (curPage === pagesLength) {\n getAllPagesURLFin = true;\n var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });\n if (wrongPages.length !== 0) {\n pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });\n pushDialog('\\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\\n');\n if (pagesRange.length === 0) {\n pushDialog('Nothing matches provided pages range, stop downloading.');\n alert('Nothing matches provided pages range, stop downloading.');\n insertCloseButton();\n return;\n }\n }\n totalCount = pagesRange.length || pageURLsList.length;\n pushDialog('\\n\\n');\n initProgressTable();\n requestDownload();\n }\n else {\n xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);\n xhr.send();\n pushDialog('\\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + pagesLength + ') ... ');\n }\n };\n xhr.ontimeout = xhr.onerror = function(){\n if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) {\n pushDialog('Failed! Retrying... ');\n retryCount++;\n xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);\n xhr.timeout = 30000;\n xhr.send();\n }\n else {\n pushDialog('Failed!\\nFetch Pages\\' URL failed, Please try again later.');\n isDownloading = false;\n alert('Fetch Pages\\' URL failed, Please try again later.');\n }\n };\n xhr.open('GET', location.origin + location.pathname + '?p=' + curPage);\n xhr.timeout = 30000;\n xhr.send();\n pushDialog('\\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + (pagesLength || '?') + ') ... ');\n }\n else {\n var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });\n if (wrongPages.length !== 0) {\n pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });\n pushDialog('\\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\\n');\n if (pagesRange.length === 0) {\n pushDialog('Nothing matches provided pages range, stop downloading.');\n alert('Nothing matches provided pages range, stop downloading.');\n insertCloseButton();\n return;\n }\n }\n\n totalCount = pagesRange.length || pageURLsList.length;\n pushDialog('\\n\\n');\n initProgressTable();\n requestDownload();\n }\n}",
"function downloadAll(urls) {\r\n for (let i = 0; i < urls.length; i++) {\r\n let a = document.createElement(\"a\");\r\n a.setAttribute(\"href\", urls[i][0]);\r\n a.setAttribute(\"download\", urls[i][1]);\r\n a.setAttribute(\"target\", \"_blank\");\r\n a.click();\r\n }\r\n }",
"function initialSiteCheck(){\n\tchrome.storage.local.get(\"urls\", function(result){\n\t\tresult = result[\"urls\"];\n\t\tresult = (result === undefined ? {} : result);\n\t\t\n\t\t//Prompt if empty\n\t\tif (Object.keys(result).length === 0 && result.constructor === Object){\n\t\t\tpromptUserForSite(false, function(url){\n\t\t\t\t\n\t\t\t\tlet type = getURLType(url);\n\t\t\t\t\n\t\t\t\tif (type == \"pokebeach\"){\n\t\t\t\t\turl = url.substr(0, url.lastIndexOf('/') + 1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\telse if (type == \"qt\"){\n\t\t\t\t\tif (url.indexOf('?') !== -1)\n\t\t\t\t\t\turl = url.substr(0, url.indexOf('?'));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//Save url\n\t\t\t\tresult[url] = {url:url, currentPage: null, type: type, version:VERSION};\n\t\t\t\tchrome.storage.local.set({\"urls\" : result}, function() {\n\t\t\t\t\t//Download Posts\n\t\t\t\t\t//alert(\"hello world\");\n\t\t\t\t\tdownloadPosts();\n\t\t\t\t});\n\t\t\t})\n\t\t\t}\n\t\t}\n)\n\t\n}",
"function getdata() {\n\t// Iterate of URL list.\n\tfor (var i = 0;i<urls.length;i++) {\n\t\t// Request each URL and call urldone() when complete.\n\t\trequest(urls[i], function(error, response, body) {\n\t\t\tif (!error && response.statusCode == 200) {\n\t\t\t\t//console.log(\"Downloaded \"+response.request.uri.href);\n\t\t\t\turldone(body,response.request.uri.href);\n\t\t\t} else {\n\t\t\t\tconsole.log(\"Problem downloading \"+response.request.uri.href);\n\t\t\t\turldone(\"\",response.request.uri.href);\n\t\t\t}\n\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the leave command to the command parameter fed to this function Expects this.commandParameters to be set prior to calling this function | ProcessLeaveChangeCommand() {
var newYtLink = this.commandParameters[0];
this.leaveLink = newYtLink;
var msg = 'Leave audio changed to the link: ' + newYtLink;
this.ReplyToMessage(msg);
} | [
"endCommand() {\n this.activeCommand = null;\n this.state = {};\n }",
"function leaveBuilding() {\n inBuilding.inside = false;\n var eventObject = {\n \"event\": \"\",\n \"description\": \"\",\n \"image\": naratorImg\n };\n eventObject.event = \"You have left\";\n eventObject.description = inBuilding.buildingName;\n sendEventToIo(eventObject);\n // $scope.eventHistory.push(eventObject);\n resetVariables();\n updateScroll('event_home');\n }",
"function adjustCommand(cmd, newPoint) {\n\t if (cmd.length > 2) {\n\t cmd[cmd.length - 2] = newPoint.x;\n\t cmd[cmd.length - 1] = newPoint.y;\n\t }\n\t }",
"function adjustCommand(cmd, newPoint) {\n if (cmd.length > 2) {\n cmd[cmd.length - 2] = newPoint.x;\n cmd[cmd.length - 1] = newPoint.y;\n }\n }",
"onYesDiscardChanges () {\n this.dispatchParamViewDeleteByModel(this.digest) // discard parameter view state and edit changes\n this.isYesToLeave = true\n this.$router.push(this.pathToRouteLeave)\n }",
"cursorDown(params) {\n let param = params[0];\n if (param < 1) {\n param = 1;\n }\n this._terminal.y += param;\n if (this._terminal.y >= this._terminal.rows) {\n this._terminal.y = this._terminal.rows - 1;\n }\n // If the end of the line is hit, prevent this action from wrapping around to the next line.\n if (this._terminal.x >= this._terminal.cols) {\n this._terminal.x--;\n }\n }",
"restoreCursor(params) {\n this._terminal.x = this._terminal.savedX || 0;\n this._terminal.y = this._terminal.savedY || 0;\n }",
"function leaveRoom(){\n\tconsole.log(\"going to \" + player.currentDoor);\n\tgame.state.start(player.currentDoor);\n}",
"mouseLeave() {\n this.get('target').send(this.get('action'), this.get('name'), this.get('value'));\n }",
"leave(params) {\n\n // Select the channel to leave.\n let channel = this.find(params.topic)\n\n channel.leave(params.timeout)\n .receive(\"ok\", _ => this.leaveOk(params.topic) )\n }",
"leaveEntity(id) {\r\n\r\n // Pass on event to all plugins\r\n this.passEvent(\"leaveEntity\", id)\r\n\r\n }",
"function leaveRoom(deck, leaveRoom) {\n deck.splice(0, 4);\n \n deck = deck.concat(leaveRoom);\n console.log(leaveRoom)\n let newRoom = deck.slice(0,4);\n setData({\n ...data,\n deck: deck,\n room: newRoom,\n hasRan: true\n })\n }",
"_onLeaveButton() {\n this.dispatchEvent(new Event(this._leaveEvent));\n }",
"getCommandState(params) {\n let sel = params.selection\n let newState = {\n disabled: !sel.isPropertySelection(),\n active: false\n }\n return newState\n }",
"function sendLeft(callback){\n\n\t\taddCommands(Left,callback);\n\t\n\t}",
"onLeavingState(stateName) {\n \tdebug('Leaving state: ' + stateName);\n \tthis.clearPossible();\n }",
"function buttonLeaveHandler() {\n log('Leaving room...');\n activeRoom.disconnect();\n }",
"ProcessJoinChangeCommand() {\n var newYtLink = this.commandParameters[0];\n this.joinLink = newYtLink;\n var msg = 'Join audio changed to the link: ' + newYtLink;\n this.ReplyToMessage(msg);\n }",
"leavesPlay() {\n // If this is an attachment and is attached to another card, we need to remove all links between them\n if(this.parent && this.parent.attachments) {\n this.parent.removeAttachment(this);\n this.parent = null;\n }\n\n if(this.isParticipating()) {\n this.game.currentConflict.removeFromConflict(this);\n }\n\n if(this.isDishonored && !this.anyEffect(EffectNames.HonorStatusDoesNotAffectLeavePlay)) {\n this.game.addMessage('{0} loses 1 honor due to {1}\\'s personal honor', this.controller, this);\n this.game.openThenEventWindow(this.game.actions.loseHonor().getEvent(this.controller, this.game.getFrameworkContext()));\n } else if(this.isHonored && !this.anyEffect(EffectNames.HonorStatusDoesNotAffectLeavePlay)) {\n this.game.addMessage('{0} gains 1 honor due to {1}\\'s personal honor', this.controller, this);\n this.game.openThenEventWindow(this.game.actions.gainHonor().getEvent(this.controller, this.game.getFrameworkContext()));\n }\n\n this.makeOrdinary();\n this.bowed = false;\n this.covert = false;\n this.new = false;\n this.fate = 0;\n super.leavesPlay();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
push our new position to the positionContainer | pushPosition(position) {
this.positionContainer.push(position);
} | [
"updatePosContainerPositions() {\n const chart = this.chart;\n // If exporting, don't add these containers to the DOM.\n if (chart.renderer.forExport) {\n return;\n }\n const rendererSVGEl = chart.renderer.box;\n chart.container.insertBefore(this.afterChartProxyPosContainer, rendererSVGEl.nextSibling);\n chart.container.insertBefore(this.beforeChartProxyPosContainer, rendererSVGEl);\n unhideChartElementFromAT(this.chart, this.afterChartProxyPosContainer);\n unhideChartElementFromAT(this.chart, this.beforeChartProxyPosContainer);\n }",
"setPosition() {\n this._setWrapperPosition();\n this._setContentPosition();\n }",
"function pushPlacement() {\n\t\t\tplacements.push(point.matrixTransform(matrix));\n\t\t}",
"moveTo(position) {\n this.pos = position;\n }",
"setPosition (newPos)\n {\n if (newPos.length != 2)\n {\n console.log(\"Error\");\n return;\n }\n this.positions[this.pos_offset] = newPos[0];\n this.positions[this.pos_offset + 1] = newPos[1];\n }",
"addChild(pos) {\r\n this.children.push(pos);\r\n }",
"function _setPositions() {\r\n clones.forEach(function (draggable) { draggable.setPosition(); });\r\n }",
"changePosition() {\n if (this.draggingElOrder < this.targetElOrder) {\n // index of dragging element is smaller than entered element\n // dragging element insert after entered element\n this.targetEl.insertAdjacentElement('afterend', this.draggingEl);\n }\n else if (this.draggingElOrder > this.targetElOrder) {\n // index of dragging element is bigger than entered element\n // dragging element insert before entered element\n this.targetEl.insertAdjacentElement('beforebegin', this.draggingEl);\n }\n }",
"updatePosition() {\n const position = this.overlayRef.getConfig().positionStrategy;\n position.withPositions([\n POSITION_MAP[this.placement].position,\n ...DEFAULT_POPOVER_POSITIONS,\n ]);\n }",
"_positionChanged(position) {\n if (this.__entity !== undefined)\n this.__entity.setAttribute(\"position\", position);\n }",
"setNewPosition() {\r\n this.gravitySpeed += this.gravity;\r\n this.x += this.newPositionX;\r\n this.y += this.newPositionY + this.gravitySpeed;\r\n this.bottomBorder();\r\n this.topBorder();\r\n }",
"function recalculatePosition() {\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n scope.position.top += element.prop('offsetHeight');\n }",
"function recalculatePosition() {\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n scope.position.top += element.prop('offsetHeight');\n }",
"function updateContainerOnMove(mouseLoc){\n updateContainerSizeDate(mouseLoc);\n drawContainerShape(mouseLoc);\n}",
"updatePosition(position) \n {\n this.position = position;\n }",
"setPosition(x, y, type){\n let coordinate = x + \", \" + y;\n this.cards.push(new Card(x, y, this.numberOfCards, type));\n this.field.set(coordinate, this.numberOfCards);\n this.numberOfCards++;\n }",
"function recalculatePosition() {\n\t scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n\t scope.position.top += element.prop('offsetHeight');\n\t }",
"_updatePositionInParent(newPosition) {\n const element = this._elementRef.nativeElement;\n const parent = element.parentNode;\n if (newPosition === 'end') {\n if (!this._anchor) {\n this._anchor = this._doc.createComment('mat-drawer-anchor');\n parent.insertBefore(this._anchor, element);\n }\n parent.appendChild(element);\n } else if (this._anchor) {\n this._anchor.parentNode.insertBefore(element, this._anchor);\n }\n }",
"UpdatePosition()\n {\n this.position.x = this.parentOffset.x * this.parent.scale * this.parent.globalScale.scale + this.parent.position.x;\n this.position.y = this.parentOffset.y * this.parent.scale * this.parent.globalScale.scale + this.parent.position.y;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a path, which can be a directory or file, will return a located adapter path or will throw. | function resolveAdapterPath(inboundAdapterPath) {
var outboundAdapterPath = undefined;
// Try to open the provided path
try {
// If we're given a directory, append index.js
if (_fs2['default'].lstatSync(inboundAdapterPath).isDirectory()) {
// Modify the path and make sure the modified path exists
outboundAdapterPath = _path2['default'].join(inboundAdapterPath, 'index.js');
_fs2['default'].lstatSync(outboundAdapterPath);
} else {
// The file exists and is a file, so just return it
outboundAdapterPath = inboundAdapterPath;
}
return outboundAdapterPath;
} catch (err) {
throw err;
}
} | [
"function getCustomAdapter(projectRoot, adapterName)\n{\n let adapter, adapterFile;\n\n if (adapterName.match(path.sep))\n {\n try\n {\n return require(path.resolve(`${projectRoot}/${adapterName}`));\n }\n catch (e)\n {}\n }\n else\n {\n try\n {\n return require(adapterName);\n }\n catch (e)\n {}\n }\n}",
"function findAdapter(adapters, mediaType, method) {\n for (let i = 0; i < adapters.length; i += 1) {\n if (adapters[i].mediaTypes.indexOf(mediaType) !== -1 && adapters[i][method]) {\n return adapters[i];\n }\n }\n\n return null;\n}",
"function _findAdapter(adapters, mediaType, method) {\n for (var i = 0; i < adapters.length; i++) {\n if (adapters[i].mediaTypes.indexOf(mediaType) !== -1 && adapters[i][method]) {\n return adapters[i];\n }\n }\n}",
"function findAdapter(adapters, mediaType) {\n for (let i = 0; i < adapters.length; i++) {\n if (adapters[i].mediaTypes.indexOf(mediaType) !== -1) {\n return adapters[i];\n }\n }\n}",
"function implPath(path) {\n return _funcPath(false, path, implementations);\n }",
"function implPath(path) {\n return _funcPath (false, path, implementations);\n }",
"function resolvePath(path) {\n if (typeof path === 'string') {\n return path;\n }\n else {\n if (path.debug) {\n return path.debug;\n }\n else {\n return path.default;\n }\n }\n}",
"function determineDevicePath (path) {\n if (!path || path.indexOf('/sys/') !== 0) return path\n try {\n var files = fs.readdirSync(path)\n var device = _.find(files, startsWithUSB)\n return device ? '/dev/' + device : null\n } catch (e) {\n console.log('hub path not connected: ' + path)\n return null\n }\n}",
"function realPath(path) {\n var dir = Path.dirname(path);\n if (path === dir) {\n // is this an upper case drive letter?\n if (/^[A-Z]\\:\\\\$/.test(path)) {\n path = path.toLowerCase();\n }\n return path;\n }\n var name = Path.basename(path).toLowerCase();\n try {\n var entries = FS.readdirSync(dir);\n var found = entries.filter(function (e) { return e.toLowerCase() === name; }); // use a case insensitive search\n if (found.length === 1) {\n // on a case sensitive filesystem we cannot determine here, whether the file exists or not, hence we need the 'file exists' precondition\n var prefix = realPath(dir); // recurse\n if (prefix) {\n return Path.join(prefix, found[0]);\n }\n }\n else if (found.length > 1) {\n // must be a case sensitive $filesystem\n var ix = found.indexOf(name);\n if (ix >= 0) {\n var prefix = realPath(dir); // recurse\n if (prefix) {\n return Path.join(prefix, found[ix]);\n }\n }\n }\n }\n catch (error) {\n }\n return null;\n}",
"function find(name) {\n return adapters[name] || null;\n }",
"function getAdapter() {\n return internal.loader.adapter();\n }",
"function tryDirectory(path) {\n for (var f = 0; f < INFERRED_DIRECTORY_FILES.length; f++) {\n try {\n var file_path = cleanPath(path + '/' + INFERRED_DIRECTORY_FILES[f]);\n var file_string = __readFileSync(file_path);\n if (typeof file_string === 'string') {\n return file_path;\n }\n } catch(error) {\n continue;\n }\n }\n return null;\n }",
"function extensionFromPath(path) {\n var ext = tryGetExtensionFromPath(path);\n if (ext !== undefined) {\n return ext;\n }\n Debug.fail(\"File \" + path + \" has unknown extension.\");\n }",
"function getTestAdapterDir(adapterDir, testDir) {\n const adapterName = (0, adapterTools_1.getAdapterFullName)(adapterDir);\n return path.resolve(testDir, \"node_modules\", adapterName);\n}",
"function getDirectoryFromPath(path) {\n return path.substr(0, path.lastIndexOf(\"\\\\\"));\n}",
"function findItemByPath(path) {\n var trimmedPath = path.trim();\n var elementsInPath = trimmedPath.split(\"/\");\n if (elementsInPath[elementsInPath.length - 1] == \"\") {\n elementsInPath.pop();\n }\n var currentElement = null;\n if (elementsInPath.length > 0 && elementsInPath[0] == \"root\") {\n currentElement = fsStorage[0];\n } else {\n return null;\n }\n for (var i = 1; i < elementsInPath.length; i++) {\n currentElement = findChildByName(elementsInPath[i], currentElement);\n if (currentElement == null) {\n return null;\n }\n }\n return currentElement;\n }",
"getPackageFromPath(path) {\n const packageDirs = this.getPackageDirectories();\n const match = packageDirs.find((packageDir) => path_1.basename(path) === packageDir.name || path.includes(packageDir.fullPath));\n return match;\n }",
"localPath(path) {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {\n return coreutils_1.PathExt.removeSlash(path);\n }\n return coreutils_1.PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));\n }",
"function adapter(name) {\n // XXX: tmp lazy-load\n exports.model || (exports.model = require('tower-model'))\n return exports.collection[name] || (exports.collection[name] = new Adapter(name));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return object containing different Leaflet layers | function getLayers(options) {
var layers = {};
// Set layer types to return
// Defaults to return only `streets` layer
options = angular.merge({
streets: true,
satellite: false,
outdoors: false
}, options || {});
// Streets
if(options.streets && isMapboxAvailable && appSettings.mapbox.maps.streets) {
// Streets: Mapbox
layers.streets = getMapboxLayer(
'Streets',
'streets',
appSettings.mapbox.maps.streets
);
// Streets fallback
} else if(options.streets) {
// Streets: OpenStreetMap
layers.streets = {
name: 'Streets',
type: 'xyz',
url: '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
layerOptions: {
subdomains: ['a', 'b', 'c'],
attribution: '<a href="https://www.openstreetmap.org/" target="_blank">© OpenStreetMap</a> <a href="https://www.openstreetmap.org/login#map=' + location.zoom + '/' + location.lat + '/' + location.lng + '" target="_blank" class="improve-map">Improve the underlying map</a>',
continuousWorld: true,
TRStyle: 'streets' // Not native Leaflet key, required by our layer switch
}
};
}
// Satellite
if(options.satellite && isMapboxAvailable && appSettings.mapbox.maps.satellite) {
// Satellite: Mapbox
layers.satellite = getMapboxLayer(
'Satellite',
'satellite',
appSettings.mapbox.maps.satellite
);
}
// Satellite fallback
else if(options.satellite) {
// Satellite: MapQuest
layers.satellite = {
name: 'Satellite',
type: 'xyz',
url: '//otile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg',
layerOptions: {
subdomains: ['1', '2', '3', '4'],
attribution: '<a href="http://www.mapquest.com/" target="_blank">© MapQuest</a>',
continuousWorld: true,
TRStyle: 'satellite' // Not native Leaflet key, required by our layer switch
}
};
}
// Outdoors (without fallback)
if(options.outdoors && isMapboxAvailable && appSettings.mapbox.maps.outdoors) {
// Outdoors: Mapbox
layers.outdoors = getMapboxLayer(
'Outdoors',
'streets',
appSettings.mapbox.maps.outdoors
);
}
return layers;
} | [
"function buildLeafBaseLayers() {\n\n\t\t// Create the default layers\n\t\tstreetMapLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {\n\t\t\tattribution: 'Imagery from <a href=\"http://mapbox.com/about/maps/\">MapBox</a> — Map data © <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>',\n\t\t\tsubdomains: 'abcd',\n\t\t\tid: 'juzzbott.mn25f8nc',\n\t\t\taccessToken: 'pk.eyJ1IjoianV6emJvdHQiLCJhIjoiMDlmN2JlMzMxMWI2YmNmNGY2NjFkZGFiYTFiZWVmNTQifQ.iKlZsVrsih0VuiUCzLZ1Lg'\n\t\t});\n\n\t\ttopoMapLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {\n\t\t\tattribution: 'Imagery from <a href=\"http://mapbox.com/about/maps/\">MapBox</a> — Map data © <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>',\n\t\t\tsubdomains: 'abcd',\n\t\t\tid: 'juzzbott.mn24imf3',\n\t\t\taccessToken: 'pk.eyJ1IjoianV6emJvdHQiLCJhIjoiMDlmN2JlMzMxMWI2YmNmNGY2NjFkZGFiYTFiZWVmNTQifQ.iKlZsVrsih0VuiUCzLZ1Lg'\n\t\t});\n\n\t\taerialMapLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {\n\t\t\tattribution: 'Imagery from <a href=\"http://mapbox.com/about/maps/\">MapBox</a> — Map data © <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>',\n\t\t\tsubdomains: 'abcd',\n\t\t\tid: 'juzzbott.mn74md27',\n\t\t\taccessToken: 'pk.eyJ1IjoianV6emJvdHQiLCJhIjoiMDlmN2JlMzMxMWI2YmNmNGY2NjFkZGFiYTFiZWVmNTQifQ.iKlZsVrsih0VuiUCzLZ1Lg',\n\t\t\tmaxZoom: 17\n\t\t});\n\t}",
"buildLayers(traks) {\n // Re-generate the group of feature layers\n var grouped = this.groupBy(traks, 'geoId');\n var keys = Object.keys(grouped);\n var overlays = {};\n\n keys.forEach((key, index) => {\n let feats = grouped[key];\n let markers = [];\n feats.forEach((feat, index) => {\n // assemble the HTML for the markers' popups (Leaflet's bindPopup method doesn't accept React JSX)\n const popupContent = `<h6>${feat.geoId}</h6>\n ${feat.lat}, ${feat.long}`;\n let marker = this.pointToLayer(null, [feat.lat,feat.long]);\n marker.bindPopup(popupContent);\n markers.push(marker);\n });\n \n // Add the named FeatureGroup to the collection\n overlays[key] = L.featureGroup(markers);\n //overlays[key].addTo(this.mapRef.current);\n });\n\n return overlays;\n }",
"function getLayers(options) {\n\n var layers = {};\n\n // Set layer types to return\n // Defaults to return only `streets` layer\n options = angular.merge({\n streets: true,\n satellite: false,\n outdoors: false\n }, options || {});\n\n // Streets\n if (options.streets && isMapboxAvailable && appSettings.mapbox.maps.streets) {\n // Streets: Mapbox\n layers.streets = getMapboxLayer(\n 'Streets',\n 'streets',\n appSettings.mapbox.maps.streets\n );\n // Streets fallback\n } else if (options.streets) {\n // Streets: OpenStreetMap\n layers.streets = {\n name: 'Streets',\n type: 'xyz',\n url: '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n layerOptions: {\n subdomains: ['a', 'b', 'c'],\n attribution: '<a href=\"https://www.openstreetmap.org/\" target=\"_blank\">© OpenStreetMap</a> <a href=\"https://www.openstreetmap.org/login#map=' + location.zoom + '/' + location.lat + '/' + location.lng + '\" target=\"_blank\" class=\"improve-map\">Improve the underlying map</a>',\n continuousWorld: true,\n TRStyle: 'streets' // Not native Leaflet key, required by our layer switch\n }\n };\n }\n\n // Satellite\n if (options.satellite && isMapboxAvailable && appSettings.mapbox.maps.satellite) {\n // Satellite: Mapbox\n layers.satellite = getMapboxLayer(\n 'Satellite',\n 'satellite',\n appSettings.mapbox.maps.satellite\n );\n } else if (options.satellite) {\n // Satellite fallback: NASA Earth Data\n // @link https://earthdata.nasa.gov/about/science-system-description/eosdis-components/global-imagery-browse-services-gibs\n // @link https://github.com/nasa-gibs/gibs-web-examples/blob/release/examples/leaflet/webmercator-epsg3857.js\n layers.satellite = {\n name: 'Satellite',\n type: 'xyz',\n url: '//map1{s}.vis.earthdata.nasa.gov/wmts-webmerc/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.jpg',\n layerOptions: {\n layer: 'MODIS_Terra_CorrectedReflectance_TrueColor',\n tileMatrixSet: 'GoogleMapsCompatible_Level9',\n time: '2014-12-23',\n subdomains: ['a', 'b', 'c'],\n attribution: '<a href=\"https://wiki.earthdata.nasa.gov/display/GIBS\" target=\"_blank\">© NASA Earth Data</a>',\n noWrap: true,\n continuousWorld: true,\n tileSize: 256,\n // Prevent Leaflet from retrieving non-existent tiles on the borders\n bounds: [\n [-85.0511287776, -179.999999975],\n [85.0511287776, 179.999999975]\n ],\n TRStyle: 'satellite' // Not native Leaflet key, required by our layer switch\n }\n };\n }\n\n // Outdoors (without fallback)\n if (options.outdoors && isMapboxAvailable && appSettings.mapbox.maps.outdoors) {\n // Outdoors: Mapbox\n layers.outdoors = getMapboxLayer(\n 'Outdoors',\n 'streets',\n appSettings.mapbox.maps.outdoors\n );\n }\n\n return layers;\n }",
"createLayers() {\n // container defaults to document.body\n const layersContainer = this.container || window.document.body; // use config.layers or query elements from DOM\n\n this.layers = this.config.layers || [...layersContainer.querySelectorAll('[data-tilt-layer]')];\n this.layers = this.layers.map(layer => {\n let config; // if layer is an Element convert it to a TiltLayer object and augment it with data attributes\n\n if (layer instanceof Element) {\n config = Object.assign({\n el: layer\n }, layer.dataset);\n } else if (typeof layer == 'object' && layer) {\n config = layer;\n }\n\n return config; // discard garbage\n }).filter(x => x);\n }",
"function map_laodGeoserverLayers () {\n\n // Get GeoServer Layer\n var listGeoServerLayer = [];\n listGeoServerLayer = gs_getGeoserverLayers(\n geoServerProperties.getAddress(), \n geoServerProperties.getRepository(),\n mapProperties.getProjection(),\n mapProperties.getMaxFeatures(),\n map.getBounds()\n );\n\n // Add all GeoServer Layers\n for (var i = 0; i < listGeoServerLayer.length; i++) {\n mapLayers.push(listGeoServerLayer[i]);\n\n // Verification : if the layer is checked\n if (listGeoServerLayer[i].getCheck()) {\n\n // Get style\n var layerStyle = null;\n if (styleProperties.getLayerStyle(listGeoServerLayer[i].name)) {\n layerStyle = styleProperties.getLayerStyle(listGeoServerLayer[i].name);\n }\n\n // If style exists\n if (layerStyle !== null) {\n\n var currentZoomMap = map.getZoom();\n \n // Test zoom level\n if (currentZoomMap <= layerStyle.zoom_max \n && currentZoomMap >= layerStyle.zoom_min) {\n map.addLayer(listGeoServerLayer[i].getContent());\n }\n\n } else{\n map.addLayer(listGeoServerLayer[i].getContent());\n }\n\n }\n }\n\n}",
"function createLayerSwitcher() {\n // define basemap and add layer switcher control\n var basemaps = {\n \"National Geographic\": natGeo,\n \"NASA GIBS 2012 night\": nasaNight\n };\n L.control.layers(basemaps).addTo(map);\n }",
"static getLayers() {\n return fetch('/layers.json')\n .then(response => response.json())\n .then(layers => {\n return layers;\n });\n }",
"_getJSONLayers(jsonLayers) {\n return [\n new JSONLayer({\n data: jsonLayers,\n layerCatalog: this.layerCatalog\n })\n ];\n }",
"function fetchFeatureLayers () {\n map.spin(true, {lines:9, length:40, width:24,radius:60});\n requests = {};\n requests[\"request\"] = \"fetch_data_layers\";\n $.ajax({\n url: \"./include/geoserver_requests.php\",\n type: \"post\",\n data: requests,\n success: function(data) {\n data = $.parseJSON(data);\n var features = data['featureTypes']['featureType'];\n var layer_array = [];\n features.forEach(function(feature) {\n layer_array.push(feature['name']);\n })\n layer_array.sort();\n layer_array.forEach(function(feature) {\n // ****Separate floor layers from asset layer and added to basemap layers\n if (/floor/.test(feature)) {\n window[feature] = L.geoJSON(false, {onEachFeature: onEachFloorFeature});\n layerControl.addBaseLayer(window[feature], String(feature).upperFirstChar());\n fetchFloorFeatures(feature);\n // ****Floor01 is displayed by default\n if (feature=='floor01') {\n window[feature].addTo(map);\n }\n }\n });\n map.spin(false);\n }\n });\n }",
"function addMapLayers(layersArray) {\r\n var layers = {};\r\n $.each(layersArray, function(index, value) {\r\n if (value.wmsurl.indexOf(\"{x}\") != -1) {\r\n layers[value.name] = new L.TileLayer( value.wmsurl, value );\r\n }\r\n else {\r\n layers[value.name] = new L.TileLayer.WMS( value.wmsurl, value );\r\n }\r\n if ( value.isVisible ) map.addLayer(layers[value.name]);\r\n });\r\n return layers;\r\n}",
"function Layer(projection, proxy) {\n 'use strict';\n /**\n * interact stock a reference of the current interact of the map\n * @type {Interaction}\n */\n var interact = null;\n /**\n * ListLayers contains all Layers of the map\n * @type {Array}\n */\n this.ListLayers = [];\n /**\n * selectableLayers contains all selectable Layers of the map\n * @type {Array}\n */\n this.selectableLayers = [];\n\n /**\n * defaultWMTSResolutions store the resolution array if defaultbackground is a WMTS layer\n\t * @type {Array}\n */\t \n\tthis.defaultWMTSResolutions = [];\n\t\n /**\n * defaultBackground layer name \n\t * @type {string}\n */\t \n\tthis.defaultBackground = '';\n\t\n\tthis.setDefaultBackGround = function(layerName){\n\t\tthis.defaultBackground = layerName;\n\t};\t\n\t\n /**\n * featureLayerGis is the Feature Layer object\n * @type {Feature}\n */\t \n this.featureLayerGis = new Feature(projection, proxy);\n /**\n * rasterLayerGis is the Raster Layer object\n * @type {LayerRaster}\n */\n this.rasterLayerGis = new LayerRaster(projection, proxy);\n /**\n * Layer Method\n * getLayers is a getter to all Layers\n * @returns {Array} is an array with all data layers of the map\n */\n this.getLayers = function(){\n return this.ListLayers;\n };\n\n /**\n * Layer Method\n * getVisibleLayers is a getter to all layers and his visible value\n * @returns {Array} is an array with all layers and his visible value of the map\n */\n this.getVisibleLayers = function(){\n var ListVisibleLayers = [];\n var RasterLayer = this.getLayersRasterMap();\n var FeatureLayer = this.getLayersFeatureMap();\n for(var i = 0; i < RasterLayer.length; i++){\n ListVisibleLayers.push(\"'\"+RasterLayer[i].get('title')+\"'\");\n ListVisibleLayers.push(RasterLayer[i].getVisible());\n }\n for(var j = 0; j < FeatureLayer.length; j++){\n ListVisibleLayers.push(\"'\"+FeatureLayer[j].get('title')+\"'\");\n ListVisibleLayers.push(FeatureLayer[j].getVisible());\n }\n return ListVisibleLayers;\n };\n\n /**\n * Layer Method\n * getSelectedLayers is a getter to all selectable Layers\n * @returns {Array} is an array with all selectable layers of the map\n */\n this.getSelectableLayers = function(){\n return this.selectableLayers;\n };\n\n /**\n * Layer Method\n * getFeatureLayers is a getter to Feature Layer Object\n * @returns {Feature|*}\n */\n this.getFeatureLayers = function(){\n return this.featureLayerGis;\n };\n\n /**\n * Layer Method\n * getRasterLayers is a getter to Raster Layer Object\n * @returns {LayerRaster|*}\n */\n this.getRasterLayers = function(){\n return this.rasterLayerGis;\n };\n\n /**\n * Layer Method\n * setInteract is a setter to define the interact reference\n * @param newInteract\n */\n this.setInteract = function(newInteract){\n interact = newInteract;\n };\n\n /**\n * Layer Method\n * addLayerRaster add a background map at the ListLayer\n * @param backGround is an array with all parameters to define a background\n */\n this.addLayerRaster = function(backGround){\n var name = this.rasterLayerGis.createRasterLayer(backGround);\n this.ListLayers.push(name);\n };\n\n /**\n * Layer Method\n * addWMSLayerRaster add a background map at the ListLayer to a WMS\n * @param wms is an array with all parameters to define a wms layer\n */\n this.addWMSLayerRaster = function(wms){\n var wmsLibelle = wms[0];\n var wmsServer = wms[1];\n var wmsUrl = wms[2];\n var wmsLayer = wms[3];\n var wmsAttribution = wms[4];\n this.rasterLayerGis.createWMSLayer(wmsLibelle, wmsServer, wmsUrl, wmsLayer, wmsAttribution);\n this.ListLayers.push(wmsLibelle);\n };\n\n /**\n * Layer Method\n * addWMTSLayerRaster add a background map at the ListLayer to a WMTS\n * @param wmts is an array with all parameters to define a wmts layer\n */\n this.addWMTSLayerRaster = function(wmts){\n var wmtsLibelle = wmts[0];\n var wmtsServer = wmts[1];\n var wmtsUrl = wmts[2];\n var wmtsProj = wmts[3];\n var wmtsReso = wmts[4];\n var wmtsOrigin = wmts[5];\n var wmtsAttribution = wmts[6];\n\t\tvar isDefault = this.isDefaultBackGround(wmtsLibelle);\n\t\tvar wmtsResolutions = this.rasterLayerGis.createWMTSLayer(wmtsLibelle, wmtsServer, wmtsUrl, wmtsProj, wmtsReso, wmtsOrigin, wmtsAttribution, isDefault);\n\t\t//If DefaultBackground then get the resolutions to apply it to the view\n\t\tif(wmtsResolutions !== undefined && wmtsResolutions !== '' && isDefault){\n\t\t\tthis.setDefaultWMTSResolutions(wmtsResolutions);\n\t\t}\n\t\tthis.ListLayers.push(wmtsLibelle);\n };\n\n /**\n * Layer Method\n * addWMSQueryLayerRaster add a background map at the ListLayer to a WMS\n * @param wms is an array with all parameters to define a wms layer\n */\n this.addWMSQueryLayerRaster = function(wms){\n var wmsOrder = wms[0];\n var wmsName = wms[1];\n var wmsServer = wms[2];\n var wmsUrl = wms[3];\n var wmsLayer = wms[4];\n var wmsVisbility = wms[5];\n var wmsAttribution = wms[6];\n var wmsResoMin = wms[7];\n var wmsResoMax = wms[8];\n this.featureLayerGis.createWMSQueryLayer(wmsName, wmsServer, wmsUrl, wmsLayer, wmsVisbility, wmsAttribution, wmsResoMin, wmsResoMax);\n this.ListLayers.push(wmsOrder +'-'+ wmsName);\n };\n\n /**\n * Layer Method\n * addWFSLayer add a layer map at the ListLayer to a WFS\n * @param wfs is an array with all parameters to define a wfs layer\n * @param heatmap define the heatmap parameters\n * @param thematic define the thematic parameters\n * @param cluster define the cluster parameters\n * @param thematicComplex define the thematic complex parameters\n */\n this.addWFSLayer = function(wfs, heatmap, thematic, cluster, thematicComplex){\n var wfsIdLayer = wfs[0];\n var wfsServer = wfs[1];\n var wfsUrl = wfs[2];\n var wfsProj = wfs[3];\n var wfsQuery = wfs[4];\n var wfsAttribution = wfs[5];\n var wfsLayers = this.featureLayerGis.createWFSLayer(wfsIdLayer, wfsServer, wfsUrl, wfsProj, wfsQuery, wfsAttribution, heatmap, thematic, cluster, thematicComplex);\n for(var i = 0; i < wfsLayers.length; i++) {\n this.ListLayers.push(wfsLayers[i]);\n }\n };\n\n /**\n * Layer Method\n * addLayerVector add a layer map at the ListLayer\n * @param data is an array with all parameters to define a specific layer\n * @param format is the type of data\n * @param heatmap define the heatmap parameters\n * @param thematic define the thematic parameters\n * @param cluster define the cluster parameters\n * @param thematicComplex define the thematic complex parameters\n */\n this.addLayerVector = function(data, format, heatmap, thematic, cluster, thematicComplex){\n var names = this.featureLayerGis.addLayerFeature(data, format, heatmap, thematic, cluster, thematicComplex);\n for(var i = 0; i < names.length; i++) {\n this.ListLayers.push(names[i]);\n this.selectableLayers.push(names[i].split('-')[1]);\n }\n };\n\t\n\t/**\n * Layer Method\n * returns true if the given layerName is the defaultbackground\n * @param layerName is the name of a layer\n */\n\tthis.isDefaultBackGround = function(layerName){\n\t\treturn(layerName === this.defaultBackground);\n };\n\n\t/**\n\t* activateDefaultBackGround activates the default background to initiate the map\n\t*/\n\tthis.activateDefaultBackGround = function(){\n\t\tfor (var layerMap = 0; layerMap < this.ListLayers.length; layerMap++){\n if(this.ListLayers[layerMap] === this.defaultBackground) {\n if (this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap]) !== undefined){\n\t\t\t\t\tthis.rasterLayerGis.setRasterVisibility(this.ListLayers[layerMap], true);\n\t\t\t\t}\n }\n }\n\t};\n\t\n\t\n /**\n * Layer Method\n * getLayersRasterMap is a getter to all Rasters Layers\n * @returns {Array} is an array with all raster layers of the map\n */\n this.getLayersRasterMap = function(){\n var ListLayersRasterMap = [];\n for (var layerMap = 0; layerMap < this.ListLayers.length; layerMap++){\n if(this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap])!== undefined) {\n ListLayersRasterMap.push(this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap]));\n }\n }\n return ListLayersRasterMap;\n };\n\n /**\n * Layer Method\n * getLayersFeatureMap is a getter to all Features Layers\n * @returns {Array} is an array with all feature layers of the map\n */\n this.getLayersFeatureMap = function(){\n var ListLayersFeatureMap = [];\n for (var layerMap = this.ListLayers.length-1; layerMap >= 0; layerMap--){\n var layerMapName = this.ListLayers[layerMap].split('-')[1];\n if(this.featureLayerGis.getFeatureByName(layerMapName)!== undefined) {\n ListLayersFeatureMap.push(this.featureLayerGis.getFeatureByName(layerMapName));\n }\n }\n return ListLayersFeatureMap;\n };\n\n /**\n * Layer Method\n * getLayersMap is a getter to all Layers in groups\n * @returns {Array} is an array with all data layers in groups\n */\n this.getLayersMap = function(){\n var ListLayersMap = [];\n this.ListLayers.sort();\n ListLayersMap.push(new ol.layer.Group({\n title:'Fonds de plan',\n layers: this.getLayersRasterMap()\n }));\n ListLayersMap.push(new ol.layer.Group({\n title:'Couches',\n layers: this.getLayersFeatureMap()\n }));\n ListLayersMap.push(interact.getDraw().getDrawLayer());\n ListLayersMap.push(interact.getMeasure().getMeasureLayer());\n if(interact.getEditor() !== null){\n ListLayersMap.push(interact.getEditor().getEditLayer());\n }\n return ListLayersMap;\n };\n\n /**\n * Layer Method\n * showLayer enable or disable a visibility of a layer\n * @param layerName the name of the layer\n * @param visible the indicator of visibility\n */\n this.showLayer = function(layerName, visible){\n if(this.rasterLayerGis.getRasterByName(layerName)!== undefined) {\n this.rasterLayerGis.getRasterByName(layerName).setVisible(visible);\n }\n if(this.featureLayerGis.getFeatureByName(layerName)!== undefined) {\n this.featureLayerGis.getFeatureByName(layerName).setVisible(visible);\n }\n };\n\t\n\tthis.setDefaultWMTSResolutions = function(WMTSResolutions) {\n\t\tthis.defaultWMTSResolutions = WMTSResolutions;\n\t};\n\t\n\tthis.getDefaultWMTSResolutions = function() {\n\t\treturn this.defaultWMTSResolutions;\n\t};\n}",
"function addMapLayers(layersArray) {\r\n var layers = {};\r\n $.each(layersArray, function(index, value) {\r\n if (value.wmsurl.indexOf(\"{x}\") != -1) {\r\n layers[value.name] = new L.TileLayer(value.wmsurl, value);\r\n } else {\r\n layers[value.name] = new L.TileLayer.WMS(value.wmsurl, value);\r\n }\r\n if (value.isVisible) map.addLayer(layers[value.name]);\r\n });\r\n return layers;\r\n}",
"_newLayer() { return L.layerGroup(); }",
"static create(target = 'mapdiv') {\n let map = new OLMap({\n target,\n controls: [\n new ZoomSlider(),\n new LayerSwitcher({\n reverse: true,\n groupSelectStyle: 'group'\n })\n ],\n layers: [\n new TileLayer({\n title: 'OSM',\n type: 'base',\n visible: false,\n source: new XYZ({\n url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'\n })\n }),\n new TileLayer({\n title: 'Satellit',\n type: 'base',\n visible: true,\n source: new XYZ({\n url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n maxZoom: 19\n })\n }),\n new TileLayer({\n title: 'Strassenkarte',\n type: 'base',\n visible: false,\n source: new XYZ({\n url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',\n maxZoom: 20\n })\n }),\n new TileLayer({\n title: 'Topographie',\n type: 'base',\n visible: false,\n source: new XYZ({\n url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',\n maxZoom: 20\n })\n }),\n new TileLayer({\n title: 'National Geographic',\n type: 'base',\n visible: false,\n source: new XYZ({\n url: 'http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}',\n maxZoom: 12\n })\n })\n ],\n view: new View({\n center: transform([7.454281, 46.96453], 'EPSG:4326', 'EPSG:3857'),\n zoom: 11,\n minZoom: 3,\n maxZoom: 20,\n extent: TransformCoordinates([5.9962, 45.8389, 10.5226, 47.8229])\n })\n });\n map.addInteraction(new Link({ animate: true, prefix: 'm' }));\n\n return map;\n }",
"function get_overlay_layer () {\n var geojsonData = get_basefeatures_overlay();\n return L.geoJSON(geojsonData, {\n onEachFeature: onEachFeature,\n pointToLayer: pointToLayer,\n style: styleProps,\n })\n}",
"function createLeafletTiles() {\n // Mapbox\n tiles[0] = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n className: 'saturation',\n tileSize: 512,\n zoomOffset: -1,\n id: 'mapbox/streets-v11',\n }).addTo(map);\n\n // OpenStreetMap Swiss Style\n tiles[1] = L.tileLayer('http://tile.osm.ch/osm-swiss-style/{z}/{x}/{y}.png', {\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n className: 'saturation',\n });\n\n // OpenTopoMap\n tiles[2] = L.tileLayer('https://opentopomap.org/{z}/{x}/{y}.png', {\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n className: 'saturation',\n });\n\n // ArcGIS Satellite\n tiles[3] = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {\n minZoom: MIN_ZOOM,\n maxZoom: MAX_ZOOM,\n className: 'saturation',\n });\n}",
"function addMapLayers2(){\n\t\t\t// 3-21-22 use layer.on(\"load\") and layer.on(\"error\") to make sure layers have loaded\n\n\t\t\t// Create Layer 3-21-22\n\t\t\t// Get layers from url of config.xml\n\t\t\tfunction createLayer(layer){\n\t\t\t\tvar id = layer.getAttribute(\"label\");\n\t\t\t\tvar myLayer;\n\t\t\t\ttries[id]++;\n\t\t\t\t// Set layer properties on startup if specified on url\n\t\t\t\tif (queryObj.layer && queryObj.layer != \"\") {\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1) {\n\t\t\t\t\t\tif (layerObj[id]){\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": layerObj[id].opacity,\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\": layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t// not found on url, not visible\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// FeatureServer tlb 10/19/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layerObj[id]) \n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\" : layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\" : layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t// Set layer properties from config.xml file\n\t\t\t\t} else {\n\t\t\t\t\t// MapServer\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t} \n\t\t\t\t\t// FeatureServer tlb 9/28/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// 3-21-22 check if loaded\n\t\t\t\tmyLayer.on(\"load\", layerLoadedHandler);\n\t\t\t\tmyLayer.on(\"error\", layerLoadFailedHandler);\n\t\t\t}\n\n\t\t\t// If layer loaded add to legend and map 3-21-22\n\t\t\tfunction layerLoadedHandler(event){\n\t\t\t\ttry{\n\t\t\t\t\tvar collapsedFlg;\n\t\t\t\t\tvar openSubLayers = [];\n\t\t\t\t\tvar layer;\n\t\t\t\t\t// search for layer in xmlDoc\n\t\t\t\t\tfor (var i=0;i<xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\").length;i++){\n\t\t\t\t\t\tif (event.layer.id === xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\")[i].getAttribute(\"label\")) {\n\t\t\t\t\t\t\tlayer = xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\")[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// layer from config.xml\n\t\t\t\t\tif (loadedFromCfg) {\n\t\t\t\t\t\tcollapsedFlg = false;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (layer.getAttribute(\"open\") == \"false\")\n\t\t\t\t\t\t\tcollapsedFlg = true;\n\t\t\t\t\t\tvar oslArr = layer.getAttribute(\"opensublayer\");\n\t\t\t\t\t\tif (oslArr)\n\t\t\t\t\t\t\topenSubLayers = oslArr.split(\",\");\n\t\t\t\t\t\toslArr = null;\n\t\t\t\t\t}\n\t\t\t\t\t// layer from &map or &layer on url\n\t\t\t\t\telse {\n\t\t\t\t\t\tcollapsedFlg = true;\n\t\t\t\t\t\tif (event.layer.visible)\n\t\t\t\t\t\t\tcollapsedFlg = false;\n\t\t\t\t\t\tvar num = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);\n\t\t\t\t\t\tvar j;\n\t\t\t\t\t\tvar layerInfos = [];\n\t\t\t\t\t\t// Set gmu = elk, bighorn, or goat based on what was on url\t\n\t\t\t\t\t\tif (layerObj[event.layer.id]) {\n\t\t\t\t\t\t\tlayerInfos = event.layer.layerInfos;\n\t\t\t\t\t\t\t// See what gmu is turned on\t\t \n\t\t\t\t\t\t\tif (event.layer.id == \"Hunter Reference\") {\n\t\t\t\t\t\t\t\tfor (j = 0; j < layerObj[event.layer.id].visLayers.length; j++) {\n\t\t\t\t\t\t\t\t\tif (layerInfos[layerObj[event.layer.id].visLayers[j]].name.substr(layerInfos[layerObj[event.layer.id].visLayers[j]].name.length - 3, 3).indexOf(\"GMU\") > -1) {\n\t\t\t\t\t\t\t\t\t\tgmu = layerInfos[layerObj[event.layer.id].visLayers[j]].name;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// if gmu was not visible but a game species was selected then set gmu\n\t\t\t\t\t\t\t} else if (event.layer.id == \"Game Species\") {\n\t\t\t\t\t\t\t\tfor (j = 0; j < layerObj[event.layer.id].visLayers.length; j++) {\n\t\t\t\t\t\t\t\t\tif (layerInfos[layerObj[event.layer.id].visLayers[j]].name === \"Bighorn Sheep\") {\n\t\t\t\t\t\t\t\t\t\tgmu = \"Bighorn GMU\";\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t} else if (layerInfos[layerObj[event.layer.id].visLayers[j]].name === \"Mountain Goat\") {\n\t\t\t\t\t\t\t\t\t\tgmu = \"Goat GMU\";\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Set default visibility\n\t\t\t\t\t\t\tfor (j = 0; j < layerInfos.length; j++) {\n\t\t\t\t\t\t\t\t// If layer is found in the visLayers make it visible.\n\t\t\t\t\t\t\t\tif (layerObj[event.layer.id].visLayers.indexOf(layerInfos[j].id) != -1)\n\t\t\t\t\t\t\t\t\tlayerInfos[j].defaultVisibility = true;\n\t\t\t\t\t\t\t\t// Else if this is not the top layer and it has no sub-layers set default visibility\n\t\t\t\t\t\t\t\telse if (layerInfos[j].parentLayerId != -1 && !layerInfos[j].subLayerIds) {\n\t\t\t\t\t\t\t\t\t// if this is a gmu layer make sure it is the one that was turned on in visLayers\n\t\t\t\t\t\t\t\t\tif (layerInfos[j].name.substr(layerInfos[j].name.length - 3, 3).indexOf(\"GMU\") > -1) {\n\t\t\t\t\t\t\t\t\t\t// handle this later below when all layers have loaded. Need to wait for Game Species to load. If GMU layer is not set was not working.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// use the default value for sub menu item layers that are under a menu item that is unchecked\n\t\t\t\t\t\t\t\t\telse if ((layerInfos[j].defaultVisibility == true) && (layerObj[event.layer.id].visLayers.indexOf(layerInfos[j].parentLayerId) === -1)) {\n\t\t\t\t\t\t\t\t\t\tlayerObj[event.layer.id].visLayers.push(j);\n\t\t\t\t\t\t\t\t\t\t// If by default it is visible see if the name of the parent is a number (varies with extent) and make it visible also\n\t\t\t\t\t\t\t\t\t\tif (num.indexOf(parseInt(layerInfos[layerInfos[j].parentLayerId].name.substr(0, 1))) > -1) {\n\t\t\t\t\t\t\t\t\t\t\tlayerObj[event.layer.id].visLayers.push(layerInfos[j].parentLayerId);\n\t\t\t\t\t\t\t\t\t\t\tlayerInfos[layerInfos[j].parentLayerId].defaultVisibility = true;\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// Else this is a top level toc menu item and not found in the visible list, make it not visible.\n\t\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\t\tlayerInfos[j].defaultVisibility = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tevent.layer.setVisibleLayers(layerObj[event.layer.id].visLayers.sort(function (a, b) {\n\t\t\t\t\t\t\t\treturn a - b;\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tevent.layer.refresh();\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\n\t\t\t\t\tlegendLayers.push({\n\t\t\t\t\t\tlayer: event.layer,\n\t\t\t\t\t\ttitle: event.layer.id,\n\t\t\t\t\t\tautoToggle: true, // If true, closes the group when unchecked and opens the group when checked. If false does nothing.\n\t\t\t\t\t\tslider: true, // whether to display a transparency slider\n\t\t\t\t\t\tslider_ticks: 3,\n\t\t\t\t\t\tslider_labels: [\"transparent\", \"50%\", \"opaque\"],\n\t\t\t\t\t\thideGroupSublayers: hideGroupSublayers,\n\t\t\t\t\t\tradioLayers: radioLayers,\n\t\t\t\t\t\tnoLegend: false,\n\t\t\t\t\t\topenSubLayers: openSubLayers,\n\t\t\t\t\t\tcollapsed: collapsedFlg // whether this root layer should be collapsed initially, default false. \n\t\t\t\t\t});\n//console.log(\"add layer to map \"+event.layer.id);\n\t\t\t\t\tmap.addLayer(event.layer);\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\topenSubLayers = null;\n\t\t\t\t} catch (e) {\n\t\t\t\t\talert(\"Error in readConfig.js/layerLoadedHandler \" + e.message, \"Code Error\", e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction layerLoadFailedHandler(event){\n\t\t\t\t// Layer failed to load 3-21-22\n\t\t\t\t// Wait 2 seconds, retry up to 5 times, then report the error and continue trying every 30 seconds\n\t\t\t\t// 3-10-22 NOTE: MVUM is sometimes missing some of the sublayers. Contacted victoria.smith-campbell@usda.gov\n\t\t\t\t// at USFS and they restarted one of their map services and it fixed the problem.\n//console.log(event.target.id+\" failed to load!!!!!!!\");\n//console.log(\"tries=\"+tries[event.target.id]);\n\t\t\t\tvar layer;\n\t\t\t\tfor(var i=0;i<xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\").length;i++){\n\t\t\t\t\tif (xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\")[i].getAttribute(\"label\") === event.target.id){\n\t\t\t\t\t\tlayer = xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\")[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Try every 2 seconds for up to 5 times \n\t\t\t\tif (tries[event.target.id] < 5){\n\t\t\t\t\tsetTimeout(function(){createLayer(layer);},2000);\n\t\t\t\t} \n\t\t\t\t// Greater than 5 tries, give warning\n\t\t\t\telse if (tries[event.target.id] == 5){\n\t\t\t\t\tif (event.target.id.indexOf(\"Motor Vehicle\") > -1 || event.target.id.indexOf(\"Wildfire\") > -1 || event.target.id.indexOf(\"BLM\") > -1)\n\t\t\t\t\t\talert(\"The external map service that provides \"+event.target.id+\" is experiencing problems. This issue is out of CPW control. We will continue to try to load it. We apologize for any inconvenience.\",\"External (Non-CPW) Map Service Error\");\n\t\t\t\t\telse\n\t\t\t\t\t\talert(event.target.id+\" service is busy or not responding. We will continue to try to load it.\",\"Data Error\");\n\t\t\t\t\tsetTimeout(function(){createLayer(layer);},30000);\n\t\t\t\t}\n\t\t\t\t// Greater than 5 tries. Keep trying every 30 seconds\n\t\t\t\telse {\n//DEBUG\n//console.log(\"Retrying to load: \"+event.target.id);\n//if(event.target.id.indexOf(\"Hunter Reference\")>-1)\n//layer.setAttribute(\"url\",\"https://ndismaps.nrel.colostate.edu/ArcGIS/rest/services/HuntingAtlas/HuntingAtlas_Base_Map/MapServer\");\n//if(event.target.id.indexOf(\"Game Species\")>-1)\n//layer.setAttribute(\"url\",\"https://ndismaps.nrel.colostate.edu/ArcGIS/rest/services/HuntingAtlas/HuntingAtlas_BigGame_Map/MapServer\");\n//if(event.target.id.indexOf(\"Motor Vehicle\")>-1)\n//layer.setAttribute(\"url\",\"https://apps.fs.usda.gov/arcx/rest/services/EDW/EDW_MVUM_02/MapServer\");\n//console.log(\"url=\"+layer.getAttribute(\"url\"));\n\t\t\t\t\tsetTimeout(function(){createLayer(layer);},30000);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//-----------\n\t\t\t// Variables\n\t\t\t//-----------\n\t\t\tloadedFromCfg = true; // the layer is loaded from config.xml. If false loaded from url &layers.\n\n\t\t\t// Store layers from URL into layerObj\n\t\t\t// \t\t&layer= basemap | id | opacity | visible layers , id | opacity | visible layers , repeat...\n\t\t\t// \t\t&layer= streets|layer2|.8|3-5-12,layer3|.65|2-6-10-12\n\t\t\t// \t\tget array of layers without the basemap stuff;\n\t\t\tif (queryObj.layer && queryObj.layer != \"\") {\n\t\t\t\tloadedFromCfg = false; // the layer is loaded from config.xml. If false loaded from url &layers.\n\t\t\t\tvar layersArr = queryObj.layer.substring(queryObj.layer.indexOf(\"|\") + 1).split(\",\");\n\t\t\t\tlayerObj = {};\n\t\t\t\t//if (layersArr.length == 1) layersArr.pop(); // remove empty element if no layers are visible\n\t\t\t\tfor (i = 0; i < layersArr.length; i++) {\n\t\t\t\t\t// build an array of objects indexed by layer id\n\t\t\t\t\tvar layerArr = layersArr[i].split(\"|\");\n\t\t\t\t\tif (layerArr[0] == \"\") continue;// tlb 1-5-18 if no layers are visible \n\t\t\t\t\tlayerArr[0] = layerArr[0].replace(/~/g, \" \");\n\t\t\t\t\tif (layerArr.length == 3)\n\t\t\t\t\t\tlayerArr.push(true);\n\t\t\t\t\tif (layerArr[2] == -1)\n\t\t\t\t\t\tlayerObj[layerArr[0]] = {\n\t\t\t\t\t\t\t\"opacity\": layerArr[1],\n\t\t\t\t\t\t\t\"visLayers\": [], // tlb 1-5-18 used to be [-1],\n\t\t\t\t\t\t\t\"visible\": true\n\t\t\t\t\t\t};\n\t\t\t\t\telse\n\t\t\t\t\t\tlayerObj[layerArr[0]] = {\n\t\t\t\t\t\t\t\"opacity\": layerArr[1],\n\t\t\t\t\t\t\t\"visLayers\": layerArr[2].split(\"-\"),\n\t\t\t\t\t\t\t\"visible\": layerArr[3] == \"1\" ? true : false\n\t\t\t\t\t\t};\n\t\t\t\t\t// Convert visLayers from strings to int using bitwise conversion\n\t\t\t\t\tfor (j = 0; j < layerObj[layerArr[0]].visLayers.length; j++)\n\t\t\t\t\t\tlayerObj[layerArr[0]].visLayers[j] = layerObj[layerArr[0]].visLayers[j] | 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// ---------------------------------------------------\n\t\t\t// Load each Layer from config.xml operationallayers\n\t\t\t// ---------------------------------------------------\n\t\t\tvar layer = xmlDoc.getElementsByTagName(\"operationallayers\")[0].getElementsByTagName(\"layer\");\n// DEBUG: make if fail\n//layer[0].setAttribute(\"url\",\"https://ndismaps.nrel.colostate.edu/ArcGIS/rest/services/HuntingAtlas/HuntingAtlas_Base_Map2/MapServer\");\n//layer[1].setAttribute(\"url\",\"https://ndismaps.nrel.colostate.edu/ArcGIS/rest/services/HuntingAtlas/HuntingAtlas_BigGame_Map2/MapServer\");\n//layer[2].setAttribute(\"url\",\"https://apps.fs.usda.gov/arcx/rest/services/EDW/EDW_MVUM_03/MapServer\");\n\t\t\tfor (i = 0; i < layer.length; i++) {\n\t\t\t\ttries[layer[i].getAttribute(\"label\")] = 0;\t\t\t\t\n\t\t\t\tcreateLayer(layer[i]);\t\t\t\n\t\t\t}\n\t\t}",
"function getLayers() {\n var objects = document.activecanvas.getObjects();\n var layers = \"\";\n for (var object in objects) {\n var index = objects.length - object - 1;\n object = objects[index];\n var value;\n if (object.type == \"i-text\") value = object.text;\n else if (object.type == \"image\") value = object.width + \" x \" + object.height;\n else value = \" <span class=\\\"layercolor\\\" style=\\\"background: \"+object.fill+\"; border: 3px solid \"+(object.stroke || \"transparent\")+\"\\\"></span>\";\n if (object == document.activecanvas.getActiveObject())\n var li = \"<li class=\\\"active\\\">\"\n else\n var li = \"<li>\"\n layers += li;\n layers += \"<span onclick=\\\"toggleVisible(\"+index+\",'set')\\\">\"+toggleVisible(index,'get')+\"</span>\";\n layers += \"<label onclick=\\\"layerOps(\"+index+\")\\\">\" + object.type + \" - \" + value + \"</label>\";\n layers += \"<div class=\\\"moveLayer\\\">\";\n layers += \"<a class=\\\"down\\\" onclick=\\\"moveBack(\"+index+\")\\\">▴</a>\";\n layers += \"<a class=\\\"up\\\" onclick=\\\"moveFront(\"+index+\")\\\">▴</a>\";\n layers += \"</div>\\n\";\n }\n $(\"#layers\").html(\"<span>Layers on this side:</span>\"+layers);\n }",
"function getLayerLeaflet(layerID) {\r\n var theLayer = null;\r\n $.each(map._layers, function(index, val){\r\n if (val.options.id == layerID ) theLayer = index;\r\n });\r\n return theLayer;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Variablelength FizzBuzz with arrays: Write a function which prints out the numbers mn with substitutions of: each element of the numbers array replaced by the element at the same index of the terms array. e.g., to mimic the behavior of fizzBuzz1, you would call the function like so: fizzBuzz4(1,100,[3,5],['fizz','buzz']) Validation the m <= n is a plus. The arrays may have any length, but validation that their length is the SAME is a plus. | function fizzBuzz4(m,n,numbers,terms){
} | [
"function superFizzBuzz(array){\n for (var i = 0 ; i < array.length; i++){\n if (array[i] % 15 === 0 ){\n array[i] = \"FizzBuzz\"; }\n else if (array[i] % 5 === 0 ){\n array[i] = \"Buzz\"; }\n else if(array[i] % 3 === 0 ){\n array[i] = \"Fizz\"; }\n else {\n array[i];\n };\n };\n return array\n}",
"function preFizz(n) {\nlet newArray=[];\nfor (let i=1; i<=n;i++){\n newArray.push(i)\n\n}\nreturn (`[${newArray}], Array should be from 1 to ${n}`)\n}",
"function fizzBuzz(n) {\nlet arr = new Array(n)\narr.fill('', 0, n)\nreturn arr.map((x, i) => {\n if (i % 3 === 0 && i % 5 === 0)\n return 'fizzbuzz'\n if (i % 3 === 0)\n return 'fizz'\n if (i % 5 === 0)\n return 'buzz'\n return ''\n }\n)\n}",
"function fizzBuzz4(m,n,numbers,terms){\n if (isNaN(Number(m)) || isNaN(Number(n)) || m > n){\n console.log('invalid input');\n return;}\n let output = \"\";\n for(i = m; i < n; i++){\n for(let j in numbers){\n if(i % numbers[j] === 0){\n output += terms[j];\n }\n } \n if (output){\n console.log(output);\n } else {\n console.log(i);\n }\n output = \"\";\n }\n}",
"function fizzBuzz(number) {\n var i;\n var array = [];\n if(number>1){\n for(i = 1; i<=number; i++) {\n array[i-1] = i;\n if(array[i-1]%3 == 0 && array[i-1]%5 == 0) {\n array[i-1] = \"FizzBuzz\";\n }\n else if(array[i-1]%3 == 0) {\n array[i-1] = \"Fizz\";\n }\n else if(array[i-1]%5 == 0) {\n array[i-1] = \"Buzz\";\n }\n }\n }\n return array;\n }",
"function fizzBuzz(array) {\n let result = []; // Fizz, Buzz, FizzBuzz, Buzz, Fizz, 7\n\n for (let i = 0; i < array.length; i++) {\n let num = array[i];\n console.log(num); // 3, 5, 15....\n\n if (num % 3 === 0 && num % 5 === 0) {\n result.push(\"FizzBuzz\");\n } else if (num % 3 === 0) {\n result.push(\"Fizz\");\n } else if (num % 5 === 0) {\n result.push(\"Buzz\");\n } else {\n result.push(num);\n }\n }\n\n return result;\n}",
"function fizzBuzz(number) {\n let array = [];\n for (let i = 1; i <= number; i++) {\n if (i % 3 == 0 && i % 5 == 0) {\n array[i] = \"FizzBuzz\";\n } else if (i % 5 == 0) {\n array[i] = \"Buzz\";\n } else if (i % 3 == 0) {\n array[i] = \"Fizz\";\n } else {\n array[i] = i;\n }\n }\n return array.slice(1, array.length + 1);\n}",
"function fizzbuzz(){\r\n var myArr=[];\r\n for(i=0; i<=100; i++){\r\n myArr.push(i);\r\n \r\n if (myArr[i] % 3===0 && myArr[i] % 5===0){\r\n myArr[i] = 'fizzbuzz';\r\n \r\n }\r\n \r\n else if( myArr[i] % 3===0) {\r\n myArr[i] = 'fizz'; \r\n }\r\n\r\n \r\n \r\n }\r\n \r\n \r\n}",
"function fizzBuzz3(m,n,fizzNum,buzzNum){\n\n}",
"function fillArray(){\n \nvar arr = [];\n for(i=1;i<n;i++){\n if(i%3==0 && i%5==0){\n arr.push(\"fizzbuzz\");\n }\n } else if(i%3==0){\n arr.push(\"fizz\")\n }\n else if (i%5==0){\n arr.push(\"buzz\")\n } else arr.push(i)\n}",
"function FizzBuzz(num) {\n let strArr = [];\n for (let i = 1; i <= num; i++) {\n if (i % 3 === 0 && i % 5 === 0) {\n strArr.push(\"FizzBuzz\");\n } else if (i % 3 === 0) {\n strArr.push(\"Fizz\");\n } else if (i % 5 === 0) {\n strArr.push(\"Buzz\");\n } else {\n strArr.push(i);\n }\n }\n return strArr.join(\" \");\n}",
"function fizzbuzz_3(arr) {\n\t\tfor (i = 0; i < arr.length; i++) {\n\t\t\tif ( (arr[i] % 3 === 0) && (arr[i] % 5 === 0)) {\n\t\t\t\toutput = \"FizzBuzz\";\n\t\t\t}\n\t\t\telse if (arr[i] % 3 === 0) {\n\t\t\t\toutput = \"Fizz\";\n\t\t\t}\n\t\t\telse if (arr[i] % 5 === 0) {\n\t\t\t\toutput = \"Buzz\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\toutput = arr[i];\n\t\t\t}\n\n\t\t\t$(\"#fizzbuzz3\").append(\"<li>\" + output + \"</li>\");\n\t\t}\n\t}",
"function fizzBuzz(numInput) {\n var array = [];\n \n if (numInput <= 1) {\n return array;\n }\n \n for (let i = 1; i <= numInput; i++) {\n if (i % 3 == 0 && i % 5 == 0) {\n array.push(\"FizzBuzz\");\n } else if (i % 5 == 0) {\n array.push(\"Buzz\");\n } else if (i % 3 == 0) {\n array.push(\"Fizz\");\n } \n else {\n array.push(i);\n }\n }\n return array;\n }",
"function fizzBuzz(numberOfTimes){\n\tvar fizzArray = [];\n\tfor (var i = 0; i <= numberOfTimes; i++) \n\t{\n\t\tif((i % 3 === 0) && (i % 5 === 0))\n\t\t{\n\t\t\tfizzArray.push(\"FizzBuzz\");\n\t\t}\n\t\telse if (i % 3 === 0) \n\t\t{\n\t\t\tfizzArray.push(\"Fizz\");\n\t\t}\n\t\telse if (i % 5 === 0)\n\t\t{\n\t\t\tfizzArray.push(\"Buzz\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfizzArray.push(i);\n\t\t}\n\t}\n return fizzArray;\n}",
"function fizzBuzz() {\n var result = [];\n for (var i = 1; i <= 20; i++){\n if(i % 15 === 0){\n result.push(\"fizzbuzz\");\n } else if (i % 3 === 0) {\n result.push(\"fizz\");\n } else if (i % 5 === 0) {\n result.push(\"buzz\");\n } else {\n result.push(i);\n }\n }\n return result;\n}",
"function fizzBuzz(array){\n let result = [];\n\n for(let i = 0; i < array.length; i++){\n let num = array[i];\n console.log(num)\n\n if(num % 3 === 0 && num % 5 === 0){\n result.push(\"Fizzbuzz\");\n } else if(num % 3 === 0){\n result.push(\"fizz\");\n }else if(num % 5 === 0){\n result.push(\"buzz\");\n }else{\n result.push(num);\n }\n return result;\n\n \n }\n console.log(fizzBuzz([3,5,15,20,9,7]));\n }",
"function fizzBuzz() {\r\n\r\n let output = \"\";//initialize empty string\r\n for (let i = 1; i <= 100; i++){\r\n //get multiples of 3's\r\n if (i % 3 === 0){\r\n output = output.concat(\"Fizz \");\r\n }\r\n //get multiples of 5's\r\n if (i % 5 === 0){\r\n output = output.concat(\"Buzz \");\r\n }\r\n //If the other numbrs are not multiple of 3's or 5's\r\n if (i % 3 != 0 && i % 5 != 0){\r\n output = output.concat(i.toString());\r\n }\r\n output = output.concat(\" \");\r\n }\r\n console.log(output);\r\n\r\n}",
"function substitute(arg){\r\n let mapped = [];\r\n let i = 0;\r\n mapArray(arg, function (el) {\r\n if (el > 30) {\r\n mapped[i] = el;\r\n } else {\r\n mapped[i] = '*';\r\n }\r\n i++;\r\n });\r\n return mapped;\r\n}",
"function fizzbuzz(num) {//done\n let result = [];\n for (let i = 1; i<=num; i++) {\n if (i%3===0 && i%5===0) {\n result.push('fizzbuzz')\n } else if (i%3===0) {\n result.push(\"fizz\")\n } else if (i%5===0) {\n result.push(\"buzz\")\n } else {\n result.push(i)\n }\n }\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
===== Mobile marker menu ===== | function showMarkerMenu() {
state.set({
marker_menu_open: true
});
} | [
"function markerMenu(event, ATMId) {\n var x = event.pageX;\n var y = event.pageY;\n $(\"#defaultMarkerMenu\").attr(\"atmid\", ATMId);\n $(\"#defaultMarkerMenu\")\n .css({top: y + \"px\", left: x + \"px\"})\n .show();\n}",
"function lm() {\n var locationsMenu = new UI.Menu({\n sections: [{\n items: [{\n title: 'Add to Favorites'\n },{\n title: 'Trains Coming Soon' \n },{\n title: 'Map My Location'\n }]\n }]\n });\n\n //Locations callbacks\n locationsMenu.on('select', function(e){\n if(e.itemIndex === 0) {\n addCurrentLocationToFavorites();\n }else if(e.itemIndex === 1) {\n arrivingTrainsAtCurrent();\n locationsMenu.hide();\n }else if(e.itemIndex === 2){\n mapMyLocation();\n locationsMenu.hide();\n }\n });\n locationsMenu.show();\n}",
"function mobMenu(){\n\t\t$('#mob-menu-contacts').click(function(e){\n\t\t\t$('.open-menu__left').hide();\n\t\t\t$('.open-menu__right').show();\n\t\t})\n\t\t$('#mob-menu-contacts--back').click(function(e){\n\t\t\t$('.open-menu__left').show();\n\t\t\t$('.open-menu__right').hide();\n\t\t})\n\t}",
"function smMenu() {\n\t //create the menu toggle\n $('.topMenu').before('<div class=\"menuToggle\"><a href=\"#\">menu<span class=\"indicator\">+</span></a></div>');\n // append the + indicator\n $('.topMenu h3').append('<span class=\"indicator\">+</span>');\n // wire up clicks and changing the various menu states\n\t//we'll use clicks instead of touch in case a smaller screen has a pointer device\n\t//first, let's deal with the menu toggle\n\t$('.menuToggle a').click(function() {\n\t\t//expand the menu\n\t\t$('.topMenu').toggleClass('expand');\n\t\t// figure out whether the indicator should be changed to + or -\n\t\tvar newValue = $(this).find('span.indicator').text() == '+' ? '-' : '+';\n\t\t// set the new value of the indicator\n\t\t$(this).find('span.indicator').text(newValue);\n\t});\n\t//indicate current window state\n\twindowState = 'small';\n}",
"function menuMobile(){\n\tresetVisibility(\"login-content\");\n\tupdateVisibility(\"menu-content\");\n}",
"menuInteraction(label, marker) {\n label.setInteractive({useHandCursor: true});\n label.on(\"pointerover\", ()=> {\n marker.setVisible(true);\n marker.x = label.x - label.width;\n marker.y = label.y;\n });\n label.on(\"pointerout\", ()=> {\n marker.setVisible(false);\n });\n }",
"function showLocations() {\n slideMenu('loc-layout',1);\n slideMenu('category-layout',0);\n slideMenu('areas-layout',0);\n}",
"function showMapMobile(){\n\t$(this).off(\"click\");\n\t$('#mapBox').addClass(\"mapBoxMobile\").removeClass(\"mapBoxHidden\");\n\t$('#mapWrapper').addClass(\"mapWrapperMobile\").css({\"transform\": \"translate(0px,-450px)\",\n\t\t\"-webkit-transition\": \"transform .5s ease-in-out\"});\n\t$('#map').addClass(\"mapMobile\");\n\tvar arrow = \"<span class='glyphicon glyphicon-arrow-down' aria-hidden='true'></span>\"\n\t$( this ).html(arrow);\n\t$(this).click(hideMapMobile);\n}",
"function mobileMenu() {\n var $navMenu = $('#nav-menu'),\n smallClass = 'small-menu',\n breakPoint = 941;\n\n\n if ( $(window).width() < breakPoint ) {\n if ( ! $navMenu.hasClass(smallClass) ) {\n $navMenu.addClass(smallClass).prepend('<a id=\"toggle-menu\" href=\"#\"><i class=\"fa fa-bars\"></i></a>');\n } \n } else {\n $navMenu.removeClass(smallClass).removeClass('open-small-nav').find('#toggle-menu').remove();\n }\n }",
"function Mobile_ShowMap() {\n var $ = jQuery;\n if($(window).width() > 480) return;\n\n // show\n $(\".icon-map-active\").css(\"display\", \"block\");\n // hide\n $(\"main\").css(\"display\", \"none\");\n $(\".icon-map-inactive\").css(\"display\", \"none\");\n $(\".search-address\").css(\"display\", \"none\");\n $(\".opacity-active\").css(\"display\", \"none\");\n}",
"function mobileMenu() {\r\n var outputElem = $('#mobile_menu');\r\n $('#slick_menu').slicknav({\r\n appendTo: outputElem,\r\n label: ''\r\n });\r\n }",
"function showMobileMenu() {\n if(isMobileContactOpen) {\n hideContactMenu();\n }\n $(burgerIcon).addClass('active');\n isMobileMenuOpen = true;\n navContainer.css({left: 0});\n }",
"function mobileNavAni() {\n $(\"#mobileNav\").slideDown();\n $(\"#menuClick\").css(\"visibility\", \"hidden\");\n $(\"#icon1\").animate({\n right: \"50%\",\n \"margin-right\": \"115px\",\n top: mobileTop\n }, 1000);\n $(\"#icon2\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"45px\"\n }, 1100);\n $(\"#icon3\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-25px\"\n }, 1150);\n $(\"#icon4\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-95px\"\n }, 1250);\n $(\"#icon5\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-165px\"\n }, 1350);\n }",
"function Mobile_Menu() {\n \"use strict\";\n\n $('.mm-page').addClass('mm-slideout');\n\n if( jQuery('#mobile-menu').length > 0 ) return;\n\n var mob_menu1 = jQuery(\".fly-site-navigation#fly-menu-primary .fly-nav-menu\").clone();\n jQuery('<nav id=\"mobile-menu\"></nav>').appendTo('.fly-header-site .fly-nav-wrap');\n var mob_menu = jQuery('#mobile-menu');\n mob_menu.append(mob_menu1);\n if (jQuery('.fly-site-navigation#fly-menu-secondary').length > 0) {\n var mob_menu2 = jQuery(\".fly-site-navigation#fly-menu-secondary .fly-nav-menu\").clone();\n jQuery('#mobile-menu > ul > li:last-child').after(mob_menu2);\n }\n\n if(jQuery('.fly-header-site.fly-header-type-2').length > 0){\n jQuery('<a href=\"#mobile-menu\" class=\"mmenu-link\"><i class=\"fa fa-navicon\"></i></a>').prependTo(\".fly-header-site .container\");\n }\n else{\n jQuery('<a href=\"#mobile-menu\" class=\"mmenu-link\"><i class=\"fa fa-navicon\"></i></a>').prependTo(\".fly-header-site\");\n }\n\n mob_menu.mmenu({\n counters: true,\n searchfield: true,\n onClick: {\n preventDefault: false,\n close: true\n },\n offCanvas: {\n position : \"left\"\n }\n }, {\n classNames: {\n selected: \"current-menu-item\"\n }\n });\n\n}",
"function initializeMobileMenu() {\n\t\tvar mobile_menu = jQuery('<nav />').attr('id','menu');\n\t\tvar ul = jQuery('<ul class=\"links\"></ul>');\n\t\tvar nav_clone = jQuery('#mainNav > ul').clone();\n\t\t\n\t\tnav_clone.find('> li').each(function() {\n\t\t\tul.append(jQuery(this));\n\t\t});\n\n\t\tmobile_menu.append(ul);\n\t\tul.prepend('<li><a href=\"/\">Home</li>');\n\t\tul.prepend('<li><a href=\"http://www.ihg.com/crowneplaza/hotels/us/en/hollywood/fllso/hoteldetail\" target=\"_blank\">Reservations</li>');\n\t\tul.append(jQuery('#footerMenu ul').html());\n\t\tmobile_menu.prependTo('#pageWrapper');\n\n\t\tjQuery('nav#menu').mmenu({\n\t\t\tclasses: \"mm-cp\",\n\t\t\t//counters: true,\n\t\t\tlabels: true,\n\t\t\toffCanvas: {\n\t\t\t\tposition: \"right\"\t\n\t\t\t}\n\t\t});\n \n jQuery('nav#menu').css('z-index','102');\n \n // apply some adjustments for Kentico server\n jQuery('#ui-datepicker-div').parent().removeClass('mm-page mm-slideout');\n jQuery('#form').addClass('mm-page mm-slideout');\n\t}",
"function showMenu() {\n\t$('#searchNavigation').show();\n\t$('#menuContainer').css('left', 310);\n\t// map.setCenter({lat: 38.453131, lng: -121.335495});\n}",
"function initMobileNav() {\n jQuery('.wrap').mobileNav({\n menuActiveClass: 'active',\n menuOpener: '.opener'\n });\n \n jQuery('.wrap2').mobileNav({\n hideOnClick: true,\n menuActiveClass: 'active',\n menuOpener: '.opener',\n menuDrop: '.drop'\n });\n jQuery('.menu li').touchHover({ hoverClass: 'custom-hover' });\n}",
"function setMobileMenuButton() {\n\tif ( screen.availWidth < 748) {\n\t\tvar menuButton = document.getElementById(\"mobileMenuButton\");\n\t\tmenuButton.nav = document.getElementsByTagName(\"header\")[0].getElementsByTagName(\"nav\")[0];\n\t\t\n\t\tmenuButton.onclick = function() {\n\t\t\t\tif (!(/doHide\\s/).test(this.className)) {\n\t\t\t\t\tthis.className = \"doHide \" + this.className;\n\t\t\t\t\tthis.nav.style.height = String(this.nav.getElementsByTagName(\"ul\")[0].offsetHeight) + \"px\"\n\t\t\t\t} else {\n\t\t\t\t\tthis.className = this.className.replace(/doHide\\s/g, \"\");\n\t\t\t\t\tthis.nav.style.height = \"0\"\n\t\t\t\t}\n\t\t\t};\n\t}\n}",
"function showMobileBar(){\n\t\t\t$(menu).hide(0);\n\t\t\t$(showHideButton).show(0).click(function(){\n\t\t\t\tif($(menu).css(\"display\") == \"none\")\n\t\t\t\t\t$(menu).slideDown(settings.showSpeed);\n\t\t\t\telse\n\t\t\t\t\t$(menu).slideUp(settings.hideSpeed).find(\".dropdown, .megamenu\").hide(settings.hideSpeed);\n\t\t\t});\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
traversal algorithms Breadthfirst search / Starting from one node and checks for all child nodes. Then checks all child nodes of these nodes and so on... until we find the node we are searching for.Layer by layer. | bfs (firstNode, searchedNode) {
const queue = [firstNode] // queue ds
const visited = {} // obj(or Map) stores all the visited nodes
while (queue.length) {
let current = queue.shift()
// we check if the current Node is visited
if (visited[current]) {
continue
}
// we check if the current Node is the searchedNode
if (current === searchedNode) {
console.log(
`The node you are searching for was found!Node: ${searchedNode}`
)
return true
}
// if the node isn't visited or the node we are searching for
// we mark it as visited
visited[current] = true
// we get all neighbours of the current node and add each node to the queue
let neighbour = this.nodes.get(current)
neighbour.forEach(n => queue.push(n))
}
// if theres a problem (the searchedNode doesn't exist) return false
return false
} | [
"traverseBreadthFirst(callback)\n {\n\t\t\n\t\tvar queue = new Queue();\n\t \n\t\tqueue.enqueue(this._root);\n\t \n\t\tlet currentNode = queue.dequeue();\n\t\twhile(currentNode){\n\t\t\tfor (var i = 0, length = currentNode.next.length; i < length; i++) {\n\t\t\t\tqueue.enqueue(currentNode.next[i]);\n\t\t\t}\n\t \n\t\t\tcallback(currentNode);\n\t\t\tcurrentNode = queue.dequeue();\n\t\t}\n }",
"traverseBF(fn) {\n let arr = [this.root]; // queue\n while (arr.length) {\n let node = arr.shift(); // take first node out\n arr.push(...node.children); // append all children node to the queue\n\n fn(node); // evaluation function AKA \"Is this the node you were searching for?\"\n }\n }",
"traverseBreadthFirst(callback) {\n\n }",
"traverseBreadthFirst(callback) {\n const queue = [];\n queue.push(this);\n while(queue.length) {\n const current = queue.shift();\n callback(current);\n current.children.forEach(child => queue.push(child));\n }\n }",
"traverseBreadthFirst(startingNode, fn) {\n const visited = {};\n const queue = [startingNode];\n\n // while there are nodes in the queue\n while (queue.length > 0) {\n // get the nest node in queue\n const node = queue.shift();\n if (node in visited) {\n continue;\n }\n fn(node);\n visited[node] = true;\n\n for (let adjNode of this.nodes[node]) {\n if (adjNode in visited !== true) {\n queue.push(adjNode);\n }\n }\n }\n }",
"function depthFirstSearch() {\r\n\r\n queue = [];\r\n reachedNodes = [];\r\n parentChildRelationObject = [];\r\n let resultMatrix = document.getElementById(\"resultMatrix\");\r\n //This will clear the DOM child every time\r\n resultMatrix.innerHTML = \"\";\r\n\r\n // reset every time\r\n goalStatus = false;\r\n queue.push(rootNode);\r\n let count = 0;\r\n\r\n\r\n while (queue.length != 0 && !goalStatus && count < 150000) {\r\n\r\n let addToQueue = true;\r\n let depthExceeded = false;\r\n let presentNode = queue[0];\r\n let parentDepth = 0;\r\n reachedNodes.push(presentNode);\r\n\r\n\r\n //For DFS search\r\n\r\n\r\n for (let obj in parentChildRelationObject) {\r\n if (JSON.stringify(parentChildRelationObject[obj].value) == JSON.stringify(presentNode)) {\r\n parentDepth = parentChildRelationObject[obj].depth;\r\n }\r\n }\r\n\r\n if (parentDepth + 1 <= acceptableDepth) {\r\n puzzleExpander(presentNode);\r\n }\r\n\r\n if (children.length != 0 && !goalStatus && count < 150000) {\r\n // check whether the node is already present in queue\r\n for (let i = 0; i < children.length; i++) {\r\n\r\n if (!goalStatus && count < 1500) {\r\n addToQueue = true;\r\n\r\n for (let j = 0; j < queue.length; j++) {\r\n if (JSON.stringify(queue[j]) === JSON.stringify(children[i])) {\r\n console.log('Already exists');\r\n addToQueue = false;\r\n count = count + 1;\r\n\r\n }\r\n }\r\n //This will check whether the children is in the reachedNodes or not\r\n if (addToQueue) {\r\n for (let k = 0; k < reachedNodes.length; k++) {\r\n if (JSON.stringify(reachedNodes[k]) === JSON.stringify(children[i])) {\r\n console.log('Already exists');\r\n addToQueue = false;\r\n }\r\n }\r\n }\r\n\r\n //Add that child to the queue if add to queue variable is true\r\n if (addToQueue && !depthExceeded) {\r\n //should not add if the depth is exceeded the input limit\r\n if (parentDepth + 1 <= acceptableDepth) {\r\n let val = children[i].slice(0);\r\n queue.insert(\"1\", val);\r\n let parent = [];\r\n parent[\"value\"] = val;\r\n parent[\"parent\"] = presentNode;\r\n parent[\"depth\"] = parentDepth + 1;\r\n parentChildRelationObject.push(parent)\r\n }\r\n\r\n }\r\n //If one of the child is the goal status there is no need to check for the others\r\n if (goalReached(children[i])) {\r\n break;\r\n }\r\n ;\r\n }\r\n }\r\n\r\n }\r\n\r\n //This will remove the first element of an array\r\n queue.shift();\r\n }\r\n\r\n if (goalStatus == true) {\r\n\r\n let pathFolowed = tracePath();\r\n console.log(\"goalReached\");\r\n console.log(pathFolowed);\r\n printNode(pathFolowed);\r\n } else {\r\n console.log(parentChildRelationObject);\r\n let resultMatrix = document.getElementById(\"resultMatrix\");\r\n resultMatrix.innerHTML = \"The result is not obtained for given depth\";\r\n console.log(\"No result\");\r\n }\r\n\r\n}",
"function iterativeDeepeningSearch() {\r\n\r\n queue = [];\r\n reachedNodes = [];\r\n parentChildRelationObject = [];\r\n let resultMatrix = document.getElementById(\"resultMatrix\");\r\n //This will clear the DOM child every time\r\n resultMatrix.innerHTML = \"\";\r\n\r\n // reset every time\r\n goalStatus = false;\r\n queue.push(rootNode);\r\n let count = 0;\r\n\r\n\r\n while (queue.length != 0 && !goalStatus && count < 1500) {\r\n\r\n let addToQueue = true;\r\n let depthExceeded = false;\r\n let presentNode = queue[0];\r\n let parentDepth = 0;\r\n reachedNodes.push(presentNode);\r\n\r\n for (let obj in parentChildRelationObject) {\r\n if (JSON.stringify(parentChildRelationObject[obj].value) == JSON.stringify(presentNode)) {\r\n parentDepth = parentChildRelationObject[obj].depth;\r\n }\r\n }\r\n puzzleExpander(presentNode);\r\n\r\n\r\n if (children.length != 0 && !goalStatus && count < 1500) {\r\n // check whether the node is already present in queue\r\n for (let i = 0; i < children.length; i++) {\r\n\r\n if (!goalStatus && count < 1500) {\r\n addToQueue = true;\r\n\r\n for (let j = 0; j < queue.length; j++) {\r\n if (JSON.stringify(queue[j]) === JSON.stringify(children[i])) {\r\n console.log('Already exists');\r\n addToQueue = false;\r\n count = count + 1;\r\n\r\n }\r\n }\r\n //This will check whether the children is in the reachedNodes or not\r\n if (addToQueue) {\r\n for (let k = 0; k < reachedNodes.length; k++) {\r\n if (JSON.stringify(reachedNodes[k]) === JSON.stringify(children[i])) {\r\n console.log('Already exists');\r\n addToQueue = false;\r\n }\r\n }\r\n }\r\n\r\n //Add that child to the queue if add to queue variable is true\r\n if (addToQueue) {\r\n //should not add if the depth is exceeded the input limit\r\n\r\n let val = children[i].slice(0);\r\n queue.push(val);\r\n let parent = [];\r\n parent[\"value\"] = val;\r\n parent[\"parent\"] = presentNode;\r\n parent[\"depth\"] = parentDepth + 1;\r\n parentChildRelationObject.push(parent)\r\n }\r\n\r\n }\r\n //If one of the child is the goal status there is no need to check for the others\r\n if (goalReached(children[i])) {\r\n break;\r\n }\r\n ;\r\n }\r\n }\r\n\r\n //This will remove the first element of an array\r\n queue.shift();\r\n // sorting queue based on the parent depth\r\n sortingBasedOnDepth();\r\n }\r\n\r\n if (goalStatus == true) {\r\n\r\n let pathFolowed = tracePath();\r\n console.log(\"goalReached\");\r\n console.log(pathFolowed);\r\n printNode(pathFolowed);\r\n } else {\r\n let resultMatrix = document.getElementById(\"resultMatrix\");\r\n resultMatrix.innerHTML = \"The result is not obtained for given depth\";\r\n console.log(\"No result\");\r\n }\r\n\r\n}",
"function breadthFirstSearch(root, targetVal) {\n\n}",
"traverseDepthFirst(callback) {\n callback(this);\n for(let i = 0; i < this.children.length; i++) {\n this.children[i].traverseDepthFirst(callback);\n }\n }",
"traverse(callback) {\n const visitedBranches = {};\n const crawlPath = [];\n\n crawlPath.push(this.root);\n\n while (crawlPath.length > 0) {\n const current = crawlPath.slice(-1)[0];\n\n console.log(`Robot at branch ${current.id}`);\n\n // Let's find next unexplored branch\n const next = current.children.find(branch => !(branch.id in visitedBranches));\n\n if (next) {\n // Let's look at this next\n crawlPath.push(next);\n } else {\n // No children to be visited, let's process this branch\n if (callback) {\n callback(current);\n visitedBranches[current.id] = true;\n }\n\n crawlPath.pop();\n }\n }\n }",
"traverseDepthFirst(startingNode, fn) {\n const visited = {};\n const stack = [startingNode];\n\n //while there's something on the stack\n while (stack.length > 0) {\n // get next node, check to see if visited\n const node = stack.pop();\n if (node in visited) {\n continue;\n }\n\n // do sth\n fn(node);\n visited[node] = true;\n\n // push all (unvisited) adj nodes on the stack\n for (let adjNode of this.nodes[node]) {\n if (!(adjNode in visited)) {\n stack.push(adjNode);\n }\n }\n }\n }",
"traverseDepthFirst_inOrder() {\n\n }",
"traverseDepthFirst(callback) {\n\n }",
"depthFirstIterative(vertex){\n let result = new Queue();\n let visitedVertices = new HashTable();\n let toVisit = new Stack();\n\n toVisit.push(vertex);\n\n while(toVisit.size > 0){\n let next = toVisit.pop();\n \n if(!visitedVertices.get(next)){\n result.enqueue(next);\n visitedVertices.set(next, true);\n for(let neighbor of this.adjacencyList.get(next)){\n toVisit.push(neighbor);\n }\n }\n }\n return result;\n }",
"function breadth_first_search(initial_state) {\n let open = []; //See push()/pop() and unshift()/shift() to operate like stack or queue\n //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\n let closed = new Set(); //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\n\n /***Your code for breadth-first search here***/\n let found = false;\n let final;\n\n //if initial_state is goal state then return\n if(is_goal_state(initial_state)){\n return {\n actions : [] /*array of action ids*/,\n states : [] /*array of states*/\n };\n }\n\n //push initial_state\n open.push({\n actionID : 0,\n resultState : initial_state,\n parentState : null\n });\n\n //keep looking for successors until found the goal state\n while(!found){\n let parent = open.shift(); /* open the first one in the open array */\n let childs = find_successors(parent.resultState); /* find its successors */\n while(childs.length != 0){ /* check each child see if it is goal state*/\n if(is_goal_state(childs[0].resultState)){ /*if yes, then exit the loop and go find the path*/\n final = {\n actionID : childs[0].actionID,\n resultState : childs[0].resultState,\n parentState : parent\n }\n found = true;\n }else{ /*if no, then append it to the end of open*/\n open.push({\n actionID : childs[0].actionID,\n resultState : childs[0].resultState,\n parentState : parent\n })\n }\n childs.shift();\n }\n closed.add(parent); /*add parent to close set*/\n }\n\n /*\n Hint: In order to generate the solution path, you will need to augment\n the states to store the predecessor/parent state they were generated from\n and the action that generates the child state from the predecessor state.\n\n\t For example, make a wrapper object that stores the state, predecessor and action.\n\t Javascript objects are easy to make:\n\t\tlet object={\n\t\t\tmember_name1 : value1,\n\t\t\tmember_name2 : value2\n\t\t};\n\n Hint: Because of the way Javascript Set objects handle Javascript objects, you\n will need to insert (and check for) a representative value instead of the state\n object itself. The state_to_uniqueid function has been provided to help you with\n this. For example\n let state=...;\n closed.add(state_to_uniqueid(state)); //Add state to closed set\n if(closed.has(state_to_uniqueid(state))) { ... } //Check if state is in closed set\n */\n\n /***Your code to generate solution path here***/\n let actions = [];\n let states = [];\n let currentState = final;\n // find the path by looping up to the root\n while(currentState.parentState != null){\n actions.unshift(currentState.actionID);\n states.unshift(currentState.resultState);\n currentState = currentState.parentState\n }\n\n if(actions != null){\n return {\n actions : actions /*array of action ids*/,\n states : states /*array of states*/\n };\n }else{\n return null;\n }\n}",
"function traverseBreadthFirst(rootNode, options) {\n options = extend({\n subnodesAccessor: function(node) { return node.subnodes; },\n userdataAccessor: function(node, userdata) { return userdata; },\n onNode: function(node, callback, userdata) { callback(); },\n onComplete: function(rootNode) {},\n userdata: null\n }, options);\n\n var queue = [];\n queue.push([rootNode, options.userdata]);\n\n (function next() {\n if (queue.length == 0) {\n options.onComplete(rootNode);\n return;\n }\n\n var front = queue.shift();\n var node = front[0];\n var data = front[1];\n\n options.onNode(node, function() {\n var subnodeData = options.userdataAccessor(node, data);\n var subnodes = options.subnodesAccessor(node);\n async.eachSeries(subnodes,\n function(subnode, nextNode) {\n queue.push([subnode, subnodeData]);\n async.setImmediate(nextNode);\n },\n function() {\n async.setImmediate(next);\n }\n );\n },\n data);\n })();\n}",
"breadthFirstTraverse() {\n var queue = [this]\n var result = []\n while (queue.length != 0) {\n var head = queue.shift()\n if (head.leftChild !== null)\n queue.push(head.leftChild)\n if (head.rightChild !== null)\n queue.push(head.rightChild)\n result.push(head)\n }\n return result\n }",
"function breadthFirstTraversal(tree, func) {\n var max = 0;\n if (tree && tree.length > 0) {\n var currentDepth = tree[0].depth;\n var fifo = [];\n var currentLevel = [];\n\n fifo.push(tree[0]);\n while (fifo.length > 0) {\n var node = fifo.shift();\n if (node.depth > currentDepth) {\n func(currentLevel);\n currentDepth++;\n max = Math.max(max, currentLevel.length);\n currentLevel = [];\n }\n currentLevel.push(node);\n if (node.children) {\n for (var j = 0; j < node.children.length; j++) {\n fifo.push(node.children[j]);\n }\n }\n }\n func(currentLevel);\n return Math.max(max, currentLevel.length);\n }\n return 0;\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MultiplexClient sits on top of a SockJS connection and lets the caller open logical SockJS connections (channels). The SockJS connection is closed when all of the channels close. This means you can't start with zero channels, open a channel, close that channel, and then open another channel. | function MultiplexClient(sockjsUrl, whitelist) {
// The URL target for our SockJS connection(s)
this._sockjsUrl = sockjsUrl;
// The whitelisted SockJS protocols
this._whitelist = whitelist;
// Placeholder for our SockJS connection, once we open it.
this._conn = null;
// A table of all active channels.
// Key: id, value: MultiplexClientChannel
this._channels = {};
this._channelCount = 0;
// ID to use for the next channel that is opened
this._nextId = 0;
// Channels that need to be opened when the SockJS connection's open
// event is received
this._pendingChannels = [];
// A list of functions that fire when our connection goes away.
this.onclose = [];
// Backlog of messages we need to send when we have a connection.
this._buffer = [];
// Whether or not this is our first connection.
this._first = true;
// No an updated value like readyState, but rather a Boolean which will be set
// true when the server has indicated that this connection can't ever be resumed.
this._diconnected = false;
// The timer used to delay the display of the reconnecting dialog.
this._disconnectTimer = null;
// The message shown to be shown to the user in the dialog box
this._dialogMsg = '';
this._autoReconnect = false;
var self = this;
// Open an initial connection
this._openConnection_p()
.fail(function(err){
self._disconnected = true;
self.onConnClose.apply(self, arguments);
})
.done();
} | [
"function MultiplexClient(conn) {\n // The underlying SockJS connection. At this point it is not likely to\n // be opened yet.\n this._conn = conn;\n // A table of all active channels.\n // Key: id, value: MultiplexClientChannel\n this._channels = {};\n this._channelCount = 0;\n // ID to use for the next channel that is opened\n this._nextId = 0;\n // Channels that need to be opened when the SockJS connection's open\n // event is received\n this._pendingChannels = [];\n // A list of functions that fire when our connection goes away.\n this.onclose = []\n\n var self = this;\n this._conn.onopen = function() {\n log(\"Connection opened. \" + window.location.href);\n var channel;\n while ((channel = self._pendingChannels.shift())) {\n // Be sure to check readyState so we don't open connections for\n // channels that were closed before they finished opening\n if (channel.readyState === 0) {\n channel._open();\n } else {\n debug(\"NOT opening channel \" + channel.id);\n }\n }\n };\n this._conn.onclose = function(e) {\n log(\"Connection closed. Info: \" + JSON.stringify(e));\n debug(\"SockJS connection closed\");\n // If the SockJS connection is terminated from the other end (or due\n // to loss of connectivity or whatever) then we can notify all the\n // active channels that they are closed too.\n for (var key in self._channels) {\n if (self._channels.hasOwnProperty(key)) {\n self._channels[key]._destroy();\n }\n }\n for (var i = 0; i < self.onclose.length; i++) {\n self.onclose[i]();\n }\n };\n this._conn.onmessage = function(e) {\n var msg = parseMultiplexData(e.data);\n if (!msg) {\n log(\"Invalid multiplex packet received from server\");\n self._conn.close();\n return;\n }\n var id = msg.id;\n var method = msg.method;\n var payload = msg.payload;\n var channel = self._channels[id];\n if (!channel) {\n log(\"Multiplex channel \" + id + \" not found\");\n return;\n }\n if (method === \"c\") {\n // If we're closing, we want to close everything, not just a subapp.\n // So don't send to a single channel.\n self._conn.close();\n } else if (method === \"m\") {\n channel.onmessage({data: payload});\n }\n };\n }",
"connect() {\n if (!this.channels || this.channels.length < 1)\n return;\n this.channels.forEach((infos) => {\n let conn = new Mixer.ChatService(this.client).join(infos.id).then((response) => {\n let channel = new channel_1.Channel(this, infos.id, response.body);\n channel.connect();\n infos.channel = channel;\n }).catch((e) => {\n console.log(\"Cannot connect to channel #\" + infos.id);\n });\n });\n }",
"_chooseAndConnect() {\n\t\tlet servers = g_PingedServers;\n\t\tif (servers.length == 0) {\n\t\t\tservers = this.user._cmList.websocket_servers;\n\t\t}\n\n\t\tlet addr = servers[Math.floor(Math.random() * servers.length)];\n\t\tthis._debug(`Randomly chose WebSocket CM ${addr}`);\n\t\tthis.stream = new WS13.WebSocket(`wss://${addr}/cmsocket/`, {\n\t\t\tpingInterval: 30000,\n\t\t\tproxyTimeout: this.user.options.proxyTimeout,\n\t\t\tconnection: {\n\t\t\t\tlocalAddress: this.user.options.localAddress,\n\t\t\t\tagent: this.user._getProxyAgent()\n\t\t\t}\n\t\t});\n\n\t\t// Set up the connection timeout\n\t\tthis.stream.setTimeout(this.user._connectTimeout);\n\n\t\tthis.stream.on('debug', msg => this._debug(msg, true));\n\t\tthis.stream.on('message', this._readMessage.bind(this));\n\n\t\tthis.stream.on('disconnected', (code, reason) => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._disconnected = true;\n\t\t\tthis._debug('WebSocket disconnected with code ' + code + ' and reason: ' + reason);\n\t\t\tthis.user._handleConnectionClose(this);\n\t\t});\n\n\t\tthis.stream.on('error', (err) => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._disconnected = true;\n\t\t\tthis._debug('WebSocket disconnected with error: ' + err.message);\n\n\t\t\tif (err.proxyConnecting || err.constructor.name == 'SocksClientError') {\n\t\t\t\t// This error happened while connecting to the proxy\n\t\t\t\tthis.user.emit('error', err);\n\t\t\t} else {\n\t\t\t\tthis.user._handleConnectionClose(this);\n\t\t\t}\n\t\t});\n\n\t\tthis.stream.on('connected', () => {\n\t\t\tthis._debug('WebSocket connection success; now logging in');\n\t\t\tthis.stream.setTimeout(0); // Disable timeout\n\t\t\tthis.user._sendLogOn();\n\t\t});\n\n\t\tthis.stream.on('timeout', () => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._disconnected = true;\n\t\t\tthis._debug('WS connection timed out');\n\t\t\tthis.user._connectTimeout = Math.min(this.user._connectTimeout * 2, 10000); // 10 seconds max\n\t\t\tthis.stream.disconnect();\n\t\t\tthis.user._doConnection();\n\t\t});\n\t}",
"function openCubeConnection() {\n if (settings.is_multiple_collectors) {\n revlogger.log('info', \"Open socket connection for multiple cubes\");\n var no_of_cubes = settings.cube.length;\n for (i = 0; i < no_of_cubes; i++) {\n cube_url = settings.cube[i].protocol + \"://\" + settings.cube[i].domain + \":\" + settings.cube[i].port;\n settings.cube[i].client = cube.emitter(cube_url);\n }\n } else {\n revlogger.log('info', \"Open socket connection for Single cube\");\n cube_url = settings.cube[0].protocol + \"://\" + settings.cube[0].domain + \":\" + settings.cube[0].port;\n settings.cube[0].client = cube.emitter(cube_url);\n }\n}",
"function MultiplexedSocket (stream) {\n\n var MODE_MESG = 1;\n var MODE_END = 2;\n\n var self = this;\n var top = this;\n\n var channels = {};\n var mode_header_width = 1;\n var chan_list_header_width = 2;\n var chan_id_width = 4;\n var mesg_length_header_width = 2;\n\n var max_channel_id = 4294967295;\n var header_size = chan_list_header_width + mesg_length_header_width;\n\n\n stream.removeAllListeners(\"data\");\n\n var streamE = new iter.StreamEnumerator(stream);\n\n var mode_handlers = {};\n mode_handlers[MODE_MESG] = mesgHandler;\n mode_handlers[MODE_END] = endHandler;\n\n // The reader is always the starting place...\n function modeReader () {\n streamE.run(readNBytes(1), function(mode) {\n mode = (mode[0] | 0);\n debug(\"Mode is: \" + mode);\n mode_handlers[mode]();\n });\n };\n\n // The client has sent an end signal\n function endHandler () {\n streamE.run(readNBytes(2), function (chan_to_end) {\n chan_to_end = parseN(2, chan_to_end);\n debug(\"Channels to end: \" + chan_to_end);\n if (channels[chan_to_end]) channels[chan_to_end].emit(\"end\");\n delete channels[chan_to_end];\n modeReader();\n });\n };\n\n function mesgHandler () {\n streamE.run(readNBytes(2), function(number_of_channels) {\n number_of_channels = parseN(2, number_of_channels);\n debug(\"Number of channels is: \" + number_of_channels);\n streamE.run(readNBytes(2), function(mesg_length) {\n mesg_length = parseN(2, mesg_length);\n debug(\"message length is: \" + mesg_length);\n streamE.run(readNBytes(number_of_channels * chan_id_width), function (chans_str) {\n var chans = [];\n for (var i = 0; i < number_of_channels; i++) {\n var slice = chans_str.slice(i*chan_id_width, (i*chan_id_width) + chan_id_width);\n chans.push(parseN(4, slice));\n }\n debug(\"Channels are: \" + chans);\n streamE.run(readNBytes(mesg_length), function(mesg) {\n debug(\"Message is: \" + mesg.toString());\n\n chans.forEach(function(chan_id) {\n var chan = channels[chan_id];\n if (chan == undefined) {\n chan = new SocketChannel(chan_id);\n self.emit(\"channel\", chan);\n channels[chan_id] = chan;\n }\n process.nextTick(function() {\n if (mesg) chan.emit(\"data\", mesg.toString(\"utf-8\"));\n });\n });\n modeReader();\n });\n });\n });\n });\n }\n\n modeReader();\n\n function emitOnAllChannels (signal) {\n if (channels.length == 0)\n return false;\n\n var args = Array.prototype.slice.call(arguments,1);\n for (channel in channels) {\n if (channels.hasOwnProperty(channel)) {\n channels[channel].emit(signal, args);\n }\n }\n\n return true;\n };\n\n function getNewChannelId () {\n for (var i = 0; i < max_channel_id; i++) {\n if (!(i in channels)) {\n return i;\n }\n }\n };\n\n this.newChannel = function () {\n var nid = getNewChannelId();\n var chan = new SocketChannel(nid);\n channels[nid] = chan;\n return chan;\n };\n\n function removeChannel (id) {\n if (id in channels)\n delete channels[id];\n };\n\n stream.on(\"close\",function(){\n emitOnAllChannels (\"close\");\n self.emit(\"close\");\n });\n\n stream.on(\"end\",function(){\n emitOnAllChannels (\"end\");\n self.emit(\"end\");\n });\n\n stream.on(\"error\",function (e){\n // Node will throw an exception if an \"error\" event isn't\n // handled. Unconditionally emitting an error event on self is\n // hard to catch in client applications that just use channels.\n //emitOnAllChannels (\"error\", e) || self.emit(\"error\", e);\n });\n\n stream.on(\"connect\",function(){ self.emit(\"connect\"); emitOnAllChannels (\"connect\") });\n\n this.end = function () { stream.end() }\n this.destroy = function () { stream.destroy() }\n\n ////////////////////////////////////////////////////////////////////////\n\n function SocketChannel (id) {\n\n var self = this;\n\n this.toString = function () {\n return \"<SocketChannel #\" + id + \">\"\n };\n\n this.getId = function () { return id };\n\n this.getSocket = function () { return stream };\n\n this.end = this.destroy = function () {\n var buf = new Buffer(pack('Cn', MODE_END, self.getId()), 'binary');\n doWrite(buf);\n removeChannel(id);\n };\n\n this.write = function (data) {\n self._write([this], data)\n }\n\n this.multiWrite = function (chans, data) {\n self._write(chans, data);\n }\n\n this.writeRaw = function (str) { self._write([this], str); }\n\n this._write = function (chans, json) {\n debug(\"Writing data: \" + json);\n\n var bufA = new Buffer(Buffer.byteLength(json) + mode_header_width + header_size + (chan_id_width * chans.length),'binary');\n\n var bufB = new Buffer(pack('Cnn', MODE_MESG, chans.length, Buffer.byteLength(json)),'binary');\n bufB.copy(bufA,0,0);\n\n var bufD = new Buffer(chans.length * chan_id_width, 'binary');\n for (var i = 0; i < chans.length; i++) {\n (new Buffer(pack('N', chans[i].getId()), 'binary')).copy(bufD, i * chan_id_width, 0)\n };\n bufD.copy(bufA, bufB.length, 0);\n\n var bufC = new Buffer(json);\n bufC.copy(bufA,bufB.length + bufD.length,0);\n doWrite(bufA);\n }\n\n function doWrite (buf) {\n if (stream.writeable !== false) {\n try {\n stream.write(buf);\n } catch (e) {\n this.emit(\"error\", e);\n }\n }\n }\n\n };\n SocketChannel.inheritsFrom(event.EventEmitter);\n\n}",
"static connectToMultiplexingDuplex(server, cancellationToken = cancellationtoken_1.default.CONTINUE) {\n return __awaiter(this, void 0, void 0, function* () {\n assert(server);\n const multiplexingStream = yield nerdbank_streams_1.MultiplexingStream.CreateAsync(server, cancellationToken);\n const channel = yield multiplexingStream.acceptChannelAsync('', undefined, cancellationToken);\n const rpc = frameworkServices_1.FrameworkServices.remoteServiceBroker.constructRpc(channel);\n const serviceBroker = new proxyForIRemoteServiceBroker_1.ProxyForIRemoteServiceBroker(rpc);\n const result = yield this.connectToMultiplexingRemoteServiceBroker(serviceBroker, multiplexingStream, cancellationToken);\n result.ownsMxStream = true;\n return result;\n });\n }",
"connect() {\n const host = config.server.server_host, port = config.server.server_port;\n console.log(`*** mediator: ${config['_state']} connecting to server ${host}:${port}`);\n mediator['socket'] = io(\"https://\" + host + \":\" + port);\n for (const channel of config.server.channels) {\n mediator.log(`Mediator created channel with name = ${channel}`);\n mediator['socket']['on'](channel, (o) => {\n queue.push(o);\n });\n }\n }",
"function openCubeConnection(){\n\tif(settings.is_multiple_collectors){\n\t\tvar no_of_cubes = settings.cube.length;\n\t\tfor( i=0;i<no_of_cubes;i++){\n\t\t\tcube_url = settings.cube[i].protocol+\"://\"+settings.cube[i].domain+\":\"+settings.cube[i].port;\n\t\t\tsettings.cube[i].client = cube.emitter(cube_url);\t\n\t\t}\n\t}else{\n\t\tcube_url = settings.cube[0].protocol+\"://\"+settings.cube[0].domain+\":\"+settings.cube[0].port;\n\t\tsettings.cube[0].client = cube.emitter(cube_url);\n\t}\n}",
"function connect() {\n var socket = new SockJS(URL_SERVER + '/short_url');\n stompClient = Stomp.over(socket);\n stompClient.connect({}, function (frame) {\n console.info('Connected: ' + frame);\n stompClient.subscribe('/user/url_shortener/short_url', function (response) {\n dealMessageFromServer(JSON.parse(response.body));\n });\n });\n}",
"startClients() {\n\t\tconst url = this.options.url;\n\t\tconst strBody = JSON.stringify(this.options.body);\n\t\tfor (let index = 0; index < this.options.concurrency; index++) {\n\t\t\tif (this.options.indexParam) {\n\t\t\t\tlet oldToken = new RegExp(this.options.indexParam, 'g');\n\t\t\t\tif(this.options.indexParamCallback instanceof Function) {\n\t\t\t\t\tlet customIndex = this.options.indexParamCallback();\n\t\t\t\t\tthis.options.url = url.replace(oldToken, customIndex);\n\t\t\t\t\tif(this.options.body) {\n\t\t\t\t\t\tlet body = strBody.replace(oldToken, customIndex);\n\t\t\t\t\t\tthis.options.body = JSON.parse(body);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.options.url = url.replace(oldToken, index);\n\t\t\t\t\tif(this.options.body) {\n\t\t\t\t\t\tlet body = strBody.replace(oldToken, index);\n\t\t\t\t\t\tthis.options.body = JSON.parse(body);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet constructor = httpClient.create;\n\t\t\t// TODO: || this.options.url.startsWith('wss:'))\n\t\t\tif (this.options.url.startsWith('ws:')) {\n\t\t\t\tconstructor = websocket.create;\n\t\t\t}\n\t\t\tconst client = constructor(this, this.options);\n\t\t\tthis.clients[index] = client;\n\t\t\tif (!this.options.requestsPerSecond) {\n\t\t\t\tclient.start();\n\t\t\t} else {\n\t\t\t\t// start each client at a random moment in one second\n\t\t\t\tconst offset = Math.floor(Math.random() * 1000);\n\t\t\t\tsetTimeout(() => client.start(), offset);\n\t\t\t}\n\t\t}\n\t}",
"connect() {\n if (this.dead) return;\n if (this.ws) this.reset();\n if (this.attempts >= 5) {\n this.emit('debug', new Error(`Too many connection attempts (${this.attempts}).`));\n return;\n }\n\n this.attempts++;\n\n /**\n * The actual WebSocket used to connect to the Voice WebSocket Server.\n * @type {WebSocket}\n */\n this.ws = new WebSocket(`wss://${this.voiceConnection.authentication.endpoint}`);\n this.ws.onopen = this.onOpen.bind(this);\n this.ws.onmessage = this.onMessage.bind(this);\n this.ws.onclose = this.onClose.bind(this);\n this.ws.onerror = this.onError.bind(this);\n }",
"function connect() {\n var stompClient = null;\n var socket = new SockJS('/hello');\n stompClient = Stomp.over(socket);\n stompClient.connect({}, function(frame) {\n console.log('Connected: ' + frame);\n stompClient.subscribe('/topic/clockstatus', function(clockStatus){\n showBerlinClockStatus(clockStatus);\n });\n stompClient.subscribe('/topic/clocktime', function(clockTime){\n showBerlinClock(JSON.parse(clockTime.body));\n });\n });\n}",
"function Client (url, connspec) {\n // Open a connection to the Switchboard server.\n var conn = new WebSocket(url);\n var sender = new Sender (conn);\n\n /**\n * On the websocket's `onopen`, send a connect command with the connection\n * specification.\n */\n conn.onopen = function() {\n sender.sendCmds([sender.makeCmd(\"connect\", connspec)]);\n }.bind(this);\n\n /******************\n * Public Interface\n */\n\n this.watchMailboxes = function (mailboxes, callback) {\n sender.sendCmds([\n sender.makeCmd(\"watchMailboxes\", {list: mailboxes}, callback)]);\n return this;\n }.bind(this);\n\n this.getMailboxes = function (callback) {\n sender.sendCmds([sender.makeCmd(\"getMailboxes\", [], callback)]);\n return this;\n }.bind(this);\n\n this.getMessageList = function (mailboxId, callback) {\n var args = {mailboxId: mailboxId};\n sender.sendCmds([sender.makeCmd(\"getMessageList\", args, callback)]);\n return this;\n }.bind(this);\n\n this.getMessages = function(ids, properties, callback) {\n var args = {ids: ids,\n properties: properties || [\"textBody\"]};\n sender.sendCmds([sender.makeCmd(\"getMessages\", args, callback)]);\n return this;\n }.bind(this);\n }",
"connect () {\n Logger.info('Initializing ticker connect')\n this.websocket = new WebsocketClient(this.coins, this.websocketURI, false, {channels: ['ticker']})\n // turn on the websocket for errors\n this.websocket.on('error', (err) => {\n const message = 'Error occurred in the ticker websocket.'\n const errorMsg = new Error(err)\n Logger.error({ message, errorMsg, err })\n this.connect()\n })\n\n // Turn on the websocket for closes to restart it\n this.websocket.on('close', () => {\n Logger.debug('Ticker websocket closed, restarting...')\n this.connect()\n })\n\n // Turn on the websocket for messages\n this.websocket.on('message', (data) => {\n if (data.type === 'ticker') {\n this.emit(data.coin, data)\n TickerTable.createFromTicker(data)\n }\n })\n\n }",
"function Client(stream, options) {\n events.EventEmitter.call(this);\n\n this.stream = stream;\n this.originalCommands = [];\n this.queuedOriginalCommands = [];\n this.queuedRequestBuffers = [];\n this.channelCallbacks = {};\n this.requestBuffer = new Buffer(512);\n this.replyParser = new ReplyParser(this.onReply_, this);\n this.reconnectionTimer = null;\n this.maxReconnectionAttempts = 10;\n this.reconnectionAttempts = 0;\n this.reconnectionDelay = 500; // doubles, so starts at 1s delay\n this.connectionsMade = 0;\n\n if (options !== undefined) \n this.maxReconnectionAttempts = Math.abs(options.maxReconnectionAttempts || 10);\n\n var client = this;\n\n stream.addListener(\"connect\", function () {\n if (exports.debugMode)\n sys.debug(\"[CONNECT]\");\n\n stream.setNoDelay();\n stream.setTimeout(0);\n\n client.reconnectionAttempts = 0;\n client.reconnectionDelay = 500;\n if (client.reconnectionTimer) {\n clearTimeout(client.reconnectionTimer);\n client.reconnectionTimer = null;\n }\n\n var eventName = client.connectionsMade == 0 \n ? 'connected' \n : 'reconnected';\n\n client.connectionsMade++;\n client.expectingClose = false;\n\n // If this a reconnection and there were commands submitted, then they\n // are gone! We cannot say with any confidence which were processed by\n // Redis; perhaps some were processed but we never got the reply, or\n // perhaps all were processed but Redis is configured with less than\n // 100% durable writes, etc. \n //\n // We punt to the user by calling their callback with an I/O error.\n // However, we provide enough information to allow the user to retry\n // the interrupted operation. We are certainly not retrying anything\n // for them as it is too dangerous and application-specific.\n\n if (client.connectionsMade > 1 && client.originalCommands.length > 0) {\n if (exports.debug) {\n sys.debug(\"[RECONNECTION] some commands orphaned (\" + \n client.originalCommands.length + \"). notifying...\");\n }\n\n client.callbackOrphanedCommandsWithError();\n }\n \n client.originalCommands = [];\n client.flushQueuedCommands();\n\n client.emit(eventName, client);\n });\n\n stream.addListener('error', function (e) {\n if (exports.debugMode)\n sys.debug(\"[ERROR] Connection to redis encountered an error: \" + e);\n });\n\n stream.addListener(\"data\", function (buffer) {\n if (exports.debugMode)\n sys.debug(\"[RECV] \" + debugFilter(buffer));\n\n client.replyParser.feed(buffer);\n });\n\n stream.addListener(\"error\", function (e) {\n\tif (exports.debugMode)\n\t sys.debug('[ERROR] ' + e);\n\tclient.replyParser.clearState();\n\tclient.maybeReconnect();\n\tthrow e;\n });\n\n stream.addListener(\"end\", function () {\n if (exports.debugMode && client.originalCommands.length > 0) {\n sys.debug(\"Connection to redis closed with \" + \n client.originalCommands.length + \n \" commands pending replies that will never arrive!\");\n }\n\n stream.end();\n });\n\n stream.addListener(\"close\", function (hadError) {\n if (exports.debugMode)\n sys.debug(\"[NO CONNECTION]\");\n\n client.maybeReconnect();\n });\n}",
"testConnect() {\n const outerConnectCallback = recordFunction();\n const innerConnectCallback = recordFunction();\n\n // Connect the two channels.\n outerChannel.connect(outerConnectCallback);\n innerChannel.connect(innerConnectCallback);\n mockClock.tick(1000);\n\n // Check that channels were connected and callbacks invoked.\n assertEquals(1, outerConnectCallback.getCallCount());\n assertEquals(1, innerConnectCallback.getCallCount());\n assertTrue(outerChannel.isConnected());\n assertTrue(innerChannel.isConnected());\n }",
"function midsockets(options) {\n if (typeof options == \"string\") { options = {url: options}; }\n return new midsockets.SockjsClient(options);\n }",
"static connectToMultiplexingRemoteServiceBroker(server, stream, cancellationToken = cancellationtoken_1.default.CONTINUE) {\n return __awaiter(this, void 0, void 0, function* () {\n assert(server);\n assert(stream);\n const clientMetadata = new serviceBrokerClientMetadata_1.ServiceBrokerClientMetadata();\n clientMetadata.supportedConnections = 'multiplexing';\n const result = yield RemoteServiceBroker.initializeBrokerConnection(server, cancellationToken, clientMetadata, stream);\n result.ownsMxStream = false;\n return result;\n });\n }",
"function createClient(options) {\n\t\tif(options) {\n\t\t\tclientHost = options.host || 'localhost';\n\t\t\tclientPort = options.port || 9000;\n\t\t} else {\n\t\t\tclientHost = 'localhost';\n\t\t\tclientPort = 9000;\n\t\t}\n\t\t\n\t\tclient = new BinaryClient('ws://' + clientHost + ':' + clientPort + '/');\n\n\t\tif(client == false) {\n\t\t\treturn;\n\t\t}\n\n\t\t//wait for client open\n\t\tclient.on('open', function() {\n\t \t\tidleStreams = [];\n\t \t\tactiveStreams = [];\n\n\t \t\tfor (var i = 0; i < MAX_STREAMS; i++) {\n\t\t\t\tvar stream;\n\t\t\t\tidleStreams.push(stream);\n\t\t\t}\n\t \t});\n\n\t \t/**\n\t \t * Receives messages from the server\n\t \t * @param stream -- the data sent\n\t \t * @param meta -- information describing data sent\n\t \t */\n\t\tclient.on('stream', function (stream, meta) {\n\t\t\tif (meta.cmd === Server2ClientFlag.sent) {\n\t\t\t\tfileCount++;\n\t\t\t\tconsole.log('done sending file chunk ' + meta.chunkName);\n\t\t\t\tidleStreams.push(activeStreams.shift());\n\t\t\t\tsend();\n\t\t\t} else if (meta.cmd === Server2ClientFlag.sentMul) {\n\t\t\t\tfileCount++;\n\t\t\t\tconsole.log('done sending file chunk ' + meta.chunkName);\n\t\t\t\tidleStreams.push(activeStreams.shift());\n\t\t\t\tsendMul();\n\t\t\t} else if (meta.cmd === Server2ClientFlag.error) {\n\t\t\t\t//notify client that there was an error.\n\t\t\t} else if(meta.cmd === Client2ServerFlag.transferComplete) {\n\n\t\t\t}\n\t\t});\n\t\t\n\t\tclient.on('close', function() {\n\t\t\tconsole.log('Client connection was stopped abruptly');\n\t\t});\n\n\t\tclient.on('error', function(error) {\n\t\t\tconsole.log(error);\n\t\t});\n\t\t\n\t\treturn client;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the score of a comparison with another subject by taking the Manhattan, or L_1 distance between the vectors. When the `weights` property is on, the method returns a weighted version of the L_1 distance. | function compareWithSubject(subject, subjectToCompare) {
var returnValue = 0.0
if(!weighted) {
for (index = 0; index < subjectToCompare.length; index++) {
var valueToAccumulate = subject[index] - subjectToCompare[index]
// Get absolute values
if (valueToAccumulate < 0) valueToAccumulate *= -1
returnValue += valueToAccumulate
}
} else {
var ourWeights = getWeights(subject)
var comparisonWeights = getWeights(subjectToCompare)
for (index = 0; index < subjectToCompare.length; index++) {
// Apply weights
var valueToAccumulate = subject[index] * ourWeights[index]
valueToAccumulate -= subjectToCompare[index] * comparisonWeights[index]
// Get absolute values
if (valueToAccumulate < 0) valueToAccumulate *= -1
returnValue += valueToAccumulate
}
}
return returnValue
} | [
"function weightedDistanceMatching(poseVector1, poseVector2) {\n const vector1PoseXY = poseVector1.slice(0, 34);\n const vector1Confidences = poseVector1.slice(34, 51);\n const vector1ConfidenceSum = poseVector1.slice(51, 52);\n\n const vector2PoseXY = poseVector2.slice(0, 34);\n\n // First summation\n const summation1 = 1 / vector1ConfidenceSum;\n\n // Second summation\n let summation2 = 0;\n for (let i = 0; i < vector1PoseXY.length; i++) {\n const tempConf = Math.floor(i / 2);\n const tempSum = vector1Confidences[tempConf] * Math.abs(vector1PoseXY[i] - vector2PoseXY[i]);\n summation2 += tempSum;\n }\n\n return summation1 * summation2;\n}",
"static compareWeights(a, b) {\n return a.weight - b.weight;\n }",
"function weightComparator(a, b) {\n return (a.weight >= 0 ? a.weight : 1000) - (b.weight >= 0 ? b.weight : 1000);\n }",
"function getSimilarity(tech1, tech2) {\n var hildeSimWeight = {\n \"activity\": 50\n };\n var simWeight = weight;\n var similarityScore = 0;\n\n for (property in hildeSimWeight) {\n similarityScore += getPropertySimilarityScore(tech1.hildesheimTechnique, tech2.hildesheimTechnique, property, hildeSimWeight[property]);\n }\n\n for (property in simWeight) {\n if (tech1[property] === tech2[property]) similarityScore += simWeight[property];\n else if (Math.abs(tech1[property] - tech2[property]) <= 1) similarityScore += simWeight[property] / 2; // doesn't work for gruppe, moderiert, dauer\n }\n\n return similarityScore;\n}",
"function euclidean(person1, person2) {\n // Ratings of person 1 and 2\n var ratings1 = ratings[person1];\n var ratings2 = ratings[person2];\n\n // Need to add up all the differences\n var sum = 0;\n\n // All the movies rated by person 1\n var movies = Object.keys(ratings1);\n // For every movie\n for (var i = 0; i < movies.length; i++) {\n var movie = movies[i];\n // As long as both rated the movie\n if (ratings2[movie] !== undefined) {\n var rating1 = ratings1[movie];\n var rating2 = ratings2[movie];\n // Difference between the ratings\n var diff = rating1 - rating2;\n // Square it\n sum += diff * diff;\n }\n }\n\n // This maps the distance to 0 and 1\n // Higher score is more similar\n return 1 / (1 + sqrt(sum));\n}",
"function weighted_dissimilarity(word_list1, word_list2, word_weight){\n if (word_list1.length == 0 || word_list2.length == 0){\n\treturn 0;\n }\n var prod11 = product(word_list1, word_list1, word_weight);\n var prod22 = product(word_list2, word_list2, word_weight);\n var prod12 = product(word_list1, word_list2, word_weight);\n // is it right?\n var cos12 = prod12 / Math.sqrt(0.1 + prod11 * prod22);\n return Math.sqrt(prod11 * prod22 * (1-cos12*cos12)) / word_list1.length / word_list2.length;\n}",
"function LevenshteinDistance(word1, word2){\n var len1 = word1.length;\n var len2 = word2.length;\n var matrix = [];\n for (var line = 0; line <= len1; line++) {\n matrix[line] = [];\n for (var column = 0; column <= len2; column++) matrix[line][column] = 0;\n }\n\n for (var i = 1; i <= len1; i++) matrix[i][0] = i;\n for (var j = 1; j <= len2; j++) matrix[0][j] = j;\n\n for (var j = 1; j <= len2; j++){\n for (var i = 1; i <= len1; i++){\n var cost = word1[i-1] == word2[j-1] ? 0 : 1;\n matrix[i][j] = Math.min(Math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1), matrix[i-1][j-1] + cost);\n }\n }\n return matrix[len1][len2];\n}",
"function weightedManhattanDistance(nodeOne, nodeTwo, nodes) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n\n if (noc[0] < ntc[0] && noc[1] < ntc[1]) {\n\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] < ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] < ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n }\n\n\n return xChange + yChange;\n\n\n}",
"function madlibsWeight(p1, p2) {\n var madlib = `<p>See the weight difference between the ${p1.name} vs ${p2.name}.</p>`;\n\n try {\n const w1_lbs = convert(p1.weight.data[0].val).from('oz').to('lb');\n const w2_lbs = convert(p2.weight.data[0].val).from('oz').to('lb');\n\n const w1_kg = convert(p1.weight.data[0].val).from('oz').to('kg');\n const w2_kg = convert(p2.weight.data[0].val).from('oz').to('kg');\n\n const diff_oz = Math.round(\n (p1.weight.data[0].val - p2.weight.data[0].val) * 100\n ) / 100;\n const adjective = (diff_oz > 0) ? 'more' : 'less';\n if (w1_lbs === w2_lbs) {\n madlib += `<p>The ${p1.name} and ${p2.name} both weigh ${w1_lbs} lbs (${w1_kg} kg)</p>`;\n } else {\n madlib += `<p>The lightest version of the ${p1.name} weighs <b>${Math.abs(diff_oz)} ounces ${adjective}</b> than the lighest version of the ${p2.name}.</p>`;\n }\n return madlib;\n } catch (err) {\n return madlib;\n }\n}",
"function euclidean(ratings, user1, user2) {\n // Ratings of person 1 and 2\n const ratings1 = ratings[user1];\n const ratings2 = ratings[user2];\n\n // Need to add up all the differences\n let sum = 0;\n\n // All the movies rated by person 1\n const movies = Object.keys(ratings1);\n // For every movie\n for (let i = 0; i < movies.length; i += 1) {\n const movie = movies[i];\n // As long as both rated the movie\n if (ratings2[movie] !== undefined) {\n const rating1 = ratings1[movie];\n const rating2 = ratings2[movie];\n // Difference between the ratings\n const diff = rating1 - rating2;\n // Square it\n sum += diff * diff;\n }\n }\n\n // This maps the distance to 0 and 1\n // Higher score is more similar\n return 1 / (1 + Math.sqrt(sum));\n}",
"function getWeight(distToOthersSquared, distToPointSquared) {\n return distToOthersSquared - distToPointSquared;\n }",
"distance(room, s1, s2) {\n const d1 = room.findStudentDesk(s1),\n d2 = room.findStudentDesk(s2);\n\n if (!d1 || !d2) {\n return 0.0;\n }\n\n return d1.distance(d2);\n }",
"function LevenshteinResults(distance, insertCount, deleteCount, substituteCount) {\n this.distance = distance;\n this.insertCount = insertCount;\n this.deleteCount = deleteCount;\n this.substituteCount = substituteCount;\n }",
"function comparisonByDistance(a, b) {\n return a.distance - b.distance;\n }",
"function compareCities(searchType, cityInd1, cityInd2, criteria, weights, numToSatisfy)\n{\n\t// alpha is the similarity of the two cities\n\tvar alpha;\n\tvar pivotTemp;\n\tvar otherTemp;\n\tvar temp;\n\tvar i;\n\n\tswitch(searchType){\n\t\tcase 0: // Root Sum Squared Relative Error\n\t\t\talpha = 0.0;\n\t\t\tfor(i = 0; i < criteria.length; i++)\n\t\t\t{\n\t\t\t\tpivotTemp = DataSet[cityInd1][criteria[i]];\n\t\t\t\totherTemp = DataSet[cityInd2][criteria[i]];\n\t\t\t\ttemp = (pivotTemp - otherTemp)/pivotTemp;\n\t\t\t\talpha += temp*temp;\n\t\t\t}\n\t\t\treturn Math.sqrt(alpha);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn alpha;\n}",
"function heuristicFunction(heuristicFunction, pos0, pos1, weight) {\n let dx = Math.abs(pos1.x - pos0.x);\n let dy = Math.abs(pos1.y - pos0.y);\n switch (heuristicFunction) {\n case 'Manhatten':\n /**\n * Calculate the Manhatten distance.\n * Generally: Overestimates distances because diagonal movement not taken into accout.\n * Good for a 4-connected grid (diagonal movement not allowed)\n */\n return (dx + dy) * weight;\n case 'Euclidean':\n /**\n * Calculate the Euclidean distance.\n * Generally: Underestimates distances, assuming paths can have any angle.\n * Can be used f.e. when units can move at any angle.\n */\n return Math.sqrt(dx * dx + dy * dy) * weight;\n case 'Chebyshev':\n /**\n * Calculate the Chebyshev distance.\n * Should be used when diagonal movement is allowed.\n * D * (dx + dy) + (D2 - 2 * D) * Math.min(dx, dy)\n * D = 1 and D2 = 1\n * => (dx + dy) - Math.min(dx, dy)\n * This is equivalent to Math.max(dx, dy)\n */\n return Math.max(dx, dy) * weight;\n case 'Octile':\n /**\n * Calculate the Octile distance.\n * Should be used on an 8-connected grid (diagonal movement allowed).\n * D * (dx + dy) + (D2 - 2 * D) * Math.min(dx, dy)\n * D = 1 and D2 = sqrt(2)\n * => (dx + dy) - 0.58 * Math.min(dx, dy)\n */\n return (dx + dy - 0.58 * Math.min(dx, dy)) * weight;\n }\n}",
"closestApproachII2(l1l) {\n let ca = this.findClosestApproachII(l1l);\n if (ca)\n return ca.dist2;\n // parallel\n let l0 = this.vector;\n let d0 = l1l.P0.minus(this.P0);\n let q = d0.minus(l0.times(l0.dot(d0) / l0.magnitude2));\n return q.magnitude2;\n }",
"function manhattanDistance(p1, p2) {\n\treturn [(p2[0] - p1[0]), (p2[1] - p1[1])];\n}",
"function scoreMatch (A) {\n\n\t// initialize score\n\tvar score = 0;\n\n\t// Set weights for each list\n\tvar weights = [5, 2, 2, 1];\n\n\tfor (var i = 0; i < numRows; i++) {\n\n\t\tfor (var j = 0; j < numCols; j++) {\n\n\t\t\tscore += weights[i]*A[i][j];\t\n\n\t\t}\n\t}\n\n\treturn score;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The bigger of the two totals are taken unless, the biggertotal is greater than 21, the chosen total is display in the game area | function biggerTotal(hand) {
if (hand.firsttotal < hand.secondtotal && hand.secondtotal <= 21) {
hand.total = hand.secondtotal;
} else {
hand.total = hand.firsttotal;
}
playerscore.innerHTML = playerHand.total;
dealerscore.innerHTML = dealerHand.total;
} | [
"function evaluateDealerTotal(){ \n displayDealerFirstCard(); \n if (dealer.total > 21){\n $(\"#instructions\").text(dealer.name + \" busts\")\n winMonies();\n }else if (dealer.total < 17){ //if the dealer's total is under 17, they have to take cards until they are over 17. right??? i think??\n hitDealer();\n }else{\n compareTotals();\n }\n }",
"function checkDealerTotal() {\r\n\r\n // dealer stands on 17 (or more)\r\n if (dealerTotal > 16 && dealerTotal < 21) {\r\n dealerMessage.innerHTML = 'Dealer Stands'\r\n comparePlayerVSDealer();\r\n }\r\n // dealer got 21, see if the player did also\r\n else if (dealerTotal == 21) {\r\n comparePlayerVSDealer();\r\n }\r\n // dealer busted\r\n else if (dealerTotal > 21) {\r\n dealerMessage.innerHTML = 'Dealer Busted'\r\n win();\r\n }\r\n // dealer needs to hit again\r\n else {\r\n dealerHit();\r\n }\r\n}",
"function hitung_total(){\n\t\t\tvar b_kirim = $(\"#biaya_kirim\").val();\n\t\t\tvar b_packing = $(\"#biaya_packing\").val();\n\t\t\tvar b_asuransi = $(\"#biaya_asuransi\").val();\n\t\t\tvar dibayar = $(\"#dibayar\").val();\n\n\t\t\tvar totalnya = parseInt(b_kirim) + parseInt(b_packing) + parseInt(b_asuransi);\n\t\t\t$(\"#subtotal\").html(rupiah(totalnya));\n\t\t\t\n\t\t\tif(dibayar >= totalnya){\n\t\t\t\tvar totalakhir = parseInt(dibayar) - totalnya;\n\t\t\t\t$('#status_bayar').val('lunas');\n\t\t\t\t$('#ketuang').html('Kembalian');\n\t\t\t}else{\n\t\t\t\tvar totalakhir = totalnya - parseInt(dibayar);\n\t\t\t\t$('#status_bayar').val('belum_lunas');\n\t\t\t\t$('#ketuang').html('Kekurangan');\n\t\t\t}\n\t\t\t$(\"#total\").html(rupiah(totalakhir));\n\t\t}",
"function hitung_total(){\n\t\t\tvar b_kirim = $(\"#biaya_kirim\").val();\n\t\t\tvar b_packing = $(\"#biaya_packing\").val();\n\t\t\tvar b_asuransi = $(\"#biaya_asuransi\").val();\n\t\t\tvar dibayar = $(\"#dibayar\").val();\n\t\t\tvar totalnya = parseInt(b_kirim) + parseInt(b_packing) + parseInt(b_asuransi);\n\t\t\t$(\"#subtotal\").html(rupiah(totalnya));\n\t\t\t\n\t\t\tif(dibayar >= totalnya){\n\t\t\t\tvar totalakhir = parseInt(dibayar) - totalnya;\n\t\t\t\t$('#status_bayar').val('lunas');\n\t\t\t\t$('#ketuang').html('Kembalian');\n\t\t\t}else{\n\t\t\t\tvar totalakhir = totalnya - parseInt(dibayar);\n\t\t\t\t$('#status_bayar').val('belum_lunas');\n\t\t\t\t$('#ketuang').html('Kekurangan');\n\t\t\t}\n\t\t\t$(\"#total\").html(rupiah(totalakhir));\n\t\t}",
"function crystalClick () {\n yourTotal += parseInt($(this).attr(\"value\"));\n $(\".yourTotal-box\").html(yourTotal);\n if (yourTotal === targetNumber) {\n wins++;\n gameReset();\n }\n else if (yourTotal > targetNumber) {\n losses++;\n gameReset();\n };\n }",
"function hitung_total(){\n\t\t\tvar b_kirim = $(\"#biaya_kirim_darat\").val();\n\t\t\tvar b_packing = $(\"#biaya_packing_darat\").val();\n\t\t\tvar b_asuransi = $(\"#biaya_asuransi_darat\").val();\n\t\t\tvar dibayar = $(\"#dibayar_darat\").val();\n\t\t\tvar totalnya = parseInt(b_kirim) + parseInt(b_packing) + parseInt(b_asuransi);\n\t\t\t$(\"#subtotal_darat\").html(rupiah(totalnya));\n\t\t\t\n\t\t\tif(dibayar >= totalnya){\n\t\t\t\tvar totalakhir = parseInt(dibayar) - totalnya;\n\t\t\t\t$('#status_bayar_darat').val('lunas');\n\t\t\t\t$('#ketuang_darat').html('Kembalian');\n\t\t\t}else{\n\t\t\t\tvar totalakhir = totalnya - parseInt(dibayar);\n\t\t\t\t$('#status_bayar_darat').val('belum_lunas');\n\t\t\t\t$('#ketuang_darat').html('Kekurangan');\n\t\t\t}\n\t\t\t$(\"#total_darat\").html(rupiah(totalakhir));\n\t\t}",
"function billTotal(subTotal){\n\treturn subTotal + subTotal*.095 + subTotal*.15;\n}",
"plusGood() {\r\n if (this.costOngood >= 0 && this.costOngood < this.other - this.costOnentertainment - this.costOnrotten) {\r\n this.costOngood++;\r\n document.getElementById(\"costForgood\").innerHTML = \"$\" + this.costOngood;\r\n }\r\n }",
"function hitung_total_laut(){\n\t\t\tvar b_kirim = $(\"#biaya_kirim_laut\").val();\n\t\t\tvar b_packing = $(\"#biaya_packing_laut\").val();\n\t\t\tvar b_asuransi = $(\"#biaya_asuransi_laut\").val();\n\t\t\tvar dibayar = $(\"#dibayar_laut\").val();\n\t\t\tvar totalnya = parseInt(b_kirim) + parseInt(b_packing) + parseInt(b_asuransi);\n\t\t\t$(\"#subtotal_laut\").html(rupiah(totalnya));\n\t\t\t\n\t\t\tif(dibayar >= totalnya){\n\t\t\t\tvar totalakhir = parseInt(dibayar) - totalnya;\n\t\t\t\t$('#status_bayar_laut').val('lunas');\n\t\t\t\t$('#ketuang_laut').html('Kembalian');\n\t\t\t}else{\n\t\t\t\tvar totalakhir = totalnya - parseInt(dibayar);\n\t\t\t\t$('#status_bayar_laut').val('belum_lunas');\n\t\t\t\t$('#ketuang_laut').html('Kekurangan');\n\t\t\t}\n\t\t\t$(\"#total_laut\").html(rupiah(totalakhir));\n\t\t}",
"function updateSubTotalScore($clickedCell) {\n if ($clickedCell.parent().hasClass(\"upperSection\")) {\n $subTotalCell = $(\n \"#subTotalRow :nth-child(\" + (playerYatzyColumn + 2) + \")\"\n );\n $subTotalCell.text(\n Number($subTotalCell.text()) + (result === \"/\" ? 0 : result)\n );\n\n subTotalCellToSendToOtherPlayers = {\n rowId: \"SUBTOTAL\",\n yatzyColumn: playerYatzyColumn,\n score: $subTotalCell.text()\n };\n\n checkBonus();\n }\n\n // Checks whether or not the player has a bonus, and updates the bonus cell accordingly\n function checkBonus() {\n $bonusCell = $(\"#bonusRow :nth-child(\" + (playerYatzyColumn + 2) + \")\");\n numOfClickedCellsInUpperSection = $(\n \".upperSection .clicked:nth-child(\" + (playerYatzyColumn + 2) + \")\"\n ).length;\n\n var hasBonus = Number($subTotalCell.text()) >= 63,\n upperSectionIsComplete = numOfClickedCellsInUpperSection === 6;\n\n if (hasBonus || upperSectionIsComplete) {\n if (hasBonus) {\n $bonusCell.text(50);\n } else {\n $bonusCell.text(\"/\");\n }\n\n bonusCellToSendToOtherPlayers = {\n rowId: \"BONUS\",\n yatzyColumn: playerYatzyColumn,\n score: $bonusCell.text()\n };\n }\n }\n }",
"function filtertotal(num) {\n return num.Total > 50000;}",
"function bonusCheck() {\n if (bonusCheck1 === null && ((plr1Upper.reduce((acc, num) => acc += num, 0)) >= 63)) {\n plr1Upper.push(35)\n bonus1.innerText = 35\n bonusCheck1 = 1\n } else {\n bonus1.innerText = \"\"\n }\n if (bonusCheck2 === null && ((plr2Upper.reduce((acc, num) => acc += num, 0)) >= 63)) {\n plr2Upper.push(35)\n bonus2.innerText = 35\n bonusCheck2 = 1\n } else {\n bonus2.innerText = \"\"\n }\n}",
"function checkTotal(){\n var fare = parseFloat(window.staticTexts()[2].name().replace('$',''));\n var tip = parseFloat(window.staticTexts()[4].name().replace('$',''));\n var docFee = parseFloat(window.staticTexts()[6].name().replace('$',''));\n var curbCredits = parseFloat(window.staticTexts()[9].name().replace('$',''));\n var total = parseFloat(window.staticTexts()[12].name().replace('$',''));\n var actualTotal = (fare+tip+docFee+curbCredits).toFixed(2);\n if (actualTotal == total){\n UIALogger.logPass(\"Total calculated correctly\");\n }\n else{\n UIALogger.logFail(\"Total was not calculated correctly\");\n }\n}",
"function compare() {\n console.log(`Working total is: ${workingTotal} and target number is ${targetNumber}`);\n if (targetNumber === workingTotal) {\n winGame();\n } else if (targetNumber < workingTotal) {\n loseGame();\n }\n}",
"function checkTotals(){\n\tgrandTotal = $(\"#departmentCourses li:visible\").length;\n\tnotUsingCanvasTotal = $(\"#departmentCourses .icon-remove-sign:visible\").length;\n\tnotUsingCanvasPer = Math.floor((notUsingCanvasTotal/grandTotal) * 100);\n\tusingCanvasTotal = grandTotal-notUsingCanvasTotal;\n\tusingCanvasPer = Math.floor((usingCanvasTotal/grandTotal) * 100);\n\tnoSyllabusTotal = $(\"#departmentCourses .icon-question-sign:visible\").length;\n\tnoSyllabusPer = Math.floor((noSyllabusTotal/usingCanvasTotal) * 100);\n\thasSyllabusTotal = $(\"#departmentCourses .icon-ok-sign:visible\").length;\n\thasSyllabusPer = Math.floor((hasSyllabusTotal/usingCanvasTotal) * 100);\n\tusedWizardTotal = $(\"#departmentCourses .icon-magic:visible\").length;\n\tusedWizardPer = Math.floor((usedWizardTotal/grandTotal) * 100);\n\n\t$('.grandTotal').html(grandTotal);\n\t$('.notUsingCanvasTotal').html(notUsingCanvasTotal);\n\t$('.notUsingCanvasPer').html(notUsingCanvasPer+'%');\n\t$('.usingCanvasTotal').html(usingCanvasTotal);\n\t$('.usingCanvasPer').html(usingCanvasPer+'%');\n\t$('.noSyllabusTotal').html(noSyllabusTotal);\n\t$('.noSyllabusPer').html(noSyllabusPer+'%');\n\t$('.hasSyllabusTotal').html(hasSyllabusTotal);\n\t$('.hasSyllabusPer').html(hasSyllabusPer+'%');\n\t$('.usedWizardTotal').html(usedWizardTotal);\n\t$('.usedWizardPer').html(usedWizardPer+'%');\n\n\t$('#canvasUse').highcharts({\n\t\tchart: {type: 'column'},\n\t\tcolors: [\n\t\t '#999999', \n\t\t '#3a87ad'\n\t\t],\n\t\ttitle: {text: null },\n\t\txAxis: {categories: ['Canvas Usage'] },\n\t\tyAxis: {\n\t\t min: 0,\n\t\t title: {text: 'Course Percentage'}\n\t\t},\n\t\ttooltip: {\n\t\t pointFormat: '<span style=\"color:{series.color}\">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',\n\t\t shared: true\n\t\t},\n\t\tplotOptions: {\n\t\t column: {stacking: 'percent'}\n\t\t},\n\t series: [{\n\t\t name: 'Not In Canvas',\n\t\t data: [notUsingCanvasTotal]\n\t\t}, {\n\t\t name: 'In Canvas',\n\t\t data: [usingCanvasTotal]\n\t\t}]\n\t});\n\t$('#syllabusState').highcharts({\n\t\tchart: {type: 'column'},\n\t\tcolors: [\n\t\t '#B94A48', \n\t\t '#468847'\n\t\t],\n\t\ttitle: {text: null },\n\t\txAxis: {categories: ['Syllabus Usage'] },\n\t\tyAxis: {\n\t\t min: 0,\n\t\t title: {text: '% Courses Using Canvas'}\n\t\t},\n\t\ttooltip: {\n\t\t pointFormat: '<span style=\"color:{series.color}\">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',\n\t\t shared: true\n\t\t},\n\t\tplotOptions: {\n\t\t column: {stacking: 'percent'}\n\t\t},\n\t series: [{\n\t\t name: 'No Content in Syllabus Page',\n\t\t data: [noSyllabusTotal]\n\t\t}, {\n\t\t name: 'Content in Syllabus Page',\n\t\t data: [hasSyllabusTotal]\n\t\t}]\n\t});\n\t// Data specific to \"All USU Courses\"\n\tif($(\".retrieveAllCourses:visible\").length>0){\n\t\tvar collegeList = [];\n\t\tvar collegeTotalCourses = [];\n\t\tvar collegePublished = [];\n\t\tvar collegeUnpublished = [];\n\t\tvar collegeUsingSyllabus = [];\n\t\tvar collegeNotUsingSyllabus = [];\n\t\t$('h2').each(function(){\n\t\t\tcollegeList.push($(this).text());\n\t\t\tcollegeTotalCourses.push($(this).parents(\".collegeList\").find('li:visible').length);\n\t\t\tcollegePublished.push($(this).parents(\".collegeList\").find('.usingCanvas:visible').length);\n\t\t\tcollegeUnpublished.push($(this).parents(\".collegeList\").find('.notUsingCanvas:visible').length);\n\t\t\tcollegeUsingSyllabus.push($(this).parents(\".collegeList\").find('.icon-ok-sign:visible').length);\n\t\t\tcollegeNotUsingSyllabus.push($(this).parents(\".collegeList\").find('.icon-question-sign:visible').length);\n\t\t\tvar myClass = $(this).index();\n\t\t\t$(this).before('<a name=\"'+myClass+'\"></a>');\n\t\t\tvar noSyllabus = $(this).next('.collegeGroup').find('.icon-question-sign').length;\n\t\t\tvar hasSyllabus = $(this).next('.collegeGroup').find('.icon-ok-sign').length;\n\t\t\tvar totalCourses = noSyllabus+hasSyllabus;\n\t\t\tvar name = $(this).html();\n\t\t\t$(this).find(\"a\").remove();\n\t\t\t$(this).append('<a class=\"topLink\" href=\"#top\"><i class=\"icon-circle-arrow-up\"></i> Top</a>');\n\t\t});\n\t\t$('#collegeCount').highcharts({\n\t chart: {type: 'bar'},\n\t colors: [\n\t\t\t\t \t'#B94A48', \n\t\t\t\t \t'#468847',\n\t \t'#3a87ad',\n\t\t\t\t \t'#999999', \n\t \t'#000000'\n\t\t\t\t],\n\t title: {\n\t text: 'USU Canvas Usage'\n\t },\n\t subtitle: {\n\t text: 'By College (Based on courses with student enrollments)'\n\t },\n\t xAxis: {\n\t categories: collegeList,\n\t title: {text: null }\n\t },\n\t yAxis: {\n\t min: 0,\n\t title: {\n\t text: 'Number of Courses',\n\t align: 'high'\n\t },\n\t labels: {overflow: 'justify'}\n\t },\n\t tooltip: {valueSuffix: ' Courses'},\n\t plotOptions: {\n\t bar: {\n\t dataLabels: {\n\t enabled: true\n\t }\n\t }\n\t },\n\t legend: {\n\t layout: 'vertical',\n\t align: 'right',\n\t verticalAlign: 'top',\n\t x: -40,\n\t y: 100,\n\t floating: true,\n\t borderWidth: 1,\n\t backgroundColor: '#FFFFFF',\n\t shadow: true\n\t },\n\t credits: {\n\t enabled: false\n\t },\n\t series: [{\n\t \tname: 'No Content in Syllabus Page',\n\t \tdata: collegeNotUsingSyllabus\n\t }, {\n\t \tname: 'Content in Syllabus Page',\n\t \tdata: collegeUsingSyllabus\n\t }, {\n\t name: 'Courses Published',\n\t data: collegePublished\n\t }, {\n\t name: 'Courses UnPublished',\n\t data: collegeUnpublished\n\t }, {\n\t name: 'Total Courses',\n\t data: collegeTotalCourses\n\t }]\n\t });\n\t}\n\tgetInstructors();\n}",
"function displayTotal(value, element) {\n\t\tvar $total = element;\n\t\tif (value <= 21) {\n\t\t\t$total.text(value);\n\t\t} else {\n\t\t\t$total.text('BUST!');\n\t\t}\n\t}",
"function severity_anx(total) {\n const severityField = document.querySelector('#severityanx');\n\n\n if (total === 0){\n severity.innerText = \"All zero\"\n } else if (total > 0 && total < 5) {\n severityField.innerText = \"Minimal Anxiety\";\n } else if (total > 4 && total < 10) {\n severityField.innerText = \"Mild Anxiety\";\n } else if (total > 9 && total < 15) {\n severityField.innerText = \"Moderate Anxiety\";\n } else if (total > 14 && total < 20) {\n severityField.innerText = \"Moderately Severe Anxiety\";\n } else if (total > 19) {\n severityField.innerText = \"Severe Anxiety\";\n }\n}",
"function calculateTotals(eachMatch){\n\t\t\t//-- This block mainly converts the batting score to a number from its numerous possible types --//\n\t\t\tvar batScr = eachMatch[\"batting_score\"];\n\t\t\tif(typeof batScr === \"number\"){\n\t\t\t\t//when batted and was out\n\t\t\t\t$scope.sachinStatHolder.timesOut++;\n\t\t\t}else if(batScr.charAt(batScr.length - 1) == \"*\"){\n\t\t\t\t//when batted and was not-out, the values are given as \"58*\" meaning 58 not out.\n\t\t\t\tbatScr = Number(batScr.slice(0, batScr.length-1));\n\t\t\t}else{\n\t\t\t\t//when DNB - Did Not Bat\n\t\t\t\tbatScr = 0;\n\t\t\t}\n\t\t\t//-- ----------------------------------------------------------------------------------------- --//\n\t\t //Adding the score to the total\n\t\t\t$scope.sachinStatHolder.battingScore += batScr;\n\t\t\t//calculating top score\n\t\t\tif(batScr > $scope.sachinStatHolder.topScore){\n\t\t\t\t$scope.sachinStatHolder.topScore = batScr;\n\t\t\t}\n\t\t\t//calculating 100s and 50s\n\t\t\tif(batScr >= 50){\n\t\t\t\tif(batScr >= 100){\n\t\t\t\t\t$scope.sachinStatHolder.hundreds++;\n\t\t\t\t}else{\n\t\t\t\t\t$scope.sachinStatHolder.fifty++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$scope.sachinStatHolder.wickets += (typeof eachMatch[\"wickets\"] === \"number\") ? eachMatch[\"wickets\"] : 0;\n\t\t\t$scope.sachinStatHolder.runsConceded += (typeof eachMatch[\"runs_conceded\"] === \"number\") ? eachMatch[\"runs_conceded\"] : 0;\n\t\t\t$scope.sachinStatHolder.catches += (typeof eachMatch[\"catches\"] === \"number\") ? eachMatch[\"catches\"] : 0;\n\t\t\t$scope.sachinStatHolder.stumps += (typeof eachMatch[\"stumps\"] === \"number\") ? eachMatch[\"stumps\"] : 0;\n\t\t\tif(eachMatch[\"match_result\"].toLowerCase() == \"lost\"){\n\t\t\t\t$scope.sachinStatHolder.matchesLost++;\n\t\t\t}else{\n\t\t\t\t$scope.sachinStatHolder.matchesWon++;\n\t\t\t}\n\t\t\t//calculating overall stats here\n\t\t\t$scope.sachinStatHolder.totalMatches = $scope.sachinStatHolder.matchesWon + $scope.sachinStatHolder.matchesLost;\n\t\t\t$scope.sachinStatHolder.battingAvg = ($scope.sachinStatHolder.battingScore / $scope.sachinStatHolder.timesOut).toFixed(2);\n\t\t\t$scope.sachinStatHolder.bowlingAvg = ($scope.sachinStatHolder.runsConceded / $scope.sachinStatHolder.wickets).toFixed(2);\n\n\t\t\t//creating the timeline\n\t\t\trunHistoryLabels.push(eachMatch[\"date\"]);\n\t\t\trunHistoryData.push(batScr);\n\t\t}//end of calculateTotals()",
"function displayTotal() {\n\tscreen1.bugCount.html(prettyNumber(Math.round(state.larvae)));\n\tscreen1.larvaePerSec.html(prettyNumber(state.lps));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if O wins,it has an array and a number as parameters | function checkO(array,i){
var wincombo=[[],[],[],[],[],[],[],[]];
wincombo[0]=[document.getElementById("1"),document.getElementById("2"),document.getElementById("3")];
wincombo[1]=[document.getElementById("4"),document.getElementById("5"),document.getElementById("6")];
wincombo[2]=[document.getElementById("7"),document.getElementById("8"),document.getElementById("9")];
wincombo[3]=[document.getElementById("1"),document.getElementById("4"),document.getElementById("7")];
wincombo[4]=[document.getElementById("2"),document.getElementById("5"),document.getElementById("8")];
wincombo[5]=[document.getElementById("3"),document.getElementById("6"),document.getElementById("9")];
wincombo[6]=[document.getElementById("1"),document.getElementById("5"),document.getElementById("9")];
wincombo[7]=[document.getElementById("3"),document.getElementById("5"),document.getElementById("7")];
if(wincombo[i][0].innerHTML.match("circle")&&wincombo[i][1].innerHTML.match("circle")&&wincombo[i][2].innerHTML.match("circle")){
if (counter==10){
myFun(2);
done=true;
document.getElementsByTagName("p")[0].innerHTML="Player O win";
colorChange(wincombo,i);
}
else{
myFun(2);
done=true;
finishGame=true;
document.getElementsByTagName("p")[0].innerHTML="Player O win";
colorChange(wincombo,i);
}
}
} | [
"function isO(piece){ return piece == 1 || piece == 2;}",
"function arrCheck (a){\n if ((a[0]===1 || a[1]===1)||(a[0]===3 || a[1]===3)){\n return \"yes it is\"\n } else {\n return \"No its not\"\n }\n}",
"function checkNoArrays(checkPlayer,t,s)\n{\n\tswitch(t)\n\t{\n\t\tcase \"suspect\":\n\t\t\treturn players[checkPlayer].suspects.no.indexOf(s);\n\t\tcase \"weapon\":\n\t\t\treturn players[checkPlayer].weapons.no.indexOf(s);\n\t\tcase \"room\":\n\t\t\treturn players[checkPlayer].rooms.no.indexOf(s);\n\t\tdefault:\n\t\t\tconsole.log(\"error\");\n\t\t\treturn 0;\n\t}\n}",
"function checkWin(){\r\n if(player.poison == poisonPotionArr.length){\r\n win = true;\r\n }\r\n}",
"function isContainedByArray(num, arr) {\r\tvar x;\r\tfor (x = 0; x < arr.length; x++) {\r\t\tif (arr[x] == num) return true;\r\t}\r\treturn false;\r}",
"function arrayDoesNot(arr) {\n if (arr.includes(1) || arr.includes(3) ) {\n return (\"no it is not\")\n }\n\n }",
"contains(num, arr) {\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === num) {\n return true;\n }\n }\n return false;\n }",
"contains(number, array) {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === number) {\n return true;\n }\n }\n return false;\n }",
"function checkSubArrays() {\n\t\t\twinningMove = subArray.every(function(val) {\n\t\t\t\treturn playerArr.indexOf(val) >= 0;\n\t\t\t});\n\t\t}",
"function oob(ar,n) {\n\tfor(var i=0;i<ar.length;i++) {\n\t\tif(ar[i] > n) {\n\t\t\treturn ar[i];\n\t\t}\n\t}\n\treturn 0;\n}",
"function noNumCheck(arr) {\n return (arr.indexOf(1) == -1 || arr.indexOf(3) == -1);\n }",
"function arrayLike(data) {\n return assigned(data) && greaterOrEqual(data.length, 0);\n }",
"function computerLogic() {\n\n // determines whether there are any available winning arrays for X or O\n\n arrayLoop()\n\n // checks for immediate winning array for O\n\n if (oArray.length === 3) {\n indexArray = oArray.findIndex(function (value) {\n return value.innerHTML === ''\n })\n\n // and selects the appropriate square \n\n oArray[indexArray].click()\n }\n\n // if not, checks if X needs to be blocked from winning\n\n else if (targetArray.length === 3) {\n\n cellIndex = targetArray.findIndex(function (value) {\n return value.innerHTML === ''\n })\n\n // and selects the apporpriate square\n\n targetArray[cellIndex].click()\n\n }\n\n // if not, checks for optimal placement (although the computer doesn't always play very intelligently if the human does counterintuitive things)\n\n else if (c4.innerHTML === '') {\n c4.click()\n }\n\n else if (c0.innerHTML === '' && c4.innerHTML !== '' && c5.innerHTML !== 'X') {\n c0.click()\n }\n else if (c2.innerHTML === '' && c0.innerHTML === 'O') {\n c2.click()\n }\n else if (c1.innerHTML === '') {\n c1.click()\n }\n\n else if (c6.innerHTML === '') {\n c6.click()\n }\n else if (c8.innerHTML === '') {\n c8.click()\n }\n\n else if (c3.innerHTML === '') {\n c3.click()\n }\n}",
"function arrayLike(data) {\n return assigned(data) && data.length >= 0;\n}",
"function array(numbers){\n for(let i=0;i<numbers.length;i++){\n if((numbers[i] === 1)||(numbers[i]===3)){\n return true;\n }\n }\n return false;\n }",
"function arrayLike (data) {\n return assigned(data) && number(data.length);\n }",
"function arrayLike(data) {\n return assigned(data) && data.length >= 0;\n }",
"function check1(element, array){\n\n\t\treturn array.includes(element)\n\t\n}",
"function exists(arr, num) {\n // implementation\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a unique version number 20140816a4d4bd9f | function createVersionNumber() {
return new Date().toJSON().slice(0, 10) + '--' + uniqueId();
} | [
"createVersion(){\n return \"key-\"+Math.floor(Date.now() / 1000);\n }",
"versionNumber () {\n let release = this.release();\n if (release) {\n return release.versionNumber\n }\n }",
"get version() {\n return crypto_1.createHash('md5').update(JSON.stringify(this.manifest())).digest('hex').slice(0, 10);\n }",
"function default_versionCode(version) {\n var nums = version.split('-')[0].split('.').map(Number);\n var versionCode = nums[0] * 10000 + nums[1] * 100 + nums[2];\n return versionCode;\n}",
"version() {\n return fmt('{0}.{1}.{2}', _.random(0, 11), _.random(0, 11), _.random(0, 11))\n }",
"function getProductVersionId(version) {\n if (version == '7.4') {\n return '206111201';\n }\n if (version == '7.3') {\n return '175004848';\n }\n if (version == '7.2') {\n return '130051253';\n }\n if (version == '7.1') {\n return '102311424';\n }\n if (version == '7.0') {\n return '101625504';\n }\n if (version == '6.x') {\n return '101625503';\n }\n return '';\n}",
"function generateVersionInfo() {\n const versionInfo = git.gitDescribeSync({ longSemver: true });\n\n if (versionInfo.dirty || versionInfo.distance) {\n let versionString = versionInfo.raw.startsWith('v') ? versionInfo.raw.substr(1) : versionInfo.raw;\n if (versionInfo.dirty) {\n versionString = `${versionString}-${Date.now().toString()}`;\n }\n if (!versionInfo.tag) {\n versionString = `0.0.0-${versionString}`;\n }\n\n return versionString;\n }\n\n return undefined;\n}",
"function generateVersionNumber(previousVersion){\n\tlet today = new Date();\n\tvar newMajor = `${today.getFullYear()}.${parseInt(today.getMonth()) + 1}`\n\tnewMajor = newMajor.substr(2);\n\toldMajorArr = previousVersion.split('.')\n\toldMajor = `${oldMajorArr[0]}.${oldMajorArr[1]}`\n\n\tif(oldMajor == newMajor){\n\t\tnewVersion = `${newMajor}.${parseInt(oldMajorArr[2]) + 1}`\n\t} else {\n\t\tnewVersion = newMajor + '.0'\n\t}\n\treturn newVersion;\n}",
"get versionId() {\n // Report the RTV.\n // TODO: Make this a more readable string.\n return this.opts.version;\n }",
"static async generateTagVersion() {\n let tag = await this.getTag();\n\n if (tag.charAt(0) === 'v') {\n tag = tag.slice(1);\n }\n\n return tag;\n }",
"getVersion() {\n const { bin, versionOption } = this.metadata;\n const version = execa_1.default.sync(bin, [versionOption]).stdout.trim();\n const match = version.match(/(\\d+)\\.(\\d+)\\.(\\d+)/u);\n return match ? match[0] : '0.0.0';\n }",
"function generateNewRevisionId() {\n return generateId(9);\n }",
"async getVersion() {\n return '';\n }",
"static getVersion() { return 1; }",
"get buildNumber()\n\t{\n\t\tvar build = 0;\n\t\tvar ver = Prefs.getPref(\"currentVersion\");\n\t\tvar vm = ver.match(/^(\\d+)\\.(\\d+)\\.(\\d+)/);\n\t\tif (vm)\n\t\t{\n\t\t\tbuild = parseInt(vm[3], 10);\n\t\t}\n\t\treturn build;\n\t}",
"function getBeautifulVersionnumber(ver) {\n\t\n\t// internal version number\n\tif(ver > 1000000) {\n\t\tvar parts = new Array();\n\t\t\n\t\tparts[3] = ver % 1000000;\n\t\tver = (ver - parts[3]) / 1000000;\n\t\tparts[2] = ver % 1000000;\n\t\tver = (ver - parts[2]) / 1000000;\n\t\tparts[1] = ver % 1000;\n\t\tver = (ver - parts[1]) / 1000;\n\t\tparts[0] = ver % 1000;\n\t}\n\t\n\t// raw number\n\telse {\n\t\tvar parts = ver ? ver.split(/\\./) : new Array();\n\t}\n\t\n\t// compose\n\tvar version = (parts[3] > 0) ? ((parts[3] > 1000) ? 'beta' : parts[3]) : undefined;\n\tversion = (parts[2] > 0) ? (((parts[2] > 1000) ? 'beta' : parts[2]) + (version ? (\".\" + version) : '')) : ((undefined == version) ? undefined : 0 + \".\" + version);\n\tversion = (parts[1] > 0) ? (parts[1] + (version ? (\".\" + version) : '')) : ((undefined == version) ? undefined : \"0.\" + version);\n\tversion = (parts[0] > 0) ? (parts[0] + (version ? (\".\" + version) : '.0')) : ((undefined == version) ? undefined : \"0.\" + version);\n\t\n\t//alert(parts[0] + \".\" + parts[1] + \".\" + parts[2] + \".\" + parts[3] + \" -- \" + version);\n\treturn version;\n}",
"function getBuildVersion() {\n if (isSnapshotStamp) {\n // Note that we cannot store the commit SHA as prerelease segment as it will not comply\n // with the semver specification in some situations. For example: `1.0.0-00abcdef` will\n // break since the SHA starts with zeros. To fix this, we create a prerelease segment with\n // label where the SHA is considered part of the label and not the prerelease number.\n // Here is an example of the valid format: \"1.0.0-sha-00abcdef\".\n // See issue: https://jubianchi.github.io/semver-check/#/^8.0.0/8.2.2-0462599\n return `${packageJson.version}-sha-${getAbbreviatedCommitSha()}`;\n }\n return packageJson.version;\n}",
"formatVersionNumber(version) {\n if (version) {\n return ('00000' + Number(version)).substr(-5, 5)\n }\n }",
"get versionId() {\n return this.getStringAttribute('version_id');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HW470: Cylinder derivative function | function cylinderDerivative(t) {
return 0
} | [
"function derivative(x, coefficients)\n{\n\tvar sum = 0;\n\tfor (i = POLY_DEG - 1; i >= 0; i--)\n\t{\n\t\tsum += (i + 1) * Math.pow(x, i) * coefficients[POLY_DEG - 1 - i];\n\t}\n\treturn sum;\n}",
"function derivative(f){\n return function(x){\n return (f(x+.01)-f(x)) / .01\n }\n}",
"function derivFunc(x) {\n return 3 * x * x - 2 * x;\n}",
"getDerivative(t) {\n if (this.solutionType === SolutionType.CRITICALLY_DAMPED) {\n assert && assert(this.angularFrequency !== undefined);\n return Math.exp(-this.angularFrequency * t) * (this.c2 - this.angularFrequency * (this.c1 + this.c2 * t));\n } else if (this.solutionType === SolutionType.UNDER_DAMPED) {\n assert && assert(this.frequency !== undefined);\n const theta = this.frequency * t;\n const cos = Math.cos(theta);\n const sin = Math.sin(theta);\n const term1 = this.frequency * (this.c2 * cos - this.c1 * sin);\n const term2 = 0.5 * this.dampingConstant * (this.c1 * cos + this.c2 * sin);\n return Math.exp(-0.5 * this.dampingConstant * t) * (term1 - term2);\n } else if (this.solutionType === SolutionType.OVER_DAMPED) {\n assert && assert(this.positiveRoot !== undefined);\n assert && assert(this.negativeRoot !== undefined);\n return this.c1 * this.negativeRoot * Math.exp(this.negativeRoot * t) + this.c2 * this.positiveRoot * Math.exp(this.positiveRoot * t);\n } else {\n throw new Error('Unknown solution type?');\n }\n }",
"function firstDerivative4thDegrees(f, x, h)\n{\n return (8*(f(x+h/2)-f(x-h/2))-f(x+h)+f(x-h))/(6*h);\n}",
"function cylinderCurve(t) {\n return 1\n}",
"function dragCoeff() {\n return 0.5 * cd * a * rho;\n}",
"function Cylinder(height, diameter) {\n this.height = height;\n this.diameter = diameter;\n this.volumen = function(){\n var radius = this.diameter/2;\n\n var volume = Math.PI*Math.pow(radius, 2)*this.height;\n\n return volume.toFixed(4);\n }\n}",
"function derivative(f, dx) {\n return function(x) {\n return (f(x + dx) - f(x)) / dx;\n };\n}",
"function dihedral2() {\n if (x < 0) {\n x = -x;\n inversions += 1;\n change = true;\n }\n if (y < 0) {\n y = -y;\n inversions += 1;\n change = true;\n }\n}",
"function derivative(t, r) {\n\n var res = [];\n res.push(0);\n\n for (var i = 1; i < r.length; i++) {\n var dt = t[i] - t[i - 1];\n var dr = r[i] - r[i - 1];\n res.push(dr / dt);\n }\n\n return res;\n }",
"getDragCoefficient() {\n var dragco;\n var dragCam0Thk5, dragCam5Thk5, dragCam10Thk5, dragCam15Thk5, dragCam20Thk5;\n var dragCam0Thk10,\n dragCam5Thk10,\n dragCam10Thk10,\n dragCam15Thk10,\n dragCam20Thk10;\n var dragCam0Thk15,\n dragCam5Thk15,\n dragCam10Thk15,\n dragCam15Thk15,\n dragCam20Thk15;\n var dragCam0Thk20,\n dragCam5Thk20,\n dragCam10Thk20,\n dragCam15Thk20,\n dragCam20Thk20;\n var dragThk5, dragThk10, dragThk15, dragThk20;\n var dragCam0, dragCam5, dragCam10, dragCam15, dragCam20;\n var camd = this.getCamber();\n var thkd = this.getThickness();\n var alfd = this.getAngle();\n\n dragCam0Thk5 =\n -9e-7 * Math.pow(alfd, 3) +\n 0.0007 * Math.pow(alfd, 2) +\n 0.0008 * alfd +\n 0.015;\n dragCam5Thk5 =\n 4e-8 * Math.pow(alfd, 5) -\n 7e-7 * Math.pow(alfd, 4) -\n 1e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0033 * alfd +\n 0.0301;\n dragCam10Thk5 =\n -9e-9 * Math.pow(alfd, 6) -\n 6e-8 * Math.pow(alfd, 5) +\n 5e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) -\n 0.0001 * Math.pow(alfd, 2) -\n 0.0025 * alfd +\n 0.0615;\n dragCam15Thk5 =\n 8e-10 * Math.pow(alfd, 6) -\n 5e-8 * Math.pow(alfd, 5) -\n 1e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) -\n 0.0027 * alfd +\n 0.0612;\n dragCam20Thk5 =\n 8e-9 * Math.pow(alfd, 6) +\n 1e-8 * Math.pow(alfd, 5) -\n 5e-6 * Math.pow(alfd, 4) +\n 6e-6 * Math.pow(alfd, 3) +\n 0.001 * Math.pow(alfd, 2) -\n 0.001 * alfd +\n 0.1219;\n\n dragCam0Thk10 =\n -1e-8 * Math.pow(alfd, 6) +\n 6e-8 * Math.pow(alfd, 5) +\n 6e-6 * Math.pow(alfd, 4) -\n 2e-5 * Math.pow(alfd, 3) -\n 0.0002 * Math.pow(alfd, 2) +\n 0.0017 * alfd +\n 0.0196;\n dragCam5Thk10 =\n 3e-9 * Math.pow(alfd, 6) +\n 6e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) +\n 0.0038 * alfd +\n 0.0159;\n dragCam10Thk10 =\n -5e-9 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) +\n 1e-5 * Math.pow(alfd, 3) +\n 0.0004 * Math.pow(alfd, 2) -\n 3e-5 * alfd +\n 0.0624;\n dragCam15Thk10 =\n -2e-9 * Math.pow(alfd, 6) -\n 2e-8 * Math.pow(alfd, 5) -\n 5e-7 * Math.pow(alfd, 4) +\n 8e-6 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0034 * alfd +\n 0.0993;\n dragCam20Thk10 =\n 2e-9 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) +\n 2e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0023 * alfd +\n 0.1581;\n\n dragCam0Thk15 =\n -5e-9 * Math.pow(alfd, 6) +\n 7e-8 * Math.pow(alfd, 5) +\n 3e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) -\n 7e-5 * Math.pow(alfd, 2) +\n 0.0017 * alfd +\n 0.0358;\n dragCam5Thk15 =\n -4e-9 * Math.pow(alfd, 6) -\n 8e-9 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) -\n 9e-7 * Math.pow(alfd, 3) +\n 0.0002 * Math.pow(alfd, 2) +\n 0.0031 * alfd +\n 0.0351;\n dragCam10Thk15 =\n 3e-9 * Math.pow(alfd, 6) +\n 3e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 1e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.004 * alfd +\n 0.0543;\n dragCam15Thk15 =\n 3e-9 * Math.pow(alfd, 6) +\n 5e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) +\n 0.0087 * alfd +\n 0.1167;\n dragCam20Thk15 =\n 3e-10 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) -\n 6e-7 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0006 * Math.pow(alfd, 2) +\n 0.0008 * alfd +\n 0.1859;\n\n dragCam0Thk20 =\n -3e-9 * Math.pow(alfd, 6) +\n 2e-8 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) -\n 8e-6 * Math.pow(alfd, 3) -\n 4e-5 * Math.pow(alfd, 2) +\n 0.0003 * alfd +\n 0.0416;\n dragCam5Thk20 =\n -3e-9 * Math.pow(alfd, 6) -\n 7e-8 * Math.pow(alfd, 5) +\n 1e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0004 * Math.pow(alfd, 2) +\n 5e-5 * alfd +\n 0.0483;\n dragCam10Thk20 =\n 1e-8 * Math.pow(alfd, 6) +\n 4e-8 * Math.pow(alfd, 5) -\n 6e-6 * Math.pow(alfd, 4) -\n 2e-5 * Math.pow(alfd, 3) +\n 0.0014 * Math.pow(alfd, 2) +\n 0.007 * alfd +\n 0.0692;\n dragCam15Thk20 =\n 3e-9 * Math.pow(alfd, 6) -\n 9e-8 * Math.pow(alfd, 5) -\n 3e-6 * Math.pow(alfd, 4) +\n 4e-5 * Math.pow(alfd, 3) +\n 0.001 * Math.pow(alfd, 2) +\n 0.0021 * alfd +\n 0.139;\n dragCam20Thk20 =\n 3e-9 * Math.pow(alfd, 6) -\n 7e-8 * Math.pow(alfd, 5) -\n 3e-6 * Math.pow(alfd, 4) +\n 4e-5 * Math.pow(alfd, 3) +\n 0.0012 * Math.pow(alfd, 2) +\n 0.001 * alfd +\n 0.1856;\n\n if (liftAnalisis == 2) {\n dragco = 0;\n } else {\n if (-20.0 <= camd && camd < -15.0) {\n dragThk5 =\n (camd / 5 + 4) * (dragCam15Thk5 - dragCam20Thk5) + dragCam20Thk5;\n dragThk10 =\n (camd / 5 + 4) * (dragCam15Thk10 - dragCam20Thk10) + dragCam20Thk10;\n dragThk15 =\n (camd / 5 + 4) * (dragCam15Thk15 - dragCam20Thk15) + dragCam20Thk15;\n dragThk20 =\n (camd / 5 + 4) * (dragCam15Thk20 - dragCam20Thk20) + dragCam20Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-15.0 <= camd && camd < -10.0) {\n dragThk5 =\n (camd / 5 + 3) * (dragCam10Thk5 - dragCam15Thk5) + dragCam15Thk5;\n dragThk10 =\n (camd / 5 + 3) * (dragCam10Thk10 - dragCam15Thk10) + dragCam15Thk10;\n dragThk15 =\n (camd / 5 + 3) * (dragCam10Thk15 - dragCam15Thk15) + dragCam15Thk15;\n dragThk20 =\n (camd / 5 + 3) * (dragCam10Thk20 - dragCam15Thk20) + dragCam15Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-10.0 <= camd && camd < -5.0) {\n dragThk5 =\n (camd / 5 + 2) * (dragCam5Thk5 - dragCam10Thk5) + dragCam10Thk5;\n dragThk10 =\n (camd / 5 + 2) * (dragCam5Thk10 - dragCam10Thk10) + dragCam10Thk10;\n dragThk15 =\n (camd / 5 + 2) * (dragCam5Thk15 - dragCam10Thk15) + dragCam10Thk15;\n dragThk20 =\n (camd / 5 + 2) * (dragCam5Thk20 - dragCam10Thk20) + dragCam10Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-5.0 <= camd && camd < 0) {\n dragThk5 =\n (camd / 5 + 1) * (dragCam0Thk5 - dragCam5Thk5) + dragCam5Thk5;\n dragThk10 =\n (camd / 5 + 1) * (dragCam0Thk10 - dragCam5Thk10) + dragCam5Thk10;\n dragThk15 =\n (camd / 5 + 1) * (dragCam0Thk15 - dragCam5Thk15) + dragCam5Thk15;\n dragThk20 =\n (camd / 5 + 1) * (dragCam0Thk20 - dragCam5Thk20) + dragCam5Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (0 <= camd && camd < 5) {\n dragThk5 = (camd / 5) * (dragCam5Thk5 - dragCam0Thk5) + dragCam0Thk5;\n dragThk10 =\n (camd / 5) * (dragCam5Thk10 - dragCam0Thk10) + dragCam0Thk10;\n dragThk15 =\n (camd / 5) * (dragCam5Thk15 - dragCam0Thk15) + dragCam0Thk15;\n dragThk20 =\n (camd / 5) * (dragCam5Thk20 - dragCam0Thk20) + dragCam0Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (5 <= camd && camd < 10) {\n dragThk5 =\n (camd / 5 - 1) * (dragCam10Thk5 - dragCam5Thk5) + dragCam5Thk5;\n dragThk10 =\n (camd / 5 - 1) * (dragCam10Thk10 - dragCam5Thk10) + dragCam5Thk10;\n dragThk15 =\n (camd / 5 - 1) * (dragCam10Thk15 - dragCam5Thk15) + dragCam5Thk15;\n dragThk20 =\n (camd / 5 - 1) * (dragCam10Thk20 - dragCam5Thk20) + dragCam5Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (10 <= camd && camd < 15) {\n dragThk5 =\n (camd / 5 - 2) * (dragCam15Thk5 - dragCam10Thk5) + dragCam10Thk5;\n dragThk10 =\n (camd / 5 - 2) * (dragCam15Thk10 - dragCam10Thk10) + dragCam10Thk10;\n dragThk15 =\n (camd / 5 - 2) * (dragCam15Thk15 - dragCam10Thk15) + dragCam10Thk15;\n dragThk20 =\n (camd / 5 - 2) * (dragCam15Thk20 - dragCam10Thk20) + dragCam10Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (15 <= camd && camd <= 20) {\n dragThk5 =\n (camd / 5 - 3) * (dragCam20Thk5 - dragCam15Thk5) + dragCam15Thk5;\n dragThk10 =\n (camd / 5 - 3) * (dragCam20Thk10 - dragCam15Thk10) + dragCam15Thk10;\n dragThk15 =\n (camd / 5 - 3) * (dragCam20Thk15 - dragCam15Thk15) + dragCam15Thk15;\n dragThk20 =\n (camd / 5 - 3) * (dragCam20Thk20 - dragCam15Thk20) + dragCam15Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n }\n\n var cldin = this.getLiftCoefficient();\n\n var reynolds = this.getReynolds();\n\n /**\n * The following is for the reynolds number correction\n */\n if (reCorrection == true)\n dragco = dragco * Math.pow(50000 / reynolds, 0.11);\n\n /**\n * The following is for the induced drag option\n */\n if (induced == true)\n dragco = dragco + (cldin * cldin) / (3.1415926 * aspr * 0.85);\n\n /**\n * If the velocity is 0 then the dragCoefficient will be 0\n */\n\n if (this.getVelocity() == 0) dragco = 0;\n }\n\n return dragco;\n }",
"function dihedral3() {\n if (x < 0) {\n x = -x;\n inversions += 1;\n change = true;\n }\n if (y > 0) {\n if (x > rt3 * y) {\n const h = 0.5 * (rt3 * x - y);\n x = 0.5 * (x + rt3 * y);\n y = h;\n inversions += 1;\n change = true;\n }\n } else {\n if (x > -rt3 * y) {\n const h = 0.5 * (rt3 * x - y);\n x = 0.5 * (x + rt3 * y);\n y = h;\n inversions += 1;\n change = true;\n } else {\n const h = 0.5 * (rt3 * x - y);\n x = -0.5 * (x + rt3 * y);\n y = h;\n change = true;\n }\n }\n}",
"de_dx(l, s) {\n\t\tconst p1 = this.transformPoint(Cube.points[Cube.lines[s][0]])\n\t\tconst p2 = this.transformPoint(Cube.points[Cube.lines[s][1]])\n\t\tconst u = this.projectPoint(p1)\n\t\tconst v = this.projectPoint(p2)\n\t\tconst dedu = de_du(l, u, v)\n\t\tconst dedv = de_du(l, v, u)\n\t\tconst d = new Array(3)\n\t\td[0] = this.f*(dedu[0]/p1[2] + dedv[0]/p2[2])\n\t\td[1] = this.f*(dedu[1]/p1[2] + dedv[1]/p2[2])\n\t\td[2] = -this.f*((p1[0]*dedu[0] + p1[1]*dedu[1])/p1[2]**2 + (p2[0]*dedv[0] + p2[1]*dedv[1])/p2[2]**2)\n\t\treturn d\n\t}",
"function DCR(sketch) {\r\n var max = maxCurve(sketch);\r\n var averageChange = averageCurvature(sketch);\r\n var DCR = max / averageChange;\r\n // console.log(\"Direction change ratio is \" + DCR);\r\n return DCR;\r\n}",
"function makeDerivative( f, deltaX )\n{\n var deriv = function(x) \n /*将函数赋值给一个变量*/\n { \n return ( f(x + deltaX) - f(x) )/ deltaX;\n /*作为参数传递给其他函数 */\n }\n return deriv;\n /*作为函数返回值 */\n}",
"findZeroDerivative(p0, p1, p2) {\n let A = ((p0.y - p2.y) * (p1.x - p2.x) - (p1.y - p2.y) * (p0.x - p2.x)) / ((p0.x * p0.x - p2.x * p2.x) * (p1.x - p2.x) - (p1.x * p1.x - p2.x * p2.x) * (p0.x - p2.x));\n let B = ((p1.y - p2.y) - A * (p1.x * p1.x - p2.x * p2.x)) / (p1.x - p2.x);\n let C = p0.y - B * p0.x - A * p0.x * p0.x;\n let x = -B / (2 * A);\n let y = A * x * x + B * x + C;\n return { x: x, y: y };\n }",
"function deriv(g) {\n return x => (g(x + dx) - g(x)) / dx;\n}",
"function dy(tx, d) {\n return d * Math.sin(rad(tx));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method Name: backShadowExp Function : to reset the widget from the shadow view | function backShadowExp()
{
kony.print("\n**********in backShadowExp*******\n");
frmHome.show();
//"shadowDepth" : Represents the depth of the shadow in terms of dp.
//As the shadow depth increases, widget appears to be elevated from the screen and the casted shadow becomes soft
frmShodowView.flxShadow.shadowDepth = 0;
//"shadowType" : Specifies the shape of the widget shadow that is being casted. By default, widget shadow takes the shape of the widget background.
frmShodowView.flxShadow.shadowType = constants.VIEW_BOUNDS_SHADOW;
} | [
"deactivate() {\n this.context.shadowOffsetX = undefined;\n this.context.shadowOffsetY = undefined;\n this.context.shadowColor = undefined;\n this.context.shadowBlur = undefined;\n this.isActive = false;\n }",
"function shadowExp()\n{\n kony.print(\"\\n**********in shadowExp*******\\n\");\n frmShodowView.flxShadow.shadowDepth = 30;\n frmShodowView.flxShadow.shadowType = constants.VIEW_BOUNDS_SHADOW;\n}",
"unsetSelectedAsShadowBlock() {\n // From wfactory_controller.js\n if (!this.view.selectedBlock) {\n return;\n }\n ShadowController.unmarkShadowBlock(this.view.selectedBlock);\n this.currentResource.removeShadowBlock(this.view.selectedBlock.id);\n this.checkShadowStatus();\n this.view.showAndEnableShadow(true,\n ShadowController.isValidShadowBlock(this.view.selectedBlock, true));\n\n // Save and update the preview.\n this.saveStateFromWorkspace();\n this.updatePreview();\n }",
"function resetOpt() {\r\n document.getElementById('greenButton').style.boxShadow = \"0px 0px 0px 0px white\"; \r\n document.getElementById('whiteButton').style.boxShadow = \"0px 0px 0px 0px white\";\r\n document.getElementById('blueButton').style.boxShadow = \"0px 0px 0px 0px white\";\r\n document.getElementById('redButton').style.boxShadow = \"0px 0px 0px 0px white\";\r\n document.getElementById('normal').style.boxShadow = \"0px 0px 0px 0px white\";\r\n document.getElementById('hard').style.boxShadow = \"0px 0px 0px 0px white\";\r\n document.getElementById('insane').style.boxShadow = \"0px 0px 0px 0px white\";\r\n}",
"function shadow() {\n stroke(0, 0, 0);\n translate(2, 2);\n }",
"updateShadowType() {\n\t\tthis.shadowType = this.switchControl.isEnabled() ? 'inset' : '';\n\t}",
"function reset() {\n clearVirtualStack()\n updateDisplay('previous', virtualStack)\n clearStack()\n}",
"drawShadow() {\n if (this.shadow && !this.shadow.isActive) {\n this.shadow.activate();\n } else if (this.shadow) {\n this.shadow.deactivate();\n }\n }",
"function switchSettings2Back() {\n /* Reset Focus */\n Draw.resetFocus();\n }",
"function reset(){\n\t\t\t\tcont.find(\"span\").css({\"top\":\"-100px\",\"opacity\":\"1\"});\n\t\t\t}",
"onEnterBack() {\n state.glassBottle.alpha = 0;\n clear(state.ctx.glassBottle);\n }",
"resetStyle()\n {\n this.setStyle(this._defaultValue);\n }",
"restoreWindow () {\n this.focus()\n this.shadowRoot.querySelector('div.windowContainer').classList.remove('minimized')\n this.shadowRoot.querySelector('div.windowContainer').style.transform = 'translate3d(' + this._initialX + 'px, ' + this._initialY + 'px, 0)'\n }",
"clearBackOverride() {\r\n $(this.backTerm).off(\"click\");\r\n }",
"function draw_backDrop() {\n \tvar backDropChanges = backDrop( backdropInfo, backDropY, backdropCleared );\n \tbackDropY = backDropChanges.backDropY;\n \tbackdropCleared = backDropChanges.backdropCleared;\n }",
"function resetShadowRoot(vm) {\n vm.children = EmptyArray;\n ShadowRootInnerHTMLSetter.call(vm.cmpRoot, ''); // disconnecting any known custom element inside the shadow of the this vm\n\n runShadowChildNodesDisconnectedCallback(vm);\n }",
"restore () {\n\t\tthis.$element.removeClass('screenlayer-minimized');\n\t\tthis.show();\n\t}",
"function w_toBack()\n{\n\t// if there are results\n\tif (g_resetButton.enabled)\n\t{\n//maybe dynamically get the width/height of the back image? if it's smaller than currnet size\n\t\twr_resizeTo(302, 128, wr_showBack);\n\t}\n\telse\n\t{\n\t\twr_showBack();\n\t}\n}",
"reset() {\r\n this.changeState(\"normal\");\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sends the chat message to the server | function sendMessage() {
var message = data.value;
data.value = "";
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
} | [
"function sendMessage() {\n let message = data.value;\n data.value = \"\";\n // tell server to execute 'sendchat' and send along one parameter\n socket.emit(\"sendchat\", message);\n }",
"function sendMessage() {\n let message = data.value;\n data.value = \"\";\n // tell server to execute 'sendchat' and send along one parameter\n socket.emit(\"sendchat\", message);\n}",
"function sendChat (message){\n UI.addChatMessage(\"me: \"+message);\n rtc._socket.send(JSON.stringify({\n eventName:\"chat_msg\",\n data:{\n msg:message,\n room:App.getRoom(),\n nick:App.getNick()\n }\n }),function(err){\n console.log(err);\n });\n }",
"function sendMessage() {\n\t \tvar msg = chatinput.val();\n\n\t \tif (!msg) {\n\t \t\treturn;\n\t \t}\n\n\t \tif (msg == 'clear') {\n\t \t\tchatcontent.text('');\n\t \t\tchatinput.val('');\n\t \t\treturn;\n\t \t}\n\n\t \tif (name != chatuser.val()) {\n\t \t\tnameChange();\n\t \t}\n\n\t \tsocket.emit('message', { text: msg, points: points });\n\t \tchatinput.val('');\n\t }",
"function sendMessage() {\n text = $('#txtMsg').val();\n if (text == \"\") return;\n $('#txtMsg').val('');\n $.post('/chat/send_chat', { msg: text });\n getNewMessages();\n }",
"function PlayerChat( message ){ \n\tsocket.emit( \"chat up\", { 'sessionId': sessionId, 'message': message, 'channelId': currentChannel } );\n}",
"function sendChat(text) {\n let chatRequest = {\n type: \"chat\",\n text: text,\n gameID: currentGameID,\n playerID: currentPlayerID\n }\n\n socket.send(JSON.stringify(chatRequest));\n}",
"function SendToChat(text) {\n client.say(current_channel, text);\n}",
"function _send(message, chatstate) {\n var elem = $msg({\n to: contact.jid,\n from: jtalk.me.jid,\n type: \"chat\"\n });\n\n if (message) elem.c(\"body\", message);\n if (chatstate) {\n elem.c(chatstate, {xmlns: Strophe.NS.CHATSTATE});\n }\n\n connection.send(elem);\n }",
"function sendMessage() {\n if (angular.isDefined(chat.messageText) && chat.messageText !== \"\") {\n $wamp.call('com.chat.talkto.'+chat.currentConversation.guid, [chat.messageText, {username:chat.user.username, guid:chat.user.guid}]).then(\n function(res) {\n chat.currentConversation.messages.push({\n from: chat.user.username,\n time: moment().format('hh:mm:ss'),\n message: chat.messageText\n });\n\n scrollToLastMessage();\n \n chat.messageText = \"\";\n $log.info(res);\n }\n ).catch(function(error) {\n $log.info(error);\n });\n }\n }",
"function chatSend (str) {\n\t\t\td20.textchat.doChatInput(str);\n\t\t}",
"function sendMessage(data) {\r\n //Hacemos que el servidor emita el mensaje hacia todos los clientes\r\n //para que se sincronicen:\r\n socket.broadcast.emit(\"sendMessage\", {mensaje: data.mensaje, username: data.username});\r\n }",
"send() {\n let data = {\n text: this.text,\n user: this.user,\n room: this.room\n };\n\n socket.emit('send-message', {\n message: data\n });\n }",
"function sendMessageToServer(message) {\n socket.send(message);\n }",
"function sendMessageToServer(message) {\n socket.send(message);\n }",
"function sendMessage(message) {\n chat.perform(\"send_message\", message);\n}",
"function submitChat() {\n // Retrieve the chat text from the input\n const chatText = document.getElementById(\"chat-input\").value;\n\n // Clear the input field for the next message\n document.getElementById(\"chat-input\").value = \"\";\n\n // Emit the text and user to the server\n socket.emit(\"submitChat\", { chatText, chatUser });\n}",
"function sendMessage() {\n // Create a new message object\n var message = {\n text: $scope.messageText\n };\n\n // Emit a 'chatMessage' message event\n PlaygroundService.emit('chatMessage', message);\n\n // Clear the message text\n $scope.messageText = '';\n }",
"function sendChatMessage(message)\n {\n\t var httpRequest = new XMLHttpRequest();\n\t var jsonmsg = { \"message\" : message};\n\t httpRequest.open(\"POST\", \"http://localhost:3000/chats\", true);\n\t httpRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n\n\t chats.push(message);\n\n\t httpRequest.send(JSON.stringify(jsonmsg));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
code TODO: contactarCtrl | controller_by_user controller by user | function controller_by_user(){
try {
} catch(e){
console.log("%cerror: %cPage: `contactar` and field: `Custom Controller`","color:blue;font-size:18px","color:red;font-size:18px");
console.dir(e);
}
} | [
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page form_contact_us => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page faq_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page faqs => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page about_us => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page index => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `recuperar_contrasea` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page storie_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `formlarios_para_publicar` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page about => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `prod_aptos_para_celacos` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page winner_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `frutos_secos_y_frutas_pasas` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `complementos_nutricionales` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `pastas_quesos_y_cremas` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `harinas_y_salvados` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `raciones_y_otros` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `congelados` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `prod_bajas_calorias` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `aceites` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This DFT verifies an update in PPT Name as direct PPT name verification is covered in BVTS | function VerifySharedPPTName()
{
LogMessage("DataCollabTest :: VerifySharedPPTName");
var selfDisplayName = GetTestCaseParameters("DisplayName1");
var presenterName = GetBuddyDisplayName(0);
var pptName1 = GetPPTName();
var pptName2 = GetPPTName();
//Share PPT from Bot
GotoMyInfo();
SetNote("VerifySharedPPTName " + pptName1 + " " + pptName2);
AceptRejectCallToast(AcceptString);
//Confirm that conference join is successful
WaitForCallToGetConnected();
WaitForCollabPane();
VerifyPPTName(pptName1);
WaitForContentToBeLoaded();
//Ask bot to stop PPT1
SendStopPPTMessage(selfDisplayName);
try
{
var messageToRecieve = presenterName + " - " + "PPT Sharing Stopped";
messageToRecieve = messageToRecieve.split(" ").join(" ");
VerifyReceivedIM(GetBuddyDisplayName(0), messageToRecieve);
}
catch(error)
{}
DelayInSec(5);
//Ask bot to share another PPT
SendStartPPTMessage(selfDisplayName);
WaitForCollabPane();
VerifyPPTName(pptName2);
//Ask bot to stop PPT2
SendStopPPTMessage(selfDisplayName);
EndConversation();
} | [
"function VerifyPPTPresenterName()\n{\n LogMessage(\"DataCollabTest :: VerifyPPTPresenterName\");\n var selfDisplayName = GetTestCaseParameters(\"DisplayName1\");\n var presenterName1 = GetBuddyDisplayName(0);\n var presenterName2 = GetBuddyDisplayName(1);\n \n //Share PPT from Bot\n GotoMyInfo();\n SetNote(\"VerifyPPTPresenterName \" + GetPPTName() + \" \" + GetPPTName());\n \n AceptRejectCallToast(AcceptString);\t\n \n //Confirm that conference join is successful\n WaitForCallToGetConnected();\n\n //TODO : Accept Sharing Request When feature is Implemented\n WaitForCollabPane();\n VerifyPresenterName(presenterName1);\n WaitForContentToBeLoaded();\n \n //Ask bot to stop PPT\n SendStopPPTMessage(selfDisplayName);\n \n //TODO : Remove try catch when bug #3176304 gets Fixed\n try\n {\n var messageToRecieve = presenterName1 + \" - \" + \"PPT Sharing Stopped\";\n messageToRecieve = messageToRecieve.split(\" \").join(\" \");\n VerifyReceivedIM(GetBuddyDisplayName(0), messageToRecieve);\n }\n catch(error)\n {}\n DelayInSec(10);\n WaitForCollabPane();\n VerifyPresenterName(presenterName2);\n \n //Ask bot to stop PPT\n SendStopPPTMessage(selfDisplayName);\n \n EndConversation();\n}",
"function vpta_processTeamName(vpta_teamname) {\n try {\n //Check if Team Name from PCMM integration service already exist in CRM\n var vpta_conditionalFilter = \"(ftp_name eq '\" + vpta_teamname + \"')\";\n vpta_getMultipleEntityDataAsync('ftp_pactSet', 'ftp_pactId, ftp_name', vpta_conditionalFilter, 'ftp_name', 'asc', 0, vpta_processTeamName_response, vpta_teamname);\n }\n catch (err) {\n alert('Veteran form load, PCMM Integration Service Function Error (vpta_processTeamName): ' + err.message);\n }\n}",
"function panStatusCheckValdt() {\r\n\r\n\tvar status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;\r\n\tvar pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;\r\n\tvar assesseeVerPAN = document\r\n\t\t\t.getElementsByName('verification.declaration.assesseeVerPAN')[0].value;\r\n\r\n\tif ((pan.substring(3, 4) == 'P' || pan.substring(3, 4) == 'p')\r\n\t\t\t&& (status == 'I')\r\n\t\t\t&& (assesseeVerPAN == '' || assesseeVerPAN == undefined || assesseeVerPAN == null)) {\r\n\t\tassesseeVerPAN = document\r\n\t\t\t\t.getElementsByName('partAGEN1.personalInfo.pan')[0].value\r\n\t\t\t\t.toUpperCase();\r\n\t}\r\n\r\n}",
"function validName(sprintname) {\n if (!sprintname)\n return false;\n return true;\n}",
"function checkPrereqs(p) {\n\t\t\t\tlet eventOccurred = EventSelector.__p.eventsOccurred.includes(p);\n\t\t\t\tlet epiphRealized = EpiphanyManager.__alreadyRealized(p);\n\t\t\t\tlet switchFlipped = __getRMMVSwitch(p);\n\t\t\t\tlet logicEvaluated = false; \n\t\t\t\t\n\t\t\t\tif (!p.endsWith(eventFileType) && !p.startsWith(\"s_\")) {\n\t\t\t\t\tlogicEvaluated = LogicEvaluator.__evaluateLogic(p);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn eventOccurred || epiphRealized || switchFlipped || logicEvaluated;\n\t\t\t}",
"function CMP10_TC015(TestName)\n{\nvar exestatus = true;\n \n// add a comment\n//Login\nexestatus = Features.MvLogin(TestName,exestatus);\n\n//Enter Patient Register\nexestatus = Features.MvPatientRegister(TestName,exestatus);\n\n//Enter Patient Demographics\n//exestatus = Features.MvPatientDemographics(TestName,exestatus);\n//Validation of DocumentPresenceTTube \n//Flowsheet validation to be checked\nexestatus = Features.MvDocumentPresenceTTube(TestName,exestatus);\n\n//Logout\nexestatus = Features.MvLogout(TestName,exestatus);\n \n}",
"async verifyHotelName() {\n\t\tif (this.world.debug) console.log(\"verifyHotelName\");\n\n\t\tif (this.expectedHotelName) {\n\t\t\tconst { bookingPageHotelNameSpan } = this.elements;\n\n\t\t\tawait this.world.helper.waitFor(bookingPageHotelNameSpan);\n\t\t\tlet actualHotelName = await this.world.helper.getElementText(bookingPageHotelNameSpan);\n\t\t\tactualHotelName = actualHotelName.replace(\"Hotelbeschreibung\", \"\").trim();\n\t\t\tif (this.world.debug) console.log(actualHotelName);\n\n\t\t\tthis.world.expect(actualHotelName).to.equal(this.expectedHotelName);\n\t\t\tawait this.world.sleep(2000);\n\t\t} else {\n\t\t\tthrow new Error(\"Couldn't find the hotel name\");\n\t\t}\n\t}",
"function MvDBUpdateUnsaved(TestName,exestatus)\n{\n \n \nif (equal(exestatus,true)) {\n\nvar tcDesc = Data.getData(TestName,\"Patient\",\"TC_DESC\");\nLog.Checkpoint(\"Start of validating quit confirmation pop up and validation of unsaved changes\"+tcDesc ,\"The flow is started\");\n \n //Start of the feature \n\t vProcess = Sys.Process(\"MvDBUpdate\");\n \n \n\t// ** Fill in the details for different fields **\n Log.Message(\"***Enter details for different fields***\");\n var MRN = Data.getData(TestName,\"Patient\",\"MRN\");\n var FirstName = Data.getData(TestName,\"Patient\",\"FirstName\");\n var LastName = Data.getData(TestName,\"Patient\",\"LastName\");\n \n var tcDesc = Data.getData(TestName,\"DBUpdate\",\"TC_DESC\");\n var UpdateFirstname = Data.getData(TestName,\"DBUpdate\",\"UpdateFirstname\"); \n var Updatelastname = Data.getData(TestName,\"DBUpdate\",\"Updatelastname\");\n \n \n// To enter input details for different fields\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"TextEdit\\\", \\\"\\\", 3)\",MRN,exestatus);\n \n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Search\\\", 1)\",exestatus);\n //aqUtils.Delay(2000);\n \n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"TableView\\\", \\\"\\\", 1)\", 120,exestatus);\n \n var patientsGrid = vProcess.Find(\"Name\", \"WPFObject(\\\"GridControl\\\", \\\"\\\", 1)\", 1000); \n \n var RowCount = aqObject.GetPropertyValue(patientsGrid, \"VisibleRowCount\");\n\n \n\t var k = 0;\n\t var j = 0;\n for (i = 1; i <= RowCount; i++) {\n \n j = j+1; \n \n var patGridRow = patientsGrid.FindChild(\"Name\", \"WPFObject(\\\"GridRow\\\", \\\"\\\",\"+j+\")\", 1000);\n if(!patGridRow.exists)\n {\n j=1;\n } \n var patGridRow = patientsGrid.FindChild(\"Name\", \"WPFObject(\\\"GridRow\\\", \\\"\\\",\"+j+\")\", 1000);\n patGridRow.Click();\n patGridRow.Keys(\"[Down]\");\n patGridRow.Keys(\"[Down]\");\n \n var PatientListObject = patGridRow.FindChild(\"Name\", \"WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1)\", 1000);\n \n var admittedPatientList = PatientListObject.FindChild(\"Name\", \"WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 5)\", 1000); \n\tvar searchMRN = admittedPatientList.FindChild(\"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", 1000);\n\t\n \n var listMRN = aqObject.GetPropertyValue(searchMRN, \"Text\");\n\n Log.Message(\"Patient MRN: \"+ listMRN );\n \n \n if (aqString.Contains(listMRN, MRN) != -1 ) {\n admittedPatientList.DblClick();\n Log.CheckPoint(\"Patient with given MRN is found\");\n k = 1\n break;\n \n\t }\n k = 0;\n \n\t}\n \n\n if (k===0){ \n\t\tLog.Error(\"Patient with given search criteria is not found\")\n\t\texestatus = false\n }\n \n // To update the different fields\n Log.Message(\"Enter updated input details\");\n \n \n aqUtils.Delay(1000);\n exestatus =mvObjects.clearText(vProcess,\"FullName\",\"*WPFObject(\\\"WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\", 1).WPFObject(\\\"GroupBox\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"txtFirstName\\\")\",exestatus);\n exestatus =mvObjects.clearText(vProcess,\"FullName\",\"*WPFObject(\\\"WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\", 1).WPFObject(\\\"GroupBox\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"TextEdit\\\", \\\"\\\", 2)\",exestatus);\n \n \n // To enter updated first name and last name\n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\", 1).WPFObject(\\\"GroupBox\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"txtFirstName\\\")\",UpdateFirstname,exestatus);\n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\", 1).WPFObject(\\\"GroupBox\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"TextEdit\\\", \\\"\\\", 2)\",Updatelastname,exestatus);\n \n \n // Click on close button\n exestatus = mvObjects.buttonClick(vProcess,\"FullName\",\"*WPFObject(\\\"HwndSource: WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\").WPFObject(\\\"WindowUpdateRecord\\\", \\\"MV Production/Archive DB Update window\\\", 1).WPFObject(\\\"GroupBox\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 3).WPFObject(\\\"StackPanel\\\", \\\"\\\", 1).WPFObject(\\\"Button\\\", \\\"Close\\\", 3)\",exestatus);\n \n // To proceed with quit confirmation message and discard the changes\n \n var MsgForm = vProcess.Find(\"Name\", \"WPFObject(\\\"WindowMessageBox\\\", \\\"Message\\\", 1)\", 1000);\n \n if (MsgForm.Exists)\n {\n \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"Button\\\", \\\"Yes\\\", 1)\",exestatus);\n }\n aqUtils.Delay(1000);\n \n\n //To search for the same patient again\n exestatus =mvObjects.clearText(vProcess,\"Name\",\"WPFObject(\\\"TextEdit\\\", \\\"\\\", 3)\",exestatus); \n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"TextEdit\\\", \\\"\\\", 3)\",MRN,exestatus);\n \n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Search\\\", 1)\",exestatus);\n \n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"TableView\\\", \\\"\\\", 1)\", 120,exestatus);\n \n var PatientListObject = patGridRow.FindChild(\"Name\", \"WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1)\", 1000);\n \n var admittedPatientList = PatientListObject.FindChild(\"Name\", \"WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 1)\", 1000); \n\tvar searchFirstName = admittedPatientList.FindChild(\"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", 1000);\n \n var admittedPatientListPatientName = PatientListObject.FindChild(\"Name\", \"WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 2)\", 1000); \n\tvar searchLastName = admittedPatientListPatientName.FindChild(\"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", 1000);\n \n var listFirstName = aqObject.GetPropertyValue(searchFirstName, \"Text\");\n var listLastName = aqObject.GetPropertyValue(searchLastName, \"Text\");\n\n Log.Message(\"Patient FirstName: \"+ listFirstName);\n Log.Message(\"Patient LastName: \"+ listLastName );\n\n \n if (aqString.Compare(listFirstName, FirstName,false)== 0 && aqString.Compare(listLastName, LastName,false)== 0) {\n Log.CheckPoint(\"First and Last name for the patient are not updated since the action has been discarded\");\n\t }\n else\n {\n Log.CheckPoint(\"First and Last name for the patient are updated even though the action has been discarded \");\n exestatus= false;\n }\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Patient with given first and last name details are not updated in DB Update tool\");\n Log.Checkpoint(\"Validation of quit confirmation pop up and Unsaved changes in DBUpdate tool\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped validation of quit confirmation pop up and Unsaved changes in DBUpdate tool\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function manuallyCheckForUpdate() {\r\n\tcheckForUpdate(true);\r\n} //End manual update check",
"function CMP16_TC012(TestName)\n{\nvar exestatus = true;\n \n//Login to DBUpdate tool\nexestatus = Features.MvDBUpdateLogin(TestName,exestatus);\n\n//Enter partial AUID field and validate in DB update tool\nexestatus = Features.MvDBUpdateSearchByAUID(TestName,exestatus);\n\n//Logout of DBUpdate tool\nexestatus = Features.MvDBUpdateLogout(TestName,exestatus);\n \n}",
"validateListSuccessfullyRenamed() {\n return this\n .waitForElementVisible('@successBanner')\n .assert.containsText('@successBanner', 'List renamed');\n }",
"isSamePalletName( allPallet , userPallet ){\n let n = allPallet.length;\n let check = 0;\n for(let i = 0; i < n; i++){\n let name_old = allPallet[i].name.trim().toLowerCase();\n let name_new = userPallet.name.trim().toLowerCase();\n\n if(name_old === name_new){\n check = 1;\n }\n }\n if(check === 1){\n return true\n }else{\n return false;\n }\n }",
"checkNameAvailability(name){\n for (const key in this.planetList) {\n if (this.planetList.hasOwnProperty(key)) {\n let planetName = this.planetList[key].planet.inputs[PLANET('name').value];\n if (planetName == name){\n return true;\n }\n }\n }\n return false;\n }",
"function checkName() {\n\tif(getPlaylistName()){ //if the playlist name is filled out\n\t\tremoveFromErrors(noPlaylistError);\n\t}\n\telse { //if the playlist name isn't filled out\n\t\taddToErrors(noPlaylistError);\n\t}\n\tupdateErrorText();\n}",
"validateSuccesfullyUpdatedBusinessDetails() {\n return this\n .waitForElementVisible('@successBanner')\n .assert.containsText('@successBanner', 'Your business details have been successfully updated.');\n }",
"function validateUpdate(nm, dm, pn, em, zip,pw, pwc) {\n\tvar resText = 'You have changed ...'\n\tif (!validateName(nm) && nm != '')\n\t\treturn 'Invalid username. Must start with a letter and can only contains letters and numbers.'\n\telse if (nm != '')\n\t\tresText+='username; '\n\tif (dm != '')\n\t\tresText+='displayName; '\n\tif (!validateEmail(em) && em != '')\n\t\treturn 'Invalid email. Must be like a@b.co'\n\telse if (em != '')\n\t\tresText+='email; '\n\tif (!validatePhone(pn) && pn != '')\n\t\treturn 'Invalid phone number. Should and only contain 10 digits'\n\telse if (pn != '')\n\t\tresText+='phoneNumber; '\n\tif (!validateZip(zip) && zip != '')\n\t\treturn 'Invalid zipcode. Must be 5 digits in length, e.g., 77005'\n\telse if (zip != '')\n\t\tresText+='zipcode; '\n\tif (!validatePwd(pw, pwc) && pw != '' & pwc != '')\n\t\treturn 'Password do not match'\n\telse if (pw != '' && pwc != '')\n\t\tresText+='Password'\n\n\treturn resText\n}",
"function personCheck_hasNameAlternative( person ){\n if (checkKeyIsValid(person, \"name_info\")){\n for (var i = 0; i < person.name_info.length; i++){\n var nameinfo = person.name_info[i];\n if (nameinfo.type === \"alternative\" ){\n return true;\n }\n }\n }\n return false;\n}",
"async returntoPLP(){\n await t.click(this.backtoPLP)\n await t.expect(await productListing.returnPLPtitle()).eql(PAGE.PAGETITLES.PRODUCTLIST)\n }",
"async function updatePr(existingPr) {\n logger.debug(`updatePr: ${existingPr.number}`);\n await api.updatePr(existingPr.number, prTitle, prBody);\n logger.info(`${depName}: Updated ${existingPr.displayNumber}`);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an array of all US IRS campus prefixes | function enUsGetPrefixes() {
var prefixes = [];
for(var location in enUsCampusPrefix)// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
// istanbul ignore else
if (enUsCampusPrefix.hasOwnProperty(location)) prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location]));
return prefixes;
} | [
"function enUsGetPrefixes() {\n var prefixes = [];\n\n for (var location in enUsCampusPrefix) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (enUsCampusPrefix.hasOwnProperty(location)) {\n prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location]));\n }\n }\n\n return prefixes;\n}",
"function _all_string_prefixes() {\n return [\n '', 'FR', 'RF', 'Br', 'BR', 'Fr', 'r', 'B', 'R', 'b', 'bR',\n 'f', 'rb', 'rB', 'F', 'Rf', 'U', 'rF', 'u', 'RB', 'br', 'fR',\n 'fr', 'rf', 'Rb'];\n}",
"static prefixes () {\n if (this.prefixesCache) {\n return this.prefixesCache\n }\n\n this.prefixesCache = [];\n for (let name in agents$4) {\n this.prefixesCache.push(`-${agents$4[name].prefix}-`);\n }\n\n this.prefixesCache = utils\n .uniq(this.prefixesCache)\n .sort((a, b) => b.length - a.length);\n\n return this.prefixesCache\n }",
"get issuePrefixes() {\n /** @type {string[]} */\n let prefixes = this.qa._tests.reduce( (prefixes, test) => [...prefixes, ...test.namespaces.prefixes()], [] );\n return [...(new Set(prefixes))];\n }",
"async get_prefixes(n = 1, provider_id = null, query = \"\") {\n let prefixes = await this.prefix_list(n, provider_id, query);\n\n return prefixes;\n }",
"async _getLabelPrefixes() {\n const projectRequestMessage = {\n project_name: this.projectName};\n const labelsResponse = await prpcClient.call(\n 'monorail.Projects', 'GetLabelOptions', projectRequestMessage);\n const labelPrefixes = new Set();\n for (let i = 0; i < labelsResponse.labelOptions.length; i++) {\n let label = labelsResponse.labelOptions[i].label;\n if (label.includes('-')) {\n labelPrefixes.add(label.split('-')[0]);\n }\n }\n return Array.from(labelPrefixes);\n }",
"async function getPrefixes( templ ) {\n\n // load the template\n const content = await Fs.readFile( templ, 'utf8' );\n\n // extract all prefixes\n const prefixes = [];\n content.replace( regexp.prefixes, (match) => {\n prefixes.push( match );\n return match;\n });\n\n return prefixes;\n}",
"_getCountriesCodeArray() {\n var countries = this.options.countries;\n return countries.split(',');\n }",
"function _build_turtle_prefixes(){\n\t\t\tvar turtle_prefixes = \"\";\n\t\t\tfor (var i = 0; i < browser_conf_json.prefixes.length; i++) {\n\t\t\t\tvar pref_elem = browser_conf_json.prefixes[i];\n\t\t\t\tturtle_prefixes = turtle_prefixes+\" \"+\"PREFIX \"+pref_elem[\"prefix\"]+\":<\"+pref_elem[\"iri\"]+\"> \";\n\t\t\t}\n\t\t\treturn turtle_prefixes;\n\t\t}",
"findMissionCreeps(namePrefix) {\n let creepNames = [];\n for (let creepName in Game.creeps) {\n if (creepName.startsWith(namePrefix) && creepName.includes(this.missionName)) {\n creepNames.push(creepName);\n }\n }\n return creepNames;\n }",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"function collectionsPrefixes(collections) {\n\t let prefixes = [];\n\t Object.keys(collections).forEach((category) => {\n\t prefixes = prefixes.concat(Object.keys(collections[category]));\n\t });\n\t return prefixes;\n\t}",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"* prefixes() {\n yield* this.prefixToNamespace.xs();\n }",
"getKeysByPrefix(prefix) {\n const keys = []\n\n store.each((value, key) => {\n if (key && key.indexOf(prefix) === 0) {\n keys.push(key)\n }\n })\n\n return keys\n }",
"keys() {\n const keys = [];\n const name = this.name;\n const l = this.name.length;\n\n for( let key in localStorage ) {\n /**\n * if the key of the item does not start with the prefix, skip this item.\n */\n if( key.indexOf( name ) ) continue;\n keys.push( key.substr( l ) );\n }\n\n return Promise.resolve( keys );\n }",
"_stripPrefixes(nameTokens) {\n for (let i in nameTokens) {\n if (!this._containsString(this.NAME_PREFIXES, nameTokens[i])) {\n return nameTokens.slice(i);\n }\n }\n return [];\n }",
"function getNicknames(){\r\n nicknames = [];\r\n Object.keys(nickNames).forEach(function(key){\r\n nicknames.push(nickNames[key]);\r\n });\r\n return nicknames;\r\n }",
"getNames(prefix = '', out = null) {\n if (!out) out = []\n\n if (!this._subTextureNames) {\n // optimization: store sorted list of texture names\n this._subTextureNames = []\n for (const name of this._subTextures.keys()) {\n this._subTextureNames[this._subTextureNames.length] = name\n }\n this._subTextureNames.sort()\n }\n\n for (const name of this._subTextureNames) {\n if (name.indexOf(prefix) === 0) {\n out[out.length] = name\n }\n }\n\n return out\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function : SimpleGlyph / comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph. | function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
this.raw = raw;
this.numberOfContours = numberOfContours;
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.compound = false;
} | [
"function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {\n this.raw = raw;\n this.numberOfContours = numberOfContours;\n this.xMin = xMin;\n this.yMin = yMin;\n this.xMax = xMax;\n this.yMax = yMax;\n this.compound = false;\n }",
"function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {\n var data, flags;\n this.raw = raw;\n this.xMin = xMin;\n this.yMin = yMin;\n this.xMax = xMax;\n this.yMax = yMax;\n this.compound = true;\n this.glyphIDs = [];\n this.glyphOffsets = [];\n data = this.raw;\n\n while (true) {\n flags = data.readShort();\n this.glyphOffsets.push(data.pos);\n this.glyphIDs.push(data.readShort());\n\n if (!(flags & MORE_COMPONENTS)) {\n break;\n }\n\n if (flags & ARG_1_AND_2_ARE_WORDS) {\n data.pos += 4;\n } else {\n data.pos += 2;\n }\n\n if (flags & WE_HAVE_A_TWO_BY_TWO) {\n data.pos += 8;\n } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {\n data.pos += 4;\n } else if (flags & WE_HAVE_A_SCALE) {\n data.pos += 2;\n }\n }\n }",
"function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {\n\t\t var data, flags;\n\t\t this.raw = raw;\n\t\t this.xMin = xMin;\n\t\t this.yMin = yMin;\n\t\t this.xMax = xMax;\n\t\t this.yMax = yMax;\n\t\t this.compound = true;\n\t\t this.glyphIDs = [];\n\t\t this.glyphOffsets = [];\n\t\t data = this.raw;\n \n\t\t while (true) {\n\t\t\tflags = data.readShort();\n\t\t\tthis.glyphOffsets.push(data.pos);\n\t\t\tthis.glyphIDs.push(data.readShort());\n \n\t\t\tif (!(flags & MORE_COMPONENTS)) {\n\t\t\t break;\n\t\t\t}\n \n\t\t\tif (flags & ARG_1_AND_2_ARE_WORDS) {\n\t\t\t data.pos += 4;\n\t\t\t} else {\n\t\t\t data.pos += 2;\n\t\t\t}\n \n\t\t\tif (flags & WE_HAVE_A_TWO_BY_TWO) {\n\t\t\t data.pos += 8;\n\t\t\t} else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {\n\t\t\t data.pos += 4;\n\t\t\t} else if (flags & WE_HAVE_A_SCALE) {\n\t\t\t data.pos += 2;\n\t\t\t}\n\t\t }\n\t\t}",
"function PositionedGlyph(codePoint, x, y, glyph) {\n this.codePoint = codePoint;\n this.x = x;\n this.y = y;\n this.glyph = glyph;\n}",
"function Glyph(name, points) {\n\tthis.name = name\n\t\n\t// Get extreme points\n\tvar minX = points.reduce(function (min, p) {\n\t\treturn Math.min(min, p.x)\n\t}, Infinity)\n\tvar maxX = points.reduce(function (max, p) {\n\t\treturn Math.max(max, p.x)\n\t}, -Infinity)\n\tvar minY = points.reduce(function (min, p) {\n\t\treturn Math.min(min, p.y)\n\t}, Infinity)\n\tvar maxY = points.reduce(function (max, p) {\n\t\treturn Math.max(max, p.y)\n\t}, -Infinity)\n\t\n\tvar factorX = maxX-minX\n\tvar factorY = maxY-minY\n\tvar dx = 0.5-(maxX-minX)/(2*factorX)\n\tvar dy = 0.5-(maxY-minY)/(2*factorY)\n\tthis.points = points.map(function (p) {\n\t\tvar x = (p.x-minX)/factorX+dx\n\t\tvar y = (p.y-minY)/factorY+dy\n\t\treturn new Point(x, y)\n\t})\n\t\n\t// Points in the global space\n\tthis.globalPoints = points.map(function (p) {\n\t\treturn new Point(p.x*320+(568-320)/2, p.y*320)\n\t})\n}",
"constructor(x, y, wid, ht, data, color, xlbl, ylbl) {\n this.resize(x, y, wid, ht);\n this.data = data;\n this.dataType = 0; // how to interpret data\n this.startY = 0;\n this.endY = 0;\n this.color = color;\n this.xLbl = xlbl;\n this.yLbl = ylbl;\n }",
"function PositionedGlyph(codePoint, x, y, glyph) {\n\t this.codePoint = codePoint;\n\t this.x = x;\n\t this.y = y;\n\t this.glyph = glyph;\n\t}",
"pt() {\n\t\tlet [x, y] = this.cursor;\n\t\treturn document.querySelector(`svg rect[data-x=\"${x}\"][data-y=\"${y}\"]`);\n\t}",
"get localBounds() {\n return {\n x: this.x, //I changed this, it was \"x: 0,\"\n y: this.y, //I changed this, it was \"y: 0,\"\n width: this.width,\n height: this.height\n } \n }",
"limits() {\n var keys = Object.keys(this.data);\n var min = parseInt(this.data[keys[0]]); // ignoring case of empty list for conciseness\n var max = parseInt(this.data[keys[0]]);\n var i;\n for (i = 1; i < keys.length; i++) {\n var value = parseInt(this.data[keys[i]]);\n if (value < min) min = value;\n if (value > max) max = value;\n }\n this.yMin =min - Math.round(min/4);\n if(this.yMin <= 0)\n this.yMin=0;\n this.yMax = max + Math.round(max/4);\n\n }",
"static get glyphPixels() {\n return 96 * (38 / (VF.DEFAULT_FONT_STACK[0].getResolution() * 72));\n }",
"function getLabelBounds(){\n\tswitch(labelPosition) {\n\t\tcase('left'):\n\t\t\treturn [[this.x-this.width,this.y-this.height/2],[this.x,this.y+this.height/2]];\n\t\tcase('above'):\n\t\t\treturn [[this.x-this.width/2,this.y-this.height],[this.x+this.width/2,this.y]];\n\t\tcase('right'):\n\t\t\treturn [[this.x,this.y-this.height/2],[this.x+this.width,this.y+this.height/2]];\n\t\tcase('below'):\n\t\t\treturn [[this.x-this.width/2,this.y],[this.x+this.width/2,this.y+this.height]];\n\t}\n\n}",
"get GlyphRanges() { return this.internal.GlyphRanges; }",
"static get glyphPixels() {\n return 96 * (38 / (VF.Glyph.MUSIC_FONT_STACK[0].getResolution() * 72));\n }",
"updateRectDetails(rectPosition, tempX, tempY, tempWidth, tempHeight, text, x, dataXIndex, dataYIndex) {\n rectPosition.x = tempX;\n rectPosition.y = tempY;\n rectPosition.width = tempWidth;\n rectPosition.height = tempHeight;\n rectPosition.value = text;\n rectPosition.id = this.heatMap.element.id + '_HeatMapRect_' + x;\n rectPosition.xIndex = dataXIndex;\n rectPosition.yIndex = dataYIndex;\n }",
"function Glyph() {\n this.textureInfo = undefined;\n this.dimensions = undefined;\n this.billboard = undefined;\n }",
"map_data() {\n [this.sx, this.sy] = this.map_to_screen(this._x, this._y);\n [this.svx, this.svy] = this._get_unscaled_vertices();\n }",
"function boundingBox(x,y,xextent,yextent)\n{\n \n this.x1=x;\n this.y1=y;\n this.x2=x+xextent;\n this.y2=y+yextent;\n this.toString=function(){ return 'boundingBox(('+this.x1+','+this.y1+'),('+this.x2+','+this.y2+'))'; }\n}",
"get pointsToPixels() {\n return this.textFont.pointsToPixels;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets timer on or off when play/pause button is pressed and starts session (displays countdown) | function playPause() {
setSession(true);
setIsTimerRunning((prevState) => !prevState);
} | [
"function startCountDown(){\n playing = true;\n finished = false;\n if(paused===true){\n paused = false;\n countDown('remain');\n }\n else{\n countDown('session');\n }\n}",
"function startTimer() {\n minutes = times.sessionMinutes;\n seconds = minutes * 60;\n document.getElementById('top-label').innerText = times.breakMinutes + ' minute break coming up';\n document.getElementById('label').innerText = 'Session';\n toggleTop();\n document.body.style.background = 'tomato';\n toggleControlButtons();\n interval = setInterval(timer, 1000);\n }",
"function startSession() {\n // Take current number in session span * 60 (for seconds) -> create timer using that\n var sessionLength = (Number($(\"#session\").text())) * 60,\n timer = new CountDownTimer(sessionLength);\n // Change div to reflect this is session timer. \n $(\"#timerType\").text(\"Session\");\n // Add format() and startBreak() to timer functions, start timer\n timer.onTick(format).onTick(startBreak).start();\n }",
"onPlayPauseClick() {\n if (this.state.timerStatus === 'running') {\n this.setState({ timerStatus: 'paused'})\n clearInterval(this.timer);\n } else {\n if (this.state.timerStatus === 'paused') {\n this.resumeTimer();\n } else {\n this.startTimer(this.state.sessionLength * 60);\n }\n this.setState({ timerStatus: 'running'});\n }\n }",
"function start(){\n if(timerStarted){\n timerStarted = false;\n document.getElementById(\"start-button\").innerHTML = \"Start\";\n }\n else{\n timerStarted = true;\n if (sessionInProgress){\n startSession();\n }\n else{\n startBreak();\n }\n \n document.getElementById(\"start-button\").innerHTML = \"Stop\";\n }\n}",
"function play() {\n pressPlay = true;\n timerId = setInterval(countdown, 1000);\n playButton.hidden = true;\n stopButton.hidden = false;\n}",
"function quit() {\n onTimesUp();\n isPaused = true;\n document.getElementById( \"pause\" ).style.display = \"none\";\n document.getElementById( \"play\" ).style.display = \"inline-block\";\n console.log(timerIsRunning);\n }",
"function countdown() {\n setPlayCounter(!playCounter)\n }",
"function countDown() {\n totalSeconds--;\n timerDisplay(totalSeconds);\n if (totalSeconds == 0) {\n playSound();\n clearInterval(timer);\n time.innerHTML = \"00:00\";\n }\n }",
"function playPause() {\n setIsTimerRunning((prevState) => !prevState);\n }",
"function pauseTimer () {\n timerPauseTimestamp = Date.now();\n window.clearInterval(timerIntervalId);\n timerIntervalId = null;\n window.clearInterval(pageTitleIntervallId);\n pageTitleIntervallId = null;\n startPauseButton.innerHTML = 'Start';\n if (getActiveMode() == 'countdown') {\n startPauseButton.setAttribute('onclick', 'startCountdown();');\n } else if (getActiveMode() == 'stopwatch') {\n startPauseButton.setAttribute('onclick', 'startStopwatch();');\n };\n}",
"function defSettings(){\n Time.setTimer((defSeconds*secToMs) + (defSession*minToMs) + (defHours*hourToMs),defBreak*minToMs); \n Time.getTimer().session_phase = true;\n set = true; //timer is set boolean\n clickHandlers(); \n\n }",
"function startPause() {\n\n if(running === 0) {\n running = 1;\n timer();\n buttonStart.setAttribute('value', 'Pause');\n buttonStop.setAttribute('value', 'Reset');\n } else {\n running = 0;\n buttonStart.setAttribute('value', 'Resume');\n }\n}",
"function start() {\n console.log(\"Starting timer\");\n //play the \"start\" sound effect, if applicable\n if (count === RESET_VALUE) {\n playStartSound();\n }\n if (!isRunning) {\n isRunning = true;\n counter = setInterval(timer, 1000);\n startButtonText.innerHTML = \"Pause\";\n }\n}",
"function switchTimes() {\n \n if(session) {\n minutes = breakTime;\n session = false;\n $(\"#current\").html(\"Break\");\n }\n else {\n minutes = sessionTime;\n session = true;\n $(\"#current\").html(\"Session\");\n } \n seconds = 0;\n}",
"function resetTimer(){\n // when click to indicator or controls button stop timer\n clearInterval(timer);\n // then started again timer\n timer=setInterval(autoPlay,6000);\n }",
"function startTimer() {\n clearInterval(countdown);\n // grab the data in the buttons for each time and convert from string to integer\n const seconds = parseInt(this.dataset.time, 10);\n timer(seconds);\n}",
"function controlTimer() {\n startStopButton.addEventListener(\"click\", function () {\n if (status === \"playing\") {\n pauseTimer();\n startStopButton.dataset.status = \"stopped\";\n status = startStopButton.getAttribute(\"data-status\");\n startStopBtnIcon.classList.remove(\"fa-pause\");\n startStopBtnIcon.classList.add(\"fa-play\");\n } else if (status === \"complete\") {\n startStopButton.dataset.status = \"stopped\";\n status = startStopButton.getAttribute(\"data-status\");\n resetTimer();\n startStopBtnIcon.classList.remove(\"fa-redo\");\n startStopBtnIcon.classList.add(\"fa-play\");\n } else if (status === \"countdown\") {\n pauseCountdown();\n startStopButton.dataset.status = \"stopped\";\n status = startStopButton.getAttribute(\"data-status\");\n startStopBtnIcon.classList.remove(\"fa-pause\");\n startStopBtnIcon.classList.add(\"fa-play\");\n } else {\n startStopButton.dataset.status = \"playing\";\n status = startStopButton.getAttribute(\"data-status\");\n countDown();\n startStopBtnIcon.classList.remove(\"fa-play\");\n startStopBtnIcon.classList.add(\"fa-pause\");\n }\n });\n}",
"function runClock(){\n document.getElementById(\"startButton\").value = \"Reset\";\n \n var sessionLength = document.getElementById(\"clockTime\").innerHTML;\n \n var count = document.getElementById(\"clockTime\").innerHTML;\n \n \n var breakLength = document.getElementById(\"breakLength\").innerHTML;\n //breakFlag is ticker to keep track of if the session is in Session mode or Break mode (0 means Session mode)\n var breakFlag = 0;\n if (clockFlag == 0){\n timer = setInterval(function(){\n clockFlag = 1;\n seconds--;\n document.getElementById(\"clock\").innerHTML = count-1 + \":\" + seconds;\n \n //statement to add 0 in 10s digit of clock seconds when seconds reach single digits \n if(seconds<10){\n document.getElementById(\"clock\").innerHTML = count-1 + \":\" + \"0\" + seconds\n }\n //check for break flag when clock expires. If break flag on, change to session mode \n if(seconds == 0 && count == 1 && breakFlag > 0){\n count = sessionLength;\n seconds = 60;\n breakFlag = 0;\n document.getElementById(\"clock\").style.color=\"mediumspringgreen\";\n } \n //rollover for minutes in clock upon seconds reaching 0 \n if(seconds == 0 && count > 0){\n count--;\n seconds = 60;\n }\n //condition to change to break mode\n if (count <= 0 && breakFlag <= 0){\n count = breakLength;\n seconds = 60;\n breakFlag = 1;\n document.getElementById(\"clock\").style.color=\"Gold\";\n }\n\n }, 1000);}\n //resets timer upon second press of \"Click to Start Button\"\n else{ \n clearInterval(timer);\n clockFlag = 0;\n document.getElementById(\"clock\").innerHTML = sessionLength + \":\" + \"00\";\n seconds = 60;\n document.getElementById(\"startButton\").value = \"Click to Start\";\n \n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a variable size (height) from given index. | getVarSize(index, nocache) {
const { delta, variable, item } = this;
const cache = delta.varCache[index];
if (!nocache && cache) {
return cache.size;
}
if (typeof variable === 'function') {
return variable(index) || 0;
}
// when using item, it can only get current components height,
// need to be enhanced, or consider using variable-function instead
// eslint-disable-next-line no-nested-ternary
const slot = item
? (this.$children[index] ? this.$children[index].$vnode : null)
: this.$slots.default[index];
const style = slot && slot.data && slot.data.style;
if (style && style.height) {
const shm = style.height.match(/^(.*)px$/);
return (shm && +shm[1]) || 0;
}
const attrData = slot && slot.elm && slot.elm.dataset;
if (attrData && attrData.autoHeight) {
return +attrData.autoHeight || 0;
}
return 0;
} | [
"getSizeAt(index) {\n return this.sizesCache[index + 1] - this.sizesCache[index];\n }",
"getHeightForWhitespaceIndex(index) {\n this._checkPendingChanges();\n index = index | 0;\n return this._arr[index].height;\n }",
"_getItemSize(idx) {\n return {\n [this._sizeDim]: this._getSize(idx) || this._itemDim1,\n [this._secondarySizeDim]: this._itemDim2,\n };\n }",
"rowHeight({ index }) {\n\t\tlet rh = this.rowHeightCache[index] ? this.rowHeightCache[index] : 1;\n\t\treturn rh * this.props.itemHeight;\n\t}",
"getScrollForIndex(index, bottom) {\n const containerSize = parseInt(this.igxForContainerSize, 10);\n const scroll = bottom ? Math.max(0, this.sizesCache[index + 1] - containerSize) : this.sizesCache[index];\n return scroll;\n }",
"function getBarHeight(i) {\n return i;\n}",
"updateVariable(index) {\n // clear/update all the offfsets and heights ahead of index.\n this.getVarOffset(index, true);\n }",
"getVarOffset(index, nocache) {\n const { delta } = this;\n const cache = delta.varCache[index];\n\n if (!nocache && cache) {\n return cache.offset;\n }\n\n let offset = 0;\n for (let i = 0; i < index; i += 1) {\n const size = this.getVarSize(i, nocache);\n // If we can't get this item's height and then size is zero, so don't cache it\n // and the offset value use the default size\n // modify by andyhuang\n if (size > 0) {\n delta.varCache[i] = {\n size,\n offset,\n };\n offset += size;\n } else {\n offset += this.size;\n }\n }\n\n delta.varLastCalcIndex = Math.max(delta.varLastCalcIndex, index - 1);\n delta.varLastCalcIndex = Math.min(delta.varLastCalcIndex, delta.total - 1);\n\n return offset;\n }",
"function getIndex (index) {\n index = parseInt(index);\n var o = {};\n o.o = index*mtu; o.l = ((Math.ceil(main.size/mtu)-1 == index) ? (main.size % mtu) : mtu); o.i = index;\n return o;\n}",
"function getHeight(size) {\n return BASE_SIZE / (function() {\n switch(size) {\n case '1':\n case '2h':\n return 1;\n case '2v':\n case '3':\n return 2;\n case '4':\n return 4;\n }\n })();\n}",
"get detailHeight() {}",
"GetInterpolatedHeight() {}",
"function getHeight(index, instance) {\n return instance.sectionInfo[index].height = instance.$sectionWrappers.eq(index).children().outerHeight(true);\n }",
"get estimatedHeight() { return -1; }",
"getWhitespacesAccumulatedHeight(index) {\n this._checkPendingChanges();\n index = index | 0;\n let startIndex = Math.max(0, this._prefixSumValidIndex + 1);\n if (startIndex === 0) {\n this._arr[0].prefixSum = this._arr[0].height;\n startIndex++;\n }\n for (let i = startIndex; i <= index; i++) {\n this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height;\n }\n this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);\n return this._arr[index].prefixSum;\n }",
"get stretchHeight() {}",
"function bigger(index) {\n return mediant(index, RIGHT_BOUNDARY);\n}",
"getVarAllHeight() {\n const {\n delta: {\n total, end, keeps, varLastCalcIndex, start, varAverSize\n }, getVarOffset, size\n } = this;\n if (total - end <= keeps || varLastCalcIndex === total - 1) {\n return getVarOffset(total);\n }\n return getVarOffset(start) + ((total - end) * (varAverSize || size));\n }",
"findHeight(value) {\n if (value < 24) return 24;\n return value;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2.Get the tens of a number having 3 digits | function getTheTensNumber(n) {
if (n.toString().length !== 3) return -1;
return Math.trunc(n / 10) % 10;
} | [
"function smallestThreeDigit(t) {\r\n\tvar result\r\n\tfor (var i=9; i>=0; i--) {\r\n\t\tfor (var j=9; j>=0; j--) {\r\n\t\t\tfor (var k=9; k>=0; k--) {\r\n\t\t\t\tif (i*j*k === t)\r\n\t\t\t\t\tresult = i*100 + j*10 + k\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn result\r\n}",
"function extractDigit3(num,digitNum) {\n var tens = 10;\n if (digitNum == 0) {\n digitNum = 1;\n tens = 1;\n }\n var tempNum = digitNum;\n if (digitNum < 0) {\n tempNum *= -1;\n }\n for (i=1; i<tempNum; i++) {\n tens *= 10;\n }\n if (digitNum > 0) {\n firstValue = Math.trunc((num/tens)%(10*digitNum));\n } else {\n firstValue = Math.trunc((num*tens)%(10*digitNum));\n }\n \n // console.log(firstValue);\n theValue = firstValue%10;\n console.log(theValue);\n}",
"function nDigit(n, number){\n return Math.floor((number / Math.pow(10, n)) % 10);\n }",
"function getTheHundredsNumber(n) {\n if (n.toString().length !== 3) return -1;\n \n return Math.trunc(n / 100);\n}",
"function tetra(n) {\r\n return (n * (n + 1) * (n + 2)) / 6;\r\n}",
"function onesDigit(n){\n return n % 10;\n }",
"function findDigits(n) {\n let d = 0,\n i,\n arr = n.toString().split('');\n for (i of arr) {\n if (n % i === 0) {\n d++;\n }\n }\n return d;\n}",
"function factDigits(n) {\n \n let factor = 1n;\n\n for(let i = BigInt(n); i >= 1; i--){\n factor *= i;\n }\n const convert = new String(factor).length;\n\n return convert\n}",
"function getDigit(number, n){\r\n\treturn Math.floor(number/(Math.pow(10,n-1)))%10;\r\n}",
"function onesDigit(n) {\n return n % 10;\n}",
"function ProductDigits(num) {\n var ref = Math.sqrt(num);\n var len = num.toString().length + 1;\n for (i = 0; i <= ref; i++) {\n if (num % i === 0) {\n let other = num / i;\n let len1 = other.toString().length;\n let len2 = i.toString().length;\n if (len1 + len2 < len) {\n return len1 + len2;\n }\n }\n }\n return len;\n}",
"function smallerPowersOfTen(n) { \n const i = 4- Math.floor(Math.log10(n)/3)\n return powersOfTen.slice(i)\n}",
"function eanCheckDigit(s)\r\n{\r\n var result = 0;\r\n var rs = s.reverse();\r\n for (counter = 0; counter < rs.length; counter++)\r\n {\r\n result = result + parseInt(rs.charAt(counter)) * Math.pow(3, ((counter+1) % 2));\r\n }\r\n return (10 - (result % 10)) % 10;\r\n}",
"function lastNDigits(num, n) {\n divisor = 10 ** n;\n return (num >= 0) ? num % divisor : -1 * num % divisor;\n}",
"function tetra(n) {\n return n*(n+1)*(n+2)/6\n }",
"function digitnPowers(n) {\n\tlet sum = 0;\n\t// very naive assumption, but seems to work\n\tfor (let i = 2; i < n * 9 ** n; i += 1) {\n\t\tconst powSum = String(i)\n\t\t\t.split('')\n\t\t\t.map(d => parseInt(d) ** n)\n\t\t\t.reduce((prev, next) => prev + next, 0);\n\t\tif (powSum === i) {\n\t\t\tsum += i;\n\t\t}\n\t}\n\treturn sum;\n}",
"function digitDegree(n) {\n function getSum(num){\n var sum = 0;\n while(num){\n sum += num % 10;\n num = Math.floor(num/ 10);\n\n }\n return sum;\n }\n\n var i = 0;\n for(; n > 9; i++){\n n = getSum(n);\n }\n return i;\n}",
"function makeNumberMultiple(number){\n // console.log(number)\n let digits = `${number}`.split('').length\n // console.log('<< Multiple is running >>')\n\n\n if(digits%3){\n // console.log('its not a multiple, fix it')\n return makeNumberMultiple(`0${number}`)\n }\n else{\n // console.log(' its a multiple, fixed!')\n return number;\n }\n\n}",
"function squareDigits(n) {\n const arr = n.toString().split('');\n return arr.map(a => Math.pow(Number(a), 2)).join('');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is Unique Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Solution 1: create a set and loop through the string. Check if character exists in set. If yes, return false. If not, add character. Time: O(N) Additional Space: O(N) | function isUnique1(string){
let charsSet = new Set();
for(let i = 0; i < string.length; i++){
if(charsSet.has[string[i]]){
return false;
} else {
charsSet.add[string[i]];
};
return true;
}
} | [
"function isUnique(s) {\n // assuming only lowercase characters; can be changed to suit other character combinations\n if (s.length > 26) {\n return false\n }\n let charSet = new Set([])\n for (var i=0; i<s.length; i++) {\n if (charSet.has(s[i])) {\n return false\n } else {\n charSet.add(s[i])\n }\n }\n return true\n}",
"function isUnique(str) {\n // I will need to traverse through a string.\n for (let i = 0; i < str.length; i++) {\n // I need to somehow keep track of the letters that I saw but I cannot use additional data stuctures.\n // I guess I could use a nested for loop and then check to see if any of the characters match to one another.\n for (let j = 0; j < str.length; j++) {\n if (i === j) {\n return false;\n }\n }\n }\n\n return true;\n}",
"function isUniqueCharacters(string) {\n\t// 26 characters in the english alphabet.\n if (string.length > 26) {\n \treturn false;\n }\n \n const char_set = [];\n for (let i = 0; i < string.length; i++) {\n \tlet val = string[i];\n if (char_set[val]) {\n \treturn false;\n }\n char_set[val] = true;\n }\n return true;\n}",
"function isUniqueSet(str) {\n var set = new Set();\n\n for( var i = 0; i < str.length; i++ ) {\n var char = str.charAt(i);\n\n if( set.has(char) ) {\n return false;\n }\n\n set.add(char)\n }\n\n return true;\n }",
"function hasUniqueChars(word){\nlet uniqueChars = new Set([])\nfor (let i = 0; i < word.length; i++){\n uniqueChars.add(word[i])\n}\nreturn uniqueChars.size === word.length\n}",
"function uniqueChars(string) {\n let chars = string.split('');\n\tif (chars.length > 256) return false;\n for (let i=0; i < chars.length; i++) {\n for (let j=i+1; j < chars.length; j++) {\n if (chars[i] === chars[j]) {\n return false;\n }\n }\n }\n return true;\n}",
"function hasUniqueChars(str) {\n const holdingArr = [];\n\n const charArr = str.toLowerCase().split(\"\");\n // console.log(charArr)\n for (let i = 0; i < charArr.length; i++) {\n if (holdingArr.includes(charArr[i])) {\n // console.log(charArr[i], holdingArr)\n return false;\n } else {\n holdingArr.push(charArr[i]);\n }\n }\n return true;\n}",
"function everyCharUnique(str) {\n for (let i = 0; i < str.length; i++) {\n for(let j = i + 1; j<str.length; j++) {\n if (str[i] === str[j]) {\n return false\n }\n }\n }\n return true;\n}",
"function hasUniqueChars(str){\n let wordArray =str.split('');\n let status= true;\n for (let i =0; i< wordArray.lenght;i ++){\n for (let j=i+1; j<wordArray.lenght; j ++){\n if(wordArray[i]=== wordArray[j]){\n status = false;\n return status;\n }\n }\n }\n return status;\n}",
"function isUniq(str) {\n var hash = {};\n for (var i = 32; i <= 126; i++) {\n hash[String.fromCharCode(i)] = false;\n }\n for (var i = 0; i < str.length; i++) {\n if (hash[str[i]]) {\n return false;\n } else {\n hash[str[i]] = true;\n }\n }\n return true;\n}",
"function hasUniqueChars(s) {\n var chars = []\n , i = 0\n ;\n if (s.length > 256) { return false; }\n for (i; i < s.length; i++) {\n var val = s.charAt(i);\n if (chars[val]) { return false; }\n chars[val] = true;\n }\n return true;\n}",
"function isUnique(str){\n let map = {}\n for(let i = 0; i < str.length; i++){\n if(map.hasOwnProperty(str[i])){\n return false\n } else {\n map[str[i]] = 1\n }\n }\n return true \n}",
"function allUnique(input) {\n var characterCounts = countCharacters(input);\n\n for (character in characterCounts) {\n if (characterCounts[character] !== 1) {\n return false;\n }\n }\n\n return true;\n }",
"function isUnique(s){\n console.log(\"isUnique receives a String - version with aux array data structure\", s)\n let aux = [];\n for(let i=0; i<s.length; i++){\n aux.push(s[i]);\n for(let j=0; j<aux.length-1; j++){\n if(s[i] === aux[j])\n return false\n }\n }\n return true;\n}",
"function hasUniqueChars(word) {\n let uniqueChars = new Set([]);\n for (let i = 0; i < word.length; i++) {\n uniqueChars.add(word[i]);\n }\n return uniqueChars.size === word.length;\n}",
"function isUnique(str) {\n if (str.length > 256) {\n return false;\n }\n for (var i = 0; i < str.length; i++) {\n if (str.indexOf(str[i]) !== str.lastIndexOf(str[i])) {\n return false;\n }\n }\n return true;\n}",
"function uniqueCharsInWords(string) {\n let words = string.split(\" \");\n\n for (let i = 0; i < words.length; i++) {\n let word = words[i];\n if (!unique(word)) {\n return false;\n }\n }\n return true;\n}",
"function isCharactersInSubstitionAlphabetUnique(alphabet) {\n\n const arrOfAlphabet = [...alphabet];\n for (let character of arrOfAlphabet) {\n\n const isDuplicateFound = arrOfAlphabet.filter((char) => (character === char))\n \n if (isDuplicateFound.length > 1) {\n return false;\n }\n return true;\n }\n }",
"function isUniqueWithHash(s){\n console.log(\"isUnique receives a String - version with Hash\", s)\n let hashTable = {}\n for(let i=0 ; i<s.length; i++) {\n if(!hashTable[s[i]])\n hashTable[s[i]] = 1\n else {\n return false\n }\n }\n return true\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores host binding fn and number of host vars so it will be queued for binding refresh during CD. | function queueHostBindingForCheck(tView,def,hostVars){ngDevMode&&assertEqual(getFirstTemplatePass(),true,'Should only be called in first template pass.');var expando=tView.expandoInstructions;var length=expando.length;// Check whether a given `hostBindings` function already exists in expandoInstructions,
// which can happen in case directive definition was extended from base definition (as a part of
// the `InheritDefinitionFeature` logic). If we found the same `hostBindings` function in the
// list, we just increase the number of host vars associated with that function, but do not add it
// into the list again.
if(length>=2&&expando[length-2]===def.hostBindings){expando[length-1]=expando[length-1]+hostVars;}else{expando.push(def.hostBindings,hostVars);}} | [
"function allocHostVars(count) {\n var lView = Object(render3_state.m)(), tView = lView[interfaces_view.s];\n tView.firstTemplatePass && (function(tView, def, hostVars) {\n var expando = tView.expandoInstructions, length = expando.length;\n // Check whether a given `hostBindings` function already exists in expandoInstructions,\n // which can happen in case directive definition was extended from base definition (as a part of\n // the `InheritDefinitionFeature` logic). If we found the same `hostBindings` function in the\n // list, we just increase the number of host vars associated with that function, but do not add it\n // into the list again.\n length >= 2 && expando[length - 2] === def.hostBindings ? expando[length - 1] = expando[length - 1] + hostVars : expando.push(def.hostBindings, hostVars);\n }(tView, Object(render3_state.i)(), count), function(tView, lView, totalHostVars) {\n for (var i = 0; i < totalHostVars; i++) lView.push(tokens.a), tView.blueprint.push(tokens.a), \n tView.data.push(null);\n }(tView, lView, count));\n }",
"setHost (hostName) {\n this.gbl_host = hostName\n }",
"function queueHostBindingForCheck(tView, def, hostVars) {\n ngDevMode &&\n assertEqual(tView.firstTemplatePass, true, 'Should only be called in first template pass.');\n var expando = tView.expandoInstructions;\n var length = expando.length;\n // Check whether a given `hostBindings` function already exists in expandoInstructions,\n // which can happen in case directive definition was extended from base definition (as a part of\n // the `InheritDefinitionFeature` logic). If we found the same `hostBindings` function in the\n // list, we just increase the number of host vars associated with that function, but do not add it\n // into the list again.\n if (length >= 2 && expando[length - 2] === def.hostBindings) {\n expando[length - 1] = expando[length - 1] + hostVars;\n }\n else {\n expando.push(def.hostBindings, hostVars);\n }\n}",
"function queueHostBindingForCheck(tView, def, hostVars) {\n ngDevMode &&\n assertEqual(getFirstTemplatePass(), true, 'Should only be called in first template pass.');\n var expando = tView.expandoInstructions;\n var length = expando.length;\n // Check whether a given `hostBindings` function already exists in expandoInstructions,\n // which can happen in case directive definition was extended from base definition (as a part of\n // the `InheritDefinitionFeature` logic). If we found the same `hostBindings` function in the\n // list, we just increase the number of host vars associated with that function, but do not add it\n // into the list again.\n if (length >= 2 && expando[length - 2] === def.hostBindings) {\n expando[length - 1] = expando[length - 1] + hostVars;\n }\n else {\n expando.push(def.hostBindings, hostVars);\n }\n}",
"function setHostBindings(tView,viewData){if(tView.expandoInstructions){var bindingRootIndex=viewData[BINDING_INDEX]=tView.expandoStartIndex;setBindingRoot(bindingRootIndex);var currentDirectiveIndex=-1;var currentElementIndex=-1;for(var i=0;i<tView.expandoInstructions.length;i++){var instruction=tView.expandoInstructions[i];if(typeof instruction==='number'){if(instruction<=0){// Negative numbers mean that we are starting new EXPANDO block and need to update\n// the current element and directive index.\ncurrentElementIndex=-instruction;// Injector block and providers are taken into account.\nvar providerCount=tView.expandoInstructions[++i];bindingRootIndex+=INJECTOR_BLOOM_PARENT_SIZE+providerCount;currentDirectiveIndex=bindingRootIndex;}else{// This is either the injector size (so the binding root can skip over directives\n// and get to the first set of host bindings on this node) or the host var count\n// (to get to the next set of host bindings on this node).\nbindingRootIndex+=instruction;}setBindingRoot(bindingRootIndex);}else{// If it's not a number, it's a host binding function that needs to be executed.\nif(instruction!==null){viewData[BINDING_INDEX]=bindingRootIndex;instruction(2/* Update */,readElementValue(viewData[currentDirectiveIndex]),currentElementIndex);}currentDirectiveIndex++;}}}}",
"function setBindingRootForHostBindings(value) {\n var lframe = instructionState.lFrame;\n lframe.bindingIndex = lframe.bindingRootIndex = value;\n}",
"function setHostBindings(bindings) {\n if (bindings != null) {\n var defs = currentView.tView.directives;\n for (var i = 0; i < bindings.length; i += 2) {\n var dirIndex = bindings[i];\n var def = defs[dirIndex];\n def.hostBindings && def.hostBindings(dirIndex, bindings[i + 1]);\n }\n }\n}",
"function setHostBindings(bindings) {\n if (bindings != null) {\n var defs = tView.directives;\n for (var i = 0; i < bindings.length; i += 2) {\n var dirIndex = bindings[i];\n var def = defs[dirIndex];\n def.hostBindings && def.hostBindings(dirIndex, bindings[i + 1]);\n }\n }\n}",
"function allocHostVars(count) {\n if (!getFirstTemplatePass())\n return;\n var lView = getLView();\n var tView = lView[TVIEW];\n queueHostBindingForCheck(tView, getCurrentDirectiveDef(), count);\n prefillHostVars(tView, lView, count);\n}",
"function bindDragHandlerToNewHost(){\r\n\t//array that hold DragHandler object that bind to new host\r\n\tvar hostDragHandler=new Array();\r\n\t//Iterating the received json data of new discovered host \r\n\tfor(i in newHostJson){\r\n\t\t//binding drag handler to new discovered host\r\n\t\tvar dh=DragHandler.attach(document.getElementById(newHostJson[i].name));\r\n\t\t//binding drag end handler function\t\t\r\n\t\tdh.dragEnd=findandmark;\r\n\t\thostDragHandler.push(dh);\r\n\t}\t\r\n}",
"function setHostBindings(tView, viewData) {\n var selectedIndex = getSelectedIndex();\n try {\n if (tView.expandoInstructions) {\n var bindingRootIndex = viewData[BINDING_INDEX] = tView.expandoStartIndex;\n setBindingRoot(bindingRootIndex);\n var currentDirectiveIndex = -1;\n var currentElementIndex = -1;\n for (var i = 0; i < tView.expandoInstructions.length; i++) {\n var instruction = tView.expandoInstructions[i];\n if (typeof instruction === 'number') {\n if (instruction <= 0) {\n // Negative numbers mean that we are starting new EXPANDO block and need to update\n // the current element and directive index.\n currentElementIndex = -instruction;\n setActiveHostElement(currentElementIndex);\n // Injector block and providers are taken into account.\n var providerCount = tView.expandoInstructions[++i];\n bindingRootIndex += INJECTOR_BLOOM_PARENT_SIZE + providerCount;\n currentDirectiveIndex = bindingRootIndex;\n }\n else {\n // This is either the injector size (so the binding root can skip over directives\n // and get to the first set of host bindings on this node) or the host var count\n // (to get to the next set of host bindings on this node).\n bindingRootIndex += instruction;\n }\n setBindingRoot(bindingRootIndex);\n }\n else {\n // If it's not a number, it's a host binding function that needs to be executed.\n if (instruction !== null) {\n viewData[BINDING_INDEX] = bindingRootIndex;\n var hostCtx = unwrapRNode(viewData[currentDirectiveIndex]);\n instruction(2 /* Update */, hostCtx, currentElementIndex);\n // Each directive gets a uniqueId value that is the same for both\n // create and update calls when the hostBindings function is called. The\n // directive uniqueId is not set anywhere--it is just incremented between\n // each hostBindings call and is useful for helping instruction code\n // uniquely determine which directive is currently active when executed.\n incrementActiveDirectiveId();\n }\n currentDirectiveIndex++;\n }\n }\n }\n }\n finally {\n setActiveHostElement(selectedIndex);\n }\n}",
"_setValueAndParseData() {\n\t\tconst localStorageHostId = webix.storage.local.get(\"hostId\");\n\t\tconst firstHostItemId = process.env.SERVER_LIST[0].id;\n\t\tconst hostId = localStorageHostId || firstHostItemId;\n\t\tthis._putValuesAfterHostChange(hostId);\n\t\tthis._hostBox.setValue(hostId);\n\t\tthis._view.$scope.parseCollectionData();\n\t}",
"bind() {\n this.bindings.forEach(binding => {\n binding.bind()\n })\n }",
"function setBinding(binding, value) {\n if (!data.bindings[binding]) {\n data.bindings[binding] = {\n elements: [],\n lastValue: undefined,\n value: undefined,\n listeners: []\n };\n }\n\n data.bindings[binding].lastValue = data.bindings[binding].value;\n data.bindings[binding].value = value;\n data.bindings[binding].elements.map(element => {\n element.element[element.value] = data.bindings[binding].value;\n });\n }",
"setHost(host) {\n if (!host) {\n this._host = undefined;\n }\n else {\n this.set(host, \"SCHEME_OR_HOST\");\n }\n }",
"function setBinding(binding, value) {\n if (!data.bindings[binding]) {\n data.bindings[binding] = {\n elements: [],\n lastValue: undefined,\n value: undefined,\n listeners: []\n };\n }\n\n data.bindings[binding].lastValue = data.bindings[binding].value;\n data.bindings[binding].value = value;\n data.bindings[binding].elements.map(element => {\n element.element[element.value] = data.bindings[binding].value;\n });\n}",
"_bindDependencies() {\n\t\tthis._config.initBindCore(ns, this._oc, this._config.bind);\n\t\tthis._config.initBindApp(ns, this._oc, this._config.bind);\n\t}",
"bind(key) {\n const binding = new binding_1.Binding(key.toString());\n this.add(binding);\n return binding;\n }",
"function updateHostInfos() {\n Receiver.hostInfo()\n .then(docs => {\n return Receiver.listHostDb();\n })\n .then(docs => {\n\n console.log(docs);\n let storageSize = 0;\n $('.dash__storage__hashes').text('');\n\n for (let i = 0; i < docs.length; i++) {\n if (docs[i].isHosted === true) {\n storageSize += docs[i].fileSize;\n }\n const hashAddress = docs[i].hashAddress;\n // const hashDiv = $('<div></div>');\n // hashDiv.text(hashAddress);\n $('.dash__storage__hashes').append(hashAddress + '<br>');\n }\n storageSize = bytesMag(storageSize);\n $('.dash__storage__size__num').text(storageSize);\n })\n .catch(err => {\n console.error(err);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
count the nonnull elements in an array | function countNonEmpty(array) {
return array.filter(Boolean).length;
} | [
"function arrayLengthWithoutNull(array) {\n var length = 0;\n for (var i=0; i<array.length; i++) {\n if (array[i])\n length++;\n }\n return length;\n}",
"function _countMissing(array) {\n\t return array.length - _.without(array, undefined, null).length;\n\t }",
"function countTrue(arr) {\n\treturn arr.length == 0 ? 0 : arr.filter(val => val).length;\n}",
"function countTrue(arr) {\n return arr.filter( v => v ).length;\n}",
"function count(arr) {\n return arr.length;\n}",
"function countZeroes(array) {\n // SOLUTION GOES HERE\n}",
"function countZeroes(array) {\n function counter(total, element) {\n return total + (element === 0 ? 1 : 0);\n }\n return reduce(counter, 0, array);\n}",
"function getUndefined(array){\n\t\t\tlet count = 0;\n\t\t\tfor(let i=0; i<array.length; i++){\n\t\t\t\tif(array[i] === \"\") count++\n\t\t\t}\n\t\t\treturn count;\n\t\t}",
"function countTruthy(array) {\n\n let count = 0;\n for (let element of array) {\n if (element)\n count++\n }\n console.log(count);\n}",
"function theTruthCounts(array) {\n\t// create a counter variable to accumulate the elements\n\tlet count = 0;\n\t// iterate through the array\n\tfor (let i = 0; i < array.length; i++) {\n\t\t// grab the element\n\t\tlet element = array[i];\n\t\t// if the element is an array\n\t\tif (Array.isArray(element)) {\n\t\t\t// then get the count of truthy elements in the array\n\t\t\tcount += theTruthCounts(element);\n\t\t} else {\n\t\t\t// if it is just a value and is true\n\t\t\tif (element) {\n\t\t\t\t// increment count\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t} // return count\n\treturn count;\n}",
"function countTrue(arr){\n return array.filter(t=>t==true).length;\n}",
"function count(array) {\n\treturn d3.keys(array).length;\n}",
"function countTrue(array){\n let counter = 0;\n \n for(let i = 0; i < array.length; i++){\n if(array[i]) counter++;\n } \n return counter;\n}",
"function theTruthCounts(array){\n\n let count = 0;\n\n for (let i = 0; i < array.length; i++){\n \n let element = array[i];\n\n if(Array.isArray(element)){\n\n count += theTruthCounts(element); \n // get result from nested object - 1 or 0\n\n } else if(element)count++;\n }\n \n return count;\n}",
"function getLengthOfMissingArray(arrayOfArrays) {\n let missing = 0;\n \n if(arrayOfArrays && !arrayOfArrays.includes(null)) {\n arrayOfArrays.sort((a, b) => a.length - b.length);\n for(let i = 0; i <= arrayOfArrays.length - 1; i++){\n if(arrayOfArrays[i].length == 0){\n missing = 0;\n break;\n } else if(arrayOfArrays[i].length + 1 != arrayOfArrays[i + 1].length){\n missing = arrayOfArrays[i].length + 1;\n break;\n }\n }\n }\n \n return missing;\n}",
"function countOccurrences(arr) {\r\nlet result = arr.reduce(function(count,item) { \r\n if(count[item] === undefined) count[item] = 1;\r\n else count[item] += 1;\r\n return count;\r\n },[])\r\n return result;\r\n}",
"function zeroPlentiful(arr){\n let t = arr.join('').match(/0+/g);\n if(t === null){\n return 0;\n }\n // return t.every(a => a.length > 3) ? t.length : 0;\n return t.map(function(a){\n return a.length > 3;\n }) ? t.length : 0;\n}",
"function nonEmpty(data){\n\n var count = 0; /**Variable that stores the number of element that are not empty.*/\n\n for(var i = 0; i < data.length; i++) /**For loop iteration through the dataset from the beginning to the end*/\n {\n if(data[i].appraisalValue != 0) {/**If the current element is not null then enter if statement*/\n count += 1; /**Increment the count*/\n }\n }\n\n return count; /**Return the variable count*/\n}",
"function countPositives(arr) {\n var count = 0;\n for(var i=0;i<arr.length;i++) {\n if(arr[i] > 0) {\n count++;\n }\n }\n return count;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a promise for response trailers from the mock data. | promiseTrailers() {
var _a;
const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers;
return trailers instanceof RpcError
? Promise.reject(trailers)
: Promise.resolve(trailers);
} | [
"fetchWaitTimes() {\n return new Promise(((resolve, reject) => {\n // request challenge string\n this.http({\n method: 'POST',\n url: `${this.constructor.apiBase}/queue-times`,\n headers: {\n connection: 'Keep-Alive',\n },\n }).then((data) => {\n if (!data.challenge) {\n reject(new Error(`Failed to get challenge string from API: ${JSON.stringify(data)}`));\n return;\n }\n this.log(`Got challenge string ${data.challenge} for park ${this.constructor.parkName}`);\n\n this.GenerateAPIResponse(data.challenge).then((response) => {\n this.log(`Generated response string ${response}`);\n\n // make API request with our response request\n this.http({\n method: 'POST',\n url: `${this.constructor.apiBase}/queue-times`,\n headers: {\n connection: 'Keep-Alive',\n 'content-type': 'application/x-www-form-urlencoded',\n },\n data: {\n response,\n challenge: data.challenge,\n resort: this.constructor.resortId || null,\n },\n }).then((waittimes) => {\n // park API results differ ever so slightly.\n // Chessington has it under \"queue-times\", Alton Towers just returns an array\n const rideData = (waittimes['queue-times'] || waittimes);\n\n rideData.forEach((ride) => {\n const rideName = this.constructor.rideNames[ride.id];\n // skip if we have no name for this asset\n if (!rideName) return;\n\n // apply each wait time data\n const rideObject = this.getRideObject({\n id: ride.id,\n name: rideName,\n });\n\n if (!rideObject) {\n this.log(`Failed to find ride with ID ${ride.id}`);\n } else {\n // update ride wait time\n rideObject.waitTime = ride.status === 'closed' ? -1 : (ride.wait_time || -1);\n }\n });\n resolve();\n }, reject);\n }, reject);\n }, reject);\n }));\n }",
"function getMoviesMock() {\n return returnPromise();\n}",
"function setup() {\n console.log('Setting up clients and policies...')\n let clients = []\n let policies = []\n return new Promise(async resolve => {\n clients = JSON.parse(await request.get({\n url: 'https://www.mocky.io/v2/5808862710000087232b75ac',\n rejectUnauthorized: false,\n })).clients\n policies = JSON.parse(await request.get({\n url: 'https://www.mocky.io/v2/580891a4100000e8242b75c5',\n rejectUnauthorized: false,\n })).policies\n console.log('Setup complete')\n resolve({clients, policies})\n })\n}",
"async function readTrailers(headers, r) {\n const trailers = parseTrailer(headers.get(\"trailer\"));\n if (trailers == null)\n return;\n const trailerNames = [...trailers.keys()];\n const tp = new mod_ts_3.TextProtoReader(r);\n const result = await tp.readMIMEHeader();\n if (result == null) {\n throw new Deno.errors.InvalidData(\"Missing trailer header.\");\n }\n const undeclared = [...result.keys()].filter((k) => !trailerNames.includes(k));\n if (undeclared.length > 0) {\n throw new Deno.errors.InvalidData(`Undeclared trailers: ${Deno.inspect(undeclared)}.`);\n }\n for (const [k, v] of result) {\n headers.append(k, v);\n }\n const missingTrailers = trailerNames.filter((k) => !result.has(k));\n if (missingTrailers.length > 0) {\n throw new Deno.errors.InvalidData(`Missing trailers: ${Deno.inspect(missingTrailers)}.`);\n }\n headers.delete(\"trailer\");\n }",
"function fakeRequest(data) {\n return new es6_promise_1.Promise(function (resolve) {\n setTimeout(function () {\n resolve(data);\n }, (Math.random() * 100));\n });\n}",
"function getMockDependencies() {\n\n MOCKS.SessionService = {\n data : {\n authlogindata : {'customerId' : '123456', 'accountId' : '456789' }\n },\n get : function(key) {\n \n if (flag == true){\n return factory.build('api998-repLogindataUnverified');\n }\n else {\n return factory.build('api998-repLogindata');\n }\n },\n set : function(key, value) {\n this.data[key] = value;\n }\n };\n\n MOCKS.LOGIN_CONSTANTS= {\n 'AUTHLOGINDATA': 'authlogindata'\n };\n\n MOCKS.ENV = {\n 'apigeeRoot': 'http://rebelliondev-dev01.apigee.net/'\n };\n\n\n MOCKS.contentApiFactory={\n getAEMRequest : function() { var defer = $q.defer(); defer.resolve({}); return defer.promise; },\n getContentData : function(){\n var deferred = $q.defer();\n deferred.resolve(facadeData);\n return deferred.promise;\n }\n };\n\n MOCKS.CONTENT_API_ENDPOINTS={\n };\n MOCKS.FACADE_API_ENDPOINTS={\n 'API_290_getDropDowns': 'assisted/v1/reference-list/drop-down?type={type}',\n 'API_353_getRepDashLookupCriteria': 'assisted-customer/v1/reference-list/rep-dash?type={tabLabel}',\n 'API_321_getSearchOrders': 'assisted-customer/v1/{tabLabel}/search?{searchCriteria}={searchParameter}&offset={offset}&limit={limit}&sort={sortByValue}&sortOrder={sortOrder}&filter={filterOptions}',\n 'API_321_getSearchOrdersNew': 'assisted-customer/v1/{tabLabel}/search?{paramString}',\n 'API_331_getRolePermissions': 'assisted-customer/v1/customers/{customerId}/accounts/{accountId}/roles',\n 'API_337_getSpecialInstructions': 'assisted-customer/v1/customers/{customerId}/accounts/{accountId}/special-instructions',\n 'API_205_customerVerification': 'assisted-customer/v1/customers/{id}/verification',\n 'API_233_postRepVerification': 'assisted-customer/v1/rep-verification',\n 'API_396_postDeadAir':'v1/rep-dash/log',\n 'API_420_sendTemporaryPin': 'assisted-customer/v1/utility/send-temp-pin'\n };\n\n MOCKS.ERROR_CONST={\n UNKNOWN_ERROR:'UNKNOWN_ERROR'\n }\n\n MOCKS.LOOKUP_CONST={\n 'STATUS_VERIFY': 'Verified',\n 'HIDECHECK_MARK': 'hideCheckmark',\n 'HIDDEN_EMAIL': 'XXXXXX',\n 'NOTIFICATION_PREFERENCE_EMAIL': 'email'\n }\n}",
"async getTrades() {\n var exchangeHistoricTrades = {}\n if (this.exchange === 'GDAX') {\n let accounts = await this.api.getAccounts()\n var accountHistoryCalls = []\n accounts.forEach(function (account) {\n accountHistoryCalls.push(this.api.getAccountHistory(account.id)\n .then(function (histories) {\n return this.parseHistories(histories, account.currency)\n }.bind(this))\n .catch(function (error) {\n throw new Error(error)\n }))\n }.bind(this))\n\n return Promise.all(accountHistoryCalls)\n .then(parsed_histories => {\n exchangeHistoricTrades[this.exchange] = parsed_histories\n return exchangeHistoricTrades\n })\n .catch(error => {\n throw new Error(error)\n })\n }\n else {\n exchangeHistoricTrades[this.exchange] = this.exchange + ' not implemented yet'\n return exchangeHistoricTrades\n }\n }",
"function onSessionTrailers(id) {\n var owner = this[kOwner];\n var streams = owner[kStreams];\n var stream = streams.get(id);\n assert(stream, 'Internal HTTP/2 Failure. Stream does not exist.');\n var trailers = new Holder();\n stream.emit('fetchTrailers', trailers);\n return mapToHeaders(trailers);\n}",
"BuildWaitTimesResponse() {\n // convert all our ride objects into JSON\n const result = [];\n Object.keys(this[sRideObjects]).forEach((rideID) => {\n result.push(this[sRideObjects][rideID].toJSON());\n });\n return Promise.resolve(result);\n }",
"getTracers() {\n\t\t//TODO: make configurable\n\t\t/* Create the HTTP GET request to the /tracers API endpoint. */\n\t\tvar req = new Request(`http://127.0.0.1:8081/tracers`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { Hoot: \"!\" }\n\t\t});\n\n\t\tfetch(req)\n\t\t\t.then(response => response.json())\n\t\t\t.catch(error => setTimeout(this.getTracers, 1500)) // If the API isn't up, retry until it comes up\n\t\t\t.then(response => {\n\t\t\t\ttry {\n\t\t\t\t\tif (\n\t\t\t\t\t\tJSON.stringify(this.state.tracers) !==\n\t\t\t\t\t\tJSON.stringify(response)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.setState({\n\t\t\t\t\t\t\ttracers: response,\n\t\t\t\t\t\t\tptracers: this.parseVisibleTracers(\n\t\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t\t\tthis.state.filters\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\t// Probably an error with parsing the JSON.\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t});\n\t}",
"function getMockDependencies() {\n MOCKS.navigateToNextstate = function(){\n return 'navigateToNextstateSuccess'\n };\n MOCKS.navigateToProcessedState = function(){\n return 'navigateToProcessedStateSuccess'\n };\n MOCKS.getNextItemOnReasonSelection = function(){\n return 'getNextItemOnReasonSelectionSuccess'\n };\n MOCKS.orderPageOnReasonSelection = function(){\n return 'orderPageOnReasonSelectionSuccess'\n };\n MOCKS.redirectToCartOnReasonSelection = function(){\n return 'redirectToCartOnReasonSelectionSuccess'\n };\n\n MOCKS.RETURN_EXCHANGE_CONSTS ={\n RETURN_ELIGIBLE: 'returnEligible',\n EXCHANGE_ELIGIBLE: 'remorseExchangeEligible',\n RETURN_FLAG: 'returnFlag',\n EXCHANGE_FLAG: 'exchangeFlag',\n CANCELLED_STATUS: 'Cancelled',\n PARENT_STATE: 'returnWarrantyExchange',\n ORDER_FORM: '.order',\n PROCESSED_ARRAY: 'processedArray',\n POST_VOID_LABEL :'PostVoid',\n CANCEL:'Cancel',\n MY_ACCOUNT : 'myAccount',\n PRINT_SHIPPING : 'shippingLabel',\n EXCHANGE : 'Exchange',\n DEVICE_TYPE_PHONE: 'phone',\n TABLET : 'tablet'\n };\n\n MOCKS.facadeApiFactory = {\n getRequest : function() { var defer = $q.defer(); defer.resolve(); return defer.promise; },\n postRequest : sinon.stub(),\n getRequestWithQueryOptions : sinon.stub()\n };\n MOCKS.returnFormDataService = {\n createCart : sinon.stub()\n };\n\n MOCKS.returnExchangeService ={\n getFromSession : sinon.stub(),\n isAllEnabled : function(data){\n return true;\n },\n setInSession : sinon.stub()\n };\n MOCKS.returnExchangeChangeService ={\n persistState : function(data){\n return data;\n },\n restoreCheck : function(data){\n return data;\n },\n restoreApprovedItems : function(data){\n return data;\n },\n restoreAssessedItems : function(data){\n return data;\n },\n restoreReturnExchangeCheck : function(data){\n return data;\n }\n };\n MOCKS.returnExchangeHelperService ={\n checkItems : function(data){\n return data;\n },\n populateParentId : function(data){\n return data;\n },\n getWarrantyStatus : sinon.stub(),\n setGrandCentralIneligibilityResultFlag : sinon.stub(),\n getResponseData : sinon.stub()\n };\n MOCKS.ENV = {\n 'apigeeRoot': 'http://rebelliondev-dev01.apigee.net/'\n };\n MOCKS.SessionService = {\n data : {'authlogindata' : {'customerId' : '12345', 'accountId' : '123123' }},\n get : function(key) {\n return this.data[key];\n }\n };\n MOCKS.FACADE_API_ENDPOINTS={\n API_347_getPrintReceipt: 'v1/utility/printReceipt?orderId={orderId}'\n };\n MOCKS.ChannelConfigService = {\n channel : 'Retail',\n setDefaults : sinon.stub()\n };\n MOCKS.commonUtils = {\n nullable : sinon.stub()\n };\n MOCKS.SOFTGOODS_CONSTANTS ={\n REQUEST_TYPE_RETURN_EXCHANGE : 'returnExchange'\n };\n MOCKS.cartService = {\n getCartRequest : function() { var defer = $q.defer(); defer.resolve(); return defer.promise; },\n postCartDetails : sinon.stub\n };\n\n\n}",
"function chaiSupportChainPromise(chai, utils){\n function copyChainPromise(promise, assertion){\n let protoPromise = Object.getPrototypeOf(promise);\n let protoNames = Object.getOwnPropertyNames(protoPromise);\n let protoAssertion = Object.getPrototypeOf(assertion);\n protoNames.forEach(function(protoName){\n if(protoName !== 'constructor' && !protoAssertion[protoName]){\n assertion[protoName] = promise[protoName].bind(promise);\n }\n });\n }\n function doAsserterAsync(asserter, assertion, args){\n let self = utils.flag(assertion, \"object\");\n if(self && self.then && typeof self.then === \"function\"){\n let promise = self.then(function(value){\n assertion._obj = value;\n asserter.apply(assertion, args);\n return value;\n }, function(error){\n assertion._obj = new Error(error);\n asserter.apply(assertion, args);\n });\n copyChainPromise(promise, assertion);\n }\n else{\n return asserter.apply(assertion, args);\n }\n }\n let Assertion = chai.Assertion;\n let propertyNames = Object.getOwnPropertyNames(Assertion.prototype);\n\n let propertyDescs = {};\n propertyNames.forEach(function (name) {\n propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name);\n });\n\n let methodNames = propertyNames.filter(function (name) {\n return name !== \"assert\" && typeof propertyDescs[name].value === \"function\";\n });\n\n methodNames.forEach(function (methodName) {\n Assertion.overwriteMethod(methodName, function (originalMethod) {\n return function () {\n doAsserterAsync(originalMethod, this, arguments);\n };\n });\n });\n\n let getterNames = propertyNames.filter(function (name) {\n return name !== \"_obj\" && typeof propertyDescs[name].get === \"function\";\n });\n\n getterNames.forEach(function (getterName) {\n let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName);\n if (isChainableMethod) {\n Assertion.overwriteChainableMethod(\n getterName,\n function (originalMethod) {\n return function() {\n doAsserterAsync(originalMethod, this, arguments);\n };\n },\n function (originalGetter) {\n return function() {\n doAsserterAsync(originalGetter, this);\n };\n }\n );\n } else {\n Assertion.overwriteProperty(getterName, function (originalGetter) {\n return function () {\n doAsserterAsync(originalGetter, this);\n };\n });\n }\n });\n}",
"getTiers(){\n this.isLoading = true;\n \n this.handlePromise( getTiers() );\n }",
"function fetchMocking (fetchMockResponses) {\n window.origFetch = window.fetch.bind(window)\n window.fetch = async (...args) => {\n const url = args[0]\n if (url === 'https://ethgasstation.info/json/ethgasAPI.json') {\n return { json: async () => clone(fetchMockResponses.ethGasBasic) }\n } else if (url === 'https://ethgasstation.info/json/predictTable.json') {\n return {\n json: async () => clone(fetchMockResponses.ethGasPredictTable),\n }\n } else if (url.match(/chromeextensionmm/)) {\n return { json: async () => clone(fetchMockResponses.metametrics) }\n }\n return window.origFetch(...args)\n }\n if (window.chrome && window.chrome.webRequest) {\n window.chrome.webRequest.onBeforeRequest.addListener(\n cancelInfuraRequest,\n { urls: ['https://*.infura.io/*'] },\n ['blocking']\n )\n }\n function cancelInfuraRequest (requestDetails) {\n console.log(`fetchMocking - Canceling request: \"${requestDetails.url}\"`)\n return { cancel: true }\n }\n function clone (obj) {\n return JSON.parse(JSON.stringify(obj))\n }\n }",
"static getList() {\n return new Promise(resolve => {\n setTimeout(() => {\n // build some dummy traders list\n let traders = [];\n for (let x = 1; x <= 15; x++) {\n //mapping trader to a desk id.\n let deskid = x % 5 + 1;\n\n traders.push(\n new Trader(\n x,\n 'Trader ' + x,\n deskid,\n Utils.getRandomIntInclusive(5, 20) * 100));\n }\n resolve(traders);\n }, 1000);\n });\n }",
"function promiseGetBeers() {\n return __awaiter(this, void 0, void 0, function* () {\n let p;\n if (listaBeers) {\n p = Promise.resolve(listaBeers);\n }\n else {\n //obtener la lista y crear cache\n p = punkAPI.getBeers()\n .then((beers) => {\n listaBeers = beers;\n return listaBeers;\n })\n .catch((error) => {\n console.log(error);\n throw error;\n });\n }\n return p;\n });\n}",
"getTracers() {\n\t\t/* Create the HTTP GET request to the /tracers API endpoint. */\n\t\tvar req = new XMLHttpRequest();\n\t\treq.open(\"GET\", \"http://localhost:8081/tracers\", true);\n\t\treq.setRequestHeader(\"Hoot\", \"!\");\n\t\treq.onreadystatechange = this.setTracers;\n\t\treq.send();\n\t}",
"function getMockDependencies() {\n MOCKS.returnExchangeHelperService = {\n imeiParse : sinon.stub()\n };\n MOCKS.RETURN_EXCHANGE_CONSTS ={\n RETURN_REASON : 'return',\n EXCHANGE_REASON: 'exchange',\n SELECTED_ITEM : 'selectedItem',\n ITEM_TYPE_BATTERY : 'Battery',\n ITEM_TYPE_CHARGER : 'Charger',\n FORMAT_MSISDN : 'formatmsisdn',\n CONDITION_YES : 'YES',\n CONDITION_No : 'NO',\n ASSESS_ITEM : 'AssessItem',\n SELECT_REASON : 'SelectReason',\n RUN_DIAGNOSTIC: 'RunDiagnostic',\n };\n MOCKS.facadeApiFactory = {\n getRequest : function() { var defer = $q.defer(); \n defer.resolve(\n {\n \"success\" : true,\n \"diagnosticResult\": true\n }); \n return defer.promise; }\n };\n MOCKS.FACADE_API_ENDPOINTS={\n API_232_getOrderDetails : 'v1/orders/{orderId}',\n API_326_getAdjustmentReasons: 'v1/reference-list/reasons?type={type}',\n API_434_getQuickCode: 'v1/devices/validations?quickcode={quickcode}'\n };\n \n MOCKS.returnExchangeService={\n getFromSession : sinon.stub()\n };\n MOCKS.returnExchangeFormService={\n getReason : sinon.stub(),\n validateImeiNo : sinon.stub(),\n imeiUnParsed : sinon.stub(),\n setImeiValidFlag : function(){\n return true;\n }\n };\n MOCKS.TEXT_CONSTANTS={\n PHONE_MAKE_APPLE :'Apple'\n };\n MOCKS.commonUtils = {\n nullable :sinon.stub()\n };\n\n MOCKS.returnFormService = {\n getCurrentItemFlags : sinon.stub()\n };\n\n}",
"function getTrailer(movie){\n var deferred = jQuery.Deferred();\n theMovieDb.movies.getTrailers({\"id\": movie.id }, function(data){\n var result = JSON.parse(data);\n if(result.youtube.length > 0) {\n var trailerLink = 'https: //www.youtube.com/watch?v=' + result.youtube[0].source;\n movie.trailerLink = trailerLink;\n }\n deferred.resolve(movie);\n }, function(error){\n deferred.reject(error);\n });\n return deferred;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
called when a student presses the submit button on the home page if input was given, create the questions popup, otherwise display error | function submitQuestion() {
var input = document.getElementById("questionInput").value || null;
var error = document.getElementById("questionError");
if (input) {
error.style.display = "none"; //hide error message
createPopup();
//the button to proceed with posting the question
var continueB = popupVerify();
continueB.onclick = function() {
loadingIMG("whitePrompt");
//process the question with processQ.php
var data = "question=" + input;
XMLRequest("processQ.php", data, function(xhttp) {
if (xhttp.responseText) {
popupResult(true);
}
else {
popupResult(false);
}
});
}
}
else {
error.innerHTML = "Please enter a question first.<br />";
error.style.display = "inline"; //show error message
}
} | [
"function changeToCreateQuestions () {\n const basicInformationQuizz = savingBasicQuizzInformation();\n let numCharOk;\n let urlOk;\n let nQuestionsOk;\n let nLevelsOk;\n \n if (basicInformationQuizz.title.length >= 20 && basicInformationQuizz.title.length <= 65) {\n numCharOk = true;\n }\n if (isValidHttpUrl(basicInformationQuizz.image)) {\n urlOk = true; \n }\n if (basicInformationQuizz.nQuestions >=3) {\n nQuestionsOk = true;\n }\n if (basicInformationQuizz.nLevels >=2) {\n nLevelsOk = true;\n }\n if (numCharOk && urlOk && nQuestionsOk && nLevelsOk) {\n asksAboutQuizzDisplay();\n displayMyQuestionsBox(basicInformationQuizz.nQuestions)\n }else {alert(\"Preencha os campos com informacoes validas\")}\n}",
"function submitQuestion(){\n\n\n}",
"function validateForm() {\r\n var questionName = document.getElementById(\"questionTitle\");\r\n var questionType = document.getElementById(\"questionTypeSelect\");\r\n var submitQuestionButton = document.getElementById(\"submitQuestionButton\");\r\n var questionModal = document.getElementById(\"newQuestionModal\");\r\n if(questionName.value == \"\" || questionType.value == \"default\") {\r\n alert(\"Please complete the form\");\r\n } else { // call add card function and clear modal if form is valid\r\n hideModal();\r\n fillQuestionData();\r\n addQuestionCard();\r\n clearModal();\r\n }\r\n}",
"function submitQuiz()\n{\n\t//Validation checks\n\tvar c1 = answerCheck();\n\tif(c1 == true)\n\t{\n\t\tswal(\"Fill in all answers.\");\n\t}\n\t\n\tif(c1 == false)\n\t{\n\t\t//Loop through student's answers and set up JSON format for each question/answer\n\t\tvar answers = [];\n\t\tfor(var i = 0; i < qtype.length; i++)\n\t\t{\n\t\t\tvar index = i+1;\n\t\t\tif(qtype[i] === \"mc\")\n\t\t\t{\n\t\t\t\tvar temp = $(\"#MCQ\" + index.toString()).clone(true);\n\t\t\t\tvar a = {\n\t\t\t\t\tqnum: index,\n\t\t\t\t\tanswer: temp.find(\"input[name=MC\" + index.toString() + \"]:checked\").val()\n\t\t\t\t};\n\t\t\t\tanswers.push(a);\n\t\t\t}\n\t\t\tif(qtype[i] === \"tf\")\n\t\t\t{\n\t\t\t\tvar temp = $(\"#TFQ\" + index.toString()).clone(true);\n\t\t\t\tvar a = {\n\t\t\t\t\tqnum: index,\n\t\t\t\t\tanswer: temp.find(\"input[name=TFC\" + index.toString() + \"]:checked\").val()\n\t\t\t\t};\n\t\t\t\tanswers.push(a);\n\t\t\t}\n\t\t\tif(qtype[i] === \"sa\")\n\t\t\t{\n\t\t\t\tvar temp = $(\"#SAQ\" + index.toString()).clone(true);\n\t\t\t\t//var answer = temp.find(\"input[name=TFC\" + index.toString() + \"]:checked\").val()\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t//Send the answers to be saved into the database\n\t\t$.ajax({\n\t\t\t//async: true, \n\t\t\ttype: 'POST',\n\t\t\turl: \"quizload.php\",\n\t\t\tdataType: 'html',\n\t\t\tdata: {answers: answers},\n\t\t\n\t\t\tsuccess: function(result){\n\t\t\t\t//alert(result);\n\t\t\t\t//Sends answers if student accepts the submission\n\t\t\t\tswal({\n\t\t\t\t\ttitle: \"Quiz\",\n\t\t\t\t\ttext: \"You have successfully completed the quiz.\",\n\t\t\t\t\tconfirmButtonText: \"Ok\",\n\t\t\t\t\tcloseOnConfirm: true},\n\t\t\t\t\tfunction(isConfirm){\n\t\t\t\t\t\tif(isConfirm)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//Navigates student back to concept view\n\t\t\t\t\t\t\twindow.location = '../concept_view/concept_view.html';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\treturn false;\n}",
"function submitInitialsHS(event) {\n event.preventDefault();\n var initials = document.querySelector(\"#enterInitials-text\").value.trim();\n if(initials) {\n setData(initials,timeScore);\n window.location.href = \"./viewScore.html\";\n \n }\n\n\n}",
"function addQuestions(){\r\n if (document.getElementById('exerciseTitle').value == \"\") { //Validation incase no exercise title is entered.\r\n displayInfo(\"Please enter a exercise title.\");\r\n } else if (document.getElementById('question').value == \"\") { // Validation incase no question is entered\r\n displayInfo(\"Please enter a question.\");\r\n } else if (document.getElementById('answer').value == \"\") { // Validation incase no answer is entered\r\n displayInfo(\"Please enter an answer.\");\r\n } else if(!/^[a-zA-Z\\u00C0-\\u017F/\\s]*$/g.test(document.getElementById('answer').value)){ //Validation incase any characters besides spaces and latin alphabet are entered\r\n\t\t\t displayInfo(\"Please remove any special characters.\");\r\n\t\t }else {\r\n\t\t\t //Pushing the user form inputs to the array\r\n categories.push([document.getElementById('answer').value]);\r\n hints.push([document.getElementById('hintTextArea').value]);\r\n feedbacks.push([document.getElementById('feedback').value]);\r\n questions.push([document.getElementById('question').value]);\r\n numberOfQuestions++; //Incrementing number of questions\r\n document.getElementById('questionNumber').value = numberOfQuestions + 1; //updating DOM\r\n document.getElementById('maxQuestion').value = numberOfQuestions + 1; //updating DOM\r\n clearForm();//Clearing the form\r\n current += 1; //adding one to the current question\r\n displayInfo(\"Question \" + numberOfQuestions + \" added to the exercise.\"); //Notification displaying that question has been added.*/\r\n }\r\n }",
"function prepareQuestionDialog() {\n if ($(\"#question-graded\").prop(\"checked\") && !isFinite(safeParseInt($(\"#question-max\").val()))) {\n $('#question-error').text(intError(safeParseInt($(\"#question-max\").val())));\n $('#question-error-container').show();\n return false;\n } else if ($(\"#question-graded\").prop(\"checked\") && $(\"#question-gradebook-title\").val() === '') {\n $('#question-error').text(msg(\"simplepage.gbname-expected\"));\n $('#question-error-container').show();\n return false;\n } else if ($(\"#question-text-area-evolved\\\\:\\\\:input\").val() === '') {\n $('#question-error').text(msg(\"simplepage.missing-question-text\"));\n $('#question-error-container').show();\n } else if ($(\"#multipleChoiceSelect\").prop(\"checked\") &&\n $(\".question-multiplechoice-answer\").filter(function (index){return $(this).val() !== '';}).length < 2) {\n $('#question-error').text(msg(\"simplepage.question-need-2\"));\n $('#question-error-container').show();\n return false;\n } else {\n $('#question-error-container').hide();\n }\n\n updateMultipleChoiceAnswers();\n updateShortanswers();\n\n $(\"input[name='\" + $(\"#activeQuestion\").val() + \"'\").val($(\"#question-text-area-evolved\\\\:\\\\:input\").val());\n SPNR.disableControlsAndSpin( this, null );\n\n // RSF bugs out if we don't undisable these before submitting\n $(\"#multipleChoiceSelect\").prop(\"disabled\", false);\n $(\"#shortanswerSelect\").prop(\"disabled\", false);\n return true;\n}",
"function createQAForm() {\n updateNewCounter();\n $('#questions').empty();\n $('#questions').html(`<form>\n <section>\n <h3 class =\"questionBlock\">${STORE[questionCount].question}</h3>\n ${renderAnswers(STORE[questionCount].answer)}\n </section>\n </form>\n <button type=\"button\" class=\"redButton\" id=\"submitButton\">Submit</button>`);\n checkAnswer();\n}",
"function studentValidationForm() {\n\n\n// 4 variables that help keep track of the content within the dropdown lists and the comment box. Used in the \"you have joined a lecture alert\" - Chris\n var studyprogram = document.getElementById(\"category\").value;\n var Course = document.getElementById(\"subcategory\").value;\n var lecture = document.getElementById(\"sub_subcategory\").value;\n var comment = document.getElementById(\"comment\").value;\n\n\n// Variable form_valid is set to true as a standard. When something is not selected the form_valid is set to false - Chris\n var form_valid = true;\n\n\n// New variable for validation message. It is empty now since we dont know what the user has done wrong yet - Chris\n var validation_message = \"\";\n\n\n// This validation form works by first defining a new variable with the content of the dropdown list - Chris\n// Here we simply say that if the content of the dropdown list is null or empty (e.g. not selected) the validation form (form_valid) is set to false and a new validation message is added - Chris\n// This is done for all 3 of the dropdown lists - Chris\n var studyprogram1 = document.getElementById(\"category\").value;\n if (studyprogram1 == null || studyprogram1 == \"\") {\n form_valid = false;\n validation_message += \"A studyprogram must be selected \\n\";\n }\n var course1 = document.getElementById(\"subcategory\").value;\n if (course1 == null || course1 == \"\") {\n form_valid = false;\n validation_message += \"A course must be selected \\n\";\n }\n var lecture1 = document.getElementById(\"sub_subcategory\").value;\n if (lecture1 == null || lecture1 == \"\") {\n form_valid = false;\n validation_message += \"A lecture must be selected \\n\";\n }\n\n\n// \"If form_valid\" triggers if it is true. Form_valid default setting is true therefore it will happen if none of the 3 if statements above are triggered - Chris\n// Alert that confirms which lecture you have joined - Chris\n if (form_valid) {\n alert(\"You have joined a lecture\"\n + \"\\nStudy Program: \" + studyprogram\n + \"\\nCourse: \" + Course\n + \"\\nLecture: \" + lecture\n + \"\\nAdditional comment:\" + \" \" + comment);\n }\n\n\n// If the form_valid is false it will trigger an alert with the validation message - Chris\n else {\n alert(validation_message);\n }\n return form_valid;\n }",
"function submitSingleAnswer() {\n \"use strict\";\n var question = document.getElementById(\"singleAnswerQuestion\").value;\n var answer = document.getElementById(\"singleAnswerAnswer\").value;\n if ((question.length) > 0 && (answer.length) > 0) {\n var variables = \"type=singleAnswerQuestion&question=\" + question + \"&answer=\" + answer + \"&languageId=\" + getLanguage() + \"&difficulty=\" + getDifficulty();\n submitValidated(variables);\n } else {\n //form did not pass validation, cannot submit empty or null values\n document.getElementById(\"errorcodeQuestions\").innerHTML = \"Invalid Input.\";\n }\n}",
"function handle_question_submit() {\n\tif (can_ask) {\n\t\tif (hand_up)\n\t\t\tput_hand_down();\n\t\telse\n\t\t\tadd_question();\n\t}\n}",
"function submitQuestion() {\n var text = document.getElementById(\"questionArea\").value;\n\n putQuestion(\"Eric Higgins\", new Date(), text);\n}",
"function sub(){\r\n try{\r\n if(addMsg.checked && userMsg.value==\"\"){//if selected but no message given\r\n throw \"enter a message or unchecked this selection\"//throw error advising user\r\n }\r\n asnsweErr[4].innerHTML = \"\";//clears error message on scene reload if valid\r\n quest(7);//if valid submit (nothing to submit to, instead display success scene)\r\n }catch(err){//catches error given\r\n asnsweErr[4].innerHTML = err;//displays error to user\r\n }\r\n}",
"function addQuestions() {\n createQuestions(\"What is the incantation for unlocking a door?\", \"Wingardium Leviosa\",\n \"Sectumsempra\",\n \"Silencio\",\n \"Alohomora\");\n createQuestions(\"When affected by a Dementor what should one eat?\", \"Broccoli\",\n \"Bread\",\n \"Soup\",\n \"Chocolate\");\n createQuestions(\"What is the difference between a Werewolf and an Animagus?\",\n \"Nothing they are synonyms\",\n \"A Werewolf chooses when to transform and an Animagus does not\",\n \"A Werewolf is a version of an Animagus, they just chose a wolf\",\n \"A Werewolf is cursed and must transform, an Animagus chooses to turn into an animal\");\n createQuestions(\"If one were to drink a Unicorn’s blood what would happen?\",\n \"They would get a wish\",\n \"They would die instantly\",\n \"They would turn into a Unicorn\",\n \"They would be kept alive indefinitely but would live a cursed life\");\n createQuestions(\"Which one is an Unforgivable Curse?\",\n \"Reducto\",\n \"Stupefy\",\n \"Aguamenti\",\n \"Imperio\");\n createQuestions(\"What cures most poisons?\",\n \"Dragon’s blood\",\n \"Pixie wings\",\n \"Polyjuice Potion\",\n \"A Bezoar\");\n createQuestions(\"What is the incantation to Disarm someone?\",\n \"Expecto Patronum\",\n \"Petrificus Totalus\",\n \"Serpensortia\",\n \"Expelliarmus\");\n createQuestions(\"How long does it take to brew a Polyjuice Potion?\",\n \"6 days\",\n \"3 hours\",\n \"1 year\",\n \"1 month\");\n createQuestions(\"What is a Horcrux?\",\n \"A type of currency\",\n \"A sword used to destroy unbreakable items\",\n \"A ball used in Quidditch\",\n \"A fragment of a soul hidden in an object\");\n createQuestions(\"What should one do first before approaching a Hippogriff?\",\n \"Wave\",\n \"Sing\",\n \"Clap\",\n \"Bow\");\n }",
"validateSave(question){\n \n if (question.questionText == \"\"){\n writeToErrorDiv(\"You have no question text\")\n return false;\n } \n\n if (question.answer1 == \"\"){\n writeToErrorDiv(\"You are missing an answer\")\n return false;\n } \n\n if (question.answer2 == \"\"){\n writeToErrorDiv(\"You are missing an answer\")\n return false;\n } \n\n if (question.answer3 == \"\"){\n writeToErrorDiv(\"You are missing an answer\")\n return false;\n } \n\n if (question.answer4 == \"\"){\n writeToErrorDiv(\"You are missing an answer\")\n return false;\n } \n \n return true;\n }",
"function submitAnswer() {\n $('.question-box').on('click', '#submit-button', function (event) {\n event.preventDefault();\n //$('.altBox').hide();\n //$('.response').show();\n let selectAns = $('input:checked').val();\n //let answer = selected.val();\n let correct = STORE[questionNumber].answer;\n if (!selectAns) {\n selectionRequired();\n } else if (selectAns === correct) {\n correctAnswer();\n nextQuestion();\n } else{\n wrongAnswer();\n nextQuestion();\n }\n });\n}",
"function generateQuiz() {\n\n // function showQuestions(questions, quizContainer) {\n // // we'll need a place to store the output and the answer choices\n // var output = [];\n // var answers;\n\n // // for each question...\n // for (var i = 0; i < questions.length; i++) {\n\n // // first reset the list of answers\n // answers = [];\n\n // // for each available answer...\n // for (letter in questions[i].answers) {\n\n // // ...add an html radio button\n // answers.push(\n // '<label>'\n // + '<input type=\"radio\" name=\"question' + i + '\" value=\"' + letter + '\">'\n // + letter + ': '\n // + questions[i].answers[letter]\n // + '</label>'\n // );\n // }\n\n // // add this question and its answers to the output\n // output.push(\n // '<div class=\"question\">' + questions[i].question + '</div>'\n // + '<div class=\"answers\">' + answers.join('') + '</div>'\n // );\n // }\n // // finally combine our output list into one string of html and put it on the page\n // .innerHTML = output.join('');\n // }\n // show questions right away\n // showQuestions(questions, quizContainer);\n // on submit, show results\n var startSection=document.getElementById('startScreen')\n startSection.classList.add(\"hidden\")\n var questionSection=document.getElementById('questions')\n questionSection.classList.remove(\"hidden\")\n document.getElementById('timer').innerHTML = time\n\n timer=setInterval(startTimer, 1000); \n showQuestions()\n}",
"function sendQuestion() {\n const question = document.getElementById('questionInput').value;\n const e = document.getElementById('skill_list');\n const skill_id = e.options[e.selectedIndex].getAttribute('values');\n const skillType = document.getElementById('skillType').value;\n const company = document.getElementById('company').value;\n if (question === \"\" || skill_id === \"\" || company === \"\") {\n alert('Please enter all the required fields');\n }\n props.saveQuestion({question, skill_id, company, skillType}, props.skills);\n }",
"function validateAnswerAndSetNextQuestion() {\n\t\tif ( answerProvided() ) {\n\t\t\tdisableNextQuestionButton(); // prevents user of clicking button/starting event again, until new question comes \n\t\t\tvalidateAnswers();\n\t\t\tgv.currentQuestion += 1;\n\n\t\t\tswordAnimationStart();\n\t\t\t//after 3 seconds show the next question or the final result\n\t\t\tsetTimeout(function() {\n\t\t\t\tif (gv.currentQuestion < gv.totalNumOfQuestions) {\n\t\t\t\t\tsetQuestion(gv.currentQuestion);\n\t\t\t\t\tenableNextQuestionButtonAgain(); \n\t\t \t} else {\n\t\t \t\tshowFinalResult();\n\t\t \t}\n\t\t \tswordAnimationFinish();\n\t \t}, 3000);\n\n\n\t\t} else {\n\t\t\t$('.quiz__answer-not-provided').show();\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
searchByProfessions : given an array of professions , this method tries to search it in the data store. param professionSearch : the array of values to search return itemId : the id of the first item found or item_not_found in other case. | searchByProfessions( professionSearch ) {
let itemId = this.ItemNotFound;
let list = this.state[this.townName];
for( let indx=0; indx<list.length; ++indx ) {
for( let indxProf=0; indxProf<list[indx].professions.length; ++indxProf ) {
if( list[indx].professions[indxProf].toLowerCase() === professionSearch.toLowerCase() ) {
itemId = list[indx].id;
break;
}
}
}
console.log('searchByProfessions :',itemId);
return itemId;
} | [
"function ItemsSearch(proc, callback) {\n\tvar tab=[];\n\t// loop on the procs list\n\tproc.forEach(function(p) {\n\t\t// for each proc we search info in mongodb\n\t\titemOneSearch(p,function(ret) {\n\t\t\ttab.push(ret);\n\t\t\t// return of the outcomes when it is fully filled\n\t\t\tif (tab.length == proc.length)\n\t\t\t\tcallback(tab);\n\t\t})\n\t})\n}",
"function pSearch(people, id){\n var i;\n for (i = 0; i < people.length; i++) {\n if (people[i].loginID == id) {\n return people[i];\n }\n }\n return 'NAP';\n}",
"getProfessions (conditions) {\n return new Promise((resolve, reject) => {\n\n conditions = conditions || {};\n\n try {\n let professions = Professions.find(conditions);\n let results = [];\n professions.forEach(function (profession) {\n results.push(profession);\n });\n\n resolve(results);\n }\n catch (error) {\n reject(error);\n }\n });\n }",
"function searchByOccupation(people) {\n let occupation = promptFor(\n \"Please enter person's Occupation - options below:\\n\" + \n \"'assistant' , 'architect', 'doctor' , 'landscaper' ,\" +\n \" 'nurse' , 'politician' , 'programmer' , 'student' ,\", chars);\n\n let foundPerson = people.filter(function (person) {\n if (person.occupation === occupation) {\n return true;\n } else {\n return false;\n }\n });\n\n return foundPerson;\n}",
"function findByProfession(profession, citySortOrder) {\n var cursor = users.find({profession: profession}, { sort: {city: citySortOrder}});\n return Q.ninvoke(cursor, 'toArray');\n }",
"function searchById(people){\n idSearch = promptFor(\"What is the ID number you searching for?\", autoValid);\n let foundPeople = people.filter(function(potentialMatch){\n if(potentialMatch.id == idSearch){\n return true;\n }\n else{\n return false;\n }\n \n })\n // TODO: find the person us\n return foundPeople;\n \n}",
"function getProfession(celebName){\n for (var i=0; i < name.length; i++){\n if (celebName == name[i]){\n return profession[i];\n }\n }\n}",
"function searchByOccupation(people){\n let occupationSearch = promptFor(\"What occupation does the person you are looking for do?\", autoValid);\n let foundPeople = people.filter(function(potentialMatch){\n if(potentialMatch.occupation == occupationSearch){\n return true;\n}\n else{\n return false;\n }\n })\n\n return foundPeople;\n}",
"function SearchEmployee(empid)\r\n{\r\n if (empid == undefined)\r\n {\r\n return undefined;\r\n }\r\n\r\n var result = null;\r\n for (var i = 0; i < employees.length; i++)\r\n {\r\n if (empid == employees[i].EmpId)\r\n {\r\n result = employees[i];\r\n break;\r\n }\r\n }\r\n return result;\r\n}",
"async function profession(req, res, next) {\r\n /*get gender_id in gender_type*/\r\n let gender_type = [req.body.gender_type, 3];\r\n /*find gender type and parent id in profession collection*/\r\n let profession = await db.Profession.find({gender_type: {$in : gender_type}, parent_id: req.body.parent_id});\r\n if (profession.length >0) {\r\n /*success responce*/\r\n res.status(200).json({\r\n status : 'success',\r\n message : 'Profession type list found',\r\n data : profession\r\n });\r\n } else {\r\n /*failed responce*/\r\n res.status(402).json({\r\n status : 'failed',\r\n message : 'Level type list not found'\r\n });\r\n }\r\n}",
"search_employee(code_emp){\n for(let nv of this.List_Employee){\n if(nv.code_employee === code_emp){\n return nv;\n breack;\n }\n }\n }",
"function searchByID(people) {\n let idNumber = promptFor(\"What is the person's ID number?\", integer);\n\n let foundPerson = people.filter(function (person) {\n if (person.id == idNumber) {\n return true;\n } else {\n return false;\n }\n });\n return foundPerson;\n}",
"searchSkill(sqlControl, index, experience) {\n\t\tvar query = \"SELECT e.ExpertID, e.FirstName, e.LastName, e.ProfileEmail, e.GithubLink, e.About FROM Experts e \"\n\t\tquery += \"INNER JOIN ExpertSkills es ON es.FK_ExpertID = e.ExpertID \";\n\t\tquery += \"INNER JOIN Skills s ON es.FK_SkillID = s.SkillID \";\n\t\tquery += \"WHERE s.SkillID = ? AND es.Experience >= ? \";\n\t\tquery += \"GROUP BY e.ExpertID ORDER BY e.LastName DESC\";\n\t\tvar insert = [index,experience];\n\t\tsqlControl.setQuery(query, insert);\n\t\t\n}",
"searchByAge( ageToSearch ) {\n let itemId = this.ItemNotFound;\n let list = this.state[this.townName];\n \n for( let indx=0; indx<list.length; ++indx ) {\n if( list[indx].age.toString() === ageToSearch ) {\n itemId = list[indx].id;\n break;\n }\n }\n console.log('searchByAge :',itemId);\n \n return itemId;\n }",
"async function hireProfessional(req, res, next) {\r\n /*If no parameter get validation message show*/\r\n if ((typeof req.body.level !='undefined' && req.body.level) || (typeof req.body.city !='undefined' && req.body.city) || (typeof req.body.profession !='undefined' && req.body.profession)) {\r\n let condition={};\r\n /*condition for search parameters according to requiement*/\r\n if (typeof req.body.level !='undefined' && req.body.level) {\r\n condition.level = req.body.level\r\n }\r\n condition.role_type = req.body.search;\r\n\r\n if (typeof req.body.city !='undefined' && req.body.city) {\r\n condition.city = { $in: req.body.city }\r\n }\r\n if (typeof req.body.profession !='undefined ' && req.body.profession) {\r\n condition.profession = { $in: req.body.profession }\r\n }\r\n /*find professional users in professional collection according to level, profession, and city*/\r\n var search = await db.User.find(condition);\r\n if (search) {\r\n /*success responce*/\r\n res.status(200).json({\r\n status : 'success',\r\n message : 'Professional search list found',\r\n data : search\r\n });\r\n } else {\r\n /*failed responce*/\r\n res.status(409).json({\r\n status : 'failed',\r\n message : 'Professional search list found'\r\n });\r\n }\r\n } else {\r\n /*failed responce*/\r\n res.status(409).json({\r\n status : 'failed',\r\n message : \"Please send at-least one parameter\",\r\n });\r\n }\r\n}",
"function searchBooks(books, bookIdsFound) {\n // loops through books\n for(let i = 0; i < books.length; i++) {\n // loops through booksIds array\n for(let j = 0; j < bookIdsFound.length; j++){\n // if there's any matches\n if(books[i].id === bookIdsFound[j]) {\n // print information from the book found\n console.log(books[i]);\n }\n }\n }\n}",
"function searchEmployees(search) {\r\n var searchFields = new Array('phone','mobilePhone','officePhone','homePhone');\r\n\r\n var resultColumns = new Array('salutation','firstName','lastName','entityId');\r\n\r\n search.doSearch('employee',searchFields,resultColumns,writeEmployeeResult);\r\n}",
"function searchFruit(fruitsObj, fruitName)\n{\n return fruitsObj.filter(x => x.name === fruitName);\n}",
"function search(searchValue) {\n searchValue = searchValue.toLowerCase();\n console.log(searchValue);\n\n let filteredFamilyMembers = [];\n\n for (let familyMember of _familyMembers) {\n let name = familyMember.name.toLowerCase();\n if (name.includes(searchValue.toLowerCase())) {\n filteredFamilyMembers.push(familyMember);\n }\n }\n appendPersons(filteredFamilyMembers);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the log handlers to the default ones. | resetLogHandlers() {
this[logHandlersSymbol] = [this.defaultLogHandler];
this.initializeLogHandlers();
} | [
"initializeLogHandlers() {\n this.removeAllListeners();\n this[logHandlersSymbol].forEach((handler) => {\n this.on('log', handler);\n });\n }",
"function resetLogger() {\n globalLogManager = new DefaultLogManager();\n globalLogLevel = models.LogLevel.NOTSET;\n }",
"function resetLogger() {\n Util.Logger.enable();\n Util.Logger.removeAllHooks();\n Util.Logger.removeAllFilters();\n}",
"function setDefaultLogFunctions() {\n var _this2 = this;\n\n (0, _lodash2.default)(['trace', 'debug', 'info', 'warning', 'error']).forEach(function (name, index) {\n addLogLevel.call(_this2, index, name);\n });\n this.setLevel('debug');\n}",
"function setDefaultLogFunctions() {\n _(['trace', 'debug', 'info', 'warning', 'error']).forEach((name, index) => {\n addLogLevel.call(this, index, name);\n });\n this.setLevel('debug');\n}",
"reset() {\n this.close();\n this._handlers = {};\n }",
"function setAllDefaultHandlers() {\n\t\tsetGo();\n\t\tsetInspect();\n\t\tsetInventory();\n\t\tsetUse();\n\t\tsetGive();\n\t\tsetLookAt();\n\t\tsetTalkTo();\n\t\tsetOpen();\n\t\tsetClose();\n\t\tsetPush();\n\t\tsetPull();\n\t\tsetPickUp();\n\t}",
"function LoggerSettings() {\n NullHandler.call(this);\n\n this._handlers = [];\n}",
"_setDefaultMessageHandlers() {\n for (let key in defaultMessageHandlers) {\n this._setMessageHandler(key, defaultMessageHandlers[key], true);\n }\n }",
"function setLevels() { // request logger must have same methods as log\n\tfor (var level in log.levels) { // define functions if available in log\n\t\tif (log[level]){\n\t\t\tLogger[level] = (function (level) {\n\t\t\t\treturn function (msg, meta) {\n\t\t\t\t\tvar meta = meta || msg || {};\n\t\t\t\t\tif ('string' === typeof meta) meta = {};\n\t\t\t\t\tif ('string' !== typeof msg) msg = '' + msg;\n\t\t\t\t\tlog[level](msg, x(this.extend(meta),{name:this.name}));\n\t\t\t\t};\n\t\t\t})(level);\n\t\t}\n\t\telse {\n\t\t\tif (Logger[level]) {\n\t\t\t\tdelete Logger[level];\n\t\t\t}\n\t\t}\n\t}\n}",
"clearEventHandlers() {\n for (const [eventName, listeners] of this.eventHandlers) {\n listeners.forEach(listener => {\n this.bot.off(eventName, listener);\n });\n }\n this.eventHandlers.clear();\n }",
"function resetErrorHandler(){\n\terrorHandler = originalErrorHandler;\n}",
"function unsetRootLogger() {\n if (exports.logger !== undefined) {\n console.log = originalConsoleLog;\n console.info = originalConsoleInfo;\n console.warn = originalConsoleWarn;\n console.error = originalConsoleError;\n exports.logger = undefined;\n }\n}",
"function clearLogs () {\n log = [];\n}",
"function unsetRootLogger() {\n if (exports.logger !== undefined) {\n logger_protocol_1.ConsoleLogger.reset();\n exports.logger = undefined;\n }\n}",
"function defaultLoggers() {\n return [\n {\n name: /.*/,\n level: 'error',\n target: defaultImplementation(),\n }\n ];\n}",
"clearAll() {\n for (channel in this._handlers) {\n this.off(channel);\n }\n }",
"function unsubscribeAll() {\n uninstallGlobalHandler();\n handlers = [];\n }",
"function unsubscribeAll() {\n uninstallGlobalHandler();\n handlers = [];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fixes the position of adjacent tiles after a resize event ui > the ui element from the resize event TODO: if the n handle of the top element is pulled, move it back. same for w of left, s of bottom, e of right | function resizeFixup(ui){
var resizeId = ui.element.attr('id');
//which direction did it resize?
if(resizeDir == 'n'){
var diff = virtical_location(ui.originalPosition.top, 0) - virtical_location(ui.helper.position().top, 0);
if(diff <= 0 && parseInt(ui.element.attr('row')) <= 1){
//the tile is at the top
return;
}
var virt_adj = new Set();
for (var i = resizeStartX; i < resizeStartX + resizeStartSizeX; i++) {
if(board[i-1][resizeStartY-2].tile != resizeId){
virt_adj.add(board[i-1][resizeStartY-2].tile);
}
};
//did it go up or down?
$(ui.element).attr({
'row':parseInt(ui.element.attr('row'))-diff,
'sizey':parseInt(ui.element.attr('sizey'))+diff
});
update_board(resizeId);
var moved = new Set();
moved.add(resizeId);
if(diff < 0){
//it moved down
virt_adj.forEach(function(item){
recursiveResize(moved, 'down', diff, 's', item);
});
}
else if(diff > 0){
//it moved up
virt_adj.forEach(function(item){
recursiveResize(moved, 'up', diff, 's', item);
});
}
}
if(resizeDir == 's'){
var diff = virtical_location(ui.originalPosition.top, ui.originalSize.height) - virtical_location(ui.helper.position().top, ui.helper.height());
if(parseInt(ui.element.attr('row'))+parseInt(ui.element.attr('sizey'))-1 == maxHeight ){
//the tile is at the bottom
return;
}
var virt_adj = new Set();
for (var i = resizeStartX; i < resizeStartX + resizeStartSizeX; i++) {
if(board[i-1][resizeStartY + resizeStartSizeY - 1].tile != resizeId){
virt_adj.add(board[i-1][resizeStartY + resizeStartSizeY - 1].tile);
}
};
//did it go up or down?
$(ui.element).attr({
'sizey':parseInt(ui.element.attr('sizey'))-diff
});
update_board(resizeId);
var moved = new Set();
moved.add(resizeId);
if( diff < 0){
//it moved down
virt_adj.forEach(function(item){
recursiveResize(moved, 'down', diff, 'n', item);
});
}
else if(diff > 0){
//it moved up
virt_adj.forEach(function(item){
recursiveResize(moved, 'up', diff, 'n', item);
});
}
}
if(resizeDir == 'e'){
if(parseInt(ui.element.attr('col'))+parseInt(ui.element.attr('sizex'))-1 == maxCols){
//the element is on the right of the board
return;
}
var horz_adj = new Set();
for (var i = resizeStartY; i < resizeStartY + resizeStartSizeY; i++) {
if(board[resizeStartX + resizeStartSizeX - 1][i-1].tile != resizeId){
horz_adj.add(board[resizeStartX + resizeStartSizeX - 1][i-1].tile);
}
};
//did it go right or left?
var diff = horizontal_location(ui.originalPosition.left, ui.originalSize.width) - horizontal_location(ui.helper.position().left, ui.helper.width());
ui.element.attr({
'sizex':parseInt(ui.element.attr('sizex'))-diff
});
update_board(resizeId);
var moved = new Set();
moved.add(resizeId);
if( diff < 0){
//it moved right
horz_adj.forEach(function(item){
recursiveResize(moved, 'right', diff, 'w', item);
});
}
else if(diff > 0){
//it moved left
horz_adj.forEach(function(item){
recursiveResize(moved, 'left', diff, 'w', item);
});
}
}
if(resizeDir == 'w'){
if(parseInt(ui.element.attr('col')) == 1){
//the element is on the left side of the board
return;
}
var horz_adj = new Set();
for (var i = resizeStartY; i < resizeStartY + resizeStartSizeY; i++) {
if(board[resizeStartX - 2][i-1].tile != resizeId){
horz_adj.add(board[resizeStartX - 2][i-1].tile);
}
};
//did it go right or left?
var diff = horizontal_location(ui.originalPosition.left,0) - horizontal_location(ui.helper.position().left, 0);
ui.element.attr({
'col':parseInt(ui.element.attr('col'))-diff,
'sizex':parseInt(ui.element.attr('sizex'))+diff
});
update_board(resizeId);
var moved = new Set();
moved.add(resizeId);
if( diff < 0){
//it moved right
horz_adj.forEach(function(item){
recursiveResize(moved, 'right', diff, 'e', item);
});
}
else if(diff > 0){
//it moved left
horz_adj.forEach(function(item){
recursiveResize(moved, 'left', diff, 'e', item);
});
}
}
} | [
"function positionFixup(){\n\t\tfor (var i = tiles.length - 1; i >= 0; i--) {\n\t\t\tvar layout = returnBalanced(maxCols, maxHeight);\n\t\t\tvar t = $('#'+tiles[i]);\n\t\t\tt.attr({\n\t\t\t\t'row': layout[tiles.length-1][i].row(maxHeight),\n\t\t\t\t'col': layout[tiles.length-1][i].col(maxCols),\n\t\t\t\t'sizex': layout[tiles.length-1][i].sizex(maxCols),\n\t\t\t\t'sizey': layout[tiles.length-1][i].sizey(maxHeight)\n\t\t\t});\n\t\t\tvar tile_offset = offset_from_location(parseInt(t.attr('row')), parseInt(t.attr('col')));\n\t\t\tt.css({\n\t\t\t\t\"top\": tile_offset.top,\n\t\t\t\t\"left\":tile_offset.left,\n\t\t\t\t\"width\":t.attr('sizex')*tileWidth,\n\t\t\t\t\"height\":t.attr('sizey')*tileHeight});\n\t\t\tupdate_board(tiles[i]);\n\t\t};\n\t}",
"function recursiveResize(moved, dir, diff, side, id){\n\t \tvar curWindow = $('#'+id);\n\t \tvar x = parseInt(curWindow.attr('col'));\n\t \tvar y = parseInt(curWindow.attr('row'));\n\t \tvar sizex = parseInt(curWindow.attr('sizex'));\n\t \tvar sizey = parseInt(curWindow.attr('sizey'));\n\t \tvar toAdd = true;\n\t \tvar adj = new Array();\n\t \tif(dir == 'up'){\n\t \t\tif(side == 'n'){\n\t \t\t\t//var adj = new Set();\n\t \t\t\tfor (var i = x; i < x + sizex; i++) {\n\t \t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[i-1][y - 2].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[i-1][y - 2].tile);\n\t \t\t\t\t}\n\t \t\t\t};\n\t \t\t\tvar helperReturn = adjHelper(adj, moved);\n\t \t\t\tvar startY = curWindow.offset().top;\n\t \t\t\tcurWindow.attr({\n\t \t\t\t\t'row':y-diff,\n\t \t\t\t\t'sizey':sizey+diff\n\t \t\t\t});\n\t \t\t\tcurWindow.css({\n\t \t\t\t\t//'top':(y-diff)*tileHeight + $('.navbar').height() - 1,\n\t \t\t\t\t'top': startY - (diff*tileHeight), \n\t \t\t\t\t'height':(sizey+diff)*tileHeight\n\t \t\t\t});\n\t \t\t\tupdate_board(id);\n\t \t\t\tmoved.add(id);\n\t \t\t\tremoveHelper(curWindow);\n\t \t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, done resizing\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizing\n\t\t\t\t\trecursiveResize(moved, dir, diff, 's', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(side =='s'){\n\t\t\t\tfor (var i = x; i < x + sizex; i++) {\n\t\t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[i-1][y + sizey - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[i-1][y + sizey - 1].tile);\n\t \t\t\t\t}\n\t\t\t\t};\n\t\t\t\tvar helperReturn = adjHelper(adj, moved);\n\t\t\t\tcurWindow.attr({\n\t\t\t\t\t'sizey':sizey-diff\n\t\t\t\t});\n\t\t\t\tcurWindow.css({\n\t\t\t\t\t'height':(sizey-diff)*tileHeight\n\t\t\t\t});\n\t\t\t\tupdate_board(id);\n\t\t\t\tmoved.add(id);\n\t\t\t\tremoveHelper(curWindow);\n\t\t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'n', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t} else {\n\t \t\t\t//error\n\t \t\t\treturn\n\t \t\t}\n\t \t}\n\t \telse if(dir == 'down'){\n\t \t\tif(side == 'n'){\n\t \t\t\tfor (var i = x; i < x + sizex; i++) {\n\t \t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[i-1][y - 2].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[i-1][y - 2].tile);\n\t \t\t\t\t}\n\t \t\t\t};\n\t\t\t\t//check the base case-> all windows have been moved\n\t\t\t\tmoved.add(id);\n\t\t\t\tvar helperReturn = adjHelper(adj, moved);\n\t\t\t\tvar startY = curWindow.offset().top;\n\t\t\t\tcurWindow.attr({\n\t\t\t\t\t'row':y-diff,\n\t\t\t\t\t'sizey':sizey+diff\n\t\t\t\t});\n\t\t\t\tcurWindow.css({\n\t\t\t\t\t//'top':(y-diff)*tileHeight + $('.navbar').height() - 1,\n\t\t\t\t\t'top': startY - (diff*tileHeight),\n\t\t\t\t\t'height':(sizey+diff)*tileHeight\n\t\t\t\t});\n\t\t\t\tupdate_board(id);\n\t\t\t\tmoved.add(id);\n\t\t\t\tremoveHelper(curWindow);\n\t\t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, done resizing\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizing\n\t\t\t\t\trecursiveResize(moved, dir, diff, 's', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(side =='s'){\n\t\t\t\tfor (var i = x; i < x + sizex; i++) {\n\t\t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[i-1][y + sizey - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[i-1][y + sizey - 1].tile);\n\t \t\t\t\t}\n\t\t\t\t};\n\t\t\t\t//check the base case-> all windows have been moved\n\t\t\t\tmoved.add(id);\n\t\t\t\tvar helperReturn = adjHelper(adj, moved);\n\t\t\t\tcurWindow.attr({\n\t\t\t\t\t'sizey':sizey-diff\n\t\t\t\t});\n\t\t\t\tcurWindow.css({\n\t\t\t\t\t'height':(sizey-diff)*tileHeight\n\t\t\t\t});\n\t\t\t\tupdate_board(id);\n\t\t\t\tmoved.add(id);\n\t\t\t\tremoveHelper(curWindow);\n\t\t\t\tif(helperReturn.finished == true){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'n', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t} else {\n\t \t\t\t//error\n\t \t\t\treturn\n\t \t\t}\n\t \t}\n\t \telse if(dir == 'right'){\n\t \t\tif(side == 'e'){\n\t \t\t\tfor (var i = y; i < y + sizey; i++) {\n\t \t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[x + sizex - 1][i - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[x + sizex - 1][i - 1].tile);\n\t \t\t\t\t}\n\t \t\t\t};\n\t \t\t\tvar helperReturn = adjHelper(adj, moved);\n\t \t\t\tcurWindow.attr({\n\t \t\t\t\t'sizex':sizex-diff\n\t \t\t\t});\n\t \t\t\tcurWindow.css({\n\t \t\t\t\t'width':(sizex-diff)*tileWidth,\n\t \t\t\t});\n\t \t\t\tupdate_board(id);\n\t \t\t\tmoved.add(id);\n\t \t\t\tremoveHelper(curWindow);\n\t \t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'w', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(side =='w'){\n\t\t\t\tfor (var i = y; i < y + sizey; i++) {\n\t\t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[x - 2][i - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[x - 2][i - 1].tile);\n\t \t\t\t\t}\n\t\t\t\t};\n\t\t\t\tvar helperReturn = adjHelper(adj, moved);\n\t\t\t\tcurWindow.attr({\n\t\t\t\t\t'col':x-diff,\n\t\t\t\t\t'sizex':sizex+diff\n\t\t\t\t});\n\t\t\t\tcurWindow.css({\n\t\t\t\t\t'width':(sizex+diff)*tileWidth,\n\t\t\t\t\t'left':(x-diff-1)*tileWidth+$('.tile-holder').offset().left\n\t\t\t\t});\n\t\t\t\tupdate_board(id);\n\t\t\t\tmoved.add(id);\n\t\t\t\tremoveHelper(curWindow);\n\t\t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'e', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t} else {\n\t \t\t\t//error\n\t \t\t\treturn\n\t \t\t}\n\t \t}\n\t \telse if(dir == 'left'){\n\t \t\tif(side == 'e'){\n\t \t\t\tfor (var i = y; i < y + sizey; i++) {\n\t \t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[x + sizex - 1][i - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[x + sizex - 1][i - 1].tile);\n\t \t\t\t\t}\n\t \t\t\t};\n\t \t\t\tvar helperReturn = adjHelper(adj, moved);\n\t \t\t\tcurWindow.attr({\n\t \t\t\t\t'sizex':sizex-diff\n\t \t\t\t});\n\t \t\t\tcurWindow.css({\n\t \t\t\t\t'width':(sizex-diff)*tileWidth,\n\t \t\t\t});\n\t \t\t\tupdate_board(id);\n\t \t\t\tmoved.add(id);\n\t \t\t\tremoveHelper(curWindow);\n\t \t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'w', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(side =='w'){\n\t\t\t\tfor (var i = y; i < y + sizey; i++) {\n\t\t\t\t\tfor(var j = 0; j < adj.length; j++){\n\t \t\t\t\t\tif(adj[j] == board[x - 2][i - 1].tile){\n\t \t\t\t\t\t\ttoAdd = false;\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t} else {\n\t \t\t\t\t\t\ttoAdd = true;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tif(toAdd){\n\t \t\t\t\t\tadj.push(board[x - 2][i - 1].tile);\n\t \t\t\t\t}\n\t\t\t\t};\n\t\t\t\tvar helperReturn = adjHelper(adj, moved);\n\t\t\t\tcurWindow.attr({\n\t\t\t\t\t'col':x-diff,\n\t\t\t\t\t'sizex':sizex+diff\n\t\t\t\t});\n\t\t\t\tcurWindow.css({\n\t\t\t\t\t'width':(sizex+diff)*tileWidth,\n\t\t\t\t\t'left':(x-diff-1)*tileWidth + $('.wrapper').offset().left\n\t\t\t\t});\n\t\t\t\tupdate_board(id);\n\t\t\t\tmoved.add(id);\n\t\t\t\tremoveHelper(curWindow);\n\t\t\t\tif(helperReturn.finished){\n\t\t\t\t\t//base case, all windows have been resized\n\t\t\t\t\treturn; \n\t\t\t\t} else {\n\t\t\t\t\t//we need to keep resizeing \n\t\t\t\t\trecursiveResize(moved, dir, diff, 'e', helperReturn.adj[0]);\n\t\t\t\t}\n\t\t\t} else {\n\t \t\t\t//error\n\t \t\t\treturn;\n\t \t\t}\n\t \t} else {\n\t \t\t//error\n\t \t\treturn;\n\t \t}\n\t }",
"function move_tiles(){\r\n\t\toriginalTop = parseInt(this.style.top);\r\n\t\toriginalLeft = parseInt(this.style.left);\r\n\t\tif (originalTop == eTop && originalLeft == (eLeft-100) || originalTop == eTop && originalLeft == (eLeft+100) || originalTop == (eTop-100) && originalLeft == eLeft || originalTop == (eTop+100) && originalLeft == eLeft){\r\n\t\t\tthis.style.top = eTop + \"px\";\r\n\t\t\tthis.style.left = eLeft + \"px\";\r\n\t\t\teTop = originalTop;\r\n\t\t\teLeft = originalLeft;\r\n\t\t}\r\n\t}",
"function repositionSideResizer() {\n posTop.style.left = ((element.offsetWidth / 2) - 5) + 'px';\n\n posleft.style.top = ((element.offsetHeight / 2) - 5) + 'px';\n\n posBottom.style.left = ((element.offsetWidth / 2) - 5) + 'px';\n\n posRight.style.top = ((element.offsetHeight / 2) - 5) + 'px';\n }",
"function dragFixup(col, row) {\n\n\t\tif(col < 0 || col > maxCols || row < 0 || row > maxHeight){\n\t\t\t$('.ui-draggable-dragging').remove();\n\t\t\treturn;\n\t\t}\n\t\tvar targetId = board[col-1][row-1].tile;\n\t\tvar targetX = parseInt($('#'+targetId).attr('col'));\n\t\tvar targetY = parseInt($('#'+targetId).attr('row'));\n\t\tvar targetSizeX = parseInt($('#'+targetId).attr('sizex'));\n\t\tvar targetSizeY = parseInt($('#'+targetId).attr('sizey'));\n\t\tvar targetGrid = $('#'+targetId);\n\t\tvar startGrid = $('#'+dragStartId);\n\t\tif(targetId == dragStartId) {\n\t\t\tvar targetOffset = offset_from_location(row,col);\n\t\t\t$('#'+targetId).css({\n\t\t\t\t'top':dragStartOffset.top,\n\t\t\t\t'left':dragStartOffset.left,\n\t\t\t\t'height':dragStartSizeY*tileHeight,\n\t\t\t\t'width':dragStartSizeX*tileWidth\n\t\t\t});\n\t\t} else {\n\t\t\tvar startOffset = offset_from_location(dragStartSizeY, dragStartSizeX);\n\t\t\tvar targetOffset = offset_from_location(targetY, targetX);\n\t\t\tstartGrid.attr({\n\t\t\t\t'col': targetGrid.attr('col'),\n\t\t\t\t'row': targetGrid.attr('row'),\n\t\t\t\t'sizex': targetGrid.attr('sizex'),\n\t\t\t\t'sizey': targetGrid.attr('sizey')\n\t\t\t});\n\t\t\tstartGrid.css({\n\t\t\t\t'top':targetOffset.top,\n\t\t\t\t'left':targetOffset.left,\n\t\t\t\t'width':parseInt(startGrid.attr('sizex'))*tileWidth,\n\t\t\t\t'height':parseInt(startGrid.attr('sizey'))*tileHeight\n\t\t\t});\n\t\t\tupdate_board(dragStartId);\n\n\t\t\ttargetGrid.attr({\n\t\t\t\t'col': dragStartX,\n\t\t\t\t'row': dragStartY,\n\t\t\t\t'sizex': dragStartSizeX,\n\t\t\t\t'sizey': dragStartSizeY\n\t\t\t});\n\t\t\ttargetGrid.css({\n\t\t\t\t'top':dragStartOffset.top,\n\t\t\t\t'left':dragStartOffset.left,\n\t\t\t\t'width':parseInt(targetGrid.attr('sizex'))*tileWidth,\n\t\t\t\t'height':parseInt(targetGrid.attr('sizey'))*tileHeight\n\t\t\t});\n\t\t\tupdate_board(targetId);\n\t\t}\n\t}",
"_resizeMoveHandler(event) {\n const that = this;\n\n if (that.disabled || !that.resizable || !that._resizeStarted) {\n return;\n }\n\n const rectObject = that.getBoundingClientRect(),\n min = { width: 50, height: 50 },\n newWidth = that.rightToLeft ? (rectObject.width + rectObject.left - event.clientX) : (event.clientX - rectObject.left),\n newHeight = event.clientY - rectObject.top;\n\n if (newWidth > min.width) {\n that.style.width = newWidth + 'px';\n }\n\n if (newHeight > min.height) {\n that.style.height = newHeight + 'px';\n }\n }",
"function move(neighbor) {\t\t\n\t\tvar left = emptyCol * tileSize + \"px\";\n\t\tvar top = emptyRow * tileSize + \"px\";\n\t\t\n\t\temptyRow = parseInt(neighbor.style.top) / tileSize;\n\t\temptyCol = parseInt(neighbor.style.left) / tileSize;\n\t\tneighbor.style.top = top;\n\t\tneighbor.style.left = left;\t\n\t}",
"function reposition ( dleft, dtop, dright, dbottom ) {\n var left = $element.offset().left,\n top = $element.offset().top,\n right = $element.offset().left + $element.innerWidth(),\n bottom = $element.offset().top + $element.innerHeight(),\n isResizing = (dleft == 0 && dtop == 0) || (dright == 0 && dbottom == 0);\n while ( ( Math.abs(dleft) >= 1.0 || Math.abs(dright) >= 1.0 )\n && positionIsOkay( left + Math.sign( dleft ), top,\n right + Math.sign( dright ), bottom ) ) {\n left += Math.sign( dleft );\n right += Math.sign( dright );\n dleft -= Math.sign( dleft );\n dright -= Math.sign( dright );\n }\n while ( ( Math.abs(dtop) >= 1.0 || Math.abs(dbottom) >= 1.0 )\n && positionIsOkay( left, top + Math.sign( dtop ),\n right, bottom + Math.sign( dbottom ) ) ) {\n top += Math.sign( dtop );\n bottom += Math.sign( dbottom );\n dtop -= Math.sign( dtop );\n dbottom -= Math.sign( dbottom );\n }\n $element.offset( { left : left, top : top } );\n $element.innerWidth( right - left );\n $element.innerHeight( bottom - top );\n\n // if there's a wrapped img directly below this element resize it too\n if (isResizing && $element.find('> div > img').length != 0) {\n const $img = $element.find('> div > img');\n $img.css('width', right - left - 2*DEFAULT_RESIZING_MARGIN)\n .css('height', bottom - top - 2*DEFAULT_RESIZING_MARGIN);\n }\n }",
"function ResizeHandle() {\n\n var minWidth = 50;\n var minHeight = 20;\n\n // dragstart\n this.dragstart = function (event) {\n var dt = event.dataTransfer;\n var parent = event.target.parentNode;\n var parentStyle = document.defaultView.getComputedStyle(parent);\n var rtl = parent.classList.contains(\"lang_rtl\");\n var parentLeft = parseInt(parentStyle.getPropertyValue(\"left\"), 10);\n var parentTop = parseInt(parentStyle.getPropertyValue(\"top\"), 10);\n var parentWidth = parseInt(parentStyle.getPropertyValue(\"width\"), 10);\n var parentHeight = parseInt(parentStyle.getPropertyValue(\"height\"), 10);\n parentHeight -= event.clientY;\n if (rtl) {\n parentWidth += event.clientX;\n parentHeight - +event.clientY;\n parentLeft -= event.clientX;\n } else {\n parentWidth -= event.clientX;\n }\n parent.style.opacity = \"0.9\";\n dt.setData(\"text/plain\", parentLeft + \",\" + parentTop + \",\" + parentWidth + \",\" + parentHeight);\n\n document.getElementById(\"alerter\").innerHTML = \"Resizing Information Node\";\n };\n\n // drag\n this.drag = function (event) {\n event.preventDefault();\n // var dt = event.target;\n // dt.effectAllowed = \"all\";\n // dt.dropEffect = \"move\";\n\n };\n\n // dragover\n this.dragover = function (event, e_id) {\n event.preventDefault();\n var myData = event.dataTransfer.getData(\"text/plain\").split(',');\n var parent = document.getElementById(e_id).parentNode;\n var rtl = parent.classList.contains(\"lang_rtl\");\n var parentLeft = parseInt(myData[0], 10);\n var parentTop = parseInt(myData[1], 10);\n var parentWidth = parseInt(myData[2]);\n var parentHeight = parseInt(myData[3]);\n\n if (rtl) {\n var newWidth = parentWidth - event.clientX;\n var newHeight = parentHeight + event.clientY;\n var newLeft = parentLeft + event.clientX;\n if (newWidth > minWidth) {\n parent.style.left = newLeft + 'px';\n parent.style.width = newWidth + 'px';\n }\n if (newHeight > minHeight) {\n parent.style.height = newHeight + 'px';\n }\n }\n else {\n var newWidth = parentWidth + event.clientX;\n var newHeight = parentHeight + event.clientY;\n if (newWidth > minWidth) {\n parent.style.width = newWidth + 'px';\n }\n if (newHeight > minHeight) {\n parent.style.height = newHeight + 'px';\n }\n }\n };\n\n // drop (minWidth limitation)\n this.drop = function (event, e_id) {\n event.preventDefault();\n var me = document.getElementById(e_id);\n var parent = me.parentNode;\n parent.style.opacity = \"\";\n\n document.getElementById(\"alerter\").innerHTML = \"ready\";\n };\n\n}",
"function moveRectsToContainer(col, element, recordelem, flag) {\n \tif(element.nodeType != document.ELEMENT_NODE && typeof element == 'string'){\n \t\t// debugger;\n \t\t\telement = document.querySelector(element);\n \t\t}\n \t\tif(recordelem.nodeType != document.ELEMENT_NODE && typeof recordelem == 'string'){\n \t\t\trecordelem = document.querySelector(recordelem);\n \t\t}\n \t\t// debugger;\n \t//move the working column of rects to resize container\n \tif(col == -1){\n \t\t//choose no column, update workingCol and return\n //only happens when showing resize layer from clicking of resize button\n workingCol = rectColsManager.length;\n workingIdx = -1;\n \t\treturn;\n \t}else{\n \t\t//move the rects in column\n \t\tfor(var i=0;i<rectColsManager[col].length;i++){\n \t\t\t// debugger;\n var order = rectColsManager[col][i];\n \t\t\tvar selectedRect = $(\".rectUnit[data-order=\" + order + \"]\");\n \t\t\tvar oriWidth = $(selectedRect).width();\n \t\t\tvar oriHeight = $(selectedRect).height();\n \t\t\tvar oriLoc = $(selectedRect).position();\n var selectedIpt = $(\".rectItem[data-order=\" + order + \"]\"); \n //moving inputs\n // $(\".rectItem[data-order=\" + order + \"]\").appendTo(recordelem);\n if(!flag){\n //moving input from view page to resize page\n $(selectedIpt).appendTo(recordelem); \n }else{\n //moving input from resize page to view page\n if(i==0){\n //the first input\n if(col==0){\n //the first col\n $(selectedIpt).prependTo(recordelem);\n }else if(rectColsManager[col-1].length==0){\n //the previous col is empty\n $(selectedIpt).appendTo(recordelem);\n }else{\n //insert after the last input of previous column\n var preIpt = $(\".rectItem[data-order=\" + rectColsManager[col-1].slice(-1)[0] + \"]\");\n $(preIpt).after($(selectedIpt));\n }\n }else{\n //the latter inputs insert after the previous one\n var preIpt = $(\".rectItem[data-order=\" + rectColsManager[col][i-1] + \"]\");\n $(preIpt).after($(selectedIpt));\n }\n }\n \n \t\t\t//moving rects\n $(selectedRect).appendTo(element); \n if (!flag) {\n //moving the working column of rects to resize container\n var newWidth = oriWidth * resizeRect.ratio;\n var newHeight = oriHeight * resizeRect.ratio;\n var newTop = oriLoc.top * resizeRect.ratio;\n var newLeft = (oriLoc.left - resizeRect.left) * resizeRect.ratio;\n }else{\n //moving the rects from resize container to view container\n var newWidth = oriWidth / resizeRect.ratio;\n var newHeight = oriHeight / resizeRect.ratio;\n var newTop = oriLoc.top / resizeRect.ratio;\n var newLeft = oriLoc.left / resizeRect.ratio + resizeRect.left;\n }\n $(selectedRect).css({\n \t\t\t\twidth: newWidth,\n \t\t\t\theight: newHeight,\n \t\t\t\ttop: newTop,\n \t\t\t\tleft: newLeft,\n \t\t\t});\n lib.updateRectParam(order, newWidth, newHeight, 1, {top:newTop, left:newLeft});\n \t\t}\n \t}\n }",
"_resizeMoveHandler(event) {\n const that = this;\n\n if (that.disabled || !that.resizable || !that._resizeStarted) {\n return;\n }\n\n const rectObject = that.getBoundingClientRect(),\n min = { width: 50, height: 50 },\n newWidth = event.clientX - rectObject.left,\n newHeight = event.clientY - rectObject.top;\n\n if (newWidth > min.width) {\n that.style.width = newWidth + 'px';\n }\n\n if (newHeight > min.height) {\n that.style.height = newHeight + 'px';\n }\n }",
"function fRepositionThumbnails (elem, xPos, yPos) {\n elem.style.left = xPos + \"px\";\n elem.style.top = yPos + \"px\";\n }",
"function _resize_n(e) {\n var tag = e.target,\n diff = (_prevY - e.clientY),\n eventY = e.clientY - containerY,\n height = parseInt(tag.style.height, 10),\n top = parseInt(tag.style.top, 10),\n newHeight;\n\n if (height === _maxHeight && (diff > 0 || eventY < top)) {\n return;\n }\n if (height === _minHeight && (diff < 0 || eventY > top + _resizeHandleWidth)) {\n return;\n }\n\n newHeight = height + diff;\n if (newHeight < _minHeight) {\n diff -= (newHeight - _minHeight);\n newHeight = _minHeight;\n } else if (newHeight > _maxHeight) {\n diff -= (newHeight - _maxHeight);\n newHeight = _maxHeight;\n }\n\n if (newHeight !== height || (top - diff) !== top) {\n tagging.setDirty(tag);\n tag.style.height = newHeight + 'px';\n tag.style.top = (top - diff) + 'px';\n if (!_enforceImageBoundaries(_getImageFor(tag), tag, true)) {\n _prevY = e.clientY;\n _offY = eventY - (top - diff);\n }\n }\n }",
"function rePositionCell($this) {\n var top = parseInt($this.position().top);\n var left = parseInt($this.position().left);\n var width = parseInt($this.width());\n var height = parseInt($this.height());\n var cellWrapWH = parseInt($this.attr('_cell_wrap_wh'));\n var cellMargin = parseInt($this.attr('_cell_margin'));\n var rowSrcFrom = parseInt($this.attr('_row'));\n var columnSrcFrom = parseInt($this.attr('_column'));\n var topSrc = $this.attr('_top');\n var leftSrc = $this.attr('_left');\n\n var centerTop = top + height / 2;\n var centerLeft = left + width / 2;\n\n var rowNew = Math.floor((centerTop - jQuery.DesktopGrid.dataObj.gridDivPaddingTop) / cellWrapWH);\n var columnNew = Math.floor((centerLeft - jQuery.DesktopGrid.dataObj.gridDivPaddingLeft) / cellWrapWH);\n jQuery.osxUtils.logger.info('rowSrc=' + rowSrcFrom + ', columnSrc=' + columnSrcFrom)\n jQuery.osxUtils.logger.info('rowNew=' + rowNew + ', columnNew=' + columnNew);\n\n rowNew = Math.max(rowNew, 0);\n columnNew = Math.max(columnNew, 0);\n rowNew = Math.min(rowNew, jQuery.DesktopGrid.dataObj.rows - 1);\n columnNew = Math.min(columnNew, jQuery.DesktopGrid.dataObj.columns - 1);\n\n var cellAbsDragFrom = getCellAbs(rowSrcFrom, columnSrcFrom, cellWrapWH, cellMargin);\n var cellAbsDragTo = getCellAbs(rowNew, columnNew, cellWrapWH, cellMargin);\n\n if (rowSrcFrom == rowNew && columnSrcFrom == columnNew) {\n jQuery.osxUtils.logger.info('position, row=' + rowNew + ', column=' + columnNew + ' is the src position, do not need move');\n moveCellTo(jQuery.DesktopGrid.dataObj.currentScreen, $this, cellAbsDragFrom, rowSrcFrom, columnSrcFrom, rowSrcFrom, columnSrcFrom, false);\n return;\n }\n\n var cellIdDragTo = jQuery.DesktopGrid.dataObj.cellIdIJ[jQuery.DesktopGrid.dataObj.currentScreen + '_' + rowNew + '_' + columnNew];\n var $cellDragTo = $('#' + cellIdDragTo);\n// jQuery.osxUtils.logger.info('cellIdDragTo=' + cellIdDragTo);\n\n //the target cell is empty, so move cell which you dragged to the position directly\n if ($cellDragTo.size() == 0) {\n moveCellTo(jQuery.DesktopGrid.dataObj.currentScreen, $this, cellAbsDragTo, rowSrcFrom, columnSrcFrom, rowNew, columnNew, true);\n } else {\n //the target cell is already occupied\n if (jQuery.DesktopGrid.dataObj.exchangeCellContent) {\n jQuery.osxUtils.logger.info('position, row=' + rowNew + ', column=' + columnNew + ' is already occupied, exchange two cells content');\n moveCellTo(jQuery.DesktopGrid.dataObj.currentScreen, $this, cellAbsDragTo, rowSrcFrom, columnSrcFrom, rowNew, columnNew, false);\n moveCellTo(jQuery.DesktopGrid.dataObj.currentScreen, $cellDragTo, cellAbsDragFrom, rowNew, columnNew, rowSrcFrom, columnSrcFrom, false);\n } else {\n jQuery.osxUtils.logger.info('position, row=' + rowNew + ', column=' + columnNew + ' is already occupied, please change other position');\n moveCellTo(jQuery.DesktopGrid.dataObj.currentScreen, $this, cellAbsDragFrom, rowSrcFrom, columnSrcFrom, rowSrcFrom, columnSrcFrom, false);\n }\n }\n }",
"function resizeRect() {\n changeCursor(\"nw-resize\")\n coordinates = getCanvasMousePosition(canvas, event)\n if(coordinates.x > panels[whichPanel][i].x && coordinates.y > panels[whichPanel][i].y)\n {\n resizeRectangle(canvas, event, i)\n }\n }",
"function resizePanes(e) {\n event.stop(e);\n $wrapper.addClass('resizing');\n var min = 550;\n var width = domStyle.get('wrapper', 'width');\n\n var dragHandle = on(window, 'mousemove', function(e){\n event.stop(e);\n if (e.pageX > min) {\n setHandlePosition(e.pageX + 8, width);\n }\n });\n\n on.once(parent.document, 'mouseup', function(e){\n $wrapper.removeClass('resizing');\n connect.disconnect(dragHandle);\n });\n\n function setHandlePosition(pos, width) {\n // vanilla JS is a *lot* faster than dojo :/\n $code[0].style.right = (width - pos) + 'px';\n $output[0].style.left = pos + 'px';\n }\n }",
"changePosition() {\n if (this.draggingElOrder < this.targetElOrder) {\n // index of dragging element is smaller than entered element\n // dragging element insert after entered element\n this.targetEl.insertAdjacentElement('afterend', this.draggingEl);\n }\n else if (this.draggingElOrder > this.targetElOrder) {\n // index of dragging element is bigger than entered element\n // dragging element insert before entered element\n this.targetEl.insertAdjacentElement('beforebegin', this.draggingEl);\n }\n }",
"resize() {\n this.tileWidth = this.board.clientWidth / this.cols;\n this.board.style.height = this.board.clientWidth + 'px';\n\n for (let tile of this.tiles) {\n tile.style.width = Math.floor(100 / this.cols) - 2 + \"%\";\n tile.style.height = Math.floor(100 / this.rows) - 2 + \"%\";\n tile.style.lineHeight = this.tileWidth + 'px'; // Vertical align to be middle\n tile.style.fontSize = this.tileWidth / 2 + 'px';\n this.moveOne(tile, false);\n }\n }",
"function _resize_nw(e) {\n _resize_n(e);\n _resize_w(e);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to control the pages to slide arg: 1 | 1 1 slide up 1 slide down | function pageSlide(arg){
if(isReachBoundary(arg)){
return false;
}
var page_height = $(".fullPage").eq(0).height();
var pre_top = parseInt($(".fullPage-Container").css("top"));
_index -= arg;
var callback = $(".fullPage").eq(_index).attr("inView");
return $(".fullPage-Container").animate({top:pre_top+arg*page_height+"px"},400,"swing",function(){
strTofunc(callback);
location.hash=$(".fullPage").eq(_index).attr("page-id");
});
} | [
"function nextslide() {if(current==total_slides){current = 1}else{current++} check_slide();}",
"function slideIn(callback) {\n setX(upperPage(), 0, slideOpts(), callback);\n }",
"function turnPageSlider() {\n leftPageNo = _getSliderPage();\n rightPageNo = leftPageNo + 1;\n _updateUrlPage(); /* Causes init, and therefore _setPage() */\n}",
"function setSlide(n) {\n SlideIndex = n;\n slideShow();\n}",
"function switchForward() {\n currentSlide += 1;\n switchSlide();\n }",
"function slideForward() {\n if ($run.activeIndex < ($conf.slides.length - 1)) {\n $run.activeIndex += 1;\n } else if ($conf.cycle) {\n $run.activeIndex = 0;\n }\n\n alignToActiveSlide();\n }",
"function currentSlide(n){\n slideIndex = n;\n}",
"function callNextSlide() {\r\n\t\t\tvar nextIndex = (currentIndex < itemNum - 1) ? (currentIndex + 1) : 0;\r\n\t\t\tchangeSlide(nextIndex);\r\n\t\t}",
"function nextSlide() {\r\n var index = (currentIndex == numSlides - 1) ? 0 : (currentIndex + 1);\r\n gotoSlide(index);\r\n }",
"goToFirstSlide() {\n\n this.goTo(0, -1);\n\n }",
"function beforeSlide( curr, next , opt )\n{\n sliderExpr = opt.slideExpr;\n slideFlag = true;\n}",
"function currentSlide(n) { //aktuelle Seite\r\n showSlides(slideIndex= n);\r\n}",
"function navigate(n) {\n var position = currentPosition();\n var numSlides = document.getElementsByClassName('slide').length;\n\n /* Positions are 1-indexed, so we need to add and subtract 1 */\n var nextPosition = (position - 1 + n) % numSlides + 1;\n\n /* Normalize nextPosition in-case of a negative modulo result */\n nextPosition = (nextPosition - 1 + numSlides) % numSlides + 1;\n\n document.getElementById('slide-' + position).classList.add('hidden');\n document.getElementById('slide-' + nextPosition).classList.remove('hidden');\n\n updateProgress();\n updateURL();\n updateTabIndex();\n}",
"reposSlide() {\n this.current_button.classList.toggle('scroller__page_current', false);\n this.current_button = this.paginator_buttons[Math.min(Math.max(this.current_page, 0), this.count - 1)];\n this.current_button.classList.toggle('scroller__page_current', true);\n this.move(this.current_page);\n }",
"function slideTo(index) {\n\t slide(index);\n\t }",
"function move_to_slide() {\n\tif (currentSlide == 1)\n\t{\n\t\tset_the_stage();\n\t}\n\telse if (currentSlide == 2)\n\t{\n\t\tslide1();\n\t}\n\telse if (currentSlide == 3)\n\t{\n\t\tslide2();\n\t}\n\telse if (currentSlide == 4)\n\t{\n\t\tslide3();\n\t}\n\telse if (currentSlide == 5)\n\t{\n\t\tslide4();\n\t}\n\telse if (currentSlide == 6)\n\t{\n\t\tslide5();\n\t}\n}",
"function increaseSlide() {\r\n currentSlide++;\r\n showSlide(currentSlide);\r\n}",
"function slideShowNext() {\n slideShow((curIndex !== slides.length - 1) ? curIndex + 1 : 0, 'left');\n }",
"function movsControlPage(){\n\n //adicionando evento de click previous da paginação dos movimentos\n // Adding event of click PREVIOUS of pagination of the movements\n $('.pageM-1').on('click', () => {\n controlePaginacaoMov(--pageMovActual);\n });\n\n //Adding event of click NEXT of pagination of the movements\n $('.pageM-2').on('click', () => {\n controlePaginacaoMov(++pageMovActual);\n });\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a number to superscript. | toSuperscript(value, supToNormal) {
const chars = '-0123456789',
sup = '⁻⁰¹²³⁴⁵⁶⁷⁸⁹';
let result = '';
for (let i = 0; i < value.length; i++) {
if (supToNormal === true) {
const m = sup.indexOf(value.charAt(i));
result += (m !== -1 ? chars[m] : value[i]);
}
else {
const n = chars.indexOf(value.charAt(i));
result += (n !== -1 ? sup[n] : value[i]);
}
}
return result;
} | [
"function superscript(n) {\r\n\tvar s = n.toString();\r\n\tvar out = '';\r\n\tfor(var i=0;i<s.length;i++) {\r\n\t\tout += superscript_numbers[s[i]];\r\n\t}\r\n\treturn out;\r\n}",
"exponentialToSuperscript(exponentialValue) {\n const indexOfE = exponentialValue.indexOf('e'),\n power = exponentialValue.slice(indexOfE + 1).replace(/0{1,2}/, '');\n let scientificValue = exponentialValue.slice(0, indexOfE + 1);\n\n scientificValue = scientificValue.replace('e', '×10');\n scientificValue += this.toSuperscript(power);\n scientificValue = scientificValue.replace('+', '');\n\n return scientificValue;\n }",
"function superscript(s) {\n\t\t\tvar openTag = findTag('{', s);\n\t\t\treturn s.split('<').join(openTag).split('>').join('</sup>').split(openTag).join('<sup>');\n\t\t}",
"function superscript(ch, supressTag) {\n var st = 1;\n //if (/[^a-zA-Z0-9]/.test(ch))\n // return ch;\n ch = ch.replace(\" \", \" \");\n\n if (st < ch.length) {\n ch = ch.substring(0, st) + \"<sup>\" + ch.substring(st) + \"</sup>\";\n }\n if (ch.indexOf(\"|\") == -1) {\n if (!supressTag)\n ch = ch.replace(\"</chord>\", \"\");\n }\n ch = ch.replace(\" \", \" \");\n return ch;\n}",
"function add_fr_num_superscript(html_str) {\n\tlet edited_html_str = html_str.replaceAll(/\\b1er\\b/g, \"1<sup>er</sup>\");\n\tedited_html_str = edited_html_str.replaceAll(/\\b([0-9]+)e\\b/g, \"$1<sup>e</sup>\");\n\treturn edited_html_str;\n}",
"function subscript(n) {\n\tconst DIGITS = (Unicode) ? \"₀₁₂₃₄₅₆₇₈₉\" : \"0123456789\";\n\tif (n > 99 || n != Math.floor(n)) return true;\n\tconst digits = n % 10;\n\tconst tens = (n - digits) / 10;\n \n\tlet s = (tens > 0) ? DIGITS.charAt(tens) : \"\";\n\ts += DIGITS.charAt(digits);\n\n\treturn s;\n}",
"function sup (ctx, node, index, parent) {\n const contents = all(ctx, node)\n\n return `\\\\textsuperscript{${contents}}`\n}",
"function convertToSciNotation (num) {\n var p = 0;\n while (Math.pow(10, p) <= num) {\n p += 1;\n }\n p -= 1;\n num /= Math.pow(10, p);\n var decimal = num.toFixed(2);\n return decimal + \" x 10<sup>\" + p + \"</sup>\";\n}",
"function sup(ctx, node, index, parent) {\n var contents = all(ctx, node);\n return \"\\\\textsuperscript{\".concat(contents, \"}\");\n}",
"function tNumber() {\n const [h, k] = [opt.h, opt.k];\n eid(\"tnumber\").innerHTML = `= ${h}<sup>2</sup> + (${h})(${k}) + ${k}<sup>2</sup> = ${h * h + h * k + k * k}`;\n}",
"function superDigit(n) {\n const sumOfDigits = x => {\n return x\n .toString()\n .split('')\n .reduce((sum, i) => sum + Number(i), 0);\n };\n return n / 10 < 1 ? n : superDigit(sumOfDigits(n));\n}",
"toggleSuperscript() {\n if (!this.owner.isReadOnlyMode) {\n let value = this.selection.characterFormat.baselineAlignment === 'Superscript' ? 'Normal' : 'Superscript';\n this.selection.characterFormat.baselineAlignment = value;\n }\n }",
"function toggleSuperscript(editor) {\n execCommand_1.default(editor, \"superscript\" /* Superscript */);\n}",
"addTextSuperscript(text) {\n const symbolType = ChordSymbol.symbolTypes.TEXT;\n const symbolModifier = ChordSymbol.symbolModifiers.SUPERSCRIPT;\n return this.addSymbolBlock({ text, symbolType, symbolModifier });\n }",
"function mySuperScript(){\n\t\t\n\t\t\t\n\t\t\tvar line = document.createElement(\"BR\");\n\t\t\tdocument.body.appendChild(line);\n\t\t\t\n\t\t\tvar num = document.createElement(\"INPUT\");\n\t\t\tnum.type = \"text\";\n\t\t\tnum.setAttribute(\"id\",\"sup\");\n\t\t\t\n\t\t\t$(element).find(\"#hello\").get(0).appendChild(num);\t\t\t\n\t\t\tvar superb = document.createElement(\"BUTTON\");\n\t\n\t\t\tvar superText = document.createTextNode(\"SuperScript\");\n\t\t\t\n\t\t\t\n\t\t\tsuperb.addEventListener(\"click\", superscript);\n\t\t\tsuperb.appendChild(superText);\n\t\t\n\t\t\t$(element).find(\"#hello\").get(0).appendChild(superb);\t\n\t\t}",
"addGlyphSuperscript(glyph) {\n const symbolType = ChordSymbol.symbolTypes.GLYPH;\n const symbolModifier = ChordSymbol.symbolModifiers.SUPERSCRIPT;\n return this.addSymbolBlock({ glyph, symbolType, symbolModifier });\n }",
"function convertInteger (integer) {\n\t\t\t\tif (integer >= base) {\n\t\t\t\t\treturn `{${integer}}`;\n\t\t\t\t}\n\t\t\t\tif (integer >= 10) {\n\t\t\t\t\treturn String.fromCharCode(\"a\".charCodeAt(0) - 10 + integer);\n\t\t\t\t}\n\t\t\t\treturn `${integer}`;\n\t\t\t}",
"function baseConverter(num, b) {\n\n}",
"function strBaseConverter (number,ob,nb) {\n number = number.toUpperCase();\n var list = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var dec = 0;\n for (var i = 0; i <= number.length; i++) {\n dec += (list.indexOf(number.charAt(i))) * (Math.pow(ob , (number.length - i - 1)));\n }\n number = '';\n var magnitude = Math.floor((Math.log(dec)) / (Math.log(nb)));\n for (var i = magnitude; i >= 0; i--) {\n var amount = Math.floor(dec / Math.pow(nb,i));\n number = number + list.charAt(amount);\n dec -= amount * (Math.pow(nb,i));\n }\n return number;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the newest datetime as a string | function newest(files) {
const dates = extractDates(files);
const newest = String(Math.max.apply(null, dates));
return newest;
} | [
"async getLastSyncedDate() {\n const data = await this.DynamoDBDocumentClient.get(\n {\n Key: {\n PlayerName: Constants.LAST_SYNCED_DATE\n },\n TableName: Constants.PLAYER_TABLE_NAME\n }).promise();\n return data.Item && data.Item.Date ? data.Item.Date : \"\";\n }",
"getLatestTime(){\n for(let i=this.feeds.length-1;i>=0;i--){\n if(!this.feeds[i].isDynamic){\n return this.feeds[i].createdAt.timestamp;\n }\n }\n return 0;\n }",
"function latestDate(latest, updated) {\n\t //latest date display format.\n\t// console.log(latest, updated);\n\t var today = moment(new Date()), displayDate, diff;\n\n\t if (moment(latest).toISOString().substring(0,10)===moment(updated).toISOString().substring(0,10)) {\n\t displayDate = moment(updated);\n\t diff = displayDate.fromNow();\n\n\t if (diff==='a day ago') {\n\t return 'Yesterday at ' + displayDate.format('HH:mm');\n\t } else if (diff.indexOf('days') > -1) {\n\t return diff + ' at ' + displayDate.format('HH:mm');\n\t } else {\n\t return diff + '.';\n\t }\n\t } else {\n\t displayDate = moment(latest);\n\t diff = today.diff(displayDate, 'days');\n\n\t //for 0 and 1 day(s) ago use the special term.\n\t if (diff===0) {\n\t return 'Today';\n\t } else if (diff===1) {\n\t return 'Yesterday';\n\t } else {\n\t return diff + ' days ago.';\n\t }\n\t }\n\t }",
"function stringify( dateTime ) {\n const dt = day( dateTime );\n\n const isPast = verify( dateTime );\n\n return dt.fromNow();\n}",
"function latestTime() {\n return web3.eth.getBlock('latest').timestamp;\n}",
"function getOldestBackupDate()\n{\n let backups = [];\n for (let machineName in machines)\n {\n let machine = machines[machineName];\n let machinePath = path.join(config.data_dir, machine.name);\n backups.push(...getPreviousBackupNames(machinePath));\n }\n return util.parseISODateString(backups.reduce((min, value) => {\n return value < min ? value : min;\n }));\n}",
"function formatHumanDate() {\n return 'These results were last updated on '+lastUpdateDateObj.toLocaleDateString(\"en-US\")\n +' at '+lastUpdateDateObj.toLocaleTimeString(\"en-US\")+'.';\n }",
"function nowStringDate() {\n return stringFromTime(new Date().getTime() / 1000);\n}",
"function build_oldest_datestamp () {\n // Figure out how many days we want to keep\n var days_to_keep = GM_config.get('days_to_keep');\n\n // Take the current date and subtract days to keep\n var date = new Date(new Date().setDate(new Date().getDate() - days_to_keep));\n\n // Get the new year, month,day\n var year = date.getFullYear();\n var month = date.getMonth();\n var day = date.getDate();\n\n // Combine them into a datestamp and return it\n var datestamp = [year,month+1,day].join('');\n return datestamp;\n}",
"function findOldestItemTime() {\n var oldest_item_time_str = \"2200-01-01-01-01-00-UTC\";\n var oldest_item_time = dateStrToDateObj(oldest_item_time_str);\n $(\".savetime-item\").each(function() {\n var item_time_str = $(this).attr(\"data-item-date-time\");\n var item_time = dateStrToDateObj(item_time_str);\n if (oldest_item_time > item_time) {\n oldest_item_time = item_time;\n oldest_item_time_str = item_time_str;\n }\n });\n return oldest_item_time_str;\n}",
"function latestTime () {\n return web3.eth.getBlock('latest').timestamp\n}",
"function generateLastEdited(timestamp){\n return `Last Edited ${moment(timestamp).fromNow()}`\n}",
"function latesttime() {\n utcdate = new Date(datetime);\n utchours = utcdate.getHours();\n utcminutes = utcdate.getMinutes();\n \n if (utchours < 10) {\n utchours = \"0\" + utchours\n }\n \n if (utcminutes < 10 ) {\n utcminutes = \"0\" + utcminutes\n }\n \n // Return objects\n return {\n hours: utchours, \n mins: utcminutes,\n };\n }",
"function getPreciseNowString() {\n\treturn new Date(Date.now()).toISOString();\n}",
"function GetLatestMessageTime( ){\n \n return document.querySelector( `#main > div > div > div > div > div:nth-last-of-type(1) > div > div > div > div > div > span[dir='auto']` ).innerHTML;\n \n}",
"function timestampString() {\n\t return (new Date()).toISOString().replace(/T/, '.')\n}",
"function getCurrentTimeFormatted() {\n var curDateTime = new Date().toISOString(); // Keeping same as iso string\n\n /* let curDate = curDateTime.split(\"T\")[0];\n let curTimeExceptMillis = curDateTime\n .split(\"T\")[1]\n .split(\"Z\")[0]\n .split(\".\")[0];\n let curTimeMillis = curDateTime.split(\"Z\")[0].split(\".\")[1];\n return curDate + \" \" + curTimeExceptMillis + \"+\" + curTimeMillis; */\n\n return curDateTime;\n}",
"dateForNewComment() {\n if (this.actionList.length === 0) {\n return new Date();\n } else {\n const latestAction = this.actionList.sort().first();\n const afterLatest = moment(latestAction.getDate())\n .add(1, 'seconds')\n .toDate();\n return _.max([new Date(), afterLatest]);\n }\n }",
"function getCurrentTimeFormatted() {\n const curDateTime = new Date().toISOString();\n // Keeping same as iso string\n /* let curDate = curDateTime.split(\"T\")[0];\n let curTimeExceptMillis = curDateTime\n .split(\"T\")[1]\n .split(\"Z\")[0]\n .split(\".\")[0];\n let curTimeMillis = curDateTime.split(\"Z\")[0].split(\".\")[1];\n return curDate + \" \" + curTimeExceptMillis + \"+\" + curTimeMillis; */\n return curDateTime;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get non IMS messages. Get red and green message bars. | function getNonIMSMessages() {
/**
* result.
*/
var result = [];
/**
* temp message bar.
* @type {Object}
*/
var tempMessageBar = null;
/**
* m.
* @type {Number}
*/
var m = 0;
for (m = 0; m < messageBoxes.length; m++) {
tempMessageBar = messageBoxes[m];
if (tempMessageBar.data("severity") !== 'gray') {
result.push(tempMessageBar);
}
}
return result;
} | [
"getColor() {\n return this.remoteMsg[RNRemoteMessage.NOTIFICATION.COLOR];\n }",
"HighlightedMessages() {\n let ret = [];\n if (this.HighlightedRegion.t0 == -999 || this.HighlightedRegion.t1 == -999) { return ret; }\n const lb = Math.min(this.HighlightedRegion.t0, this.HighlightedRegion.t1);\n const ub = Math.max(this.HighlightedRegion.t0, this.HighlightedRegion.t1);\n for (let i=0; i<this.Titles.length; i++) {\n const title = this.Titles[i];\n if (title.header == true) continue; // Do not include headers. TODO: Allow rectangular selection\n\n const line = [ title.title, [] ];\n const interval_idx = title.intervals_idxes[0];\n const intervals_i = this.Intervals[interval_idx];\n for (let j=0; j<intervals_i.length; j++) {\n const m = intervals_i[j];\n if (!(m[0] > ub || m[1] < lb)) {\n line[1].push(m);\n }\n }\n if (line[1].length > 0) {\n ret.push(line);\n }\n }\n return ret;\n }",
"function statusChecker(green, red) {\n if (green === true && red === true) {\n return \"#D79D45\"; // for incomplete data\n }\n else if (green === true && red === false) {\n return \"#438a4c\"; // for complete data\n }\n else {\n return \"#CA4448\"; // for missing data\n }\n }",
"displayRestOfMessages() {\n let msgToShow = [\n ...this.state.slackMsg.slice(this.state.displayIndex[1]),\n ...this.state.slackMsg.slice(0, this.state.displayIndex[1])\n ];\n return msgToShow;\n }",
"static getMessages() {\n\t\ttry {\n\t\t\tconst messages = [];\n\t\t\t\n\t\t\tfor (const ele of this.getMessageElements()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst props = this.getMessageElementProps(ele);\n\t\t\t\t\t\n\t\t\t\t\tif (props != null) {\n\t\t\t\t\t\tmessages.push(props.message);\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.error(\"[DHT] Error extracing message data, skipping it.\", e, ele, DOM.tryGetReactProps(ele));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn messages;\n\t\t} catch (e) {\n\t\t\tconsole.error(\"[DHT] Error retrieving messages.\", e);\n\t\t\treturn [];\n\t\t}\n\t}",
"showMessages () {\n this.messages.forEach((message) => {\n console.log(`${messageStyles[message.getType()]} ${message.getType()}: ${message.getText()}`)\n })\n }",
"function hideAllMessage() {\n [].forEach.call(messages, function(message) {\n if (!message.classList.contains('msgInvisible')) {\n message.classList.add('msgInvisible');\n }\n })\n}",
"@action\n toggleMessagesNoColor() {\n const color = store.theme.palette.background.default;\n if (this.messagesNoColor) {\n for (const [k, v] of Object.entries(this.channelsSheet.classes)) {\n this.channelsSheet.getRule(k).prop(\"background-color\", `${color}`);\n }\n } else {\n for (const [k, v] of Object.entries(this.channelsSheet.classes)) {\n const originalBackgroundColor = this.channelsSheet.getRule(k).style[\n \"original-background-color\"\n ];\n this.channelsSheet\n .getRule(k)\n .prop(\"background-color\", `${originalBackgroundColor}`);\n }\n }\n }",
"static _getMessageStyles(message) {\n let marker = 'asdcsDiagramArrowSolid';\n let dasharray = '';\n let css = 'asdcs-diagram-message';\n if (message.type === 'request') {\n css = `${css} asdcs-diagram-message-request`;\n } else {\n css = `${css} asdcs-diagram-message-response`;\n marker = 'asdcsDiagramArrowOpen';\n dasharray = '30, 10';\n }\n\n if (message.asynchronous) {\n css = `${css} asdcs-diagram-message-asynchronous`;\n marker = 'asdcsDiagramArrowOpen';\n } else {\n css = `${css} asdcs-diagram-message-synchronous`;\n }\n\n return { css, marker, dasharray };\n }",
"function resetMessageStyle() {\n if (otherUnitsElement.classList !== undefined) {\n otherUnitsElement.classList.remove ('page-message', 'page-message--warning');\n }\n }",
"function wpi_message_stack_check() {\r\n\r\n if(jQuery('.wpi_yellow_notification .wpi_message_holder:visible').length == 0) {\r\n jQuery('.wpi_yellow_notification').remove();\r\n }\r\n\r\n if(jQuery('.wpi_red_notification .wpi_message_holder:visible').length == 0) {\r\n jQuery('.wpi_red_notification').remove();\r\n }\r\n\r\n\r\n}",
"getMessageOdds() {\n return this.messageodds;\n }",
"async function getMissedMessages({state, commit, rootState}) {\n if (rootState.token && state.active) {\n try {\n Vue.set(state, 'isLoading', true)\n let lastIndexOffline = state.messages.reduceRight((result, value, index) => {\n if (result) {\n return result\n }\n if (value.__connectionStatus === 'offline') {\n result = index\n }\n return result\n }, 0)\n let params = {\n from: !lastIndexOffline ? 0 : Math.floor(state.messages[lastIndexOffline - 1].timestamp) + 1,\n to: Math.floor(state.messages[lastIndexOffline + 1].timestamp)\n }\n let resp = await Vue.connector.gw.getDevicesMessages(state.active, {data: JSON.stringify(params)})\n let data = resp.data\n errorsCheck(data)\n commit('setMissingMessages', {data: data.result, index: lastIndexOffline})\n Vue.set(state, 'isLoading', false)\n }\n catch (e) {\n errorHandler && errorHandler(e)\n if (DEV) { console.log(e) }\n Vue.set(state, 'isLoading', false)\n }\n }\n }",
"function getClusterMessages(feature) {\n var messages = [];\n for (var i = 0; i < feature.cluster.length; i++) {\n var msi = feature.cluster[i].attributes.msi;\n if ($.inArray(msi, messages) == -1 && !feature.cluster[i].attributes.bg) {\n messages.push(msi);\n }\n }\n return messages;\n }",
"function getUnread() {\n unreadMsgs = [];\n animDelay = 1;\n \n var request = gapi.client.gmail.users.messages.list({\n 'userId': 'me',\n 'labelIds': 'UNREAD',\n 'maxResults': 20\n });\n\n request.execute(function(response) {\n //null response.messages means no new messages\n if(response.messages != null) {\n envelopePaper = Raphael(windowWidth/8, windowHeight/3, 0.625*windowWidth, windowHeight/2);\n envelopesShowing=true;\n var promises = [];\n $.each(response.messages, function() {\n var messageRequest = gapi.client.gmail.users.messages.get({\n 'userId': 'me',\n 'id': this.id\n });\n // Gmail API is asyncronous, so wrap all server responses in a Promise.all()\n var promise = $.Deferred();\n promises.push(promise);\n messageRequest.execute(function(message) {\n // Save the message in a collection \n unreadMsgs.push(message);\n promise.resolve(message);\n });\n });\n Promise.all(promises).then(function(messages) {\n // Sort messages by date in descending order\n messages.sort(compareMessages); //unreadMsgs\n\n // Finally, process the messages\n messages.forEach(function(message){\n handleUnread(message);\n });\n });\n createX();\n } else {\n showSnackbar(\"0 unread emails.\");\n }\n });\n}",
"function msgtype(msg)\n{\n const MSGTYPE_xre = `^ (?: ${ANSI_COLOR(true)} )* (?<label> \\\\[ [^\\\\]]+ \\\\] )`.XRE(); //allow nested colors at start\n const parts = tostr(msg).match(MSGTYPE_xre); // /^\\[[^\\]]+\\]/); //check for msg label/type\n return (parts || {}).label;\n}",
"function getNetworkWarnings()\n{\n\t// Remove outdated messages\n\tfor (let guid in g_NetworkWarnings)\n\t\tif (Date.now() > g_NetworkWarnings[guid].added + g_NetworkWarningTimeout ||\n\t\t guid != \"server\" && !g_PlayerAssignments[guid])\n\t\t\tdelete g_NetworkWarnings[guid];\n\n\t// Show local messages first\n\tlet guids = Object.keys(g_NetworkWarnings).sort(guid => guid != \"server\");\n\n\tlet font = Engine.GetGUIObjectByName(\"gameStateNotifications\").font;\n\n\tlet messages = [];\n\tlet maxTextWidth = 0;\n\n\tfor (let guid of guids)\n\t{\n\t\tlet msg = g_NetworkWarnings[guid].msg;\n\n\t\t// Add formatted text\n\t\tmessages.push(g_NetworkWarningTexts[msg.warntype](msg, colorizePlayernameByGUID(guid)));\n\n\t\t// Add width of unformatted text\n\t\tlet username = guid != \"server\" && g_PlayerAssignments[guid].name;\n\t\tlet textWidth = Engine.GetTextWidth(font, g_NetworkWarningTexts[msg.warntype](msg, username));\n\t\tmaxTextWidth = Math.max(textWidth, maxTextWidth);\n\t}\n\n\treturn {\n\t\t\"messages\": messages,\n\t\t\"maxTextWidth\": maxTextWidth\n\t};\n}",
"showMessageStatus(color, message) {\n $(\"#request-status\").css(\"color\", color);\n $(\"#request-status\").html(message);\n }",
"function doParseMessages(){\n var msgs = $x('//td[@class=\"message_body\"]');\n if(msgs && msgs.length > 0){\n for (var i = 0, iLength=msgs.length; i < iLength; ++i){\n // Log Minipack kick-off\n if(/Mini[\\s\\w]+Buff/i.test(msgs[i].innerHTML)){\n addToLog('yeah Icon', msgs[i].innerHTML);\n setGMTime('miniPackTimer', '8 hours');\n break;\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save textbox when enter is pressed. | function saveOnEnter(e) {
codeReporter("saveOnEnter()");
e.preventDefault();
var box = ($(e.target).attr('id') ? $(e.target) : $(e.target).parent());
// Grab the current value of the textarea.
var new_text = box.find("textarea").val();
// Empty the current contents of the box.
box.empty();
// Write the new text to the box.
box.css("background-color", "white");
box.text(new_text);
flash_saved(box);
} | [
"function inputPressEnter(e) {\n \n if (e.which === 13) {\n\n var editedItem = $(this).parent().find('.editText').val();\n $(this).hide();\n $(this).parent().find('.editText').hide();\n $(this).parent().find('.newText').text(editedItem);\n $(this).parent().find('.newText').show();\n $(this).parent().find('.editButton').hide();\n $('.editText').focus();\n \n }; \n }",
"function enterKey (event) {\n var code = event.charCode || event.keyCode;\n if (code === 13) {\n textInputArea.value = \"\";\n }\n}",
"function finishEdit(event) {\n var updatedTooth = $(this).data('tooth');\n if (event.which === 13) {\n updatedTooth.text = $(this)\n .children('input')\n .val()\n .trim();\n $(this).blur();\n updateTooth(updatedTooth);\n }\n }",
"function finishEdit() {\n var updatedReview = $(this).data(\"review\");\n if (event.keyCode === 13) {\n updatedReview.text = $(this).children(\"input\").val().trim();\n $(this).blur();\n updateReview(updatedReview);\n }\n }",
"function handleSaveKeys(event) {\n if (event.which === 13) { // 13 = enter key.\n saveState();\n }\n else {\n updateSaveButton();\n }\n}",
"function finishEdit(event) {\n var updatedActivity = $(this).data(\"activity\");\n if (event.which === 13) {\n updatedActivity.text = $(this).children(\"input\").val().trim();\n $(this).blur();\n updateActivity(updatedActivity);\n }\n }",
"function finishEdit(event) {\n var updatedJoke = $(this).data(\"joke-list\");\n if (event.which === 13) {\n updatedJoke.text = $(this).children(\"input\").val().trim();\n $(this).blur();\n updateJoke(updatedJoke);\n }\n }",
"function saveOnEnter (event) {\n if (event.keyCode === 13 &&\n $('#saveTemplate .btn-success').is(':enabled')) {\n $scope.saveTemplate();\n }\n }",
"function enter_pressed(e){if(e.keyCode==13){oraculo();}}",
"function saveOnKeyDown(eventParameter) {\n\tvar eventObject = window.event? event : eventParameter;\n\tif (eventObject.keyCode == 13 && eventObject.ctrlKey) {\n\t\tdocument.getElementById('tx-lfeditor-button-submit').click();\n\t}\n}",
"function searchEnterEvent(e)\r\n{\r\n\t// if press enter in textbox\r\n\tif(e.keyCode == 13)\r\n\t\tloadData();\r\n}",
"function saveColumnText() {\n if (window.location.href.includes(\"settings\")) {\n // save text when enter pressed\n $(\".text-box\").keydown(function (event) {\n if (event.which == 13) {\n event.preventDefault();\n setColumnText(this.id, this.value);\n $(this).blur();\n }\n });\n // save text when clicking outside of text area\n $(\".text-box\").focusout(function (event) {\n event.preventDefault();\n setColumnText(this.id, this.value);\n });\n }\n}",
"function clickEnterToGet(i) {\n input[i].addEventListener(\"keypress\", function(e) {\n if(e.keyCode === ENTER_KEYCODE) {\n // get input text and display it none\n var inputText = input[i].value;\n input[i].style.display = \"none\";\n\n // set input text and display it to screen\n allIText[i].innerText = inputText;\n allIText[i].style.display = \"\";\n }\n }, false);\n }",
"textEnter() {}",
"function keypressHandler(e) {\r\n document.getElementById(\"status\").innerHTML = \"\";\r\n if(e.keyCode == 13) {\r\n saveOptions();\r\n }\r\n}",
"function finishEdit(event) {\n const pw = {};\n const $input = $(this).children(\"input\");\n pw.id = $(this).parent().attr(\"data-pw\");\n if (event.which === 13) {\n console.log(\"Enter pressed\");\n pw[$input.attr(\"name\")] = $input.val().trim();\n console.log(pw);\n $(this).blur();\n updatePw(pw);\n }\n }",
"function finishEdit(event) {\n var updatedProduct = $(this).data(\"product\");\n if (event.which === 13) {\n updatedProduct.text = $(this).children(\"input\").val().trim();\n $(this).blur();\n updateProduct(updatedProduct);\n }\n }",
"onKeyUp(ev) {\n // check if 'Enter' was pressed\n if (ev.code === 'Enter') {\n ChromeGA.event(ChromeGA.EVENT.TEXT, this.name);\n this.fireEvent('setting-text-changed', this.value);\n }\n }",
"function finishEdit(event) {\n var updatedBand;\n if (event.key === \"Enter\") {\n updatedBand = {\n id: $(this).data(\"todo\").id,\n text: $(this).children(\"input\").val().trim()\n };\n $(this).blur();\n updateBand(updatedBand);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push the specified item onto the specified list if it is not already there. | function pushIfNotPresent(item, list) {
for (var j = 0; j < list.length; j++) {
if (item === list[j]) {
return;
}
}
list.push(item);
} | [
"function addItem(array, item) {\n if (!array.contains(item))\n array.push(item);\n }",
"function add(array, item){\n if(!contains(array, item)){\n array.push(item);\n array[array.length] = item;\n \n // var bla = [item];\n // array.concat(bla);\n } \n}",
"function add(array, item) {\n if (array && array.indexOf(item) === -1) {\n //array[array.length] = item;\n array.push(item);\n }\n}",
"add( item ) {\n // Add the item to the list, get its key.\n const key = this._updateMap( item );\n // Find the first item on the list whose key is >= than the item's key.\n const idx = this.findIndex( item => this._key( item ) >= key );\n // If an item was found...\n if( idx > -1 ) {\n // ...and if the found item shares the same key...\n if( this._key( this[idx] ) === key ) {\n // ...then replace the item.\n this[idx] = item;\n }\n // ...else insert the new item before the found item.\n else this.splice( idx, 0, item );\n }\n // ...else no key found >= current key, append new item to end of list.\n else super.push( item );\n }",
"function _add_permanently_to(stack, item_or_list){\n\tif( item_or_list && tcache[stack] ){\n\t if( ! us.isArray(item_or_list) ){ // atom\n\t\ttcache[stack].push(item_or_list);\n\t }else{ // list\n\t\ttcache[stack] = tcache[stack].concat(item_or_list);\n\t }\n\t}\n\treturn tcache[stack];\n }",
"function append(target, item) {\n if (Array.isArray(target)) {\n if (!target.includes(item)) {\n target.push(item);\n }\n }\n else {\n target.add(item);\n }\n return item;\n}",
"addItemToStack(newItem) {\n if (newItem == null) {\n return;\n }\n const index = this.itemStack.indexOf(newItem);\n if (index !== -1) this.itemStack.splice(index, 1);\n return this.itemStack.push(newItem);\n }",
"function addItem(list , item) {\n return list.concat(item)\n}",
"push(item) {\n this.items[this.top++] = item;\n this.len++;\n }",
"addItem(item) {\n // base case for adding to empty list or to list with start at 0\n if (!this.arr.length || !this.start) {\n this.arr.push(item);\n }\n // otherwise, add new item to right before start\n else {\n this.arr.splice(this.start, 0, item); // Learned how to insert anywhere in array at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\n this.start = this.start + 1;\n }\n }",
"function addItem(item) {\n var index = topBarItems.findIndex((x) => x.id === item.id);\n if (index === -1) {\n topBarItems.push(item);\n } else return;\n }",
"function appendTo(array, item) {\n\t return array.push(item), array;\n\t }",
"function appendTo(array, item) {\n return array.push(item), array;\n }",
"push(item) {\n\t\tthis.stack.push(item);\n\t}",
"pushItem(item) {\n $.each(this.shoppingItems, (i)=>{\n if(this.shoppingItems[i].article.id === item.article.id) {\n this.shoppingItems.splice(i,1);\n return false;\n }\n });\n this.shoppingItems.unshift(item);\n }",
"function appendTo(array, item) {\r\n return array.push(item), array;\r\n }",
"add(item) {\r\n this.emit(\"added\", this.list);\r\n if (item.includes(\"frozen\")) {\r\n this.emit(\"bringFreezerBag\", \"bring freezer bag!\");\r\n }\r\n if (item.includes(\"computer\")) {\r\n this.emit(\"error\", new Error(\"Sorry we only sell food!\"));\r\n return;\r\n }\r\n this.list = [...this.list, item];\r\n }",
"function arrayPush(array, item) {\n\n}",
"function addOrRemove(arr, item, add) {\n if(add) {\n arr.push(item);\n } else {\n removeItem(arr, item);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize Templates Does not save template parents and may not need to. | serializeTemplates(templates) {
let _this = this;
// Skip if template does not have filePath
if (!templates.getRootPath()) return BbPromise.resolve();
return BbPromise.try(function () {
// Validate: Check project path is set
if (!S.hasProject()) throw new SError('Templates could not be saved because no project path has been set on Serverless instance');
let tempaltesObj = templates.toObject()
if (_.isEmpty(tempaltesObj)) {
if (S.utils.fileExistsSync(templates.getFilePath())) {
return fs.unlinkAsync(templates.getFilePath());
}
} else {
return S.utils.writeFile(templates.getFilePath(), tempaltesObj);
}
})
.then(function () {
return templates;
});
} | [
"function serializeAndSaveSitecoreTemplates() { \n FileSystem.showSaveDialog(\"Save serialized Sitecore templates as...\", null, \"Untitled.json\", function (err, filename) {\n if (!err) {\n if (filename) {\n // save the file\n var file = FileSystem.getFileForPath(filename);\n var templates = generateJsonTemplates();\n var json = JSON.stringify(templates);\n \n // write the json to the file\n FileUtils.writeText(file, json, true)\n .done(function () {\n Dialogs.showInfoDialog(\"File saved successfully!\")\n })\n .fail(function (err) {\n console.error(err);\n Dialogs.showErrorDialog(\"Uh oh! An error occurred while saving. See the DevTools console for details.\");\n return;\n }); \n } else { // User canceled\n return; \n }\n } else {\n console.error(err);\n Dialogs.showErrorDialog(\"Uh oh! An error occurred while saving the serialized Sitecore templates. See the DevTools console for more information\");\n }\n }); \n }",
"function saveStoredTemplates() {\n localStorage[\"templateArray\"] = JSON.stringify(templateArray);\n}",
"function serializeTemplate(template,options) {\r\n var buildObjectsText = template.buildObjectsText;\r\n var decodeFunctionsText = template.decodeFunctionsText;\r\n var encodeFunctionsText = template.encodeFunctionsText;\r\n \r\n //var dataToSend = {\"type\":\"unpack\",\"template\":\"object1\"};\r\n var rawTemplate = {numbers:[], strings:[], booleans:[], nulls:[]};\r\n\r\n //save the options that were used to serialize so we can correctly deserialize\r\n if (typeof options != \"object\") {\r\n options = {};\r\n }\r\n rawTemplate.strings.push(JSON.stringify(options));\r\n\r\n //dataToSend[\"buildObjectsCount\"] = buildObjectsText.length;\r\n rawTemplate.numbers.push(buildObjectsText.length);\r\n for (var i=0; i<buildObjectsText.length; i++) {\r\n //dataToSend[\"structure_\" + i] = buildObjectsText[i];\r\n rawTemplate.strings.push(buildObjectsText[i]);\r\n }\r\n\r\n //dataToSend[\"decodeFunctionCount\"] = decodeFunctionsText.length; \r\n rawTemplate.numbers.push(decodeFunctionsText.length);\r\n for (var i=0; i<decodeFunctionsText.length; i++) {\r\n //dataToSend[\"decode_\" + i] = decodeFunctionsText[i];\r\n rawTemplate.strings.push(decodeFunctionsText[i]);\r\n }\r\n\r\n //dataToSend[\"encodeFunctionCount\"] = encodeFunctionsText.length; \r\n rawTemplate.numbers.push(encodeFunctionsText.length);\r\n for (var i=0; i<encodeFunctionsText.length; i++) {\r\n //dataToSend[\"encode_\" + i] = encodeFunctionsText[i];\r\n rawTemplate.strings.push(encodeFunctionsText[i]);\r\n }\r\n\r\n if (options.encodeValues) {\r\n rawTemplate.numbers = rawTemplate.numbers.concat(template.typeValues.numbers);\r\n rawTemplate.strings = rawTemplate.strings.concat(template.typeValues.strings);\r\n rawTemplate.booleans = rawTemplate.booleans.concat(template.typeValues.booleans);\r\n rawTemplate.nulls = rawTemplate.nulls.concat(template.typeValues.nulls);\r\n }\r\n\r\n return(rawTemplate);\r\n}",
"function saveAllTraits(templateObject) {\n\tif(templateObject){\n\t\tif(!templateObject.id) {\n\t\t\ttemplateObject.id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n\t \t\tvar r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);\n\t \t\treturn v.toString(16);\n\t\t\t});\n\t\t\t//Add new build\n\t\t\tif(!window.templates) {\n\t\t\t\twindow.templates = [];\n\t\t\t\twindow.templates[0] = templateObject;\n\t\t\t} else {\n\t\t\t\tvar length = window.templates.length;\n\t\t\t\twindow.templates[length] = templateObject;\n\t\t\t}\n\t\t} else {\n\t\t//ID is not new. Check to make sure to save over old copy\n\t\t\tfor(i=0; i<window.templates.length; i++) {\n\t\t\t\tif(window.templates[i].id === templateObject.id) window.templates[i] = templateObject;\n\t\t\t}\n\t\t}\n\t}\n\t//Save json object\n\tlocalStorage.setItem('gw2templates', JSON.stringify(window.templates));\n}",
"function generateJsonTemplates() {\n var SitecoreTemplateField = function(\n name, \n fieldType, \n sortOrder,\n title,\n source,\n standardValue,\n shared,\n unversioned,\n sectionName) {\n this.Name = name;\n this.FieldType = fieldType;\n this.SortOrder = sortOrder;\n this.Title = title;\n this.Source = source;\n this.StandardValue = standardValue;\n this.Shared = shared;\n this.Unversioned = unversioned;\n this.SectionName = sectionName;\n };\n \n var SitecoreTemplate = function(\n referenceId,\n name,\n fields,\n path,\n baseTemplates) {\n this.ReferenceId = referenceId;\n this.Name = name;\n this.Fields = fields;\n this.Path = path;\n this.BaseTemplates = baseTemplates;\n };\n\n // get the folders\n var umlPackages = Repository.select(\"@UMLPackage\");\n var sitecorePathMap = [];\n\n // recursively adds the folder and its ancestors to the path map\n var recursivelyBuildFolderPathMap = function (umlPackage) {\n var folderPath = sitecorePathMap[umlPackage._id];\n // if the folder path was already set then nothing more to do\n if (folderPath) {\n return folderPath;\n } \n \n // if there is no parent folder then make the folder path, store and return it\n if (!umlPackage._parent || umlPackage._parent.constructor.name != \"UMLPackage\") {\n // folder path should just be the current folder\n folderPath = \"/\" + umlPackage.name;\n // store the folder path\n sitecorePathMap[umlPackage._id] = folderPath;\n return folderPath;\n } else {\n // ensure the path was added for the parent\n recursivelyBuildFolderPathMap(umlPackage._parent);\n // add the path for the current folder to its parent's folder path\n sitecorePathMap[umlPackage._id] = \n sitecorePathMap[umlPackage._parent._id] + \"/\" + umlPackage.name;\n }\n };\n\n // populate the path map with the folder paths\n umlPackages.forEach(recursivelyBuildFolderPathMap);\n\n // get the templates\n var umlInterfaces = Repository.select(\"@UMLInterface\");\n\n var inheritanceMap = [];\n // get an array of sitecore templates\n var defaultFieldSectionName = SitecorePreferencesLoader.getSitecoreDeployDefaultFieldSectionName();\n var sitecoreTemplates = umlInterfaces.map(function(umlInterface, index) { \n var fields = umlInterface.attributes.map(function(attribute, index) { \n var field = new SitecoreTemplateField(\n attribute.name,\n attribute.type,\n index); \n\n try {\n var fieldAttributeMap = {}; \n attribute.ownedElements.forEach(function(element) {\n if (element instanceof type.Tag) {\n fieldAttributeMap[element.name] = element.value;\n }\n });\n\n field.Title = fieldAttributeMap[\"Title\"] || null;\n field.Source = fieldAttributeMap[\"Source\"] || null;\n field.Shared = fieldAttributeMap[\"Shared\"] || false; // by default, fields are not shared\n field.Unversioned = fieldAttributeMap[\"Unversioned\"] || false; // by default, fields are not shared\n field.SectionName = (fieldAttributeMap[\"SectionName\"] || \"\").trim() || defaultFieldSectionName; // fall back to the default name set in preferences\n field.StandardValue = fieldAttributeMap[\"StandardValue\"];\n } catch (e) {\n console.error(\"Eval error occurred while trying to retrieve the extended field info for \" + umlInterface.name + \"::\" + attribute.name, e);\n }\n\n return field;\n });\n\n // add inheriting templates to inheritance map\n umlInterface.ownedElements.forEach(function(ele) {\n if (inheritanceMap[ele.source._id]) {\n inheritanceMap[ele.source._id].push(ele.target._id);\n } else {\n inheritanceMap[ele.source._id] = [ ele.target._id ];\n }\n });\n\n // build the path to the template\n var parentPath = umlInterface._parent \n ? (sitecorePathMap[umlInterface._parent._id] || \"\")\n : \"\";\n var templatePath = parentPath + \"/\" + umlInterface.name;\n sitecorePathMap[umlInterface._id] = templatePath;\n \n return new SitecoreTemplate(\n umlInterface._id,\n umlInterface.name, \n fields,\n templatePath);\n });\n\n // add each template's base templates\n sitecoreTemplates = sitecoreTemplates.map(function(sitecoreTemplate) {\n var baseTemplateReferences = inheritanceMap[sitecoreTemplate.ReferenceId];\n if (baseTemplateReferences) {\n var baseTemplates = baseTemplateReferences.map(function(referenceId) {\n return sitecorePathMap[referenceId];\n });\n sitecoreTemplate.BaseTemplates = baseTemplates;\n }\n\n return sitecoreTemplate;\n });\n\n // write the sitecore templates to the console for debugging purposes\n console.log(sitecoreTemplates);\n\n return sitecoreTemplates;\n }",
"getTemplates() {\n return _.cloneDeep(this.templates ? this.templates : {});\n }",
"function serializeAndValidateSitecoreTemplates() {\n var templates = SitecoreTemplatesJsonGenerator_get().generateJsonTemplates();\n var json = JSON.stringify(templates);\n \n var sitecoreUrl = SitecorePreferencesLoader_get().getSitecoreUrl();\n var validateRoute = SitecorePreferencesLoader_get().getSitecoreValidateRoute();\n \n sitecoreUrl = sitecoreUrl.lastIndexOf(\"/\") == sitecoreUrl.length - 1 \n ? sitecoreUrl.substr(0, sitecoreUrl.length - 1) \n : sitecoreUrl;\n validateRoute = validateRoute.indexOf(\"/\") == 0 \n ? validateRoute \n : \"/\" + validateRoute;\n\n var postUrl = sitecoreUrl + validateRoute;\n $.ajax(\n postUrl, \n {\n method: \"POST\",\n data: json,\n cache: false,\n contentType: \"application/json; charset=utf-8\",\n complete: function(data) { \n var responseJson = JSON.parse(JSON.parse(data.responseText)); \n \n var errorMessageHtml = \"\";\n if (responseJson.InvalidTemplateFieldTypes.length) { \n errorMessageHtml += getInvalidFieldTypesHtml(responseJson.InvalidTemplateFieldTypes);\n }\n if (responseJson.InvalidItemNames.length) {\n errorMessageHtml += getInvalidItemNamesHtml(responseJson.InvalidItemNames);\n }\n\n if (errorMessageHtml) { \n Dialogs_get().showErrorDialog(errorMessageHtml); \n } else { \n Dialogs_get().showAlertDialog(\"No validation errors detected!\");\n }\n }\n })\n .fail(function(jqXHR, textStatus, errorThrown) {\n console.error(\"Validation Errore: \", errorThrown, textStatus, jqXHR);\n Dialogs_get().showErrorDialog(\"Uh oh! An error occurred while validating the Sitecore templates. See the DevTools console for more details.\");\n return;\n });\n }",
"saveTemplates(callback){\n var fs = require('fs')\n var file = __dirname + '/../assets/data/templates.json'\n fs.writeFile(file, JSON.stringify(this.templates), function(err) {\n if(err) {\n return callback(err)\n }\n else{\n return callback(undefined, true)\n }\n })\n }",
"_save(fullyTemplates, callback) {\n const data = {}\n data[this.STORAGE_KEY_TEMPLATE] = fullyTemplates\n\n this.set(data, callback)\n }",
"function templatesToString(templates) {\n if (templates) {\n for (let templateName in templates) {\n let Template = templates[templateName]\n let isReactComp = String(Template).includes(\"jsxRuntime\")\n if (isReactComp)\n templates[templateName] = (...props) => renderToStaticMarkup(<Template props={props} />)\n }\n }\n}",
"function createTemplates( root )\n {\n var templates = [];\n var queue = [];\n var node;\n var template;\n var cur;\n var i;\n var key;\n var numChildren;\n\n root.templateIndex = 0;\n\n for ( key in root.children ) {\n if ( Object.hasOwnProperty.call( root.children, key ) ) {\n queue.push( root.children[key] );\n }\n }\n\n // while queue not empty\n while( queue.length > 0 ) {\n // remove a ode from the queue,\n node = queue.shift();\n numChildren = 0;\n\n // add its children to the queue.\n for ( key in node.children ) {\n if ( Object.hasOwnProperty.call( node.children, key ) ) {\n queue.push( node.children[key] );\n numChildren += 1;\n }\n }\n\n // if the node had more than one child, or it has links,\n if ( numChildren > 1 || node.links.length > 0 ) {\n template = [];\n cur = node;\n\n // follow the path up from the node until one with a template\n // id is reached.\n while( cur.templateIndex === null ) {\n template.unshift( cur.key );\n cur = cur.parent;\n }\n\n template.unshift( cur.templateIndex );\n\n templates.push( template );\n node.templateIndex = templates.length;\n\n for( i = 0; i < node.links.length; i++ ) {\n node.links[i][\"\"].unshift( node.templateIndex );\n }\n }\n }\n\n return templates;\n }",
"parseTemplates() {\n var self = this;\n var templates = this.view.find('[data-view-templates]');\n templates.find('[data-view-template-wrapper]').each(function(){\n var twrapper = $(this);\n self.templates[twrapper.data('view-template-name')] = twrapper.html();\n })\n .remove();\n }",
"function serializeFormTemplate($form){\r\n\tvar envelope={'template':{\r\n\t 'data':[]\r\n\t}};\r\n\t// get all the inputs into an array.\r\n var $inputs = $form.children(\"input\"),\r\n $selects = $form.children(\"select\");\r\n\r\n $inputs.each(function(){\r\n \tvar data = {};\r\n data.name = this.name;\r\n \tdata.value = $(this).val();\r\n \tenvelope.template.data.push(data);\r\n });\r\n\r\n $selects.each(function(){\r\n \tvar data = {};\r\n data.name = this.name;\r\n \tdata.value = this.value;\r\n \tenvelope.template.data.push(data);\r\n });\r\n return envelope;\r\n\r\n}",
"function createTableTemplates() {\n\t/*\n\t * Initialize the codes (from the xml in templates, the names in xml, and the transcription to cover all information)\n\t */\n\tvar done = {};\n\tif (trjs.data.codesxml) {\n\t\t/*\n\t\t * if template exists\n\t\t */\n\t\tfor (var i=0 ; i < trjs.data.codesxml.length; i++) {\n\t\t\tdone[trjs.data.codesxml[i][\"code\"]] = true;\n\t\t}\n\t} else {\n trjs.data.codesxml = {}; // creates it\n }\n\n\t/*\n\t * Initialize now codesxml with data from transcription if missing information.\n\t */\n\tfor (var i in trjs.data.codesdata) {\n\t\tif (done[i] !== true)\n trjs.data.codesxml.push({\n\t\t\t\t'code': i,\n\t\t\t\t'type': '-',\n\t\t\t\t'parent': 'none',\n\t\t\t\t'description': '',\n\t\t\t});\n\t}\n\n\t/*\n\t * Initialize the tiers (from the xml in templates, and the transcription to cover all information)\n\t */\n\tdone = {};\n\n\tif (trjs.data.tiersxml) {\n\t\t/*\n\t\t * if template exists\n\t\t */\n\t\tfor (var i=0 ; i < trjs.data.tiersxml.length; i++) {\n\t\t\tvar code = trjs.data.tiersxml[i][\"code\"];\n\t\t\tdone[code] = true;\n\t\t}\n\t} else {\n trjs.data.tiersxml = {};\n }\n\t/*\n\t * Initialize now pdata with data from transcription if missing information.\n\t */\n\tfor (var i in trjs.data.tiersdata) {\n\t\tif (done[i] !== true)\n trjs.data.tiersxml.push({\n\t\t\t\t'code': i,\n\t\t\t\t'type': trjs.data.ASSOC,\n\t\t\t\t'parent': 'main',\n\t\t\t\t'description': '',\n\t\t\t});\n\t}\n}",
"function collectTemplates() {\n\t\tvar templates = {};\n\n\t\t$('script[type=\"text/template\"]').each(function (i, el) {\n\t\t\tvar id = Framework.Util.el2id(el, true);\n\t\t\ttemplates[id] = $(el).html();\n\n\t\t\t// Strip whitespace leftover from script tags\n\t\t\ttemplates[id] = templates[id].replace(/^\\s+/,'');\n\t\t\ttemplates[id] = templates[id].replace(/\\s+$/,'');\n\n\t\t\t// Remove from DOM\n\t\t\t$(el).remove();\n\t\t});\n\n\t\treturn templates;\n\t}",
"function resetTemplates()\n\t{\n\t\tprocessed_templates = {};\n\t}",
"function serializeFormTemplate($form){\n\tvar envelope={'template':{\n\t\t\t\t\t\t\t\t'data':[]\n\t}};\n\t// get all the inputs into an array.\n var $inputs = $form.children(\"input\");\n $inputs.each(function(){\n \tvar _data = {};\n \t_data.name = this.name;\n \t_data.value = $(this).val();\n \tenvelope.template.data.push(_data);\n });\n return envelope;\n\n}",
"function _hydrateAndRenderBodyTemplate() {\n const reverse = new Reverse();\n const template = new Template(\n reverse.templateName, \n reverse.parentBlock,\n reverse.data, \n );\n\n const render = new RenderLocalTemplate();\n render.render(template);\n}",
"initTemplates(tedata) {\n\t\tif (tedata.resources.hasOwnProperty('count') && tedata.resources.count > 0) {\n\t\t\tfor (let i = tedata.resources.count - 1; i >= 0; i--) {\n\t\t\t\tlet strID = GameObject.idToStringNumber(i+1)\n\t\t\t\tif (tedata.resources.hasOwnProperty('RESOURCE_'+strID)) {\n\t\t\t\t\tthis.templateEntities.resources['RESOURCE_'+strID] = tedata.resources['RESOURCE_'+strID]\n\t\t\t\t} else {throw new Error(\"initTemplates: RESOURCE_\"+strID+\" is not a property.\")}\n\t\t\t}\n\t\t}\n\t\tif (tedata.resourcegroups.hasOwnProperty('count') && tedata.resourcegroups.count > 0) {\n\t\t\tfor (let i = tedata.resourcegroups.count - 1; i >= 0; i--) {\n\t\t\t\tlet strID = GameObject.idToStringNumber(i+1)\n\t\t\t\tif (tedata.resourcegroups.hasOwnProperty('RESOURCEGRP_'+strID)) {\n\t\t\t\t\tthis.templateEntities.resourcegroups['RESOURCEGRP_'+strID] = tedata.resourcegroups['RESOURCEGRP_'+strID]\n\t\t\t\t} else {throw new Error(\"initTemplates: RESOURCEGRP_\"+strID+\" is not a property.\")}\n\t\t\t}\n\t\t}\n\t\tconsole.log(this.templateEntities)\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
; public static const ISSUE_MODIFIER_WITH_LIST:BEMModifier = | function ISSUE_MODIFIER_WITH_LIST$static_(){IssuesPanelBase.ISSUE_MODIFIER_WITH_LIST=( IssuesPanelBase.ISSUE_BLOCK.createModifier("with-list"));} | [
"function ISSUE_ELEMENT_LIST$static_(){IssuesPanelBase.ISSUE_ELEMENT_LIST=( IssuesPanelBase.ISSUE_BLOCK.createElement(\"list\"));}",
"function __FIXME_SBean_assert_ignore_list() {\n\tthis._pname_ = \"assert_ignore_list\";\n\t//this.keywords:\t\tset[string]\t\n}",
"get format_list_bulleted () {\n return new IconData(0xe241, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }",
"static list() {\nvar i, ix, len, lgr, msg, ref;\nmsg = \"\";\nref = this._loggers;\nfor (ix = i = 0, len = ref.length; i < len; ix = ++i) {\nlgr = ref[ix];\nif (ix > 0) {\nmsg += \", \";\n}\nmsg += lgr.modName;\n}\nreturn msg;\n}",
"function Modifiers() {\n this.modTypes = [];\n}",
"function ISSUE_BLOCK$static_(){IssuesPanelBase.ISSUE_BLOCK=( new com.coremedia.ui.models.bem.BEMBlock(\"cm-issue\"));}",
"function DRAGGABLE_ITEM_MODIFIER_TODO_IN_PROGRESS$static_(){ProjectTodosPanel.DRAGGABLE_ITEM_MODIFIER_TODO_IN_PROGRESS=( com.coremedia.ui.components.DraggableItem.BLOCK.createModifier(\"todo-in-progress\"));}",
"static get modifiers(){\n throw new Error(\"Must be subclassed\");\n }",
"function listeNonDiffusableMNR(){\n return ['SALLES','RCL', 'NET', 'CARTELS'];\n}",
"static get legitExtensionIDs () {\n const sheetmonkeyExtensionIDDev = 'ffnljkjkjkjalaeioncbnbpfgnkohblm'\n const sheetmonkeyExtensionIDProd = 'gdnefhegodkfgopmjacoenelkfkbkkdg'\n return [sheetmonkeyExtensionIDDev, sheetmonkeyExtensionIDProd]\n }",
"getCustomListString() {\n this.generatePackingList();\n return this.arrayToBulletList(this.packingList);\n }",
"addModifier(mod, reason, list) {\n if (!!list) this.modifierStack._add(list, mod, reason)\n else this.modifierStack.add(mod, reason)\n this.refresh()\n }",
"function MODIFIER_DISABLED$static_(){IconWithTextBEMEntities.MODIFIER_DISABLED=( IconWithTextBEMEntities.BLOCK.createModifier(\"disabled\"));}",
"function methodDenyListPlugin() {\n const METHOD_DENY_LIST = ['requestUpdate', 'performUpdate', 'shouldUpdate', 'update', 'render', 'firstUpdated', 'updated', 'willUpdate'];\n\n return {\n moduleLinkPhase({moduleDoc}){\n const classes = moduleDoc?.declarations?.filter(declaration => declaration.kind === 'class');\n\n classes?.forEach(klass => {\n if(!klass?.members) return;\n klass.members = klass?.members?.filter(member => !METHOD_DENY_LIST.includes(member.name));\n });\n },\n }\n }",
"function memberDenyListPlugin() {\n const MEMBER_DENY_LIST = ['properties', 'styles'];\n\n return {\n moduleLinkPhase({moduleDoc}){\n const classes = moduleDoc?.declarations?.filter(declaration => declaration.kind === 'class');\n\n classes?.forEach(klass => {\n if(!klass?.members) return;\n klass.members = klass?.members?.filter(member => !MEMBER_DENY_LIST.includes(member.name));\n });\n },\n }\n }",
"function getExemptedModules(list) {\n return getModuleVersionMap(list, '###');\n}",
"static defineModifier() {\n let mod = new Modifier;\n return (tag) => {\n if (tag.modified.indexOf(mod) > -1)\n return tag;\n return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));\n };\n }",
"function LIST_MODIFIER_EMPTY$static_(){WidgetContentListBase.LIST_MODIFIER_EMPTY=( WidgetContentListBase.LIST_BLOCK.createModifier(\"empty\"));}",
"get format_list_numbered () {\n return new IconData(0xe242,{fontFamily:'MaterialIcons'})\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop song by setting the current time to 0 and pausing the song. | function stopSong(){
activeSong.currentTime = 0;
activeSong.pause();
} | [
"function stopSong() {\n activeSong.currentTime = 0;\n activeSong.pause();\n }",
"function stopSong(){\r\n activeSong.currentTime = 0;\r\n activeSong.pause();\r\n}",
"function stopSong() {\n\tpauseSong();\n\tinstance.setPosition(0);\n}",
"function stopSong(){\n $(\"#theme\")[0].pause();\n $(\"#theme\")[0].currentTime = 0;\n}",
"function stop() {\n _visualizations2.default.stop();\n\n /*\n Set the current time of the song to 0 which will reset the song.\n */\n if (_config2.default.audio.currentTime != 0) {\n _config2.default.audio.currentTime = 0;\n }\n\n /*\n Run pause so the song will stop\n */\n _config2.default.audio.pause();\n\n /*\n If the song is live, disconnect the stream.\n */\n if (_config2.default.active_metadata.live) {\n disconnectStream();\n }\n\n /*\n Run the stop callback\n */\n _callbacks2.default.run(\"stop\");\n }",
"function stopSong(){\n if(!audioElement.paused){\n audioElement.pause();\n audioElement.currentTime = 0;\n coinInserted=false;\n disableProgressBar(getPageSongIndex(currentSongIndex))\n playNext();\n }else{\n // showModal(\"No song playing now\"); \n console.log(\"no song to stop\");\n }\n}",
"stop() {\n // The HTML5 audio player only has a pause(), no stop().\n // To differentiate between the two, set a flag.\n this.sound.pause();\n this.sound.currentTime = 0;\n }",
"function stop(){\n\t\t/*\n\t\t\tRuns the before stop callback.\n\t\t*/\n\t\tAmplitudeHelpers.runCallback('before_stop');\n\n\t\t/*\n\t\t\tSet the current time of the song to 0 which will reset the song.\n\t\t*/\n\t\tif( config.active_song.currentTime != 0 ){\n\t\t\tconfig.active_song.currentTime = 0;\n\t\t}\n\n\t\t/*\n\t\t\tRun pause so the song will stop\n\t\t*/\n\t\tconfig.active_song.pause();\n\n\t\t/*\n\t\t\tIf the song is live, disconnect the stream.\n\t\t*/\n\t\tif( config.active_metadata.live ){\n\t\t\tdisconnectStream();\n\t\t}\n\n\t\t/*\n\t\t\tRun the after stop callback\n\t\t*/\n\t\tAmplitudeHelpers.runCallback('after_stop');\n\t}",
"stopTrack() {\n if (this.#playingTrack != null) {\n this.#playingTrack.pause();\n this.#playingTrack.currentTime = 0;\n this.#playingTrack = null;\n }\n }",
"function stop(){\n\t\tAmplitudeHelpers.runCallback('before_stop');\n\n\t\tif( config.active_song.currentTime != 0 ){\n\t\t\tconfig.active_song.currentTime = 0;\n\t\t}\n\n\t\tconfig.active_song.pause();\n\n\t\tif( config.active_metadata.live ){\n\t\t\tdisconnectStream();\n\t\t}\n\n\t\tAmplitudeHelpers.runCallback('after_stop');\n\t}",
"stop() {\n RNAudioStreamer.pause();\n //we've stopped playing\n this.isPlaying = false;\n RNAudioStreamer.setUrl('');\n this.currentAudio = null;\n this.currentTime = 0;\n this.setPlaybackProgress(0);\n this.alert_audioPlaybackTimeChange();\n if (this.currentTimeout) {\n clearTimeout(this.currentTimeout);\n }\n }",
"stop() {\n this.audioElement.pause();\n this.audioElement.currentTime = 0;\n }",
"pause() {\n if (this._stopwatch) {\n this._stopwatch.stop();\n }\n this._player.pause();\n }",
"stop() {\n this.pause();\n this._playingState = 'idle';\n this.index = 0;\n }",
"function playStop() {\n\n\t\tif (Amplitude.getSongPlayedPercentage()) {\n\t\t\tAmplitude.setSongPlayedPercentage(0);\n\t\t\tAmplitude.pause();\n\t\t}\n\n\t\tif (isRefreshDivs) clearDivs([options.mainArtist, options.mainSong]);\n\n\t\tif (isShuffle) setPlsShuffled();\n\n\t}",
"stop() {\n // The HTML5 audio player only has a pause(), no stop().\n // To differentiate between the two, set a flag.\n this._pauseIsStop = true;\n this.sound.pause();\n }",
"stop() {\n if (this._stopwatch) {\n this._stopwatch.reset();\n this._stopwatch.stop();\n }\n this._player.stop();\n }",
"stop() {\n this._isPlaying = false;\n this.sound.pause();\n }",
"function amplitude_stop_song(){\n\t//Before stop is called\n\tif( amplitude_active_config.amplitude_before_stop_callback ){\n\t\tvar amplitude_before_stop_callback_function = window[amplitude_active_config.amplitude_before_stop_callback];\n\t\tamplitude_before_stop_callback_function();\n\t}\n\n\tamplitude_active_config.amplitude_active_song.currentTime = 0;\n\tamplitude_active_config.amplitude_active_song.pause();\n\n\tif(typeof amplitude_active_config.amplitude_active_song.live != 'undefined'){\n\t\tif( amplitude_active_config.amplitude_active_song.live ){\n\t\t\tamplitude_disconnect_stream();\n\t\t}\n\t}\n\n\t//After stop is called\n\tif( amplitude_active_config.amplitude_after_stop_callback ){\n\t\tvar amplitude_after_stop_callback_function = window[amplitude_active_config.amplitude_after_stop_callback];\n\t\tamplitude_after_stop_callback_function();\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Individual function to get suit | function getSuit() {
var s = document.querySelectorAll("input[name= 'suit']:checked")[0].getAttribute('value');
return cards[s][0];
} | [
"function pickCard(){ \r\n var suit = Math.round(Math.random()*3); \r\n if (suit === 0) suit = \"Hearts\"; \r\n else if (suit === 1) suit = \"Diamonds\"; \r\n else if (suit === 2) suit = \"Clubs\"; \r\n else suit = \"Spades\"; \r\n \r\n //your code here \r\n \r\n return suit; \r\n \r\n} \r\n \r\n// ANSWER: ",
"function getRandomSuit() {\n\tvar s = Math.floor((Math.random() * 3) + 0); \n\treturn cards[s][0];\n}",
"getSuit(suit){\n\t\tthis.cards = this.cards.filter(card=>card.suit == suit)\n\t}",
"getSuit(){\n\n\t\tif (this.suit=='Spades'){\n\t\t\treturn '♠';\n\t\t}\n\n\t\telse if (this.suit=='Hearts'){\n\t\t\treturn '♥';\n\t\t}\n\t\telse if (this.suit=='Diamonds'){\n\t\t\treturn '♦';\n\t\t}\n\n\t\telse if (this.suit=='Clubs'){\n\t\t\treturn'♣';\n\t\t}\n\n\n\t}",
"getSuit() {\n return this.#suit;\n }",
"function pickCard(){\n var suit = Math.round(Math.random()*4);\n if (suit === 0) suit = \"Hearts\";\n else if (suit === 1) suit = \"Diamonds\";\n else if (suit === 2) suit = \"Clubs\";\n else suit = \"Spades\";\n\n //your code here\n\tvar num = Math.floor(Math.random()*13) +1;\n\tif (num == 1) {return \"Ace of \" + suit}\n\tif (num == 11) {return \"Jack of \" + suit}\n\tif (num == 12) {return \"Queen of \" + suit}\n\tif (num == 13) {return \"King of \" + suit}\n \treturn num + \" of \" + suit;\n}",
"function getCard(values, suits) {\n const randomVal = choice(values);\n const randomSuit = choice(suits);\n return randomVal + randomSuit;\n}",
"function cardSuit(number) { return SUITS[Math.floor((number-1)/13)]; }",
"function suit(cardId) {\n\n var fl = Math.floor(cardId / 13);\n \n if (fl == 0) {\n return 'C';\n } \n else if (fl == 1) {\n return 'D';\n }\n else if (fl == 2) {\n return 'H';\n }\n else {\n return 'S';\n }\n\n return false;\n}",
"function getDeck() {\n console.log(getDeck.name);\n var deck = [\n // Cards with Hearts suit\n {suit: \"H\", face: \"A\"},\n {suit: \"H\", face: 2},\n {suit: \"H\", face: 3},\n {suit: \"H\", face: 4},\n {suit: \"H\", face: 5},\n {suit: \"H\", face: 6},\n {suit: \"H\", face: 7},\n {suit: \"H\", face: 8},\n {suit: \"H\", face: 9},\n {suit: \"H\", face: 10},\n {suit: \"H\", face: \"J\"},\n {suit: \"H\", face: \"Q\"},\n {suit: \"H\", face: \"K\"},\n\n // Cards with Spades suit\n {suit: \"S\", face: \"A\"},\n {suit: \"S\", face: 2},\n {suit: \"S\", face: 3},\n {suit: \"S\", face: 4},\n {suit: \"S\", face: 5},\n {suit: \"S\", face: 6},\n {suit: \"S\", face: 7},\n {suit: \"S\", face: 8},\n {suit: \"S\", face: 9},\n {suit: \"S\", face: 10},\n {suit: \"S\", face: \"J\"},\n {suit: \"S\", face: \"Q\"},\n {suit: \"S\", face: \"K\"},\n\n // Cards with Diamonds suit\n {suit: \"D\", face: \"A\"},\n {suit: \"D\", face: 2},\n {suit: \"D\", face: 3},\n {suit: \"D\", face: 4},\n {suit: \"D\", face: 5},\n {suit: \"D\", face: 6},\n {suit: \"D\", face: 7},\n {suit: \"D\", face: 8},\n {suit: \"D\", face: 9},\n {suit: \"D\", face: 10},\n {suit: \"D\", face: \"J\"},\n {suit: \"D\", face: \"Q\"},\n {suit: \"D\", face: \"K\"},\n\n // Cards with Clubs suit\n {suit: \"C\", face: \"A\"},\n {suit: \"C\", face: 2},\n {suit: \"C\", face: 3},\n {suit: \"C\", face: 4},\n {suit: \"C\", face: 5},\n {suit: \"C\", face: 6},\n {suit: \"C\", face: 7},\n {suit: \"C\", face: 8},\n {suit: \"C\", face: 9},\n {suit: \"C\", face: 10},\n {suit: \"C\", face: \"J\"},\n {suit: \"C\", face: \"Q\"},\n {suit: \"C\", face: \"K\"}\n ];\n return deck;\n}",
"function pickCard() {\n var suit = Math.round(Math.random() * 3);\n if (suit === 0) suit = \"Hearts\";\n else if (suit === 1) suit = \"Diamonds\";\n else if (suit === 2) suit = \"Clubs\";\n else suit = \"Spades\";\n\n //your code here\n var rank = Math.ceil(Math.random() * 13);\n if (rank === 1) rank = \"Ace\";\n if (rank === 2) rank = \"2\";\n if (rank === 3) rank = \"3\";\n if (rank === 4) rank = \"4\";\n if (rank === 5) rank = \"5\";\n if (rank === 6) rank = \"6\";\n if (rank === 7) rank = \"7\";\n if (rank === 8) rank = \"8\";\n if (rank === 9) rank = \"9\";\n if (rank === 10) rank = \"10\";\n if (rank === 11) rank = \"Jack\";\n if (rank === 12) rank = \"Queen\";\n if (rank === 13) rank = \"King\";\n\n return rank + \" of \" + suit;\n}",
"function computerCards() {\n giveCard('computer');\n giveCard('computer');\n}",
"function pickCard() {\n var suit = Math.round(Math.random() * 3);\n if (suit === 0) suit = \"Hearts\";\n else if (suit === 1) suit = \"Diamonds\";\n else if (suit === 2) suit = \"Clubs\";\n else suit = \"Spades\";\n\n var num = Math.round(Math.random() * 12 + 1)\n var card;\n if (num === 10) card = \"J\";\n else if (num === 11) card = \"Q\";\n else if (num === 12) card = \"K\";\n else if (num === 13) card = \"A\";\n else if (num < 10) card = num;\n\n return card + \" of \" + suit;\n\n}",
"isSuited() {\n let suites = this.hand.reduce((acc, card) => {\n card.suite === \"h\" ? ++acc.hearts :\n card.suite === \"c\" ? ++acc.clubs :\n card.suite === \"s\" ? ++acc.spades :\n ++acc.diamonds;\n return acc;\n }, {\n hearts: 0,\n clubs: 0,\n spades: 0,\n diamonds: 0\n });\n\t\t\n //only evalute if all the cards are the same suit\n return Object.values(suites).some(suite => suite > \"4\");\n }",
"translateSuitToEntityCode(){\nreturn this.suitObjects[`${this.randomSuitName0 }`];\n }",
"checkForSuit(suit) {\r\n\t\tif (typeof suit == 'number') suit = SUITS[suit];\r\n\t\telse if (typeof suit == 'string') {\r\n\t\t\tswitch (suit.toLowerCase()) {\r\n\t\t\t\tcase 'club': case 'clubs': case 'c': suit = 'Clubs'; break;\r\n\t\t\t\tcase 'diamond': case 'diamonds': case 'd': suit = 'Diamonds'; break;\r\n\t\t\t\tcase 'heart': case 'hearts': case 'h': suit = 'Hearts'; break;\r\n\t\t\t\tcase 'spade': case 'spades': case 's': suit = 'Spades'; break;\r\n\t\t\t\tcase '': return true;\r\n\t\t\t\tdefault: console.error('Invalid suit.'); return false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tconsole.error('Invalid suit.');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfor (let c of this.hand) \r\n\t\t\tif (cardSuit(c) == suit)\r\n\t\t\t\treturn true;\r\n\r\n\t\treturn false;\r\n\t}",
"function getSuitSymbol(suit) {\r\n\tswitch (suit) {\r\n\t\tcase \"diams\":\r\n\t\t\treturn \"♦\";\r\n\t\tcase \"hearts\":\r\n\t\t\treturn \"♥\"\r\n\t\tcase \"clubs\":\r\n\t\t\treturn \"♣\";\r\n\t\tcase \"spades\":\r\n\t\t\treturn \"♠\";\r\n\t\tdefault:\r\n\t\t\treturn \"\";\r\n\t}\r\n}",
"function getCardSuitValue (card) {\n\tvar suit = card.substring(0, 5);\n\t\n\tif (suit == SPADES) {\n\t\treturn 0;\n\t} else if (suit == HEARTS) {\n\t\treturn 1;\n\t} else if (suit == CLUBS) {\n\t\treturn 2;\n\t} else if (suit == DIAMONDS) {\n\t\treturn 3;\n\t} else {\n\t\treturn 4;\n\t}\n}",
"function seeAllCards() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the tx or send it to the blockchain based on user's config | async function printTxOrSend(call) {
if (program.opts().send) {
const { pair } = await useKey();
// const r = await call.signAndSend(pair, );
// How to specify {nonce: -1}?
const r = await new Promise(async (resolve, reject) => {
const unsub = await call.signAndSend(pair, (result) => {
if (result.status.isInBlock) {
let error;
for (const e of result.events) {
const { event: { data, method, section } } = e;
if (section === 'system' && method === 'ExtrinsicFailed') {
error = data[0];
}
}
unsub();
if (error) {
reject(error);
} else {
resolve({
hash: result.status.asInBlock.toHuman(),
events: result.toHuman().events,
});
}
} else if (result.status.isInvalid) {
unsub();
resolve();
reject('Invalid transaction');
}
});
});
printObject(r, 4);
} else {
console.log(call.toHex());
}
} | [
"async sendUtxo(utxo, sendToAddr, walletInfo, BITBOX) {\n try {\n //console.log(`utxo: ${util.inspect(utxo)}`)\n\n // instance of transaction builder\n if (walletInfo.network === `testnet`)\n var transactionBuilder = new BITBOX.TransactionBuilder(\"testnet\")\n else var transactionBuilder = new BITBOX.TransactionBuilder()\n\n const originalAmount = utxo.satoshis\n\n const vout = utxo.vout\n const txid = utxo.txid\n\n // add input with txid and index of vout\n transactionBuilder.addInput(txid, vout)\n\n // get byte count to calculate fee. paying 1 sat/byte\n const byteCount = BITBOX.BitcoinCash.getByteCount(\n { P2PKH: 1 },\n { P2PKH: 1 }\n )\n\n // Calculate the transaction fee\n const satoshisPerByte = 1.1\n const txFee = Math.floor(satoshisPerByte * byteCount)\n //console.log(`txFee: ${txFee} satoshis\\n`)\n\n // amount to send\n const satoshisToSend = originalAmount - txFee\n\n // add output w/ address and amount to send\n transactionBuilder.addOutput(\n BITBOX.Address.toLegacyAddress(sendToAddr),\n satoshisToSend\n )\n\n // Generate a keypair from the change address.\n const change = appUtil.changeAddrFromMnemonic(\n walletInfo,\n utxo.hdIndex,\n BITBOX\n )\n const keyPair = BITBOX.HDNode.toKeyPair(change)\n\n // Sign the transaction with the HD node.\n let redeemScript\n transactionBuilder.sign(\n 0,\n keyPair,\n redeemScript,\n transactionBuilder.hashTypes.SIGHASH_ALL,\n originalAmount\n )\n\n // build tx\n const tx = transactionBuilder.build()\n\n // output rawhex\n const hex = tx.toHex()\n //console.log(`Transaction raw hex: `)\n //console.log(hex)\n\n // sendRawTransaction to running BCH node\n const broadcast = await BITBOX.RawTransactions.sendRawTransaction(hex)\n //console.log(`Transaction ID: ${broadcast}`)\n return broadcast\n } catch (err) {\n console.log(`Error in sendUtxo()`)\n throw err\n }\n }",
"htmlCreateTransaction(){\n configs.rawtx == null;\n $('#commitTx').html(\"\");\n $('#rawtx').html(\"\");\n if (wallet == null) {showError(\"WalletNULL\", 2);}\n else {\n var destination = $('#txDestination').val();\n var amount = $('#txAmount').val();\n var passphrase = $('#txPassphrase').val();\n $('#rawtx').html(\"Creating a transaction send to \" + destination + \" \" + amount + \" SIN\");\n try {\n var tx = wallet.createTransaction(destination, amount, passphrase);\n passphrase = '';\n $('#passphrase').html(\"\");\n $('#txCreate').html(\"\");\n if (!tx){\n configs.rawtx = null;\n $('#commitTx').html(\"\");\n }else{\n configs.rawtx = tx;\n $('#txFee').html(bitcore.Unit.fromSatoshis(tx.getFee()).toBTC());\n $('#rawtx').html(tx.serialize());\n $('#commitTx').html(\"<button type=\\\"button\\\" id=\\\"txSend\\\" onclick=\\\"ui.htmlSendTransaction()\\\">Send</button>\");\n }\n } catch(e) {\n alert(e);\n configs.rawtx = null;\n $('#commitTx').html(\"\");\n }\n }\n }",
"async function netTransaction(callback){\n \n if(offChainBalanceUserA<=onChainBalanceUserA){\n amount=await Web3.utils.fromWei((onChainBalanceUserA-offChainBalanceUserA).toString(), 'ether')\n \n recipient= userB\n sender= userA\n }\n else{\n amount=await Web3.utils.fromWei((onChainBalanceUserB-offChainBalanceUserB).toString(), 'ether')\n \n recipient= userA\n sender= userB\n\n }\n\n callback()\n }",
"function printTxBase(tx = {}, tabs = '') {\n printUnderscored(`${tabs}Tx hash`, tx.hash);\n printUnderscored(`${tabs}Block hash`, tx.blockHash);\n printUnderscored(`${tabs}Block height`, tx.blockHeight);\n printUnderscored(`${tabs}Signatures`, tx.signatures);\n\n printUnderscored(`${tabs}Tx Type`, tx?.tx?.type ?? 'N/A');\n}",
"async createTx() {\n if (this.pendingTx) {\n await this.cb.call(this, \"error\", String(\"Waiting for pending transaction to be mined\"));\n return\n }\n await this.cb.call(this, \"wait\", \"Sending transacton\");\n for await (let txOut of this.txOuts) {\n try {\n switch (txOut.type) {\n case \"VS\":\n await this.wallet.Transaction.createValueStore(txOut.fromAddress, txOut.value, txOut.toAddress, txOut.bnCurve ? 2 : 1)\n break;;\n case \"DS\":\n await this.wallet.Transaction.createDataStore(txOut.fromAddress, txOut.index, txOut.duration, txOut.rawData)\n break;;\n default:\n throw new Error(\"Invalid TxOut type\");\n }\n }\n catch (ex) {\n this.txOuts = [];\n this.changeAddress = {};\n await this.wallet.Transaction._reset();\n await this.cb.call(this, \"error\", String(ex));\n return\n }\n }\n await this.sendTx();\n }",
"function handleTx(tx) {\n console.log('blockchain.info api: processing transaction ', tx.hash);\n\n // find a matching wallet\n for(var i=0; i<wallets.length; i++) {\n var wallet = wallets[i];\n var address = wallet.addresses[0];\n var utxos = [];\n\n // locate matching tx\n tx.out.forEach(function(out, i) {\n if(out.addr != address)\n return;\n\n utxos.push({\n hash: tx.hash,\n outputIndex: i,\n address: out.addr,\n value: out.value\n });\n });\n\n if(utxos.length > 0) {\n console.log(\"Balance before: \" + wallet.getBalance());\n //wallet.setUnspentOutputs(utxos);\n\n // build locally parseable transactions\n var btTx = new Bitcoin.Transaction();\n utxos.forEach(function(utxo) {\n btTx.addInput(tx.hash, utxo.outputIndex);\n btTx.addOutput(wallet.addresses[0], utxo.value);\n });\n\n // process in the wallet\n wallet.processConfirmedTx(btTx);\n console.log(\"Balance after: \" + wallet.getBalance());\n\n // save the transactions to the database for future processing\n DAO.addUnspentTxOutputs(utxos);\n\n // notify any currently watching UIs\n notifyUpdate(address);\n\n break;\n }\n }\n }",
"function accountTransactionsDisplay(userAccount) {\n\tconsole.log(view.separateLine);\n\tconsole.log(view.requestTransactionsHeader);\n\tdisplayTransactions(userAccount);\n\n\t// Return to transaction menu when done\n\ttransactionMenu(userAccount);\n}",
"async sendTransaction(txn) {\n if (this.wallet.options.rpcServerAddr) {\n try {\n return await _wallet.default.sendTransaction(txn, this.wallet.options);\n } catch (e) {}\n }\n\n return await _wallet.default.sendTransaction(txn, this.options);\n }",
"async function testWalletTx(tx, testConfig) {\n \n // validate / sanitize inputs\n testConfig = Object.assign({}, testConfig);\n delete testConfig.wallet; // TODO: re-enable\n if (!(tx instanceof MoneroWalletTx)) {\n console.log(\"TX is not a MoneroWalletTx!\");\n console.log(tx);\n }\n assert(tx instanceof MoneroWalletTx);\n testConfig = Object.assign({}, testConfig);\n if (testConfig.wallet) assert (testConfig.wallet instanceof MoneroWallet);\n assert(testConfig.hasDestinations == undefined || typeof config.hasDestinations === \"boolean\");\n \n // test common field types\n testWalletTxTypes(tx);\n \n // test confirmed\n if (tx.getIsConfirmed()) {\n assert(tx.getBlock());\n assert(tx.getBlock().getTxs().includes(tx));\n assert(tx.getBlock().getHeader().getHeight() > 0);\n assert(tx.getBlock().getHeader().getTimestamp() > 0);\n assert.equal(tx.getIsRelayed(), true);\n assert.equal(tx.getIsFailed(), false);\n assert.equal(tx.getInTxPool(), false);\n assert.equal(tx.getDoNotRelay(), false);\n assert(tx.getNumConfirmations() > 0);\n assert.equal(tx.getIsDoubleSpend(), false);\n } else {\n assert.equal(tx.getBlock(), undefined);\n assert.equal(tx.getNumConfirmations(), 0);\n }\n \n // test in tx pool\n if (tx.getInTxPool()) {\n assert.equal(tx.getIsConfirmed(), false);\n assert.equal(tx.getDoNotRelay(), false);\n assert.equal(tx.getIsRelayed(), true);\n assert.equal(tx.getIsDoubleSpend(), false); // TODO: test double spend attempt\n assert.equal(tx.getLastFailedHeight(), undefined);\n assert.equal(tx.getLastFailedId(), undefined);\n \n // these should be initialized unless a response from sending\n if (!testConfig.sendConfig) {\n assert(tx.getReceivedTimestamp() > 0);\n tx.getNumEstimatedBlocksUntilConfirmed() > 0\n }\n } else {\n assert.equal(tx.getNumEstimatedBlocksUntilConfirmed(), undefined);\n assert.equal(tx.getLastRelayedTimestamp(), undefined);\n }\n \n // test coinbase tx\n if (tx.getIsCoinbase()) {\n assert.equal(tx.getFee().compare(new BigInteger(0)), 0);\n assert(tx.getIncomingTransfers().length > 0);\n }\n \n // test failed // TODO: what else to test associated with failed\n if (tx.getIsFailed()) {\n assert(tx.getOutgoingTransfer() instanceof MoneroTransfer);\n assert(tx.getReceivedTimestamp() > 0)\n } else {\n if (tx.getIsRelayed()) assert.equal(tx.getIsDoubleSpend(), false);\n else {\n assert.equal(tx.getIsRelayed(), false);\n assert.equal(tx.getDoNotRelay(), true);\n assert.equal(tx.getIsDoubleSpend(), undefined);\n }\n }\n assert.equal(tx.getLastFailedHeight(), undefined);\n assert.equal(tx.getLastFailedId(), undefined);\n \n // received time only for tx pool or failed txs\n if (tx.getReceivedTimestamp() !== undefined) {\n assert(tx.getInTxPool() || tx.getIsFailed());\n }\n \n // test relayed tx\n if (tx.getIsRelayed()) assert.equal(tx.getDoNotRelay(), false);\n if (tx.getDoNotRelay()) assert(!tx.getIsRelayed());\n \n // test outgoing transfer per configuration\n if (testConfig.hasOutgoingTransfer === false) assert(tx.getOutgoingTransfer() === undefined);\n if (testConfig.hasDestinations) assert(tx.getOutgoingTransfer() && tx.getOutgoingTransfer().getDestionations().length > 0);\n \n // test outgoing transfer\n if (tx.getOutgoingTransfer()) {\n testTransfer(tx.getOutgoingTransfer());\n if (testConfig.isSweep) assert.equal(tx.getOutgoingTransfer().getDestinations().length, 1);\n \n // TODO: handle special cases\n } else {\n assert(tx.getIncomingTransfers().length > 0);\n assert.equal(tx.getOutgoingAmount(), undefined);\n assert.equal(tx.getOutgoingTransfer(), undefined);\n assert.equal(tx.getMixin(), undefined);\n assert.equal(tx.getHex(), undefined);\n assert.equal(tx.getMetadata(), undefined);\n assert.equal(tx.getKey(), undefined);\n }\n \n // test incoming transfers\n if (tx.getIncomingTransfers()) {\n assert(tx.getIncomingTransfers().length > 0);\n TestUtils.testUnsignedBigInteger(tx.getIncomingAmount()); \n assert.equal(tx.getIsFailed(), false);\n \n // test each transfer and collect transfer sum\n let transferSum = new BigInteger(0);\n for (let transfer of tx.getIncomingTransfers()) {\n testTransfer(transfer);\n assert(transfer.getAddress());\n assert(transfer.getAccountIndex() >= 0);\n assert(transfer.getSubaddressIndex() >= 0);\n transferSum = transferSum.add(transfer.getAmount());\n if (testConfig.wallet) assert.equal(transfer.getSubaddressIndex()), transfer.getAddress(), await testConfig.wallet.getAddress(transfer.getAccountIndex());\n \n // TODO special case: transfer amount of 0\n }\n \n // incoming transfers add up to incoming tx amount\n assert.equal(transferSum.compare(tx.getIncomingAmount()), 0);\n } else {\n assert(tx.getOutgoingTransfer());\n assert.equal(tx.getIncomingAmount(), undefined);\n assert.equal(tx.getIncomingTransfers(), undefined);\n }\n \n // test tx result from send(), sendSplit(), or relayTxs()\n if (testConfig.sendConfig) {\n \n // test common attributes\n let sendConfig = testConfig.sendConfig;\n assert.equal(tx.getIsConfirmed(), false);\n testTransfer(tx.getOutgoingTransfer());\n assert.equal(tx.getMixin(), sendConfig.getMixin());\n assert.equal(tx.getUnlockTime(), sendConfig.getUnlockTime() ? sendConfig.getUnlockTime() : 0);\n assert.equal(tx.getBlock(), undefined);\n if (sendConfig.getCanSplit()) assert.equal(tx.getKey(), undefined); // TODO monero-wallet-rpc: key only known on `transfer` response\n else assert(tx.getKey().length > 0);\n assert.equal(typeof tx.getHex(), \"string\");\n assert(tx.getHex().length > 0);\n assert(tx.getMetadata());\n assert.equal(tx.getReceivedTimestamp(), undefined);\n \n // test destinations of sent tx\n assert.equal(tx.getOutgoingTransfer().getDestinations().length, sendConfig.getDestinations().length);\n for (let i = 0; i < sendConfig.getDestinations().length; i++) {\n assert.equal(tx.getOutgoingTransfer().getDestinations()[i].getAddress(), sendConfig.getDestinations()[i].getAddress());\n if (testConfig.isSweep) {\n assert.equal(sendConfig.getDestinations().length, 1);\n assert.equal(sendConfig.getDestinations()[i].getAmount(), undefined);\n assert.equal(tx.getOutgoingTransfer().getDestinations()[i].getAmount().toString(), tx.getOutgoingTransfer().getAmount().toString());\n } else {\n assert.equal(tx.getOutgoingTransfer().getDestinations()[i].getAmount().toString(), sendConfig.getDestinations()[i].getAmount().toString());\n }\n }\n \n // test relayed txs\n if (!sendConfig.getDoNotRelay()) {\n assert.equal(tx.getInTxPool(), true);\n assert.equal(tx.getDoNotRelay(), false);\n assert.equal(tx.getIsRelayed(), true);\n assert(tx.getLastRelayedTimestamp() > 0);\n assert.equal(tx.getIsDoubleSpend(), false);\n }\n \n // test non-relayed txs\n else {\n assert.equal(tx.getInTxPool(), false);\n assert.equal(tx.getDoNotRelay(), true);\n assert.equal(tx.getIsRelayed(), false);\n assert.equal(tx.getLastRelayedTimestamp(), undefined);\n assert.equal(tx.getIsDoubleSpend(), undefined);\n }\n } else {\n assert.equal(tx.getMixin(), undefined);\n assert.equal(tx.getKey(), undefined);\n assert.equal(tx.getHex(), undefined);\n assert.equal(tx.getMetadata(), undefined);\n assert.equal(tx.getLastRelayedTimestamp(), undefined);\n }\n \n // test vouts\n if (tx.getIncomingTransfers() && tx.getIsConfirmed() && testConfig.getVouts) assert(tx.getVouts().length > 0);\n if (tx.getVouts()) for (let vout of tx.getVouts()) testVout(vout);\n \n // test deep copy\n if (!testConfig.doNotTestCopy) await testWalletTxCopy(tx, testConfig);\n}",
"sendTransaction(txn) {\n return Wallet.sendTransaction(txn, this.options);\n }",
"function printTransactionTransfer(transaction, transfer) {\n if (transfer.isDeposit) {\n console.log(`Account ${transaction.account_addr} deposits ${transfer.value} from ${transfer.counterparty} at ${transaction.now}`);\n } else {\n console.log(`Account ${transaction.account_addr} withdraws ${transfer.value} to ${transfer.counterparty} at ${transaction.now}`);\n }\n}",
"function debugOutput(tx, level, from) {\n if (level >= 3) {\n console.log('transaction details: ', stringify(tx));\n }\n if (level >= 2) {\n console.log(`transaction size: `+ tx.hex.length/2 + ` Bytes` );\n }\n if (level >= 1) {\n console.log(\"P2PKH by \" + from.name + ` - track here: https://www.blockchain.com/bch-testnet/tx/`+ tx.txid);\n }\n}",
"function addTransaction(tx) {\n\n\t // Get user's secret key\n\t keychain.requestSecret(id.account, id.username, function (err, secret) {\n\t if (err) {\n\t console.log(\"client: txQueue: error while unlocking wallet: \", err);\n\n\t return;\n\t }\n\n\t var transaction = ripple.Transaction.from_json(tx.tx_json);\n\n\t transaction.remote = network.remote;\n\t transaction.secret(secret);\n\n\t // If account is funded submit the transaction right away\n\t if ($scope.account.Balance) {\n\t transaction.submit();\n\t }\n\n\t // If not, add it to the queue.\n\t // (Will be submitted as soon as account gets funding)\n\t else {\n\t var item = {\n\t tx_json: tx.tx_json,\n\t type: tx.tx_json.TransactionType\n\t };\n\n\t // Additional details depending on a transaction type\n\t if ('TrustSet' === item.type) {\n\t item.details = tx.tx_json.LimitAmount;\n\t }\n\n\t $scope.userBlob.unshift(\"/txQueue\", item);\n\t }\n\t });\n\t }",
"handlePushTx() {\n if (this.transaction === null) {\n throw new WalletError(ErrorMessages.TRANSACTION_IS_NULL);\n }\n\n this.emit('send-tx-start', this.transaction);\n const txHex = this.transaction.toHex();\n txApi.pushTx(txHex, false, (response) => {\n if (response.success) {\n this.transaction.updateHash();\n this.emit('send-tx-success', this.transaction);\n if (this._unmarkAsSelectedTimer !== null) {\n // After finishing the push_tx we can clearTimeout to unmark\n clearTimeout(this._unmarkAsSelectedTimer);\n this._unmarkAsSelectedTimer = null;\n }\n } else {\n this.updateOutputSelected(false);\n this.emit('send-error', response.message);\n }\n }).catch(() => {\n this.updateOutputSelected(false);\n this.emit('send-error', this.unexpectedPushTxError);\n });\n }",
"SendBlockchain()\n{\n // todo: broadcast lasted blockchain\n}",
"async function sendCoins() {\n if (typeof window.ethereum !== 'undefined') {\n await requestAccount()\n const provider = new ethers.providers.Web3Provider(window.ethereum);\n const signer = provider.getSigner();\n const contract = new ethers.Contract(bvgTokenAddress, BVGToken.abi, signer);\n // We parse the amount to be sent. eg : amount of BVG to be sent = ethers.utils.parseEther(amount BVG written on the UI)\n // since BVG and Ether has the same decimal 18\n // For a token with another value of the decimal, we should update our parse method\n const parsedAmount = ethers.utils.parseEther(amount);\n const transation = await contract.transfer(userAccount, parsedAmount);\n await transation.wait();\n console.log(`${ethers.utils.formatEther(parsedAmount)} BVG successfully sent to ${userAccount}`);\n }\n }",
"function printTransactionXdr() {\n loadAccount(publicKey).then(function (account) {\n var transaction = createTransaction(account);\n var signatureBase = transaction.signatureBase();\n printHexBlocks(signatureBase);\n fs.writeFile(\"/tmp/txSignatureBase\", signatureBase.toString('hex'), function (err) {\n if (err) console.log(\"could not write signature base file\");\n else console.log(\"saved signature base\");\n });\n });\n}",
"spendUTXO(utxo, toAddress, amount, fromUtxoIndex, cb) {\n if (!cb) { cb = fromUtxoIndex; fromUtxoIndex = 0; }\n let utxoAmount = -1;\n let change;\n if (utxo.txid) {\n // this is a listunspent entry\n fromUtxoIndex = utxo.vout;\n utxoAmount = utxo.amount;\n utxo = utxo.txid;\n }\n const recipientDict = {};\n const utxoDict = [{\n txid: utxo,\n vout: fromUtxoIndex,\n }];\n recipientDict[toAddress] = amount;\n if (utxoAmount > 0) {\n // we do not have to addChangeOutputToTransaction\n change = utxoAmount - amount - 0.0003;\n }\n const trimmedRD = (rd) => {\n const r = {};\n for (const txid of Object.keys(rd)) {\n r[txid] = rd[txid].toFixed(8);\n }\n return r;\n };\n async.waterfall([\n (c) => async.waterfall([\n (cc) => {\n if (utxoAmount > 0) {\n if (change > 0) {\n return this.getNewAddress((err, addr) => {\n recipientDict[addr] = change;\n cc();\n });\n }\n }\n cc();\n },\n (cc) => this.createRawTransaction(trimmedRD(recipientDict), utxoDict, cc),\n ], c),\n (rawtx, c) => utxoAmount > 0 ? c(null, rawtx) : this.addChangeOutputToTransaction(rawtx, c),\n (rawtx, c) => this.sendRawTransaction(rawtx, true, c),\n ], (err, info) => cb(embed(err, { toAddress, amount, utxoAmount, change, fromUtxoIndex }), info));\n }",
"function sendtx(src, tgtaddr, amount, strData) {\n\t\t\n\tchain3.mc.sendTransaction(\n\t\t{\n\t\t\tfrom: src,\n\t\t\tvalue:chain3.toSha(amount,'mc'),\n\t\t\tto: tgtaddr,\n\t\t\tgas: \"22000\",//min 1000\n\t\t\tgasPrice: chain3.mc.gasPrice,\n\t\t\tdata: strData\n\t\t}, function (e, transactionHash){\n if (!e) {\n console.log('Transaction hash: ' + transactionHash);\n }\n });\n\t\t\n\tconsole.log('sending from:' + \tsrc + ' to:' + tgtaddr + ' amount:' + amount + ' with data:' + strData);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_shift: number; _inverted: boolean; _samplesSinceChange: number; _lastBit: boolean; _loHys: number; _hiHys: number; _bit: boolean; _lastr: number; _lasti: number; _bitsum: number; _scopeData: number[][]; _scnt: number; _sx: number; _sf: Filter; _mf: Filter; _dataFilter: Filter; _symbollen: number; _halfsym: number; | constructor(par) {
super(par);
this._shift = 170.0;
this.inverted = false;
this.rate = 45.0;
this._samplesSinceChange = 0;
this._lastBit = false;
// receive
this._loHys = -1.0;
this._hiHys = 1.0;
this._bit = false;
this._lastr = 0;
this._lasti = 0;
this._bitsum = 0;
// scope
this._scopeData = new Array(SSIZE);
this._scnt = 0;
this._sx = -1;
} | [
"handleDemodData(iFloat,iShort,asComplex) {\n // if( this.printSlicer ) {\n // console.log('enter demodData ' + iShort.length + ' ' + asComplex.length);\n // }\n\n // this is \n // output of reverse mover, named reverse_mover in AirPacket.cpp\n let moverOut = [];\n\n for( let i = 0; i < iShort.length; i++ ) {\n let mod = i % 1024;\n\n let found = this.reverseMoverConfig.has(mod);\n\n if( found ) {\n moverOut.push(iShort[i]);\n }\n\n // console.log(\"mod \" + mod + \" has \" + found);\n\n // auto it = find (reverse_mover.begin(), reverse_mover.end(), mod);\n // if (it != reverse_mover.end()) {\n // vmem_mover_out.push_back(rx_out[i]);\n // }\n }\n\n if( this.printSlicer ) {\n // for( let x of moverOut ) {\n // console.log(x.toString(16));\n // }\n }\n\n let sliced_out = [];\n\n let word = 0;\n for(let i = 0; i < moverOut.length; i++) {\n let j = i % 16;\n let input = moverOut[i];\n\n let bits = (( ( (input >>> 30) & 0x2 ) >>> 0 ) | (( (input >>> 15) & 0x1 )>>>0))>>>0;\n word = (((word >>> 2)) | ((bits<<30)))>>>0;\n\n // console.log(`j: ${j} ${word.toString(16)} ${input.toString(16)}`);\n\n if( j == 15 ) {\n sliced_out.push(word);\n // std::cout << HEX32_STRING(word) << std::endl;\n word = 0;\n }\n }\n\n // for(let x of sliced_out) {\n // // console.log(x.toString(16));\n // console.log(mutil.bitMangleSliced(x).toString(16));\n // }\n\n if( this.onMapmovData !== null ) {\n this.onMapmovData(sliced_out);\n }\n\n if( this.printSlicer ) {\n for(let i = 0; i < sliced_out.length; i++) {\n let j = mutil.transformWords128(i);\n console.log(mutil.bitMangleSliced(sliced_out[j]).toString(16) + \" fbtag\");\n }\n }\n\n // increment header seq, send header and body\n this.vec_demod_data.seq = this.uint.frame_track_counter;\n this.push(mutil.IShortToStreamable(this.vec_demod_data));\n this.push(mutil.IShortToStreamable(sliced_out));\n }",
"updateDataType_() {\r\n this.dataType = {\r\n bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,\r\n fp: this.bitDepth == '32f' || this.bitDepth == '64',\r\n signed: this.bitDepth != '8',\r\n be: this.container == 'RIFX'\r\n };\r\n if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {\r\n this.dataType.bits = 8;\r\n this.dataType.signed = false;\r\n }\r\n }",
"update (freqs, symbol) {\n // State check\n let low = this._low\n let high = this._high\n // console.log(`======== Updating ${symbol} =========`);\n // console.log(`this._low = ${this._low.toString(16)}`);\n // console.log(`this._high = ${this._high.toString(16)}`);\n // console.log(`low & this._state_mask = ${low & this._state_mask.toString(16)}`);\n // console.log(`high & (this._state_mask) = ${high & (this._state_mask).toString(16)}`);\n if (low >>> 0 >= high >>> 0 || ((low & this._state_mask) !== low) || ((high & (this._state_mask)) !== high)) {\n throw new RangeError(`Low or high out of range, low = ${low}, high = ${high}`)\n }\n let range = high - low + 1\n // console.log(`range = ${range.toString(16)}`);\n if (!(this._minimum_range >>> 0 <= range >>> 0 && range >>> 0 <= this._full_range >>> 0)) {\n throw new RangeError('Range out of range')\n }\n\n // Frequency table values check\n let total = freqs.total\n let symlow = freqs.getLow(symbol)\n let symhigh = freqs.getHigh(symbol)\n // console.log(`symlow = ${symlow.toString(16)}`);\n // console.log(`symhigh = ${symhigh.toString(16)}`);\n if (symlow === symhigh) {\n throw new Error('Symbol has zero frequency')\n }\n if (this._maximum_total >>> 0 <= total >>> 0) {\n throw new Error('Cannot code symbol because total is too large')\n }\n\n // Update\n // console.log(`total = ${total.toString(16)}`);\n let newlow = low + Math.floor(range * symlow / total)\n let newhigh = low + Math.floor(range * symhigh / total) - 1\n // console.log(`newlow = ${newlow.toString(16)}`);\n // console.log(`newhigh = ${newhigh.toString(16)}`);\n this._low = newlow\n this._high = newhigh\n\n // While low and high have the same top bit value, shift them out\n while (((this._low ^ this._high) & (this._half_range)) === 0) {\n this._shift()\n this._low = (this._low << 1) & (this._state_mask)\n this._high = (this._high << 1) & (this._state_mask) | 1\n }\n\n // Now low's top bit must be 0 and high's top bit must be 1\n\n // While low's top two bits are 01 and high's are 10, delete the second highest bit of both\n while ((this._low & (~this._high) & (this._quarter_range)) !== 0) {\n this._underflow()\n this._low = (this._low << 1) ^ (this._half_range)\n this._high = ((this._high ^ (this._half_range)) << 1) | this._half_range | 1\n }\n }",
"function mdct_short(inout,inoutPos){for(var l=0;l<3;l++){var tc0,tc1,tc2,ts0,ts1,ts2;ts0=inout[inoutPos+2*3]*win[Encoder.SHORT_TYPE][0]-inout[inoutPos+5*3];tc0=inout[inoutPos+0*3]*win[Encoder.SHORT_TYPE][2]-inout[inoutPos+3*3];tc1=ts0+tc0;tc2=ts0-tc0;ts0=inout[inoutPos+5*3]*win[Encoder.SHORT_TYPE][0]+inout[inoutPos+2*3];tc0=inout[inoutPos+3*3]*win[Encoder.SHORT_TYPE][2]+inout[inoutPos+0*3];ts1=ts0+tc0;ts2=-ts0+tc0;tc0=(inout[inoutPos+1*3]*win[Encoder.SHORT_TYPE][1]-inout[inoutPos+4*3])*2.069978111953089e-11;/*\n * tritab_s [ 1 ]\n */ts0=(inout[inoutPos+4*3]*win[Encoder.SHORT_TYPE][1]+inout[inoutPos+1*3])*2.069978111953089e-11;/*\n * tritab_s [ 1 ]\n */inout[inoutPos+3*0]=tc1*1.907525191737280e-11+tc0;/*\n * tritab_s[ 2 ]\n */inout[inoutPos+3*5]=-ts1*1.907525191737280e-11+ts0;/*\n * tritab_s[0 ]\n */tc2=tc2*0.86602540378443870761*1.907525191737281e-11;/*\n * tritab_s[ 2]\n */ts1=ts1*0.5*1.907525191737281e-11+ts0;inout[inoutPos+3*1]=tc2-ts1;inout[inoutPos+3*2]=tc2+ts1;tc1=tc1*0.5*1.907525191737281e-11-tc0;ts2=ts2*0.86602540378443870761*1.907525191737281e-11;/*\n * tritab_s[ 0]\n */inout[inoutPos+3*3]=tc1+ts2;inout[inoutPos+3*4]=tc1-ts2;inoutPos++;}}",
"update(freqs, symbol) {\n // State check\n let low = this._low;\n let high = this._high;\n // console.log(`======== Updating ${symbol} =========`);\n // console.log(`this._low = ${this._low.toString(16)}`);\n // console.log(`this._high = ${this._high.toString(16)}`);\n // console.log(`low & this._state_mask = ${low & this._state_mask.toString(16)}`);\n // console.log(`high & (this._state_mask) = ${high & (this._state_mask).toString(16)}`);\n if (low >>> 0 >= high >>> 0 || ((low & this._state_mask) !== low) || ((high & (this._state_mask)) !== high)) {\n throw RangeError(`Low or high out of range, low = ${low}, high = ${high}`);\n }\n let range = high - low + 1;\n // console.log(`range = ${range.toString(16)}`);\n if (!(this._minimum_range >>> 0 <= range >>> 0 && range >>> 0 <= this._full_range >>> 0)) {\n throw RangeError('Range out of range');\n }\n\n // Frequency table values check\n let total = freqs.total;\n let symlow = freqs.getLow(symbol);\n let symhigh = freqs.getHigh(symbol);\n // console.log(`symlow = ${symlow.toString(16)}`);\n // console.log(`symhigh = ${symhigh.toString(16)}`);\n if (symlow === symhigh) {\n throw Error('Symbol has zero frequency');\n }\n if (this._maximum_total >>> 0 <= total >>> 0) {\n throw Error('Cannot code symbol because total is too large');\n }\n\n // Update \n // console.log(`total = ${total.toString(16)}`);\n let newlow = low + Math.floor(range * symlow / total);\n let newhigh = low + Math.floor(range * symhigh / total) - 1;\n // console.log(`newlow = ${newlow.toString(16)}`);\n // console.log(`newhigh = ${newhigh.toString(16)}`);\n this._low = newlow;\n this._high = newhigh;\n\n // While low and high have the same top bit value, shift them out\n while (((this._low ^ this._high) & (this._half_range)) === 0) {\n this._shift();\n this._low = (this._low << 1) & (this._state_mask);\n this._high = (this._high << 1) & (this._state_mask) | 1;\n }\n\n // Now low's top bit must be 0 and high's top bit must be 1\n\n // While low's top two bits are 01 and high's are 10, delete the second highest bit of both\n while ((this._low & (~this._high) & (this._quarter_range)) !== 0) {\n this._underflow();\n this._low = (this._low << 1) ^ (this._half_range);\n this._high = ((this._high ^ (this._half_range)) << 1) | this._half_range | 1;\n }\n }",
"SCF(op){\n op.subtraction_flag = 0;\n op.half_carry_flag = 0;\n op.carry_flag = 1;\n }",
"_transform(chunk,encoding,cb) {\n\n const uint8_view = new Uint8Array(chunk, 0, chunk.length);\n var dataView = new DataView(uint8_view.buffer);\n\n let iFloat = Array(this.sz*2);\n let asComplex = Array(this.sz);\n\n\n // for(let i = 0; i < this.sz*2; i+=1) {\n // iFloat[i] = dataView.getFloat64(i*8, true);\n // }\n\n for(let i = 0; i < this.sz*2; i+=2) {\n let re = dataView.getFloat64(i*8, true);\n let im = dataView.getFloat64((i*8)+8, true);\n\n asComplex[i/2] = mt.complex(re,im);\n\n iFloat[i] = re;\n iFloat[i+1] = im;\n\n // if( i < 16 ) {\n // console.log(re);\n // }\n\n }\n\n let iShort = mutil.IFloatToIShortMulti(iFloat);\n\n if( this.onFrameIShort !== null ) {\n this.onFrameIShort(iShort);\n }\n\n // console.log(\"iFloat length \" + iFloat.length);\n // console.log(iFloat.slice(0,16));\n\n // console.log(\"iShort length \" + iShort.length);\n // console.log(iShort.slice(0,16));\n\n\n this.handleDefaultStream(iFloat,iShort,asComplex);\n this.handleFineSync(iFloat,iShort,asComplex);\n this.handleAllSubcarriers(iFloat,iShort,asComplex);\n this.handleDemodData(iFloat,iShort,asComplex);\n\n\n // for(x of iFloat) {\n // console.log(x);\n // }\n\n\n this.uint.frame_track_counter++;\n cb();\n }",
"function williams (\n\t// byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, ushort u1\n\tb1, b2, b3, b4, b5, b6, b7, u1\n) {\n\tconst b = new Uint8Array([b1, b2, b3, b4, b5, b6, b7]) // input values as bytes\n\tconst u = new Uint16Array([u1])\n\tconst c = new Uint8Array(2) // internal storage\n\tconst count = new Uint16Array(1) // internal counter\n\tconst sound = new Uint8Array(1) // current sound level\n\tconst data = new Uint8Array(WMS_MAX_SIZE)\n\tlet dataIndex = 0\n\t// copy the current sound value this many times into the output\n\tfunction dup (d) {\n\t\twhile (d-- > 0) {\n\t\t\tdata[dataIndex++] = sound[0]\n\t\t}\n\t}\n\n\tdup(8)\n\tsound[0] = b[6]\n\tdo {\n\t\tdup(14)\n\t\tc[0] = b[0]\n\t\tc[1] = b[1]\n\t\tdo {\n\t\t\tdup(4)\n\t\t\tcount[0] = u[0]\n\t\t\twhile (true) {\n\t\t\t\tdup(9)\n\t\t\t\tsound[0] = ~sound[0]\n\n\t\t\t\tconst t1 = c[0] !== 0 ? c[0] : 256\n\t\t\t\tdup(Math.min(count[0], t1) * 14 - 6)\n\t\t\t\tif (count[0] <= t1) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdup(12)\n\t\t\t\tcount[0] -= t1\n\n\t\t\t\tsound[0] = ~sound[0]\n\n\t\t\t\tconst t2 = c[1] !== 0 ? c[1] : 256\n\t\t\t\tdup(Math.min(count[0], t2) * 14 - 3)\n\t\t\t\tif (count[0] <= t2) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdup(10)\n\t\t\t\tcount[0] -= t2\n\t\t\t}\n\n\t\t\tdup(15)\n\n\t\t\tif (sound[0] < 128) {\n\t\t\t\tdup(2)\n\t\t\t\tsound[0] = ~sound[0]\n\t\t\t}\n\n\t\t\tdup(27)\n\t\t\tc[0] += b[2]\n\t\t\tc[1] += b[3]\n\t\t} while (c[1] !== b[4] && dataIndex < WMS_MAX_SIZE)\n\n\t\tdup(7)\n\t\tif (b[5] === 0) break\n\t\tdup(11)\n\t\tb[0] += b[5]\n\t} while (b[0] !== 0 && dataIndex < WMS_MAX_SIZE)\n\n\tconsole.log(`williams used ${dataIndex} bytes`)\n\n\treturn dataIndex < WMS_MAX_SIZE ? data.subarray(0, dataIndex) : data\n}",
"buildCodes() {\n let nextCode = new Int32Array(this.maxLength);\n let code = 0;\n this.codes = new Int16Array(this.freqs.length);\n for (let bits = 0; bits < this.maxLength; bits++) {\n nextCode[bits] = code;\n code += this.bitLengthCounts[bits] << (15 - bits);\n }\n for (let i = 0; i < this.numCodes; i++) {\n let bits = this.length[i];\n if (bits > 0) {\n this.codes[i] = DeflaterHuffman.bitReverse(nextCode[bits - 1]);\n nextCode[bits - 1] += 1 << (16 - bits);\n }\n }\n }",
"function extractSteim1Samples(dataView, offset, littleEndian) {\n /* get nibbles */\n var nibbles = dataView.getInt32(offset, littleEndian);\n var currNibble = 0;\n var temp = []; // 4 samples * 16 longwords, can't be more than 64\n var currNum = 0;\n var i = void 0,\n n = void 0;\n for (i = 0; i < 16; i++) {\n // i is the word number of the frame starting at 0\n //currNibble = (nibbles >>> (30 - i*2 ) ) & 0x03; // count from top to bottom each nibble in W(0)\n currNibble = nibbles >> 30 - i * 2 & 0x03; // count from top to bottom each nibble in W(0)\n //System.err.print(\"c(\" + i + \")\" + currNibble + \",\"); // DEBUG\n // Rule appears to be:\n // only check for byte-swap on actual value-atoms, so a 32-bit word in of itself\n // is not swapped, but two 16-bit short *values* are or a single\n // 32-bit int *value* is, if the flag is set to TRUE. 8-bit values\n // are naturally not swapped.\n // It would seem that the W(0) word is swap-checked, though, which is confusing...\n // maybe it has to do with the reference to high-order bits for c(0)\n switch (currNibble) {\n case 0:\n //System.out.println(\"0 means header info\");\n // only include header info if offset is 0\n if (offset == 0) {\n temp[currNum++] = dataView.getInt32(offset + i * 4, littleEndian);\n }\n break;\n case 1:\n //System.out.println(\"1 means 4 one byte differences\");\n for (n = 0; n < 4; n++) {\n temp[currNum] = dataView.getInt8(offset + i * 4 + n);\n currNum++;\n }\n break;\n case 2:\n //System.out.println(\"2 means 2 two byte differences\");\n for (n = 0; n < 4; n += 2) {\n temp[currNum] = dataView.getInt16(offset + i * 4 + n, littleEndian);\n currNum++;\n }\n break;\n case 3:\n //System.out.println(\"3 means 1 four byte difference\");\n temp[currNum++] = dataView.getInt32(offset + i * 4, littleEndian);\n break;\n default:\n throw new CodecException(\"unreachable case: \" + currNibble);\n //System.out.println(\"default\");\n }\n }\n return temp;\n }",
"readBits(frame) {\n let bits = \"\";\n const waveformAnnotation = [];\n const explanations = [];\n waveformAnnotation.push(new LabelAnnotation(\"Previous\", frame, frame, true));\n while (true) {\n const expectedNextFrame = frame + this.period;\n const [bit, clockPulse, dataPulse] = this.readBit(frame, true);\n if (clockPulse.resultType === PulseResultType.NOISE || clockPulse.resultType === PulseResultType.SILENCE) {\n const left = expectedNextFrame - this.quarterPeriod;\n const right = expectedNextFrame + this.period - this.quarterPeriod;\n waveformAnnotation.push(new LabelAnnotation(clockPulse.resultType === PulseResultType.NOISE ? \"Noise\" : \"Silence\", left, right, true));\n if (clockPulse.explanation !== \"\") {\n explanations.push(clockPulse.explanation);\n }\n waveformAnnotation.push(...clockPulse.waveformAnnotations);\n break;\n }\n const bitChar = bit ? \"1\" : \"0\";\n bits += bitChar;\n if (clockPulse.explanation !== \"\") {\n explanations.push(clockPulse.explanation);\n }\n if (dataPulse.explanation !== \"\") {\n explanations.push(dataPulse.explanation);\n }\n waveformAnnotation.push(...clockPulse.waveformAnnotations);\n waveformAnnotation.push(...dataPulse.waveformAnnotations);\n const nextFrame = clockPulse.frame;\n const left = nextFrame - this.quarterPeriod;\n const right = nextFrame + this.period - this.quarterPeriod;\n waveformAnnotation.push(new LabelAnnotation(bitChar, left, right, true));\n frame = nextFrame;\n this.peakThreshold = Math.round(clockPulse.range / 4);\n }\n return [bits, waveformAnnotation, explanations];\n }",
"function state_1d(){\n let n = 128;\n let psi = wavefunction(n);\n for(let i = 0; i < n; i++){\n psi[i].real = Math.exp(-(i-20)*(i-20)/(5*5))*0.75;\n psi[i].imag = 0;\n }\n return psi;\n}",
"function extractSteim1Samples(dataView, offset, littleEndian) {\n /* get nibbles */\n var nibbles = dataView.getInt32(offset, littleEndian);\n var currNibble = 0;\n var temp = []; // 4 samples * 16 longwords, can't be more than 64\n var currNum = 0;\n var i = void 0,\n n = void 0;\n for (i = 0; i < 16; i++) {\n // i is the word number of the frame starting at 0\n //currNibble = (nibbles >>> (30 - i*2 ) ) & 0x03; // count from top to bottom each nibble in W(0)\n currNibble = nibbles >> 30 - i * 2 & 0x03; // count from top to bottom each nibble in W(0)\n //System.err.print(\"c(\" + i + \")\" + currNibble + \",\"); // DEBUG\n // Rule appears to be:\n // only check for byte-swap on actual value-atoms, so a 32-bit word in of itself\n // is not swapped, but two 16-bit short *values* are or a single\n // 32-bit int *value* is, if the flag is set to TRUE. 8-bit values\n // are naturally not swapped.\n // It would seem that the W(0) word is swap-checked, though, which is confusing...\n // maybe it has to do with the reference to high-order bits for c(0)\n switch (currNibble) {\n case 0:\n //System.out.println(\"0 means header info\");\n // only include header info if offset is 0\n if (offset == 0) {\n temp[currNum++] = dataView.getInt32(offset + i * 4, littleEndian);\n }\n break;\n case 1:\n //System.out.println(\"1 means 4 one byte differences\");\n for (n = 0; n < 4; n++) {\n temp[currNum] = dataView.getInt8(offset + i * 4 + n);\n currNum++;\n }\n break;\n case 2:\n //System.out.println(\"2 means 2 two byte differences\");\n for (n = 0; n < 4; n += 2) {\n temp[currNum] = dataView.getInt16(offset + i * 4 + n, littleEndian);\n currNum++;\n }\n break;\n case 3:\n //System.out.println(\"3 means 1 four byte difference\");\n temp[currNum++] = dataView.getInt32(offset + i * 4, littleEndian);\n break;\n default:\n throw new CodecException(\"unreachable case: \" + currNibble);\n //System.out.println(\"default\");\n }\n }\n return temp;\n}",
"function\nStreamDemo_prev1_683_(a2x1)\n{\nlet xtmp277;\nlet xtmp281;\nlet xtmp282;\n;\n// ././../../DATS/StreamDemo.dats: 4215(line=336, offs=1) -- 4253(line=337, offs=30)\n{\n{\n// ././../../DATS/StreamDemo.dats: 3568(line=291, offs=1) -- 3655(line=297, offs=8)\nfunction\nStreamDemo_set_dir_448_(a3x1, a3x2)\n{\nlet xtmp280;\n;\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/prelude.dats: 7443(line=455, offs=1) -- 7492(line=457, offs=33)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\na0ref_set_2496_ = XATS2JS_a0ref_set\n;\nxtmp280 = a0ref_set_2496_(a3x1[1], a3x2);\n}\n;\nreturn xtmp280;\n} // function // StreamDemo_set_dir(75)\n;\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/basics.dats: 3589(line=255, offs=1) -- 3646(line=256, offs=50)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\ngint_sub_sint_sint_3524_ = XATS2JS_gint_sub_sint_sint\n;\nxtmp281 = gint_sub_sint_sint_3524_(0, 1);\n}\n;\nxtmp277 = StreamDemo_set_dir_448_(a2x1, xtmp281);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(277)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(277)));\n} // val(H0Pnil())\n;\n{\n// ././../../DATS/StreamDemo.dats: 3238(line=266, offs=1) -- 3442(line=281, offs=15)\nfunction\nStreamDemo_get_elt_291_(a3x1)\n{\nlet xtmp284;\nlet xtmp285;\nlet xtmp286;\nlet xtmp287;\nlet xtmp288;\n;\n// ././../../DATS/StreamDemo.dats: 3294(line=271, offs=1) -- 3324(line=272, offs=23)\n// L1DCLnone1(H0Cnone1(...));\n// ././../../DATS/StreamDemo.dats: 3328(line=274, offs=1) -- 3360(line=275, offs=24)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/prelude.dats: 7289(line=444, offs=1) -- 7338(line=446, offs=33)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\na0ref_get_2457_ = XATS2JS_a0ref_get\n;\nxtmp284 = a0ref_get_2457_(a3x1[2]);\n}\n;\n;\n} // val(H0Pvar(xs(117)))\n;\n// ././../../DATS/StreamDemo.dats: 3361(line=276, offs=1) -- 3392(line=277, offs=27)\n{\nxtmp285 = XATS2JS_lazy_eval(xtmp284);\nif(0!==xtmp285[0]) XATS2JS_patckerr0();\n;\nxtmp286 = xtmp285[1];\nxtmp287 = xtmp285[2];\n} // val(H0Pdapp(H0Pcon(strxcon_cons(4)); -1; H0Pvar(x0(118)), H0Pvar(xs(119))))\n;\n// ././../../DATS/StreamDemo.dats: 3393(line=278, offs=1) -- 3429(line=279, offs=28)\n{\n{\n// /home/hwxi/Research/ATS-Xanadu/prelude/DATS/CATS/JS/prelude.dats: 7443(line=455, offs=1) -- 7492(line=457, offs=33)\n// { // val-binding\n// } // val-binding\nconst // implval/fun\na0ref_set_2496_ = XATS2JS_a0ref_set\n;\nxtmp288 = a0ref_set_2496_(a3x1[2], xtmp287);\n}\n;\n//L1PCKxpat(H0Pnil(); L1VALtmp(tmp(288)));\n//L1CMDmatch(H0Pnil(); L1VALtmp(tmp(288)));\n} // val(H0Pnil())\n;\nreturn xtmp286;\n} // function // StreamDemo_get_elt(72)\n;\nxtmp282 = StreamDemo_get_elt_291_(a2x1);\n}\n;\nreturn xtmp282;\n}",
"MultiChannelDFT_BandPass(signalBuffer,nSeconds,freqStart,freqEnd, texOut = false) {\n \n var signalBufferProcessed = [];\n \n signalBuffer.forEach((row) => {\n signalBufferProcessed.push(...row);\n });\n //console.log(signalBufferProcessed);\n \n var freqEnd_nyquist = freqEnd*2;\n var nSamplesPerChannel = signalBuffer[0].length;\n var sampleRate = nSamplesPerChannel/nSeconds\n\n this.listdft1D_windowed.setOutput([signalBufferProcessed.length]); //Set output to length of list of signals\n this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel); //Set loop size to the length of one signal (assuming all are uniform length)\n \n var outputTex = this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist);\n if(texOut === true) { return outputTex; }\n signalBufferProcessed = outputTex.toArray();\n outputTex.delete();\n\n //TODO: Optimize for SPEEEEEEED.. or just pass it str8 to a shader\n\n var posMagsList = [];\n //var orderedMagsList = [];\n var summedMags = [];\n for(var i = 0; i < signalBufferProcessed.length; i+=nSamplesPerChannel){\n posMagsList.push([...signalBufferProcessed.slice(i,Math.ceil(nSamplesPerChannel*.5+i))]);\n //orderedMagsList.push([...signalBufferProcessed.slice(Math.ceil(nSamplesPerChannel*.5+i),nSamplesPerChannel+i),...signalBufferProcessed.slice(i,Math.ceil(nSamplesPerChannel*.5+i))]);\n }\n //console.log(posMagsList);\n \n if(nSeconds > 1) { //Need to sum results when sample time > 1 sec\n posMagsList.forEach((row, k) => {\n summedMags.push([]);\n for(var i = 0; i < row.length; i++ ){\n if(i == 0){\n summedMags[k]=row.slice(i,Math.floor(sampleRate));\n i = Math.floor(sampleRate);\n }\n else {\n var j = i-Math.floor(Math.floor(i/sampleRate)*sampleRate)-1; //console.log(j);\n summedMags[k][j] = (summedMags[k][j] * row[i-1]/sampleRate);\n }\n }\n summedMags[k] = [...summedMags[k].slice(0,Math.ceil(summedMags[k].length*0.5))]\n })\n //console.log(summedMags);\n return summedMags; \n }\n else {return posMagsList;}\n }",
"function extractSteim2Samples(dataView, offset, swapBytes) {\n /* get nibbles */\n var nibbles = dataView.getUint32(offset, swapBytes);\n var currNibble = 0;\n var dnib = 0;\n var temp = new Int32Array(106); //max 106 = 7 samples * 15 long words + 1 nibble int\n var tempInt = void 0;\n var currNum = 0;\n var diffCount = 0; // number of differences\n var bitSize = 0; // bit size\n var headerSize = 0; // number of header/unused bits at top\n for (var i = 0; i < 16; i++) {\n currNibble = nibbles >> 30 - i * 2 & 0x03;\n switch (currNibble) {\n case 0:\n //System.out.println(\"0 means header info\");\n // only include header info if offset is 0\n if (offset == 0) {\n temp[currNum++] = dataView.getInt32(offset + i * 4, swapBytes);\n }\n break;\n case 1:\n //console.log(\"1 means 4 one byte differences \" +currNum+\" \"+dataView.getInt8(offset+(i*4))+\" \"+dataView.getInt8(offset+(i*4)+1)+\" \"+dataView.getInt8(offset+(i*4)+2)+\" \"+dataView.getInt8(offset+(i*4)+3));\n temp[currNum++] = dataView.getInt8(offset + i * 4);\n temp[currNum++] = dataView.getInt8(offset + i * 4 + 1);\n temp[currNum++] = dataView.getInt8(offset + i * 4 + 2);\n temp[currNum++] = dataView.getInt8(offset + i * 4 + 3);\n break;\n case 2:\n tempInt = dataView.getUint32(offset + i * 4, swapBytes);\n dnib = tempInt >> 30 & 0x03;\n switch (dnib) {\n case 1:\n //console.log(\"2,1 means 1 thirty bit difference\");\n temp[currNum++] = tempInt << 2 >> 2;\n break;\n case 2:\n //console.log(\"2,2 means 2 fifteen bit differences\");\n temp[currNum++] = tempInt << 2 >> 17; // d0\n temp[currNum++] = tempInt << 17 >> 17; // d1\n break;\n case 3:\n //console.log(\"2,3 means 3 ten bit differences\");\n temp[currNum++] = tempInt << 2 >> 22; // d0\n temp[currNum++] = tempInt << 12 >> 22; // d1\n temp[currNum++] = tempInt << 22 >> 22; // d2\n break;\n default:\n //console.log(\"default\");\n }\n break;\n case 3:\n tempInt = dataView.getUint32(offset + i * 4, swapBytes);\n dnib = tempInt >> 30 & 0x03;\n // for case 3, we are going to use a for-loop formulation that\n // accomplishes the same thing as case 2, just less verbose.\n diffCount = 0; // number of differences\n bitSize = 0; // bit size\n headerSize = 0; // number of header/unused bits at top\n switch (dnib) {\n case 0:\n //System.out.println(\"3,0 means 5 six bit differences\");\n headerSize = 2;\n diffCount = 5;\n bitSize = 6;\n break;\n case 1:\n //System.out.println(\"3,1 means 6 five bit differences\");\n headerSize = 2;\n diffCount = 6;\n bitSize = 5;\n break;\n case 2:\n //System.out.println(\"3,2 means 7 four bit differences, with 2 unused bits\");\n headerSize = 4;\n diffCount = 7;\n bitSize = 4;\n break;\n default:\n //System.out.println(\"default\");\n }\n if (diffCount > 0) {\n for (var d = 0; d < diffCount; d++) {\n // for-loop formulation\n temp[currNum++] = tempInt << headerSize + d * bitSize >> (diffCount - 1) * bitSize + headerSize;\n }\n }\n }\n }\n var out = new Int32Array(currNum);\n for (var _i = 0; _i < currNum; _i++) {\n out[_i] = temp[_i];\n }\n return out;\n }",
"constructor(){\n\tthis.i = 0;//class member: record the i position\n\tthis.j = 0;//class member: record the j position\n\tthis.s = [];//class member: record the state array\n\t//initiate state array by signing 0->255 to s[]\n \tfor (var a = 0; a < 256; a++)\n\t this.s[a]=a;\n }",
"updateDataType_() {\n /** @type {!Object} */\n this.dataType = {\n bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,\n float: this.bitDepth == '32f' || this.bitDepth == '64',\n signed: this.bitDepth != '8',\n be: this.container == 'RIFX'\n };\n if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {\n this.dataType.bits = 8;\n this.dataType.signed = false;\n }\n }",
"GetSpectrumData() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PointSet Description: An object a collection of points Attributes: _points an array containing all the points in the set _size the number of points in the set _centroid a Point object which is located at the centroid of this collection of points (should not be accessed directly as it will be null until explicitly computed) | function PointSet() {
this._points = [];
this._size = 0;
/***************************************************************************
* addPoint
*
* Description:
* Adds a point to this collection of points; an attempt to add a preexisting point will fail, and result in no changes
*
* Args:
* point - a Point object, the point to add to this collection.
*
* Returns:
* An integer - the number of points in the set after adding this new one; returns the current size on an attempted point duplication
***************************************************************************/
this.addPoint = function(point) {
for (var i = 0; i < this._size; i++) {
if (point.equals(this._points[i])) {
return this._size;
}
}
this._points.push(point);
this._size++;
this._centroid = null;
return this._size;
}
/***************************************************************************
* removePoint
*
* Description:
* Removes a point from this collection of points
*
* Args:
* point - a Point object, the point to remove to this collection.
*
* Returns:
* An integer - the number of points in the set after removing this one
***************************************************************************/
this.removePoint = function(point) {
var ind = this._points.indexOf(point);
if (ind > -1) {
this._points.splice(ind,1);
this._size--;
this._centroid = null;
}
return this._size;
}
/***************************************************************************
* generateRandomPoints
*
* Description:
* Adds a certain number of random points to the pointset
*
* Args:
* num - an integer, the number of points to add
* minx - the minimum x value allowed
* maxx - the maximum x value allowed
* miny - the minimum y value allowed
* maxy - the maximum y value allowed
*
* Returns:
* An integer - the number of points in the set after adding the random ones
***************************************************************************/
this.generateRandomPoints = function(num, minx, maxx, miny, maxy) {
var startsize = this._size;
while (this._size - startsize < num) {
var x = Math.floor(Math.random() * (maxx - minx + 1)) + minx;
var y = Math.floor(Math.random() * (maxy - miny + 1)) + miny;
this.addPoint(new Point(x, y));
}
return this._size;
}
/***************************************************************************
* getMinYPoint
*
* Description:
* Finds the point in this pointset that has the minimum y value
*
* Args:
* None
*
* Returns:
* a Point object
***************************************************************************/
this.getMinYPoint = function() {
if (!this._size) {
return;
}
var miny = this._points[0];
for (var i = 1; i < this._size; i++) {
if (this._points[i].y < miny.y) {
miny = this._points[i];
}
}
return miny;
}
/***************************************************************************
* halfSpacePointCount
*
* Description:
* counts points of this pointset on one side of a line
*
* Args:
* points - a Line object, against whom the points will be compared
*
* Returns:
* An integer - the number of points which are clockwise from the given line's end points
***************************************************************************/
this.halfSpacePointCount = function(line) {
var runsum = 0;
for (var i = 0; i < this._size; i++) {
if (window.GeomUtil.orient(line._point1, line._point2, this._points[i]) == -1) {
runsum++;
}
}
return runsum;
}
/***************************************************************************
* isCenterPoint
*
* Description:
* determines whether given point is a centerpoint of the pointset
*
* Args:
* querypoint - a Point object, which will be evaluated as a potential centerpoint
*
* Returns:
* A boolean - true if the point is a centerpoint, false otherwise
***************************************************************************/
this.isCenterPoint = function(querypoint) {
return this.findCenterPointCounterExample(querypoint) ? false : true;
}
/***************************************************************************
* findCenterPointCounterExample
*
* Description:
* finds a line illustrating that the query point is not a fit centerpoint, if such a line exists
*
* Args:
* querypoint - a Point object, which will be evaluated as a potential centerpoint
*
* Returns:
* A Line - the line should pass through querypoint and illustrate that it is not a center point
***************************************************************************/
this.findCenterPointCounterExample = function(querypoint) {
// Make a list of points with the points below the query point getting rotated above it
var shiftedpoints = [];
for (var i = 0; i < this._size; i++) {
var curpoint = this._points[i];
if(curpoint.y < querypoint.y) {
shiftedpoints[i] = new Point((querypoint.x + (querypoint.x - curpoint.x)), (querypoint.y + (querypoint.y - curpoint.y)));
}
else {
shiftedpoints[i] = curpoint;
}
}
// Sort the points in ccw order in relation to the query point using orient test. remove redundant colinear points
var numshiftedpoints = this._size;
var sortedpoints = [];
var numsorted = 2;
sortedpoints[0] = new Point((querypoint.x + 1), querypoint.y);
sortedpoints[1] = new Point((querypoint.x - 1), querypoint.y);
for(var shiftedindex = 0; shiftedindex < numshiftedpoints; shiftedindex++) {
var sortedindex = 0;
var curccw = window.GeomUtil.orient(querypoint, sortedpoints[sortedindex], shiftedpoints[shiftedindex]);
while(curccw == 1) {
sortedindex++;
var curccw = window.GeomUtil.orient(querypoint, sortedpoints[sortedindex], shiftedpoints[shiftedindex]);
}
// Insert the new point into the sorted list
if(curccw == -1) {
var insertionindex = sortedindex;
numsorted++;
for(sortedindex = numsorted - 1; sortedindex > insertionindex; sortedindex--) {
sortedpoints[sortedindex] = sortedpoints[sortedindex - 1];
}
sortedpoints[insertionindex] = shiftedpoints[shiftedindex];
}
//if new point is colinear with another point we've already sorted, just ignore it
}
// Make a list of lines intersecting the query point and the centroid of each pair of adjacent elements in the ordered point list (including query point (+1,+0) and query point (-1, +0))
var linelist = [];
var linecount = 0;
for(var curindex = 0; curindex < numsorted - 1; curindex++) {
var curpt = new Point((sortedpoints[curindex].x + sortedpoints[curindex + 1].x)/2, (sortedpoints[curindex].y + sortedpoints[curindex + 1].y)/2);
linelist[2 * curindex] = new Line(querypoint, curpt);
linelist[(2 * curindex) + 1] = new Line(curpt, querypoint);
linecount += 2;
}
// Find the line which has the most points on one side of it
var largestline;
var largestpoints = 0;
for(var i = 0; i < linecount; i++) {
var count = this.halfSpacePointCount(linelist[i]);
if (count > largestpoints) {
largestline = linelist[i];
largestpoints = count;
}
}
// If the line with the largest point count is larger than 2/3rd of the total points, return it
if (largestpoints > Math.floor(2*(this._size / 3))) {
return largestline;
}
return;
}
/***************************************************************************
* centroid
*
* Description:
* Computes the centroid for this collection of points
*
* Args:
* None
*
* Returns:
* a Point object - the centroid of this collection of points
***************************************************************************/
this.centroid = function() {
var totalx = 0;
var totaly = 0;
for (var i = 0; i < this._size; i++) {
var p = this._points[i];
totalx += p.x;
totaly += p.y;
}
return new Point(totalx / this._size, totaly / this._size);
}
/***************************************************************************
* getCenterPointBoundaries
*
* Description:
* Finds all halfspaces which define the pointset's centerpoint space
*
* Args:
* None
*
* Returns:
* a list of Lines, in order of rotation.
***************************************************************************/
this.getCenterPointBoundaries = function() {
var ps = this;
// returns next line segment of rotation
var next_line = function(ln, add) {
return new Line(ln._point1, ps.findNextPoint(ln, add));
};
// List of halfspace lines:
var lines = [];
// Get first line
var l1 = this.findFirstLine();
lines.push(l1);
// Get size of 1/3 points needed out of halfspace
var size_hlfspc = Math.ceil(this._size/3.0);
// Find starting halfspace line
for (var i = 0; i < size_hlfspc-1; i++) {
lines.push(next_line(lines.slice(-1)[0],1));
}
// Keep track of starting line
var s_line = lines.slice(-1)[0];
lines.push(next_line(lines.slice(-1)[0].flip(),1));
var count = 1;
// Add all lines in rotation
while (!s_line.equals(lines.slice(-1)[0])) {
count ++;
lines.push(next_line(lines.slice(-1)[0].flip()));
// Return error if line doesn't return back to start
if (count > 4*this._size*this._size) {
return 1;
}
}
return lines;
}
/***************************************************************************
* findNextPoint
*
* Description:
* Finds the next point in ccw order wrt a line segment.
* 'add' determines order of collinear points on line segment.
* If add=0 and collinear points wrt l.point1, l.point2 outside l, next
* point will be collinear point on l nearest to l.point2
* If add=1 and collinear points wrt l.point1, l.point2 outside l, next
* point will be collinear point outside l nearest to l.point2
*
* Args:
* l - a line object
* add - boolean
*
* Returns:
* a point - the next point in ccw order
***************************************************************************/
this.findNextPoint = function(l, add) {
// Create PointSet L of potential next points ( [0,180) deg)
// and PointSet R of potential next points ( [180,360) deg)
var L = new PointSet;
var R = new PointSet;
l_exist = 0;
r_exist = 0;
for (var i = 0; i < this._size; i++) {
var pt = this._points[i];
var ccw = window.GeomUtil.orient(l._point1, l._point2,pt);
if (ccw == 1) {
L.addPoint(pt);
}
else if (ccw == 0) {
var t = (pt.x-l._point1.x)/(l._point2.x-l._point1.x);
if (((t > 1.0) && (add == 1)) || ((t>0.0) && (t < 1.0) && (add == 0))) {
L.addPoint(pt);
}
}
else {
R.addPoint(pt)
}
}
// See if points in L and R
if (L._size > 0) {
l_exist = 1;
}
if (R._size > 0) {
r_exist = 1;
}
// Find next point from L
var pcL = L._points[0];
L.removePoint(pcL);
while (L._size>0) {
// Test if pc is on l; move to next section if so
if (window.GeomUtil.orient(l._point1,l._point2,pcL) == 0) {
break;
}
// Test if pt has smaller angle than pc
// If same angle, choose pt if closer to l._point1 than pc
var pt = L._points[0];
L.removePoint(pt);
var ccw = window.GeomUtil.orient(l._point1,pcL,pt);
if (ccw == -1) {
pcL = pt;
}
else if (ccw == 0) {
var t = (pt.x-l._point1.x)/(pcL.x-l._point1.x);
if (t < 1.0) {
pcL = pt;
}
}
}
// Find next point from R
if (R._size > 0) {
var pcR = R._points[0];
R.removePoint(pcR);
while (R._size>0) {
// Test if pc is on l; move to next section if so
if (window.GeomUtil.orient(l._point1,l._point2,pcR) == 0) {
break;
}
// Test if pt has smaller angle than pc
// If same angle, choose pt if closer to l._point1 than pc
var pt = R._points[0];
R.removePoint(pt);
var ccw = window.GeomUtil.orient(l._point1,pcR,pt);
if (ccw == -1) {
pcR = pt;
}
else if (ccw == 0) {
var t = (pt.x-l._point1.x)/(pcR.x-l._point1.x);
if (t < 1.0) {
pcR = pt;
}
}
}
}
var pc = pcL
if (l_exist == 0 || (r_exist == 1 && window.GeomUtil.orient(l._point1,pcL,pcR) == 1)) {
pc = pcR;
}
return pc;
}
/***************************************************************************
* findFirst
*
* Description:
* Finds the first line segment lf in a set of points such that the
* halfspace defined by lf contains all points
*
* Args:
* None
*
* Returns:
* a line - a line segment whose halfspace contains all points in P
***************************************************************************/
this.findFirstLine = function() {
// Ensure this point set contains enough points
if (this._size < 2) {
return 1;
}
// Point comparison for sorting
// Sort y, then x in ascending order (prefer top left of canvas)
function compare(a, b) {
if (a.y === b.y) {
return (a.x < b.x) ? -1 : 1;
}
else {
return (a.y < b.y) ? -1 : 1;
}
}
// Make copy of the points, sort, then return line with
// first two sorted points
var L = this._points.slice(0);
L = L.sort(compare);
var p1 = L[0];
var p2 = L[1];
// If p1 p2 not collinear, call findNextPoint to locate nearest point by angle
if (p1.y != p2.y) {
horz_pt = new Point(p1.x + 10, p1.y);
p2 = this.findNextPoint(new Line(p1, horz_pt), 1);
}
return new Line(p1, p2);
}
} | [
"function PointSet() {\n\t var argv = Array.prototype.slice.call(arguments), argc = argv.length;\n\n\t var _points;\n\t if (argc === 1 && _.isArray(argv[0])) {\n\t if (argv[0].length === 0) {\n\t throw new Error('PointSet() Can not determin pointset dimension from []');\n\t }\n\t _points = argv[0];\n\t this._rn = maxNumOfComponents(_points);\n\t } else if (argc === 2 && typeof argv[0] === 'number' && typeof argv[1] === 'number') {\n\t _points = _.array2d(argv[0], argv[1], 0.0);\n\t this._rn = maxNumOfComponents(_points);\n\t } else if (argc === 2 && typeof argv[0] === 'number' && typeof argv[1] === 'function') {\n\t _points = _.array1d(argv[0], argv[1]);\n\t this._rn = maxNumOfComponents(_points);\n\t } else if (argc === 2 && _.isArray(argv[0]) && typeof argv[1] === 'number') {\n\t _points = argv[0];\n\t this._rn = argv[1];\n\t } else {\n\t throw new Error('PointSet() can not initialize with args: ' + argv);\n\t }\n\n\t this._points = new Array(_points.length);\n\t _.each(_points, function(p, i) {\n\t var coords = _.array1d(this._rn, 0.0);\n\t _.each(p, function(val, j) { coords[j] = val; });\n\t this._points[i] = coords;\n\t }, this);\n\n\t function maxNumOfComponents(pts) {\n\t return _.reduce(pts, function(sofar, p) {\n\t if (p.length > sofar) sofar = p.length;\n\t return sofar;\n\t }, 0);\n\t }\n\t}",
"function PointSet() {\n var argv = Array.prototype.slice.call(arguments), argc = argv.length;\n\n var _points;\n if (argc === 1 && _.isArray(argv[0])) {\n if (argv[0].length === 0) {\n throw new Error('PointSet() Can not determin pointset dimension from []');\n }\n _points = argv[0];\n this._rn = maxNumOfComponents(_points);\n } else if (argc === 2 && typeof argv[0] === 'number' && typeof argv[1] === 'number') {\n _points = _.array2d(argv[0], argv[1], 0.0);\n this._rn = maxNumOfComponents(_points);\n } else if (argc === 2 && typeof argv[0] === 'number' && typeof argv[1] === 'function') {\n _points = _.array1d(argv[0], argv[1]);\n this._rn = maxNumOfComponents(_points);\n } else if (argc === 2 && _.isArray(argv[0]) && typeof argv[1] === 'number') {\n _points = argv[0];\n this._rn = argv[1];\n } else {\n throw new Error('PointSet() can not initialize with args: ' + argv);\n }\n\n this._points = new Array(_points.length);\n _.each(_points, function(p, i) {\n var coords = _.array1d(this._rn, 0.0);\n _.each(p, function(val, j) { coords[j] = val; });\n this._points[i] = coords;\n }, this);\n\n function maxNumOfComponents(pts) {\n return _.reduce(pts, function(sofar, p) {\n if (p.length > sofar) sofar = p.length;\n return sofar;\n }, 0);\n }\n}",
"function PointIndexSet() {\n this._set = {};\n }",
"function STPointSet( name )\n{\n\tthis.uuid = UTILS.generateUUID();\n\tthis.name = name;\n\tthis.points = [];\n\tthis.attributes = {};\n\tthis.bbox = null;\n\tthis.timeSpan = null;\n}",
"function vtkPointSet(publicAPI,model){// Set our className\nmodel.classHierarchy.push('vtkPointSet');// Create empty points\nif(!model.points){model.points=_Points2.default.newInstance();}else{model.points=(0,_vtk2.default)(model.points);}publicAPI.getBounds=function(){return model.points.getBounds();};publicAPI.computeBounds=function(){publicAPI.getBounds();};}// ----------------------------------------------------------------------------",
"function vtkPointSet(publicAPI, model) {\n // Set our className\n model.classHierarchy.push('vtkPointSet');\n\n // Create empty points\n if (!model.points) {\n model.points = _Points2.default.newInstance();\n } else {\n model.points = (0, _vtk2.default)(model.points);\n }\n\n publicAPI.getBounds = function () {\n return model.points.getBounds();\n };\n\n publicAPI.computeBounds = function () {\n publicAPI.getBounds();\n };\n}",
"function Point(x, y, centroid) {\n this.x = x;\n this.y = y;\n this.centroid = centroid;\n}",
"static centroid(pts) {\n return Num.average(pts);\n }",
"function Point(x, y, centroid) {\n this.x = x;\n this.y = y;\n this.centroid = centroid;\n }",
"function centroid(points) {\n var sumX = 0;\n var sumY = 0;\n for (var i = 0; i < points.length; i++) {\n sumX += points[i][0];\n sumY += points[i][1];\n }\n return [sumX / points.length, sumY / points.length];\n}",
"function computeCentroid(points) {\n var latitude = 0;\n var longitude = 0;\n var n = points.length;\n for(i in points) {\n latitude += points[i].lat;\n longitude += points[i].lng;\n }\n return {lat: latitude/n, lng: longitude/n};\n}",
"function chooseInitialCenters(points) {\n\n // Convert to list for indexed access. Make it unmodifiable, since removal of items\n // would screw up the logic of this method.\n var pointList = points;\n // The number of points in the list.\n var numPoints = pointList.length;\n\n // Set the corresponding element in this array to indicate when\n // elements of pointList are no longer available.\n var taken = new Array(numPoints);\n for (var i = 0; i < taken.length; i++) {\n taken[i] = false;\n }\n\n // The resulting list of initial centers.\n var resultSet = [];\n\n // Choose one center uniformly at random from among the data points.\n var firstPointIndex = nextInt(numPoints);\n var firstPoint = pointList[firstPointIndex];\n resultSet.push(new CentroidCluster(firstPoint));\n // Must mark it as taken\n taken[firstPointIndex] = true;\n\n // To keep track of the minimum distance squared of elements of\n // pointList to elements of resultSet.\n\n var minDistSquared = new Float32Array(numPoints);\n\n // Initialize the elements. Since the only point in resultSet is firstPoint,\n // this is very easy.\n for (var i = 0; i < numPoints; i++) {\n if (i !== firstPointIndex) { // That point isn't considered\n var d = distance(firstPoint, pointList[i]);\n minDistSquared[i] = d * d;\n }\n }\n\n while (resultSet.length < k) {\n // Sum up the squared distances for the points in pointList not\n // already taken.\n var distSqSum = 0.0;\n\n for (var i = 0; i < numPoints; i++) {\n if (!taken[i]) {\n distSqSum += minDistSquared[i];\n }\n }\n\n // Add one new data point as a center. Each point x is chosen with\n // probability proportional to D(x)2\n var r = nextDouble() * distSqSum;\n\n // The index of the next point to be added to the resultSet.\n var nextPointIndex = -1;\n\n // Sum through the squared min distances again, stopping when\n // sum >= r.\n var sum = 0.0;\n for (var i = 0; i < numPoints; i++) {\n if (!taken[i]) {\n sum += minDistSquared[i];\n if (sum >= r) {\n nextPointIndex = i;\n break;\n }\n }\n }\n\n // If it's not set to >= 0, the point wasn't found in the previous\n // for loop, probably because distances are extremely small. Just pick\n // the last available point.\n if (nextPointIndex === -1) {\n for (var i = numPoints - 1; i >= 0; i--) {\n if (!taken[i]) {\n nextPointIndex = i;\n break;\n }\n }\n }\n\n // We found one.\n if (nextPointIndex >= 0) {\n\n var p = pointList[nextPointIndex];\n\n resultSet.push(new CentroidCluster(p));\n\n // Mark it as taken.\n taken[nextPointIndex] = true;\n\n if (resultSet.length < k) {\n // Now update elements of minDistSquared. We only have to compute\n // the distance to the new center to do this.\n for (var j = 0; j < numPoints; j++) {\n // Only have to worry about the points still not taken.\n if (!taken[j]) {\n var d = distance(p, pointList[j]);\n var d2 = d * d;\n if (d2 < minDistSquared[j]) {\n minDistSquared[j] = d2;\n }\n }\n }\n }\n\n } else {\n // None found --\n // Break from the while loop to prevent\n // an infinite loop.\n break;\n }\n }\n return resultSet;\n }",
"function AdjSet() {\n this._points = [];\n this._edges = [];\n }",
"function assignCentroids() {\n\n for(var p = 0; p < points.length; p++){\n var curr_best = Number.MAX_VALUE;\n var curr_centroid;\n var point = points[p];\n for(var c = 0; c < centroids.length; c++){\n var centroid = centroids[c];\n\n var dist = Math.sqrt(((point.x - centroid.x)*(point.x - centroid.x)) +((point.y - centroid.y)*(point.y - centroid.y)));\n if (dist < curr_best){\n curr_best = dist;\n curr_centroid = centroid;\n }\n }\n point.centroid = curr_centroid;\n }\n\n \n}",
"function assignCentroids() {\n\n var i; \n for (i = 0; i < points.length; i++) {\n var j;\n var minDist = Infinity;\n for (j = 0; j < centroids.length; j++) {\n var closestCentroid;\n var checkDist = Math.sqrt((centroids[j].x - points[i].x)*(centroids[j].x - points[i].x) + (centroids[j].y - points[i].y)*(centroids[j].y - points[i].y))\n //console.log(\"Distance between point and centroid: \" + checkDist);\n if (checkDist < minDist) {\n minDist = checkDist;\n closestCentroid = centroids[j];\n }\n }\n points[i].centroid = closestCentroid;\n }\n \n}",
"function getCenter(points) {\n var center = {\n x: 0,\n y: 0\n };\n for (var i = 0; i < points.length; ++i) {\n center.x += points[i].x;\n center.y += points[i].y;\n }\n center.x /= points.length;\n center.y /= points.length;\n return center;\n }",
"function getCenter(points) {\n var center = { x: 0, y: 0 };\n for (var i = 0; i < points.length; ++i) {\n center.x += points[i].x;\n center.y += points[i].y;\n }\n center.x /= points.length;\n center.y /= points.length;\n return center;\n }",
"get centroid() {}",
"function centroid(){\n var xc = 0;\n var yc = 0;\n for(var i = 0; i < conHull.length; i++){\n xc += conHull[i].x;\n yc += conHull[i].y;\n }\n xc = xc/conHull.length;\n yc = yc/conHull.length;\n return {\n x: xc,\n y: yc\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the inverted matrix | invert() {
let result = new Matrix();
result._matrix = ExtMath.inv(this._matrix);
return result;
} | [
"static get inverseMatrix() {}",
"get inverseMatrix() {\n if (this.dirty) {\n this.refreshMatrices();\n }\n return this._inv;\n }",
"inverse() {\n\t\tconst n = this.constructor.n;\n\t\tconst adj = this.adjugate();\n\t\tif(!this.det)\n\t\t\tthrow new Error(\"Matrix is not invertible\");\n\t\tconst idet = 1. / this.det;\n\t\tfor(let i = 0; i < n**2; i++)\n\t\t\tadj._val[i] = adj.val[i] * idet;\n\t\treturn adj;\n\t}",
"function matrix_invert(r){if(r.length===r[0].length){var f=0,n=0,t=0,e=r.length,o=0,i=[],g=[];for(f=0;f<e;f+=1)for(i[i.length]=[],g[g.length]=[],t=0;t<e;t+=1)i[f][t]=f==t?1:0,g[f][t]=r[f][t];for(f=0;f<e;f+=1){if(0==(o=g[f][f])){for(n=f+1;n<e;n+=1)if(0!=g[n][f]){for(t=0;t<e;t++)o=g[f][t],g[f][t]=g[n][t],g[n][t]=o,o=i[f][t],i[f][t]=i[n][t],i[n][t]=o;break}if(0==(o=g[f][f]))return}for(t=0;t<e;t++)g[f][t]=g[f][t]/o,i[f][t]=i[f][t]/o;for(n=0;n<e;n++)if(n!=f)for(o=g[n][f],t=0;t<e;t++)g[n][t]-=o*g[f][t],i[n][t]-=o*i[f][t]}return i}}",
"static inverse(matrix, inverse){\n\t\tlet x = matrix[12], y = matrix[13], z = matrix[14], w = matrix[15];\n\t\tlet a = new vector(matrix[0], matrix[4], matrix[8]), b = new vector(matrix[1], matrix[5], matrix[9]);\n\t\tlet c = new vector(matrix[2], matrix[6], matrix[10]), d = new vector(matrix[3], matrix[7], matrix[11]);\n\n\t\tlet a2 = a.scalarMultiply(y), b2 = b.scalarMultiply( x);\n\t\tlet c2 = c.scalarMultiply(w), d2 = d.scalarMultiply(z);\n\t\tlet u = vector.subtract(a2, b2);\n\t\tlet v = vector.subtract(c2, d2);\n\n\t\tlet s = vector.cross(a, b), t = vector.cross(c, d);\n\t\tlet bv = vector.cross(b, v), va = vector.cross(v, a);\n\t\tlet du = vector.cross(d, u), uc = vector.cross(u, c);\n\n\t\tlet t2 = t.scalarMultiply(y), t3 = t.scalarMultiply(x); \n\t\tlet s2 = s.scalarMultiply(w), s3 = s.scalarMultiply(z);\n\t\tlet r0 = vector.add(bv, t2);\n\t\tlet r1 = vector.subtract(va, t3);\n\t\tlet r2 = vector.add(du, s2);\n\t\tlet r3 = vector.subtract(uc, s3);\n\n\t\tlet invDet = 1 / (vector.dot(s, v) + vector.dot(t,u));\n\t\tr0 = r0.scalarMultiply(invDet);\n\t\tr1 = r1.scalarMultiply(invDet);\n\t\tr2 = r2.scalarMultiply(invDet);\n\t\tr3 = r3.scalarMultiply(invDet);\n\t\t\n\t\tinverse[0] = r0.x; inverse[4] = r0.y; inverse[8] = r0.z;inverse[1] = r1.x; \n\t\tinverse[5] = r1.y; inverse[9] = r1.z; inverse[2] = r2.x; inverse[6] = r2.y; inverse[10] = r2.z;\n\t\tinverse[3] = r3.x; inverse[7] = r3.y; inverse[11] = r3.z; inverse[12] = -1 * vector.dot(b, t) * invDet; \n\t\tinverse[13] = vector.dot(a, t) * invDet; inverse[14] = -1 * vector.dot(d, s) * invDet; \n\t\tinverse[15] = vector.dot(c, s) * invDet; \n\t}",
"inv() {\n if (this.rows !== this.cols) throw \"Impossibile trovare la matrice inversa di una matrice non quadrata\"\n let det = this.det();\n if (det.equals(0)) throw \"Impossibile calcolare la matrice inversa quando il determinante è uguale a zero\";\n let newMat = this._createMatrix();\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.cols; j++) {\n newMat[i][j] =\n new Matrix(this.rows - 1, this.cols - 1, this._eliminaRigaColonna(this.matrix, i, j)).det()\n .mult(Math.pow(-1, i + j));\n }\n }\n return new Matrix(this.rows, this.cols, newMat).tr().mult(det.reciprocal());\n }",
"static set inverseMatrix(value) {}",
"inverse()\r\n {\r\n var newMatrix = this.duplicateMatrix();\r\n\r\n // make an identity matrix with the same dimensions as this matrix\r\n var identityArr = [];\r\n for (var r = 0; r < a.m; r++)\r\n {\r\n identityArr.push([])\r\n for (var c = 0; c < a.n; c++)\r\n {\r\n if (c == r)\r\n identityArr[r][c] = 1;\r\n else\r\n identityArr[r][c] = 0;\r\n }\r\n }\r\n\r\n // run the RREF algorithm and do all the row operations on the identity matrix simultaneously\r\n var invertedMatrix = new Matrix(identityArr);\r\n\r\n var completeRows = 0;\r\n // repeat until all rows are complete\r\n while (completeRows < newMatrix.m)\r\n {\r\n // find the row with the leftmost leading variable\r\n // by looping through incomplete rows, finding which has min leadingVar\r\n var leadingIndex = newMatrix.indexOfLeadingVar(completeRows);\r\n var leadingRow = completeRows;\r\n var leadingVar = newMatrix.matrix[completeRows][leadingIndex];\r\n\r\n for (var r = completeRows; r < newMatrix.m; r++)\r\n {\r\n var rowIndex = newMatrix.indexOfLeadingVar(r)\r\n if (rowIndex < leadingIndex)\r\n {\r\n leadingIndex = rowIndex;\r\n leadingRow = r;\r\n leadingVar = newMatrix.matrix[r][leadingIndex];\r\n }\r\n }\r\n\r\n // swap this row with the topmost incomplete row\r\n if (leadingRow != completeRows)\r\n {\r\n newMatrix.swapRows(leadingRow, completeRows);\r\n invertedMatrix.swapRows(leadingRow, completeRows);\r\n }\r\n\r\n if (!newMatrix.isZeroRow(completeRows))\r\n {\r\n // multiply the row by 1/leadingVar\r\n newMatrix.scaleRow(completeRows, math.divide(1, leadingVar));\r\n invertedMatrix.scaleRow(completeRows, math.divide(1, leadingVar));\r\n\r\n // subtract (c * this row) from all other rows,\r\n // where c = the coefficient in the same column as this row's leading variable\r\n for (var r = 0; r < newMatrix.m; r++)\r\n {\r\n if (r != completeRows)\r\n {\r\n var c = math.multiply(newMatrix.matrix[r][leadingIndex], -1);\r\n newMatrix.addRows(c, completeRows, r);\r\n invertedMatrix.addRows(c, completeRows, r);\r\n }\r\n }\r\n }\r\n\r\n // increase the complete rows counter by one\r\n completeRows++;\r\n }\r\n return invertedMatrix;\r\n\r\n }",
"get inverse() {\r\n if (this._shouldUpdateInverse) {\r\n mat4InvertCompat(this._inverseCache.copy(this.matrix));\r\n this._shouldUpdateInverse = false;\r\n }\r\n return this._inverseCache;\r\n }",
"get viewMatrixInverseTranspose() {\r\n\t\treturn this._v.inverseTranspose;\r\n\t}",
"get viewMatrixInverse() {\r\n\t\treturn this._v.inverse;\r\n\t}",
"static inverse(matrix, result = new M4()) {\n return matrix.inversed4(result);\n }",
"invert(outMatrix, inMatrix) {\n let a00 = inMatrix[0], a01 = inMatrix[1], a02 = inMatrix[2], a03 = inMatrix[3];\n let a10 = inMatrix[4], a11 = inMatrix[5], a12 = inMatrix[6], a13 = inMatrix[7];\n let a20 = inMatrix[8], a21 = inMatrix[9], a22 = inMatrix[10], a23 = inMatrix[11];\n let a30 = inMatrix[12], a31 = inMatrix[13], a32 = inMatrix[14], a33 = inMatrix[15];\n \n let b00 = a00 * a11 - a01 * a10;\n let b01 = a00 * a12 - a02 * a10;\n let b02 = a00 * a13 - a03 * a10;\n let b03 = a01 * a12 - a02 * a11;\n let b04 = a01 * a13 - a03 * a11;\n let b05 = a02 * a13 - a03 * a12;\n let b06 = a20 * a31 - a21 * a30;\n let b07 = a20 * a32 - a22 * a30;\n let b08 = a20 * a33 - a23 * a30;\n let b09 = a21 * a32 - a22 * a31;\n let b10 = a21 * a33 - a23 * a31;\n let b11 = a22 * a33 - a23 * a32;\n \n // Calculate the determinant\n let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n \n if (!det) {\n return null;\n }\n det = 1.0 / det;\n \n outMatrix[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n outMatrix[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n outMatrix[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n outMatrix[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n outMatrix[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n outMatrix[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n outMatrix[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n outMatrix[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n outMatrix[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n outMatrix[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n outMatrix[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n outMatrix[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n outMatrix[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n outMatrix[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n outMatrix[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n outMatrix[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n \n return outMatrix;\n }",
"invert(outMatrix, inMatrix) {\r\n let a00 = inMatrix[0], a01 = inMatrix[1], a02 = inMatrix[2], a03 = inMatrix[3];\r\n let a10 = inMatrix[4], a11 = inMatrix[5], a12 = inMatrix[6], a13 = inMatrix[7];\r\n let a20 = inMatrix[8], a21 = inMatrix[9], a22 = inMatrix[10], a23 = inMatrix[11];\r\n let a30 = inMatrix[12], a31 = inMatrix[13], a32 = inMatrix[14], a33 = inMatrix[15];\r\n \r\n let b00 = a00 * a11 - a01 * a10;\r\n let b01 = a00 * a12 - a02 * a10;\r\n let b02 = a00 * a13 - a03 * a10;\r\n let b03 = a01 * a12 - a02 * a11;\r\n let b04 = a01 * a13 - a03 * a11;\r\n let b05 = a02 * a13 - a03 * a12;\r\n let b06 = a20 * a31 - a21 * a30;\r\n let b07 = a20 * a32 - a22 * a30;\r\n let b08 = a20 * a33 - a23 * a30;\r\n let b09 = a21 * a32 - a22 * a31;\r\n let b10 = a21 * a33 - a23 * a31;\r\n let b11 = a22 * a33 - a23 * a32;\r\n \r\n // Calculate the determinant\r\n let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\r\n \r\n if (!det) {\r\n return null;\r\n }\r\n det = 1.0 / det;\r\n \r\n outMatrix[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\r\n outMatrix[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\r\n outMatrix[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\r\n outMatrix[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\r\n outMatrix[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\r\n outMatrix[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\r\n outMatrix[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\r\n outMatrix[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\r\n outMatrix[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\r\n outMatrix[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\r\n outMatrix[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\r\n outMatrix[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\r\n outMatrix[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\r\n outMatrix[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\r\n outMatrix[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\r\n outMatrix[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\r\n \r\n return outMatrix;\r\n }",
"get viewMatrixInverseTranspose$() {\r\n\t\treturn this._v.inverseTranspose$;\r\n\t}",
"get viewMatrixInverse() {\n\t\treturn this._v.inverse;\n\t}",
"get viewMatrixInverseTranspose() {\n\t\treturn this._v.inverseTranspose;\n\t}",
"get viewMatrixInverse$() {\r\n\t\treturn this._v.inverse$;\r\n\t}",
"get modelMatrixInverse() {\r\n\t\treturn this._m.inverse;\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION THAT CREATES FACULTY | function createFaculty(name) {
return new Faculty(name);
} | [
"function giveDifficulties(difficulty) {\r\n difficulties = difficulty;\r\n}",
"function createTeam() {\n inquirer.prompt([\n {\n type: 'list',\n name: 'memberChoice',\n message: 'What team member would you like to create?',\n choices: [\n 'Engineer',\n 'Intern',\n 'I\\'m done creating my team'\n ]\n },\n ]).then(userChoice => {\n if (userChoice.memberChoice === 'Engineer') {\n createEngineer();\n } else if (userChoice.memberChoice === 'Intern') {\n createIntern();\n } else {\n buildTeam();\n }\n }\n )\n}",
"function createNewFaculty(facultyInstance) {\n var faculty = {};\n faculty.facultyName = facultyInstance;\n facultyService.insertNewFaculty(faculty).then(function (response) {\n if (response.status === 200) {\n swal('success', \"insert new faculty\", 'success');\n getFacultyData();\n } else {\n swal('Error', 'Not inserted record', 'error');\n }\n });\n }",
"function makeNewTaskDifficulty()\n{\n const cell = makeTableCell(\"difficulty\");\n return cell;\n}",
"function createTeam() {\n inquirer.prompt(teamAdd).then(response => {\n if (response.team === \"Engineer\") {\n createEngineer();\n } else if (response.team === \"Intern\") {\n createIntern();\n } else if (response.team === \"None\") {\n const finalHTML = render(teamMembers)\n fs.writeFile(\"./output/team.html\", finalHTML, function (err) {\n if (err) {\n return console.log(err);\n }\n console.log(\"File written!\");\n });\n }\n })\n}",
"function generateFaculties() {\n var faculties = [];\n\n for (var i = 0; i < 100; i++) {\n faculties.push({\n id: i,\n name: 'Faculty #'+i,\n university: \"University #\"+(Math.floor(Math.random() * 25) + 1)\n });\n }\n return faculties;\n}",
"createDifficultySelect() {\n const difficultySelect = document.createElement(\"select\");\n difficultySelect.id = \"ms-js-difficulty\";\n for(let i=0; i<this.difficulties.length; i++) {\n let option = document.createElement(\"option\");\n option.value = i;\n option.text = this.difficulties[i].name;\n if(i===this.selectedDifficulty) {\n option.setAttribute(\"selected\", true);\n }\n difficultySelect.appendChild(option);\n }\n\n difficultySelect.addEventListener(\"change\", () => {\n const selected = parseInt(difficultySelect.value);\n if(selected!==this.selectedDifficulty) {\n const difficulty = this.difficulties[selected];\n this.newGame(difficulty.x, difficulty.y, difficulty.mines);\n this.selectedDifficulty = selected;\n }\n });\n\n return difficultySelect;\n }",
"function createTeam() {\n inquirer.prompt(teamAdd).then(response => {\n switch (response.team) {\n case \"Engineer\":\n createTeamMember(engineerQuestions, Engineer);\n break;\n case \"Intern\":\n createTeamMember(internQuestions, Intern);\n break;\n default:\n // if none, render team members array into file\n const finalHTML = render(teamMembers)\n fs.writeFile(\"./output/team.html\", finalHTML, function (err) {\n if (err) {\n return console.log(err);\n }\n console.log(\"File written!\");\n });\n }\n })\n}",
"function newMember() {\n inquirer.prompt([\n {\n type: 'list',\n name: 'typeEmployee',\n message: 'What type of employee would you like to add?',\n choices: ['Engineer', 'Intern', 'Manager', 'Thats everyone!']\n },\n // Switch statement works, changed 'employee-type' to 'typeEmployee', program didn't like \"answers.employee-type\"\n ]).then((answers) => {\n switch (answers.typeEmployee) {\n case \"Engineer\":\n newEngineer();\n break;\n case \"Intern\":\n newIntern();\n break;\n case \"Manager\":\n makeTeam();\n break;\n case \"Thats everyone!\":\n makeHTML();\n break;\n }\n })\n}",
"function generateNewTeamMember() {\n inquirer.prompt([\n { type: \"list\",\n message: \"Which type of team member would you like to add?\",\n name: \"role\",\n choices: [ \n \"Engineer\", \n \"Intern\", \n \"I don't want to add any more team members\",\n ]}])\n .then (response => {\n if (response.role === \"Engineer\"){\n addEngineer();\n } else if (response.role === \"Intern\"){\n addIntern();\n }else{\n // After the user has input all employees desired, call the `render` function (required\n // above) and pass in an array containing all employee objects; the `render` function will\n // generate and return a block of HTML including templated divs for each employee!\n const html = render(employees);\n fs.writeFile(outputPath, html, (err) => {\n if (err) throw err;\n });\n }\n })\n }",
"function createEmployee() {\n inquirer.prompt(profileType)\n .then((answers) => {\n if (answers.profile === \"Engineer\") {\n engineerFunc()\n }\n if (answers.profile === \"Intern\") {\n internFunc();\n }\n if (answers.profile === \"Manager\") {\n managerFunc();\n }\n \n })\n ;\n}",
"addDifficulty() {\n var difficulty = this.getDifficulty();\n var difficultyHolder = document.getElementById(\"difficultyStamp\");\n\n switch (difficulty) {\n case \"easy\":\n difficultyHolder.textContent = \"Mode: Easy\";\n break;\n case \"medium\":\n difficultyHolder.textContent = \"Mode: Medium\";\n break;\n case \"hard\":\n difficultyHolder.textContent = \"Mode: Hard\";\n break;\n }\n }",
"function legendaryAttribute(){\n//____________________________________________________________________________________________________\n\n\n//Set Name\n\n\n//____________________________________________________________________________________________________\nabilityName = prompt(\"What is the Name of your Legendary Ability ?\")\nname1 = prompt(\"What is the First-Part Aspect Name from your Legendary Ability ?\")\nname2 = prompt(\"What is the Second-Part Aspect Name from your Legendary Ability ?\")\nvariableName = abilityName.replace(/\\s/g, '');\nname = variableName + \" = new LegendaryAbility([\\\"\" + abilityName + \"\\\"\" + \",\\\"\" + name1 + \"\\\"\" + \",\\\"\" + name2 + \"\\\"]\" \n\n\n//____________________________________________________________________________________________________\n\n\n//Set NPC Types\n\n//____________________________________________________________________________________________________\n\n\nfunction typeChoiceFunction (){\ntypeChoicePrompt = prompt(\"What type of creature is your NPC ? \\n1- Titanspawn \\n2- Mythborn\");\nif (typeChoicePrompt == \"1\") {titanspawnTypeChoiceFunction();\n}\nelse if (typeChoicePrompt == \"2\") {mythbornTypeChoiceFunction()}\nelse if (typeChoicePrompt !== \"1\" && typeChoicePrompt !== \"2\"){typeChoiceFunction()}\n}\nnpcOptions = \"\"\n typeChoiceFunction() \n\nfunction restart(){\n if(npcOptions === \"\"){npcOptions += (\"[\\\"\" + typeChoice + \"\\\"\" + \",\\\"\" + originChoice + \"\\\"\" + \",\\\"\" + subOriginChoice + \"\\\"]\"); titanspawnTypeChoiceFunction()} \n else{npcOptions += (\",[\\\"\" + typeChoice + \"\\\"\" + \",\\\"\" + originChoice + \"\\\"\" + \",\\\"\" + subOriginChoice + \"\\\"]\"); titanspawnTypeChoiceFunction()}\n}\n\nfunction restart2(){\n if(npcOptions === \"\"){npcOptions += (\"[\\\"\" + typeChoice + \"\\\"\" + \",\\\"\" + originChoice + \"\\\"\" + \",\\\"\" + subOriginChoice + \"\\\"]\"); mythbornTypeChoiceFunction()} \n else{npcOptions += (\",[\\\"\" + typeChoice + \"\\\"\" + \",\\\"\" + originChoice + \"\\\"\" + \",\\\"\" + subOriginChoice + \"\\\"]\"); mythbornTypeChoiceFunction()}\n}\n\nfunction titanspawnTypeChoiceFunction() {\ntypeChoice = \"Titanspawn\";\n\n originChoice = prompt(\"Which Titan is your Titanspawn from ? Possibilities: \\n1 - Muspelheim \\n2 - Nyx \\n3 - Soku no Kumi \\n4 - Aether \\n5 - Amaunet \\n6 - Terra \\n7 - Nun \\n8 - Death \\n99 - Move to Mythborn \\n0 - End\");\n if (originChoice === \"1\") {\n subOriginChoice = prompt(\"What Avatar of Muspelheim is your Titanspawn linked to ? \\n11 - Vrtra \\n12 - Surtr \\n13 - Prometheus \\n99 - Any\");\n restart()}\n else if (originChoice === \"2\") {\n subOriginChoice = prompt(\"What Avatar of Nyx is your Titanspawn linked to ? \\n21 - Nott \\n22 - Fenrir \\n23 - Apep \\n24 - Selene \\n99 - Any\");\n restart()}\n else if (originChoice === \"3\") {\n subOriginChoice = prompt(\"What Avatar of Soku no Kumi is your Titanspawn linked to ? \\n31 - Huehueteotl \\n32 - Mikaboshi \\n33 - Erebus \\n99 Any\");\n restart()}\n else if (originChoice === \"4\") {\n subOriginChoice = prompt(\"What Avatar of Aether is your Titanspawn linked to ? \\n41 - Aten\\n42 - Hyperion\\n99 - Any\");\n restart()}\n else if (originChoice === \"5\") {\n subOriginChoice = prompt(\"What Avatar of Amaunet is your Titanspawn linked to ? \\n51 - Huracan\\n52 - Typhon\\n53 - Ouranos\\n99 - Any\");\n restart();}\n else if (originChoice === \"6\") {\n subOriginChoice = prompt(\"What Avatar of Terra is your Titanspawn linked to ? Possibilities:\\n61 - Gaia\\n62 - Kur\\n63 - Dis Pater\\n64 - Ourea \\n65 - Crom Cruach \\n99 - Any\"); \n restart();}\n else if (originChoice === \"7\") {\n subOriginChoice = prompt(\"What Avatar of Nun is your Titanspawn linked to ? Possibilities: \\n71 Yam \\n72 - Tiamat \\n73 - Abzu \\n74 - Cipactli \\n99 - Any\"); \n restart();}\n\n else if (originChoice === \"8\") {\n subOriginChoice = prompt(\"What Avatar of Death is your Titanspawn linked to ? Possibilities: \\n81 - Styx\\n82 - Grim Reaper \\n83 - Camatotz \\n99 - Any\");\n restart();}\n \n else if (originChoice === \"0\") {\n return; }\n\n else if (originChoice === \"99\") {\n mythbornTypeChoiceFunction(); } \n \n else{titanspawnTypeChoiceFunction();}\n\n}\n \nfunction mythbornTypeChoiceFunction(){ \ntypeChoice = \"Mythborn\"; \n originChoice = prompt(\"Which Race is your Mythborn ? Possibilities: \\n1 - Summer Court of Fairie \\n2 - Winter Court of Fairie \\n3 - Jade Sea \\n4 - Dark Forest \\n5 - Shambhala \\n6 - Atlantis \\n0 - End\");\n if (originChoice === \"1\") {\n subOriginChoice = prompt(\"What type of Summer Court Fairie Mythborn is your NPC ? \\n11 - Fey \\n12 - Elf \\n13 - Small Folk \\n14 - Pixie \\n15 - Nymph \\n98 - Any\");\n restart2()}\n else if (originChoice === \"2\") {\n subOriginChoice = prompt(\"What type of Winter Court Fairie Mythborn is your NPC ? \\n21 - Fey \\n22 - Elf \\n23 - Small Folk \\n24 - Pixie \\n25 - Nymph \\n98 - Any\");\n restart2()}\n else if (originChoice === \"3\") {\n subOriginChoice = prompt(\"What type of Jade Sea Mythborn is your NPC ? \\n31 - Western Dragon \\n32 - Eastern Dragon \\n33 - Wyvern \\n34 - Coatl \\n35 - Naga \\n98 - Any\");\n restart2()}\n else if (originChoice === \"4\") {\n subOriginChoice = prompt(\"What type of Dark Forest Mythborn is your NPC ? \\n41 - Ent \\n42 - Small Folk \\n43 - Garou \\n44 - Witch \\n98 - Any\");\n restart2()}\n else if (originChoice === \"5\") {\n subOriginChoice = prompt(\"What type of Shambhala Mythborn is your NPC ? \\n51 - Raksasha \\n52 - Asura \\n53 - Nymph \\n54 - Naga \\n98 - Any\");\n restart2()}\n else if (originChoice === \"6\") {\n subOriginChoice = prompt(\"What type of Atlantis Mythborn is your NPC ? \\n61 - Triton \\n62 - Nymph \\n98 - Any\");\n restart2()} \n else if (originChoice === \"0\") {\n return; } \n \n else{mythbornTypeChoiceFunction();}\n} \n\n//____________________________________________________________________________________________________\n\n\n//Set Combat 1\n\n//____________________________________________________________________________________________________\ncombat1Options = \"\"\n\nfunction combat1ChoiceFunction() {\n combatChoice1 = prompt(\"What is your NPC's combat style ? \\n 1 - Warrior\\n 2 - Mage\\n 3 - Rogue \\n 0 - End\");\n if (combatChoice1 === \"1\" || combatChoice1 === \"2\" || combatChoice1 === \"3\") {\n if(combat1Options === \"\"){ combat1Options += (\"\\\"\" + combatChoice1 + \"\\\"\");combat1ChoiceFunction(); }\n else{combat1Options += (\",\\\"\" + combatChoice1 + \"\\\"\");combat1ChoiceFunction();}\n }\n\n \n};\ncombat1ChoiceFunction()\n\n//____________________________________________________________________________________________________\n\n\n//Set Combat 2\n\n//____________________________________________________________________________________________________\ncombat2Options = \"\"\n\nfunction combat2ChoiceFunction() {\n combatChoice2 = prompt(\"What is your NPC's combat speciality ? \\n1 - Support \\n2 - Fighter \\n3 - Controller \\n4 - Tank \\n 0 - End\");\n if (combatChoice2 === \"1\" || combatChoice2 === \"2\" || combatChoice2 === \"3\" || combatChoice2 === \"4\") {\n if(combatChoice2 === \"\"){ combatChoice2 += (\"\\\"\" + combatChoice2 + \"\\\"\");combat2ChoiceFunction(); }\n else{combat2Options += (\",\\\"\" + combatChoice2 + \"\\\"\");combat2ChoiceFunction(); }}\n \n}\ncombat2ChoiceFunction()\n\n//____________________________________________________________________________________________________\n\n\n//Set Intelligence\n\n//____________________________________________________________________________________________________\n\n\nintelligenceOptions = \"\"\n\nfunction intelligenceChoiceFunction() {\n intelligenceChoice = prompt(\"What is your NPC's Intelligence ? \\n1 - Feral \\n2 - Human \\n 0 - End\");\n if (intelligenceChoice === \"1\" || intelligenceChoice === \"2\" || intelligenceChoice === \"3\" || intelligenceChoice === \"4\") {\n if(intelligenceChoice === \"\"){ intelligenceOptions += (\"\\\"\" + intelligenceChoice + \"\\\"\");intelligenceChoiceFunction(); }\n else{intelligenceOptions += (\",\\\"\" + intelligenceChoice + \"\\\"\");intelligenceChoiceFunction(); }}\n \n}\nintelligenceChoiceFunction()\n\n\n\nalert(name + \",[\" + npcOptions + \"],[\" + combat1Options + \"],[\" + combat2Options + \"],[\" + intelligenceOptions + \"]),\")\n}",
"function difficulty(num){\n if(num <= 333)\n return \"Easy\";\n else if(num <= 667)\n return \"Medium\";\n else\n return \"Hard\";\n}",
"function createGame() {\r\n createBoard();\r\n createCoins();\r\n createRules();\r\n}",
"function createQuizData() {\n\n //create all people with their required values\n var alanKay = MakePerson(\"Alan Kay\", \"images/alan_kay.jpg\", \"If you're not failing 90% of the time, then you're probably not working on sufficiently challenging problems.\");\n var edsgerDijkstra = MakePerson(\"Edsger Dijkstra\", \"images/edsger_dijkstra.jpg\", \"The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.\");\n var billGates = MakePerson(\"Bill Gates\", \"images/bill_gates.jpg\", \"Success is a lousy teacher. It seduces smart people into thinking they can’t lose.\");\n var ericSchmidt = MakePerson(\"Eric Schmidt\",\"images/eric_schmidt.jpg\", \"The Internet is the first thing that humanity has built that humanity doesn't understand, the largest experiment in anarchy that we have ever had.\");\n var linusTorvalds = MakePerson(\"Linus Torvalds\",\"images/linus_torvalds.jpg\", \"Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program\");\n var markZuckerberg = MakePerson(\"Mark Zuckerberg\", \"images/mark_zuckerberg.jpg\", \"In a world that's changing really quickly, the only strategy that is guaranteed to fail is not taking risks.\");\n var raymondKurzweil = MakePerson(\"Raymond Kurzweil\", \"images/raymond_kurzweil.jpg\",\"By 2029, computers will have emotional intelligence and be convincing as people.\");\n var stephenHawking = MakePerson(\"Stephen Hawking\", \"images/stephen_hawking.jpg\", \"I think computer viruses should count as life. I think it says something about human nature that the only form of life we have created so far is purely destructive. We've created life in our own image.\");\n var steveJobs = MakePerson(\"Steve Jobs\", \"images/steve_jobs.jpg\", \"Innovation distinguishes between a leader and a follower.\");\n var steveWozniak = MakePerson(\"Steve Wozniak\", \"images/steve_wozniak.jpg\", \"My goal wasn't to make a ton of money. It was to build good computers.\");\n\n //create all questions with the correct choice of people and the index of the correct answer\n var question1 = MakeQuestion(billGates, steveJobs, markZuckerberg, 1);\n var question2 = MakeQuestion(steveWozniak, edsgerDijkstra, billGates, 2);\n var question3 = MakeQuestion(ericSchmidt, markZuckerberg, linusTorvalds, 2);\n var question4 = MakeQuestion(markZuckerberg, billGates, steveJobs, 0);\n var question5 = MakeQuestion(edsgerDijkstra, alanKay, stephenHawking, 1);\n var question6 = MakeQuestion(ericSchmidt, stephenHawking, steveJobs, 0);\n var question7 = MakeQuestion(alanKay, raymondKurzweil, steveWozniak, 1);\n var question8 = MakeQuestion(edsgerDijkstra, raymondKurzweil, stephenHawking, 2);\n var question9 = MakeQuestion(linusTorvalds, steveJobs, edsgerDijkstra, 2);\n var question10 = MakeQuestion(billGates, steveWozniak, steveJobs, 1);\n\n //create list of questions\n questionList = [question1, question2, question3, question4, question5, question6, question7, question8, question9, question10];\n\n //shuffle list of questions from: https://css-tricks.com/snippets/javascript/shuffle-array/\n questionList.sort(function() {\n return 0.5 - Math.random()\n });\n\n //copy of list of questions used for output since the original uses pop()\n questionListCopy = questionList.slice();\n }",
"function nextDifficulty() {\n console.log(\"nextDifficulty\")\n DIFFICULTY ++\n}",
"function createTeam(name, skill) {\n return{\n name: name,\n skill: skill,\n };\n}",
"function setDifficulty(dif){\n if(dif==='easy'){\n elementsAroundMines.clear();\n clear();\n amountOfMines=10;\n elementsCount=100;\n difficulty='easy';\n drawGame(100, '50vw', '80vh', '10%', '10%', 10, 10);\n }\n if(dif==='normal'){\n elementsAroundMines.clear();\n clear();\n amountOfMines=38;\n elementsCount=240;\n difficulty='normal';\n drawGame(240, '65vw', '80vh', '5%', '8.33333%', 12, 20);\n }\n if(dif==='hard'){\n elementsAroundMines.clear();\n clear();\n amountOfMines=90;\n elementsCount=500;\n difficulty='hard';\n drawGame(500, '80vw', '80vh', '4%', '5%', 20, 25); \n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expands the given item tree. | expandItem(item){if(!this._isExpanded(item)){this.push("expandedItems",item)}} | [
"expandItem(item){if(!this._isExpanded(item)){this.push('expandedItems',item);}}",
"expandItem(item) {\n if (!this._isExpanded(item)) {\n this.push('expandedItems', item);\n }\n }",
"expandItem(item) {\n if (!this._isExpanded(item)) {\n this.push('expandedItems', item);\n }\n }",
"function expandItem(){\n vm.expanded = !vm.expanded;\n }",
"collapseItem(item){if(this._isExpanded(item)){this.splice('expandedItems',this._getItemIndexInArray(item,this.expandedItems),1);}}",
"collapseItem(item){if(this._isExpanded(item)){this.splice(\"expandedItems\",this._getItemIndexInArray(item,this.expandedItems),1)}}",
"function expandItem(item) {\n item._collapsed = false;\n _expandedRows.push(item);\n \n // display pre-loading template\n if (!item._detailViewLoaded || _options.loadOnce !== true) {\n item._detailContent = _options.preTemplate(item);\n } else {\n _self.onAsyncResponse.notify({\n \"itemDetail\": item,\n \"detailView\": item._detailContent\n }, undefined, this);\n applyTemplateNewLineHeight(item);\n _dataView.updateItem(item.id, item);\n\n return;\n }\n\n applyTemplateNewLineHeight(item);\n _dataView.updateItem(item.id, item);\n\n // async server call\n _options.process(item);\n }",
"expand(item) {\n const that = this;\n\n if (typeof item === 'number') {\n item = that._items[item];\n }\n\n if (!item) {\n return;\n }\n\n const closestSplitter = (that.enableShadowDOM ? item.getRootNode().host : item).closest('jqx-splitter')\n\n if (item instanceof JQX.SplitterItem && closestSplitter === that) {\n item.expand();\n return;\n }\n\n if (typeof item !== 'number' || !that._items[item]) {\n that.error(that.localize('invalidIndex', { elementType: that.nodeName.toLowerCase(), method: 'expand' }));\n return;\n }\n\n item.expand();\n }",
"expand(item) {\n const that = this;\n\n if (typeof item === 'number') {\n item = that._items[item];\n }\n\n if (!item) {\n return;\n }\n\n const closestSplitter = that.closest('smart-splitter') || (that.getRootNode() && that.getRootNode().host ? that.getRootNode().host.closest('smart-splitter') : undefined);\n\n if (item instanceof Smart.SplitterItem && closestSplitter === that) {\n item.expand();\n return;\n }\n\n if (typeof item !== 'number' || !that._items[item]) {\n that.error(that.localize('invalidIndex', { elementType: that.nodeName.toLowerCase(), method: 'expand' }));\n return;\n }\n\n item.expand();\n }",
"ExpandAll() {\n if (this.IsNode) {\n for (let i = 0, ln = this.fItems.length; i < ln; i++) {\n this.fItems[i].ExpandAll();\n }\n\n this.Expand();\n }\n }",
"expand() {\n const args = {\n owner: this.tree,\n node: this,\n cancel: false\n };\n this.tree.nodeExpanding.emit(args);\n if (!args.cancel) {\n this.treeService.expand(this, true);\n this.cdr.detectChanges();\n this.playOpenAnimation(this.childrenContainer);\n }\n }",
"function expandCompressNode(id) {\t\n\tvar node = nodeIndex[id];\n\t \n\tif (!node.expanded) {\n\t\tnode.expandChildren();\n\t} else {\t\t\n\t\tnode.expanded = false;\n\t\tnode.compressChildren();\n\t}\n}",
"function expandLevel() {\n instance.collapse(1);\n instance.expand(1);\n}",
"function ECMS_expand(name, tree) {\n\tECMS_control_node(ECMS_find_node_name(tree, name), 1);\n}",
"function customExpand( node ) {\n // stores the current node's collapsed children nodes into an array\n var collapsedChildren = new Array();\n jQuery.each( node.getSubnodes(1), function( i, v ) { // starting from its first child, not itself (as getSubnodes() would do)\n if( v.collapsed ) {\n collapsedChildren.push( v );\n v.collapsed = false;\n }\n });\n\n st.op.expand( node ); // expand node; node is set to not collapsed\n\n // if there were collapsed children nodes, re-collapse the children that were previously set to collapse, as expanding the current node had expanded all its children too\n if( collapsedChildren.length ) {\n jQuery.each( collapsedChildren, function( i, v ) {\n st.op.contract( v );\n });\n }\n}",
"_expandItemsByDefault(collapseBeforehand) {\n const that = this;\n\n if (that._menuItemsGroupsToExpand.length === 0 && !collapseBeforehand ||\n that.mode !== 'tree' && !that._minimized) {\n return;\n }\n\n const restoreAnimation = that.hasAnimation,\n animationType = that.animation;\n\n if (restoreAnimation) {\n that.animation = 'none';\n }\n\n if (collapseBeforehand) {\n that._collapseAll(false);\n }\n\n for (let i = 0; i < that._menuItemsGroupsToExpand.length; i++) {\n that.expandItem(that._menuItemsGroupsToExpand[i].path, undefined, false);\n }\n\n if (restoreAnimation) {\n that.animation = animationType;\n }\n\n that._menuItemsGroupsToExpand = [];\n }",
"function expandObjTree(data) {\n\n\tif (!resp) return false;\n\n\tvar curchild = data;\n\tvar i = 0;\n\tvar subdiv = document.getElementById(curchild.expandSingle);\n\t\n\tsubdiv.innerHTML = \"\";\n\tsubdiv.appendChild(createTree(curchild));\n\n}",
"collapseItem(item) {\n if (this._isExpanded(item)) {\n this.splice('expandedItems', this._getItemIndexInArray(item, this.expandedItems), 1);\n }\n }",
"expandNodeRecursive(){this._selectedField.expandRecursive()}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio. | get halfDrawWidth() {
return this.drawWidth / 2;
} | [
"get drawWidth() {\n if (this._camera) {\n return this.scaledWidth / this._camera.z / this.pixelRatio;\n }\n return this.scaledWidth / this.pixelRatio;\n }",
"get halfDrawWidth() {\n return this.screen.halfDrawWidth;\n }",
"static get screenWidth() {\n if (Engine.client === exports.Client.Electron)\n return GameWindow.browserWindow.getContentSize()[0];\n else\n return Engine.graphics.canvas.getBoundingClientRect().width;\n }",
"get halfCanvasWidth() {\n return this.screen.halfCanvasWidth;\n }",
"get drawWidth() {\n return this.screen.drawWidth;\n }",
"get screenWidthInWorldPixels()\n {\n return this.screenWidth / this.scale.x;\n }",
"get halfCanvasWidth() {\n return this.canvas.width / 2;\n }",
"get screenWidthInWorldPixels()\n {\n return this.screenWidth / this.scale.x;\n }",
"get screenWidthInWorldPixels() {\n return this.screenWidth / this.scale.x;\n }",
"get halfWidth() {\n return Math.round(this._frame.size.width/2);\n }",
"get pixelWidth() {}",
"function widthScaling() {\n var canvas = document.getElementById(\"gameWorld\");\n var htmlCanvasWidth = canvas.width;\n var cssCanvasWidth = parseFloat(window.getComputedStyle(canvas).width);\n return cssCanvasWidth / htmlCanvasWidth;\n}",
"get canvasWidth() {\n return this.screen.canvasWidth;\n }",
"getPictureWidth() {\n const mwm = (this.camera.MatrixWidth / 10000); /* Matrix Width in meters */\n const { altitude } = this.mission;\n const fm = (this.camera.Focal / 10000); /* focal in meters */\n return ((mwm * altitude) / fm).toFixed(2);\n }",
"_getCanvasWidthInWorldUnits() {\n return (1.0 / this._scaleFactor) * CANVAS_WIDTH_PX;\n }",
"get worldScreenWidth() {\n return this.screenWidth / this.scale.x;\n }",
"function _getWidth() {\r\n\t\t\treturn self.isOneColumnView() ? 12 : self.tile.width;\r\n\t\t}",
"function windowWidthFactor(game) {\n return game.canvas.width / 1366;\n}",
"function getCanvasSize() {\n\tlet canvasSize;\n\t\t\n\tif(innerWidth > innerHeight) {\n\t\tcanvasSize = innerHeight / 2;\n\t}else {\n\t\tcanvasSize = innerWidth / 2;\n\t}\n\t\t\n\treturn canvasSize;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile arguments, pushing an Arguments object onto the stack. | function CompileArgs({
params,
hash,
blocks,
atNames
}) {
let out = [];
let blockNames = blocks.names;
for (let i = 0; i < blockNames.length; i++) {
out.push(Object(_blocks__WEBPACK_IMPORTED_MODULE_3__["PushYieldableBlock"])(blocks.get(blockNames[i])));
}
let {
count,
actions
} = CompilePositional(params);
out.push(actions);
let flags = count << 4;
if (atNames) flags |= 0b1000;
if (blocks) {
flags |= 0b111;
}
let names = _glimmer_util__WEBPACK_IMPORTED_MODULE_0__["EMPTY_ARRAY"];
if (hash) {
names = hash[0];
let val = hash[1];
for (let i = 0; i < val.length; i++) {
out.push(Object(_encoder__WEBPACK_IMPORTED_MODULE_1__["op"])('Expr', val[i]));
}
}
out.push(Object(_encoder__WEBPACK_IMPORTED_MODULE_1__["op"])(84
/* PushArgs */
, Object(_operands__WEBPACK_IMPORTED_MODULE_2__["strArray"])(names), Object(_operands__WEBPACK_IMPORTED_MODULE_2__["strArray"])(blockNames), flags));
return out;
} | [
"function CompileArgs({\n params,\n hash,\n blocks,\n atNames\n}) {\n let out = [];\n let blockNames = blocks.names;\n\n for (let i = 0; i < blockNames.length; i++) {\n out.push(PushYieldableBlock(blocks.get(blockNames[i])));\n }\n\n let {\n count,\n actions\n } = CompilePositional(params);\n out.push(actions);\n let flags = count << 4;\n if (atNames) flags |= 0b1000;\n\n if (blocks) {\n flags |= 0b111;\n }\n\n let names = EMPTY_ARRAY;\n\n if (hash) {\n names = hash[0];\n let val = hash[1];\n\n for (let i = 0; i < val.length; i++) {\n out.push(op('Expr', val[i]));\n }\n }\n\n out.push(op(82\n /* PushArgs */\n , strArray(names), strArray(blockNames), flags));\n return out;\n}",
"visitArgumentsExpression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function CompileArgs({\n params,\n hash,\n blocks,\n atNames\n }) {\n var out = [];\n var blockNames = blocks.names;\n\n for (var i = 0; i < blockNames.length; i++) {\n out.push(PushYieldableBlock(blocks.get(blockNames[i])));\n }\n\n var {\n count,\n actions\n } = CompilePositional(params);\n out.push(actions);\n var flags = count << 4;\n if (atNames) flags |= 0b1000;\n\n if (blocks) {\n flags |= 0b111;\n }\n\n var names = _util.EMPTY_ARRAY;\n\n if (hash) {\n names = hash[0];\n var val = hash[1];\n\n for (var _i = 0; _i < val.length; _i++) {\n out.push(op('Expr', val[_i]));\n }\n }\n\n out.push(op(84\n /* PushArgs */\n , strArray(names), strArray(blockNames), flags));\n return out;\n }",
"function compile_arguments(exprs, environment_index_table) {\n let i = 0;\n let s = length(exprs);\n let max_stack_size = 0;\n while (i < s) {\n max_stack_size = math_max(i + \n compile(head(exprs), \n environment_index_table, \n false),\n max_stack_size);\n i = i + 1;\n exprs = tail(exprs);\n }\n return max_stack_size;\n }",
"static arguments() {\n\t\treturn ChainArguments.constructor.apply(null, arguments);\n\t}",
"function compile (tree) {\n var source = [\n \"var ret = [];\",\n compileArgumentList(tree),\n \"return ret;\"\n ];\n \n return new Function([\"args\", \"runt\"], source.join(\"\\n\"));\n }",
"function pushOpArgs(args)\n {\n opFuncArgsStack.push(args);\n }",
"compile(arg, env, make) {\n if (arg === null)\n throw new EvalException(\"arglist and body expected\", arg);\n let table = new Map();\n let [hasRest, arity] = makeArgTable(arg.car, table);\n let body = cdrCell(arg);\n body = scanForArgs(body, table);\n body = this.expandMacros(body, 20); // Expand macros up to 20 nestings\n body = this.compileInners(body);\n return make((hasRest) ? -arity : arity, body, env);\n }",
"function compile_arguments(exprs, index_table) {\n let i = 0;\n let s = length(exprs);\n let max_stack_size = 0;\n while (i < s) {\n max_stack_size = math_max(\n i + compile(head(exprs), index_table, false),\n max_stack_size\n );\n i = i + 1;\n exprs = tail(exprs);\n }\n return max_stack_size;\n }",
"visitArguments(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"async compileExpressionList () {\n this.pushScope('compile expression list')\n await this.pause()\n let nArgs = 0\n const isExpressionEnd = this.lookAhead(')')\n if (isExpressionEnd) {\n this.popScope()\n return nArgs\n }\n while (true) {\n await this.compileExpression()\n nArgs++\n this.tokenizer.advance()\n const value = this.tokenizer.tokenValue()\n if (value !== ',') {\n this.tokenizer.back()\n break\n }\n }\n\n this.popScope()\n return nArgs\n }",
"function getArguments() { return args; }",
"addArguments(args = []) {\n if (null !== args) {\n forEach(args,argument => this.addArgument(argument));\n }\n }",
"async compileParameterList () {\n this.pushScope('compile parameter list')\n await this.pause()\n const { tokenizer } = this\n const isParameterEnd = this.lookAhead(')')\n if (isParameterEnd) {\n this.popScope()\n return\n }\n\n while (true) {\n await this.compileType()\n const type = this.tokenizer.tokenValue()\n this.assert({ [TOKEN_TYPE.IDENTIFIER]: null })\n const name = tokenizer.tokenValue()\n this.symbolTable.define(name, type, KIND_TYPE.ARG)\n tokenizer.advance()\n if (tokenizer.tokenValue() !== ',') {\n tokenizer.back()\n break\n }\n }\n\n this.popScope()\n }",
"function collectArguments() {\n var args = arguments, i = args.length, arr = new Array(i);\n while (i--) {\n arr[i] = args[i];\n }\n return arr;\n }",
"function parseArgumentList() {\r\n let token, expr;\r\n const args = [];\r\n\r\n while (true) {\r\n expr = parseExpression();\r\n if (typeof expr === 'undefined') {\r\n // TODO maybe throw exception?\r\n break;\r\n }\r\n args.push(expr);\r\n token = lexer.peek();\r\n if (!checkToken(token, ',')) {\r\n break;\r\n }\r\n lexer.next();\r\n }\r\n return args;\r\n }",
"function parseArgumentList() {\n var token, expr, args = [];\n\n while (true) {\n expr = parseExpression();\n if (typeof expr === 'undefined') {\n // TODO maybe throw exception?\n break;\n }\n args.push(expr);\n token = lexer.peek();\n if (!matchOp(token, ',')) {\n break;\n }\n lexer.next();\n }\n\n return args;\n }",
"function parseArgumentList() {\n let token, expr, args = [];\n\n while (true) {\n expr = parseExpression();\n if (typeof expr === 'undefined') {\n // TODO maybe throw exception?\n break;\n }\n args.push(expr);\n token = lexer.peek();\n if (!matchOp(token, ',')) {\n break;\n }\n lexer.next();\n }\n\n return args;\n }",
"function assembleArguments(thisGuy) {\n switch (thisGuy.callExpression.callee.property.name) {\n case 'animation':\n case 'component':\n case 'config':\n case 'controller':\n case 'decorator':\n case 'directive':\n case 'factory':\n case 'filter':\n case 'run':\n case 'service':\n return [thisGuy.callExpression.callee, thisGuy];\n case 'provider':\n return assembleProviderArguments(thisGuy);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up listeners for the live links. | function setUpListeners(state) {
// If they click on one of the live links, pause the video.
$('.hx-link-text-live').on('click tap', function() {
state.videoPlayer.pause();
});
} | [
"_setupLinks() {\n\t\tthis.$links = this.$control.find( '.link' );\n\n\t\tthis._bindLinked();\n\t}",
"function setupConfigLinkListeners()\n{\n var allAs, thisA;\n allAs = outputDiv.getElementsByTagName('a');\n for (var aIdx = 0; aIdx < allAs.length; aIdx++)\n {\n thisA = allAs[aIdx];\n if (thisA.className == 'expandSidebar')\n {\n thisA.addEventListener('click', expandSidebarEventHandler, false);\n }\n if (thisA.className == 'shrinkSidebar')\n {\n thisA.addEventListener('click', shrinkSidebarEventHandler, false);\n }\n if (thisA.className == 'switchSides')\n {\n thisA.addEventListener('click', switchSidesEventHandler, false);\n }\n }\n}",
"setupLinks() {\n for (let link in this.links) {\n this.links[link].addEventListener(\"click\", (e) => {\n let linkID = e.target.id;\n let viewToShow = linkID.slice(0, -5);\n let pointerToShow = `${viewToShow}-pointer`;\n this.showView(viewToShow);\n this.showPointer(pointerToShow);\n });\n\n // Events mouseover and mouseout simulates a hover effect for links.\n this.links[link].addEventListener(\"mouseover\", (e) => {\n let linkID = e.target.id;\n let pointerToShow = `${linkID.slice(0, -5)}-pointer`;\n this.showPointer(pointerToShow);\n });\n\n this.links[link].addEventListener(\"mouseout\", (e) => {\n for (let view in this.views) {\n if (this.views[view].classList != \"hidden\") {\n let activeView = `${this.views[view].id}-pointer`;\n this.showPointer(activeView);\n }\n }\n });\n }\n }",
"function setUpClickListeners() {\n $(\"#content a\").live('click', function() { //If links point to galleries, make them use getContent.\n var href = $(this).attr('href');\n if(href.indexOf(\"image/tid\") > -1) {\n var id = href.split(\"/\")[3];\n getContent(id);\n return false;\n }\n });\n $('.galleria-images .galleria-image img').live('click', function() { //Make images clickable. This is to make up for the\n window.open($(this).attr('src'), '_blank'); //wrapping a-tag removed above.\n });\n }",
"function setupListeners() {\n setupAppHomeOpenedListener();\n setupClearGoalsButtonListener();\n}",
"addLinkEvents() {\n for (let link of document.getElementsByTagName('a')) {\n let oldUrl = link.getAttribute('href');\n let hashPos = oldUrl.indexOf('#');\n\n if (hashPos === -1) {\n link.href = '#' + oldUrl;\n }\n\n // link.addEventListener('click', (event) => {\n // event.preventDefault();\n // router.navigate(link.getAttribute('href'));\n // return false;\n // });\n }\n }",
"function _setup_history_clicks(){\n\t\t// here we use the 'addClicker' fct to add event listener to the provided elements\n\t\t\t//if(theDocument.getElementById('indexlink'))\n\t\t\t//_addClicker(document.getElementById('indexlink')); // LATER: >here we add it to all <a> on the page (without caring about their classes / their container[R: they can be added dynamically..])\n\t\t\t//for later: for (var i= document.links.length; i-->0;)\n \t//document.links.onclick= clicklink;\n \tvar pageLinks = theDocument.links;\n \tvar ajaxLinks = [];\n \tfor(var i = 0; i < pageLinks.length; i++){\n \t\tif( neatFramework.helpers_module_hasClass(pageLinks[i], 'ajaxlink') ){\n \t\t\t_addClicker(pageLinks[i]);\n \t\t}\n \t}\n }",
"__attachListeners() {\n qx.event.Idle.getInstance().addListener(\n \"interval\",\n this.__onHashChange,\n this\n );\n }",
"linksHandler() {\n\t\t\treplaceLinks(this.content, (href) => {\n\t\t\t\tthis.emit(EVENTS.CONTENTS.LINK_CLICKED, href);\n\t\t\t});\n\t\t}",
"linksHandler() {\n\t\treplaceLinks(this.content, (href) => {\n\t\t\tthis.emit(EVENTS.CONTENTS.LINK_CLICKED, href);\n\t\t});\n\t}",
"function anchorListeners() {\n const allAnchors = Array.from(document.querySelectorAll('a'));\n const anchors = allAnchors.filter(a => (a.classList.contains('currentPage') === false));\n function cachePage(e) {\n loadPage(e.target.href);\n }\n anchors.forEach(a => a.addEventListener('mouseover', cachePage));\n }",
"function setupEventListeners() {\n\t\ttry {\n\t\t\tbrowser.commands.onCommand.addListener(onCommand);\n\t\t} catch (e) {\n\t\t\t// Don't let the extension fail on Firefox for Android.\n\t\t}\n\n\t\tbrowser.tabs.onUpdated.addListener(onTabUpdated);\n\t\tbrowser.tabs.onRemoved.addListener(onTabRemoved);\n\t\tbrowser.tabs.onActivated.addListener((activeInfo) => {\n\t\t\tonTabChanged(activeInfo.tabId);\n\t\t});\n\n\t\tbrowser.runtime.onMessage.addListener(onMessage);\n\t\tbrowser.runtime.onConnect.addListener((port) => {\n\t\t\tport.onMessage.addListener((message) => {\n\t\t\t\tonPortMessage(message, port.sender);\n\t\t\t});\n\t\t});\n\t}",
"monitorLinkClicks() {\n this._qsAll(\"a\").forEach((link) => {\n link.addEventListener(\"click\", () => this.setAsActive());\n });\n }",
"function addLinkHandlers() {\n // get all the links\n // attach handlers\n ['first', 'prev', 'next', 'last'].forEach(function (elem) {\n var selector = '#link_' + elem;\n var element = document.querySelector(selector);\n // element = <a href='#link_first'> element for the first loop\n element.addEventListener('click', function (event) {\n event.preventDefault(); // stop the user from navigating to the url\n if (this.href) {\n getRepositoryResults(this.href);\n }\n });\n });\n}",
"_setExternalLinks() {\n \tlet links = document.getElementsByClassName(\"external\");\n\n \tArray.from(links).forEach((link) => {\n\t \tlink.addEventListener(\"click\", (e) => {\n\t\t\t\tthis._goExternal(e.target.getAttribute('data-route'), e);\n\t\t\t});\n \t});\n }",
"function _initEvents () {\n // we observe for any click inside the document\n document.addEventListener('click', function (event) {\n // if it is an A tag (link)\n if (event.target.nodeName === 'A') {\n // we create a reference\n var link = event.target\n // see if it has a hash\n var hasHash = (link.href.indexOf('#') > -1)\n // and if there's a url assigned to it\n var noHttp = !!link.href.match(/(http|s)/gi)\n // if there's no URL and no hash\n if (hasHash && noHttp) {\n // we cancel the event\n event.preventDefault()\n // and try to active the view\n try {\n var targetView = link.href.match(/#[a-zA-Z0-9]+/)[0].toString().replace('#', '')\n View.setActive(targetView)\n } catch (e) {\n console.error(e)\n }\n }\n }\n })\n // if there is a MENU set via View.setMenu,\n // it will be assign the proper events by _initEvents\n // if event setting is enabled.\n if (MENU) {\n this._menu.addEventListener('click', function (event) {\n event.preventDefault()\n // Get the VIEW identifier\n var url = event.target.href.match(/#[a-zA-Z0-9]+/)[0].toString().replace('#', '')\n if (url === 'all') {\n View.activateAll()\n } else {\n View.setActive(url)\n }\n })\n }\n }",
"function setClickHandlers()\n {\n\t\t\t$$('body a[data-video-id]').invoke('observe', 'click', function(e)\n\t\t\t{\n\t\t\t e.stop(); var el = e.findElement('a'), id = el.readAttribute('data-video-id');\n\t\t\t if(Number(id)) sho.video.load({ 'id' : id }); \n\t\t\t});\n }",
"function addClickListeners(enable) {\n\t\tif (!linkTrackingInstalled) {\n\t\t\tlinkTrackingInstalled = true;\n\n\t\t\t// iterate through anchor elements with href and AREA elements\n\n\t\t\tvar i,\n\t\t\t\tignorePattern = getClassesRegExp(configIgnoreClasses, 'ignore'),\n\t\t\t\tlinkElements = rfDocument.links;\n\n\t\t\tif (linkElements) {\n\t\t\t\tfor (i = 0; i < linkElements.length; i++) {\n\t\t\t\t\tif (!ignorePattern.test(linkElements[i].className)) {\n\t\t\t\t\t\taddClickListener(linkElements[i], enable);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function setEvents () {\n\t\t\n\t\t\t// Start link event\n\t\t\t$(o.startLink).click(function(){\n\t\t\t\tuser.showForm();\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t});\n\t\t\t\n\t\t\t// Start popin form event\n\t\t\t$(o.form).submit(function(){\n\t\t\t\tuser.hideForm();\n\t\t\t\treturn api.send($(this));\t\t\t\n\t\t\t});\n\t\t\t\n\t\t\t// Set release and records link event\n\t\t\t$(o.releaseLink+', '+o.recordsLink).click(function(){\n\t\t\t\tapi.send($(this));\n\t\t\t\treturn false;\n\t\t\t});\t\t\t\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the toolbar ui iframe and inject it in the current page | function initToolbar(searchTerm) {
var url = "toolbar/ui.html?searchTerm=" + searchTerm;
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "augmentedSearch");
iframe.setAttribute("src", chrome.runtime.getURL(url));
iframe.setAttribute("style", "position: fixed; bottom: 0; left: 0; z-index: 10000; width: 100%; height: 200px;");
document.body.appendChild(iframe);
return toolbarUI = {
iframe: iframe, visible: true
};
} | [
"function generateToolBar (){\n\n //generate toolbar\n var toolbar = document.createElement(\"div\");\n toolbar.id = \"toolbar\";\n toolbar.style.position = \"fixed\";\n toolbar.style.display = \"inline-block\";\n \n\n //append toolbar\n var body = document.getElementsByTagName(\"body\");\n body[0].appendChild(toolbar);\n\n}",
"_createToolbar() {\n this._nodes.toolbarDiv = document.createElement('div');\n this._nodes.toolbarDiv.id = 'debug-toolbar';\n this._nodes.toolbarDiv.innerHTML = toolbarMarkup;\n\n document.body.appendChild(this._nodes.toolbarDiv);\n\n this._bindNodes();\n\n // attach events\n this._attachEvents();\n\n // show toolbar\n this.show();\n }",
"function createToolbarElement() {\n var toolbar = $('<div class=\"editor_toolbar\"></div>');\n // editor.before(toolbar);\n if($(\"#toolbar\"))\n $(\"#toolbar\").before(toolbar);\n else\n editor.before(toolbar); // this.editor.insert({before: toolbar});\n\n editor.toolbar_element = toolbar;\n\n return toolbar;\n }",
"function addToolbar() {\n const container = $(\"<div>\").addClass(\"back\");\n const back = $(\"<button>\")\n .text(\"Back\")\n .on(\"click\", () => {\n window.location = \"..\";\n });\n const code = $(\"<button>\").text(\"Code\").on(\"click\", showTheCode);\n container.append(back);\n if (window.location.pathname.indexOf(\"/docs/\") === -1) {\n container.append($(\"<span>\").addClass(\"separator\")).append(code);\n }\n $(\"body\").append(container);\n}",
"function addToolbarButton() {\n\t\t// They are using WikiEditor\n\t\tmw.loader.using( 'ext.wikiEditor', function () {\n\t\t\t// Add CodeMirror button to the enhanced editing toolbar.\n\t\t\t$( addCodeMirrorToWikiEditor );\n\t\t} );\n\t}",
"_injectResourcesInsidePreview() {\n const stl = this._iframeRefs.document.createElement('style');\n\n stl.innerHTML = `\n\t\t\tbody {\n\t\t\t\tmargin:0;\n\t\t\t\tpadding:0;\n\t\t\t}\n\t\t\t#wrapper {\n\t\t\t\tpadding: 20px;\n\t\t\t}\n\t\t`;\n\n this._iframeRefs.body.appendChild(stl);\n\n if (this.props.scripts) {\n // make sure it's an array\n const scripts = [].concat(this.props.scripts);\n scripts.forEach(script => {\n const scriptTag = this._iframeRefs.document.createElement('script');\n\n scriptTag.src = script;\n\n this._iframeRefs.body.appendChild(scriptTag);\n });\n }\n\n if (this.props.styles) {\n // make sure it's an array\n const styles = [].concat(this.props.styles);\n styles.forEach(style => {\n const styleTag = this._iframeRefs.document.createElement('link');\n\n styleTag.href = style;\n styleTag.rel = 'stylesheet';\n\n this._iframeRefs.body.appendChild(styleTag);\n });\n }\n }",
"createToolbar() {\n const toolbar = document.createElement(\"div\");\n toolbar.className = this.options.className;\n toolbar.style.visibility = \"hidden\";\n\n const buttonsContainer = document.createElement(\"div\");\n buttonsContainer.className = `${this.options.className}__buttons`;\n\n this.options.buttons.map((button) => {\n const buttonElement = document.createElement(\"button\");\n buttonElement.innerHTML = button.innerHTML;\n buttonElement.dataset.action = button.name;\n buttonsContainer.appendChild(buttonElement);\n });\n\n toolbar.appendChild(buttonsContainer);\n document.body.appendChild(toolbar);\n return toolbar;\n }",
"buildCallback_() {\n this.toolbarClone_ = this.toolbarDomElement_.cloneNode(true);\n const targetId = userAssert(\n this.toolbarDomElement_.getAttribute('toolbar-target'),\n '\"toolbar-target\" is required',\n this.toolbarDomElement_\n );\n // Set the target element to the toolbar clone if it exists.\n const targetElement = this.ampdoc_.getElementById(targetId);\n if (targetElement) {\n this.toolbarTarget_ = targetElement;\n this.toolbarClone_.classList.add('i-amphtml-toolbar');\n toggle(this.toolbarTarget_, false);\n } else {\n // This error will be caught and the side bar will continue to function\n // without the toolbar feature.\n throw user().createError(\n `Could not find the toolbar-target element with an id: ${targetId}`\n );\n }\n }",
"function createToolbarElement() {\n var toolbar = new Element('div', { 'class': 'editor_toolbar' });\n this.editor.insert({before: toolbar});\n return toolbar;\n }",
"function createSibebarPage() {\n chrome.devtools.panels.elements.createSidebarPane('Cubbles Injector', function(sidebar) {\n cubblesSidepanel = sidebar;\n sidebar.setPage('cubx_injector_sidebar.html');\n\n sidebar.onShown.addListener(function(sideBarWindow) {\n if (firstTimeCubblesSidebar) {\n cubblesSidepanel.window = sideBarWindow;\n sideBarWindow.postMessageToBackgroundScript = function(name, content) {\n postMessageToBackgroundScript(name, content);\n };\n sideBarWindow.performAutoInjection();\n firstTimeCubblesSidebar = false;\n }\n cubblesSidebarIsVisible = true;\n });\n\n sidebar.onHidden.addListener(function() {\n cubblesSidebarIsVisible = false;\n });\n });\n }",
"function createDivToolbar() {\n\n var toolbarDivHtml =\n '<div id=\"divScreenShotMngToolbar\"> </div>';\n\n $(viewer.container).append(toolbarDivHtml);\n\n $('#divScreenShotMngToolbar').css({\n 'bottom': '0%',\n 'left': '50%',\n 'z-index': '100',\n 'position': 'absolute'\n });\n\n var toolbar = new Autodesk.Viewing.UI.ToolBar(true);\n\n $('#divScreenShotMngToolbar')[0].appendChild(\n toolbar.container);\n\n return toolbar;\n }",
"function setupAddonBarWidget() {\n var panel = panels.Panel({\n width: 200,\n height: 128,\n contentURL: self.data.url('widget-panel.html'),\n contentScriptFile: self.data.url('widget-panel.js')\n });\n panel.on('show', function() {\n var url = getCanonicalUrl(tabs.activeTab.url);\n if (!url.length) {\n panel.port.emit('show', null);\n } else {\n panel.port.emit('show', {\n 'enabled': isInjectionEnabledForUrl(url)\n });\n }\n });\n panel.port.on('perform', function(action) {\n switch (action) {\n case 'toggle':\n toggleInjectionForActiveTab();\n panel.hide();\n break;\n case 'reset':\n resetOptionsForActiveTab();\n panel.hide();\n break;\n case 'show_ui':\n showUi();\n panel.hide();\n break;\n }\n });\n\n var widget = widgets.Widget({\n id: 'wtf-toggle',\n label: 'Toggle Web Tracing Framework',\n contentURL: self.data.url('widget.html'),\n contentScriptFile: self.data.url('widget.js'),\n panel: panel\n });\n\n // Update the widget icon when the URL changes.\n function tabChanged() {\n var url = getCanonicalUrl(tabs.activeTab.url);\n widget.port.emit('update', {\n 'enabled': url.length ? isInjectionEnabledForUrl(url) : false\n });\n };\n tabs.on('open', tabChanged);\n tabs.on('close', tabChanged);\n tabs.on('ready', tabChanged);\n tabs.on('activate', tabChanged);\n tabs.on('deactivate', tabChanged);\n}",
"function toolbarSetup() {\r\n\r\n\tvar menu = document.createElement(\"div\");\r\n\tvar newDiv = document.createElement(\"div\");\r\n\tvar newButton = document.createElement(\"button\");\r\n\tvar newImage = document.createElement(\"img\");\r\n\r\n\tmenu.id = \"smallmenu\";\r\n\tnewDiv.id = \"smallbox\";\r\n\tnewButton.className = \"menubutton\";\r\n\tnewButton.id = \"options\";\r\n\tnewButton.title = \"Options\";\r\n\r\n\t// Button to expand toolbar view to the full popup view\r\n\tnewButton.addEventListener(\"click\", function() {\r\n\t\tdocument.getElementsByTagName(\"html\")[0].className = \"popup\";\r\n\t\tdocument.body.className = \"popup\";\r\n\t\tdocument.body.removeChild(document.body.lastChild);\r\n\t\tdefaultSetup();\r\n\t});\r\n\r\n\tnewImage.className = \"menuicon\";\r\n\tnewImage.id = \"optionsicon\";\r\n\tnewImage.src = SOURCE.options;\r\n\r\n\tnewButton.appendChild(newImage);\r\n\tmenu.appendChild(newButton);\r\n\tmenu.appendChild(newDiv);\r\n\tdocument.body.appendChild(menu);\r\n\r\n\tdocument.getElementsByTagName(\"html\")[0].className = \"toolbar\";\r\n\tdocument.body.className = \"toolbar\";\r\n\r\n\ttoolbarTab();\r\n\r\n}",
"html() {\n const toolBar = document.createElement(\"div\");\n toolBar.classList.add(\"editToolbar\");\n\n if (this.buttons.includes(\"link\")) {\n this.linkButton = new Button(\"link\").html();\n this.linkButton.addEventListener(\"click\", () => {\n this.cb(\"link\");\n });\n toolBar.appendChild(this.linkButton);\n }\n if (this.buttons.includes(\"delete\")) {\n this.deleteButton = new Button(\"delete\").html();\n this.deleteButton.addEventListener(\"click\", () => {\n this.cb(\"delete\");\n });\n toolBar.appendChild(this.deleteButton);\n }\n\n if (this.buttons.includes(\"cancel\")) {\n this.cancelButton = new Button(\"cancel\").html();\n this.cancelButton.addEventListener(\"click\", () => {\n this.cb(\"cancel\");\n });\n toolBar.appendChild(this.cancelButton);\n }\n return toolBar;\n }",
"_createIframe(button, embedded, url) {\n let iframe = document.createElement('iframe')\n iframe.setAttribute('allowfullscreen', 'allowfullscreen')\n iframe.classList.add('widgetry-frame')\n if (embedded) {\n iframe.classList.add('widgetry-embedded')\n button.parentNode.replaceChild(iframe, button)\n } else {\n iframe.classList.add('widgetry-overlay')\n document.body.appendChild(iframe)\n }\n // Add a loader before content is fetched remotely\n this._fillIframe(iframe, '<html><body><div style=\"text-align:center; margin:calc(35%) auto 0; width:100px; background:#fff; border-radius:16px; padding:8px 14px; font-family:sans-serif\">Loading ...</div></body></html>')\n if (embedded) this._fetch(iframe, `${url}?embedded=true`)\n return iframe\n }",
"function embedToolbar () {\n /* Only add 'find me' button if HTML5 geocoding is supported */\n var find_user_location_button = (Modernizr.geolocation) ? '<a href=\"#\" class=\"button button--geolocate js-find-me\" title=\"Find my location\"><span class=\"icon-crosshairs\"></span></a>' : '';\n var toolbar_markup = '<div class=\"map-embed__directions map-embed__directions--' + config.baseConfig.directionsPositionY + '\">';\n\n if (config.baseConfig.directionsSpanColumns < 12) {\n toolbar_markup += '<div class=\"grid grid--flush\">' +\n '<div class=\"grid__item ' + columns[(12 - config.baseConfig.directionsSpanColumns)] + '-twelfths portable-small-one-whole map-embed__title\">' +\n ' ' +\n '</div><div class=\"grid__item ' + columns[config.baseConfig.directionsSpanColumns] + '-twelfths portable-small-one-whole map-embed__toolbar\">';\n }\n\n toolbar_markup += '<form action=\"#\">' +\n '<div class=\"grid grid--tight\">' +\n ' <div class=\"grid__item four-twelfths portable-five-twelfths portable-small-four-twelfths palm-one-half\">' +\n ' <div class=\"grid grid--flush travel-options\">' +\n ' <div class=\"grid__item one-quarter\">' +\n ' <a href=\"#\" data-mode=\"driving\" class=\"travel-options__item driving is-selected\" title=\"Driving\">' +\n ' <span class=\"icon-driving\"></span>' +\n ' </a>' +\n ' </div><div class=\"grid__item one-quarter\">' +\n ' <a href=\"#\" data-mode=\"transit\" class=\"travel-options__item transit\" title=\"Public transport\">' +\n ' <span class=\"icon-transit\"></span>' +\n ' </a>' +\n ' </div><div class=\"grid__item one-quarter\">' +\n ' <a href=\"#\" data-mode=\"walking\" class=\"travel-options__item walking\" title=\"Walking\">' +\n ' <span class=\"icon-walking\"></span>' +\n ' </a>' +\n ' </div><div class=\"grid__item one-quarter\">' +\n ' <a href=\"#\" data-mode=\"bicycling\" class=\"travel-options__item bicycling\" title=\"Cycling\">' +\n ' <span class=\"icon-cycling\"></span>' +\n ' </a>' +\n ' </div>' +\n ' </div>' +\n ' </div><div class=\"grid__item six-twelfths portable-five-twelfths portable-small-five-twelfths palm-one-half location-options\">' +\n ' <input type=\"text\" class=\"text-input visitor-location\" name=\"from\" placeholder=\"From:\">' +\n ' ' + find_user_location_button +\n ' </div><div class=\"grid__item two-twelfths portable-small-three-twelfths palm-one-whole location-options\">' +\n ' <button type=\"submit\" title=\"Go\" class=\"button display--block\" disabled>Go</button>' +\n ' </div>' +\n '</div>' +\n '</form>';\n\n if (config.baseConfig.directionsSpanColumns) {\n toolbar_markup += '</div>' +\n '</div>';\n }\n\n toolbar_markup += '</div>' + \n '<div class=\"alert alert--error\" style=\"display: none;\"></div>';\n\n\n /**\n * Position the toolbar based on the config option\n */\n if (config.baseConfig.directionsPositionY === 'top') {\n config.$map_container.before(toolbar_markup);\n } else {\n config.$map_container.after(toolbar_markup);\n }\n\n var $container_parent = config.$map_container.parent();\n $directions_form = $container_parent.find('form');\n $directions_error = $container_parent.find('.alert--error');\n $location_options = $container_parent.find('.location-options');\n $location_field = $container_parent.find('.visitor-location');\n $travel_options = $container_parent.find('.travel-options');\n }",
"function WORKAREA$static_(){ToolbarSkin.WORKAREA=( new ToolbarSkin(\"workarea\"));}",
"_createWidget() {\n try {\n createWidget(this.iframeEl, (widget) => {\n if (widget) {\n this._setupWidget(widget);\n this._reloadWidget();\n }\n });\n } catch (err) {\n console.log(err)\n }\n }",
"function initNavBar() {\n\n var iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"id\", \"nav-bar-iframe\");\n iframe.setAttribute(\"src\", chrome.runtime.getURL(\"resources/nav-bar.html\"));\n iframe.setAttribute(\"class\", \"nav-bar-iframe-left\");\n document.body.appendChild(iframe);\n\n // When the navBar is ready this call findInput function to find all input fields of the web page\n $('#nav-bar-iframe').on(\"load\", function () {\n findInput();\n\n //handle the clic event of the attacks popover's checkbox\n $(\".vuln-label-ch\").click(function () {\n syncPopoverNavbar($(this), 2)\n });\n });\n\n\n return navBarUI = {\n iframe: iframe, visible: true\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define a function that is executed prior to any invoking a route, if the fun returns false it will cancel the route invokation | function pre(fun) {
preRouteHook = fun;
} | [
"function controlFnExec(fnParam){\n return function(allowed){\n if(allowed){\n fnParam();\n }\n }\n}",
"function revocable(fun) {\n return {\n invoke: function(a) {\n if(fun !== undefined) {\n return fun(a);\n }\n },\n revoke: function() { run = undefined; }\n };\n }",
"function cancelRoute() {\r\n\tenableEditRtDetail(\"disabled\");\r\n\tremoveRoute();\r\n\tdisableMap();\r\n\thideRtDetailsTool();\r\n\tshowNewRtTool();\t\r\n}",
"function cancelled_fn() { // canceled_fn \n // No cancel handler code since we don't provide a cancel method \n }",
"handleExec() {\n if (this._fmc._fpHasChanged) {\n this._fmc._fpHasChanged = false;\n this._state.isModifying = false;\n \n this._fmc.activateRoute(false, () => {\n this.update();\n this._fmc.onExecDefault();\n });\n }\n }",
"beforeRouting(cb){\n this.#before += cb;\n }",
"_outOfRouteChain(){\n // *Changing the route chain state:\n this._isInRouteChain = false;\n }",
"function session_or_abort(){\n return function(req,res,next){\n if(req.session !== undefined && req.session.st){\n logger.debug('have session. steady as she goes');\n // okay, pass control\n return next();\n }else{\n logger.debug('no session, switch to next route');\n return next('route');\n }\n }\n}",
"function fun(callback, bool){\n if(bool === true){\n callback()\n }\n else{\n console.log(\"Ignoring the callback\")\n }\n}",
"function _a(cond, fn, msg){if (!cond) _e(fn,msg)}",
"forceDispatch() {\n if (this.scheduledCallbackId == NOT_SCHEDULED)\n return;\n this.cancel();\n this.fn();\n }",
"beforeEachRoute(userFunc, to, from) {\n return new Promise((resolve, reject) => {\n if (!userFunc)\n resolve();\n userFunc(to, from, resolve);\n });\n }",
"function runFunctionIfPossible(funt){\n\tif(funt){funt();}\n}",
"forceDispatch() {\n if (this.scheduledCallbackId == NOT_SCHEDULED)\n return;\n this.cancel();\n this.fn();\n }",
"function guard(fn) {\n var shouldCall = false;\n\n var guard = function() {\n if (shouldCall) {\n return fn.apply(this, arguments);\n }\n };\n\n // in JavaScript you can actually add\n // functions to existing functions\n guard.start = function() {\n shouldCall = true;\n };\n\n return guard;\n }",
"reactivate (req, fn) {\n return reactivate(req, fn)\n }",
"function continuable(func, context) {\n ensureFunc(func, 'function');\n\n if (context) { // TODO: Handle falsy things?\n func = bind(func, context);\n }\n\n steps.push(func);\n return continuable;\n }",
"_cancelPreviousPromiseIfPending() {\n this.routeState = {};\n this.transaction.keys().forEach(tId => {\n const entry = this.transaction.get(tId);\n if (entry && entry.cancelOnNext) {\n entry.shouldCancel = true;\n }\n });\n }",
"function caller2 (callback, param) {\n if (param === true) {\n callback();\n } else if (param === false) {\n console.log(\"Ignoring the callback\")\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deregisters the fs storage as plugin. | static deregister() {
delete __WEBPACK_IMPORTED_MODULE_0__common_plugin__["a" /* PLUGINS */]["FSStorage"];
} | [
"static deregister() {\n delete common_plugin[\"a\" /* PLUGINS */][\"IndexedStorage\"];\n }",
"static deregister() {\n delete common_plugin[\"a\" /* PLUGINS */][\"PartitioningAdapter\"];\n }",
"static deregister() {\n delete __WEBPACK_IMPORTED_MODULE_0__common_plugin__[\"a\" /* PLUGINS */][\"MemoryStorage\"];\n }",
"async destroy() {\n for (const plugin of this.registry) {\n this.uninstall(plugin.name);\n }\n this.root = null;\n }",
"destroy() {\n delete instances[this.key];\n if (!Object.keys(instances).length) {\n removeStorageListener();\n }\n }",
"destroy() {\n delete instances[this.key_];\n if (!Object.keys(instances).length) {\n removeStorageListener();\n }\n }",
"delStorage() {\n\t\tdelete localStorage.wuid\n\t}",
"async deleteStorageFromDisk(){\n await fs.remove(`./.metaapi/${this._accountId}-${this._application}-config.bin`);\n await fs.remove(`./.metaapi/${this._accountId}-${this._application}-deals.bin`);\n await fs.remove(`./.metaapi/${this._accountId}-${this._application}-historyOrders.bin`);\n }",
"async deleteStorageFromDisk(){}",
"close() {\n this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`);\n this.reset();\n\n _classPrivateFieldLooseBase$6(this, _storeUnsubscribe)[_storeUnsubscribe]();\n\n this.iteratePlugins(plugin => {\n this.removePlugin(plugin);\n });\n\n if (typeof window !== 'undefined' && window.removeEventListener) {\n window.removeEventListener('online', _classPrivateFieldLooseBase$6(this, _updateOnlineStatus)[_updateOnlineStatus]);\n window.removeEventListener('offline', _classPrivateFieldLooseBase$6(this, _updateOnlineStatus)[_updateOnlineStatus]);\n }\n }",
"close() {\n this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`);\n this.reset();\n\n _classPrivateFieldLooseBase(this, _storeUnsubscribe)[_storeUnsubscribe]();\n\n this.iteratePlugins(plugin => {\n this.removePlugin(plugin);\n });\n\n if (typeof window !== 'undefined' && window.removeEventListener) {\n window.removeEventListener('online', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n window.removeEventListener('offline', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n }\n }",
"close() {\n this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`);\n this.reset();\n\n _classPrivateFieldLooseBase$6(this, _storeUnsubscribe)[_storeUnsubscribe]();\n\n this.iteratePlugins(plugin => {\n this.removePlugin(plugin);\n });\n\n if (typeof window !== 'undefined' && window.removeEventListener) {\n window.removeEventListener('online', _classPrivateFieldLooseBase$6(this, _updateOnlineStatus)[_updateOnlineStatus]);\n window.removeEventListener('offline', _classPrivateFieldLooseBase$6(this, _updateOnlineStatus)[_updateOnlineStatus]);\n }\n }",
"unregister() {\n\t\tthis.module = null;\n\t\tthis.settings = null;\n\t}",
"async _unloadPlugin() {\n if (this.adapter.loaded) this.adapter.unload();\n this.adapter.loaded = false;\n this.adapter.socket.close();\n }",
"function removeStorageListener() {\n window.removeEventListener('storage', storageListener);\n isListening = false;\n}",
"purge() {\n let dirReader = this.fs.root.createReader();\n dirReader.readEntries(entries => {\n for (let i = 0, entry; entry = entries[i]; ++i) {\n if (entry.isDirectory) {\n entry.removeRecursively(() => {\n }, ChromeStore.errorHandler);\n } else {\n entry.remove(() => {\n }, ChromeStore.errorHandler);\n }\n }\n console.log('Local storage emptied.');\n }, ChromeStore.errorHandler);\n }",
"_disconnect() {\n if (this._htmlLangMutationObserver) {\n this._htmlLangMutationObserver.disconnect();\n }\n // tear down StorageEvent handler, using _onStorageEventBindThis as a status indicator\n if (this._onStorageEventBindThis) {\n window.removeEventListener('storage', this._onStorageEventBindThis);\n this._onStorageEventBindThis = null;\n }\n }",
"removeStoredSettings() {\n try {\n // removes a file or a symbolic link\n fs.unlinkSync(settings.file());\n } catch (error) {\n if (error.code !== 'ENOENT') {\n throw error;\n }\n }\n }",
"function deletePluginFile(event) {\n if (event.type === 'deleted') {\n var filePathFromPlugins = path.relative(\n path.resolve(externalPluginsDirectory), event.path);\n\n var destFilePath = path.resolve(\n config.dirs.pluginsTmp, filePathFromPlugins);\n\n del.sync(destFilePath);\n webpackFn(browserSyncReload);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show all times here | showTime(time) {
const current = new Date(time.time);
const currentMonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][current.getMonth()];
const currentDay = current.getDate();
const currentYear = current.getFullYear();
const curTime = ui.formatTime(current);
this.sunrise.innerHTML = ui.formatTime(new Date(time.sunrise));
this.sunset.innerHTML = ui.formatTime(new Date(time.sunset));
this.currentTime.innerHTML = `${curTime}, ${currentMonth} ${currentDay}, ${currentYear}`;
} | [
"function overview() {\n var eventsDB = Db.shared.get('events');\n \n // getting the times, starting by most recent time\n var times = Object.keys(eventsDB);\n times.reverse();\n \n // and render for each day the time\n Dom.div(function () {\n Dom.style({\n textAlign: 'center',\n marginTop: '1em'\n });\n \n times.forEach(function (time) {\n // show what day it is\n timeMessage(timeString(time));\n \n // display the events\n var events = eventsDB[time];\n events.reverse();\n events.forEach(renderEvent);\n });\n });\n }",
"function update_times() {\n $('time').each(function() {\n var time = $(this).data('time');\n $(this).html(moment(time).startOf('minute').fromNow());\n });\n }",
"displayTimeSlots(){\n const div = document.getElementById(\"displayHours\"+this.id);\n for (let i=0; i<24; i+=2) {\n this.displayHourWeather(i, div);\n }\n }",
"function displaySchedules() {\n\t\tclearSchedules();\n\t\t\n\t\tdisplayNextSchedules(10);\n\t}",
"function _displayTimes() {\n if (_playing) {\n _lblTotalTime.innerHTML = Utils.formatPlayingTime(_playing.getDuration());\n setInterval(_updateTimeAndSlider, 500);\n //requestAnimationFrame(updateTimeAndSlider);\n }\n }",
"function showTime() {\n let today = new Date(),\n hour = today.getHours(),\n min = today.getMinutes(),\n sec = today.getSeconds();\n weekDay = today.getDay();\n day = today.getDate();\n month = today.getMonth();\n\n\n // Set AM or PM\n //const amPm = hour >= 12 ? 'PM' : 'AM';\n\n // 12hr Format\n // hour = hour % 12 || 12;\n\n // Output Time\n time.innerHTML = `${hour}<span>:</span>${addZero(min)}<span>:</span>${addZero(\n sec\n )}`;\n date.innerHTML = `${DAYS[weekDay]}<span> </span>${day}<span> </span>${MONTHS[month]}`;\n //${showAmPm ? amPm : ''}`;\n\n setTimeout(showTime, 1000);\n}",
"function refreshAllTime(){\n\t\tvar noticesTime = $('#msgs_display_board .newTempClass .info ');\n\t\tvar noticeTime='';\n\t\tvar currTimeNum = new Date().getTime();\n\t\tfor(var i=0; i<noticesTime.length; i++){\n\t\t\tnoticeTime = noticesTime[i];\n\t\t\tvar time = $(noticeTime).find('.realtime').text();\n\t\t\t$(noticeTime).find('.showtime').text(formatTime(time,currTimeNum));\n\t\t}\n\t}",
"showEvents() {\n this.showEventTimespans();\n this.showRaterTimelines();\n }",
"function getOpeningTimes() {\n\t\t$.each(museums[selectedId].opening_hours, function(daytime, timehour) {\n\t\t\tvar trytime =\"<b>\" + daytime + \":</b> \"+ timehour +\"<br>\";\n\t\t\tdocument.getElementById(\"openinghourbox\").innerHTML+=trytime;\n\t\t\tconsole.log(trytime);\n\t\t});\n\t}",
"function displaySunTimes() {\n if (displayData.cod == 200) {\n sunTimesData[0].textContent = (new Date(displayData.sys.sunrise * 1000)).toString().slice(16, 21);\n sunTimesData[1].textContent = (new Date(displayData.sys.sunset * 1000)).toString().slice(16, 21);\n }\n}",
"function displayPrayerTimes(hours, minutes, seconds) {\n\t\treturn `${padArrayDisplay((armyTimeConverter(hours)))}${armyTimeConverter(hours)}:${padArrayDisplay(minutes)}${minutes}:${padArrayDisplay(seconds)}${seconds}`;\n\t}",
"function showTime(){\n me.renderView(me.options.view);\n me.renderToc(me.options.toc);\n return me;\n }",
"function displayTime(info) {\n console.log(`Your Time: ${timeformat(info.time)}`);\n console.log(`Total Time: ${timeformat(info.total)}`);\n}",
"function time() {\r\n\r\n var t = new Date();\r\n var s = t.getSeconds();\r\n var m = t.getMinutes();\r\n var h = t.getHours();\r\n\r\n $(\".rightNow\").html(h + \":\" + m + \":\" + s);\r\n\r\n }",
"displayCurrentTime() {\n\t\tthis.display(this.hours, this.minutes, this.seconds, this.milliseconds);\n\t}",
"function showTime(time) { \r\n var theHour = time.getHours();\r\n var theMinutes = time.getMinutes();\r\n if (theHour < 12) {\r\n period = \"AM\";\r\n }\r\n else {\r\n period = \"PM\";\r\n theHour = theHour - 12;\r\n }\r\n\t\t\t\r\n\t\t\tif (theMinutes < 10) {\r\n minutesText = \"0\" + theMinutes;\r\n }\r\n else {\r\n minutesText = theMinutes;\r\n }\t\t\r\n return (theHour + \":\" + minutesText + \" \" + period);\r\n }",
"function renderTimeSlot() {\n for (var i = state.setBeginingHour; i <= state.setEndingHour; i++) {\n var content = `<div class=\"row\">\n <div class=\"hour\" data-hour=${i}>${i <= 12 ? i + \"AM\" : i - 12 + \"PM\"}</div>\n <textarea class=\"content\"></textarea>\n <button class=\"btn\">\n <svg class=\"icon icon-save-disk\">\n <use xlink:href=\"./assets/sprite.svg#icon-save-disk\">\n </use>\n </svg>\n <p>save</p>\n </button>\n </div>`;\n\n $(\"main\").append(content);\n }\n\n $(\"[data-hour=12]\").text(\"12PM\");\n }",
"function show() {\n var time = /(..)(:..)/.exec(new Date()); // The prettyprinted time.\n var hour = time[1] % 12 || 12; // The prettyprinted hour.\n var period = time[1] < 12 ? 'a.m.' : 'p.m.'; // The period of the day.\n new Notification(hour + time[2] + ' ' + period, {\n icon: '128.png',\n body: getInsult()\n });\n}",
"function show() {\n var time = /(..)(:..)/.exec(new Date()); // The prettyprinted time.\n var hour = time[1] % 12 || 12; // The prettyprinted hour.\n var period = time[1] < 12 ? 'a.m.' : 'p.m.'; // The period of the day.\n new Notification(hour + time[2] + ' ' + period, {\n icon: '48.png',\n body: 'Time to make the toast.'\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
let contentDivOrder: HTMLDivElement = document.getElementById("deleteContent"); | function deleteContent() {
console.log("deleteContent");
divname.innerHTML = "";
divdescription.innerHTML = "";
divkindOfPotion.innerHTML = "";
divduration.innerHTML = "";
divAdd.innerHTML = "";
divheat.innerHTML = "";
divcool.innerHTML = "";
divstir.innerHTML = "";
consistency.innerHTML = "";
divcolor.innerHTML = "";
//delete.deleteContent;
/* for (let category in contentDivOrder) {
//if (category == "")
console.log(category);
//else if (delete.contentDivOrder);
} */
} | [
"function deleteDiv() {\n let thisDiv = $(this).closest('.generatedDiv');\n thisDiv.remove();\n}",
"function deleteContent() {\n let child = container.lastElementChild;\n while (child) {\n container.removeChild(child);\n child = container.lastElementChild;\n }\n }",
"function deleteRow() {\n div = document.querySelector(\".letter\");\n document.querySelector(\"#binary-container\").removeChild(div);\n}",
"function deleteDivs() {\n let grid = Array.from(container.childNodes);\n grid.forEach((element) => {\n container.removeChild(element); \n })\n}",
"function crearDivBorrarSiguiente() {\n var element = event.target;\n var elementDomNodes = document.getElementById(\"domNodes\");\n var nuevoDiv = crearNuevoDiv(element);\n nuevoDiv.innerHTML = \"Remove Next\";\n elementDomNodes.appendChild(nuevoDiv);\n nuevoDiv.addEventListener(\"click\", borrarSiguienteDiv, false);\n}",
"function add_notes_to_delete_menu(){\n $('#notes_to_delete_container').innerHTML = \"\";\n let dom_string = ``;\n for(let i = 0; i < all_notes_data.length; i += 1){\n let note_data = all_notes_data[i];\n dom_string += `\n <div class=\"note_to_delete nav_item\" id=\"note_delete_${i}\">\n <span>${note_data.note_heading_name}</span>\n \n </div>\n `;\n }\n $('#notes_to_delete_container').innerHTML = dom_string;\n}",
"function setDeleteButtonDiv(i) {\n let deleteButtonDiv = document.createElement('div');\n deleteButtonDiv.className = 'deleteButtonDiv';\n let deleteButton = document.createElement('input');\n deleteButton.type = 'Button';\n deleteButton.className = 'delete';\n deleteButton.value = 'Delete';\n deleteButton.onclick = function () {\n todoList.removeTodo(i);\n let todoRemoved = document.getElementById(i)\n let checkboxTodoRemoved = document.getElementById('check_' + i)\n if (!checkboxTodoRemoved.checked) { checkTask() }\n todoRemoved.parentNode.removeChild(todoRemoved)\n removeTodo()\n };\n deleteButtonDiv.appendChild(deleteButton);\n return deleteButtonDiv;\n }",
"function displayDeleteModal() {\n let adminDelete = document.getElementById('id01');\n adminDelete.style.display='block';\n}",
"function removeslot_domdelete(domchange){\n console.log('entered removeslot_domdelete');\n var object_domid = domchange['object_id'];\n var button_ele = document.getElementById(object_domid);\n var row_ele = button_ele.parentElement;\n //alert(\"about to delete dom object\");\n //row_ele.parentNode.replaceChild(eletoplace[0], row_ele);\n row_ele.remove();\n }",
"function deleteOverlay(){\n\tvar targetDIV = \"overlay-holder\";\n\tvar targetELE = document.getElementsByClassName(targetDIV);\n\ttargetELE[0].innerHTML = \" \";\n}",
"handleDelete(e) {\n let deleteBtn = document.getElementsByClassName(\"del\")\n console.log(deleteBtn)\n for (var i = 0; i < deleteBtn.length; i++) {\n if (e.target === deleteBtn[i]) {\n let x = deleteBtn[i].parentNode\n let y = x.parentNode\n y.removeChild(x)\n }\n }\n }",
"function minusDivs() {\n var removeEl = position.lastElementChild;\n position.removeChild(removeEl);\n}",
"function deleteItem() {\n\n // Create an array of existing items, grab the last one, and remove it from the parent element\n const newArray = parentContainer.querySelectorAll(\"div\");\n const lastElement = newArray[newArray.length - 1];\n return parentContainer.removeChild(lastElement);\n}",
"function delDiv() {\n var subMol = Div();\n while(subMol.length > 0)\n subMol.pop();\n}",
"function deleteDiv(){\n console.log('delete div activted');\n $(this).parent().remove();\n }",
"function removeDetalles() { \n var divDetalles = document.getElementById(\"divDetalles\");\n var hijos = divDetalles.childElementCount;\n if (hijos > 0) {\n for (var i = hijos; i > 0; i--) {\n divDetalles.removeChild(divDetalles.childNodes[i]);\n }\n }\n}",
"function comment() {\r\n\r\n var inputelement = document.querySelector(\"#cmnt\").value;\r\n\r\n\r\n var newelement = document.createElement(\"div\");\r\n // newelement.textContent = inputelement;\r\n\r\n\r\n\r\n var child1 = document.createElement(\"div\");\r\n var child2 = document.createElement(\"button\");\r\n\r\n child1.textContent = inputelement;\r\n child2.textContent = \"Delete\";\r\n\r\n newelement.appendChild(child1);\r\n newelement.appendChild(child2);\r\n\r\n\r\n\r\n var commentelement = document.querySelector(\"#Commentbox\");\r\n\r\n // commentelement.appendChild(newelement);\r\n commentelement.insertBefore(newelement, commentelement.firstChild);\r\n\r\n document.querySelector(\"#cmnt\").value = \" \";\r\n\r\n}",
"resetDeleteButtons() {\n const buttonsDelete = this.elements.content.getElementsByClassName('button-delete');\n\n buttonsDelete.forEach((e) => {\n e.style.display = 'block';\n });\n\n const buttonsReallyDelete = this.elements.content.getElementsByClassName('button-really-delete');\n\n buttonsReallyDelete.forEach((e) => {\n e.style.display = 'none';\n });\n }",
"function deleteDomField()\n{ \n let out = document.getElementById(\"output\");\n while(out.firstChild){\n out.removeChild(out.firstChild);\n }\n let form = document.getElementById(\"form\");\n while(form.firstChild){\n form.removeChild(form.firstChild);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
async functions To get the count of films where a character exists | async function countOfFilms(arr_people){
let todo = 0;
try{
for (const [idx, pid] of arr_people.entries()) {
todo += parseInt(await filmModel.countDocuments({ characters: { $in: [pid] } }))
}
}catch(e){
console.log(e)
}
return todo;
} | [
"function filmCount(){\n return films.length;\n}",
"static get allCamerasCount() {}",
"count (ngram, options) {\n let matchingDocs = this.findDocs(ngram, options)\n return matchingDocs.length\n }",
"count (ngram, options) {\n const matchingDocs = this.findDocs(ngram, options)\n return matchingDocs.length\n }",
"function getCharactersCount(req, res, next) {\n Character.count({}, function(err, count) {\n if (err) return next(err);\n\n res.send( { count: count });\n })\n}",
"function resultCountForWord(word) {\n let url = \"https://api.finna.fi/v1/search?&lookfor=\" + word + \"&limit=0\";\n let response = getFromWeb(url);\n return response.resultCount;\n}",
"getCount(){\n const members = this.props.chapter.filter(member => member.title)\n return members.length;\n }",
"function getCharFrequency(char, filter, limit) {\n var session = driver.session();\n if (filter == 'city') {\n return session\n .run(\n \"MATCH(char:characteristic {characteristic:{char}})-[:PARTICIPATED_IN]->(i:incident)-[:HAPPENED_IN]->(c:city_or_county)\\\n RETURN c.city_or_county AS city, c.state AS state, COUNT(i) AS frequency \\\n ORDER BY frequency DESC \\\n LIMIT {limit}\", {char: char, limit: limit})\n .then(result => {\n session.close();\n return result.records.map(record => {\n return new CityChar(record.get('city'), record.get('state'), record.get('frequency'));\n });\n })\n .catch(error => {\n session.close();\n throw error;\n });\n } else {\n return session\n .run(\n \"MATCH(char:characteristic {characteristic: {char}})-[:PARTICIPATED_IN]->(i:incident)-[:HAPPENED_IN]->(c:city_or_county)-[:BELONGS_TO]->(s:state)\\\n RETURN s.state AS state, COUNT(i) AS frequency \\\n ORDER BY frequency DESC \\\n LIMIT {limit}\", {char: char, limit: limit})\n .then(result => {\n session.close();\n return result.records.map(record => {\n return new StateChar(record.get('state'), record.get('frequency'));\n });\n })\n .catch(error => {\n session.close();\n throw error;\n });\n }\n}",
"function countMovies() {\n return movies.length\n}",
"function numOfMatches(userProfile, tarProfile, getCount){\n return new Promise(function(resolve, reject) {\n try{\n var counter = 0;\n for(var ukey in userProfile){\n if(userProfile.hasOwnProperty(ukey)){\n if((ukey.startsWith(getCount)) && (userProfile[ukey] != null)){\n for(var tkey in tarProfile){\n if(tarProfile.hasOwnProperty(tkey)){\n if((tkey.startsWith(getCount)) && (tarProfile[tkey] != null)){\n if(userProfile[ukey] == tarProfile[tkey]){\n counter ++;\n console.log(\"NUM OF \",getCount ,\" MATCHES --> \", counter);\n }\n }\n }\n }\n }\n }\n }\n if(counter != 0){\n resolve(counter);\n }\n else{\n resolve(counter);\n }\n }catch (e){ \n reject(e);\n }\n });\n}",
"countResponses (column, response, data) {\n const columnIndex = this.getColumnIndex(column, data);\n let rows = data.slice(1);\n let count = 0;\n for (let k = 0; k < rows.length; k++){\n if (rows[k].Data[columnIndex].VarCharValue == response) {\n count++;\n };\n };\n return count\n }",
"function get_encodings_count(s) {\n // Write your code here\n\n}",
"function CountMovies() {\n return movies.length;\n}",
"function getDistinctMoodsForThisImage(){\n sendCommand('get_mood_count_for_this_image');\n}",
"static async searchFilms(title) {\n const response = await this.request('films/', { title });\n\n return response.films;\n }",
"async countMagicWords(files,magic_word,event=null) {\r\n let that = this;\r\n \r\n return new Promise(async (resolve,reject) => {\r\n let totalMagic = that.totalMagicWord; // have a copy of total magic word\r\n let totalFileReads = 0; // Total number of files to read\r\n\r\n files.forEach( async function(file) {\r\n try {\r\n if (!(that.excludeFiles.includes(path.extname(file).toLowerCase()) && stat[\"size\"] < 1073741824)) { //exclude\r\n if (event && event == 'deleted') { // For delete, we don't need to read files, it will not exist\r\n totalFileReads++;\r\n totalMagic = await that.reUpdateCache(file, 0, event, totalMagic);\r\n } else {\r\n totalFileReads++;\r\n if (fs.existsSync(file)) { //read file only if it exists\r\n let text = await fsExtra.readFile(file);\r\n let count = await that.searchWord(text.toString(),magic_word); // search for magic word\r\n \r\n if (!event) { //initial scan\r\n that.allFiles[file] = count ? count : 0;\r\n totalMagic = count ? (totalMagic + count) : totalMagic; //update total \r\n } else {\r\n totalMagic = await that.reUpdateCache(file, count, event, totalMagic);\r\n } \r\n }\r\n }\r\n if (that.isReadComplete(totalFileReads) == true) { //If all the files are processed, return\r\n resolve(totalMagic);\r\n }\r\n }\r\n } catch (err) {\r\n reject(err);\r\n }\r\n })\t\r\n })\r\n }",
"function moodCounter(mood) {\n let counter = 0;\n Object.keys(accessMap).forEach((el) => {\n const entry = accessMap[el];\n if (entry.title === mood) {\n counter++;\n }\n });\n return counter;\n}",
"static async getAccidentsWhereCount(options){\n try{\n return await Accident.count({\n where: options,\n })\n .then(function (count){\n console.log(count);\n return count;\n\n });\n }catch (error){\n console.log(`Accidents not found. ${error}`)\n }\n }",
"static async count(){\n return await db.favorites().find().count()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a telemetry set | build() {
let set = {
"asset": this.config.asset,
"collectedAt": Date.now()
}
const measurements = this.measurements.where(function(item) {
return item.reading !== null && typeof item.reading !== 'undefined'
})
if (!measurements && measurement.length === 0) {
this.emit('error', {
name: 'InvalidData',
message: 'There are no measurements available to build'
})
return measurements
}
for (const measurement of measurements) {
set[measurement.artifact] = measurement
}
return set
} | [
"function buildChartDatasets() {\n // datasets: [\n // {\n // type: 'bar',\n // label: 'Bar Component',\n // data: [10, 20, 30],\n // },\n // {\n // type: 'line',\n // label: 'Line Component',\n // data: [30, 20, 10],\n // }\n // ]\n var speed = getChartTicks(speedEvents, formatSpeed);\n var cadence = [];\n var power = [];\n var estimatedPower = [];\n var targetPower = [];\n var servoPosition = []; \n\n var chartDatasets = [\n {\n type: 'line',\n label: 'Speed (mph)',\n data: speed,\n },\n {\n type: 'line',\n label: 'Cadence',\n data: cadence,\n },\n {\n type: 'line',\n label: 'Power',\n data: power,\n },\n {\n type: 'line',\n label: 'Estimated Power',\n data: estimatedPower,\n },\n {\n type: 'line',\n label: 'Target Power',\n data: targetPower,\n },\n {\n type: 'line',\n label: 'Servo Position',\n data: servoPosition,\n },\n ];\n\n var chartData = {\n labels: getChartXAxisLabels(),\n datasets: chartDatasets\n };\n }",
"GetDataCollectorSets(string, string) {\n\n }",
"function generateTelemetry() {\n const telemetry = {\n localtime: new Date(),\n temperature: +(Math.random() * 20 + 12).toFixed(4),\n humidity: +(Math.random()).toFixed(4),\n };\n pendingMessages.push(telemetry);\n console.log('Telemetry generated. Pending messages:', pendingMessages.length);\n}",
"function generateSetlistData() {\n\tconst setlistData = {tracks: []};\n\tfor (let i = 1; i <= 7; i++) {\n\t\tsetlistData.tracks.push({\n\t\t\ttrackName: faker.name.firstName(),\n\t\t\tbpm: Math.floor(Math.random() * (350 - 1 + 1)) + 1,\n\t\t\tkey: randomKeyGen(),\n\t\t});\n\t}\n\treturn setlistData;\n}",
"upload() {\n const set = super.build()\n if(Object.keys(set).length >= 3){\n this.iot.publish(\"$aws/rules/AssetTelemetryData/\"+this.config.asset+\"/telemetry/data\", JSON.stringify(set), {}, () => {\n super.emit('upload', set)\n })\n }\n }",
"stories() {\n const reqMetrics = this.sampleArr\n .filter(elem => elem.name === this.selected_metric);\n const storiesByGuid = [];\n reqMetrics.map(elem => storiesByGuid\n .push(this.guidValue.get(elem.diagnostics.stories)[0]));\n return Array.from(new Set(storiesByGuid));\n }",
"build() {\n this.cacheTargets();\n }",
"function buildDataSet(dataSet) {\n var data = new google.visualization.DataTable();\n data.addColumn('datetime', 'Time');\n data.addColumn('number', 'Temperature (F)');\n data.addColumn('number', 'Wind Speed (MPH)');\n data.addColumn('number', 'Humidity (%)');\n\n for (var idx=0;idx<dataSet.length;idx++){\n data.addRows([[new Date(dataSet[idx].created),dataSet[idx].tempf,dataSet[idx].windspeedmph,dataSet[idx].humidity]]);\n }\n\n var formatter_medium = new google.visualization.DateFormat({formatType: 'medium'});\n formatter_medium.format(data,1);\n\n return data;\n }",
"function LabelSetBuilder()\n {\n var _records = new Array();\n\n // Returns label set records \n this.getRecords = function() { return _records; };\n }",
"function buildTestingSet(event){\n var size = event.data.testSize\n pixelValuesTest = new Array(size)\n for (var image = 0; image < size; image++) { \n var pixels = new Array(784);\n for (var y = 0; y <= 27; y++) {\n for (var x = 0; x <= 27; x++) {\n pixels[28*y+x] = dataFileBuffer[(image * 28 * 28) + (x + (y * 28)) + 15]/255;\n }\n }\n console.log('...Building Testing Set')\n var output = JSON.stringify(labelFileBuffer[image + 8])\n var o = {input: arrayToMatrix(pixels), output: arrayToMatrix(labelToArray(output))}\n pixelValuesTest[image] = o\n }\n console.log('Testing Set built')\n return pixelValuesTest\n}",
"function buildAdminUnits() {\n t.obj.adminUnitId = [];\n t.obj.adminUnit = [];\n $.each(t.obj.adminUnits, function(i, v) {\n let id = String(v.attributes.geonameid.split(\":\")[1].split(\")\")[0]);\n // let n = id.includes(\",\");\n let n = id.indexOf(\",\");\n if (n > -1) {\n id = id.split(\",\");\n v.attributes.id1 = id[0];\n v.attributes.id2 = id[1];\n t.obj.adminUnit.push(v);\n $.each(id, function(i, v) {\n id = v;\n t.obj.adminUnitId.push(String(id));\n });\n } else {\n t.obj.adminUnitId.push(id);\n v.attributes.id1 = String(\n v.attributes.geonameid.split(\":\")[1].split(\")\")[0]\n );\n t.obj.adminUnit.push(v);\n }\n });\n }",
"diagnostics() {\n if (this.selected_story !== null && this.selected_metric !== null) {\n const result = this.sampleArr\n .filter(value => value.name === this.selected_metric &&\n this.guidValue\n .get(value.diagnostics.stories)[0] ===\n this.selected_story);\n const allDiagnostics = result.map(val => Object.keys(val.diagnostics));\n return _.union.apply(this, allDiagnostics);\n }\n }",
"diagnostics() {\n if (this.selected_story !== null && this.selected_metric !== null) {\n const result = this.sampleArr\n .filter(value => value.name === this.selected_metric &&\n this.guidValue\n .get(value.diagnostics.stories)[0] ===\n this.selected_story);\n const allDiagnostic = [];\n result.map(val => allDiagnostic.push(Object.keys(val.diagnostics)));\n return _.union.apply(this, allDiagnostic);\n }\n }",
"buildWAPSOList() {\n const info = this.args.ticketingInfo;\n const {ticketPackage} = this.args;\n const {defaultDate} = this;\n\n const list = ticketPackage.wapso.map((row) =>\n new Changeset({\n id: row.id,\n name: row.name,\n access_date: (row.access_date || defaultDate)\n })\n );\n\n // Pad out to the max\n const max = info.wap_so_max;\n while (list.length < max) {\n list.push(new Changeset({id: 'new', name: '', access_date: defaultDate}));\n }\n\n this.wapSOList = list;\n this.wapSOCount = ticketPackage.wapso.length;\n }",
"function makeTelemetryFile(baseFileName)\n{\n // Build the telemetry message IDs output file name and include flag\n var tlmFileName = ccdd.getOutputPath() + baseFileName + \".h\";\n var headerIncludeFlag = \"_\" + baseFileName.toUpperCase() + \"_H_\";\n\n // Open the telemetry message IDs output file\n var tlmFile = ccdd.openOutputFile(tlmFileName);\n\n // Check if the telemetry message IDs file successfully opened\n if (tlmFile != null)\n {\n // Add the build information to the output file\n outputFileCreationInfo(tlmFile);\n\n // Add the header include to prevent loading the file more than once\n ccdd.writeToFileLn(tlmFile, \"#ifndef \" + headerIncludeFlag);\n ccdd.writeToFileLn(tlmFile, \"#define \" + headerIncludeFlag);\n ccdd.writeToFileLn(tlmFile, \"\");\n\n ccdd.writeToFileLn(tlmFile, \"#include \\\"\" + projectName + \"_base_ids.h\\\"\");\n ccdd.writeToFileLn(tlmFile, \"\");\n\n // Get an array containing all group names\n var groupNames = ccdd.getGroupNames(false);\n\n var minimumLength = 12;\n\n // Step through each structure name\n for (var nameIndex = 0; nameIndex < structureNames.length; nameIndex++)\n {\n // Get the value of the structure's message ID name data field\n var msgIDName = ccdd.getTableDataFieldValue(structureNames[nameIndex], \"Message ID Name\");\n\n // Check if the field exists and isn't empty, and the length exceeds\n // the minimum length found thus far\n if (msgIDName != null && !msgIDName.isEmpty() && msgIDName.length() > minimumLength)\n {\n // Store the new minimum length\n minimumLength = msgIDName.length();\n }\n }\n\n // Step through each group name\n for (var groupIndex = 0; groupIndex < groupNames.length; groupIndex++)\n {\n // Get the value of the group's message ID name data field\n var msgIDName = ccdd.getGroupDataFieldValue(groupNames[groupIndex], \"Message ID Name\");\n\n // Check if the field exists and isn't empty, and the length exceeds\n // the minimum length found thus far\n if (msgIDName != null && !msgIDName.isEmpty() && msgIDName.length() > minimumLength)\n {\n // Store the new minimum length\n minimumLength = msgIDName.length();\n }\n }\n\n // Build the format string used to align the message ID definitions\n var format = \"#define %-\" + (minimumLength + 1) + \"s %s\\n\";\n\n ccdd.writeToFileLn(tlmFile, \"/* Structure message IDs: \" + structureNames.length + \" structures */\");\n\n // Step through each structure name\n for (var nameIndex = 0; nameIndex < structureNames.length; nameIndex++)\n {\n // Get the values of the structure's message ID and ID name data\n // fields\n var msgID = ccdd.getTableDataFieldValue(structureNames[nameIndex], \"Message ID\");\n var msgIDName = ccdd.getTableDataFieldValue(structureNames[nameIndex], \"Message ID Name\");\n\n // Output the telemetry message ID to the file\n outputIDDefine(tlmFile, format, msgID, msgIDName);\n }\n\n ccdd.writeToFileLn(tlmFile, \"\");\n ccdd.writeToFileLn(tlmFile, \"/* Group message IDs: \" + groupNames.length + \" groups */\");\n\n // Step through each group\n for (var groupIndex = 0; groupIndex < groupNames.length; groupIndex++)\n {\n // Get the values of the group's message ID and ID name data fields\n var msgID = ccdd.getGroupDataFieldValue(groupNames[groupIndex], \"Message ID\");\n var msgIDName = ccdd.getGroupDataFieldValue(groupNames[groupIndex], \"Message ID Name\");\n\n // Output the telemetry message ID to the file\n outputIDDefine(tlmFile, format, msgID, msgIDName);\n }\n\n // Finish and close the telemetry message IDs output file\n ccdd.writeToFileLn(tlmFile, \"\");\n ccdd.writeToFileLn(tlmFile, \"#endif /* #ifndef \" + headerIncludeFlag + \" */\");\n ccdd.closeFile(tlmFile);\n }\n // The telemetry message IDs file failed to open\n else\n {\n // Display an error dialog\n ccdd.showErrorDialog(\"<html><b>Error opening telemetry message IDs output file '</b>\" + tlmFileName + \"<b>'\");\n }\n}",
"_makePayload(source) {\n if (source) {\n const payload = new Set();\n each(source, this._addToPayload, payload);\n return Array.from(payload);\n }\n }",
"function create_time_set(times) {\n let count = 0;\n let time_array = [];\n\n while (count < times.length) {\n time_array.push(times[count].trace_time)\n count++;\n }\n\n // console.log(\"time array \", time_array);\n\n return time_array;\n}",
"function publishTelemetry() {\n data.number = Math.floor(Math.random() * (max - min)) + min;\n client.publish('v1/devices/me/telemetry', JSON.stringify(data));\n}",
"function buildTrainingSet(event){\n var size = event.data.trainingSize\n pixelValues = new Array(size)\n for (var image = 0; image < size; image++) { \n var pixels = new Array(784);\n for (var y = 0; y <= 27; y++) {\n for (var x = 0; x <= 27; x++) {\n pixels[28*y+x] = dataFileBuffer[(image * 28 * 28) + (x + (y * 28)) + 15]/255;\n }\n }\n console.log('...Building Training Set')\n var output = JSON.stringify(labelFileBuffer[image + 8])\n var o = {input: arrayToMatrix(pixels), output: arrayToMatrix(labelToArray(output))}\n pixelValues[image] = o\n }\n console.log('Training Set built')\n return pixelValues\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests whether an object is an instance of the class represented by the specified base id. | function __instanceof(ptr, baseId) {
const U32 = new Uint32Array(memory.buffer);
let id = U32[ptr + ID_OFFSET >>> 2];
if (id <= U32[__rtti_base >>> 2]) {
do {
if (id == baseId) return true;
id = getBase(id);
} while (id);
}
return false;
} | [
"function __instanceof(ptr, baseId) {\n const U32 = new Uint32Array(memory.buffer);\n var id = U32[(ptr + ID_OFFSET) >>> 2];\n if (id <= U32[rttiBase >>> 2]) {\n do if (id == baseId) return true;\n while (id = getBase(id));\n }\n return false;\n }",
"function __instanceof(ptr, baseId) {\r\n const U32 = new Uint32Array(memory.buffer);\r\n var id = U32[(ptr + ID_OFFSET) >>> 2];\r\n if (id <= U32[rttiBase >>> 2]) {\r\n do if (id == baseId) return true;\r\n while (id = getBase(id));\r\n }\r\n return false;\r\n }",
"function __instanceof(ptr, baseId) {\n const U32 = new Uint32Array(memory.buffer);\n let id = U32[ptr + ID_OFFSET >>> 2];\n \n if (id <= getRttiCount(U32)) {\n do {\n if (id == baseId) return true;\n id = getRttBase(id);\n } while (id);\n }\n \n return false;\n }",
"hasInstanceWithId(id) {\n if (typeof(id) === 'string') {\n id = database.ObjectId(id);\n }\n\n for (const instance of this) {\n if (instance._id.equals(id))\n return true;\n }\n return false;\n }",
"static isInstanceOf(targetObject, typeUuid) {\n if (targetObject === undefined || targetObject === null) {\n return false;\n }\n let objectPrototype = Object.getPrototypeOf(targetObject);\n while (objectPrototype !== undefined && objectPrototype !== null) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const registeredUuid = objectPrototype[classPrototypeUuidSymbol];\n if (registeredUuid === typeUuid) {\n return true;\n }\n // Walk upwards an examine base class prototypes\n objectPrototype = Object.getPrototypeOf(objectPrototype);\n }\n return false;\n }",
"function instanceOf( baseclass ) {\n if(this instanceof baseclass) return true;\n return subOf(this.constructor, baseclass);\n}",
"function is(object, name) {\n var x = registry.registeredClasses[name];\n return x != null && object instanceof x;\n }",
"function isInstance(object, clazz) {\n if ((object == null) || (clazz == null)) {\n return false;\n }\n if (object instanceof clazz) {\n return true;\n }\n if ((clazz == String) && (typeof(object) == \"string\")) {\n return true;\n }\n if ((clazz == Number) && (typeof(object) == \"number\")) {\n return true;\n }\n if ((clazz == Array) && (typeof(object) == \"array\")) {\n return true;\n }\n if ((clazz == Function) && (typeof(object) == \"function\")) {\n return true;\n }\n var base = object.base;\n while (base != null) {\n if (base == clazz) {\n return true;\n }\n base = base.base;\n }\n return false;\n}",
"function is(object, name) {\n var x = registry.registeredClasses[name];\n return x != null && object instanceof x;\n}",
"static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiUnknown\");\n }",
"static IsInstance(obj) {\n return obj instanceof XMObject;\n }",
"function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name;}",
"function xInstanceOf(obj, name) {\r\n var browser = obj.constructor;\r\n while (browser.name !== name && browser.super)\r\n browser = browser.super;\r\n return browser.name === name;\r\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Subnet.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === TargetGroup.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Budget.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ManagedInstance.__pulumiType;\n }",
"static isInstance(obj) {\n return utils.isInstance(obj, \"__pulumiCustomResource\");\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DomainAssociation.__pulumiType;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Carga los datos del proveedor seleccionado en el formulario | function mostrarDatosProveedor() {
//tomar el idProveedor desde el value del select
let idProvedor = document.getElementById("idProveedor").value;
//buscar el proveedor en la lista
for (let i = 0; i < listaProveedores.length; i++) {
let dato = listaProveedores[i].getData();
if(dato['idProveedor'] === parseInt(idProvedor)){
//desplegar los datos en el formulario
vista.setDatosForm(dato);
break;
}
}
} | [
"function getDatosSelect() {\n getCompetenciasAndComportamientos(getGestores);\n}",
"function cargarOption() {\n \n // sacar los array de alumno y tutor\n \n addOptions(\"selectPrimero\", oPasen.cargarOptions());\n addOptions(\"selectSegundo\", oPasen.cargarOptions());\n }",
"function cargarValoresCampos(){\r\n\t\t\t\t\tfpGestionCampos.findById('nombre').setValue(DameSeleccionadoCampos(\"nombre\"));\r\n\t\t\t\t\tfpGestionCampos.findById('nombrec').setValue(DameSeleccionadoCampos(\"nombre_mostrar\"));\r\n\t\t\t\t\tfpGestionCampos.findById('longitud').setValue(DameSeleccionadoCampos(\"longitud\"));\r\n\t\t\t\t\tfpGestionCampos.findById('tipod').setValue(DameSeleccionadoCampos(\"tipo\"));\r\n\t\t\t\t\tfpGestionCampos.findById('nombrec').setValue(DameSeleccionadoCampos(\"nombre_mostrar\"));\r\n\t\t\t\t\tfpGestionCampos.findById('tipoc').setValue(DameSeleccionadoCampos(\"tipocampo\"));\r\n\t\t\t\t\tfpGestionCampos.findById('visible').setValue(DameSeleccionadoCampos(\"visible\"));\r\n\t\t\t\t\tfpGestionCampos.findById('descripcion').setValue(DameSeleccionadoCampos(\"descripcion\"));\r\n\t\t\t\t}",
"mostrarFormularioIngresoPaciente() {\n let datosPersonal = this.hospital.nombresPersonal;\n let clase = \"ingresoPaciente\";\n let funcion = () => { this.ingresarDatos(Paciente.name, clase) };\n crearFormulario([\"nombre\", \"apellidos\", \"edad\", \"enfermedad\"], clase, funcion);\n let botonAltaForm = document.getElementById(\"confirmacion\");\n addSelect(botonAltaForm, datosPersonal, clase);\n }",
"function rellenarFormulario(objeto){\n //propiedad es el nodo que voy a buscar del objeto\n for (let propiedad in objeto){\n $(`#${propiedad}`).val(objeto[propiedad])\n }\n }",
"construirSelectCriptomonedas() {\n // Obtiene un 'Array' de monedas de la API \n cotizador .obtenerMonedasAPI() // 'Promise'\n .then( data => {\n console .log( data ); // Objeto con un 'Array' monedas\n // Crear un elemento SELECT\n const monedas = data .monedas, // 'Array' de Objetos con cada moneda\n select = document .getElementById( 'criptomoneda' ); // Obtiene el elemento select del DOM\n \n // Recorre y construye SELECT con los datos de la REST API\n monedas .forEach( moneda => {\n // Agrega ID\n const option = document .createElement( 'option' ); // Crea un elemento 'option'\n \n option .value = moneda .id; // Agrega la propiedad 'value' al elemento 'option'\n option .appendChild( document .createTextNode( moneda .name ) ); // Agrega un nodo de texto al elemento 'option'\n select .appendChild( option ); // Agrega el elemento 'option' dentro del 'select' en el DOM \n });\n });\n }",
"function obtenerSeleccionados() {\n var strcadena = \"\";\n var strID = \"\";\n var strIdTotal = \"\";\n var aFilas = FilasDe(\"tblDatos\");\n if (aFilas != null) {\n for (var i = 0; i < aFilas.length; i++) {\n strIdTotal += aFilas[i].id + \",\";\n if (aFilas[i].getAttribute(\"selected\") == \"true\") {\n strID += aFilas[i].id + \",\";\n strcadena += aFilas[i].cells[2].innerText.toUpperCase() + \"/\";\n }\n }\n }\n $I(\"hdnNombreProfesionales\").value = strcadena;\n $I(\"hdnIdFicepis\").value = strID.substring(0, strID.length - 1);\n $I(\"hdnIdFicepisTotal\").value = strIdTotal.substring(0, strIdTotal.length - 1);\n}",
"function cargaProvincias (data) {\n const selectProv = document.querySelector('#select_prov');\n selectProv.setAttribute('required', true);\n selectProv.removeAttribute('disabled');\n selectProv.classList.add('tocheck');\n if (selectProv) {\n let html = '<option></option>';\n data.forEach(item => {\n html += `<option value=\"${item.label}\">${item.label}</option>`;\n });\n selectProv.innerHTML = html;\n }\n }",
"inicializarDetallesVenta() {\n $('#devolucion_venta-datos_venta').addEventListener('change', event => {\n this.tablaDetalleVenta.setData(util.URL_APP, {\n clase: 'Venta',\n accion: 'listarDetalleVenta',\n idVenta: event.target.value\n }).then(() => {\n if (this.totalVentas > 0) { // el cliente tiene ventas registradas\n let datosVenta = event.target.options[event.target.selectedIndex].text;\n $('#devolucion_venta-info').innerHTML = `<div id=\"devolucion_venta-info\" class=\"grid-example col s12\"><b>Detalle de la venta ${datosVenta}</span></div>`;\n } else { // el cliente no tiene ventas registradas\n $('#devolucion_venta-info').innerHTML = `<div id=\"devolucion_venta-info\" class=\"grid-example col s12\"><b>Detalle de la venta</b></div>`;\n }\n }).catch((error) => {\n util.mensaje(error, 'Problemas al actualizar la tabla de detalles de venta');\n });\n });\n }",
"function getDatos(valor) \r\n\t{\r\n\t\t// Obtenes el valor del cliente seleccionado.\r\n\t\tvar clienteId = $(\"#id_cliente\").val();\r\n\t\tvar circuito = $(\"#id_tipo_documento\").val();\r\n\t\t//Comprobamos que la variable clienteId contenga algún valor.\r\n\t\tif (clienteId) \r\n\t\t{\r\n\t\t\tif(valor=='[object Object]')\r\n\t\t\t{\r\n\t\t\t\t// Eliminamos las opciones anteriores del select\r\n\t\t\t\t$(\"#id_ordencompra\").html(\"\");\r\n\t\t\t}\r\n\t\t\t//Agregamos un llamado ajax.\r\n\t\t\t// el tipo es GET\r\n\t\t\t// la url según lo que se determina en la documentación\r\n\t\t\t// data: pasamos el valor del cliente.\r\n\t\t\tvar request = $.ajax(\r\n\t\t\t{\r\n\t\t\t\ttype: \"GET\",\r\n\t\t\t\turl: \"{% url 'venta:get_datos' %}\",\r\n\t\t\t\tdata: {\"id_cliente\": clienteId,'circuito': circuito},\r\n\t\t\t});\r\n\r\n\t\t\t//Luego de haber realizado la llamada mediante Ajax, \r\n\t\t\t//trabajamos con los valores devueltos.\r\n\t\t\trequest.done(function(response) \r\n\t\t\t{\r\n\t\t\t\t// Agregamos los resultados al select\r\n\t\t\t\tif(valor=='[object Object]')\r\n\t\t\t\t{\t\t\r\n\t\t\t\t\t$(\"#id_ordencompra\").html(response.ordenesdecompra);\r\n\t\t\t\t\t$(\"#id_ordencompra\").trigger(\"change\", [false]);\r\n\t\t\t\t} \r\n\t\t\t});\r\n\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(valor=='[object Object]')\r\n\t\t\t\t{\r\n\t\t\t\t\tvaciarSelectOC();\r\n\t\t\t\t}\r\n\t\t\t}\t\t\r\n\t\t}",
"function SeleccionadoViviendas() {\n MuestraObj(subTipoViviendas);\n MuestraObj(antiguedadViviendas);\n MuestraObj(caracteristicas);\n MuestraObj(caracteristicasViviendas1);\n MuestraObj(caracteristicasViviendas2);\n MuestraObj(caracteristicasViviendas3);\n MuestraObj(estado);\n MuestraObj(extrasViviendas);\n MuestraObj(btnEjecutarConsulta);\n MuestraObj(precioInmuebles);\n OcultaObj(subTipoLocales);\n OcultaObj(subTipoTerrenos);\n OcultaObj(caracteristicasOficinas);\n OcultaObj(caracteristicasLocales);\n OcultaObj(caracteristicasTerrenos1);\n OcultaObj(caracteristicasTerrenos2);\n OcultaObj(caracteristicasTerrenos3);\n OcultaObj(caracteristicasTrasteros);\n OcultaObj(caracteristicasGarajes1);\n OcultaObj(caracteristicasGarajes2);\n OcultaObj(caracteristicasGarajes3);\n OcultaObj(extrasHabitaciones);\n OcultaObj(extrasOficinas);\n OcultaObj(extrasLocales);\n OcultaObj(extrasTerrenos);\n OcultaObj(extrasTrasteros);\n OcultaObj(extrasGarajes);\n OcultaObj(precioAlquilerHabitacionesDesde);\n OcultaObj(precioAlquilerHabitacionesHasta);\n OcultaObj(precioVentaOficinasDesde);\n OcultaObj(precioVentaOficinasHasta);\n OcultaObj(precioAlquilerOficinasDesde);\n OcultaObj(precioAlquilerOficinasHasta);\n OcultaObj(precioVentaLocalesDesde);\n OcultaObj(precioVentaLocalesHasta);\n OcultaObj(precioAlquilerLocalesDesde);\n OcultaObj(precioAlquilerLocalesHasta);\n OcultaObj(precioVentaTerrenosDesde);\n OcultaObj(precioVentaTerrenosHasta);\n OcultaObj(precioAlquilerTerrenosDesde);\n OcultaObj(precioAlquilerTerrenosHasta);\n OcultaObj(precioVentaTrasterosDesde);\n OcultaObj(precioVentaTrasterosHasta);\n OcultaObj(precioAlquilerTrasterosDesde);\n OcultaObj(precioAlquilerTrasterosHasta);\n OcultaObj(precioVentaGarajesDesde);\n OcultaObj(precioVentaGarajesHasta);\n OcultaObj(precioAlquilerGarajesDesde);\n OcultaObj(precioAlquilerGarajesHasta);\n if (btnComprar.checked) {\n MuestraObj(precioVentaViviendasDesde);\n MuestraObj(precioVentaViviendasHasta);\n OcultaObj(precioAlquilerViviendasDesde);\n OcultaObj(precioAlquilerViviendasHasta);\n }\n if (btnAlquilar.checked) {\n MuestraObj(precioAlquilerViviendasDesde);\n MuestraObj(precioAlquilerViviendasHasta);\n OcultaObj(precioVentaViviendasDesde);\n OcultaObj(precioVentaViviendasHasta);\n }\n }",
"function seleccionarServicio(e){\n let servicioSeleccionado\n categorias.map((cat) =>{\n if(cat.nombre===datosPagina.Categoria_id.nombre){\n servicioSeleccionado = cat.servicios.filter((serv) => serv.nombre === e.target.value)\n }\n })\n setdatosPagina({\n ...datosPagina,\n Servicio_id: servicioSeleccionado[0] \n })\n }",
"function carregaDadosForm(dados){\n objJSON = JSON.parse(dados);\n var nome = document.getElementById('pronome');\n nome.value = decodeURI(objJSON.pronome);\n var marca = document.getElementById('promarca');\n marca.value = decodeURI(objJSON.promarca);\n var cod = document.getElementById('procodig');\n cod .value= objJSON.procodig;\n var categoria = document.getElementById('procateg');\n categoria.value = objJSON.procateg;\n}",
"function buscar_unidad($objeto) {\n\txx=window.location.href;\n\t\n\tif(xx.match(/formNuevo\\/[0-9]{1,}/) ) {\n\t\tbaseUrl='../../../';\n\t}else {\n\t\tbaseUrl='../../';\n\t}\n\t\n\turl=baseUrl+'index.php/product/buscar_unidad';\n\t\n\t$.ajax({\n\t\turl: url,\n\t\ttype: 'POST',\n\t\tdata: $objeto,\n\t\tdataType: 'json',\n\t\tsuccess: function(response){\n\t\t\t$material=response[0];\n\t\t\t$('#select_unidad').html('<option value=\"'+$material.idUni+'\" selected=\"selected\">'+$material.compuesto+'</option>');\n\t\t\t// console.log($material);\n\t\t\n\t//** Refrescamos el select para que el usuario visualice el cambio\n\t\t\t$objeto=[];\n\t\t\t\t\n\t\t// Creamos un arreglo con los id de los select\n\t\t\t$objeto[0]='select_unidad';\n\t\t\t\t\t\n\t\t// Mandamos llamar la funcion que crea el buscador\n\t\t\tselect_buscador($objeto);\n\t\t}\n\t});\n}",
"function buscarClienteOnClick(){\n if ( get('formulario.accion') != 'clienteSeleccionado' ) {\n // var oid;\n // var obj = new Object();\n var whnd = mostrarModalSICC('LPBusquedaRapidaCliente','',new Object());//[1] obj);\n if(whnd!=null){\n \n //[1] }else{\n /* posicion N°\n 0 : oid del cliente\n 1 : codigo del cliente\n 2 : Nombre1 del cliente\n 3 : Nombre2 del cliente\n 4 : apellido1 del cliente\n 5 : apellido2 del cliente */\n \n var oid = whnd[0];\n var cod = whnd[1];\n //[1] var nombre1 = whnd[2];\n //[1] var nombre2 = whnd[3];\n //[1] var apellido1 = whnd[4]; \n //[1] var apellido2 = whnd[5]; \n \n // asigno los valores a las variables y campos corresp.\n set(\"frmFormulario.hOidCliente\", oid);\n set(\"frmFormulario.txtCodigoCliente\", cod);\n \n } \n }\n }",
"function pegarSelecionados() {\n var list_atributos = [];\n\n let valores = []; //lista com todos os campos selecionados\n $(\"[id^='divselect'\").each(function () {\n valores.push($(this).val());\n })\n\n if (valores.length > 0) {\n\n //compara cada valor com a propriedade da estrutura e adiciona no array \n var j = 0;\n while (j < valores.length) {\n var i = 0;\n while (i < lista_estrutura.Propriedades.length) {\n if (lista_estrutura.Propriedades[i].Identifier == valores[j]) {\n list_atributos.push(valores[j]);\n }\n\n i++;\n }\n\n j++;\n }\n\n return list_atributos;\n }\n return [];\n}",
"function iniciareditaractividadeconomica(datos) {\n\n document.getElementById(\"idtae\").value = datos[0][\"idtipoactividad\"]\n document.getElementById(\"nombretipoactividadeconomica\").value = datos[0][\"nombre\"];\n document.getElementById(\"descripciontipoactividadeconomica\").value = datos[0][\"descripcion\"];\n document.getElementById(\"ayudatipoactividadeconomica\").value = datos[0][\"ayuda\"];\n\n}",
"function preseleccionaValores() {\n canalOnChange();\n //[1] var subacceso = get(FORMULARIO + '.subacceso');\n //[1] var acceso = get(FORMULARIO + '.acceso');\n set(FORMULARIO + '.cbAcceso', [objsGen.acceso]);//[1][acceso]);\n accesoOnChange();\n set(FORMULARIO + '.cbSubacceso', [objsGen.subacceso]);//[1] [subacceso]);\n}",
"function SeleccionadoOficinas() {\n MuestraObj(caracteristicas);\n MuestraObj(caracteristicasOficinas);\n MuestraObj(estado);\n MuestraObj(extrasOficinas);\n MuestraObj(precioInmuebles);\n MuestraObj(btnEjecutarConsulta);\n OcultaObj(subTipoViviendas);\n OcultaObj(subTipoLocales);\n OcultaObj(subTipoTerrenos);\n OcultaObj(antiguedadViviendas);\n OcultaObj(caracteristicasViviendas1);\n OcultaObj(caracteristicasViviendas2);\n OcultaObj(caracteristicasViviendas3);\n OcultaObj(caracteristicasLocales);\n OcultaObj(caracteristicasTerrenos1);\n OcultaObj(caracteristicasTerrenos2);\n OcultaObj(caracteristicasTerrenos3);\n OcultaObj(caracteristicasTrasteros);\n OcultaObj(caracteristicasGarajes1);\n OcultaObj(caracteristicasGarajes2);\n OcultaObj(caracteristicasGarajes3);\n OcultaObj(extrasViviendas);\n OcultaObj(extrasHabitaciones);\n OcultaObj(extrasLocales);\n OcultaObj(extrasTerrenos);\n OcultaObj(extrasTrasteros);\n OcultaObj(extrasGarajes);\n OcultaObj(precioVentaViviendasDesde);\n OcultaObj(precioVentaViviendasHasta);\n OcultaObj(precioAlquilerViviendasDesde);\n OcultaObj(precioAlquilerViviendasHasta);\n OcultaObj(precioAlquilerHabitacionesDesde);\n OcultaObj(precioAlquilerHabitacionesHasta);\n OcultaObj(precioVentaLocalesDesde);\n OcultaObj(precioVentaLocalesHasta);\n OcultaObj(precioAlquilerLocalesDesde);\n OcultaObj(precioAlquilerLocalesHasta);\n OcultaObj(precioVentaTerrenosDesde);\n OcultaObj(precioVentaTerrenosHasta);\n OcultaObj(precioAlquilerTerrenosDesde);\n OcultaObj(precioAlquilerTerrenosHasta);\n OcultaObj(precioVentaTrasterosDesde);\n OcultaObj(precioVentaTrasterosHasta);\n OcultaObj(precioAlquilerTrasterosDesde);\n OcultaObj(precioAlquilerTrasterosHasta);\n OcultaObj(precioVentaGarajesDesde);\n OcultaObj(precioVentaGarajesHasta);\n OcultaObj(precioAlquilerGarajesDesde);\n OcultaObj(precioAlquilerGarajesHasta);\n if (btnComprar.checked) {\n MuestraObj(precioVentaOficinasDesde);\n MuestraObj(precioVentaOficinasHasta);\n OcultaObj(precioAlquilerOficinasDesde);\n OcultaObj(precioAlquilerOficinasHasta);\n }\n if (btnAlquilar.checked) {\n MuestraObj(precioAlquilerOficinasDesde);\n MuestraObj(precioAlquilerOficinasHasta);\n OcultaObj(precioVentaOficinasDesde);\n OcultaObj(precioVentaOficinasHasta);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pass draw function to superclass, then draw sprites, then check for overlap | draw() {
// PNG room draw
super.draw();
drawSprite(this.piggySprite)
// talk() function gets called
playerSprite.overlap(this.piggySprite, talkToPiggy);
if( this.talk2 !== null && talkedToPiggy === true ) {
image(this.talk2, this.drawX + 40, this.drawY - 190);
}
} | [
"draw() {\n\n // PNG room draw\n super.draw();\n if (x0 === true) this.bookSprites[0].remove();\n if (x1 === true) this.bookSprites[1].remove(); \n if (x2 === true) this.bookSprites[2].remove();\n if (x3 === true) this.bookSprites[3].remove(); \n\n drawSprite(this.bookSprites[0]);\n drawSprite(this.bookSprites[1]);\n drawSprite(this.bookSprites[2]);\n drawSprite(this.bookSprites[3]);\n\n playerSprite.overlap(this.bookSprites[0], this.bookCollect0);\n playerSprite.overlap(this.bookSprites[1], this.bookCollect1);\n playerSprite.overlap(this.bookSprites[2], this.bookCollect2);\n playerSprite.overlap(this.bookSprites[3], this.bookCollect3);\n }",
"draw() {\n // PNG room draw\n super.draw();\n\n //this.present.draw();\n drawSprite(this.PresentSprite)\n drawSprite(this.DadSitNpc)\n\n //overlap with sprite\n // talk() function gets called\n playerSprite.overlap(this.PresentSprite,talkToWeirdy);\n playerSprite.overlap(this.DadSitNpc,talkToNpc);\n\n if (this.textimg !== null && talkedToWeirdNPC === true){\n image(this.textimg,0,0);\n }\n if (this.textimg2 !== null && talkedToXNPC === true){\n image(this.textimg2,0,0);\n clickables[1].visible = true;\n }\n }",
"draw() {\n // PNG room draw\n super.draw();\n\n //this.present.draw();\n drawSprite(this.Femaleworker)\n drawSprite(this.Maleworker)\n\n //overlap with sprite\n // talk() function gets called\n playerSprite.overlap(this.Femaleworker,talkToWeirdy);\n playerSprite.overlap(this.Maleworker,talkToNpc);\n\n if (this.textimg !== null && talkedToWeirdNPC === true){\n image(this.textimg,0,0);\n }\n if (this.textimg2 !== null && talkedToXNPC === true){\n image(this.textimg2,0,0);\n clickables[5].visible = true;\n }\n }",
"function drawSprite(posX, posY, sizeX, sizeY, thisSprite) {\n let k = 0;\n\n for (let y = posY; y < posY + sizeY; ++y) {\n for (let x = posX; x < posX + sizeX; ++x) {\n if (thisSprite[k]) {\n ctx.fillStyle = thisSprite[k];\n ctx.fillRect(x, y, 1, 1);\n }\n k++;\n }\n }\n}",
"draw() {\n let sprite = this.sprite;\n if (sprite == null)\n return;\n ctx.drawImage(sprite.sprite, sprite.animationFrame * sprite.width, 0, sprite.width, sprite.height, this.rect.x + sprite.xOffset, this.rect.y + sprite.yOffset, this.rect.width * sprite.xStretch, this.rect.height * sprite.yStretch);\n if (Entity.showEntityRects) {\n ctx.beginPath();\n ctx.lineWidth = \"5\";\n ctx.strokeStyle = \"#00ff00\";\n ctx.rect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);\n ctx.stroke();\n }\n }",
"draw() {\n sprite(this.spriteNumber, this.x, this.y)\n }",
"function paintSprites() {\n\tlaunchPad.paint(context);\n\tbucket.paint(context);\n\tball.paint(context);\n}",
"spriteOverlap(a, b) {\n let ab = a.getBounds();\n let bb = b.getBounds();\n return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height;\n }",
"draw() {\n if (this.sprite === null) {\n super.draw();\n }\n else {\n context.drawImage(this.sprite, this.srcX, this.srcY, this.srcWidth, this.srcHeight, this.x, this.y, this.width, this.height);\n }\n }",
"drawSprite(graphics){\n var r = this.toRect();\n graphics.image(this.equipment.sprite, r[0], r[1], r[2], r[3]);\n }",
"draw() {\r\n if(this.gameState === 'Game Over') {\r\n this.drawGameOver();\r\n this.drawScoreboard();\r\n }\r\n else if(this.gameState === 'Paused') {\r\n this.drawPauseScreen();\r\n }\r\n else {\r\n if(this.world.isBackgroundLoaded)\r\n this.world.drawBackground(this.ctx, this.canvas);\r\n\r\n this.drawWeapons();\r\n this.drawPickUps();\r\n this.drawPlacedTraps();\r\n\r\n if(this.world.player.isImageLoaded)\r\n this.world.player.draw(this.ctx, this.world.camera, this.controller.mouse);\r\n\r\n this.drawEnemies();\r\n this.drawEnemyProjectiles();\r\n this.drawBullets();\r\n this.drawEnvironmentObjects();\r\n this.drawMiniMap();\r\n this.drawHUD();\r\n }\r\n this.ctx.drawImage(this.cursor.image, this.controller.mouse[0] - this.cursor.image.width/2, this.controller.mouse[1] - this.cursor.image.height/2);\r\n }",
"collisionDraw() {\r\n this.collision.element.forEach((element) => {\r\n\r\n if (Haya.Utils.invalid(element._graphic)) {\r\n element._graphic = new PIXI.Graphics();\r\n this.graphicCollision.addChild(element._graphic);\r\n }\r\n element._graphic.clear();\r\n if ($.editor.collisionFloor === \"all\" || (element.floor === $.editor.collisionFloor)) {\r\n this.collisionGraphic(element);\r\n }\r\n\r\n\r\n if (element._graphic.stage === undefined || element._graphic.stage === null) {\r\n this.graphicCollision.addChild(element._graphic);\r\n }\r\n })\r\n }",
"draw() {\n //check if the boat is dead\n if (this.allSpots.length == this.hitSpots.length) {\n this.dead = true;\n }\n stroke(255);\n\n //check if the boat is red and make it red or green fill depending on that + draw all spots\n for (let i = 0; i < this.length; i++) {\n if (this.dead) {\n fill(255, 0, 0);\n } else {\n if (this.player) {\n fill(0, 255, 0);\n } else {\n fill(151);\n strokeWeight(2);\n stroke(0);\n }\n }\n rect((this.allSpots[i][0] + 2) * res, (this.allSpots[i][1] + 2) * res, res, res);\n }\n }",
"draw() {\n if(this.isDead()) {\n return;\n }\n\n super.draw();\n }",
"draw(){\n\t\tthis.context.clearRect(this.x, this.y, this.width, this.height);\n\t\tthis.y = this.y - this.speed;\n\t\tif(this.y <= 0 - this.height || this.collision === true){\n\t\t\treturn true;\n\t\t} else{\n\t\t\t\tthis.context.drawImage(imagesHolder.pill, this.x, this.y, this.width, this.height);\n\t\t}\n\t}",
"function drawSprite(img, rect) {\n \n // Draw the image at the rect location\n image(img, rect.x, rect.y, rect.width, rect.height);\n \n}",
"function drawBattleground(sprites) {\r\n let userSpaceship = sprites[0];\r\n \r\n let battleground = document.getElementById(\"battleground\");\r\n let context = battleground.getContext(\"2d\");\r\n \r\n // determine the offsets needed\r\n let deltaX = (battleground.width / 2) - userSpaceship.x;\r\n let deltaY = (battleground.height / 2) - userSpaceship.y;\r\n\r\n // clear battleground\r\n context.clearRect(0, 0, battleground.width, battleground.height);\r\n\r\n for (let sprite of sprites) { // draw each sprite\r\n context.save(); // return to normal orientation afterwards\r\n\r\n // orient to the sprite\r\n context.translate(sprite.x + deltaX, sprite.y + deltaY);\r\n context.rotate(sprite.rotation);\r\n\r\n // we use the same base images with alternative hue\r\n context.filter = \"hue-rotate(\" + sprite.hue + \"deg)\";\r\n \r\n let spaceship = document.getElementById(\"spaceship\");\r\n\r\n if (sprite.engine) { // afterburn underneath if engine is on\r\n let afterburn = document.getElementById(\"afterburn\");\r\n context.drawImage(afterburn, -(spaceship.width * 6 / 8), -afterburn.height / 2);\r\n }\r\n\r\n if (sprite.laserGun) { // laserburn if laser is fired\r\n let laserburn = document.getElementById(\"laserburn\");\r\n context.drawImage(laserburn, (spaceship.width / 3) + (laserburn.width), -laserburn.height / 2);\r\n }\r\n\r\n // and always the spaceship itself\r\n context.drawImage(spaceship, -spaceship.width / 2, -spaceship.height / 2);\r\n \r\n context.restore(); // go back to normal\r\n } // end draw each sprite\r\n }",
"function drawSprites() {\n for (i=spriteList.length; i>0; i--) {\n sprite = spriteList[i-1];\n if (sprite.shown) {\n draw(sprite.currentAction[sprite.currentSkinIndex], sprite.x, sprite.y, sprite.width);\n sprite.nextSkin();\n }\n }\n }",
"draw(){\n //draws the background\n if(this.type == 'image'){\n var ctx = this.context;\n ctx.drawImage(this.image,0,0,960,640);\n }\n else{\n this.level.canvas.style.backgroundColor = this.color;\n }\n //draw all bawckground objects and make them solid\n this.drawables.forEach(function(d){d.draw();});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribes to notifycc messages from the server | subscribeToNotifyCC(func) {
// Do something with the data recieved.
this.socket.on('notify-cc', (data) => {
func(data);
});
} | [
"static subscribe(commands,interval,callback){return Server.subscribeEx(commands,interval,null,callback)}",
"subscribeCid()\n {\n /**\n * subscrible CID_CHANNEL\n * received message with SystemSub\n * if message is delete\n * call updateCid to re-init this cluster 's cid \n */\n this.redis.subClient.subscribe(_Setting.CID_CHANNEL);\t \t\t//listening event from internal messages\n this.redis.subClient.on('message', (channel, message)=>{\n console.log(\"Message '\" + message + \"' on channel '\" + channel + \"' arrived!\");\n var msgObj = JSON.parse(message);\n //the channels that we are going to do work\n switch (msgObj.event) {\n case 'delete':\n this.updateCid();\n break;\n }\n });\n }",
"function xcoffee_subscribe(sensor_id)\r\n{\r\n console.log('** subscribing to',sensor_id);\r\n\r\n var msg_obj = { msg_type: 'rt_subscribe',\r\n request_id: 'A',\r\n filters: [ { test: \"=\",\r\n key: \"acp_id\",\r\n value: sensor_id } ]\r\n };\r\n //sock_send_str(JSON.stringify(msg_obj));\r\n rt_mon.subscribe(sensor_id, msg_obj, handle_records);\r\n}",
"subscribeNotifications() {\n\t\tthis.nListen.on(\"data\", (data) => {\n\t\t\twinston.verbose(\"Nordic notification: \" + data.toString(\"hex\"));\n\t\t\tfor (let c of this.nCallbacks)\n\t\t\t\tc(data);\n\t\t});\n\n\t\tthis.gpListen.on(\"data\", (data) => {\n\t\t\twinston.verbose(\"GP notification: \" + data.toString(\"hex\"));\n\t\t\tfor (let c of this.gpCallbacks)\n\t\t\t\tc(data);\n\t\t});\n\n\t\tthis.rssiListen.on(\"data\", (data) => {\n\t\t\twinston.verbose(\"RSSI notification: \" + data.toString(\"hex\"));\n\t\t});\n\n\t\tthis.nListen.subscribe((error) => {\n\t\t\tif (error)\n\t\t\t\twinston.error(\"Error while subscribing to NordicListen: \" + error);\n\t\t});\n\n\t\tthis.gpListen.subscribe((error) => {\n\t\t\tif (error)\n\t\t\t\twinston.error(\"Error while subscribing to GeneralPlusListen: \" + error);\n\t\t});\n\n\t\tthis.rssiListen.subscribe((error) => {\n\t\t\tif (error)\n\t\t\t\twinston.error(\"Error while subscribing to RSSIListen: \" + error);\n\t\t});\n\t}",
"function subscribe_all()\r\n{\r\n rt_mon.subscribe('A',{},handle_records);\r\n //sock_send_str('{ \"msg_type\": \"rt_subscribe\", \"request_id\": \"A\" }');\r\n}",
"connectedCallback() {\n this.subscriptionMessage();\n }",
"registerPreConnectedSubs() {\n //todo: create some sort of front SERVER class wrapper so we can optimaly handle backChannel -> front SERVER messages (things that not every channel need to handle)\n this.sub.SEND_FRONT.register(data => {\n this._onMessage(data);\n });\n this.sub.CONNECTION_CHANGE.register(data => {\n // only handle if not from redundant connect response\n if (!(this.connectedChannelIds.has(data.channelId))) {\n this._onConnectionChange(data.channelId, data.backMasterIndex, data.connectionStatus, data.options);\n }\n });\n this.sub.BROADCAST_ALL_FRONTS.register(data => {\n this._onMessage(data);\n });\n }",
"function _subscribe() {\n\n _comapiSDK.on(\"conversationMessageEvent\", function (event) {\n console.log(\"got a conversationMessageEvent\", event);\n if (event.name === \"conversationMessage.sent\") {\n $rootScope.$broadcast(\"conversationMessage.sent\", event.payload);\n }\n });\n\n _comapiSDK.on(\"participantAdded\", function (event) {\n console.log(\"got a participantAdded\", event);\n $rootScope.$broadcast(\"participantAdded\", event);\n });\n\n _comapiSDK.on(\"participantRemoved\", function (event) {\n console.log(\"got a participantRemoved\", event);\n $rootScope.$broadcast(\"participantRemoved\", event);\n });\n\n _comapiSDK.on(\"conversationDeleted\", function (event) {\n console.log(\"got a conversationDeleted\", event);\n $rootScope.$broadcast(\"conversationDeleted\", event);\n });\n\n }",
"function onConnect() {\n // Once a connection has been made, make a subscription and send a message.\n console.log(\"onConnect\");\n client.subscribe(SUBSCRIBER);\n }",
"onClientSubscribed(callback) {\n this.subCallback = callback;\n }",
"subscribeToMessageChannel() {\n this.subcription = subscribe(\n this.messageContext,\n CART_ITEM_CHANNEL,\n (message) => {\n this.handleMessage(message);\n }\n );\n }",
"function initSubscribe() {\n pubSubClient.subscribe(redis_config.buffer_redis.notice_channel_config.server_to_site_channel);\n pubSubClient.on('message', function (channel, message) {\n handleSubMsg(channel, message);\n });\n}",
"function onConnect() {\n // Once a connection has been made, make a subscription and send a message.\n console.log(\"onConnect\");\n client.subscribe(\"#\");\n}",
"async _onSubscribe (client, msg) {\n // TODO Make sure invoice exists\n // We really want to do this as soon as client connects.\n // If we don't, then we open ourselves up to DoS attacks.\n // So. perhaps, we force a subscribe within X seconds.\n // Otherwise, we boot the client for being cunts.\n\n if (!this.subscriptions[msg.invoiceId]) {\n this.subscriptions[msg.invoiceId] = []\n }\n\n this.subscriptions[msg.invoiceId].push(client)\n\n return client.emit('subscribed', {\n message: `Subscribed to ${msg.invoiceId}`\n })\n }",
"subscribe() {}",
"notify (artistId, subject, message, from)\n {\n const suscription = this.findArtistSuscription(parseInt(artistId));\n console.log(suscription);\n suscription.notifySubscripber(this.gmail, subject, message, from);\n }",
"notify() {\n /*\n We iterate through the subscribing functions, notifying each of them.\n */\n [...this.subscriptions].forEach(([subscribed, subscription]) => {\n subscription(this);\n });\n }",
"static subscribeEx(commands,interval,requestOptions,callback){if(!TcHmi.System.Services.serverManager)return TcHmi.Callback.callSafeEx(callback,null,{error:TcHmi.Errors.E_WEBSOCKET_NOT_READY,details:{code:TcHmi.Errors.E_WEBSOCKET_NOT_READY,message:TcHmi.Errors[TcHmi.Errors.E_WEBSOCKET_NOT_READY],domain:\"TcHmi.Server\"}}),null;if(!Array.isArray(commands))return TcHmi.Callback.callSafeEx(callback,null,{error:TcHmi.Errors.E_PARAMETER_INVALID,details:{code:TcHmi.Errors.E_PARAMETER_INVALID,message:TcHmi.Errors[TcHmi.Errors.E_PARAMETER_INVALID],reason:\"commands parameter must be an array\",domain:\"TcHmi.Server\"}}),null;let request={requestType:\"Subscription\",commands:commands};return null!=interval&&\"number\"==typeof interval&&(request.intervalTime=interval),TcHmi.System.Services.serverManager.requestEx(request,requestOptions,Server.__handleServerResponse({completed:data=>{TcHmi.Callback.callSafeEx(callback,null,data)}}))}",
"function broadcast() {\r\n\t\t\tvar clength = channel.clients.length;\r\n\t\t\t/*for (var i = 0; i < clength; i++) {\r\n\t\t\t\tchannel.publish('say', getCurrentChannel().channelName,\r\n\t\t\t\t\t\tchannel.clients[i].id);\r\n\t\t\t}*/\r\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalizes am / a.m. / etc. to AM (uppercase, no other characters) | function normalizeAMPM(ampm) {
return ampm.replace(/[^apm]/gi, '').toUpperCase();
} | [
"function convertTimeIntoAmPm(time){\n var timeString = time;\n var hourEnd = timeString.indexOf(\":\");\n var H = +timeString.substr(0, hourEnd);\n var h = H % 12 || 12;\n var ampm = H < 12 ? \"AM\" : \"PM\";\n timeString = h + timeString.substr(hourEnd, 3) + ampm;\n return timeString\n\n}",
"function ampm (time) {\n \n var split_time = time.split(\":\");\n var ampm_time = \"\";\n \n if (Number(split_time[0]) <= 11) {\n ampm_time = `${split_time[0]}:${split_time[1]} AM}`;\n } else if (Number(split_time[0]) == 12) {\n ampm_time = `${split_time[0]}:${split_time[1]} PM}`;\n } else {\n var pm_time = Number(split_time[0])-12;\n ampm_time = `${pm_time}:${split_time[1]} PM`;\n }\n \n return ampm_time;\n \n }",
"convertTime(time) {\n if (this.state.clock12h) {\n const h23 = parseInt(time.substr(0,2));\n const h12 = h23 % 12 || 12;\n const ampm = h23 < 12 ? \" am\" : \" pm\"\n return h12 + time.substr(2, 3) + ampm;\n } else {\n return time;\n }\n }",
"function ampm(h) {\n if(h < 12)\n var a = 'AM';\n else\n var a = 'PM';\n return a;\n}",
"function zenNormalizeTime(str)\n{\n\tvar out = '';\n\ttry {\n\t\tvar t = str.split(\":\");\n\n\t\tvar hour = parseInt(t[0],10);\n\t\tvar min = parseInt(t[1],10);\n\t\tvar sec = parseInt(t[2],10);\n\t\t// am/pm\n\t\tvar mod1 = str.substr(str.length-1,1);\n\t\tvar mod2 = str.substr(str.length-2,2);\n\n\t\tif (!isNaN(hour)) {\n\t\t\tif ((mod1=='a'||mod1=='A'||mod2=='am'||mod2=='AM')&&(hour==12)) {\n\t\t\t\thour = 0;\n\t\t\t}\n\t\t\telse if ((mod1=='p'||mod1=='P'||mod2=='pm'||mod2=='PM')&&(hour<12)) {\n\t\t\t\thour += 12;\n\t\t\t}\n\t\t\thour = hour < 0 ? 0 : hour;\n\t\t\thour = hour > 23 ? 0 : hour;\n\t\t\tout = ((hour < 10) ? '0' : '') + hour;\n\n\t\t\tif (!isNaN(min)) {\n\t\t\t\tmin = min < 0 ? 0 : min;\n\t\t\t\tmin = min > 59 ? 0 : min;\n\t\t\t\tout += ((min < 10) ? ':0' : ':') + min;\n\t\t\t\tif (!isNaN(sec)) {\n\t\t\t\t\tsec = sec < 0 ? 0 : sec;\n\t\t\t\t\tsec = sec > 59 ? 0 : sec;\n\t\t\t\t\tout += ((sec < 10) ? ':0' : ':') + sec;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout += \":00\";\n\t\t\t}\n\t\t}\n\t}\n\tcatch(ex) {\n\t}\n\n\treturn out;\n}",
"tConvert(time, format) {\n if (format == 12) {\n let timeArr = time.split(\":\");\n let hours = timeArr[0];\n let _ext = \"AM\";\n if (hours >= 12) {\n hours = timeArr[0] % 12;\n _ext = \"PM\";\n }\n return hours + \":\" + timeArr[1] + \":\" + timeArr[2] + \" \" + _ext;\n } else {\n }\n }",
"get displayAmPm() {\n return this.isAM ? 'AM' : 'PM';\n }",
"function formattingTime(str) {\n let formattedTime = str.replace(/:00/g, \"\").replace(/ PM/g, \"pm\").replace(/ AM/g, \"am\")\n\n //check and replace duplicate in row\n if (formattedTime.match(/am.*am/)) { // Check if there are 2 'am'\n formattedTime = formattedTime.replace('am', '') // Remove the first one\n } else if (formattedTime.match(/pm.*pm/)) { // Check if there are 2 'pm'\n formattedTime = formattedTime.replace('pm', '') // Remove the first one\n }\n return formattedTime\n}",
"function formattingTime(str) {\n let formattedTime = str.replace(/:00/g, \"\").replace(/ PM/g, \"pm\").replace(/ AM/g, \"am\")\n\n //check and replace duplicate in row\n if (formattedTime.match(/am.*am/)) { // Check if there are 2 'am'\n formattedTime = formattedTime.replace('am', ''); // Remove the first one\n } else if (formattedTime.match(/pm.*pm/)) { // Check if there are 2 'pm'\n formattedTime = formattedTime.replace('pm', ''); // Remove the first one\n }\n return formattedTime\n}",
"function parseAMPM() {\r\n\t\tvar result = str.substr(strPointer, valueLength).toLowerCase() == Zapatec.Date.Pm ? true : false;\r\n\t\treturn result || (str.substr(strPointer, valueLength).toLowerCase() == Zapatec.Date.Am ? false : null);\r\n\t}",
"function am_pm(h)\n{\n with (Math) {\n var hours, minutes, ampm, result=\"\";\n hours = floor(h);\n minutes = floor((h - hours) * 60 + 0.5);\n if (minutes == 60)\n {\n hours += 1;\n minutes = 0;\n }\n\n if (hours > 11)\n {\n hours -= 12;\n ampm = \" pm\";\n }\n else\n {ampm = \" am\";}\n if (hours < 1) hours = 12;\n\n if (hours < 10)\n {result = result + \"0\" + floor(hours);}\n else\n {result = result + floor(hours);}\n result = result + \":\";\n\n if (minutes < 10)\n {result = result + \"0\" + minutes;}\n else\n {result = result + minutes;}\n }\n result = result + ampm;\n return result;\n}",
"function ampm(time) {\n if (time >= 12) {\n return \"pm\";\n } else {\n return \"am\";\n }\n}",
"function amOrPm(hr) {\r\n if ((parseInt(hr,10)>=8) && (parseInt(hr)<=11))\r\n return \"AM\"\r\n else\r\n return \"PM\"\r\n }",
"function convert_to_12_format (time) {\n var timeString = time;\n var hourEnd = timeString.indexOf(\":\");\n var Hour = +timeString.substr(0, hourEnd);\n var get_hour = Hour % 12 || 12;\n var ampm = Hour < 12 ? \"AM\" : \"PM\";\n timeString = get_hour + timeString.substr(hourEnd, 3) + ' '+ ampm;\n \n console.log(timeString)\n return timeString;\n}",
"function formatTimeToAMPM(date) {\n let hours = date.getHours();\n let minutes = date.getMinutes();\n let ampm = hours >= 12 ? 'PM' : 'AM';\n\n hours = hours % 12;\n hours = hours ? hours : 12;\n minutes = minutes < 10 ? '0' + minutes : minutes;\n\n let timeInAMPM = hours + \":\" + minutes + \" \" + ampm\n return timeInAMPM\n }",
"function formatTime3(string) {\n let newStr = \"\";\n\n let strArr = string.split(\" \");\n // strArr = [\"1:00\", \"AM\"]\n\n newStr += strArr[0];\n\n let isAM = strArr[1][0] === \"A\";\n\n if (isAM) {\n newStr += \"a\";\n\n } else {\n newStr += \"p\";\n }\n\n return newStr;\n }",
"function getAMPM(hour) {\n\t\treturn hour >= 12 ? 'PM' : 'AM';\n\t}",
"function strToMilitaryTime(time) {\n\tvar am_pm = time.substring(time.length - 2, time.length);\n\tvar hour = parseInt(time.substring(0, 2));\n\tif (am_pm === \"AM\") {\n\t\tif (hour === 12) return 0; // case for 12:00 AM\n\t\treturn hour;\n\t}\n\tif (hour < 12) return hour + 12;\n\treturn hour; // case for 12:00 PM\n}",
"function toddMMMYYYYHHMMSSAP(input) {\n if (input && input != null && !(\"Invalid Date\" == new Date(input))) {\n return moment(input).format('DD MMM YYYY hh:mm:ss a');\n }\n else {\n return '';\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dialog when a user clicks on map marker/pin that shows a list of the services offered by the person at that marker | function createServiceChoiceDialog(chosenMarker) {
console.log(chosenMarker);
var chosenMarkerUserID = chosenMarker;
var chosenMarkerUser = readUser(chosenMarkerUserID);
var chosenMarkerName = chosenMarkerUser.FirstName + " " + chosenMarkerUser.LastName;
//set name on dialog
$('#servicesChoiceDialogName').text(chosenMarkerName);
$.mobile.changePage("#page-dialog", {
role : "dialog",
allowSamePageTransition : true
});
var currentUser = getCurrentUser();
var filteredServices = [];
$('#servicesListView').empty();
if (services != null && services.length > 0) {
for (var i = 0; i < services.length; i++) {
if (chosenMarkerUserID == services[i].UserID) {
filteredServices.push(services[i]);
//$('#servicesListView').append('<li><a onclick="createServicePageWindow('+services[i]+', '+ currentUser +')">' +services[i].Description+ '</a></li>');
$('#servicesListView').append('<li><a onclick="createServicePageWindow(' + services[i].ServiceID + ', ' + currentUser.UserID + ', "' + chosenMarkerName + '")">' + services[i].Description + '</a></li>');
}
}
}
$('#servicesListView').listview('refresh');
//$('#servicesListView').empty().append('<li><a data-rel="dialog" href="#page-subdialog">Test</a></li><li><a data-rel="dialog" href="#page-subdialog">Test2</a></li>').listview('refresh');
} | [
"function addMarkerClickListener(marker, map, service, place){\n var infoWindow = new google.maps.InfoWindow();\n google.maps.event.addListener(marker, 'click', function() {\n service.getDetails(place, function(result, status) {\n if (status !== google.maps.places.PlacesServiceStatus.OK) {\n alert(status);\n return;\n }\n var contentString = '<div class=\"info\" style=\"color: black\">'+\n '<strong>' + result.name + '</strong><br>' +\n '<em>' + result.formatted_phone_number + '</em>';\n infoWindow.setContent(contentString);\n infoWindow.open(map, marker);\n });\n });\n }",
"function makeInfoBoxListener(marker) {\r\n return function() {\r\n var info = marker.info;\r\n var contentString = '<div id=\"popup-content\"><table>';\r\n for (var i = 0; i < userOptions.infoBox.length; i++) {\r\n var infoBoxField = userOptions.infoBox[i];\r\n var name = userOptions[infoBoxField].name;\r\n var infoPoint = info[infoBoxField];\r\n var value = userOptions[infoBoxField].values[infoPoint] ?\r\n userOptions[infoBoxField].values[infoPoint].name : infoPoint;\r\n contentString += '<tr><td>' + name + '</td><td>' + value + '</td></tr>';\r\n }\r\n contentString += '</table></div>';\r\n \r\n infoWindow.content = contentString;\r\n infoWindow.open(map, marker);\r\n };\r\n}",
"function liClicked(clickLi) {\n populateInfoWindow(clickLi, new google.maps.InfoWindow());\n}",
"function place_marker(meet) {\n meets.push(meet);\n\n latitude = meet.fields.location[0];\n longitude = meet.fields.location[1];\n var latLng = new google.maps.LatLng(latitude,longitude);\n var marker = new google.maps.Marker({\n position : latLng,\n map : map,\n });\n markers.push(marker)\n\n google.maps.event.addListener(marker, 'click', function(){\n this_index = markers.indexOf(marker);\n this_meet = meets[this_index];\n selected_meet = this_meet;\n\n html = '<div class=\"marker-details\"><h2 class=\"text-center\">' + meet.fields.name + '</h2>' +\n '<p>' + meet.fields.description + '</p>' +\n '<button type=\"button\" class=\"btn btn-default text-center\" onClick=\"show_event_details_dialog()\">' +\n 'View Details'+\n '</button>' +\n '</div>'\n infoWindow.close();\n infoWindow.setContent(html);\n infoWindow.open(map, marker);\n });\n}",
"function markerOnClick (e) {\n let poi = e.target.feature.info\n // popupFromFeatureInfo(poi);\n setupInfoWindow(poi)\n // $(\".modal-content\").html(popupFromFeatureInfo(poi));\n // 'This is marker ' + JSON.stringify(e.target.feature));\n $('#infoWindow').modal('show')\n // let centre = (e.target.getLatLng) ? e.target.getLatLng() : e.target.getCenter()\n // e.target._map.setView(centre);\n // e.preventDefault();\n }",
"addMarker(currDonor, view, markerSymbol, Point, Graphic){\n // Create a point geometry\n var point = new Point({\n longitude: currDonor.longitude,\n latitude: currDonor.latitude\n });\n // Create an object for storing attributes related to the point\n var pointAtt = {\n fullName: [currDonor.firstName, currDonor.lastName].join(\" \"),\n bloodGroup: currDonor.bloodGroup,\n currAddress: currDonor.currAddress,\n contactNumber: currDonor.contactNumber,\n emailAddress: currDonor.emailAddress\n };\n\n // Create a point graphic, add the geometry and symbol to it\n var pointGraphic = new Graphic({\n geometry: point,\n symbol: markerSymbol,\n attributes: pointAtt,\n popupTemplate: {\n title: \"{fullName}\",\n content: `\n <table>\n <tr>\n <th class=\"esri-popup-renderer__field-header\">Blood Group</th>\n <td class=\"esri-popup-renderer__field-data\">{bloodGroup}</td>\n </tr>\n <tr>\n <th class=\"esri-popup-renderer__field-header\">Address</th>\n <td class=\"esri-popup-renderer__field-data\">{currAddress}</td>\n </tr>\n <tr>\n <th class=\"esri-popup-renderer__field-header\">Contact Number</th>\n <td class=\"esri-popup-renderer__field-data\">xxxxx-xxxxx</td>\n </tr>\n <tr>\n <th class=\"esri-popup-renderer__field-header\">Address</th>\n <td class=\"esri-popup-renderer__field-data\">xxx@xxx.xxx</td>\n </tr>\n </table>\n `,\n actions: [{\n id: \"show-hidden-info\",\n title: \"Show Hidden Info\"\n }]\n }\n });\n\n // Add Marker Point Graphic to the MapView\n view.graphics.add(pointGraphic);\n }",
"function personListinDialog(calledby) {\n\t// Callbackfunktion f�r die Suchanfragen an die Datenbank\n\t// Eine Suchanfrage liefert immer eine Liste von Personen, die sich f�r die\n\t// Suche qualifizieren, zur�ck\n\t// die XML response des http requests wird geparsed\n\t// und die Resultatliste der Personen aufgebaut.\n\t// Das Ergebnis wird als Tabelle unten hingeschrieben.\n\t// danach wird die Onclick Aktion gesetzt.\n\t\n\tif (req.readyState == 4) {\n\t\t// req Status 200 = OK, 404 = page not found\n\t\tif (req.status == 200) {\n\t\t\tprocessXMLResponse();\n\t\t\tvar footer = $(\"#dialog1bottom\");\n\t\t\tfooter.html(listOfPerson.toTable(\"dialogUpdateClass\"));\n\t\t\t// Das click behavior im Dialog ist anders als bei einer quicksearch oder advancedsearch\n\t\t\tsetDialogPersonOnClick(calledby); \n\t\t}\n\t}\n}",
"function showVehiclePopup(v) {\n if (v.poi) {\n html = '<h4>' + v.name + '</h4><p>' + v.position.time_of_day + '</p><p>' + v.position.occurred_at.substring(0, 10) + '</p>';\n \n MapPane.popup(v.poi, html);\n }\n }",
"function bindInfoClick(marker, content){\n //adding info \n var info = new google.maps.InfoWindow({\n content: content\n });\n \n //adding click\n google.maps.event.addListener(marker, 'click', function(){\n info.open(map, marker);\n });\n \n }",
"function showInfoWindow() {\n var marker = this;\n places.getDetails({ placeId: marker.placeResult.place_id },\n function(place, status) {\n if (status !== google.maps.places.PlacesServiceStatus.OK) {\n return;\n }\n infoWindow.open(map, marker);\n buildIWContent(place);\n\n // Checks what the dropdown list is currently selected on and fills either\n // text boxes with the location's name.\n if (document.getElementById('poi').value === 'lodging') {\n document.getElementsByClassName('selectedHotelTB')[0].value =\n place.name,\n // Stores address for Navigation.\n startID = place.formatted_address;\n // Displays the text boxes for selected locations.\n showDisplayTwo();\n\n }\n else {\n document.getElementsByClassName('selectedPOItb')[0].value =\n place.name,\n // Stores address for Navigation.\n finishID = place.formatted_address;\n // Displays the POI textbox.\n showDisplayFour();\n }\n // if textbox ISN'T empty then display satnav btn.\n if (document.getElementsByClassName('selectedPOItb')[0].value !== \"\") {\n showDisplayThree();\n }\n else {\n return;\n }\n });\n}",
"function displayMap(e) {\n e.preventDefault();\n var ctr = getCenter();\n var z = getZoom();\n googleMap = new google.maps.Map(document.getElementById('mymap'), {\n center: ctr,\n zoom: z\n });\n var marker = new google.maps.Marker( {\n position: ctr\n });\n \n marker.setMap(googleMap);\n\n var infoWindow = new google.maps.InfoWindow( {\n content: selectedName\n });\n\n marker.addListener( 'click', function() {\n infoWindow.open(googleMap, marker)\n });\n}",
"function onClickList(name)\n{\n var marker;\n for (i = 0; i < markers.length; i++) {\n if (markers[i].title == name){\n marker= markers[i];\n }\n }\n showInfo(marker);\n}",
"function insertOracleMarker(map) {\n // Oracle Location\n var OracleLocation = new google.maps.LatLng(37.4852, -122.2364);\n var OracleLocationMarker = new google.maps.Marker({\n position: OracleLocation,\n icon: {\n url: \"http://maps.google.com/mapfiles/ms/icons/yellow-dot.png\",\n scaledSize: new google.maps.Size(20, 20)\n }\n });\n\n OracleLocationMarker.setMap(map);\n\n // This block of code is for the small info window\n var contentOracle =\n ' <h1 style=\"text-align: center;\">ORACLE CORPORATION</h1>' +\n ' <img src=\"./assets/Images/oracleInfoImg.jpg\" ' +\n ' style=\"float:left; width: 34%; border-radius: 30px 50px 0 50px; float: left; width: 34% !important;\">' +\n ' <p style = \"text-align: center;\"><b>ORACLE</b> is an American multinational computer technology corporation ' +\n 'headquartered in Redwood Shores, California. The company sells database software and technology, ' +\n 'cloud engineered systems, and enterprise software products.<br>' +\n '<a href=\"https://en.wikipedia.org/wiki/Oracle_Corporation\"><button type=\"button\" class=\"common-btn-styling\">LEARN MORE!</button></a>' +\n ' </p>';\n\n\n var infoOracle = new google.maps.InfoWindow({\n content: contentOracle\n });\n\n\n var OracleLocationInfo = new google.maps.InfoWindow({\n content: \"ORACLE\"\n });\n\n google.maps.event.addListener(OracleLocationMarker, 'click', function () {\n OracleLocationInfo,\n infoOracle.open(map, OracleLocationMarker);\n });\n\n}",
"function showAddressSearchBox(){ \n\tvar place = autocomplete.getPlace();\n\tvar point = place.geometry.location;\n\t\n\tnewRideInfo = {};\n\tnewRideInfo.lat = point.lat();\n\tnewRideInfo.lng = point.lng();\n\tnewRideInfo.address = place.formatted_address;\n\tbeginRideCreationPopup(); \n}",
"function onClickMarker(title, attributes) {\n\tvar selected_item = title;\n\tView.openDialog('ab-waste-rpt-map-bl-loc-details.axvw', null, true, {\n\t\twidth : 1280,\n\t\theight : 600,\n\t\tbl_id:\"\",\n\t\tsite_id:\"\",\n\t\tcloseButton : true,\n\t\tafterInitialDataFetch : function(dialogView) {\n\t\t\tvar dialogController = dialogView.controllers.get('blDetail');\n\t\t\tif (dialogView.getOpenerView().controllers.get('mapCtrl').dataSourceId != 'dsBuilding') {\n\t\t\t\tdialogController.site_id = '';\n\t\t\t\tdialogController.storage_location = selected_item;\n\t\t\t}else{\n\t\t\t\tdialogController.site_id = selected_item;\n\t\t\t\tdialogController.storage_location = '';\n\t\t\t}\n\t\t}\n\t});\n}",
"function markerInfoWindow(id) {\n // Coordinate of the new points\n var lat = markers[id].position.lat()\n var lng = markers[id].position.lng()\n \n // Text to show\n var text = newPointInfoTemplate.format(id, lat, lng);\n infoWindow.setContent(text);\n // Position of the point\n var anchor = new google.maps.MVCObject();\n anchor.setValues({\n position: markers[id].position,\n\t// Ofset del text-box a las coordenadas\n anchorPoint: new google.maps.Point(0, 0)\n });\n\n infoWindow.open(map, anchor);\n}",
"function showPopup(response) {\n if (response.length > 0) {\n view.popup.open({\n features: response,\n location: event.mapPoint\n });\n }\n document.getElementById(\"viewDiv\").style.cursor = \"auto\";\n }",
"function addEventListener(map) {\n map.addListener('click', function (event) {\n var title = window.prompt(\"name this title\");\n var description = window.prompt(\"describe this place\");\n if (title && description) {\n addMarker(event.latLng, title, map, description);\n $(\"input[name='pins_array']\").val(\"\");\n $(\"input[name='pins_array']\").val(JSON.stringify(markerArr));\n }\n });\n }",
"function createList_of_markers_modal(dataFromApi){ \n\t var allList = \"<br><h4>Your list of markers: \" + Object.keys(dataFromApi.features).length + \" items.</h4>\";\n\t\t\n\t dataFromApi.features.forEach(function(dataZ, i) {\n\t\t\tallList += \"<p>\" + (i +1) + \" \" + dataZ.properties.title + \"</p>\"; //number + title\n\t\t});\n\t\t$(\"#list_of_markers\").html(allList);\n\t\t\n\t\t\n\t\t \n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
K1 and b are tuning constants from the report mentioned above: K1 modifies term frequency (higher values increase the influence) b modifies document length (between 0 and 1; 1 means that long documents are repetitive and 0 means they are multitopic) | constructor(names, texts, customStopwords = [], K1 = 1.5, b = 0.75) {
this.stopwordFilter = term => !Stopwords.includes(term) && !customStopwords.includes(term);
this.K1 = K1;
this.b = b;
this.documents = new Map();
this.collectionFreq = new Map();
this.termWeights = new Map();
this.uniqueDocuments = new Map();
for (let i = 0; i < texts.length; i++) {
this.documents.set(names[i], new Document(texts[i]));
}
this.calculateTermFrequencies();
this.calculateTermWeights();
this.calculateVectors();
} | [
"function updateDeltaK() {\n deltaK = (k1 - k2) / 2;\n}",
"train(){\n for(let [key, value] of this.ids){\n // Calculate probability for all of the classifications\n for(let classification of this.documents.keys()){\n let repetitionsInClass = this.documents.get(classification).get(key) + 1;\n if(isNaN(repetitionsInClass)){\n repetitionsInClass = 1;\n }\n let totalWordsInClass = this.documents.get(classification).size;\n let totalWordsInVocabulary = this.ids.size;\n // Calculate probability equation for each element\n let probability = repetitionsInClass / (totalWordsInClass + totalWordsInVocabulary);\n this.ids.get(key).set(classification, probability);\n }\n }\n // Calculate bias for each classification\n let totalDocuments = 0;\n for(let total of this.bias.values()){\n totalDocuments += total;\n }\n for(let key of this.bias.keys()){\n this.bias.set(key, this.bias.get(key) / totalDocuments);\n }\n }",
"function doTF(c){\n termfrequency = {};\n\n let words = text[c].split(' '); //gives the individual words\n for (let i = 0; i < words.length; i++) {\n //The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).\n if(termfrequency.hasOwnProperty(words[i])) {\n // the word is already in the data structure\n termfrequency[words[i]]++;\n } else {\n termfrequency[words[i]]=1;\n }\n }\n\n for (i in termfrequency) {\n termfrequency[i] = termfrequency[i]/documentfrequency[i];\n }\n}",
"function kwToKs() {\r\n ks.value = Math.round(kw.value * 1.359621617);\r\n if (kw.value * 0 != 0 || kw.value == \"\") {\r\n kw.value = \"\"\r\n ks.value = \"\"\r\n }\r\n}",
"function ksToKw() {\r\n kw.value = Math.round(ks.value * 0.73549875);\r\n if (ks.value * 0 != 0 || ks.value == \"\") {\r\n ks.value = \"\";\r\n kw.value = \"\";\r\n }\r\n}",
"relevance(that){cov_25grm4ggn6.f[4]++;let total=(cov_25grm4ggn6.s[15]++,0);let words=(cov_25grm4ggn6.s[16]++,Object.keys(this.count));cov_25grm4ggn6.s[17]++;words.forEach(w=>{cov_25grm4ggn6.f[5]++;cov_25grm4ggn6.s[18]++;total+=this.rank(w)*that.rank(w);});//return the average rank of using my words in the other vocabulary\ncov_25grm4ggn6.s[19]++;return total/words.length;}",
"relevance(that){cov_25grm4ggn6.f[4]++;let total=(cov_25grm4ggn6.s[13]++,0);let words=(cov_25grm4ggn6.s[14]++,Object.keys(this.count));cov_25grm4ggn6.s[15]++;words.forEach(w=>{cov_25grm4ggn6.f[5]++;cov_25grm4ggn6.s[16]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[17]++;return total/words.length;}",
"textMining() {\n\t\tthis.phraseByName();\n\t\t// elimina i nomi dalle frasi, e assegna un nome a ciascuna di esse\n\t\tconst topics = this.typeAnalysis();\n\t\tif (this.problems.length !== 0) this.resolveProblems();\n\t\tthis.documento = TextMiner.eraseNames(this.documento, this.names);\n\t\tthis.documento = TextMiner.eraseNames(this.documento, STWS.IT);\n\t\tconst doc = this.documento.match(/[^.!?]+[.!?]+/g);\n\t\tlet result = lda(doc, topics, 10, null, null, null, 100);\n\t\t// Arbitrario il numero di termini per topics\n\t\t// result.combine(arrayuserkeywords); aggiungere keywords personalizzate\n\t\tresult = this.addKeywords(result);\n\t\tthis.scoreAssignment(TextMiner.ldaToWords(result));\n\t}",
"function updateKWIC() {\n // kwic = RiTa.kwic(theText.join('\\n'), word, {\n // ignorePunctuation: true,\n // ignoreStopWords: true,\n // wordCount: 200\n // });\n kwic = RiTa.kwic(theTextCopy, word, {\n ignorePunctuation: true,\n // ignoreStopWords: true,\n wordCount: 10\n });\n // console.log(kwic);\n if (kwic.length == 0) {\n // textAlign(CENTER);\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n text(\"Context word not found\", width / 1.7, height / 4);\n } else {\n\n var tw = textWidth(word);\n\n for (var i = 0; i < kwic.length; i++) {\n\n //console.log(display[i]);\n var parts = kwic[i].split(word);\n var x = width / 1.7,\n y = i * 20 + 115;\n\n if (y > height - 20) return;\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n // fill(0);\n textAlign(RIGHT);\n text(parts[0], x - tw/1.5, y);\n\n fill(200, 0, 0);\n textFont(\"Lucida Console\");\n textAlign(CENTER);\n text(word, x, y);\n\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textAlign(LEFT);\n text(parts[1], x + tw/1.5, y);\n }\n }\n}",
"function Term(){\n\tthis.word = \"empty\";\t\t\t\t\t\t\t//text of the term as a character string\n\tthis.pos = \"empty\";\t\t\t\t\t\t\t\t//term Part Of Speech (POS) tag\n\tthis.frequency = 1;\t\t\t\t\t\t\t\t//frequency of term in document\n\tthis.score = 0;\t\t\t\t\t\t\t\t\t//value of term based on attributes\n\tthis.rank = 0;\t\t\t\t\t\t\t\t\t//sequential rank based on value of all terms in document\n\t//eventualy try to do a prototype here\n\tthis.acronym = false;\t\t\t\t\t\t\t//is term all caps and probably an acronym?\n\tthis.frontCapital = false; \t \t\t\t//is first letter capitalized but NOT after period/at beggining of sentence\n\tthis.midCapital = false;\t\t\t\t\t\t//does term have a capitalized letter in the middle?\n\tthis.commaSeparated = false;\t\t\t\t\t//is it between two commas?\n\tthis.stop1 = false;\t\t\t\t\t\t\t\t//is it in the stopword list? List one is shortest and has greatest negative impact on term value\n\tthis.stop2 = false;\t\t\t\t\t\t\t\t//is it in the stopword list? List one is mid length/value\n\tthis.stop3 = false;\t\t\t\t\t\t\t\t//is it in the stopword list? List one is longest and has least negative impact on term value\n\tthis.contextLocal = 0; \t\t\t\t //self generated high value context list based on top terms\n\tthis.multiWordBool = false; \t \t\t\t//is it a two word compound term?\n\tthis.multiComponent1 = 0;\t\t\t\t\t\t//info on first component word, declare as Term when needed\n\tthis.multiComponent2 = 0;\t\t\t\t\t\t//info on second component word, declare as Term when needed\n}",
"tf() {\n this.query.forEach(term => {\n term[\"_tf\"] = this.keywords.reduce((acc, item) => {\n if(item.includes(term[\"word\"])) {\n acc++;\n }\n return acc;\n }, 0)\n })\n }",
"static gain1m(freq) {\n return 10 *this.log10(4 * Math.PI / Math.pow(this.lambda(freq), 2));\n }",
"function setWordCounts(authors){\n\tvar result = new Object();\n\t//set vocabulary\n\tvar vocObj = new Object();\n\t//set vocabulary\n\n\tfor(var author in authors){\n\t\tauthors[author].totalWordCount = 0;\n\t\tif(typeof authors[author][\"wordProbs\"] == \"undefined\")\n\t\t\tauthors[author][\"wordProbs\"] = new Object();\n\t\tfor(var i=0; i<authors[author].train.length; i++){ //handle all docs of author\n\t\t\tvar docTokenized = tokenizer(authors[author].train[i].content);\n\t\t\tfor(var j=0; j<docTokenized.length; j++){ \n\t\t\t\tif(typeof docTokenized[j] == \"undefined\" || docTokenized[j] == \"\")\n\t\t\t\t\tcontinue;\n\t\t\t\tif(typeof authors[author][\"wordProbs\"][docTokenized[j]] == \"undefined\")\n\t\t\t\t\tauthors[author][\"wordProbs\"][docTokenized[j]] = 1;\n\t\t\t\telse\n\t\t\t\t\tauthors[author][\"wordProbs\"][docTokenized[j]]++;\n\t\t\t\tauthors[author].totalWordCount++;\n\t\t\t\n\t\t\t\t//set vocabulary\n\t\t\t\tvocObj[docTokenized[j]] = 1; //Save unique word into vocabulary\n\t\t\t\t//set vocabulary\t\t\t\n\t\t\t}\n\t\t}\n\t\tauthors[author].uniqueWordCount = Object.keys(authors[author][\"wordProbs\"]).length;\t\t\n\t}\n\n\t//Bonus\n\tvocObj[\"averageWordCount\"] = 1; //Save bonus feature to vocabulary\n\n\t//set vocabulary\n\tvar vocArray = new Array(); \n\tvar vocId = 1;//Start from 1. index\n\tfor(var voc in vocObj){\n\t\tvocObj[voc] = vocId;\n\t\tvocArray[vocId] = voc;\n\t\tvocId++;\n\t}\t\n\treturn {vocArray: vocArray, vocObj: vocObj};\t\n\t//set vocabulary\n}",
"function useIndexData(autoindex,knodule,baseweight,whendone){\n var ntags=0, nitems=0, handle_weak=false;\n var allterms=metaBook.allterms, prefixes=metaBook.prefixes;\n var tagweights=metaBook.tagweights;\n var maxweight=metaBook.tagmaxweight, minweight=metaBook.tagminweight;\n var tracelevel=Math.max(Trace.startup,Trace.indexing);\n var alltags=[];\n if (!(autoindex)) {\n if (whendone) whendone();\n return;}\n for (var tag in autoindex) {\n if (tag[0]===\"_\") continue;\n else if (!(autoindex.hasOwnProperty(tag))) continue;\n else alltags.push(tag);}\n // Number chosen to exclude exhaustive auto tags\n if (alltags.length<1000) handle_weak=true;\n function handleIndexEntry(tag){\n var ids=autoindex[tag]; ntags++;\n var occurrences=[];\n var bar=tag.indexOf('|'), tagstart=tag.search(/[^*~]/);\n var taghead=tag, tagterm=tag, knode=false, weight=false;\n if (bar>0) {\n taghead=tag.slice(0,bar);\n tagterm=tag.slice(tagstart,bar);}\n else tagterm=taghead=tag.slice(tagstart);\n if ((handle_weak)||(tag[0]!=='~'))\n knode=metaBook.knodule.handleSubjectEntry(tag);\n else knode=metaBook.knodule.probe(taghead)||\n metaBook.knodule.probe(tagterm);\n /* Track weights */\n if (knode) {\n weight=knode.weight;\n tagweights.set(knode,weight);}\n else if (bar>0) {\n var body=tag.slice(bar);\n var field_at=body.search(\"|:weight=\");\n if (field_at>=0) {\n var end=body.indexOf('|',field_at+1);\n weight=((end>=0)?\n (parseFloat(body.slice(field_at+9,end))):\n (parseFloat(body.slice(field_at+9))));\n tagweights.set(tagterm,weight);}}\n else {}\n if (weight>maxweight) maxweight=weight;\n if (weight<minweight) minweight=weight;\n if (!(knode)) {\n var prefix=((tagterm.length<3)?(tagterm):\n (tagterm.slice(0,3)));\n allterms.push(tagterm);\n if (prefixes.hasOwnProperty(prefix))\n prefixes[prefix].push(tagterm);\n else prefixes[prefix]=[tagterm];}\n var i=0; var lim=ids.length; nitems=nitems+lim;\n while (i<lim) {\n var idinfo=ids[i++];\n var frag=((typeof idinfo === 'string')?\n (idinfo):\n (idinfo[0]));\n var info=metaBook.docinfo[frag];\n // Pointer to non-existent node. Warn here?\n if (!(info)) {\n metaBook.missing_nodes.push(frag);\n continue;}\n if (typeof idinfo !== 'string') {\n // When the idinfo is an array, the first\n // element is the id itself and the remaining\n // elements are the text strings which are the\n // basis for the tag (we use this for\n // highlighting).\n var knodeterms=info.knodeterms, terms;\n var tagid=((knode)?(knode._qid||knode.getQID()):(tagterm));\n // If it's the regular case, we just assume that\n if (!(info.knodeterms)) {\n knodeterms=info.knodeterms={};\n knodeterms[tagid]=terms=[];}\n else if ((terms=knodeterms[tagid])) {}\n else knodeterms[tagid]=terms=[];\n var j=1; var jlim=idinfo.length;\n while (j<jlim) {terms.push(idinfo[j++]);}}\n occurrences.push(info);}\n addTags(occurrences,knode||taghead);}\n addClass(document.body,\"mbINDEXING\");\n fdjtAsync.slowmap(\n handleIndexEntry,alltags,\n {watchfn: ((alltags.length>100)&&(tracelevel>1)&&(indexProgress)),\n slice: 50,space: 5})\n .then(function(state){\n fdjtLog(\"Book index links %d keys to %d refs\",ntags,nitems);\n dropClass(document.body,\"mbINDEXING\");\n metaBook.tagmaxweight=maxweight;\n metaBook.tagminweight=minweight;\n if (whendone) return whendone();\n else return state;});}",
"function condWordFreq(seperatedList){ \n var newSeperatedList = seperatedList.split(\" \");\n var subsetKVP = condWordCount(seperatedList);\n var condWordFrequency = {};\n var keyInSubset = Object.values(subsetKVP)[0];\n var valuesToBeAdded = Object.values(Object.values(subsetKVP)[0]);\n var newLength = Object.values(Object.values(subsetKVP)[0]).length;\n var m = 0;\n var sumOfValuesTwo = 0;\n while(m < newLength ){ \n sumOfValuesTwo += valuesToBeAdded[m];\n m ++; \n } \n var p = 0;\n var percent = valuesToBeAdded[p]/valuesToBeAdded.length;\n var x = 0;\n var firstNewYeah = Object.keys(condWordCount)[0];\n while(x < Object.keys(subsetKVP).length){\n newKeys = Object.keys(subsetKVP)[x];\n condWordFrequency[newKeys] = percent;\n x ++; \n }\n return condWordFrequency;\n\n}",
"function merge_1(KB1, KB2) {\n let kbs = KB1\n for(let k in KB2) {\n kbs[k] = KB2[k]\n }\n return kbs\n }",
"function __init_2551() {\n\t/* eslint-disable no-invalid-this */\n\tvar topic;\n\tvar newz;\n\tvar len;\n\tvar wt;\n\tvar d;\n\tvar i;\n\n\tthis.z = new Array( this.D );\n\tfor ( d = 0; d < this.D; d++ ) {\n\t\tthis.z[ d ] = [];\n\t\tlen = this.w[ d ].length;\n\n\t\t// Initialize random topics...\n\t\tfor ( i = 0; i < len; i++ ) {\n\t\t\tnewz = _$floor_1932( _$randu_1777() * this.K );\n\t\t\tthis.z[ d ].push( newz );\n\t\t}\n\t\tthis.ndSum[ d ] = len;\n\t\tfor ( i = 0; i < len; i++ ) {\n\t\t\twt = this.w[ d ][ i ];\n\t\t\ttopic = this.z[ d ][ i ];\n\n\t\t\t// Number of instances of word i assigned to topic j:\n\t\t\tthis.nw.set( wt, topic, this.nw.get( wt, topic ) + 1 );\n\n\t\t\t// Number of words in document i assigned to topic j:\n\t\t\tthis.nd.set( d, topic, this.nd.get( d, topic ) + 1 );\n\n\t\t\t// Total number of words assigned to topic j:\n\t\t\tthis.nwSum[ topic ] = this.nwSum[ topic ] + 1;\n\t\t}\n\t}\n} // end FUNCTION init()",
"function\n updateWordCounts( documentObject, documentText ){\n if ( documentObject.wordToCount ){ return false; }\n\n recomputeInvDocFreq = true;\n var documentWordArray = tokenize( documentText );\n\n // Collect document map[ word -> count ]\n var documentWordToCount = {};\n for ( var w = 0; w < documentWordArray.length; ++w ){\n var word = documentWordArray[w];\n if ( word in STOP_WORDS ){ continue; }\n incrementMapValue( documentWordToCount, word, 1 );\n }\n\n // Store documentWordToCount in documentObject\n documentObject.wordToCount = documentWordToCount;\n return true;\n }",
"function deriveK(scoreArr, lastReintro) {\n var score = scoreArr.reduce(function (sum, char) {\n return sum + char / (scoreArr.length * 2);\n }, 0);\n if (score > 0.9) {\n score = 0.9;\n } else if (score === 0) {\n score = 1 / (scoreArr.length * 2);\n }\n return Math.abs(Math.log(score) / ((Date.now() - lastReintro) / 1000));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Welcome. In this kata, you are asked to square every digit of a number. For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. Note: The function accepts an integer and returns an integer | function squareDigits(num){
//may the code be with you
var newnum=num.toString()
var square = ""
for (i=0;i<newnum.length;i++){
square += newnum[i] ** 2
}
return parseInt(square)
} | [
"function squareDigits(num){\n //may the code be with you\n const numArray = num.toString().split('')\n const result = [];\n for (let index of numArray) {\n result.push(index * index);\n }\n return (parseInt(result.join('')));\n}",
"function squareDigits(num) {\r\n let result = '';\r\n num = num.toString();\r\n //may the code be with you\r\n for (let i = 0; i < num.length; i++) {\r\n result += Number(num.charAt(i)) ** 2;\r\n }\r\n return Number(result);\r\n}",
"function squareEveryDigit(number) {\n let sn = \"\"; // o(1)\n number = number.toString(); // o(n)\n for (let i = 0; i < number.length; i++) {\n let digit = number[i]; // o(1)\n digit = Math.pow(digit,2); // o(1)\n sn += digit; // o(1)\n }// // o(n)\n console.log(parseInt(sn)); //o(n)\n}",
"function squareDigits(num) {\n let stringDigits = String(num).split(\"\");\n // console.log(stringDigits);\n \n return console.log(Number(stringDigits.map(numb => {\n numb = Number(numb);\n let square = numb * numb;\n let total = \"\";\n total+= square;\n return total;\n }).reduce((acc, value) => acc + value)));\n}",
"function squareDigits(n) {\n const arr = n.toString().split('');\n return arr.map(a => Math.pow(Number(a), 2)).join('');\n}",
"iteratedSquare(n) {\n // Good luck!\n while (n !== 1 && n !== 89) {\n let a = n.toString().split(\"\");\n if (a[1] == undefined) {\n n = a[0] ** 2;\n } else {\n n = a[0] ** 2 + a[1] ** 2;\n }\n }\n return n;\n }",
"function iteratedSquare(n) {\n\n let sumSquaredDigits;\n\n while (n !== 1 && n !== 89) {\n sumSquaredDigits = 0;\n while (n > 0) {\n sumSquaredDigits += (n % 10) ** 2;\n n = (n / 10) >> 0;\n }\n n = sumSquaredDigits;\n }\n\n return n;\n}",
"function iteratedSquare(n) {\n while (true) {\n if (n === 1 || n === 89) {\n break;\n }\n n = n\n .toString()\n .split(\"\")\n .reduce((prev, curr) => {\n return +prev + (+curr) ** 2;\n }, 0);\n }\n return n;\n}",
"function squareDigitsSequence(a0) {\n let mul = a0;\n let arr = [];\n let count = 1;\n do {\n arr.push(mul);\n let nums = mul\n .toString()\n .split(\"\")\n .map(el => +el);\n mul = nums.reduce((a, b) => a + Math.pow(b, 2), 0);\n count++;\n } while (!arr.includes(mul));\n return count;\n}",
"function square(num){\n return num * num\n }",
"function digitSquareSum(num) {\n let sum = 0;\n while (num) {\n sum += (num % 10) * (num % 10);\n num = Math.floor(num / 10);\n }\n return sum;\n }",
"function squareDigitsSequence(a0) { //No native methods challenge\n let current = a0, sequence = [a0], sum = 0, keepGoin = true;\n while (keepGoin) {\n for (let i = 0, curStr = '' + current; i < curStr.length; i++)\n sum += curStr[i] ** 2;\n for (let i in sequence)\n if (sum === sequence[i])\n keepGoin = false;\n sequence[sequence.length] = sum;\n current = sum;\n sum = 0;\n }\n return sequence.length;\n}",
"function square(num) {\n return multiply(num, num);\n}",
"function numberSquares() {\n for (let i = 1; i < 101; i++) {\n console.log(Math.pow(i,2));\n }\n}",
"function squareRoot(number){\n return (21)\n}",
"function calculateSquare(num) {\r\n return num * num;\r\n }",
"function onesDigit(n){\n return n % 10;\n }",
"function isSquareNumber(number12) {}",
"function squareRootFunction1(n) {\n let i = 1;\n while (true) {\n if (i * i === n) {\n return i;\n }\n i++;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Excluir vinculo com o animal | function excluirAnimalMedico(animal, usuario, res){
console.log("Excluir animal");
console.log(animal);
console.log(usuario);
connection.acquire(function(err, con){
con.query("update MedicoAnimal set MedicoAnimal.status=2 where MedicoAnimal.Medico=? and MedicoAnimal.Animal=?",[usuario.idusuario, animal],function(err, result){
con.release();
if (err) {
res.send({status: 1, message: 'Failed to delete'});
} else {
res.send({status: 0, message: 'Deleted successfully'});
}
});
});
} | [
"removeAnimal() {\n\t\tthis.animal = null;\n\t}",
"function remove(animals, name){\n \n \n for(var i = 0; i< animals.length; i++){\n//Check if name exist in animals array \n if(name === animals[i].name){\n//if name exist remove it \n animals.splice(i, 1);\n }\n }\n \n}",
"function deleteAnimal(pId, pListAnimal) {\n\n //borrar del array\n //busco la posicion del elemento cuyo id es el que pasan por parametro\n\n let posicionBorrar = pListAnimal.findIndex(animal => {\n return animal.id == pId;\n })\n\n pListAnimal.splice(posicionBorrar, 1)\n console.log(animales);\n\n //borrar del interfaz\n let elementoDomBorrar = document.querySelector('#item' + pId);\n elementoDomBorrar.parentNode.removeChild(elementoDomBorrar);\n\n}",
"_removeInsect(insect){\n if(insect instanceof Bee){\n var index = this._bees.indexOf(insect);\n if(index >= 0){\n this._bees.splice(index,1);\n }\n } else {\n if (insect.contained !== undefined) { // replaces container ant with the contained ant\n this._ant = insect.contained; \n } else {\n this._ant = undefined;\n }\n }\n }",
"function removeExistingBananas() {\n let existingBananas = document.querySelectorAll(\".pbjellify-image\");\n for (let pbjt of existingBananas) {\n pbjt.remove();\n }\n }",
"function remove(animals, name){\n //var loweranimals = animals.map(names => names.toLowerCase());\n //console.log(\"lowercase\" + animals);\n for (var i = 0; i < animals.length; i++ ){\n if( animals[i].name.toLowerCase() === name.toLowerCase() )\n {\n console.log('before splice ' + animals);\n animals.splice(i);\n console.log('after splice ' + animals);\n }\n }\n}",
"die() {\r\n creatures.splice(this.creatureId);\r\n super.remove();\r\n }",
"removeAnimalFromBoard(animal, x, y) {\n\t\tvar square = this.board[x][y];\n\t\t// If square has pet then make square empty after animal passes through\n\t\t// Check that the calling object is a pet\n\t\tif (square.hasPet() && animal instanceof Pet) {\n\t\t\tthis.removeSquareFromBoard(x, y);\n\t\t}\n\t\t// If square has person then remove from square and leave the square as is\n\t\t// Check that the calling object is a person\n\t\telse if (square.hasPerson() && animal instanceof Person) {\n\t\t\tsquare.removeAnimal();\n\t\t\tupdateSquareHTML(square, x, y);\n\t\t}\n\t\t\n\t}",
"function remove(animals, name) {\n// declare a for loop that loops through the indices of the animals array\n for (let i = 0; i < animals.length - 1; i++) {\n//declare a conditional that checks if the name parameter is in the array\n if (animals[i][\"name\"] === name) {\n//if true remove the name object from the array\n animals.splice(animals[i], 1);\n }\n }\n}",
"function remove(animals, name){\n// use for loop to look through array to see if name matches a name in the animals array of objects \n for(var i = 0; i < animals.length; i++){\n if(name === animals[i].name){\n// use .splice to then delete that item if found \n animals.splice(i,1);\n }\n }\n}",
"function removeDog(eachDog) {\n dataModelDogs.splice(dataModelDogs.indexOf(eachDog), 1);\n renderDogList();\n}",
"function remove(animals, name){\n // create a for loop to look through the array of animals \n for (let i = 0; i < animals.length; i++){\n //check if animal name using strick comparison is in the animals index\n if(name === animals[i].name){\n \n return animals.shift(i,1);\n }\n \n}\n}",
"function delete_animal(id){\n const key = datastore.key([ANIM, parseInt(id,10)]);\n return datastore.delete(key);\n}",
"function remove(animals, name) {\n //loop over animal array\n for (var i = 0; i < animals.length; i++) {\n //if name in animals array matches name\n if (animals[i].name === name) {\n //remove the animal from animals array using splice\n return animals.splice(name, 1);\n }\n } \n}",
"async removeAnimal(context, payload) {\n await deleteDocument(payload)\n\n context.commit('deleteDocument', payload)\n\n }",
"removeFromPlage(){\n var newPlages = []\n for (var plage of SemaineLogic.jours[this.njour].plages ) {\n if ( this.owner.id === plage.travail.id ) continue ;\n newPlages.push(plage)\n }\n SemaineLogic.jours[this.njour].plages = newPlages ;\n }",
"function excluir() {\n for (var i = 0; i < resExclusiones.length; i++) {\n const search = resultado.findIndex(\n (indice) => indice.palabra === resExclusiones[i]\n )\n if (search != -1) resultado.splice(search, 1)\n }\n}",
"function removeButtons() {\n $(\".animal\").remove();\n }",
"function removeExistingMoods() {\n let existingMoods = document.querySelectorAll(\".moodify-image\");\n for (let mood of existingMoods) {\n mood.remove();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper function for generating the CodeTree for the given tree | function getCodeTree(originalTree, type, sourceFile, appId) {
return new CodeTree(originalTree, type, sourceFile, appId);
} | [
"function CodeTree(originalTree, type, sourceFile, appId) {\n if (type == \"ast\") {\n this.tree = transformAstToCodeTree(originalTree, sourceFile, appId);\n }\n else if (type == \"dom\") {\n this.tree = transformDomToCodeTree(originalTree, sourceFile, appId);\n }\n }",
"function ToolGenerator(){\n\t\t\tvar ast = this.Structure;\n\n\t\t\tvar ret = ''\n\t\t\tfor( var type in ast ){\n\t\t\t\tvar tag = ast[ type ]\n\t\t\t\tvar walk = '\\tn.parent = p\\nif(this.Pre)this.Pre(n)\\n'\n\n\t\t\t\tvar copy = '\\tc.type = n.type\\n'+\n\t\t\t\t\t\t\t'\\tif(n.store) c.store = n.store\\n'+\n\t\t\t\t\t\t\t'\\tif(n.parens) c.parens = n.parens\\n'+\n\t\t\t\t\t\t\t'\\tif(n.comments) c.comments = n.comments\\n'+\n\t\t\t\t\t\t\t'\\tc.start = n.start\\n'+\n\t\t\t\t\t\t\t'\\tc.end = n.end\\n'\n\n\t\t\t\tvar clone = '\\tvar c = Object.create(this.AST)\\n'+\n\t\t\t\t\t\t\t'\\tc.type = n.type\\n'+\n\t\t\t\t\t\t\t'\\tif(n.store) c.store = n.store\\n'+\n\t\t\t\t\t\t\t'\\tif(n.parens) c.parens = n.parens\\n'+\n\t\t\t\t\t\t\t'\\tif(n.comments) c.comments = n.comments\\n'+\n\t\t\t\t\t\t\t'\\tc.start = n.start\\n'+\n\t\t\t\t\t\t\t'\\tc.end = n.end\\n'\n\t\t\t\tvar v = 0\n\t\t\t\tfor( var k in tag ){\n\t\t\t\t\tvar t = tag[ k ]\n\t\t\t\t\t\n\t\t\t\t\tcopy += '\\tvar _'+v+'=n.'+k+';if(_'+v+' !== undefined)c.'+k+'=_'+v+'\\n'\n\n\t\t\t\t\tif( t === 0){\n\t\t\t\t\t\tclone += '\\tvar _'+v+' = n.'+k+'\\n\\tif(_'+v+' !== undefined)c.'+k+'=_'+v+'\\n'\n\t\t\t\t\t} \n\t\t\t\t\telse if( t === 1){\n\t\t\t\t\t\tclone += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t'\\tif(_'+v+') c.'+k+' = this[_'+v+'.type](_'+v+')\\n'\n\n\t\t\t\t\t\twalk += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t'\\tif(_'+v+' && this[_'+v+'.type](_'+v+', n)) return 1\\n'\n\n\t\t\t\t\t} \n\t\t\t\t\telse if(t === 2){\n\t\t\t\t\t\tclone += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t'\\tif(_'+v+'){\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tvar x, y = []\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tfor(var len = _'+v+'.length, i = 0; i < len; i++){\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tx = _'+v+'[i]\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tif(x) y[i] = this[x.type](x)\\n'+\n\t\t\t\t\t\t\t\t'\\t\\t}\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tc.'+k+' = y\\n'+\n\t\t\t\t\t\t\t'\\t}\\n'\n\n\t\t\t\t\t\twalk += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t'\\tif(_'+v+'){\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tvar x\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tfor(var len = _'+v+'.length, i = 0; i < len; i++){\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tx = _'+v+'[i]\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tif(x && this[x.type](x, n)) return 1\\n'+\n\t\t\t\t\t\t\t\t'\\t\\t}\\n'+\n\t\t\t\t\t\t\t'\\t}\\n'\n\n\t\t\t\t\t}\n\t\t\t\t\telse if(t === 3){\n\t\t\t\t\t\tclone += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t\t'\\tif(_'+v+'){\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tvar x, y = []\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tfor(var len = _'+v+'.length,i = 0; i < len; i++){\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tx = _'+v+'[i], y[i] = {key:this[x.key.type](x.key)}\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tif(x.value) y[i].value = this[x.value.type](x.value)\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\telse y[i].short = x.short\\n'+\n\t\t\t\t\t\t\t\t'\\t\\t}\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tc.'+k+'=y\\n'+\n\t\t\t\t\t\t\t'\\t}\\n'\n\n\t\t\t\t\t\twalk += '\\tvar _'+v+' = n.'+k+'\\n'+\n\t\t\t\t\t\t\t\t'\\tif(_'+v+'){\\n'+\n\t\t\t\t\t\t\t\t'\\t\\tfor(var len = _'+v+'.length,i = 0; i < len; i++){\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tvar x = _'+v+'[i]\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tif(this[x.key.type](x.key, n)) return 1\\n'+\n\t\t\t\t\t\t\t\t\t'\\t\\t\\tif(x.value && this[x.value.type](x.value, n)) return 1\\n'+\n\t\t\t\t\t\t\t\t'\\t\\t}\\n'+\n\t\t\t\t\t\t\t'\\t}\\n'\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tv++\n\t\t\t\t}\n\t\t\t\tret += '\\n_walk.'+type+'=function(n, p){\\n' + walk + '\\n\\tif(this.Post && this.Post(n))return 1\\n}\\n' \n\t\t\t\tret += '\\n_clone.'+type+'=function(n){\\n' + clone + '\\treturn c\\n}\\n' \n\t\t\t\tret += '\\n_copy.'+type+'=function(n, c){\\n'+ copy +'\\treturn\\n}\\n'\n\t\t\t}\n\t\t\t(new Function('_clone', '_copy', '_walk', ret))( this.Clone, this.Copy, this.Walk )\n\n\t\t\tthis.Clone.AST = this\n\t\t\tthis.Clone.Unary = function( n ){\n\t\t\t\tvar c = Object.create( this.AST )\n\t\t\t\tc.start = n.start\n\t\t\t\tc.end = n.end\n\t\t\t\tc.type = n.type\n\t\t\t\tc.prefix = n.prefix\n\t\t\t\tif(n.parens)c.parens = n.parens\n\t\t\t\tif(n.comments)c.comments = n.comments\n\t\t\t\tc.op = n.op\n\t\t\t\tif( n.prefix && n.op == '%'){\n\t\t\t\t\tif(n.arg.type !== 'Id') throw new Error('Unknown template & argument type')\n\t\t\t\t\tif( this.template ) this.template.push( c )\n\t\t\t\t}\n\t\t\t\tc.arg = this[n.arg.type]( n.arg )\n\t\t\t\treturn c\n\t\t\t}\n\t\t}",
"function buildCodeTable (root = {}) {\n let codeTable = {};\n dfs(root, \"\");\n function dfs (node, code) {\n if (node.leftChild === null && node.rightChild === null) {\n codeTable[node.value] = code;\n return;\n }\n\n if (node.leftChild !== null) dfs(node.leftChild, code + \"0\");\n if (node.rightChild !== null) dfs(node.rightChild, code + \"1\");\n }\n return codeTable;\n}",
"function transformAstToCodeTree(ast, sourceFile, appId) {\n var stack = [ ast ], i, j, key, len, node, child, subchild;\n \n //Create a CodeTreeNode for the root\n var newCodeTreeNode = new CodeTreeNode(\"ast\", ast.type, null, sourceFile, appId);\n if (ast.loc != undefined) {\n newCodeTreeNode.addLoc(ast.loc.start.line, ast.loc.start.column);\n }\n ast.codetreeref = newCodeTreeNode;\n\n //Now, walk through all the nodes\n for (i = 0; i < stack.length; i++) {\n node = stack[i];\n\n for (key in node) {\n if (key !== \"codetreeref\") {\n child = node[key];\n\n if (child instanceof Array) {\n for (j = 0, len = child.length; j < len; j += 1) {\n subchild = child[j];\n addChildNode(subchild, node, sourceFile, appId);\n stack.push(subchild);\n }\n } else if (child != void 0 && typeof child.type === 'string') {\n addChildNode(child, node, sourceFile, appId); \n stack.push(child);\n }\n \n //The above considers identifiers and literals as nodes in the CodeTree as well. These must \n //be added as the child of an Identifier or a Literal node. Also, the \"Literal\" label \n //should be changed based on the 'value' property. If it's a number literal, it should be \n //changed to \"NumberLiteral\". If it's a string literal, it should be changed to \n //\"StringLiteral\". We should also look at the \"operator\" property of a BinaryExpression, \n //UpdateExpression, or UnaryExpression, if any. For UpdateExpression and UnaryExpression, \n //we should also look at the prefix value (i.e., true or false), which indicates whether \n //the operator is before or after.\n }\n }\n }\n \n return ast.codetreeref;\n }",
"compileTree(tree, buffer, parentPointer, referenceVariable, outVariable) {\n Object.keys(tree).forEach((field) => {\n this.compileNode(field, tree[field], buffer, parentPointer, referenceVariable, outVariable);\n });\n }",
"_createInternalSyntaxTree(node)\n {\n if (!node)\n return null;\n\n var result = null;\n switch (node.type) {\n case \"ArrayExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ArrayExpression,\n elements: node.elements.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ArrayPattern\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ArrayPattern,\n elements: node.elements.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ArrowFunctionExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression,\n id: this._createInternalSyntaxTree(node.id),\n params: node.params.map(this._createInternalSyntaxTree, this),\n body: this._createInternalSyntaxTree(node.body),\n generator: node.generator,\n expression: node.expression, // Boolean indicating if the body a single expression or a block statement.\n async: node.async,\n typeProfilingReturnDivot: node.range[0]\n };\n break;\n case \"AssignmentExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.AssignmentExpression,\n operator: node.operator,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right)\n };\n break;\n case \"AssignmentPattern\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.AssignmentPattern,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right),\n };\n break;\n case \"AwaitExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.AwaitExpression,\n argument: this._createInternalSyntaxTree(node.argument),\n };\n break;\n case \"BlockStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.BlockStatement,\n body: node.body.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"BinaryExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.BinaryExpression,\n operator: node.operator,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right)\n };\n break;\n case \"BreakStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.BreakStatement,\n label: this._createInternalSyntaxTree(node.label)\n };\n break;\n case \"CallExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.CallExpression,\n callee: this._createInternalSyntaxTree(node.callee),\n arguments: node.arguments.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"CatchClause\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.CatchClause,\n param: this._createInternalSyntaxTree(node.param),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"ClassBody\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ClassBody,\n body: node.body.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ClassDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ClassDeclaration,\n id: this._createInternalSyntaxTree(node.id),\n superClass: this._createInternalSyntaxTree(node.superClass),\n body: this._createInternalSyntaxTree(node.body),\n };\n break;\n case \"ClassExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ClassExpression,\n id: this._createInternalSyntaxTree(node.id),\n superClass: this._createInternalSyntaxTree(node.superClass),\n body: this._createInternalSyntaxTree(node.body),\n };\n break;\n case \"ConditionalExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ConditionalExpression,\n test: this._createInternalSyntaxTree(node.test),\n consequent: this._createInternalSyntaxTree(node.consequent),\n alternate: this._createInternalSyntaxTree(node.alternate)\n };\n break;\n case \"ContinueStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ContinueStatement,\n label: this._createInternalSyntaxTree(node.label)\n };\n break;\n case \"DoWhileStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.DoWhileStatement,\n body: this._createInternalSyntaxTree(node.body),\n test: this._createInternalSyntaxTree(node.test)\n };\n break;\n case \"DebuggerStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.DebuggerStatement\n };\n break;\n case \"EmptyStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.EmptyStatement\n };\n break;\n case \"ExpressionStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ExpressionStatement,\n expression: this._createInternalSyntaxTree(node.expression)\n };\n break;\n case \"ForStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ForStatement,\n init: this._createInternalSyntaxTree(node.init),\n test: this._createInternalSyntaxTree(node.test),\n update: this._createInternalSyntaxTree(node.update),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"ForInStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ForInStatement,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"ForOfStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ForOfStatement,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right),\n body: this._createInternalSyntaxTree(node.body),\n await: node.await\n };\n break;\n case \"FunctionDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.FunctionDeclaration,\n id: this._createInternalSyntaxTree(node.id),\n params: node.params.map(this._createInternalSyntaxTree, this),\n body: this._createInternalSyntaxTree(node.body),\n generator: node.generator,\n async: node.async,\n typeProfilingReturnDivot: node.range[0]\n };\n break;\n case \"FunctionExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.FunctionExpression,\n id: this._createInternalSyntaxTree(node.id),\n params: node.params.map(this._createInternalSyntaxTree, this),\n body: this._createInternalSyntaxTree(node.body),\n generator: node.generator,\n async: node.async,\n typeProfilingReturnDivot: node.range[0] // This may be overridden in the Property AST node.\n };\n break;\n case \"Identifier\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Identifier,\n name: node.name\n };\n break;\n case \"IfStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.IfStatement,\n test: this._createInternalSyntaxTree(node.test),\n consequent: this._createInternalSyntaxTree(node.consequent),\n alternate: this._createInternalSyntaxTree(node.alternate)\n };\n break;\n case \"Literal\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Literal,\n value: node.value,\n raw: node.raw\n };\n break;\n case \"LabeledStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.LabeledStatement,\n label: this._createInternalSyntaxTree(node.label),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"LogicalExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.LogicalExpression,\n left: this._createInternalSyntaxTree(node.left),\n right: this._createInternalSyntaxTree(node.right),\n operator: node.operator\n };\n break;\n case \"MemberExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.MemberExpression,\n object: this._createInternalSyntaxTree(node.object),\n property: this._createInternalSyntaxTree(node.property),\n computed: node.computed\n };\n break;\n case \"MetaProperty\":\n // i.e: new.target produces {meta: \"new\", property: \"target\"}\n result = {\n type: WI.ScriptSyntaxTree.NodeType.MetaProperty,\n meta: this._createInternalSyntaxTree(node.meta),\n property: this._createInternalSyntaxTree(node.property),\n };\n break;\n case \"MethodDefinition\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.MethodDefinition,\n key: this._createInternalSyntaxTree(node.key),\n value: this._createInternalSyntaxTree(node.value),\n computed: node.computed,\n kind: node.kind,\n static: node.static\n };\n result.value.typeProfilingReturnDivot = node.range[0]; // \"g\" in \"get\" or \"s\" in \"set\" or \"[\" in \"['computed']\" or \"m\" in \"methodName\".\n break;\n case \"NewExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.NewExpression,\n callee: this._createInternalSyntaxTree(node.callee),\n arguments: node.arguments.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ObjectExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ObjectExpression,\n properties: node.properties.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ObjectPattern\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ObjectPattern,\n properties: node.properties.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"Program\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Program,\n sourceType: node.sourceType,\n body: node.body.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"Property\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Property,\n key: this._createInternalSyntaxTree(node.key),\n value: this._createInternalSyntaxTree(node.value),\n kind: node.kind,\n method: node.method,\n computed: node.computed\n };\n if (result.kind === \"get\" || result.kind === \"set\" || result.method)\n result.value.typeProfilingReturnDivot = node.range[0]; // \"g\" in \"get\" or \"s\" in \"set\" or \"[\" in \"['computed']\" method or \"m\" in \"methodName\".\n break;\n case \"RestElement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.RestElement,\n argument: this._createInternalSyntaxTree(node.argument)\n };\n break;\n case \"ReturnStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ReturnStatement,\n argument: this._createInternalSyntaxTree(node.argument)\n };\n break;\n case \"SequenceExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.SequenceExpression,\n expressions: node.expressions.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"SpreadElement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.SpreadElement,\n argument: this._createInternalSyntaxTree(node.argument),\n };\n break;\n case \"Super\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Super\n };\n break;\n case \"SwitchStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.SwitchStatement,\n discriminant: this._createInternalSyntaxTree(node.discriminant),\n cases: node.cases.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"SwitchCase\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.SwitchCase,\n test: this._createInternalSyntaxTree(node.test),\n consequent: node.consequent.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"TaggedTemplateExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.TaggedTemplateExpression,\n tag: this._createInternalSyntaxTree(node.tag),\n quasi: this._createInternalSyntaxTree(node.quasi)\n };\n break;\n case \"TemplateElement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.TemplateElement,\n value: node.value,\n tail: node.tail\n };\n break;\n case \"TemplateLiteral\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.TemplateLiteral,\n quasis: node.quasis.map(this._createInternalSyntaxTree, this),\n expressions: node.expressions.map(this._createInternalSyntaxTree, this)\n };\n break;\n case \"ThisExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ThisExpression\n };\n break;\n case \"ThrowStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ThrowStatement,\n argument: this._createInternalSyntaxTree(node.argument)\n };\n break;\n case \"TryStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.TryStatement,\n block: this._createInternalSyntaxTree(node.block),\n handler: this._createInternalSyntaxTree(node.handler),\n finalizer: this._createInternalSyntaxTree(node.finalizer)\n };\n break;\n case \"UnaryExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.UnaryExpression,\n operator: node.operator,\n argument: this._createInternalSyntaxTree(node.argument)\n };\n break;\n case \"UpdateExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.UpdateExpression,\n operator: node.operator,\n prefix: node.prefix,\n argument: this._createInternalSyntaxTree(node.argument)\n };\n break;\n case \"VariableDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.VariableDeclaration,\n declarations: node.declarations.map(this._createInternalSyntaxTree, this),\n kind: node.kind\n };\n break;\n case \"VariableDeclarator\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.VariableDeclarator,\n id: this._createInternalSyntaxTree(node.id),\n init: this._createInternalSyntaxTree(node.init)\n };\n break;\n case \"WhileStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.WhileStatement,\n test: this._createInternalSyntaxTree(node.test),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"WithStatement\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.WithStatement,\n object: this._createInternalSyntaxTree(node.object),\n body: this._createInternalSyntaxTree(node.body)\n };\n break;\n case \"YieldExpression\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.YieldExpression,\n argument: this._createInternalSyntaxTree(node.argument),\n delegate: node.delegate\n };\n break;\n\n // Modules.\n\n case \"ExportAllDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ExportAllDeclaration,\n source: this._createInternalSyntaxTree(node.source),\n };\n break;\n case \"ExportNamedDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ExportNamedDeclaration,\n declaration: this._createInternalSyntaxTree(node.declaration),\n specifiers: node.specifiers.map(this._createInternalSyntaxTree, this),\n source: this._createInternalSyntaxTree(node.source),\n };\n break;\n case \"ExportDefaultDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ExportDefaultDeclaration,\n declaration: this._createInternalSyntaxTree(node.declaration),\n };\n break;\n case \"ExportSpecifier\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ExportSpecifier,\n local: this._createInternalSyntaxTree(node.local),\n exported: this._createInternalSyntaxTree(node.exported),\n };\n break;\n case \"Import\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.Import,\n };\n break;\n case \"ImportDeclaration\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ImportDeclaration,\n specifiers: node.specifiers.map(this._createInternalSyntaxTree, this),\n source: this._createInternalSyntaxTree(node.source),\n };\n break;\n case \"ImportDefaultSpecifier\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ImportDefaultSpecifier,\n local: this._createInternalSyntaxTree(node.local),\n };\n break;\n case \"ImportNamespaceSpecifier\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ImportNamespaceSpecifier,\n local: this._createInternalSyntaxTree(node.local),\n };\n break;\n case \"ImportSpecifier\":\n result = {\n type: WI.ScriptSyntaxTree.NodeType.ImportSpecifier,\n imported: this._createInternalSyntaxTree(node.imported),\n local: this._createInternalSyntaxTree(node.local),\n };\n break;\n\n default:\n console.error(\"Unsupported Syntax Tree Node: \" + node.type, node);\n return null;\n }\n\n let {start, end} = node.loc;\n result.startPosition = new WI.SourceCodePosition(start.line - 1, start.column);\n result.endPosition = new WI.SourceCodePosition(end.line - 1, end.column);\n\n result.range = node.range;\n // This is an object for which you can add fields to an AST node without worrying about polluting the syntax-related fields of the node.\n result.attachments = {};\n\n return result;\n }",
"function compile (tree) {\n var source = [\n \"var ret = [];\",\n compileArgumentList(tree),\n \"return ret;\"\n ];\n \n return new Function([\"args\", \"runt\"], source.join(\"\\n\"));\n }",
"function AST(){}",
"function build_function_tree(node) {\n\n var rootnode; // the root node of tree\n var funcnode_uid = 0; // unique id\n var currentFuncNode; // iterator\n\n function visit(astnode, parent) {\n\n var fnode;\n\n // every ast node has a type property\n if (!astnode || typeof astnode.type !== \"string\") {\n return;\n }\n\n if (astnode.type === \"Program\") {\n\n fnode = new FunctionNode(Compiler, funcnode_uid++, astnode, undefined);\n\n // reverse annotation for debug\n astnode.fnode = fnode;\n rootnode = fnode;\n currentFuncNode = fnode;\n }\n else if (astnode.type === \"FunctionDeclaration\"\n || astnode.type === \"FunctionExpression\") {\n\n fnode = new FunctionNode(Compiler, funcnode_uid++, astnode,\n currentFuncNode);\n\n // reverse annotation for debug\n astnode.fnode = fnode;\n currentFuncNode.children.push(fnode);\n currentFuncNode = fnode;\n }\n\n for ( var prop in astnode) {\n if (astnode.hasOwnProperty(prop)) {\n if (prop === \"__parent__\") {\n continue;\n }\n\n var child = astnode[prop];\n if (Array.isArray(child)) {\n for (var i = 0; i < child.length; i++) {\n visit(child[i], astnode);\n }\n }\n else {\n visit(child, astnode);\n }\n }\n }\n\n if (astnode.type === \"FunctionDeclaration\"\n || astnode.type === \"FunctionExpression\") {\n\n currentFuncNode = currentFuncNode.parent;\n }\n } // End of visit\n\n visit(node);\n\n return rootnode;\n}",
"function CodeTreeNode(_type, _label, _parent, _sourceFile, _appId) {\n this.type = _type;\n this.label = _label;\n this.parent = _parent;\n this.childNodes = [];\n this.shouldAbstractOut = false;\n this.lineNumber = null;\n this.columnNumber = null;\n this.sourceFile = _sourceFile;\n this.appId = _appId;\n }",
"function transformDomToCodeTree(dom, sourceFile, appId) {\n var domRoot = dom;\n var stack = [ domRoot ], i, j, key, len, node, child, subchild;\n \n //Create a CodeTreeNode for the root\n var newCodeTreeNode = new CodeTreeNode(\"dom\", \"DocumentNode\", null, sourceFile, appId);\n if (domRoot.loc != undefined) {\n newCodeTreeNode.addLoc(domRoot.loc.start.line, domRoot.loc.start.column);\n }\n domRoot.codetreeref = newCodeTreeNode;\n\n //Now, walk through all the nodes\n for (i = 0; i < stack.length; i++) {\n node = stack[i];\n \n //Find children of elements, or name and value of attribute, or value of text\n var type = node.nodeType;\n if (type == 1 || node === domRoot) { //Element, or Document node\n //Get all the children\n var children = node.childNodes;\n \n for (j = 0; j < children.length; j++) {\n var child = children[j];\n \n //What kind of node is it?\n var childType = child.nodeType;\n if (childType == 1) { //Element\n var newCodeTreeNode = new CodeTreeNode(\"dom\", child.tagName, node.codetreeref, \n sourceFile, appId);\n if (child.loc != undefined) {\n newCodeTreeNode.addLoc(child.loc.start.line, child.loc.start.column);\n }\n node.codetreeref.addChild(newCodeTreeNode);\n child.codetreeref = newCodeTreeNode;\n stack.push(child);\n }\n else if (childType == 3) { //Text\n if (child.nodeValue.trim() == \"\") continue; //Don't care if text node is empty\n var newCodeTreeNode = new CodeTreeNode(\"dom\", \"TextNode\", node.codetreeref, \n sourceFile, appId);\n if (child.loc != undefined) {\n newCodeTreeNode.addLoc(child.loc.start.line, child.loc.start.column);\n }\n node.codetreeref.addChild(newCodeTreeNode);\n child.codetreeref = newCodeTreeNode;\n stack.push(child);\n }\n }\n \n //Get attributes too\n if (type == 1) {\n var attrs = node.attributes;\n for (j = 0; j < attrs.length; j++) {\n var attr = attrs[j];\n var newCodeTreeNode = new CodeTreeNode(\"dom\", \"AttributeNode\", \n node.codetreeref, sourceFile, appId);\n if (attr.loc != undefined) {\n newCodeTreeNode.addLoc(attr.loc.start.line, attr.loc.start.column);\n }\n node.codetreeref.addChild(newCodeTreeNode);\n attr.codetreeref = newCodeTreeNode;\n stack.push(attr);\n }\n }\n }\n else if (type == 2) { //Attr\n //Add the attribute name and value (no need to push to the stack)\n var newCodeTreeNode = new CodeTreeNode(\"dom\", node.nodeName, node.codetreeref, \n sourceFile, appId);\n if (node.loc != undefined) {\n newCodeTreeNode.addLoc(node.loc.start.line, node.loc.start.column);\n }\n node.codetreeref.addChild(newCodeTreeNode);\n \n //For the value, determine whether it's a NumberLiteral, BooleanLiteral, or, by default,\n //a StringLiteral\n var val = node.nodeValue, valType = \"StringLiteral\";\n if (!isNaN(val)) {\n valType = \"NumberLiteral\";\n }\n else if (val == \"true\" || val == \"false\") {\n valType = \"BooleanLiteral\";\n }\n var typeNode = new CodeTreeNode(\"dom\", valType, node.codetreeref, sourceFile, appId);\n typeNode.abstractOut();\n if (node.loc != undefined) {\n typeNode.addLoc(node.loc.start.line, node.loc.start.column);\n }\n node.codetreeref.addChild(typeNode);\n newCodeTreeNode = new CodeTreeNode(\"dom\", node.nodeValue, typeNode, sourceFile, appId);\n newCodeTreeNode.abstractOut();\n if (node.loc != undefined) {\n newCodeTreeNode.addLoc(node.loc.start.line, node.loc.start.column);\n }\n typeNode.addChild(newCodeTreeNode);\n }\n else if (type == 3) { //Text\n newCodeTreeNode = new CodeTreeNode(\"dom\", node.nodeValue, node.codetreeref, sourceFile, appId);\n if (node.loc != undefined) {\n newCodeTreeNode.addLoc(node.loc.start.line, node.loc.start.column);\n }\n node.codetreeref.addChild(newCodeTreeNode);\n }\n }\n \n return domRoot.codetreeref;\n }",
"function buildTree() {\n var treeStuff = validateInputs();\n tree(treeStuff) }",
"function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1);\n /* next code value for each bit length */\n\n var code = 0;\n /* running code value */\n\n var bits;\n /* bit index */\n\n var n;\n /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n\n for (n = 0; n <= max_code; n++) {\n var len = tree[n * 2 + 1]\n /*.Len*/\n ;\n\n if (len === 0) {\n continue;\n }\n /* Now reverse the bits */\n\n\n tree[n * 2]\n /*.Code*/\n = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n}",
"function gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n for (n = 0; n <= max_code; n++) {\n const len = tree[n * 2 + 1]/*.Len*/;\n if (len === 0) {\n continue; \n }\n /* Now reverse the bits */\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n}",
"function ParseTreeTransformer() {}",
"function generateFlatTree(){\n var parser = Sk.executionReports['parser'];\n //Tree's already been built, don't do anything else\n if(flatTree.length > 0){\n return;\n }\n var ast;\n if (parser.success) {\n ast = parser.ast;\n } else {\n var filename = \"__main__\"\n var parse = Sk.parse(filename,\"\");\n ast = Sk.astFromParse(parse.cst, filename, parse.flags);\n }\n var visitor = new NodeVisitor();\n visitor.visit = function(node){\n flatTree.push(node);\n /** Visit a node. **/\n var method_name = 'visit_' + node._astname;\n //console.log(flatTree.length - 1 + \": \" + node._astname)\n if (method_name in this) {\n return this[method_name](node);\n } else {\n return this.generic_visit(node);\n }\n }\n visitor.visit(ast);\n //console.log(flatTree);\n }",
"function gen_codes(tree, max_code, bl_count)\r\n// ct_data *tree; /* the tree to decorate */\r\n// int max_code; /* largest code with non zero frequency */\r\n// ushf *bl_count; /* number of codes at each bit length */\r\n{\r\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\r\n var code = 0; /* running code value */\r\n var bits; /* bit index */\r\n var n; /* code index */\r\n\r\n /* The distribution counts are first used to generate the code values\r\n * without bit reversal.\r\n */\r\n for (bits = 1; bits <= MAX_BITS; bits++) {\r\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\r\n }\r\n /* Check that the bit counts in bl_count are consistent. The last code\r\n * must be all ones.\r\n */\r\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\r\n // \"inconsistent bit counts\");\r\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\r\n\r\n for (n = 0; n <= max_code; n++) {\r\n var len = tree[n * 2 + 1]/*.Len*/;\r\n if (len === 0) { continue; }\r\n /* Now reverse the bits */\r\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\r\n\r\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\r\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\r\n }\r\n}",
"function renderCodeTree(codeData, height, width, visit_id) {\n // Set the dimensions and margins of the diagram\n\n var svg = d3.select(\"#code-tree-vis\" + visit_id).append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .append(\"g\")\n .attr(\"transform\", \"translate(\"\n + 0 + \",\" + 0 + \")\");\n\n var i = 0,\n duration = 500,\n root;\n\n // declares a tree layout and assigns the size\n var treemap = d3.tree().size([height, width]);\n\n // Assigns parent, children, height, depth\n root = d3.hierarchy(codeData, function (d) {\n return d.children;\n });\n root.x0 = height / 2;\n root.y0 = 0;\n\n // Collapse after the second level\n root.children.forEach(collapse);\n\n update(root);\n\n // Collapse the node and all it's children\n function collapse(d) {\n if (d.children) {\n d._children = d.children\n d._children.forEach(collapse)\n d.children = null\n }\n }\n\n function update(source) {\n\n // Assigns the x and y position for the nodes\n var treeData = treemap(root);\n\n // Compute the new tree layout.\n var nodes = treeData.descendants(),\n links = treeData.descendants().slice(1);\n\n // Normalize for fixed-depth.\n nodes.forEach(function (d) {\n d.y = d.depth * 140\n });\n\n // ****************** Nodes section ***************************\n\n // Update the nodes...\n var node = svg.selectAll('g.node')\n .data(nodes, function (d) {\n return d.id || (d.id = ++i);\n });\n\n // Enter any new modes at the parent's previous position.\n var nodeEnter = node.enter().append('g')\n .attr('class', 'node')\n .attr(\"transform\", function (d) {\n return \"translate(\" + source.y0 + \",\" + source.x0 + \")\";\n })\n .on('click', click);\n\n // Add Circle for the nodes\n nodeEnter.append('circle')\n .attr('class', 'node')\n .attr('r', 3)\n .style(\"fill\", function (d) {\n return d._children ? \"#fff\" : \"#999\";\n });\n\n // Add labels for the nodes\n nodeEnter.append('text')\n .attr(\"dy\", \".35em\")\n .style(\"font\", \"10px sans-serif\")\n .attr(\"x\", function (d) {\n return d.children || d._children ? -13 : 13;\n })\n .attr(\"text-anchor\", function (d) {\n return d.children || d._children ? \"end\" : \"start\";\n })\n .text(d => {\n return d.children ? '' : ptTestData[2][d.data.name] + \"\\xa0\\xa0\\xa0\" + \"code cont:\" +\n parseFloat(d.data.cont).toFixed(2) +\n \"\\xa0\\xa0\\xa0\\xa0\\xa0\\xa0\" + 'kg cont:' + parseFloat(d.data.kg_cont).toFixed(2);\n });\n\n // UPDATE\n var nodeUpdate = nodeEnter.merge(node);\n\n // Transition to the proper position for the node\n nodeUpdate.transition()\n .duration(duration)\n .attr(\"transform\", function (d) {\n return \"translate(\" + d.y + \",\" + d.x + \")\";\n });\n\n // Update the node attributes and style\n nodeUpdate.select('circle.node')\n .attr('r', 3)\n .style(\"fill\", function (d) {\n return d.children ? \"#fff\" : \"#999\";\n })\n .attr('cursor', 'pointer');\n\n\n // Remove any exiting nodes\n var nodeExit = node.exit().transition()\n .duration(duration)\n .attr(\"transform\", function (d) {\n return \"translate(\" + source.y + \",\" + source.x + \")\";\n })\n .remove();\n\n // On exit reduce the node circles size to 0\n nodeExit.select('circle')\n .attr('r', 3);\n\n // On exit reduce the opacity of text labels\n nodeExit.select('text')\n .style('fill-opacity', 1e6);\n\n // ****************** links section ***************************\n\n // Update the links...\n var link = svg.selectAll('path.link')\n .data(links, function (d) {\n return d.id;\n });\n\n // Enter any new links at the parent's previous position.\n var linkEnter = link.enter().insert('path', \"g\")\n .attr(\"class\", \"link\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"#555\")\n .attr(\"stroke-opacity\", 0.4)\n .attr(\"stroke-width\", 1.5)\n .attr('d', function (d) {\n var o = {x: source.x0, y: source.y0}\n return diagonal(o, o)\n });\n\n // UPDATE\n var linkUpdate = linkEnter.merge(link);\n\n // Transition back to the parent element position\n linkUpdate.transition()\n .duration(duration)\n .attr('d', function (d) {\n return diagonal(d, d.parent)\n });\n\n // Remove any exiting links\n var linkExit = link.exit().transition()\n .duration(duration)\n .attr('d', function (d) {\n var o = {x: source.x, y: source.y}\n return diagonal(o, o)\n })\n .remove();\n\n // Store the old positions for transition.\n nodes.forEach(function (d) {\n d.x0 = d.x;\n d.y0 = d.y;\n });\n\n // Creates a curved (diagonal) path from parent to the child nodes\n function diagonal(s, d) {\n\n path = `M ${s.y} ${s.x}\n C ${(s.y + d.y) / 2} ${s.x},\n ${(s.y + d.y) / 2} ${d.x},\n ${d.y} ${d.x}`\n\n return path\n }\n\n // Toggle children on click.\n function click(d) {\n if (d.children) {\n d._children = d.children;\n d.children = null;\n } else {\n d.children = d._children;\n d._children = null;\n }\n update(d);\n }\n }\n}",
"function parseTree(sourceCode, sourceFileName) {\r\n const associate = [];\r\n const functions = [];\r\n const extras = [];\r\n const enumList = [];\r\n const functionNames = [];\r\n const metadataFunctionNames = [];\r\n const ids = [];\r\n const sourceFile = ts.createSourceFile(sourceFileName, sourceCode, ts.ScriptTarget.Latest, true);\r\n buildEnums(sourceFile);\r\n visit(sourceFile);\r\n const parseTreeResult = {\r\n associate,\r\n extras,\r\n functions,\r\n };\r\n return parseTreeResult;\r\n function buildEnums(node) {\r\n if (ts.isEnumDeclaration(node)) {\r\n enumList.push(node.name.getText());\r\n }\r\n ts.forEachChild(node, buildEnums);\r\n }\r\n function visit(node) {\r\n if (ts.isFunctionDeclaration(node)) {\r\n if (node.parent && node.parent.kind === ts.SyntaxKind.SourceFile) {\r\n const functionDeclaration = node;\r\n const position = getPosition(functionDeclaration);\r\n const functionErrors = [];\r\n const functionName = functionDeclaration.name ? functionDeclaration.name.text : \"\";\r\n if (checkForDuplicate(functionNames, functionName)) {\r\n const errorString = `Duplicate function name: ${functionName}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n functionNames.push(functionName);\r\n if (isCustomFunction(functionDeclaration)) {\r\n const extra = {\r\n errors: functionErrors,\r\n javascriptFunctionName: functionName,\r\n };\r\n const idName = getTagComment(functionDeclaration, CUSTOM_FUNCTION);\r\n const idNameArray = idName.split(\" \");\r\n const jsDocParamInfo = getJSDocParams(functionDeclaration);\r\n const jsDocParamTypeInfo = getJSDocParamsType(functionDeclaration);\r\n const jsDocParamOptionalInfo = getJSDocParamsOptionalType(functionDeclaration);\r\n const [lastParameter] = functionDeclaration.parameters.slice(-1);\r\n const isStreamingFunction = hasStreamingInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const isCancelableFunction = hasCancelableInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const isInvocationFunction = hasInvocationParameter(lastParameter, jsDocParamTypeInfo);\r\n const parametersToParse = isStreamingFunction || isCancelableFunction || isInvocationFunction\r\n ? functionDeclaration.parameters.slice(0, functionDeclaration.parameters.length - 1)\r\n : functionDeclaration.parameters.slice(0, functionDeclaration.parameters.length);\r\n const parameterItems = {\r\n enumList,\r\n extra,\r\n jsDocParamInfo,\r\n jsDocParamOptionalInfo,\r\n jsDocParamTypeInfo,\r\n parametersToParse,\r\n };\r\n const parameters = getParameters(parameterItems);\r\n const description = getDescription(functionDeclaration);\r\n const helpUrl = normalizeLineEndings(getTagComment(functionDeclaration, HELPURL_PARAM));\r\n const result = getResults(functionDeclaration, isStreamingFunction, lastParameter, jsDocParamTypeInfo, extra, enumList);\r\n const options = getOptions(functionDeclaration, isStreamingFunction, isCancelableFunction, isInvocationFunction, extra);\r\n const funcName = functionDeclaration.name ? functionDeclaration.name.text : \"\";\r\n const id = normalizeCustomFunctionId(idNameArray[0] || funcName);\r\n const name = idNameArray[1] || id;\r\n validateId(id, position, extra);\r\n validateName(name, position, extra);\r\n if (checkForDuplicate(metadataFunctionNames, name)) {\r\n const errorString = `@customfunction tag specifies a duplicate name: ${name}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n metadataFunctionNames.push(name);\r\n if (checkForDuplicate(ids, id)) {\r\n const errorString = `@customfunction tag specifies a duplicate id: ${id}`;\r\n functionErrors.push(logError(errorString, position));\r\n }\r\n ids.push(id);\r\n associate.push({ functionName, id });\r\n const functionMetadata = {\r\n description,\r\n helpUrl,\r\n id,\r\n name,\r\n options,\r\n parameters,\r\n result,\r\n };\r\n if (!options.cancelable &&\r\n !options.requiresAddress &&\r\n !options.stream &&\r\n !options.volatile &&\r\n !options.requiresParameterAddresses) {\r\n delete functionMetadata.options;\r\n }\r\n else {\r\n if (!options.cancelable) {\r\n delete options.cancelable;\r\n }\r\n if (!options.requiresAddress) {\r\n delete options.requiresAddress;\r\n }\r\n if (!options.stream) {\r\n delete options.stream;\r\n }\r\n if (!options.volatile) {\r\n delete options.volatile;\r\n }\r\n if (!options.requiresParameterAddresses) {\r\n delete options.requiresParameterAddresses;\r\n }\r\n }\r\n if (!functionMetadata.helpUrl) {\r\n delete functionMetadata.helpUrl;\r\n }\r\n if (!functionMetadata.description) {\r\n delete functionMetadata.description;\r\n }\r\n if (!functionMetadata.result) {\r\n delete functionMetadata.result;\r\n }\r\n extras.push(extra);\r\n functions.push(functionMetadata);\r\n }\r\n }\r\n }\r\n ts.forEachChild(node, visit);\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the instruction to generate for interpolated text. | function getTextInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.textInterpolate;
case 3:
return Identifiers$1.textInterpolate1;
case 5:
return Identifiers$1.textInterpolate2;
case 7:
return Identifiers$1.textInterpolate3;
case 9:
return Identifiers$1.textInterpolate4;
case 11:
return Identifiers$1.textInterpolate5;
case 13:
return Identifiers$1.textInterpolate6;
case 15:
return Identifiers$1.textInterpolate7;
case 17:
return Identifiers$1.textInterpolate8;
default:
return Identifiers$1.textInterpolateV;
}
} | [
"function getTextInterpolationExpression(interpolation){switch(getInterpolationArgsLength(interpolation)){case 1:return Identifiers$1.textInterpolate;case 3:return Identifiers$1.textInterpolate1;case 5:return Identifiers$1.textInterpolate2;case 7:return Identifiers$1.textInterpolate3;case 9:return Identifiers$1.textInterpolate4;case 11:return Identifiers$1.textInterpolate5;case 13:return Identifiers$1.textInterpolate6;case 15:return Identifiers$1.textInterpolate7;case 17:return Identifiers$1.textInterpolate8;default:return Identifiers$1.textInterpolateV;}}",
"function getTextInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 1:\n return Identifiers$1.textInterpolate;\n case 3:\n return Identifiers$1.textInterpolate1;\n case 5:\n return Identifiers$1.textInterpolate2;\n case 7:\n return Identifiers$1.textInterpolate3;\n case 9:\n return Identifiers$1.textInterpolate4;\n case 11:\n return Identifiers$1.textInterpolate5;\n case 13:\n return Identifiers$1.textInterpolate6;\n case 15:\n return Identifiers$1.textInterpolate7;\n case 17:\n return Identifiers$1.textInterpolate8;\n default:\n return Identifiers$1.textInterpolateV;\n }\n }",
"function getTextInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 1:\n return Identifiers$1.textInterpolate;\n case 3:\n return Identifiers$1.textInterpolate1;\n case 5:\n return Identifiers$1.textInterpolate2;\n case 7:\n return Identifiers$1.textInterpolate3;\n case 9:\n return Identifiers$1.textInterpolate4;\n case 11:\n return Identifiers$1.textInterpolate5;\n case 13:\n return Identifiers$1.textInterpolate6;\n case 15:\n return Identifiers$1.textInterpolate7;\n case 17:\n return Identifiers$1.textInterpolate8;\n default:\n return Identifiers$1.textInterpolateV;\n }\n }",
"function getTextInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 1:\n return Identifiers$1.textInterpolate;\n\n case 3:\n return Identifiers$1.textInterpolate1;\n\n case 5:\n return Identifiers$1.textInterpolate2;\n\n case 7:\n return Identifiers$1.textInterpolate3;\n\n case 9:\n return Identifiers$1.textInterpolate4;\n\n case 11:\n return Identifiers$1.textInterpolate5;\n\n case 13:\n return Identifiers$1.textInterpolate6;\n\n case 15:\n return Identifiers$1.textInterpolate7;\n\n case 17:\n return Identifiers$1.textInterpolate8;\n\n default:\n return Identifiers$1.textInterpolateV;\n }\n}",
"function getTextInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 1:\n return Identifiers$1.textInterpolate;\n case 3:\n return Identifiers$1.textInterpolate1;\n case 5:\n return Identifiers$1.textInterpolate2;\n case 7:\n return Identifiers$1.textInterpolate3;\n case 9:\n return Identifiers$1.textInterpolate4;\n case 11:\n return Identifiers$1.textInterpolate5;\n case 13:\n return Identifiers$1.textInterpolate6;\n case 15:\n return Identifiers$1.textInterpolate7;\n case 17:\n return Identifiers$1.textInterpolate8;\n default:\n return Identifiers$1.textInterpolateV;\n }\n}",
"function getTextInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 1:\n return Identifiers.textInterpolate;\n\n case 3:\n return Identifiers.textInterpolate1;\n\n case 5:\n return Identifiers.textInterpolate2;\n\n case 7:\n return Identifiers.textInterpolate3;\n\n case 9:\n return Identifiers.textInterpolate4;\n\n case 11:\n return Identifiers.textInterpolate5;\n\n case 13:\n return Identifiers.textInterpolate6;\n\n case 15:\n return Identifiers.textInterpolate7;\n\n case 17:\n return Identifiers.textInterpolate8;\n\n default:\n return Identifiers.textInterpolateV;\n }\n}",
"function getInstruction(instruction) {\n return instruction.instruction;\n}",
"toString(){return this.__expression}",
"function getAttributeInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 3:\n return Identifiers$1.attributeInterpolate1;\n\n case 5:\n return Identifiers$1.attributeInterpolate2;\n\n case 7:\n return Identifiers$1.attributeInterpolate3;\n\n case 9:\n return Identifiers$1.attributeInterpolate4;\n\n case 11:\n return Identifiers$1.attributeInterpolate5;\n\n case 13:\n return Identifiers$1.attributeInterpolate6;\n\n case 15:\n return Identifiers$1.attributeInterpolate7;\n\n case 17:\n return Identifiers$1.attributeInterpolate8;\n\n default:\n return Identifiers$1.attributeInterpolateV;\n }\n }",
"function getAttributeInterpolationExpression(interpolation){switch(getInterpolationArgsLength(interpolation)){case 3:return Identifiers$1.attributeInterpolate1;case 5:return Identifiers$1.attributeInterpolate2;case 7:return Identifiers$1.attributeInterpolate3;case 9:return Identifiers$1.attributeInterpolate4;case 11:return Identifiers$1.attributeInterpolate5;case 13:return Identifiers$1.attributeInterpolate6;case 15:return Identifiers$1.attributeInterpolate7;case 17:return Identifiers$1.attributeInterpolate8;default:return Identifiers$1.attributeInterpolateV;}}",
"function getAttributeInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 3:\n return Identifiers$1.attributeInterpolate1;\n case 5:\n return Identifiers$1.attributeInterpolate2;\n case 7:\n return Identifiers$1.attributeInterpolate3;\n case 9:\n return Identifiers$1.attributeInterpolate4;\n case 11:\n return Identifiers$1.attributeInterpolate5;\n case 13:\n return Identifiers$1.attributeInterpolate6;\n case 15:\n return Identifiers$1.attributeInterpolate7;\n case 17:\n return Identifiers$1.attributeInterpolate8;\n default:\n return Identifiers$1.attributeInterpolateV;\n }\n }",
"get formula() { return this.ast ? this.ast.toString(this.id) : ''; }",
"function getAttributeInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 3:\n return Identifiers$1.attributeInterpolate1;\n case 5:\n return Identifiers$1.attributeInterpolate2;\n case 7:\n return Identifiers$1.attributeInterpolate3;\n case 9:\n return Identifiers$1.attributeInterpolate4;\n case 11:\n return Identifiers$1.attributeInterpolate5;\n case 13:\n return Identifiers$1.attributeInterpolate6;\n case 15:\n return Identifiers$1.attributeInterpolate7;\n case 17:\n return Identifiers$1.attributeInterpolate8;\n default:\n return Identifiers$1.attributeInterpolateV;\n }\n }",
"get instruction_register(){ return this.memory[this.PC]; }",
"function getAttributeInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 3:\n return Identifiers$1.attributeInterpolate1;\n\n case 5:\n return Identifiers$1.attributeInterpolate2;\n\n case 7:\n return Identifiers$1.attributeInterpolate3;\n\n case 9:\n return Identifiers$1.attributeInterpolate4;\n\n case 11:\n return Identifiers$1.attributeInterpolate5;\n\n case 13:\n return Identifiers$1.attributeInterpolate6;\n\n case 15:\n return Identifiers$1.attributeInterpolate7;\n\n case 17:\n return Identifiers$1.attributeInterpolate8;\n\n default:\n return Identifiers$1.attributeInterpolateV;\n }\n}",
"function infixTex(code)\n{\n\treturn function(thing,texArgs)\n\t{\n\t\tvar arity = jme.builtinScope.functions[thing.tok.name][0].intype.length;\n\t\tif( arity == 1 )\t//if operation is unary, prepend argument with code\n\t\t{\n\t\t\treturn code+texArgs[0];\n\t\t}\n\t\telse if ( arity == 2 )\t//if operation is binary, put code in between arguments\n\t\t{\n\t\t\treturn texArgs[0]+' '+code+' '+texArgs[1];\n\t\t}\n\t}\n}",
"function getAttributeInterpolationExpression(interpolation) {\n switch (getInterpolationArgsLength(interpolation)) {\n case 3:\n return Identifiers$1.attributeInterpolate1;\n case 5:\n return Identifiers$1.attributeInterpolate2;\n case 7:\n return Identifiers$1.attributeInterpolate3;\n case 9:\n return Identifiers$1.attributeInterpolate4;\n case 11:\n return Identifiers$1.attributeInterpolate5;\n case 13:\n return Identifiers$1.attributeInterpolate6;\n case 15:\n return Identifiers$1.attributeInterpolate7;\n case 17:\n return Identifiers$1.attributeInterpolate8;\n default:\n return Identifiers$1.attributeInterpolateV;\n }\n}",
"get instructionPointer() {\n\t\treturn this._program.instructionPointer;\n\t}",
"static call_obj_to_instruction_src_for_function(eval_args=false){\n let instruction_name = this.get_instruction_name_from_ui()\n let id\n let elt\n id = this.arg_name_to_dom_elt_id(\"name\")\n elt = window[id]\n let the_name_src = elt.value.trim()\n id = this.arg_name_to_dom_elt_id(\"...params\")\n elt = window[id]\n let the_params_src = elt.value.trim()\n id = this.arg_name_to_dom_elt_id(\"body\")\n elt = window[id]\n let the_body_src = elt.value.trim()\n the_body_src = \"\\n\" + the_body_src\n the_body_src = replace_substrings(the_body_src, \"\\n\", \"\\n \")\n\n let result = ((the_name_src == \"\") ? instruction_name: instruction_name + \" \" + the_name_src )\n result += \"(\" + the_params_src + \"){\" + the_body_src + \"\\n}\\n\"\n return result\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.