query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Returns this class reoresentaion as a string in JSON format. Important: The value of km/yaer is a computed field and NOT part of the class, it's not included in the string. | toString() {
return "{ \"brand\": \"" + this.brand + "\", \"model\": \"" + this.model + "\", \"color\": \"" + this.color + "\", \"year\": " + this.year + ", \"km\": " + this.km + " }";
} | [
"toString() {\n return JSON.stringify(this.memory, this.getCircularReplacer());\n }",
"toString() {\n return JSON.stringify(this.toJSON());\n }",
"toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }",
"toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }",
"toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }",
"toJSON() {\n return {\n type: \"Point\",\n coordinates: [this.longitude, this.latitude],\n crs: { type: \"name\", properties: { name: WorldGeodeticSystem1984 } }\n };\n }",
"toString() {\n return JSON.stringify(this.value);\n }",
"toJSON () {\n return {\n value: this.value / COIN,\n valueZat: Number(this.value),\n scriptPubKey: this.scriptPubKey.toString('hex')\n }\n }",
"toJSON() { return this.degrees; }",
"toString() {\r\n return this._trytes;\r\n }",
"toString() {\n return this.to_str()\n }",
"toString() {\n\t\treturn `{${this.blossoms2string()} ${this.trees2string()}}`;\n\t}",
"toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }",
"toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }",
"convert_to_json() {\n return JSON.stringify(this);\n }",
"toJSON() {\n return {\n r: this.r,\n g: this.g,\n b: this.b,\n a: this.a,\n };\n }",
"toString() {\n return (JSON.stringify(this.object));\n }",
"toString() {\n return this.name + ', scienficically known as ' + this.scientificName;\n }",
"saveToJSON () {\n\t\tlet humanJSON = JSON.stringify(this);\n\n\t\treturn humanJSON;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fix vertical when not overflow call fullscreenFix() if .fullscreen content changes | function fullscreenFix() {
var h = $( 'body' ).height();
// set .fullscreen height
$( ".content-b" ).each( function ( i ) {
if ( $( this ).innerHeight() <= h ) {
$( this ).closest( ".fullscreen" ).addClass( "not-overflow" );
}
} );
} | [
"function fullscreenFix() {\n var h = $('body').height();\n // set .fullscreen height\n $(\".content-b\").each(function (i) {\n if ($(this).innerHeight() <= h) {\n $(this).closest(\".fullscreen\").addClass(\"not-overflow\");\n }\n });\n }",
"function fullscreenFix(){\n\t\t var h = $('body').height();\n\t\t // set .fullscreen height\n\t\t $(\".content-b\").each(function(i){\n\t\t if($(this).innerHeight() <= h){\n\t\t $(this).closest(\".fullscreen\").addClass(\"not-overflow\");\n\t\t }\n\t\t });\n\t\t}",
"function fullscreenFix(){\n var h = $('body').height();\n // set .fullscreen height\n $(\".content-b\").each(function(i){\n if($(this).innerHeight() <= h){\n $(this).closest(\".fullscreen\").addClass(\"not-overflow\");\n }\n });\n }",
"function fullscreenFix(){\n\t var h = $('body').height();\n\t // set .fullscreen height\n\t $('.content-b').each(function(i){\n\t if($(this).innerHeight() <= h){\n\t $(this).closest('.fullscreen').addClass('not-overflow');\n\t }\n\t });\n\t}",
"function fullscreenFix(){\n\t\tvar h = $('body').height();\n\t\t// set .fullscreen height\n\t\t$(\".content-b\").each(function(i){\n\t\t\tif($(this).innerHeight() > h){ $(this).closest(\".fullscreen\").addClass(\"overflow\");\n\t\t\t}\n\t\t});\n\t}",
"function fullscreenFix(){\n\t var h = $('body').height();\n\t // set .fullscreen height\n\t $(\".content-b\").each(function(i){\n\t if($(this).innerHeight() <= h){\n\t $(this).closest(\".fullscreen\").addClass(\"not-overflow\");\n\t }\n\t });\n\t}",
"function fullscreenFix(){\n var h = $('body').height();\n // set .fullscreen height\n $(\".content-b\").each(function(i){\n if($(this).innerHeight() <= h){\n $(this).closest(\".fullscreen\").addClass(\"not-overflow\");\n }\n });\n }",
"function fullscreenFix(){\n var h = $('body').height();\n // set .fullscreen height\n $(\".content-b\").each(function(i){\n if($(this).innerHeight() > h){ $(this).closest(\".fullscreen\").addClass(\"overflow\");\n }\n });\n }",
"function escope_resize_fullscreen() {\r\n var windowHeight = $(window).height();\r\n $('.fullscreen, .revslider-fullscreen').height(windowHeight);\r\n }",
"function thememascot_resize_fullscreen() {\n var windowHeight = $(window).height();\n $('.fullscreen, .revslider-fullscreen').height(windowHeight);\n }",
"function resize_fullscreen() {\n var windowHeight = $(window).height();\n $('.fullscreen, .revslider-fullscreen').height(windowHeight);\n }",
"function _toggleFullscreen( $ele ){\r\n if (!$ele) return;\r\n var $target = $ele.closest(\".vis-view\");\r\n if (!$target) return;\r\n var styleold = $target.attr(\"styleold\");\r\n if (styleold) {\r\n $target.attr(\"style\",styleold);\r\n $target.removeAttr(\"styleold\");\r\n $target.appendTo(\".mdui-id-\"+$target.attr(\"id\"));\r\n } else {\r\n $target.parent().addClass(\"mdui-id-\"+$target.attr(\"id\"));\r\n $target.attr(\"styleold\",$target.attr(\"style\"));\r\n $target.attr(\"style\",\"position:fixed; left:0; top:0; width:100%; height:100%; z-index: 2147483647 !important;background:#212121 !important; \");\r\n $target.appendTo( \"body\" );\r\n //$target.appendTo( \"body #vis_container\" );\r\n }\r\n}",
"function startFullScreenHandler (start, finish) {\n\nfunction check () {\n\n if (\n document.fullscreenElement || /* Standard syntax */\n document.webkitFullscreenElement || /* Chrome, Safari and Opera syntax */\n document.mozFullScreenElement || /* Firefox syntax */\n document.msFullscreenElement /* IE/Edge syntax */\n ) {\n\n $(\"html\").css(\"overflow\", \"hidden\");\n start ();\n\n } else {\n\n $(\"html\").css(\"overflow\", \"auto\");\n finish ();\n }\n\n}\n\n// EVENT LISTENERS \ndocument.addEventListener('webkitfullscreenchange', function(e) { check(); }, false);\ndocument.addEventListener('mozfullscreenchange', function(e) { check(); }, false);\ndocument.addEventListener('fullscreenchange', function(e) { check(); }, false);\ndocument.addEventListener('msfullscreenchange', function(e) { check(); }, false);\n\n}",
"function onFullscreenChange() {\n if(!document.webkitFullscreenElement && !document.mozFullScreenElement) {\n vrMode = false;\n }\n resize();\n }",
"function heightFullscreen() {\n if ($('#jarviswidget-fullscreen-mode')\n .length) {\n\n /**\n * Setting height variables.\n **/\n var heightWindow = $(window)\n .height();\n var heightHeader = $('#jarviswidget-fullscreen-mode')\n .children(self.o.widgets)\n .children('header')\n .height();\n\n /**\n * Setting the height to the right widget.\n **/\n $('#jarviswidget-fullscreen-mode')\n .children(self.o.widgets)\n .children('div')\n .height(heightWindow - heightHeader - 15);\n }\n }",
"function exit_fullscreen(){\n\t\tvar breakpoint = SETTINGS.VIEWPORT_SIZE;\n\t\tif ( breakpoint == 'large' || breakpoint == 'xlarge' || breakpoint == 'xxlarge') {\n\t\t\t\n\t\t\tvar w_top = window.scrollY || document.body.scrollTop;\n\t\t\tvar e_pos = $('#what-we-do').offset().top;\n\n\t\t\tvar e_top = e_pos - w_top;\n\n\t\t\tif ( e_top <= 10 ){\n\t\t\t\t$('#page-wrapper').addClass('scrolled');\n\t\t\t\t$('#page-wrapper').addClass('flow');\n\t\t\t} else if ( e_top >= 11 ) { \n\t\t\t\t$('#page-wrapper').removeClass('scrolled');\n\t\t\t\t$('#page-wrapper').removeClass('flow');\n\t\t\t}\n\n\t\t}\n\t}",
"function heightFullscreen() {\n if ($('#jarviswidget-fullscreen-mode')\n .length) {\n\n /**\n * Setting height variables.\n **/\n var heightWindow = $(window)\n .height();\n var heightHeader = $('#jarviswidget-fullscreen-mode')\n .find(self.o.widgets)\n .children('header')\n .height();\n\n /**\n * Setting the height to the right widget.\n **/\n $('#jarviswidget-fullscreen-mode')\n .find(self.o.widgets)\n .children('div')\n .height(heightWindow - heightHeader - 15);\n }\n }",
"onFullScreenChanged () {}",
"updateFullScreenButtonVisibility() {\n // If already in full screen, do nothing\n if (this.fullscreen) {\n return;\n }\n\n let forceFullscreen = false;\n if (this.options.layout.fullScreen.fullScreenMode === 'always') {\n forceFullscreen = true;\n }\n else if (this.options.layout.fullScreen.fullScreenMode === 'dynamic') {\n forceFullscreen = (this.$container.width() < this.options.layout.fullScreen.forceFullScreenWidthThreshold);\n }\n\n this.$container.toggleClass('h5p-mini-course-force-fullscreen', forceFullscreen);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate a yup schema. | function validateYupSchema(values,schema,sync,context){if(sync===void 0){sync=false;}if(context===void 0){context={};}var validateData=prepareDataForValidation(values);return schema[sync?'validateSync':'validate'](validateData,{abortEarly:false,context:context});} | [
"function yupMaker(schema, config) {\n const { name, validationType, validations = [] } = config;\n if (!yup[validationType]) {\n return schema;\n }\n let validator = yup[validationType]();\n validations.forEach((validation) => {\n const { params, type } = validation;\n if (!validator[type]) {\n return;\n }\n validator = validator[type](...params);\n });\n schema[name] = validator;\n return schema;\n}",
"static validate(doc, schema, options) {\n schema = (this.schema.props || yup_1.object());\n return schema.validateSync(doc, options);\n }",
"function validateYupSchema(values, schema, sync, context) {\n if (sync === void 0) {\n sync = false;\n }\n\n if (context === void 0) {\n context = {};\n }\n\n var validateData = prepareDataForValidation(values);\n return schema[sync ? 'validateSync' : 'validate'](validateData, {\n abortEarly: false,\n context: context\n });\n}",
"function validateSchema(schema){\n\treturn true;\n}",
"static isValid(doc, schema, options) {\n schema = (this.schema.props || yup_1.object());\n return schema.isValidSync(doc, options);\n }",
"function validateAgainstSchema(api, state) {\n util.debug('Validating \"%s\" against the Swagger schema', state.swaggerPath);\n\n tv4.addSchema(swaggerSchema);\n if (tv4.validate(api, swaggerSchema)) {\n util.debug(' Validated successfully');\n }\n else {\n throw util.newSyntaxError(\n '%s \\nData path: \"%s\" \\nSchema path: \"%s\"\\n',\n tv4.error.message, tv4.error.dataPath, tv4.error.schemaPath);\n }\n}",
"function validateSchema(schema) {\n var result = tv4_validateSchema(schema);\n return result;\n}",
"_validate (schema){\n return SwaggerParser.validate(schema);\n }",
"function checkSchema (instance, schema) {\n if (validate(instance, schema).errors.length > 0) \n return false\n return true\n}",
"function validateMetaSchema(schema) {\n const ajv = createSchemaProcessor()\n const valid = ajv.validate(META_SCHEMA, schema)\n if (!valid) {\n throw new Error(ajv.errorsText(ajv.errors, { separator: '\\n' }))\n }\n}",
"function verifyYMLContent(path) {\n var errors = validateSchema(path, {\n schemaPath: './schema.yaml' // can also be schema.json\n });\n return (errors.length == 0) ? true : false;\n}",
"isValid(data, schema) {\n \n }",
"function checkProcessedAgainstSchema(processed) {\n const ajv = new AJV();\n const schema = fs.readFileSync(schemaPath);\n const isValid = ajv.validate(schema, processed);\n if (!isValid) console.warn('May not be perfectly valid', ajv.errors);\n}",
"function schemaCheck(req, res, next){\n console.log('schemaCheck req', req.body)\n var schema = req.body.schema;\n var schemaDoubleQuote = singleToDoubleQuote(schema);\n if(validatedParsedJSON(schemaDoubleQuote)){\n req.body.schema = schemaDoubleQuote;\n \tconsole.log('validatedSchema')\n next();\n } else {\n \tres.json({error : 'Incorrect schema format'})\n }\n}",
"function validate(instance, schema, tightenSchema) {\n if (!schema || !_.isObject(schema)) {\n return {\n valid: false,\n errors: [\n 'Invalid schema.'\n ]\n };\n }\n\n if (_.isUndefined(tightenSchema) || tightenSchema) {\n schema = tighten(schema);\n }\n\n if (!instance || !_.isObject(instance)) {\n return {\n valid: false,\n errors: [\n 'Invalid instance.'\n ]\n };\n }\n return validator.validate(instance, schema);\n}",
"schemaValidation() {\n return {\n nameSchema: check('name')\n .notEmpty()\n .isLength({ min: 2, max: 15 })\n .withMessage('name must be between 4 to 15 chars'),\n };\n }",
"function valid_schema(schema) {\n\t\tif (typeof schema !== \"object\") {\n\t\t\tvar help = \"\";\n\t\t\tif (typeof schema == \"function\") help = \" It is a function, did you forget to use new?\"\n\t\t\tthrow new Error(\"schema '\" + schema + \"' is not an object.\" + help);\n\t\t}\n\n\t\tif (schema.__proto__['_schema_valid']) return schema;\n\n\t\tschema.__proto__['_schema_checking'] = true;\n\n\t\tfor (var field in schema) {\n\t\t\tif (field.indexOf('_schema_') === 0) continue;\n\n\t\t\t// Make sure a qualifier is set.\n\t\t\tif (schema[field].qualifier != \"required\" &&\n\t\t\t\t\tschema[field].qualifier != \"optional\" &&\n\t\t\t\t\tschema[field].qualifier != \"repeated\")\n\t\t\t\tthrow new Error(\"Invalid qualifier '\" + schema[field].qualifier + \"' on field '\" + field + \"'\");\n\n\t\t\t// Check the type of the field.\n\n\t\t\tif (isPrimitive(schema[field].type)) {\n\t\t\t\t// Primitive fields cannot go wrong.\n\t\t\t\t; // Nothing to do.\n\t\t\t} else {\n\t\t\t\t// Fields that are schemas have to be recursively. We watch out for loops!\n\t\t\t\tif (schema[field].type['_schema_checking']) {\n\t\t\t\t\tif (schema[field].qualifier == \"required\") {\n\t\t\t\t\t\tthrow new Error(\"required fields can not be used recursively (think about it, it makes sense)\");\n\t\t\t\t\t}\n\t\t\t\t\tschema_log(\"loop detected, already checked\");\n\t\t\t\t} else {\n\t\t\t\t\tvalid_schema(schema[field].type);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tschema.__proto__['_schema_checked'] = true;\n\t\tdelete schema.__proto__['_schema_valid'];\n\n\t\treturn schema;\n\t}",
"function compileSchema (schema) {\n return (payload) => {\n return Joi.validate(payload, schema)\n }\n}",
"function validateAgainstSchema(swaggerObject) {\n // Don't do anything if validation is disabled\n if (!parseState.options.validateSpec) return;\n\n // Validate against the schema\n if (tv4.validate(swaggerObject, swaggerSchema)) {\n return true;\n }\n else {\n throw syntaxError('%s \\nData path: \"%s\" \\nSchema path: \"%s\"\\n',\n tv4.error.message, tv4.error.dataPath, tv4.error.schemaPath);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the named range corresponding to the data table (ie as part of deleting the data table) | function deleteTableRange(ss, tableName, range) {
var matchingRange = range || findTableRange(ss, tableName)
if (range) {
tableName = range.getName()
} else {
tableName = buildTableRangeName_(tableName)
}
if (null != matchingRange) {
matchingRange.getRange().clearNote()
matchingRange.getRange().clear()
ss.removeNamedRange(tableName)
}
} | [
"removeRange({columns,owner,start,stop,table}) { this.$publish('removeRange', {columns,owner,start,stop,table})}",
"function deleteNamedRanges () {\n this.named_ranges = template_sheet.getNamedRanges();\n\n this.removeNamedRanges()\n\n // Apply pending Spreadsheet changes\n SpreadsheetApp.flush();\n }",
"function deleteNamedRanges () {\n if (typeof named_ranges != \"undefined\") {\n named_ranges.forEach(function (e) { e.remove() });\n } else {\n var named_ranges = ss.getNamedRanges();\n named_ranges.forEach(function (e) { e.remove() });\n }\n\n // Apply pending Spreadsheet changes\n SpreadsheetApp.flush();\n }",
"function removeNamedRange(id) {\n var namedRange = getNamedRangeById(id);\n namedRange.remove();\n}",
"function deleteRange(model, range) {\n return model.deferNotifications({ content: true, selection: true }, () => {\n model.deleteAtoms(range);\n model.position = range[0];\n });\n}",
"function clearTableRanges(ss) {\n var tableRanges = listTableRanges(ss)\n for (var k in tableRanges) {\n deleteTableRange(ss, null, tableRanges[k])\n }\n }",
"function deleteRange(range, deleteRange) {\n if (!range || !deleteRange)\n return;\n var lineSpan = deleteRange.endLine - deleteRange.startLine;\n var oldStartLine = range.startLine;\n var oldStartColumn = range.startColumn;\n var oldEndLine = range.endLine;\n var oldEndColumn = range.endColumn;\n // delete range entirely before range\n if (deleteRange.endLine < oldStartLine || (deleteRange.endLine === oldStartLine && deleteRange.endColumn < oldStartColumn)) {\n range.startLine -= lineSpan;\n range.endLine -= lineSpan;\n if (deleteRange.endLine === oldStartLine) {\n var columnSpan = deleteRange.endColumn - deleteRange.startColumn;\n range.startColumn -= columnSpan;\n // adjust end column if the range is on a single line\n if (oldStartLine === oldEndLine)\n range.endColumn -= columnSpan;\n }\n return;\n }\n // delete range entirely after range\n if (deleteRange.startLine > oldEndLine || (deleteRange.startLine === oldEndLine && deleteRange.startColumn > oldEndColumn)) {\n // nothing to do...\n return;\n }\n // delete range intersects range\n // compute new start and end lines\n range.startLine = Math.min(deleteRange.startLine, oldStartLine);\n range.endLine = oldEndLine < deleteRange.endLine ? deleteRange.startLine : Math.max(range.startLine, oldEndLine - lineSpan);\n // compute new start column\n if (oldStartLine === deleteRange.startLine)\n range.startColumn = Math.min(deleteRange.startColumn, oldStartColumn);\n else if (oldStartLine > deleteRange.startLine)\n range.startColumn = deleteRange.startColumn;\n // compute new end column\n if (oldEndLine === deleteRange.endLine)\n range.endColumn = Math.max(deleteRange.startColumn, oldEndColumn + deleteRange.startColumn - deleteRange.endColumn);\n else if (oldEndLine < deleteRange.endLine) {\n // delete range ends after the range\n range.endColumn = deleteRange.startColumn;\n }\n}",
"deleteRange(start, end) {\n // Exit without traversing the tree if the range has zero size.\n if (start === end) {\n return;\n }\n const iterator = this.rbTree.ge(start);\n while (iterator.valid && iterator.key < end) {\n this.rbTree = this.rbTree.remove(iterator.key);\n iterator.next();\n }\n }",
"function deleteTable(name) { return TableService_.deleteTable(name) }",
"function _clearRange (range) {\n Logger.log('Clearing ' + range);\n Sheets.Spreadsheets.Values.clear({}, _getId(), range);\n }",
"remove(start: number, end: number) {\n if (typeof start !== 'number' || typeof end !== 'number') {\n throw new Error(\n `cannot remove non-numeric range [${start}, ${end})`\n );\n }\n this.log(\n 'REMOVE', `[${start}, ${end})`,\n JSON.stringify(this.context.source.slice(start, end))\n );\n this.editor.remove(start, end);\n }",
"function eraseInputData(inputSheetObj, rCount, cCount)\n{\n var dataColumns = cCount - 1;\n var dataRange = inputSheetObj.getRange(1, 2, rCount, dataColumns);\n dataRange.clear();\n}",
"exec() {\r\n return this.kv.deleteRange(this.namespace.applyToRequest(this.request), this.callOptions);\r\n }",
"remove(range) { \n for(let i = range[0]; i <= range[1]; i++){\n let position = this.rangesList.indexOf(i);\n if ( ~position ) this.rangesList.splice(position, 1);\n } \n }",
"delete( range ) {\n range = cobalt.range(range);\n return new CobaltFragment(\n cobaltText.delete( this.text, range ),\n cobaltAnnotations.delete( this.annotations, range )\n );\n }",
"_clearRangeTable() {\n let range = this._range;\n let rows = this._rows;\n for (let i = range.low; i <= range.high; i++) {\n rows[i].classList.remove('selected');\n }\n range.low = -1;\n range.high = -1;\n }",
"deleteTable() {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n let startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n if (startPos.paragraph.isInsideTable) {\n let table = this.getOwnerTable(this.selection.isForward).combineWidget(this.viewer);\n this.selection.owner.isShiftingEnabled = true;\n if (this.checkIsNotRedoing()) {\n this.initHistory('DeleteTable');\n //Sets the insert position in history info as current table. \n this.updateHistoryPosition(startPos, true);\n }\n let paragraph = this.getParagraphForSelection(table);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.editorHistory.currentBaseHistoryInfo.removedNodes.push(table.clone());\n }\n this.removeBlock(table);\n this.selection.selectParagraphInternal(paragraph, true);\n if (this.checkIsNotRedoing() || isNullOrUndefined(this.editorHistory)) {\n this.reLayout(this.selection);\n }\n }\n }",
"function removeRange(nput) {\n var id = parseInt(nput.substring(1, nput.length));\n self.removeControl(id);\n self.draw();\n }",
"function delete_old_data(sheet_city) {\n var oldest_data = sheet_city.getRange(2, 6).getValue();\n var first_last_row = identify_first_last_row(sheet_city, 'Crawl_Time', oldest_data);\n var last_row = sheet_city.getLastRow();\n var range = sheet_city.getRange(first_last_row[0] + first_last_row[1], 6, last_row, 4).getValues();\n sheet_city.getRange('F2:I').clear();\n sheet_city.getRange(2, 6, range.length, range[0].length).setValues(range);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotate the vector by an angle and direction | rotate({ angle, direction }) {
// Throw an error if the angle is not an Angle
validate({ angle }, 'Angle');
// Throw an error if the direction is not a Direction
validate({ direction }, 'Direction');
// Create a Quaternion from the angle and direction
const rotationQuaterion = Quaternion.fromAngleAndDirection({ angle, direction });
// Rotate the vector
const { vector } = this.quaternion.rotate(rotationQuaterion);
// Return the rotated vector
return new Vector(vector);
} | [
"rotate(angle)\n {\n //rotate the vector clockwise by the given degrees\n var x = this.x * Math.cos(angle * Math.PI / 180) - this.y * Math.sin(angle * Math.PI / 180);\n var y = this.x * Math.sin(angle * Math.PI / 180) + this.y * Math.cos(angle * Math.PI / 180);\n\n return new Vector(x, y);\n }",
"rotateInPlace({ angle, direction }) {\n\n // Throw an error if the angle is not an Angle\n validate({ angle }, 'Angle');\n\n // Throw an error if the direction is not a Direction\n validate({ direction }, 'Direction');\n\n // Rotate the vector by the angle and direction\n const vector = this.rotate({ angle, direction });\n\n // Update the vector with the rotated vector\n this.update(vector);\n }",
"function rotateVector(direction, theta){\n var rotateM = mat2(Math.cos(theta), -Math.sin(theta), Math.sin(theta), Math.cos(theta));\n return normalize(mult(rotateM, direction))\n}",
"function rotateVector(direction, theta)\n{\n var rotateM = mat2(Math.cos(theta), -Math.sin(theta), Math.sin(theta), Math.cos(theta));\n return normalize(mult(rotateM, direction))\n}",
"function rotateVector(velocity, angle) {\n rotatedX = velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle);\n rotatedY = velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle);\n return rotatedVelocity = {\n x : rotatedX,\n y: rotatedY\n }\n}",
"function vector_rotate() {\n var args = Array.prototype.slice.call(arguments);\n var angle = args.shift();\n var result = [];\n var sin=Math.sin(angle);\n var cos=Math.cos(angle);\n var vector;\n\n while (vector = args.shift()) {\n result.push([vector[0] * cos - vector[1] * sin,\n vector[0] * sin + vector[1] * cos]);\n }\n\n return result.length == 1 ? result[0] : result;\n}",
"function rotateVec(vec, angle) {\n let hX = vec.x;\n vec.x = (vec.x * Math.cos(angle)) - (vec.y * Math.sin(angle));\n vec.y = (hX * Math.sin(angle)) + (vec.y * Math.cos(angle));\n}",
"function rotateVector(vec)\r\n{\r\n\t rotateVector_yaw(vec, moverDirection.phi); \r\n\t rotateVector_pitch(vec, moverDirection.theta); \r\n\t rotateVector_roll(vec, moverDirection.psi); \r\n}",
"function rotate(vector, direction1, direction2, angle)\n{\n\tvar component1 = -inner(vector, direction1);\n\tvar component2 = -inner(vector, direction2);\n\tvar vector1 = scale(direction1, component1);\n\tvar vector2 = scale(direction2, component2);\n\tvar vector_fixed = subtract(vector, add(vector1, vector2));\n\tvar component1_rotated = component1 * Math.cos(angle) - component2 * Math.sin(angle);\n\tvar component2_rotated = component1 * Math.sin(angle) + component2 * Math.cos(angle);\n\tvar vector1_rotated = scale(direction1, component1_rotated);\n\tvar vector2_rotated = scale(direction2, component2_rotated);\n\tvar vector_rotated = add(vector1_rotated, vector2_rotated);\n\treturn add(vector_rotated, vector_fixed);\n}",
"function rotate(vec, angle) {\n return new RotateExpr(vec, expr_1.wrapInValue(angle));\n}",
"static Rotate(v, angle) {\n var newX = v.x * Math.cos(angle) - v.y * Math.sin(angle);\n var newY = v.y * Math.cos(angle) + v.x * Math.sin(angle);\n v.x = newX;\n v.y = newY;\n return v;\n }",
"rotate(toVector, perpendicularVector, angle) {\n this.scale(Math.cos(angle * DEGREES_TO_RADIANS));\n toVector.scale(Math.sin(angle * DEGREES_TO_RADIANS));\n this.add(toVector);\n this.normalize();\n toVector.cross(perpendicularVector, this);\n }",
"function rotateVec(vec, amount){\r\n return rotate(vec, {x:0,y:0}, amount);\r\n}",
"function rotate(v){\n\t\treturn $M([[0, -1],[1, 0]]).x(v)\n\t}",
"static rotate2D(v, angle) {\n\t\tvar x = v.x * Math.cos(angle) - v.y * Math.sin(angle);\n\t\tvar y = v.x * Math.sin(angle) + v.y * Math.cos(angle);\n\t\tvar args = [];\n\t\targs.push(x);\n\t\targs.push(y);\n\t\tif (v.z) {\n\t\t\targs.push(v.z);\n\t\t}\n\t\tif (v.w) {\n\t\t\targs.push(v.w);\n\t\t}\n\t\treturn Vector.arrayToVector(args);\n\t}",
"function rotateVectorByAngle(vec, ang)\n{\n var cos = Math.cos(ang);\n var sin = Math.sin(ang);\n return new Array(Math.round(10000*(vec[0] * cos - vec[1] * sin))/10000, Math.round(10000*(vec[0] * sin + vec[1] * cos))/10000);\n}",
"rotated(angle) {\n const newAngle = this.angle + angle;\n const mag = this.magnitude;\n return v2(mag * Math.cos(newAngle), mag * Math.sin(newAngle));\n }",
"function rotate(vector, theta){\n if(typeof theta == 'function'){\n var originalFunction = theta;\n theta = vector;\n return function(parameter){\n return rotate(originalFunction(parameter), theta);\n }\n }else{\n var x = vector[0], y = vector[1];\n return [\n x*Math.cos(theta) - y*Math.sin(theta),\n x*Math.sin(theta) + y*Math.cos(theta)\n ];\n }\n}",
"function rotateVector(v, ...rots){\n let r = v;\n for(let rot of rots){\n if(typeof rot == 'number'){\n // scalar rotation\n const cr = Math.cos(rot);\n const sr = Math.sin(rot);\n r = {\n x: cr * r.x - sr * r.y,\n y: sr * r.x + cr * r.y\n };\n } else {\n // complex (vector) rotation\n r = {\n x: r.x * rot.x - r.y * rot.y,\n y: r.x * rot.y + r.y * rot.x\n };\n }\n }\n return r;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures that all fields in the given array exist within the model | static assertFieldsExist(fields = []) {
if (fields === RETURNS_ALL_FIELDS) {
return;
}
const modelFields = this.fields();
// Ensure that all fields are defined within our model
const missing = fields.reduce((missing, field) => {
if (modelFields.indexOf(field) === -1) {
missing.push(field);
}
return missing;
}, []);
if (missing.length > 0) {
throw new Error(
`All fields must be defined within your model. Missing: ` +
missing.join(', ')
);
}
} | [
"function hasFields(model, fields, exists)\n{\n if ( isArray( fields ) )\n {\n for (var i = 0; i < fields.length; i++)\n {\n if ( !exists( model[ fields[ i ] ] ) )\n {\n return false;\n }\n }\n\n return true;\n }\n else // isString( fields )\n {\n return exists( model[ fields ] );\n }\n}",
"function validateArrayFields(fields, company) {\n let error;\n _.some(fields, field => {\n try {\n if (company[field] && company[field].length > 0) {\n company[field] = JSON.parse(company[field]);\n }\n } catch (err) {\n error = AppErr.reject(err, ERROR['INVALID_' + field.toUpperCase()]);\n return true;\n }\n });\n return error;\n}",
"function valid_fields( fields, obj) {\n\n var valid = true;\n\n fields.every(function(value) {\n return valid = obj.hasOwnProperty( value );\n });\n\n return valid;\n}",
"validateFieldOptions() {\n this.options.fields.forEach((f) => {\n let name = f;\n if (typeof f === 'object') {\n name = f.name;\n }\n\n if (this.availableFields.indexOf(name) === -1) {\n throw new Error(`Field ${name} not available. Make sure the fields array item has\\\n a string or a object with a name attribute containing one of the available fields.`);\n }\n });\n }",
"function validateRequiredFields() {\n var requiredFields = getRequiredFields();\n\n return requiredFields.map(validateRequiredField).every( id );\n}",
"function confirmHasFields(obj, fields) {\n if (_.isString(fields)) {\n return _.has(obj, fields)\n ? Promise.resolve()\n : Promise.reject(errors.missingFields(fields));\n }\n if (!_.isArray(fields)) {\n return Promise.reject(\n errors.argumentError('Fields should be an array or string')\n );\n }\n var missingFields = [];\n fields.forEach(function(field) {\n if (!_.has(obj, field))\n missingFields.push(field);\n });\n return (missingFields.length === 0)\n ? Promise.resolve()\n : Promise.reject(errors.missingFields(fields));\n }",
"function allFilled(fields){\r\n for(let y=0;y<fields.length;y++){\r\n if(!fields[y].value){\r\n return false;\r\n }\r\n }\r\n return true;\r\n}",
"function requireFields(args, fields, mandatoryFields){\n\n\t//check whether field is valid\n\tfor(var index in fields) {\n\n\t\tif(!args.hasOwnProperty(fields[index])) {\n\t\t\tLog('Invalid Field : ' + fields[index] + ' found.');\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfor(var index in mandatoryFields) {\n\t\tvar fieldName = mandatoryFields[index];\n\t\t//check whether mandatory field is not empty\n\t\tif(args.hasOwnProperty(fieldName)) {\n\t\t\tif(isArray(args[fieldName])) {\n\t\t\t\tif(args[fieldName].length == 0) {\n\t\t\t\t\tLog('mandatory field : ' + fields[index] + ' found with length zero.');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(isObject(args[fieldName])) {\n\t\t\t\tif(args[fieldName].keys().length == 0) {\n\t\t\t\t\tLog('mandatory field : ' + fields[index] + ' found with key size zero.');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}",
"allValid(){\n for (var key in this.fields) {\n if( this.fieldValid(key) === false ) {\n return false;\n }\n }\n return true;\n }",
"filled(fields) {\n for (let field of fields) {\n if (! truthy(this.form[field])) {\n return false\n }\n }\n\n return true\n }",
"allValid() {\n for (var key in this.fields) {\n if( this.fieldValid(key) === false ) {\n return false;\n }\n }\n return true;\n }",
"function setArray(publicAPI, model, fieldNames, size) {\n\t fieldNames.forEach(function (field) {\n\t publicAPI['set' + capitalize(field)] = function () {\n\t for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n\t args[_key2] = arguments[_key2];\n\t }\n\n\t if (model.deleted) {\n\t console.log('instance deleted - cannot call any method');\n\t return false;\n\t }\n\n\t var array = args;\n\t // allow an array passed as a single arg.\n\t if (array.length === 1 && Array.isArray(array[0])) {\n\t array = array[0];\n\t }\n\n\t if (array.length !== size) {\n\t throw new RangeError('Invalid number of values for array setter');\n\t }\n\t var changeDetected = false;\n\t model[field].forEach(function (item, index) {\n\t if (item !== array[index]) {\n\t if (changeDetected) {\n\t return;\n\t }\n\t changeDetected = true;\n\t }\n\t });\n\n\t if (changeDetected) {\n\t model[field] = [].concat(array);\n\t publicAPI.modified();\n\t }\n\t return true;\n\t };\n\t });\n\t}",
"static checkIsInsertable(obj) {\n // check all required fields are present\n const required = this.fields.filter((f) => f.required === true);\n const missing = required.find((f) => !(f.name in obj));\n if (missing) throw new DbErrorBadRequest(`missing field ${missing.name}`);\n return true;\n }",
"validateAll () {\n for (let fieldID of Object.keys(this.fields)) {\n this.fields[fieldID].validate()\n }\n }",
"function chmIsAllEmpty(arrFields,msg)\r\n {\r\n // set this flag to true if you want this function to validate\r\n var bValidate = true; \r\n var len = arrFields.length;\r\n var iIndex = 0;\r\n\r\n if(!bValidate)\r\n {\r\n return false;\r\n }\r\n\r\n for(iIndex = 0; iIndex < len; iIndex++)\r\n {\r\n if(eval(arrFields[iIndex]))\r\n {\r\n if(!isEmpty(eval(arrFields[iIndex])))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n alert(msg);\r\n return true;\r\n }",
"function has_all_of_attributes(model) {\n\t\treturn _.isObject(model) && has_all_of_keys.apply(null, construct(model.attributes, _.rest(arguments)));\n }",
"function someFilled(fields){\r\n let filledOnes = [];\r\n for(let z=0;z<fields.length;z++){\r\n if(fields[z].value) filledOnes.push(fields[z]);\r\n }\r\n if(filledOnes.length > 0 && filledOnes.length < fields.length){\r\n return true;\r\n }\r\n return false;\r\n}",
"function missingFields(fields){\n let isMissing = false\n fields.forEach(field => {\n if(!field){\n isMissing = true\n }\n })\n return isMissing\n }",
"validateAllDirty () {\n for (let fieldID of Object.keys(this.fields)) {\n let field = this.fields[fieldID]\n\n if (field.dirty) {\n field.validate()\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
share across calls. Convert any css string to 4 element Uint8ClampedArray TypedArray. If you need a JavaScript Array, use `new Array(...TypedArray)` | stringToUint8s (string) {
this.sharedCtx1x1.clearRect(0, 0, 1, 1)
this.sharedCtx1x1.fillStyle = string
this.sharedCtx1x1.fillRect(0, 0, 1, 1)
return this.sharedCtx1x1.getImageData(0, 0, 1, 1).data
} | [
"setCss (string) {\n return this.setColor(...Color.stringToUint8s(string))\n }",
"function convertUint8ArrayToArray(data) {\n return [...data];\n}",
"function DOMtoArray(string) { \n\tvar strLen = string.length;\n\t// break off the array enclosures '[' & ']'\n\tvar strEdit = string.slice(1,length-1);\n\t// slice the string from the DOM into a useable JS array\n\tvar output = strEdit.split(\",\");\n\treturn output;\n}",
"SetColorArray() {}",
"function setupTypedArray(name,fallback){// Check if TypedArray exists, and use if so.\nif(name in window){return window[name];}// Check if WebGLArray exists\nif(typeof window[fallback]===\"function\"){return window[fallback];}// Use Native JS array\nreturn function(obj){if(obj instanceof Array){return obj;}if(typeof obj===\"number\"){var arr=[];arr.length=obj;return arr;}};}",
"styleDecoder(){\n let style = this.style;\n let firstLayerStyles = style.split(\";\");\n var array = [];\n for(var i=0;i<firstLayerStyles.length;i++){\n let secondLayerStyles = firstLayerStyles[i].split(\":\");\n array.push([]);\n array[i].push(secondLayerStyles[0]);\n array[i].push(secondLayerStyles[1]);\n }\n return array;\n }",
"typedColor(r, g, b, a = 255) {\n if (g === undefined) return this.toTypedColor(r)\n const u8array = new Uint8ClampedArray([r, g, b, a])\n u8array.pixelArray = new Uint32Array(u8array.buffer) // one element array\n // Make this an instance of TypedColorProto\n Object.setPrototypeOf(u8array, TypedColorProto)\n return u8array\n }",
"function str2Uint8Array(input: string): Uint8Array {\n const encoder = new TextEncoder()\n const view = encoder.encode(input)\n return view\n}",
"GetColorArray() {}",
"function makeUint8Array(arg) {\n return new Uint8Array(arg);\n}",
"static fromArrayBuffer() {\n DishByteArray.checkForValue(this.value);\n this.value = Array.prototype.slice.call(new Uint8Array(this.value));\n }",
"function asUint32Array(arr) {\n return new Uint32Array(arr);\n}",
"ensureUint8Array(obj) {\n return obj instanceof Uint8Array\n ? obj\n : Uint8Array.from(obj);\n }",
"function stringToArrayBuffer(str) {\n if (isNullOrEmpty(str)) {\n return null;\n }\n var buffer = new ArrayBuffer(str.length);\n var bufferView = new Uint8Array(buffer);\n for (var i = 0, strLen = str.length; i < strLen; i++) {\n bufferView[i] = str.charCodeAt(i);\n }\n return bufferView;\n }",
"function stringToUint8Array(str) {\n return Uint8Array.from(buffer_1.Buffer.from(str));\n}",
"generateCodePointArray() {\n let index = 0;\n this.codePoints = [];\n while (index < this.str.length) {\n const num = JSUtils.toCodePoint(this.str, index);\n index += ((num > 0xFFFF) ? 2 : 1);\n this.codePoints.push(num);\n }\n }",
"function asUint32Array(arr) {\n return new Uint32Array(arr);\n }",
"function rgb_string_to_array(cs) {\n return cs.replace('rgb','').replace('(','').replace(')','').split(',').map(function(v) {\n return Number(v);\n })\n}",
"function TypedArray(arg1) {\nvar result;\n if (typeof arg1 === \"number\") {\n result = new Array(arg1);\n \n for (var i = 0; i < arg1; ++i)\n result[i] = 0;\n } else\n result = arg1.slice(0)\n\n result.subarray = subarray\n result.buffer = result\n result.byteLength = result.length\n result.set = set_\n\n if (typeof arg1 === \"object\" && arg1.buffer)\n result.buffer = arg1.buffer\n \n return result\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the json for this map | get map() {
return this._json
} | [
"\n ()\n {\n return (\n JSON\n .stringify( this.map_o )\n )\n }",
"function getJSON() {\n\t\treturn _json;\n\t}",
"toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }",
"getJson() {\n let data = {};\n data.name = this.settings.name;\n data.settings = this.settings;\n data.scripts = this.scripts;\n return data;\n }",
"function serializeMap(map) {\r\n\t\t\t\tif (map === null || map === undefined) return null;\r\n\r\n\t\t\t\tvar meta = {\r\n\t\t\t\t\tgeometries: {},\r\n\t\t\t\t\tmaterials: {},\r\n\t\t\t\t\ttextures: {},\r\n\t\t\t\t\timages: {}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar json = map.toJSON(meta);\r\n\t\t\t\tvar images = extractFromCache(meta.images);\r\n\t\t\t\tif (images.length > 0) json.images = images;\r\n\t\t\t\tjson.sourceFile = map.sourceFile;\r\n\r\n\t\t\t\treturn json;\r\n\t\t\t}",
"function serializeMap(map) {\n\t\t\t\tif (map === null || map === undefined) return null;\n\n\t\t\t\tvar meta = {\n\t\t\t\t\tgeometries: {},\n\t\t\t\t\tmaterials: {},\n\t\t\t\t\ttextures: {},\n\t\t\t\t\timages: {}\n\t\t\t\t};\n\n\t\t\t\tvar json = map.toJSON(meta);\n\t\t\t\tvar images = extractFromCache(meta.images);\n\t\t\t\tif (images.length > 0) json.images = images;\n\t\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\t\treturn json;\n\t\t\t}",
"get geoJSON(){\n return this.featureCollection(this.entries);\n }",
"function serializeMap( map ) {\n\n\t\t\tif ( map === null || map === undefined ) return null;\n\n\t\t\tconst meta = {\n\t\t\t\tgeometries: {},\n\t\t\t\tmaterials: {},\n\t\t\t\ttextures: {},\n\t\t\t\timages: {}\n\t\t\t};\n\n\t\t\tconst json = map.toJSON( meta );\n\t\t\tconst images = extractFromCache( meta.images );\n\t\t\tif ( images.length > 0 ) json.images = images;\n\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\treturn json;\n\n\t\t}",
"function getJson() {\n var out = {};\n var lt = getProp('lighttable');\n var info = {\n datetime : new Date()\n }\n out = {\n info : info,\n images : lt\n\n }\n var json = JSON.stringify(out);\n return json;\n }",
"function getJSON() {\n\treturn JSONdata;\n}",
"function serializeMap(map) {\n\t if (map === null || map === undefined) return null;\n\t var meta = {\n\t geometries: {},\n\t materials: {},\n\t textures: {},\n\t images: {}\n\t };\n\t var json = map.toJSON(meta);\n\t var images = extractFromCache(meta.images);\n\t if (images.length > 0) json.images = images;\n\t json.sourceFile = map.sourceFile;\n\t return json;\n\t } // Note: The function 'extractFromCache' is copied from Object3D.toJSON()",
"get _json() {\n const json = {\n policyName: this.policyName,\n definitionName: VersionPolicyDefinitionName[this.definitionName]\n };\n if (this.lockedMajor !== undefined) {\n json.lockedMajor = this.lockedMajor;\n }\n return json;\n }",
"function serializeMap(map) {\n if (map === null || map === undefined) return null;\n\n var meta = {\n geometries: {},\n materials: {},\n textures: {},\n images: {}\n };\n\n var json = map.toJSON(meta);\n var images = extractFromCache(meta.images);\n if (images.length > 0) json.images = images;\n json.sourceFile = map.sourceFile;\n\n return json;\n }",
"getJSONString() {\n var obj = {\n 'templateinfo' : this.templateinfo,\n 'settings' : this.settings,\n 'data' : this.data\n };\n return JSON.stringify(obj);\n }",
"toJSON() {\n return {\n type: \"Point\",\n coordinates: [this.longitude, this.latitude],\n crs: { type: \"name\", properties: { name: WorldGeodeticSystem1984 } }\n };\n }",
"function getMap() {\r\n return map;\r\n }",
"function displayJson() {\n console.log(JSON.stringify(selectedMaps));\n}",
"function items_geojson(){\n\t\treturn [{\n\t\t \"isEnabled\" : true,\n\t\t \"name\": name, \n\t\t \"type\": format['type'],\n\t\t \"url\": resource_url,\n\t\t}]\n\t }",
"get json() {\n // TODO return each service as something that can be parsed on the other side\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if current url is in the neverCacheUrls list | function checkNeverCacheList(url) {
if ( this.match(url) ) {
return false;
}
return true;
} | [
"function checkNeverCacheList(url) {\n if (this.match(url)) {\n return false;\n }\n return true;\n}",
"function check_never_cache_urls(url) {\r\n\tif (this.match(url)) {\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}",
"function checkExcludeURLStatus() {\n var excludeStatus = false,\n urls = settings.excludeURL,\n len = urls.length,\n i = -1,\n href = document.referrer;\n\n while (++i < len && !excludeStatus) {\n if (url_check_equals(urls[i], href)) {\n excludeStatus = true;\n }\n }\n return excludeStatus;\n }",
"inCache(url) {\n if ((Date.now() - this.cache[this.hashValue(url)]) > (this.cacheTimeoutMinutes * 60 * 1000)) {\n return false;\n }\n if (this.cache[this.hashValue(url)]) {\n return true;\n }\n return false;\n }",
"function isCached(url) {\n return requestRedditJsonCache.has(url);\n}",
"function isURLCrawled(url) {\r\n return urlHistory.has(url);\r\n }",
"function isUrlListed(url) {\n return appSettings.appendAuthTokenUrls && \n _.some(appSettings.appendAuthTokenUrls, function (listedUrl) { return _.startsWith(url, listedUrl) });\n }",
"function shouldBlock(req) {\r\n var stor = browser.storage.local.get(null);\r\n return stor.then((blacklist) => {\r\n console.log(\"Blacklist: \" + Object.keys(blacklist));\r\n for(var key in blacklist) {\r\n //console.log(\"Key \" + key + \" value \" + result[key]);\r\n if(req.url.indexOf(key) != -1) {\r\n console.log(\"Blocking \" + req.type + \" at \" + req.url + \" as it contains \\\"\" + key + \"\\\"\");\r\n return true;\r\n }\r\n }\r\n return false;\r\n }, onError);\r\n\r\n}",
"function isOnTheList(url) {\n for (i = 0; i < sites.length; i++) {\n var site = sites[i];\n if (url.indexOf(site) > -1) {\n return true;\n }\n }\n return false;\n}",
"async function checkIfUrlMatches() {\n const storageKey = \"scrollPercentageUrls\";\n let data = await getStorageData(storageKey);\n\n const urls = data[storageKey];\n\n if(!urls) {\n return;\n }\n\n for (const url of urls) {\n if (window.location.href.includes(url)) {\n addScript(\"extension.js\");\n return;\n }\n }\n }",
"canAllowUrl(url) {\n if (this._exclude !== null && [...this._exclude].filter(pattern => matchesGlob(pattern, url)).length) {\n return false;\n }\n\n if (this._include !== null && [...this._include].filter(pattern => matchesGlob(pattern, url)).length === 0) {\n return false;\n }\n\n return true;\n }",
"function isUrlUniqueInUrlsList(url, urlList){\n let counter = -1\n urlList.forEach(item => {\n if(item.includes(url)){\n counter++\n }\n })\n return !counter\n }",
"checkUrl() {\n // turned this off for now... Check Tags runs EVERYWHERE...\n var i;\n var found = false;\n for (i in Mavelet.config.url) {\n if (document.URL.match(Mavelet.config.url[i])) {\n //Mavelet.hazUrl[i]();\n //found = true;\n }\n }\n return found;\n }",
"static isPreviouslyScraped(url) {\n const dirAndFilename = Page.getDirAndFilenameFromURI(url.path || \"\");\n const writeOutPath = Page.getWriteOutPath(dirAndFilename);\n return fs.existsSync(writeOutPath);\n }",
"function checkBlock(url) {\n for (let i = 0; i < locallist.length; i++) {\n if (url.indexOf(locallist[i]) != -1) {\n return true;\n }\n }\n return false;\n}",
"function isRepeat(url, list) {\n var existingList = []\n\n for (var i = 0; i < list.length; i++) { //Set up the list of existing url's\n if (!existingList.includes(list[i].url)) {\n existingList.push(list[i].url)\n }\n }\n\n if (existingList.includes(url)) {\n return true;\n }\n else {\n return false;\n }\n}",
"repeatedUrl(){\n let link = this.list.listContent.links;\n for(let i = 0; i < link.length; i++){\n if(this.url === link[i].url){\n return true;\n }\n }\n return false;\n }",
"function isBannedURL() {\n // Header(s) removed so that we can find the correct period to substring to\n // in order to collect only the domain name\n let url = window.location.href;\n url = url.toLowerCase();\n\t\n // O(1) and whO(l)esome\n if (!url.includes('fightthenewdrug') && !url.includes('github') ) {\n if (pornMap[url]) {\n window.stop();\n return true;\n }\n }\n\n// Old method of detection\n// if (!url.includes('fightthenewdrug') && !url.includes('github') ) {\n// // O(n) worst case feels bad but whO(l)esome porn-checker feels good\n// // $$$$$ B R U T E F O R C E $$$$$\n// for (let i = 0; i < bannedLinks.length; i++) {\n// if (url.includes(bannedLinks[i].toLowerCase())) {\n// // GTFOOOO\n// return true;\n// }\n// }\n// }\n\n // Inconclusive\n return false;\n}",
"async isBlockable() {\n if (!this.url.includes('.')) {\n return false\n }\n\n return new Promise((resolve) => {\n chrome.storage.local.get(['redirectUrl'], (items) => {\n var redirectUrl = items.redirectUrl || 'theguardian.com'\n this.url.includes(redirectUrl) ? resolve(false) : resolve(true)\n })\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes the dead units (occurs at the end of the update function) | removeDead(){
for(var i = 0; i < this.units.length; i++){
if(this.units[i].isDead()){
this.units[i].unitAnimations("Die");
//used to play the death animation for 4 seconds
var deathEvent = this.game.time.addEvent({ delay: 3000, callback: this.destroyUnit,
callbackScope: this, loop: false, args: [this.units[i]]});
this.units.splice(i, 1);
this.unitsAmount--;
}
}
for(var i = 0; i < this.buildings.length; i++){
let building = this.buildings[i];
if(building.isDead()){
building.destroy();
building.bar.destroy();
this.buildings.splice(i,1);
this.buildingsAmount--;
}
}
} | [
"unstageUnit(){\n this.image.parent.removeChild(this.image);\n this.healthBar.parent.removeChild(this.healthBar);\n }",
"removeAllSpawnables(){\n\n let currentSpawnables = this.spawnables.children;\n let amntCurrentSpawnables = currentSpawnables.entries.length;\n\n // done manually to as iterate will miss some blocks off\n for(var currentSpawnableNum = 0; currentSpawnableNum < amntCurrentSpawnables; currentSpawnableNum++){\n let currentSpawnable = currentSpawnables.get(currentSpawnableNum);\n currentSpawnable.destroy();\n }\n\n // duplicate the array instead of passing by reference\n availableBlocks = JSON.parse(JSON.stringify( levelBaseBlocks ));\n this.munchkinSpawner.currentMunchkins = 0;\n // add to the calculation of score\n MainGameScene.gameStats.addToCount(\"resets\");\n this.updateUI()\n }",
"function ResetUnits(){\n\tfor(var i = 0; i < TotalUnitCount; i++){\n\t\tunits[i].GetComponent(UnitControl).hasMoved = false;\n\t}\n\tUnitsMoved = 0;\n}",
"removeUnit (unit) \n {\n this.units.delete (unit.unitId);\n unit.unsetLeader ();\n \n this.updateBalloonInfo ();\n }",
"function clearDead(){\n for(var i in Memory.creeps) {\n if(!Game.creeps[i]) {\n var job = Memory.creeps[i].role;\n var roomName = Memory.creeps[i].room;\n if(roomName){\n modUtil.decrementCreepNum(job,roomName);\n modSpawning.enqueuByJob(job,roomName,false);\n }\n delete Memory.creeps[i];\n console.log(\"Removed creep \"+i+\" (a \"+job+\") from memory\");\n }\n }\n}",
"unload() {\n\t\tif (this._current_position === 'up1' && this.is_full()) {\n\t\t\tdo{\n\t\t\t\tlet current_material_delivered = this._current_materials.pop();\n\t\t\t\tif (current_material_delivered !== undefined) {\n\t\t\t\t\tthis._system.deliver_material(current_material_delivered);\n\t\t\t\t}\n\t\t\t} while(this._current_materials.length > 0);\n\t\t}\n\t}",
"function killDeadUnits() {\r\n if (playerTeamGlobal[0].hp <= 0) {\r\n killUnit(playerTeamGlobal[0]);\r\n }\r\n if (playerTeamGlobal[1].hp <= 0) {\r\n killUnit(playerTeamGlobal[1]);\r\n }\r\n if (playerTeamGlobal[2].hp <= 0) {\r\n killUnit(playerTeamGlobal[2]);\r\n }\r\n if (enemyTeamGlobal[0].hp <= 0) {\r\n killUnit(enemyTeamGlobal[0]);\r\n }\r\n if (enemyTeamGlobal[1].hp <= 0) {\r\n killUnit(enemyTeamGlobal[1]);\r\n }\r\n if (enemyTeamGlobal[2].hp <= 0) {\r\n killUnit(enemyTeamGlobal[2]);\r\n }\r\n}",
"function removeKilledElems() {\r\n elements.forEach(function(element) {\r\n if (!element.alive) {\r\n gamePanel.setElementPosition(element, -1, -1);\r\n }\r\n });\r\n}",
"clearLocalUnits() {\n\t\tconst gameObjectsService = this.scene.gameObjectsService;\n\t\tconst player = this.scene.getPlayer();\n\n\t\t// Clear local gameObjects to replace them by network units (except player)\n\t\tgameObjectsService.getUnits().forEach((unit) => {\n\t\t\tif (!unit.params.fromNetwork && unit !== player) {\n\t\t\t\tgameObjectsService.destroyGameObject(unit);\n\t\t\t}\n\t\t});\n\t}",
"function removeHealth(){\n for (let index = 0; index < healthNumber; index++) {\n scene.remove(scene.getObjectByName(\"health\"+String(index)) )\n }\ndelete healthBoxes;\nhealthBoxes = [];\n}",
"function Remove(unit : GameObject){\n\tif(unit.GetComponent(UnitControl).hasMoved){\n\t\tUnitsMoved--;\n\t}\n\tvar removalIndex : int;\n\tfor(var i = 0; i < TotalUnitCount; i++){\n\t\tif(units[i].Equals(unit)){\n\t\t\tremovalIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t//move all units after the deleted one up a space\n\tfor(var j = removalIndex; j < TotalUnitCount; j++){\n\t\tunits[j] = units[j+1];\n\t}\n\t\n\tTotalUnitCount --;\n}",
"function key_unit_disband()\n{\n var funits = get_units_in_focus();\n for (var i = 0; i < funits.length; i++) {\n var punit = funits[i]; \n var packet = {\"type\" : packet_unit_disband, \"unit_id\" : punit['id'] };\n send_request (JSON.stringify(packet));\n\n /* Also remove unit immediately in client, to ensure it is removed. */\n clear_tile_unit(punit);\n client_remove_unit(punit);\n\n } \n}",
"removeDeadPlayer (arg1) {\n\t\t// arg1 = unit\n\t\tif (arg1.team == 0) {\n\t\t\tvar index = this.redUnitsAlive.indexOf(arg1);\n\t\t\tif (index > -1) {\n\t\t\t\tthis.redUnitsAlive.splice(index, 1);\n\t\t\t}\n\t\t}\n\t\tif (arg1.team == 1) {\n\t\t\tvar index = this.blueUnitsAlive.indexOf(arg1);\n\t\t\tif (index > -1) {\n\t\t\t\tthis.blueUnitsAlive.splice(index, 1);\n\t\t\t}\n\t\t}\n\t}",
"removeKilledGems() {\n\n var obj = this;\n this.gems.forEach(function (gem) {\n if (!gem.alive) {\n obj.setGemPos(gem, -1, -1);\n }\n });\n\n }",
"cleanUp() {\n // clear activeEnemies\n this.activeEnemies.forEach(function(enemy) {\n enemy.cleanUp();\n });\n // clear active players\n this.activeObjects.forEach(function(object) {\n object.cleanUp();\n });\n // stop game loop\n this.animation.forEach(function(frame,index) {\n cancelAnimationFrame(frame);\n });\n }",
"function CafeUngagPlayer() {\n\tInventoryRemove(Player, \"ItemMouth\");\n\tInventoryRemove(Player, \"ItemMouth2\");\n\tInventoryRemove(Player, \"ItemMouth3\");\n\tInventoryRemove(Player, \"ItemHead\");\n\tInventoryRemove(Player, \"ItemHood\");\n}",
"function depopulateEnemies(){\n allEnemies = [];\n}",
"pruneDead() {\n\t\tfor (var actor of this.actors) {\n\t\t\tif (! actor.dead) { continue; }\n\t\t\t// if (actor.className == 'Ship') {this.view.boom(actor.x, actor.y, actor.type.shield);}\n\t\t\tthis.actors.splice( this.actors.indexOf(actor), 1 );\n\t\t}\n\t\tfor (var proj of this.projs) {\n\t\t\tif (! proj.dead) { continue; }\n\t\t\t// this.view.boom(proj.x, proj.y, proj.type.damage);\n\t\t\tthis.projs.splice( this.projs.indexOf(proj), 1 );\n\t\t}\n\t}",
"update() {\n let toDelete = [];\n for (let i=0; i<this.items.length; i++) {\n this.items[i].updatePosition();\n this.items[i].setVisibility(!this.inventory.isVisible() && this._visible);\n if (this.items[i].getDistanceTo(this.player.x, this.player.y) < 60) {\n if (this.inventory.addItem(this.items[i].item)) {\n this.items[i].destroy();\n toDelete.push(i);\n }\n }\n }\n toDelete.sort().reverse();\n for (let index of toDelete) {\n this.items.splice(index, 1);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessing these APIs directly under context.foundation is deprecated. | function _registerLegacyAPIs() {
context.foundation = {
makeLogger,
startWorkers,
getConnection,
getEventEmitter: getSystemEvents
};
} | [
"_mapDeprecatedFunctionality(){\n\t\t//all previously deprecated functionality removed in the 5.0 release\n\t}",
"get deprecated() {\n return false;\n }",
"sendExperiences () {\n console.log('deprecated')\n }",
"function UContext() {\n }",
"isVertexArrayObjectSupported() {\n console.warn('deprecated : please use through createContext.');\n return this.defaultContext.isVertexArrayObjectSupported();\n }",
"server_features() {\n return this.request('server.features', []);\n }",
"function DASFeature() {\n}",
"hasSupport() {\n return ( window && ( 'Notification' in window ) );\n }",
"function inspect(){\n var supportDOM2Core = document.implementation.hasFeature(\"Core\", \"2.0\");\n var supperDOM2Views = document.implementation.hasFeature(\"Views\", \"2.0\");\n var supportDOM2XML = document.implementation.hasFeature(\"XML\", 2.0);\n var supportDOM2CSS2 = document.implementation.hasFeature(\"CSS2\", \"2.0\");\n console.log(\"supportDOM2Core: \" + supportDOM2Core);\n console.log(\"supperDOM2Views: \" + supperDOM2Views);\n console.log(\"supportDOM2XML: \" + supportDOM2XML);\n console.log(\"supportDOM2CSS2: \" + supportDOM2CSS2);\n}",
"_buildDeprecatedContext(module, context) {\n var deprecatedContext = Object.create(context);\n\n var keysForDeprecation = Object.keys(module);\n\n for (var i = 0, l = keysForDeprecation.length; i < l; i++) {\n this._proxyDeprecation(module, deprecatedContext, keysForDeprecation[i]);\n }\n\n return deprecatedContext;\n }",
"function DASFeature() {}",
"function PlatformTools() {\n }",
"getFeature(feature, version) {\n throw new Error(\"This DOM method is not implemented.\");\n }",
"onContextNotAvailable(){}",
"static GetGraphicsAPIs() {}",
"componentDidMount() {\n $(document).foundation();\n }",
"function DeprecatedWarning() {\n}",
"static get apiCompatibilityLevel() {}",
"function showContext() {\n addLoader();\n // send API request\n smxProxy.sendRequest(\"get-context\", null, \"onContext\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompts need at least two arguments passed in to work: theme name and Component name. Without those we can't create a basic component. | prompting() {
// If we DO have both the theme name _and_ component name passed
// as arguments we can skip all the prompts.
if (this.options.themeName && this.options.name) {
return;
}
let defaultThemeName = '';
try {
// See if package.json exists.
fs.accessSync(this.destinationPath('package.json'), fs.constants.R_OK);
// If it does, read it and use the name as our default
// theme machine name.
const pkg = JSON.parse(
fs.readFileSync(
path.resolve(this.destinationPath('package.json')), 'utf8'
)
);
defaultThemeName = pkg.name;
}
// If it doesn't, let the user know we can't continue. We need to run from
// the theme root.
catch (err) {
assert.fail(
`
🚨 ${chalk.red(this.destinationPath('package.json'))} ${chalk.red('is missing')}.
${chalk.blue('Make sure you\'re running this command from your theme root.')}`
);
}
let prompts = [{
name: 'themeNameMachine',
message: 'What is your theme\'s machine name? EX: unicorn_theme',
default: defaultThemeName
},
{
name: 'name',
message: 'What should we name your component? EX: Hero',
default: 'Hero'
},
{
name: 'includeJSBehavior',
type: 'confirm',
message: 'Would you like to include a JavaScript Behavior file?',
default: false
}];
return this.prompt(prompts).then(function (props) {
// Use the user provided theme machine name.
this.themeNameMachine = _.snakeCase(props.themeNameMachine);
// Use the component name provided.
this.componentName.raw = props.name;
// Create a dashed version of the layout name.
this.componentName.dashed = _.kebabCase(props.name);
// See if we need to include a JS behavior file.
this.includeJS = props.includeJSBehavior;
// To access props later use this.props.someAnswer;
this.props = props;
}.bind(this));
} | [
"function customTheme(cb) {\n prompt.start();\n\n // Prompt and get user input then display those data in console.\n prompt.get(theme_name_prompt, function (err, result) {\n if (err) {\n console.log(err);\n cb();\n return 1;\n \n } else {\n // Get user input from result object.\n name = result.theme_name;\n let message = \" Creating new theme : \" + name;\n\n // Display user input in console log.\n console.log(message);\n\n const hugo = spawn(\"hugo\", ['new', 'theme', name]);\n // Log message from Bugo\n hugo.stdout.on('data', (data) => {\n console.log(`Bugo: ${data}`);\n });\n\n // Log Errors\n hugo.stderr.on('data', (data) => {\n console.log(`Bugo Error: ${data}`);\n });\n\n // Log Exit\n hugo.on('close', (code) => {\n console.log(`Bugo exited with code ${code}`);\n // copy base files over to new build\n copyAssets(cb);\n });\n }\n });\n}",
"_prompt() {\n\n let _this = this,\n overrides = {};\n\n if (!_this.S.config.interactive) return BbPromise.resolve();\n\n ['module', 'function'].forEach(memberVarKey => {\n overrides[memberVarKey] = _this.evt.options[memberVarKey];\n });\n\n let prompts = {\n properties: {\n module: {\n default: 'resource',\n description: 'Enter a name for your new module: '.yellow,\n message: 'Module name must contain only letters, numbers, hyphens, or underscores.',\n required: true,\n conform: function(moduleName) {\n return SUtils.isModuleNameValid(moduleName);\n }\n },\n function: {\n default: 'show',\n description: 'Enter a function name for your new module: '.yellow,\n message: 'Function name must contain only letters, numbers, hyphens, or underscores.',\n required: true,\n conform: function(functionName) {\n return SUtils.isFunctionNameValid(functionName);\n }\n }\n }\n };\n\n return _this.cliPromptInput(prompts, overrides)\n .then(function(answers) {\n _this.evt.options.module = answers.module;\n _this.evt.options.function = answers.function;\n })\n .then(function() {\n return _this.cliPromptSelectComponent('Select a component to create your module in: ', _this.evt.options.component)\n .then(component => {\n _this.evt.options.component = component;\n BbPromise.resolve();\n });\n });\n }",
"function createPublicComponent() {\n var prompt = {\n name: ' name: ',\n repo: ' repo (username/project): ',\n desc: ' description: ',\n author: ' author: '\n };\n program.prompt(prompt, function(obj){\n console.log();\n conf.name = obj.name;\n conf.repo = obj.repo;\n conf.author = obj.author;\n conf.description = obj.desc;\n conf.license = \"MIT\";\n createDirectory();\n createSkeleton();\n saveConfig(); \n process.exit();\n });\n}",
"createDialog(title, text, argumentName) {\n return new FrontendDialog(title, text, argumentName);\n }",
"function constructColorPaletteBox(passColorPalette = null) {\n //Create the Color Palette Box <div> itself \n var colorPaletteBox = document.createElement(\"div\");\n colorPaletteBox.classList.add(\"color-palette-box\");\n\n var colorPaletteBoxHeadHolder = document.createElement(\"div\");\n colorPaletteBoxHeadHolder.classList.add(\"color-palette-box-head-holder\");\n\n //Creates the Color Palette Box Title Text <input> \n var colorPaletteBoxTitle = document.createElement(\"input\");\n colorPaletteBoxTitle.classList.add(\"color-palette-name\");\n colorPaletteBoxTitle.type = \"text\";\n colorPaletteBoxTitle.placeholder = \"New Palette\";\n if(passColorPalette != null && passColorPalette.name != undefined) {\n colorPaletteBoxTitle.value = passColorPalette.name;\n }\n\n var colorPaletteCheckBox = document.createElement(\"input\");\n colorPaletteCheckBox.classList.add(\"color-palette-check-box\");\n colorPaletteCheckBox.type = \"checkbox\";\n\n\n colorPaletteBoxHeadHolder.appendChild(colorPaletteBoxTitle);\n colorPaletteBoxHeadHolder.appendChild(colorPaletteCheckBox);\n\n //Creates the Color Palette Box Color Grid <div>\n var colorPaletteGrid = document.createElement(\"div\");\n colorPaletteGrid.classList.add(\"color-palette-grid\");\n\n //Adds the color buttons to the color palettes based on the project console color palette limit \n for (var i = 0; i < workingProject.projectConsole.colorPaletteLimit; i++) {\n\n //Element creation for each color of the color Palette \n var colorButtonHolder = document.createElement(\"div\");\n var colorButton = document.createElement(\"button\");\n var colorButtonBitLabel = document.createElement(\"p\");\n\n //Class Assigning \n colorButtonHolder.classList.add(\"color-button-holder\");\n colorButton.classList.add(\"color-button\");\n colorButtonBitLabel.classList.add(\"color-button-bit-label\");\n\n //If a color is passed in (i.e. a project was opened), it would set the buttons color the the appropriate color \n if (passColorPalette != null) {\n colorButton.style.backgroundColor = passColorPalette.colors[i].rgbColorString;\n } else {\n colorButton.style.backgroundColor = \"rgb(255, 255, 255)\";\n }\n\n colorButtonBitLabel.innerHTML = colorPalette2BitStrings[i];\n\n colorButtonHolder.appendChild(colorButton);\n colorButtonHolder.appendChild(colorButtonBitLabel);\n\n colorPaletteGrid.appendChild(colorButtonHolder);\n }\n\n //Adds the children to the Color Palette Box <div> \n colorPaletteBox.appendChild(colorPaletteBoxHeadHolder);\n colorPaletteBox.appendChild(colorPaletteGrid);\n colorPaletteBox.setAttribute(\"draggable\", \"true\");\n\n //Returns the Color Palette Box \n return colorPaletteBox;\n}",
"uicomponent(){\n if (this.options.createUicomponent !== undefined) {\n return true;\n }\n \n const prompt = [{\n type: 'confirm',\n name: 'createUicomponent',\n message: 'Would you like to create uicomponent(s)?',\n }];\n \n return this.prompt(prompt).then((response) => {\n this.options.createUicomponent = response.createUicomponent;\n });\n }",
"static createPrompt(tools, args) {\n const { prefix = prompt_js_1.PREFIX, suffix = prompt_js_1.SUFFIX, humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE, } = args ?? {};\n const toolStrings = tools\n .map((tool) => `${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n const template = [prefix, toolStrings, prompt_js_1.FORMAT_INSTRUCTIONS, suffix].join(\"\\n\\n\");\n const messages = [\n chat_js_1.SystemMessagePromptTemplate.fromTemplate(template),\n chat_js_1.HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),\n ];\n return chat_js_1.ChatPromptTemplate.fromPromptMessages(messages);\n }",
"_prompt() {\n\n let _this = this,\n overrides = {};\n\n // If non-interactive, skip\n if (!S.config.interactive || _this.evt.options.name) return BbPromise.resolve();\n\n let prompts = {\n properties: {\n name: {\n description: 'Enter a new plugin name: '.yellow,\n message: 'Plugin name must contain only letters, numbers, hyphens, or underscores.',\n required: true,\n conform: (pluginName) => {\n return S.classes.Plugin.validateName(pluginName);\n }\n }\n }\n };\n\n return _this.cliPromptInput(prompts, overrides)\n .then(function(answers) {\n _this.evt.options.name = answers.name;\n });\n }",
"function prepareTheme(themeName) {\n console.log(`Start design for ${themeName} theme`);\n console.log(\"Complete design\");\n}",
"function ShowCustomDialog() {\n ShowDialogBox('Welcome to RailsBit.com',\n 'Congratulations! You are about to change your life by becoming a web developer. ' +\n 'We are here to keep you motivated and guide you through this Journey.' +\n ' This page is a \\'userpanel\\' page to track your progress and access your tutorials and courses \\r\\n' +\n ', Lets Begin!',\n 'Start Your Journey!','', 'GoToAssetList',null);\n}",
"promptCustomConnectorInfo() {\n if (this.shouldExit()) return;\n if (this.artifactInfo.connector !== 'other') {\n debug('custom connector option was not selected');\n return;\n } else {\n debug('prompting for custom connector');\n const prompts = [\n {\n name: 'customConnector',\n message: \"Enter the connector's package name:\",\n validate: utils.validate,\n },\n ];\n\n return this.prompt(prompts).then(props => {\n this.artifactInfo.connector = props.customConnector;\n return props;\n });\n }\n }",
"_prompt() {\n\n let _this = this,\n overrides = {};\n\n if (!_this.S.config.interactive) return BbPromise.resolve();\n\n ['function'].forEach(memberVarKey => {\n overrides[memberVarKey] = _this.evt.options[memberVarKey];\n });\n\n let prompts = {\n properties: {\n function: {\n description: 'Enter a new function name: '.yellow,\n message: 'Function name must contain only letters, numbers, hyphens, or underscores.',\n required: true,\n conform: function(functionName) {\n return SUtils.isFunctionNameValid(functionName);\n }\n }\n }\n };\n\n return _this.cliPromptInput(prompts, overrides)\n .then(function(answers) {\n _this.evt.options.function = answers.function;\n })\n .then(function() {\n return _this.cliPromptSelectComponent('Select a component to create your function in: ', _this.evt.options.component)\n .then(component => {\n _this.evt.options.component = component;\n BbPromise.resolve();\n });\n })\n .then(function() {\n return _this.cliPromptSelectModule('Select a component module to create your function in: ', _this.evt.options.module, _this.evt.options.component)\n .then(module => {\n _this.evt.options.module = module;\n BbPromise.resolve();\n });\n });\n }",
"validateTheme(newTheme) {\n if (!newTheme) {\n return;\n }\n if (themeNames.includes(newTheme)) {\n this.buttonTheme = newTheme;\n }\n else {\n console.warn(`Theme \"${newTheme}\" is not valid`);\n }\n }",
"prompting() {\n const prompts = [{\n type : 'input',\n name : 'name',\n message : 'Your project name',\n default : this.options.appname // Default to current folder name\n }, {\n type : 'list',\n name : 'controlSystemType',\n message : 'Which control system would you like to target?',\n choices: [{\n name: 'Crestron',\n value: 'Crestron'\n }, {\n name: 'AMX',\n value: 'AMX'\n }]\n },{\n type : 'confirm',\n name : 'dsp',\n message : 'Does your system include a DSP?'\n }];\n\n return this.prompt(prompts).then(answers => {\n this.appName = answers.name;\n this.controlSystem = answers.controlSystemType;\n this.hasDsp = answers.dsp;\n });\n }",
"function makePWDialogBox(guid)\n\t{\n\t\t/* */\n\t\tvar dialogTemplateHTML = pwDialogContent({ \n\t\t\t'guid': guid \n\t\t});\n\t\tvar dialogContext = {\n\t\t\t//title: 'asdf', \n\t\t\tdClass: 'pw-dialog',\n\t\t\tbody: dialogTemplateHTML\n\t\t};\n\t\trenderer.append('module-dialog', dialogContext, {}, $('body'), function(attachReturn) {\n\t\t\tconsole.log('pw dialog rendered');\n\t\t});\n\t\t/* */\n\t}",
"function setupTheme() {\n var theme = interactive.theme;\n if (arrays.isArray(theme)) {\n // [\"a\", \"b\"] => \"lab-theme-a lab-theme-b\"\n theme = theme.map(function(el) {\n return 'lab-theme-' + el;\n }).join(' ');\n } else if (theme) {\n theme = 'lab-theme-' + theme;\n } else {\n theme = '';\n }\n $interactiveContainer.alterClass('lab-theme-*', theme);\n }",
"function create(clean) {\n\n // Next need to find out what kind of widget the user needs.\n return prompt(clean).then(responses => {\n return buildSkeletonWidget(responses, clean)\n })\n}",
"createThemeOverrides() {\n const themeHeader = document.createElement(\"h2\");\n themeHeader.textContent = \"Event Theme Overrides: \";\n themeHeader.style.fontFamily = \"Rubik\";\n\n this.themeOverrideContainer.replaceChildren(\n themeHeader,\n this.createColorPicker(\n \"Background Color\",\n \"background\",\n this._config.customColors?.background ?? \"#FFFFFF\"\n ),\n this.createColorPicker(\n \"Primary Text Color\",\n \"textPrimary\",\n this._config.customColors?.textPrimary ?? \"#000000\"\n ),\n this.createColorPicker(\n \"Secondary Text Color\",\n \"textSecondary\",\n this._config.customColors?.textSecondary ?? \"#b8b8b8\"\n )\n );\n }",
"function createtheme(props) {\n // Disabled\n if (props.disabled) {\n return disabledTheme(props);\n }\n\n // Primary\n if (props.type === 'primary') {\n return primaryTheme(props);\n }\n\n // Success\n if (props.type === 'success') {\n return successTheme(props);\n }\n\n // Light\n if (props.type === 'light') {\n return lightTheme(props);\n }\n\n // Default\n return defaultTheme(props);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
react object inside the method, that will prepare the render to receive the json resource, after it's mounted. Therefore, it needs to define an empty attribute that will receive it. After the resource is received, the state will be updated in the render. in this case, the attribute will be an empty array called "players" in json sytax, (that's why the :). | componentDidMount(){ //will happen after render()
axios.get('http://192.168.15.12:9000/api/players').then(response => {
const players = response.data;
this.setState({players});
});
//axios will GET (http method such as post, put, etc)
//...this resource, a Json with an objects list.
//after the get, we'll use a fat arrow syntax with .then() method
//we'll call the response of this get "response".
//lets create a new variable "players" that will recieve only the data (body/payload),
//which is the json player list,
//and not the entire package (with status code, headers, etc).
// this. refers to this current file (Personlist.js), and setState updates the state that
//...already existed in the beginning, and contained an empty object - players.
//now that we have recieved our json player list and attributed it to players,
//we need to update our pre-existing state, and the render will be updated.
} | [
"renderPlayer() {\n return <Player\n information={this.player.info}\n nationalTeam={this.player.nationalTeam}\n age={this.player.age}\n name={this.player.name}\n playerID={this.player.id}\n currentTeam={this.player.currentTeam}\n />\n }",
"componentDidMount() {\n\n try {\n const playerJSON = localStorage.getItem('players');\n const players = JSON.parse(playerJSON);\n\n if (players) {\n this.setState(() => ({ players }));\n }\n } catch (e) {\n // No action required.\n }\n }",
"componentDidMount() {\n const token = this.getToken();\n axios\n .get('https://enigmatic-brook-88093.herokuapp.com/api/adv/init', token)\n .then(response => {\n this.setState(() => ({\n username: response.data['name'],\n title: response.data['title'],\n description: response.data['description'],\n players: response.data['players'],\n uuid: response.data['uuid'],\n color: colors[Math.floor(Math.random()*colors.length)]\n }))\n })\n .then(() => {\n var pusher = new Pusher('20fd2caaca38261dedb4', {\n cluster: 'us2'\n });\n var channel = pusher.subscribe(`p-channel-${this.state.uuid}`);\n channel.bind('broadcast', data => {\n this.setState({ broadcast: data.message });\n if (data.status === 'enter') {\n let copy = this.state.players.slice()\n copy.push(data.player)\n this.setState({ players: copy });\n } else if (data.status === 'exit') {\n let copy = this.state.players.slice()\n let index = copy.indexOf(data.player)\n copy.splice(index, 1)\n this.setState({ players: copy });\n }\n });\n }) \n .catch(error => {\n console.error('Server Error', error);\n });\n }",
"componentDidMount() {\n this.getPlayers();\n }",
"componentDidMount() {\n API.getplayer(this.props.match.params.id)\n .then(res => this.setState({ player: res.data }))\n .catch(err => console.log(err));\n }",
"renderPlayers() {\n let players = this.state.players.map((playerObject, index) => {\n return(<Player {...playerObject} key={index} />);\n });\n return players;\n }",
"componentDidMount() {\n $.getJSON('/api/v1/skills.json',\n (response) => {\n this.setState({ skills: response })\n });\n }",
"componentDidMount() {\n fetch('https://jsonplaceholder.typicode.com/users')\n .then(response => response.json())\n .then(users => this.setState({ monsters: users }));\n }",
"componentDidMount() {\n this._buildPlayer();\n }",
"componentDidMount() {\n this.apiCall(this.props.selectedGame);\n }",
"componentDidMount() {\n axios.get('/api/cardgames').then(result => {\n this.setState({\n //we're getting the data sent from server.js\n //this wraps the data in an object, then updates the state\n games: result.data\n })\n })\n }",
"fetchData() {\n const api_url = '/baseball/api/players/' + this.state.value;\n fetch(api_url)\n .then(response => response.json())\n .then(data => this.setState({data: data}));\n }",
"getInitialState() {\n return { skills: [] }\n }",
"componentDidMount() {\n fetch('http://localhost:4000/songs').then(response => {\n return response.json();\n }).then(songs => {\n this.setState({\n songs: songs\n });\n });\n }",
"componentDidMount() {\n this.setState({ loading: true });\n fetch(\"https://swapi.co/api/people/2\")\n .then(response => response.json())\n .then(data => {\n this.setState({\n loading: false,\n character: data\n });\n });\n }",
"renderPlayers() {\n /*si la collecion esta vacia, se dara un mensaje en la pagina por medio de la etiqueta <p>\n accede a la coleccion a traves de client/main.js:12:5 letplayer Y llama al let players por medio\n del this.props*/\n if (this.props.players.length === 0) {\n return (\n <div className=\"item\">\n {\" \"}\n <p className=\"item__message\">Agrega un jugador para empezar</p>\n </div>\n );\n } else {\n /* si no esta vacia, simplemente va a MAPEAR los documentos de la coleccion, tomando como parametro\n player, que sera cada documento, luego coje varios atributos de este documento para poder visualizar\n en la pagina, ES CLAVE la key que es el que nos permite borrar un elemento especifico,\n asi tengan igual nombre, la id es unica y es dada por mongo*/\n return this.props.players.map(player => {\n /*Usamos el componente Player, que lo que hace es recibir player._id y player,\n para dar a visualizar a la pagina*/\n return <Player key={player._id} player={player} />;\n });\n }\n }",
"componentDidMount() {\n API.getgame(this.props.match.params.id)\n .then(res => this.setState({ game: res.data }))\n .catch(err => console.log(err));\n }",
"render () {\n return (\n <SongsList songs={this.state.songs}/>\n )\n }",
"componentDidMount() {\n API.getGame(this.props.match.params.id)\n .then(res => this.setState({ game: res.data }))\n .catch(err => console.log(err));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, descriptors, and functions, for situations in which at least one part of the expression is async. Adapted from Sucrase ( See | async function _asyncOptionalChain(ops) {
let lastAccessLHS = undefined;
let value = ops[0];
let i = 1;
while (i < ops.length) {
const op = ops[i] ;
const fn = ops[i + 1] ;
i += 2;
// by checking for loose equality to `null`, we catch both `null` and `undefined`
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
// really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it
return;
}
if (op === 'access' || op === 'optionalAccess') {
lastAccessLHS = value;
value = await fn(value);
} else if (op === 'call' || op === 'optionalCall') {
value = await fn((...args) => (value ).call(lastAccessLHS, ...args));
lastAccessLHS = undefined;
}
}
return value;
} | [
"function _optionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}",
"function _optionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n }",
"async function _asyncNullishCoalesce(lhs, rhsFn) {\n return _nullishCoalesce._nullishCoalesce(lhs, rhsFn);\n}",
"function orElseAsyncForMaybe(input, recoverer) {\n if (Maybe_1.isNotNullAndUndefined(input)) {\n return Promise.resolve(input);\n }\n var fallback = recoverer();\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(fallback, ErrorMessage_1.ERR_MSG_RECOVERER_MUST_RETURN_PROMISE);\n return fallback;\n}",
"function parseAwait() {\n parseMaybeUnary();\n}",
"shortcircuit () {\n return null\n }",
"function maybe_call(expr) {\n expr = expr();\n return is_punc(\"(\") ? parse_call(expr) : expr;\n }",
"async function asyncChaining() {\n const res = await functions.reduce((promise, fn) => promise.then(fn), Promise.resolve());\n console.log(res);\n}",
"function transformChainExpression(node) {\n if (node.type === \"CallExpression\") {\n node.type = \"OptionalCallExpression\";\n node.callee = transformChainExpression(node.callee);\n } else if (node.type === \"MemberExpression\") {\n node.type = \"OptionalMemberExpression\";\n node.object = transformChainExpression(node.object);\n }\n // typescript\n else if (node.type === \"TSNonNullExpression\") {\n node.expression = transformChainExpression(node.expression);\n }\n return node;\n}",
"OptionalCallExpression(node) {\n this.visitTypeParameters(node);\n this.visit(node.callee);\n node.arguments.forEach(this.visit, this);\n }",
"function optional(parser) {\n return function(stream) {\n var next = parser(stream)\n if (next != null) return next\n else return stream\n }\n }",
"function maybe_call(expr) {\n expr = expr();\n return is_punc(\"(\") ? parse_call(expr) : expr;\n }",
"function andThenAsyncForNullable(input, transformer) {\n if (Nullable_1.isNull(input)) {\n return Promise.resolve(input);\n }\n var result = transformer(input);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(result, ErrorMessage_1.ERR_MSG_TRANSFORMER_MUST_RETURN_PROMISE);\n return result;\n}",
"function mapOrElseAsyncForOption(input, recoverer, transformer) {\n if (Option_1.isNone(input)) {\n var fallback = recoverer();\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(fallback, ErrorMessage_1.ERR_MSG_RECOVERER_MUST_RETURN_PROMISE);\n return fallback;\n }\n var inner = unwrap_1.unwrapOption(input);\n var result = transformer(inner);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(result, ErrorMessage_1.ERR_MSG_TRANSFORMER_MUST_RETURN_PROMISE);\n return result;\n}",
"visitExpressionOptional(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function orElseForMaybe(input, recoverer) {\n if (input !== undefined && input !== null) {\n return input;\n }\n var fallback = recoverer();\n return fallback;\n}",
"function fallback(...args) {\n for (let i = 0; i < args.length; i += 1) {\n if (args[i] != null) { return args[i] }\n }\n return null\n}",
"function parseToAsync(expression, options) {\n var parsedExpression = parse(expression, options);\n return function (path, basename, siblingsFn) {\n var result = parsedExpression(path, basename, siblingsFn);\n return result instanceof winjs_base_1.TPromise ? result : winjs_base_1.TPromise.as(result);\n };\n }",
"async function ev(f) {\n\ttry {\n\t\tconst result = eval(`(()=>{\n\t\t\treturn ${f}\n\t\t})()`);\n\t\tconst p = result instanceof Promise;\n\t\tlet error = false;\n\t\treturn {\n\t\t\tpromise: p,\n\t\t\tdata: p ? await result.catch(e => { error = true; return e; }) : result,\n\t\t\terror\n\t\t};\n\t} catch(e) {\n\t\t// no-op\n\t}\n\ttry {\n\t\treturn {\n\t\t\tdata: await eval(`(async()=>{\n\t\t\t\treturn ${f}\n\t\t\t})()`)\n\t\t};\n\t} catch(e) {\n\t\t// no-op\n\t}\n\ttry {\n\t\tconst result = eval(`(()=>{\n\t\t\t${f}\n\t\t})()`);\n\t\tconst p = result instanceof Promise;\n\t\tlet error = false;\n\t\treturn {\n\t\t\tpromise: p,\n\t\t\tdata: p ? await result.catch(e => { error = true; return e; }) : result,\n\t\t\terror\n\t\t};\n\t} catch(e) {\n\t\t// no-op\n\t}\n\ttry {\n\t\treturn {\n\t\t\tdata: await eval(`(async() => {\n\t\t\t\t${f}\n\t\t\t})()`)\n\t\t};\n\t} catch(e) {\n\t\treturn {\n\t\t\terror: true,\n\t\t\tdata: e\n\t\t};\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the SVG picker's size. | _setPickerSize() {
const that = this,
parentWidth = that.$.svgContainer.offsetWidth,
parentHeight = that.$.svgContainer.offsetHeight;
let size = Math.min(parentWidth, parentHeight) * 0.9;
if (that._pickerSize !== undefined && that._pickerSize !== size) {
that._sizeChanged = true;
}
else {
that._sizeChanged = false;
}
that._pickerSize = size;
that._measurements.radius = size / 2;
that._measurements.innerRadius = that._measurements.radius - 10;
size += 'px';
that.$.picker.style.width = size;
that.$.picker.style.height = size;
} | [
"function setSVGSize() {\n var display = this._select.style(\"display\");\n\n this._select.style(\"display\", \"none\");\n\n var _getSize = getSize(this._select.node().parentNode),\n _getSize2 = _slicedToArray(_getSize, 2),\n w = _getSize2[0],\n h = _getSize2[1];\n\n w -= parseFloat(this._select.style(\"border-left-width\"), 10);\n w -= parseFloat(this._select.style(\"border-right-width\"), 10);\n h -= parseFloat(this._select.style(\"border-top-width\"), 10);\n h -= parseFloat(this._select.style(\"border-bottom-width\"), 10);\n\n this._select.style(\"display\", display);\n\n if (this._autoWidth) {\n this.width(w);\n\n this._select.style(\"width\", \"\".concat(this._width, \"px\")).attr(\"width\", \"\".concat(this._width, \"px\"));\n }\n\n if (this._autoHeight) {\n this.height(h);\n\n this._select.style(\"height\", \"\".concat(this._height, \"px\")).attr(\"height\", \"\".concat(this._height, \"px\"));\n }\n } // Calculates the width and/or height of the Viz based on the this._select, if either has not been defined.",
"setSvgSize (sz) {\n Object(__WEBPACK_IMPORTED_MODULE_1__utils_js__[\"a\" /* copyObj */])(this.svg, sz);\n this.initSvg();\n this.update(this.root);\n }",
"updateSize() {\n this.size = this.preferredSize();\n\n this[_svgRect].attr(\"width\", this.size[0]);\n this[_svgRect].attr(\"height\", this.size[1]);\n\n this[_svgName].attr(\"x\", this.size[0] / 2);\n this[_svgName].attr(\"y\", this.renderer.config.group.padding);\n }",
"setSvgSize (sz) {\n copyObj(this.svg, sz);\n this.initSvg();\n this.update(this.root);\n }",
"setSVGSize(width, height) {\n let element = document.getElementById(this.rootId);\n let size = !isNullOrUndefined(element) ? element.getBoundingClientRect() : null;\n if (isNullOrUndefined(this.width) || this.width <= 0) {\n this.svgObj.setAttribute('width', width ? width.toString() : size.width.toString());\n }\n else {\n this.svgObj.setAttribute('width', this.width.toString());\n }\n if (isNullOrUndefined(this.height) || this.height <= 0) {\n this.svgObj.setAttribute('height', height ? height.toString() : '450');\n }\n else {\n this.svgObj.setAttribute('height', this.height.toString());\n }\n }",
"function size () {\n\n\t\tsvg.height = screen.height;\n\t\tsvg.width = screen.width;\n\n\t\tsvg.cont.style({'width': svg.width+'px', 'height': svg.height+'px'});\n\t\tsvg.svg.attr({\n\t\t\t'width': svg.width + 'px',\n\t\t\t'height': svg.height + 'px',\n\t\t\t'viewBox': [0,0,svg.width,svg.height]\n\t\t});\n\t}",
"fitSize() {\n this.svg.attr('width', this.svgContainer.clientWidth);\n this.svg.attr('height', this.svgContainer.clientHeight);\n }",
"function updateSvgSize() {\n let g = document.getElementById('graph');\n width = g.clientWidth;\n height = g.clientHeight;\n}",
"setSize(size) {\n while (this.dom.firstChild) {\n this.dom.removeChild(this.dom.lastChild)\n }\n\n this.dom.setAttributeNS(null, 'width', size[0])\n this.dom.setAttributeNS(null, 'height', size[1])\n this.initCanvas()\n this.initHeatmap()\n }",
"function setSize() {\n \t\tvar h = jq(element).parent().height();\n \t\tvar w = jq(element).parent().width();\n\n \t\tjq(element).css({height: h, width: w});\n \t}",
"setSize(size) {\n this.size = size;\n }",
"function setSizing () {\n bounds = d3.select('.graph').node().getBoundingClientRect()\n\n svgSize = {\n width: bounds.width,\n height: 550\n }\n\n graphSize = {\n width: svgSize.width - margin.right - margin.left,\n height: svgSize.height - margin.bottom - margin.top\n }\n\n helper.setCanvasSize(svgSize.width, svgSize.height)\n }",
"_changeSliderSize() {\n\t\t\t\tlet width = this.model.get('width'),\n\t\t\t\t\theight = this.model.get('height');\n\n\t\t\t\tthis.$el.css({width, height});\n\t\t\t}",
"function setBrushSize(){\n\tpaintSize = this.value;\n//\tinstructions.style.display = 'none';\n\t}",
"setSize(size) {\n this.dom.setAttributeNS(null, 'width', size[0])\n this.dom.setAttributeNS(null, 'height', size[1])\n\n while (this.dom.firstChild) {\n this.dom.removeChild(this.dom.lastChild)\n }\n this.initCanvas()\n this.initLabels()\n this.initHistogram()\n }",
"onResize(_) {\n if (this.currentPicker)\n this.currentPicker.layout();\n }",
"function set_svg_size(svg_element, number_of_columns){\n\t\tswitch(number_of_columns){\n\t\t\tcase 1:\n\t\t\t\tsvg_element.setAttribute('width', 600)\n\t\t\t\tsvg_element.setAttribute('height', 3350)\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tsvg_element.setAttribute('width', 1200)\n\t\t\t\tsvg_element.setAttribute('height', 1700)\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tsvg_element.setAttribute('width', 1550)\n\t\t\t\tsvg_element.setAttribute('height', 1100)\n\t\t\t\tbreak;\n }\n}",
"function setupCanvasSize() {\n margin = {top: MARGIN_TOP, left: MARGIN_LEFT, bottom: MARGIN_BOTTOM, right: MARGIN_RIGHT};\n width = SVG_WIDTH - margin.left - margin.right;\n height = SVG_HEIGHT - margin.top - margin.bottom;\n}",
"function setupSizeElement() {\n L.StyleEditor.formElements.SizeElement = L.StyleEditor.formElements.FormElement.extend({\n /** create the 3 standard icon sizes */\n createContent: function createContent() {\n var uiElement = this.options.uiElement;\n var select = L.DomUtil.create('div', 'leaflet-styleeditor-sizeicon sizeicon-small', uiElement);\n L.DomEvent.addListener(select, 'click', function () {\n this.setStyle(this.options.styleEditorOptions.markerType.options.size.small);\n }, this);\n select = L.DomUtil.create('div', 'leaflet-styleeditor-sizeicon sizeicon-medium', uiElement);\n L.DomEvent.addListener(select, 'click', function () {\n this.setStyle(this.options.styleEditorOptions.markerType.options.size.medium);\n }, this);\n select = L.DomUtil.create('div', 'leaflet-styleeditor-sizeicon sizeicon-large', uiElement);\n L.DomEvent.addListener(select, 'click', function () {\n this.setStyle(this.options.styleEditorOptions.markerType.options.size.large);\n }, this);\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a boolean indicating that at least one task in the selection is on a calendar that is writable. | get todo_items_writable() {
let selectedTasks = getSelectedTasks();
for (let task of selectedTasks) {
if (cal.acl.isCalendarWritable(task.calendar)) {
return true;
}
}
return false;
} | [
"isCalendarWritable(aCalendar) {\n return (\n !aCalendar.getProperty(\"disabled\") &&\n !aCalendar.readOnly &&\n (!Services.io.offline ||\n aCalendar.getProperty(\"cache.enabled\") ||\n aCalendar.getProperty(\"cache.always\") ||\n aCalendar.getProperty(\"requiresNetwork\") === false)\n );\n }",
"get all_readonly() {\n let calMgr = cal.getCalendarManager();\n return calMgr.readOnlyCalendarCount == calMgr.calendarCount;\n }",
"get all_local_calendars_readonly() {\n // We might want to speed this part up by keeping track of this in the\n // calendar manager.\n let calendars = cal.getCalendarManager().getCalendars();\n let count = calendars.length;\n for (let calendar of calendars) {\n if (!cal.acl.isCalendarWritable(calendar)) {\n count--;\n }\n }\n return count == 0;\n }",
"function canEditSelectedItems() {\n let items = currentView().getSelectedItems();\n return items.every(item => {\n let calendar = item.calendar;\n return (\n cal.acl.isCalendarWritable(calendar) &&\n cal.acl.userCanModifyItem(item) &&\n calendar.supportsScheduling &&\n !calendar.getSchedulingSupport().isInvitation(item)\n );\n });\n}",
"async hasCalendar() {\n return (await getCalendarId(this.host())) != null;\n }",
"isTaskCalendar(aCalendar) {\n return aCalendar.getProperty(\"capabilities.tasks.supported\") !== false;\n }",
"userCanAddItemsToCalendar(aCalendar) {\n let aclEntry = aCalendar.aclEntry;\n return (\n !aclEntry || !aclEntry.hasAccessControl || aclEntry.userIsOwner || aclEntry.userCanAddItems\n );\n }",
"async isCalendarOpen() {\n // `aria-owns` is set only if there's an open datepicker so we can use it as an indicator.\n const host = await this.host();\n return (await host.getAttribute('aria-owns')) != null;\n }",
"get has_enabled_reloadable_calendars() {\n return cal\n .getCalendarManager()\n .getCalendars()\n .some(\n calendar =>\n !calendar.getProperty(\"disabled\") &&\n (calendar.type == \"ics\" || calendar.getProperty(\"requiresNetwork\") !== false)\n );\n }",
"function isWritable() {\n var currentActivity = WorkOrder.getManageWorkOrderActivity();\n return (\n !isReadOnly() &&\n ( !WorkOrder.isWorkOrderSignedByTechnician( workOrder ) ||\n WorkOrder.isWorkOrderSignedByTechnician( workOrder ) &&\n ( currentActivity == WorkOrder.MANAGE_WORK_ORDER_EDIT ||\n currentActivity == WorkOrder.MANAGE_WORK_ORDER_OPEN_NOCLOCKING )\n )\n );\n }",
"function canPaste() {\n if (Services.prefs.getBoolPref(\"calendar.paste.intoSelectedCalendar\", false)) {\n let selectedCal = getSelectedCalendar();\n if (\n !selectedCal ||\n !cal.acl.isCalendarWritable(selectedCal) ||\n !cal.acl.userCanAddItemsToCalendar(selectedCal)\n ) {\n return false;\n }\n } else {\n let calendars = cal\n .getCalendarManager()\n .getCalendars()\n .filter(cal.acl.isCalendarWritable)\n .filter(cal.acl.userCanAddItemsToCalendar);\n if (!calendars.length) {\n return false;\n }\n }\n\n const flavors = [\"text/calendar\", \"text/unicode\"];\n return Services.clipboard.hasDataMatchingFlavors(flavors, Ci.nsIClipboard.kGlobalClipboard);\n}",
"async calendarPermissions() {\n const { status } = await Calendar.requestCalendarPermissionsAsync();\n if (status === 'granted') {\n const calendars = await Calendar.getCalendarsAsync();\n }\n }",
"userCanDeleteItemsFromCalendar(aCalendar) {\n let aclEntry = aCalendar.aclEntry;\n return (\n !aclEntry || !aclEntry.hasAccessControl || aclEntry.userIsOwner || aclEntry.userCanDeleteItems\n );\n }",
"async openCalendar() {\n const [isDisabled, hasCalendar] = await parallel(() => [this.isDisabled(), this.hasCalendar()]);\n if (!isDisabled && hasCalendar) {\n return this._openCalendar();\n }\n }",
"get has_local_calendars() {\n let calMgr = cal.getCalendarManager();\n return calMgr.networkCalendarCount < calMgr.calendarCount;\n }",
"function isAssigneeTicked() {\n return (filteredAssignees.length != 0);\n }",
"isValid() {\n return this.selection != null && this._isValidDateInstance(this.selection);\n }",
"function allHasSelected() {\n\t\tvar dayList = $('#day .custom-list');\n\t\tvar monthList = $('#month .custom-list');\n\t\tvar yearList = $('#year .custom-list');\n\t\treturn hasSelected(dayList) && hasSelected(monthList) && hasSelected(yearList);\n\t}",
"isEventCalendar(aCalendar) {\n return aCalendar.getProperty(\"capabilities.events.supported\") !== false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
number to hex helper function | function toHex(n){return (n<16?"0":"")+n.toString(16);} | [
"function IntToHex(n)\r\n{\r\n\tvar result = n.toString(16);\r\n\tif (result.length==1) result = \"0\"+result;\r\n\treturn result;\r\n}",
"function hex(x) {\n return $builtin_base_convert_helper(x, 16)\n}",
"function hex($num) {\n var str = \"\";\n for(var j = 7; j >= 0; j--)\n str += _chars.charAt(($num >> (j * 4)) & 0x0F);\n return str;\n }",
"function hex(number) {\n if (number > 255) {\n throw new Error(\"'\" + number + \"'' is greater than 255(0xff);\");\n }\n var str = Number(number).toString(16);\n return (\"0\" + str).slice(-2);\n }",
"function hex(number) {\n if (number > 255) {\n throw new Error(\"'\" + number + \"'' is greater than 255(0xff);\");\n }\n\n var str = Number(number).toString(16);\n return (\"0\" + str).slice(-2);\n }",
"function number2hex2(num) {\n\treturn (\"0\"+num.toString(16).toUpperCase()).slice(-2);\n}",
"function number2stringHex(number) {\n let str = number.toString(16).toUpperCase();\n while (str.length < 4) { str = \"0\" + str; }\n return \"0x\" + str;\n}",
"function number2hex4(num) {\n\treturn (\"000\"+num.toString(16).toUpperCase()).slice(-4);\n}",
"function completeHex(num){\r\n var n = num + \"\"; \r\n while (n.length < 8) n = \"0\" + n;\r\n return n;\r\n}",
"function intToHex(num, length) {\n\tvar ret = num.toString(16);\n\twhile (ret.length < length) {\n\t\tret = '0' + ret;\n\t}\n\treturn ret;\n}",
"function createEscapedHex( number ){\n return fromCharCode(parseInt( number.toString(16) , 16));\n}",
"function toHex (number)\n{\n // Make sure the number passed in is an integer.\n if (Number.isInteger(number) == false)\n return \"00\";\n\n // Convert the given number to a string, and make it\n // uppercase.\n var str = number.toString(16).toUpperCase();\n\n // Format the hexidecimal string, such that it appears as\n // \"00\" to \"0F\" if the number is less than 16.\n if (number < 16)\n {\n return \"0\" + str;\n }\n else\n {\n return str;\n }\n}",
"static toHexDigit(num) {\n if (num < 10) {\n return \"\" + num;\n }\n else {\n return String.fromCharCode(65 + num - 10);\n }\n }",
"function dec2HexString(n) {\n return '0x' + n.toString(16)\n}",
"function numberToHex(integer) {\n if (integer < 0) {\n throw new Error('Invalid integer as argument, must be unsigned!');\n }\n const hex = integer.toString(16);\n return hex.length % 2 ? `0${hex}` : hex;\n}",
"toHex() {\n const value = this.value.toString(16).toUpperCase();\n return new Hex(`#${value}`);\n }",
"function dec2Hex(n) {\n return n.toString(16)\n}",
"function NumToHexStr(v)\n{ \n\tif (v < 0)\n {\n \tv = 0xFFFFFFFF + v + 1;\n }\n \n return v.toString(16).toUpperCase();\n}",
"function hex(n) {\n var hexdigit = \"0123456789ABCDEF\";\n var b = \"\";\nfor(var i=0; n > 0; i++) {\n\nc=n%16;\n\nif(c >= 0 && c<= 15){\n b=hexdigit[c]+b; \n}\n\n n = Math.floor(n/16);\n \n }\n return \"0x\" + b;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the client area based on widget. | updateClientAreaByWidget(widget) {
this.clientArea.x = widget.x;
this.clientArea.y = widget.y;
this.clientActiveArea.x = widget.x;
this.clientActiveArea.y = widget.y;
} | [
"updateClientAreaLocation(widget, area) {\n widget.x = area.x;\n widget.y = area.y;\n widget.width = area.width;\n }",
"function updateWidget()\n {\n //todo\n }",
"updateClientAreaForTable(tableWidget) {\n this.clientActiveArea.x = this.clientArea.x = tableWidget.x;\n this.clientActiveArea.width = this.clientArea.width = tableWidget.width;\n }",
"function assignWidgetContent(){\n $.each(splittedRegionContent, function(){\n $.each(this, function(){\n var tempContent = this;\n var widgetDiv = _iframe.contents().find('div[widgetid =\"' + tempContent.widgetId + '\"]');\n try\n {\n widgetDiv.html(tempContent.content);\n }\n catch(err)\n {\n //TODO: I18N TEST\n $.perc_utils.info(I18N.message(\"perc.ui.iframe.view@Failed to fill widget content\") + tempContent.widgetId + I18N.message(\"perc.ui.iframe.view@Error is\") + err);\n }\n widgetDiv.attr('ownerId', tempContent.ownerid);\n if (tempContent.isTransparent) {\n widgetDiv.addClass('perc-widget-transperant');\n }\n //Remove the height and width attribute of Widget's Region puff\n widgetDiv.parents('.perc-region-puff:first').removeAttr('style').addClass('perc-new-splitted-region');\n\n });\n\n });\n _layoutFunctions.removeDropsSortingResizing(true);\n _layoutFunctions.setLayoutDirty(true);\n clearItoolMarkup();\n activateInspectionToolButton();\n }",
"function update_Widget(){\n build_url();\n\tget_widget();\n}",
"function updateWidget(widgetId, widget)\n {\n //todo\n }",
"_addToMainArea(widget, options) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n options = options || {};\n const dock = this._dockPanel;\n const mode = options.mode || 'tab-after';\n let ref = this.currentWidget;\n if (options.ref) {\n ref = find(dock.widgets(), value => value.id === options.ref) || null;\n }\n const { title } = widget;\n // Add widget ID to tab so that we can get a handle on the tab's widget\n // (for context menu support)\n title.dataset = Object.assign(Object.assign({}, title.dataset), { id: widget.id });\n if (title.icon instanceof LabIcon) {\n // bind an appropriate style to the icon\n title.icon = title.icon.bindprops({\n stylesheet: 'mainAreaTab'\n });\n }\n else if (typeof title.icon === 'string' || !title.icon) {\n // add some classes to help with displaying css background imgs\n title.iconClass = classes(title.iconClass, 'jp-Icon');\n }\n dock.addWidget(widget, { mode, ref });\n // The dock panel doesn't account for placement information while\n // in single document mode, so upon rehydrating any widgets that were\n // added will not be in the correct place. Cache the placement information\n // here so that we can later rehydrate correctly.\n if (dock.mode === 'single-document') {\n this._mainOptionsCache.set(widget, options);\n }\n if (options.activate !== false) {\n dock.activateWidget(widget);\n }\n }",
"function updateWidget() {\n var cms = $propertiesFrame[0].contentWindow.CMS;\n if (typeof cms !== 'undefined') {\n var saveStatusFieldSelector = cms.Application.widgetProperties.saveStatusFieldSelector;\n var $saveStatus = $propertiesFrame.contents().find(saveStatusFieldSelector);\n\n if ($saveStatus.val() === '1' && typeof handlers.updateWidget === 'function') {\n var widgetId = widgetSelection.getSelectedWidgetIdentifier();\n var widget = widgetSelection.getSelectedWidget();\n handlers.updateWidget(widgetId)\n .done(function(response) {\n widgetValidationService.validateWidget(response.Identifier, response.HasUnfilledRequiredProperty);\n widgetValidationService.checkValidity();\n })\n .done(function() {\n widgetSelection.adjustWidgetHeaderPosition(widget)\n });\n $saveStatus.val('');\n }\n }\n }",
"_addToBottomArea(widget, options) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n // Temporary: widgets are added to the panel in order of insertion.\n this._bottomPanel.addWidget(widget);\n this._onLayoutModified();\n if (this._bottomPanel.isHidden) {\n this._bottomPanel.show();\n }\n }",
"function refresh(widget) {\n widget.setVisible(hasVisibleChild(widget));\n }",
"onInspectorUpdate(sender, args) {\n const { content } = args;\n // Update the content of the inspector widget.\n if (!content || content === this._content) {\n return;\n }\n this._content.dispose();\n this._content = content;\n content.addClass(CONTENT_CLASS);\n this.layout.addWidget(content);\n }",
"function onDataUpdate(update) {\n function replaceKeepYScroll(replaced, replacement) {\n const top = replaced.scrollTop();\n replaced.replaceWith(replacement);\n replacement.scrollTop(top); \n }\n if (update.widget === undefined) {\n onGlobalUpdate(update);\n return;\n }\n const widget = update.widget;\n const data = update.data;\n const alerts = update.alerts;\n const annotations = update.annotations;\n const widgetNode = $('#widget-' + widget.target);\n if (widgetNode.length == 0)\n return; // can't update, widget is not in page\n if (widget.selected) {\n widgetNode.addClass('chart-selected');\n } else {\n widgetNode.removeClass('chart-selected');\n }\n const contentNode = widgetNode.find('.WidgetContent').first();\n if (widget.type == 'top') {\n contentNode.addClass('WidgetContentTop');\n } else {\n contentNode.removeClass('WidgetContentTop');\n }\n let headerNode = widgetNode.find('.WidgetHeader').first();\n let legendNode = widgetNode.find('.Legend').first();\n let indicatorNode = widgetNode.find('.Indicator').first();\n if (indicatorNode.length == 0)\n indicatorNode = widgetNode.find('.RAGIndicator').first();\n let alertsNode = widgetNode.find('.AlertTable').first();\n let annotationsNode = widgetNode.find('.AnnotationTable').first();\n let legend = createLegendModel(widget, data, alerts, annotations); // OBS this has side effect of setting .legend attribute in series data\n if (data !== undefined && (widget.type === 'line' || widget.type === 'bar')) {\n MonitoringConsole.Chart.getAPI(widget).onDataUpdate(update);\n }\n replaceKeepYScroll(headerNode, Components.createWidgetHeader(createWidgetHeaderModel(widget)));\n if (widget.type == 'rag') {\n alertsNode.hide();\n legendNode.hide();\n replaceKeepYScroll(indicatorNode, Components.createRAGIndicator(createRAGIndicatorModel(widget, legend)));\n annotationsNode.hide();\n } else {\n replaceKeepYScroll(alertsNode, Components.createAlertTable(createAlertTableModel(widget, alerts, annotations)));\n replaceKeepYScroll(legendNode, Components.createLegend(legend));\n replaceKeepYScroll(indicatorNode, Components.createIndicator(createIndicatorModel(widget, data)));\n replaceKeepYScroll(annotationsNode, Components.createAnnotationTable(createAnnotationTableModel(widget, annotations))); \n }\n }",
"function updateWidgets() {\n\t\n\t// get all the active widgets on the current page.\n\tvar widgets = $.map($(\".w_container\"), function(widget) {\n\t\t\t\t\t\treturn { \"elementId\": widget.id, \"widgetTypeId\" : $(widget).data(\"widgetTypeId\") };\n\t\t\t\t\t});\n\t\n\tfor(var i = 0; i < widgets.length; i++) {\n\t\t$currentWidget = $('#' + widgets[i].elementId);\n\t\t$currentWidget.css('opacity', 0.5);\n\t\tfunction revertOpacity($widget) {\n\t\t\treturn function() { $widget.css('opacity', 1.0); }\n\t\t}\n\t\tupdateWidget(widgets[i].widgetTypeId, widgets[i].elementId, revertOpacity($currentWidget));\n\t}\n}",
"addToTopArea(widget, options = {}) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n // Temporary: widgets are added to the panel in order of insertion.\n this._topPanel.addWidget(widget);\n this._onLayoutModified();\n }",
"_onCurrentChanged(sender, args) {\n const oldWidget = args.previousTitle\n ? this._findWidgetByTitle(args.previousTitle)\n : null;\n const newWidget = args.currentTitle\n ? this._findWidgetByTitle(args.currentTitle)\n : null;\n if (oldWidget) {\n oldWidget.hide();\n }\n if (newWidget) {\n newWidget.show();\n }\n this._lastCurrent = newWidget || oldWidget;\n if (newWidget) {\n const id = newWidget.id;\n document.body.setAttribute(`data-${this._side}-sidebar-widget`, id);\n }\n else {\n document.body.removeAttribute(`data-${this._side}-sidebar-widget`);\n }\n this._refreshVisibility();\n }",
"updateClientAreaForCell(cell, beforeLayout) {\n // tslint:disable-next-line:max-line-length\n let rowWidget = cell.ownerRow;\n let cellWidget = cell;\n if (beforeLayout) {\n this.clientActiveArea.x = this.clientArea.x = cellWidget.x;\n this.clientActiveArea.y = cellWidget.y;\n this.clientActiveArea.width = this.clientArea.width = cellWidget.width > 0 ? cellWidget.width : 0;\n if (this instanceof PageLayoutViewer) {\n this.clientActiveArea.height = Number.POSITIVE_INFINITY;\n }\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n else {\n this.clientActiveArea.x = this.clientArea.x = cellWidget.x + cellWidget.width + cellWidget.margin.right;\n if (rowWidget.x + rowWidget.width - this.clientArea.x < 0) {\n this.clientActiveArea.width = this.clientArea.width = 0;\n }\n else {\n this.clientActiveArea.width = this.clientArea.width = rowWidget.x + rowWidget.width - this.clientArea.x;\n }\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea.y = cellWidget.y - cellWidget.margin.top - HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.cellSpacing);\n if (!cell.ownerTable.isInsideTable) {\n this.clientActiveArea.height = this.clientArea.bottom - rowWidget.y > 0 ? this.clientArea.bottom - rowWidget.y : 0;\n }\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n }",
"function update() {\n resize();\n controls.update();\n }",
"addToMainArea(widget, options = {}) {\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n let dock = this._dockPanel;\n let ref = null;\n if (options.ref) {\n ref = algorithm_1.find(dock.widgets(), value => value.id === options.ref) || null;\n }\n let mode = options.mode || 'tab-after';\n dock.addWidget(widget, { mode, ref });\n // The dock panel doesn't account for placement information while\n // in single document mode, so upon rehydrating any widgets that were\n // added will not be in the correct place. Cache the placement information\n // here so that we can later rehydrate correctly.\n if (dock.mode === 'single-document') {\n this._addOptionsCache.set(widget, options);\n }\n if (options.activate !== false) {\n dock.activateWidget(widget);\n }\n }",
"_addToTopArea(widget, options) {\n var _a;\n if (!widget.id) {\n console.error('Widgets added to app shell must have unique id property.');\n return;\n }\n options = options || {};\n const rank = (_a = options.rank) !== null && _a !== void 0 ? _a : DEFAULT_RANK;\n this._topHandler.addWidget(widget, rank);\n this._onLayoutModified();\n if (this._topHandler.panel.isHidden) {\n this._topHandler.panel.show();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieves appropriate pair from the guestPairs array | function getPair(){
for (var i=0; i<3; i++){
if (roomGuest === guestPairs[i][0]){
if (guestPairs[i][1] != "alone"){
roomGuestPair = guestPairs[i][1];
} else {
roomGuestPair = "only myself";
}
} else if (roomGuest === guestPairs[i][1]){
roomGuestPair = guestPairs[i][0];
} else if (roomGuest === murderer){
roomGuestPair = guestPairs[3][1];
}
}
} | [
"async function getPair() {\n const result = await db.query(\n 'select pair from meta where test_id = 1', []\n );\n return result[0].pair;\n}",
"getPriceFetcherForPair(a: string, b: string) {\n if (!this.boundPriceMapByExchange) {\n throw new Error('No price map yet! Call exchangeService.generatePricemap first.');\n }\n const exchangeKeys = Object.keys(EXCHANGES);\n const pricesByExchange = this.boundPriceMapByExchange;\n\n for (let i = 0; i < exchangeKeys.length; i++) {\n const key = exchangeKeys[i];\n const priceMap = pricesByExchange[key];\n const pair = this.generatePair(a, b, key);\n const hasPair = Object.prototype.hasOwnProperty.call(priceMap, pair);\n\n if (hasPair) {\n return priceMap[pair];\n }\n }\n\n throw new UnsupportedPairError(`Pair ${a}-${b} not found on any exchange`);\n }",
"function getNextPair(playerStandings, tournament) {\n\tvar first = playerStandings.splice(0,1)[0];\n\tfor (var i=0; i<playerStandings.length; i++) {\n\t\tif (!tournament.hasPlayed(first.id, playerStandings[i].id)) {\n\t\t\tvar second = playerStandings.splice(i,1)[0];\n\t\t\treturn [first, second];\n\t\t}\n\t}\n\t//throw 'Swiss pairing algorithm failed';\n\tthrow \"Tournament finished.Cann't execute more rounds\";\n\n}",
"allPairs() {\n const pairs = [];\n if (this.probeStrategy == \"CHAINING\") {\n for (let hash = 0; hash < this.slots.length; hash++) {\n let probe = 0;\n let link = this.slots[hash];\n if (!!link) {\n if (link.occupied) {\n pairs.push([link.key, link.value]);\n }\n while (!!link.next) {\n link = link.next;\n if (link.occupied) {\n pairs.push([link.key, link.value]);\n }\n probe += 1;\n if (probe > MAX_PROBES) {\n throw new TypeError(\n `${this.probeStrategy} Max Probes Exceeded At ${probe}`\n );\n }\n }\n }\n }\n } else {\n for (let hash = 0; hash < this.slots.length; hash++) {\n if (!!this.slots[hash]) {\n const item = this.slots[hash];\n pairs.push([item.key, item.value]);\n }\n }\n }\n return pairs;\n }",
"function hiddenPair(){\n\t\t return hiddenLockedCandidates(2);\n\t }",
"function get_current_pair() {\n var screw = document.querySelector(\".screw[selected]\");\n if (!screw) return;\n var pair = screw.getAttribute(\"pair\");\n return pair;\n}",
"function getPair(NeighborName1, NeighborName2) {\n\tif (NeighborName2 < NeighborName1) {\n\t\tvar temp = NeighborName1;\n\t\tNeighborName1 = NeighborName2;\n\t\tNeighborName2 = temp;\n\t}\n\tvar N1 = getNeighborInfo(NeighborName1);\n\tvar N2 = getNeighborInfo(NeighborName2);\n\tvar pairRoutes = getPairRoutes(NeighborName1, NeighborName2);\n\tvar result = {};\n\tresult[NeighborName1] = N1;\n\tresult[NeighborName2] = N2;\n\tresult[\"Routes\"] = pairRoutes;\n\treturn result;\n}",
"function getShownPair() {\n\n for(var i = 0; i < nbOfPair * 2; ++i) {\n var cardItem1 = items.cardRepeater.itemAt(i)\n for(var j = 0; j < nbOfPair * 2; ++j) {\n var cardItem2 = items.cardRepeater.itemAt(j)\n if(i != j &&\n !cardItem1.isFound &&\n cardItem1.isShown &&\n !cardItem2.isFound &&\n cardItem2.isShown &&\n (cardItem1.pairData.matchCode ===\n cardItem2.pairData.matchCode) ) {\n return [cardItem1, cardItem2]\n }\n }\n }\n return\n}",
"function hiddenPair() {\n return hiddenLockedCandidates(2);\n}",
"handlePair(data) {\n // Hack to circumvent a weird screen artifact we are seeing in firmware\n // NOTHING TO SEE HERE\n if (data[0] === '_' || data[0] === '[') data = data.slice(1)\n\n // If we didn't timeout, submit the secret and hope for success!\n this.wait(\"Establishing connection with your Lattice\");\n this.state.session.pair(data, (err) => {\n this.unwait();\n if (err) {\n // If there was an error here, the user probably entered the wrong secret\n const pairErr = 'Failed to pair. You either entered the wrong code or have already connected to this app.'\n this.setError({ msg: pairErr, cb: this.connectSession });\n } else if (this.state.keyringOrigin === null) {\n // Success! Load our addresses from this wallet.\n this.fetchAddresses(this.fetchData);\n } else {\n this.returnKeyringData();\n }\n })\n }",
"function pairingDetail (rowID) {\n try {\n // ToDo: Return all of the Pairing Details for a Single Pairing.\n var retVal = find(pairings(), \"RowID\", rowID); // HACK: This is for demo purposes only. \n if (retVal.length = 0) {\n return null;\n }\n else {\n var pd = retVal[0];\n return pd;\n }\n }\n catch (err) {\n ex.log(err, this.Name + \".PairingDetail(RowID:\" + rowID + \")\");\n }\n }",
"function processVoting(personalPrivateKey, choice) {\n\t\n\ttry {\n \t// Get xG and yG (only way to get values from a Struct)\n var voter = WaveVoteAddr.getVoterBis(addr);\n\t\tvar adminPublicKeyStr_x = voter[3][0].toString(10);\n\t\tvar adminPublicKeyStr_y = voter[3][1].toString(10);\n var xG = [voter[4][0], voter[4][1]];\n var yG = [voter[5][0], voter[5][1]];\n\t\t\n\t\tvar adminPublicKey = [voter[3][0], voter[3][1]];\n\t\t//We create the private voting key from the personal private key and the admin public key.\n\t\tvar res = cryptoAddr.buildVotingPrivateKey.call(new BigNumber(personalPrivateKey), adminPublicKey);\n console.log(res);\n console.log(res[0].toString(10));\n\t\t\n var x = res[0];\n var _x = res[1][0];\n var _y = res[1][1];\n\n\t\t\n\t\t//Check if the registeredKey is the same\n\t\tif(!_x.equals(xG[0]) || !_y.equals(xG[1])) {\n\t\t\tconsole.log(_x);\n\t\t\tconsole.log(xG[0]);\n\t\t\tconsole.log(_y);\n\t\t\tconsole.log(xG[1]);\n\t\t\talert(\"Error : the registeredKey in the Smartcontract isnt equal of the calculated registeredKey\");\n\t\t\treturn;\n\t\t}\n \n \n\t\t//On initie la variable res1D\n var w = new BigNumber(ec.genKeyPair().getPrivate().toString());\n var totalVoter = WaveVoteAddr.totalregistered();\n var totalAnswers = WaveVoteAddr.getTotalAnswers();\n var res1D = [x,w,choice,totalAnswers,totalVoter];\n \n \t//Init de res2D\n \tvar res2D = [xG,yG];\n \t\n \t//On instancie les nombres aléatoires : il en faut totalAnswers-1 \n \tvar diAndRiList = new Array();\n \tfor(var i=0;i<totalAnswers-1;i++) {\n \t\tvar di = new BigNumber(ec.genKeyPair().getPrivate().toString());\n \t\tvar ri = new BigNumber(ec.genKeyPair().getPrivate().toString());\n \t\tdiAndRiList.push([di,ri]);\n \t}\n \t\n \t//We generate the zkp\n \tvar result = cryptoAddr.generateZKP.call(res1D, res2D, diAndRiList, {\n from: web3.eth.accounts[accounts_index]\n }); \n \tconsole.log(result);\n \t\n\t\tres1D = [totalAnswers, totalVoter];\n\t\tvar y = result[0];\n\t\tvar aList = result[1];\n\t\tvar bList = result[2];\n\t\tvar dAndrList = result[3];\n\t\t\n\t\t//We verify the ZKP\n\t\tvar resultVerif = cryptoAddr.verifyZKPVote.call(res1D, y, res2D, dAndrList, aList, bList, {\n from: web3.eth.accounts[accounts_index]\n });\n\t\tconsole.log(resultVerif);\n\n // Let's make sure the zero knowledge proof checked out...\n if (resultVerif[0]) {\n\n var castvote = false;\n\n if (state == 2) {\n if (confirm(\"You are voting \" + web3.toUtf8(WaveVoteAddr.answerList(choice)) + \"... You will not be able to change your vote\")) {\n castvote = true;\n }\n \n if (castvote) {\n web3.personal.unlockAccount(addr, password);\n var res = WaveVoteAddr.submitVote.call(y, dAndrList, aList, bList, {\n from: web3.eth.accounts[accounts_index]\n });\n \n if(res[0]) {\n \ttry {\n \tWaveVoteAddr.submitVote.sendTransaction(y, dAndrList, aList, bList, {\n from: web3.eth.accounts[accounts_index],\n gas: 9000000, \n value: 0\n });\n \t\n db.find({account: addr}, function(err, docs) {\n \tconsole.log(docs);\n \tif (docs.length) {\n \t\ttry {\n \t\tdb.update({account: addr}, {account: addr, personalPrivateKey: docs[0].personalPrivateKey, privateVotingKey: x.toString(10)}, {});\n \t\t} catch(e) {\n \t\t\tconsole.log(e);\n \t\t\talert(e);\t \t\t\t\n \t\t}\n \t}\n });\n \t\n \tdocument.getElementById('do_vote').innerHTML = 'Vote has been submitted... Waiting for confirmation';\n } catch (e) {\n \tconsole.log(e);\n \talert(\"Error during the transaction of your vote\");\n }\n } else {\n \talert(res[1]);\n } \n }\n }\n } else {\n \tconsole.log(resultVerif[1]);\n alert(resultVerif[1]);\n }\n\t} catch(e) {\n\t\tconsole.log(e);\n\t\talert(e);\n\t}\n}",
"getExchanges(pair, callback) {\n this._validateTokenPair(pair, (err, pair) => {\n if (err) { return callback(err); }\n\n this.utils.call(`exchangelist_v2/${pair.base}-${pair.token}`, (err, pBody) => {\n if (err) { return callback(err); }\n\n if (typeof pBody.exchange === \"undefined\" || pBody.exchange.length < 1) {\n return callback(new Error(\"Unable to get available exchanges for this token !\"));\n }\n\n return callback(null, pBody.exchange);\n });\n });\n }",
"function pairings () {\n try{\n // ToDo: Retrieve the Pairings from the JavaScript Database.\n var retVal = jQuery.parseJSON(localStorage.Pairings);\n return retVal;\n }\n catch (err) {\n ex.log(err, this.Name + \".Pairings()\");\n return [];\n }\n }",
"function pairingDetails(pairingID) {\n try{\n // ToDo: Return all of the Pairing Details for a Single Pairing.\n var retVal = find(pairings(), \"PairingID\", pairingID); // HACK: This is for demo purposes only.\n return retVal;\n }\n catch (err) {\n ex.log(err, this.Name + \".pairingDetails(pairingID:\" + pairingID + \")\");\n return [];\n }\n }",
"function findPairing(heltourConfig, white, black, leagueTag) {\n var request = heltourRequest(heltourConfig, \"find_pairing\");\n request.parameters = {\n 'white': white,\n 'black': black\n };\n if(!_.isNil(leagueTag)){\n request.parameters.league = leagueTag;\n }\n\n return http.fetchURLIntoJSON(request);\n}",
"function createPrivateVotingKey(addressVoter, personalPrivateKey) {\n var voter = WaveVoteAddr.getVoterBis(addr);\n\n var xG = [voter[4][0], voter[4][1]];\n\tvar adminPublicKey = [voter[3][0], voter[3][1]];\n\t\n\tvar res = cryptoAddr.buildVotingPrivateKey.call(new BigNumber(personalPrivateKey), adminPublicKey);\n console.log(res);\n\n var x = res[0];\n var _x = res[1][0];\n var _y = res[1][1];\n\n\t//Check if the registeredKey is the same\n\tif(!_x.equals(xG[0]) || !_y.equals(xG[1])) {\n\t\tconsole.log(_x);\n\t\tconsole.log(xG[0]);\n\t\tconsole.log(_y);\n\t\tconsole.log(xG[1]);\n\t\talert(\"Error : the registeredKey in the Smartcontract isnt equal of the calculated registeredKey\");\n\t\treturn;\n\t} else {\n\t\treturn x;\n\t}\n\t\t\n}",
"async show ({ request, response }) {\n const query = request.get();\n let singlePair = await Database.select('pair_id', 'base', 'quote', 'exchanges').from('pairs').where({\n base: query.base.toUpperCase(),\n quote: query.quote.toUpperCase()\n })\n return response.json(singlePair);\n }",
"function getPairings(res, mysql, context, complete){\r\n mysql.pool.query(\"SELECT pairing_name, brands.brand_name FROM pairings INNER JOIN brands ON brands.brand_ID = pairings.brand_ID\", function(error, results, fields){\r\n if(error){\r\n res.write(JSON.stringify(error));\r\n res.end();\r\n }\r\n context.pairings = results;\r\n complete();\r\n });\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggles the link modal, which will be populated by whatever url and openInNewTab values are given, if any. If none are given, it is assumed that we are creating a new link. If some are given, it is assumed that we are editing an existing link. | handleToggleLinkModal() {
const { modalComponent } = this.state;
if (modalComponent) {
this.handleCloseModal();
} else {
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
const entityKey = getSelectionEntity(editorState);
const entity = entityKey ? contentState.getEntity(entityKey) : null;
this.handleOpenModal(() => (
<LinkModal
isOpen
onAddLink={this.handleAddLink}
onRemoveLink={this.handleRemoveLink}
openInNewTab={entity ? entity.getData().target === '_blank' : false}
toggle={this.handleCloseModal}
url={entity ? entity.getData().url : null}
/>
));
}
} | [
"function showEditLinkModal(){\n resetModal();\n currEle.popover('hide');\n $('#modal').modal('show');\n $(\"#modal-title\").html('Add Link Address');\n $(\"#modal-body\").html('<b>Text you want the on the hyperlink:</b>\\\n <input type=\"text\" class=\"form-control\" id=\"link-text\" placeholder=\"Text to display\">\\\n <b>To what URL should this link go?</b> \\\n <input type=\"text\" class=\"form-control\" id=\"link-url\" placeholder=\"Link Address\">\\\n <input type=\"button\" class=\"btn btn-default\" value=\"Test this link\" onclick=\"window.open($(\\'#link-url\\').val())\">\\\n <p style=\"color:red;display:none;\" id=\"link-url-error\">Please enter a URL or link address!</p>');\n $('#save-btn').unbind( \"click\" );\n $('#save-btn').on('click', function(){\n if($('#link-url').val()){\n currEle.attr(\"href\", $('#link-url').val());\n if($('#link-text').val()){\n currEle.html($('#link-text').val());\n $('#modal').modal('hide');\n }\n else{\n currEle.html($('#link-url').val());\n $('#modal').modal('hide');\n }\n }\n else{\n $('#link-url-error').show();\n }\n });\n}",
"function showLinkModal () {\n var linkDialog = $(\"#link-dialog\");\n var linkInput = $(\"#link-input\");\n var goButton = $(\"#go-to-button\");\n\n // Go to URL when \"Go to! button is pressed\"\n goButton.on('click',function() {\n window.location.href = linkInput.val();\n });\n\n // Focus on input field after dialog is shown \n // and select its contents for quick copy & paste\n linkDialog.on('shown.bs.modal', function (e) {\n linkInput.focus().select();\n\n });\n // Clear input field after any type of dialog close\n linkDialog.on('hidden.bs.modal', function (e) {\n linkInput.val(\"\");\n });\n\n linkDialog.modal();\n }",
"function editLink(event) {\n\n function isPopUpChecked() {\n if($j('#editPopUpToggle:checked').val() !== undefined) {\n return true;\n }\n return false;\n }\n\n function isLinkPopUp() {\n if($j(event.currentTarget).children('a').hasClass('popUp')) {\n return true;\n }\n return false;\n }\n\n\n\n var editLinkDialog = $j(\n '<div class=\"dialog\" id=\"editLinkDialog\" title=\"Edit this link\">' +\n '<fieldset>' +\n '<label for=\"newText\" class=\"pop-left\">Text</label>' +\n '<input type=\"text\" id=\"newText\" value=\"' + $j(event.currentTarget).children('a').text() + '\"></input></fieldset>' +\n '<fieldset><label for=\"newTarget\" class=\"pop-left\">Target</label>' +\n '<input type=\"text\" id=\"newTarget\" value=\"' + $j(event.currentTarget).children('a').attr('href') + '\"></input></fieldset>' +\n '<fieldset><label for=\"editPopUpToggle\" class=\"pop-left\">Popup</label>' +\n '<input type=\"checkbox\" id=\"editPopUpToggle\" ' + ( isLinkPopUp() ? 'checked' : '' ) +'></input>' +\n '</fieldset>' +\n '</div>'\n ).dialog({\n //buttons\n modal:true,\n resizable: false,\n buttons: {\n Ok: function() {\n $j(event.currentTarget).children('a').text(\n $j('#newText').val()\n );\n $j(event.currentTarget).children('a').attr('href',\n $j('#newTarget').val()\n );\n\n// if($j('#editPopUpToggle:checked').val() !== undefined) {\n if( isPopUpChecked() ) {\n $j(event.currentTarget).children('a').addClass('popUp');\n } else {\n $j(event.currentTarget).children('a').removeClass('popUp');\n }\n\n $j(this).dialog('close');\n },\n Delete: function() {\n $j(event.currentTarget).remove();\n $j(this).dialog('close');\n }\n },\n //onclose\n close: function() {\n editLinkDialog.remove();\n }\n });\n\n } // :------)",
"function addLink()\n{\n linkUrlEl.value = \"\";\n linkTitleEl.value = \"\";\n modalResult = \"create\";\n showModal(modalEditEl);\n}",
"function toggleBookmarkModal () {\n console.log(\"You clicked!\");\n if (bookmarkModal.classList.contains('is-active')) {\n bookmarkModal.classList.remove('is-active');\n } else {\n bookmarkModal.classList.add('is-active');\n }\n }",
"function configureLinksToOpenInNewTabs() {\n var issueLinks = getCandidateLinks();\n issueLinks.forEach(function(link) {\n link.target = \"_blank\";\n\n // there are click listeners on the class \"issue-link\" that override the click event\n link.classList.remove(\"issue-link\");\n });\n}",
"function toggle() {\n setModal(!modal);\n }",
"function modal_check_box_handler(){\n modal_check_box = $('#open_urls_link');\n shareble_textarea = $('#myModal textarea')\n modal_check_box.click(\n function(){\n if (modal_check_box.is(':checked')) { // tests if checkbox is checked\n shareble_textarea.val(shareble_textarea.val()+\"&open=true\"); // adds a second variable to the query string set to true this will cause this link to automatically open windows\n }\n else\n shareble_textarea.val(shareble_textarea.val().replace('&open=true','')); // removes \"&open=true\" from the shareble link text.\n }\n )\n }",
"function toggle() {\n setModal(!modal);\n }",
"function showModalEditMenu(url, name, id, url_href, is_active)\n{\n\t$('#myModalEditMenu').modal('show');\n\t$('#namIdMenu').attr(\"value\", id);\n\t$('#namNewMenuE').attr(\"value\", name);\n\t$('#namUrlMenu').attr(\"value\", url);\n\t$('#namUrlHrefMenu').attr(\"value\", url_href);\n\tif (is_active == 1)\n\t{\n\t\t$('#isActiveEdit').attr('checked', 'checked');\n\t}\n}",
"function showModalEdit(url, name, id, title, url_href)\n{\n\t$('#myModalEdit').modal('show');\n\t$('#myModalLabelsE').text('Edit '+title+' - '+name);\n\t$('#namId').attr(\"value\", id);\n\t$('#namNew').attr(\"value\", name);\n\t$('#namUrl').attr(\"value\", url);\n\t$('#namUrlHref').attr(\"value\", url_href);\n}",
"toggleEditForm() {\n if (this.state.inputLinkClicked) {\n this.setState({\n inputLinkClicked: false,\n });\n } else {\n this.setState({\n inputLinkClicked: true,\n });\n }\n }",
"function editLink() {\n\t\tvar href = $('[name=href]', editor.legend);\n\t\tvar path = getNodePath(editor.node);\n\t\tvar text = prompt('Edit link of [' + path + ']:', href.length ? href.html() : 'http://');\n\t\tif (text) {\n\t\t\thref.html(text);\n\t\t\teditor.enable();\n\t\t}\n\t}",
"function openLinkDialog() {\n var inviteAttributes = void 0;\n\n if (roomUrl === null) {\n inviteAttributes = 'data-i18n=\"[value]roomUrlDefaultMsg\" value=\"' + APP.translation.translateString(\"roomUrlDefaultMsg\") + '\"';\n } else {\n inviteAttributes = \"value=\\\"\" + encodeURI(roomUrl) + \"\\\"\";\n }\n APP.UI.messageHandler.openTwoButtonDialog(\"dialog.shareLink\", null, null, '<input id=\"inviteLinkRef\" type=\"text\" ' + inviteAttributes + ' onclick=\"this.select();\" readonly>', false, \"dialog.Invite\", function (e, v) {\n if (v && roomUrl) {\n JitsiMeetJS.analytics.sendEvent('toolbar.invite.button');\n emitter.emit(_UIEvents2.default.USER_INVITED, roomUrl);\n } else {\n JitsiMeetJS.analytics.sendEvent('toolbar.invite.cancel');\n }\n }, function (event) {\n if (roomUrl) {\n document.getElementById('inviteLinkRef').select();\n } else {\n if (event && event.target) {\n $(event.target).find('button[value=true]').prop('disabled', true);\n }\n }\n }, function (e, v, m, f) {\n if (!v && !m && !f) JitsiMeetJS.analytics.sendEvent('toolbar.invite.close');\n });\n}",
"function openLink() {\n window.open(link_placeholder);\n return false;\n }",
"function handleCrmLinkModal(event){\n \n setCurrentCrmOppType(event.currentTarget.id);\n crmModalToggle();\n setCurrentCrmSelectedOpp(null);\n setCurrentCrmSelectedOppText(\"Type-in and Select the CRM Opportunity to link !\");\n }",
"function editLink() {\n Graph.editLinkLabel(Graph.selectedLink, linkLabelInput.val());\n Networker.updateLink(Graph.selectedLink);\n // Close the panel after update.\n Graph.unselectLink();\n updateMenu();\n}",
"toggleSetLinkForm() {\n this.setState({ openSetLink: !this.state.openSetLink });\n }",
"toggleModal() {\n this.isModalOpen = !this.isModalOpen;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a classroom and add it to the stored "list" ("dictionary" / object literal) of classroom objects | function createClassroom(classroomid) {
classrooms[classroomid] = {
clients: {},
students: {},
teacher: undefined
};
} | [
"addRoom(){\n\t\tvar newRoom = new Room(this);\n\t\tthis.rooms.push(newRoom);\n\t}",
"function setup_default_room(){\n var list = ['Java is the best', 'C++/C is the best', 'Python is the best', 'PHP is the best', 'JavaScript is the best'];\n for (var i =0, size = list.length; i < size; i++){\n console.log(list[i]);\n rooms[list[i]] = { room: list[i], users : { admin : 'admin' } };\n }\n console.log(rooms)\n}",
"function createClassroom(row) {\n return new Classroom(row.classroom, row.maxNumberOfSeats);\n}",
"createGameObjects() {\n this.background = new Background(this);\n this.plane = new Plane(this);\n this.sea = new Sea(this);\n this.dashboard = new Dashboard(this);\n this.boat = new Boat(this);\n this.backgroundGameObjects = [this.background, this.plane];\n this.parachutists = new LinkedList();\n this.foregroundGameObjects = [this.sea, this.dashboard, this.boat];\n }",
"createFoyer () {\n this.rooms.push(new Room('foyer', 'foyer.dae'))\n }",
"function Classroom (width, height, className, classType, ghostSeats, leftSeats, totalSeats, numPerStation) {\n this.width = width\n this.height = height\n this.className = className\n this.classType = classType\n this.ghostSeats = ghostSeats\n this.leftSeats = leftSeats\n this.totalSeats = totalSeats\n this.numPerStation = numPerStation\n this.seatOrder = [] // param if room is a lab\n}",
"function initializeRoomData() {\n\tvar rooms = JSONData.rooms;\n\tfor (var i = 0; i < rooms.length; i++) {\n\t\tvar newRoom = {};\n\t\tnewRoom[\"_id\"] = generateUUID();\n\t\tnewRoom.title = rooms[i].prefix + \" \" + rooms[i].number;\n\t\tnewRoom.classes = [];\n\t\troomData.push(newRoom);\n\t}\n}",
"AddRoom(room)\n {\n this.rooms[room.ID] = room;\n }",
"function relationships_classes() {\n //part 1: create properties field for classes\n let keyArray1 = Object.keys(memory_classes);\n for (let i = 0; i < keyArray1.length; i++) {\n memory_classes[keyArray1[i]][\"properties\"] = [];\n }\n}",
"create () {\n\t\t\t\tconst { name, location, date, rock } = this.get();\t\t//creates a constant to the list\n\t\t\t\trock.push({ name, location, date });\t\t//used push() method to add one data endo of the list\n\t\t\t\tthis.set({\n\t\t\t\t\trock,\n\t\t\t\t\tname: '',\n\t\t\t\t\tlocation: '',\n date: '',\n\t\t\t\t\tlist: rock.length + 1\t\t\t\t\t\t\t\t\t//adds 1 data to the length of list\n\t\t\t\t});\n\t\t\t}",
"function createBuildings() {\n buildings = [];\n let buildingA = new Building(\"A\");\n let buildingB = new Building(\"B\");\n let buildingC = new Building(\"C\");\n let buildingD = new Building(\"D\");\n let buildingE = new Building(\"E\");\n\n buildings.push(buildingA,buildingB,\n buildingC,buildingD,buildingE);\n}",
"function create_room(room)\n{\n\tvar players = room.players;\t// this is an array of player info\n\t// NOTE: the id of tag CANNOT BE a number, so need to add \"room\" before the number\n\t$(\"#game_hall\").append(\"<li class='room' id='r\" + room.id + \"'></li>\");\n\tconsole.log(\"room \" + JSON.stringify(room));\n\n\tvar li_tag = find_room_tag(room.id);\n\t// put the room number\n\t// $(\"#r\" + room.id).append(\"<p>Room \" + (++num_room) + \"</p>\");\n\t$(\"#r\" + room.id).append(\"<p class=\\\"room_title\\\"> Game Room </p>\");\n\n\t// adding the seat in the room\n\tfor(var i = 2; i >= 0; i--)\n\t{\n\t\t$(\"#r\" + room.id).append(\"<div class='seat\" + i + \"'></div>\");\n\t}\n\t\n\t// check if occurpied, if yes, then fill in color\n\t// we separate because the seat1 and seat3 maybe occupied, but not others\n\t\n\tfor(var i = 0; i < players.length; i++)\n\t{\n\t\tvar num = players[i].color\n\t\t// var color = $(\"#r\" + room.id + \" .seat\" + num).css(\"color\");\n\t\t// $(\"#r\" + room.id + \" .seat\" + num).css(\"background\", color);\n\t\t$(\"#r\" + room.id + \" .seat\" + num).addClass('fillSeat');\n\t}\n\t\n\t// there is still available seat in the room\n\tif(players.length < 3)\n\t{\n\t\tli_tag.title = \"Join game\";\n\t\t// add event listener for other to join in the game\n\t\tli_tag.addEventListener(\"click\", join_game, false);\n\t}\n\telse\t// when the room is full\n\t{\n\t\tli_tag.title = \"Room is full\";\n\t\t// need to remove it if the room is available again\n\t\tli_tag.addEventListener(\"click\", room_is_full, false); \n\t}\n}",
"addPlayer (firstName, lastName, age){\r\n let player = {\r\n firstName,\r\n lastName,\r\n age\r\n }\r\n //adding an instance object to the players list\r\n this._players.push(player);\r\n }",
"function Pickups (room) {\n\n //hold individual pickup objects\n this.objects = {};\n\n //counter for object id's\n this.idCounter = 0;\n\n //save room that object exists in\n this.room = room;\n}",
"function CaroNewGame(room) {\n currentRoom = CaroRooms.get(room);\n const board = new CaroBoard();\n currentRoom.board = board;\n}",
"addRooms(state, rooms) {\n for (let r of rooms) {\n if (state.rooms.hasOwnProperty(r.id)) { continue; }\n Vue.set(state.rooms, r.id, new Room(r.id, r.name, r.users, r.picture_url));\n }\n }",
"add(room) {\n\tthis._rooms[room.identifier] = room;\n\treturn room;\n }",
"function addRoom(room,pwd,game){\n rooms.push({room,pwd,game});\n}",
"function createRoom(cinemaId,name,numberOfRows,numberOfseatsByRows){\n \n let room =new Room(name,numberOfRows,numberOfseatsByRows)\n createdCinema[cinemasId].rooms.push(room)\n\n return room;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get metadata for a fax file pass in name of the fax file pass in response object | getFaxMetadata(faxFileName, res){
try{
this._connectToMongo();
} catch(e) {
console.error(e);
return res.status(500).send('Internal Server Error');
}
mongoose.connection.once('open', async function() {
console.log('connection opened for downloading');
var gridfs = Grid(mongoose.connection.db);
if (gridfs) {
gridfs.files.find({filename: faxFileName}).toArray(function(err, files) {
if(!files || files.length === 0) {
return res.status(404).send('No matching files found!');
}
// pass in metadata as JSON response
res.set('Content-Type', 'application/json');
return res.status(200).send(files[0].metadata);
})
} else {
console.error('No GridFS object found');
return res.status(500).send('Internal Server Error!');
}
await setTimeout(() => {
console.log('metadata for fax file with name '+faxFileName+' sent successfully');
mongoose.connection.close();
console.log('database connection closed');
}, 3000);
});
} | [
"static metadataFromFile(file) {\n return {\n filename: file.name,\n };\n }",
"function extract_fax_info(sfax_response_obj){\n //var sfax_response_obj = JSON.parse('{\"inboundFaxItem\":{\"FaxId\":\"2190401201000980691\",\"Pages\":\"4\",\"ToFaxNumber\":\"18557916085\",\"FromFaxNumber\":\"5302731333\",\"FromCSID\":\"2731333\",\"FaxDateUtc\":\"4/1/2019 8:10:18 PM\",\"FaxSuccess\":\"1\",\"Barcodes\":{\"FirstBarcodePage\":1,\"TotalPagesWithBarcodes\":1,\"PagesWithBarcodes\":[1],\"BarcodeItems\":[{\"BarcodeSpacingXAxis\":0,\"BarcodeSpacingYAxis\":0,\"BarcodeType\":0,\"BarcodeMode\":1,\"BarcodeData\":\"9612019971424215517488\",\"BarcodeX\":157,\"BarcodeY\":1773,\"BarcodePage\":1,\"BarcodeScale\":0,\"BarcodeWidth\":684,\"BarcodeHeight\":303},{\"BarcodeSpacingXAxis\":0,\"BarcodeSpacingYAxis\":0,\"BarcodeType\":0,\"BarcodeMode\":1,\"BarcodeData\":\"[)>010295112840019971424215517488FDEB97142420501/12.0LBN725 E. Santa Clara Street, Ste 202San JoseCA 0610ZGD00811ZBetter Health Pharmacy12Z650488743423ZN22ZN20Z 028Z97142421551748831Z 33Z 34Z019KD261R818T33379P26Z1891\",\"BarcodeX\":116,\"BarcodeY\":1455,\"BarcodePage\":1,\"BarcodeScale\":0,\"BarcodeWidth\":556,\"BarcodeHeight\":245}]},\"InboundFaxId\":\"2190401201000980691\",\"FaxPages\":\"4\",\"FaxDateIso\":\"2019-04-01T20:10:18Z\",\"WatermarkId\":\"2190401201018997198\",\"CreateDateIso\":\"2019-04-01T20:10:18.1207720Z\"},\"isSuccess\":true,\"message\":null}')\n\n var res = {}\n \n if(!sfax_response_obj['inboundFaxItem']) return sfax_response_obj //if it's an error, then just return original content\n \n //debugEmail('SFax Response to Query about Inbound details', JSON.stringify(sfax_response_obj))\n \n res['faxPages'] = sfax_response_obj['inboundFaxItem']['FaxPages']\n res['faxSuccess'] = sfax_response_obj['inboundFaxItem']['FaxSuccess']\n var barcodes = sfax_response_obj['inboundFaxItem']['Barcodes']['BarcodeItems']\n var tracking_nums = []\n var rx = /971424215(\\d{6})/\n for(var i = 0; i < barcodes.length; i++){\n var parsed = barcodes[i]['BarcodeData'].toString().match(rx)\n if(parsed) tracking_nums.push(parsed[0].toString())\n }\n res['tracking_nums'] = \"\" + tracking_nums\n Logger.log(res)\n return res\n}",
"function getMetadataForFile(n, callback) {\n var fileinfo = createdFiles[n];\n var fileRequest = storage.get(fileinfo.name); \n fileRequest.onsuccess = function() {\n var file = fileRequest.result;\n dsdb.metadataParser(file, function(metadata) {\n fileinfo.metadata = metadata;\n n++;\n if (n === createdFiles.length) // if we're done\n callback();\n else // Otherwise get the next one\n getMetadataForFile(n, callback);\n });\n }\n }",
"function getFileMetadata(req, res) {\n var upload = multer({ storage: storage }).single('upfile');\n upload(req, res, () => {\n return res.json({\n name: req.file.originalname,\n type: req.file.mimetype,\n size: req.file.size\n })\n });\n}",
"getfileMetadata() {\n this.getFileMeta.emit();\n }",
"getFile(response) {\n return paths.getJSONFile(this.path, response);\n }",
"function despMetadataFile(file) {\n console.log(\"Se eligio un archivo: --- --- ---\");\n console.log(\"Id: \" + file.id);\n console.log(\"Titulo: \" + file.title);\n console.log(\"MIME Type: \" + file.mimeType);\n console.log(\"Download link: \" + file.webContentLink);\n console.log(\"File extension: \" + file.fileExtension)\n}",
"function getMetadata()\n {\n var displayMetadata = function(metadata) {\n navigator.notification.alert(metadata, null, 'Metadata');\n },\n callback = function(entry) {\n entry.getMetadata(displayMetadata, onFileSystemError);\n };\n \n // look up file system entry and display its metadata\n window.resolveLocalFileSystemURI(getFileSystemURI(), callback, onFileSystemError);\n }",
"function getMetaData (filePath, cb) {\n ffmpeg.ffprobe(filePath, function (err, metadata) {\n if (err) {\n logger.error('ffmpeg cannot get metadata for file: ' + filePath)\n cb(null)\n } else { cb(metadata) }\n })\n}",
"function r(e){return{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.filename||e.name,size:e.size,type:e.type,uid:e.uid,response:e.response,error:e.error,percent:0,originFileObj:e}}",
"async getFileMetadata() {\n return this.fileMetadata;\n }",
"function getMetadata (bucketName, fileName, callback) {\n // Instantiates a client\n const storageClient = Storage();\n\n // References an existing bucket, e.g. \"my-bucket\"\n const bucket = storageClient.bucket(bucketName);\n\n // References an existing file, e.g. \"file.txt\"\n const file = bucket.file(fileName);\n\n // Gets the metadata for the file\n file.getMetadata((err, metadata) => {\n if (err) {\n callback(err);\n return;\n }\n\n console.log(`File: ${metadata.name}`);\n console.log(`Bucket: ${metadata.bucket}`);\n console.log(`Storage class: ${metadata.storageClass}`);\n console.log(`ID: ${metadata.id}`);\n console.log(`Size: ${metadata.size}`);\n console.log(`Updated: ${metadata.updated}`);\n console.log(`Generation: ${metadata.generation}`);\n console.log(`Metageneration: ${metadata.metageneration}`);\n console.log(`Etag: ${metadata.etag}`);\n console.log(`Owner: ${metadata.owner}`);\n console.log(`Component count: ${metadata.component_count}`);\n console.log(`Crc32c: ${metadata.crc32c}`);\n console.log(`md5Hash: ${metadata.md5Hash}`);\n console.log(`Cache-control: ${metadata.cacheControl}`);\n console.log(`Content-type: ${metadata.contentType}`);\n console.log(`Content-disposition: ${metadata.contentDisposition}`);\n console.log(`Content-encoding: ${metadata.contentEncoding}`);\n console.log(`Content-language: ${metadata.contentLanguage}`);\n console.log(`Metadata: ${metadata.metadata}`);\n callback();\n });\n}",
"function getSourceMetadata() {\n sourceFactory.getSourceMetadata()\n .then(function (response) {\n $scope.metadata = response.data.data;\n /*var customObj = {\"commonName\":\"CUSTOM\"};\n $scope.metadata.push(customObj);*/\n },\n function (error) {\n var objCustom = {'displayValue': id, 'mode': 'fetch'};\n $scope.error = $rootScope.getErrorMessage(error, $scope.section, objCustom);\n $scope.error = message;\n toasterService.showToastr(message, 'error');\n }\n );\n }",
"function showMetadata(fileId) {\n var fileUrl1 = \"files/\" + fileId + '.json';\n console.log(fileUrl1);\n var xmlHttpResult1 = new XMLHttpRequest();\n xmlHttpResult1.open(\"GET\", fileUrl1, false);\n xmlHttpResult1.send(null); \n if(xmlHttpResult1.status != 404) { \n var obj1 = $.parseJSON(xmlHttpResult1.responseText);\n\n if(obj1.fileName) {\n var fileUrl2 = \"files/\" + obj1.fileName + '.json';\n console.log(fileUrl2);\n var xmlHttpResult2 = new XMLHttpRequest();\n xmlHttpResult2.open(\"GET\", fileUrl2, false);\n xmlHttpResult2.send(null); \n if(xmlHttpResult2.status == 404) {\n ; // do nothing.\n }\n else {\n var obj2 = $.parseJSON(xmlHttpResult2.responseText); \n\n $('#queueResultDiv').removeClass();\n $('#queueResultDiv').addClass('alert alert-success'); \n $('#queueResultDiv').empty().append('Your file has been processed successfully.<br>'\n + '<br>File Name: ' + obj2.fileName \n + '<br>File Size: ' + obj2.fileSize + ' Bytes' \n + '<br>Processing Time: ' + obj2.estimatedTime + ' Seconds'\n + '<br>Uploaded on: ' + obj1.timeStamp);\n $('#queueResultDiv').show();\n } \n } \n }\n }",
"get metadata(){\r\n\t\treturn this.store.metadata(this.path) }",
"function getFile(response) {\n return new File(getData(response));\n }",
"function metadata(stream, callback) {\n form.parse(stream, (error, fields, files) => {\n\n if (error) {\n callback(new Error());\n return;\n }\n\n if (!files.files) {\n callback(null, null);\n return;\n }\n\n if (!(files.files instanceof Array)) {\n callback(null, {name: files.files.name, size: files.files.size, md5: files.files.hash});\n return;\n }\n\n callback(null, files.files.reduce((accumulator, file) => {\n return accumulator.concat({name: file.name, size: file.size, md5: file.hash});\n }, []));\n\n });\n}",
"function loadFilesMetaFromServer() {\n\n var lURLRestAPI = LocalData.getAppSetting('url-restapi');\n LocalData.addSessionLogMessage('ApplicationDataSynchronizer - Refresh Files metadata from \"'+lURLRestAPI+'file/\" !');\n\n // Launch AJAX Request !\n Axios.get('file/')\n .then(function(response){\n if(response.status == 200){\n console.log('ApplicationDataSynchronizer - HTTP GET Response OK (HTTP:200).');\n LocalData.addSessionLogMessage('ApplicationDataSynchronizer - HTTP GET Response OK (HTTP:200).');\n LocalData.setFiles(response.data);\n }\n else {\n console.log('AppMyDocsContainer - Erreur lors du chargement des données des Fichiers (HTTP Code:'+response.status+').');\n }\n }).catch(function(error){\n console.log(error);\n });\n}",
"function donwload_metadata(token, file_path) {\n return new Promise(function (resolve, reject) {\n var URI = \"https://graph.microsoft.com/v1.0/me/drive/root:/\" + file_path;\n\n var metaData_request = new XMLHttpRequest();\n\n metaData_request.onreadystatechange = function () {\n if (this.readyState == 4) {\n if (this.status == 200) {\n resolve([this.status, metaData_request.responseText]);\n } else {\n reject([this.status, metaData_request.responseText]);\n }\n }\n };\n metaData_request.open(\"GET\", URI, true);\n metaData_request.setRequestHeader(\"Authorization\", \"bearer \" + token);\n metaData_request.send();\n });\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Partitions a given array into 2 arrays, based on a boolean value returned by the condition function. | function partitionArray(arr, conditionFn) {
const truthy = [];
const falsy = [];
for (const item of arr) {
(conditionFn(item) ? truthy : falsy).push(item);
}
return [truthy, falsy];
} | [
"function partitionArray(arr, conditionFn) {\n const truthy = [];\n const falsy = [];\n for (const item of arr) {\n (conditionFn(item) ? truthy : falsy).push(item);\n }\n return [truthy, falsy];\n }",
"function partitionArray(arr, conditionFn) {\n var truthy = [];\n var falsy = [];\n\n var _iterator = (0,D_Projects_capacitor_pwa_app_pedido_node_modules_babel_runtime_helpers_esm_createForOfIteratorHelper_js__WEBPACK_IMPORTED_MODULE_11__[\"default\"])(arr),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var item = _step.value;\n (conditionFn(item) ? truthy : falsy).push(item);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return [truthy, falsy];\n}",
"function partition(arr, partitioner) {\n let newArr = [];\n let trueArr = [];\n let falseArr = [];\n for (let i = 0; i < arr.length; i++) {\n if (partitioner(arr[i], i, arr) === true) {\n trueArr.push(arr[i])\n } else {\n falseArr.push(arr[i])\n }\n }\n newArr.push(trueArr, falseArr);\n return newArr;\n}",
"function arrayPartition(array, predicate) {\n const pass = [];\n const fail = [];\n array.forEach(elem => predicate(elem) ? pass.push(elem) : fail.push(elem));\n return [pass, fail];\n}",
"function partition(array, func) {\n var resolvesTrue = [];\n var resolvesFalse = [];\n var sortedTF = [];\n for (var i = 0; i < array.length; i++) {\n if (func(array[i], i , array)) {\n resolvesTrue.push(array[i]);\n } else if (func(array[i], i, array) === false) {\n resolvesFalse.push(array[i]);\n } \n }\n sortedTF.push(resolvesTrue, resolvesFalse);\n return sortedTF;\n }",
"function partitionBy(arr, pred) {\n let ret = arr.length ? [[arr[0]]] : [[]];\n let retidx = 0;\n for (let i = 1; i < arr.length; i++) {\n if (pred(arr[i], i, arr)) {\n ret.push([arr[i]]);\n retidx++;\n }\n else {\n ret[retidx].push(arr[i]);\n }\n }\n return ret;\n}",
"function partition(arr, func){\n var outArray =[];\n outArray.push(filter(arr, func)) + outArray.push(reject(arr, func));\n return outArray;\n }",
"function partition(arr, callback) {\n\treturn arr.reduce(function(acc, next){\n\t\tif(callback(next)) {\n\t\t\tacc[0].push(next);\n\t\t} else {\n\t\t\tacc[1].push(next);\n\t\t}\n\t\treturn acc;\n\t}, [[],[]])\n}",
"function prioritize(array, callback){\n const trueArr = []\n const falseArr = [];\n for(let i = 0; i < array.length; i++){\n const output = callback(array[i])\n if(output === false){\n falseArr.push(array[i])\n } else {\n trueArr.push(array[i])\n }\n }\n return trueArr.concat(falseArr)\n}",
"__map_int_to_bool(arr, dim) {\n let new_arr = []\n if (dim == 2) {\n arr.map(outer_val => {\n let temp_arr = []\n outer_val.map(val => {\n if (val == 1) {\n temp_arr.push(true)\n } else {\n temp_arr.push(false)\n }\n })\n new_arr.push(temp_arr)\n })\n return new_arr\n } else {\n arr.map(val => {\n if (val == 1) {\n new_arr.push(true)\n } else {\n new_arr.push(false)\n }\n })\n return new_arr\n }\n\n }",
"function processArray(a) {\n\t\tvar p = composePredicatesWith(preds, and);\n\t\treturn a.reduce(function(acc, current){\n\t\t\treturn acc && p(current);\n\t\t}, true);\n\t}",
"function untilTrue(array) {\n // While first element of array returns false from args[1] -- remove first element\n while (!args[1](array[0])) {\n array.shift();\n }\n // return array with removed elements array[0] now returns true for args[1]\n return array;\n }",
"function evenOddPartition(arr) {\n evenArr = []\n oddArr = []\n // outputArr = [evenArr, oddArr]\n outputArr = [oddArr, evenArr]\n console.log(arr)\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2) {\n evenArr.push(arr[i])\n } else {\n oddArr.push(arr[i])\n }\n }\n console.log('outputArr', outputArr)\n return outputArr\n}",
"function partition(collection, pred) {\n const ret = [];\n let i = 0;\n while (i < collection.length) {\n if (pred(collection[i])) {\n ret.push(collection.splice(i, 1)[0]);\n }\n else {\n i++;\n }\n }\n return ret;\n}",
"function bubbleSort(array, conditionFunction) {\n var tempArrayElement;\n for (var j = 0; j < array.length; ++j) {\n for (var i = 0; i < array.length - 1 - j; ++i) {\n if (conditionFunction(array[i], array[i + 1])) {\n tempArrayElement = array[i];\n array[i] = array[i + 1];\n array[i + 1] = tempArrayElement;\n }\n }\n }\n return array;\n}",
"function partitionOn(pred, items) {\n var itemsEven = items.filter(pred);\n itemsOdd = items.filter(function (val) {\n return !pred(val);\n })\n\n val = itemsOdd.length;\n itemsNew = itemsOdd.concat(itemsEven);\n items.length = 0;\n for (i = 0; i < itemsNew.length; i++) {\n items.push(itemsNew[i]);\n }\n return val;\n}",
"function partitionBooksByBorrowedStatus(books) {\n //filter which are loaned out \n let loanedBooks = books.filter((book) => book.borrows[0].returned === false);\n //filter which are returned\n let returnedBooks = books.filter((book) => book.borrows[0].returned === true);\n //returning both inside new arr\n const results = [loanedBooks, returnedBooks];\n\n return results;\n}",
"function partition(predicate, thisArg) {\n return function (source) {\n return [\n Object(filter[\"a\" /* filter */])(predicate, thisArg)(source),\n Object(filter[\"a\" /* filter */])(Object(not[\"a\" /* not */])(predicate, thisArg))(source)\n ];\n };\n}",
"function partition(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> (list<a>, list<a>) */ {\n return partitionAcc(xs, pred, Nil, Nil);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Math.min() and Math.max(): Write a function midrange, that calculates the midrange of 3 numbers. The midrange is the mean of the smallest and largest number. Example: midrange(3, 9, 1) should return (9+1)/2 = 5. | function midrange (a, b,c) {
let min = Math.min(a, b,c);
let max = Math.max(a, b,c);
let mid = (max+min)/2
return mid;
} | [
"function midrange(num1, num2, num3) {\n var theMin = Math.min(num1, num2, num3);\n var theMax = Math.max(num1, num2, num3);\n return (theMin + theMax) / 2;\n}",
"function midrange(num1, num2, num3){\n let min = Math.min(num1, num2, num3);\n let max = Math.max(num1, num2, num3);\n return (min + max) / 2\n }",
"function midrange(a, b, c) {\n return (Math.min(a, b, c) + Math.max(a, b, c)) / 2;\n}",
"function midpoint(range) {\n return range[0] + (range[1] - range[0]) / 2.0;\n}",
"function middle(myRange) {\n const { max: max, min: min } = myRange;\n\n return (max + min) / 2;\n}",
"function threeNums(n1,n2,n3){\n console.log(Math.min(n1,n2,n3))\n console.log(Math.max(n1,n2,n3))\n}",
"function numberBoundaries (num, min, max) {\n return num > max ? max : (num < min ? min : num);\n }",
"function findSminSmaxAtStartingPoint(){\n //เอาไว้เช็คว่า มันเกิน Range รึเปล่า\n //ถ้าเกิน ให้แก้ค่า l/r Window\n var smax = Math.max.apply(null, initial_S);\n console.log(smax)\n var smin = Math.min.apply(null, initial_S);\n console.log(smin)\n savg = (smax + smin) / 2;\n console.log(savg)\n if (smax - smin <= range){\n rightWindow = savg + (range / 2);\n leftWindow = savg - (range / 2);\n }else{\n temprange = smax - smin;\n rightWindow = smax;\n leftWindow = smin;\n }\n\n console.log(leftWindow,rightWindow)\n\n}",
"function scale(value, mid, max, min) {\r\n min = min || 0;\r\n return value > 1 ?\r\n mid + (value - 1) * (max - mid) :\r\n min + value * (mid - min);\r\n}",
"function rangeFunc() {\n let rangeNum = Math.max(num1, num2, num3) - Math.min(num1, num2, num3);\n console.log(\"RANGE: \" + rangeNum);\n results[4].textContent = \"Range: \" + rangeNum;\n}",
"function between(n, min, max) {\n return Math.max(min, Math.min(n, max));\n}",
"function range(num, min, max) {\n\treturn Math.min(Math.max(min, num), max);\n}",
"function between(n, min, max) {\n return Math.max(min, Math.min(n, max));\n}",
"function range(input,min,max) {\n\t\tif(min > max) { var x = min; min = max; max = x;}\n\t\treturn Math.max(Math.min(input,max),min);\n\t}",
"function map_range(input, minIn, maxIn, minOut, maxOut) {\n return minOut + (maxOut - minOut) * (input - minIn) / (maxIn - minIn);\n}",
"function midpoint(minx, maxx, f) {\n var x, mid;\n for(x = minx; x < maxx; x++) {\n if(!f(x)) {\n mid = minx + x;\n if(mid % 2) mid = (mid-1)/2;\n else mid = mid/2;\n return mid;\n }\n }\n }",
"function rangeDivisor(start, end, divisor) {\n const min = start;\n const max = end;\n const number = divisor;\n if(min % number == 0 && max % number == 0){\n return 2;\n }else if(min % number == 0 && max % number !== 0){\n return 1;\n }else if(min % number !== 0 && max % number == 0){\n return 1;\n }else{\n return 0;\n }\n \n}",
"function map(x, in_min, in_max, out_min, out_max,checkRanges) {\n if ((typeof checkRanges != 'undefined') && checkRanges) {\n if (x < in_min) x = in_min;\n else if (x > in_max) x = in_max;\n }\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}",
"constructor(min, mid, max) {\n this.min = min;\n this.max = max;\n\n const min2 = min * min;\n const max2 = max * max;\n const mid2 = mid * mid;\n const tmp0 = min + max - 2 * mid;\n const tmp1 = max - mid;\n this.a = ((2 * max - mid) * min - mid * max) / tmp0;\n this.b = (tmp1 * min2 + (mid2 - max2) * min + mid * max2 - mid2 * max)\n / (min2 + (2 * max - 4 * mid) * min + max2 - 4 * mid * max + 4 * mid2);\n this.c = -tmp1 / tmp0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
movesnitch() Moves the snitch based on random velocity changes | function movesnitch() {
//noise time values
tx = tx + .005;
ty = ty + .015;
nx = noise(tx);
ny = noise(ty);
//map noise to correspond to snitch XY velocity
snitchVX = map(nx,0,1,-snitchMaxSpeed,snitchMaxSpeed);
snitchVY = map(ny,0,1,-snitchMaxSpeed,snitchMaxSpeed);
// Update snitch position based on velocity
snitchX += snitchVX;
snitchY += snitchVY;
// Screen wrapping
if (snitchX < 0) {
snitchX += width;
}
else if (snitchX > width) {
snitchX -= width;
}
if (snitchY < 0) {
snitchY += height;
}
else if (snitchY > height) {
snitchY -= height;
}
} | [
"move() {\n // Set velocity via noise()\n if (random() < 0.05) {\n this.vx = map(random(), 0, 1, -this.speed, this.speed);\n this.vy = map(random(), 0, 1, -this.speed, this.speed);\n }\n super.move();\n // Update time properties\n this.tx += 0.01;\n this.ty += 0.01;\n }",
"function Twitch() {\n\t\tif (ms.x < 6 || ms.y < 6) {\n\t\t\tvar forceRange = 5; // -value to +value\n\t\t\tInsertImpulse(Math.random() * WIDTH, (Math.random() * (forceRange * 2) - forceRange));\n\t\t}\n\t}",
"function twitch() {\n\t\t\tif( ms.x < 6 || ms.y < 6 ) {\n\t\t\t\tvar forceRange = 15; // -value to +value\n\t\t\t\tinsertImpulse( Math.random() * WIDTH, (Math.random()*(forceRange*2)-forceRange ) );\n\t\t\t}\n\t\t}",
"function setupsnitch() {\n snitchX = width/5;\n snitchY = height/2;\n snitchVX = -snitchMaxSpeed;\n snitchVY = snitchMaxSpeed;\n snitchHealth = snitchMaxHealth;\n}",
"function Twitch() {\nif( ms.x < 6 || ms.y < 6 ) {\nvar forceRange = 5; // -value to +value\nInsertImpulse( Math.random() * WIDTH, (Math.random()*(forceRange*2)-forceRange ) );\n}\n}",
"randomPlay() {\n let availablePositions = this.board.getEmptyPositions();\n let totalPossibilities = availablePositions.length;\n let rdm = Math.floor(Math.random() * totalPossibilities);\n \n this.board.performMove(this.playerNo, availablePositions[rdm]);\n \n }",
"function movesmurf() {\n // Change the smurf's velocity at random intervals\n // random() will be < 0.02 2% of the time, so the smurf\n // will change direction on 2% of frames\n if (random() < 0.02) {\n // Set velocity based on random values to get a new direction\n // and speed of movement\n //\n // Use map() to convert from the 0-1 range of the random() function\n // to the appropriate range of velocities for the smurf\n smurfVX = map(noise(smurfNoiseTx), 0, 1, -smurfMaxSpeed, smurfMaxSpeed);\n smurfVY = map(noise(smurfNoiseTy), 0, 1, -smurfMaxSpeed, smurfMaxSpeed);\n smurfNoiseTx += 5;\n smurfNoiseTy += 5;\n }\n\n // Update smurf position based on velocity\n smurfX = smurfX + smurfVX;\n smurfY = smurfY + smurfVY;\n\n // Screen wrapping\n if (smurfX < 0) {\n smurfX = smurfX + width;\n } else if (smurfX > width) {\n smurfX = smurfX - width;\n }\n\n if (smurfY < 0) {\n smurfY = smurfY + height;\n } else if (smurfY > height) {\n smurfY = smurfY - height;\n }\n}",
"randomSteer() {\n this.velocity.rotate(random(-HALF_PI/8, HALF_PI/8))\n }",
"move() {\n // Set velocity via noise()\n this.vx = map(noise(this.tx), 0, 1, -this.speed, this.speed);\n this.vy = map(noise(this.ty), 0, 1, -this.speed, this.speed);\n // Update position\n this.x += this.vx;\n this.y += this.vy;\n // Update time properties\n this.tx += 0.02;\n this.ty += 0.02;\n // Handle wrapping\n this.handleWrapping();\n }",
"move() {\n // Set velocity via noise()\n this.vx = map(noise(this.tx), 0, 1, -this.speed, this.speed);\n this.vy = map(noise(this.ty), 0, 1, -this.speed, this.speed);\n // Update position\n this.x += this.vx;\n this.y += this.vy;\n // Update time properties\n this.tx += 0.01;\n this.ty += 0.01;\n // Handle wrapping\n this.handleWrapping();\n }",
"move() {\n // Set velocity via noise()\n this.vx = map(noise(this.tx), 0, 1, -this.speed, this.speed);\n this.vy = map(noise(this.ty), 0, 1, -this.speed, this.speed);\n // Update position\n this.x += this.vx;\n this.y += this.vy;\n // Update time properties\n this.tx += 0.01;\n this.ty += 0.01;\n // Handle wrapping\n this.handleWarping();\n //////////////// FIXED = move() function has no end bracket, added one\n }",
"move() {\n this.x += random(-5, 5);\n this.y += random(-5, 5);\n }",
"move() {\n // Set velocity via noise()\n this.vx = map(noise(this.tx), 0, 1, -this.speed, this.speed);\n this.vy = map(noise(this.ty), 0, 1, -this.speed, this.speed);\n // Update position\n this.x += this.vx;\n this.y += this.vy;\n // Update time properties\n this.tx += 0.01;\n this.ty += 0.01;\n // Update health\n this.health += 0.1;\n this.health = constrain(this.health, 1, this.maxHealth);\n // Handle wrapping\n this.handleWrapping();\n }",
"move(){\n if (Math.random()<0.01){\n this.x+=100*Math.random()-50;\n this.y+=100*Math.random()-50;\n }\n }",
"function movePrey() {\n // Change the prey's velocity at random intervals\n // random() will be < 0.05 5% of the time, so the prey\n // will change direction on 5% of frames\n if (random() < 0.05) {\n // Set velocity based on random values to get a new direction\n // and speed of movement\n // Use map() to convert from the 0-1 range of the noise function\n // to the appropriate range of velocities for the prey\n preyTX = random(0,500);\n preyTY = random(0,500);\n preyVX = map(noise(preyTX),0,1,-preyMaxSpeed,preyMaxSpeed);\n preyVY = map(noise(preyTY),0,1,-preyMaxSpeed,preyMaxSpeed);\n }\n\n // Update prey position based on velocity\n preyX += preyVX;\n preyY += preyVY;\n\n // Screen wrapping\n if (preyX < 0) {\n preyX += width;\n }\n else if (preyX > width) {\n preyX -= width;\n }\n\n if (preyY < 0) {\n preyY += height;\n }\n else if (preyY > height) {\n preyY -= height;\n }\n preyTX += 0.01;\n preyTY =+ 0.01;\n}",
"function movePrey() {\n // Change the prey's velocity at random intervals\n // random() will be < 0.05 5% of the time, so the prey\n // will change direction on 5% of frames\n if (random() < 0.05) {\n // Set velocity based on random values to get a new direction\n // and speed of movement\n // Use map() to convert from the 0-1 range of the random() function\n // to the appropriate range of velocities for the prey\n preyVX = map(random(),0,1,-preyMaxSpeed,preyMaxSpeed);\n preyVY = map(random(),0,1,-preyMaxSpeed,preyMaxSpeed);\n }\n\n // Update prey position based on velocity\n preyX += preyVX;\n preyY += preyVY;\n\n // Screen wrapping\n if (preyX < 0) {\n preyX += width;\n //Added random size to be generated for the prey everytime it goes offscreen\n preyRadius = random(35,75);\n }\n else if (preyX > width) {\n preyX -= width;\n preyRadius = random(35,75);\n }\n\n if (preyY < 0) {\n preyY += height;\n preyRadius = random(35,75);\n }\n else if (preyY > height) {\n preyY -= height;\n preyRadius = random(35,75);\n }\n}",
"drift() {\n this.posX = this.posX + this.deltaX;\n this.posY = this.posY + this.deltaY;\n }",
"function rand_velocity_modifier () {\n\treturn Math.floor(Math.random()*5) +1;\n}",
"collide(snitch) {\n let d = dist(this.x, this.y, snitch.x, snitch.y)\n if (d < 30) {\n introspellSFX.play();\n image(this.image, width / 2, height / 2, 1400, 1400);\n snitch.frozen = true;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Occasionally it may be useful to make an expression behave as if it was 'hoisted', whereby the result of the expression is available before its location in the source, but the expression's variable scope corresponds to the source position. This is used extensively to deal with executable class bodies in classes. Calling this method mutates the node, proxying the `compileNode` and `compileToFragments` methods to store their result for later replacing the `target` node, which is returned by the call. | hoist() {
var compileNode, compileToFragments, target;
this.hoisted = true;
target = new HoistTarget(this);
compileNode = this.compileNode;
compileToFragments = this.compileToFragments;
this.compileNode = function(o) {
return target.update(compileNode, o);
};
this.compileToFragments = function(o) {
return target.update(compileToFragments, o);
};
return target;
} | [
"hoist() {\n var compileNode, compileToFragments, target;\n this.hoisted = true;\n target = new HoistTarget(this);\n compileNode = this.compileNode;\n compileToFragments = this.compileToFragments;\n this.compileNode = function(o) {\n return target.update(compileNode, o);\n };\n this.compileToFragments = function(o) {\n return target.update(compileToFragments, o);\n };\n return target;\n }",
"AssignmentExpression(path) {\n const { start, end } = path.node;\n path.insertAfter(createTraceCall({\n bindings: getBindingsForScope(path.scope, this.bindings),\n ...getOffsettedRange(start, end, this.fnOffset),\n }));\n }",
"function normalizeExpression(nd, target) {\n var res;\n function getTarget() {\n return target || (target = genTmp());\n }\n \n switch(nd.type) {\n case 'Literal':\n // target = literal;\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), nd))];\n break;\n \n case 'Identifier':\n var tmp = null;\n if(!isTmp(nd.name) && scope.isGlobal(nd.name)) {\n // global reads are rewritten into property accesses on __global; however, reading an undeclared, undefined global\n // should result in a ReferenceError, so we (optionally) introduce an if statement checking whether the global has\n // been declared/defined, and throw an error if not\n \n // temporary to hold the name of the global\n tmp = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.name)))];\n \n if(!options.reference_errors || scope.isDeclaredGlobal(nd.name)) {\n // target = __global[tmp];\n res[1] = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true)));\n } else {\n // check for shadowing of ReferenceError; give up if this happens\n // TODO: even if it isn't shadowed, some clown may have overwritten ReferenceError...\n if(!scope.isGlobal('ReferenceError'))\n throw new Error(\"global variable ReferenceError is shadowed\");\n \n /* tmp2 = x in __global;\n * if(tmp2) {\n * target = __global[tmp2];\n * } else {\n * tmp3 = 'ReferenceError';\n * tmp4 = __global[tmp3];\n * tmp5 = new tmp4();\n * throw tmp5;\n * } */\n var tmp2 = genTmp(), tmp3 = genTmp(), tmp4 = genTmp(), tmp5 = genTmp();\n res = res.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier('__global')))),\n mkIf(tmp2,\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true)))],\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp3), new ast.Literal('ReferenceError'))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp4), new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp3), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp5), new ast.NewExpression(new ast.Identifier(tmp4), []))),\n new ast.ThrowStatement(new ast.Identifier(tmp5))]));\n }\n } else {\n // locals are easy: target = x;\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(nd.name)))];\n }\n \n // handle possible 'with' bindings\n var with_bindings = scope.possibleWithBindings(nd.name);\n if(with_bindings.length) {\n var prelude = null;\n \n // load name of variable into 'tmp'; store code to do so into 'prelude'\n if(tmp) {\n prelude = res[0];\n res.shift();\n } else {\n tmp = genTmp();\n prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.name))); \n }\n \n with_bindings.forEach(function(with_var) {\n /*\n * tmp2 = tmp in with_var;\n * if(tmp2) {\n * target = with_var[tmp];\n * } else {\n * ...\n * }\n */\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(tmp), true)))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n break;\n \n case 'ArrayExpression':\n // allocate one temporary variable per array element (y1, ..., yn)\n var elt_tmps = genTmps(nd.elements.length);\n // recursively normalize array element expressions, skipping over omitted elements; the temporary will then\n // keep its initial undefined value, which is what we want\n var elements = nd.elements.flatmap(function(elt, i) { return elt ? normalizeExpression(elt, elt_tmps[i]) : []; });\n // target = [y1, ..., yn];\n res = elements.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.ArrayExpression(elt_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n \n case 'ObjectExpression':\n // allocate one temporary variable per property; we may not need all of them if there are getters or setters\n var prop_tmps = genTmps(nd.properties.length);\n var props = [];\n var body = nd.properties.flatmap(function(prop, i) {\n switch(prop.kind) {\n case 'init':\n props[props.length] = new ast.Property(prop.key, new ast.Identifier(prop_tmps[i]), 'init');\n inheritPosition(props[props.length-1], prop);\n // recursively normalize property value expression\n return normalizeExpression(prop.value, prop_tmps[i]);\n case 'get':\n case 'set':\n // recursively normalize getter/setter\n var funexpr = normalizeEntity(prop.value, new scopes.FunctionScope(scope, prop.value));\n props[props.length] = new ast.Property(prop.key, funexpr, prop.kind);\n inheritPosition(props[props.length-1], prop);\n return [];\n default:\n throw new Error();\n }\n });\n res = body.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.ObjectExpression(props))));\n break;\n \n case 'MemberExpression':\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd), base_tmp);\n var index = normalizeExpression(getIndex(nd), index_tmp);\n var idx = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n // remember whether this member expression was a computed one originally\n if(nd.computed)\n ast.setAttribute(idx, 'isComputed', true);\n res = base.concat(index,\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), idx)));\n break;\n \n case 'ThisExpression':\n if(scope instanceof scopes.GlobalScope)\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier('__global')))];\n else\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.ThisExpression()))];\n break;\n \n case 'FunctionExpression':\n var fn = normalizeEntity(nd, new scopes.FunctionScope(scope, nd));\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), fn))];\n break;\n \n case 'AssignmentExpression':\n if(nd.operator === '=') {\n // simple assignments are handled similar to case 'Identifier' above\n if(nd.left.type === 'Identifier') {\n var res, tmp = null, right;\n var with_bindings = scope.possibleWithBindings(nd.left.name);\n if(!isTmp(nd.left.name) && scope.isGlobal(nd.left.name)) {\n tmp = genTmp();\n right = normalizeExpression(nd.right, getTarget());\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.left.name))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true),\n new ast.Identifier(getTarget())))];\n } else {\n // mark variables that are written across scopes\n if(!scope.isLocal(nd.left.name))\n ast.setAttribute(scope.lookup(nd.left.name), 'exposed', true);\n \n if(target || with_bindings.length) {\n right = normalizeExpression(nd.right, getTarget());\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(nd.left.name), new ast.Identifier(getTarget())))];\n } else {\n target = nd.left.name;\n right = normalizeExpression(nd.right, nd.left.name);\n res = [];\n }\n }\n \n // handle 'with'\n if(with_bindings.length) {\n var prelude = null;\n if(tmp) {\n prelude = res[0];\n res.shift();\n } else {\n tmp = genTmp();\n prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.left.name))); \n }\n \n with_bindings.forEach(function(with_var) {\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(tmp), true), new ast.Identifier(getTarget())))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n \n res = right.concat(res);\n } else if(nd.left.type === 'MemberExpression') {\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd.left), base_tmp),\n index = normalizeExpression(getIndex(nd.left), index_tmp);\n var lhs = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n \n if(nd.left.computed)\n ast.setAttribute(lhs, 'isComputed', true);\n \n var rhs_comp = normalizeExpression(nd.right, getTarget());\n res = base.concat(index, rhs_comp, new ast.ExpressionStatement(new ast.AssignmentExpression('=', lhs, new ast.Identifier(getTarget()))));\n } else {\n throw new Error(\"unexpected lhs of type \" + nd.left.type);\n }\n } else {\n // compound assignments are desugared into normal assignments and then rewritten recursively\n var op = nd.operator.substring(0, nd.operator.length-1);\n var lhs = nd.left, rhs = nd.right;\n \n if(nd.left.type === 'Identifier') {\n var tmp = genTmp();\n res = normalizeExpression(rhs, tmp)\n .concat(normalizeExpression(new ast.AssignmentExpression('=', new ast.Identifier(nd.left.name), new ast.BinaryExpression(op, new ast.Identifier(nd.left.name), new ast.Identifier(tmp)))));\n } else if(nd.left.type === 'MemberExpression') {\n var tmp = genTmp(), trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp();\n \n res = normalizeExpression(getBase(lhs), base_tmp)\n .concat(normalizeExpression(getIndex(lhs), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n normalizeExpression(rhs, tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.BinaryExpression(op, new ast.Identifier(extra), new ast.Identifier(tmp)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true), new ast.Identifier(target))));\n } else {\n throw new Error(\"unexpected lhs\");\n }\n }\n break;\n \n case 'CallExpression':\n if(nd.callee.type === 'MemberExpression') {\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd.callee), base_tmp);\n var index = normalizeExpression(getIndex(nd.callee), index_tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n var callee = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n \n if(nd.callee.computed)\n ast.setAttribute(callee, 'isComputed', true);\n \n res = base.concat(index, args,\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(callee, arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n } else if(nd.callee.type === 'Identifier') {\n if(nd.callee.name === 'eval') {\n // TODO: handle 'eval' inside 'with'\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = args.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(nd.callee, arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n } else {\n var tmp = genTmp();\n var fn = normalizeExpression(nd.callee, tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast[nd.type](new ast.Identifier(tmp), arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); }))))];\n \n var with_bindings = scope.possibleWithBindings(nd.callee.name);\n if(with_bindings.length) {\n var name_tmp = genTmp();\n var prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(name_tmp), new ast.Literal(nd.callee.name))); \n \n with_bindings.forEach(function(with_var) {\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(name_tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(name_tmp), true), \n arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); }))))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n \n res = fn.concat(args, res);\n }\n break;\n }\n \n case 'NewExpression':\n var tmp = genTmp();\n var fn = normalizeExpression(nd.callee, tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = fn.concat(args, new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast[nd.type](new ast.Identifier(tmp), arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n \n case 'SequenceExpression':\n var n = nd.expressions.length;\n res = nd.expressions.flatmap(function(expr, i) {\n if(i < n - 1)\n return normalizeExpression(expr);\n return normalizeExpression(expr, target);\n });\n break;\n \n case 'LogicalExpression':\n var ltmp, l, r;\n if(nd.operator === '&&') {\n ltmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n res = mkIf(ltmp, normalizeExpression(nd.right, getTarget()),\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(ltmp)))]);\n res = l.concat(res);\n } else if(nd.operator === '||') {\n ltmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n res = mkIf(ltmp, [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(ltmp)))],\n normalizeExpression(nd.right, getTarget()));\n res = l.concat(res);\n } else {\n throw new Error(\"unknown logical expression\");\n }\n break;\n \n case 'BinaryExpression':\n var ltmp = genTmp(), rtmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n r = normalizeExpression(nd.right, rtmp);\n res = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.BinaryExpression(nd.operator, new ast.Identifier(ltmp), new ast.Identifier(rtmp))));\n res = l.concat(r, res);\n break;\n \n case 'ConditionalExpression':\n var tmp = genTmp();\n res = normalizeExpression(nd.test, tmp)\n .concat(mkIf(tmp, normalizeExpression(nd.consequent, target), \n normalizeExpression(nd.alternate, target)));\n break;\n \n case 'UpdateExpression':\n var op = nd.operator === '++' ? '+' : '-';\n // postfix expressions in void context are handled like prefix expressions\n if(!nd.prefix && target) {\n if(nd.argument.type === 'Identifier') {\n res = normalizeExpression(nd.argument, target)\n .concat(normalizeExpression(new ast.AssignmentExpression('=', new ast.Identifier(nd.argument.name), \n new ast.BinaryExpression(op, new ast.Identifier(nd.argument.name), new ast.Literal(1)))));\n \n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp(), extra_extra = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra_extra), new ast.Literal(1))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), new ast.BinaryExpression(op, new ast.Identifier(target), new ast.Identifier(extra_extra)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true), new ast.Identifier(extra))));\n } else {\n throw new Error(\"unexpected operand to postfix expression\");\n }\n } else {\n if(nd.argument.type === 'Identifier') {\n res = normalizeExpression(new ast.AssignmentExpression('=', nd.argument, new ast.BinaryExpression(op, new ast.Identifier(nd.argument.name), new ast.Literal(1))),\n target);\n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp(), extra_extra = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra_extra), new ast.Literal(1))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.BinaryExpression(op, new ast.Identifier(extra), new ast.Identifier(extra_extra)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true),\n new ast.Identifier(target))));\n } else {\n throw new Error(\"unexpected operand to prefix expression\");\n }\n }\n break;\n \n case 'UnaryExpression': \n var op = nd.operator;\n if(op === 'delete') {\n if(nd.argument.type === 'Identifier') {\n if(!isTmp(nd.argument.name) && scope.isGlobal(nd.argument.name)) {\n var trg = getTarget();\n var tmp = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.argument.name))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.UnaryExpression('delete',\n new ast.MemberExpression(new ast.Identifier('__global'),\n new ast.Identifier(tmp), true))))]; \n } else {\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), nd))];\n }\n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.UnaryExpression('delete',\n new ast.MemberExpression(new ast.Identifier(base_tmp),\n new ast.Identifier(index_tmp), true)))));\n } else {\n throw new Error();\n }\n } else {\n var tmp = genTmp();\n res = normalizeExpression(nd.argument, tmp)\n .concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.UnaryExpression(op, new ast.Identifier(tmp)))));\n }\n break;\n \n default:\n throw new Error(\"unknown expression type: \" + nd.type);\n }\n return inheritPosition(res, nd);\n }",
"function normalizeExpression(nd, target) {\n var res;\n function getTarget() {\n return target || (target = genTmp());\n }\n \n switch(nd.type) {\n case 'Literal':\n // target = literal;\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), nd))];\n break;\n \n case 'Identifier':\n var tmp = null;\n if(!isTmp(nd.name) && scope.isGlobal(nd.name)) {\n // global reads are rewritten into property accesses on __global; however, reading an undeclared, undefined global\n // should result in a ReferenceError, so we (optionally) introduce an if statement checking whether the global has\n // been declared/defined, and throw an error if not\n \n // temporary to hold the name of the global\n tmp = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.name)))];\n \n if(!options.reference_errors || scope.isDeclaredGlobal(nd.name)) {\n // target = __global[tmp];\n res[1] = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true)));\n } else {\n // check for shadowing of ReferenceError; give up if this happens\n // TODO: even if it isn't shadowed, some clown may have overwritten ReferenceError...\n if(!scope.isGlobal('ReferenceError'))\n throw new Error(\"global variable ReferenceError is shadowed\");\n \n /* tmp2 = x in __global;\n * if(tmp2) {\n * target = __global[tmp2];\n * } else {\n * tmp3 = 'ReferenceError';\n * tmp4 = __global[tmp3];\n * tmp5 = new tmp4();\n * throw tmp5;\n * } */\n var tmp2 = genTmp(), tmp3 = genTmp(), tmp4 = genTmp(), tmp5 = genTmp();\n res = res.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier('__global')))),\n mkIf(tmp2,\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true)))],\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp3), new ast.Literal('ReferenceError'))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp4), new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp3), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp5), new ast.NewExpression(new ast.Identifier(tmp4), [new ast.BinaryExpression('+', new ast.Literal('ReferenceError: '), new ast.BinaryExpression('+', new ast.Identifier(tmp), new ast.Literal(' is not defined')))]))),\n new ast.ThrowStatement(new ast.Identifier(tmp5))]));\n }\n } else {\n // locals are easy: target = x;\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(nd.name)))];\n }\n \n // handle possible 'with' bindings\n var with_bindings = scope.possibleWithBindings(nd.name);\n if(with_bindings.length) {\n var prelude = null;\n \n // load name of variable into 'tmp'; store code to do so into 'prelude'\n if(tmp) {\n prelude = res[0];\n res.shift();\n } else {\n tmp = genTmp();\n prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.name))); \n }\n \n with_bindings.forEach(function(with_var) {\n /*\n * tmp2 = tmp in with_var;\n * if(tmp2) {\n * target = with_var[tmp];\n * } else {\n * ...\n * }\n */\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(tmp), true)))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n break;\n \n case 'ArrayExpression':\n // allocate one temporary variable per array element (y1, ..., yn)\n var elt_tmps = genTmps(nd.elements.length);\n // recursively normalize array element expressions, skipping over omitted elements; the temporary will then\n // keep its initial undefined value, which is what we want\n var elements = nd.elements.flatmap(function(elt, i) { return elt ? normalizeExpression(elt, elt_tmps[i]) : []; });\n // target = [y1, ..., yn];\n res = elements.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.ArrayExpression(elt_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n \n case 'ObjectExpression':\n // allocate one temporary variable per property; we may not need all of them if there are getters or setters\n var prop_tmps = genTmps(nd.properties.length);\n var props = [];\n var body = nd.properties.flatmap(function(prop, i) {\n switch(prop.kind) {\n case 'init':\n case undefined: // Nick's addition, since CoffeeScript Redux doesn't seem to add 'init' to these things like it should.\n props[props.length] = new ast.Property(prop.key, new ast.Identifier(prop_tmps[i]), 'init');\n inheritPosition(props[props.length-1], prop);\n // recursively normalize property value expression\n return normalizeExpression(prop.value, prop_tmps[i]);\n case 'get':\n case 'set':\n // recursively normalize getter/setter\n var funexpr = normalizeEntity(prop.value, new scopes.FunctionScope(scope, prop.value));\n props[props.length] = new ast.Property(prop.key, funexpr, prop.kind);\n inheritPosition(props[props.length-1], prop);\n return [];\n default:\n throw new Error();\n }\n });\n res = body.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.ObjectExpression(props))));\n break;\n \n case 'MemberExpression':\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd), base_tmp);\n var index = normalizeExpression(getIndex(nd), index_tmp);\n var idx = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n // remember whether this member expression was a computed one originally\n if(nd.computed)\n ast.setAttribute(idx, 'isComputed', true);\n res = base.concat(index,\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), idx)));\n break;\n \n case 'ThisExpression':\n if(scope instanceof scopes.GlobalScope)\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier('__global')))];\n else\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.ThisExpression()))];\n break;\n \n case 'FunctionExpression':\n var fn = normalizeEntity(nd, new scopes.FunctionScope(scope, nd));\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), fn))];\n break;\n \n case 'AssignmentExpression':\n if(nd.operator === '=') {\n // simple assignments are handled similar to case 'Identifier' above\n if(nd.left.type === 'Identifier') {\n var res, tmp = null, right;\n var with_bindings = scope.possibleWithBindings(nd.left.name);\n if(!isTmp(nd.left.name) && scope.isGlobal(nd.left.name)) {\n tmp = genTmp();\n right = normalizeExpression(nd.right, getTarget());\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.left.name))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier('__global'), new ast.Identifier(tmp), true),\n new ast.Identifier(getTarget())))];\n } else {\n // mark variables that are written across scopes\n if(!scope.isLocal(nd.left.name))\n ast.setAttribute(scope.lookup(nd.left.name), 'exposed', true);\n \n if(target || with_bindings.length) {\n right = normalizeExpression(nd.right, getTarget());\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(nd.left.name), new ast.Identifier(getTarget())))];\n } else {\n target = nd.left.name;\n right = normalizeExpression(nd.right, nd.left.name);\n res = [];\n }\n }\n \n // handle 'with'\n if(with_bindings.length) {\n var prelude = null;\n if(tmp) {\n prelude = res[0];\n res.shift();\n } else {\n tmp = genTmp();\n prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.left.name))); \n }\n \n with_bindings.forEach(function(with_var) {\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(tmp), true), new ast.Identifier(getTarget())))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n \n res = right.concat(res);\n } else if(nd.left.type === 'MemberExpression') {\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd.left), base_tmp),\n index = normalizeExpression(getIndex(nd.left), index_tmp);\n var lhs = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n \n if(nd.left.computed)\n ast.setAttribute(lhs, 'isComputed', true);\n \n var rhs_comp = normalizeExpression(nd.right, getTarget());\n res = base.concat(index, rhs_comp, new ast.ExpressionStatement(new ast.AssignmentExpression('=', lhs, new ast.Identifier(getTarget()))));\n } else {\n throw new Error(\"unexpected lhs of type \" + nd.left.type);\n }\n } else {\n // compound assignments are desugared into normal assignments and then rewritten recursively\n var op = nd.operator.substring(0, nd.operator.length-1);\n var lhs = nd.left, rhs = nd.right;\n \n if(nd.left.type === 'Identifier') {\n var tmp = genTmp();\n res = normalizeExpression(rhs, tmp)\n .concat(normalizeExpression(new ast.AssignmentExpression('=', new ast.Identifier(nd.left.name), new ast.BinaryExpression(op, new ast.Identifier(nd.left.name), new ast.Identifier(tmp)))));\n } else if(nd.left.type === 'MemberExpression') {\n var tmp = genTmp(), trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp();\n \n res = normalizeExpression(getBase(lhs), base_tmp)\n .concat(normalizeExpression(getIndex(lhs), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n normalizeExpression(rhs, tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.BinaryExpression(op, new ast.Identifier(extra), new ast.Identifier(tmp)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true), new ast.Identifier(target))));\n } else {\n throw new Error(\"unexpected lhs\");\n }\n }\n break;\n \n case 'CallExpression':\n if(nd.callee.type === 'MemberExpression') {\n var base_tmp = genTmp(), index_tmp = genTmp();\n var base = normalizeExpression(getBase(nd.callee), base_tmp);\n var index = normalizeExpression(getIndex(nd.callee), index_tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n var callee = new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true);\n \n if(nd.callee.computed)\n ast.setAttribute(callee, 'isComputed', true);\n \n res = base.concat(index, args,\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(callee, arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n } else if(nd.callee.type === 'Identifier') {\n if(nd.callee.name === 'eval') {\n // TODO: handle 'eval' inside 'with'\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = args.concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(nd.callee, arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n } else {\n var tmp = genTmp();\n var fn = normalizeExpression(nd.callee, tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast[nd.type](new ast.Identifier(tmp), arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); }))))];\n \n var with_bindings = scope.possibleWithBindings(nd.callee.name);\n if(with_bindings.length) {\n var name_tmp = genTmp();\n var prelude = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(name_tmp), new ast.Literal(nd.callee.name))); \n \n with_bindings.forEach(function(with_var) {\n var tmp2 = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp2), new ast.BinaryExpression('in', new ast.Identifier(name_tmp), new ast.Identifier(with_var)))),\n new ast.IfStatement(new ast.Identifier(tmp2),\n mkBlock([new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.CallExpression(new ast.MemberExpression(new ast.Identifier(with_var), new ast.Identifier(name_tmp), true), \n arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); }))))]),\n mkBlock(res))];\n });\n \n res.unshift(prelude);\n }\n \n res = fn.concat(args, res);\n }\n break;\n }\n \n case 'NewExpression':\n var tmp = genTmp();\n var fn = normalizeExpression(nd.callee, tmp);\n var arg_tmps = genTmps(nd.arguments.length);\n var args = nd.arguments.flatmap(function(arg, i) { return normalizeExpression(arg, arg_tmps[i]); });\n res = fn.concat(args, new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast[nd.type](new ast.Identifier(tmp), arg_tmps.map(function(tmp) { return new ast.Identifier(tmp); })))));\n break;\n \n case 'SequenceExpression':\n var n = nd.expressions.length;\n res = nd.expressions.flatmap(function(expr, i) {\n if(i < n - 1)\n return normalizeExpression(expr);\n return normalizeExpression(expr, target);\n });\n break;\n \n case 'LogicalExpression':\n var ltmp, l, r;\n if(nd.operator === '&&') {\n ltmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n res = mkIf(ltmp, normalizeExpression(nd.right, getTarget()),\n [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(ltmp)))]);\n res = l.concat(res);\n } else if(nd.operator === '||') {\n ltmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n res = mkIf(ltmp, [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), new ast.Identifier(ltmp)))],\n normalizeExpression(nd.right, getTarget()));\n res = l.concat(res);\n } else {\n throw new Error(\"unknown logical expression\");\n }\n break;\n \n case 'BinaryExpression':\n var ltmp = genTmp(), rtmp = genTmp();\n l = normalizeExpression(nd.left, ltmp);\n r = normalizeExpression(nd.right, rtmp);\n res = new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.BinaryExpression(nd.operator, new ast.Identifier(ltmp), new ast.Identifier(rtmp))));\n res = l.concat(r, res);\n break;\n \n case 'ConditionalExpression':\n var tmp = genTmp();\n res = normalizeExpression(nd.test, tmp)\n .concat(mkIf(tmp, normalizeExpression(nd.consequent, target), \n normalizeExpression(nd.alternate, target)));\n break;\n \n case 'UpdateExpression':\n var op = nd.operator === '++' ? '+' : '-';\n // postfix expressions in void context are handled like prefix expressions\n if(!nd.prefix && target) {\n if(nd.argument.type === 'Identifier') {\n res = normalizeExpression(nd.argument, target)\n .concat(normalizeExpression(new ast.AssignmentExpression('=', new ast.Identifier(nd.argument.name), \n new ast.BinaryExpression(op, new ast.Identifier(nd.argument.name), new ast.Literal(1)))));\n \n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp(), extra_extra = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra_extra), new ast.Literal(1))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), new ast.BinaryExpression(op, new ast.Identifier(target), new ast.Identifier(extra_extra)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true), new ast.Identifier(extra))));\n } else {\n throw new Error(\"unexpected operand to postfix expression\");\n }\n } else {\n if(nd.argument.type === 'Identifier') {\n res = normalizeExpression(new ast.AssignmentExpression('=', nd.argument, new ast.BinaryExpression(op, new ast.Identifier(nd.argument.name), new ast.Literal(1))),\n target);\n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp(), extra = genTmp(), extra_extra = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra), \n new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(extra_extra), new ast.Literal(1))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.BinaryExpression(op, new ast.Identifier(extra), new ast.Identifier(extra_extra)))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.MemberExpression(new ast.Identifier(base_tmp), new ast.Identifier(index_tmp), true),\n new ast.Identifier(target))));\n } else {\n throw new Error(\"unexpected operand to prefix expression\");\n }\n }\n break;\n \n case 'UnaryExpression': \n var op = nd.operator;\n if(op === 'delete') {\n if(nd.argument.type === 'Identifier') {\n if(!isTmp(nd.argument.name) && scope.isGlobal(nd.argument.name)) {\n var trg = getTarget();\n var tmp = genTmp();\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(tmp), new ast.Literal(nd.argument.name))),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.UnaryExpression('delete',\n new ast.MemberExpression(new ast.Identifier('__global'),\n new ast.Identifier(tmp), true))))]; \n } else {\n res = [new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()), nd))];\n }\n } else if(nd.argument.type === 'MemberExpression') {\n var trg = getTarget();\n var base_tmp = genTmp(), index_tmp = genTmp();\n res = normalizeExpression(getBase(nd.argument), base_tmp)\n .concat(normalizeExpression(getIndex(nd.argument), index_tmp),\n new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(trg),\n new ast.UnaryExpression('delete',\n new ast.MemberExpression(new ast.Identifier(base_tmp),\n new ast.Identifier(index_tmp), true)))));\n } else {\n throw new Error();\n }\n } else {\n var tmp = genTmp();\n res = normalizeExpression(nd.argument, tmp)\n .concat(new ast.ExpressionStatement(new ast.AssignmentExpression('=', new ast.Identifier(getTarget()),\n new ast.UnaryExpression(op, new ast.Identifier(tmp)))));\n }\n break;\n \n default:\n throw new Error(\"unknown expression type: \" + nd.type);\n }\n return inheritPosition(res, nd);\n }",
"function targetModifyNotTest() {\n /* Ensure that target is not modified (this would happen if expression is\n * not allocated a real temporary register but operates directly on a register\n * bound value).\n */\n\n var x = 123;\n print(~x);\n print(x);\n\n var obj = {x:1};\n print(~obj.x);\n print(obj.x);\n}",
"function smashIndirects(expr) {\n var indirects = [];\n var target;\n while (expr.target) {\n indirects.push(expr);\n target = expr.target;\n delete expr.target;\n expr = target;\n }\n for (var i = 0; i < indirects.length; i++)\n indirects[i].target = expr;\n return expr;\n}",
"resolveTarget(ast) {\n const binding = this.tcb.boundTarget.getExpressionTarget(ast);\n if (binding === null) {\n return null;\n }\n const expr = this.scope.resolve(binding);\n addParseSpanInfo(expr, ast.sourceSpan);\n return expr;\n }",
"goUpToParentExpress(target) {\n let currNode = target;\n while (true) {\n const kind = currNode.parent.kind;\n if (kind === typescript_1.SyntaxKind.CallExpression && currNode.parent.expression === currNode ||\n kind === typescript_1.SyntaxKind.PropertyAccessExpression && currNode.parent.expression === currNode ||\n kind === typescript_1.SyntaxKind.ElementAccessExpression && currNode.parent.expression === currNode) {\n currNode = currNode.parent;\n }\n else {\n break;\n }\n }\n return currNode;\n }",
"compile(sourceCtx) {\n\n return new CFNode(JS.assign(this.expr.compile(sourceCtx), JS.ID('undefined')));\n }",
"function transformClassLikeDeclarationToExpression(node){// [source]\n// class C extends D {\n// constructor() {}\n// method() {}\n// get prop() {}\n// set prop(v) {}\n// }\n//\n// [output]\n// (function (_super) {\n// __extends(C, _super);\n// function C() {\n// }\n// C.prototype.method = function () {}\n// Object.defineProperty(C.prototype, \"prop\", {\n// get: function() {},\n// set: function() {},\n// enumerable: true,\n// configurable: true\n// });\n// return C;\n// }(D))\nif(node.name){enableSubstitutionsForBlockScopedBindings();}var extendsClauseElement=ts.getClassExtendsHeritageElement(node);var classFunction=ts.createFunctionExpression(/*modifiers*/undefined,/*asteriskToken*/undefined,/*name*/undefined,/*typeParameters*/undefined,extendsClauseElement?[ts.createParameter(/*decorators*/undefined,/*modifiers*/undefined,/*dotDotDotToken*/undefined,ts.createFileLevelUniqueName(\"_super\"))]:[],/*type*/undefined,transformClassBody(node,extendsClauseElement));// To preserve the behavior of the old emitter, we explicitly indent\n// the body of the function here if it was requested in an earlier\n// transformation.\nts.setEmitFlags(classFunction,ts.getEmitFlags(node)&65536/* Indented */|524288/* ReuseTempVariableScope */);// \"inner\" and \"outer\" below are added purely to preserve source map locations from\n// the old emitter\nvar inner=ts.createPartiallyEmittedExpression(classFunction);inner.end=node.end;ts.setEmitFlags(inner,1536/* NoComments */);var outer=ts.createPartiallyEmittedExpression(inner);outer.end=ts.skipTrivia(currentText,node.pos);ts.setEmitFlags(outer,1536/* NoComments */);var result=ts.createParen(ts.createCall(outer,/*typeArguments*/undefined,extendsClauseElement?[ts.visitNode(extendsClauseElement.expression,visitor,ts.isExpression)]:[]));ts.addSyntheticLeadingComment(result,3/* MultiLineCommentTrivia */,\"* @class \");return result;}",
"function transformSourceFile(node){if(node.isDeclarationFile){return node;}currentSourceFile=node;var visited=saveStateAndInvoke(node,visitSourceFile);ts.addEmitHelpers(visited,context.readEmitHelpers());currentSourceFile=undefined;return visited;}",
"function replace(target, node) {\n\tbefore(target, node);\n\tremove$2(target);\n\treturn node;\n}",
"compileNode(o) {\n var answer, compiledName, isValue, name, properties, prototype, ref1, ref2, ref3, ref4, ref5, val, varBase;\n isValue = this.variable instanceof Value;\n if (isValue) {\n // When compiling `@variable`, remember if it is part of a function parameter.\n this.variable.param = this.param;\n // If `@variable` is an array or an object, we’re destructuring;\n // if it’s also `isAssignable()`, the destructuring syntax is supported\n // in ES and we can output it as is; otherwise we `@compileDestructuring`\n // and convert this ES-unsupported destructuring into acceptable output.\n if (this.variable.isArray() || this.variable.isObject()) {\n // This is the left-hand side of an assignment; let `Arr` and `Obj`\n // know that, so that those nodes know that they’re assignable as\n // destructured variables.\n this.variable.base.lhs = true;\n if (!this.variable.isAssignable()) {\n if (this.variable.isObject() && this.variable.base.hasSplat()) {\n return this.compileObjectDestruct(o);\n } else {\n return this.compileDestructuring(o);\n }\n }\n }\n if (this.variable.isSplice()) {\n return this.compileSplice(o);\n }\n if ((ref1 = this.context) === '||=' || ref1 === '&&=' || ref1 === '?=') {\n return this.compileConditional(o);\n }\n if ((ref2 = this.context) === '//=' || ref2 === '%%=') {\n return this.compileSpecialMath(o);\n }\n }\n if (!this.context || this.context === '**=') {\n varBase = this.variable.unwrapAll();\n if (!varBase.isAssignable()) {\n this.variable.error(`'${this.variable.compile(o)}' can't be assigned`);\n }\n varBase.eachName((name) => {\n var commentFragments, commentsNode, message;\n if (typeof name.hasProperties === \"function\" ? name.hasProperties() : void 0) {\n return;\n }\n message = isUnassignable(name.value);\n if (message) {\n name.error(message);\n }\n // `moduleDeclaration` can be `'import'` or `'export'`.\n this.checkAssignability(o, name);\n if (this.moduleDeclaration) {\n return o.scope.add(name.value, this.moduleDeclaration);\n } else if (this.param) {\n return o.scope.add(name.value, this.param === 'alwaysDeclare' ? 'var' : 'param');\n } else {\n o.scope.find(name.value);\n // If this assignment identifier has one or more herecomments\n // attached, output them as part of the declarations line (unless\n // other herecomments are already staged there) for compatibility\n // with Flow typing. Don’t do this if this assignment is for a\n // class, e.g. `ClassName = class ClassName {`, as Flow requires\n // the comment to be between the class name and the `{`.\n if (name.comments && !o.scope.comments[name.value] && !(this.value instanceof Class) && name.comments.every(function(comment) {\n return comment.here && !comment.multiline;\n })) {\n commentsNode = new IdentifierLiteral(name.value);\n commentsNode.comments = name.comments;\n commentFragments = [];\n this.compileCommentFragments(o, commentsNode, commentFragments);\n return o.scope.comments[name.value] = commentFragments;\n }\n }\n });\n }\n if (this.value instanceof Code) {\n if (this.value.isStatic) {\n this.value.name = this.variable.properties[0];\n } else if (((ref3 = this.variable.properties) != null ? ref3.length : void 0) >= 2) {\n ref4 = this.variable.properties, [...properties] = ref4, [prototype, name] = splice.call(properties, -2);\n if (((ref5 = prototype.name) != null ? ref5.value : void 0) === 'prototype') {\n this.value.name = name;\n }\n }\n }\n if (this.csx) {\n this.value.base.csxAttribute = true;\n }\n val = this.value.compileToFragments(o, LEVEL_LIST);\n compiledName = this.variable.compileToFragments(o, LEVEL_LIST);\n if (this.context === 'object') {\n if (this.variable.shouldCache()) {\n compiledName.unshift(this.makeCode('['));\n compiledName.push(this.makeCode(']'));\n }\n return compiledName.concat(this.makeCode(this.csx ? '=' : ': '), val);\n }\n answer = compiledName.concat(this.makeCode(` ${this.context || '='} `), val);\n // Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration,\n // if we’re destructuring without declaring, the destructuring assignment must be wrapped in parentheses.\n // The assignment is wrapped in parentheses if 'o.level' has lower precedence than LEVEL_LIST (3)\n // (i.e. LEVEL_COND (4), LEVEL_OP (5) or LEVEL_ACCESS (6)), or if we're destructuring object, e.g. {a,b} = obj.\n if (o.level > LEVEL_LIST || isValue && this.variable.base instanceof Obj && !this.nestedLhs && !(this.param === true)) {\n return this.wrapInParentheses(answer);\n } else {\n return answer;\n }\n }",
"instructionBefore(target, value) {\n var child, i, removed;\n // temporarily remove children starting *with* this\n i = this.parent.children.indexOf(this);\n removed = this.parent.children.splice(i);\n // add the new child\n child = this.parent.instruction(target, value);\n // add back removed children after new child\n Array.prototype.push.apply(this.parent.children, removed);\n return this;\n }",
"function transformClassLikeDeclarationToExpression(node) {\n // [source]\n // class C extends D {\n // constructor() {}\n // method() {}\n // get prop() {}\n // set prop(v) {}\n // }\n //\n // [output]\n // (function (_super) {\n // __extends(C, _super);\n // function C() {\n // }\n // C.prototype.method = function () {}\n // Object.defineProperty(C.prototype, \"prop\", {\n // get: function() {},\n // set: function() {},\n // enumerable: true,\n // configurable: true\n // });\n // return C;\n // }(D))\n if (node.name) {\n enableSubstitutionsForBlockScopedBindings();\n }\n var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node);\n var classFunction = ts.createFunctionExpression(\n /*modifiers*/undefined,\n /*asteriskToken*/undefined,\n /*name*/undefined,\n /*typeParameters*/undefined, extendsClauseElement ? [ts.createParameter( /*decorators*/undefined, /*modifiers*/undefined, /*dotDotDotToken*/undefined, \"_super\")] : [],\n /*type*/undefined, transformClassBody(node, extendsClauseElement));\n // To preserve the behavior of the old emitter, we explicitly indent\n // the body of the function here if it was requested in an earlier\n // transformation.\n if (ts.getEmitFlags(node) & 32768 /* Indented */) {\n ts.setEmitFlags(classFunction, 32768 /* Indented */);\n }\n // \"inner\" and \"outer\" below are added purely to preserve source map locations from\n // the old emitter\n var inner = ts.createPartiallyEmittedExpression(classFunction);\n inner.end = node.end;\n ts.setEmitFlags(inner, 1536 /* NoComments */);\n var outer = ts.createPartiallyEmittedExpression(inner);\n outer.end = ts.skipTrivia(currentText, node.pos);\n ts.setEmitFlags(outer, 1536 /* NoComments */);\n return ts.createParen(ts.createCall(outer,\n /*typeArguments*/undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : []));\n }",
"function visitNewExpression(node) {\n if (node.transformFlags & 524288 /* ContainsSpread */) {\n // We are here because we contain a SpreadElementExpression.\n // [source]\n // new C(...a)\n //\n // [output]\n // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()\n var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, \"bind\"), hoistVariableDeclaration),\n target = _a.target,\n thisArg = _a.thisArg;\n return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/false, /*multiLine*/false, /*hasTrailingComma*/false)),\n /*typeArguments*/undefined, []);\n }\n return ts.visitEachChild(node, visitor, context);\n }",
"function onSubstituteNode(hint,node){node=previousOnSubstituteNode(hint,node);if(isSubstitutionPrevented(node)){return node;}if(hint===1/* Expression */){return substituteExpression(node);}else if(hint===4/* Unspecified */){return substituteUnspecified(node);}return node;}",
"async into(target) {\n if (typeof target === \"string\") {\n let element = document.querySelector(target);\n if (element instanceof HTMLElement) {\n return this.into(element);\n }\n throw new Error(`target not found: ${target}`);\n }\n const fragment = await this.asFragment();\n target.innerHTML = \"\";\n target.appendChild(fragment);\n return fragment;\n }",
"function nodeVisitor(node) {\n const { factory, tsInstance, transformationContext } = this;\n /**\n * Update require / import functions\n *\n * require('module')\n * import('module')\n */\n if (isRequire(this, node) || isAsyncImport(this, node))\n return utils_1.resolvePathAndUpdateNode(this, node, node.arguments[0].text, (p) => {\n const res = factory.updateCallExpression(node, node.expression, node.typeArguments, [p]);\n /* Handle comments */\n const textNode = node.arguments[0];\n const commentRanges = tsInstance.getLeadingCommentRanges(textNode.getFullText(), 0) || [];\n for (const range of commentRanges) {\n const { kind, pos, end, hasTrailingNewLine } = range;\n const caption = textNode\n .getFullText()\n .substr(pos, end)\n .replace(\n /* searchValue */ kind === tsInstance.SyntaxKind.MultiLineCommentTrivia\n ? // Comment range in a multi-line comment with more than one line erroneously\n // includes the node's text in the range. For that reason, we use the greedy\n // selector in capture group and dismiss anything after the final comment close tag\n /^\\/\\*(.+)\\*\\/.*/s\n : /^\\/\\/(.+)/s, \n /* replaceValue */ \"$1\");\n tsInstance.addSyntheticLeadingComment(p, kind, caption, hasTrailingNewLine);\n }\n return res;\n });\n /**\n * Update ExternalModuleReference\n *\n * import foo = require(\"foo\");\n */\n if (tsInstance.isExternalModuleReference(node) && tsInstance.isStringLiteral(node.expression))\n return utils_1.resolvePathAndUpdateNode(this, node, node.expression.text, (p) => factory.updateExternalModuleReference(node, p));\n /**\n * Update ImportTypeNode\n *\n * typeof import(\"./bar\");\n */\n if (tsInstance.isImportTypeNode(node)) {\n const argument = node.argument;\n if (!tsInstance.isStringLiteral(argument.literal))\n return node;\n const { text } = argument.literal;\n if (!text)\n return node;\n return utils_1.resolvePathAndUpdateNode(this, node, text, (p) => factory.updateImportTypeNode(node, factory.updateLiteralTypeNode(argument, p), node.qualifier, node.typeArguments, node.isTypeOf));\n }\n /**\n * Update ImportDeclaration\n *\n * import ... 'module';\n */\n if (tsInstance.isImportDeclaration(node) && node.moduleSpecifier && tsInstance.isStringLiteral(node.moduleSpecifier))\n return utils_1.resolvePathAndUpdateNode(this, node, node.moduleSpecifier.text, (p) => {\n let importClause = node.importClause;\n if (!this.isDeclarationFile && (importClause === null || importClause === void 0 ? void 0 : importClause.namedBindings)) {\n const updatedImportClause = utils_1.elideImportOrExportClause(this, node);\n if (!updatedImportClause)\n return undefined; // No imports left, elide entire declaration\n importClause = updatedImportClause;\n }\n return factory.updateImportDeclaration(node, node.decorators, node.modifiers, importClause, p);\n });\n /**\n * Update ExportDeclaration\n *\n * export ... 'module';\n */\n if (tsInstance.isExportDeclaration(node) && node.moduleSpecifier && tsInstance.isStringLiteral(node.moduleSpecifier))\n return utils_1.resolvePathAndUpdateNode(this, node, node.moduleSpecifier.text, (p) => {\n let exportClause = node.exportClause;\n if (!this.isDeclarationFile && exportClause && tsInstance.isNamedExports(exportClause)) {\n const updatedExportClause = utils_1.elideImportOrExportClause(this, node);\n if (!updatedExportClause)\n return undefined; // No export left, elide entire declaration\n exportClause = updatedExportClause;\n }\n return factory.updateExportDeclaration(node, node.decorators, node.modifiers, node.isTypeOnly, exportClause, p);\n });\n /**\n * Update module augmentation\n */\n if (tsInstance.isModuleDeclaration(node) && tsInstance.isStringLiteral(node.name))\n return utils_1.resolvePathAndUpdateNode(this, node, node.name.text, (p) => factory.updateModuleDeclaration(node, node.decorators, node.modifiers, p, node.body));\n return tsInstance.visitEachChild(node, this.getVisitor(), transformationContext);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes a MySQL query to replace a specified comment with new data. Returns a Promise that resolves to true if the comment specified by `id` existed and was successfully updated or to false otherwise. | async function replaceCommentById(id, comment) {
comment = extractValidFields(comment, CommentSchema);
const [ result ] = await mysqlPool.query(
'UPDATE comments SET ? WHERE commentId = ?',
[ comment, id ]
);
return result.affectedRows > 0;
} | [
"async function updateComment(comment){\n //Insert new autosaved entry\n if (debug){console.log(\"updateComment() -> Called\");}\n try {\n var sql = \"UPDATE comments SET comment_text = $1::text WHERE comment_pk = $2::int AND comment_entry_fk = $3::int RETURNING comment_pk, comment_entry_fk, comment_user_fk, comment_date, comment_text\";\n var params = [comment.text, comment.id, comment.jotID];\n var results = await pool.query(sql, params);\n } catch (err){\n if (debug){console.log(\"updateComment() -> ERROR CAUGHT\");}\n console.log(err);\n return false;\n };\n return parseCommentFromDB(results.rows[0]); \n }",
"function updateComment(comments, id) {\n var find = comments.find(id);\n find.fail(log('comment: find failed ' + id));\n find.done(log('comment: found by id ' + id));\n find.done(function(comment) {\n comment.text = 'This is my updated comment!';\n // the inline callback and Promise styles can be mixed\n comments.save(comment, function(updated, error) {\n console.log('comment: update succeeded', updated, error);\n }).done(function() {\n // callbacks can be chained\n comments.remove(id)\n .done(log('comment: delete succeeded'))\n .fail(log('comment: delete failed'));\n });\n });\n }",
"function editCommentInDb(text, commentId) {\n\n\treturn new Promise((resolve, reject) => {\n\n\t // update the comment text in the database\n\t\tComment.findByIdAndUpdate(mongoose.Types.ObjectId(commentId),\n\t\t\t{ $set: { comment: text }}, { new: true}, (error, doc) => {\n\t\t\t// throw any error\n\t\t\tif (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t\tconsole.log(doc);\n\t\t\t// return the updated comment\n\t\t\tresolve(doc);\n\t\t});\n\n\t});\n\n}",
"async function checkCommentId(newId){\n const [ comments ] = await mysqlPool.query(\n 'SELECT * FROM comments ORDER BY id'\n );\n\n if(comments){\n for(var i = 0; i < comments.length; i++){\n if(comments[i].commentId === newId){\n return false;\n }\n }\n }\n return true;\n}",
"async function deleteCommentById(id) {\n const [ result ] = await mysqlPool.query(\n 'DELETE FROM comments WHERE commentId = ?',\n [ id ]\n );\n return result.affectedRows > 0;\n}",
"function updateComment(commentId, comment) {\n\t\tvar deferred = q.defer();\n\t\tCommentModel.findByIdAndUpdate(commentId, comment, function(err, res){\n\t\t\tvar postId = res.postId;\n\t\t\tCommentModel.find({ postId : postId}, function(err, res){\n\t\t\t\tdeferred.resolve(res);\n\t\t\t});\n\t\t});\n\t\treturn deferred.promise;\n\t}",
"editComment(knex, id, updateFields) {\n return knex\n .from(\"comments\")\n .where({ id })\n .update(updateFields);\n }",
"function updateComment(id, updatedComment) {\n var deferred = $q.defer();\n $http.put(\"/api/project/beer/comment/\" + id, updatedComment)\n .success(function(response) {\n deferred.resolve(response);\n });\n return deferred.promise;\n }",
"async editComment(id, commentText) {\r\n const data = {\r\n commentId: id,\r\n userId: this.userId,\r\n comment: {\r\n text: commentText,\r\n needsModeration: 0\r\n }\r\n };\r\n const header = this.handleHeaders();\r\n const dataQueryString = {\r\n method: 'PUT',\r\n headers: header,\r\n body: JSON.stringify(data)\r\n };\r\n const url = `${this.apiUrl}/comment`;\r\n return this.apiService(url, dataQueryString);\r\n }",
"put (comment) { return Api().put('comment/' + commentId, comment)}",
"async updateComment(id, postID, comment, authToken) {\n return updateComment(client.baseURL, id, postID, comment, authToken)\n }",
"async function replaceReviewById(id, review) {\n review = extractValidFields(review, ReviewSchema);\n const [ result ] = await mysqlPool.query(\n 'UPDATE reviews SET ? WHERE id = ?',\n [ review, id ]\n );\n return result.affectedRows > 0;\n}",
"editCommentReply(commentId, text) {\n return __awaiter(this, void 0, void 0, function* () {\n this.checkTokenAndThrow();\n const data = JSON.parse(JSON.stringify(constants_1.COMMENT_DATA));\n data.id = commentId;\n data.snippet.textOriginal = text;\n const response = yield this.youtube._request.put('comments', { part: 'id,snippet' }, JSON.stringify(data), null, this.youtube.accessToken);\n return new _1.YTComment(this.youtube, response, response.snippet.channelId ? 'channel' : 'video');\n });\n }",
"async function deleteCommentsByPostId(id){\n const [ result ] = await mysqlPool.query(\n 'DELETE FROM comments WHERE postId = ?',\n [ id ]\n );\n return result.affectedRows > 0;\n}",
"updateComment(apiId, commentId, commentInfo, callback = null) {\n const promise = this.client.then((client) => {\n return client.apis['Comment (Individual)'].put_apis__apiId__comments__commentId_(\n { apiId, commentId, body: commentInfo },\n this._requestMetaData(),\n );\n }).catch((error) => {\n console.error(error);\n });\n if (callback) {\n return promise.then(callback);\n } else {\n return promise;\n }\n }",
"updateComment(id, updatedContent, updatedRating) {\r\n return comments().then((commentCollection) => {\r\n let date = new Date();\r\n let updateInfo = {\r\n content: updatedContent,\r\n date: date.toLocaleString(),\r\n rating: parseFloat(updatedRating)\r\n };\r\n\r\n let updateCommand = {\r\n $set: updateInfo\r\n };\r\n return this.getCommentByDbId(id).then((comment) => {\r\n return courseData.updateCourseRating(comment.courseId, updatedRating, comment.rating).then((course) => {\r\n return commentCollection.updateOne({ _id: id }, updateCommand).then((result) => {\r\n return this.getCommentByDbId(id);\r\n });\r\n });\r\n })\r\n });\r\n }",
"updateComment(apiId, commentId, commentInfo, callback = null) {\n let promise = this.client.then(\n (client) => {\n return client.apis[\"Comment (Individual)\"].put_apis__apiId__comments__commentId_(\n {apiId: apiId, commentId: commentId, body: commentInfo}, this._requestMetaData());\n }\n ).catch(\n error => {\n console.error(error);\n }\n );\n if (callback) {\n return promise.then(callback);\n } else {\n return promise;\n }\n }",
"async function replaceSongById(id, song) {\n song = extractValidFields(song, SongSchema);\n const [ result ] = await mysqlPool.query(\n 'UPDATE songs SET ? WHERE id = ?',\n [ song, id ]\n );\n return result.affectedRows > 0;\n}",
"function replaceReviewByID(reviewID, review, mysqlPool) {\n return new Promise((resolve, reject) => {\n review = validation.extractValidFields(review, reviewSchema);\n mysqlPool.query('UPDATE reviews SET ? WHERE id = ?', [ review, reviewID ], function (err, result) {\n if (err) {\n console.log(err);\n reject(err);\n } else {\n console.log(\"no error\");\n resolve(result.affectedRows > 0);\n }\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================== Functions =================================== This function sends some stats to my server, only your username and version of the script that you are using will be sent You can disable this from the script config menu | function sendStats() {
var username = getUsername(),
version = GM_info.script.version;
if (username && version) {
GM_xmlhttpRequest({
method: 'POST',
url: 'http://acid.nu/hbfs.php',
data: 'user='+ username +'&version='+ version,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
onload: function(data) {
var r = $.parseJSON(data.responseText);
//console.log(r.msg);
}
});
}
} | [
"function sendStats() {\n if (hostname.indexOf(\"local\") != -1) {\n cleanup();\n return;\n }\n var app = options.app;\n var key = hostname + \".\"+path;\n\n\n // Status Code\n var statusCode = res.statusCode || 'unknown_status';\n client.increment(app + '.' + 'status-code-' + statusCode + \".\" + key);\n\n // Response Time\n var duration = new Date().getTime() - startTime;\n client.timing(app + '.' + 'response-time' + \".\" + key, duration);\n\n // Total requests\n client.increment(app + '.' + 'requests' + \".\" + key);\n\n cleanup();\n }",
"function postStats()\n{\n\t// ignore for test bot\n\tif(!config.testing) snekfetch.post(`https://discordbots.org/api/bots/${client.user.id}/stats`)\n\t\t.set(\"Authorization\", config.discordBotsToken)\n\t\t.send({ server_count: client.guilds.size })\n\t\t.then(() => console.log(\"Updated discordbots.org stats.\"))\n\t\t.catch(err => console.error(`Error updating stats: ${err.body}`));\n}",
"sendStatsToClients() {\n this.sendMessageToAllClients({\n command: 'stats',\n bandwidth: this.getBandwidth(),\n rtt: this.getRTT()\n });\n }",
"function sendStats() {\n push('stats', {\n hits: hits,\n totalHits: totalHits,\n bytes: bytes,\n totalBytes: totalBytes,\n cost: cost,\n totalCost: totalCost,\n period: STATS_PERIOD,\n uptime: +(new Date) - startTime\n });\n\n hits = 0;\n bytes = 0;\n cost = 0;\n}",
"function sendStats() {\n\t\tconnection.emuc.addConnectionInfoToPresence(convertToMUCStats(stats));\n\t\tconnection.emuc.sendPresence();\n\t }",
"function apiSendGenericStats() {\n var pref = Components.classes[\"@mozilla.org/preferences-service;1\"]\n .getService(Components.interfaces.nsIPrefService)\n .getBranch(\"extensions.thundersec.\");\n\n // Check if API usage is allowed in preferences\n if ( pref.getBoolPref('api_enabled') ) {\n // Set period end to now\n stats.periodEnd = Date.now() / 1000;\n\n // Add version information for the API\n stats.version = VERSION;\n \n // Send stats\n $.post (API_URL + 'stat', stats, function () {\n // Reset stats, only on success\n stats = { periodStart: Date.now() / 1000,\n periodEnd: null,\n inspectTotal: 0,\n dnsblLookup: 0,\n dnsblViolation: 0,\n dnsblWhitelist: 0,\n surblLookup: 0,\n surblViolation: 0,\n surblWhitelist: 0,\n spfViolation: 0,\n spfWhitelist:0,\n dkimViolation: 0,\n dkimWhitelist: 0 };\n });\n }\n}",
"function sendUsageStats() {\n if (!SETTINGS.sendUsageStats) return; // not allowed!\n if (device.uid === undefined) return; // no data yet!\n if (!device.appsInstalled.length) return; // no installed apps or disconnected\n /* Work out what we'll send:\n * A suitably garbled UID so we can avoid too many duplicates\n * firmware version\n * apps installed\n * apps favourited\n */\n var usageInfo = `uid=${encodeURIComponent(device.uid)}&fw=${encodeURIComponent(device.version)}&apps=${encodeURIComponent(device.appsInstalled.map(a=>a.id).join(\",\"))}&favs=${encodeURIComponent(SETTINGS.favourites.join(\",\"))}`;\n // Do a quick check for unchanged data to reduce server load\n if (usageInfo != submittedUsageInfo) {\n console.log(\"sendUsageStats: Submitting usage stats...\");\n var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance\n xmlhttp.open(\"POST\", \"https://banglejs.com/submit_app_stats.php\", true /*async*/);\n xmlhttp.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n xmlhttp.onload = (e) => {\n if (xmlhttp.readyState === 4)\n console.log(`sendUsageStats (${xmlhttp.status}): ${xmlhttp.responseText}`);\n };\n xmlhttp.onerror = (e) => {\n console.error(\"sendUsageStats ERROR: \"+xmlhttp.statusText);\n };\n xmlhttp.send(usageInfo);\n submittedUsageInfo = usageInfo;\n }\n}",
"update() {\n this.emit('fetch');\n if (this.guilds > 0 && this.users > 0) {\n if (!config.beta) {\n dogstatsd.gauge('musicbot.guilds', this.guilds);\n dogstatsd.gauge('musicbot.users', this.users);\n }\n let requestOptions = {\n headers: {\n Authorization: config.discord_bots_token\n },\n url: `https://bots.discord.pw/api/bots/${config.bot_id}/stats`,\n method: 'POST',\n json: {\n 'server_count': this.guilds\n }\n };\n request(requestOptions, (err, response, body) => {\n if (err) {\n return this.emit('error', err);\n }\n this.emit('info', 'Stats Updated!');\n this.emit('info', body);\n });\n if (!config.beta) {\n let requestOptionsCarbon = {\n url: 'https://www.carbonitex.net/discord/data/botdata.php',\n method: 'POST',\n json: {\n 'server_count': this.guilds,\n 'key': config.carbon_token\n }\n };\n request(requestOptionsCarbon, (err, response, body) => {\n if (err) {\n return this.emit('error', err)\n }\n this.emit('info', 'Stats Updated Carbon!');\n this.emit('info', body);\n });\n }\n }\n }",
"function update() {\r\n stats = JSON.parse(fs.readFileSync('../stats.json'));\r\n stats.guilds.guild_bot_3 = client.guilds.cache.size;\r\n stats.requests.global_requests = stats.requests.global_requests + 1;\r\n stats.requests.request_bot_3 = stats.requests.request_bot_3 + 1;\r\n stats.users.user_bot_3 = client.users.cache.size;\r\n saveStatsFile();\r\n}",
"function postSessionStats(message){\n console.log(chalk.green('Session stats requested by: ' + chalk.yellow(message.author.username)));\n let users = (client.guilds.reduce(function(sum, guild){ return sum + guild.memberCount;}, 0));\n users = numberWithCommas(users);\n const guilds = numberWithCommas(client.guilds.size);\n const msgpersec = Math.trunc(messageCount * 1000 * 60 / (Date.now() - referenceTime));\n const topCrypto = coinArrayMax(requestCounter);\n const popCrypto = coinArrayMax(mentionCounter);\n\n\n const msgh = (\"Serving `\" + users + \"` users from `\" + guilds + \"` servers.\\n\"\n + \"⇒ Current uptime is: `\" + Math.trunc(client.uptime / (3600000)) + \"hr`.\\n\"\n + \"⇒ Current messages per minute is `\" + msgpersec + \"`.\\n\"\n + (topCrypto[1] > 0 ? \"⇒ Top requested crypto: `\" + topCrypto[0] + \"` with `\" + topCrypto[1] + \"%` dominance.\\n\" : \"\")\n + (popCrypto[1] > 0 ? \"⇒ Top mentioned crypto: `\" + popCrypto[0] + \"` with `\" + popCrypto[1] + \"%` dominance.\\n\" : \"\")\n + \"⇒ Join the support server! (https://discord.gg/VWNUbR5)\\n\"\n + \"`⇒ ETH donations appreciated at: 0x169381506870283cbABC52034E4ECc123f3FAD02.`\");\n\n let embed = new Discord.RichEmbed()\n .addField(\"TsukiBot Stats\", msgh)\n .setColor('BLUE')\n .setThumbnail('https://i.imgur.com/r6yCs2T.png')\n .setFooter('Part of CehhNet', 'https://imgur.com/OG77bXa.png');\n message.channel.send({embed});\n}",
"function sendStatistics() {\n if (localStorage[\"paused\"] == \"true\") {\n console.log(\"Paused, not sending statistics.\");\n return;\n }\n\n console.log(\"Sending statistics.\");\n if (localStorage[\"storageType\"] == \"appengine\") {\n console.log(\"Sending stats to server.\");\n sendStatisticsToServer();\n } else {\n console.log(\"Warning: Unsupported storage type.\");\n }\n }",
"function apiSendSurblStats (host, code, source) {\n var pref = Components.classes[\"@mozilla.org/preferences-service;1\"]\n .getService(Components.interfaces.nsIPrefService)\n .getBranch(\"extensions.thundersec.\");\n\n // Check if API usage is allowed in preferences\n if ( pref.getBoolPref('api_enabled') ) {\n // We will hash the sender for privacy\n $.post( API_URL + 'surbl/stat',\n { 'host': host,\n 'code': code,\n 'surbl': source,\n 'version': VERSION } );\n }\n}",
"askForInfo(){\r\n\t\tthis.activeConnection.sendToServer({\r\n\t\t\tcommand: \"PLAYERS\",\r\n\t\t\ttoken: this.activeConnection.token,\r\n\t\t});\r\n\r\n\t\tthis.activeConnection.sendToServer({\r\n\t\t\tcommand: \"CPUUSAGE\",\r\n\t\t\ttoken: this.activeConnection.token,\r\n\t\t});\r\n\r\n\t\tthis.activeConnection.sendToServer({\r\n\t\t\tcommand: \"RAMUSAGE\",\r\n\t\t\ttoken: this.activeConnection.token,\r\n\t\t});\r\n\t}",
"askForInfo(){\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"PLAYERS\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"CPUUSAGE\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\n\t\tthis.activeConnection.sendToServer({\n\t\t\tcommand: \"RAMUSAGE\",\n\t\t\ttoken: this.activeConnection.token,\n\t\t});\n\t}",
"function returnStatistics() {\n var results = {\n type:'STATISTICS',\n status: 'SUCCESS',\n clients: clients.length,\n games: games.length,\n twowaiting: newTwoPlayer.length,\n fourwaiting: newFourPlayer.length\n };\n if(clients.length > 0) {\n\t // console.log('System: returning statistics to all users - ' + JSON.stringify(results));\n\t clients.forEach(function(user) {\n\t \tuser.remoteClient.write(JSON.stringify(results) + '\\n');\n\t });\n\t}\n}",
"function sendReqGlobalStatistics(userID)\r\n{\r\n\tsend_obj=\r\n\t{\r\n\t\t\"type\":\"loadGlobalStatistics\",\r\n\t\t\"object\":{\r\n\t\t\t\"user\":{\r\n\t\t\t\t\"userID\": userID\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\tsend(send_obj);\r\n}",
"_sendCarbonStats() {\n\t\tconst config = this.config.values;\n\t\trequest({\n\t\t\tmethod: 'POST',\n\t\t\turi: config.carbonUrl,\n\t\t\tbody: Object.assign(this._stats, { key: config.carbonKey }),\n\t\t\tjson: true\n\t\t}).then(() => {\n\t\t\tthis.logger.info(`Sent guild count to Carbon with ${this.client.guilds.size} guilds.`);\n\t\t}).catch(err => {\n\t\t\tthis.logger.error('Error while sending guild count to Carbon.', err);\n\t\t});\n\t}",
"update(guilds, users) {\n dogstatsd.gauge(`${stat}.guilds`, guilds);\n dogstatsd.gauge(`${stat}.users`, users);\n let requestOptions = {\n headers: {\n Authorization: config.discord_bots_token\n },\n url: `https://bots.discord.pw/api/bots/${config.bot_id}/stats`,\n method: 'POST',\n json: {\n 'server_count': guilds\n }\n };\n request(requestOptions, (err, response, body) => {\n if (err) {\n return this.emit('error', err);\n }\n this.emit('info', 'Stats Updated!');\n this.emit('info', body);\n });\n if (!config.beta) {\n let requestOptionsCarbon = {\n url: 'https://www.carbonitex.net/discord/data/botdata.php',\n method: 'POST',\n json: {\n 'server_count': guilds,\n 'key': config.carbon_token\n }\n };\n request(requestOptionsCarbon, (err, response, body) => {\n if (err) {\n return this.emit('error', err);\n }\n this.emit('info', 'Stats Updated Carbon!');\n this.emit('info', body);\n });\n }\n\n }",
"function uploadStats() {\n var data = {};\n data.type = os.type();\n data.uptime = os.uptime();\n data.mem = os.freemem() / os.totalmem();\n console.log('Publishing OS info & stats: %s', JSON.stringify(data));\n client.publish(telemetryTopic, JSON.stringify(data));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update query string, assigning a new value to each parameter given in kvpairs | function updateQueryStringParameter(kvpairs) {
console.log('updateQueryStringParameter: begin');
var uri = URI(window.location.href);
for (var key in kvpairs) {
var value = kvpairs[key];
uri.removeSearch(key);
uri.addSearch(key, value);
}
return uri.href();
} | [
"function updateQueryStringParameter(key, value) {\r\n var uri_parts = window.location.href.split('/')\r\n var uri_local = uri_parts[uri_parts.length - 1]\r\n var re = new RegExp(\"([?&])\" + key + \"=.*?(&|$)\", \"i\");\r\n var separator = uri_local.indexOf('?') !== -1 ? \"&\" : \"?\";\r\n if (uri_local.match(re)) {\r\n return uri_local.replace(re, '$1' + key + \"=\" + value + '$2');\r\n }\r\n else {\r\n return uri_local + separator + key + \"=\" + value;\r\n }\r\n}",
"function updateURLQuery(key, value) {\n let uri = window.location.href;\n\n if (key === 'bldg')\n uri = removeQueryStringParam('flr', uri);\n\n window.location.href = getUpdatedURL(uri, key, value)\n}",
"function UpdateQueryString(key, value, url) {\n\tif (!url) url = window.location.href;\n\tvar re = new RegExp(\"([?&])\" + key + \"=.*?(&|#|$)(.*)\", \"gi\"),\n\t\thash;\n\n\tif (re.test(url)) {\n\t\tif (typeof value !== 'undefined' && value !== null)\n\t\t\treturn url.replace(re, '$1' + key + \"=\" + value + '$2$3');\n\t\telse {\n\t\t\thash = url.split('#');\n\t\t\turl = hash[0].replace(re, '$1$3').replace(/(&|\\?)$/, '');\n\t\t\tif (typeof hash[1] !== 'undefined' && hash[1] !== null)\n\t\t\t\turl += '#' + hash[1];\n\t\t\treturn url;\n\t\t}\n\t} else {\n\t\tif (typeof value !== 'undefined' && value !== null) {\n\t\t\tvar separator = url.indexOf('?') !== -1 ? '&' : '?';\n\t\t\thash = url.split('#');\n\t\t\turl = hash[0] + separator + key + '=' + value;\n\t\t\tif (typeof hash[1] !== 'undefined' && hash[1] !== null)\n\t\t\t\turl += '#' + hash[1];\n\t\t\treturn url;\n\t\t} else\n\t\t\treturn url;\n\t}\n}",
"addURLQueryString(key, value) {\n const searchParams = new URL.URLSearchParams(this.urlObj.search);\n searchParams.append(key, value);\n this.urlObj.search = searchParams.toString();\n }",
"function insertParam(key, value) {\n key = encodeURI(key);\n value = encodeURI(value);\n\n var kvp = document.location.search.substr(1).split('&');\n\n var i = kvp.length;\n var x;\n while (i--) {\n x = kvp[i].split('=');\n\n if (x[0] == key) {\n x[1] = value;\n kvp[i] = x.join('=');\n break;\n }\n }\n\n if (i < 0) {\n kvp[kvp.length] = [key, value].join('=');\n }\n\n //this will reload the page, it's likely better to store this until finished\n document.location.search = kvp.join('&');\n }",
"function update_query_params(params, hash_mode) {\n if (hash_mode === void 0) { hash_mode = false; }\n var search = hash_mode ? get_hash_search() : get_location_search();\n for (var key in params) {\n var value = params[key];\n if (typeof value === \"undefined\" || value === \"\" || value === false)\n search.delete(key);\n else\n search.set(key, value.toString());\n }\n if (hash_mode)\n set_hash_search(search);\n else\n set_location_search(search);\n}",
"function updateQuery() {\n var newUrl = window.location.href;\n // clean out valueless parameters to simplify ensuing matching\n newUrl = newUrl.replace(/(.*[?&])param1(&(.*))?$/, \"$1$3\");\n if (param1 !== default1) {\n if (newUrl.match(/[?&]param1=/)) {\n newUrl = newUrl.replace(/(.*[?&]param1=)[^&]*(.*)/, '$1' + param1 + '$2');\n } else if (newUrl.indexOf('?') > 0) {\n newUrl = newUrl + '¶m1=' + param1;\n } else {\n newUrl = newUrl + '?param1=' + param1;\n }\n } else {\n newUrl = newUrl.replace(/(.*[?&])param1=[^&]*&?(.*)/, '$1$2');\n }\n\n // tidy up\n if (newUrl.match(/[?&]$/)) {\n newUrl = newUrl.slice(0, -1);\n } \n window.history.pushState('', '', newUrl);\n}",
"function insertParamPriceHL(key, value) {\n key = encodeURI(key);\n value = encodeURI(value);\n var kvp = document.location.search.substr(1).split('&');\n var i = kvp.length;\n var x;\n while (i--) {\n x = kvp[i].split('=');\n\n if (x[0] == key) {\n x[1] = value;\n kvp[i] = x.join('=');\n break;\n }\n }\n if (i < 0) {\n kvp[kvp.length] = [key, value].join('=');\n }\n\n //this will reload the page, it's likely better to store this until finished\n document.location.search = kvp.join('&');\n}",
"function addToURL(key, value) {\n\tkey = encodeURI(key); value = encodeURI(value);\n\tvar kvp = document.location.search.substr(1).split(\"&\");\n\tvar i = kvp.length; \n\tvar x;\n\n\t// format url\n\twhile (i--) {\n\t\tx = kvp[i].split(\"=\");\n\t\tif (x [0] == key) {\n\t\t\tx [1] = value;\n\t\t\tkvp [i] = x.join(\"=\");\n\t\t\tbreak;\n\t\t} // if\n\t} // while\n\n\t// join keys and values together\n\tif (i < 0) kvp[kvp.length] = [key, value].join(\"=\");\n\n\t// reload page\n\tdocument.location.search = kvp.join(\"&\"); \n} // addToURL",
"function setUrlParameter(key, value) {\n key = encodeURI(key);\n value = encodeURI(value);\n\n var kvp = document.location.search.substr(1).split('&');\n var i = kvp.length;\n var x;\n while (i--) {\n x = kvp[i].split('=');\n\n if (x[0] == key) {\n x[1] = value;\n kvp[i] = x.join('=');\n break;\n }\n }\n\n if (i < 0) {\n kvp[kvp.length] = [key, value].join('=');\n }\n\n //Set back url\n window.history.replaceState('', '', window.location.href.split(\"?\")[0] + \"?\" + kvp.join('&'));\n}",
"updateQueryParameters() {\n const query = Object.assign({}, this.$route.query);\n\n Object.keys(this.filters).forEach(parameter => {\n query[parameter] = this.filters[parameter];\n if (!query[parameter]) {\n delete query[parameter];\n }\n });\n\n this.$router.push({ to: this.$route.name, query });\n }",
"function updateUrl(url,key,value){\n\tif(value!=undefined){\n\t\tvalue = encodeURI(value);\n\t}\n\tvar urls = url.split('?');\n\tvar baseUrl = urls[0];\n\tvar parameters = '';\n\tvar outPara = {};\n\tif(urls.length>1){\n\t\tparameters = urls[1];\n\t}\n\tif(parameters!=''){\n\t\tparameters = parameters.split('&');\n\t\tfor(k in parameters){\n\t\t\tvar keyVal = parameters[k];\n\t\t\tkeyVal = keyVal.split('=');\n\t\t\tvar ekey = keyVal[0];\n\t\t\tvar eval = '';\n\t\t\tif(keyVal.length>1){\n\t\t\t\teval = keyVal[1];\n\t\t\t}\n\t\t\toutPara[ekey] = eval;\n\t\t}\n\t}\n\n\tif(value!=undefined){\n\t\toutPara[key] = value;\n\t}else{\n\t\tdelete outPara[key];\n\t}\n\tparameters = [];\n\tfor(var k in outPara){\n\t\tparameters.push(k + '=' + outPara[k]);\n\t}\n\n\tvar finalUrl = baseUrl;\n\n\tif(parameters.length>0){\n\t\tfinalUrl += '?' + parameters.join('&'); \n\t}\n\n\treturn finalUrl; \n}",
"function updateUrl(argDict) {\n var url = window.location.origin + window.location.pathname + '?';\n\n for (var key in argDict) {\n var values = argDict[key];\n for (var i in values) {\n url += '&' + key + '=' + values[i];\n }\n }\n window.location.href = url;\n}",
"parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n } else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }",
"append(current_url, key, value) {\n const current = url.parse(current_url)\n const params = new URLSearchParams(current.search)\n \n params.set(key, value)\n return params.toString()\n }",
"addQueryParameter(url, key, value, isFirstParameter){\n var newUrl = url;\n if (isFirstParameter) {\n newUrl += `?${key}=${value}`;\n }\n else {\n newUrl += `&${key}=${value}`;\n }\n \n return newUrl;\n }",
"function addNewQueryParam() {\n const newQueryParamKey = document.getElementById(\"newQueryStringKey\").value;\n const newQueryParamVal = document.getElementById(\"newQueryStringValue\").value;\n if(newQueryParamKey !== \"\" && newQueryParamVal !== \"\") {\n if(deletedParams.indexOf(newQueryParamKey) !== -1) {\n deletedParams.splice(deletedParams.indexOf(newQueryParamKey), 1);\n }\n storeQueryParamsinStorage(newQueryParamKey,newQueryParamVal, true);\n }\n}",
"updateQuery(queryParamsToUpdate) {\n const query = fromJS(this.props.location.query)\n .merge(fromJS(queryParamsToUpdate))\n .toJS();\n this.setQuery(query);\n }",
"parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n }\n else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Username Validation / Have the function usernameValidation(str) take the str parameter being passed and determine if the string is a valid username according to the following rules: 1. The username is between 4 and 25 characters. 2. It must start with a letter. 3. It can only contain letters, numbers, and the underscore character. 4. It cannot end with an underscore character. If the username is valid then your program should return the string true, otherwise return the string false. | function usernameValidation(str) {
const letters = /[A-Za-z]/g, regExp = /[A-Za-z0-9_]/g, regExp_ = /[^_]/g;
if (4 < str.length < 25 && letters.test(str[0]) && regExp.test(str) && regExp_.test(str[str.length - 1]))
return true;
else return false
} | [
"function fnIsValidUsername(username){\n // username must have a length of minimum 1 char and maximum 31 chars\n if (username.length < 1 || username.length > 31){\n return false;\n }\n\n // username must start with a lowercase letter or an underscore\n if (fnValidateString(username.charAt(0), [\"az\", \"_\"]) !== true){\n return false;\n }\n\n // username last char must be a lowercase letter, a digit, an underscore, a hyphen or a dollar sign\n if (fnValidateString(username.charAt(username.length - 1), [\"az\", \"09\", \"_\", \"-\", \"$\"]) !== true){\n return false;\n }\n\n // username body (except first and last char) must contain lowercase letters, digits, underscores or hyphens\n if (username.length > 2 && fnValidateString(username.substring(1).slice(0, -1), [\"az\", \"09\", \"_\", \"-\"]) !== true){\n return false;\n }\n\n return true;\n}",
"function CodelandUsernameValidation(str) {\n // YOUR CODE HERE\n let pattern = \"/^w+$/\";\n if (str.length >= 4 || str.length <= 25)\n if (str[0] === \"/^w\")\n if (str === pattern)\n if (str[str.length - 1] !== \"_\") return true;\n else {return false;};\n}",
"function validateUsername(username){\n var re = /^[a-zA-Z0-9-_]{3,20}$/;\n return re.test(username);\n}",
"function validate(username){\n if (username === undefined || username === null)\n return false;\n\n // https://stackoverflow.com/questions/60068785/regex-to-username-that-contains-alphanumeric-characters-and-at-most-one-undersco\n // return /^(?=.{4})[a-z\\d]*_?[a-z\\d]+$/i.test(username);\n\n // https://stackoverflow.com/questions/11431154/regular-expression-for-username-start-with-letter-and-end-with-letter-or-number\n // return /^[a-zA-Z]([._-]?[a-zA-Z0-9]+)*$/i.test(username);\n\n // my version: \n return /^(?=.{4})[a-z]([_]?[a-z\\d]+)*$/i.test(username);\n}",
"function validate_username(input_username) {\n\tvar re = /(?=.*[a-zA-Z0-9])^[a-zA-Z0-9]{6,12}$/;\n\treturn re.test(input_username);\n}",
"function validateUsername() {\n var _userName = getUserName();\n\n return !checkSpace(_userName);\n}",
"function test_username(username) {\r\n\tif(typeof username == 'undefined')\r\n\t\treturn \"No username was provided.\";\r\n\r\n\tvar regex = /^([A-z0-9]|_|-|\\.){3,30}$/;\r\n\tif(!regex.test(username)) {\r\n\t\treturn \"Invalid username.\";\r\n\t}\r\n\r\n\treturn '';\r\n}",
"function validateUsername(username) {\n\n}",
"function userName() {\n var errors = document.querySelector(\"#errors\");\n var user = document.querySelector(\"#user\");\n var uName = user.value.trim();\n var patt = /^[a-z]{6,16}$/ig;\n if(!patt.test(uName)) {\n errorMessage(\"<p>Please enter a User Name that starts with a letter</p>\");\n return false;\n } else {\n return true;\n }\n}",
"function isValidUsername(username) {\n if (username.length > 8) return false;\n else return true;\n}",
"validateUsername(username) {\n var re = /\\d{2}\\D{1,2}\\d{4,6}/;\n\n return re.test(username);\n }",
"function validateUsername(username){\n let validUsername = /^[a-zA-Z0-9]{5,20}$/;\n return validUsername.test(username);\n}",
"is_legal_username(username) {\n // eliminate leading and trailing spaces\n let re_space_before = new RegExp('^ ');\n let re_space_after = new RegExp(' $');\n let re_illegal_characters = new RegExp('[^a-zA-Z0-9 @_?!~-]');\n if (re_space_before.test(username)) {\n return \"Please remove the leading spaces from your name.\"\n }\n if (re_space_after.test(username)) {\n return \"Please remove the trailing spaces from your name.\";\n }\n // it also allows stuff like ()%*^$\\ but let's *not* break regular expressions...\n if (re_illegal_characters.test(username)) {\n return \"Please only use these symbols, if any: @_?!~-_ (or spaces)\";\n }\n else {\n return \"\";\n }\n }",
"function validateUserName(username) {\n if (username.length < 3) {\n notifier.showError('Invalid username: should be at least 3 characters long and should contain only english alphabet letters.');\n return false;\n }\n\n let regex = new RegExp(`^[a-zA-Z]+$`);\n if (!regex.exec(username)) {\n notifier.showError('Invalid username: should be at least 3 characters long and should contain only english alphabet letters.');\n return false;\n }\n\n return true;\n }",
"function isValidUsername(username){\n return username.length > 0;\n}",
"static checkInvalidUsernameChars(username) {\n if (!username || username.length === 0) {\n return false;\n }\n let c = username.charAt(0);\n if (c >= '0' && c <= '9') {\n return true;\n }\n return /[^a-zA-Z0-9_]/.test(username)\n }",
"static checkInvalidUsernameChars(username) {\n if (!username || username.length === 0) {\n return false;\n }\n let c = username.charAt(0);\n if (c >= '0' && c <= '9') {\n return true;\n }\n return /[^a-zA-Z0-9_]/.test(username)\n }",
"function validUserName(userName) {\n\treturn userName.length >= 4;\n}",
"function checkUserName(username) {\n if(username === undefined){\n return;\n }\n if (username.length < 6 || username.length > 30) {\n return false;\n }\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
display message when trace is running | function traceRunning() {
console.log("Trace initialized...");
messageControl.onTraceStart();
} | [
"function showTrace() {Config.LogLevel = LogLevels.TRACE;}",
"function traceSuccess() {\n messageControl.onTraceComplete();\n var msg = \"Trace Complete\";\n console.log(msg);\n }",
"function trace( message) \n{\n if(!debugWindow || !debugWindow.open || debugWindow.closed)\n {\n debugWindow = window.open(\"about:blank\",\"debug\");\n // to avoid permission denied exception if another window has open the window before\n //\n debugWindow.close();\n debugWindow = window.open(\"about:blank\",\"debug\");\n if(parent!=null && parent.frames['menu'] && debugWindow!=null)\n {\n parent.frames['menu'].debugWindow = debugWindow;\n }\n }\n debugWindow.document.writeln(\"<pre>\"+message+\"</pre>\")\n}",
"function trace(txt) {\r\n\tif (DEBUG_MODE) { \r\n\t\tconsole.log(txt);\r\n\t}\r\n}",
"function trace() {\n controllerObj.pushCommand(controllerObj.debuggerCommands.trace, arguments);\n}",
"function trace(msg) {\n if (DEBUG_TRACE && msg) {\n console.log('TRACE: %s', msg);\n }\n}",
"function frameTrace(message)\r\n {\r\n if (traceLevel > 2 && ((new Date()).getTime()-tStart)/1000 < 10.0)\r\n {\r\n try\r\n { \r\n // console.log(idDiv+\": \"+((new Date()).getTime()-tStart)/1000+\"s: \"+message);\r\n }\r\n catch (e) {}\r\n }\r\n }",
"Trace(aMsg) {\r\n this.AddLogMessage(aMsg, ButtplugLogLevel.Trace);\r\n }",
"function trace(msg){\r\n rootLogger.trace(msg)\r\n}",
"set trace(msg) {\n logger.trace = msg;\n }",
"drawTrace() {\n super.drawTrace();\n }",
"function trace (text, force = false) {\r\n if (options.traceEnabled || force) {\r\n\tconsole.log(text+\"\\r\\n\");\r\n }\r\n}",
"function zenTRACE(msg,reason,code)\r\n{\r\n\tvar now = new Date();\r\n\r\n\tvar txt = '';\r\n\ttxt += zenJustify(now.getMinutes(),2,'0') + \":\" + zenJustify(now.getSeconds(),2,'0') + \".\" + zenJustify(now.getMilliseconds(),3,'0') + \" \";\r\n\ttxt += msg;\r\n\r\n\tif (null != reason && '' != reason) {\r\n\t\ttxt += ': ' + reason;\r\n\t}\r\n\tif (null != code && '' != code) {\r\n\t\tcode= code.replace(/\\x04/g,','); // could be an argument list\r\n\t\ttxt += '(' + code + ')';\r\n\t}\r\n\ttxt += '\\n';\r\n\r\n\tvar tracewin = window.open(\"\",\"zenTRACEWindow\",\"scrollbars,resizable,height=400,width=700,toolbar=no,directories=no,status=no,menubar=no\");\r\n\tif (null == tracewin.document.getElementById(\"code\")) {\r\n\t\ttracewin = window.open(\"\",\"zenTRACEWindow\",\"scrollbars,resizable,height=400,width=700,toolbar=no,directories=no,status=no,menubar=no\");\r\n\t\ttracewin.document.write('<html><head></head><body style=\"font-family: verdana; background: #c5d6d6;\">');\r\n\t\ttracewin.document.title='ZEN TRACE';\r\n\t\ttracewin.document.write('<div style=\"font-size:0.8em; font-variant: small-caps;\">Event Trace:</div><textarea id=\"code\" cols=\"80\" rows=\"16\">');\r\n\t\ttracewin.document.write(txt);\r\n\t\ttracewin.document.write('</textarea>');\r\n\t\ttracewin.document.write('<br><br><input type=\"button\" value=\"Clear\" title=\"Clear trace list\" onclick=\"window.document.getElementById(\\'code\\').value=\\'\\';\">');\r\n\t\ttracewin.document.write(' <input type=\"button\" value=\"Close\" title=\"Close this window\" onclick=\"window.close();\">');\r\n\t\ttracewin.document.write('</body></html>');\r\n\t\ttracewin.document.close();\r\n\t}\r\n\telse {\r\n\t\t// append\r\n\t\ttracewin.document.getElementById(\"code\").value = tracewin.document.getElementById(\"code\").value + txt;\r\n\t}\r\n\r\n\ttracewin.focus();\r\n}",
"function __h_trace(msg, args, res) {\n var str = \"TRACE: \" + msg + \"\\n\"\n + \" ARGS: \" + args + \"\\n\"\n + \" RETURNS: \" + res;\n __h_debug(str);\n return res;\n}",
"function trace (text, force = false) {\n if (options.traceEnabled || force) {\n TracePlace.textContent += text + \"\\r\\n\";\n }\n}",
"function trace(bytLevel, strText) {\n\n if (g_bytTraceLevel >= bytLevel) {\n WScript.Echo(strText);\n }\n\n}",
"trace ( /* ... */ ) {\n this.TRACE >= this.level.number &&\n this.log.call( this, arguments, console && console.debug, console ); // not console.trace(), which would log the stack\n }",
"function do_print(msg) {\n var caller_stack = Components.stack.caller;\n msg = _wrap_with_quotes_if_necessary(msg);\n _dump(\"TEST-INFO | \" + caller_stack.filename + \" | \" + msg + \"\\n\");\n}",
"tracegx ( /* label, ... */ ) {\n this.TRACE >= this.level.number &&\n this.log.call( this, arguments, console && console.group, console, true );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wraps object returned by createElement in constructor function to have same signature as Class Component (call render) | function wrapper() {
this.render = () => {
return element;
};
} | [
"mountComponent(container){\n\n // get the wrapped class\n const Component = this._currentElement.type;\n\n // call the wrapped class\n const componentInstance = new Component(this._currentElement.props)\n \n // get the props of wrapped element\n let element = componentInstance.render()\n\n // if passed element is a custom component, get its type and props\n while(typeof element.type === 'function'){\n element = (new element.type(element.props)).render();\n }\n \n // pass element type and props into FeactDomComponent to render in the DOM\n const domComponentInstance = new FeactDomComponent(element);\n\n return domComponentInstance.mountComponent(container);\n }",
"function createElement() {\n const args = Array.prototype.slice.call(arguments, 0)\n const def = args.shift()\n\n invariant(def, \"createElement needs a component definition\")\n\n let component =\n typeof def === \"string\" || typeof def === \"function\" ? def : cache.get(def)\n\n if (component == null) {\n component = createComponent(def)\n cache.set(def, component)\n }\n\n args.unshift(component)\n\n return React.createElement.apply(React, args)\n}",
"function Foo() {\n return new Component({});\n}",
"function createElement(...args) {\n const def = args[0]\n\n invariant(def, \"createElement needs a component definition\")\n\n if (typeof def !== \"string\" && typeof def !== \"function\") {\n let component = cache.get(def)\n\n if (component == null) {\n component = createComponent(def)\n cache.set(def, component)\n }\n\n args[0] = component\n }\n\n return React.createElement(...args)\n}",
"mountElement() {\n let { children, ...props } = this.getReactProps();\n\n if (!children) {\n const childNodes = this.element.childNodes;\n children = [\n React.createElement(YieldWrapper, {\n key: this.elementId,\n nodes: [...childNodes],\n }),\n ];\n }\n\n const KlassToRender = isFunctionalComponent(Klass)\n ? Klass\n : grantOwnerAccess(Klass, getOwner(this));\n\n ReactDOM.render(\n React.createElement(KlassToRender, props, children),\n this.element\n );\n }",
"function Component() {}",
"constructor() {\n super(); // loading the parent component methods and properties\n return this.buildComponenent(); // this function should always be called, it returns the object to render\n }",
"function createElement(type,config,children){var propName;// Reserved names are extracted\nvar props={};var key=null;var ref=null;var self=null;var source=null;if(config!=null){if(hasValidRef(config)){ref=config.ref;}if(hasValidKey(config)){key=''+config.key;}self=config.__self===undefined?null:config.__self;source=config.__source===undefined?null:config.__source;// Remaining properties are added to a new props object\nfor(propName in config){if(hasOwnProperty.call(config,propName)&&!RESERVED_PROPS.hasOwnProperty(propName)){props[propName]=config[propName];}}}// Children can be more than one argument, and those are transferred onto\n// the newly allocated props object.\nvar childrenLength=arguments.length-2;if(childrenLength===1){props.children=children;}else if(childrenLength>1){var childArray=Array(childrenLength);for(var i=0;i<childrenLength;i++){childArray[i]=arguments[i+2];}{if(Object.freeze){Object.freeze(childArray);}}props.children=childArray;}// Resolve default props\nif(type&&type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}}{if(key||ref){if(typeof props.$$typeof==='undefined'||props.$$typeof!==REACT_ELEMENT_TYPE){var displayName=typeof type==='function'?type.displayName||type.name||'Unknown':type;if(key){defineKeyPropWarningGetter(props,displayName);}if(ref){defineRefPropWarningGetter(props,displayName);}}}}return ReactElement(type,key,ref,self,source,ReactCurrentOwner.current,props);}",
"function createElement(type,config,children){var propName=void 0;// Reserved names are extracted\nvar props={};var key=null;var ref=null;var self=null;var source=null;if(config!=null){if(hasValidRef(config)){ref=config.ref;}if(hasValidKey(config)){key=''+config.key;}self=config.__self===undefined?null:config.__self;source=config.__source===undefined?null:config.__source;// Remaining properties are added to a new props object\nfor(propName in config){if(hasOwnProperty.call(config,propName)&&!RESERVED_PROPS.hasOwnProperty(propName)){props[propName]=config[propName];}}}// Children can be more than one argument, and those are transferred onto\n// the newly allocated props object.\nvar childrenLength=arguments.length-2;if(childrenLength===1){props.children=children;}else if(childrenLength>1){var childArray=Array(childrenLength);for(var i=0;i<childrenLength;i++){childArray[i]=arguments[i+2];}{if(Object.freeze){Object.freeze(childArray);}}props.children=childArray;}// Resolve default props\nif(type&&type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}}{if(key||ref){var displayName=typeof type==='function'?type.displayName||type.name||'Unknown':type;if(key){defineKeyPropWarningGetter(props,displayName);}if(ref){defineRefPropWarningGetter(props,displayName);}}}return ReactElement(type,key,ref,self,source,ReactCurrentOwner.current,props);}",
"constructor (){\n super()\n //every class component must have a render method\n }",
"getElementConstructor(type) {\n return JSXElement;\n }",
"function Component(params) {\n\n //default type\n this.type = \"div\";\n\n //default children = empty array\n this.children = [];\n\n //initalize object with specified parameters\n for (var property in params) {\n if (params.hasOwnProperty(property)) {\n this[property] = params[property];\n }\n }\n\n this.render = function(target) {\n\n if (target instanceof Component) {\n //ref for adding child\n var targetComponent = target;\n target = target.ref;\n }\n\n //default target is body tag\n if (!target) {\n target = document.body;\n }\n\n //create element, DIV if not specified\n var element = document.createElement(this.type);\n\n //loop through compontent properties and add to element\n for (var property in this) {\n if (this.hasOwnProperty(property)) {\n if (property === \"id\") {\n element.id = this.id;\n } else if (property === \"classes\") {\n for (var i = 0; i < this.classes.length; i++) {\n element.classList.add(this.classes[i]);\n }\n } else if (property === \"text\") {\n element.textContent = this.text;\n } else if (property === \"src\") {\n element.src = this.src;\n } else if (property === \"listener\") {\n element.addEventListener(this.listener[0], this.listener[1].bind(this), false);\n }\n }\n }\n\n //if not top level component\n if (this.parent) {\n //if position of compontent unspecified, default to last position\n if (arguments[2] == null) {\n target.appendChild(element);\n }\n\n //if specified, add element to position\n else {\n if (this.position === 0) {\n target.prepend(element);\n } else if (this.position === this.parent.children.length - 1) {\n target.appendChild(element);\n } else {\n target.insertBefore(element, target.children[this.position]);\n }\n }\n } \n \n //if top level component\n else {\n if (arguments[2] == null) {\n target.appendChild(element);\n }\n\n else {\n if (arguments[2] === 0) {\n target.prepend(element);\n } else if (arguments[2] === this.containerElement.children.length - 1) {\n target.appendChild(element);\n } else {\n target.insertBefore(element, target.children[arguments[2]]);\n }\n }\n }\n \n //DOM reference to component\n this.ref = element;\n //DOM reference to parent element\n this.containerElement = this.ref.parentElement;\n\n //if called from parent, parent object passed in as second argument\n //if component is child of another component, store parent and positional information\n if (arguments[1]) {\n this.parent = arguments[1];\n this.position = arguments[1].children.indexOf(this);\n }\n\n //render all children of this element\n if (this.hasOwnProperty(\"children\")) {\n for (var i = 0; i < this.children.length; i++) {\n this.children[i].render(this.ref, this);\n }\n } \n\n if (targetComponent && targetComponent.children.indexOf(this) === -1) {\n targetComponent.children.push(this);\n }\n };\n\n //pass in object containing paramaters to change\n //automatically updates and re-renders component\n this.update = function(params) {\n\n for (var property in params) {\n if (params.hasOwnProperty(property)) {\n this[property] = params[property];\n }\n }\n\n //if top level component, must remember position via DOM positions\n if (!this.parent) {\n var position = Array.prototype.slice.call(this.containerElement.children).indexOf(this.ref);\n }\n \n //remove component from dom\n this.containerElement.removeChild(this.ref);\n\n if (this.parent) {\n //update parent to contain updated component\n this.parent.children[this.position] = this;\n //render component is same place\n this.render(this.containerElement, false, this.position);\n } else {\n this.render(this.containerElement, false, position);\n }\n }\n}",
"function create(\n Component: ReactClass<any>,\n): ReactClass<any> {\n\n class Container extends React.Component<any, Props, any> {\n\n _component: any;\n _onComponentRef: (view: any) => void;\n _onPositionChange: (data: {value: number}) => void;\n _pointerEvents: string;\n _positionListener: ?NavigationAnimatedValueSubscription;\n\n props: Props;\n\n constructor(props: Props, context: any) {\n super(props, context);\n this._pointerEvents = this._computePointerEvents();\n }\n\n componentWillMount(): void {\n this._onPositionChange = this._onPositionChange.bind(this);\n this._onComponentRef = this._onComponentRef.bind(this);\n }\n\n componentDidMount(): void {\n this._bindPosition(this.props);\n }\n\n componentWillUnmount(): void {\n this._positionListener && this._positionListener.remove();\n }\n\n componentWillReceiveProps(nextProps: Props): void {\n this._bindPosition(nextProps);\n }\n\n render(): ReactElement<any> {\n this._pointerEvents = this._computePointerEvents();\n return (\n <Component\n {...this.props}\n pointerEvents={this._pointerEvents}\n onComponentRef={this._onComponentRef}\n />\n );\n }",
"function createComponent(Ctor, props, context, vnode) {\n var list = components[Ctor.name],\n inst = void 0;\n\n if (Ctor.prototype && Ctor.prototype.render) {\n inst = new Ctor(props, context);\n Component.call(inst, props, context);\n } else {\n inst = new Component(props, context);\n inst.constructor = Ctor;\n inst.render = doRender;\n }\n vnode && (inst.scopedCssAttr = vnode.css);\n\n if (list) {\n for (var i = list.length; i--;) {\n if (list[i].constructor === Ctor) {\n inst.nextBase = list[i].nextBase;\n list.splice(i, 1);\n break;\n }\n }\n }\n return inst;\n }",
"function BaseLightningElementConstructor() {\n // This should be as performant as possible, while any initialization should be done lazily\n if (isNull(vmBeingConstructed)) {\n throw new ReferenceError('Illegal constructor');\n }\n\n {\n assert.invariant(vmBeingConstructed.elm instanceof HTMLElement, `Component creation requires a DOM element to be associated to ${vmBeingConstructed}.`);\n }\n\n const vm = vmBeingConstructed;\n const {\n elm,\n mode,\n def: {\n ctor\n }\n } = vm;\n const component = this;\n vm.component = component;\n vm.tro = getTemplateReactiveObserver(vm);\n vm.oar = create(null); // interaction hooks\n // We are intentionally hiding this argument from the formal API of LWCElement because\n // we don't want folks to know about it just yet.\n\n if (arguments.length === 1) {\n const {\n callHook,\n setHook,\n getHook\n } = arguments[0];\n vm.callHook = callHook;\n vm.setHook = setHook;\n vm.getHook = getHook;\n } // attaching the shadowRoot\n\n\n const shadowRootOptions = {\n mode,\n delegatesFocus: !!ctor.delegatesFocus,\n '$$lwc-synthetic-mode$$': true\n };\n const cmpRoot = elm.attachShadow(shadowRootOptions); // linking elm, shadow root and component with the VM\n\n associateVM(component, vm);\n associateVM(cmpRoot, vm);\n associateVM(elm, vm); // VM is now initialized\n\n vm.cmpRoot = cmpRoot;\n\n {\n patchComponentWithRestrictions(component);\n patchShadowRootWithRestrictions(cmpRoot, EmptyObject);\n }\n\n return this;\n } // HTML Element - The Good Parts",
"function createElement(type,config,children){var propName;// Reserved names are extracted\nvar props={};var key=null;var ref=null;var self=null;var source=null;if(config!=null){if(hasValidRef(config)){ref=config.ref;{warnIfStringRefCannotBeAutoConverted(config);}}if(hasValidKey(config)){key=''+config.key;}self=config.__self===undefined?null:config.__self;source=config.__source===undefined?null:config.__source;// Remaining properties are added to a new props object\nfor(propName in config){if(hasOwnProperty.call(config,propName)&&!RESERVED_PROPS.hasOwnProperty(propName)){props[propName]=config[propName];}}}// Children can be more than one argument, and those are transferred onto\n// the newly allocated props object.\nvar childrenLength=arguments.length-2;if(childrenLength===1){props.children=children;}else if(childrenLength>1){var childArray=Array(childrenLength);for(var i=0;i<childrenLength;i++){childArray[i]=arguments[i+2];}{if(Object.freeze){Object.freeze(childArray);}}props.children=childArray;}// Resolve default props\nif(type&&type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}}{if(key||ref){var displayName=typeof type==='function'?type.displayName||type.name||'Unknown':type;if(key){defineKeyPropWarningGetter(props,displayName);}if(ref){defineRefPropWarningGetter(props,displayName);}}}return ReactElement(type,key,ref,self,source,ReactCurrentOwner.current,props);}",
"render() {\n let div = document.createElement(\"div\");\n\n div.setAttribute('id', this.elementID());\n div.setAttribute('doze', this.componentType());\n\n if (this.classes.count > 0) {\n div.setAttribute('class', this.htmlClasses());\n }\n\n this.element = div;\n\n return this.element;\n }",
"function instantiateComponent(element){\n\tlet componentInstance\n\tif (typeof element.type === 'function'){\n\t\t// class\n\t\tcomponentInstance = new element.type(element.props)\n\t\tcomponentInstance._construct(element) // this._currentElement = element\n\t}else if (typeof element.type === 'string'){\n\t\t// DOM component like 'div'...\n\t\tcomponentInstance = new DOMComponent(element)\n\t}else if(typeof element === 'string' || typeof element === 'number' ){\n\t\t// Text like 'helloworld'...\n\t\tcomponentInstance = new DOMComponent({\n\t\t\ttype : 'span',\n\t\t\tprops: {\n\t\t\t\tchildren : element\n\t\t\t}\n\t\t})\n\t}\n\n\treturn componentInstance\n}",
"function renderTo() {\n var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document.body;\n\n return function (WrappedComponent) {\n var EnhancedComponent = function (_PureComponent) {\n inherits(EnhancedComponent, _PureComponent);\n\n function EnhancedComponent() {\n classCallCheck(this, EnhancedComponent);\n return possibleConstructorReturn(this, (EnhancedComponent.__proto__ || Object.getPrototypeOf(EnhancedComponent)).apply(this, arguments));\n }\n\n createClass(EnhancedComponent, [{\n key: 'componentWillMount',\n value: function componentWillMount() {\n this.wrapNode = document.createElement('div');\n target.appendChild(this.wrapNode);\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n this.renderComponent();\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this.renderComponent();\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n ReactDOM.unmountComponentAtNode(this.wrapNode);\n this.wrapNode.parentNode.removeChild(this.wrapNode);\n }\n }, {\n key: 'renderComponent',\n value: function renderComponent() {\n ReactDOM.unstable_renderSubtreeIntoContainer(this, React.createElement(WrappedComponent, this.props), this.wrapNode);\n }\n }, {\n key: 'render',\n value: function render() {\n return null;\n }\n }]);\n return EnhancedComponent;\n }(PureComponent);\n\n index$2(EnhancedComponent, WrappedComponent);\n return EnhancedComponent;\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event handler for the select onchange event. Updates the speed with the new speed selected by the user by making an ajax request to the database to update the user's speed in the table. | function updateSpeed(){
var selectedSpeed = g.wpmSelect.value;
//validates first if the selected speed is a number between 50 - 20000
if(selectedSpeed.match(/^\d+$/) && g.speedArr.indexOf(selectedSpeed) !== -1){
var req = createHTTPRequest();
req.open("POST", "speedreaderajax.php", true);
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var jsonResponse = JSON.parse(req.responseText);
if(jsonResponse !== null){
console.log(jsonResponse.result);
}
} else if (req.readyState == 4) {
g.speedReaderError.innerText = "Something bad happened. Problem updating speed.";
}
};
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.send('selectedSpeed=' + selectedSpeed);
}
} | [
"function updateSpeed() {\n\tturnSpeed = $(\"#speedSlider\").val();\n}",
"function updateSpeedOption() {\n var currText = 'Velocidad';\n var currValue = gameSpeed;\n $('#optSpeed').attr('value', currText + ' (' + currValue + ')');\n}",
"function updateSpeed(){\n\tspeedMultiplier = (document.getElementById('input-speed').value)/20;\n}",
"function setSpeedFromSelect(select) {\n\tvar interval = intervals[select.value];\n\tif (!interval)\n\t\treturn;\n\n\tcurrentInterval = select.value;\n\tif (running) {\n\t\tclearInterval(loop);\n\t\tloop = setInterval(updateAndDraw, interval);\n\t}\n}",
"function getUpdateSpeed() {\r\n\tupdateSpeed = $('updateSpeed').value;\r\n}",
"function handleSpeedInputChange(evt)\n {\n activeVisualizer.setSpeed(parseFloat(evt.target.value));\n playbackSpeed.value = evt.target.value;\n }",
"function updateSpeed() {\n\tif(!paused) {\n\t\tclearInterval(interval);\n\t\tinterval = setInterval(doTick, speed);\n\t}\n\t$('#speed-input').val(speed);\n\t$('#speed-text').html(speed);\n\n\tlet rotation = (speed / (MAX_SPEED - MIN_SPEED) ) * 180 - 90;\n\trotation *= -1;\n\t$('#speed-line').css('transform', 'rotate('+rotation+'deg)');\n}",
"function handleUnitChange()\n\t{\n\t\tspeedLimitUnit = document.getElementById(\"speedUnit\").value;\n\t\tclearSpeedlimitAlongRoute();\n\t\tgenerateMaxSpeedlimitAlongRoute();\n\t\thandleSpeedlimitChanged();\n\t}",
"function speedChanged() {\n\n const speedChanger = document.getElementById(\"speedChanger\");\n const temp = speedChanger.options[speedChanger.selectedIndex];\n hdxAV.delay = temp.value;\n hdxAV.speedName = temp.innerHTML;\n\n // for run options, set update time, should match the values\n // set in the speedChanged when created in index.php\n if (hdxAV.delay < -1) {\n\thdxAV.delay = 0;\n\tif (hdxAV.speedName == \"1 Update/sec\") {\n\t hdxAV.updateTime = 1000;\n\t}\n\telse if (hdxAV.speedName == \"15 Updates/sec\") {\n\t hdxAV.updateTime = 67;\n\t}\n\telse { //if (hdxAV.speedName == \"60 Updates/sec\")\n\t hdxAV.updateTime = 17;\n\t}\n }\n // this will hide the log message when running on faster speeds\n // when it is going by too fast to see anyway\n if (hdxAV.delay == -1 || hdxAV.delay == 2000 || hdxAV.delay == 675) {\n document.getElementById(\"algorithmStatus\").style.display = \"\";\n }\n else {\n document.getElementById(\"algorithmStatus\").style.display = \"none\";\n }\n}",
"function changeSpeed(value) {\n playbackitem.setSpeed(parseFloat(value));\n}",
"function setSpeed() {}",
"function updateTransitionSpeed(){\n\ttransitionSpeedMultiplier = document.getElementById(\"transitionSpeedMultiplier\").value;\n}",
"changeSpeed() {\n this.speed = document.getElementById('slider').value;\n document.getElementById('speed-text').innerHTML = \"Animation Speed: \" + this.speed + \" ms\";\n }",
"function handleDesiredIntervalChange(e) {\n let speed = e.target.value\n if (speed < 100) {\n speed = 100\n } else if (speed > 1000) {\n speed = 1000\n }\n setDesiredUpdateInterval(speed)\n }",
"set SpeedUS(newSpeed){\n this.speed = newSpeed * 1.6\n }",
"function setSpeed(newSpeed) {\n console.log(newSpeed);\n speedObj.speed[myTabId] = newSpeed;\n videoSpeed = parseFloat(newSpeed);\n input.value = videoSpeed.toFixed(2);\n chrome.tabs.query({ currentWindow: true, active: true },\n function (tabs) {\n chrome.tabs.sendMessage(tabs[0].id, {\n type: 'video-speed',\n speed: newSpeed\n })\n });\n }",
"function alterSpeed(tabs) {\n browser.tabs.sendMessage(tabs[0].id, {\n msg_type: \"alterSpeed\",\n newSpeed: numSpeed.value\n })\n }",
"function userSpeed()\n{\n\t// Initialisations of values to use for calculations\n\tlet initialtime, finalTime, totalTime;\n\tlet averageSpeed, estimatedTimeValue;\n\n\tlet speedRef = document.getElementById(\"speed\");\n\tlet estimatedTimeRef = document.getElementById(\"estimatedTimeRemaining\");\n\n\tlet distCoveredValue = distanceCovered();\n\tlet remainingDistValue = remainingDistance();\n\n\t// Calculation of total time the user has been navigating for\n\tinitialTime = userHistory[0].timestamp;\n\tfinalTime = userHistory[userHistory.length - 1].timestamp;\n\ttotalTime = finalTime - initialTime;\n\n\t// Calculation of average speed\n\taverageSpeed = distCoveredValue / (totalTime * 10**-3);\n\n\t// Calculation of estimated time ONLY if the average speed is above 0.5 ms-1, else the user\n\t// needs to move more\n\tif (averageSpeed > 0.5) {\n\t\testimatedTimeValue = remainingDistValue / averageSpeed;\n\t\testimatedTimeValue = estimatedTimeValue.toFixed(0);\n\t}\n\telse {\n\t\testimatedTimeValue = \" - \";\n\t}\n\n\taverageSpeed = averageSpeed.toFixed(1);\n\tspeedRef.innerHTML = averageSpeed + \" m/s\";\n\testimatedTimeRef.innerHTML = estimatedTimeValue + \" s\";\n}",
"function speeding() {\r\n\tvar speedInput = document.getElementById('speed');\r\n\r\n\tif (ENABLE_SPEEDING || ENABLE_LAST_LEG_ADJUST) {\r\n\t\tif (SPEED_INCREASE < 0) {\r\n\t\t\tshowVarTooLowAlert('SPEED_INCREASE', 0);\r\n\t\t\tSPEED_INCREASE = 0;\r\n\t\t}\r\n\t\tvar dashboard = getRouteInformation();\r\n\t\tvar defaultSpeed = parseInt(speedInput.defaultValue, 10);\r\n\t\tvar maxSpeed = defaultSpeed + SPEED_INCREASE;\r\n\t\tvar truckSpeed = dashboard.rows[1].cells[3];\r\n\t\tvar maxTruckSpeed = parseInt(truckSpeed.innerText ||\r\n\t\t\ttruckSpeed.textContent, 10);\r\n\t\tvar milesToGo = parseInt(dashboard.rows[6].cells[3]\r\n\t\t\t.firstChild.nodeValue.replace(/,/g, ''), 10);\r\n\r\n\t\tvar legSpeed = defaultSpeed;\r\n\t\tif (ENABLE_SPEEDING) {\r\n\t\t\tlegSpeed = Math.min(maxTruckSpeed, maxSpeed);\r\n\t\t}\r\n\t\t\r\n\t\tif (maxTruckSpeed < TOPSPEED_THRESHOLD) {\r\n\t\t\ttruckSpeed.style.backgroundColor = TOPSPEED_COLOUR;\r\n\t\t}\r\n\r\n\t\tif (ENABLE_LAST_LEG_ADJUST) {\r\n\t\t\tif (milesToGo <= legSpeed) {\r\n\t\t\t\tlegSpeed = milesToGo;\r\n\t\t\t}\r\n\t\t\tif (ENABLE_LAST_LEG_SPEEDING && milesToGo <= maxTruckSpeed) {\r\n\t\t\t\tlegSpeed = milesToGo;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tspeedInput.value = Math.max(legSpeed, MIN_SPEED);\r\n\t\tif (SPEED_COLOUR)\r\n\t\t\tspeedInput.style.backgroundColor = SPEED_COLOUR;\r\n\r\n\t\t/*alert('Default speed: '+defaultSpeed+' Max speed: '\r\n\t\t +maxSpeed+' Truck speed: '+maxTruckSpeed+' Miles to go: '\r\n\t\t +milesToGo+' Selected speed: '+legSpeed);*/\r\n\t}\r\n\telse {\r\n\t\tspeedInput.value = speedInput.defaultValue;\r\n\t}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unchecks all Checkboxes specified in the argument param: items An array of input fields | function ListHelp_uncheckAll(items) {
for (var i=0; i < items.length; i++) {
if (items[i].type == 'checkbox' ) {
// uncheck checkbox
items[i].checked = false;
}
}
} | [
"function uncheck_item(item_list){\r\n if (item_list.length>0){\r\n for(var i=0;i<item_list.length;i++)\r\n item_list[i].checked = false;\r\n }\r\n else{\r\n console.log(\"Cannot uncheck list element!\")\r\n }\r\n}",
"function uncheckAll(field){\n if(field){\n if(field.length){\n for (i = 0; i < field.length; i++)\n field[i].checked = false;\n }else{\n field.checked = false;\n }\n }\n}",
"function uncheckAll(){\n\tfor (var i = 0; i < basefrm.list.length; i++)\n\t{\n\t\tbasefrm.list.elements[i].checked = false;\n\t}\n}",
"unCheck() {\n let checkboxes = document.getElementsByTagName('input');\n for (var i=0; i<checkboxes.length; i++) {\n if (checkboxes[i].type === 'checkbox') {\n checkboxes[i].checked = false;\n }\n }\n }",
"function uncheckAll(){\n for (let i = 0; i < checkboxes.length; i++) {\n checkboxes[i].checked = false;\n }\n}",
"function uncheckAll(name, checkboxes)\r\n{\r\n\tfor (i = 0; i < checkboxes; i++)\r\n\t{\r\n\t\tname[i].checked = \"\";\r\n\t}\r\n}",
"function resetAllCheckboxes() {\n $(checkoxInps).each(function (el, m) {\n $(m).on(\"click\", function () {\n let k = $(this).parent().parent().parent().children().children();\n\n $(k).each(function (el, it) {\n if ($(it).children().length > 1)\n {\n let inp = $(it).children()[1];\n\n // console.log(inp);\n $(inp).prop('checked', false);\n }\n })\n });\n });\n }",
"function removeItems() {\n var itemsList = document.getElementById('list');\n var checkedItems = itemsList.querySelectorAll('input');\n for (var count = 0; count < checkedItems.length; count++) {\n if (checkedItems[count].checked) {\n itemsList.removeChild(checkedItems[count].parentElement);\n }\n }\n }",
"function selectAllCheckboxes(items) {\n items.forEach((item) => {\n item.find(':input').attr('checked', true);\n });\n }",
"function unCheckAll() {\n totalAreaBeChecked = 0;\n $('.myCheckBox').each(function() {\n var id = $(this).attr('class');\n var detail = id.split(\" \");\n id = detail[1];\n $('.' + id).prop('checked', false);\n });\n showRemoveButton(totalAreaBeChecked);\n }",
"function uncheckTech() {\n var checkboxes = $('#tech-required').find('input.tech-check');\n $.map(checkboxes, function(item, index) {\n item.checked = false;\n });\n renderGrid();\n}",
"uncheckGroupItems() {\n let me = this,\n radios;\n\n // discuss: we could limit this to radios inside the same form, IF a top level form is used\n radios = ComponentManager.find({\n ntype: 'radiofield',\n name : me.name\n });\n\n radios.forEach(item => {\n if (item.id !== me.id && item._checked) {\n item._checked = false; // silent update\n\n // keep the vdom & vnode in sync for future updates\n item.vdom.cn[1].checked = false;\n\n if (item.vnode) {\n item.vnode.childNodes[me.hideLabel ? 0 : 1].attributes.checked = 'false';\n }\n\n item.fire('change', {\n component: me,\n oldValue : true,\n value : false\n });\n }\n });\n }",
"function UncheckAll(){ \n var w = document.getElementsByTagName('input'); \n for(var i = 0; i < w.length; i++){ \n if(w[i].type=='checkbox'){ \n w[i].checked = false; \n }\n\t\tif(w[i].type=='radio'){ \n w[i].checked = false; \n }\n }\n }",
"function deselectAllComponents(){\n $(\"input[type=checkbox]\").prop(\"checked\", false);\n }",
"function clearAll() {\n\tvar boxes = document.getElementsByClassName(\"listCheck\");\n\tfor (var i = 0; i < boxes.length; i++) {\n\t\tboxes[i].checked = false;\n\t}\n\thandleChange(this);\n}",
"uncheckGroupItems() {\n let me = this,\n radios;\n\n // discuss: we could limit this to radios inside the same form, IF a top level form is used\n radios = _manager_Component_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].find({\n ntype: 'radiofield',\n name : me.name\n });\n\n radios.forEach(item => {\n if (item.id !== me.id && item._checked) {\n item._checked = false; // silent update\n\n // keep the vdom & vnode in sync for future updates\n item.vdom.cn[1].checked = false;\n\n if (item.vnode) {\n item.vnode.childNodes[me.hideLabel ? 0 : 1].attributes.checked = 'false';\n }\n\n item.fire('change', {\n component: me,\n oldValue : true,\n value : false\n });\n }\n });\n }",
"function uncheckGroup(elems) {\n elems.removeProp(\"checked\");\n }",
"function uncheckAllByButton(button, listOfCheckboxes) {\n\tdocument.getElementById(button).onclick = () => {\n\t\tlistOfCheckboxes.forEach( checkbox => {\n\t\t\tif (checkbox.checked == true) {\n\t\t\t\tcheckbox.click();\n\t\t\t}\n\t\t})\n\t}\n}",
"function checkUncheckAll(){\n\n var status=$(\"#awesome-item-11\").is(':checked');\n if(status==true){\n $('.gender_checkbox').each(function(){ //iterate all listed checkbox items\n this.checked = true; //change \".checkbox\" checked status\n });\n }else{\n $('.gender_checkbox').each(function(){ //iterate all listed checkbox items\n this.checked = false; //change \".checkbox\" checked status\n });\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Agregar gastos al listado | agregarGastoListado(gastos) {
this.limpiarHTML();
//iterar sobre los gastos
gastos.forEach(gasto => {
const { cantidad, nombre, id } = gasto;
//Crear un LI
const nuevoGasto = document.createElement('li');
nuevoGasto.className = 'list-group-item d-flex justify-content-between align-items-center';
nuevoGasto.dataset.id = id;
//Agregar el HTML gasto
nuevoGasto.innerHTML = `
${nombre}
<span class="gasto">${cantidad} € </span>`;
//Boton para borrar el gasto
const btnBorrar = document.createElement('button');
btnBorrar.classList.add('btn', 'btn-danger', 'borrar-gasto');
btnBorrar.setAttribute("type", "button")
btnBorrar.innerHTML = 'Borrar ×';
nuevoGasto.appendChild(btnBorrar);
//Agregar el html
listado.appendChild(nuevoGasto);
});
} | [
"agregar_gasto_lista(nombre_gasto, cantidad_gasto) {\n\t\tconst listado_gastos = document.querySelector(\"#gastos ul\");\n\t\tconst li = document.createElement(\"li\");\n\t\tli.className =\n\t\t\t\"list-grop-item d-flex justify-content-between align-items-center\";\n\t\t// Insertar gasto\n\t\tli.innerHTML = `\n ${nombre_gasto}\n <span class=\"badge badge-primary badge-pill\">$${cantidad_gasto}\n `;\n\n\t\t// Insertar al HTML\n\t\tlistado_gastos.appendChild(li);\n\t}",
"agregarGastoListado(nombre,cantidad){\r\n\r\n /*query señector busca un id o una clase de nombre gastos y despues una etiqueta ul*/\r\n const gastoListado = document.querySelector('#gastos ul');\r\n\r\n /*crear un <li>*/\r\n const li = document.createElement('li');\r\n li.innerHTML=`\r\n ${nombre}\r\n $${cantidad}\r\n `;\r\n\r\n gastoListado.appendChild(li);\r\n\r\n }",
"crearListadoGastos(nombre, gasto){\n const list = document.querySelector('#gastos .list-group');\n const item = document.createElement('li');\n item.classList = 'list-group-item d-flex justify-content-between align-items-center';\n item.innerHTML = `${nombre} <span class='badge badge-primary badge-pill'>${gasto}</span>`\n list.appendChild(item);\n }",
"insertarGastoLista(nombreGasto,cantidad){\n const principal=document.querySelector(\"#gastos ul\");\n const li=document.createElement(\"li\");\n li.innerHTML=`${nombreGasto}\n <span class=\"badge badge-primary badge-pill\">${cantidad}$</span>`;\n //bootstrap\n li.className=\"list-group-item d-flex justify-content-between align-item-center\";\n principal.appendChild(li);\n }",
"function crearLista(){\n listaJugadores.push({nombre: nombreJugador, puntos: letrasAcertadas});\n }",
"mostrarGastos(gastos) {\n\t\t// Eliminar HTML previo.\n\t\tthis.limpiarHTML();\n\n\t\t// Iterar gastos\n\t\tgastos.forEach((gasto) => {\n\t\t\tconst { cantidad, nombre, id } = gasto; //? Destructiring para no poner gasto.cantidad, etc...\n\n\t\t\t// Crear un LI\n\t\t\tconst nuevoGasto = document.createElement('li');\n\t\t\tnuevoGasto.className =\n\t\t\t\t'list-group-item d-flex justify-content-between align-items-center'; //? Cómodo para añadir muchas clases\n\n\t\t\t// Añadir atributo id. Dos formas:\n\t\t\t//! nuevoGasto.setAttribute('data-id',id) // Hacen lo mismo\n\t\t\tnuevoGasto.dataset.id = id;\n\n\t\t\t// Agregar el HTML del gasto.\n\t\t\t//? No recomendable innerHTML por seguridad. Lo hace porque se ahorra muchos createElement() y textContent().\n\t\t\tnuevoGasto.innerHTML = `${nombre} <span class='badge badge-primary badge-pill'> ${cantidad} $ </span>`;\n\n\t\t\t// Botón para borrar el gasto.\n\t\t\tconst btnBorrar = document.createElement('button');\n\t\t\tbtnBorrar.classList.add('btn', 'btn-danger', 'borrar-gasto');\n\t\t\tbtnBorrar.innerHTML = 'Borrar ×'; //? Lleva HTML\n\t\t\t// Para las funciones de borrar gastos\n\t\t\t//? Utilizamos el Id que generamos por fechas. Si hubiiera BBDD vendría de ahí.\n\t\t\tbtnBorrar.onclick = () => {\n\t\t\t\teliminarGasto(id);\n\t\t\t};\n\t\t\tnuevoGasto.appendChild(btnBorrar);\n\n\t\t\t// Agregar al HTML\n\t\t\tgastoListado.appendChild(nuevoGasto);\n\t\t});\n\t}",
"function Dispositivo_Listo() {\n\t\tComienza();\n\t}",
"function aggiungi(oggetto){\r\n // SELEZIONO E CLONO IL TEMPLATE\r\n var cosaManca = $('.template li').clone();\r\n // AGGIUNGO LA LISTA DELLA SPESA AL TEMPLATE\r\n cosaManca.prepend(oggetto);\r\n // AGGIUNGO IL TEMPLATE CON LA LISTA DELLA SPESA ALLA LISTA PRESENTE NEL FILE HTML\r\n $('.todo-list').append(cosaManca);\r\n}",
"colocarNaves(ejercito, capa) {\n for (let index = 0; index < ejercito.listadoNaves.length; index++) {\n const element = ejercito.listadoNaves[index];\n //Le doy un index a cada nave para poder cambiar su imagen por un PUM! cuando es destruída\n ejercito.listadoNaves[index].identificador = capa + index;\n\n this.poscionNaves.push(element);\n let div = document.getElementById(capa);\n\n div.innerHTML +=\n '<li id=\"' +\n capa +\n index +\n '\"><img src=\"img/' +\n element.imagen +\n '\" alt=\"' +\n element.nombre +\n '\"></li>';\n }\n }",
"function actulizarLista(listadoGastos) {\n localStorage.setItem(\"listado_gastos\", JSON.stringify(listadoGastos))\n}",
"function agregarALista(){\r\n listaProductos.push(new pesosProductos (nombreProducto.value, parseInt(pesoProducto.value), parseInt(sku.value)));\r\n }",
"function listarGrupos(id, nome) {\n group_list = document.querySelector(\".group-list\");\n\n let grupo = document.createElement(\"div\");\n grupo.classList.add(\"grupo\");\n\n let img = document.createElement(\"img\");\n img.classList.add(\"imagem\");\n img.src = \"https://cdn.pixabay.com/photo/2016/11/14/17/39/person-1824147_960_720.png\";\n\n let nome_gp = document.createElement(\"div\");\n nome_gp.classList.add(\"nome_gp\");\n nome_gp.textContent = nome;\n\n //pega o id do grupo clicado\n grupo.addEventListener(\"click\", ()=> {\n console.log(id);\n globalIdGrupo = id;\n GETmensagens(globalIdGrupo);\n })\n\n grupo.appendChild(img);\n grupo.appendChild(nome_gp);\n group_list.appendChild(grupo);\n return group_list;\n}",
"function obtenerListadoGastos() {\n let listadoGastos = JSON.parse(localStorage.getItem(\"listado_gastos\"))\n if (listadoGastos == null) {\n listadoGastos = [];\n actulizarLista(listadoGastos)\n }\n return listadoGastos;\n}",
"function displayGroceries() {\n const groceryList = document.getElementById('groceries');\n\n groceries.forEach((r) => {\n const groceryContainer = document.createElement('list');\n groceryContainer.setAttribute('id', 'list')\n\n addGrocery(groceryContainer, r.grocery);\n\n groceryList.insertAdjacentElement('beforeend', groceryContainer);\n });\n\n}",
"add_bingo_list(filename) {\n this.bingoLists.push(filename)\n this.drawSelect()\n }",
"function agregarProducto(agregar) {\n carrito.push(agregar);\n}",
"function agregarProductoLista(p){\r\n this.producto.push(p);\r\n}",
"function displayGroceries() {\n groceries.forEach((item) => {\n let itemList = document.createElement('li');\n itemList.innerText = item;\n\n let list = document.getElementById('groceries');\n list.insertAdjacentElement('beforeEnd',itemList);\n });\n}",
"function inicializar_listados() {\n // listados que los items se cargan al ir scroleando hacia abajo\n init_ver_mas();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A shim for requirejs define calls that calls `exposedModules` on the array of dependencies before delegating to the requirejs function. | function shimmedRequirejsDefine(name, deps, callback) {
var modulesToExpose = _.isArray(name) ? name :
_.isArray(deps) ? deps :
parseDeps(name);
exposeModules(modulesToExpose);
warnOnPrivateModuleRequests(modulesToExpose);
requirejsDefine.apply(null, arguments);
} | [
"function shimmedRequirejsDefine(name, deps, callback) {\n var modulesToExpose = _.isArray(name) ? name :\n _.isArray(deps) ? deps :\n parseDeps(name);\n exposeModules(modulesToExpose);\n warnOnPrivateModuleRequests(modulesToExpose);\n requirejsDefine.apply(null, arguments);\n }",
"function shimmedRequirejsRequire(modules) {\n\t if (_.isArray(modules)) {\n\t exposeModules(modules);\n\t }\n\t warnOnPrivateModuleRequests(modules);\n\t return requirejsRequire.apply(null, arguments);\n\t }",
"function shimmedRequirejsRequire(modules) {\n if (_.isArray(modules)) {\n exposeModules(modules);\n }\n warnOnPrivateModuleRequests(modules);\n return requirejsRequire.apply(null, arguments);\n }",
"function define(name, deps, impl) {\n // only executed if function has dependencies\n for (var i=0; i <deps.length; i++) {\n console.log(\"before\", deps[i]);\n deps[i] = modules[deps[i]];\n console.log(\"after\", deps[i]);\n }\n /*\n calls the function with the dependencies as parameters\n and returns the object with function properties.\n */\n modules[name] = impl.apply( impl, deps);\n }",
"function define(name, deps, impl){\n\t\t\n\t/* a life line of the code Here we are converting or assiging a object to the deps array\n\tfor each of its string values one by one. Means if deps contains string as bar then the actual \n\tobject named bar which is stored in modules array will be replaced here.*/\n\n\t\tfor(var i = 0 ; i < deps.length ; i++){\n\t\t\tdeps[i] = modules[deps[i]];\n\t\t}\n\t/*The apply function actually calls the impl with the arguments in deps array as modified above \n\t which are actually objects */\n\t\tmodules[name] = impl.apply(impl, deps);\t\n\t}",
"function define(depNames, moduleFunction) {\n var myMod = currentMod;\n var deps = depNames.map(getModule);\n\n deps.forEach(function(mod) {\n if (!mod.loaded) {\n mod.onLoad.push(whenDepsLoaded);\n }\n });\n\n function whenDepsLoaded() {\n if (!deps.every(function(m) {\n return m.loaded;\n }))\n return;\n\n var args = deps.map(function(m) {\n return m.exports;\n });\n var exports = moduleFunction.apply(null, args);\n if (myMod) {\n myMod.exports = exports;\n myMod.loaded = true;\n myMod.onLoad.forEach(function(f) {\n f();\n });\n }\n }\n whenDepsLoaded();\n}",
"function define(name, deps, factory) {\n var id = getCurrentScript(),\n mod = Cache.get(id);\n if (!factory) {\n //define([deps], fn)\n if (deps) {\n // Object.assign(_path,{[name]:id});\n if (_isFunction(deps)) {\n factory = deps;\n } else {\n var tmp = deps;\n factory = function(){\n return tmp;\n }\n }\n deps = name;\n } else {\n //define(fn)\n if (_isFunction(name)) {\n factory = name;\n } else {\n var tmp = name;\n factory = function(){\n return tmp;\n }\n }\n deps = [];\n }\n }\n if (!Array.isArray(deps)) {\n deps = [deps];\n }\n mod.deps = deps;\n mod.factory = factory;\n if (deps.length) {\n Promise.all(deps.map((dep)=>{\n return new Promise((resolve, reject)=>{\n dep = _normalize(id, dep);\n var depModule = Cache.get(dep) || new Module(dep);\n depModule.on('completed', ()=>{\n resolve(depModule.getExports());\n });\n depModule.on('error', reject);\n })\n })).then(()=>{\n mod.setStatus('completed');\n }).catch((err)=>{\n mod.setStatus('error', err);\n })\n }else {\n mod.setStatus('completed');\n }\n\n }",
"function amdDefine(sModuleName, aDependencies, vFactory) {\n\t\tlet oArgs = arguments;\n\t\tconst bExportIsSet = typeof oArgs[oArgs.length - 1] === \"boolean\";\n\n\t\t// bExport parameter is proprietary and should not be used for an AMD compliant define()\n\t\tif (bExportIsSet) {\n\t\t\toArgs = Array.prototype.slice.call(oArgs, 0, oArgs.length - 1);\n\t\t}\n\n\t\tui5Define.apply(this, oArgs);\n\t}",
"function define(name, depends, callback) {\n\n if (typeof depends === \"function\") {\n\n callback = depends;\n depends = [];\n\n }\n\n modules[name] = {\n name: name,\n depends: depends,\n callback: callback\n };\n\n addModule(name, depends).then(function (mods) {\n callback.apply(undefined, mods);\n });\n\n }",
"function ModuleWrapper() {}",
"function setupModuleLoader(window) {\n var ensure = function(obj, name, factory) {\n return obj[name] || (obj[name] = factory());\n };\n\n // make sure the angular should be global singleton\n var angular = ensure(window, \"angular\", Object);\n\n // will not check whether the module with name is already existed or not, just override\n var createModule = function(name, requires, modules, configFn) {\n // check module name validity\n if(name === \"hasOwnProperty\") {\n throw \"hasOwnProperty is not a valid module name\";\n }\n\n // choose the method to operate on the invoke queue\n var invokeLater = function(service, method, arrayMethod) {\n // this returned function will be invoked when registering constant or provider\n return function() {\n var item = [service, method, arguments];\n moduleInstance._invokeQueue[arrayMethod || \"push\"](item);\n // to support chaining\n return moduleInstance;\n };\n };\n\n // exposed api for module instance\n var moduleInstance = {\n name: name,\n requires: requires,\n constant: invokeLater(\"$provide\", \"constant\", \"unshift\"),\n provider: invokeLater(\"$provide\", \"provider\"),\n factory: invokeLater(\"$provide\", \"factory\"),\n value: invokeLater(\"$provide\", \"value\"),\n service: invokeLater(\"$provide\", \"service\"),\n // the config function is invoked by the providerInjector\n config: invokeLater(\"$injector\", \"invoke\"),\n directive: invokeLater(\"$compileProvider\", \"directive\"),\n run: function(fn) {\n moduleInstance._runBlocks.push(fn);\n return moduleInstance;\n },\n // this array will be processed when calling createInjector([module_name])\n // the elements in this array are like:\n // [\n // [\"$provide\", \"factory\", actual_arguments],\n // [\"$injector\", \"invoke\", actual_arguments],\n // ...\n // ]\n _invokeQueue: [],\n _runBlocks: []\n };\n\n if(configFn) {\n moduleInstance.config(configFn);\n }\n\n // store the module instance\n modules[name] = moduleInstance;\n\n // return the module instance to enable chained declaration\n return moduleInstance;\n };\n\n var getModule = function(name, modules) {\n if(modules.hasOwnProperty(name)) {\n return modules[name];\n } else {\n throw \"Module \" + name + \" is not available\";\n }\n };\n\n // angular.module is a function\n ensure(angular, \"module\", function() {\n // holding all the modules\n var modules = {};\n // receives two parameters\n // 1. module's name\n // 2. module's dependencies\n return function(name, requires, configFn) {\n if(requires) {\n return createModule(name, requires, modules, configFn);\n } else {\n return getModule(name, modules);\n }\n };\n });\n}",
"function requireModule(app, name) {\n\t var methods = nativeModules[name];\n\t var target = {};\n\t\n\t var _loop2 = function _loop2(methodName) {\n\t target[methodName] = function () {\n\t for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n\t args[_key] = arguments[_key];\n\t }\n\t\n\t return app.callTasks({\n\t module: name,\n\t method: methodName,\n\t args: args\n\t });\n\t };\n\t };\n\t\n\t for (var methodName in methods) {\n\t _loop2(methodName);\n\t }\n\t return target;\n\t}",
"function wrapRequire() {\n const originalRequire = Module.prototype.require;\n Module.prototype.require = function (moduleName) {\n // Inject workspace node_modules directory\n this.paths.unshift(workspaceModulesDir);\n\n const moduleInfo = getModuleInfo(moduleName);\n\n try {\n return originalRequire.apply(this, [moduleName]);\n } catch (err) {\n if (!moduleInfo.isThirdPartyModule) throw err;\n\n installModule(moduleInfo.path);\n return originalRequire.apply(this, [\n path.join(workspacePath, 'node_modules', moduleName),\n ]);\n }\n };\n}",
"function requireModule (app, name) {\n var methods = nativeModules[name];\n var target = {};\n var loop = function ( methodName ) {\n Object.defineProperty(target, methodName, {\n configurable: true,\n enumerable: true,\n get: function moduleGetter () {\n return function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return app.callTasks({\n module: name,\n method: methodName,\n args: args\n });\n }\n },\n set: function moduleSetter (value) {\n if (typeof value === 'function') {\n return app.callTasks({\n module: name,\n method: methodName,\n args: [value]\n })\n }\n }\n });\n };\n\n for (var methodName in methods) loop( methodName );\n return target\n}",
"function requireModule$1 (app, name) {\n var methods = nativeModules[name];\n var target = {};\n var loop = function ( methodName ) {\n Object.defineProperty(target, methodName, {\n configurable: true,\n enumerable: true,\n get: function moduleGetter () {\n return function () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return app.callTasks({\n module: name,\n method: methodName,\n args: args\n });\n }\n },\n set: function moduleSetter (value) {\n if (typeof value === 'function') {\n return app.callTasks({\n module: name,\n method: methodName,\n args: [value]\n })\n }\n }\n });\n };\n\n for (var methodName in methods) loop( methodName );\n return target\n}",
"function require(depends, callback) {\n\n if (!Array.isArray(depends)) {\n depends = [depends];\n }\n\n Promise.all(depends.map(resolveDependency)).then(function (mods) {\n callback.apply(undefined, mods);\n });\n\n }",
"function define(moduleName, deps, payload) {\n if (typeof moduleName != \"string\") {\n console.error(this.depth + \" Error: Module name is not a string.\");\n console.trace();\n return;\n }\n\n if (arguments.length == 2) {\n payload = deps;\n }\n else {\n payload.deps = deps;\n }\n\n if (define.debugDependencies) {\n console.log(\"define: \" + moduleName + \" -> \" + payload.toString()\n .slice(0, 40).replace(/\\n/, '\\\\n').replace(/\\r/, '\\\\r') + \"...\");\n }\n\n if (moduleName in define.modules) {\n console.error(this.depth + \" Error: Redefining module: \" + moduleName);\n }\n define.modules[moduleName] = payload;\n}",
"function requireProxy( dependencies, successCallback, errorCallback ) {\n\n // Make sure the callbacks are defined - this makes\n // the logic easier down below.\n successCallback = ( successCallback || angular.noop );\n errorCallback = ( errorCallback || angular.noop );\n\n // NOTE: This \"require\" reference is the core,\n // global reference to RequireJS.\n require(\n ( dependencies || [] ),\n function successCallbackProxy() {\n var args = arguments;\n $rootScope.$apply(\n function() {\n successCallback.apply( this, args );\n }\n );\n },\n function errorCallbackProxy() {\n var args = arguments;\n $rootScope.$apply(\n function() {\n errorCallback.apply( this, args );\n }\n );\n }\n );\n }",
"_loadModules (moduleNames) {\n return new Ember.RSVP.Promise(resolve => {\n esriLoader.dojoRequire(moduleNames, (...modules) => {\n resolve(modules);\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add prices of all checked activities and display in DOM | function updateActivitiesPrice(activityItems) {
activitiesTotalPrice = 0;
for (let i=0; i<activityItems.length; i++) {
if (activityItems[i].children[0].checked) {
const activityCost = parseInt(activityItems[i].children[0].getAttribute('data-cost'));
activitiesTotalPrice += activityCost;
};
}
const activityCostText = document.getElementById('activities-cost');
activityCostText.textContent = `Total: $${activitiesTotalPrice}`;
} | [
"function getActivities() {\n var activities = document.querySelectorAll('.activities input');\n\n // Add event listener to every activity option\n for (var i = 0; i < activities.length; i++) {\n activities[i].addEventListener('click', activitiesEvent);\n }\n\n function activitiesEvent() {\n var price = getPrice(this.parentNode.innerText);\n if (this.checked === true) {\n // When the activity box is checked\n updateTotalPrice(price);\n updateActivities(this, true);\n } else {\n // When the activity box is unchecked\n updateTotalPrice(-price);\n updateActivities(this, false);\n } \n }\n\n function updateActivities(e, disable) {\n var activities = document.querySelectorAll('.activities input');\n var thisTime = getTime(e.parentNode.innerText);\n var activityTime;\n\n for (var i = 0; i < activities.length; i++) {\n activityTime = getTime(activities[i].parentNode.innerText);\n if (activityTime && activities[i].name !== e.name && thisTime === activityTime) {\n if (disable) {\n activities[i].disabled = true;\n activities[i].parentNode.style.color = '#999';\n } else {\n activities[i].disabled = false;\n activities[i].parentNode.style.color = '#000';\n }\n }\n }\n }\n\n function updateTotalPrice(price) {\n var h3 = document.getElementById('total');\n \n if(h3.innerText !== '') {\n var currentAmount = getPrice(h3.innerText);\n if (currentAmount + price > 0) {\n h3.innerText = 'Total: $' + (currentAmount + price);\n } else {\n h3.innerText = '';\n }\n } else {\n h3.innerText = 'Total: $' + price;\n }\n }\n\n function getPrice(str) {\n var regex = /\\d{3}/;\n var price = parseInt(str.match(regex));\n return price;\n }\n\n function getTime(str) {\n var regex = /(\\d{1,2}(p|a)m-\\d{1,2}(p|a)m)/;\n var time = str.match(regex);\n if (time) {\n return time[0];\n }\n }\n\n // Creat h3 for total price\n createTotalPrice();\n}",
"function updatePrice() {\n let $selectedActivities = $activities.find('input:checked');\n let price = 0;\n // check all chosen activities and consider the price\n $selectedActivities.each( (i, item) => {\n let $element = $(item);\n price += parseInt($element.attr('data-price'));\n });\n if(price > 0) {\n $totalPrice.show().find('span').text(price);\n } else {\n $totalPrice.hide();\n }\n }",
"function priceCalc() {\n\n\t\t// Reset total\n\t\tvar total = 0;\n\n\t\t// Hide previous calculation\n\t\t$(\".price\").detach();\n\n\t\t// For each checked activity add together price properties\n\t\t$(\".activities input:checked\").each(function() {\n\n\t\t\ttotal += this.parentNode.price;\n\n\t\t});\n\n\t\t// Show new price\n\t\t$(\".activities\").append(\"<p class='price'>Total: $\" + total + \"</p>\");\n\n\t\t// Hide price of 0\n\t\tif(total === 0) {\n\t\t\t$(\".price\").hide();\n\t\t}\n\t}",
"function sumValues() {\n let total = 0;\n $('.activities input:checkbox:checked').each(function() {\n const cost = parseActivity($(this)).cost;\n total += cost;\n });\n $('.activities .js-total-value strong').text(total);\n}",
"function calculateActivities() {\n let finalCost = 0;\n if (actCheckbox[0].checked) {\n finalCost = 200;\n }\n for (let i = 1; i < actCheckbox.length; i++) {\n if (actCheckbox[i].checked) {\n finalCost += 100;\n }\n }\n total.textContent = finalCost;\n}",
"function totalCost() {\n total = 0;\n $(\".activities label input\").each(function(index, value) {\n //console.log($(this).attr('name'));\n if ($(this).prop('checked') && $(this).attr('name') === 'all') {\n total += 200;\n } else if ($(this).prop('checked')) {\n total += 100;\n }\n });\n $('#total').html(\"Total cost: \" + total);\n }",
"function updateActivityCost(activity) {\n $('.activities').append('<span id=\"total-cost\"></span>')\n if (activity.attr('name') != 'all') {\n if (activity.is(':checked')) {\n totalCost += 100;\n } else {\n totalCost -= 100;\n }\n } else if (activity.attr('name') === 'all') {\n if (activity.is(':checked')) {\n totalCost += 200;\n } else {\n totalCost -= 200;\n }\n }\n return totalCost\n}",
"function activities_Cost_Time() {\n\n/*===========================\nThe code below has been adapted \nfrom:https://stackoverflow.com/questions/14544104/checkbox-check-event-listener\n===========================*/\n\n const activities_Checkboxes = document.querySelectorAll(\"input[type=checkbox]\");\n let enabled_Checkboxes = []\n\n// Use Array.forEach to add an event listener to each checkbox.\nactivities_Checkboxes.forEach(function checkbox(checkbox) {\n checkbox.addEventListener('change', function() {\n enabled_Checkboxes = \n Array.from(activities_Checkboxes) // Convert activities_Checkboxes to an array to use filter and map.\n .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.\n .map(i => i.dataset.cost) // Use Array.map to extract only the checkbox data-cost values from the array of objects.\n \n function total_Cost_Of_Activities() {\n const numberArray = enabled_Checkboxes.map(Number) /* Code adapted from: \n https://stackoverflow.com/questions/10541770/convert-string-array-to-integer-array */\n\n const total_Cost = numberArray.reduce(function(a, b) { return a + b; }, 0); /* Code adapted from: \n https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers */\n \n document.getElementById('activities-cost').textContent = `Total: $${total_Cost}`\n }\n\n total_Cost_Of_Activities();\n \n })\n});\n}",
"function checkboxPriceAdders() {\n for (let i = 0; i < shopList.length; i++) {\n shopList[i].addEventListener('change', (e) => {\n let dollarValue = shopList[i].getAttribute('data-cost')\n if (e.target.checked) {\n totalInt += +dollarValue;\n total.textContent = totalInt;\n } else {\n totalInt -= +dollarValue;\n total.textContent = totalInt;\n };\n });\n };\n}",
"function assignPriceValue(tag){\n for (item of tag) {\n if (item.checked) {\n request.price_level = parseFloat(item.value); //assign the checked value\n }\n }\n}",
"function EnableActivityCostCalculation() {\n const $activityFieldset = $(\".activities\");\n const $activityCheckboxes = $('.activities input[type=\"checkbox\"]');\n\n // Total cost\n const $totalCostControl = $(`\n <div class=\"totalCost\">\n <span class=\"totalCost__label\">Total:</span>\n <span class=\"totalCost__cost\">$0</span>\n </div>\n `);\n $activityFieldset.append($totalCostControl);\n\n function TotalCost() {\n let result = 0;\n\n for (let i = 0; i < $activityCheckboxes.length; i++ ) {\n let $checkbox = $($activityCheckboxes[i]);\n let checkboxIsChecked = $checkbox.prop(\"checked\");\n let cost = parseInt($checkbox.data(\"cost\"), 10);\n \n if ( checkboxIsChecked ) {\n result += cost;\n }\n }\n\n return result;\n }\n\n function UpdateTotalCost() {\n $totalCostControl.find(\".totalCost__cost\").text(\"$\" + TotalCost().toString());\n }\n\n $activityFieldset.on(\"click\", UpdateTotalCost);\n UpdateTotalCost();\n }",
"function processCost () {\n if (!$(\"p.totalCost\").length) {\n costHTML= \"<p class='totalCost'><strong>Total:</strong> $<span></span></p>\"\n $activitiesSection.append(costHTML);\n }\n\n totalCost += ($(e.target).prop(\"checked\") === true) ?\n (parseInt(getCost($activityText))) :\n (parseInt(getCost($activityText)) * -1);\n\n if (totalCost === 0) {\n $(\"p.totalCost\").remove();\n } else {\n $(\"p.totalCost span\").text(totalCost);\n }\n }",
"function renderPrice() {\n\tconst stateArray = Object.entries(state);\n\tconst priceEle = document.querySelector(\".price-details\");\n\tlet totalPrice = wholeWheatBun;\n\tstateArray\n\t\t.filter((ele) => ele[1] === true)\n\t\t.forEach((item) => {\n\t\t\ttotalPrice += ingredients[item[0]];\n\t\t});\n\t// console.log(totalPrice);\n\tpriceEle.innerHTML = `INR ${totalPrice}`;\n}",
"function calculateTotal() {\r\n let total = 0; //total is set to 0\r\n let collectionTotal = 0; //collection total set to 0\r\n let eventChecked = false; //event not checked\r\n const items = form.querySelectorAll(\"div.item\"); //get array of events\r\n const itemsCount = items.length; //get length of the array\r\n\r\n\r\n //loops through the events array\r\n for (let t_i = 0; t_i < itemsCount; t_i++) {\r\n const item = items[t_i];\r\n const checkbox = item.querySelector(\"input[data-price][type=checkbox]\");\r\n\r\n if (checkbox.checked) {\r\n total = total + parseFloat(checkbox.dataset.price);\r\n eventChecked = true;\r\n }////changing the text to float so the total can be calculated\r\n }//end of for\r\n\r\n const radio = form.querySelector(\"input[data-price][type=radio]\");\r\n if (radio.checked) {\r\n collectionTotal = collectionTotal + parseFloat(radio.dataset.price);\r\n\r\n }//changing the text to float so the total can be calculated\r\n\r\n if (eventChecked === true) {\r\n selectEvent = true;\r\n } else {\r\n selectEvent = false;\r\n bookNow.disabled = true;\r\n } //if event is selected the submit button is enabled(if other elements are checked too)\r\n\r\n\r\n collectionTotal.toFixed(2);\r\n total.toFixed(2);\r\n total = collectionTotal + total;\r\n form.total.value = \"£\" + total;\r\n }",
"function updateRunningTotal() {\n runningTotal.textContent = ''\n let newRunningTotalValue = 0\n for (let i = 0; i < checkBoxArray.length; i+=1) {\n if (checkBoxArray[i].checked == true) {\n newRunningTotalValue += parseInt(checkBoxArray[i].dataset.cost);\n }\n }\n if (document.querySelector(\".activities\").children[1].firstElementChild.checked == true){ //add in the main conference cost if its checked, because its not part of the check box array\n newRunningTotalValue += parseInt(document.querySelector(\".activities\").children[1].firstElementChild.dataset.cost)\n }\n if(newRunningTotalValue == 0){\n runningTotal.innerHTML = ''\n runningTotal.style.display = \"none\"\n } else {\n runningTotal.textContent = `Total cost is $${newRunningTotalValue}`\n runningTotal.style.display = \"\"\n }\n}",
"function getTopping(runningTotal, text1) {\n var toppingTotal=0;\n var selectedTopping=[];\n var toppingArray=document.getElementsByClassName(\"toppings\");\n for (var j=0; j< toppingArray.length; j++) {\n if (toppingArray[j].checked) {\n selectedTopping.push(toppingArray[j].value)\n console.log(\"selected topping item: (\"+toppingArray[j].value+\")\");\n text1= text1+toppingArray[j].value+\"<br>\";\n }\n }\n var toppingCount=selectedTopping.length;\n if (toppingCount >1) {\n toppingTotal= (toppingCount-1);\n } else {\n toppingTotal=0;\n }\n runningTotal=(runningTotal + toppingTotal);\n console.log(\"total selected topping items: \"+ toppingCount);\n console.log(toppingCount+\" topping - 1 free topping = \" + \"$\" + toppingTotal+\".00\");\n console.log(\"topping text1: \"+text1);\n console.log(\"Purchase total: \"+\"$\"+runningTotal+\".00\");\n document.getElementById(\"showText\").innerHTML=text1;\n document.getElementById(\"totalPrice\").innerHTML=\"<h3> Total: <strong>$\"+ runningTotal+\".00\"+\"</strong></h3>\";\n}",
"function activities (x) {\n x.addEventListener('change', () => {\n if (x.checked) {\n subTotal = subTotal + 100;\n totalCost.textContent = insertCost + subTotal;\n numOfActivities++;\n } else {\n subTotal = subTotal - 100;\n totalCost.textContent = insertCost + subTotal;\n numOfActivities++;\n }\n// hide all conferences that overlap on time.\n if (jsFrameworks.checked) {\n express.disabled = true;\n } else {\n express.disabled = false;\n }\n if (jsLibs.checked) {\n node.disabled = true;\n } else {\n node.disabled = false;\n } if (express.checked) {\n jsFrameworks.disabled = true;\n } else {\n jsFrameworks.disabled = false;\n } if (node.checked) {\n jsLibs.disabled = true;\n } else {\n jsLibs.disabled = false;\n } if (express.checked) {\n jsFrameworks.disabled = true;\n } else {\n jsFrameworks.disabled = false;\n }\n \n })\n}",
"displayPrice() {\n this.updatePrice();\n var tmp_show_price = false;\n for (let option_item of this.check_option_list) {\n if (option_item) {\n tmp_show_price = true;\n break;\n }\n }\n this.show_price = tmp_show_price;\n }",
"function selectedItems(){\r\n\r\n\tvar ele = document.getElementsByName(\"product\");\r\n\tvar chosenProducts = [];\r\n\r\n\tvar c = document.getElementById('displayCart');\r\n\tc.innerHTML = \"\";\r\n\r\n\t// build list of selected item\r\n\tvar para = document.createElement(\"P\");\r\n\r\n\tpara.appendChild(document.createElement(\"br\"));\r\n\tfor (i = 0; i < ele.length; i++) {\r\n\t\tif (ele[i].checked) {\r\n\t\t\tpara.appendChild(document.createTextNode(ele[i].value));\r\n\t\t\tpara.appendChild(document.createElement(\"br\"));\r\n\t\t\tchosenProducts.push(ele[i].value);\r\n\t\t}\r\n\t}\r\n\r\n\t// add paragraph and total price\r\n\tc.appendChild(para);\r\n\tc.appendChild(document.createTextNode(\"Total Price is $\" + getTotalPrice(chosenProducts)));\r\n\topenInfo(event, 'Cart');\r\n\ttabColour(2);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by LUFileParsernewRegexDefinition. | exitNewRegexDefinition(ctx) {
} | [
"exitParse(ctx) {\n\t}",
"exitCompilationUnit(ctx) {\n\t}",
"exitSyntaxBracketLa(ctx) {\n\t}",
"exitSyntaxBracketLr(ctx) {\n\t}",
"exitRegexpPredicate(ctx) {\n\t}",
"exitSyntaxBracketRr(ctx) {\n\t}",
"exitSyntaxBracketRa(ctx) {\n\t}",
"visitNewRegexDefinition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitRulePart(ctx) {\n\t}",
"enterNewRegexDefinition(ctx) {\n\t}",
"exitRuleDeclaration(ctx) {\n\t}",
"exitNestedExpressionAtom(ctx) {\n\t}",
"exitSyntaxBracketLc(ctx) {\n\t}",
"exitSingleValuedPatternSubmodel(ctx) {\n\t}",
"exitMultiValuedPatternSubmodel(ctx) {\n\t}",
"exitRegexEntityIdentifier(ctx) {\n\t}",
"exitNewCompositeDefinition(ctx) {\n\t}",
"exitUnaryExpressionAtom(ctx) {\n\t}",
"exitSyntaxBracketLs(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove User Security Role | function removeUserSecurityRole(index) {
vm.UserSecurityRoles.splice(index, 1);
} | [
"function removeRole() {\n db.Role.getRoles(roles => {\n promptSelectRole(roles).then(function (roleid) {\n db.Role.removeRole(roleid, role => {\n mainMenu();\n });\n });\n })\n}",
"unregisterRole(role) { delete this.roles[role.key]; }",
"function removeRole(){\n localStorage.removeItem(\"role\");\n}",
"remove () {\n this.guild.remove('role', this.data.id)\n }",
"removeRole() {\n // collect role info\n inquirer.prompt([\n questions.functions.roleId\n ])\n // send results to delete role function\n .then((results) => {\n dbFunctions.deleteRole(results)\n console.log(`\\n Successfully deleted role! \\n`)\n startManagement()\n })\n }",
"function removeRole(oldRole) {\n \n console.log(\"Removing role!\\n\");\n // query to delete\n connection.query(\n \"DELETE FROM role WHERE ?\",\n {\n title: oldRole\n },\n function(err, res) {\n if (err) throw err;\n console.log(\"Role removed!\\n\");\n start();\n \n }\n );\n}",
"removeRole(role, options) {\r\n if (role instanceof Role) {\r\n role = role.name;\r\n }\r\n return this.client.userRevokeRole({ name: this.name, role }, options).then(() => this);\r\n }",
"function removeRole(role) {\n const returnValue = delete room.getConfig().roles[role];\n\n room.getPlayerList().forEach((p) => {\n removePlayerRole(p.id, role);\n });\n\n room.getPlugin(`sav/players`).getUserAuths()\n .forEach((auth) => removePlayerRole(auth, role));\n\n return returnValue;\n}",
"function deleteRole() {\n\n}",
"function removeRoleHandler() {\n alert(\"Remove Selected Role - This feature is not yet implemented\");\n }",
"function _removeRoleFromConfig(role, asyncCallback){\n // check if role even exists\n var currentRoles = system.systemVariable.getConfig('rolesPermissionGrant');\n if(!currentRoles.hasOwnProperty(role)){return asyncCallback(null);}\n delete currentRoles[role];\n system.systemVariable.updateConfig({rolesPermissionGrant: currentRoles}, function(err){\n asyncCallback(err);\n });\n }",
"function removeRole() {\n connection.query(\"SELECT id as ID, title AS Title FROM roles\", (err, res) => {\n if (err) throw err;\n console.table(res);\n\n // prompts user to select the role to remove from the database while being displayed a table as a reference guide\n inquirer.prompt({\n type: \"list\",\n name: \"deleterole\",\n message: \"Select a role you would like to remove:\",\n choices: function() {\n let delRoleArray = [];\n for (let i = 0; i < res.length; i++) {\n delRoleArray.push(res[i].Title);\n };\n return delRoleArray;\n },\n }).then(function(data) {\n\n // deletes the role from the database\n connection.query(\n \"DELETE FROM roles WHERE ?\", {\n title: data.deleterole\n },\n console.log(chalk.yellow(`Removed the role ${data.deleterole} from the database`)),\n function(err, res) {\n if (err) throw err;\n return res;\n });\n begin();\n });\n });\n}",
"static removeUser() {\n this.removeLocalVal('userName');\n this.setAccessLevel(0);\n this.removeLocalVal('aliases');\n this.removeLocalVal('selectedAlias');\n }",
"removeRole(roleId) {\n return this.connection.query(\"DELETE FROM role WHERE id = ?\", roleId);\n }",
"removeRole(roleID){\n return this.connection.query(\n \"DELETE FROM role WHERE id = ?\",\n roleID\n );\n }",
"function removeExistingRoles(callback) {\n /*\n * We remove the role from the user and check if any other\n * user is also on that role, if not we remove the role itself\n */\n var role = msg.member.roles.find(r => r.name.startsWith(\"#\"));\n //If we don't find more roles to remove, finish the function\n if (!role) {\n return callback();\n }\n\n msg.member.removeRole(role).then(() => {\n //If role is empty, remove it\n if (role.members.array().length < 1) {\n role.delete().then(() => {\n return removeExistingRoles(callback);\n }).catch(err => discordUtils.sendAndDelete(msg.channel, ':warning: | Bot error! ' + err.response.body.message));\n } else {\n return removeExistingRoles(callback);\n }\n });\n }",
"_removeUserRole(userId, role) {\n return __awaiter(this, void 0, void 0, function* () {\n const options = new Options();\n options.secure = Secure.true;\n options.url = UrlUtil.join(this.apiRoot, this.baseEndpoint, userId, 'remove-role');\n options.parameters.add('role', role);\n return this._putWithOptions(options).catch((err) => __awaiter(this, void 0, void 0, function* () {\n return yield this.handlePromiseError('UserDataService', 'removeUserRole', err);\n }));\n });\n }",
"function removeRoleIE(data, roleName)\n{\n let role = data.guild.roles.cache.find((role) => role.name == roleName);\n if (role)\n {\n return role.delete();\n }\n \n return false;\n}",
"function userRoleDelete(userRole) {\r\n var url = getBaseURL() + \"UserRoles/\" + userRole.UserID + \"/\" + userRole.RoleID;\r\n return $http.delete(url);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if castling is possible with rook at given position TODO needs to check if King is currently in check | function canCastle(castlingKingTile, castlingRookTile) {
var canCastle = true;
if (castlingRookTile !== null && castlingRookTile.piece.type == 'Rook' && !castlingRookTile.piece.hasMoved && !castlingKingTile.piece.hasMoved) {
var possibleEnemyActions = [];
if (castlingKingTile.piece.isInCheck) { //if (inCheck(castlingKingTile, possibleEnemyActions))
return false;
}
var startCol, endCol;
if (castlingRookTile.column == 0) {
startCol = 1; //inclusive
endCol = 4; //exclusive
}
else {
startCol = 5; //inclusive
endCol = 7; //exclusive
}
// check that there are no pieces between the king and the rook
for (let i = startCol; i < endCol; i++) {
if (board.getPiece(castlingKingTile.row, i) !== null)
return false;
}
// find the actions every enemy piece on the board can take from their current positions to determine if castling is possible
for (let currentRow = 0; currentRow < 8; currentRow++) {
for (let currentColumn = 0; currentColumn < 8; currentColumn++) {
let currentTile = board.getTile(currentRow, currentColumn);
if (currentTile !== null && currentTile.piece.isWhite !== castlingKingTile.piece.isWhite) {
if (currentTile.piece.type !== 'Pawn') {
possibleEnemyActions = possibleEnemyActions.concat(currentTile.piece.getStandardMoves(board, false, currentTile.row, currentTile.column));
}
else {
if (Math.abs(currentTile.row - castlingKingTile.row) == 1) { // piece needs to be 1 row away from the king
let columnDifference = currentTile.column - castlingKingTile.column;
// left-hand or right-hand rook
if (startCol == 1) { // lefthand
if (columnDifference > -4 && columnDifference <= 1) {
// console.log("can't castle left");
canCastle = false;
break;
}
}
else {
if (columnDifference >= -1) {
// console.log("can't castle right");
canCastle = false;
break;
}
}
}
}
}
}
}
if (canCastle) {
for (let i = 0; i < possibleEnemyActions.length; i++) {
var currentMove = possibleEnemyActions[i];
if (currentMove.row === castlingKingTile.row && currentMove.column >= startCol && currentMove.column < endCol) {
console.log("in castle check");
canCastle = false;
break;
}
}
}
}
else
canCastle = false;
// Need to update the data of last tile as the current way of checking pieces changes the lastSelectedPiece and associated data
// DEBUG
var sRookToCastleWith = (castlingRookTile.column == 0) ? 'left rook' : 'right rook';
console.log('canCastle with ' + sRookToCastleWith + ': ' + canCastle);
return canCastle;
} | [
"function p4_check_castling(board, s, colour, dir, side){\n var e;\n var E;\n var m, p;\n var pawn = colour + 2;\n var rook = colour + 4;\n var knight = colour + 6;\n var bishop = colour + 8;\n var queen = colour + P4_QUEEN;\n var king = colour + P4_KING;\n\n /* go through 3 positions, checking for check in each\n */\n for(p = s; p < s + 3; p++){\n //bishops, rooks, queens\n for(m = dir - 1; m < dir + 2; m++){\n e = p;\n do{\n e += m;\n E=board[e];\n } while (! E);\n if (E == queen ||\n (E == rook && m == dir) ||\n (E == bishop && m != dir))\n return 0;\n }\n //knights\n if (board[p + dir - 2] == knight ||\n board[p + dir + 2] == knight ||\n board[p + 2 * dir + 1] == knight ||\n board[p + 2 * dir - 1] == knight)\n return 0;\n }\n\n /* a pawn or king in any of 5 positions on row 7.\n *(though some of those involve impossible king-king contact) */\n for(p = s + dir - 1; p < s + dir + 4; p++){\n E = board[p];\n if(E == pawn || E == king)\n return 0;\n }\n /* scan back row for rooks, queens on the other side.\n * Same side check is impossible, because the castling rook is there\n */\n E=0;\n if (side == -1)\n s += 2;\n while (E == 0){ //queen or rook out on other side\n s -= side;\n E=board[s];\n if(E == rook || E == queen)\n return 0;\n }\n return 1;\n}",
"function p4_check_castling(board, s, colour, dir, side){\n var e;\n var E;\n var m, p;\n var knight = colour + P4_KNIGHT;\n var diag_slider = P4_BISHOP | colour;\n var diag_mask = 27;\n var grid_slider = P4_ROOK | colour;\n var king_pawn = 2 | colour;\n var grid_mask = 23;\n\n /* go through 3 positions, checking for check in each\n */\n for(p = s; p < s + 3; p++){\n //bishops, rooks, queens\n e = p;\n do{\n e += dir;\n E=board[e];\n } while (! E);\n if((E & grid_mask) == grid_slider)\n return 0;\n e = p;\n var delta = dir - 1;\n do{\n e += delta;\n E=board[e];\n } while (! E);\n if((E & diag_mask) == diag_slider)\n return 0;\n e = p;\n delta += 2;\n do{\n e += delta;\n E=board[e];\n } while (! E);\n if((E & diag_mask) == diag_slider)\n return 0;\n /*knights on row 7. (row 6 is handled below)*/\n if (board[p + dir - 2] == knight ||\n board[p + dir + 2] == knight)\n return 0;\n }\n\n /* a pawn or king in any of 5 positions on row 7.\n * or a knight on row 6. */\n for(p = s + dir - 1; p < s + dir + 4; p++){\n E = board[p] & grid_mask;\n if(E == king_pawn || board[p + dir] == knight)\n return 0;\n }\n /* scan back row for rooks, queens on the other side.\n * Same side check is impossible, because the castling rook is there\n */\n e = (side < 0) ? s + 2 : s;\n do {\n e -= side;\n E=board[e];\n } while (! E);\n if((E & grid_mask) == grid_slider)\n return 0;\n\n return 1;\n}",
"checkKingSafety(pos, target) {\n const board = this.board;\n const tarP = board[target].piece;\n const tarC = board[target].color;\n // Get current color\n const kingColor = board[pos].color;\n\n // Get king location\n var kingPos = -1;\n kingPos = board.find((val) => { kingPos++; return val.color == kingColor && val.piece == PieceE.KING }) && kingPos;\n // Try move\n this.replacePiece(pos, target);\n\n // Check rook here\n // If danger is true, then move is not possible.\n var danger = false;\n for (var i = 1;; i++) {\n if (board[kingPos+i] === undefined) break;\n if (board[kingPos+i].piece != PieceE.NONE) {\n if (board[kingPos+i].color != board[kingPos].color) danger=true;\n break;\n }\n }\n for (var i = -1;; i--) {\n if (board[kingPos+i] === undefined) break;\n if (board[kingPos+i].piece != PieceE.NONE) {\n if (board[kingPos+i].color != board[kingPos].color) danger=true;\n break;\n }\n }\n\n // Redo move\n this.replacePiece(target, pos);\n board[target].piece = tarP;\n board[target].color = tarC;\n return !danger;\n }",
"in_check(player){\n var row, col;\n var attacked_positions = [];\n var player_king;\n for (row = 0; row < this.board.length; row++) {\n for (col = 0; col < this.board[0].length; col++) {\n var piece = this.board[row][col];\n if(piece === null){\n // no piece\n continue;\n }\n if(piece.get_color() === player){\n if(piece instanceof King){\n player_king = piece;\n }\n }else{\n attacked_positions = attacked_positions.concat(piece.get_moves(this));\n }\n }\n }\n // If no king nothing to check, so false\n if(player_king === undefined){\n return false;\n }\n var i;\n for(i = 0; i < attacked_positions.length; i++){\n if(attacked_positions[i].isEqual(player_king.get_curr_loc())){\n return true;\n }\n }\n return false;\n }",
"willKingBeThreatened(origin, destination) {\n //keep original board situation for restoration\n let originPiece = this.grid[origin.x][origin.y];\n let originMoved = originPiece.moved;\n let destinationPiece = this.grid[destination.x][destination.y];\n let originAiCaptured = this.aiCaptured.map((x) => x);\n let originPlayerCaptured = this.playerCaptured.map((x) => x);\n //need to remember rook position when castling\n let rookPiece;\n if (originPiece instanceof King && !originPiece.moved && destination.x === 6) {\n rookPiece = this.grid[7][origin.y];\n }\n //determine opposing player's color\n let otherColor;\n if (originPiece.color === 'black') {\n otherColor = 'white';\n } else {\n otherColor = 'black';\n }\n //make the move\n this.move(origin, destination);\n //see if king is now left open after move\n const result = this.isKingThreatened(otherColor);\n //restore board to original configuration\n originPiece.moved = originMoved;\n this.grid[origin.x][origin.y] = originPiece;\n this.grid[destination.x][destination.y] = destinationPiece;\n this.aiCaptured = originAiCaptured;\n this.playerCaptured = originPlayerCaptured;\n //restore rook if move was castling\n if (rookPiece) {\n this.grid[5][origin.y] = null;\n this.grid[7][origin.y] = rookPiece;\n rookPiece.moved = false;\n }\n\n return result;\n }",
"performCastle(side, input) {\n // The row where the king and the rook should be.\n var rankToCheck = (this.moveLog.turn == \"W\" ? \"1\" : \"8\");\n // Stores the tiles that need to be empty in order to rook.\n var spaceNeeded;\n console.log(rankToCheck);\n\n if (side == \"queen\") {\n spaceNeeded = [\"b\" + rankToCheck,\n \"c\" + rankToCheck,\n \"d\" + rankToCheck];\n } else if (side == \"king\") {\n spaceNeeded = [\"f\" + rankToCheck,\n \"g\" + rankToCheck];\n }\n\n // Make sure all the spaces between the rook and the king are empty.\n var allSpacesEmpty = true;\n for (var i = 0; i < spaceNeeded.length; i++) {\n var c = spaceNeeded[i];\n if (Tile.get(c) != \"\") {\n allSpacesEmpty = false;\n }\n }\n\n if (allSpacesEmpty) {\n for (var i = 0; i < this.chessBoard.pieces.length; i++) {\n var c = this.chessBoard.pieces[i];\n if (c.color == this.moveLog.turn) {\n if (!c.isDead()) {\n if (c.timesMoved == 0) {\n if (side == \"queen\") {\n if (c.constructor.name == \"King\") {\n c.changePos(\"c\" + rankToCheck);\n moveSuccessful = true;\n }\n if (c.constructor.name == \"Rook\") {\n if (c.pos == \"a\" + rankToCheck) {\n c.changePos(\"d\" + rankToCheck);\n moveSuccessful = true;\n }\n }\n }\n if (side == \"king\") {\n if (c.constructor.name == \"King\") {\n c.changePos(\"g\" + rankToCheck);\n moveSuccessful = true;\n }\n if (c.constructor.name == \"Rook\") {\n if (c.pos == \"h\" + rankToCheck) {\n c.changePos(\"f\" + rankToCheck);\n moveSuccessful = true;\n }\n }\n }\n }\n }\n }\n }\n } else {\n alert(\"You need to clear the area between the rook and the king.\");\n }\n\n if (moveSuccessful) {\n this.logMoveAndSwitchTurn(input);\n }\n }",
"isCastleAvailable(start,end) {\n // King cannot castle while in check\n if (this.inCheck(this.board,start)) return false;\n let color = this.getSquare(start).color;\n if (start === 'e1' && color === 'w') {\n if (end === 'g1' && this.canCastleKing.w) {\n if (this.isEmptyBetween(1,1,5,7)) {\n // King cannot be attacked in square f1 (modelMove later checks for square g1)\n return ! this.inCheck(this.board,'f1');\n }\n } else if (end === 'c1' && this.canCastleQueen.w) {\n if (this.isEmptyBetween(1,1,5,3)) {\n // King cannot be attacked in square d1 (modelMove later checks for square b1)\n return ! this.inCheck(this.board,'d1');\n }\n }\n } else if (start === 'e8' && color === 'b') {\n if (end === 'g8' && this.canCastleKing.b) {\n if (this.isEmptyBetween(8,8,5,7)) {\n // King cannot be attacked in square f1 (modelMove later checks for square g1)\n return ! this.inCheck(this.board,'f8');\n }\n } else if (end === 'c8' && this.canCastleQueen.b) {\n if (this.isEmptyBetween(8,8,5,3)) {\n // King cannot be attacked in square d1 (modelMove later checks for square b1)\n return ! this.inCheck(this.board,'d8');\n }\n }\n }\n return false;\n }",
"playerInCheck() {\n // get all the opponent's pieces\n const opponentSquares = this.squares.reduce((squares, square) => {\n if(square.piece && square.piece.color !== this.player) return squares.concat(square)\n return squares\n }, [])\n\n // find the king\n const kingSquare = this.squares.find(square => {\n return square.piece instanceof King && square.piece.color === this.player\n })\n\n // check if any of the pieces can move to the king's square\n return opponentSquares.some(square => {\n return this.canMove(square, kingSquare, square.piece.color)\n })\n }",
"function executeCastling(startSquare, targetSquare) {\n if (board[startSquare].charAt(1) == \"k\") //only perform the check if the moved piece is a king\n {\n var diff = targetSquare - startSquare; //check how much did the piece move\n if (diff == directionOffsets[2] * 2) //if the piece was moved 2 squares to the right\n {\n var moveTarget = targetSquare + directionOffsets[3];\n if (board[startSquare] == wKing) { //check which king is it\n board[63] = \"\"; //move the rook at the start to the left of the king\n board[moveTarget] = wRook;\n } else {\n board[7] = \"\";\n board[moveTarget] = bRook;\n }\n } else if (diff == directionOffsets[3] * 2) //if the piece was moved 2 squares to the left\n {\n var moveTarget = targetSquare + directionOffsets[2];\n if (board[startSquare] == wKing) {\n board[56] = \"\"; //move the rook at the start to the right of the king\n board[moveTarget] = wRook;\n } else {\n board[0] = \"\";\n board[moveTarget] = bRook;\n }\n }\n }\n}",
"function isCheckEscapable() {\n for(let r = myKingPos.r-1; r < myKingPos.r+1; r++) {\n for(let c = myKingPos.c-1; c < myKingPos.c+1; c++) {\n if(r == c) { continue; }\n if(isMoveLegal(myKingPos.r, myKingPos.c, r, c)) {\n let isPositionSafe = true;\n for(let i = 0; i < chessPieces.length; i++) {\n if(isMoveLegal(chessPieces[i].pos.r, chessPieces[i].pos.c, r, c)) {\n isPositionSafe = false;\n break;\n }\n }\n if(isPositionSafe) { return true; }\n }\n }\n }\n return false;\n}",
"function isOppChecked(){\n let team = currentPiece.team\n let king = allPieces.find(piece => piece.team === team && piece instanceof King)\n let kingPosition = king.getPosition()\n return getAllMoves(team === playTeam.RED ? playTeam.BLACK : playTeam.RED).indexOf(kingPosition) !== -1\n}",
"moveCheck(moveArray) {\n var skr = moveArray\n var brak_ruchu = false\n for (let f = 0; f < 8; f++) {\n for (let g = 0; g < 8; g++) {\n if (skr[f][g] == 1) {\n brak_ruchu = true\n }\n }\n }\n return brak_ruchu\n\n // if true tu już wiesz co się ma dziać, ja nwm jak to wygląda\n // nie odsyła się nic do klientów\n // zmiana tury\n // checkPlaces dla tego co ma ruch\n // i wtedy odsyłanie\n // pewnie trzeba to całe w paczke zebrać typu funkcja(xyz){i tu cała sekwencja kończaca się moveCheck if true else}\n // i bedzie działać\n }",
"isKingInCheck(kingOwner) {\n let arrPossibleMoves;\n let enemyRow, enemyCol;\n\n for (let r = 0; r <= this.MAX_ROW; r++) {\n for (let c = 0; c <= this.MAX_COL; c++) {\n // For every piece on the chessboard...\n if (this.pieceAt(r, c) !== EMPTY_CELL) {\n // ...owned by the king's enemy...\n if (this.pieceAt(r, c).owner !== kingOwner) {\n // Last parameter is false because is doesn't matter\n // if the enemy will put their king to risk,\n // if they capture the enemy king they win\n arrPossibleMoves = this.getPossibleMovesForPiece(r, c, false);\n // ...check all the cells that piece can be moved to\n for (let i = 0; i < arrPossibleMoves.length; i++) {\n // If the piece can capture another piece...\n if (arrPossibleMoves[i].isEnemy) {\n enemyRow = arrPossibleMoves[i].row;\n enemyCol = arrPossibleMoves[i].col;\n // ...and that piece is the king...\n if (this.pieceAt(enemyRow, enemyCol).type === PieceTypeEnum.King) {\n return true;\n }\n }\n }\n }\n }\n }\n }\n\n return false;\n }",
"function checkAvailable(pos) {\n return board[pos] !== 'X' && board[pos] !== 'O';\n}",
"function validKingMove(state){\n console.log('kingmove',state)\n if ((Math.abs(state.origin[0] - state.dest[0]) < 2) && (Math.abs(state.origin[1] - state.dest[1]) < 2)) {\n if (state.turn === 'w') {\n state.whiteKingPos = state.dest\n } else {\n state.blackKingPos = state.dest\n }\n return true\n } else if(state.dest[0] === 7 && state.dest[1] == 6 && state.whiteKingSideCastle && noHorizontalJump(state)) {\n state.board[7][7]='empty'\n state.board[7][5]='w-r'\n return true\n } else if(state.dest[0] === 7 && state.dest[1] == 2 && state.whiteQueenSideCastle && noHorizontalJump(state)) {\n state.board[7][0]='empty'\n state.board[7][3]='w-r'\n return true\n } else if(state.dest[0] === 0 && state.dest[1] == 6 && state.blackKingSideCastle && noHorizontalJump(state)) {\n state.board[0][7]='empty'\n state.board[0][5]='b-r'\n return true\n } else if(state.dest[0] === 0 && state.dest[1] == 2 && state.blackQueenSideCastle && noHorizontalJump(state)) {\n state.board[0][0]='empty'\n state.board[0][3]='b-r'\n return true\n }\n else {\n return false\n }\n}",
"function rookCanMove(t_row, t_col) {\n let row = currentPieceSel.row;\n let col = currentPieceSel.col;\n if (t_row == row) {\n if (t_col > col) {\n for (let i = col + 1; i < t_col; i++) {\n if ($(\"[row=\" + row + \"][col=\" + i + \"]\").attr(\"player\") != \"\") {\n return false\n }\n }\n return true\n } else if (t_col < col) {\n\n for (let i = col - 1; i > t_col; i--) {\n if ($(\"[row=\" + row + \"][col=\" + i + \"]\").attr(\"player\") != \"\") {\n return false\n }\n }\n return true\n }\n } else if (t_col == col) {\n if (t_row > row) {\n for (let i = row + 1; i < t_row; i++) {\n if ($(\"[row=\" + i + \"][col=\" + col + \"]\").attr(\"player\") != \"\") {\n return false\n }\n }\n return true\n } else if (t_row < row) {\n for (let i = row - 1; i > t_row; i--) {\n if ($(\"[row=\" + i + \"][col=\" + col + \"]\").attr(\"player\") != \"\") {\n return false\n }\n }\n return true\n }\n } else {\n return false\n }\n }",
"function isPositionUnderThreat(board,position,player){\n let rlist = [];\n let state = 0;\n let i = 0;\n \n let enemy = 20; \n if (player == 20) {\n enemy = 10;\n }\n \n while (true) { //see if position is in the range of any peices\n if (i == 0) {\n rlist = pawnmoves(board,position);\n }\n else if (i == 1) {\n rlist = knightmoves(board,position);\n }\n else if (i == 2) {\n rlist = bishopmoves(board,position);\n }\n else if (i == 3) {\n rlist = rookmoves(board,position);\n }\n else if (i == 4){\n rlist = queenmoves(board,position);\n }\n else if (i == 5){\n rlist = kingmoves(board,position);\n }\n else if (i == 6){\n return false;\n }\n for (let j in rlist) {\n if (board[rlist[j]] == enemy + i) {\n return true;\n }\n }\n i += 1;\n }\n}",
"function castleCheck()\n{\n\t// The piece is white, and is able to castle left\n\tif(color == 0 && manager.whiteCastleLeft == 1)\n\t{\n\t\t// checks to see if squares are empty.\n\t\tvar hit : RaycastHit;\n\t\tvar squareCheck = transform.TransformDirection (Vector3(-1,0,0));\n\n\t\tif(Physics.Raycast(transform.position, squareCheck, hit, 3))\n\t\t{\n\t\t\t// Something was hit, no castle is allowed.\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Nothing was hit, castle is allowed.\n\t\t\tlegalMoves.push(square - 3);\n\n\t\t\t// Lets the manager script know that the array does contain the \n\t\t\t// possiblity of a castle.\n\t\t\tmanager.castleDetectorOn();\n\t\t}\n\t}\n\n\t// The piece is white, and is able to castle right\n\tif(color == 0 && manager.whiteCastleRight == 1)\n\t{\n\t\t// checks to see if squares are empty.\n\t\tsquareCheck = transform.TransformDirection (Vector3(1,0,0));\n\n\t\tif(Physics.Raycast(transform.position, squareCheck, hit, 2))\n\t\t{\n\t\t\t// Something was hit, no castle is allowed.\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Nothing was hit, castle is allowed.\n\t\t\tlegalMoves.push(square + 2);\n\n\t\t\t// Lets the manager script know that the array does contain the \n\t\t\t// possiblity of a castle.\n\t\t\tmanager.castleDetectorOn();\n\t\t}\n\t}\n\n\t// The piece is black, and is able to castle left\n\tif(color == 1 && manager.blackCastleLeft == 1)\n\t{\n\t\t// checks to see if squares are empty.\n\t\tsquareCheck = transform.TransformDirection (Vector3(-1,0,0));\n\n\t\tif(Physics.Raycast(transform.position, squareCheck, hit, 3))\n\t\t{\n\t\t\t// Something was hit, no castle is allowed.\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Nothing was hit, castle is allowed.\n\t\t\tlegalMoves.push(square - 3);\n\n\t\t\t// Lets the manager script know that the array does contain the \n\t\t\t// possiblity of a castle.\n\t\t\tmanager.castleDetectorOn();\n\t\t}\n\t}\n\n\t// The piece is black, and is able to castle right\n\tif(color == 1 && manager.blackCastleRight == 1)\n\t{\n\t\t// checks to see if squares are empty.\n\t\tsquareCheck = transform.TransformDirection (Vector3(1,0,0));\n\n\t\tif(Physics.Raycast(transform.position, squareCheck, hit, 2))\n\t\t{\n\t\t\t// Something was hit, no castle is allowed.\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Nothing was hit, castle is allowed.\n\t\t\tlegalMoves.push(square + 2);\n\n\t\t\t// Lets the manager script know that the array does contain the \n\t\t\t// possiblity of a castle.\n\t\t\tmanager.castleDetectorOn();\n\t\t}\n\t}\n\n}",
"checkAvailableMove() {\n for (let i = 0; i < this.boardSize; i++) {\n if ((this.gameState.board[i] === this.gameState.board[i + 1] && (i + 1) % this.size !== 0) ||\n (this.gameState.board[i] === this.gameState.board[i - 1] && i % this.size !== 0) ||\n this.gameState.board[i] === this.gameState.board[i - this.size] ||\n this.gameState.board[i] === this.gameState.board[i + this.size]) {\n return true;\n }\n } return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SEARCH ADDRESS parses the user input for the address search and calls the SearchAddress module to build a search request | function handleSearchAddressRequest(atts) {
var address = atts.address;
var lastSearchResults = atts.lastSearchResults;
lastSearchResults = lastSearchResults ? lastSearchResults.split(' ') : null;
ui.searchAddressChangeToSearchingState(true);
if (lastSearchResults) {
map.clearMarkers(map.SEARCH, lastSearchResults);
}
searchAddress.requestCounter++;
searchAddress.find(address, handleSearchAddressResults, handleSearchAddressFailure, preferences.language);
} | [
"function doAddressSearch() {\n var address = $(\"search_input\").value;\n var radius = $(\"select_radius\").value;\n \n g_searchService.search({\n address: address,\n radius: radius,\n filters: getFilters(),\n maxResults: MAX_RESULTS,\n sortBy: 'distance',\n mapId: MAP_ID,\n }, showAddressSearchResults);\n \n}",
"function addressSearch() {\n const locationIQKey = \"c8f4ef91fa2470\";\n const commonAddressComponents = [\n \"country\",\n \"state\",\n \"county\",\n \"postcode\",\n \"city\",\n \"road\"\n ];\n const minimumCommonComponents = 4;\n let fetchReturnedAddresses = false;\n\n /**\n * LocationIQ element that represents the likelihood the returned address\n * matches its search parameters. Ordered from greatest likelihood to\n * least likelihood\n */\n const matchCodes = [\n \"exact\",\n \"fallback\",\n \"approximate\"\n ];\n\n /**\n * LocationIQ element that represents the granularity of the returned\n * address. Ordered from most granular to least granular.\n */\n const matchLevels = [\n \"venue\",\n \"building\",\n \"street\",\n \"neighbourhood\",\n \"island\",\n \"borough\",\n \"city\",\n \"county\",\n \"state\",\n \"country\",\n \"marine\",\n \"postalcode\"\n ];\n\n /**\n * Update DOM elements to reflect the search for addresses has ended\n */\n function endSearch() {\n MicroModal.show(\"addresses-modal\");\n\n // Remove \"Searching...\" message\n $(\".find-address\").text(\"Find Address\");\n\n $(\".find-address\").prop(\"disabled\", false);\n }\n\n /**\n * Handle the provided error\n */\n function handleError(error) {\n const errorMessage = `An error occurred while finding addresses: ${error.message}`;\n console.log(errorMessage);\n $(\".find-addresses-status\").text(errorMessage);\n MicroModal.show(\"addresses-modal\");\n }\n\n /**\n * Convert the provided address component to a readable format\n */\n function formatAddressComponent(component) {\n let formattedComponent = component.replace(/[-_]/g, \" \");\n\n // Capitalize the first letter of each word\n const componentWords = formattedComponent.toLowerCase().split(\" \");\n formattedComponent = componentWords.map((word) => {\n return word.charAt(0).toUpperCase() + word.substring(1);\n }).join(' ');\n\n return formattedComponent;\n }\n\n /**\n * Convert the provided address components to a string\n */\n function convertAddressToHTML({common, uncommon}) {\n let htmlParts = [];\n\n // Convert common components to HTML\n htmlParts.push(`Country: ${common.country}`);\n if (common.state != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">State: ${common.state}</span>\n `);\n }\n if (common.county != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">County: ${common.county}</span>\n `);\n }\n if (common.postcode != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">\n Postal Code: ${common.postcode}\n </span>\n `);\n }\n if (common.city != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">City: ${common.city}</span>\n `);\n }\n if (common.road != undefined) {\n htmlParts.push(`\n <span class=\"address-component\">Road: ${common.road}</span>\n `);\n }\n\n /**\n * Convert uncommon components to HTML if there aren't enough common\n * components to display\n */\n if (common.length < minimumCommonComponents) {\n for(const component in uncommon) {\n let formattedComponent = formatAddressComponent(component);\n htmlParts.push(`\n <span class=\"address-component\">${formattedComponent}: ${uncommon[component]}</span>\n `);\n }\n }\n\n return htmlParts.join(\"\");\n }\n\n /**\n * Display the provided addresses in the found addresses modal\n */\n function displayAddresses(addressOptions) {\n // Display each of the address options\n if (addressOptions.length > 0) {\n for(const addressOption of addressOptions) {\n const htmlElements = [];\n const radioInput = `\n <input\n type=\"radio\"\n id=\"${addressOption.placeID}\"\n class=\"address-option\"\n name=\"address\"\n value=\"${addressOption.lat},${addressOption.lon}\">\n `;\n htmlElements.push(radioInput);\n\n const customRadioInput = '<span class=\"custom-radio\"></span>';\n htmlElements.push(customRadioInput);\n\n let addressAsText = convertAddressToHTML(addressOption.addressComponents);\n const labelTag = `\n <label for=\"${addressOption.placeID}\" class=\"address-option-label\">\n ${addressAsText}\n </label>\n `;\n htmlElements.push(labelTag);\n\n // Also include a break tag\n htmlElements.push(\"<br>\");\n\n const htmlContent = `\n <div class=\"address-option-div\">\n ${htmlElements.join(\"\\n\")}\n </div>\n `;\n $(\".select-address\").append(htmlContent);\n }\n\n // Set the address options to be required\n $(\".address-option\").first().attr(\"required\", true);\n\n // Create the submit button\n $(\".select-address\").append(`\n <button type=\"submit\" class=\"submit-button address-submit\">\n Submit Selected Address\n </button>\n `);\n } else {\n /**\n * Either the fetch didn't return any addresses, or all of the\n * returned addresses were invalid\n */\n const message = \"No addresses were found\";\n console.log(message);\n $(\".find-addresses-status\").text(message);\n }\n }\n\n /**\n * Find the best address of the provided addresses\n */\n function getBestAddress(addresses) {\n // Keep only the addresses with the best match code\n /**\n * I haven't found any test data with duplicate addresses that have\n * different match codes. Until I find any such data, there's no need\n * to compare match codes\n */\n\n // Keep only the addresses with the most granular match level\n /**\n * I haven't found any test data with duplicate addresses that have\n * different match levels. Until I find any such data, there's no\n * need to compare match levels\n */\n\n /**\n * If there are still multiple addresses left, then they're\n * equal-enough; return the first one\n */\n return addresses[0];\n }\n\n /**\n * Return a new array with the following: From each set of addresses that\n * have identical common address components, remove all addresses except\n * for the best address\n */\n function removeDuplicates(allAddressData) {\n const uniqueAddressData = [];\n for(const addressData of allAddressData) {\n /**\n * Check if an equivalent address option already exists in the\n * filtered array\n */\n const existingDataIndex = uniqueAddressData.findIndex((data) => {\n return _.isEqual(data.addressComponents.common, addressData.addressComponents.common);\n });\n\n // Found a duplicate address\n if (existingDataIndex > -1) {\n const existingData = uniqueAddressData[existingDataIndex];\n console.log(`Address ${addressData.placeID} has an identical match: address ${existingData.placeID}`);\n\n // Keep the better of the two addresses\n const bestAddress = getBestAddress([addressData, existingData]);\n console.log(`----Keeping address ${bestAddress.placeID} and removing address ${existingData.placeID}`);\n uniqueAddressData[existingDataIndex] = bestAddress;\n } else {\n // Not a duplicate address\n uniqueAddressData.push(addressData);\n }\n }\n\n return uniqueAddressData;\n }\n\n /**\n * Return an object containing the uncommon address components of the\n * provided components\n */\n function getUncommonComponents(addressComponents) {\n const returningComponents = {};\n for(const component in addressComponents) {\n if (!commonAddressComponents.includes(component)) {\n returningComponents[component] = addressComponents[component];\n }\n }\n\n return returningComponents;\n }\n\n /**\n * Return an object containing the common address components of the\n * provided components\n */\n function getCommonComponents(addressComponents) {\n const returningComponents = {};\n for(const component in addressComponents) {\n if (commonAddressComponents.includes(component)) {\n returningComponents[component] = addressComponents[component];\n }\n }\n\n return returningComponents;\n }\n\n /**\n * Return true if the provided address refers to an area that is too large\n */\n function addressIsTooLarge(addressJson) {\n // island, borough, city, county, state, country, marine, postalcode\n const unacceptableMatchLevels = matchLevels.slice(-8);\n\n /**\n * The match level is a LocationIQ API property that represents the\n * granularity of the address\n */\n const matchLevel = addressJson.matchquality.matchlevel;\n return unacceptableMatchLevels.includes(matchLevel);\n }\n\n /**\n * Return true if the provided address is unlikely to match the search\n * parameters\n */\n function addressIsUnlikely(addressJson) {\n // approximate\n const unacceptableMatchCodes = matchCodes.slice(-1);\n\n /**\n * The match code is a LocationIQ API property that represents the\n * likelihood the returned address matches its search parameters\n */\n const matchCode = addressJson.matchquality.matchcode;\n return unacceptableMatchCodes.includes(matchCode);\n }\n\n /**\n * Return true if the provided address passes all the tests\n */\n function addressIsValid(addressJson) {\n // Fail the address if it's missing a country\n if (addressJson.address.country == undefined) {\n console.log(`Removing address ${addressJson.place_id}: it is missing its country`);\n return false;\n }\n\n /**\n * Fail the address if its probability of matching the search\n * parameters is too low\n */\n if (addressIsUnlikely(addressJson)) {\n console.log(`Removing address ${addressJson.place_id}: it is unlikely to match the user's search parameters`);\n return false;\n }\n\n if (addressIsTooLarge(addressJson)) {\n console.log(`Removing address ${addressJson.place_id}: it refers to an area that is too large`);\n return false;\n }\n\n return true;\n }\n\n /**\n * Return an array containing the relevant data from each of the provided\n * addresses that are valid\n */\n function getRelevantAddressData(addressesJson) {\n const relevantData = [];\n\n // Iterate through the returned address options\n if (fetchReturnedAddresses) {\n for(const addressJson of addressesJson) {\n if (addressIsValid(addressJson)) {\n const addressOption = {};\n\n // Make a copy of the addressJson's address object\n const addressComponentsCopy = { ...addressJson.address };\n\n // Remove extra address component fields\n if (addressComponentsCopy.country_code != undefined) {\n delete addressComponentsCopy.country_code;\n }\n\n const commonComponents = getCommonComponents(addressComponentsCopy);\n const uncommonComponents = getUncommonComponents(addressComponentsCopy);\n addressOption.addressComponents = {\n common: commonComponents,\n uncommon: uncommonComponents\n };\n\n addressOption.lat = addressJson.lat;\n addressOption.lon = addressJson.lon;\n addressOption.placeID = addressJson.place_id;\n\n relevantData.push(addressOption);\n }\n }\n }\n\n return relevantData;\n }\n\n /**\n * Fetch JSON address data from the provided LocationIQ URL, handle if no\n * addresses are returned, and handle if some other problem occurs with\n * the request\n */\n function fetchCoordinatesJson(url) {\n return fetch(url).then((response) => {\n if (response.ok) {\n fetchReturnedAddresses = true;\n return response.json();\n } else if (response.status === 404) {\n // No addresses were returned\n return response.json();\n } else {\n throw Error(response.statusText);\n }\n });\n }\n\n /**\n * Use the LocationIQ API to convert the provided address into latitude\n * and longitude coordinates, then fetch the wildlife data\n */\n function getLatLonCoordinates(address) {\n const baseURL = \"https://us1.locationiq.com/v1/search.php\";\n const params = {\n key: locationIQKey,\n street: address.street,\n city: address.city,\n county: address.county,\n state: address.state,\n country: address.country,\n postalCode: address.postalCode,\n format: \"json\",\n normalizecity: \"1\",\n addressdetails: \"1\",\n matchquality: \"1\",\n limit: \"50\"\n };\n const queryParams = formatQueryParams(params);\n const url = baseURL + \"?\" + queryParams;\n console.log(`Fetching data from the LocationIQ API: ${url}`);\n\n return fetchCoordinatesJson(url);\n }\n\n /**\n * Reset all variables and DOM elements that are left over from previous\n * address searches\n */\n function resetEnvironment() {\n fetchReturnedAddresses = false;\n\n // Clear previous errors\n $(\".find-addresses-status\").text(\"\");\n\n // Clear previous addresses results\n $(\".select-address\").empty();\n }\n\n /**\n * Create an event listener for when the \"Find Address\" button is clicked\n */\n function handleFindAddressClick() {\n $(\".search-form.address\").submit((event) => {\n event.preventDefault();\n\n console.log(\"Starting address search\");\n\n $(\".find-address\").prop(\"disabled\", true);\n\n resetEnvironment();\n\n // Grab user input\n const userAddress = {};\n userAddress.street = $(\"#search-street\").val();\n userAddress.city = $(\"#search-city\").val();\n userAddress.county = $(\"#search-county\").val();\n userAddress.postalCode = $(\"#search-postal-code\").val();\n\n userAddress.country = $(\"#search-country\").val();\n if (userAddress.country === \"United States of America\") {\n userAddress.state = $(\"#search-state\").val();\n } else {\n /**\n * Ignore the \"US State or Territory\" field if the country\n * isn't the United States of America\n */\n userAddress.state = \"\";\n }\n\n // Tell the user the search is running\n $(\".find-address\").text(\"Searching...\");\n\n getLatLonCoordinates(userAddress)\n .then((addressesJson) => {\n console.log(\"----------Addresses found----------\");\n console.log(addressesJson);\n\n const allAddressData = getRelevantAddressData(addressesJson);\n const uniqueAddressData = removeDuplicates(allAddressData);\n return uniqueAddressData;\n })\n .then(displayAddresses)\n .catch(handleError)\n .finally(endSearch);\n });\n }\n\n /**\n * Enable the user to fill out the wildlife search form\n */\n function enableWildlifeSearch() {\n /**\n * Enable all form elements in the wildlife search except for the\n * \"Found Address\" field\n */\n $(\".wildlife-form *:disabled\").not(\"#found-address\")\n .removeAttr(\"disabled\");\n\n /**\n * Add the \"checked\" class to all custom checkboxes that are\n * overlaying checked checkboxes\n */\n const customCheckboxes = $(\".custom-checkbox\");\n for(const customCheckbox of customCheckboxes) {\n const checkedRealCheckbox = $(customCheckbox)\n .siblings('input[type=\"checkbox\"]:checked');\n if (checkedRealCheckbox.length > 0) {\n $(customCheckbox).addClass(\"checked\");\n }\n }\n\n /**\n * Remove the \"disabled\" class from the custom checkboxes for the\n * wildlife types\n */\n $(\".custom-checkbox\").removeClass(\"disabled\");\n \n console.log(\"Wildlife search enabled\");\n }\n\n /**\n * Create an event listener for when the address is submitted from the\n * modal\n */\n function handleSubmitAddress() {\n $(\".select-address\").submit((event) => {\n event.preventDefault();\n\n // Get the selected coordinates\n const coordinates = $('.select-address input[name=\"address\"]:checked')\n .val();\n console.log(`Selected address coordinates: ${coordinates}`);\n\n // Store the selected coordinates in the \"Found Address\" field\n $(\"#found-address\").val(coordinates);\n\n // Close the modal\n MicroModal.close(\"addresses-modal\");\n\n // Enable the wildlife search form, if it's disabled\n if ($(\".wildlife-submit:disabled\").length > 0) {\n enableWildlifeSearch();\n }\n });\n }\n\n handleFindAddressClick();\n handleSubmitAddress();\n}",
"function callSearchLocation(){\n\tif(\"undefined\" != address && null != address && 0 < address.length && currentlyEmittedAddressIndex < address.length-1){\n\t\taddressString = address.slice(currentlyEmittedAddressIndex + 1,address.length).join(\" \");\n\t\tcurrentlyEmittedAddressIndex ++;\n\t\tsearchLocationOnMapAddressArray(addressString);\n\t}\n}",
"function handleSearchAddressInput(e) {\n\t\t\tclearTimeout(typingTimerSearchAddress);\n\t\t\tif (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {\n\t\t\t\ttypingTimerSearchAddress = setTimeout(function() {\n\t\t\t\t\t//empty search results\n\t\t\t\t\tvar resultContainer = document.getElementById('fnct_searchAddressResults');\n\t\t\t\t\twhile (resultContainer.hasChildNodes()) {\n\t\t\t\t\t\tresultContainer.removeChild(resultContainer.lastChild);\n\t\t\t\t\t}\n\t\t\t\t\tvar numResults = $('#zoomToAddressResults').get(0);\n\t\t\t\t\twhile (numResults.hasChildNodes()) {\n\t\t\t\t\t\tnumResults.removeChild(numResults.lastChild);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar lastSearchResults = $('#searchAddress').attr('data-search');\n\t\t\t\t\ttheInterface.emit('ui:searchAddressRequest', {\n\t\t\t\t\t\taddress : e.currentTarget.value,\n\t\t\t\t\t\tlastSearchResults : lastSearchResults\n\t\t\t\t\t});\n\t\t\t\t}, DONE_TYPING_INTERVAL);\n\t\t\t}\n\t\t}",
"#submitSearch(e) {\n let searchParameter;\n const searchField = Utility\n .getMatchingParent(e.currentTarget, \".search-container\")\n .querySelector(\".search-field\");\n let searchQuery = searchField.value; \n // searches can come as zip code, city name / state, city name / country, or by lat / long coordinates.\n // trim any extra white space\n searchQuery = searchQuery.replace(\", \", \",\");\n searchQuery = searchQuery.trim(); \n \n // If there are numbers in the query, infer that it is a US zip code.\n if (searchQuery.match(/[0-9]/g)\n && searchQuery.match(/[0-9]/g).length === 5\n ) {\n searchParameter = \"&zip=\" + searchQuery;\n // else check for lat long\n } else if (searchQuery.match(/[0-9]\\./g)\n && searchQuery.match(/[0-9]\\./g).length === 2\n ) {\n searchQuery = searchQuery.split(\",\");\n searchParameter = `&lat=${searchQuery[0]}&lon=${searchQuery[1]}`;\n // else check for a state abbreviation provided as the second argument.\n } else if (searchQuery.includes(\",\")\n && searchQuery.split(\",\")[1] !== null\n && searchQuery.split(\",\").length == 2\n ) {\n // in this case, we append us to the end\n searchQuery += \",US\";\n searchParameter = `&q=${searchQuery}`;\n } else {\n // else just throw it to q to query for.\n searchParameter = `&q=${searchQuery}`;\n }\n\n this.#locationQuery = searchParameter;\n this.#updateDisplay(true);\n }",
"function searchfromurl() {\n\n var pageurl = top.location.href\n var x = pageurl.split( '?' )[ 1 ];\n if ( x === \"ECP\" ) { // Early Childhood Program\n $( '#ECPmodal' ).modal( 'show' );\n return;\n }\n //debugger;\n if ( x != undefined ) {\n var addressLable = x.split( '=' )[ 0 ]; // Address or Schools\n var b = x.split( '=' )[ 1 ]; // 1234+N+Western&Type or 610212;609848;609774;609695\n\n if ( addressLable === \"Address\" ) {\n var addressContent = b.split( '&' )[ 0 ]; // 1234+N+Western\n var c = x.split( '&' )[ 1 ]; // Look for &Type=HS/ES\n\n if ( c != undefined ) {\n var typeContent = c.split( '=' )[ 1 ]; // HS/ES\n if ( typeContent === \"HS\" ) {\n addressQtype = \"HS\";\n _trackClickEventWithGA( \"Search\", \"URL\", \"Address-HS\" );\n }\n if ( typeContent === \"ES\" ) {\n addressQtype = \"ES\";\n _trackClickEventWithGA( \"Search\", \"URL\", \"Address-ES\" );\n }\n // otherwise Type=\"\" and all neihborhood schools will be displayed.\n var addressContent = addressContent.replace( /\\+/g, \" \" );\n $( \"#autocomplete\" ).val( addressContent );\n searchInputField();\n return;\n\n } else { //Address=\n _trackClickEventWithGA( \"Search\", \"URL\", \"Address-All\" );\n var addressContent = addressContent.replace( /\\+/g, \" \" );\n $( \"#autocomplete\" ).val( addressContent );\n searchInputField();\n return;\n }\n }\n\n if ( addressLable === \"Schools\" ) {\n if ( b != undefined ) {\n var schoollist = [];\n b = b.split( ';' );\n for ( var i = 0; i < b.length; i++ ) {\n schoollist.push( b[ i ] );\n }\n\n if ( schoollist.length === 1 ) {\n // url search with one result - change to school search\n _trackClickEventWithGA( \"Search\", \"URL\", \"Profile Page: \" + schoollist );\n searchtype = \"school\";\n } else {\n _trackClickEventWithGA( \"Search\", \"URL\", \"Profile Comparison: \" + schoollist );\n // url search with more than one result\n searchtype = \"url\";\n }\n // whereClause = filterSchools();\n var query = \"SELECT ID, School, Address, City, Phone, Type, Classification, BoundaryGrades, Grades, Boundary, Uniqueid,\" +\n \" Zip, Marker, Typenum, ProgramType, Lat, Long, Rating, \" +\n \" Count, Growth, Attainment, Culture, Graduation, Mobility, Dress, Reading, Math, SAT, ADA, College \" +\n \" FROM \" + fusionTableId + \" WHERE ID IN (\" + schoollist + \")\"; // + whereClause;\n encodeQuery( query, resultListBuilder );\n }\n }\n } else {\n // not a url search\n startTour();\n }\n}",
"function callSearchLocation() {\n var address = data[currentlySearchingIndex].mapSearchableAddress;\n var currentlyEmittedAddressIndex = data[currentlySearchingIndex].mapSearchableAddressEmittedAddress\n if (\"undefined\" != typeof address && null != address && 0 < address.length && currentlyEmittedAddressIndex < address.length - 1) {\n data[currentlySearchingIndex].addressString = address.slice(currentlyEmittedAddressIndex + 1, address.length).join(\" \");\n data[currentlySearchingIndex].mapSearchableAddressEmittedAddress++;\n searchLocationOnMapAddressArray(data[currentlySearchingIndex].addressString);\n } else {\n currentlySearchingIndex++;\n if (currentlySearchingIndex < data.length) {\n callSearchLocation();\n }\n }\n}",
"function handleSearch(event) {\n\t\tevent.preventDefault();\n\t\tlet userAddress = $userSearchTerm.val();\n\t\t//encode it right here, then pass it to getMaps\n\t\tlet encodedAddress = encodeURI(userAddress);\n\t\tgetMaps(encodedAddress);\n\t}",
"function search() {\n var latlong = \"\";\n var myarr = [];\n\n if (vm.place && (vm.place != \"\" || vm.place != undefined)) {\n latlong = vm.place.value;\n }\n\n if (latlong != \"\" && latlong != undefined) {\n myarr = latlong.split(\",\");\n coordinates = {\n lat: (myarr[0]) ? parseFloat(myarr[0]).toFixed(5) : 0.00000,\n long: (myarr[1]) ? parseFloat(myarr[1]).toFixed(5) : 0.00000\n }\n getTruckInfo(coordinates);\n }\n else {\n WEBSERVICE.createAlert(1, \"Unable to find address\", 3);\n vm.isSearchMap = true;\n vm.isSearch = false;\n vm.loading = false;\n }\n }",
"function submitAddress( addr ) {\r\n\tgeocode( addr, function( places ) {\r\n\t\tvar n = places && places.length;\r\n\t\tlog( 'Number of matches: ' + n );\r\n\t\tif( ! n ) {\r\n\t\t\tspin( false );\r\n\t\t\tdetailsOnly( S(\r\n\t\t\t\tlog.print(),\r\n\t\t\t\tT('didNotFind')\r\n\t\t\t) );\r\n\t\t}\r\n\t\telse if( n == 1 ) {\r\n\t\t\tfindPrecinct( places[0], addr );\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif( places ) {\r\n\t\t\t\tdetailsOnly( T('selectAddressHeader') );\r\n\t\t\t\tvar $radios = $('#radios');\r\n\t\t\t\t$radios.append( formatPlaces(places) );\r\n\t\t\t\t$detailsbox.show();\r\n\t\t\t\t$details.find('input:radio').click( function() {\r\n\t\t\t\t\tvar radio = this;\r\n\t\t\t\t\tspin( true );\r\n\t\t\t\t\tsetTimeout( function() {\r\n\t\t\t\t\t\tfunction ready() {\r\n\t\t\t\t\t\t\tfindPrecinct( places[ radio.id.split('-')[1] ] );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif( $.browser.msie ) {\r\n\t\t\t\t\t\t\t$radios.hide();\r\n\t\t\t\t\t\t\tready();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t$radios.slideUp( 350, ready );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}, 250 );\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tsorry();\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}",
"function search() {\n console.log(\"isSearching: \" + isSearching());\n if (isSearching()) return; // if still in the middle of searching, abort\n \n // get the search query from input box\n var search_str = search_viewcontroller.getSearchQuery(); \n\n // clear the previous search results\n search_viewcontroller.clearSearchResults();\n\n // Show loading animiation\n search_viewcontroller.loadingUI(true);\n\n // Send requests using parsers\n for (var key in values.hosts) {\n values.hosts[key].parsers.search(search_str, searchResponse)\n search_flag_dict[values.hosts[key].name] = true;\n }\n}",
"function search(evt){\n\n if (evt){\n // don't search if pressing keys to navigate the list\n switch(evt.which){\n case 13:\n case 37:\n case 38:\n case 40:\n evt.preventDefault();\n evt.stopPropagation();\n return false; \n break;\n }\n }\n\n var searchstring = plugin.acInput.val();\n\n if (searchstring == ''){\n return;\n }\n\n // store the search string\n plugin.acInput.data('search-text',searchstring);\n\n var dataset = plugin.config.dataset;\n\n if ($.trim(searchstring) == ''){\n return false;\n }\n \n if(xhr && xhr.readyState != 4){\n xhr.abort();\n }\n xhr = $.ajax({\n\t\t \n url: constants.searchURL.replace('{key}',plugin.config.searchkey)+dataset+'/'+searchstring+'/?format=json',\n type: 'GET',\n dataType: 'jsonp',\n success: function(data){\n \n var addresses = data.predictions;\n\n if (addresses.length > 0){\n \n plugin.acAddressSelect.html('');\n\n // check searchstring is still current.\n if (searchstring === plugin.acInput.val()){\n \n // add the addresses to the Select drop down\n $.each(addresses, function(index, value){\n var listitem = $('<li></li>');\n var css = 'finish';\n var listitemlink = $('<a href=\"#\" class=\"'+css+'\">'+value.prediction+'</a>').data('finish-id',value.refs);\n\n plugin.acAddressSelect.append(listitem.append(listitemlink)).trigger('show');\n\n });\n\n }\n\n }\n\n },\n error: function(jqXHR, textStatus, errorThrown ) {\n if (textStatus != 'abort'){\n debug('Search failed: '+textStatus, 2);\n }\n },\n timeout: 2000\n });\n }",
"async getAddress(request, response) {\n console.log(\"\\n---> GetAddress()\");\n var maxSearches = this.config.POSTCODER_MAX_SEARCHES;\n var playerToken = request.body.playerToken;\n if (!request.body.hasOwnProperty(\"postcode\") && (!request.body.postcode)) {\n throw new Error(\"A postcode has not been submitted.\");\n }\n var postcode = request.body.postcode.trim().toUpperCase();\n var status = await this.db.getPlayerAddressStatus(playerToken);\n if (status.length === 0) {\n throw new Error('The player was not found in the database.');\n }\n var addressStatus = status[0].playerAddressStatus;\n var addressSearches = status[0].playerAddressSearches;\n var responseObj = {\n \"address\": {}\n }\n console.log('current stored address statues: ' + addressStatus + '; searches: ' + addressSearches);\n // If the address is already found, do not call PostCoder, instead just return the address back and the appropriate completionCode.\n /*if (addressStatus == 1) {\n console.log(\"address already known...\");\n var email = await this.db.getUserEmail(playerToken);\n var ageVerified = await this.db.isAgeVerified(playerToken, request);\n responseObj[ageVerified] = ageVerified;\n await this.completionServices.sendFailResponse(request, response, self.completionServices.completionCodes.POSTCODER_ADDRESS_ALREADY_FOUND, responseObj);\n return;\n }*/\n\n // On the other cases, determine how many times a search has been attempted, and either do a search or return an empty array so that the user will have to manually input the address.\n // Do not search if the maximum number of searches has been reached.\n if (addressSearches >= maxSearches) {\n await this.completionServices.sendFailResponse(request, response, self.completionServices.completionCodes.POSTCODER_TOO_MANY_SEARCHES, responseObj);\n return;\n }\n // Otherwise, send a request to the PostCoder service.\n // Set up the API call.\n var country = \"uk\";\n const API_KEY = \"PCWSH-WZXV5-K23Y4-ZWJR5\";\n const address_url = `https://ws.postcoder.com/pcw/${ API_KEY }/address/${ country }/${ postcode }`;\n // Make the call.\n try {\n var body = await self.promisifyReq(address_url);\n } catch (err) {\n console.log('PostCoder API... failure :/ ', err);\n this.completionServices.sendFailResponse(request, response, self.completionServices.completionCodes.POSTCODER_ADDRESS_NOT_FOUND, responseObj);\n return;\n }\n\n console.log('PostCoder API... success!');\n addressSearches += 1;\n await this.db.setPlayerAddressSearches(playerToken, addressSearches);\n var addresses = JSON.parse(body);\n for (var i = 0; i < addresses.length; i++) {\n responseObj.address[addresses[i].summaryline] = addresses[i];\n }\n\n this.completionServices.sendOkResponse(request, response, responseObj);\n }",
"function addressSearch(key, filter, order, pageNum) {\n\tvar term = \"'%\" + key + \"%'\";\n\tvar pageSize = 10;\n\tvar subQueryToFetchNumOfResults = 'count(*) OVER() AS numresults, ';\n\tvar subQueryToFetchPageCount = 'ceil((count(*) OVER())::numeric/'+ pageSize + ') AS numpages ';\n\tvar subQueryToHandlePagination = ' LIMIT ' + 10 + ' OFFSET ' + ((pageNum - 1 ) * 10);\n\treturn db.any('SELECT *, ' + subQueryToFetchNumOfResults + subQueryToFetchPageCount + ' FROM listings WHERE LOWER(address) LIKE LOWER(' + term + ') ' + filter + ' ORDER BY ' + order + ' ' + subQueryToHandlePagination);\n}",
"function search( input )\n{\n // get the placeholder element and delete its content\n var listBox = document.getElementById( \"Names\" );\n listBox.innerHTML = \"\"; // clear the display box\n\n // if no search string is specified all the names are displayed\n if ( input == \"\" ) // if no search value specified\n {\n showAddressBook(); // Load the entire address book\n } // end if\n else\n {\n callWebService( \"/search/\" + input, parseData );\n } // end else \n} // end function search",
"function addressSearch( theAddress ) {\n var address = theAddress;\n if ( address != \"\" ) {\n if ( address.toLowerCase().indexOf( \"tulsa, oklahoma\" ) == -1 ) {\n address = address + \" tulsa, oklahoma\";\n }\n geocoder.geocode( {\n 'address': address\n }, function ( results, status ) {\n if ( status == google.maps.GeocoderStatus.OK ) {\n geoaddress = ( results[ 0 ].formatted_address );\n map.setCenter( results[ 0 ].geometry.location );\n radiusLoc = results[ 0 ].geometry.location;\n map.setZoom( 14 );\n if ( addrMarker ) {\n addrMarker.setMap( null );\n }\n addrMarker = new google.maps.Marker( {\n position: results[ 0 ].geometry.location,\n map: map,\n icon: addrMarkerImage,\n animation: google.maps.Animation.DROP,\n title: geoaddress\n } );\n //_trackClickEventWithGA(\"Search\", \"Address\", geoaddress);\n //_trackClickEventWithGA(\"Search\", \"Address\", theAddress);\n map.panTo( addrMarker.position );\n positionMarkersOnMap();\n whereClause = \" WHERE \"\n whereClause += \"Boundary = 'Attendance Area School' \";\n if ( addressQtype === \"HS\" ) {\n whereClause += \" AND Typenum = 3 \"; //HS //addressQtype is for a search initiated thru the URL for only HS or ES.\n }\n if ( addressQtype === \"ES\" ) {\n whereClause += \" AND Typenum IN (1,2) \"; //ES and MS\n }\n whereClause += \" AND ST_INTERSECTS('Polygon', CIRCLE(LATLNG\" + results[ 0 ].geometry.location.toString() + \",\" + .00001 + \"))\";\n whereClause += \" ORDER BY 'School'\";\n var query = \"SELECT ID, School, Address, City, Phone, Type, Classification, BoundaryGrades, Grades, Boundary, Uniqueid,\" +\n \" Zip, Marker, Typenum, ProgramType, Lat, Long, Rating, \" +\n \" Count, Growth, Attainment, Culture, Graduation, Mobility, Dress, Reading, Math, SAT, ADA, College \" +\n \" FROM \" + fusionTableId + whereClause;\n //console.log(query);\n //encodeQuery(query, resultListHomeSchool);\n encodeQuery( query, resultListBuilder );\n } else { //geocoder status not ok\n alert( \"We could not find your address: \" + status );\n }\n } );\n } else { //didn't enter an address\n alert( \"Please enter an address.\" );\n }\n}",
"function searchPlace() {\n const query = document.getElementById('place-search-input').value.trim();\n if (query == '') {\n handleSearchCallback([]);\n return;\n }\n const request = {\n query: query,\n type: 'food',\n };\n service.textSearch(request, handleSearchCallback);\n}",
"function search() {\n\t\t// clear the current contacts list\n\t\twhile (parent.lastChild)\n\t\t\tparent.removeChild(parent.lastChild);\n\t\t\n\t\tval = document.getElementById(\"searchField\").value;\n\n\t\txhttp.open(\"POST\", \"http://students.engr.scu.edu/~adiaztos/resources/contacts.php?query=\" + val, true);\n\t\txhttp.send();\n\t}",
"function processAddress()\n{\n\tvar address = getAddress();\n\n\t//creating a geocoder object\n\tvar geocoder = new google.maps.Geocoder();\n\n\tgeocoder.geocode({'address': address}, function(results, status)\n\t{\n\t\t//If this was successful, then...\n\t\tif (status === 'OK')\n\t\t{\n\t\t\t//get the latitude and longitude: Note this is part of what I would store to the database or session\n\t\t\tvar latitude = results[0].geometry.location.lat();\n\t\t\tvar longitude = results[0].geometry.location.lng();\n\t\t\tsetMarker(results[0].geometry.location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else if (status==\"ZERO_RESULTS\")\n\t\t{\n\t\t\t//get the latitude and longitude in case when coordinates are provided in the address field and set the marker as well as string to the database or session\n\t\t\tvar location=address.replace(/[()]/g, '').split(',');\n\t\t\tvar latitude = location[0];\n\t\t\tvar longitude = location[1];\n\t\t\tsetMarker({lat:parseFloat(latitude), lng:parseFloat(longitude)});\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else \n\t\t{\n\t\t\tconsole.error('Geocode was not successful for the following reason: ' + status);\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This will contact the TestAPI to update an existing test case. | function updateTestCase(name, testCase) {
if(testCase.name != ""){
var testCase_url = ctrl.requestUrl + '/' + name;
ctrl.testCasesRequest = $http.put(testCase_url, testCase)
ctrl.testCasesRequest.success(function (data){
ctrl.success = "Test case is successfully updated"
loadDetails();
ctrl.toastSuccess();
})
.catch(function (data) {
ctrl.error = data.statusText;
ctrl.toastError()
});
return ctrl.testCasesRequest;
}
else{
ctrl.error = 'Name is missing.'
ctrl.toastError()
}
} | [
"function updateContests() {}",
"updateTest() {\n // run the editors save method\n this.$refs.textEditor.saveEditorData()\n // update the document\n db.collection(\"tests\")\n .doc(this.$route.params.test_id)\n .update({\n title: this.title,\n type: this.department,\n description: this.$refs.textEditor.htmlForEditor,\n editorImages: this.$refs.textEditor.images\n })\n .then(() => {\n alert(\"Test info updated!\")\n })\n .catch((error) => {\n console.error(\"Error writing document: \", error)\n return // dont leave the page if save fails\n })\n // return to tests page\n this.$router.push(\"/view-tests\")\n }",
"static testTestIdPUT({ testId, test }) {\n return new Promise(async resolve => {\n try {\n resolve(Service.successResponse(\"\"));\n } catch (e) {\n resolve(\n Service.rejectResponse(e.message || \"Invalid input\", e.status || 405)\n );\n }\n });\n }",
"function test_update() {\n //List existing contacts\n contactApi.list_contacts((err, res) => {\n if (err) {\n sharedResource.dbgOut(err);\n }\n if (res) {\n //pick the first contact\n let contact = res.list[0];\n sharedResource.dbgOut(`Before update contact: ` + contact);\n //update it's mdn\n contact.primary_mdn = \"17207871234\";\n sharedResource.dbgOut(`New primary_mdn: ${contact.primary_mdn}`);\n contactApi.update_contact(contact, (err_update) => {\n sharedResource.dbgOut(err_update ? err_update : `Updated successfully`);\n })\n }\n })\n}",
"function updateOnlineTest(idOnlineTest, onlineTestData) {\n const requestOptions = {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: authHeader(),\n },\n };\n\n const url = `/document_online/${idOnlineTest}/`;\n\n return axios.patch(`${apiUrl}${url}`, onlineTestData, requestOptions)\n .then(response => response.data).then(updatedOnlineTest => updatedOnlineTest);\n}",
"function test_update_contacts () {\n\n\t//Test update contact query\n\tdescribe ('Contact Address Book API Tests Suite #4 : Update and Delete Contacts', function () {\n\t\tit('Update Contact \\'user10\\' -> \\'user18\\'', function(success) {\n\t\t\tapi.put('/contact/user10')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'user10', newname: 'user18'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\tit('Update Contact \\'firstname2\\' -> \\'firstname4\\'', function(success) {\n\t\t\tapi.put('/contact/firstname2')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'firstname2', newname: 'firstname4'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\tit('Delete Contact \\'user18\\' ', function(success) {\n\t\t\tapi.put('/contact/user18')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'user18'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\tit('Delete Contact \\'firstname4\\' ', function(success) {\n\t\t\tapi.delete('/contact/firstname4')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'firstname4'})\n\t\t\t.expect(200,success);\n\t\t});\n\t});\n\n}",
"static async editTestResult(req, res, next) {\n try {\n const input = req.body;\n const ret = await this.database.editTestResult(input);\n res.send(ret);\n } catch (error) {\n next(error);\n }\n }",
"function test_update_contacts () {\n\tdescribe ('Contact Address Book API Tests Suite #4 : Update and Delete Contacts', function () {\n\t\t\n\t\t//Test update contact query\n\t\tit('Update Contact \\'user10\\' -> \\'user18\\'', function(success) {\n\t\t\tapi.put('/contact/user10')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'user10', newname: 'user18'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\tit('Update Contact \\'firstname2\\' -> \\'firstname4\\'', function(success) {\n\t\t\tapi.put('/contact/firstname2')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'firstname2', newname: 'firstname4'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\t//Test delete contact query\n\t\tit('Delete Contact \\'user18\\' ', function(success) {\n\t\t\tapi.put('/contact/user18')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'user18'})\n\t\t\t.expect(200,success);\n\t\t});\n\n\t\tit('Delete Contact \\'firstname4\\' ', function(success) {\n\t\t\tapi.delete('/contact/firstname4')\n\t\t\t.set('Accept', 'application/json')\n\t\t\t.send({name: 'firstname4'})\n\t\t\t.expect(200,success);\n\t\t});\n\t});\n\n}",
"_passed(test) {\n const sessionId = this._getSessionId();\n this._updateJob(sessionId, { 'test[success]': true, 'test[name]': test.title });\n }",
"async update(id, newExercise) {\n // Finding desired workout by searching the ID\n const workoutById = await workoutController.findOne({_id:ObjectId(id)});\n const updatedWorkout = workoutModel.createExercise(workoutById,newExercise);\n return workoutController.replaceOne({_id:ObjectId(id)},updatedWorkout);\n }",
"function test_update() {\n //List all channels\n channelApi.list_channel((err, res) => {\n if (err) {\n sharedResource.dbgOut(err);\n }\n if (res) {\n //sharedResource.dbgOut(res);\n if (res.list.length < 1) {\n sharedResource.dbgOut('Please add some channel first');\n } else {\n //Take the first channel\n let chan = res.list[0];\n //update the channel name\n chan.name = chan.name + Date.now();\n //call update_channel API, pass the new updated channel and the callback\n channelApi.update_channel(chan, (err_u, res_u) => {\n if (err_u) {\n sharedResource.dbgOut(err_u);\n }\n if (res_u) {\n sharedResource.dbgOut(res_u);\n }\n })\n }\n \n }\n })\n}",
"function testSinglePlan_Update() {\n asyncTestCase.waitForAsync('testSinglePlan_Update');\n assertEquals(0, cache.getCount());\n\n var newTitle = 'Quantum Physicist';\n var queryTask = new lf.proc.UserQueryTask(\n hr.db.getGlobal(), [getSampleQuery()]);\n queryTask.exec().then(function() {\n assertEquals(ROW_COUNT, cache.getCount());\n var query = /** @type {!lf.query.UpdateBuilder} */ (\n db.update(j).set(j.title, newTitle)).getTaskItem();\n var updateQueryTask = new lf.proc.UserQueryTask(\n hr.db.getGlobal(), [query]);\n return updateQueryTask.exec();\n }).then(function() {\n return lf.testing.util.selectAll(global, j);\n }).then(function(results) {\n assertEquals(ROW_COUNT, results.length);\n assertEquals(ROW_COUNT, cache.getCount());\n for (var i = 0; i < ROW_COUNT; ++i) {\n assertEquals(newTitle, results[i].payload()[j.title.getName()]);\n var id = rows[i].id();\n assertEquals(newTitle, cache.get(id).payload()[j.title.getName()]);\n }\n asyncTestCase.continueTesting();\n });\n}",
"update (id, instance) {\n let response = api.patch(this.endpoints.update.replace(':id', id), instance)\n return response\n }",
"async updateProfile(testController, firstName) {\n const newFirstName = 'New First Name';\n await this.isDisplayed(testController);\n // Delete text from first name field.\n await testController.selectText(`#${ComponentIDs.homeFormFirstName}`).pressKey('delete');\n // Type in new first name.\n await testController.typeText(`#${ComponentIDs.homeFormFirstName}`, newFirstName);\n // Submit it.\n await testController.click(`#${ComponentIDs.homeFormSubmit} input.btn.btn-primary`);\n // Click the OK button on the Sweet Alert.\n await testController.click(Selector('.swal-button--confirm'));\n // Check that the field is updated.\n await testController.expect(Selector(`#${ComponentIDs.homeFormFirstName}`).value).eql(newFirstName);\n // Now restore original value.\n await testController.selectText(`#${ComponentIDs.homeFormFirstName}`).pressKey('delete');\n await testController.typeText(`#${ComponentIDs.homeFormFirstName}`, firstName);\n await testController.click(`#${ComponentIDs.homeFormSubmit} input.btn.btn-primary`);\n await testController.click(Selector('.swal-button--confirm'));\n await testController.expect(Selector(`#${ComponentIDs.homeFormFirstName}`).value).eql(firstName);\n }",
"function updateTestDataOnServer(newTest, oldname, testData, callback) {\n\n var theURL = \"StudySetup?command=updateTestData&new=\" + newTest + \"&oldname=\"+oldname;;\n $.ajax({\n url: theURL,\n type: 'GET',\n data: {testData: JSON.stringify(testData)},\n dataType: 'json',\n success: function(data, status) {\n callback(true, \"\");\n },\n error: function(data, status) {\n //handle error\n alert(\"there was an errror saving the\"\n + \" test on the server___ STATUS: \" + status);\n }\n });\n\n\n}",
"function Update(id, taskUpdate, response) {\n\t\"use strict\";\n\tif(Validate(taskUpdate, response)){\n\t\ttaskConnection.Update(id, taskUpdate, response);\n\t}\n}",
"function saveModifiedTest() {\n var setup = new Setup(test);\n setup.saveModifiedTest();\n\n}",
"async function testExcerciseUpdate() {\n try {\n const response = await axios.put('http://localhost:8080/api/excercisies/6002fac4a95df31d5ce58f0b', {\n count: 4,\n distance: 100 , \n });\n if(response.status == 200) return true;\n return false;\n } catch (error) {\n logger.error(`error - testExcerciseUpdate - ${error}`);\n }\n}",
"createUpdateHackathon(details, success, failure) {\n this.postCall(URI.CREATE_UPDATE_HACKATHON, details, success, failure, true);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== from functions/maths/PolarCoordinates.java =================================================================== Needed early: Builtin Needed late: Complex Pair Real | function PolarCoordinates() {
} | [
"toPolarCoords() {\n return ({\n r: Math.sqrt(this.x ** 2 + this.y ** 2),\n a: Point.angle(this),\n });\n }",
"toPolar()\r\n {\r\n return createVector(this.center.x + this.radius * cos(this.angle), \r\n this.center.y + this.radius * sin(this.angle));\r\n }",
"static fromPolar(r, θ) {\n return new Complex(r * Math.cos(θ), r * Math.sin(θ));\n }",
"static toPolar(xyz){\r\n\t\tlet t = new Array();\r\n\t\tt[0] = Math.sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2]);\r\n\t\tt[1] = Math.acos(xyz[2] / t[0]);\r\n\t\tt[2] = Math.atan2(xyz[1], xyz[0]);\r\n\r\n\t\tif(t[1]<0){t[1]+=2*Math.PI;}\r\n\t\tif(t[2]<0){t[2]+=2*Math.PI;}\r\n\r\n\t\treturn t;\r\n\t}",
"static fromPolar(angle, r = 1) {\n return new Point(r * Math.cos(angle), r * Math.sin(angle));\n }",
"function cartesian2Polar(point){\n var x = point[0];\n var y = point[1];\n var theta = rad2deg(Math.atan(y/x));\n \n // Q1: Use theta\n // Q2, Q3: Use theta + 180\n // Q4: Use theta + 360\n if(x < 0) theta += 180; // Handles Q2, Q3\n if(x > 0 && y < 0) theta += 360; // Handles Q4 \n \n if(x == 0){\n if(y > 0) theta = 90;\n else if(y < 0) theta = 270;\n else theta = 0;\n }\n \n return [magnitude(x,y), theta];\n}",
"function toPolar(complexNumber)\n{\n\tvar r = Math.sqrt((complexNumber.real * complexNumber.real) + (complexNumber.img * complexNumber.img));\n\tvar theta = Math.atan2(complexNumber.img, complexNumber.real);\n\n\treturn new PolarCoordinate(r, theta);\n}",
"function cartesianToPolar(x, y) {\n\n\t\tconst radius = height/6\n\t\tconst _x = (radius + 400 * y/height) * Math.sin(2 * Math.PI * x/width) + width/2\n\t\tconst _y = (radius + 400 * y/height) * Math.cos(2 * Math.PI * x/width) + height/2\n\n\t\treturn { X:_x, Y:_y}\n\t}",
"function toPolarCoordinates(inpt) {\n\t//Find origin point.\n\tvar xorig=(inpt[0].xpos+inpt[1].xpos)/2;\n\tvar yorig=(inpt[0].ypos+inpt[1].ypos)/2;\n\t\t\n\t//First reset the original point. We have done all of the reference spiral calculations at this point, so safe. \n\tinpt[0].r=Math.sqrt(Math.pow(inpt[0].xpos-xorig,2)+Math.pow(inpt[0].ypos-yorig,2));\n\t//Compute theta, but adjust for the preceding point so that theta is always positively increasing. \n\tinpt[0].theta=atanRotate(inpt[0].ypos-yorig,inpt[0].xpos-xorig);\n\t\n\t//Now do this for all spiral points.\n\tvar pre=inpt[0].theta; \n\tvar zeroCrossing = 0; \n\tfor (var i=1; i<inpt.length;i++) {\n\t\tinpt[i].r=Math.sqrt(Math.pow(inpt[i].xpos-xorig,2)+Math.pow(inpt[i].ypos-yorig,2));\n\t\t\n\t\tvar tmp=atanRotate(inpt[i].xpos-xorig,inpt[i].ypos-yorig)+360*(zeroCrossing-1);\n\t\tif (tmp<pre) {\n\t\t\t//Hit a point where we cross back over x=1,y=0. Need to add 360 degrees.\n\t\t\tzeroCrossing++;\n\t\t}\n\t\tinpt[i].theta = tmp; \n\t\tpre=tmp; \n\t}\n\t\n\t//Now convert back to radians.\n\tfor (var i=0; i<inpt.length; i++) {\n\t\tinpt[i].theta=toRadian(inpt[i].theta);\n\t}\n}",
"function cartesianToPolar(x, y) {\n\t\tvar r = scope.radiusScale(x);\n\t\tvar a = scope.xScale(y) - Math.PI / 2;\n\t\tx = r * Math.cos(a) + size.width / 2;\n\t\ty = r * Math.sin(a) + size.height / 2;\n\t\treturn ({x: x, y: y});\n\t\t\n\t}",
"function polar(rFunctionOfTheta){\n return function(parameter){\n var theta = parameter;\n var radius = rFunctionOfTheta(theta);\n return [radius * Math.cos(theta), radius * Math.sin(theta)];\n }\n}",
"function cartesianToPolar(x,y) {\n var r = scope.radiusScale(x);\n var a = scope.thetaScale(y) - Math.PI/2;\n x = r * Math.cos(a) + size.width/2;\n y = r * Math.sin(a) + size.height/2;\n return ({x:x,y:y});\n\n }",
"polarToCartesian(cx, cy, r, angleDegrees) {\n let angleInRad = ((angleDegrees - 90) * Math.PI) / 180;\n let x = cx + r * Math.cos(angleInRad);\n let y = cy + r * Math.sin(angleInRad);\n return { x, y };\n }",
"r() {\n // Polar coordinates (theta=0 is East on screen, and increases in CCW\n // direction\n return Math.sqrt(this.x*this.x + this.y*this.y);\n }",
"get polarAngle() {\n return this._spherical.phi;\n }",
"function PolarCoordinate(r, theta)\n{\n\tthis.r = r;\n\tthis.theta = theta;\n}",
"function polarToCartesian(r, theta) {\n return [r * Math.cos(theta), r * Math.sin(theta)];\n }",
"pointToPolarAngle(point) {\n\t\tlet relativePoint = point.sub(this.center);\n\t\tlet angleInRadians = Math.acos(relativePoint.z/this.radius);\n\n\t\treturn angleInRadians;\n\n\t}",
"function radialCoordinate(rad, r) {\n rad -= Math.PI / 2;\n return {\n x: r * Math.cos(rad),\n y: r * Math.sin(rad)\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating New Patient through the forms | function createPatient() {
const patient = {
name: document.getElementById('name').value,
sex: document.getElementById('sex').value,
gender: document.getElementById('gender').value,
age: document.getElementById('age').value,
date_of_birth: document.getElementById('date_of_birth').value
}
fetch("http://localhost:3000/patients", {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(patient)
})
.then(resp => resp.json())
.then(patient => {
clearPatientHtml()
getPatients()
Patient.newPatientForm()
})
} | [
"function createPatient(id_, password_, email_, phoneNum_,fName_, lName_, gender_, bday_, hcNum_) {\n const newPatient = new Patient (id_, password_, email_, phoneNum_,fName_, lName_, gender_, bday_, hcNum_);\n patientList.push(newPatient);\n}",
"function addNewPatient(newPatient){\n\tlet id = newPatient.id;\n\tlet first = newPatient.firstName;\n\tlet last = newPatient.lastName;\n\tlet doctorId = newPatient.doctor.id;\n\taddPatient(id, first, last, heart, doctorId);\n}",
"function CreateNewPatient(username, password, email, phone, firstname, lastname) {\r\n var patient = new Object();\r\n patient.username = username;\r\n patient.password = password;\r\n patient.email = email;\r\n patient.phone = phone;\r\n return patient;\r\n}",
"function populateFormWithPatient(patient) {\n var form = document.getElementById('createUpdateForm')\n form.querySelector('input[name=\"patientId\"]').disabled = true\n form.querySelector('input[name=\"patientId\"]').value = patient.patientId\n form.querySelector('input[name=\"patientName\"]').value = patient.patientName\n form.querySelector('input[name=\"phone\"]').value = patient.phone\n form.querySelector('select[name=\"dentistId\"]').value = patient.dentistId\n return patient\n}",
"function createNewPatient() {\n $.ajax({\n url: `${proxyurl + baseUrl}/auth/register`,\n type: 'POST',\n dataType: 'application/json', // added data type,\n data: getNewPatientData(),\n\n success: function(res) {\n console.log(res);\n // alert(res);\n },\n\n error: function(res) {\n console.log(res);\n // alert(res);\n }\n });\n }",
"function addPatient(patient) {\n patientsIdArray.push(patient.id);\n patientsNameArray.push(patient.first_name + ((patient.last_name !== '') ? (' ' + patient.last_name) : '') + ' (' + patient.patient_id + ')');\n }",
"function addPatient(name, firstname, address, secuId, sex, birthday, tel, pathology) {\n const P = new Patient(name, firstname, address, secuId, sex, birthday, tel, pathology);\n exports.mapPatient.set(P.getSecuId(), P);\n addPatientSubject.next(P);\n return P;\n}",
"function addNewPatient(patientName, homeAddress, telephoneNumber)\n{\n\tif (patientName && homeAddress && telephoneNumber)\n\t{\n\t\tif (data.patients[patientName] == null)\n\t\t{\n\t\t\tdata.patients[patientName] = { name: patientName, address: homeAddress, telephoneNumber: telephoneNumber }\n\t\t\tdata.patientList.push(patientName);\t\t\t\n\t\t}\n\t}\n\telse\n\t{\n\t\tthrow new AppException('Patient Not Created', 'Patient Name, home address and telephone number has to be specified');\n\t}\n}",
"submitNewPatient()\n\t\t{\n\t\t\tvar self = this;\n\t\t\tvar value= document.getElementById('value');\n\t\t\tconsole.log(this.get('l_Name'));\n var val = value.options[value.selectedIndex].text;\n\t\t\tlet ajaxPost = this.get('ajax').request('/api/patients',\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\ttype: 'application/json',\n\t\t\t\tdata: { patient:\n\t\t\t\t\t{\n\n\t\t\t\t\tclient: this.get('c_ID'),\n\t\t\t\t\tspecies: \tthis.get('patientSpecies'),\n\t\t\t\t\tfirst_name: this.get('patientFirstName'),\n\t\t\t\t\tlast_name: this.get('l_Name'),\n\t\t\t\t\tdateOfBirth: \t\tJSON.stringify(formatDate(document.getElementById('patientAge').value)),\n\t\t\t\t\tcolour: \tthis.get('patientColor'),\n\t\t\t\t\ttattoo: \tthis.get('patientTatoo'),\n\t\t\t\t\tmicrochip: \tthis.get('patientMicrochip'),\n\t\t\t\t\tsex: \tval\n\t\t\t\t}\n\t\t\t}, \n\t\t\n\t\t\t});\n\t\t\tajaxPost.then(function(data){\n\t\t\t\tself.transitionToRoute('search-patient');\n\t\t\t},\n\t\t\tfunction(response){\n\t\t\t\tif (response === false){\n\t\t\t\t\tif (self.get('session.isAuthenticated')){\n\t\t\t\t\t\tself.get('session').invalidate();\n\t\t\t\t\t}\n\t\t\t\tself.transitionToRoute('/login');\n\t\t\t}\n\t\t\telse{\n showAlert(response.errors[0].title, false, \"failure\");\n }\n\t\t\t});\n\t\treturn ajaxPost;\n\t}",
"function Patient (firstName, lastName, medicalcode, diagnosis, treatment,appointment) {\n this.firstName = firstName || '';\n this.lastName = lastName || '';\n // This refers to the medical professional's code the patient will provide during registration\n this.medicalcode = medicalcode || '';\n this.diagnosis = diagnosis || 'Undiagnosed';\n // This refers to an array to represent the appointments that the patient will have.\n // As appointments are added, they will be pushed into the array\n this.appointment = appointment || [];\n // This refers to an array to represent the treatment widgets the patient will be\n // assigned. As treatment widgets are added, they will be pushed into the array\n this.treatment = treatment || [];\n this.role = 'patient';\n this.roleType = 'public';\n // This is an object for keeping track of whether or not the patient\n // is being transferred to a new medical professional.\n this.transfer = {\n inProgress: false,\n newMp: '',\n mpCode: ''\n }\n this.mail = [];\n}",
"function getPatientFromForm() {\n var form = document.getElementById('createUpdateForm')\n var patient = {}\n patient.patientId = form.querySelector('input[name=\"patientId\"]').value\n patient.patientName = form.querySelector('input[name=\"patientName\"]').value\n patient.phone = parseInt(form.querySelector('input[name=\"phone\"]').value, 10)\n patient.dentistId = form.querySelector('select[name=\"dentistId\"]').value\n // console.log(JSON.stringify(patient))\n return patient\n}",
"function submitClientForm() {\n UserService.newAppointment.createNewAppointment(vm.clientReferralForm)\n .then(appointmentCreateSuccess, appointmentCreateError);\n }",
"function showAddPatientForm(){\n\tvar f = document.createElement(\"form\");\n\n\tvar table = document.createElement(\"table\");\n\n\n\t/**Surname row**/\n\tvar row = document.createElement(\"tr\");\n\tvar data1 = document.createElement(\"td\");\n\tvar text1 = document.createTextNode(\"Surname: \");\n\t\tdata1.appendChild(text1);\n\n\tvar surname = document.createElement(\"input\"); //input element, text\n\tsurname.setAttribute('type',\"text\");\n\tsurname.setAttribute('name',\"surname\");\n\tsurname.setAttribute('id',\"surname\");\n\tvar data2 = document.createElement(\"td\");\n\tdata2.appendChild(surname);\n\t//creating row structure\n\t\trow.appendChild(data1);\n\t\trow.appendChild(data2);\n\ttable.appendChild(row);\n\n\t/**Name row**/\n\tvar row = document.createElement(\"tr\");\n\tvar data1 = document.createElement(\"td\");\n\tvar text1 = document.createTextNode(\"Name: \");\n\t\tdata1.appendChild(text1);\n\n\tvar name = document.createElement(\"input\"); //input element, text\n\tname.setAttribute('type',\"text\");\n\tname.setAttribute('name',\"name\");\n\tname.setAttribute('id',\"name\");\n\tvar data2 = document.createElement(\"td\");\n\tdata2.appendChild(name);\n\t//creating row structure\n\t\trow.appendChild(data1);\n\t\trow.appendChild(data2);\n\ttable.appendChild(row);\n\n\t/**Age row**/\n\tvar row = document.createElement(\"tr\");\n\tvar data1 = document.createElement(\"td\");\n\tvar text1 = document.createTextNode(\"Age: \");\n\t\tdata1.appendChild(text1);\n\n\tvar age = document.createElement(\"input\"); //input element, text\n\tage.setAttribute('type',\"text\");\n\tage.setAttribute('name',\"age\");\n\tage.setAttribute('id',\"age\");\n\tvar data2 = document.createElement(\"td\");\n\tdata2.appendChild(age);\n\t//creating row structure\n\t\trow.appendChild(data1);\n\t\trow.appendChild(data2);\n\ttable.appendChild(row);\n\n\t//BUTTONS\n\n\tvar row = document.createElement(\"tr\");\n\tvar data1 = document.createElement(\"td\");\n\tvar s = document.createElement(\"input\"); //input element, Submit button\n\ts.setAttribute('type',\"button\");\n\ts.setAttribute('onclick', \"addPatient();\")\n\ts.setAttribute('value',\"Submit\");\n\tdata1.appendChild(s);\n\ttable.appendChild(data1);\t\n\n\n\tf.appendChild(s);\n\tf.appendChild(table);\n\n\tdocument.getElementsByTagName('article')[0].innerHTML = \"\";\n\tdocument.getElementsByTagName('article')[0].appendChild(f);\n\n\t//Adding element to print the addPatient result\n\tvar result = document.createElement(\"p\"); //input element, Submit button\n\tresult.setAttribute('id',\"addPatientResult\");\n\tdocument.getElementsByTagName('article')[0].appendChild(result);\n}",
"function createNewForm( ) {\n // -10 Indicates to the API that we are going to create a new Challenge\n get( -10 );\n //$scope.promo_form.$setPristine();\n //document.getElementById( 'promo_description' ).focus( );\n }",
"function addPatientIntoMongo(p) {\n connexionBD();\n console.log(\"Ajout d'un patient : \" + p);\n let patient = new PatientModel({ name: p.getName(), firstname: p.getFirstname(), address: p.getAddress(),\n secuId: p.getSecuId(), sex: p.getSex(), birthday: p.getBirthdayId(), tel: p.getTel(), pathology: p.getPathology() });\n patient.save(function (err, p) {\n if (err) {\n console.log(err + \"\\n\" + p);\n }\n else {\n console.log(\"Ajout Patient OK\");\n }\n });\n}",
"function createOne() {\n var participantForm = session.forms.giftregistry.event.participant;\n\n Form.get(session.forms.giftregistry).clear();\n\n participantForm.firstName.value = customer.profile.firstName;\n participantForm.lastName.value = customer.profile.lastName;\n participantForm.email.value = customer.profile.email;\n\n app.getView().render('account/giftregistry/eventparticipant');\n}",
"async createPhysician(req, res) {\n let data = {\n name: req.body.name,\n phone: req.body.phone\n }\n\n // Input validation\n try {\n if (!data.name || !data.phone || typeof data.name != \"string\", typeof data.phone != \"string\") {\n throw \"Invalid input\"\n }\n if (!data.phone.match(/^\\([2-9]\\d\\d\\) \\d\\d\\d-\\d{4}/)) {\n throw \"Invalid phone number\";\n }\n } catch (err) {\n this.sendResponse(res, this.HttpStatus.BAD_REQUEST, false, null, \"Invalid input\");\n return;\n }\n let qData = await this.db.physician.insert.one(data).catch(this.throwError);\n this.sendResponse(res, this.HttpStatus.OK, true, qData, \"Success creating physician\");\n }",
"function createRxPatient(){\n\tvar $form = $('#createRxChoosePatient');\n\tvar name = $form.find( \"input[name='name']\" ).val();\n\tvar phone = $form.find( \"input[name='phone']\" ).val();\n\tvar url = '/createRX?&name='+name+'&phone='+phone;\n\t$.get(url, function(data){\n\t\t$('#dialog').dialog({\n\t\t\tmodal: true,\n\t\t\theight: 'auto',\n\t\t\twidth:950,\n\t\t\ttop:20,\n\t\t\tposition: {\n\t\t\t\tmy: \"center top\",\n\t\t\t\tat: \"center top\",\n\t\t\t\tof: window\n\t\t\t}\n\t\t});\n\t\t$('#dialog').css('background', 'transparent');\n\t\t$('#dialog').css('overflow', 'auto');\n\t\t$('#dialog').css('width', '950px');\n\t\t$('#dialog').html(data);\n\t});\n}",
"function Patient(nom, prenom, sexe, naissance, numero, adresse) {\n this.nom = nom;\n this.prenom = prenom;\n this.sexe = sexe;\n this.naissance = naissance;\n this.numero = numero;\n this.adresse = adresse;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
called when loaded for the first time or when all ops are purged | async function initOps() {
const newop = await loadNewDefaultOp();
await resetOps(); // deletes everything including newop
newop.update(); // re-saves newop
} | [
"function initOps() {\n const newop = loadNewDefaultOp();\n resetOps(); // deletes everything including newop\n newop.update(); // re-saves newop\n}",
"function loaded() {\n\t\t$$invalidate(3, counter++, counter);\n\t}",
"afterLoadData() {\n this.refreshRecurringEventsCache('splice', this.storage.allValues);\n super.afterLoadData && super.afterLoadData();\n }",
"function unloadAllAndClearMemory() {\n\t\t\tobjectCausality.resetObjectIds();\n\t\t\timageCausality.resetObjectIds();\n\t\t\tdelete instance.persistent;\n\t\t\tdbIdToDbImageMap = {};\n\t\t\tsetupDatabase();\n\t\t}",
"onInitialLoad() {\n return;\n }",
"function purge() {\n loadedDataSets = {};\n promises = {};\n cacheSizeInBytes = 0;\n}",
"function purge() {\n loadedDataSets = {};\n promises = {};\n }",
"clearStore() {}",
"function purge() {\n loadedDataSets = {};\n promises = {};\n}",
"bootstrap(){this._cacheStore.bootstrap();}",
"clearOperations() {\n this._Operations = undefined;\n }",
"clearOperations () {\n\t\tthis.operations = [];\n\t}",
"_load() {\n\n // if already loaded, do nothing\n if (this._loaded) {\n return;\n }\n\n this._refreshSlot();\n\n }",
"static onShutdown() {\n Cache.save();\n Cache.temporary.map((key) => {\n Cache.remove(key);\n });\n }",
"afterCompetenceCreate(){\n this.loadData(false);\n }",
"deallocate () {\n this.lastReturnTime = Date.now()\n this.state = PooledResourceStateEnum.IDLE\n }",
"function _reloadData() {\n try {\n _loadStorage();\n } catch (E) {\n _storage_available = false;\n return;\n }\n _handleTTL();\n }",
"function test_edit_catalog_item_after_remove_resource_pool() {}",
"function _reloadData() {\n try {\n _load_storage();\n } catch (E) {\n _storage_available = false;\n return;\n }\n _handleTTL();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Represents an entity instance in the stage. This class cannot be instantiated directly, instances can be obtained using other methods such as `Canvace.Stage.forEachInstance`, `Canvace.Stage.getInstance` or their `Canvace.Stage.Entity` equivalents. In every moment, an entity instance is characterized by the following state: a position vector, a velocity vector, a uniform velocity vector, an acceleration vector. Each one of these vectors is a vector in a threedimensional space and is thus characterized by three real components `i`, `j` and `k`. An instance can be "ticked". Ticking an instance means updating its state based on the following physics rules: the acceleration vector is not changed, the uniform velocity vector is not changed, the velocity vector is updated by adding the acceleration vector, the position vector is updated by adding the velocity and uniform velocity vectors. To tick an instance use the `Canvace.Stage.Instance.tick` method. Ticking an instance, and thus updating its physics state, is not enough in order to update the actual position of its frames in the graphical rendering. Another separate operation, called "update", is necessary. An instance can be updated by invoking its `update` method. You do not usually need to invoke neither the `tick` nor the `update` method directly, as they are automatically invoked by the global `Canvace.Stage.tick` and `Canvace.Stage.update` methods which, in turn, are automatically invoked by the `RenderLoop`. Both the `Canvace.Stage.Instance.tick` and the `Canvace.Stage.Instance.update` methods are invoked _only_ for the instances that have physics enabled (physics can be toggled perentity in the Canvace Development Environment). The point in having two separate operations, "tick" and "update", to do one thing, which is moving an entity instance in the game, is that other operations can be accomplished between the two. These operations typically consist in further physics processing, e.g. collision testing. | function Instance(instanceOrId, element) {
var id, instance;
if (typeof instanceOrId !== 'number') {
id = null;
instance = instanceOrId;
} else {
id = instanceOrId;
instance = data.instances[id];
}
var entity = data.entities[instance.id];
var remove = instances.add(this);
if (entity.enablePhysics) {
remove = (function (remove1, remove2) {
return function () {
return remove1() && remove2();
};
})(remove, instancesWithPhysics.add(this));
}
// FIXME
this.drawBoundingBox = function (view, context, color) {
var position = view.project(
instance.position.i + entity.box.i0,
instance.position.j + entity.box.j0,
instance.position.k);
var dimension = view.project(
entity.box.iSpan,
entity.box.jSpan,
0);
context.save();
context.strokeStyle = (color || "red");
context.strokeRect(
position[0],
position[1],
dimension[0],
dimension[1]);
context.restore();
};
/**
* Returns the numeric ID of the instance, or `null` if this instance
* was not initially present in the JSON data exported from the Canvace
* Development Environment and was later added to the stage.
*
* @method getId
* @return {Number} The numeric ID of the instance, or `null` if the
* instance has no ID.
*/
this.getId = function () {
return id;
};
/**
* Returns the entity instance's custom properties as set in the Canvace
* Development Environment.
*
* The original `properties` object is returned, so that modifications
* actually affect the instance's properties.
*
* @method getProperties
* @return {Object} The entity instance's `properties` field containing
* the custom properties the user set in the Canvace Development
* Environment.
*/
this.getProperties = function () {
return instance.properties;
};
/**
* Returns the numeric ID of the entity of this instance.
*
* @method getEntityId
* @return {Number} The numeric ID of the entity of this instance.
*/
this.getEntityId = function () {
return instance.id;
};
/**
* Returns a `Canvace.Stage.Entity` object representing the entity whose
* instance is represented by this object.
*
* @method getEntity
* @return {Canvace.Stage.Entity} This instance's entity as a
* `Canvace.Stage.Entity` object.
*/
this.getEntity = function () {
return entities[instance.id] || new Entity(instance.id);
};
/**
* Returns the instance's `(i, j, k)` position vector as an object
* containing three fields, `i`, `j` and `k`.
*
* Note that the original position vector object associated to the
* instance is returned: changes made to the returned object affect the
* position of the instance. You may use the returned object to manually
* control the position of the instance.
*
* Also note that changing the position of an instance by modifying the
* returned object does not affect its _rendered_ position until the
* `update` method is called.
*
* @method getPosition
* @return {Object} An object containing three fields, `i`, `j` and `k`,
* indicating the current position.
*/
this.getPosition = function () {
return instance.position;
};
/**
* Returns the instance's projected position, which is its `(i, j, k)`
* position left-multiplied by the projection matrix.
*
* Note that this method returns the last calculated projected position,
* which means it does not reflect changes made by the `tick` method or
* by changing the position, velocity or uniform velocity objects
* returned by the `getPosition`, `getVelocity`, and
* `getUniformVelocity` methods. For changes to be reflected, the
* instance must be first updated using the `update` method.
*
* The position is returned as an object containing three fields, `x`,
* `y` and `z`, containing the `i`, `j` and `k` projected coordinates,
* respectively.
*
* @method getProjectedPosition
* @return {Object} The projected position as an object containing three
* `x`, `y` and `z` fields.
*/
this.getProjectedPosition = element.getProjectedPosition;
/**
* Returns the 2D rectangular area corresponding to the instances's
* bounds.
*
* Note that this method returns the last calculated projected
* rectangle, which means it does not reflect changes made by such
* methods as `tick`, `moveBy`, `setPosition` and so on. For changes to
* be reflected, the instance must be first updated using the `update`
* method.
*
* The rectangle is returned as an object containing four fields: the
* `x` and `y` coordinates of the origin and the `width` and `height`.
*
* The coordinates of the origin are calculated by left-multiplying the
* `(i, j, k)` position vector of the instance by the projection matrix
* and adding the entity's offset. The width and height are simply
* copied from the entity descriptor.
*
* @method getProjectedRectangle
* @return {Object} An object that describes the projected rectangle and
* contains four fields: `x`, `y`, `width` and `height`.
*/
this.getProjectedRectangle = element.getProjectedRectangle;
/**
* Indicates whether the instance is in or out of range.
*
* An entity instance is in range when its projected position (as
* returned by the `getProjectedPosition` method) falls within the
* "range" area, which is a rectangular area centered in the center of
* the viewport. The range area is usually much larger than the viewport
* area.
*
* This method is useful, for example, for discarding too far entity
* instances when stepping/ticking the physics of the game in order to
* improve performance, and is used by the `Stage.Range` inner class.
*
* @method inRange
* @param width {Number} The width of the range area.
* @param height {Number} The height of the range area.
* @return {Boolean} `true` if this instance falls within the specified
* range area, `false` otherwise.
*/
this.inRange = (function () {
var viewportWidth = view.getWidth();
var viewportHeight = view.getHeight();
return function (width, height) {
var position = element.getProjectedPosition();
var origin = view.getOrigin();
var frameWidth = (width - viewportWidth) / 2;
var frameHeight = (height - viewportHeight) / 2;
return (position.x >= -origin.x - frameWidth) &&
(position.x <= -origin.x + viewportWidth + frameWidth) &&
(position.y >= -origin.y - frameHeight) &&
(position.y <= -origin.y + viewportHeight + frameHeight);
};
})();
/**
* Returns the velocity vector of this instance as an object containing
* three fields, `i`, `j` and `k`, indicating the respective components
* of the vector. The velocity vector is initially `(0, 0, 0)`.
*
* This velocity vector is influenced by the acceleration vector of the
* instance: the components of the acceleration vector are added to the
* respective components of the velocity vector each time the instance
* is ticked using the `tick` method.
*
* Note that the original velocity vector object associated to the
* instance is returned: changes made to the returned object affect the
* velocity of the instance. You may use the returned object to manually
* control the velocity of the instance.
*
* @method getVelocity
* @return {Object} The instance's velocity vector as an object
* containing three fields, `i`, `j` and `k`, indicating the respective
* components of the vector.
*/
this.getVelocity = function () {
return instance.velocity;
};
/**
* Returns the uniform velocity vector of this instance.
*
* The vector is returned as an object containing three fields, `i`, `j`
* and `k`, indicating the respective components of the vector.
*
* Note that the original uniform velocity vector object associated to
* the instance is returned: changes made to the returned object affect
* the uniform velocity of the instance. You may use the returned object
* to manually control the uniform velocity of the instance.
*
* @method getUniformVelocity
* @return {Object} The instance's uniform velocity vector as an object
* containing three fields, `i`, `j` and `k`, indicating the respective
* components of the vector.
*/
this.getUniformVelocity = function () {
return instance.uniformVelocity;
};
/**
* Returns the full velocity vector of the instance.
*
* The full velocity vector is the velocity vector plus the uniform
* velocity vector.
*
* The vector is returned as an object containing three fields, `i`, `j`
* and `k`, indicating the respective components of the vector.
*
* A new object is created, filled and returned every time this method
* is called; modifying its content does not have any effects on the
* state of the instance. The velocity and uniform velocity of the
* instance must be controlled independently.
*
* @method getFullVelocity
* @return {Object} The instance's full velocity vector as an object
* containing three fields, `i`, `j` and `k`, indicating the respective
* components of the vector.
*/
this.getFullVelocity = (function () {
var fullVelocity = {
i: instance.velocity.i + instance.uniformVelocity.i,
j: instance.velocity.j + instance.uniformVelocity.j,
k: instance.velocity.k + instance.uniformVelocity.k
};
return function () {
fullVelocity.i = instance.velocity.i + instance.uniformVelocity.i;
fullVelocity.j = instance.velocity.j + instance.uniformVelocity.j;
fullVelocity.k = instance.velocity.k + instance.uniformVelocity.k;
return fullVelocity;
};
})();
/**
* Returns the instance's own acceleration vector as an object
* containing three fields, `i`, `j` and `k`, indicating the respective
* components of the vector.
*
* The acceleration vector is initially `(0, 0, 0)`.
*
* Note that the original acceleration vector object associated to the
* instance is returned: changes made to the returned object affect the
* acceleration of the instance. You may use the returned object to
* manually control the acceleration of the instance.
*
* @method getAcceleration
* @return {Object} The instance's acceleration vector as an object
* containing three fields, `i`, `j` and `k`, indicating the respective
* components of the vector.
*/
this.getAcceleration = function () {
return instance.acceleration;
};
/**
* Tests for collisions between this entity instance and the tiles of
* the specified `Canvace.TileMap`.
*
* This method invokes the `Canvace.TileMap.rectangleCollision` using
* the position of the instance, its current full velocity vector and
* the bounding box of its entity, as set in the Canvace Development
* Environment.
*
* This method does not change the state of the instance in any way; it
* only forwards the return value of the
* `Canvace.TileMap.rectangleCollision` method to the caller.
*
* @method testTileCollision
* @param tileMap {Canvace.TileMap} A `Canvace.TileMap` object whose
* tiles are tested for collisions with this entity instance.
* @param dt {Number} TODO
* @param [collides] {Function} An optional user-defined callback
* function that is invoked by the `testTileCollision` method for every
* tile that collides with the instance.
*
* The function receives two arguments, the tile's walkable flag and its
* properties, and must return a boolean value indicating whether the
* tile is "solid" for this instance and must be taken into account as a
* colliding tile. If the function returns `false` the tile is _not_
* taken into account.
* @return {Object} A vector that is computed by the method and can be
* used to restore a "regular" configuration where the entity instance
* does not collide with the tiles.
*
* See the `Canvace.TileMap.rectangleCollision` method for more
* information, the return value is the same.
*/
this.testTileCollision = function (tileMap, dt, collides) {
return tileMap.rectangleCollision(
Math.floor(instance.k),
instance.position.i + entity.box.i0,
instance.position.j + entity.box.j0,
entity.box.iSpan,
entity.box.jSpan,
instance.velocity.i + instance.uniformVelocity.i,
instance.velocity.j + instance.uniformVelocity.j,
instance.acceleration.i,
instance.acceleration.j,
dt,
collides
);
};
/**
* Reacts to possible collisions between this entity instance and the
* tiles of the specified
* {{#crossLink "Canvace.TileMap"}}{{/crossLink}}.
*
* This method invokes the `Canvace.TileMap.rectangleCollision` method
* using the position of the instance, its current full velocity vector
* and the bounding box of its entity, as set in the Canvace Development
* Environment.
*
* It then reacts to the collision by updating the state of the instance
* trying to resume a regular configuration where there is no collision.
*
* Specifically, the position of the instance is updated by adding the I
* and J components of the vector returned by
* `Canvace.TileMap.rectangleCollision` and each one of the I and J
* components of the velocity vector is set to zero only if its sign is
* the opposite of the corresponding component in the vector returned by
* `Canvace.TileMap.rectangleCollision`.
*
* Note that only the velocity vector is changed, the uniform velocity
* vector is not.
*
* The vector returned by `Canvace.TileMap.rectangleCollision` is also
* forwarded to the caller.
*
* @method tileCollision
* @param tileMap {Canvace.TileMap} A `Canvace.TileMap` object whose
* tiles are tested for collisions with this entity instance.
* @param dt {Number} TODO
* @param [collides] {Function} TODO
* @return {Object} The vector object returned by the
* `rectangleCollision` method of
* {{#crossLink "Canvace.TileMap"}}{{/crossLink}}.
*/
this.tileCollision = function (tileMap, dt, collides) {
var v = tileMap.rectangleCollision(
Math.floor(instance.k),
instance.position.i + entity.box.i0,
instance.position.j + entity.box.j0,
entity.box.iSpan,
entity.box.jSpan,
instance.velocity.i + instance.uniformVelocity.i,
instance.velocity.j + instance.uniformVelocity.j,
instance.acceleration.i,
instance.acceleration.j,
dt,
collides
);
instance.position.i += v.i;
instance.position.j += v.j;
if ((v.i > 0) && (instance.velocity.i < 0)) {
instance.velocity.i = 0;
} else if ((v.i < 0) && (instance.velocity.i > 0)) {
instance.velocity.i = 0;
}
if ((v.j > 0) && (instance.velocity.j < 0)) {
instance.velocity.j = 0;
} else if ((v.j < 0) && (instance.velocity.j > 0)) {
instance.velocity.j = 0;
}
return v;
};
/**
* Detects collisions between a rectangular area and the bounding box of
* this entity instance.
*
* A vector is returned indicating two I and J values that must be added
* to the coordinates of the rectangular area in order to resume a
* regular configuration where the area does not collide with the
* instance.
*
* In case there is not any collision, the returned vector is `(0, 0)`.
*
* The rectangular area is specified by the `i`, `j`, `di` and `dj`
* arguments.
*
* The implementation of this method assumes the rectangular area
* represents a moving entity (though not necessarily a Canvace entity)
* which is characterized by its own velocity vector; this vector is
* used in the collision algorithm in that it assumes the moving entity
* cannot have compenetrated the bounding box of this instance along the
* I or J axis more than the velocity vector component for that axis.
* This is necessary in order to obtain a functional physics algorithm.
*
* If the rectangular area actually is the bounding box of a Canvace
* entity, you can specify the I and J components of its actual velocity
* vector for the `vi` and `vj` arguments; such vector can be retrieved
* by adding the two vectors returned by the `getVelocity` and
* `getUniformVelocity` methods.
*
* If specifying a velocity vector is not suitable, you can specify
* arbitrary constant values; a good choice is usually 1 for both `vi`
* and `vj`. However, do not specify 0, as this would _always_ result in
* no collision.
*
* This method can be used to implement in-layer, bounding box based,
* entity vs. entity collisions. If the rectangular area represents an
* entity's bounding box, the `i` and `j` coordinates of its origin can
* be obtained using the `Canvace.Stage.Instance.getPosition` method,
* while the `di` and `dj` span values are usually constant and must be
* arbitrarily determined by the developer.
*
* @method rectangleCollision
* @param i {Number} The I coordinate of the origin of the rectangular
* area. This may be a real number.
* @param j {Number} The J coordinate of the origin of the rectangular
* area. This may be a real number.
* @param di {Number} The span of the rectangular area along the I axis.
* This may be a real number.
* @param dj {Number} The span of the rectangular area along the J axis.
* This may be a real number.
* @param vi {Number} The I component of the velocity vector. This may
* be a real number.
* @param vj {Number} The J component of the velocity vector. This may
* be a real number.
* @param ai {Number} TODO
* @param aj {Number} TODO
* @param dt {Number} TODO
* @return {Object} An object containing two number fields, `i` and `j`,
* specifying the I and J components of the computed vector.
*/
this.rectangleCollision = function (i, j, di, dj, vi, vj, ai, aj, dt) {
var v = {
i: 0,
j: 0
};
if (i < instance.position.i + entity.box.i0) {
if (i + di > instance.position.i + entity.box.i0) {
if (j < instance.position.j + entity.box.j0) {
if (j + dj > instance.position.j + entity.box.j0) {
if (i + di < instance.position.i + entity.box.i0 + entity.box.iSpan) {
v.i = instance.position.i + entity.box.i0 - i - di;
}
if (j + dj < instance.position.j + entity.box.j0 + entity.box.jSpan) {
v.j = instance.position.j + entity.box.j0 - j - dj;
}
}
} else if (j < instance.position.j + entity.box.j0 + entity.box.jSpan) {
if (i + di < instance.position.i + entity.box.i0 + entity.box.iSpan) {
v.i = instance.position.i + entity.box.i0 - i - di;
}
if (j + dj > instance.position.j + entity.box.j0 + entity.box.jSpan) {
v.j = instance.position.j + entity.box.j0 - j - dj;
}
}
}
} else if (i < instance.position.i + entity.box.i0 + entity.box.iSpan) {
if (j < instance.position.j + entity.box.j0) {
if (j + dj > instance.position.j + entity.box.j0) {
v.i = instance.position.i + entity.box.i0 + entity.box.iSpan - i;
if (j + dj < instance.position.j + entity.box.j0 + entity.box.jSpan) {
v.j = instance.position.j + entity.box.j0 - j - dj;
}
}
} else if (j < instance.position.j + entity.box.j0 + entity.box.jSpan) {
if (i + di > instance.position.i + entity.box.i0 + entity.box.iSpan) {
v.i = instance.position.i + entity.box.i0 + entity.box.iSpan - i;
}
if (j + dj > instance.position.j + entity.box.j0 + entity.box.jSpan) {
v.j = instance.position.j + entity.box.j0 + entity.box.jSpan - j;
}
}
}
var dt2 = dt * dt * 0.5;
if (Math.abs(v.i) > Math.abs((instance.velocity.i + instance.uniformVelocity.i - vi) * dt + (instance.acceleration.i - ai) * dt2) + 0.001) {
v.i = 0;
}
if (Math.abs(v.j) > Math.abs((instance.velocity.j + instance.uniformVelocity.j - vj) * dt + (instance.acceleration.j - aj) * dt2) + 0.001) {
v.j = 0;
}
return v;
};
/**
* Tests for collisions between this entity instance and the specified
* one.
*
* This method invokes the `rectangleCollision` method of the specified
* _other_ instance using the position of _this_ instance, its current
* full velocity vector and the bounding box of its entity as set in the
* Canvace Development Environment.
*
* This method does not change the state of the instances in any way; it
* only forwards the return value of the `rectangleCollision` method to
* the caller.
*
* @method testCollision
* @param otherInstance {Canvace.Stage.Instance} Another `Instance`
* object that is tested for collisions with this instance.
* @return {Object} A vector that is computed by the method and can be
* used to restore a "regular" configuration where the specified
* instance does not collide with this instance.
*
* See the `Canvace.Stage.Instance.rectangleCollision` method for more
* information, the return value is the same.
*/
this.testCollision = function (otherInstance, dt) {
return otherInstance.rectangleCollision(
instance.position.i + entity.box.i0,
instance.position.j + entity.box.j0,
entity.box.iSpan,
entity.box.jSpan,
instance.velocity.i + instance.uniformVelocity.i,
instance.velocity.j + instance.uniformVelocity.j,
instance.acceleration.i,
instance.acceleration.j,
dt
);
};
/**
* Reacts to possible collisions between this entity instance and the
* specified one.
*
* This method invokes the `Canvace.Stage.Instance.rectangleCollision`
* method of the specified _other_ instance passing the position of
* _this_ instance, its current full velocity vector and the bounding
* box of its entity as set in the Canvace Development Environment.
*
* It then reacts to the collision by updating the state of _this_
* instance trying to resume a regular configuration where there is no
* collision.
*
* Specifically, the position of the instance is updated by adding the I
* and J components of the vector returned by `rectangleCollision` and
* each one of the I and J components of the velocity vector is set to
* zero only if its sign is the opposite of the corresponding component
* in the vector returned by `rectangleCollision`.
*
* Note that only the velocity vector is changed, the uniform velocity
* vector is not.
*
* The vector returned by `Canvace.Stage.Instance.rectangleCollision`
* is also forwarded to the caller.
*
* @method collision
* @param otherInstance {Canvace.Stage.Instance} Another `Instance`
* object that is tested for collisions with this instance.
* @return {Object} The vector object returned by the
* `Canvace.Stage.Instance.rectangleCollision` method.
*/
this.collision = function (otherInstance, dt) {
var v = otherInstance.rectangleCollision(
instance.position.i + entity.box.i0,
instance.position.j + entity.box.j0,
entity.box.iSpan,
entity.box.jSpan,
instance.velocity.i + instance.uniformVelocity.i,
instance.velocity.j + instance.uniformVelocity.j,
instance.acceleration.i,
instance.acceleration.j,
dt
);
instance.position.i += v.i;
instance.position.j += v.j;
if ((v.i > 0) && (instance.velocity.i < 0)) {
instance.velocity.i = 0;
} else if ((v.i < 0) && (instance.velocity.i > 0)) {
instance.velocity.i = 0;
}
if ((v.j > 0) && (instance.velocity.j < 0)) {
instance.velocity.j = 0;
} else if ((v.j < 0) && (instance.velocity.j > 0)) {
instance.velocity.j = 0;
}
return v;
};
/**
* "Ticks" the instance, updating its position based on its velocity and
* its velocity based on its acceleration.
*
* This method is automatically called by the `Canvace.Stage.tick`
* method if the entity has physics enabled.
*
* @method tick
* @param dt {Number} TODO
*/
this.tick = function (dt) {
var dt2 = dt * dt * 0.5;
instance.position.i += (instance.velocity.i + instance.uniformVelocity.i) * dt + instance.acceleration.i * dt2;
instance.position.j += (instance.velocity.j + instance.uniformVelocity.j) * dt + instance.acceleration.j * dt2;
instance.position.k += (instance.velocity.k + instance.uniformVelocity.k) * dt + instance.acceleration.k * dt2;
instance.velocity.i += instance.acceleration.i * dt;
instance.velocity.j += instance.acceleration.j * dt;
instance.velocity.k += instance.acceleration.k * dt;
};
/**
* Updates the instance so that its graphical representation in
* subsequent renderings reflect its actual position.
*
* Since this method is potentially costly, it should be called only
* once per instance at each iteration of the render loop. This is what
* the `RenderLoop` class does.
*
* This method is automatically called by the `Canvace.Stage.update`
* method if the entity has physics enabled.
*
* @method update
*/
this.update = function () {
element.updatePosition(instance.position.i, instance.position.j, instance.position.k);
};
/**
* Removes the entity instance from the stage. The instance will not be
* rendered any more by subsequent `Renderer.render` calls and will not
* be enumerated any more by the `DefaultRenderer.forEachEntity` method.
*
* This method does not do anything if the instance has already been
* removed or replaced with another entity using the `replaceEntity`
* method.
*
* @method remove
*/
this.remove = function () {
element.remove();
remove();
};
/**
* Replaces this entity instance with a new instance of another entity.
*
* After being replaced, this instance becomes invalid and this object
* should be discarded. The method returns a new `Stage.Instance` object
* that can be used to control the new instance.
*
* The new instance inherits this instance's position, velocity and
* acceleration vectors.
*
* This method throws an exception if it is invoked after the instance
* has been removed or already replaced by a previous call.
*
* @method replaceWith
* @param entity {Canvace.Stage.Entity} An entity to be instantiated
* and whose new instance must replace this one.
* @return {Canvace.Stage.Instance} A new `Stage.Instance` object
* representing the new instance.
*/
this.replaceWith = function (entity) {
if (remove()) {
return new Instance(instance, element.replace(instance.id = entity.getId()));
} else {
throw 'the instance cannot be replaced because it has been removed';
}
};
/**
* Duplicates the instance, also replicating its velocity, uniform
* velocity and acceleration vectors.
*
* An entity may be optionally specified as a `Canvace.Stage.Entity`
* object to the `entity` argument so that the new instance refers to
* another entity.
*
* The new instance is returned as a `Canvace.Stage.Instance` object.
*
* @method fork
* @param [entity] {Canvace.Stage.Entity} An optional entity the new
* instance refers to. The new instance refers to the same entity of
* this instance if this argument is not specified.
* @return {Canvace.Stage.Instance} The new instance.
*/
this.fork = function (entity) {
var id = entity ? entity.getId() : instance.id;
return new Instance({
id: id,
i: instance.i,
j: instance.j,
k: instance.k,
position: {
i: instance.position.i,
j: instance.position.j,
k: instance.position.k
},
velocity: {
i: instance.velocity.i,
j: instance.velocity.j,
k: instance.velocity.k
},
uniformVelocity: {
i: instance.uniformVelocity.i,
j: instance.uniformVelocity.j,
k: instance.uniformVelocity.k
},
acceleration: {
i: instance.acceleration.i,
j: instance.acceleration.j,
k: instance.acceleration.k
},
properties: {}
}, buckets.addEntity(id, instance.position.i, instance.position.j, instance.position.k));
};
} | [
"function Instance(instanceOrId, element) {\n\t\tvar id, instance;\n\t\tif (typeof instanceOrId !== 'number') {\n\t\t\tid = null;\n\t\t\tinstance = instanceOrId;\n\t\t} else {\n\t\t\tid = instanceOrId;\n\t\t\tinstance = data.instances[id];\n\t\t}\n\t\tvar entity = data.entities[instance.id];\n\n\t\tvar remove = instances.add(this);\n\t\tif (entity.enablePhysics) {\n\t\t\tremove = (function (remove1, remove2) {\n\t\t\t\treturn function () {\n\t\t\t\t\treturn remove1() && remove2();\n\t\t\t\t};\n\t\t\t}(remove, instancesWithPhysics.add(this)));\n\t\t}\n\n\t\t/**\n\t\t * Returns the numeric ID of the instance, or `null` if this instance\n\t\t * was not initially present in the JSON data exported from the Canvace\n\t\t * Development Environment and was later added to the stage.\n\t\t *\n\t\t * @method getId\n\t\t * @return {Number} The numeric ID of the instance, or `null` if the\n\t\t * instance has no ID.\n\t\t */\n\t\tthis.getId = function () {\n\t\t\treturn id;\n\t\t};\n\n\t\t/**\n\t\t * Returns the entity instance's custom properties as set in the Canvace\n\t\t * Development Environment.\n\t\t *\n\t\t * The original `properties` object is returned, so that modifications\n\t\t * actually affect the instance's properties.\n\t\t *\n\t\t * @method getProperties\n\t\t * @return {Object} The entity instance's `properties` field containing\n\t\t * the custom properties the user set in the Canvace Development\n\t\t * Environment.\n\t\t */\n\t\tthis.getProperties = function () {\n\t\t\treturn instance.properties;\n\t\t};\n\n\t\t/**\n\t\t * Returns the numeric ID of the entity of this instance.\n\t\t *\n\t\t * @method getEntityId\n\t\t * @return {Number} The numeric ID of the entity of this instance.\n\t\t */\n\t\tthis.getEntityId = function () {\n\t\t\treturn instance.id;\n\t\t};\n\n\t\t/**\n\t\t * Returns a `Canvace.Stage.Entity` object representing the entity whose\n\t\t * instance is represented by this object.\n\t\t *\n\t\t * @method getEntity\n\t\t * @return {Canvace.Stage.Entity} This instance's entity as a\n\t\t * `Canvace.Stage.Entity` object.\n\t\t */\n\t\tthis.getEntity = function () {\n\t\t\treturn entities[instance.id] || new Entity(instance.id);\n\t\t};\n\n\t\t/**\n\t\t * Indicates whether physics is enabled for this instance's entity.\n\t\t *\n\t\t * @method isPhysicsEnabled\n\t\t * @return {Boolean} `true` if physics is enabled, `false` otherwise.\n\t\t */\n\t\tthis.isPhysicsEnabled = function () {\n\t\t\treturn entity.enablePhysics;\n\t\t};\n\n\t\t/**\n\t\t * Returns the instance's `(i, j, k)` position vector as an object\n\t\t * containing three fields, `i`, `j` and `k`.\n\t\t *\n\t\t * Note that the original position vector object associated to the\n\t\t * instance is returned: changes made to the returned object affect the\n\t\t * position of the instance. You may use the returned object to manually\n\t\t * control the position of the instance.\n\t\t *\n\t\t * Also note that changing the position of an instance by modifying the\n\t\t * returned object does not affect its _rendered_ position until the\n\t\t * `update` method is called.\n\t\t *\n\t\t * @method getPosition\n\t\t * @return {Object} An object containing three fields, `i`, `j` and `k`,\n\t\t * indicating the current position.\n\t\t */\n\t\tthis.getPosition = function () {\n\t\t\treturn instance.position;\n\t\t};\n\n\t\t/**\n\t\t * Returns the instance's projected position, which is its `(i, j, k)`\n\t\t * position left-multiplied by the projection matrix.\n\t\t *\n\t\t * Note that this method returns the last calculated projected position,\n\t\t * which means it does not reflect changes made by the `tick` method or\n\t\t * by changing the position, velocity or uniform velocity objects\n\t\t * returned by the `getPosition`, `getVelocity`, and\n\t\t * `getUniformVelocity` methods. For changes to be reflected, the\n\t\t * instance must be first updated using the `update` method.\n\t\t *\n\t\t * The position is returned as an object containing three fields, `x`,\n\t\t * `y` and `z`, containing the `i`, `j` and `k` projected coordinates,\n\t\t * respectively.\n\t\t *\n\t\t * @method getProjectedPosition\n\t\t * @return {Object} The projected position as an object containing three\n\t\t * `x`, `y` and `z` fields.\n\t\t */\n\t\tthis.getProjectedPosition = element.getProjectedPosition.bind(element);\n\n\t\t/**\n\t\t * Returns the 2D rectangular area corresponding to the instances's\n\t\t * bounds.\n\t\t *\n\t\t * Note that this method returns the last calculated projected\n\t\t * rectangle, which means it does not reflect changes made by such\n\t\t * methods as `tick`, `moveBy`, `setPosition` and so on. For changes to\n\t\t * be reflected, the instance must be first updated using the `update`\n\t\t * method.\n\t\t *\n\t\t * The rectangle is returned as an object containing four fields: the\n\t\t * `x` and `y` coordinates of the origin and the `width` and `height`.\n\t\t *\n\t\t * The coordinates of the origin are calculated by left-multiplying the\n\t\t * `(i, j, k)` position vector of the instance by the projection matrix\n\t\t * and adding the entity's offset. The width and height are simply\n\t\t * copied from the entity descriptor.\n\t\t *\n\t\t * @method getProjectedRectangle\n\t\t * @return {Object} An object that describes the projected rectangle and\n\t\t * contains four fields: `x`, `y`, `width` and `height`.\n\t\t */\n\t\tthis.getProjectedRectangle = element.getProjectedRectangle.bind(element);\n\n\t\t/**\n\t\t * Indicates whether the instance is in or out of range.\n\t\t *\n\t\t * An entity instance is in range when its projected position (as\n\t\t * returned by the `getProjectedPosition` method) falls within the\n\t\t * \"range\" area, which is a rectangular area centered in the center of\n\t\t * the viewport. The range area is usually much larger than the viewport\n\t\t * area.\n\t\t *\n\t\t * This method is useful, for example, for discarding too far entity\n\t\t * instances when stepping/ticking the physics of the game in order to\n\t\t * improve performance, and is used by the `Stage.Range` inner class.\n\t\t *\n\t\t * @method inRange\n\t\t * @param width {Number} The width of the range area.\n\t\t * @param height {Number} The height of the range area.\n\t\t * @return {Boolean} `true` if this instance falls within the specified\n\t\t * range area, `false` otherwise.\n\t\t */\n\t\tthis.inRange = (function () {\n\t\t\tvar viewportWidth = view.getWidth();\n\t\t\tvar viewportHeight = view.getHeight();\n\t\t\treturn function (width, height) {\n\t\t\t\tvar position = element.getProjectedPosition();\n\t\t\t\tvar origin = view.getOrigin();\n\t\t\t\tvar frameWidth = (width - viewportWidth) / 2;\n\t\t\t\tvar frameHeight = (height - viewportHeight) / 2;\n\t\t\t\treturn (position.x >= -origin.x - frameWidth) &&\n\t\t\t\t\t(position.x <= -origin.x + viewportWidth + frameWidth) &&\n\t\t\t\t\t(position.y >= -origin.y - frameHeight) &&\n\t\t\t\t\t(position.y <= -origin.y + viewportHeight + frameHeight);\n\t\t\t};\n\t\t}());\n\n\t\t/**\n\t\t * Returns the velocity vector of this instance as an object containing\n\t\t * three fields, `i`, `j` and `k`, indicating the respective components\n\t\t * of the vector. The velocity vector is initially `(0, 0, 0)`.\n\t\t *\n\t\t * This velocity vector is influenced by the acceleration vector of the\n\t\t * instance: the components of the acceleration vector are added to the\n\t\t * respective components of the velocity vector each time the instance\n\t\t * is ticked using the `tick` method.\n\t\t *\n\t\t * Note that the original velocity vector object associated to the\n\t\t * instance is returned: changes made to the returned object affect the\n\t\t * velocity of the instance. You may use the returned object to manually\n\t\t * control the velocity of the instance.\n\t\t *\n\t\t * @method getVelocity\n\t\t * @return {Object} The instance's velocity vector as an object\n\t\t * containing three fields, `i`, `j` and `k`, indicating the respective\n\t\t * components of the vector.\n\t\t */\n\t\tthis.getVelocity = function () {\n\t\t\treturn instance.velocity;\n\t\t};\n\n\t\t/**\n\t\t * Returns the uniform velocity vector of this instance.\n\t\t *\n\t\t * The vector is returned as an object containing three fields, `i`, `j`\n\t\t * and `k`, indicating the respective components of the vector.\n\t\t *\n\t\t * Note that the original uniform velocity vector object associated to\n\t\t * the instance is returned: changes made to the returned object affect\n\t\t * the uniform velocity of the instance. You may use the returned object\n\t\t * to manually control the uniform velocity of the instance.\n\t\t *\n\t\t * @method getUniformVelocity\n\t\t * @return {Object} The instance's uniform velocity vector as an object\n\t\t * containing three fields, `i`, `j` and `k`, indicating the respective\n\t\t * components of the vector.\n\t\t */\n\t\tthis.getUniformVelocity = function () {\n\t\t\treturn instance.uniformVelocity;\n\t\t};\n\n\t\t/**\n\t\t * Returns the full velocity vector of the instance.\n\t\t *\n\t\t * The full velocity vector is the velocity vector plus the uniform\n\t\t * velocity vector.\n\t\t *\n\t\t * The vector is returned as an object containing three fields, `i`, `j`\n\t\t * and `k`, indicating the respective components of the vector.\n\t\t *\n\t\t * A new object is created, filled and returned every time this method\n\t\t * is called; modifying its content does not have any effects on the\n\t\t * state of the instance. The velocity and uniform velocity of the\n\t\t * instance must be controlled independently.\n\t\t *\n\t\t * @method getFullVelocity\n\t\t * @return {Object} The instance's full velocity vector as an object\n\t\t * containing three fields, `i`, `j` and `k`, indicating the respective\n\t\t * components of the vector.\n\t\t */\n\t\tthis.getFullVelocity = (function () {\n\t\t\tvar fullVelocity = {\n\t\t\t\ti: instance.velocity.i + instance.uniformVelocity.i,\n\t\t\t\tj: instance.velocity.j + instance.uniformVelocity.j,\n\t\t\t\tk: instance.velocity.k + instance.uniformVelocity.k\n\t\t\t};\n\t\t\treturn function () {\n\t\t\t\tfullVelocity.i = instance.velocity.i + instance.uniformVelocity.i;\n\t\t\t\tfullVelocity.j = instance.velocity.j + instance.uniformVelocity.j;\n\t\t\t\tfullVelocity.k = instance.velocity.k + instance.uniformVelocity.k;\n\t\t\t\treturn fullVelocity;\n\t\t\t};\n\t\t}());\n\n\t\t/**\n\t\t * Returns the instance's own acceleration vector as an object\n\t\t * containing three fields, `i`, `j` and `k`, indicating the respective\n\t\t * components of the vector.\n\t\t *\n\t\t * The acceleration vector is initially `(0, 0, 0)`.\n\t\t *\n\t\t * Note that the original acceleration vector object associated to the\n\t\t * instance is returned: changes made to the returned object affect the\n\t\t * acceleration of the instance. You may use the returned object to\n\t\t * manually control the acceleration of the instance.\n\t\t *\n\t\t * @method getAcceleration\n\t\t * @return {Object} The instance's acceleration vector as an object\n\t\t * containing three fields, `i`, `j` and `k`, indicating the respective\n\t\t * components of the vector.\n\t\t */\n\t\tthis.getAcceleration = function () {\n\t\t\treturn instance.acceleration;\n\t\t};\n\n\t\t/**\n\t\t * Tests for collisions between this entity instance and the tiles of\n\t\t * the specified `Canvace.TileMap`.\n\t\t *\n\t\t * This method invokes the `Canvace.TileMap.rectangleCollision` using\n\t\t * the position of the instance, its current full velocity vector and\n\t\t * the bounding box of its entity, as set in the Canvace Development\n\t\t * Environment.\n\t\t *\n\t\t * This method does not change the state of the instance in any way; it\n\t\t * only forwards the return value of the\n\t\t * `Canvace.TileMap.rectangleCollision` method to the caller.\n\t\t *\n\t\t * @method testTileCollision\n\t\t * @param [collides] {Function} An optional user-defined callback\n\t\t * function that is invoked by the `testTileCollision` method for every\n\t\t * tile that collides with the instance.\n\t\t *\n\t\t * The function receives two arguments, the tile's solid flag and its\n\t\t * properties, and must return a boolean value indicating whether the\n\t\t * tile is \"solid\" for this instance and must be taken into account as a\n\t\t * colliding tile. If the function returns `false` the tile is _not_\n\t\t * taken into account.\n\t\t * @param [tileMap] {Canvace.TileMap} An optional `Canvace.TileMap`\n\t\t * object whose tiles are tested for collisions with this entity\n\t\t * instance. When not specified, this stage's tile map is used.\n\t\t * @return {Object} A vector that is computed by the method and can be\n\t\t * used to restore a \"regular\" configuration where the entity instance\n\t\t * does not collide with the tiles.\n\t\t *\n\t\t * See the `Canvace.TileMap.rectangleCollision` method for more\n\t\t * information, the return value is the same.\n\t\t */\n\t\tthis.testTileCollision = function (collides, tileMap) {\n\t\t\treturn (tileMap || map).rectangleCollision(\n\t\t\t\tMath.floor(instance.k),\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j,\n\t\t\t\tcollides\n\t\t\t\t);\n\t\t};\n\n\t\t/**\n\t\t * Reacts to possible collisions between this entity instance and the\n\t\t * tiles of the specified\n\t\t * {{#crossLink \"Canvace.TileMap\"}}{{/crossLink}}.\n\t\t *\n\t\t * This method invokes the `Canvace.TileMap.rectangleCollision` method\n\t\t * using the position of the instance, its current full velocity vector\n\t\t * and the bounding box of its entity, as set in the Canvace Development\n\t\t * Environment.\n\t\t *\n\t\t * It then reacts to the collision by updating the state of the instance\n\t\t * trying to resume a regular configuration where there is no collision.\n\t\t *\n\t\t * Specifically, the position of the instance is updated by adding the I\n\t\t * and J components of the vector returned by\n\t\t * `Canvace.TileMap.rectangleCollision` and each one of the I and J\n\t\t * components of the velocity vector is set to zero only if its sign is\n\t\t * the opposite of the corresponding component in the vector returned by\n\t\t * `Canvace.TileMap.rectangleCollision`.\n\t\t *\n\t\t * Note that only the velocity vector is changed, the uniform velocity\n\t\t * vector is not.\n\t\t *\n\t\t * The vector returned by `Canvace.TileMap.rectangleCollision` is also\n\t\t * forwarded to the caller.\n\t\t *\n\t\t * @method tileCollision\n\t\t * @param [collides] {Function} TODO\n\t\t * @param [tileMap] {Canvace.TileMap} A `Canvace.TileMap` object whose\n\t\t * tiles are tested for collisions with this entity instance.\n\t\t * @return {Object} The vector object returned by the\n\t\t * `rectangleCollision` method of\n\t\t * {{#crossLink \"Canvace.TileMap\"}}{{/crossLink}}.\n\t\t */\n\t\tthis.tileCollision = function (collides, tileMap) {\n\t\t\tvar v = (tileMap || map).rectangleCollision(\n\t\t\t\tMath.floor(instance.k),\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j,\n\t\t\t\tcollides\n\t\t\t\t);\n\t\t\tinstance.position.i += v.i;\n\t\t\tinstance.position.j += v.j;\n\t\t\tif ((v.i > 0) && (instance.velocity.i < 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t} else if ((v.i < 0) && (instance.velocity.i > 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t}\n\t\t\tif ((v.j > 0) && (instance.velocity.j < 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t} else if ((v.j < 0) && (instance.velocity.j > 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t}\n\t\t\treturn v;\n\t\t};\n\n\t\t/**\n\t\t * TODO\n\t\t *\n\t\t * @method collidesWithTiles\n\t\t * @param [collides] {Function} TODO\n\t\t * @param [tileMap] {Canvace.TileMap} TODO\n\t\t * @return {Boolean} TODO\n\t\t */\n\t\tthis.collidesWithTiles = function (collides, tileMap) {\n\t\t\tvar v = (tileMap || map).rectangleCollision(\n\t\t\t\tMath.floor(instance.k),\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j,\n\t\t\t\tcollides\n\t\t\t\t);\n\t\t\tinstance.position.i += v.i;\n\t\t\tinstance.position.j += v.j;\n\t\t\tif ((v.i > 0) && (instance.velocity.i < 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t} else if ((v.i < 0) && (instance.velocity.i > 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t}\n\t\t\tif ((v.j > 0) && (instance.velocity.j < 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t} else if ((v.j < 0) && (instance.velocity.j > 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t}\n\t\t\treturn v.i || v.j;\n\t\t};\n\n\t\t/**\n\t\t * Detects collisions between a rectangular area and the bounding box of\n\t\t * this entity instance.\n\t\t *\n\t\t * A vector is returned indicating two I and J values that must be added\n\t\t * to the coordinates of the rectangular area in order to resume a\n\t\t * regular configuration where the area does not collide with the\n\t\t * instance.\n\t\t *\n\t\t * In case there is not any collision, the returned vector is `(0, 0)`.\n\t\t *\n\t\t * The rectangular area is specified by the `i`, `j`, `di` and `dj`\n\t\t * arguments.\n\t\t *\n\t\t * The implementation of this method assumes the rectangular area\n\t\t * represents a moving entity (though not necessarily a Canvace entity)\n\t\t * which is characterized by its own velocity vector; this vector is\n\t\t * used in the collision algorithm in that it assumes the moving entity\n\t\t * cannot have compenetrated the bounding box of this instance along the\n\t\t * I or J axis more than the velocity vector component for that axis.\n\t\t * This is necessary in order to obtain a functional physics algorithm.\n\t\t *\n\t\t * If the rectangular area actually is the bounding box of a Canvace\n\t\t * entity, you can specify the I and J components of its actual velocity\n\t\t * vector for the `vi` and `vj` arguments; such vector can be retrieved\n\t\t * by adding the two vectors returned by the `getVelocity` and\n\t\t * `getUniformVelocity` methods.\n\t\t *\n\t\t * If specifying a velocity vector is not suitable, you can specify\n\t\t * arbitrary constant values; a good choice is usually 1 for both `vi`\n\t\t * and `vj`. However, do not specify 0, as this would _always_ result in\n\t\t * no collision.\n\t\t *\n\t\t * This method can be used to implement in-layer, bounding box based,\n\t\t * entity vs. entity collisions. If the rectangular area represents an\n\t\t * entity's bounding box, the `i` and `j` coordinates of its origin can\n\t\t * be obtained using the `Canvace.Stage.Instance.getPosition` method,\n\t\t * while the `di` and `dj` span values are usually constant and must be\n\t\t * arbitrarily determined by the developer.\n\t\t *\n\t\t * @method rectangleCollision\n\t\t * @param i {Number} The I coordinate of the origin of the rectangular\n\t\t * area. This may be a real number.\n\t\t * @param j {Number} The J coordinate of the origin of the rectangular\n\t\t * area. This may be a real number.\n\t\t * @param di {Number} The span of the rectangular area along the I axis.\n\t\t * This may be a real number.\n\t\t * @param dj {Number} The span of the rectangular area along the J axis.\n\t\t * This may be a real number.\n\t\t * @param Di {Number} TODO\n\t\t * @param Dj {Number} TODO\n\t\t * @return {Object} An object containing two number fields, `i` and `j`,\n\t\t * specifying the I and J components of the computed vector.\n\t\t */\n\t\tthis.rectangleCollision = function (i, j, di, dj, Di, Dj) {\n\t\t\tvar v = {\n\t\t\t\ti: 0,\n\t\t\t\tj: 0\n\t\t\t};\n\t\t\tif (i < instance.position.i + entity.box.i0) {\n\t\t\t\tif (i + di > instance.position.i + entity.box.i0) {\n\t\t\t\t\tif (j < instance.position.j + entity.box.j0) {\n\t\t\t\t\t\tif (j + dj > instance.position.j + entity.box.j0) {\n\t\t\t\t\t\t\tif (i + di < instance.position.i + entity.box.i0 + entity.box.iSpan) {\n\t\t\t\t\t\t\t\tv.i = instance.position.i + entity.box.i0 - i - di;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (j + dj < instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\t\t\t\tv.j = instance.position.j + entity.box.j0 - j - dj;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (j < instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\t\tif (i + di < instance.position.i + entity.box.i0 + entity.box.iSpan) {\n\t\t\t\t\t\t\tv.i = instance.position.i + entity.box.i0 - i - di;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (j + dj > instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\t\t\tv.j = instance.position.j + entity.box.j0 - j - dj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (i < instance.position.i + entity.box.i0 + entity.box.iSpan) {\n\t\t\t\tif (j < instance.position.j + entity.box.j0) {\n\t\t\t\t\tif (j + dj > instance.position.j + entity.box.j0) {\n\t\t\t\t\t\tv.i = instance.position.i + entity.box.i0 + entity.box.iSpan - i;\n\t\t\t\t\t\tif (j + dj < instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\t\t\tv.j = instance.position.j + entity.box.j0 - j - dj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (j < instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\tif (i + di > instance.position.i + entity.box.i0 + entity.box.iSpan) {\n\t\t\t\t\t\tv.i = instance.position.i + entity.box.i0 + entity.box.iSpan - i;\n\t\t\t\t\t}\n\t\t\t\t\tif (j + dj > instance.position.j + entity.box.j0 + entity.box.jSpan) {\n\t\t\t\t\t\tv.j = instance.position.j + entity.box.j0 + entity.box.jSpan - j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (Math.abs(v.i) > Math.abs(instance.position.i - instance.previousPosition.i - Di) + 0.001) {\n\t\t\t\tv.i = 0;\n\t\t\t}\n\t\t\tif (Math.abs(v.j) > Math.abs(instance.position.j - instance.previousPosition.j - Dj) + 0.001) {\n\t\t\t\tv.j = 0;\n\t\t\t}\n\t\t\treturn v;\n\t\t};\n\n\t\t/**\n\t\t * Tests for collisions between this entity instance and the specified\n\t\t * one.\n\t\t *\n\t\t * This method invokes the `rectangleCollision` method of the specified\n\t\t * _other_ instance using the position of _this_ instance, its current\n\t\t * full velocity vector and the bounding box of its entity as set in the\n\t\t * Canvace Development Environment.\n\t\t *\n\t\t * This method does not change the state of the instances in any way; it\n\t\t * only forwards the return value of the `rectangleCollision` method to\n\t\t * the caller.\n\t\t *\n\t\t * @method testCollision\n\t\t * @param otherInstance {Canvace.Stage.Instance} Another `Instance`\n\t\t * object that is tested for collisions with this instance.\n\t\t * @return {Object} A vector that is computed by the method and can be\n\t\t * used to restore a \"regular\" configuration where the specified\n\t\t * instance does not collide with this instance.\n\t\t *\n\t\t * See the `Canvace.Stage.Instance.rectangleCollision` method for more\n\t\t * information, the return value is the same.\n\t\t */\n\t\tthis.testCollision = function (otherInstance) {\n\t\t\treturn otherInstance.rectangleCollision(\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j\n\t\t\t\t);\n\t\t};\n\n\t\t/**\n\t\t * Reacts to possible collisions between this entity instance and the\n\t\t * specified one.\n\t\t *\n\t\t * This method invokes the `Canvace.Stage.Instance.rectangleCollision`\n\t\t * method of the specified _other_ instance passing the position of\n\t\t * _this_ instance, its current full velocity vector and the bounding\n\t\t * box of its entity as set in the Canvace Development Environment.\n\t\t *\n\t\t * It then reacts to the collision by updating the state of _this_\n\t\t * instance trying to resume a regular configuration where there is no\n\t\t * collision.\n\t\t *\n\t\t * Specifically, the position of the instance is updated by adding the I\n\t\t * and J components of the vector returned by `rectangleCollision` and\n\t\t * each one of the I and J components of the velocity vector is set to\n\t\t * zero only if its sign is the opposite of the corresponding component\n\t\t * in the vector returned by `rectangleCollision`.\n\t\t *\n\t\t * Note that only the velocity vector is changed, the uniform velocity\n\t\t * vector is not.\n\t\t *\n\t\t * The vector returned by `Canvace.Stage.Instance.rectangleCollision`\n\t\t * is also forwarded to the caller.\n\t\t *\n\t\t * @method collision\n\t\t * @param otherInstance {Canvace.Stage.Instance} Another `Instance`\n\t\t * object that is tested for collisions with this instance.\n\t\t * @return {Object} The vector object returned by the\n\t\t * `Canvace.Stage.Instance.rectangleCollision` method.\n\t\t */\n\t\tthis.collision = function (otherInstance) {\n\t\t\tvar v = otherInstance.rectangleCollision(\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j\n\t\t\t\t);\n\t\t\tinstance.position.i += v.i;\n\t\t\tinstance.position.j += v.j;\n\t\t\tif ((v.i > 0) && (instance.velocity.i < 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t} else if ((v.i < 0) && (instance.velocity.i > 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t}\n\t\t\tif ((v.j > 0) && (instance.velocity.j < 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t} else if ((v.j < 0) && (instance.velocity.j > 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t}\n\t\t\treturn v;\n\t\t};\n\n\t\t/**\n\t\t * TODO\n\t\t *\n\t\t * @method collidesWithInstance\n\t\t * @param otherInstance {Canvace.Instance} TODO\n\t\t * @return {Boolean} TODO\n\t\t */\n\t\tthis.collidesWithInstance = function (otherInstance) {\n\t\t\tvar v = otherInstance.rectangleCollision(\n\t\t\t\tinstance.position.i + entity.box.i0,\n\t\t\t\tinstance.position.j + entity.box.j0,\n\t\t\t\tentity.box.iSpan,\n\t\t\t\tentity.box.jSpan,\n\t\t\t\tinstance.position.i - instance.previousPosition.i,\n\t\t\t\tinstance.position.j - instance.previousPosition.j\n\t\t\t\t);\n\t\t\tinstance.position.i += v.i;\n\t\t\tinstance.position.j += v.j;\n\t\t\tif ((v.i > 0) && (instance.velocity.i < 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t} else if ((v.i < 0) && (instance.velocity.i > 0)) {\n\t\t\t\tinstance.velocity.i = 0;\n\t\t\t}\n\t\t\tif ((v.j > 0) && (instance.velocity.j < 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t} else if ((v.j < 0) && (instance.velocity.j > 0)) {\n\t\t\t\tinstance.velocity.j = 0;\n\t\t\t}\n\t\t\treturn v.i || v.j;\n\t\t};\n\n\t\t/**\n\t\t * \"Ticks\" the instance, updating its position based on its velocity and\n\t\t * its velocity based on its acceleration.\n\t\t *\n\t\t * This method is automatically called by the `Canvace.Stage.tick`\n\t\t * method if the entity has physics enabled.\n\t\t *\n\t\t * @method tick\n\t\t * @param dt {Number} TODO\n\t\t */\n\t\tthis.tick = function (dt) {\n\t\t\tvar dt2 = dt * dt * 0.5;\n\t\t\tinstance.previousPosition.i = instance.position.i;\n\t\t\tinstance.previousPosition.j = instance.position.j;\n\t\t\tinstance.previousPosition.k = instance.position.k;\n\t\t\tinstance.position.i += (instance.velocity.i + instance.uniformVelocity.i) * dt + instance.acceleration.i * dt2;\n\t\t\tinstance.position.j += (instance.velocity.j + instance.uniformVelocity.j) * dt + instance.acceleration.j * dt2;\n\t\t\tinstance.position.k += (instance.velocity.k + instance.uniformVelocity.k) * dt + instance.acceleration.k * dt2;\n\t\t\tinstance.velocity.i += instance.acceleration.i * dt;\n\t\t\tinstance.velocity.j += instance.acceleration.j * dt;\n\t\t\tinstance.velocity.k += instance.acceleration.k * dt;\n\t\t};\n\n\t\t/**\n\t\t * Updates the instance so that its graphical representation in\n\t\t * subsequent renderings reflect its actual position.\n\t\t *\n\t\t * Since this method is potentially costly, it should be called only\n\t\t * once per instance at each iteration of the render loop. This is what\n\t\t * the `RenderLoop` class does.\n\t\t *\n\t\t * This method is automatically called by the `Canvace.Stage.update`\n\t\t * method if the entity has physics enabled.\n\t\t *\n\t\t * @method update\n\t\t */\n\t\tthis.update = function () {\n\t\t\telement.updatePosition(instance.position.i, instance.position.j, instance.position.k);\n\t\t};\n\n\t\t/**\n\t\t * Removes the entity instance from the stage. The instance will not be\n\t\t * rendered any more by subsequent `Renderer.render` calls and will not\n\t\t * be enumerated any more by the `Buckets.forEachElement` method.\n\t\t *\n\t\t * This method does not do anything if the instance has already been\n\t\t * removed or replaced with another entity using the `replaceWith`\n\t\t * method.\n\t\t *\n\t\t * @method remove\n\t\t */\n\t\tthis.remove = function () {\n\t\t\telement.remove();\n\t\t\tremove();\n\t\t};\n\n\t\t/**\n\t\t * Indicates whether this instance has been removed from the stage.\n\t\t *\n\t\t * @method isRemoved\n\t\t * @return {Boolean} `true` if this instance has been removed, `false`\n\t\t * otherwise.\n\t\t */\n\t\tthis.isRemoved = element.isRemoved.bind(element);\n\n\t\t/**\n\t\t * Replaces this entity instance with a new instance of another entity.\n\t\t *\n\t\t * After being replaced, this instance becomes invalid and this object\n\t\t * should be discarded. The method returns a new `Stage.Instance` object\n\t\t * that can be used to control the new instance.\n\t\t *\n\t\t * The new instance inherits this instance's position, velocity and\n\t\t * acceleration vectors.\n\t\t *\n\t\t * This method throws an exception if it is invoked after the instance\n\t\t * has been removed or already replaced by a previous call.\n\t\t *\n\t\t * @method replaceWith\n\t\t * @param entity {Canvace.Stage.Entity} An entity to be instantiated\n\t\t * and whose new instance must replace this one.\n\t\t * @return {Canvace.Stage.Instance} A new `Stage.Instance` object\n\t\t * representing the new instance.\n\t\t */\n\t\tthis.replaceWith = function (entity) {\n\t\t\tif (remove()) {\n\t\t\t\treturn new Instance(instance, element.replace(instance.id = entity.getId()));\n\t\t\t} else {\n\t\t\t\tthrow 'the instance cannot be replaced because it has been removed';\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Duplicates the instance, also replicating its velocity, uniform\n\t\t * velocity and acceleration vectors.\n\t\t *\n\t\t * An entity may be optionally specified as a `Canvace.Stage.Entity`\n\t\t * object to the `entity` argument so that the new instance refers to\n\t\t * another entity.\n\t\t *\n\t\t * The new instance is returned as a `Canvace.Stage.Instance` object.\n\t\t *\n\t\t * @method fork\n\t\t * @param [entity] {Canvace.Stage.Entity} An optional entity the new\n\t\t * instance refers to. The new instance refers to the same entity of\n\t\t * this instance if this argument is not specified.\n\t\t * @return {Canvace.Stage.Instance} The new instance.\n\t\t */\n\t\tthis.fork = function (entity) {\n\t\t\tvar id = entity ? entity.getId() : instance.id;\n\t\t\treturn new Instance({\n\t\t\t\tid: id,\n\t\t\t\ti: instance.i,\n\t\t\t\tj: instance.j,\n\t\t\t\tk: instance.k,\n\t\t\t\tposition: {\n\t\t\t\t\ti: instance.position.i,\n\t\t\t\t\tj: instance.position.j,\n\t\t\t\t\tk: instance.position.k\n\t\t\t\t},\n\t\t\t\tpreviousPosition: {\n\t\t\t\t\ti: instance.previousPosition.i,\n\t\t\t\t\tj: instance.previousPosition.j,\n\t\t\t\t\tk: instance.previousPosition.k\n\t\t\t\t},\n\t\t\t\tvelocity: {\n\t\t\t\t\ti: instance.velocity.i,\n\t\t\t\t\tj: instance.velocity.j,\n\t\t\t\t\tk: instance.velocity.k\n\t\t\t\t},\n\t\t\t\tuniformVelocity: {\n\t\t\t\t\ti: instance.uniformVelocity.i,\n\t\t\t\t\tj: instance.uniformVelocity.j,\n\t\t\t\t\tk: instance.uniformVelocity.k\n\t\t\t\t},\n\t\t\t\tacceleration: {\n\t\t\t\t\ti: instance.acceleration.i,\n\t\t\t\t\tj: instance.acceleration.j,\n\t\t\t\t\tk: instance.acceleration.k\n\t\t\t\t},\n\t\t\t\tproperties: {}\n\t\t\t}, buckets.addEntity(id, instance.position.i, instance.position.j, instance.position.k));\n\t\t};\n\t}",
"function Entity() {\n /* WARNING:\n Don't modify this internal object from the outside of the Entity.\n Instead use Entity properties and functions to modify these values\n as this allows for the internal information to update itself and keep it\n correct.\n */\n this.__Internal__Dont__Modify__ = {\n //Flag if the entity is alive or dead\n alive: true,\n\n //Store an animator for the entity\n animator: new AnimationController(),\n\n //Store the position of the entity within the world\n position: new Vec2(),\n\n //Store the dimensions of the Entity\n width: 0,\n height: 0,\n\n //Store offset values in order to update the animator\n movementOffset: new Vec2(),\n }\n}",
"static update() {\n this._jetpackParticles.updatePosition(this.entity.x, this.entity.y);\n }",
"tick() {\n super.tick();\n\n // Allow all entities to update their position\n this.fieldController.getEntities().forEach(function (key, entity) {\n entity.updatePosition(this.speedFactor, this.gameClock, this.gameTick);\n }, this);\n\n // Create a new world-entity-description,\n this.netChannel.tick(this.gameClock, new WorldEntityDescription(this, this.fieldController.getEntities()));\n\n if (this.gameClock > this.gameDuration) {\n this.shouldEndGame();\n }\n }",
"function Entity(/*attribute templates*/) {\n this.getState = function() {\n console.log(\"TODO: implement update!!!\");\n };\n this.update = function(delta, game) {\n console.log(\"TODO: implement update!!!\");\n // This function has two purposes:\n // 1. Update the state of this Entity\n // 2. Queue an action to the Game to be applied after all Entities \n // have had a chance to update by returning a callback function.\n // Per design, this function should not modify the Game directly,\n // instead through the use of the callback function (i.e. 'game'\n // and 'entities' should be treated as readonly within this function).\n };\n this.getOwner = function() {\n console.log(\"TODO: implement update!!!\");\n };\n\n let id = u.guid();\n this.getId = function() {\n return id;\n };\n\n this.isDead = false;\n\n // Put this at the end of this function so that update() gets assigned \n // along with other properties\n Object.assign(this, ...arguments);\n}",
"function Entity(instance, state) {\n\n //Public variables\n this.state = state; //A local cache of the database record representing this entity's state\n //This data is what gets written to both the DB and the client.\n // Put only dicts, arrays and pods in here, no fancy object types.\n this.type = null; //Static entity type information\n this.emitter = new EventEmitter(); //Event emitter for sending events\n this.instance = instance; //A reference to the region instance this entity is in\n\n\n //Only set if entity has a player object\n this.player = null;\n\n //Server-side only variables\n this.persistent = true; //If set, entity gets stored to db. This is done using copy-on-write semantics.\n this.net_replicated = true; //If set, then the entity gets sent across the network\n // Useful for objects that are important for the client or have long lives.\n this.net_cache = true; //If set along with net_replicated, keep track of entity state for each player to delta encode updates. \n // Useful for big entities with, small frequently changing variables.\n this.net_one_shot = false; //If set, only replicate entity creation event. Do not synchronize after creation.\n // Useful for projectiles and other shortly lived objects\n this.net_priority = 1.0; //Replication priority\n this.last_state = {}; //Last state entity was in\n this.deleted = false; //When set, the entity has been marked for deletion. This object reference is just a zombie\n this.dirty = false; //If set, the entity has pending writes and will be moved to DB at next sync point\n}",
"function Entity () {\n /**\n * Unique identifier.\n */\n this.id = nextId++\n\n /**\n * Ref to the manager for this facade, injected right after being\n * instantiated.\n * @private\n */\n this._manager = null\n\n /**\n * List of all the types of components on this entity.\n * @type {Array.<Function>}\n * @private\n */\n this._Components = []\n\n /**\n * All tags that this entity currently has.\n * @type {Array.<String>}\n * @private\n */\n this._tags = []\n\n // All entities are event emitters.\n EventEmitter.call(this)\n}",
"constructor(engine, x, y, vx, vy) {\n this.engine = engine;\n this.x = x;\n this.y = y;\n this.vx = vx;\n this.vy = vy;\n\n this.isColliding = false;\n }",
"function PhysicsInstance(node, component)\r\n{\r\n\tthis.uid = LS.generateUId(\"PHSX\"); //unique identifier for this RI\r\n\r\n\tthis.type = PhysicsInstance.BOX;\r\n\tthis.mesh = null; \r\n\r\n\t//where does it come from\r\n\tthis.node = node;\r\n\tthis.component = component;\r\n\r\n\t//transformation\r\n\tthis.matrix = mat4.create();\r\n\tthis.center = vec3.create();\r\n\r\n\t//for visibility computation\r\n\tthis.oobb = BBox.create(); //object space bounding box\r\n\tthis.aabb = BBox.create(); //axis aligned bounding box\r\n}",
"function Entity() {\n this._components = [];\n}",
"update ()\n {\n let cType = 0;\n if (this.useCEngine === true)\n {\n cType = this.CEngine.cType;\n }\n const inputSys = this.input;\n for (let i = 0, length = this.inputs.length; i < length; ++i)\n {\n const input = this.inputs[i];\n if (input.continuous === true)\n {\n if (inputSys.isPressed(input.key) === true)\n {\n input.active = true;\n input.onPress(this.runTime, input.parameter);\n }\n else if (input.active === true)\n {\n input.active = false;\n input.onRelease(this.runTime, input.parameter);\n }\n }\n else if (input.active === false)\n {\n if (inputSys.isPressed(input.key) === true)\n {\n input.active = true;\n input.onPress(this.runTime, input.parameter);\n }\n }\n else if (inputSys.isPressed(input.key) === false)\n {\n input.active = false;\n input.onRelease(this.runTime, input.parameter);\n }\n }\n\n let entity;\n let stopped = false;\n let vec = [0, 0];\n let pVec = [0, 0];\n let dX = 0;\n let dY = 0;\n let collisions;\n this.waiting = 0;\n for (let i = 0, length = this.entities.length; i < length; ++i)\n {\n stopped = false;\n entity = this.entities[i];\n if (entity.frozen === true)\n {\n if (entity.frame !== 0 && entity._sprite.dirs[entity.dir].reset > -1)\n {\n if (entity.ticks > entity._sprite.dirs[entity.dir].reset)\n {\n entity.frame = 0;\n entity.ticks = 0;\n entity.needsUpdate = true;\n }\n else\n {\n ++entity.ticks;\n }\n }\n }\n else if (entity.end === entity.insert)\n {\n entity.scripts.onIdle(this.runTime, entity);\n if (entity.end === entity.insert)\n {\n if (entity.frame !== 0 && entity._sprite.dirs[entity.dir].reset > -1)\n {\n if (entity.ticks > entity._sprite.dirs[entity.dir].reset)\n {\n entity.frame = 0;\n entity.ticks = 0;\n entity.needsUpdate = true;\n }\n else\n {\n ++entity.ticks;\n }\n }\n ++this.waiting;\n }\n }\n else\n {\n const action = entity.queue[entity.end];\n if (action.type === spriteMOVE || action.type === spriteANIMATE)\n {//individual conditions to avoid dependence on ordering\n if (entity._sprite.dir_Id[entity.queue[entity.end].direction] !== entity.dir)\n {\n entity.ticks = 0;\n entity.frame = 0;\n entity.dir = entity._sprite.dir_Id[entity.queue[entity.end].direction];\n entity.needsUpdate = true;\n }\n else\n {\n entity.ticks = (entity.ticks + 1) % entity._sprite.dirs[entity.dir].dt;\n if (entity.ticks === 0)\n {\n entity.frame = (entity.frame + 1) % entity._sprite.dirs[entity.dir].frames.length;\n entity.needsUpdate = true;\n }\n }\n }\n if (action.type === spriteMOVE)\n {\n vec = entity._vectors[entity.dir];\n pVec = entity._pVectors[entity.dir];\n if (this.tileMovement === true && action.pos < this.tSize)\n {\n if (action.pos === 0 && this.useCEngine === true)\n {//#FIX ME the +1 stuff should be gone\n collisions = this.CEngine.collide(i + 1, entity.internalLayer, entity._x, entity._y, vec[0], vec[1], entity.poly);\n if (collisions.length > 0)\n {\n for (let j = 0; j < collisions.length; ++j)\n {\n if (collisions[j].type === 0)\n {\n stopped = true;\n const collidedWith = this.entities[collisions[j].ref];\n if (collidedWith.attached === true)\n {\n entity.scripts.onTouchPlayer(this.runTime, entity, collidedWith);\n }\n else\n {\n entity.scripts.onTouchOther(this.runTime, entity, collidedWith);\n }\n }\n else if (collisions[j].type === 1)\n {\n stopped = true;\n }\n else if (collisions[j].type === 2)\n {\n const collidedWith = this.entities[collisions[j].ref];\n if (collidedWith.attached === true)\n {\n collisions[j].scripts.onTouchPlayer(this.runTime, entity);\n }\n else\n {\n collisions[j].scripts.onTouchOther(this.runTime, entity);\n }\n }\n }\n }\n if (stopped === true)\n {\n --action.ticks;\n }\n else\n {\n if (cType === 0)\n {\n if (entity.tile_x + vec[0] >= 0 && entity.tile_y + vec[1] >= 0)\n {\n this.tObs[entity.internalLayer][entity.tile_x + vec[0]][entity.tile_y + vec[1]] = i + 1;\n }\n }\n else if (cType === 1)\n {\n throw new SEngineError(\"attempt to use tile based movement with polygon based collisions - this is not yet supported\");\n }\n }\n }\n if (stopped === false)\n {\n ++action.pos;\n }\n }\n else\n {\n --action.ticks;\n action.pos = 0;\n if (this.tileMovement === true)\n {\n if (this.useCEngine && entity.tile_x >= 0 && entity.tile_y >= 0)\n {\n this.tObs[entity.internalLayer][entity.tile_x][entity.tile_y] = 0;\n }\n entity.tile_x = Math.floor(entity._x * this._tFract);\n entity.tile_y = Math.floor(entity._y * this._tFract);\n stopped = true;\n }\n else if (this.useCEngine === true)\n {\n dX = (entity._px + pVec[0] >> 7) - entity._x;\n dY = (entity._py + pVec[1] >> 7) - entity._y;\n\n collisions = this.CEngine.collide(i, entity.internalLayer, entity._x, entity._y, dX, dY, entity.poly);\n if (collisions.length > 0)\n {\n for (let j = 0; j < collisions.length; ++j)\n {\n if (collisions[j].type === 0)\n {\n stopped = true;\n const collidedWith = this.entities[collisions[j].ref];\n if (collidedWith.attached === true)\n {\n entity.scripts.onTouchPlayer(this.runTime, entity, collidedWith);\n }\n else\n {\n entity.scripts.onTouchOther(this.runTime, entity, collidedWith);\n }\n }\n else if (collisions[j].type === 1)\n {\n stopped = true;\n }\n else /* type 2 = trigger, type 3 = zone - handling is the same */\n {\n if (entity.attached === true)\n {\n collisions[j].scripts.onPlayer(this.runTime, entity);\n }\n else\n {\n collisions[j].scripts.onOther(this.runTime, entity);\n }\n }\n }\n }\n }\n }\n if (stopped === false)\n {\n if (this.useCEngine)\n {\n if (cType === 1)\n {\n this.updateCollisions(i, entity._x, entity._y, dX, dY, entity.internalLayer, entity.internalLayer, false);\n }\n for (let j = 0; j < entity.poly.length; ++j)\n {\n entity.poly[j].x += dX;\n entity.poly[j].y += dY;\n }\n }\n entity._x += dX;\n entity._y += dY;\n entity._px += pVec[0];\n entity._py += pVec[1];\n }\n entity.scripts.onStep(this.runTime, entity);\n }\n else if (action.type === spriteSCRIPT)\n {\n action.script(this.runTime, entity);\n --action.ticks;\n }\n else if (action.type === spriteY)\n {\n if (entity._y !== action.pos)\n {\n if (cType === 1)\n {\n this.updateCollisions(i, entity._x, entity._y, 0, action.pos - entity._y, entity.internalLayer, entity.internalLayer, false);\n }\n else if (cType === 0)\n {\n const newTileY = Math.floor(action.pos * this._tFract);\n this.tObs[entity.internalLayer][entity.tile_x][newTileY] = i + 1;\n this.tObs[entity.internalLayer][entity.tile_x][entity.tile_y] = 0;\n }\n entity._y = action.pos;\n entity._py = action.pos * 128;\n }\n action.ticks = 0;\n --i;//when the action is teleporting let them take another action\n }\n else if (action.type === spriteX)\n {\n if (entity._x !== action.pos)\n {\n if (cType === 1)\n {\n this.updateCollisions(i, entity._x, entity._y, action.pos - entity._x, 0, entity.internalLayer, entity.internalLayer, false);\n }\n else if (cType === 0)\n {\n const newTileX = Math.floor(action.pos * this._tFract);\n this.tObs[entity.internalLayer][newTileX][entity.tile_y] = i + 1;\n this.tObs[entity.internalLayer][entity.tile_x][entity.tile_y] = 0;\n }\n entity._x = action.pos;\n entity._px = action.pos * 128;\n }\n action.ticks = 0;\n --i;//when the action is teleporting let them take another action\n }\n else if (action.type === spriteLAYER)\n {\n if (entity.internalLayer !== action.pos)\n {\n this._renders[entity.internalLayer].splice(entity.position, 1);\n this._renders[action.pos].push(entity);\n entity.position = 0;\n if (cType === 1)\n {\n this.updateCollisions(i, entity._x, entity._y, 0, 0, entity.internalLayer, action.pos, false);\n }\n else if (cType === 0)\n {\n this.tObs[action.pos][entity.tile_x][entity.tile_y] = i + 1;\n this.tObs[entity.internalLayer][entity.tile_x][entity.tile_y] = 0;\n }\n entity.internalLayer = action.pos;\n }\n action.ticks = 0;\n --i;//when the action is just changing layer let them take another action\n }\n else if (action.type === spriteDESTROY)\n {\n entity.scripts.onDestroy(this.runTime, entity);\n if (this.CEngine.ctype === 1)\n {\n this.updateCollisions(i, entity._x, entity._y, 0, 0, entity.internalLayer, entity.internalLayer, false, true);\n }\n else if (cType === 0)\n {\n this.tObs[entity.internalLayer][entity.tile_x][entity.tile_y] = 0;\n }\n this._renders[entity.internalLayer].splice(entity.position, 1);\n entity.inUse = false;\n entity.frozen = true;\n //this.entities.splice(i,1);//#FIX ME should we actually remove?\n //at the moment splicing the entity from the array will break stuff\n }\n if (action.ticks === 0)\n {\n ++entity.end;\n if (entity.end === entity.insert)\n {\n entity.end = 0;\n entity.insert = 0;\n }\n }\n }\n }\n //re-order the render queue - #FIX-ME, consider if this should be done by moving inidividual entities\n //currently made stable with added position value - probably a tad slow\n for (let i = 0; i < this.layers; ++i)\n {\n this._renders[i].sort(compareEntities);\n }\n }",
"function GameEntity(type) {\n this.type = type;\n this.animation = (type.animation) ? new GameAnimation(type.animation) : null;\n this.sprite = (type.sprite) ? new GameSprite(type.sprite) : null;\n this.bounds = {\n x: type.bounds.x,\n y: type.bounds.y,\n dx: type.bounds.dx || 0.0,\n dy: type.bounds.dy || 0.0,\n width: type.bounds.width,\n height: type.bounds.height,\n };\n }",
"constructor() {\r\n /**\r\n * Stage x position\r\n * @protected\r\n * @type {number}\r\n */\r\n this.x = 0;\r\n /**\r\n * Stage y position\r\n * @protected\r\n * @type {number}\r\n */\r\n this.y = 0;\r\n\r\n /**\r\n * Whether to update the stage or not\r\n * @protected\r\n * @type {bool}\r\n */\r\n this.enable = true;\r\n }",
"function VisualEntity(_entity)\n\t{\n\t this.entity;//related entity\n\t this.healthBar;//health bar\n\t this.hpChangePosTxt;//positive health changing notifying text\n\t this.hpChangeNegTxt;//positive health changing notifying text\n\t this.dHPPos;//positive change in HP per frame\n\t this.dHPNeg;//negative change in HP per frame\n\t this.spriteModule;\n\t \n\t\t\n\t this.entity = _entity;\n\t this.dHPPos = this.dHPNeg = 0;\n\t this.entituOnAim = false;\n\t\t\n\t\t\n\t this.spriteModule = spriteModuleList[this.entity.getSpriteModuleName()];\n\t var spriteSheet = spriteSheetList[this.spriteModule.sheetID];\n\n\n\t //call super class constructor\n\t SceneObject.call(this, spriteSheet);\n\t this.setSize(this.entity.getWidth(), this.entity.getHeight());\n\t this.playAnimation(\"normal\");//play the animation named \"normal\"\n\t //caatActor.setScale(entity.getWidth() / caatActor.width, entity.getHeight() / caatActor.height);\n\t\t\n\t\tif (this.entity.isGround())//should make it ground level, but still above map's non-obstacle tiles\n\t\t\tworldNode.setZOrder(this, numNonObstacleTiles);\n\t\t\n\t //add mouse click event listener\n\t if (this.entity.getHP() <= 0)\n\t\t{\n\t\t\t//hp = 0 is not an interactive entity\n\t\t\tthis.enableEvents(false);\n\t\t}\n\n\n\t\tif (this.entity.getHP() > 0)\n\t\t{\n\t\t\t//create health bar\n\t\t\tthis.healthBar = new CAAT.Foundation.UI.ShapeActor();\n\t\t\tthis.healthBar.setShape(CAAT.Foundation.UI.ShapeActor.SHAPE_RECTANGLE);\n\t\t\tthis.healthBar.enableEvents(false);\n\t\t\tthis.healthBar.setFillStyle('#ff0000');\n\t\t\t\n\t\t\tworldNode.addChild(this.healthBar);\n\t\t\t\n\t\t\tvar scale = 1.0/ Constant.PHYSICS_UNIT_SCALE;\n\t\t\t\n\t\t\tvar font= \"13px sans-serif\";\n\t\t\t//create health notification texts\n\t\t\tthis.hpChangePosTxt = new CAAT.Foundation.UI.TextActor()\n\t\t\t\t\t\t\t\t\t\t.setFont(font)\n\t\t\t\t\t\t\t\t\t\t.setAlign(\"center\")\n\t\t\t\t\t\t\t\t\t\t.setTextFillStyle('#00ff00')\n\t\t\t\t\t\t\t\t\t\t//.setOutline(true)\n\t\t\t\t\t\t\t\t\t\t//.setOutlineColor('white')\n\t\t\t\t\t\t\t\t\t\t.setVisible(false)\n\t\t\t\t\t\t\t\t\t\t.setScale(scale, scale)\n\t\t\t\t\t\t\t\t\t\t.enableEvents(false)\n\t\t\t\t\t\t\t\t\t\t;\n\t\t\tworldNode.addChild(this.hpChangePosTxt);\t\t\t\t\t\t\t\n\t\t\t\n\t\t\tthis.hpChangeNegTxt = new CAAT.Foundation.UI.TextActor()\n\t\t\t\t\t\t\t\t\t\t.setFont(font)\n\t\t\t\t\t\t\t\t\t\t.setAlign(\"center\")\n\t\t\t\t\t\t\t\t\t\t.setTextFillStyle('#ff0000')\n\t\t\t\t\t\t\t\t\t\t//.setOutline(true)\n\t\t\t\t\t\t\t\t\t\t//.setOutlineColor('white')\n\t\t\t\t\t\t\t\t\t\t.setVisible(false)\n\t\t\t\t\t\t\t\t\t\t.setScale(scale, scale)\n\t\t\t\t\t\t\t\t\t\t.enableEvents(false)\n\t\t\t\t\t\t\t\t\t\t;\n\t\t\tworldNode.addChild(this.hpChangeNegTxt);\n\n\n\n\t\t}\n\t\t //if (this.entity.getHP() > 0)\n\t\telse\n\t\t{\n\t\t\tthis.healthBar = null;\n\t\t\tthis.hpChangePosTxt = null;\n\t\t\tthis.hpChangeNegTxt = null;\n\t\t}\n\t\n\t\t\n\t\tthis.entity.visualPart = this;//now the entity will know what is its visual part\n\t\t\n\t\tthis.commitChanges();\n\t\t\n\t}//VisualEntity = function(entity)",
"function Instance(options) {\n this.value = {\n name: options.name,\n data: options.data,\n time: options.time,\n };\n this.time = options.time;\n this.position = options.position;\n this.neg = options.neg;\n\n // Predecessor points to the previous instance of this instance's symbol\n this.predecessor = options.predecessor || null;\n // Previous points to the most recent instance of the previous symbol\n this.previous = options.previous || null;\n}",
"start(entity) {\n this.entity = entity;\n this.container = PIXI.Sprite.fromFrame(entity.attributes.textureId);\n entity.container.addChild(this.container);\n }",
"function AnimatedEntity(game, x, y, width, height) {\n Entity.call(this, game, x, y);\n this.image = null;\n this.animation = null;\n this.width = width;\n this.height = height;\n // default values for the scaling\n this.scaleToX = 32;\n this.scaleToY = 32;\n this.lastUpdateTime = null;\n // keep track of the sound that the entity is emitting\n this.sound = {\n name : null,\n isPlaying : false,\n source : null\n };\n this.VELOCITY = 0; // in pixels per second (if applicable)\n}",
"function Instance(region, db, region_set) {\n this.region = region;\n this.emitter = new EventEmitter();\n\n this.entities = {};\n this.players = {};\n this.chunk_set = new voxels.ChunkSet();\n \n this.dirty_entities = [];\n this.deleted_entities = [];\n this.dirty_chunks = {};\n \n this.running = false;\n this.db = db;\n this.region_set = region_set; \n this.game_module = region_set.game_module\n \n this.server = true;\n this.client = false;\n \n this.tick_interval = null;\n this.sync_interval = null;\n \n this.chunk_ids = {}; //List of chunk ids from the database\n}",
"function SpriteTimeEngine() {\r\n this.initialize.apply(this, arguments);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert 2D array to markdown table. The first row is headings. | function twoDArrayToMarkdownTable(twoDArr) {
let output = " \n";
twoDArr.forEach((arr, offset) => {
let i = 0;
output += "|";
while (i < arr.length) {
output += arr[i] + "|";
i += 1;
}
output += " \n";
if (offset === 0) {
output += "|";
i = 0;
while (i < arr.length) {
output += "---|";
i += 1;
}
output += " \n";
}
});
output += " ";
return output;
} | [
"function createMarkdownTable(objArray) {\n const modifiedArray = objArray.map((e) => {\n if (e.value === '') {\n e.value = '\"\"';\n }\n return [`\\`${e.name}\\``, e.description, e.extra ? '' : `\\`${e.value}\\``];\n });\n // return CliPrettify.prettify((toTable(modifiedArray, ['name', 'description', 'value'])));\n return table([\n ['Name', 'Description', 'Value'],\n ...modifiedArray,\n ]);\n}",
"function markdownTable(rows, _a) {\n var removeEmptyColumns = (_a === void 0 ? { removeEmptyColumns: true } : _a).removeEmptyColumns;\n // Constants for pretty printing the markdown tables\n var MIN_CELL_WIDTH = 3;\n var MAX_CELL_WIDTH = 50;\n var CELL_PADDING = 1;\n // Count the number of columns\n var columnCount = Math.max.apply(Math, __spread(rows.map(function (r) { return r.length; })));\n if (removeEmptyColumns) {\n // Create a boolean array where each entry tells if a column is used or not (excluding the header)\n var emptyColumns_1 = Array(columnCount)\n .fill(false)\n .map(function (b, i) { return i !== 0 && rows.slice(1).find(function (r) { return r[i] != null && r[i].length > 0; }) == null; });\n // Remove unused columns if necessary\n if (emptyColumns_1.includes(true)) {\n // Filter out the unused columns in each row\n rows = rows.map(function (row) { return row.filter(function (column, i) { return !emptyColumns_1[i]; }); });\n // Adjust the column count\n columnCount = Math.max.apply(Math, __spread(rows.map(function (r) { return r.length; })));\n }\n }\n // Escape all cells in the markdown output\n rows = rows.map(function (r) { return r.map(markdownEscapeTableCell); });\n // Create a boolean array where each entry corresponds to the preferred column width.\n // This is done by taking the largest width of all cells in each column.\n var columnWidths = Array(columnCount)\n .fill(0)\n .map(function (c, i) { return Math.min(MAX_CELL_WIDTH, Math.max.apply(Math, __spread([MIN_CELL_WIDTH], rows.map(function (r) { return (r[i] || \"\").length; }))) + CELL_PADDING * 2); });\n // Build up the table\n return \"\\n|\" + rows[0].map(function (r, i) { return fillWidth(r, columnWidths[i], CELL_PADDING); }).join(\"|\") + \"|\\n|\" + columnWidths.map(function (c) { return \"-\".repeat(c); }).join(\"|\") + \"|\\n\" + rows\n .slice(1)\n .map(function (r) { return \"|\" + r.map(function (r, i) { return fillWidth(r, columnWidths[i], CELL_PADDING); }).join(\"|\") + \"|\"; })\n .join(\"\\n\") + \"\\n\";\n}",
"function viewArrayAsTable(myArray) {\n var result;\n //var result = \"<table border=1>\";\n\n // make head row with titles\n// result += \"<tr>\";\n// if (myArray.length>0){\n// \tvar x = myArray[0];\n// \tvar y = Object.keys(x);\n// \tfor(var j=0; j<y.length; j++){\n// \tresult += \"<td><b>\" + y[j] + \"</b></td>\";\n// \t}\n//\t}\n\n // make table\n //result += \"</tr>\";\n\n if ( myArray == null || myArray.length == 0) {\n return result = '';\n }\n\n for (var i = 0; i < myArray.length; i++) {\n result += \"<tr>\";\n result += \"<td class='cargo-name'>\" + myArray[i].name + \"</td>\";\n result += \"<td class='cargo-weight'>\" + myArray[i].weight + \"</td>\";\n result += \"</tr>\";\n }\n //result += \"</table>\";\n return result;\n}",
"function makeTableHTML(myArray) {\r\n var result = \"<table border=1>\";\r\n for(var i=0; i<myArray.length; i++) {\r\n result += \"<tr>\";\r\n for(var j=0; j<myArray[i].length; j++){\r\n result += \"<td>\"+myArray[i][j]+\"</td>\";\r\n }\r\n result += \"</tr>\";\r\n }\r\n result += \"</table>\";\r\n\r\n return result;\r\n }",
"function arrayToTD(array) {\n let result = \"\";\n\n array.forEach(function (element) {\n result += '<td>' + element + '</td>';\n });\n\n return result;\n}",
"function generateTable(arr) {\n //const word for object indexing\n // Head handling\n var keys = arr.map(function(obj) {\n return Object.keys(obj);\n });\n var head = _.uniq(_.flatten(keys, 0));\n\n var table = new Table({\n head: ['(index)'.green].concat(head.map(function(str) {\n return str.cyan;\n })),\n chars: {\n 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗',\n 'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝',\n 'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼',\n 'right': '║' , 'right-mid': '╢' , 'middle': '│'\n }\n });\n\n // Body handling\n arr.forEach(function(obj, i) {\n var body = [i].concat(head.map(function(key) {\n return _.isObject(obj[key])\n ? truncate(JSON.stringify(obj[key]), 10, '...')\n : _.isUndefined(obj[key]) ? ' ' : String(obj[key]);\n }));\n table.push(body);\n });\n\n // Print it\n console.log(table.toString());\n}",
"function convertArrayIntoHTMLTab(array) {\n // enumeration variables 1 et 2\n let i = 0;\n let j;\n\n // current element 1 et 2\n let curElt;\n let curElt2;\n\n // creation of table elements\n let table = document.createElement(\"table\");\n let thead = document.createElement(\"thead\");\n let tbody = document.createElement(\"tbody\");\n let trInHead = document.createElement(\"tr\");\n\n // adding these elements to the body\n document.body.appendChild(table);\n table.appendChild(thead);\n table.appendChild(tbody);\n thead.appendChild(trInHead);\n\n // creation of the header using the first row of the array\n let firstRow = array[0];\n\n // looping through the first row to create the th elements\n while (i < firstRow.length) {\n curElt = firstRow[i];\n let th = document.createElement(\"th\");\n th.textContent = curElt;\n trInHead.appendChild(th);\n i++;\n };\n\n // excluding the first row of the array in enumeration since it's the header\n i = 1;\n\n // looping through the array to create the rows\n while (i < array.length) {\n curElt = array[i];\n let tr = document.createElement(\"tr\");\n tbody.appendChild(tr);\n i++;\n j = 0;\n //looping through the rows to create the cells\n while (j < curElt.length) {\n curElt2 = curElt[j];\n let td = document.createElement(\"td\");\n td.textContent = curElt2;\n tr.appendChild(td);\n j++;\n };\n };\n}",
"function markdownTable(headers, values, settings) {\r\n if (values.length > 0 && headers.length != values[0].length)\r\n throw new Error(`The number of headers (${headers.length}) must match the number of columns (${values[0].length})`);\r\n settings = settings !== null && settings !== void 0 ? settings : DEFAULT_SETTINGS;\r\n const mvalues = [];\r\n const maxLengths = Array.from(headers, v => escapeTable(v).length);\r\n // Pre-construct the table in memory so we can size columns.\r\n for (let row = 0; row < values.length; row++) {\r\n const current = [];\r\n for (let col = 0; col < values[row].length; col++) {\r\n const text = tableLiteral(values[row][col], settings.allowHtml, settings);\r\n current.push(text);\r\n maxLengths[col] = Math.max(maxLengths[col], text.length);\r\n }\r\n mvalues.push(current);\r\n }\r\n // Then construct the actual table...\r\n // Append the header fields first.\r\n let table = `| ${headers.map((v, i) => padright(escapeTable(v), \" \", maxLengths[i])).join(\" | \")} |\\n`;\r\n // Then the separating column.\r\n table += `| ${maxLengths.map(i => padright(\"\", \"-\", i)).join(\" | \")} |\\n`;\r\n // Then the data colunns.\r\n for (let row = 0; row < values.length; row++) {\r\n table += `| ${mvalues[row].map((v, i) => padright(v, \" \", maxLengths[i])).join(\" | \")} |\\n`;\r\n }\r\n return table;\r\n}",
"markdownTable(headers, values, settings) {\r\n return this.api.markdownTable(headers, values, settings);\r\n }",
"function convertArrayToTable(arr) {\n // DRAW HTML TABLE\n let table = document.createElement(\"table\");\n table.setAttribute('id', 'brailleTranslationTable');\n let rowCount = 0;\n\n for (let arrayRow of arr) {\n let tableRow = table.insertRow();\n let rowBitCount = 0;\n for (let bit of arrayRow) {\n let cell = tableRow.insertCell();\n cell.setAttribute('id', bit[1]);\n cell.innerHTML = '.';\n rowBitCount++;\n if (bit[0] !== 1) cell.setAttribute('class', \"colorTransparent\");\n if (rowBitCount % 2 === 0) {\n cell = tableRow.insertCell();\n cell.innerHTML = '.';\n cell.setAttribute('class', \"colorTransparent\");\n }\n }\n rowCount++;\n if (rowCount % 3 === 0) {\n table.insertRow();\n }\n }\n return table;\n}",
"function MakeHTMLTable(headers, rows) {\n Logger.log('\\n\\nHeaders = %s\\n\\n', headers);\n Logger.log('\\ninputted data array = %s\\n', JSON.stringify(rows));\n var table = '';\n \n // Format array of data into HTML cells\n for (var i=0; i < rows.length; i++) { // each row (user)\n var tableRow = '';\n for (var j=0; j < headers.length; j++) { // each column\n var header = headers[j];\n Logger.log('Header = %s', header);\n var cell = rows[i][header];\n \n // If the cell is a list of item, make it bulleted\n if (cell.constructor === Array) {\n var copy = '';\n for (var k=0; k < cell.length; k++)\n copy += '<li>'+cell[k]+'</li>';\n cell = '<ul>'+copy+'</ul>';\n }\n \n tableRow += '<td style=\"text-align: left; padding: 8px; border: 1px solid #ddd;\">'+cell+'</td>';\n }\n \n // Make it an html table row\n table += '<tr>'+tableRow+'</tr>'; \n }\n \n // Make header row\n var titleCaseHeaders = ToTitleCase(headers);\n var headerRow = '';\n for (var i=0; i < titleCaseHeaders.length; i++)\n headerRow += '<th style=\"text-align: left; padding: 8px; border: 1px solid #ddd;\"><b>'+titleCaseHeaders[i]+'<b></th>';\n headerRow = '<tr>'+headerRow+'</tr>';\n \n // Add headers to table\n table = headerRow + table;\n \n // Make it a table\n table = '<table style=\"border: 1px solid black; border-collapse: collapse;\">'+table+'</table>';\n \n return table;\n}",
"function aryToTextTable(ary){\n var num_cols = Math.floor(Math.sqrt(ary.length));\n var padsize = maxStrLen(ary);\n ary.sort();\n var rval = '';\n for(var i = 0; i < ary.length; i += num_cols){\n for(var j = 0; j < num_cols && (i + j) < ary.length; j++){\n rval += ary[i + j] + ' '.repeat(padsize - ary[i + j].length + 1) + ((j + 1) == num_cols ? '\\n' : '');\n }\n }\n return rval;\n}",
"function Table2D(array){\n this.L = array.length;\n this.W = array[0].length;\n this.border = \"1\";\n this.width = \"100%\";\n border = \" border=\\\"\" + this.border + \"\\\" \";\n width = \" style= \\\"width:\" + this.width +\"\\\"\";\n this.val = \"<table\" + width + border + \">\";\n for(j=0; j<this.L; j++){\n this.val +=\"<tr>\";\n for(i=0;i<array[j].length; i++){\n this.val += \"<td>\" + String(array[j][i]) + \"</td>\";\n }\n this.val += \"</tr>\";\n }\n this.val+= \"</table>\"\n}",
"function outputArray( heading, theArray, output )\n{\n var content = \"<h2>\" + heading + \"</h2><table>\" +\n \"<thead><th>Index</th><th>Value</th></thead><tbody>\";\n\n // output the index and value of each array element\n var length = theArray.length; // get array's length once before loop\n \n for ( var i = 0; i < length; ++i ) \n {\n content += \"<tr><td>\" + i + \"</td><td>\" + theArray[ i ] + \n \"</td></tr>\";\n } // end for\n\n content += \"</tbody></table>\";\n output.innerHTML = content; // place the table in the output element\n} // end function outputArray",
"function outputArray( heading, theArray, output )\n{\n var content = \"<h2>\" + heading + \"</h2><table>\" +\n \"<thead><th>Index</th><th>Value</th></thead><tbody>\";\n\n // output the index and value of each array element\n var length = theArray.length; // get array's length once before loop\n\n for ( var i = 0; i < length; ++i ) \n {\n content += \"<tr><td>\" + i + \"</td><td>\" + theArray[ i ] + \n \"</td></tr>\";\n } // end for\n\n content += \"</tbody></table>\";\n output.innerHTML = content; // place the table in the output element\n} // end function outputArray",
"function outputArray(heading, theArray, output) {\n\tvar content = \"<h2>\" + heading + \"</h2><table>\" + \"<thead><th>Index</th><th>Value</th</thed><tbody>\";\n\n\t//output the index and value of each array element\n\tvar length = theArray.length; //get array's length once before loop\n\n\tfor (var i = 0; i < length; ++i) {\n\t\tcontent += \"<tr><td>\" + i + \"</td><td>\" + theArray[i] + \"</td></tr>\";\n\t} //end for\n\n\tcontent += \"</tbody></table>\";\n\toutput.innerHTML = content; //place the table in the output element\n} //end function outputArray",
"function toHtmlTable(matrix){\n let table = \"<table>\"\n for(let i = 0; i < matrix.length; ++i){\n table += \"<tr>\";\n for(let j = 0; j < matrix[i].length; ++j){\n table += \"<td>\" + matrix[i][j] + \"</td>\";\n }\n }\n table += \"</table>\";\n return table;\n}",
"function outputArray( heading, theArray, output )\r\n{\r\n var content = \"<h2>\" + heading + \"</h2><table>\" +\r\n \"<thead><th>Index</th><th>Value</th></thead><tbody>\";\r\n\r\n //output the index and value of each array element\r\n var length = theArray.length;//get arrays length once before loop\r\n\r\n for ( var i = 0; i < length; ++i )\r\n {\r\n content += \"<tr><td>\" + i + \"</td><td>\" + theArray[ i ] +\r\n \"</td></tr>\"; \r\n }//end for\r\n\r\n content += \"</tbody></table>\";\r\n output.innerHTML = content;//place the table in the output element\r\n}//end function outputarray",
"function jsonToMarkdownTable(json) {\n var cols = uniq(flatten(json.map(function (obj) {\n return Object.keys(obj);\n })));\n\n var markdown = \"\";\n\n // add columns\n markdown += COL_START + cols.join(COL_SEP) + COL_END;\n\n // add header separator\n markdown += COL_START + cols.map(function (col) {\n // return a fill with the the header separator character\n return stringFill(col.length, HEAD_SEP);\n }).join(COL_SEP) + COL_END;\n\n // add rows\n json.forEach(function (row) {\n markdown += COL_START;\n\n markdown += cols.map(function (col) {\n return row.hasOwnProperty(col) ? row[col] : \"\";\n }).join(COL_SEP);\n\n markdown += COL_END;\n });\n\n return markdown;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a storyboard with frames that contain the different steps of the algorithm | storyboard() {
// Create the first frame by hand
var storyboard = new STORYBOARD.Storyboard(this);
for (var i = 1; i < 5; i++) {
for (var k = 0; k <= i; k++) {
var frame = new STORYBOARD.Storyboard.Frame();
// Get a new color from gradient
var color = 0xFF0000 + ((i + k) * 100000);
// Create outer-left line
frame.lines.push(UTIL.Util.insertSegmentStrip(this.evaluate(k, i, -10, 0), outside_color));
// Create inner lines in full-color
frame.lines.push(UTIL.Util.insertSegmentStrip(this.evaluate(k, i, 0, 1.02), color));
// Create outer-right line
frame.lines.push(UTIL.Util.insertSegmentStrip(this.evaluate(k, i, 1, 10), outside_color));
frame.title = "B" + k + "," + i + "(t)";
// Concat with previous iterations -> of same degree
if (k != 0) {
frame.lines = frame.lines.concat(storyboard.frame(storyboard.size() - 1).lines);
}
storyboard.append(frame);
}
}
return storyboard;
} | [
"function StoryBoard(animations){\n\t\tthis.animationset = animations;\n\t\tthis.clock = 0;\n\t}",
"function Storyboard(name,n,x0,xd,y0,y1,tol,imgPath,imgExtn,key,markScale) {\r\n\tif (arguments.length==0) return\r\n\tif (x0==undefined) x0=8\r\n\tif (xd==undefined) xd=96\r\n\tif (y0==undefined) y0=8\r\n\tif (y1==undefined) x1=136\r\n\tPlacePuzzle.apply(this,[name,n,placeRow(x0,y0,xd,0),placeRow(x0,y1,xd,0),\r\n \tstoryboardAnswer2key,tol,true,imgPath,imgExtn,key,markScale])\r\n\tstoryboards.push(this)\r\n\t}",
"function print_algorithm_steps( stepIndex, algorithmSteps ){\n\t\t\n\t\tvar all_nodes = nodes.get();\n\t\tdiv = document.getElementById('step');\n\t\tdiv.innerHTML = 'Step: '+stepIndex;\n\t\t\n\t\t\n\t\tvar div = document.getElementById('main-timeline');\n\t\tvar tvalue = stepIndex % 2;\n\t\t\n\t\t\n\t\tif( stepIndex > 1){\n\t\t\t\n\t\t\tvar message = 'Προσθέτουμε τον κόμβο: '+all_nodes[ algorithmSteps[stepIndex -2].stateStep -1 ].label+ ' στο κλειστό σύνολο.';\n\n\t\t\tif( algorithmSteps[stepIndex -2].childrenStep.length > 0){\n\t\t\t\tmessage = message + 'Στη συνέχεια προστίθενται τα παιδιά της κατάστασης: '+ print_labels( algorithmSteps[stepIndex -2].childrenStep )+' στο μέτωπο αναζήτησης.';\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmessage = message + 'Ο κόμβος '+all_nodes[ algorithmSteps[stepIndex -2].stateStep -1 ].label+ ' δεν έχει παιδιά που δεν έχει επισκεφθεί ο αλγόριθμος.';\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tif( algorithmSteps[stepIndex -1].stateStep ){\n\t\t\t\tmessage = message + 'Ο κόμβος '+ all_nodes[ algorithmSteps[stepIndex -1].stateStep -1 ].label + ' είναι πλέον η κατάσταση του αλγορίθμου.';\n\t\t\t}\n\t\t\t\n\t\t\tif( algorithmSteps[stepIndex -1].stackStep.length == 0 ){\n\t\t\t\tmessage = message + 'Το μέτωπο αναζήτησης είναι κενό, συνεπώς ο αλγόριθμος τερματίζεται.'\n\t\t\t}\n\t\t\t\n\t\t\tvar tooltip = 'test';\n\t\t}\n\t\telse {\n\t\t\t\n\t\t\tvar message = 'Ο κόμβος '+ all_nodes[ algorithmSteps[stepIndex -1].stateStep -1 ].label+ ' είναι η ρίζα οπότε προστίθεται στο μέτωπο αναζήτησης.';\n\t\t\tvar tooltip = 'test';\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tdiv.innerHTML = div.innerHTML + '<a href=\"#!\" id=\"'+stepIndex+'\" class=\"collection-item tooltipped\" data-position=\"left\" data-tooltip=\"Kάνε κλικ για να δείς το βήμα του αλγορίθμου.\"><i class=\"material-icons expand-icon \" >expand_more</i><span id=\"badge'+stepIndex+'\" class=\"new badge left\">'+stepIndex+'</span><div class=\"\">'+ message + '</div><div class=\"hide info\">'+tooltip+'</div></a>';\n\t\t\n\t\twindow.scrollBy(0,document.body.scrollHeight);\n\t\tjQuery('.collection-item.tooltipped').tooltip({delay: 20});\n\t\t\n\t}",
"drawFrame() {\n let puzzle = this.puzzle\n this.drawRoad()\n this.drawBorderObjects(false, o => o.type === \"gap\")\n this.drawStartPoint(puzzle.startPoints[0], this.rc)\n this.drawEndPoint(puzzle.endPoints[0], puzzle.m, puzzle.n)\n this.drawBorderObjects(false, o => o.type === \"hexagon\")\n }",
"step() { this.frame(); }",
"function buildFrameLIs(){\n $('#action-frames').html('');\n var l = viking.sprites[sprite][action].frames.length;\n \n for(i=0; i< l; i++ ){\n var data = viking.sprites[sprite][action].frames[i];\n $('#action-frames').append( '<li><canvas id=\"action-frame-'+i+'\" width=\"64\" height=\"64\"></canvas></li>' );\n var ctxx = $('#action-frames canvas:last')[0].getContext('2d');\n ctxx.clearRect(0,0,64,64);\n ctxx.putImageData(data,0,0);\n }\n }",
"function getFakeStoryboard() {\n var fakeStoryArray = new Array();\n fakeStoryArray.push({\n preview: \"\",\n previewheading: \"\",\n slide: 0,\n classactive: \"\",\n classname: \"\"\n });\n return fakeStoryArray;\n}",
"function framesDisplay() {\n for (let i = animationFrames.length; i > -1; i--) {\n $('#canvas').append(animationFrames[i]);\n }\n $('#frame0').css('visibility', 'visible');\n}",
"_generateSheetFrames() {\n\t\t\t\tvar sX = 0,\n\t\t\t\t\tsY = 0;\n\t\t\t\tfor (var i = 0; i < this.num_frames; i++) {\n\t\t\t\t\tthis.frames.push({\n\t\t\t\t\t\tname: i,\n\t\t\t\t\t\tframe: {\n\t\t\t\t\t\t\tx: sX,\n\t\t\t\t\t\t\ty: sY,\n\t\t\t\t\t\t\twidth: this.frame_width,\n\t\t\t\t\t\t\theight: this.frame_height\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tsX += this.frame_width;\n\t\t\t\t\tif (sX >= this.image.width) {\n\t\t\t\t\t\tsX = 0;\n\t\t\t\t\t\tsY += this.frame_height;\n\t\t\t\t\t\tif (sY >= this.image.height) {\n\t\t\t\t\t\t\tsY = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}",
"function displayStepByStep(steps) {\n createSolutionHeader(true);\n //add step 0\n var firstStep = { \"tankOneContent\": 0, \"tankTwoContent\": 0 };\n steps.unshift(firstStep);\n var k = 1;\n if (k == steps.length) {\n createStepContent(firstStep, 0);\n makeGreenTank(\"#tankA-step-0\", 0);\n makeGreenTank(\"#tankB-step-0\", 0);\n }\n else {\n createStepContent(firstStep, 1);\n }\n while (k < steps.length) {\n displayNextStepTimeOut(steps, k);\n k++;\n }\n}",
"drawBoard() {\n let content = '';\n for (let i = 0; i < ROWS; i++) {\n content += '<tr>';\n for (let j = 0; j < COLS; j++) {\n content += `<td style=\"padding: 3px;\">\n <div data-state=\"covered\" data-index=${(i * ROWS) + j} class=\"game-board-square\">\n <div class=\"flipper\">\n <div class=\"front\">\n <div class=\"card\" style=\"background: silver\"></div>\n </div>\n <div class=\"back\">\n <div class=\"card\" style=\"background: green\"></div>\n </div>\n </div>\n </div>\n </td>`;\n }\n content += '</tr>';\n }\n this.containerView.html(content);\n }",
"function initialBoardHTML() {\r\n let board_src = '';\r\n for (let j = 0; j < COLS; j++) {\r\n board_src += `<div class=\"column unhoverable\" data-col=\"${j}\">`;\r\n for (let i = 0; i < ROWS; i++) {\r\n board_src += `<div class=\"slot\" data-row=\"${i}\" data-col=\"${j}\"></div>`;\r\n }\r\n board_src += '</div>';\r\n }\r\n return board_src;\r\n}",
"drawPlayground(playground = this.game.playground){\n let frame = document.createElement(\"div\");\n frame.classList.add('frame');\n for (let curY = 0; curY < playground.sizeY; curY++) {\n let row = document.createElement('div');\n row.classList.add('row');\n for (let curX = 0; curX < playground.sizeX; curX++) {\n let rect = document.createElement('div');\n rect.classList.add('square');\n if (playground.frame[[curX,curY]] === 1)\n rect.classList.add(\"marked\");\n else if (playground.frame[[curX,curY]] === 2)\n rect.classList.add(\"crossed\");\n rect.setAttribute(\"coordX\", \"\"+curX);\n rect.setAttribute(\"coordY\", \"\"+curY);\n row.appendChild(rect);\n }\n frame.appendChild(row);\n }\n return frame;\n }",
"function Frames() {\n requestAnimFrame(Frames);\n drawScene();\n}",
"function generateStepDots() {\n //////console.log(\"ShellController.. generateStepDots\");\n var jsonData = pageDataJson;\n if (jsonData.dataObj.stepPoint.length > 0) {\n if (jsonData.video != undefined) {\n var stepPointArray = jsonData.dataObj.stepPoint;\n var startPointsArray = new Array();\n var stopPointsArray = new Array();\n var refArray = shellModel.getDomElementReference();\n for (var stPt = 0; stPt < stepPointArray.length; stPt++) {\n var temp = stepPointArray[stPt].split('~');\n if (temp[1] == 'start') {\n startPointsArray.push(temp[0]);\n }\n if (temp[1] == 'stop') {\n stopPointsArray.push(temp[0]);\n }\n }\n ////console.log(startPointsArray);\n ////console.log(stopPointsArray);\n if (startPointsArray.length > 1) {\n stepGeneratorObj = new StepGenerator(_classRef);\n shellModel.setStepPoint(stopPointsArray);\n shellModel.setStepStartPoint(startPointsArray);\n stepGeneratorObj.init(\n startPointsArray,\n stopPointsArray,\n jsonData.dataObj.stepTitle,\n totalFrames,\n sliderRef.width(),\n customToolTipDiv,\n customToolTipArrowDiv\n );\n _classRef.updateSliderDefaultValue();\n for (var i = 0; i < refArray.length; i++) {\n if (refArray[i].data('uniqueId') == 'navSliderStepPointHolder') {\n stepPointElement = refArray[i];\n }\n }\n stepGeneratorObj.addToDom(stepPointElement);\n // Code added on 10/11/2016\n stepGeneratorObj.disable();\n // ========================\n }\n navControlObj.enableReplay(false);\n }\n createAnimatedPlayBtn();\n }\n }",
"function steps(n) {\n\n for(let i=1; i <= n; i++){\n let print = draw(i, '#');\n print+= draw(n-i, ' ');\n console.log(print);\n }\n}",
"function setupStoryboardInterface() {\n\t$(\"#storyboard\").height($(window).height() - 10 - $(\"header\").outerHeight());\n}",
"function createTimeline()\n{\n\n\tvar exp_timeline = [];\n\tjsPsych.data.addProperties({subjectNum: subjectNum});\n\n//\texp_timeline.push(full_screen, welcome_msg, inputs, instructions, example)//, calibration_msg, calibration);\n\texp_timeline.push(full_screen, inputs);\n\n\tfor(curr_blockNum = 0; curr_blockNum < n_blocks; curr_blockNum++)\n\t{\n\t\texp_timeline.push(pre_block_msg(curr_blockNum+1, curr_totalTrialNum));\n\n\t\tfor(curr_trialNum = 0; curr_trialNum < n_Trials; curr_trialNum++)\n\t\t{\t\n\t\t\t// every 32 trials --> do forced recalibration\n/*\t\t\tif(curr_trialNum%5 == 0)\n\t\t\t{\n\t\t\t\texp_timeline.push(loop_forced_clickRecal);\n\t\t\t}\n\n\t\t\t// pre-trial eye-tracking validation\n\t\t\texp_timeline.push(loop_fixation);\n*/\n\t\t\t// get counterbalanced data\n\t\t\t//******colorCues_time = trialData[curr_totalTrialNum].....;\n\t\t\tcolorCues_time = 2000;\n\t\t\tcue_pos1 = 1;\n\t\t\tcue_pos2 = 4;\n\t\t\tcueColor1 = 'blue';\n\t\t\tcueColor2 = 'red';\n\t\t\tgratingAngles = [30, 40, 50, 90];\n\t\t\tgratingContrast = [1, 0.5, 1, 1];\n\t\t\tgratingPosition = [1, 2, 1, 2];\n\t\t\t/* position 1 = away from the vertical center\n\t\t\t position 2 = center of the placeholder\n\t\t\t position 3 = towards the vertical center\n\t\t\t*/\n\t\t\trespPos1 = 1;\n\t\t\trespPos2 = 4;\n\t\t\trespColor1 = 'blue';\n\t\t\trespColor2 = 'red';\n\n\t\t\tfixationScreen_time = 500;\n\t\t\tgratingSet1_time = 1000;\n\t\t\twhiteCues_time = 1000;\n\t\t\tdelay_time = 1000;\n\t\t\tgratingSet2_time = 100;\n\t\t\tresp1_time = 3000;\n\t\t\tresp2_time = 2000;\n\t\t\tresp3_time = 2000;\n\n\t\t\texp_timeline.push(fixationScreen(fixationScreen_time, gratingAngles, gratingContrast, gratingPosition));\n\t\t\texp_timeline.push(gratingSet1(gratingSet1_time));\n\t\t\texp_timeline.push(whiteCues(whiteCues_time, cue_pos1, cue_pos2));\n\t\t\texp_timeline.push(colorCues(colorCues_time, cue_pos1, cue_pos2, cueColor1, cueColor2));\n\t\t\texp_timeline.push(delayScreen(delay_time, gratingPosition));\n\t\t\texp_timeline.push(gratingSet2(gratingSet2_time));\n\t\t\texp_timeline.push(response1(resp1_time, respPos1, respPos2, respColor1, respColor2));\n\t\t\texp_timeline.push(response2(resp2_time, respPos1, respColor1));\n\t\t\texp_timeline.push(response3(resp3_time, respPos2, respColor2));\n\n\n\t\t//\texp_timeline.push(all_gratingSet1(colorCues_time, cue_pos1, cue_pos2, cueColor1, cueColor2));\n\n/*\t\t\tif(curr_trialNum%10 == 0 && curr_trialNum > 9)\n\t\t\t{\n\t\t\t\texp_timeline.push(loop_validation);\n\t\t\t}\n*/\n\t\t\tcurr_totalTrialNum++;\n\t\t}\n\n\t\texp_timeline.push(post_block_msg());\n//\t\texp_timeline.push(loop_validation);\n\t}\n\treturn exp_timeline;\n}",
"function renderFiveMinuteSteps(){\n\t\tfaceCtx.translate(\n\t\t\tcenter,\n\t\t\tcenter\n\t\t);\n\t\t\n\t\tfor(var i = 0; i < 12; i++){\n\t\t\tfaceCtx.save();\n\t\t\tfaceCtx.translate(\n\t\t\t\tdefaultSize/2 - fiveMinuteStepLength/2 - stepPadding,\n\t\t\t\t0\n\t\t\t);\n\t\t\t\n\t\t\tfaceCtx.fillRect(\n\t\t\t\t0-fiveMinuteStepLength/2,\n\t\t\t\t0-fiveMinuteStepWidth/2,\n\t\t\t\tfiveMinuteStepLength,\n\t\t\t\tfiveMinuteStepWidth\n\t\t\t);\n\t\t\tfaceCtx.restore();\n\t \n\t\t\tfaceCtx.rotate(Math.PI / 6);\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove message group from Message End Event & Message Throw Event | function removeMessageGroup(groups, element) {
const messageGroup = findGroup(groups, 'message');
if (isMessageEndEvent(element) || isMessageThrowEvent(element)) {
groups = groups.filter(g => g != messageGroup);
}
return groups;
} | [
"onMessagesRemoved() {}",
"onMessageRemovalFailed() {}",
"onGroupEnd () {\n this.activeGroup = null\n }",
"function onGroupLeave (e) {\n\n // If the client is currently having a call with the endpoint, we need to hang that up\n if (call && call.remoteEndpoint.id === e.connection.endpointId) {\n call.hangup();\n }\n\n // Remove the endpoint from the buddy list\n ctrl.buddyList.removeMember(e.connection.endpointId);\n \n }",
"function clearMessages(message, group)\n{\n\tvar msg;\n\tgroup = getGroup(EZ.trace.activeGroupName);\t\n\tgroup.counts = {};\n\tgroup.messages = [];\n\tgroup.messageList = [];\n\t\n\tif (message)\n\t{\n\t\tmsg = message.heading.substr(1) + ' @ ' + EZ.formatDate(message.time,'time');\n\t\tgroup.status = msg;\n\t}\n\tif (group.name == EZ.trace.activeGroupName)\n\t{\n\t\tf.messages.innerHTML = '';\ndebugger;\n\t\tf.messageList.EZfield.resetInitialAttributes('options');\n\t\t//EZ.clearList(f.messageList, 'fast defaultOptions');\n\t\tif (message)\n\t\t{\n\t\t\tEZ.displayMessage.blank = msg || 'cleared @ ' + EZ.formatDate('','time');\n\t\t\tEZ.displayMessage();\n\t\t}\n//\t\tf.messageList.options[0] = new Option(f.messageListDefault, '');\n\t\tfilterNote();\n\t}\n}",
"function removeAfterMessage(log_message_id) {\n var message_box = getMessageBox(log_message_id);\n if($('#wc-message-group-content .wc-message-wrapper:gt(' + message_box.index() + ')').length) {\n $('#wc-message-group-content .wc-message-wrapper:gt(' + message_box.index() + ')').remove();\n return true;\n }\n return false;\n }",
"SayGoodbyeParticleGroup(group) {\n this.RemoveParticleGroup(group);\n }",
"destroy () {\n this.debug('destroying bus', this.groupId, this.id);\n this.recipients = [];\n window.removeEventListener('message', this.receive, false);\n }",
"async function onGroupReceived(ev) {\n const details = ev.groupDetails;\n const { id } = details;\n const idBuffer = window.Signal.Crypto.fromEncodedBinaryToArrayBuffer(id);\n const idBytes = idBuffer.byteLength;\n if (idBytes !== 16) {\n window.log.error(`onGroupReceived: Id was ${idBytes} bytes, expected 16 bytes. Dropping group.`);\n return;\n }\n const conversation = await window.ConversationController.getOrCreateAndWait(id, 'group');\n if (conversation.isGroupV2()) {\n window.log.warn('Got group sync for v2 group: ', conversation.idForLogging());\n return;\n }\n const memberConversations = details.membersE164.map((e164) => window.ConversationController.getOrCreate(e164, 'private'));\n const members = memberConversations.map((c) => c.get('id'));\n const updates = {\n name: details.name,\n members,\n color: details.color,\n type: 'group',\n inbox_position: details.inboxPosition,\n };\n if (details.active) {\n const activeAt = conversation.get('active_at');\n // The idea is to make any new group show up in the left pane. If\n // activeAt is null, then this group has been purposefully hidden.\n if (activeAt !== null) {\n updates.active_at = activeAt || Date.now();\n }\n updates.left = false;\n }\n else {\n updates.left = true;\n }\n if (details.blocked) {\n conversation.block();\n }\n else {\n conversation.unblock();\n }\n conversation.set(updates);\n // Update the conversation avatar only if new avatar exists and hash differs\n const { avatar } = details;\n if (avatar && avatar.data) {\n const newAttributes = await window.Signal.Types.Conversation.maybeUpdateAvatar(conversation.attributes, avatar.data, {\n writeNewAttachmentData,\n deleteAttachmentData,\n doesAttachmentExist,\n });\n conversation.set(newAttributes);\n }\n window.Signal.Data.updateConversation(conversation.attributes);\n const { appView } = window.owsDesktopApp;\n if (appView && appView.installView && appView.installView.didLink) {\n window.log.info('onGroupReceived: Adding the message history disclaimer on link');\n await conversation.addMessageHistoryDisclaimer();\n }\n const { expireTimer } = details;\n const isValidExpireTimer = typeof expireTimer === 'number';\n if (!isValidExpireTimer) {\n return;\n }\n const receivedAt = Date.now();\n await conversation.updateExpirationTimer(expireTimer, window.ConversationController.getOurConversationId(), receivedAt, {\n fromSync: true,\n });\n }",
"SayGoodbyeParticleGroup(group) {\n this.RemoveParticleGroup(group);\n }",
"stop () {\n this.recipients = [];\n window.removeEventListener('message', this.receive, false);\n }",
"function removeSingleGroupListener(groupId) {\n socket.removeAllListeners(groupId)\n}",
"del() {\n if (!this._handled) {\n this._squiss.deleteMessage(this)\n this._handled = true\n }\n }",
"function cleanEvent() {\n\tvar removable = ACT.Event.removable;\n\tfor (var itor = 0; itor < removable.length; itor++) {\n\t\tif (removable[itor].eventType === 'env:envRendered') continue;\n\t\tif (removable[itor].eventType === 'message') continue;\n\t\tif (removable[itor].eventType === 'screen:status') continue;\n\t\tif (removable[itor].eventType === 'collapseStart') continue;\n if (removable[itor].eventType === 'html5:message') continue;\n\t\tremovable[itor].remove();\n\t}\n\tACT.Event.removable = [];\n}",
"function endGroup() {\n command_1.issue('endgroup');\n }",
"function endGroup() {\n command_1.issue(\"endgroup\");\n }",
"onGroupDestroyed(group) {\n\t\tlet i = this._groups.indexOf(group)\n\t\tif (i >= 0) this._groups.splice(group.groupsIndex, 1)\n\t\tconsole.log('group removed, count now:', this._groups.length)\n\t}",
"function endGroup() {\n command.issue('endgroup');\n}",
"function handleExit(topic, payload, timestamp){\n let nodeNo = parseFloat(payload[1]);\n\tlet groupName = global.activeTopics.get(topic);\n\tlet groupChannel = global.groupChannels.get(groupName);\n\tlet memberInfo = Object.entries(groupChannel.memberInfo).filter((entry) =>{\n\t return entry[1] == nodeNo;\n });\n\tlet memberSelect = [memberInfo[0][0]];\n\thandleRemoveMember(groupName, memberSelect);\n\tlet messageObj = {message:'A member has left the group :'+ memberSelect, timestamp:timestamp};\n\tgroupChannel.messages.push(messageObj);\n\tglobal.groupChannels.set(groupName, groupChannel);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number > Number Heals the human player by healthRestore amount given: a health restore amount of 20 and a player with 80 health expected: 100 | heal(healthRestore) {
if (this.health + healthRestore > 100) {
this.health = 100;
}
else {
this.health += healthRestore;
}
return this.health;
} | [
"function restoreHealth() {\n playerHealth += hero.wis * 3;\n if (playerHealth > playerMax) {\n playerMax = playerHealth\n }\n}",
"function getHealth(playerLevel) {\n const healthBonusFromLevel = playerLevel * 15;\n return 85 + healthBonusFromLevel;\n}",
"function healthbar(max, health){\n return ((100 / max)*health)\n}",
"playerHealth(value) {\n if (value <= 0 && this.monsterHealth <= 0) {\n // a draw between monster and player\n this.winner = \"draw\";\n } else if (value <= 0) {\n //player lost , monster won\n this.winner = \"monster\";\n }\n }",
"function loseHealth(){\n animateElement(healthSection, 'shake', 'faster');\n userHealth--;\n console.log('userHealth : ', userHealth); //TESTING PURPOSES\n updateHealthDisplay();\n playSound(badSound);\n checkGameOver();\n}",
"healPlayer() {\n const healValue = getMinMax(5, 10);\n if (this.playerHealth + healValue > 100) {\n this.addLogMessage('player', 'heal', 100 - this.playerHealth);\n this.playerHealth = 100;\n } else {\n this.playerHealth += healValue;\n this.addLogMessage('player', 'heal', healValue);\n }\n this.healMonster();\n }",
"function recoverHP(object, number) {\n\tobject.hp += number;\n\tif (object.hp > object.maxHP) {\n\t\tobject.hp = object.maxHP;\n\t}\n}",
"function healthLoss() {\n if (player.currentHealth >= 0) {\n player.currentHealth = player.currentHealth - 1\n //when player health hits 5, send a message saying you need food\n if (player.currentHealth === 5) {\n console.log(\"Your starting to feel a bit hungry, Maybe you should get some food\")\n }\n // when the player health hits 3, it constantly reminds the player it needs food\n if (player.currentHealth <= 3 && player.currentHealth > 0) {\n console.log(\"Your stomach growls and you start to feel a bit woozey. Food is a necessity\")\n }\n // player ded\n if (player.currentHealth === 0) {\n console.log(\"You have starved to death, you are now one of us. better luck next time.\")\n process.exit()\n }\n }\n}",
"playerHealth(value) {\n if (value <= 0 && this.monsterHealth <= 0) {\n // It is draw\n this.winner = 'draw';\n } else if (value <= 0) {\n // The monster won\n this.winner = 'monster';\n }\n }",
"function testGoblinHp(){\n let damage = rollDice(6);\n damage += player.statMods[0];\n console.log(damage);\n currentGoblinHP -= damage;\n console.log(currentGoblinHP);\n document.getElementById('goblinHP').innerHTML = currentGoblinHP + \"/7\";\n console.log(goblin);\n console.log(steveTheCommoner);\n}",
"function healPlayer(user,healVal){\n if((user.health+healVal)>=user.maxHealth){\n user.health=user.maxHealth;\n }else{\n user.health = user.health+healVal;\n }\n user.save(function(err) {\n if (err)\n console.log(err);\n return null;\n });\n}",
"function playerMaxHealth(playerNum){\n const playerMaxHealths = [240, 160, 160, 120, 160,100, 200, 160]\n return playerMaxHealths[playerNum -1]\n}",
"function useHealth() {\n playerHealth -= 1;\n playerHealth = constrain(playerHealth, 0, playerInitialHealth);\n}",
"function heal(healAmount = 10) {\r\n var newHealth = currentHealth + healAmount;\r\n currentHealth = newHealth > 100 ? maxHealth : newHealth;\r\n // currentHealth += healAmount;\r\n // return 5\r\n return calculatePercent(currentHealth / maxHealth);\r\n\r\n // function nested() {\r\n // return console.log(currentHealth);\r\n // }\r\n}",
"function damageHP(instigator, target, amount){\n if(amount >= target.currentHP){\n target.currentHP = 0;\n } else {\n target.currentHP -= amount;\n }\n return target.currentHP;\n}",
"function playerHeal(tempHealth){\n currentHealth += tempHealth;\n if (currentHealth > maxHealth){\n currentHealth = maxHealth;\n }\n parseHealthBarAnimate();\n}",
"pl1Heal(){\n let increase = Math.floor(Math.random()*10) + 1\n return this.player1.health + increase\n }",
"function healthAdd() {\n\n\t//remove 10 gold\n\tif (gold - 10 >= 0) {\n\t\tgold -= 10;\n\n\t\t//increase item 0 of buy[] by 1 (hint: item 0 is amount of health bought)\n\t\tbuy.health++;\n\n\t\t//increase player.health by 1\n\t\tplayer.health++;\n\t}\n\t//update health\n\n\n\t//update amount of health bought in stats\n\n\n\t//update shoppe\n\tupdateButtons();\n}",
"battleFightHeal(player) {\n if (player.numberOfPotions > 0) {\n player.life += 15;\n player.numberOfPotions -= 1;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
identifyDocsNeeded looks at a caseSet.docRIDs and identifies all the doc records we need to retrieve for those cases | function identifyDocsNeeded(caseSet){
//caseSet is an array, for each case record object, in_filedIn is an array of strings with the recordID of an Edge leading to a document
var uniqueEdges = new Map(); //used to collect unique doc IDs in it's keys
var docEdges = new Array(); //the array of unique edges we will return
//for every doc listed in every case, store that record ID
for (i=0; i<caseSet.length; i++) {
//if this case has any docs...
if (caseSet[i].hasOwnProperty("docRIDs")) {
for (j=0; j<caseSet[i].docRIDs.length; j++) {
uniqueEdges.set([caseSet[i].docRIDs[j]] , true);
}
}
}
//convert the keys of uniqueEdges into the values of a regular array
for (s of uniqueEdges.keys()) docEdges.push(s);
console.log("identified " + uniqueEdges.size + " unique doc edges. ");
return docEdges;
} | [
"function identifyPeopleNeeded(caseSet){\n\t//caseSet is an array, for each case record object, in_filedIn is an array of strings with the recordID of an Edge leading to a document\n\tvar uniqueEdges = new Map(); //used to collect unique doc IDs in it's keys\n\tvar personEdges = new Array(); //the array of unique edges we will return\n\t//for every doc listed in every case, store that record ID\n\tfor (i=0; i<caseSet.length; i++) {\n\t\t//if this case has any clients... (it should have!!!)\n\t\tif (caseSet[i].hasOwnProperty(\"clientRIDs\")) {\n\t\t\tfor (j=0; j<caseSet[i].clientRIDs.length; j++) {\n\t\t\t\tuniqueEdges.set([caseSet[i].clientRIDs[j]] , true);\n\t\t\t}\n\t\t}\n\t\t//if this case has any other parties... \n\t\tif (caseSet[i].hasOwnProperty(\"partyRIDs\")) {\n\t\t\tfor (j=0; j<caseSet[i].partyRIDs.length; j++) {\n\t\t\t\tuniqueEdges.set([caseSet[i].partyRIDs[j]] , true);\n\t\t\t}\n\t\t}\n\t}\n\t//convert the keys of uniqueEdges into the values of a regular array\n\tfor (s of uniqueEdges.keys()) personEdges.push(s);\n\tconsole.log(\"identified \" + uniqueEdges.size + \" unique person edges. \");\n\treturn personEdges;\n}",
"function identifyInfoNeeded(caseSet){\n\t//caseSet is an array, for each case record object, in_filedIn is an array of strings with the recordID of an Edge leading to a document\n\tvar uniqueEdges = new Map(); //used to collect unique doc IDs in it's keys\n\tvar infoEdges = new Array(); //the array of unique edges we will return\n\t//for every doc listed in every case, store that record ID\n\tfor (i=0; i<caseSet.length; i++) {\n\t\t//if this case has any clients... (it should have!!!)\n\t\tif (caseSet[i].hasOwnProperty(\"infoRIDs\")) {\n\t\t\tfor (j=0; j<caseSet[i].infoRIDs.length; j++) {\n\t\t\t\tuniqueEdges.set([caseSet[i].infoRIDs[j]] , true);\n\t\t\t}\n\t\t}\n\t}\n\t//convert the keys of uniqueEdges into the values of a regular array\n\tfor (s of uniqueEdges.keys()) infoEdges.push(s);\n\tconsole.log(\"identified \" + uniqueEdges.size + \" unique info edges. \");\n\treturn infoEdges;\n}",
"function testGetDocIdsAndPages() {\n apis.getDocIds('', rankingURL, (resp) => {\n assert(resp.docs);\n assert(resp.docs.length == 0);\n\n apis.getPages(resp.docs, indexingURL, (res) => {\n assert(res.length == 0);\n });\n });\n\n apis.getDocIds('fish', rankingURL, (resp) => {\n assert(resp.docs);\n assert(resp.docs.length > 0);\n\n const docIds = [];\n for ( let i = 0; i < resp.docs.length; i++) {\n docIds.push(resp.docs[i].docid);\n }\n\n apis.getPages(docIds, indexingURL, (res) =>{\n assert(res.length >= 2);\n });\n });\n}",
"function testGetDocIds() {\n apis.getDocIds('', rankingURL, (resp) => {\n assert(resp.docs);\n assert(resp.docs.length == 0);\n });\n\n apis.getDocIds('test test', rankingURL, (resp) => {\n assert(resp.docs);\n assert(resp.docs.length == 0);\n });\n\n apis.getDocIds('fish', rankingURL, (resp) => {\n assert(resp.docs);\n assert(resp.docs.length == 2);\n });\n}",
"function addDocuments() {\n firstQueryStub.push({\n ...MOCK_DOCUMENTS[0],\n pk: 'case|101-18',\n sk: 'docket-entry|a-document-id-123',\n });\n firstQueryStub.push({\n ...MOCK_DOCUMENTS[1],\n pk: 'case|101-18',\n sk: 'docket-entry|a-document-id-456',\n });\n }",
"function processDocIds(docIds){\n for (var i in docIds){\n var docId = docIds[i];\n console.log(docId);\n $.get(\"/get_document_info/\"+docId, function(docInfo){\n DOC_INFO_CACHE[docInfo.id] = docInfo;\n createDocPanel(docInfo);\n if (docInfo.is_valid\n && !docInfo.email_required\n && !docInfo.passcode_required){\n\n downloadDoc(docInfo.id);\n }\n });\n\n\n }\n}",
"function getTagNeedIDs( tags, userid ) {\n\n var tempTags = tags;\n\n if (tempTags.length < 1) { \n return null;\n } else {\n \n // find other needs with the same tag(s) \n\n var tempNeedUserId = userid;\n var selector1 = {snapshot: { $exists: false } };\n // check only for needs tagged by OTHER users\n var selector2 = {createdBy: {$ne: tempNeedUserId}};\n var selector3 = {tags: {$in:tempTags}};\n \n // return only the field _id \n var options = {fields: {_id: 1}};\n \n var tempNeedsWithSameTag = Needs.find( { $and: [selector1, selector2, selector3]}, options);\n //var tempNeedsWithSameTag = Needs.find( { $and: [selector1, selector2, selector3]});\n \n //var htmlString;\n\n console.log (\"---getTagNeedIDs---\")\n console.log (\"tempTags: \".concat(tempTags));\n\n var countNeedIDs = 0;\n var userNames = '';\n var needIDsArray = [];\n \n tempNeedsWithSameTag.forEach(function(doc){\n \n var tempNeedId = doc._id; \n \n needIDsArray.push(tempNeedId);\n \n countNeedIDs = countNeedIDs+1;\n console.log (\"Need ID: \".concat(tempNeedId));\n \n });\n \n if (countNeedIDs > 0) {\n \n // no double needIDs\n needIDsArray = _.uniq(needIDsArray);\n \n return needIDsArray;\n } else {\n return null;\n }\n }\n}",
"getDocumentIds(collaboratorId) {\n let collaborator = this._collaborators[collaboratorId]\n if (!collaborator) {\n // console.log('CollabEngine.getDocumentIds', collaboratorId, 'not found');\n // console.log('CollabEngine._collaborators', this._collaborators);\n return []\n }\n return Object.keys(collaborator.documents)\n }",
"function get_assoc_doc_htmls(kw){\n\t var doc_ids = kw.docs.map(function(doc){\n\t\treturn doc['id'];\n\t });\n\n\t return doc_list_dom.find('.doc').filter(function(idx, doc_html){\n\t\treturn doc_ids.indexOf($(doc_html).data('id')) >= 0;\n\t });\n\t}",
"_eachPossiblyMatchingDoc(selector, fn) {\n const specificIds = LocalCollection._idsMatchedBySelector(selector);\n\n if (specificIds) {\n specificIds.some(id => {\n const doc = this._docs.get(id);\n\n if (doc) {\n return fn(doc, id) === false;\n }\n });\n } else {\n this._docs.forEach(fn);\n }\n }",
"async function hasDocumentedSchein( args ) {\n Y.log( 'Entering Y.doccirrus.api.patient.hasDocumentedSchein', 'info', NAME );\n if( args.callback ) {\n args.callback = require( '../server/utils/logWrapping.js' )( Y, NAME )\n .wrapAndLogExitAsync( args.callback, 'Exiting Y.doccirrus.api.patient.hasDocumentedSchein' );\n }\n const {formatPromiseResult} = require( 'dc-core' ).utils;\n const {user, originalParams, callback} = args;\n\n if( !originalParams.patientId ) {\n callback( Error( 'insufficient arguments' ) );\n return;\n }\n\n const patientId = originalParams.patientId;\n\n let [err, notImportedCaseFolders] = await formatPromiseResult( Y.doccirrus.mongodb.runDb( {\n model: 'casefolder',\n user,\n query: {patientId, imported: {$ne: true}},\n options: {select: ['_id']}\n } ) );\n\n if( err ) {\n Y.log( `could not non imported case folders: ${err.stack || err}`, 'warn', NAME );\n callback( err );\n return;\n }\n\n if( !notImportedCaseFolders.length ) {\n callback( null, false );\n return;\n }\n\n let result;\n [err, result] = await formatPromiseResult( Y.doccirrus.mongodb.runDb( {\n model: 'activity',\n user,\n query: {\n actType: {$in: Y.doccirrus.schemas.activity.scheinActTypes},\n patientId,\n caseFolderId: {$in: notImportedCaseFolders.map( cf => cf._id )},\n status: {$ne: 'IMPORTED'}\n },\n options: {\n limit: 1\n }\n } ) );\n\n if( err ) {\n Y.log( `could not get first schein: ${err.stack || err}`, 'warn', NAME );\n callback( err );\n return;\n }\n\n callback( null, Boolean( result.length ) );\n }",
"function getTagNeeds( tags ) {\n\n var tempTags = tags;\n\n if (tempTags.length < 1) { \n return null;\n } else {\n \n // find other needs with the same tag(s) \n\n var selector1 = {snapshot: { $exists: false } };\n var selector2 = {tags: {$in:tempTags}};\n \n // return only the field _id \n //var options = {fields: {_id: 1}};\n \n //var tempNeedsWithSameTag = Needs.find( { $and: [selector1, selector2, selector3]}, options);\n var tempNeedsWithSameTag = Needs.find( { $and: [selector1, selector2]});\n\n console.log (\"---getTagNeeds---\")\n console.log (\"tempTags: \".concat(tempTags));\n\n var countNeedIDs = 0;\n var userNames = '';\n var needsArray = [];\n \n tempNeedsWithSameTag.forEach(function(doc){\n \n var tempNeed = doc; \n \n needsArray.push(tempNeed);\n \n countNeedIDs = countNeedIDs+1;\n console.log (\"Need: \".concat(tempNeed));\n \n });\n \n if (countNeedIDs > 0) {\n \n // no double needIDs\n //needIDsArray = _.uniq(needIDsArray);\n \n return needsArray;\n } else {\n return null;\n }\n }\n}",
"_eachPossiblyMatchingDoc(selector, fn) {\n const specificIds = LocalCollection._idsMatchedBySelector(selector);\n\n if (specificIds) {\n specificIds.some(id => {\n const doc = this._docs.get(id);\n\n if (doc) {\n return fn(doc, id) === false;\n }\n });\n } else {\n this._docs.forEach(fn);\n }\n }",
"function fetchExistingDocs(txn, docs) {\n var fetched = 0;\n var oldDocs = {};\n\n function readDone(e) {\n if (e.target.result) {\n oldDocs[e.target.result.id] = e.target.result;\n }\n if (++fetched === docs.length) {\n processDocs(txn, docs, oldDocs);\n }\n }\n\n docs.forEach(function (doc) {\n txn.objectStore(DOC_STORE).get(doc.id).onsuccess = readDone;\n });\n }",
"function fetchExistingDocs(txn, docs) {\n var fetched = 0;\n var oldDocs = {};\n\n function readDone(e) {\n if (e.target.result) {\n oldDocs[e.target.result.id] = e.target.result;\n }\n if (++fetched === docs.length) {\n processDocs$$1(txn, docs, oldDocs);\n }\n }\n\n docs.forEach(function (doc) {\n txn.objectStore(DOC_STORE).get(doc.id).onsuccess = readDone;\n });\n }",
"function generateDocuments(perfCase) {\n const documents = [];\n for (let i = 0; i < perfCase.numberOfDocuments; ++i) {\n documents.push(perfCase.documentGenerator(i));\n }\n return documents;\n}",
"function TestIncludeDocs(callback) {\n var q = cb.view(docname, \"simple\", {\n startkey : 1,\n endkey : 5,\n stale: false,\n include_docs : true,\n inclusive_end: false,\n });\n q.query(function(err, results) {\n assert(!err, \"TestIncludeDocs query failed\")\n assert(\n results[0].doc.meta.id === 'query-1',\n \"TestIncludeDocs meta.id mismatch\" )\n assert(\n results[0].doc.json.name === 'beta',\n \"TestIncludeDocs meta.id mismatch\" )\n callback(null, 5)\n });\n }",
"function existingDependTargetReqSpecs(objectId)\n{\n\n\tvar dataXML = emxUICore.getXMLData(\"../requirements/RequirementUtil.jsp?mode=existingDependTargetReqSpecs&objectId=\"+objectId+\"&derivationMode=\"+derivationMode);\n\n\tvar rows \t= $(dataXML).find(\"r\");\n\n\tfor(var i=0; i < rows.length;i++)\n\t{\tvar relatedReqSpecIds \t\t= rows[i].getAttribute('o');\n\t\tinitandDisplayTarget(relatedReqSpecIds);\t\n\t}\n\t\n\t\n}",
"function initiateDocReview()\n{\n var _resetDocSelection = $(\"#resetDocSelection\");\n var _saveDocSelection = $(\"#saveDocSelections\");\n _resetDocSelection.on('click', function(){resetDocRanking();});\n _saveDocSelection.on('click', function(){saveDocSelection();});\n // the loadDocList function is used on two different pages. On the ranking page, the left hand column needs to contain a checkbox\n // so the loadDocList function is called with a parameter of 'checkbox'\n loadDocList(\"checkbox\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Verse of the Day Picture | function getVerseOfTheDayPicture() {
let today = new Date();
let year = today.getFullYear();
var janFirst = new Date(year, 0, 1, 1, 1, 1, 1);
var days = daydiff(janFirst,today);
var dailyVersePictureToGet = Math.ceil((((days / 23) - Math.floor((days / 23)))) * 23);
console.log(dailyVersePictureToGet);
return dailyVersePictureToGet;
} | [
"function DayNightBackground(){\n CurrentTime = new Date().toLocaleTimeString();\n console.log(\"System time: \" +CurrentTime);\n if (CurrentTime >= SRtimeFormat){\n image(ImgDay,0,0);\n }\n if (CurrentTime >= SStimeFormat || CurrentTime < SRtimeFormat){\n image(ImgNight,0,0);\n }\n}",
"function todaysPicture() {\n if (inputValue == '') {\n inputValue = new Date(Date.now());\n formatDate(inputValue);\n console.log(formatDate(inputValue));\n }\n\n function formatDate(inputValue) {\n var day = inputValue.getDate();\n\n var month = inputValue.getMonth();\n month = month + 1;\n\n var year = inputValue.getFullYear();\n return year + \"-\" + month + \"-\" + day;\n }\n }",
"function getPicture(hour) {\n\tif(hour <= 5)\n\t\treturn 1;\n\telse if(hour <= 8)\n\t\treturn 2;\n\telse if(hour <= 11)\n\t\treturn 3;\n\telse if(hour <= 15)\n\t\treturn 4;\n\telse if(hour <= 18)\n\t\treturn 5;\n\telse if(hour <= 20)\n\t\treturn 6;\n\telse if(hour <= 22)\n\t\treturn 7;\n\telse\n\t\treturn 8;\n}",
"function timeGet(img){\n var year = img.slice(0,4);\n var month = img.slice(4,6);\n var day = img.slice(6,8);\n var date = month + \"/\" + day + \"/\" + year;\n return date;\n}",
"function dayMimg(){\n let today=new Date(),\n hour=today.getHours();\n \n\n\n if(hour<12){\n document.body.style.backgroundImage=\"url('img/seher.jpg') \"\n dayM.textContent=\"Sabahınız xeyir\";\n }else if(hour<18){\n document.body.style.backgroundImage=\"url('img/axsamustu.jpg') \"\n dayM.textContent=\"Günortanız xeyir\";\n }else{\n document.body.style.backgroundImage=\"url('img/gece.jpg') \"\n dayM.textContent=\"Axşamınız xeyir\"; \n document.body.style.color='white' \n }\n}",
"function episodeSevenGetInfo(content){\n\tvar movie = {} ;\n\tvar tmp = '';\n\tmovie.title = getValue(content, '<strong>', '</strong>');\t\n\tmovie.plot = getValue(content, '<li><h2 id=\"s_e\">', '</li></ul></div>').replace(/<\\/li>/gi, '\\n');\n\ttmp = getValue(content, \"background-image:url('\", ');\">','start',0, -1);\n\tif(tmp != '')\n\t\tmovie.icon = EPISODE7 + tmp;\n\treturn movie;\n}",
"function getImage(d){\n\tvar club = d[0];\n\tvar result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/notfound.png\";\n\tswitch(club){\n\t\tcase \"Arsenal\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Arsenal.png\"; break; \n\t\tcase \"Sunderland\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Sunderland.png\"; break; \n\t\tcase \"Fulham\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Fulham.png\"; break; \n\t\tcase \"Norwich\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Norwich.png\"; break; \n\t\tcase \"Newcastle\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Newcastle.png\"; break; \n\t\tcase \"Tottenham\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Tottenham.png\"; break; \n\t\tcase \"QPR\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/QPR.png\"; break; \n\t\tcase \"Swansea\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Swansea.png\"; break; \n\t\tcase \"Reading\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Reading.png\"; break; \n\t\tcase \"Stoke\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/StokeCity.png\"; break; \n\t\tcase \"West Brom\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/WestBromwich.png\"; break; \n\t\tcase \"Liverpool\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Liverpool.png\"; break; \n\t\tcase \"West Ham\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/WestHam.png\"; break; \n\t\tcase \"Aston Villa\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/AstonVilla.png\"; break; \n\t\tcase \"Man City\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/ManchesterCity.png\"; break; \n\t\tcase \"Southampton\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Southampton.png\"; break; \n\t\tcase \"Wigan\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Wigan.png\"; break; \n\t\tcase \"Chelsea\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Chelsea.png\"; break; \n\t\tcase \"Man United\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/ManchesterUnited.png\"; break; \n\t\tcase \"Everton\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Everton.png\"; break; \n\t\tcase \"Wolves\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Wolves.png\"; break; \n\t\tcase \"Blackburn\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/BlackburnRovers.png\"; break; \n\t\tcase \"Bolton\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/Bolton.png\"; break; \n\t\tcase \"Bergen\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/mons.png\"; break; \n\t\tcase \"Oud-Heverlee Leuven\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/ohl.jpg\"; break; \n\t\tcase \"Club Brugge\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/club_brugge.png\"; break; \n\t\tcase \"Waasland-Beveren\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/waasland.png\"; break; \n\t\tcase \"Germinal\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/beerschot.png\"; break; \n\t\tcase \"Lokeren\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/lokeren.png\"; break; \n\t\tcase \"Kortrijk\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/kortrijk.png\"; break; \n\t\tcase \"Anderlecht\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/anderlecht.png\"; break; \n\t\tcase \"Mechelen\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/mechelen.png\"; break; \n\t\tcase \"Charleroi\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/charleroi.png\"; break; \n\t\tcase \"Genk\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/genk.png\"; break; \n\t\tcase \"Cercle Brugge\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/cercle.png\"; break; \n\t\tcase \"Gent\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/aagent.png\"; break; \n\t\tcase \"Lierse\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/lierse.png\"; break; \n\t\tcase \"Standard\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/standard.png\"; break; \n\t\tcase \"Waregem\": result = \"http://www.student.kuleuven.be/~s0187958/Thesis/Data/Images/zulte.png\"; break; \n\t}\t\n\treturn result;\n}",
"function imagenColor(terminacion){\n\t\n\tvar path = '../';\n\tswitch (terminacion) {\n\tcase 1:\n\t\tpath= path+VERDE;\n\t\tbreak;\n\tcase 2:\n\t\tpath= path+VERDE;\n\t\tbreak;\n\tcase 3:\n\t\tpath= path+ROJO;\n\t\tbreak;\n\tcase 4:\n\t\tpath= path+ROJO;\n\t\tbreak;\n\tcase 5:\n\t\tpath= path+AMARILLO;\n\t\tbreak;\n\tcase 6:\n\t\tpath= path+AMARILLO;\n\t\tbreak;\n\tcase 7:\n\t\tpath= path+ROSA;\n\t\tbreak;\n\tcase 8:\n\t\tpath= path+ROSA;\n\t\tbreak;\n\tcase 9:\n\t\tpath= path+AZUL;\n\t\tbreak;\n\tcase 0:\n\t\tpath= path+AZUL;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\t//Ti.API.info('Terminacion: '+terminacion + 'IMG: '+path);\n\treturn path;\n}",
"function getDatePicture(date, printDesc, callback) {\n var url = URLtemplate.replace(\"{{DATE}}\", formatDate(date));\n request(url, function(error, response, html) {\n if (error) {\n console.log(error);\n return;\n }\n var $ = cheerio.load(html);\n if (printDesc)\n console.log($('body > p:nth-child(3)').text());\n callback(\"http://apod.nasa.gov/apod/\"+$(\"img\").attr('src'));\n });\n}",
"function getIconDayOrNight(){\n if(time < 5){\n return \"night\";\n }else if(time > 5 && time < 18){\n return \"day\";\n }else{\n return \"night\";\n }\n }",
"function get_photo_data(day)\n{\n switch (day) {\n case 'day1': return get_day_1();\n case 'day2': return get_day_2();\n case 'day3': return get_day_3();\n case 'day4': return get_day_4();\n case 'day5': return get_day_5();\n }\n\n return;\n}",
"function getImage(d){\n\tvar club = d[0];\n\tvar result = \"Images/notfound.png\";\n\tswitch(club){\n\t\tcase \"Arsenal\": result = \"Images/Arsenal.png\"; break; \n\t\tcase \"Sunderland\": result = \"Images/Sunderland.png\"; break; \n\t\tcase \"Fulham\": result = \"Images/Fulham.png\"; break; \n\t\tcase \"Norwich\": result = \"Images/Norwich.png\"; break; \n\t\tcase \"Newcastle\": result = \"Images/Newcastle.png\"; break; \n\t\tcase \"Tottenham\": result = \"Images/Tottenham.png\"; break; \n\t\tcase \"QPR\": result = \"Images/QPR.png\"; break; \n\t\tcase \"Swansea\": result = \"Images/Swansea.png\"; break; \n\t\tcase \"Reading\": result = \"Images/Reading.png\"; break; \n\t\tcase \"Stoke\": result = \"Images/StokeCity.png\"; break; \n\t\tcase \"West Brom\": result = \"Images/WestBromwich.png\"; break; \n\t\tcase \"Liverpool\": result = \"Images/Liverpool.png\"; break; \n\t\tcase \"West Ham\": result = \"Images/WestHam.png\"; break; \n\t\tcase \"Aston Villa\": result = \"Images/AstonVilla.png\"; break; \n\t\tcase \"Man City\": result = \"Images/ManchesterCity.png\"; break; \n\t\tcase \"Southampton\": result = \"Images/Southampton.png\"; break; \n\t\tcase \"Wigan\": result = \"Images/Wigan.png\"; break; \n\t\tcase \"Chelsea\": result = \"Images/Chelsea.png\"; break; \n\t\tcase \"Man United\": result = \"Images/ManchesterUnited.png\"; break; \n\t\tcase \"Everton\": result = \"Images/Everton.png\"; break; \n\t\tcase \"Wolves\": result = \"Images/Wolves.png\"; break; \n\t\tcase \"Blackburn\": result = \"Images/BlackburnRovers.png\"; break; \n\t\tcase \"Bolton\": result = \"Images/Bolton.png\"; break; \n\t\tcase \"Bergen\": result = \"Images/mons.png\"; break; \n\t\tcase \"Oud-Heverlee Leuven\": result = \"Images/ohl.jpg\"; break; \n\t\tcase \"Club Brugge\": result = \"Images/club_brugge.png\"; break; \n\t\tcase \"Waasland-Beveren\": result = \"Images/waasland.png\"; break; \n\t\tcase \"Germinal\": result = \"Images/beerschot.png\"; break; \n\t\tcase \"Lokeren\": result = \"Images/lokeren.png\"; break; \n\t\tcase \"Kortrijk\": result = \"Images/kortrijk.png\"; break; \n\t\tcase \"Anderlecht\": result = \"Images/anderlecht.png\"; break; \n\t\tcase \"Mechelen\": result = \"Images/mechelen.png\"; break; \n\t\tcase \"Charleroi\": result = \"Images/charleroi.png\"; break; \n\t\tcase \"Genk\": result = \"Images/genk.png\"; break; \n\t\tcase \"Cercle Brugge\": result = \"Images/cercle.png\"; break; \n\t\tcase \"Gent\": result = \"Images/aagent.png\"; break; \n\t\tcase \"Lierse\": result = \"Images/lierse.png\"; break; \n\t\tcase \"Standard\": result = \"Images/standard.png\"; break; \n\t\tcase \"Waregem\": result = \"Images/zulte.png\"; break; \n\t}\t\n\treturn result;\n}",
"function getFenImage(id) {\n return \"http://www.fen-to-image.com/image/20/single/coords/\" + gamesInPlay[id].fen().split(\" \")[0];\n}",
"function getTodayBg() {\n const timeOfDayPath = ['night/', 'morning/', 'afternoon/', 'evening/'];\n const imagesPath = [\n '01.jpg',\n '02.jpg',\n '03.jpg',\n '04.jpg',\n '05.jpg',\n '06.jpg',\n '07.jpg',\n '08.jpg',\n '09.jpg',\n '10.jpg',\n '11.jpg',\n '12.jpg',\n '13.jpg',\n '14.jpg',\n '15.jpg',\n '16.jpg',\n '17.jpg',\n '18.jpg',\n '19.jpg',\n '20.jpg',\n ];\n let base = 'img/';\n let imageSrc = '';\n\n function shuffle(arr) {\n let j, temp;\n for (let i = arr.length - 1; i > 0; i--) {\n j = Math.floor(Math.random() * (i + 1));\n temp = arr[j];\n arr[j] = arr[i];\n arr[i] = temp;\n }\n return arr;\n }\n\n for (let i = 0; i < 4; i++) {\n shuffle(imagesPath);\n for (let j = 0; j < 6; j++) {\n imageSrc = base + timeOfDayPath[i] + imagesPath[j];\n bgArray.push(imageSrc);\n }\n }\n\n return bgArray;\n}",
"function showClockImage() {\n clockImage.src = \"clockImages/warpedClock.png\";\n}",
"function getSchiffPic(id){\r\n\tswitch (id) {\r\n case 1:\r\n\t\treturn \"Schiffe/A-Wing.png\";\r\n\t\r\n\tcase 2:\r\n return \"Schiffe/X-Wing.png\";\r\n break;\r\n case 3:\r\n return \"Schiffe/Y-Wing.png\";\r\n\t\tbreak;\r\n\tcase 4:\r\n\t\treturn \"Schiffe/Tie-Interceptor.png\";\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\treturn \"Schiffe/Tie-Advanced.png\";\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\treturn \"Schiffe/Tie-Bomber.png\";\r\n\t\tbreak;\r\n\tcase 0:\r\n\t\treturn \"Schiffe/Tie-Fighter.png\";\r\n\t\tbreak;\r\n default:\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n}",
"function drawTalkImage() {\n\tif (talkImage === null) {\n\t\t//draw image of earth\n\t\timageCheck();\n\t}\n\telse {\n\t\timage(talkImage, 73, 570);\n\t}\n}",
"function iconSelect(datemaj) {\n var today = new Date();\n var delta = diffDays(today, datemaj);\n if (delta <= 60) {\n return \"img/ic_flipper_green.png\";\n } else {\n if (delta > 365) {\n return \"img/ic_flipper_black.png\";\n } else {\n return \"img/ic_flipper_orange.png\";\n }\n }\n}",
"function getImagePerDayTime() {\n let now = new Date(),\n hour = now.getHours(),\n d_time;\n\n // 24hr Format\n hour = hour % 24 || 24;\n\n if (hour < 12 && hour >= 6) {\n d_time = 0;\n } else if (hour < 18 && hour >= 12) {\n d_time = 1;\n } else if (hour < 24 && hour >= 18) {\n d_time = 2;\n } else {\n d_time = 3;\n }\n\n const index_Time = d_time;\n const index_Image = count_image % images.length;\n const imageSrc = base + day_Time[index_Time] + images[index_Image];\n\n localStorage.setItem('momentum_d_timeId', index_Time);\n localStorage.setItem('momentum_imageId', index_Image);\n localStorage.setItem('momentum_imageSrc', imageSrc);\n console.log('The getImagePerDayTime worked:');\n console.log(`Background changed to ${imageSrc}`);\n\n viewBgImage(imageSrc);\n\n count_image++;\n\n // setTimeout(getImagePerDayTime, HOUR);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain the delegate function applied to a model property by Kontext | function getDelegate(model, key) {
var result = false,
property = key.split('.'),
desc;
// deal with scoped keys such as 'foo.bar', which needs to address the 'bar' property in the submodel
// residing in model.foo
property.forEach(function(name, index, all) {
if (key) {
key = name in model ? name : null;
if (index < all.length - 1) {
model = model[key];
}
}
});
if (key && key in model) {
// if a model key is an explicitly assigned delegate, we utilize it
if (isDelegate(model[key])) {
result = model[key];
}
// otherwise we need to get the property descriptor first
else {
desc = Object.getOwnPropertyDescriptor(model, key);
result = desc.get;
}
}
return result;
} | [
"function getDelegate(model, key) {\n\t\t\tvar result = false,\n\t\t\t\tlist, length, property, desc;\n\n\t\t\tif (model && typeof model === 'object') {\n\t\t\t\tif (key in model) {\n\t\t\t\t\t// if a model key is an explicitly assigned delegate, we utilize it\n\t\t\t\t\tif (isDelegate(model[key])) {\n\t\t\t\t\t\tresult = model[key];\n\t\t\t\t\t}\n\n\t\t\t\t\t// otherwise we need to get the property descriptor first\n\t\t\t\t\telse {\n\t\t\t\t\t\tdesc = Object.getOwnPropertyDescriptor(model, key);\n\t\t\t\t\t\tresult = desc.get;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlist = key.split('.');\n\t\t\t\t\tlength = list.length - 1;\n\n\t\t\t\t\twhile (length > 0) {\n\t\t\t\t\t\tproperty = list.slice(0, length).join('.');\n\t\t\t\t\t\tif (property in model) {\n\t\t\t\t\t\t\treturn getDelegate(model[property], list.slice(length).join('.'));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t--length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}",
"get(target, prop, value, receiver) {\n\n if(ProxyFactory._ehFuncao(target[prop]) && \n props.includes(prop)){\n // retorna uma nova função com contexto dinâmico\n // antes que o apply aplicado por padrão pelo\n // interpretador seja chamado.\n return function () {\n console.log(`${prop} disparou a armadilha`);\n\n target[prop].apply(target, arguments);\n\n armadilha(target);\n }\n } else {\n return target[prop];\n }\n }",
"getFunc() {\n return this.func;\n }",
"function isFunction(target, propertyKey) {\n return Reflect.getMetadata(EdmFunction, target.prototype, propertyKey) || false;\n}",
"get (target, prop, receiver) {\n\n // This intercep the interception to test if the call is from a function already known\n // in this case we are intercepting the functions \"adiciona\" and \"esvazia\" of the class \"ListaNegociacoes\" object\n if(['adiciona', 'esvazia'].includes(prop) && typeof(target[prop]) == typeof(Function)) {\n\n return function() {\n\n console.log(`a propriedade \"${prop}\" foi interceptada`);\n Reflect.apply(target[prop], target, arguments);\n }\n\n }\n\n // and if the call is a regular GET to a object`s property just execute it\n\n console.log(`a propriedade \"${prop}\" foi interceptada`);\n return Reflect.get(target, prop, receiver);\n\n }",
"getFunction(name) {\n if (typeof(this.props.report.eventHandlers[name]) === \"function\") {\n return eval(this.props.report.eventHandlers[name]);\n } else if (typeof(this[name]) === \"function\") {\n return this[name]\n }\n }",
"get feeDataFunc() {\n return this.#feeDataFunc;\n }",
"get (target, property) {\n // If no property, just return a noop function.\n if (!property) return noop;\n // Return a function for accessing given property on\n // an arbitrary object passed as argument.\n return obj => obj && obj[property];\n }",
"visitFunctionProperty(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"@onPropertyChanged(\"name\", [\"modify\"])\n\t\t@spyDecorator\n\t\tonPropertyRegisteredCallback() {}",
"customPropCallback(callback) {\r\n this.flag |= DataFlags.USE_CUSTOM_PROP_GETTER;\r\n this.data.flag |= PropFlags$3.USE_CUSTOM_PROP_GETTER;\r\n this.propGetter = callback;\r\n\r\n return this;\r\n }",
"get accessor_prop() { /* function body here */ }",
"function getBindingsAndMakeAccessors(node, context) {lacuna_lazy_load(\"node_modules/knockout/build/output/knockout-latest.debug.js[129147:129243]\", functionData => eval(functionData))}",
"_functionNode() {\n return this.lambdaFunction.node;\n }",
"function coerceEventProp(prop, key) {\n return is.fun(prop) ? prop : key && prop ? prop[key] : undefined;\n }",
"function coerceEventProp(prop, key) {\n return is.fun(prop) ? prop : key && prop ? prop[key] : undefined;\n}",
"function MyDecoratorForProperty() {\n return function (target, property) {\n console.log('- - - - Property Decorators');\n console.log('target: ', target);\n console.log('property: ', property);\n };\n}",
"function getPropWalkFn(descriptor) {\n const parts = descriptor.split(/ ?\\[\\]/);\n if (parts.length === 2) {\n return mapProp.bind(null, parts[0]);\n }\n return getProp.bind(null, descriptor);\n }",
"function getPropWalkFn(descriptor) {\n var parts = descriptor.split(/ ?\\[\\]/);\n if (parts.length === 2) {\n return mapProp.bind(null, parts[0]);\n }\n return getProp.bind(null, descriptor);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function pour la valeur du select Retourne la valeur du select selectId | function getSelectValue(selectId)
{
/**On récupère l'élement html <select>*/
var selectElmt = document.getElementById(selectId);
/**
selectElmt.options correspond au tableau des balises <option> du select
selectElmt.selectedIndex correspond à l'index du tableau options qui est actuellement sélectionné
*/
return selectElmt.options[selectElmt.selectedIndex].value;
} | [
"function get_select_value(selectId)\n{\n\tvar index=selectId.selectedIndex;\n\tvar value=selectId.options[index].value;\n\treturn value;\n}",
"function getSelectedOptionValue(selectId)\r\n{\r\n var index = selectId.selectedIndex; //get the selected item index number \r\n var value = selectId.options[index].value;\r\n return (value);\r\n}",
"function getSelectValue(id){\r\n var elementid = \"#\" + id;\r\n var value = $(elementid).find(\":selected\").val();\r\n return value;\r\n}",
"function filterSelectID(){\n \n }",
"function getSelectedOptionValue(id){\n return $(`#${id} option:selected`).val()\n}",
"function get_id_from_selected(p_select_obj, p_hdn_obj) {\n p_hdn_obj.value = p_select_obj(p_select_obj.selectedIndex).id;\n}",
"function getSelectBoxValue(id) {\r\n return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;\r\n}",
"function onSelectChanged(event) {\n const id = event.target.value\n if (!id) return onChange(null)\n return onChange(id)\n }",
"function seleccion(){\n\t\tvar seleccion = document.getElementById(\"cliente\");\n\t\tvar idCliente = seleccion.options[seleccion.selectedIndex].value;\n\t\tdocument.getElementById(\"idCliente\").value = idCliente;\n\t}",
"function selectedIntValue(select) {\n return parseInt(select.options[select.selectedIndex].value);\n }",
"function ValorSelecionado(dom_select) {\n return dom_select.length > 0 ?\n dom_select.options[dom_select.selectedIndex].value : null;\n}",
"function getSelectedAccount(selectId)\n{\n var select = $(selectId)[0]\n return select.options[select.selectedIndex].text\n}",
"function mngCondAssessFilterPanel_blId_selectValue(){\n View.selectValue('mngCondAssessFilterPanel', getMessage(\"blCode\"),\n\t\t\t\t\t\t\t['activity_log.site_id','activity_log.bl_id'], 'bl', ['bl.site_id','bl.bl_id'], ['bl.site_id','bl.bl_id','bl.name']);\n}",
"function getSelectedValue(select) {\n return select.find('option:selected').attr('value');\n}",
"function getSelectedDataId() {\n\t\tvar retorno = null;\n\n\t\t$(\".DataGridConsulta > table > tbody > tr\").each(function(index) {\n\t\t\tif ($(this).attr(\"data-selected\") == \"true\") {\n\t\t\t\tretorno = $(this).attr(\"data-id\");\n\t\t\t}\n\t\t});\n\t\treturn retorno;\n\t}",
"function selectedValue () {\n const x = document.getElementById(\"campusesSelect\").selectedIndex;\n return document.getElementsByTagName(\"option\")[x].value;\n }",
"static getSelectedItem(id) {\n const el = document.getElementById(id);\n const selectedVal = el.options[el.selectedIndex];\n\n return selectedVal;\n }",
"function getSelectedLabel(selectId){\n\t\t\t\tvar e = document.getElementById(selectId);\n\t\t\t\tif(e.options[e.selectedIndex] === undefined){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn e.options[e.selectedIndex].value;\n\t\t\t}",
"SelectedId()\n {\n var i = this.selItem;\n if( i <= 0 || i >= this.Items.length ) return 0;\n\n return this.Items[i].Id;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================================================================== if global = 'X', then id_libelle come from common iknow text if text exists ans global not set, then put raw text if only id_libelle is define, then replace by local iobject text if chaine is not null that means &1 string in text will be replace by chaine if extended_help not null then means CTRL+F11 available ================================================================== | function set_text_help(id_libelle,texte,global,chaine,extended_help)
{
if(typeof(global) == 'undefined' || global == '')
{
if(typeof(texte) == 'undefined' || texte == '')
{
var libelle_temp = decodeURIComponent(libelle[id_libelle]);
}
else
{
var libelle_temp = texte;
}
}
else
{
var libelle_temp = decodeURIComponent(libelle_common[id_libelle]);
}
if(typeof(chaine) == 'undefined' || chaine == '') //SIBY
{
// No replace
}
else
{
libelle_temp = libelle_temp.replace(/&1/g,chaine); // Replace all " by "
}
/**==================================================================
* Display is extended help is available
====================================================================*/
if(extended_help != 'undefined' && extended_help)
{
libelle_temp = libelle_temp + ' (' + decodeURIComponent(libelle_common[205]) + ')';
}
/**==================================================================*/
/**==================================================================
* Display help text in footer
====================================================================*/
iknow_panel_set_sous_titre(libelle_temp);
/**==================================================================*/
} | [
"function over(id_doc,id_help,texte,global,chaine)\r\n\t{\r\n\t\tikdoc(id_doc);// Add call of doc page\r\n\t\tset_text_help(id_help,texte,global,chaine,id_doc);\r\n\t}",
"function replaceTextAtlassian(shortcut, autotext)\n {\n debugLog(\"Domain: Atlassian\");\n\n // Get the focused / selected text node\n var iframeWindow = document.querySelector(SELECTOR_ATLASSIAN_EDIT).contentWindow;\n var node = findFocusedNode(iframeWindow);\n debugLog(\"node:\", node);\n\n // Pass onto editable iframe text handler\n replaceTextContentEditable(shortcut, autotext, node, iframeWindow);\n }",
"function UnbInsertText(what, replace)\r\n{\r\n\tif (replace == null) replace = 0;\r\n\t\r\n// changes for pragmaMx\r\n\tif (openerdoc) {\r\n\t\tcurdoc = openerdoc;\r\n\t} else {\r\n\t\tcurdoc = document;\r\n\t}\r\n// end changes for pragmaMx\r\n\r\n\tif (textbox.createTextRange)\r\n\t{\r\n\t\ttextbox.focus();\r\n\t\tcurdoc.selection.createRange().duplicate().text = what;\r\n\t\ttextbox.focus();\r\n\t}\r\n\telse if (textbox.selectionStart >= 0)\r\n\t{\r\n\t\t// Mozilla without selected text\r\n\t\tvar start_selection = textbox.selectionStart;\r\n\t\tvar end_selection = textbox.selectionEnd;\r\n\t\tvar scroll_top = textbox.scrollTop;\r\n\t\tvar scroll_left = textbox.scrollLeft;\r\n\r\n\t\t// fetch everything from start of text area to selection start\r\n\t\tvar start = textbox.value.substring(0, start_selection - replace);\r\n\t\t// fetch everything from end of selection to end of text area\r\n\t\tvar end = textbox.value.substring(end_selection, textbox.textLength);\r\n\r\n\t\ttextbox.value = start + what + end;\r\n\r\n\t\ttextbox.selectionStart = textbox.selectionEnd = start_selection - replace + what.length;\r\n\t\ttextbox.focus();\r\n\t\ttextbox.scrollTop = scroll_top;\r\n\t\ttextbox.scrollLeft = scroll_left;\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttextbox.value += what;\r\n\t\ttextbox.focus();\r\n\t}\r\n// changes for pragmaMx\r\n\tif (openerdoc) {\r\n\t\twindow.focus();\r\n\t}\r\n// end changes for pragmaMx\r\n}",
"function setFinnishText(){\r\n\t/**\r\n\t * BASIC TOUR\r\n\t */\r\n\twelcome = \"Moi! <br/> Tämä kierros opastaa perusnavigointiin U-QASAR-alustalla.\";\r\n\tproject = \"Projektit-valikossa voit tarkastella ja editoida käynnissäolevia projekteja, luoda uusia ja tuoda/viedä projekteja.\";\r\n\tqmodel = \"Laatumallit-valikossa voit tarkastella ja editoida nykyisiä laatumalleja, luoda uusia ja tuoda/viedä niitä.\";\r\n\tsearch = \"Jos haluat etsiä tietoja alustalta, käytä tätä hakukenttää.\";\r\n\tnotify = \"Jos sinulle on saapunut ilmoituksia, sinulle näytetään ilmoitus täällä!\";\r\n\tlanguageContent = \"Vaihda alustan kieli tässä.\";\r\n\tadmin = \"Koska olet tällä hetkellä kirjautuneena <i>Järjestelmänvalvojana</i>, löydät vaihtoehtoja U-QASAR-alustan konfigurointiin ja kustomointiin, kuten käyttäjä, yritys ja metadata-tietojen hallintaan ja paljon muuta.\";\r\n\tuser = \"Tässä valikossa löydät käyttäjäprofiilit ja voit editoida niitä ja luoda ja editoida personoituja näkymiä (kojelautoja). <br/> <br/> \" +\r\n\t\t\t\"Jos haluat tehdä U-QASAR-kierroksen, tällä hetkellä on useita kierroksia valittavana: <br/>\" +\r\n\t\t\t\"<ul class='tour'>\" +\r\n\t\t\t\t\"<li><i class='icon-home'/><span>U-QASAR-perusteet (tällä hetkellä aktiivinen) </span></li>\" +\r\n\t\t\t\t\"<li><i class='icon-sitemap'/><span>Projektikierros</span></li>\" +\r\n\t\t\t\"</ul>\" +\r\n\t\t\t\"Voit aloittaa tai toistaan sivukohtaisen kierroksen milloin vain, klikkaa vain yksinkertaisesti tässä menussa <i class='icon-info-sign'/><b>\"+ $('#takeTour').text().trim() +\"</b> ollessasi halutulla sivulla.\";\r\n\r\n\t// TITLES\t\t\r\n\ttitleWelcome = \"TERVETULOA U-QASAR:iin\";\r\n\ttitleProject = \"PROJEKTIT\";\r\n\ttitleQmodel = \"LAATUMALLIT\";\r\n\ttitleSearch = \"ETSI\";\r\n\ttitleNotify = \"ILMOITUKSET\";\r\n\ttitleLanguage = \"KIELI\";\r\n\ttitleAdmin = \"JÄRJESTELMÄVALVOJA\";\r\n\ttitleUser = \"KÄYTTÄJÄ\";\r\n\t/**\r\n\t * PROJECT TOUR\r\n\t */\r\n\tprojectTree = \"Tämän avattavan/suljettavan puurakenteen ymmärtämiseksi huomioi seuraava selitys:\" +\r\n\t\t\t\t\t\"<table>\" +\r\n\t\t\t\t\t\t\"<tr><td><i class='icon-sitemap'/> Laatuprojekti ('Quality Model')</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:10px'><i class='icon-tasks'/> Laatutavoite</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:20px'><i class='icon-dashboard'/> Laatuindikaattori</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:30px'><i class='icon-signal'/> Metriikka</td></tr>\" +\r\n\t\t\t\t\t\"</table><br/>\"+\r\n\t\t\t\t\t\"Kukin puun solmu on avattavissa/suljettavissa kolmioikonin kautta ja se edustaa klikattavaa linkkiä vastaavalle puun solmun sisältösivulle.\";\r\n\ttreeOptions = \"Käytä näitä pikatoimintopainikkeita \" +\r\n\t\t\t\t\t\"<ul style='list-style:none'>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-plus'/> uusien projektien luomiseen, </li> \" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-pencil'/> nykyisen projektin muokkaukseen,</li>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-chevron-sign-down'/> puun solmujen siirtämiseen puun sisällä,</li>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-trash'/> nykyisen projektin poistamiseen.</li>\" +\r\n\t\t\t\t\t\"</ul>\";\r\n\tqualityStatus = \"Huomioi laatuprojektin nykyinen arvo tässä. Väri indikoi laatutasoa (punainen/keltainen/vihreä).\";\r\n\tprojectInformation = \"Huomioi projektille spefinen tieto, johon mm. sisältyvät osallistuvat tiimin jäsenet, käytetty metadata ja laatutrendikaaviot tällä alueella.\";\r\n\ttitleTree = \"PROJEKTIPUU\";\r\n\ttitleOptions = \"VAIHTOEHDOT\";\r\n\ttitleStatus = \"LAATUSTATUS\";\r\n\ttitleInformation= \"PROJEKTITIEDOT\";\r\n\r\n\t/**\r\n\t * dashboard TOUR\r\n\t */\r\n\taddWidget = \"Tästä menusta voit lisätä erilaisia widgettejä nykyiselle kojelaudalle. Voit valita seuraavista widgeteistä:\" +\r\n\t\t\t\t\t\"<table>\" +\r\n\t\t\t\t\t\t\"<tr><td> Projektin laatu -widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> JIRA-widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> Sonar-widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> TestLink-widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> Projektipuu-widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> Poikkeamat datassa -widget</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td> JIRA tekninen velka -widget</td></tr>\" +\r\n\t\t\t\t \"</table><br/>\";\r\n\tupdateDashboard = \"Valitse Päivitä päivittääksesi nykyisen kojelaudan ja sillä olevat widgetit.\"; \r\n\tshareDashboard = \"Valitse Jaa jakaaksesi nykyisen kojelaudan muiden käyttäjien kanssa.\";\r\n\tresetDashboard = \"Valitse Nollaa nollataksesi nykyisen kojelaudan (tyhjentää kojelaudan kaikista widgeteistä).\";\r\n\tdeleteDashboard = \"Valitse Poista tuhotaksesi nykyisen kojelaudan.\";\r\n\texportDashboard = \"Valitse Vie luodaksesi PDF-raportin kojelaudan sisällöstä.\"\r\n\ttitleAdd = \"LISÄÄ WIDGET\";\r\n\ttitleUpdate = \"PÄIVITÄ\";\r\n\ttitleShare = \"JAA KOJELAUTA\";\r\n\ttitleReset = \"NOLLAA KOJELAUTA\";\r\n\ttitleDelete = \"POISTA KOJELAUTA\";\r\n\ttitleExport = \"VIE KOJELAUTA\";\r\n\t\r\n\t/**\r\n\t * QMODEL TOUR\r\n\t */\r\n\tqmodelTree = \"Tämän avattavan/suljettavan laatumallin puurakenteen ymmärtämiseksi huomioi seuraavat:\" +\r\n\t\t\t\t\t\"<table>\" +\r\n\t\t\t\t\t\t\"<tr><td><i class='icon-sitemap'/> Laatumalli</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:10px'><i class='icon-tasks'/> Laatutavoite</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:20px'><i class='icon-dashboard'/> Laatuindikaattori</td></tr>\" +\r\n\t\t\t\t\t\t\"<tr><td style='text-indent:30px'><i class='icon-signal'/> Laatumetriikka</td></tr>\" +\r\n\t\t\t\t \"</table><br/>\"+\r\n\t\t\t\t \"Kukin laatumallipuun solmu on avattavissa/suljettavissa kolmioikonin kautta ja solmu on klikattava linkki, joka johtaa vastaavalle puun solmun sisältösivulle.\";\r\n\tqmtreeOptions = \"Käytä näitä pikatoimintopainikkeita \" +\r\n\t\t\t\t\t\"<ul style='list-style:none'>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-plus'/> uuden Laatumallin luomiseen, </li> \" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-pencil'/> olemassaolevan Laatumallin muokkaamiseen,</li>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-chevron-sign-down'/> Laatumallipuun solmujen siirtämiseen puun sisällä,</li>\" +\r\n\t\t\t\t\t\t\"<li> <i class='icon-trash'/> nykyisen Laatumallin poistamiseen.</li>\" +\r\n\t\t\t\t\t\"</ul>\";\r\n\t\r\n\ttitleQMTree = \"LAATUMALLIPUU\";\r\n\ttitleQMOptions = \"VALINNAT\";\r\n\t\r\n\t// NAVI\r\n\tprev = \"« Edellinen\";\r\n\tnext = \"Seuraava »\";\r\n\tend = \"Lopeta kierros\";\t\r\n}",
"function setTextById (id, text) {\n\n}",
"function makeItextLI(textForm, iflabel, ishint) {\n var mugType, liStr, txtStr, inputStr, id, li, text, input, currentLang, Itext, iID, iIDInput,\n isRequired;\n Itext = formdesigner.model.Itext;\n currentLang = formdesigner.currentItextDisplayLanguage;\n mugType = formdesigner.controller.getCurrentlySelectedMugType();\n if(!ishint){\n isRequired = true; //at present we can give everything an Itext ID so...\n iID = mugType.mug.properties.controlElement.properties.labelItextID;\n } else {\n isRequired = (mugType.properties.controlElement.hintItextID.presence === 'required') ||\n (mugType.properties.controlElement.hintLabel === 'required');\n iID = mugType.mug.properties.controlElement.properties.hintItextID;\n }\n if(!iID && isRequired) {\n //make a new iID;\n iID = formdesigner.util.getNewItextID(mugType,ishint);\n //set the new Itext ID in it's respective UI element\n if(ishint) {\n mugType.mug.properties.controlElement.properties.hintItextID = iID;\n iIDInput = $('#controlElement-hintItextID-input');\n }else {\n mugType.mug.properties.controlElement.properties.labelItextID = iID;\n iIDInput = $('#controlElement-labelItextID-input');\n }\n iIDInput.val(iID).keyup(); //.keyup() to trigger existing behaviour, if any.\n }\n if (ishint){\n id = 'fd-itext-hint';\n } else {\n id = 'fd-itext-' + textForm.toLowerCase();\n }\n liStr = '<li id=\"' + id + '\" class=\"fd-property\"></li>';\n txtStr = '<span id=\"' + id +'-txt\" class=\"fd-property-text\">' + iflabel + '</span>';\n inputStr = '<div id=\"' + id + '-input-div\" class=\"fd-prop-input-div chzn-container\"><input id=\"' + id + '-input\" class=\"fd-property-input\"/>';\n li = $(liStr);\n text = $(txtStr);\n input = $(inputStr);\n\n input.find(':input').val(Itext.getValue(iID, currentLang, textForm));\n li.append(text);\n li.append(input);\n\n input.data('ufid', mugType.ufid);\n input.data('textform', textForm);\n input.children(':input').data('ufid', mugType.ufid).data('textform', textForm);;\n input.find(':input').keyup ( function (e) {\n var oldVal, newVal, mugType, curIID;\n oldVal = Itext.getValue(iID,currentLang, textForm);\n newVal = $ (this).val();\n mugType = formdesigner.controller.form.controlTree.getMugTypeFromUFID($(this).data('ufid'));\n if(ishint){\n curIID = mugType.mug.properties.controlElement.properties.hintItextID;\n } else {\n curIID = mugType.mug.properties.controlElement.properties.labelItextID;\n }\n Itext.setValue(curIID, currentLang, textForm, newVal);\n formdesigner.util.changeUITreeNodeLabel($ (this).data('ufid'), formdesigner.util.getMugDisplayName(mugType))\n\n formdesigner.controller.form.fire({\n type: 'form-property-changed',\n propName: 'itext;'+textForm,\n iID: curIID,\n mugType: mugType,\n oldVal: oldVal,\n newVal: newVal\n })\n\n });\n\n return li;\n }",
"function affItalique(texte, id) {\r\n\tdocument.getElementById(id).innerHTML = \"<I>\" + texte + \"</I>\";\r\n}",
"function replaceTextGDOCS(shortcut, autotext)\n {\n debugLog(\"Domain: Google Docs\");\n\n // Get the focused / selected text node\n var iframeWindow = document.querySelector(SELECTOR_GDOCS_EDIT).contentWindow;\n var node = findFocusedNode(iframeWindow);\n debugLog(\"node:\", node);\n\n // We can catch the text / event, but we can't seem to replace\n // or dispatch events to create the additional text\n\n // var e = $.Event('keydown');\n // e.which = 65; // Character 'A'\n // $(node).trigger(e);\n // $(node).trigger(e);\n // $(node).trigger(e);\n // $(node).trigger(e);\n\n //// Custom logic\n // var textInput = node;\n // debugLog(textInput);\n //\n // // Get and process text, update cursor position\n // var text = replaceHTML(node.textContent, shortcut, autotext, 0)\n // , multiline = false\n // , lines\n // ;\n //\n // // If autotext is multiline text, split by newlines, join with <br> tag instead\n // if (autotext.indexOf('\\n') >= 0)\n // {\n // lines = text.split('\\n');\n // text = lines.join('<br>');\n // multiline = true;\n // }\n //\n // // A way to insert HTML into a content editable div with raw JS.\n // // Creates an element with the HTML content, then transfers node by node\n // // to a new Document Fragment that replaces old node\n // // Source from: http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div\n // var el = document.createElement(\"div\") // Used to store HTML\n // , frag = document.createDocumentFragment() // To replace old node\n // , cursorNode; // To track cursor position\n // el.innerHTML = text; // Set HTML to div, then move to frag\n // for (var tempNode; tempNode = el.firstChild; frag.appendChild(tempNode))\n // {\n // debugLog(tempNode.nodeType, tempNode);\n // if (tempNode.nodeType === Node.COMMENT_NODE\n // && tempNode.nodeValue == CURSOR_TRACKING_TAG) {\n // cursorNode = tempNode;\n // }\n // }\n // textInput.appendChild(frag); // add fragment of text\n //\n // // Set cursor position based off tracking node (or last child if we\n // // weren't able to find the cursor tracker), then remove tracking node\n // if (cursorNode) {\n // cursorNode.parentNode.removeChild(cursorNode);\n // }\n }",
"function replaceBtnEHandler(event, _this) {\n var editor = atom.workspace.getActiveTextEditor();\n\n var originalText = document.getElementById(\"originalText\").getModel().getText(); // the long text\n // containing that that is to be replaced\n var filterText = document.getElementById(\"filterText\").getModel().getText(); // this is to be replaced\n var replaceText = document.getElementById(\"replaceText\").getModel().getText(); // with this\n\n if(isValidRegex(filterText)){\n // treat as a regex (modifier g for global is always used, as is m for multiline)\n regexReplace(editor, originalText, filterText, replaceText);\n return;\n } else if(filterText.includes(\"?\")){\n // if filterText contains a \"?\", then we do an advanced replace\n if(advancedReplace(editor, originalText, filterText, replaceText))\n return;\n }\n\n // search through originalText for filterText and replace those instances with replaceText\n // var replacedText = originalText.replace(new RegExp(filterText, \"g\"), replaceText);\n\n // A different replace-all solution as the above solution gave an error on replace \"[0]\" with \"[1]\"\n var replacedText = originalText.split(filterText).join(replaceText);\n\n editor.insertText(replacedText);\n}",
"function suche3(id) {\n var texto;\n var ordbogform;\n var o_text = document.ordbogform.texto.value;\n var i;\n var out=\"\";\n var debug=\"\";\n var oldchar;\n var newchar;\n for (i=0; i<o_text.length; i++) {\n oldchar = o_text.charCodeAt(i);\n newchar = win1251[oldchar];\n if (newchar==undefined) {\n newchar = oldchar\n } \n out=out+String(newchar)\n }\n document.ordbogform.texto.value = out;\n window.open(id+ document.ordbogform.texto.value,'_blank');\n document.ordbogform.texto.value = o_text;\n}",
"function setTextId(num) {\n text = num;\n multiphrase = '';\n lastused_phrase = '';\n}",
"function insert_texts(raw_text,\n\tref_format=def_ref_format,\n\tbible_text_format = def_bible_text_format,\n\tverse_number_format=def_verse_number_format,\n\tafterref_newline=def_afterref_newline,\n\tinterverse_newline=def_interverse_newline,\n\tfirst_verse_number=def_first_verse_number)\n{\n\t// replace all the new lines with a filler string not found in the text\n\t// this is to prevent the bcv parser from picking multiple texts\n\traw_text = raw_text.replaceAll(\"\\n\", \"<N>\")\n\t// fetch the references as osis, using the bcv parser\n\tosises = fetch_refs(raw_text);\n\t// fetch the raw references in the original text. This is to enable the replace function\n\traw_refs = fetch_raw_refs(raw_text, osises);\n\t// console.log(raw_refs);\n\t// return;\n\n\t// if any references were found\n\tif (raw_refs.length > 0)\n\t{\n\t\t// iterate through these references\n\t\tfor (var i = 0; i < raw_refs.length; i++) {\n\t\t\t// fetch osis in osis array\n\t\t\tvar osis = osises[i];\n\t\t\t// fetch the reference\n\t\t\tvar raw_ref = raw_refs[i];\n\t\t\t// var raw_ref = raw_text.substr(osis.indices[0], osis.indices[1] - osis.indices[0]);\n\t\t\t// fetch the text\n\t\t\tvar bible_text = get_bible_text(osis.osis, verse_number_format, interverse_newline, first_verse_number);\n\t\t\t// fetch the reference to be displayed\n\t\t\tvar readable_ref = get_readable_reference(osis.osis)\n\t\t\t// compose the final display format\n\t\t\t// text_render = \">#### \" + readable_ref + \"\" + \"<N>\" + \"> \" + bible_text;\n\t\t\ttext_render = ref_format.replace(\"%ref%\", readable_ref) + (afterref_newline ? \"<N>\": \"\") + bible_text_format.replace(\"%text%\", bible_text);\n\t\t\tconsole.log(text_render);\n\t\t\tconsole.log(osis.osis);\n\t\t\t// replace the references with the appropriately formatted corresponding texts\n\t\t\traw_text = raw_text.replace(\"<N>\"+raw_ref+\"<N>\", \"<N>\"+text_render+\"<N>\");\n\t\t\t// raw_text = raw_text.replace(\"<N></N>\"+raw_ref, \"\\n\"+bible_text);\n\t\t}\n\t}\n\t// replace our filler string with newlines again.\n\traw_text = raw_text.replaceAll(\"<N>\", \"\\n\")\n\treturn raw_text;\n}",
"function replaceWordInField( word, formAndField, newWord, replaceAll )\r\n {\r\n var element = eval('opener.document.' + formAndField);\r\n \r\n if (element.setSelectionRange) \r\n {\r\n replaceWordInFieldNotIE( word, formAndField, newWord, replaceAll );\r\n }\r\n else if (element.createTextRange) \r\n {\r\n replaceWordInFieldIE( word, formAndField, newWord, replaceAll );\r\n }\r\n else\r\n {\r\n alert( WI18N[\"msgSpellPbBrowser\"]);\r\n }\r\n }",
"function gotoedition(pp_val, ee_val, pp_el, frame_id){\n var tt_val;\n tt_val = $('#span_tt_select .label_selected').attr('data-value');\n if (ITLon === true){\n UnInitialize(true);\n } //Add by JK for ITL\n if (HSon === true){\n UnInitializeHS(true);\n } //Add by JK for HS\n \n var editionLoadedCallback = function(status) {\n if (status === 'error') {\n var elem = $('#'+frame_id+\" div[id*='text_elem']\");\n if (elem.find(\".errorMsg\").length == 0) {\n var errorMsg = window.lang.convert('ERROR_LOADING_TEXT', window.lang.currentLang);\n $('<span class=\"errorMsg\">')\n .text(errorMsg)\n .appendTo(elem);\n }\n } else {\n if($('#'+frame_id).find('.doc').length <= 0){\n $('#'+frame_id)\n .find('#text')\n .addClass('doc')\n .addClass('current')\n .attr('data-doc', tt_val);\n } else {\n $('#'+frame_id+\" .doc[data-doc!='\"+tt_val+\"']\").addClass('not_current');\n }\n\n // IT: se il pulsante ITL è attivo e non sono in modalità txttxt, attiva ITL\n if ($(\"#switchITL i\").hasClass('fa fa-chain')){\n if(!($('.current_mode').attr('id') === 'txttxt_link')){\n Initialize();\n }\n } /*Add by JK for ITL*/\n if ($(\"#switchHS i\").hasClass('fa fa-dot-circle-o')){\n if(!($('.current_mode').attr('id') === 'txttxt_link')){\n InitializeHS();\n }\n } /*Add by JK for HS*/\n \n if (!$('#imgd_link').hasClass('current_mode')){\n updateLinesWidth($('#main_right_frame'));\n updateLinesWidth($('#main_left_frame'));\n }\n \n var current_doc = $('#span_tt_select .label_selected').attr('data-value');\n if ( $(\".doc[data-doc='\"+current_doc+\"']\").length > 0 ) {\n $(\".doc[data-doc='\"+current_doc+\"']\").addClass('current');\n }\n \n InitializePopup();\n InitializeRefs();\n InitializeSearch();\n \n $(\"#text_cont .doc, #text_cont-add .doc\").unbind('click').click(function(){\n selectDocumentInPage(this);\n });\n if($(\"#\"+pp_el).parents(\"div[id*='frame']\").find('.like_select.filter')){\n $(\"#\"+pp_el)\n .parents(\"div[id*='frame']\")\n .find('.like_select.filter')\n .find('.option_container .option.selected')\n .removeClass('selected')\n .trigger('click');\n \n }\n /* Integration by LS */\n window.lang.run(); \n /* /end Integration by LS */\n }\n }\n\n $(\"#\"+pp_el+\" div[id*='front_frame']\").empty()\n if ( $(\".main_pp_select .option[data-value='\"+pp_val+\"']\").attr('data-has-front') === 'true' ) {\n $(\"#\"+pp_el+\" div[id*='front_frame']\")\n .attr('data-page', pp_val)\n .load(\"data/output_data/\"+ee_val+\"/page_\"+pp_val+\"-front_\"+ee_val+\".html #text_frame #text\", \n function( response, status, xhr ){\n editionLoadedCallback(status);\n });\n }\n\n $(\"#\"+pp_el+\" div[id*='text_frame']\")\n // .empty()\n .load(\"data/output_data/\"+ee_val+\"/page_\"+pp_val+\"_\"+ee_val+\".html #text_frame #text\",\n function( response, status, xhr ) {\n editionLoadedCallback(status);\n }\n );\n\n var pp_el_upp = pp_el;\n pp_el_upp = pp_el_upp.toLowerCase().replace(/\\b[a-z]/g, function(letter) {\n return letter.toUpperCase();\n });\n\n // IT: Gestisce la scrittura nell'etichetta destra o sinistra a seconda del frame caricato\n /*if (frame_id.indexOf(\"-add\")>-1) {\n $('#zvalopz').text(pp_el_upp);\n } else{\n $('#edval span').text(pp_el_upp);\n }*/\n}",
"function insererTexteApresCurseur(sTexteAInserer, sIdChamp) { \r\n\tvar textField = document.getElementById(sIdChamp); \r\n\tsTexteAInserer = sTexteAInserer.replace(/<br>/gi, \"\\n\").replace(/<br\\/>/gi, \"\\n\").replace(/<br \\/>/gi, \"\\n\").replace(/<\\/p>/gi, \"\\n\").replace(/<p>/gi, \"\");\r\n\r\n\t//IE support \r\n\tif (document.selection) { \r\n\t\ttextField.focus(); \r\n\t\tvar sel = document.selection.createRange(); \r\n\t\tsel.text = sTexteAInserer;\r\n\t} \r\n\t//MOZILLA/NETSCAPE support \r\n\telse if (textField.selectionStart || textField.selectionStart == \"0\") {\r\n\t\tvar startPos = textField.selectionStart; \r\n\t\tvar endPos = textField.selectionEnd; \r\n\t\tvar sChaine = textField.value; \r\n\t\ttextField.value = sChaine.substring(0, startPos) + sTexteAInserer \r\n\t\t\t+ sChaine.substring(endPos, sChaine.length); \r\n\t} else { \r\n\t\ttextField.value += sTexteAInserer; \r\n\t} \r\n}",
"function changerTitres() {\n if ($('#en').hasClass(\"currentlanguage\")) { // Si en anglais\n $('#titrepatient').html(\"Modify this patient\");\n $('#textbuttonAjout').html(\"Replace\");\n } else { // Si en français\n $('#titrepatient').html(\"Modifier ce patient\");\n $('#textbuttonAjout').html(\"Remplacer\");\n }\n }",
"function suche3(id) {\n\tvar texto;\n\tvar ordbogform;\n\tvar o_text = document.ordbogform.texto.value;\n\tvar i;\n\tvar out=\"\";\n\tvar debug=\"\";\n\tvar oldchar;\n\tvar newchar;\n\tfor (i=0; i<o_text.length; i++) {\n\t\toldchar = o_text.charCodeAt(i);\n\t\tnewchar = win1251[oldchar];\n\t\tif (newchar==undefined) {\n\t\t\tnewchar = oldchar\n\t\t} \n\t\tout=out+String(newchar)\n\t}\n\tout = out.replace(/^\\s+|\\s+$/g, '');\n\twindow.open(id+ out,'_blank');\n}",
"function replaceLocaleText(data) {\n\n if (scormLocation) {\n\n $('*[data-localeid]').each(function() {\n\n var returnText = translations.text[$(this).data(\"localeid\")];\n if (returnText === undefined) {\n $(this).html(translations.text[$(this).data(\"localeid\")]);\n } else {\n var a = returnText.replace(/\\[/gi, \"<sup>\");\n returnText = a.replace(/\\]/gi, \"</sup>\");\n $(this).html(returnText);\n }\n });\n\n } else {\n $('*[data-localeid]').each(function() {\n var returnText = data.text[$(this).data(\"localeid\")];\n if (returnText === undefined) {\n $(this).html(data.text[$(this).data(\"localeid\")]);\n } else {\n $(this).html(returnText);\n }\n });\n\n $('*[data-linkid]').each(function() {\n var returnLinkURL = data.text[$(this).data(\"linkid\")];\n if (returnLinkURL === undefined) {\n $(this).attr('href', data.text[$(this).data(\"linkid\")]);\n } else {\n\n $(this).attr('href', returnLinkURL);\n }\n });\n }\n}",
"function showDescrizionePoi(bottone){\r\n \r\n coordinata=[];\r\n if (bottone.lat>0){ $$(\"mappa_button\").show();\r\n storeCoordinate(bottone.lat, bottone.lon, coordinata, bottone.titolo, bottone.dati);}\r\n $$(bottone.vista).define(\"url\",bottone.dati);\r\n \r\n \r\n $$(bottone.vista).show();\r\n \r\n return true;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
trynna get permanent access code | function getPermAccessCode () {
FB.api(
"/"+account_id+"/accounts/?access_token="+longer_token,
function (response) {
if (response && !response.error) {
console.log('API response - trynna get perm code', response);
perm_token = response.data[0].access_token;
getGroupFeed();
getPageFeed();
} else {
console.log('huh?')
console.log(response);
}
}
);
} | [
"function getAuthCode()\r\n{\t\r\n\tvar authCode;\r\n\tauthCode = sendRequest(\"/ssadmin/dog/configinfo.html?data=AuthCode\"); \r\n\treturn \"\"+authCode+\"\";\r\n}",
"function get_new_access_code(){\n\n var url = ACCESS_URL + 'grant_type=client_credential';\n url += ('&appid=' + config.TEST_APPID);\n url += ('&secret=' + config.TEST_SECRET);\n \n console.log('Get access Code timer:' + new Date());\n\n https.get(url, function(res){\n res.on('data',function(d){\n\tvar fb = JSON.parse(d.toString());\n\tconsole.log('get access token:');\n\tconsole.log(fb);\n\n\tif('errcode' in fb){\n\t console.log('Can\\\"t get access code!');\n\t console.log('无法获取access code');\n\t //setTimeout(access_code, 5000);\n\t}\n\telse{\n\t var code = fb.access_token;\n\t var expire = fb.expires_in; // in seconds\n\n\t // save it into db\n\t save_access_code(code,expire,function(){\n\t // get jsapi_ticket\n\t jsapi_ticket(code,function(){\n\t console.log('end of jsapi_ticket');\n\t });\n\t });\n\t console.log('timeout is:');\n\t //var timeout = (parseInt(expire) - 30) * 1000;\n\t //console.log(timeout);\n\t // run get access code after some time\n\t // 真的会被运行嘛?\n\t setTimeout(access_code, (parseInt(expire) - 30) * 1000);\n\t \n\t}\n });\n });\n }",
"function getAuthCode()\n\t\t{\n\t\t\tvar authCode;\n\t\t\tauthCode = sendRequest(\"auth/ConfigInfo?data=AuthCode\");\n\t\t\treturn \"\"+authCode+\"\";\n\t\t}",
"static get AccessPerm () {}",
"function getAccess(number){\n if (number == 1) return \"Read\";\n if (number == 2) return \"Read/Run\";\n if (number == 3) return \"Read/Run/Share\";\n return \"Data error!\";\n}",
"getAccessTokenSysID() {}",
"function generateAccessCode() {\n let code = \"\";\n const possible = \"abcdefghijklmnopqrstuvwxyz\";\n for(let i = 0; i < 4; i++){\n code += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n return code;\n}",
"async accessInfo(){\n return this.get(\"access-info\", null);\n }",
"issetCodePermission() {\n if (getCode()) {\n getTokenSpotify();\n }\n }",
"function getAccessCode(req, res, next){\n courseService.getAccessCode(req).then(x => {\n res.json(x);\n })\n}",
"get_apnSecret() {\n return this.liveFunc._apnSecret;\n }",
"function grantAccessCode(req, res, next){\n var email = auth(req).name;\n var clientID = req.params.clientID;\n var code = rand.generate(32);\n\n db.saveAccessGrant(email, clientID, code, function(status){\n if(status === true){\n console.log('Access code stored successfully');\n res.send(code);\n }else{\n res.status(500).send('There was an error saving access grant code to database');\n }\n });\n}",
"function getAuthCode()\n{\n\treturn parseInt(Math.random() * (999999 - 100000 + 1) + 100000);\n}",
"function getGrantCodeFromPageURL() {\n\t var pageURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n\t\n\t if (pageURL === '' && typeof window !== 'undefined') {\n\t pageURL = window.location.href;\n\t }\n\t var queries = (0, _utils.decodeQuery)(pageURL);\n\t if (!queries.hasOwnProperty('state')) {\n\t return null;\n\t }\n\t return {\n\t state: queries['state'],\n\t code: queries['access_code']\n\t };\n\t}",
"getUniqueCode(nik){\n return nik.substr(12, 4);\n }",
"async generateAuthCode(){\n\t\t// any code is allowed\n\t\t//\n\t}",
"function user_assign_code(code)\r\n{\t\t\r\n\tvar original_code = this.getCode();\r\n\t\r\n\tif(code==item_access_code)\r\n\t{\t\t\r\n\t\tthis.assignPriv(null);\r\n\t}\r\n\telse\r\n\t{\t\r\n\t\tif(this.getPriv())\r\n\t\t{\r\n\t\t\tvar priv = this.getPriv();\r\n\t\t\t\t\r\n\t\t\tpriv.code = code;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvar priv = new new_privilage(null, null, this.id, code);\t\t\t\t\r\n\t\t\t\t\r\n\t\t\tthis.assignPriv(priv);\r\n\t\t}\r\n\t}\r\n\r\n\tthis.updateIcon();\r\n}",
"function generateAccesscode() {\n var length = 8,\n charset = \"abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789\",\n retVal = \"\";\n for(var i = 0, n = charset.length; i < length; ++i) {\n retVal += charset.charAt(Math.random() * n);\n }\n return retVal;\n}",
"get accession () {\n\t\treturn this._accession;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Community functions /////////////////// //////////////////////////////////////////////////////////// /////// Add community center points to primary nodes | function findCommunityCenters() {
//Run a community algorithm on the primary nodes
var community = jLouvain().nodes(nodes_primary.map(function (d) {
return d.id;
})).edges(edges_primary);
var community_result = community(); //Find the number of nodes per community
community_count = byCount(d3__WEBPACK_IMPORTED_MODULE_6__["values"](community_result));
var community_count_by_id = {};
community_count.forEach(function (d) {
d.item = +d.item;
community_count_by_id[d.item] = d;
}); //forEach
community_count = community_count.sort(function (a, b) {
return d3__WEBPACK_IMPORTED_MODULE_6__["ascending"](a.item, b.item);
}); //Find the id of the biggest group
var counts = community_count.map(function (d) {
return d.frequency;
});
var community_biggest = community_count[counts.indexOf(Math.max.apply(Math, Object(_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_5__["default"])(counts)))].item; //Assign communities to the nodes
nodes_primary.forEach(function (d) {
d.community = community_result[d.id];
}); ///////// Replace communities that are too small ///////
//Get the number of connections between the communities
var community_connections = calculateCommunityConnections(); //Move communities with less than X member to its most connected one
community_count = replaceSmallCommunities(community_count, community_connections, community_count_by_id, community_biggest); //Which concepts are the largest per group
community_count.forEach(function (d) {
var chosen = nodes_primary.filter(function (n) {
return n.community === d.item && n.type === 'concept';
});
var counts = chosen.map(function (d) {
return d.degree;
});
d.concept = chosen[counts.indexOf(Math.max.apply(Math, Object(_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_5__["default"])(counts)))].label;
}); /////////////////// 'SMART' LOCATION - START ///////////////////
// Find placement of connected groups around circle
// community_connections = calculateCommunityConnections()
// community_connections.sort((a,b) => { return a.community_a - b.community_a })
// let left_side = []
// let right_side = []
// let biggest_remaining
// let range = d3.range(community_count.length)
// let new_value
// let current = community_biggest
// //Start with the biggest
// right_side.push(current)
// removeNum(current)
// new_value = findNextCommunity(left_side, current)
// left_side.push(new_value)
// removeNum(new_value)
// function removeNum(value) {
// let index = range.indexOf(value)
// range.splice(index, 1)
// }//function removeNum
// //Fill in the other sides
// let counter = 1
// while(counter < community_count.length - 1) {
// current = right_side[right_side.length - 1]
// new_value = findNextCommunity(right_side, current)
// removeNum(new_value)
// right_side.push(new_value)
// counter += 1
// current = left_side[left_side.length - 1]
// new_value = findNextCommunity(left_side, current)
// left_side.push(new_value)
// counter += 1
// }//while
// ///////// Find the next biggest connection that hasn't been used ///////
// function findNextCommunity(side_array, current) { //Recursive
// let next_group
// let order = side_array.slice(0) //Make clone
// //Find the largest and place left to it
// biggest_remaining = community_connections.filter(d => d.community_a === current)
// biggest_remaining.sort((a,b) => b.connections - a.connections)
// //Which connected groups is the biggest and not chosen yet
// for(let i = 0; i < biggest_remaining.length; i++) {
// let candidate = biggest_remaining[i].community_b
// if(left_side.indexOf(candidate) < 0 && right_side.indexOf(candidate) < 0) {
// next_group = candidate
// break
// }//if
// }//for i
// if(typeof next_group !== "undefined") {
// return next_group
// } else {
// if(range.length === 1) return range[0]
// else {
// //If nothing is found, go one back up the "tree" and try again
// order.pop()
// if(order.length <= 0) return range[0]
// else {
// let new_current = order[order.length - 1]
// return findNextCommunity(order, new_current)
// }//else
// }//else
// }//else
// }//function findNextCommunity
// ///////// Inverse the ordering to the index ///////
// // let order = right_side.concat(left_side.reverse())
// //Move quarter of the left side first, then full right side, then remaining left side
// let left_middle = Math.ceil(left_side.length/2)
// let left_top = left_side.slice(0, left_middle).reverse()
// let left_bottom = left_side.slice(-(left_middle-1)).reverse()
// let order = left_top.concat(right_side.concat(left_bottom))
// //Get the sorting order
// let indexed_order = order.map((d,i) => { return {index: i, order: d} })
// indexed_order.sort((a,b) => a.order - b.order)
// let indices = indexed_order.map(d => d.index)
/////////////////// 'SMART' LOCATION - END ///////////////////
community_count.forEach(function (d, i) {
// d.order = indices[d.item]
d.order = i;
d.frequency = nodes_primary.filter(function (n) {
return n.community === d.item;
}).length;
});
community_count = community_count.sort(function (a, b) {
return a.order - b.order;
}); ///////// Assign positions based on order around circle ///////
//Spread the centers of each community around a circle based on how many nodes are in each community
var total_degrees = 0;
var num = nodes_primary.length;
community_count.forEach(function (d, i) {
d.angle_slice = Math.round(Math.pow(Math.max(num / (community_count.length * 4), d.frequency), 0.75));
total_degrees += d.angle_slice;
});
var degrees = 0;
community_count.forEach(function (d, i) {
d.center_angle = pi2 * (degrees + d.angle_slice / 2) / total_degrees; // d.center_angle = pi2 * (degrees + d.frequency/2)/nodes_primary.length
// d.center_angle = pi2 * degrees/total_degrees
d.x = d.x_fixed = radius_primary * Math.cos(d.center_angle);
d.y = d.y_fixed = radius_primary * Math.sin(d.center_angle);
d.r = d.r_fixed = 50;
degrees += d.angle_slice;
}); //Redo the community numbers
var replacement = {};
community_count.forEach(function (d, i) {
replacement[d.item] = i;
d.item_old = d.item;
d.item = i;
}); // //Replace numbers for the nodes
// nodes_primary.forEach(d => { d.community = replacement[d.community] })
// console.log(community_count)
//Set-up the color scale of the communities
node_community_color.domain([0, d3__WEBPACK_IMPORTED_MODULE_6__["max"](community_count, function (d) {
return d.item;
})]); //Set the central "gravity" point for each node and a first location
nodes_primary.forEach(function (d) {
//Replace numbers for the nodes
d.community = replacement[d.community];
if (d.type === 'element' || d.type === 'concept') {
d.fill = node_color_interpolate(node_community_color(d.community));
} //if
//Set the center
var angle = community_count[d.community].center_angle;
d.focusX = radius_primary * Math.cos(angle);
d.focusY = radius_primary * Math.sin(angle);
d.x = d.focusX + Math.random();
d.y = d.focusY + Math.random();
}); //forEach
} //function findCommunityCenters | [
"function findCommunityCenters() {\r\n //Run a community algorithm on the primary nodes\r\n let community = jLouvain().nodes(nodes_primary.map(d => d.id)).edges(edges_primary)\r\n let community_result = community()\r\n\r\n //Find the number of nodes per community\r\n community_count = byCount(d3.values(community_result))\r\n let community_count_by_id = {}\r\n community_count.forEach(d => {\r\n d.item = +d.item\r\n community_count_by_id[d.item] = d\r\n })//forEach\r\n community_count = community_count.sort((a,b) => { return d3.ascending(a.item, b.item) })\r\n\r\n //Find the id of the biggest group\r\n let counts = community_count.map(d => d.frequency)\r\n let community_biggest = community_count[counts.indexOf(Math.max(...counts))].item\r\n\r\n //Assign communities to the nodes\r\n nodes_primary.forEach(d => { d.community = community_result[d.id] })\r\n\r\n ///////// Replace communities that are too small ///////\r\n\r\n //Get the number of connections between the communities\r\n let community_connections = calculateCommunityConnections()\r\n //Move communities with less than X member to its most connected one\r\n community_count = replaceSmallCommunities(community_count, community_connections, community_count_by_id, community_biggest)\r\n\r\n //Which concepts are the largest per group\r\n community_count.forEach(d => {\r\n let chosen = nodes_primary.filter(n => n.community === d.item && n.type === \"photograph\")\r\n let counts = chosen.map(d => d.degree)\r\n d.photograph = chosen[counts.indexOf(Math.max(...counts))].label\r\n })\r\n\r\n /////////////////// 'SMART' LOCATION - START ///////////////////\r\n\r\n // Find placement of connected groups around circle\r\n // community_connections = calculateCommunityConnections()\r\n // community_connections.sort((a,b) => { return a.community_a - b.community_a })\r\n\r\n // let left_side = []\r\n // let right_side = []\r\n // let biggest_remaining\r\n // let range = d3.range(community_count.length)\r\n // let new_value\r\n // let current = community_biggest\r\n\r\n // //Start with the biggest\r\n // right_side.push(current)\r\n // removeNum(current)\r\n // new_value = findNextCommunity(left_side, current)\r\n // left_side.push(new_value)\r\n // removeNum(new_value)\r\n\r\n // function removeNum(value) {\r\n // let index = range.indexOf(value)\r\n // range.splice(index, 1)\r\n // }//function removeNum\r\n\r\n // //Fill in the other sides\r\n // let counter = 1\r\n // while(counter < community_count.length - 1) {\r\n // current = right_side[right_side.length - 1]\r\n // new_value = findNextCommunity(right_side, current)\r\n // removeNum(new_value)\r\n // right_side.push(new_value)\r\n // counter += 1\r\n\r\n // current = left_side[left_side.length - 1]\r\n // new_value = findNextCommunity(left_side, current)\r\n // left_side.push(new_value)\r\n // counter += 1\r\n // }//while\r\n\r\n // ///////// Find the next biggest connection that hasn't been used ///////\r\n // function findNextCommunity(side_array, current) { //Recursive\r\n // let next_group\r\n // let order = side_array.slice(0) //Make clone\r\n\r\n // //Find the largest and place left to it\r\n // biggest_remaining = community_connections.filter(d => d.community_a === current)\r\n // biggest_remaining.sort((a,b) => b.connections - a.connections)\r\n\r\n // //Which connected groups is the biggest and not chosen yet\r\n // for(let i = 0; i < biggest_remaining.length; i++) {\r\n // let candidate = biggest_remaining[i].community_b\r\n // if(left_side.indexOf(candidate) < 0 && right_side.indexOf(candidate) < 0) {\r\n // next_group = candidate\r\n // break\r\n // }//if\r\n // }//for i\r\n\r\n // if(typeof next_group !== \"undefined\") {\r\n // return next_group\r\n // } else {\r\n // if(range.length === 1) return range[0]\r\n // else {\r\n // //If nothing is found, go one back up the \"tree\" and try again\r\n // order.pop()\r\n // if(order.length <= 0) return range[0]\r\n // else {\r\n // let new_current = order[order.length - 1]\r\n // return findNextCommunity(order, new_current)\r\n // }//else\r\n // }//else\r\n // }//else\r\n // }//function findNextCommunity\r\n\r\n // ///////// Inverse the ordering to the index ///////\r\n\r\n // // let order = right_side.concat(left_side.reverse())\r\n // //Move quarter of the left side first, then full right side, then remaining left side\r\n // let left_middle = Math.ceil(left_side.length/2)\r\n // let left_top = left_side.slice(0, left_middle).reverse()\r\n // let left_bottom = left_side.slice(-(left_middle-1)).reverse()\r\n // let order = left_top.concat(right_side.concat(left_bottom))\r\n\r\n // //Get the sorting order\r\n // let indexed_order = order.map((d,i) => { return {index: i, order: d} })\r\n // indexed_order.sort((a,b) => a.order - b.order)\r\n // let indices = indexed_order.map(d => d.index)\r\n\r\n /////////////////// 'SMART' LOCATION - END ///////////////////\r\n\r\n community_count.forEach((d,i) => {\r\n // d.order = indices[d.item]\r\n d.order = i\r\n d.frequency = nodes_primary.filter(n => n.community === d.item).length\r\n })\r\n community_count = community_count.sort((a,b) => a.order - b.order)\r\n\r\n ///////// Assign positions based on order around circle ///////\r\n\r\n //Spread the centers of each community around a circle based on how many nodes are in each community\r\n let total_degrees = 0\r\n let num = nodes_primary.length\r\n community_count.forEach((d,i) => {\r\n d.angle_slice = Math.round( Math.pow( Math.max(num / (community_count.length * 4), d.frequency), 0.75 ) )\r\n total_degrees += d.angle_slice\r\n })\r\n\r\n let degrees = 0\r\n community_count.forEach((d,i) => {\r\n d.center_angle = pi2 * (degrees + d.angle_slice/2)/total_degrees\r\n // d.center_angle = pi2 * (degrees + d.frequency/2)/nodes_primary.length\r\n // d.center_angle = pi2 * degrees/total_degrees\r\n d.x = d.x_fixed = radius_primary * Math.cos(d.center_angle)\r\n d.y = d.y_fixed = radius_primary * Math.sin(d.center_angle)\r\n d.r = d.r_fixed = 50\r\n degrees += d.angle_slice\r\n })\r\n\r\n //Redo the community numbers\r\n let replacement = {}\r\n community_count.forEach((d, i) => {\r\n replacement[d.item] = i\r\n d.item_old = d.item\r\n d.item = i\r\n })\r\n // //Replace numbers for the nodes\r\n // nodes_primary.forEach(d => { d.community = replacement[d.community] })\r\n\r\n // console.log(community_count)\r\n\r\n //Set-up the color scale of the communities\r\n node_community_color.domain([0, d3.max(community_count, d => d.item)])\r\n\r\n //Set the central \"gravity\" point for each node and a first location\r\n nodes_primary.forEach(d => {\r\n //Replace numbers for the nodes\r\n d.community = replacement[d.community]\r\n if(d.type === \"camera\" || d.type === \"photograph\" || d.type === \"distortion\") {\r\n d.fill = node_color_interpolate(node_community_color(d.community))\r\n }//if\r\n\r\n //Set the center\r\n let angle = community_count[d.community].center_angle\r\n d.focusX = radius_primary * Math.cos(angle)\r\n d.focusY = radius_primary * Math.sin(angle)\r\n d.x = d.focusX + Math.random()\r\n d.y = d.focusY + Math.random()\r\n })//forEach\r\n }//function findCommunityCenters",
"function assignCentroids() {\n \n}",
"function moveCentroids()\n {\n centroids.forEach(function(d)\n {\n // Get clusters based on their fill color\n var cluster = points.filter(function(e)\n {\n return e.fill === d.fill;\n });\n // Compute the cluster centers\n var center = computeClusterCenter(cluster);\n // Move the centroid\n d.x = center[0];\n d.y = center[1];\n\n //console.log(cluster[0])\n //console.log(d)\n //console.log(d.x,d.y,d.id)\n });\n }",
"function assignCentroids() {\n var i;\n for (i =0; i < points.length; i++ ){\n\n var minDist = Number.MAX_VALUE;\n var j;\n for (j=0;j<centroids.length; j++){\n var xDist = centroids[j].x - points[i].x;\n var yDist = centroids[j].y - points[i].y;\n var distance = Math.sqrt((xDist * xDist) + (yDist * yDist));\n if (distance < minDist){\n points[i].centroid = centroids[j];\n minDist = distance;\n }\n\n }\n }\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 moveCentroids() {\n centroids.forEach(function(d) {\n // Get clusters based on their fill color\n var cluster = points.filter(function(e) {\n return e.fill === d.fill;\n });\n // Compute the cluster centers\n var center = computeClusterCenter(cluster);\n // Move the centroid\n d.x = center[0];\n d.y = center[1];\n });\n }",
"function updateCentroids() {\n for(var i=0; i<centroids.length; i++){\n var center=centroids[i];\n var minCen=centroids[i];\n var minVal=Number.MAX_VALUE;\n var sumX=0;\n var sumY=0;\n var count=0;\n for(var j=0; j<points.length; j++){\n if(points[j].centroid.x==center.x && points[j].centroid.y==center.y){\n sumX+=points[j].x;\n sumY+=points[j].y;\n count++;\n }\n }\n centroids[i].x=sumX/count;\n centroids[i].y=sumY/count;\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 updateCentroids() {\n for(var c = 0; c < centroids.length; c++){\n var centroid = centroids[c];\n var x_sum = 0;\n var y_sum = 0;\n var p_count = 0;\n for(var p = 0; p < points.length; p++){\n\n var point= points[p];\n if(point.centroid == centroid){\n p_count ++;\n x_sum += point.x;\n y_sum += point.y;\n }\n \n }\n centroid.x = x_sum/p_count;\n centroid.y = y_sum/p_count;\n }\n}",
"assignToCentroid(){\n var nearestCentroid = this.getNearestCentroid();\n\t //only reassign if the selected centroid isnt the assigned anyway\n\t if(this.assignedCentroid != nearestCentroid){\n\t if(!this.assignedCentroid){\n\t\t\tthis.assignedCentroid = nearestCentroid;\n\t\t\tif(nearestCentroid) {\n\t\t\t\tnearestCentroid.assignedAgents.push(this);\n\t\t\t}\n\t }else{\n\t\t\tJsUtils.removeObject(this.assignedCentroid.assignedAgents,this);\n\t\t\tthis.assignedCentroid = nearestCentroid;\n\t\t\tif(nearestCentroid) {\n\t\t\t\tnearestCentroid.assignedAgents.push(this);\n\t\t\t}\n\t }\n\t }\n\t }",
"function setNodeCentroid(data, geo) {\n data.nodes = data.nodes.map(d => {\n d.x = geo.centroids[d.id]['x']\n d.y = geo.centroids[d.id]['y']\n\n return d\n })\n\n return data\n}",
"function updateCentroids() {\n\n var i;\n for (i = 0; i < centroids.length; i++) {\n var xSum = 0;\n var ySum = 0;\n var pointCount = 0;\n var j;\n for (j = 0; j < points.length; j++) {\n if (centroids[i] == points[j].centroid) {\n xSum += points[j].x;\n ySum += points[j].y;\n pointCount++;\n }\n }\n centroids[i].x = xSum/pointCount;\n centroids[i].y = ySum/pointCount;\n }\n}",
"function detectCommunities(nodes, links) {\n\n if (params.coloring) {\n var nodes_id_list = [], links_list = [], init_part = {};\n\n for (i=0; i<nodes.length; i++) {\n nodes_id_list.push(nodes[i].id)\n //init_part[nodes[i].id] = community_init[nodes[i].id]\n }\n\n for (i=0; i<links.length; i++) {\n links_list.push({source: links[i].source.id, target: links[i].target.id, weight: 1.})\n }\n\n var community = jLouvain().nodes(nodes_id_list)\n .edges(links_list)\n //.partition_init(init_part);\n\n var community_assignment = community();\n\n var max_community_number = 0;\n\n nodes.forEach(function(node) {\n node.community = community_assignment[node.id];\n max_community_number = max_community_number < community_assignment[node.id] ? community_assignment[node.id]: max_community_number;\n })\n\n var color = d3.scaleOrdinal(d3.schemeCategory10).domain(d3.range([0, max_community_number]));\n\n d3.selectAll('.node')\n .data(nodes)\n .style('fill', function(d){ return color(d.community);});\n\n d3.select(\"#community_count_div > span\")\n .text((max_community_number + 1));\n }\n else {\n d3.selectAll('.node')\n .data(nodes)\n .style('fill', 'black')\n }\n}",
"function calculateCentroidPositions() { // x location, y location, count, sum of square distances\n clearCentroidPositions();\n addupXYPositions();\n // scale sums by count....to calculate averages\n normalizeCentroidByColorTypeCount(colorCentroidStructure);\n sumOfSquares();\n }",
"function initCentroid(){\n // data corresponding to center translation matrix\n g_transforms[currObject][map.CENTER][0] = -1*centroid(currObject).x;\n g_transforms[currObject][map.CENTER][1] = -1*centroid(currObject).y;\n g_transforms[currObject][map.CENTER][2] = -1*centroid(currObject).z;\n\n // data corresponding to decenter translation matrix\n g_transforms[currObject][map.DECENTER][0] = centroid(currObject).x;\n g_transforms[currObject][map.DECENTER][1] = centroid(currObject).y;\n g_transforms[currObject][map.DECENTER][2] = centroid(currObject).z;\n}",
"function centerNodes(nodes) {\n const bounds = graphBounds(nodes);\n for (let node of nodes) {\n node.x = node.x - bounds.center.x;\n node.y = node.y - bounds.center.y;\n }\n}",
"function Bind() {\n POINTS.forEach(function(p){\n var Dist = [];\n Clusters.forEach(function(cl){\n Dist.push(Math.sqrt(Math.pow((cl.centerX- p.x),2)+Math.pow((cl.centerY- p.y),2)))\n });\n var minDist = Math.min.apply(null, Dist);\n for (var i = 0; i <= Dist.length; i++){\n if (Dist[i] == minDist){\n Clusters[i].addPoint(p);\n break;\n }\n }\n });\n\n var checkNum = 0;\n Clusters.forEach(function(cl){\n checkNum += Number.parseInt(String(Number(cl.checkCenter())));\n });\n\n if (checkNum == 0){\n return;\n }\n else {\n Clusters.forEach(function(cl){\n cl.moveCenter();\n cl.clear();\n });\n Bind();\n }\n}",
"updateCenter() {\r\n for (let i of this.Clusters) {\r\n let dx = 0\r\n let dy = 0\r\n for (let j of i.data) {\r\n dx += j[0]\r\n dy += j[1]\r\n }\r\n dx /= i.data.length\r\n dy /= i.data.length\r\n i.center = [dx, dy]\r\n }\r\n }",
"setCenterPoints()\n {\n \tfor(let n=0; n<this.nodes.length; n++)\n \t{\n \t\tlet node = this.nodes[n],\n cssTxt = node.style.cssText;\n\n node.style.cssText = this.getNodeIndexData(n, 'style');\n\n \t\tlet bounds = node.getBoundingClientRect(),\n x = (bounds.left+bounds.right )*0.5 - this.offsetX,\n y = (bounds.top +bounds.bottom)*0.5 - this.offsetY,\n jitter = this.getNodeIndexData(n, 'jitter');\n\n if(jitter && this.jitter>0)\n {\n x += jitter.x;\n y += jitter.y;\n }\n\n node.style.cssText = cssTxt;\n \t\tthis._setNodeIndexData(n, 'center', {x: x, y: y});\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds assignment to class | function addAssignmentToClass(db, res, classID, assignmentID) {
var classesCollection = db.collection('classes');
classesCollection.update({'id':classID}, {$push:{'assignments':assignmentID}}, function(err, result) {
if (err) {
console.log(err);
}
});
} | [
"function Assignment() {\n this.name = \"\";\n this.submissionLink = \"\";\n this.contents = new Array();\n // Some assignments consist of text directly on the Assignments link\n this.memo = \"\";\n this.type = this.constructor.name;\n}",
"assign(A, a) {\n this.assignment[A] = a;\n }",
"function createAssignmentObj(element) {\n return new Assignment(element.id, element.company, element.logo, element.new,element.featured, element.position, \n element.role, element.level, element.postedAt, element.contract, element.location, element.languages, element.tools);\n}",
"constructor() { \n \n Assignee.initialize(this);\n }",
"function _AssignmentExpressionEmitter() {\n}",
"Assignment(id, _is, exp, _exc) {\n return new Assignment(id.ast(), exp.ast());\n }",
"AssignmentOperator() {\n if (this._lookahead.type === 'SIMPLE_ASSIGN') {\n return this._eat('SIMPLE_ASSIGN');\n }\n return this._eat('COMPLEX_ASSIGN');\n }",
"constructor() { \n \n AssignmentDetails.initialize(this);\n }",
"async function addAssignment(req, res) {\n const _id = req.params.id;\n try {\n // find the current user\n const currentUser = req.user;\n \n const { title, content, dueDate } = req.body;\n \n const targetClass = await Class.findOne({ _id });\n \n // check if the teacher owns the class\n if (currentUser._id != targetClass.teacher) throw new Error(\"Forbidden\");\n \n targetClass.assignments.push({\n title,\n content,\n dueDate\n })\n\n // Save the user and the changes.\n await targetClass.save();\n \n res.json({ success: true, message: \"Added Assignment.\", targetClass });\n } catch (error) {\n console.error(error);\n if (error.message === \"Forbidden\") {\n res.status(403).json({\n success: false,\n message: \"You do not own this class\",\n });\n } else if (error.name === \"MongoError\") {\n const needToChange = error.keyPattern;\n res.status(409).json({\n success: false,\n message: \"DataBase Error\",\n needToChange,\n });\n } else {\n res.status(400).json({\n success: false,\n message: error.message,\n });\n }\n }\n}",
"AppendAssignment(assignmentID) {\n this.assignments.push(assignmentID);\n }",
"get isAssignment() {\n return true;\n }",
"function mergeAssignment(assignmentSpec, assignmentInstance) {\n\n}",
"constructor() {\n super(expressionType_1.ExpressionType.SetProperty, SetProperty.evaluator(), returnType_1.ReturnType.Object, SetProperty.validator);\n }",
"function Assignment(semis, cost) {\n //semis is a list [a, b, c, d] of lists of neighbors to be assigned to the semiaxes s0, s1, s2, s3 respectively\n this.semis = semis;\n this.cost = cost;\n}",
"assignmentStatement() {\n const left = this.variable()\n const token = this.token\n this.eat('ASSIGN')\n const right = this.expr()\n const node = new Assign(left, token, right)\n return node\n }",
"function AssignmentOperator(){\nequalAssOP();\naddAssigOp();\nsubAssigOp();\n}",
"function Assignment(tableRow)\n{\n var tableElements = tableRow.getElementsByTagName(\"td\");\n if(tableRow.className == \"useradded\")\n this.category = tableElements[3].firstChild.value;\n else\n this.category = tableElements[3].innerHTML;\n this.outOf = parseFloat(tableElements[6].firstChild.innerHTML);\n this.points = tableElements[5].firstChild.innerHTML;\n this.unknown = isUnknownGrade(tableElements[5].firstChild.innerHTML);\n \n this.index = parseInt(tableElements[0].innerHTML) - 1;\n \n \n this.getPercentage = getPercentage;\n this.setRow = setRow;\n this.copy = copy;\n this.getCategory = getCategory;\n}",
"function addAssignment()\n\t{\n\t\t// =\n\t\t_AST.addNode(getToken(+1).value, \"branch\");\n\n\t\t// Get the id, current scope, and line\n\t var scope = scopeManager.currentScope;\n\t var id = getToken().name;\n\t var line = getToken().line;\n\n\t\t// Add the id and its symbol table entry to the AST in an object\n\t\t_AST.addNode({\"id\": id, \"symbolTableEntry\": getSymbolTableEntry(id, scope)}, \"leaf\");\n\n\t\t// The value to be assigned\n\t var value;\n\n\t\t// Look ahead to determine if we need to add an intExpr or just a single digit, string, or id\n\t\tif(getToken(+3).kind === TOKEN_OP)\n\t\t{\n\t\t\t// Get the intExpr value for the symbol table\n\t\t\tvalue = concatenateIntExpr(index + 2);\n\t\t\t// Move to the op\n\t\t\tindex += 3;\n\t\t\taddIntExpr();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// If the token is an Id we want to add its name to the AST and its symbol table entry\n\t\t\t// Otherwise (single digit or string) just add the value\n\t\t\tif(getToken(+2).kind === TOKEN_ID)\n\t\t\t{\n\t\t\t\t// If the symbolTable entry doesnt exist generate and undeclared variable error\n\t\t\t\t// Otherwise add the node for the Id, set it as used, and assign the value\n\t\t\t\tif(!getSymbolTableEntry(getToken(+2).name, scope))\n\t\t\t\t{\n\t\t\t\t\t_OutputManager.addError(\"Assignment error on line \" + line + \", '\" + getToken(+2).name + \"' is undeclared from the point of view of '\" + id + \"' in scope \" + scope);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Add the id and its symbol table entry to the AST in an object\n\t\t\t\t\t_AST.addNode({\"id\": getToken(+2).name, \"symbolTableEntry\": getSymbolTableEntry(getToken(+2).name, scope)}, \"leaf\");\n\n\t\t\t\t\t// Set the identifier value as \"used\" if not done so already\n\t\t\t\t\tsetIdentifierAsUsed(getToken(+2).name, scope);\n\n\t\t\t\t\t// The value is an id\n\t\t\t\t\tvalue = getToken(+2).name;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t_AST.addNode(getToken(+2).value, \"leaf\");\n\n\t\t\t\t// The value is a single digit or string\n\t\t\t\tvalue = getToken(+2).value;\n\t\t\t}\n\n\t\t\t// Move to the next statement\n\t\t\tindex += 3;\n\t\t}\n\n\t\t// Get the symbol table entry for this Id (assuming it exists)\n\t\tvar symbolTableEntry = getSymbolTableEntry(id, scope);\n\n\t // If a symbol table entry exists for this Id (it has been declared in this scope or in the parent scope hierarchy), add the value and mark as \"used\"\n\t // Otherwise it is an undeclared variable\n\t if(symbolTableEntry)\n\t {\n\t \tsymbolTableEntry.value = value;\n\t \tsetIdentifierAsUsed(id, scope);\n\t }\n\t else\n\t {\n\t\t undeclaredVariableError(id, line); // Found in errors-warnings.js\n\t }\n\n\t\t// Finished with assignment\n\t\t_AST.endChildren();\n\t}",
"function AssignmentExpression() {\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[res, partialScore] = canWordBePlacedVertical(x, y, state, stateHoriz, stateVert, currWord) | canWordBePlacedVertical(x, y, state, stateHoriz, stateVert, word){
let result = false;
let partialScore = 0;
// Test if we can put the word at x, y, Vertical.
// Test if the star and end position are over invalid state value terminate early.
let endY = y + word.length - 1;
if ((stateHoriz.board[x][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||
(stateVert.board[x][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||
(stateHoriz.board[x][y] == NO_HORIZ_NO_VERT) ||
(stateVert.board[x][y] == NO_HORIZ_NO_VERT) ||
(stateHoriz.board[x][endY] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||
(stateVert.board[x][endY] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||
(stateHoriz.board[x][endY] == NO_HORIZ_NO_VERT) ||
(stateVert.board[x][endY] == NO_HORIZ_NO_VERT) ){
result = false;
partialScore = 0;
return [result, partialScore];
}
// Test if the word clash's with the Vertical constrains, for all positions of the previous words placed.
for (let i = 0; i < word.length; i++) {
let yi = y + i;
if ((stateVert.board[x][yi] == VERTICAL) ||
(stateVert.board[x][yi] == NO_HORIZ_NO_VERT) ||
(stateHoriz.board[x][yi] == NO_HORIZ_NO_VERT) ||
(stateVert.board[x][yi] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||
( (state.board[x][yi] != EMPTY) && (state.board[x][yi] != word[i])) ){
result = false;
partialScore = 0;
return [result, partialScore];
}
// Calculate the partial score of this move based on the number of crosses between words.
if ((state.board[x][yi] != EMPTY) && (state.board[x][yi] == word[i])){
partialScore = partialScore + 1;
}
}
result = true;
return [result, partialScore];
} | [
"canWordBePlacedHorizontal(x, y, state, stateHoriz, stateVert, word){\n let result = false;\n let partialScore = 0;\n\n // Test if we can put the word at x, y, Horizontal.\n \n // Test if the star and end position are over invalid state value terminate early.\n let endX = x + word.length - 1;\n if ((stateHoriz.board[x][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||\n (stateVert.board[x][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||\n (stateHoriz.board[x][y] == NO_HORIZ_NO_VERT) ||\n (stateVert.board[x][y] == NO_HORIZ_NO_VERT) ||\n \n (stateHoriz.board[endX][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||\n (stateVert.board[endX][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||\n (stateHoriz.board[endX][y] == NO_HORIZ_NO_VERT) ||\n (stateVert.board[endX][y] == NO_HORIZ_NO_VERT) ){\n \n result = false;\n partialScore = 0;\n return [result, partialScore]; \n }\n // Test if the word clash's with the Horizontal constrains, for all positions of the previous words placed.\n for (let i = 0; i < word.length; i++) {\n let xi = x + i; \n if ((stateHoriz.board[xi][y] == HORIZONTAL) ||\n (stateHoriz.board[xi][y] == NO_HORIZ_NO_VERT) ||\n (stateVert.board[xi][y] == NO_HORIZ_NO_VERT) ||\n (stateHoriz.board[xi][y] == NO_CURR_ORIENT_AND_START_NO_END_OTHER) ||\n ( (state.board[xi][y] != EMPTY) && (state.board[xi][y] != word[i])) ){\n\n result = false;\n partialScore = 0;\n return [result, partialScore];\n }\n // Calculate the partial score of this move based on the number of crosses between words.\n if ((state.board[xi][y] != EMPTY) && (state.board[xi][y] == word[i])){\n partialScore = partialScore + 1;\n }\n }\n \n result = true;\n return [result, partialScore];\n }",
"getNextValidPosition(inX, inY, state, stateHoriz, stateVert, currWord, lastOrientation){\n let valid = false;\n let currX = -1;\n let currY = -1;\n let newX = -1;\n let newY = -1;\n let partialScore = 0;\n\n let x = -1;\n let y = -1;\n let res = null;\n let flagBreak = false;\n if (lastOrientation == VERTICAL){\n inY = inY + 1;\n lastOrientation = null;\n }\n let currPosLetter = null;\n for (y = inY; y < state.sizeY; y++) { \n for (x = inX; x < state.sizeX; x++) {\n // Simple first test, to see if the position can be used, and cut the processing weight.\n // We will see if the position is not Empty and if it has a different letter then our first letter.\n currPosLetter = state.board[x][y];\n if ( (currPosLetter != EMPTY) && currPosLetter != currWord[0] ){\n continue;\n }\n if ((lastOrientation == null) || (lastOrientation != HORIZONTAL)){\n // Generate Horizontally placement.\n lastOrientation = HORIZONTAL;\n // Test if word can fit horizontally until the end.\n if (x < state.sizeX - currWord.length){\n [res, partialScore] = this.canWordBePlacedHorizontal(x, y, state, stateHoriz, stateVert, currWord);\n if (res == true){\n flagBreak = true;\n break;\n }\n }\n }\n if (lastOrientation == HORIZONTAL){\n // Generate Vertical placement.\n lastOrientation = VERTICAL;\n // Test if word can fit vertically until the bottom.\n if (y < state.sizeY - currWord.length){\n [res, partialScore] = this.canWordBePlacedVertical(x, y, state, stateHoriz, stateVert, currWord);\n if (res == true){\n flagBreak = true;\n break;\n }\n }\n }\n }\n if (flagBreak)\n break;\n }\n\n if ((res != null) && (res == true)){\n valid = true;\n currX = x;\n currY = y;\n newX = x;\n newY = y;\n }\n\n return [valid, currX, currY, newX, newY, lastOrientation, partialScore];\n }",
"function isValidPosition(square, h_word, v_word, direction, submitted) {\n // If the tile is being placed on a non-empty square, do not place it\n if([square.x, square.y] in submitted) {\n return [-1, -1];\n }\n // If the word is 0 characters, add it at the beginning of both words \n if(h_word.length == 0 && v_word.length == 0) {\n return [0,0];\n }\n\n let h_index = -1, v_index = -1;\n if(direction == 'horizontal' || direction == '' || direction == 'both')\n h_index = getWordIndex(square, h_word, 'horizontal');\n\n if(direction == 'vertical' || direction == '' || direction == 'both')\n v_index = getWordIndex(square, v_word, 'vertical');\n\n return [h_index, v_index];\n}",
"function existVerticalsWithCurrentHorizontal(dictionary, currentCrossword, index) {\n const currentWord = currentCrossword.horizontalWords[index];\n let hasConflict = false;\n let searchPattern = null;\n const currentWords = getUsedWords(currentCrossword);\n for (let i = 0; i < currentWord.length; i++) {\n searchPattern = getSearchPattern(\n currentCrossword.grid,\n { row: currentWord.cell.row, col: currentWord.cell.col + i },\n \"V\"\n );\n if (\n searchPattern !== \"^\\\\w$\" &&\n !/^\\^\\w\\$$/.test(searchPattern) /* single letter pattern is ignored */ &&\n findWord(dictionary, searchPattern, currentWords) === null\n ) {\n hasConflict = true;\n break;\n }\n }\n return !hasConflict;\n}",
"function checkfeasibility(orientation, word, coordinates) {\n let wordLength = word.length;\n switch (orientation) {\n case 'horizontal':\n if (!(coordinates[1] + wordLength < puzzleLength)) {\n return false;\n } else {\n for (\n let i = coordinates[1];\n i < coordinates[1] + wordLength && i < puzzleLength;\n i++\n ) {\n if (\n !(\n puzzle[coordinates[0]][i] === 0 ||\n puzzle[coordinates[0]][i] === word[i - coordinates[1]]\n )\n ) {\n return false;\n }\n }\n }\n return true;\n case 'horizontalBack':\n if (!(coordinates[1] - wordLength > 0)) {\n return false;\n } else {\n for (\n let i = coordinates[1];\n i >= coordinates[1] - wordLength + 1 && i < puzzleLength;\n i--\n ) {\n if (\n !(\n puzzle[coordinates[0]][i] === 0 ||\n puzzle[coordinates[0]][i] === word[i - coordinates[1]]\n )\n ) {\n return false;\n }\n }\n }\n return true;\n case 'vertical':\n if (!(coordinates[0] + wordLength < puzzleLength)) {\n return false;\n } else {\n for (\n let i = coordinates[0];\n i < coordinates[0] + wordLength && i < puzzleLength;\n i++\n ) {\n if (\n !(\n puzzle[i][coordinates[1]] === 0 ||\n puzzle[i][coordinates[1]] === word[i - coordinates[0]]\n )\n ) {\n return false;\n }\n }\n }\n return true;\n case 'verticalUp':\n if (!(coordinates[0] >= wordLength - 1)) {\n return false;\n } else {\n for (\n let i = coordinates[0];\n i >= coordinates[0] - wordLength + 1 && i < puzzleLength;\n i--\n ) {\n if (\n !(\n puzzle[i][coordinates[1]] === 0 ||\n puzzle[i][coordinates[1]] === word[i - coordinates[0]]\n )\n ) {\n return false;\n }\n }\n }\n return true;\n case 'diagonal':\n if (\n !(\n coordinates[0] + wordLength < puzzleLength &&\n coordinates[1] + wordLength < puzzleLength\n )\n ) {\n return false;\n } else {\n let i = coordinates[0];\n let j = coordinates[1];\n for (let k = 0; k < wordLength; k++) {\n if (!(puzzle[i][j] === 0 || puzzle[i][j] === word[k])) {\n return false;\n }\n i++;\n j++;\n }\n }\n return true;\n case 'diagonalUp':\n if (\n !(\n coordinates[0] + wordLength < puzzleLength &&\n coordinates[1] >= wordLength - 1\n )\n ) {\n return false;\n } else {\n let i = coordinates[0];\n let j = coordinates[1];\n for (let k = 0; k < wordLength; k++) {\n if (\n !(puzzle[i][j] === 0 || puzzle[i][j] === word[wordLength - k - 1])\n ) {\n return false;\n }\n i++;\n j--;\n }\n }\n return true;\n case 'diagonalBack':\n if (\n !(\n coordinates[1] + wordLength < puzzleLength &&\n coordinates[0] >= wordLength - 1\n )\n ) {\n return false;\n } else {\n let i = coordinates[0];\n let j = coordinates[1];\n for (let k = 0; k < wordLength; k++) {\n if (\n !(puzzle[i][j] === 0 || puzzle[i][j] === word[wordLength - k - 1])\n ) {\n return false;\n }\n i--;\n j++;\n }\n }\n return true;\n case 'diagonalUpBack':\n if (\n !(coordinates[1] >= wordLength - 1 && coordinates[0] >= wordLength - 1)\n ) {\n return false;\n } else {\n let i = coordinates[0];\n let j = coordinates[1];\n for (let k = 0; k < wordLength; k++) {\n if (!(puzzle[i][j] === 0 || puzzle[i][j] === word[k])) {\n return false;\n }\n i--;\n j--;\n }\n }\n return true;\n }\n}",
"function checkWordPositions() {\n\tfor(var i = 0; i < words.length; i++) {\n\t\tif(yPos[i] > height - 130) { //if it passed the middle of the city\n\t\t\taddCrater(i); //add a crater where it hit the city\n\t\t\tnewWord(i); //replace the word\n\t\t\tlives -= 1;\n\t\t}\n\t}\n}",
"function isOverlappingDown(x, y, word) {\n var len = word.length;\n var grid_word = \"\";\n for (var j = 0; j < len; j++) {\n if (y + j >= grid_size) continue;\n if (y + j <= grid_start) continue;\n grid_word += letterAt(x, y + j);\n }\n return wordPlaced.includes(grid_word);\n }",
"function checkWord() {\n\t// clears the pos array so that a player cannot highlight the same word twice\n\tfunction clearPos(p) {\n\t\tp.start = p.end = 0;\n\t\treturn true;\n\t}\n\t// user highlights from first letter to last\n\tif (pos.some(function(o) {\n\t\treturn o.start === click.startPos && o.end === click.endPos && clearPos(o);\n\t})) {\n\t\treturn true;\n\t}\n\t// if user highlights from last letter to first\n\telse if (pos.some(function(o) {\n\t\treturn o.start === click.endPos && o.end === click.startPos && clearPos(o);\n\t})) {\n\t\treturn true;\n\t}\n\telse return false;\n}",
"function canPlaceCrossDown(word, index, ctx, ctx2) {\n var placed = false;\n for (var i = 0; i < word.length; i++) {\n var result = matchHorPoints(word[i]);\n if (result.length > 0 && !placed) {\n for (var j = 0; j < result.length; j++) {\n var xp = result[j].x;\n var yp = result[j].y - i;\n if (isValidCrossDown(xp, yp, word))\n if (isCleanHeadDown(xp, yp, word))\n if (isCleanTailDown(xp, yp))\n if (!touchleftDown(xp, yp, word))\n if (!touchRightDown(xp, yp, word)) {\n //if (isValidCrossDown(xp, yp, word))\n // if (!isOverlappingDown(xp, yp, word))\n placeWordDown(xp, yp, word, index, ctx, ctx2);\n addVerPoints(xp, yp, word.length);\n placed = true;\n break;\n }\n }\n }\n if (placed) break;\n }\n return placed;\n }",
"function canPlaceCrossAcross(word, index, ctx, ctx2) {\n var placed = false;\n for (var i = 0; i < word.length; i++) {\n var result = matchVerPoints(word[i]);\n if (result.length > 0 && !placed) {\n for (var j = 0; j < result.length; j++) {\n var xp = result[j].x - i;\n var yp = result[j].y;\n if (isValidCrossAcross(xp, yp, word))\n if (isCleanHeadAcross(xp, yp, word))\n if (isCleanTailAcross(xp, yp))\n if (!touchTopAcross(xp, yp, word))\n if (!touchBottomAcross(xp, yp, word)) {\n //if (isValidCrossAcross(xp, yp, word))\n // if (!isOverlappingAcross(xp, yp, word))\n placeWordAcross(xp, yp, word, index, ctx, ctx2);\n addHorPoints(xp, yp, word.length);\n placed = true;\n break;\n }\n }\n }\n if (placed) break;\n }\n return placed;\n }",
"function getWordIndex(square, word, dir) {\n let index = -1;\n let first_tile = word[0], last_tile = word[word.length-1];\n // For vertical words, x pos should == square's x pos, y pos should == square's pos +- OFFSET\n let first_x = (dir == 'vertical') ? first_tile.image.x : first_tile.image.x - OFFSET;\n let first_y = (dir == 'vertical') ? first_tile.image.y - OFFSET : first_tile.image.y;\n let last_x = (dir == 'vertical') ? last_tile.image.x : last_tile.image.x + OFFSET;\n let last_y = (dir == 'vertical') ? last_tile.image.y + OFFSET : last_tile.image.y;\n // Correct if current tile is placed at the beginning of the word\n if(first_x == square.x && first_y == square.y)\n index = 0;\n // Correct if current tile is placed at the end of the word\n else if(last_x == square.x && last_y == square.y)\n index = word.length;\n // Correct if current tile is placed in the blank space in the middle of a word\n else {\n for(let i = 0; i < word.length; i++) {\n if(word[i] != null)\n continue;\n if(dir == 'horizontal' && square.x == word[i-1].image.x + OFFSET) {\n index = i; break;\n }\n if(dir == 'vertical' && square.y == word[i-1].image.y + OFFSET) {\n index = i; break;\n }\n }\n // Remove the null from the word so it is replaced by the correct tile\n if(index != -1)\n word.splice(index, 1);\n }\n return index;\n}",
"checkNewWordsOnBoard() {\n console.log('2. --- checkNewWordsOnBoard ---')\n\n let wordH = []; //to save all the infromation on the horisontal \n let wordV = []; //to save all the infromation on the vertical \n let wordArray = []; //to save the final word array(word,points,extra points word times) \n let c = ''; //temp variable to save this.board[i][j].tile[0].char\n let p = 0; //temp variable to save this.board[i][j].tile[0].points;\n let s = ''; //temp variableto save this.board[i][j].special\n\n // CHECK HORISONTAL\n for (let i = 0; i < this.board.length; i++) {\n // CHECK VERTICAL\n for (let j = 0; j < this.board[i].length; j++) {\n // If we come across a board square that has a tile on it \n if (this.board[i][j].tile) {\n\n if (i === 0 && j === 0) {\n if (!!this.board[i + 1][j].tile) {\n // Below (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j + 1].tile) {\n // Beside - right (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (j === 0 && i > 0 && i < 14) {\n if (!!this.board[i - 1][j].tile || !!this.board[i + 1][j].tile) {\n // Above and below (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j + 1].tile) {\n // Beside + right (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (j === 14 && i === 0) {\n if (!!this.board[i][j - 1].tile) {\n // Beside - left (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i + 1][j].tile) {\n // Below (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (j === 14 && i > 0 && i < 14) {\n if (!!this.board[i - 1][j].tile || !!this.board[i + 1][j].tile) {\n // Above and below (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j - 1].tile) {\n // Beside - left (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (j === 14 && i === 14) {\n if (!!this.board[i - 1][j].tile) {\n // Above (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j - 1].tile) {\n // Beside - left (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (i === 14 && j > 0 && j < 14) {\n if (!!this.board[i][j + 1].tile || !!this.board[i][j - 1].tile) {\n // Beside - right and left (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i - 1][j].tile) {\n // Above (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (i === 14 && j === 0) {\n if (!!this.board[i - 1][j].tile) {\n // Above (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j + 1].tile) {\n // Beside - right (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (i === 0 && j > 0 && j < 14) {\n if (!!this.board[i][j - 1].tile || !!this.board[i][j + 1].tile) {\n // Beside - left and right (wordH)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i + 1][j].tile) {\n // Below (wordV)\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n }\n } else if (j > 0 && j < 14 && i > 0 && i < 14) {\n if ((!!this.board[i - 1][j].tile || !!this.board[i + 1][j].tile) && (!!this.board[i][j + 1].tile || !!this.board[i][j - 1].tile)) {\n // All of the board exkl. the tiles around\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i - 1][j].tile || !!this.board[i + 1][j].tile) {\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n } else if (!!this.board[i][j + 1].tile || !!this.board[i][j - 1].tile) {\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n } else {\n c = this.board[i][j].tile[0].char;\n p = +this.board[i][j].tile[0].points;\n s = this.board[i][j].special;\n wordH.push({ x: i, y: j, char: c, points: p, special: s });\n wordV.push({ x: i, y: j, char: c, points: p, special: s });\n }\n }\n }\n }\n }\n\n wordV.sort((a, b) => a.y > b.y ? -1 : 1);//sort by value of y from small to big\n wordH.sort((a, b) => a.x > b.x ? -1 : 1);//sort by value of x from small to big\n //Collect all the letters from same column and made it up to en word. \n //Calulate the points of word even if it has extra points(2x letters,3x letters). \n //save the words multiple times if it has extra points(2x word,3x word). \n if (wordV.length > 1) {\n let word = '';\n let points = 0;\n let multiple = 1;\n let position = [];\n for (let i = 0; i < wordV.length; i++) {\n\n if (((i < wordV.length - 1) && (wordV[i].y === wordV[i + 1].y)) || ((i > 0) && (wordV[i].y === wordV[i - 1].y))) {\n word += wordV[i].char;\n position.push({ x: wordV[i].x, y: wordV[i].y });\n // Changed here. \n // count the points\n //if there are some special box then save it to avoid count it again from next round\n if (wordV[i].special && !this.usedSpecialTiles.find(tile => (tile.x === wordV[i].x && tile.y === wordV[i].y))) {\n if ((wordV[i].special) === '2xLS') { points += 2 * wordV[i].points }\n else if ((wordV[i].special) === '3xLS') { points += 3 * wordV[i].points }\n else if ((wordV[i].special) === '2xWS') { multiple *= 2; points += wordV[i].points; }\n else if ((wordV[i].special) === '3xWS') { multiple *= 3; points += wordV[i].points; }\n else if ((wordV[i].special) === 'middle-star') {\n points += +wordV[i].points;\n //only for middle char if it is not the first word (there is a another player's score is not 0)\n //then the middle word will not be count dubble point\n let sumAllPlayerScore = 0;\n for (let k = 0; k < store.players.length; k++) {\n sumAllPlayerScore += +store.score[k].points;\n }\n if (isNaN(sumAllPlayerScore) || sumAllPlayerScore === 0) { multiple *= 2 }\n else { multiple *= 1; }\n }\n else points += +wordV[i].points;\n // save the word that have used special box\n this.usedSpecialTiles.push({ x: wordV[i].x, y: wordV[i].y });\n }\n else {\n points += +wordV[i].points;\n }\n }\n //if it is another column or if it has empty box between two char in the same column\n //then save the word to wordArray.Initialize variables in order to save the new words.\n if ((i === wordV.length - 1) || (wordV[i].y !== wordV[i + 1].y) || (wordV[i + 1].x - wordV[i].x !== 1)) {\n wordArray.push({ word: word, points: points, multiple: multiple, position: position })\n word = '';\n points = 0;\n multiple = 1;\n position = [];\n }\n }\n }\n //Collect all the letters from same row and made it up to en word. \n //Calulate the points of word even if it has extra points(2x letters,3x letters). \n //save the words multiple times if it has extra points(2x word,3x word). \n if (wordH.length > 1) {\n let word = '';\n let points = 0;\n let multiple = 1;\n let position = [];\n for (let i = 0; i < wordH.length; i++) {\n\n if (((i < wordH.length - 1) && (wordH[i].x === wordH[i + 1].x)) || ((i > 0) && (wordH[i].x === wordH[i - 1].x))) {\n word += wordH[i].char;\n position.push({ x: wordH[i].x, y: wordH[i].y });\n\n if (wordH[i].special && !this.usedSpecialTiles.find(tile => (tile.x === wordH[i].x && tile.y === wordH[i].y))) {\n if ((wordH[i].special) === '2xLS') { points += 2 * wordH[i].points; }\n else if ((wordH[i].special) === '3xLS') { points += 3 * wordH[i].points }\n else if ((wordH[i].special) === '2xWS') { multiple *= 2; points += wordH[i].points; }\n else if ((wordH[i].special) === '3xWS') { multiple *= 3; points += wordH[i].points; }\n else if ((wordH[i].special) === 'middle-star') {\n points += +wordH[i].points;\n //only for middle char if it is not the first word (there is a another player's score is not 0)\n //then the middle word will not be count dubble point\n let sumAllPlayerScore = 0;\n for (let k = 0; k < store.players.length; k++) {\n sumAllPlayerScore += +store.score[k].points;\n }\n if (isNaN(sumAllPlayerScore) || sumAllPlayerScore === 0) { multiple *= 2 }\n else { multiple *= 1; }\n }\n else points += +wordH[i].points;\n // save the word that have used special box\n this.usedSpecialTiles.push({ x: wordH[i].x, y: wordH[i].y });\n }\n else {\n points += +wordH[i].points;\n }\n }\n //if it is another row or if it has empty box between two char in the same row\n //then save the word to wordArray.Initialize variables in order to save the new words.\n if ((i === wordH.length - 1) || (wordH[i].x !== wordH[i + 1].x) || (wordH[i + 1].y - wordH[i].y !== 1)) {\n wordArray.push({ word: word, points: points, multiple: multiple, position: position })\n word = '';\n points = 0;\n multiple = 1;\n position = [];\n }\n }\n }\n //------------------------------\n this.newestWords = []\n if (store.storeCurrentWords.length !== undefined && store.storeCurrentWords.length > 0) {\n // Check if a old words exists in the wordsarray\n for (let i = 0; i < wordArray.length; i++) {\n if (store.storeOldWords.indexOf(wordArray[i].word) !== -1) {\n console.log(\"Old word! \", wordArray[i].word)\n } else {\n console.log(\"New word! \", wordArray[i].word)\n this.newestWords.push(wordArray[i])\n }\n }\n store.storeCurrentWords = this.newestWords;\n } else {\n store.storeCurrentWords = wordArray;\n }\n }",
"function check_vertical(placed_token) {\n var token_row_char = placed_token[5];\n var token_row_int = parseInt(token_row_char);\n var check_row = token_row_int + 1;\n token_sequence = [];\n token_sequence.push(placed_token);\n\n while (check_row < 7) {\n var check_token = '#row-' + check_row + '-col-' + placed_token[11];\n if ((!player_1_turn && $(check_token).parent().is('.circle-red')) || (player_1_turn && $(check_token).parent().is('.circle-blue'))) {\n token_sequence.push(check_token);\n } else { break; }\n check_row++;\n }\n\n if (token_sequence.length > 3) return true;\n \n return false;\n}",
"checkVertical(x, y, playerId) {\r\n //Includes piece that was just placed\r\n let connectedPieces = 1;\r\n //Check above\r\n connectedPieces += this.checkForConnected(x, y, playerId, (x) => x, (y,i) => y + i);\r\n //Check below\r\n connectedPieces += this.checkForConnected(x, y, playerId, (x) => x, (y,i) => y - i);\r\n \r\n if(connectedPieces > 3) return true;\r\n \r\n return false;\r\n }",
"function isOverlappingAcross(x, y, word) {\n var len = word.length;\n var grid_word = \"\";\n for (var j = 0; j < len; j++) {\n grid_word += letterAt(x + j, y);\n }\n return wordPlaced.includes(grid_word);\n }",
"function isInBound(point, words) {\n let wordSize = words.length;\n let innerWordSize = words[0].length;\n\n let row = point[0];\n let col = point[1];\n if (row >= wordSize || row < 0 || col >= innerWordSize || col < 0) {\n return false;\n }\n return true;\n}",
"function canPlaceIsolateAcross(x, y, word, index, ctx, ctx2) {\n if (isCleanHeadAcross(x, y, word)) {\n if (isCleanTailAcross(x, y)) {\n if (!isOverlappingAcross(x, y, word)) {\n if (!touchTopAcross(x, y, word)) {\n if (!touchBottomAcross(x, y, word)) {\n if (isValidIsolateAcross(x, y, word)) {\n placeWordAcross(x, y, word, index, ctx, ctx2);\n addHorPoints(x, y, word.length);\n return true;\n }\n }\n }\n }\n }\n }\n return false;\n }",
"function text2TextIntesecton(x, y, size, word, otherWord){\n var wordWidth = Math.round(ctx.measureText(word).width+size);\n var wordHight = size;\n var otherWordWidth = Math.round(ctx.measureText(otherWord.word).width+otherWord.size);\n var otherWordHight = otherWord.size;\n if((x+wordWidth)<otherWord.x || (otherWord.x+otherWordWidth)<x || y<(otherWord.y-otherWord.size) || otherWord.y<(y-size)){\n return false;\n }\n return true;\n}",
"function verifyFormedWord() {\n var rIndex = 0, cIndex, letter, hasError = false, word = \"\";\n\n // Update word string with the letters gathered from tiles in the board.\n // use special character to represent gap in the board.\n for (cIndex = 0; cIndex < singleRowBoard.columnCount; ++cIndex) {\n letter = singleRowBoard.slots[rIndex][cIndex].letter;\n if (typeof(letter) === \"undefined\") {\n word += \"\\xC5\";\n } else {\n word += letter;\n }\n }\n word = word.replace(/^\\xC5+/, \"\").replace(/\\xC5+$/, \"\");\n\n // For Empty board, show no error\n if (word == \"\") {\n document.getElementById(\"nextWordButton\").disabled = true;\n verifyNoGapRule(true);\n verifyTwoLettersRule(true);\n return false;\n }\n\n // Verify gap based on regex\n var wordWithGapRegex = new RegExp(\"[A-Z_]\\xC5+[A-Z_]\");\n if (wordWithGapRegex.test(word)) {\n verifyNoGapRule(false);\n hasError = true;\n } else {\n verifyNoGapRule(true);\n hasError = false;\n }\n\n // Verify two letters rule\n if (word.length >= 2) {\n verifyTwoLettersRule(true);\n } else {\n verifyTwoLettersRule(false);\n hasError = true;\n }\n\n // disable next word button if there is error\n document.getElementById(\"nextWordButton\").disabled = hasError;\n return !hasError;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Init the current view as the top right view of the quad view | initTopRight(){
this._config = {
left: 0.5,
bottom: 0.5,
width: 0.5,
height: 0.5,
position: [ 0, -this._objectSize, 0 ],
up: [ 0, -1, 0 ],
// init with a given angle to correct issues
initAngle: {
axis: new THREE.Vector3( 1, 0, 0 ),
angle: -0.0001
}
}
this._viewName = "top_right";
this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );
} | [
"initTopRight(){\n this._config = {\n left: 0.5,\n bottom: 0.5,\n width: 0.5,\n height: 0.5,\n position: [ 0, -this._objectSize, 0 ],\n up: [ 0, -1, 0 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: -0.0001\n }\n };\n this._viewName = \"top_right\";\n this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );\n }",
"initTopLeft(){\n this._config = {\n left: 0.0,\n bottom: 0.5,\n width: 0.5,\n height: 0.5,\n position: [ -this._objectSize, 0, 0 ],\n up: [ -1, 0, 0 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: -0.0001\n }\n }\n this._viewName = \"top_left\";\n this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );\n }",
"initTopLeft(){\n this._config = {\n left: 0.0,\n bottom: 0.5,\n width: 0.5,\n height: 0.5,\n position: [ -this._objectSize, 0, 0 ],\n up: [ -1, 0, 0 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: -0.0001\n }\n };\n this._viewName = \"top_left\";\n this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );\n }",
"initBottomRight(){\n this._config = {\n left: 0.5,\n bottom: 0,\n width: 0.5,\n height: 0.5,\n position: [ -this._objectSize/10, this._objectSize/10, -this._objectSize/15 ],\n up: [ 0, 0, -1 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: 0\n }\n };\n this._viewName = \"bottom_right\";\n this._backgroundColor = new THREE.Color().setRGB( 0.97, 0.97, 0.97 );\n }",
"initBottomRight(){\n this._config = {\n left: 0.5,\n bottom: 0,\n width: 0.5,\n height: 0.5,\n position: [ -this._objectSize/10, this._objectSize/10, -this._objectSize/15 ],\n up: [ 0, 0, -1 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: 0\n }\n }\n this._viewName = \"bottom_right\";\n this._backgroundColor = new THREE.Color().setRGB( 0.97, 0.97, 0.97 );\n }",
"constructor() {\n this._viewport = { offset: { x: 0, y: 0 } };\n }",
"_initViews( DomContainer ){\n var that = this;\n\n var topLeftView = new QuadView(this._scene, this._renderer, this._cameraDistance);\n topLeftView.initTopLeft();\n topLeftView.initOrthoCamera();\n topLeftView.useRelativeCoordinatesOf(this._planeManager.getMultiplaneContainer());\n topLeftView.enableLayer( 0 );\n\n var topRightView = new QuadView(this._scene, this._renderer, this._cameraDistance);\n topRightView.initTopRight();\n topRightView.initOrthoCamera();\n topRightView.useRelativeCoordinatesOf(this._planeManager.getMultiplaneContainer());\n topRightView.enableLayer( 0 );\n\n var bottomLeft = new QuadView(this._scene, this._renderer, this._cameraDistance);\n bottomLeft.initBottomLeft();\n bottomLeft.initOrthoCamera();\n bottomLeft.useRelativeCoordinatesOf(this._planeManager.getMultiplaneContainer());\n bottomLeft.enableLayer( 0 );\n\n var bottomRight = new QuadView(this._scene, this._renderer, this._cameraDistance);\n bottomRight.initBottomRight();\n bottomRight.initPerspectiveCamera();\n bottomRight.enableLayer( 1 );\n bottomRight.disableLayer(0);\n bottomRight.addTrackballControl(this._render, this._domContainer);\n\n // adding the views\n this._quadViews.push(topLeftView);\n this._quadViews.push(topRightView);\n this._quadViews.push(bottomLeft);\n this._quadViews.push(bottomRight);\n\n // the quadviewinteraction instance deals with mouse things\n this._quadViewInteraction = new QuadViewInteraction( this._quadViews, DomContainer);\n this._quadViewInteraction.setMultiplaneContainer( this._planeManager.getMultiplaneContainer() );\n\n this._quadViewInteraction.onClickPlane(\n \"perspective\",\n\n function( point ){\n that.setMultiplanePosition( point.x, point.y, point.z);\n that.refreshUniforms();\n }\n );\n\n }",
"function firstQuadrant() {\n\tgraph.setViewport([-5, 100, -5, 100]);\n}",
"function setupView() {\n // set home buttone view point to initial extent\n var homeButton = new Home({\n view: view,\n viewpoint: new Viewpoint({\n targetGeometry: initialExtent\n })\n });\n view.ui.add(homeButton, \"top-left\");\n\n //expand widget\n editExpand = new Expand({\n expandIconClass: \"esri-icon-edit\",\n expandTooltip: \"Expand Edit\",\n expanded: false,\n view: view,\n content: editArea\n });\n view.ui.add(editExpand, \"top-right\");\n }",
"function setScreenTopRightCorner()\n{\n\tvar screenPoint : Vector3 = new Vector3(Screen.width, Screen.height, 0f);\n\tvar worldPoint : Vector3 = mainCam.ScreenToWorldPoint(screenPoint);\n\t\n\tthis.screenTopRightCorner = new Vector2(worldPoint.x, worldPoint.y);\n}",
"initBottomLeft(){\n this._config = {\n left: 0.0,\n bottom: 0.0,\n width: 0.5,\n height: 0.5,\n position: [ 0, 0, -this._objectSize ],\n up: [ 0, 1, 0 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: 0\n }\n };\n this._viewName = \"bottom_left\";\n this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );\n }",
"initBottomLeft(){\n this._config = {\n left: 0.0,\n bottom: 0.0,\n width: 0.5,\n height: 0.5,\n position: [ 0, 0, -this._objectSize ],\n up: [ 0, 1, 0 ],\n // init with a given angle to correct issues\n initAngle: {\n axis: new THREE.Vector3( 1, 0, 0 ),\n angle: 0\n }\n }\n this._viewName = \"bottom_left\";\n this._backgroundColor = new THREE.Color().setRGB( 1, 1, 1 );\n }",
"home() {\n this.setXY(0, 0);\n this.setHeading(0);\n }",
"init()\n {\n this.x = this.scene.viewport.width / 2;\n this.y = this.scene.viewport.height / 2;\n }",
"function camera_top_view() {\n camera.rotation.x += Math.PI/2;\n camera.position.y = 6;\n camera.lookAt(new THREE.Vector3(0,0,0));\n}",
"function topUpRLeg() {\n\t\n\tinstanceMatrix = mult(modelViewMatrix, translate( uRLegsTransX, torsoTransY, uTLegsTransZ) );\n\tinstanceMatrix = mult(instanceMatrix, scale4(uLegWidth, uLegHeight, -uLegDepth) );\n\t\n\tgl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(instanceMatrix));\n\tgl.drawArrays( gl.TRIANGLES, NumVertices-36, 36 );\n}",
"setViewOffset(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();}",
"attachToRightController() {\n this.root.parent = this.vrHelper.controller.right.grip;\n this.root.position = new BABYLON.Vector3(-this.verticalWeb,0,.1);\n this.root.rotation = new BABYLON.Vector3(Math.PI/2,0,-Math.PI/2);\n //this.rowOffset = new BABYLON.Vector3(this.verticalXR,0,0);\n this.rowOffset = new BABYLON.Vector3(0,this.verticalXR,0);\n this.currentController = 'right';\n }",
"function setView(l,r,b,t){\n\torthogonal.l=l;\n\torthogonal.r=r;\n\torthogonal.b=b;\n\torthogonal.t=t;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetch todos using GraphQL+ query | async fetchTodos() {
const query = `{
todos(func: has(is_todo))
{
uid
title
completed
}
}`
const res = await this.dgraph.newTxn().query(query)
return res.data.todos || []
} | [
"async fetchTodos({ commit }) {\n console.log(commit)\n const response = await axios.get('http://apicreation-260015.appspot.com/todos');\n console.log(response.data)\n commit('setTodos', response.data) //in order to call the mutation, we need to use commit. The first argument is setTodos in mutations and the second argument is the second parameter passed in mutations\n }",
"function getAll() {\n return todos;\n }",
"getAllTodos(){\n var todos = [];\n var self = this;\n request.get('/api/todos')\n .accept('application/json')\n .query({ timestamp: new Date().getTime() })\n .end((err, res) => {\n\n if(!err && !res.error) {\n var todos = JSON.parse(res.text);\n self.notifyStore(todos);\n } else{\n\n }\n }\n );\n }",
"async fetchTodos() {\n /// url to fetch todos ==== https://jsonplaceholder.typicode.com/users/1/todos\n const result = await makeRequest('GET', 'https://jsonplaceholder.typicode.com/users/1/todos');\n return JSON.parse(result);\n }",
"list(req, res) {\n return Todo\n .all()\n .then((todos) => res.status(200).send(todos))\n .catch((error) => res.status(400).send(error))\n }",
"getAll(state) {\n return state.todos;\n }",
"async getTodos() {\n try {\n const todos = await Todo.find({}).sort({ created: -1 });\n return todos;\n } catch (err) {\n throw new Error(err);\n }\n }",
"getAll() {\n return _todos;\n }",
"async fetchTodos({ commit }) {\n console.log(commit)\n const response = await axios.get('https://jsonplaceholder.typicode.com/todos');\n commit('setTodos', response.data) //in order to call the mutation, we need to use commit. The first argument is setTodos in mutations and the second argument is the second parameter passed in mutations\n }",
"function fetchTodos() {\n return todoService.getTodos();\n }",
"getAllTodos(){\n return knex('todo')\n .select()\n }",
"function fetchAllTodos() {\n\tvar TodoModel = require(\"../models/TodoList.model\")\n\treturn new Promise(function (resolve, reject) {\n\t\tvar conditions = {deleted: false};\n\t\tTodoModel.find(conditions, function (err, results) {\n\t\t\tif(err) throw err;\n\t\t\tresolve(results);\n\t\t});\n\t});\n}",
"async getTodos(order) {\n // In Dexie, we create queries by chaining methods, such as orderBy to\n // sort by an indexed field, and reverse to reverse the order we retrieve\n // data in. The toArray method returns a promise that resolves to the array\n // of the items in the todos store.\n let todos = [];\n switch (order) {\n case forwardOrder:\n todos = await this.todos.orderBy('id').toArray();\n break;\n case reverseOrder:\n todos = await this.todos.orderBy('id').reverse().toArray();\n break;\n case unfinishedFirstOrder:\n todos = await this.todos.orderBy('done').toArray();\n break;\n default:\n // as a default just fall back to forward order\n todos = await this.todos.orderBy('id').toArray();\n }\n\n // The reason we need to modify the done field on each todo is because in\n // IndexedDB, integers can be indexed, but booleans cannot, so we represent\n // \"done\" status as an integer. Only the database logic needs to know that\n // detail, though, so for convenience when we return the todos, their \"done\"\n // status is a boolean.\n return todos.map((t) => {\n t.done = !!t.done;\n return t;\n });\n }",
"async function getAllTodos() {\n const todos = await makeRequest(\"/api\", \"GET\")\n return todos\n}",
"RetrieveTodos() {\n getFetch(\n `http://localhost:5000/api/list/${this.state.currentUser.email}`\n ).then((res) => {\n if (res.success) {\n if (res.todos.length === 0)\n this.setState({\n fetching: false,\n showAddTaskButton: true,\n msg: \"You don't have any Todos! Try adding one :)\",\n todos: res.todos\n });\n else\n this.setState({\n fetching: false,\n showAddTaskButton: true,\n todos: res.todos,\n msg: \"\"\n });\n } else {\n this.setState({ fetching: false, msg: res.msg });\n }\n });\n }",
"async getTodos() {\n // return all Latest Stories\n return new Promise((resolve, _) => resolve(data));\n }",
"async function getAllTodos() {\r\n const { data: todos } = await axios.get(API_URL)\r\n return todos\r\n}",
"function getTodos(){\n return todos;\n}",
"async get(ctx) {\n const { id, dereferenceItems = false, queryDepth } = ctx.params;\n let constructQuery = '',\n whereQuery = '';\n\n if (dereferenceItems) {\n const [constructBnQuery, whereBnQuery] = buildBlankNodesQuery(queryDepth);\n constructQuery = '?s1 ?p1 ?o1 .' + constructBnQuery;\n whereQuery = '?s1 ?p1 ?o1 .' + whereBnQuery;\n }\n\n let result = await ctx.call('triplestore.query', {\n query: `\n PREFIX as: <https://www.w3.org/ns/activitystreams#>\n CONSTRUCT {\n <${id}> a ?collectionType ;\n as:items ?s1 .\n ${constructQuery}\n }\n WHERE {\n <${id}> a as:Collection, ?collectionType .\n OPTIONAL { \n <${id}> as:items ?s1 .\n ${whereQuery}\n }\n }\n `,\n accept: MIME_TYPES.JSON\n });\n\n result = await jsonld.frame(result, {\n '@context': this.settings.context,\n '@id': id\n });\n\n if (result['@graph'].length === 0) {\n ctx.meta.$statusCode = 404;\n } else {\n let { items, ...collection } = result['@graph'][0];\n items = !items ? [] : Array.isArray(items) ? items : [items];\n\n const itemsProp = this.isOrderedCollection(collection) ? 'orderedItems' : 'items';\n\n collection = {\n '@context': result['@context'],\n ...collection,\n [itemsProp]: items,\n totalItems: items.length\n };\n\n return collection;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Progress bar based on pseudologarithmic progression | function startProgressBarLogProgression(part,max){
var partition=1;
if(part!=null){
partition=part;
}
var maxTot=1200;
if(max!=null){
maxTot=max;
}
createProgressBar(maxTot,1);
if(interval!=null){
clearInterval(interval);
}
interval=setInterval('updateProgressBarLog('+partition+')',500);
} | [
"onProgress(level, currentValue, maxValue, statusLine) {\n let prefix = \"• \".repeat(level);\n console.log(prefix + \"[\" + currentValue + \"/\" + maxValue + \"] \" + statusLine);\n }",
"function bar_progress(direction) {\n const number_of_steps = progressLine.data('number-of-steps');\n const now_value = progressLine.data('now-value');\n let new_value = 0;\n if (direction == 'right') {\n new_value = now_value + (100 / number_of_steps);\n }\n else if (direction == 'left') {\n new_value = now_value - (100 / number_of_steps);\n }\n progressLine.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);\n }",
"function progressBar(progressVal,totalPercentageVal = 100) {\n var strokeVal = (4.64 * 100) / totalPercentageVal;\n\tvar x = document.querySelector('.progress-circle-prog');\n x.style.strokeDasharray = progressVal * (strokeVal) + ' 999';\n\t//$('.progress-text').data('progress', progressVal);\n}",
"function updateProgressBar(){\n \tbar.value = bar.value + 9.09;\n }",
"getProgressPercent() {\n const progressPercent = this.state.pastStepCount / this.state.stepGoal;\n return Math.floor(progressPercent * 100);\n }",
"function updateProgress() {\r\n\t\t\tlet progress = progressComponents.reduce((sum, value) => sum + value) / progressComponents.length;\r\n\t\t\tif (args && args.progress) args.progress(progress);\r\n\t\t}",
"function makeProgressBar(exp_attuale, lvl_attuale, exp_lvls){\r\n\r\n if (lvl_attuale==\"\") {\r\n\r\n for (var i=0; i <= exp_lvls.length; i++) {\r\n\r\n if (exp_lvls[i] > exp_attuale || i == exp_lvls.length) {\r\n\r\n lvl_attuale = i;\r\n\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n\r\n var exp_necessaria = exp_lvls[lvl_attuale];\r\n\r\n if (lvl_attuale == 0) {\r\n\r\n\t\t\tvar perc = (exp_attuale * 100 / exp_necessaria).toFixed(2);\r\n\r\n\t //var perc = 0;\r\n\r\n } else if (lvl_attuale == exp_lvls.length) {\r\n\r\n var perc = 100;\r\n\r\n } else {\r\n\r\n exp_attuale = exp_attuale - exp_lvls[lvl_attuale-1];\r\n\r\n exp_necessaria = exp_necessaria - exp_lvls[lvl_attuale-1];\r\n\r\n var perc = (exp_attuale * 100 / exp_necessaria).toFixed(2);\r\n\r\n }\r\n\r\n // Stile\r\n\r\n/*\r\n var cssStyle = \"\";\r\n\r\n return progress_bar_html;\r\n\r\n*/\r\n\r\n var cssStyle = \"\";\r\n\r\n\tif (GM_getValue(\"SHOW_NEW_STYLE\", false)) {\r\n\r\n cssStyle += \".bar_wrap {width:150px; margin:1 0 0 9px;border: 1px solid #1C1C1C;background-color: #65541B;-moz-box-shadow: 0 0 1px #666, inset 0 1px 1px #222;background-image:-moz-linear-gradient(#65541B, #8C7526 50%, #65541B);}.bar {height: 4px;background-color: #BABA53;border-right: 1px solid #282828;-moz-box-shadow: inset 0 0 1px #ddd;background-image: -moz-linear-gradient(#E1E266, #BABA53 50%, #ABAF4B 51%, #848738);-moz-transition: all 1s ease;-moz-animation-duration: 1s;-moz-animation-name: slidein;}@-moz-keyframes slidein {from {width: 100%}}.bar:hover {\"+/*-moz-animation: animate-stripes 3s linear infinite;*/\"}@-moz-keyframes animate-stripes {0% {background-position: 0 0;} 100% {background-position:0 22px;}}.htooltip, .htooltip:visited, .tooltip:active {color: #0077AA;text-decoration: none;}.htooltip:hover {color: #0099CC;}.htooltip span {background-color: rgba(0,0,0, 0.8);-moz-border-radius: 15px 15px 15px 0px;-moz-box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5);color: #fff;margin-left: -1px;margin-top: -25px;opacity: 0;padding: 2px 5px;position: absolute;text-decoration: none;visibility: hidden;width: 100px;z-index: 10;-ms-transition: opacity 0.4s ease-in-out, visibility 0.4s ease-in-out;}\";\r\n GM_addStyle(cssStyle);\r\n var progress_bar_html = \"<div class=\\\"bar_wrap htooltip\\\">\"+\r\n \"<div class=\\\"bar\\\" style=\\\"width:\"+ perc +\"%\\\"></div>\"+\r\n \"<span>progress: \"+ perc +\"%</span>\"+\r\n \"</div>\"+\"<div style='font-size: 8px; font-weight: bold; margin: -9px 0 0 165px'>\"+perc+\" %</div>\";\r\n\r\n } else {\r\n\r\n cssStyle += \".table_progress {width:100px; height:3px; padding: 0px; margin-left: 9px; margin-top: 0px; margin-bottom: 0px; border: 1px solid black;}\";\r\n GM_addStyle(cssStyle);\r\n var progress_bar_html = \"<DIV style='margin:1 0 0 9px;' class=\\\"table_progress\\\" title=\\\"\"+ perc +\"%\\\">\"+\r\n \"<img src=\\\"i/top/logot.jpg\\\" height=\\\"3\\\" width=\\\"\"+ perc +\"\\\" title=\\\"\"+ perc +\"%\\\" alt\\\"\"+ perc +\"%\\\">\"+\r\n\r\n \"</DIV>\"+\"<div style='font-size: 8px; font-weight: bold; margin: -9px 0 0 115px'>\"+perc+\" %</div>\";\r\n\r\n\t}\r\n\r\n return progress_bar_html;\r\n\r\n }",
"function progressBarUpdate(argProgress) {\n\tprogressBar.value = Math.floor(100 * argProgress);\n\tpercentage.innerHTML = '[' + points + '/' + possiblePoints + 'points] ' + progressBar.value + '%';\n}",
"function increment() {\n setTimeout(function() {\n if (STATUS >= 0.9) return;\n setProgress(STATUS + Math.pow(12, 1 - STATUS) / 100);\n increment();\n }, SPEED)\n }",
"function onProgress() {\n //console.log(getProgress()+\"%\"); //For debugging\n}",
"updateProgressBar() {\n let revealRange = 103 - 24; //See css comment (progressBox). \n let revealPercent = this.points / this.pointsNeeded; //Current percent of points needed.\n this.baseProgressMargin = -24; //Margin value: Progress box hides bar.\n this.progressMargin = this.baseProgressMargin - revealPercent * revealRange; //New margin value\n document.getElementById(\"progress\").style.marginTop = this.progressMargin + \"vh\"; //Reveal percent of glowing border as level progress indicator.\n }",
"function progressBar1() {\n let current = 1;\n let timerId = setInterval(function() {\n console.log(`${current}%`);\n if (current === 100) {\n clearInterval(timerId);\n }\n current++;\n }, 500);\n}",
"function scrollBarEffect() {\n var winScroll = document.body.scrollTop || document.documentElement.scrollTop;\n var height = document.documentElement.scrollHeight -\n document.documentElement.clientHeight;\n //var divScroll = document.getElementById(\"log\").scrollTop;\n var height = document.documentElement.scrollHeight -\n document.documentElement.clientHeight;\n /*var height = document.getElementById(\"log\").scrollHeight -\n document.getElementById(\"log\").clientHeight;*/\n var scrolled = (winScroll / height) * 100;\n //var scrolled = (divScroll / height) * 100;\n document.getElementById(\"progress-bar\").style.width = scrolled + \"%\";\n}",
"function onProgress(n) {\n // round by one digit (0.1234 -> 0.1) and display\n const f = Math.round(n * 10) / 10;\n if (last !== f) {\n console.log(f * 100 + \"%\"); // e.g. renders 10%\n }\n last = f;\n}",
"function progressBar(){\n\t\t\tif(percent <= 100){\n\t\t\t\t$(timerProgress).width(percent + \"%\");\n\t\t\t\tpercent++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(timer.loop === 1){\n\t\t\t\t\tpercent = 0;\n\t\t\t\t\tswitchImages(currentIndex);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}",
"function increment(param){\n \n var progress = ractive.get('progress'+progressBar.selected);\n var progressLabel = ractive.get('progressLabel'+progressBar.selected);\n ractive.set('progressLabel'+progressBar.selected,progressLabel+param);\n progress+=param;\n if(progress>=100){\n ractive.set('progress'+progressBar.selected,100);\n ractive.set('colorClass'+progressBar.selected,'progress-bar-danger');\n }\n\t\t \n else\n ractive.set('progress'+progressBar.selected,progress);\n \n }",
"function increment(progress) {\n let units = Math.round(++progress.current / progress.amount * 50);\n\n progress('[' + chalk.yellow('='.repeat(units) + ' '.repeat(50 - units)) + '] '\n + chalk.blue(progress.current + '/' + progress.amount));\n}",
"function renderProgress(val, perc, message) {\n\t\tbar.style.width = perc + \"%\";\n\n renderMessage(message);\n\t}",
"function startBar() {\n if (i == 0) {\n i = 1;\n width = 0;\n var id = setInterval(tick, 10);\n\n // 1 tick function of progress bar 1 tick = 100ms and\n function tick() {\n if (width >= 100 ) {\n clearInterval(id);\n i = 0;\n checkEndGame();\n } else {\n adjustWidth();\n }\n\n // adjust width of progress bar and % displayed each tick\n function adjustWidth() {\n width += 0.0166666666666667;\n bar.style.width = width + \"%\";\n bar.innerHTML = width.toFixed(1) + \"%\";\n\n // set width value to a var\n barWidth = width;\n }\n\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add disableinteraction layer and adjust the size and position of the layer | function _disableInteraction () {
var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');
if (disableInteractionLayer === null) {
disableInteractionLayer = document.createElement('div');
disableInteractionLayer.className = 'introjs-disableInteraction';
this._targetElement.appendChild(disableInteractionLayer);
}
_setHelperLayerPosition.call(this, disableInteractionLayer);
} | [
"function _disableInteraction(){var disableInteractionLayer=document.querySelector(\".introjs-disableInteraction\");if(disableInteractionLayer===null){disableInteractionLayer=_createElement(\"div\",{className:\"introjs-disableInteraction\"});this._targetElement.appendChild(disableInteractionLayer);}setHelperLayerPosition.call(this,disableInteractionLayer);}",
"function _disableInteraction () {\n\t var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');\n\t if (disableInteractionLayer === null) {\n\t disableInteractionLayer = document.createElement('div');\n\t disableInteractionLayer.className = 'introjs-disableInteraction';\n\t this._targetElement.appendChild(disableInteractionLayer);\n\t }\n\t\n\t _setHelperLayerPosition.call(this, disableInteractionLayer);\n\t }",
"function _disableInteraction() {\n var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');\n if (disableInteractionLayer === null) {\n disableInteractionLayer = document.createElement('div');\n disableInteractionLayer.className = 'introjs-disableInteraction';\n this._targetElement.appendChild(disableInteractionLayer);\n }\n\n _setHelperLayerPosition.call(this, disableInteractionLayer);\n }",
"function _disableInteraction () {\n var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');\n if (disableInteractionLayer === null) {\n disableInteractionLayer = document.createElement('div');\n disableInteractionLayer.className = 'introjs-disableInteraction';\n this._targetElement.appendChild(disableInteractionLayer);\n }\n\n _setHelperLayerPosition.call(this, disableInteractionLayer);\n }",
"function _disableInteraction() {\n var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');\n\n if (disableInteractionLayer === null) {\n disableInteractionLayer = document.createElement('div');\n disableInteractionLayer.className = 'introjs-disableInteraction';\n this._targetElement.appendChild(disableInteractionLayer);\n }\n\n _setHelperLayerPosition.call(this, disableInteractionLayer);\n }",
"disableDrawTool() {\n if (this.curDrawInteraction_ !== undefined) {\n this.removeInteraction(this.curDrawInteraction_);\n this.curDrawInteraction_ = undefined;\n }\n }",
"function DisableLayer(hide){\n \n if(mymap.hasLayer(hide)) {\n mymap.removeLayer(hide);\n }\n\n}",
"function activateLayer( l )\n{\n l.enabled = true;\n l.solo = false;\n}",
"disableLayer( l ){\n this._plane.children.forEach(function(sp){\n sp.layers.disable(l);\n });\n }",
"function DisableTranspOptionalLayers(index, id_minus, id_plus, checkboxId)\n{\n\n var checkid = document.getElementById(checkboxId);\n\n\n if (checkid.checked == true)//check if the layer is selected\n {\n var optionOpacity = optionalArray[index];//localte which global opacity layer it is\n\n //Disables the buttons.\n if (optionOpacity < maxOpacity) {\n document.getElementById(id_minus).disabled = false;\n changeColor(document.getElementById(id_minus), 0);//Change color to enabled\n } else {\n document.getElementById(id_minus).disabled = true;\n changeColor(document.getElementById(id_minus), 3);//Change color to disabled \n }\n\n if (optionOpacity > minOpacity) {\n document.getElementById(id_plus).disabled = false;\n changeColor(document.getElementById(id_plus), 0);//Change color to enabled\n } else {\n document.getElementById(id_plus).disabled = true;\n changeColor(document.getElementById(id_plus), 3);//Change color to disabled \n }\n }\n else\n {\n //Disables the buttons.\n document.getElementById(id_minus).disabled = true;\n changeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\n document.getElementById(id_plus).disabled = true;\n changeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\n }\n\n}",
"function cancle_add_layer(){\n\t$('#add-layer').html('');\n}",
"disable() {\n this._selectInteraction.setActive(false);\n this._dragBoxInteraction.setActive(false);\n }",
"function disablePointSelection(){\r\n\taddPointMode = false;\r\n}",
"enableCreateKeepoutAreaPolygonTool() {\n this.disableActiveTool();\n this.keepoutAreaPolygonTool.enableViewEventHandlers();\n }",
"function layerOff() {\n throttledRedraw.cancel();\n drawLayer.interrupt();\n touchLayer.selectAll('.qaItem.improveOSM')\n .remove();\n\n drawLayer\n .transition()\n .duration(250)\n .style('opacity', 0)\n .on('end interrupt', () => {\n editOff();\n dispatch.call('change');\n });\n }",
"removeLayer() {\n if (this.__shown) {\n const map = this.map;\n map.removeLayer(this.uniqueId + 'fillpoly');\n this.__shown = false;\n }\n }",
"disableComposition() {\n\n if (!this.disabledComposition) {\n this.disabledComposition = true;\n this.mainLayer.getChildren().forEach((path) => {\n if (!this.newPath || this.newPath != path) {\n path.strokeColor = path.fillColor;\n path.fillColor = null;\n }\n });\n /*\n if (this.newPath) {\n this.newPath.strokeColor = this.newPath.fillColor;\n this.newPath.fillColor = null;\n }\n */\n this.mainLayer.opacity = 1;\n\n }\n }",
"removeLayer() {\n if (this.__shown) {\n this.__casesPopup.disablePopups();\n\n const map = this.map;\n map.removeLayer(this.uniqueId + 'fillpoly');\n\n this.__shown = false;\n }\n }",
"setEnableElevationOverlay(enable) {\n // to be overloaded by subclasses\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activate interaction on the menu. Wire up keyboard listerns for clicks, keypresses, backdrop closing, etc. | function activateInteraction() {
element.addClass('md-clickable');
// close on backdrop click
if (opts.backdrop) opts.backdrop.on('click', onBackdropClick);
// Wire up keyboard listeners.
// - Close on escape,
// - focus next item on down arrow,
// - focus prev item on up
opts.menuContentEl.on('keydown', onMenuKeyDown);
opts.menuContentEl[0].addEventListener('click', captureClickListener, true);
// kick off initial focus in the menu on the first element
var focusTarget = opts.menuContentEl[0]
.querySelector(prefixer.buildSelector(['md-menu-focus-target', 'md-autofocus']));
if ( !focusTarget ) {
var firstChild = opts.menuContentEl[0].firstElementChild;
focusTarget = firstChild && (firstChild.querySelector('.md-button:not([disabled])') || firstChild.firstElementChild);
}
focusTarget && focusTarget.focus();
return function cleanupInteraction() {
element.removeClass('md-clickable');
if (opts.backdrop) opts.backdrop.off('click', onBackdropClick);
opts.menuContentEl.off('keydown', onMenuKeyDown);
opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);
};
// ************************************
// internal functions
// ************************************
function onMenuKeyDown(ev) {
var handled;
switch (ev.keyCode) {
case $mdConstant.KEY_CODE.ESCAPE:
opts.mdMenuCtrl.close(false, { closeAll: true });
handled = true;
break;
case $mdConstant.KEY_CODE.UP_ARROW:
if (!focusMenuItem(ev, opts.menuContentEl, opts, -1) && !opts.nestLevel) {
opts.mdMenuCtrl.triggerContainerProxy(ev);
}
handled = true;
break;
case $mdConstant.KEY_CODE.DOWN_ARROW:
if (!focusMenuItem(ev, opts.menuContentEl, opts, 1) && !opts.nestLevel) {
opts.mdMenuCtrl.triggerContainerProxy(ev);
}
handled = true;
break;
case $mdConstant.KEY_CODE.LEFT_ARROW:
if (opts.nestLevel) {
opts.mdMenuCtrl.close();
} else {
opts.mdMenuCtrl.triggerContainerProxy(ev);
}
handled = true;
break;
case $mdConstant.KEY_CODE.RIGHT_ARROW:
var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU');
if (parentMenu && parentMenu != opts.parent[0]) {
ev.target.click();
} else {
opts.mdMenuCtrl.triggerContainerProxy(ev);
}
handled = true;
break;
}
if (handled) {
ev.preventDefault();
ev.stopImmediatePropagation();
}
}
function onBackdropClick(e) {
e.preventDefault();
e.stopPropagation();
scope.$apply(function() {
opts.mdMenuCtrl.close(true, { closeAll: true });
});
}
// Close menu on menu item click, if said menu-item is not disabled
function captureClickListener(e) {
var target = e.target;
// Traverse up the event until we get to the menuContentEl to see if
// there is an ng-click and that the ng-click is not disabled
do {
if (target == opts.menuContentEl[0]) return;
if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||
target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {
var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');
if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {
close();
}
break;
}
} while (target = target.parentNode)
function close() {
scope.$apply(function() {
opts.mdMenuCtrl.close(true, { closeAll: true });
});
}
function hasAnyAttribute(target, attrs) {
if (!target) return false;
for (var i = 0, attr; attr = attrs[i]; ++i) {
if (prefixer.hasAttribute(target, attr)) {
return true;
}
}
return false;
}
}
} | [
"function activateInteraction(){element.addClass('md-clickable');// close on backdrop click\n\tif(opts.backdrop)opts.backdrop.on('click',onBackdropClick);// Wire up keyboard listeners.\n\t// - Close on escape,\n\t// - focus next item on down arrow,\n\t// - focus prev item on up\n\topts.menuContentEl.on('keydown',onMenuKeyDown);opts.menuContentEl[0].addEventListener('click',captureClickListener,true);// kick off initial focus in the menu on the first element\n\tvar focusTarget=opts.menuContentEl[0].querySelector(prefixer.buildSelector(['md-menu-focus-target','md-autofocus']));if(!focusTarget){var firstChild=opts.menuContentEl[0].firstElementChild;focusTarget=firstChild&&(firstChild.querySelector('.md-button:not([disabled])')||firstChild.firstElementChild);}focusTarget&&focusTarget.focus();return function cleanupInteraction(){element.removeClass('md-clickable');if(opts.backdrop)opts.backdrop.off('click',onBackdropClick);opts.menuContentEl.off('keydown',onMenuKeyDown);opts.menuContentEl[0].removeEventListener('click',captureClickListener,true);};// ************************************\n\t// internal functions\n\t// ************************************\n\tfunction onMenuKeyDown(ev){var handled;switch(ev.keyCode){case $mdConstant.KEY_CODE.ESCAPE:opts.mdMenuCtrl.close(false,{closeAll:true});handled=true;break;case $mdConstant.KEY_CODE.UP_ARROW:if(!focusMenuItem(ev,opts.menuContentEl,opts,-1)&&!opts.nestLevel){opts.mdMenuCtrl.triggerContainerProxy(ev);}handled=true;break;case $mdConstant.KEY_CODE.DOWN_ARROW:if(!focusMenuItem(ev,opts.menuContentEl,opts,1)&&!opts.nestLevel){opts.mdMenuCtrl.triggerContainerProxy(ev);}handled=true;break;case $mdConstant.KEY_CODE.LEFT_ARROW:if(opts.nestLevel){opts.mdMenuCtrl.close();}else{opts.mdMenuCtrl.triggerContainerProxy(ev);}handled=true;break;case $mdConstant.KEY_CODE.RIGHT_ARROW:var parentMenu=$mdUtil.getClosest(ev.target,'MD-MENU');if(parentMenu&&parentMenu!=opts.parent[0]){ev.target.click();}else{opts.mdMenuCtrl.triggerContainerProxy(ev);}handled=true;break;}if(handled){ev.preventDefault();ev.stopImmediatePropagation();}}function onBackdropClick(e){e.preventDefault();e.stopPropagation();scope.$apply(function(){opts.mdMenuCtrl.close(true,{closeAll:true});});}// Close menu on menu item click, if said menu-item is not disabled\n\tfunction captureClickListener(e){var target=e.target;// Traverse up the event until we get to the menuContentEl to see if\n\t// there is an ng-click and that the ng-click is not disabled\n\tdo{if(target==opts.menuContentEl[0])return;if((hasAnyAttribute(target,['ng-click','ng-href','ui-sref'])||target.nodeName=='BUTTON'||target.nodeName=='MD-BUTTON')&&!hasAnyAttribute(target,['md-prevent-menu-close'])){var closestMenu=$mdUtil.getClosest(target,'MD-MENU');if(!target.hasAttribute('disabled')&&(!closestMenu||closestMenu==opts.parent[0])){close();}break;}}while(target=target.parentNode);function close(){scope.$apply(function(){opts.mdMenuCtrl.close(true,{closeAll:true});});}function hasAnyAttribute(target,attrs){if(!target)return false;for(var i=0,attr;attr=attrs[i];++i){if(prefixer.hasAttribute(target,attr)){return true;}}return false;}}}",
"function activateInteraction() {\n element.addClass('md-clickable');\n\n // close on backdrop click\n if (opts.backdrop) opts.backdrop.on('click', onBackdropClick);\n\n // Wire up keyboard listeners.\n // - Close on escape,\n // - focus next item on down arrow,\n // - focus prev item on up\n opts.menuContentEl.on('keydown', onMenuKeyDown);\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n // kick off initial focus in the menu on the first element\n var focusTarget = opts.menuContentEl[0].querySelector('[md-menu-focus-target]');\n if (!focusTarget) {\n var firstChild = opts.menuContentEl[0].firstElementChild;\n\n focusTarget = firstChild && (firstChild.querySelector('.md-button:not([disabled])') || firstChild.firstElementChild);\n }\n\n focusTarget && focusTarget.focus();\n\n return function cleanupInteraction() {\n element.removeClass('md-clickable');\n if (opts.backdrop) opts.backdrop.off('click', onBackdropClick);\n opts.menuContentEl.off('keydown', onMenuKeyDown);\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n\n // ************************************\n // internal functions\n // ************************************\n\n function onMenuKeyDown(ev) {\n var handled;\n switch (ev.keyCode) {\n case $mdConstant.KEY_CODE.ESCAPE:\n opts.mdMenuCtrl.close(false, {\n closeAll: true\n });\n handled = true;\n break;\n case $mdConstant.KEY_CODE.UP_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, -1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.DOWN_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, 1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.LEFT_ARROW:\n if (opts.nestLevel) {\n opts.mdMenuCtrl.close();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.RIGHT_ARROW:\n var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU');\n if (parentMenu && parentMenu != opts.parent[0]) {\n ev.target.click();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n }\n if (handled) {\n ev.preventDefault();\n ev.stopImmediatePropagation();\n }\n }\n\n function onBackdropClick(e) {\n e.preventDefault();\n e.stopPropagation();\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, {\n closeAll: true\n });\n });\n }\n\n // Close menu on menu item click, if said menu-item is not disabled\n function captureClickListener(e) {\n var target = e.target;\n // Traverse up the event until we get to the menuContentEl to see if\n // there is an ng-click and that the ng-click is not disabled\n do {\n if (target == opts.menuContentEl[0]) return;\n if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||\n target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {\n var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');\n if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {\n close();\n }\n break;\n }\n } while (target = target.parentNode)\n\n function close() {\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, {\n closeAll: true\n });\n });\n }\n\n function hasAnyAttribute(target, attrs) {\n if (!target) return false;\n for (var i = 0, attr; attr = attrs[i]; ++i) {\n var altForms = [attr, 'data-' + attr, 'x-' + attr];\n for (var j = 0, rawAttr; rawAttr = altForms[j]; ++j) {\n if (target.hasAttribute(rawAttr)) {\n return true;\n }\n }\n }\n return false;\n }\n }\n\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n return function cleanupInteraction() {\n element.removeClass('md-clickable');\n opts.menuContentEl.off('keydown');\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n }",
"function activateInteraction() {\n element.addClass('_md-clickable');\n\n // close on backdrop click\n if (opts.backdrop) opts.backdrop.on('click', onBackdropClick);\n\n // Wire up keyboard listeners.\n // - Close on escape,\n // - focus next item on down arrow,\n // - focus prev item on up\n opts.menuContentEl.on('keydown', onMenuKeyDown);\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n // kick off initial focus in the menu on the first element\n var focusTarget = opts.menuContentEl[0].querySelector('[md-menu-focus-target]');\n if ( !focusTarget ) {\n var firstChild = opts.menuContentEl[0].firstElementChild;\n\n focusTarget = firstChild && (firstChild.querySelector('.md-button:not([disabled])') || firstChild.firstElementChild);\n }\n\n focusTarget && focusTarget.focus();\n\n return function cleanupInteraction() {\n element.removeClass('_md-clickable');\n if (opts.backdrop) opts.backdrop.off('click', onBackdropClick);\n opts.menuContentEl.off('keydown', onMenuKeyDown);\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n\n // ************************************\n // internal functions\n // ************************************\n\n function onMenuKeyDown(ev) {\n var handled;\n switch (ev.keyCode) {\n case $mdConstant.KEY_CODE.ESCAPE:\n opts.mdMenuCtrl.close(false, { closeAll: true });\n handled = true;\n break;\n case $mdConstant.KEY_CODE.UP_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, -1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.DOWN_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, 1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.LEFT_ARROW:\n if (opts.nestLevel) {\n opts.mdMenuCtrl.close();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.RIGHT_ARROW:\n var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU');\n if (parentMenu && parentMenu != opts.parent[0]) {\n ev.target.click();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n }\n if (handled) {\n ev.preventDefault();\n ev.stopImmediatePropagation();\n }\n }\n\n function onBackdropClick(e) {\n e.preventDefault();\n e.stopPropagation();\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, { closeAll: true });\n });\n }\n\n // Close menu on menu item click, if said menu-item is not disabled\n function captureClickListener(e) {\n var target = e.target;\n // Traverse up the event until we get to the menuContentEl to see if\n // there is an ng-click and that the ng-click is not disabled\n do {\n if (target == opts.menuContentEl[0]) return;\n if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||\n target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {\n var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');\n if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {\n close();\n }\n break;\n }\n } while (target = target.parentNode)\n\n function close() {\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, { closeAll: true });\n });\n }\n\n function hasAnyAttribute(target, attrs) {\n if (!target) return false;\n for (var i = 0, attr; attr = attrs[i]; ++i) {\n var altForms = [attr, 'data-' + attr, 'x-' + attr];\n for (var j = 0, rawAttr; rawAttr = altForms[j]; ++j) {\n if (target.hasAttribute(rawAttr)) {\n return true;\n }\n }\n }\n return false;\n }\n }\n\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n return function cleanupInteraction() {\n element.removeClass('_md-clickable');\n opts.menuContentEl.off('keydown');\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n }",
"function activateInteraction() {\n element.addClass('md-clickable');\n\n // close on backdrop click\n if (opts.backdrop) opts.backdrop.on('click', onBackdropClick);\n\n // Wire up keyboard listeners.\n // - Close on escape,\n // - focus next item on down arrow,\n // - focus prev item on up\n opts.menuContentEl.on('keydown', onMenuKeyDown);\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n // kick off initial focus in the menu on the first element\n var focusTarget = opts.menuContentEl[0].querySelector('[md-menu-focus-target]');\n if ( !focusTarget ) {\n var firstChild = opts.menuContentEl[0].firstElementChild;\n\n focusTarget = firstChild && (firstChild.querySelector('.md-button:not([disabled])') || firstChild.firstElementChild);\n }\n\n focusTarget && focusTarget.focus();\n\n return function cleanupInteraction() {\n element.removeClass('md-clickable');\n if (opts.backdrop) opts.backdrop.off('click', onBackdropClick);\n opts.menuContentEl.off('keydown', onMenuKeyDown);\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n\n // ************************************\n // internal functions\n // ************************************\n\n function onMenuKeyDown(ev) {\n var handled;\n switch (ev.keyCode) {\n case $mdConstant.KEY_CODE.ESCAPE:\n opts.mdMenuCtrl.close(false, { closeAll: true });\n handled = true;\n break;\n case $mdConstant.KEY_CODE.UP_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, -1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.DOWN_ARROW:\n if (!focusMenuItem(ev, opts.menuContentEl, opts, 1) && !opts.nestLevel) {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.LEFT_ARROW:\n if (opts.nestLevel) {\n opts.mdMenuCtrl.close();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n case $mdConstant.KEY_CODE.RIGHT_ARROW:\n var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU');\n if (parentMenu && parentMenu != opts.parent[0]) {\n ev.target.click();\n } else {\n opts.mdMenuCtrl.triggerContainerProxy(ev);\n }\n handled = true;\n break;\n }\n if (handled) {\n ev.preventDefault();\n ev.stopImmediatePropagation();\n }\n }\n\n function onBackdropClick(e) {\n e.preventDefault();\n e.stopPropagation();\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, { closeAll: true });\n });\n }\n\n // Close menu on menu item click, if said menu-item is not disabled\n function captureClickListener(e) {\n var target = e.target;\n // Traverse up the event until we get to the menuContentEl to see if\n // there is an ng-click and that the ng-click is not disabled\n do {\n if (target == opts.menuContentEl[0]) return;\n if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||\n target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {\n var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');\n if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {\n close();\n }\n break;\n }\n } while (target = target.parentNode)\n\n function close() {\n scope.$apply(function() {\n opts.mdMenuCtrl.close(true, { closeAll: true });\n });\n }\n\n function hasAnyAttribute(target, attrs) {\n if (!target) return false;\n for (var i = 0, attr; attr = attrs[i]; ++i) {\n var altForms = [attr, 'data-' + attr, 'x-' + attr];\n for (var j = 0, rawAttr; rawAttr = altForms[j]; ++j) {\n if (target.hasAttribute(rawAttr)) {\n return true;\n }\n }\n }\n return false;\n }\n }\n\n opts.menuContentEl[0].addEventListener('click', captureClickListener, true);\n\n return function cleanupInteraction() {\n element.removeClass('md-clickable');\n opts.menuContentEl.off('keydown');\n opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);\n };\n }",
"activeMenuEvent() {\n if (this._initMenuEvent) {\n return;\n }\n\n this._addHelpActionEvent('undo');\n this._addHelpActionEvent('redo');\n this._addHelpActionEvent('reset');\n this._addHelpActionEvent('delete');\n this._addHelpActionEvent('deleteAll');\n\n this._addDownloadEvent();\n\n snippet.forEach(this.options.menu, menuName => {\n this._addMenuEvent(menuName);\n this._addSubMenuEvent(menuName);\n });\n this._initMenu();\n this._initMenuEvent = true;\n }",
"function IUIMenuActivateProcessor() {}",
"focus() {\n this.toggleMenuList();\n this.input.focus();\n }",
"pressButton() {\n if (this.enabled_) {\n this.buttonPressed_ = true;\n this.menu.show();\n this.menu.lockShowing();\n this.menuButton_.el_.setAttribute('aria-expanded', 'true');\n\n // set the focus into the submenu, except on iOS where it is resulting in\n // undesired scrolling behavior when the player is in an iframe\n if (IS_IOS && isInFrame()) {\n // Return early so that the menu isn't focused\n return;\n }\n this.menu.focus();\n }\n }",
"pressButton() {\n if (this.enabled_) {\n this.buttonPressed_ = true;\n this.menu.show();\n this.menu.lockShowing();\n this.menuButton_.el_.setAttribute('aria-expanded', 'true');\n\n // set the focus into the submenu, except on iOS where it is resulting in\n // undesired scrolling behavior when the player is in an iframe\n if (IS_IOS && Dom.isInFrame()) {\n // Return early so that the menu isn't focused\n return;\n }\n\n this.menu.focus();\n }\n }",
"performMenuAction() {\n this.absPause = true;\n this.requestAbsMenu = true;\n }",
"function activateMenu() {\n $('#menu-button').removeClass('inactive');\n $('#menu-button').css('color', '#fff');\n $('#bars').hide();\n $('#cross').show();\n }",
"handleKeyReleased() {\n changeCurrentScene(new MainMenu());\n }",
"bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![' ', 'ArrowUp', 'ArrowDown', 'ArrowRight'].includes(event.key)) {\n return;\n }\n\n // Prevent play / seek\n event.preventDefault();\n event.stopPropagation();\n\n // We're just here to prevent the keydown bubbling\n if (event.type === 'keydown') {\n return;\n }\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]');\n\n // Show the respective menu\n if (!isRadioButton && [' ', 'ArrowRight'].includes(event.key)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n if (event.key !== ' ') {\n if (event.key === 'ArrowDown' || isRadioButton && event.key === 'ArrowRight') {\n target = menuItem.nextElementSibling;\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n setFocus.call(this, target, true);\n }\n }\n }, false);\n\n // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n on.call(this, menuItem, 'keyup', event => {\n if (event.key !== 'Return') return;\n controls.focusFirstMenuItem.call(this, null, true);\n });\n }",
"function openMenu() {\n gameState.menuPause = true;\n screenMan.push(gameMenu);\n screenMan.push(subSettings);\n soundMan.click.play();\n }",
"@api\n focus() {\n this.template.querySelector('a').focus();\n /**\n * The event fired when you focus the menu item.\n *\n * @event\n * @name focus\n * @public\n */\n this.dispatchEvent(new CustomEvent('focus'));\n }",
"function set_main_menu_controls() {\n document.onkeydown = function(event) {\n switch( event.key ) {\n case 'ArrowUp':\n case 'w':\n main_menu_move_cursor_up();\n break;\n case 'ArrowDown':\n case 's':\n main_menu_move_cursor_down();\n break;\n case 'Enter':\n main_menu_apply();\n break;\n }\n };\n}",
"bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n } // Prevent play / seek\n\n\n event.preventDefault();\n event.stopPropagation(); // We're just here to prevent the keydown bubbling\n\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]'); // Show the respective menu\n\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || isRadioButton && event.which === 39) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n }, false); // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n\n on.call(this, menuItem, 'keyup', event => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n }",
"function onActionActivate() {\n sendCommandActivate();\n}",
"_activate(trap) {\n // activate trap\n trap.isActive = true;\n // save trigger element - for later restoring it\n trap.triggerElement = document.activeElement;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trigger cancellation of the upgrade process and go back to landing page | function cancelUpgrade() {
vm.running = true;
upgradeFactory.cancelUpgrade().then(
function(/* response */) {
vm.running = false;
$uibModalInstance.dismiss();
// reset steps state
upgradeStepsFactory.reset();
// clear last page seen by the user
localStorage.removeItem(UPGRADE_LAST_STATE_KEY);
// go to dashboard
$window.location.href = '/';
},
function(/* errorResponse */) {
vm.running = false;
}
);
} | [
"async onAbortOtherMigration() {\n State.commit('swagMigration/ui/setIsLoading', true);\n State.commit('swagMigration/process/setIsMigrating', true);\n\n await this.migrationWorkerService.isMigrationRunningInOtherTab().then((isRunning) => {\n if (isRunning) {\n State.commit('swagMigration/ui/setIsLoading', false);\n this.isTakeoverForbidden = true;\n this.onInvalidMigrationAccessToken();\n }\n });\n\n if (this.isTakeoverForbidden) {\n return;\n }\n\n await this.migrationWorkerService.checkForRunningMigration().then((runState) => {\n if (runState.isMigrationRunning === false) {\n State.commit('swagMigration/process/setIsMigrating', false);\n State.commit('swagMigration/ui/setIsLoading', false);\n this.isOtherMigrationRunning = false;\n this.$router.push({ name: 'swag.migration.index.main' });\n return;\n }\n\n this.migrationService.abortMigration(runState.runUuid).then(() => {\n State.commit('swagMigration/process/setIsMigrating', false);\n State.commit('swagMigration/ui/setIsLoading', false);\n this.isOtherMigrationRunning = false;\n this.$router.push({ name: 'swag.migration.index.main' });\n });\n });\n }",
"cancel() {\n this.transitionToRoute('landing');\n }",
"onStop() {\n return this.migrationService.abortMigration(this.runId).then(() => {\n this.showAbortMigrationConfirmDialog = false;\n this.isMigrationInterrupted = false;\n State.commit('swagMigration/process/setIsMigrating', false);\n State.commit('swagMigration/ui/setIsPaused', false);\n State.commit('swagMigration/ui/setIsLoading', false);\n this.$nextTick(() => {\n this.$router.push({ name: 'swag.migration.index.main' });\n });\n });\n }",
"abortPageNavigate() {\n\n this.confirm_navigation_level = 2;\n\n history.back();\n\n setTimeout(function() {\n this.confirm_navigation_level = 1;\n }, 300);\n }",
"function onCloseWizard() {\n stopActivation();\n\n ExtenderSetupService.reset();\n\n setTimeout(function() {\n FobService2.extenderSetupCancel();\n }, 1000);\n }",
"function adminCancel() {\r\n window.location.replace(\"admin_master.html\");\r\n}",
"cancel() {\n this._cancelWizard.next();\n }",
"onConfiscatedMigration() {\n this.onInvalidMigrationAccessToken();\n this.isMigrationInterrupted = true;\n this.$nextTick(() => {\n this.$refs.loadingScreenTakeover.refreshState();\n });\n }",
"function cancel() {\n parentPort.postMessage('Email analytics fetch-latest job cancelled before completion');\n\n if (parentPort) {\n parentPort.postMessage('cancelled');\n } else {\n setTimeout(() => {\n process.exit(0);\n }, 1000);\n }\n}",
"function continueClose() {\n Alloy.eventDispatcher.trigger('session:renew');\n $.trigger('dashboard:dismiss', {});\n}",
"function ts_deactivate(){\n if(confirm('Do you really want to deactivate all outstanding timestamps?'))\n window.location.replace('services/tsutils.php?action=deactivate');\n}",
"handlePaymentDecline(){\n const redirectLinkToEShop=getRedirectLinkToEShop();\n if (window.confirm('Are you sure to decline the payment?')) {\n window.location.replace(redirectLinkToEShop+\"?canceled\");//redirect the user back to the E-shop\n }\n\n}",
"checkAndCancel() {\n const currentPage = this.currentPage;\n const currentPageHasOverrides = currentPage.stopCancel || currentPage.preventDefault;\n if (this.stopNavigation) {\n return;\n }\n currentPage.pageOnCancel.emit();\n if (!currentPageHasOverrides) {\n this.onCancel.emit();\n }\n if (!this.stopCancel && !currentPageHasOverrides) {\n this.close();\n }\n }",
"function stopCharging() {\n props.stoppedCharging();\n props.history.push(props.chargeComplete)\n }",
"function reset(){\n\t\tnext_upgrade = 0\n\t}",
"async function activationUiCleanup (browser) {\n try {\n // after useBraveEndpoint we can start polling for gateway to become online\n const { customGatewayUrl: braveGwUrl } = await browser.storage.local.get('customGatewayUrl')\n // wait 1m for gateway to be online (bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss)\n await waitFor(async () => {\n try {\n return await fetch(`${braveGwUrl}/ipfs/bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss`).then(response => response.ok)\n } catch (_) {\n return false\n }\n })\n log('[activation ui cleanup] Brave gateway is up, cleaning up')\n\n const welcomePageUrl = browser.runtime.getURL(welcomePage)\n const optionsPageUrl = browser.runtime.getURL(optionsPage)\n // we are unable to query ipfs:// directly due to reasons mentioned in 'closeIpfsTab'\n // so we make quick pass over all tabs and check welcome and options while at it.\n for (const tab of await browser.tabs.query({})) {\n try {\n // close tab with temporary trigger\n if (tab.url === braveIpfsUriTrigger || tab.url === braveGatewayUrlTrigger) {\n await browser.tabs.remove(tab.id)\n }\n // switch to welcome page if present (onboarding via fresh install)\n if (tab.url === welcomePageUrl) {\n await browser.tabs.reload(tab.id)\n await browser.tabs.update(tab.id, { active: true })\n }\n // switch to options page if present (onboarding via Preferences)\n if (tab.url === optionsPageUrl) {\n await browser.tabs.update(tab.id, { active: true })\n }\n } catch (e) {\n log.error('[activation ui cleanup] unexpected error, but safe to ignore', e)\n continue\n }\n }\n log('[activation ui cleanup] done')\n\n // (if ok or not, close temporary tab and switch to welcome page or open it if not existing\n // if ((await browser.tabs.get(tabId)).url.startsWith(braveIpfsUriTrigger)) {\n } catch (e) {\n // most likely tab is gone (closed by user, etc)\n log.error('[activation ui cleanup] failed to cleanup ephemeral UI tab', e)\n }\n}",
"function pageReloadHandler() {\n // Checks if voice is speaking\n if (synth.speaking) {\n // Cancel current voice\n synth.cancel();\n }\n}",
"function cancelUpdate(){\n window.location.replace(\"http://localhost:8080/static/favorites.html\");\n}",
"function backToStart(event) {\n sessionStorage.setItem(\"wasFinished\", \"finished\");\n location.reload();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets and sets the innerRef property value. | get innerRef() {
return this.#innerRef
} | [
"get ref() { return this._ref; }",
"getElementRef() {\n return this.elementRef;\n }",
"getReference() {\n return this.nodeReference;\n }",
"get localReference() {\n return this.localRef;\n }",
"get rootRef() {\n return this._db.ref();\n }",
"assignNestedValue(ref, value) {\n let props = ref.split('.');\n let prop = props.pop();\n if (props && props.length) {\n ref = getNestedProperty(this.model, props.join('.'));\n }\n this.$set(props.length >= 1 ? ref : this.model, prop, value);\n }",
"get refs() { return this.component ? this.component.refs : {} }",
"get ref(): ?DocumentReference {\n\t\treturn this._ref.get();\n\t}",
"setWrapperRef (node) {\n this.wrapperRef = node\n }",
"setWrapperRef(node) {\n this.wrapperRef = node;\n }",
"setWrapperRef(node) {\n this.wrapperRef = node;\n }",
"setWrapperRef( node ) {\n\t\tthis.wrapperRef = node;\n\t}",
"_getRef() {\n const { forwardedRef } = this.props;\n\n return forwardedRef || this._backupRef;\n }",
"set ref(ref: DocumentReference) {\n\t\tif (this._ref.get() === ref) return;\n\t\ttransaction(() => {\n\t\t\tthis._ref.set(ref);\n\t\t\tthis._updateRealtimeUpdates(true);\n\t\t});\n\t}",
"get referralValue() {\r\n return this.message.ref;\r\n }",
"getReferenceStyle() {\n\t return this.referenceStyle;\n\t }",
"function createRef() {\r\n var refObject = (function (element) {\r\n refObject.current = element;\r\n });\r\n // This getter is here to support the deprecated value prop on the refObject.\r\n Object.defineProperty(refObject, 'value', {\r\n get: function () {\r\n return refObject.current;\r\n }\r\n });\r\n refObject.current = null;\r\n return refObject;\r\n}",
"get referenceFrame() {\n return this._referenceFrame;\n }",
"get overlayRef() {\n return this._overlayRef;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add a line to the legend (color + label) | _renderLegendLine(color, label) {
let legendSvg;
switch (this.layerType) {
case 'fill':
legendSvg = svg`<svg width="30" height="15">
<rect width="30" height="15" style="fill:${color};fill-opacity:1;stroke-width:1;stroke:#444"></rect>
</svg>`
break;
case 'line':
legendSvg = svg`<svg width="30" height="15">
<line x1="0" y1="15" x2="30" y2="0" style="stroke:${color};stroke-width:${color.width};" />
</svg>`
break;
case 'circle':
legendSvg = svg`<svg width="12" height="12">
<circle cx="6" cy="6" r="5" style="fill:${color};fill-opacity:1 stroke-width:1;stroke:white" />
</svg>`
}
return html`<div><span>${legendSvg}<span><span>${label}</span></div>`
} | [
"lineRender(){\n d3.select('.circle-legend').select('svg').append('line').attr('x1',0).attr('x2',180).attr('y1',0).attr('y2',0)\n .attr('transform','translate(0,55)').classed('legendLine',true)\n }",
"function addLegend() {\n let x = 513;\n let y = 40;\n let legendcircle = midpoint\n .selectAll(\"circle.circlelegend\")\n .data(attributedColor)\n .enter()\n .append(\"circle\")\n .attr(\"class\", \"circlelegend\")\n .attr(\"r\", 5)\n .attr(\"cx\", x)\n .attr(\"cy\", (d, i) => i * y)\n .attr(\"fill\", d => d);\n let legendtexts = midpoint\n .selectAll(\"text.textlegend\")\n .data(classNames)\n .enter()\n .append(\"text\")\n .attr(\"class\", \"textlegend\")\n .attr(\"x\", x + 10)\n .attr(\"y\", (d, i) => i * y + 5)\n .text(d => d)\n .attr(\"font-size\", \"14pt\");\n }",
"function addcolorlegend(cy){\n cy.$('node[id = \"l1\"]')\n .style('color', 'black')\n .style('background-height',50)\n .style('background-width',200)\n .style('background-position-y','100%')\n .style('shape','rectangle')\n .style('width',200)\n .style('height',50)\n .style('border-width',1)\n .style('text-valign' , 'bottom')\n .style('text-max-width', 200)\n}",
"addLegend() {\n\t\tthis.chart.addLegend();\n\t}",
"function drawLegend(linegraph, color, margin, width) {\n\n // determine legend offset\n var legendOffset = margin.right / 8;\n\n // initiate legend\n var legend = linegraph.selectAll(\"g.legendcolor\")\n .data(color.domain())\n .enter().append(\"g\")\n .attr(\"class\", \"legendcolor\")\n .attr(\"transform\", function(d, i) {\n var y = i * legendOffset + legendOffset;\n return \"translate(20,\" + y + \")\";\n });\n\n // add colored cicles\n legend.append(\"circle\")\n .attr(\"r\", legendOffset / 2)\n .attr(\"cx\", width + margin.right - (legendOffset * 2))\n .attr(\"cy\", 9)\n .style(\"fill\", color)\n .style(\"stroke\", \"#000000\")\n\n // add labels to colored circles\n legend.append(\"text\")\n .attr(\"x\", width + margin.right - (legendOffset * 3))\n .attr(\"y\", legendOffset / 2)\n .attr(\"dy\", \".35em\")\n .style(\"text-anchor\", \"end\")\n .text(function(d) { return d; });\n}",
"function addLine(line, color) {\n return chartGroup.append(\"path\")\n .data([data])\n .attr(\"d\", line)\n .classed(color, true);\n }",
"function draw_common_chart_legend(svg, items, line_x_start, line_y, line_width) {\n var chart_legend_g = svg.append('g')\n .attr('class', 'series')\n var text_bbox;\n for (var i = 0; i < items.length; i++) {\n if(text_bbox) { line_x_start = text_bbox.x + text_bbox.width + 18; }\n chart_legend_g.append('line')\n .attr('class', 'series ' + items[i].replace(' ', ''))\n .attr('x1', line_x_start)\n .attr('y1', line_y)\n .attr('x2', line_x_start + line_width)\n .attr('y2', line_y);\n var text = chart_legend_g.append('text')\n .attr('x', line_x_start + line_width + 6)\n .attr('y', line_y + 5)\n .text(Main_Areas[i]);\n text_bbox = text.node().getBBox();\n }\n}",
"function addLegends(input) {\n\t\n\t var rectColor = input.color;\n\t var text = input.text;\n\t var xAxis = input.xAxis;\n\t var yAxis = input.yAxis;\n\t \n\t var group = svg.append(\"g\")\n\t\t\t\t\t\t\t.attr(\"transform\", \"translate(\" + xAxis + \",\" + yAxis + \")\")\n\n\t\t//Draws icon\n\t\tgroup.append(\"rect\")\n\t\t\t\t.attr(\"fill\", rectColor)\n\t\t\t\t.attr(\"height\", 18)\n\t\t\t\t.attr(\"width\", 18)\n\n\t\t\t//Adds text next to icon\n\t\tgroup.append(\"text\")\n\t\t\t\t.attr(\"class\", \"legend-text\")\n\t\t\t\t.attr(\"dx\", \"1.4em\")\n\t\t\t\t.attr(\"dy\", \"0.74em\")\n\t\t\t\t.text(text)\n\t}",
"function addLine(layer, lineColor = 'black') {\n\tmouse.status = mouseStatus.other;\n\tsetAllBtnColor();\n\tlet line = new fabric.Line(\n\t\t[480, 315, 580, 315],\n\t\t{\n\t\t\tstroke: lineColor,\n\t\t\tstrokeWidth: 2,\n\t\t});\n\tlayer.add(line);\n\tline.name = 'shape';\n}",
"function legend(svg, sources, color) {\n var size = 20;\n let legend_entry = svg.append(\"g\")\n .attr(\"transform\", \"translate(60, 10)\")\n .selectAll(\".legend-dots\")\n .data(sources)\n .enter()\n .append(\"g\")\n .attr(\"transform\", (d, i) => \"translate(\" + 10 + \",\" + i*(size+5) + \")\");\n legend_entry.append(\"rect\")\n .classed(\".legend-dots\", true)\n .attr(\"x\", 0)\n .attr(\"y\", -size / 2)\n .attr(\"width\", size)\n .attr(\"height\", size)\n .style(\"fill\", d => color(d.name))\n .attr(\"stroke\", \"black\")\n .on(\"click\", (d, i, g) => displayLine(g[i], color(d.name), d.name));\n legend_entry.append(\"text\")\n .attr(\"x\", size + 2) // 2 pixels pour le padding\n .attr(\"y\", 0)\n .attr(\"dominant-baseline\", \"middle\")\n .text(d => d.name);\n}",
"function addLegend(min,max) {\n var canvas = document.getElementById('legend');\n var ctx = canvas.getContext('2d');\n var x0 = 0;\n var y0 = 20;\n var x1 = 20;\n var y1 = canvas.height - (y0*2);\n var grd = ctx.createLinearGradient(x0,y0,x1,y1);\n grd.addColorStop(0,\"#FF0000\");\n grd.addColorStop(1,\"#FFFFFF\");\n ctx.fillStyle=grd;\n ctx.fillRect(canvas.width-100,y0,x1,y1);\n ctx.rect(canvas.width-100,y0,x1,y1);\n ctx.lineWidth = 2;\n ctx.stroke();\n // add labels\n ctx.font = \"15px Courier New, sans-serif\";\n ctx.fillStyle = 'black';\n var amount = 20;\n var root_min = Math.sqrt(min);\n var root_max = Math.sqrt(max);\n var range = root_max - root_min;\n for (var i = 0; i <= amount; i++) {\n var intensity = 1 - i*(1.0/amount)\n var pop_density = Math.ceil(Math.pow((intensity * range) + root_min,2))\n var y_pos = (i*y1/amount*1.0) + y0\n ctx.fillText(pop_density, canvas.width-60, y_pos);\n ctx.beginPath();\n\t\tctx.moveTo(canvas.width-100,y_pos);\n\t\tctx.lineTo(canvas.width-100 + x1, y_pos);\n\t\tctx.stroke();\n }\n}",
"function setupLegend() {\n ctx.font = '14px Helvetica';\n ctx.textAlign = 'left';\n\n // Suicide label\n ctx.fillStyle = blueColor;\n ctx.fillRect(476, 108, 24, 24);\n ctx.fillText('Suicide', 512, 126);\n\n // Unintentional label\n ctx.fillStyle = yellowColor;\n ctx.fillRect(476, 152, 24, 24);\n ctx.fillText('Unintentional Death', 512, 170);\n\n // Other\n ctx.strokeStyle = '#000000';\n ctx.strokeRect(476, 196, 24, 24);\n ctx.strokeRect(477, 197, 22, 22);\n ctx.fillStyle = '#000000';\n ctx.fillText('Other', 512, 214);\n }",
"function addLegend() {\n document.querySelector(\".legend\").innerHTML = [\n \"<div>Magnitude</div>\",\n \"<ul><li class=\\\"zero\\\"></li>\",\n \"<li class=\\\"one\\\"></li>\",\n \"<li class=\\\"two\\\"></li>\",\n \"<li class=\\\"three\\\"></li>\",\n \"<li class=\\\"four\\\"></li>\",\n \"<li class=\\\"five\\\"></li></ul>\",\n \"<hr><div class=\\\"flines\\\"> Fault lines</div>\"\n ].join(\"\");\n}",
"function legendLayer() {\n let legend = L.control({position: 'bottomright'});\n\n legend.onAdd = function(map) {\n\n var div = L.DomUtil.create('div', 'info legend');\n var mags = [0, 1, 2, 3, 4, 5];\n\n // loop through our density intervals and generate a label with a colored square for each interval\n for (var i = 0; i < mags.length; i++) {\n div.innerHTML +=\n '<i style=\"background:' + getColor(mags[i]) + '\"></i> ' +\n mags[i] + (mags[i + 1] ? '–' + mags[i + 1] + '<br>' : '+');\n }\n\n return div;\n };\n return legend;\n}",
"_applyLegend(value, old) {\n var control = this.getChildControl(\"legend\");\n\n if (value !== null) {\n control.setLabel(value);\n control.show();\n } else {\n control.exclude();\n }\n }",
"function addPlotLine(e) {\n\t\tstatsData.chart.xAxis[0].addPlotLine({\n\t\t\twidth: 1,\n\t\t\t/*jshint validthis:true */\n\t\t\tcolor: this.styling.color,\n\t\t\tdashStyle: 'dash',\n\t\t\tvalue: e.date.valueOf(),\n\t\t\tlabel: {\n\t\t\t\ttext: e.title,\n\t\t\t\tstyle: {\n\t\t\t\t\tcolor: '#FFFFFF'\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function graph_line_generate(category,text,data,dom,title,subtitle,color)\n{\n $('#' + dom).highcharts({\n title: {\n text: title\n },\n subtitle: {\n text: subtitle\n },\n xAxis: {\n categories: category,\n crosshair: true\n },\n yAxis: {\n min: 0,\n title: {\n text: text\n }\n },\n legend: {\n layout: 'vertical',\n align: 'right',\n verticalAlign: 'middle',\n borderWidth: 0\n },\n colors: color,\n series: [data]\n });\n}",
"function legend(svg, sources, color) {\n // TODO: Create the legend that supplements the graphic.\n var node = svg.node()\n var width = node.getAttribute(\"width\")\n var height = node.getAttribute(\"height\")\n\n var legend = svg.append(\"g\")\n .selectAll(\"g\")\n .data(sources)\n .enter()\n .append('g')\n .attr('class', 'legend')\n .attr('transform', function(d, i) {\n var heightCase = height / (sources.length*2)\n var x = width / 18;\n var y = 30 + i * heightCase;\n return 'translate(' + x + ',' + y + ')'\n })\n .on(\"click\", function(d) {\n displayLine(this, color)\n })\n\n legend.append(\"rect\")\n .attr('width', 0.01*width)\n .attr('height', 0.025*height)\n .style('stroke', \"black\")\n .style('fill', function(d) {\n return d.name === \"Moyenne\" ? \"#000000\" : color(d.name)\n })\n legend.append('text')\n .attr('x', 20)\n .attr('y', 10)\n .text(function(d) { return d.name })\n}",
"function legend(types){\n\n //color guide\n colors[c].setAlpha(20);\n fill(colors[c]);\n colors[c].setAlpha(255);\n stroke(colors[c]);\n ellipse(width-40, h,20,20);\n\n //text\n fill('black');\n noStroke();\n text(types, width-60,h+5);\n c++;\n h+=25;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit Custom Complexity Values | function editComplexity() {
setUpdateComplexityList(list);
findSummation(list);
setOpen(false);
} | [
"function editComplexity() {\n const apiId = api.id;\n const apiClient = new Api();\n const promisedComplexity = apiClient.updateGraphqlPoliciesComplexity(\n apiId, {\n list: editlist,\n },\n );\n updateAPI({ complexity });\n setComplexityAddDisabled(true);\n findSummation(state);\n promisedComplexity\n .then(() => {\n Alert.info(intl.formatMessage({\n id: 'Apis.Details.Configurartion.components.QueryAnalysis.complexity.added.successfully',\n defaultMessage: 'Complexity Values Updated successfully',\n }));\n })\n .catch((error) => {\n const { response } = error;\n if (response.body) {\n const { description } = response.body;\n Alert.error(description);\n }\n })\n .finally(() => {\n setComplexityAddDisabled(false);\n });\n }",
"combine(complexity) {\n const newComplexity = new Complexity({});\n if (this.value && complexity.value) {\n newComplexity.value = this.value + complexity.value + 1;\n newComplexity.value -= this.overlappingToolValue(complexity.tools);\n }\n newComplexity.calculated = this.calculated && complexity.calculated;\n newComplexity.addTools(this.tools);\n newComplexity.addTools(complexity.tools);\n return newComplexity;\n }",
"function setInitialComplexity() {\n const apiId = api.id;\n const apiClient = new Api();\n const promisedComplexityType = apiClient.getGraphqlPoliciesComplexityTypes(apiId);\n promisedComplexityType\n .then((res) => {\n const array = [];\n res.typeList.map((respond) => {\n respond.fieldList.map((ob) => {\n const obj = {};\n obj.type = respond.type;\n obj.field = ob;\n obj.complexityValue = 1;\n array.push(obj);\n return ob;\n });\n return array;\n });\n setList(array);\n findSummation(array);\n });\n }",
"Mutate (rate) {\n // TODO Fill in the mutation functions\n\n // Jiggle constant values\n // Replace some constant values\n //\n }",
"HardAlgorithm(){\n this.resilience += 3;\n console.log(this.name + \"'s\" + \" resilience is now \" + this.resilience);\n }",
"function changeBy(val){\r\n \r\n counterValue=counterValue+val;\r\n }",
"function recompute_numbers(new_value, code){\r\n if (code){\r\n sum += parseFloat(new_value);\r\n }\r\n else{\r\n sum = sum - parseFloat(new_value);\r\n }\r\n\r\n $('#budget_sum').text(accounting.formatMoney(sum));\r\n $('.b_item_percentage').each(function(){\r\n new_percentage = (100 * b_map[$(this).attr('id')] / sum).toFixed(2);\r\n $(this).text(String(new_percentage) + '%');\r\n });\r\n }",
"objectiveLargeAmount(){\n const LARGE_AMOUNT_MULTIPLIER =3;\n const globalManager=this.resourceManager.globalResourceManager;\n const highCost = globalManager.highestCost();\n\n const calcLargeAmount = (highCost,res) => {\n return (Math.floor(highCost / res.intrinsicVal) * LARGE_AMOUNT_MULTIPLIER);\n };\n\n const largeAmountVector = new AmountResourceManager();\n globalManager.resources.forEach(res=>{\n largeAmountVector.assignResourceAmount(res.name, calcLargeAmount(highCost,res));\n });\n\n const amountsWanted = this.calcAmountsWanted();\n\n const totalNeeded = amountsWanted.plus(largeAmountVector);\n const surplus = this.resourceManager.minus(totalNeeded);\n const largeSurplus = surplus.nonZeroRes();\n return largeSurplus;\n }",
"setObjectComplexity(object, complexity) {\n if (!object.complexity.calculated || complexity.compare(object.complexity) < 0) {\n object.complexity = complexity;\n for (var transition of object.transitionsAway) {\n this.calculateTransition(transition);\n }\n }\n }",
"function updateCachedValues() {\n\t\t\n\t\tvar flowSum = 0,\n\t\t flowCounter = 0,\n\t\t nodeSum = 0,\n\t\t\tnodeCounter = 0,\n\t\t\ti, j, v, flow, l,\n\t\t \n\t\t // values getting updated\n\t\t\tminFlowLength = Infinity,\n\t\t\tmaxFlowLength = 0,\n\t\t\tminFlowValue,\n\t\t\tmaxFlowValue,\n\t\t\tmeanFlowValue,\n\t\t\tminNodeValue,\n\t\t\tmaxNodeValue,\n\t\t\tmeanNodeValue;\n\t\t\n\t\tif (flows.length < 1) {\n\t\t\tminFlowValue = 0;\n\t\t\tmaxFlowValue = 0;\n\t\t} else {\n\t\t\tminFlowValue = maxFlowValue = flows[0].getValue();\n\t\t}\n\n\t\tfor(i = 0, j = flows.length; i < j; i += 1) {\n\t\t\tflow = flows[i];\n\t\t\tv = flow.getValue();\n\t\t\tif (v < minFlowValue) {\n\t\t\t minFlowValue = v;\n\t\t\t}\n if (v > maxFlowValue) {\n maxFlowValue = v;\n }\n flowSum += v;\n flowCounter += 1;\n l = flow.getBaselineLength();\n if (l > maxFlowLength) {\n maxFlowLength = l;\n }\n if (l < minFlowLength) {\n minFlowLength = l;\n }\n\t\t}\n\t\t\n\t\tmeanFlowValue = flowSum / flowCounter;\n\t\t\n\t\t\n\t\tif(nodes.length < 1) {\n\t\t\tminNodeValue = 0;\n\t\t maxNodeValue = 0;\n\t\t}\n\n\t\tif(nodes.length > 0) {\n\t\t\tminNodeValue = maxNodeValue = nodes[0].value;\n\t\t} else {\n\t\t\tminNodeValue = maxNodeValue = 0;\n\t\t}\n\t\t\n\n\t\tfor (i = 0, j = nodes.length; i < j; i += 1) {\n\t\t\t\n\t\t\tv = nodes[i].value;\n\t\t\t\n\t\t\tif(!v) {\n\t\t\t\tnodes[i].value = 1;\n\t\t\t\tv = nodes[i].value;\n\t\t\t}\n\t\t\t\n\t\t\tif (v < minNodeValue) {\n minNodeValue = v;\n }\n if (v > maxNodeValue) {\n maxNodeValue = v;\n }\n nodeSum += v;\n nodeCounter += 1;\n\t\t}\n\t\tmeanNodeValue = nodeSum / nodeCounter;\n\t\t//minFlowWidth = (settings.maxFlowWidth * settings.minFlowValue / maxFlowValue);\n\t\t\n\t\tsettings.minFlowLength = minFlowLength;\n\t\tsettings.maxFlowLength = maxFlowLength;\n\t\tsettings.minFlowValue = minFlowValue;\n\t\tsettings.maxFlowValue = maxFlowValue;\n\t\tsettings.meanFlowValue = meanFlowValue;\n\t\tsettings.minNodeValue = minNodeValue;\n\t\tsettings.maxNodeValue = maxNodeValue;\n\t\tsettings.meanNodeValue = meanNodeValue;\n\t\tsettings.allFlowsTotalValue = flowSum;\n }",
"cancluteSummarizeCost(source){\n let result = 0\n _.forEach(source, (v, idx) =>{\n result += fixMath.fixedPoint(v, 5)\n })\n return result\n }",
"_updateScore()\n\t{\n\t\tthis._score = this._base;\n\t\tthis._score += this.perms.score;\n\t\tthis._temps = this._temps.filter((mod) => {return !mod.delete;});\n\t\tthis._score += this.temps.score;\n\t\tthis._score = Math.min(this._score, 30);\n\t\tthis._modifier = calculateModifier(this.score);\n\t}",
"setObjectComplexity(object, complexity) {\n if (!object.complexity.hasValue() || complexity.compare(object.complexity) < 0) {\n object.complexity = complexity;\n\n // Favor transitions where the actor or target remains\n // Otherwise we get broken tools as the easiest transition\n const transitions = object.transitionsAway.sort((a, b) => (a.tool || a.targetRemains) ? -1 : 1);\n for (var transition of object.transitionsAway) {\n this.calculateTransition(transition);\n }\n }\n }",
"_calculateModifierValues () {\n if (this._cache.composedValue !== null) {\n return;\n }\n\n const availableModifier = Object.keys(this._modifier),\n cachedModifier = Object.keys(this._cache.modifierValue);\n\n availableModifier.filter(modifier => !cachedModifier.includes(modifier)).forEach(modifierKey => {\n this._cache.modifierValue[modifierKey] = this._modifier[modifierKey]();\n });\n }",
"randomlyChangeStatFromStatSummation(object, change) {\n var randomStat = Calculator.calculateRandom(1, 9);\n change /= 100;\n switch(randomStat) {\n case 1:\n object.strength *= change;\n break;\n case 2:\n object.wisdom *= change;\n break;\n case 3:\n object.defense *= change;\n break;\n case 4:\n object.resilience *= change;\n break;\n case 5:\n object.dexterity *= change;\n break;\n case 6:\n object.evasion *= change;\n break;\n case 7:\n object.luck *= change;\n break;\n case 8:\n object.speed *= change;\n break;\n case 9:\n object.maxHealth *= change;\n break;\n }\n }",
"calcMvalues() {\n var _this = this;\n var data = this.data;\n\n if (_this.debug || _this.debugCalc === 1) console.log(\"CALC M VALUES >>>>>>>>>>>>>>>>>>>\");\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug || _this.debugCalc === 1) console.log(\"\\nCALC M - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n // Loop through each RISK of CATEGORY - run calculations and update data model\n $.each(category.risks, function(index, risk) {\n if (_this.debug || _this.debugCalc === 1) console.log(\"\\nRISK >>>: \" + risk.name);\n // CALCULATE MNI for each RISK ////////////////////////////////////\n // Average for factors Coefficient of Project Features, Controllability + Dependency\n risk.probability = (_this.fromPercent(risk.coefficient) + _this.fromPercent(risk.controllability) + _this.fromPercent(risk.dependency)) / 3;\n // CALCULATE individual distributed ASSESSMENTS for each RISK ////////////////////////////////////\n var WeightedZero = (1 - _this.fromPercent(risk.occurrence) * risk.probability);\n risk.WeightedCost[0] = WeightedZero;\n risk.WeightedDuration[0] = WeightedZero;\n risk.WeightedQuality[0] = WeightedZero;\n // Zero Mni value - same for each GRADE in RISK - assign to element 0 of each weighted array\n var MniZero = (1 - _this.fromPercent(risk.occurrence) * risk.probability) * _this.fromPercent(risk.weight);\n risk.MniCost[0] = MniZero;\n risk.MniDuration[0] = MniZero;\n risk.MniQuality[0] = MniZero;\n // Loop over 3 project grade (1%, 2% + 3%) and add to arrays in alements 1-3 (element 0 is o% value)\n for (var i = 1; i < 4; i++) {\n // CALCULATE WEIGHTED RISK (sub calc for later)\n risk.WeightedCost[i] = _this.fromPercent(risk.occurrence) * risk.probability * _this.fromPercent(risk.costImpact[i - 1]);\n risk.WeightedDuration[i] = _this.fromPercent(risk.occurrence) * risk.probability * _this.fromPercent(risk.durationImpact[i - 1]);\n risk.WeightedQuality[i] = _this.fromPercent(risk.occurrence) * risk.probability * _this.fromPercent(risk.qualityImpact[i - 1])\n\n // CALCULATE MNI values\n risk.MniCost[i] = risk.WeightedCost[i] * _this.fromPercent(risk.weight);\n risk.MniDuration[i] = risk.WeightedDuration[i] * _this.fromPercent(risk.weight);\n risk.MniQuality[i] = risk.WeightedQuality[i] * _this.fromPercent(risk.weight);\n\n }\n if (_this.debug || _this.debugCalc === 1) console.log(\"Weighted Values: \" + risk.WeightedCost + \": \" + risk.WeightedDuration + \": \" + risk.WeightedQuality);\n if (_this.debug || _this.debugCalc === 1) console.log(\"Mni Values: \" + risk.MniCost + \": \" + risk.MniDuration + \": \" + risk.MniQuality);\n\n // CALCULATE M for each GRADE in RISK ////////////////////////////////////\n // 1-(sum of MNI_results) (MniZero + MniCost + MniDuration + MniQuality);\n risk.M[0] = 1 - ((risk.MniCost.reduce(_this.getSum)));\n risk.M[1] = 1 - ((risk.MniDuration.reduce(_this.getSum)));\n risk.M[2] = 1 - ((risk.MniQuality.reduce(_this.getSum)));\n if (_this.debug || _this.debugCalc === 1) console.log(\"M values: \" + risk.M);\n\n // CALCULATE Ml for each RISK (same for each grade) ////////////////////////////////////\n // 1-(RISK WEIGHT (convert from percentage));\n risk.Ml = 1 - _this.fromPercent(risk.weight);\n if (_this.debug || _this.debugCalc === 1) console.log(\"Ml: \" + risk.Ml);\n\n // CALCULATE Mdash for each GRADE in RISK ////////////////////////////////////\n // RISK WEIGHT * (1-(sum(GRADE WEIGHTS (inc zero))))\n // COST Mdash (risk.Mdash[0])\n risk.Mdash[0] = _this.fromPercent(risk.weight) * (1 - (risk.WeightedCost.reduce(_this.getSum)));\n risk.Mdash[1] = _this.fromPercent(risk.weight) * (1 - (risk.WeightedDuration.reduce(_this.getSum)));\n risk.Mdash[2] = _this.fromPercent(risk.weight) * (1 - (risk.WeightedQuality.reduce(_this.getSum)));\n if (_this.debug || _this.debugCalc === 1) console.log(\"Mdash values: \" + risk.Mdash);\n });\n });\n }",
"calcTechnicalFactors () {}",
"processVal(type, curField) {\n let curAmt = Number(document.getElementById(curField).value);\n if (isNaN(curAmt)) {\n curAmt = 0;\n curAmt = parseInt(curAmt, 10);\n } else {\n curAmt = parseInt(curAmt, 10);\n }\n\n for (let t of activityLookUp) {\n if (type === t[0]) {\n let amt = (t[1].increment);\n let newVal = curAmt + amt;\n return newVal;\n } \n }\n }",
"calculateFitness(){\n\n this.fitness = this.score * this.score;\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function longWordCount(string) that takes in a string and returns the number of words longer than 7 characters. | function longWordCount(string) {
var words = string.split(" ");
var count = 0;
for (var i = 0; i < words.length; i++) {
if (words[i].length > 7) {count += 1}
}
return count;
} | [
"function longWordCount(string)\n{\n\tvar noOfWords = 0;\n\n\tvar words = string.split(\" \");\n\n\tfor(var i = 0; i<= words.length - 1; i++)\n\t{\n\t\tvar word = words[i];\n\t\tif(word.length > 7)\n\t\t{\n\t\t\tnoOfWords += 1;\n\t\t}\n\t}\n\treturn noOfWords;\n}",
"function longWordCount(string) {\n var stringSplit = string.split(\" \");\n var numberOfWordsLargerThanSevenCharacters = 0;\n //console.log(\"Check 1: The split words are: \" + stringSplit);\n for (var i = 0; i < stringSplit.length; i++) {\n if (stringSplit[i].length > 7) {\n numberOfWordsLargerThanSevenCharacters += 1;\n }\n }\n return numberOfWordsLargerThanSevenCharacters;\n}",
"function longWordCount(string, n) {\n var words = string.split(\" \");\n var count = 0;\n\n words.forEach(function(word) {\n if (word.length > n) {\n count++;\n }\n });\n\n return count;\n}",
"countBigWords(input) {\n // code goes here\n //break string into separate words\n let words = input.split(\" \");\n //create a count\n let counter = 0;\n //iterate through each word in the string\n for (let i = 0; i < words.length; i++) {\n //check if each word's length is greater that 6\n //if it is increase the counter by 1\n if (words[i].length > 6) {\n counter++;\n }\n }\n\n //return the counter\n\n return counter;\n }",
"function longWordCount(string, n) {\n // your code here...\n let stringArr = string.split(\" \");\n let counter = 0;\n cb = function(word, idx, array) { //the name doesnt matter the order does\n if (word.length > n) {\n counter +=1\n }\n\n }\n stringArr.forEach(cb);\n return counter;\n}",
"countBigWords(input) {\n let inputSplit = input.split(\" \");\n let count = 0;\n for (let i=0; i<inputSplit.length; i++){\n if (inputSplit[i].length > 6){\n count++;\n }\n }\n return count;\n }",
"countBigWords(input) {\n // Split the input\n let arr = input.split(\" \");\n // Start counter from 0\n let count = 0;\n //if array contains more than 6 lettes word, add 1 otherwise neglect word and keep moving further\n //until whole string input is completed\n arr.forEach(word =>{\n if (word.length > 6){\n count++;\n }\n \n });\n\n // return the count of all words with more than 6 letters\n return count;\n }",
"function longestWordLength (str) {\n // Step 1 -> Use regular expressions to remove all non-word characters e.g. \",\" with replace function\n var stringWithoutSpecialCharacters = str.replace(/\\W/g, ' ');\n // Step 2 -> Declare a variable `longestWord` and set it equal to `0`\n var longestWord = '';\n // Step 3 -> Declare a variable `wordArray` and use split method to\n // create an array of words.\n var wordArray = stringWithoutSpecialCharacters.split(' ');\n // Step 4 -> Use for of loop to iterate through `wordArray`\n for (var count of wordArray) {\n // Step 5 -> Conditional `if` statement asking if current item in array\n // is longer then `longestWord.length`\n if (count.length > longestWord.length) {\n // In the code block set `longestWord` to the word in the array\n longestWord = count\n }\n }\n // Step 7 -> return the length of `longestWord`\n return longestWord.length;\n}",
"countBigWords(input) {\n // Count the number of letters in each words \n let str = input.split(' ');\n // Capture every word > 6 letters\n let bigWords=[];\n // returning all words over 6 Lettrs\n for (let i=0; i < str.length; i++) {\n\n if (str[i].length > 6) {\n bigWords.push(str[i]);\n }\n }\n return bigWords.length;\n }",
"countBigWords(input) {\n // code goes here\n //split the input in each character\n let words = input.split(\" \");\n //count characters in each word\n let bigWords=[];\n //put all the words longer than 6 in an array\n for (let i=0; i < words.length; i++ ) {\n \n if (words[i].length > 6) {\n bigWords.push(words[i]);\n }\n }\n //make an array\n //count lenght of the array\n return bigWords.length;\n }",
"function countWords(str) {\n // Decent average for English and efficient.\n return str.length / 5 | 0\n}",
"function isLong(text){\r\n return text.length > 7;\r\n}",
"function getLengthOfWord(word) {\n // code here\n}",
"function getLengthOfWord(word) {\n // your code here\n}",
"function wordsLongerThanThree(str){\r\n //your code is here\r\n }",
"function TotalWordCount(str) { \n return str.split(\" \").length;\n }",
"function lengthOfLongestWord(str) {\n\n const length = str.split( ' ').map((elem) => elem.length)\n\n return Math.max(...length)\n\n \n}",
"function WordCount(str) {\n var stringArray = str.split(\" \");\n return stringArray.length;\n}",
"function WordCount(str){\n return str.split(\" \").length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
change the displayed tree to tree two | function setTreeTwo(){
data = tree_two;
readTree();
d3.select("svg").remove();
drawUI();
} | [
"function treedisplay(ATREE){\n var height = 600;\n var width = 400;\n //var ATREE = document.getElementById('ATREE').innerHTML;\n d3.text(ATREE, function(error, newick){\n var tree = d3.layout.phylotree()\n .svg(d3.select(\"#tree_display\"))\n .options({\n 'zoom' : true\n })\n .size([height,width]);\n\n tree(ATREE).layout();\n\n $(\"#layout\").on(\"click\", function(e) {\n tree.radial($(this).prop(\"checked\")).placenodes().update();\n });//end tree(ATREE) main function containing attributes and actions\n \n function fix(subtreenewick){\n let newstr = subtreenewick;//check if this ; ruins all\n tree.get_nodes()\n .filter((l)=>d3.layout.phylotree.is_leafnode(l))\n .forEach(function(leaf){\n //deduplucate at all possible levels ! \n let tmp = leaf.name; //at the level of get_nodes()\n leaf.name = deduplicatestring(tmp);\n //at the level of newick format\n let res = newstr.replace(tmp+tmp, leaf.name);\n newstr = res;\n });\n return newstr;\n };\n \n tree.get_nodes()\n .filter((n)=> !d3.layout.phylotree.is_leafnode (n))\n .forEach(function(tree_node){\n d3.layout.phylotree.add_custom_menu(tree_node, my_menu_title,\n function() {\n let save_root = tree.get_nodes()[0];\n tree.get_nodes()[0] = tree_node;\n let newicksubtree = tree.get_newick();\n d3.select(\"#newick_holder\").text(fix(newicksubtree));\n tree.get_nodes()[0] = save_root;\n }\n ,(n)=>!d3.layout.phylotree.is_leafnode (n)\n );//end addcustom menu\n });//end select subtree \n });//end d3.text \n }",
"function changeTree(){\n displayTree(dataClonotypes);\n}",
"function treesorting()\n{\n\t\t$(\"#myGroupsInner\").tree({\n\t\tdropOn: \"ol\",\n\t\tcursor: \"move\",\n\t\tplaceholder: 'ol', \n\t\tcontainment: 'ol',\n\t\ttabSize: 20, \n\t\tmaxDepth: 6,\n\t\tmaxDepthError: 'ui-tree-deptherror',\n\t\tmaxDepthErrorText: 'Only 6 levels are allowed!',\n\t\tmaxItems: [30], \n\t\tmaxItemsError: 'ui-tree-limiterror', \n\t\tmaxItemsErrorText: 'You have reached the maximum number of items for this level!',\n\t\tafterChange: function(e,ui,level) {\n\t\t\tchangeLevelLines();\n\t\t\toutlinesaveflag=2;\n\t\t\t$(\"#cancelbutton\").removeAttr(\"disabled\");\n\t\t\t$(\"#savebutton\").removeAttr(\"disabled\");\n\t\t\t\n\t\t}\n\t\t\n\t});\n\t\t\n\t\n}",
"restructure(_tree) {\n let items = [];\n for (let item of _tree.getItems()) {\n let found = this.findItem(item.data);\n if (found) {\n found.setLabel(item.display);\n found.hasChildren = item.hasChildren;\n if (!found.hasChildren)\n found.expand(false);\n items.push(found);\n }\n else\n items.push(item);\n }\n this.innerHTML = \"\";\n this.addItems(items);\n }",
"function updateTree() {\n tree.loadData(document.getElementById(\"ranking-type-tree\").value);\n bio.loadData(document.getElementById(\"ranking-type-tree\").value);\n }",
"function setTreeOne(){\n\tdata = tree_one;\n\treadTree();\n\td3.select(\"svg\").remove();\n\tdrawUI();\n}",
"function draw_tree(QNode,f1,f2,f3,f4,l){\n\n // var tree=d3.tree()\n // .size(550,550);\n\n // var Tnodes=tree(QNode);\n\n tree_view.selectAll(\"*\").remove();\n tree_view.selectAll(\".h-circle\") .style(\"fill\",\"blue\");\n\n QTree.root.display(QNode,300,30,f1,f2,f3,f4,l);\n\n \n\n}",
"function SFAbstractTreeView() {\n\n}",
"function divideTree(){\r\n\t\t\r\n\t}",
"function changeTree(action, objectInfo)\n {\n var tree = getTopWindow().tempTree;\n var treeDisplayFrame = findFrames(getTopWindow(), \"treeDisplay\");\n if(treeDisplayFrame != null)\n {\n if(tree)\n {\n if (action == \"changeObjectName\") {\n tree.getSelectedNode().changeObjectName(objectInfo);\n }\n else if (action == \"changeObjectID\") {\n tree.getSelectedNode().changeObjectID(objectInfo);\n }\n else if (action == \"deleteObject\")\n {\n if (tree.nodemap[objectInfo]) {\n for (var i=0; i <tree.nodemap[objectInfo].length; i++) {\n if (tree.nodemap[objectInfo][i].parent.nodeID == \"root\") {\n getTopWindow().frames[\"mainFrame\"].location.reload();\n return ;\n }\n }\n }\n tree.deleteObject(objectInfo);\n }\n else if (action == \"removeChild\") {\n tree.getSelectedNode().removeChild(objectInfo);\n }\n }\n }\n }",
"_updateTreeData() {\n let dataTree = this.get('model.rightTreeNodes');\n restorationNodeTree(dataTree, {}, A(['folder', 'desk']), true);\n\n this.get('jstreeActionReceiverRight').send('redraw');\n }",
"changeTreeFormat(tree) {\n\t\tvar data;\n\t\tif(tree.length) { // Child\n\t\t\tdata = [];\n\t\t\tfor(var i=0; i<tree.length; i++) {\n\t\t\t\tvar node = tree[i];\n\t\t\t\tvar arr = {\n\t\t\t\t\t\"id\": this.getUniqueId(),\n\t\t\t\t\t\"title\": null\n\t\t\t\t};\n\t\t\t\tif(node.data) {\n\t\t\t\t\tarr.title = node.data;\n\t\t\t\t}\n\t\t\t\tif(node.children.length) {\n\t\t\t\t\tarr.children = this.changeTreeFormat(node.children);\n\t\t\t\t}\n\t\t\t\tdata.push(arr);\n\t\t\t}\n\t\t} else if(tree.data) { // One Root Node\n\t\t\tdata = {\n\t\t\t\t\"id\": this.getUniqueId(),\n\t\t\t\t\"title\": tree.data,\n\t\t\t\t\"children\": this.changeTreeFormat(tree.children)\n\t\t\t}\n\t\t} else { // Multilpe root rodes\n\t\t\tdata = this.changeTreeFormat(tree.children);\n\t\t}\n\n\t\treturn data;\n\t}",
"updateTree(row) {\n // ******* TODO: PART VII *******\n if (row.value.type == 'aggregate') {\n let id = row.key;\n \n let nodes = d3.selectAll('.node').filter((d) => {\n return (d.data.Team == id)\n });\n let links = d3.selectAll('.link').filter((d) => {\n return (d.data.Team == id && d.parent.data.Team == id)\n });\n\n nodes.selectAll('text').classed('selectedLabel',true);\n links.classed('selected',true);\n } else {\n let id = row.key;\n let op = row.value.Opponent;\n \n let nodes = d3.selectAll('.node').filter((d) => {\n return (d.data.Team == id && d.data.Opponent == op || d.data.Team == op && d.data.Opponent == id)\n });\n let links = d3.selectAll('.link').filter((d) => {\n return (d.data.Team == id && d.data.Opponent == op || d.data.Team == op && d.data.Opponent == id)\n });\n\n nodes.selectAll('text').classed('selectedLabel',true);\n links.classed('selected',true);\n }\n }",
"function updateTreeInfo() {\n\t if (!g_treeInfo) {\n\t g_treeInfo = o3djs.picking.createTransformInfo(g_client.root, null);\n\t }\n\t g_treeInfo.update();\n\t }",
"set drawTreesAndFoliage(value) {}",
"function hideTree() {\n vm.treeVisible = false;\n vm.currentOntology = '';\n vm.classDetails = '';\n }",
"function createTree2(container, data) {\n container.innerHTML = createText(data);\n}",
"function displayTree(node){\n\tvar\tstr = \"\";\n\tfunction createTreeHTML(node){\n\t\tstr = str + \"<div><p class='status-\" + node.status+ \"'>\" + node.value + \"</p>\";\n\t\tfor(var child in node.children){\n\t\t\tcreateTreeHTML(node.children[child]);\t\n\t\t}\n\t\tstr = str + \"</div>\";\n\t}\n\tcreateTreeHTML(node);\n\t$('#tree-container').html(str);\n}",
"function setDataToTree() {\n $(treeID).tree({\n data: treeData\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the set of IDs used by items in the queue. Arguments: callback Callback Arguments: error A string or null. reply The Redis reply object. | function queueGetIds(callback) {
return this.mredis.lrange("feed.ids:" + this.name, 0, -1, callback);
} | [
"function queueGet(timeout, callback) {\n if(!timeout) timeout = 0;\n this.bredis.brpop(\"feed.ids:\" + this.name, timeout, function(err, result) {\n if(!err) {\n var id = result[1];\n this.mredis.multi()\n .hget(\"feed.items:\" + this.name, id)\n .hdel(\"feed.items:\" + this.name, id)\n .exec(function(err, result) {\n this.thoonk.lock.unlock();\n callback(result[0], id, false);\n }.bind(this));\n } else {\n this.thoonk.lock.unlock();\n callback(null, null, true);\n }\n }.bind(this));\n}",
"function getUploadListIds(callback) {\n\n Youtube.channels.list({\n \"part\": \"statistics\",\n \"id\": id_string\n }, function (err, data) {\n\n async.each(data.items,\n function (item, callback) {\n //console.log(\"item: \"+JSON.stringify(item, undefined, 2));\n //stats_list.items.push(item.contentDetails.relatedPlaylists.uploads);\n stats_list.items.push(item);\n callback();\n },\n // 3rd param is the function to call when everything's done\n function (err) {\n callback(null, 'List of upload IDs done ' + uploadlistId_list.items);\n }\n );\n });\n //callback(null, 'List of upload IDs done '+uploadlistId_list.items);\n }",
"static async syncedItemIds(syncTarget) {\n\t\tif (!syncTarget) throw new Error('No syncTarget specified');\n\t\tconst temp = await this.db().selectAll('SELECT item_id FROM sync_items WHERE sync_time > 0 AND sync_target = ?', [syncTarget]);\n\t\tconst output = [];\n\t\tfor (let i = 0; i < temp.length; i++) {\n\t\t\toutput.push(temp[i].item_id);\n\t\t}\n\t\treturn output;\n\t}",
"getQueue() {\n const queue = [];\n // Need to use forEach because it's the only iteration method supported\n // by IE11. Suppress the underscore because we don't need it.\n // tslint:disable-next-line:enforce-name-casing\n this.rafIDs.forEach((_, key) => {\n queue.push(key);\n });\n return queue;\n }",
"function getSocketIDs() {\n var socketIDArr = [];\n queue.forEach((element) => {\n socketIDArr.push(element.socketID);\n });\n return socketIDArr;\n}",
"getReservoirIds(callback) {\n db.scan(0, 'match', '*_info', (err, resp) => {\n const reservoirs = [];\n\n for (let i = 0; i < resp[1].length; i += 1) {\n const id = resp[1][i].slice(0, -5); // slice off \"_info\"\n reservoirs.push(id);\n }\n\n return callback(err, reservoirs);\n });\n }",
"getAllMessageIds() {\n this._isMethodReady(true);\n return new es6_promise_1.Promise((resolve, reject) => {\n this._msgDb.allDocs().then((results) => {\n let ids = [];\n if (results.rows && results.rows.length > 0) {\n ids = results.rows.map((row) => {\n return row.id;\n });\n }\n resolve(ids);\n }).catch(reject);\n });\n }",
"function getReadAndUnreadIDs(auth) {\r\n query = '-from:me AND is:read';\r\n\r\n\r\n /*else if (read === false) {\r\n \tquery += 'is:unread';\r\n }*/\r\n\r\n console.log(auth);\r\n console.log(query);\r\n gmail.users.messages.list({\r\n \tauth:auth,\r\n \tuserId: 'me',\r\n \tq: query\r\n }, function(err, responseOne) {\r\n \tif (err) {\r\n \t\tconsole.log('The API returned an error while trying to get a list of messages: ' + err);\r\n \treturn;\r\n \t} else {\r\n \t//var messages = response.messages;\r\n \t//tempIdStorage = messages;\r\n gmail.users.messages.list({\r\n auth:auth,\r\n userId: 'me',\r\n q: '-from:me AND is:unread'},\r\n function(err, responseTwo) {\r\n if (err) {\r\n console.log('The API returned an error while trying to get a list of messages: ' + err);\r\n return;\r\n }\r\n else {\r\n setCallback(auth, err,responseOne, responseTwo, 0, 100, new Set(), new Set());\r\n }\r\n });\r\n /*var returnedSet = new Set();\r\n for (var i = 0; i<response.messages.length; i++) {\r\n returnedSet.add(messages[i]['id']);\r\n }\r\n return returnedSet;*/\r\n \t//gmail.users.messages.get({ auth:auth, userId:'me', id:messages[0]['id']}, function(err, response) {\r\n \t//\tmessageCallback(err, response, 1, 100, auth, messages, read);\r\n \t//});\r\n }\r\n\r\n \t});\r\n}",
"getIds() {\n\t\tthrow new Error(\"Not yet implemented\");\n\t}",
"nIDs() {\n return new Promise((resolve, rejce) => {\n this.ids.count({}, (err, count) => {\n if (err) {\n reject(err);\n } else {\n resolve(count);\n }\n });\n });\n }",
"get itemIds() {\n return filterOutUndefined(this._items.map(item => item.uniqueId));\n }",
"function responses_get_ids() {\n var ids = [];\n if ($('.index_table_body')) {\n var rows = $('.index_table_body tr');\n for (var i = 0; i < rows.length; i++) ids.push(rows[i].id);\n }\n return ids;\n}",
"async function keys() {\n return client().keys(cache.redisPrefix + \"*\");\n }",
"async listUuids(context, callback) {\n const uuids = await this.repository.queryUuids(this);\n return uuids;\n }",
"fetchAllRobotTypeIds(callback){\n var sql = \"SELECT robot_type_id FROM robot_type\";\n pool.getConnection(function(con_err, con) {\n if(con_err) {\n console.log(\"Error - \" + Date() + \"\\nUnable to connect to database.\");\n callback(con_err);\n return;\n }\n \n con.query(sql, [], function (err, result) {\n if (err) {\n console.log('Error encountered on ' + Date());\n console.log(err);\n callback(err);\n con.release();\n return;\n } \n \n var ids = [];\n result.forEach(function(item) {\n ids.push(item.robot_type_id);\n if(ids.length == result.length) callback(null, ids);\n });\n });\n\n });\n }",
"function getExchangeIDs(call, cb) {\n cb(null, ExchangeManager.exchanges);\n}",
"async queues() {\n return this.connection.redis.smembers(this.connection.key(\"queues\"));\n }",
"function getItems(callBack) {\n _getFromStorage(\"Items\", function(response) {\n items = [];\n\n if (response.Items != null && response.Items.length > 0) {\n response.Items.forEach(function(item) {\n items.push(item);\n\n if (item.Id >= nextId) {\n nextId = item.Id + 1;\n }\n });\n }\n\n callBack(items);\n });\n}",
"function getUUIDList(callback){\n new(cradle.Connection)().uuids(100, function(err, res){\n if (err) server.log(['db', 'error'], err)\n uuids = res\n callback(res)\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit entity by wizard | edit(options) {
return this.wizardInvokeService.openWizard(Object.assign(options, {
title: this._buildTitle(options.service.entityName, 'wizard_edit_caption'),
isNew: false,
readonly: false
}));
} | [
"static EditEntity (data) {\n return Put('/taxable_entity', data)\n }",
"editWorkAndEducation(){\n\t\tresources.workAndEducationTab().click();\n\t}",
"async edit ({ params, request, response, view }) {\n }",
"function setToEdit(data) {\n // $log.debug('setToEdit');\n var mark = EntityService.preprocessMarker(data);\n // se il type e' settato\n if (mark.entity_type) {\n typeIndex = _this.types.list.map(function (e) {\n return e.key;\n }).indexOf(mark.entity_type);\n type = _this.types.list[typeIndex].key;\n }\n\n //imposto i permessi\n $scope.checkList = angular.copy(_this.types.perms[type]);\n // template timepicker door_time\n if ($scope.checkList.door_time) {\n initDoorTime();\n }\n // template timepicker duration\n if ($scope.checkList.duration) {\n initDuration();\n }\n\n // $log.debug(\"EditorCtrl, setToEdit, checkList: \", $scope.checkList);\n // $log.debug(\"EditorCtrl received marker: \", mark, _this.types.list[ typeIndex ]);\n\n _this.wizard.dataForm = angular.copy(mark);\n _this.wizard.title = _this.labels.edit;\n _this.wizard.entityLabel = _this.types.list[typeIndex].name;\n // gestione logica di alcuni campi particolari\n if (mark.coordinates) {\n _this.wizard.dataForm.coordinates = [mark.lng, mark.lat];\n }\n\n if (_this.currentUser.id)\n _this.wizard.dataForm.user = parseInt(_this.currentUser.id);\n if (mark.id_wp)\n _this.wizard.dataForm.id_wp = parseInt(mark.id_wp);\n // recupero le informazioni sul padre se gia' inserite\n if (mark.parent_id != null && mark.parent_id !== \"undefined\") {\n // $log.debug(\"ha un parent! \", mark.parent_id);\n _this.wizard.dataForm.parent_id = mark.parent_id;\n setParent(mark.parent_id);\n }\n // se door_time e' richiesto e non e' nel marker\n if ($scope.checkList.door_time && !_this.wizard.dataForm.door_time) {\n // $log.debug(\"Entro in initDoorTime\");\n initDoorTime();\n }\n // se duration e' richiesto e non e' nel marker\n if ($scope.checkList.duration && !_this.wizard.dataForm.duration) {\n // $log.debug(\"Entro in initDuration\");\n initDuration();\n }\n // $log.debug('fine setToEdit', $scope.checkList);\n // $log.debug('data?',data);\n if (!_this.wizard.dataForm.address) {\n SearchService.reverseGeocoding({zoom: data.zoom_level, lat: data.lat, lng: data.lng}).then(\n function (res) {\n // $log.debug('address', res);\n _this.wizard.dataForm.address = res.display_name;\n },\n function (err) {\n $log.error(err);\n }\n );\n }\n\n // check step 2\n $scope.catStepInvalid();\n}",
"function edit() {\n let id = this.getAttribute('data-itemid');\n const item = itemOperations.search(id)\n\n fillFields(item)\n}",
"function edit(id){\n return load(id).then(editInForm).then(save);\n }",
"showEditArticle(data) {\n this.idArticleSelected = data._id\n this.form.title = data.title\n this.form.content = data.content\n this.form.status = data.status\n this.form.tags = data.tags\n this.dialogEdit = true\n }",
"function startEdit(){\n // Show edit button\n showButton(\"edit\");\n\n // Employee ID for corresponding row\n let employeeId = $(this).parent().parent().data('id');\n\n // Get employee record for corresponding row\n getOneEmployee(employeeId);\n}",
"function editModel(data) {\n /// start edit form data prepare\n /// end edit form data prepare\n dataSource.one('sync', function(e) {\n /// start edit form data save success\n /// end edit form data save success\n\n app.mobileApp.navigate('#:back');\n });\n\n dataSource.one('error', function() {\n dataSource.cancelChanges(itemData);\n });\n\n dataSource.sync();\n app.clearFormDomData('edit-item-view');\n }",
"function edit() {\n $state.go('^.edit', {'id': vm.lot._id});\n }",
"edit() {\n this.switchEditMode(true);\n }",
"showEditView() {\n this.state = FIELD_STATE.EDIT;\n this.update();\n }",
"function edit_onclick() {\n entryEdit = this.employee;\n saveFilterOptions();\n setEdit();\n window.location.href = \"Edit.html\";\n}",
"function editModel(data) {\n /// start edit form data prepare\n /// end edit form data prepare\n dataSource.one('sync', function(e) {\n /// start edit form data save success\n /// end edit form data save success\n $(\"#closerName\").val('');\n $(\"#workDetails\").val('');\n $(\"#workmaterials\").val('');\n window.plugins.toast.showWithOptions(\n {\n message: app.taskDetailView.get('strings').toastsMessages.tasksSuccess,//\"The check has been successfully saved\",\n duration: \"short\", // which is 2000 ms. \"long\" is 4000. Or specify the nr of ms yourself.\n position: \"bottom\",\n addPixelsY: -40 // added a negative value to move it up a bit (default 0)\n });\n app.mobileApp.navigate('#:back');\n });\n\n dataSource.one('error', function() {\n dataSource.cancelChanges(itemData);\n });\n\n dataSource.sync();\n\n app.clearFormDomData('edit-item-view');\n }",
"edit() {\n var _a, _b, _c;\n // deep clone object so we have the possibility to cancel editing\n const clone = JSON.parse(JSON.stringify(this.schema));\n // handle (array) example\n if (((_b = (_a = clone.items) === null || _a === void 0 ? void 0 : _a.examples) === null || _b === void 0 ? void 0 : _b.length) > 0) {\n clone.example = clone.items.examples[0];\n }\n if (((_c = clone.examples) === null || _c === void 0 ? void 0 : _c.length) > 0) {\n clone.example = clone.examples[0];\n }\n // text is default\n if (!clone.widget) {\n clone.widget = 'text';\n }\n // horizontal is default\n if (!clone.layout) {\n clone.layout = 'horizontal';\n }\n // array: apply choices and widget to items\n if (clone.items) {\n clone.widget = clone.items.widget;\n clone.choices = clone.items.choices;\n clone.errorMessage = clone.items.errorMessage;\n clone.format = clone.items.format;\n clone.required = clone.items.required;\n clone.itemlayout = clone.items.layout;\n }\n const dialogRef = this.dialog.open(EditElementDialogComponent, { minWidth: '50%', data: clone });\n dialogRef.afterClosed().subscribe(data => {\n var _a, _b;\n if (data) {\n this.schema.title = data.title;\n this.schema.description = data.description;\n this.schema.widget = data.widget;\n this.schema.layout = data.layout;\n this.schema.readOnly = data.readOnly;\n this.schema.errorMessage = data.errorMessage;\n if (data.example) {\n if (data.items) {\n this.schema.items.examples = [data.example];\n }\n else {\n this.schema.examples = [data.example];\n }\n }\n if (data.style) {\n delete data.style[''];\n }\n if (data.style && Object.keys(data.style).length > 0) {\n this.schema.style = data.style;\n }\n if (data.class) {\n data.class = data.class.filter(el => el != null);\n }\n if (((_a = data.class) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n this.schema.class = data.class;\n }\n if (data.items) {\n if (((_b = data.choices) === null || _b === void 0 ? void 0 : _b.length) > 0) {\n this.schema.items.choices = data.choices;\n }\n this.schema.items.widget = data.widget;\n this.schema.items.format = data.format;\n this.schema.items.errorMessage = data.errorMessage;\n this.schema.items.required = data.required;\n this.schema.items.layout = data.itemlayout;\n }\n else {\n this.schema.choices = data.choices;\n this.schema.widget = data.widget;\n this.schema.format = data.format;\n this.schema.errorMessage = data.errorMessage;\n this.schema.required = data.required;\n }\n this.schemaChange.emit();\n }\n });\n }",
"function edit(guid) {\n $.mobile.silentScroll();\n\n // aktuelle Wertung merken, wenn nicht schon gemacht\n if( guid != undefined )\n actWertung = WhiskyApp.tastings.getWertungByID(guid);\n \n // Page wechseln\n if( WhiskyApp.tablet == false )\n $.mobile.changePage(\"#whisky-details\", \n { transition: \"slidedown\" } );\n\n // Werte setzen\n refreshWertung();\n valid.validate();\n }",
"function editRecipe() {\n displayEditForm();\n }",
"function editPart(pk) {\n\n var url = `{% url \"api-part-list\" %}${pk}/`;\n\n var fields = partFields({\n edit: true\n });\n\n // Filter supplied parts by the Part ID\n fields.default_supplier.filters.part = pk;\n\n var groups = partGroups({});\n\n constructForm(url, {\n fields: fields,\n groups: groups,\n title: '{% trans \"Edit Part\" %}',\n reload: true,\n successMessage: '{% trans \"Part edited\" %}',\n });\n}",
"function onEditEquipe(equipeId) {\n var $dialog = $(\".newEquipeDialog\");\n $dialog.data(\"modify\", equipeId);\n $dialog.removeClass(\"hidden\");\n\n var concours_equipes = $.henka.storage.loadStorage($.henka.keys.concours_equipes);\n var equipes = concours_equipes[vars.concoursId];\n var data = equipes[equipeId];\n\n $dialog.find(\"input[name='equipeName']\").val(data.name).focus();\n $dialog.find(\".bAddEquipe\").addClass(\"hidden\");\n $dialog.find(\".bModifyEquipe\").removeClass(\"hidden\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the dialog for signing out a user | static showSignOutUserDialog(element) {
//Log
console.log("Showing \"Sign Out User\" dialog...");
//Get ID and name
var id = element.parentElement.parentElement.getAttribute("raw_id");
var name = element.parentElement.parentElement.getAttribute("raw_name");
//Create the alert
var container = document.createElement("div");
//Create the title
var title = document.createElement("div");
title.className = "cardname";
title.innerHTML = "Sign Out";
//Create the message
var message = document.createElement("div");
message.className = "alert_message";
message.innerHTML = "Are you sure you want to sign this user out?<br><b>" + name + "</b> will receive some credit for this event, up until the current time.";
//Create the buttons
var yesbutton = document.createElement("button");
var nobutton = document.createElement("button");
yesbutton.className = "half_button";
nobutton.className = "half_button";
yesbutton.innerHTML = "Yes";
nobutton.innerHTML = "No";
//Add the elements to the container
container.appendChild(title);
container.appendChild(message);
container.appendChild(yesbutton);
container.appendChild(nobutton);
//Create the dialog
var dialog = new Dialog(container,true);
//Create the handler for the yes button
yesbutton.onclick = function() {
//Log
console.log("User clicked YES: Signing user out...");
//Close the dialog
dialog.close();
//Delete the event
Actions.executeAction("api/signOut.php?id=" + id + "&delete=false");
};
//Create the handler for the no button
nobutton.onclick = function() {
//Log
console.log("User clicked NO: Closing dialog...");
//Close the dialog
dialog.close();
};
} | [
"handleSignedOutUser() {\n var ui = new firebaseui.auth.AuthUI(firebase.auth());\n // document.getElementById('user-signed-in').style.display = 'none';\n // document.getElementById('user-signed-out').style.display = 'block';\n ui.start('#firebaseui-container', this.getUiConfig());\n }",
"function showLogoutDialog() {\n // Get a flag to indicate whether or not we should proceed with the logout.\n var doLogout = (regState === 'Success'\n // The user is currently registered, confirm that they wish\n // to logout.\n ? confirm(\"Do you really want to logout?\")\n // The user is not currently registered, just let them\n // logout without any hassle.\n : true);\n\n if (doLogout) {\n logout();\n }\n}",
"function handleSignoutClick(){\r\n gapi.auth2.getAuthInstance().signOut();\r\n }",
"function handleSignoutClick() {\n gapi.auth2.getAuthInstance().signOut();\n }",
"signOut() {\n this.bitski.userManager.removeUser();\n this.contractInstance = null;\n this.showLoginButton();\n }",
"function signout() {\n firebase.auth().signOut()\n render(initialHtml)\n startAuthUi()\n }",
"handleSignedOutUser() {\n document.getElementById('user-signed-in').style.display = 'none';\n document.getElementById('user-signed-out').style.display = 'block';\n this.fbaseUi.start('#fbs-auth', this.getUiConfig());\n }",
"function handleSignoutClick() {\n gapi.auth2.getAuthInstance().signOut()\n}",
"function sign_out() {}",
"function handleSignedOutUser() {\n\t$(\"#placeOrder\").hide();\n\tdocument.getElementById(\"user-signed-in\").style.display = \"none\";\n\tdocument.getElementById(\"user-signed-out\").style.display = \"block\";\n\tui.start(\"#firebaseui-container\", getUiConfig());\n}",
"function handleSignoutClick(event) {\n gapi.auth2.getAuthInstance().signOut();\n }",
"function handleSignoutClick(event) {\n gapi.auth2.getAuthInstance().signOut();\n }",
"function signOut() {\n var auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n console.log('User signed out.');\n });\n }",
"async signOut () {\n const res = await postJSON('/api/logout')\n if (!this.checkResponse(res)) {\n this.page.profileBox.style.display = 'none'\n return\n }\n State.clearAllStore()\n State.removeAuthCK()\n window.location.href = '/login'\n }",
"function showLogoutDialog() {\n $(\"#confirmLogout\").dialog({\n resizable: false,\n height: \"auto\",\n width: 400,\n modal: true,\n buttons: {\n \"Log Out\": function() {\n $.ajax({\n type: 'GET',\n url: '/users/logout',\n success: function(res) {\n $(\"#confirmLogout\").dialog(\"close\");\n window.location.href = '/';\n }\n });\n },\n Cancel: function() {\n $(this).dialog(\"close\");\n }\n }\n });\n}",
"function signOut() {\n var auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n console.log('User signed out.');\n window.location.href = \"/\"\n });\n}",
"function signOut() {\n var auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n console.log(\"User signed out.\");\n });\n}",
"function showLogoutAlert() {\n kony.ui.Alert({\n \"alertType\": constants.ALERT_TYPE_CONFIRMATION,\n \"alertTitle\": \"\",\n \"yesLabel\": \"Yes\",\n \"noLabel\": \"No\",\n \"message\": \"Are you sure you want to logout?\",\n \"alertIcon\": \"\",\n \"alertHandler\": logoutHandler\n }, {\n\n });\n}",
"function signOut () {\n pseudoTRACKS.auth().signOut();\n window.location.replace('../src/login.html');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API call and sets state to comic with inputted ID | fetchContent(id) {
fetch('https://xkcd.now.sh/?comic=' + id, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => {
return response.text();
})
.then((data) => {
this.setState({comic: JSON.parse(data)})
})
} | [
"handleRunSelection(id) {\n axios.get(`http://localhost:2228/run/${id}`)\n .then(res => {\n this.setState({\n oneRunInfo: res.data[0],\n currentRunID: id,\n currentPlaceID: 0,\n })\n })\n .catch(err =>{\n console.log('ERROR', err)\n })\n }",
"fetch() {\n\n apiCall.get(`/course/${this.state.id}`, (err, res, body) => {\n this.setState({\n name: body.Course.Name,\n number: body.Course.Number,\n editing: true\n });\n });\n }",
"static ChangeClientStatus (id, request) {\n return Put(`/clients/${id}/${request}`)\n }",
"sendStateChange(id, interaction, state){\n //Verzend nieuwe state naar FlaSi.\n\n //Bijv. http://192.168.1.100:8080/domotica/0?state=1\n const url = `${config.FlaSi.urlbase}/domotica/${id}?state=${state}`\n \n fetch(url,{method: 'POST'})\n .then(data => data.json())\n .then(data => {\n //Doe iets\n console.log(data);\n }).catch(err => {\n console.log(err);\n });\n\n }",
"getOnePark(id) {\n Axios.get(`/parks/${id}`)\n .then(res => {\n this.setState({\n currentPark: res.data,\n clicked: true,\n }, () => console.log('one park', this.state.currentPark))\n });\n }",
"getPipelineInfoById(id) {\n let url = API.pipeline + \"/pipeline/findById?id=\" + id;\n let self = this;\n Axios.get(url).then((response) => {\n console.log(response);\n if (response.status === 200) {\n console.log(111);\n self.setState({\n pipelineInfo: response.data\n });\n }\n })\n }",
"function setIDstatus(io, data) {\n var clientStatus = data.clientStatus;\n var id = data.myID;\n //console.log('___client ' + id + ' status is: ' + clientStatus);\n if (clientStatus === true) {\n counter += 1;\n newIDaccepted = true;\n console.log('___client ' + id + ' accepted new ID');\n //add ID to array\n connectedClients.push(id);\n }\n console.log('next assigned ID will be: telefunker' + (counter));\n\n setStatus(io);\n}",
"getSingleBeer(id) {\n console.log('get one beer');\n console.log({ 'state before': this.state });\n fetch(`/api/beers/${id}`)\n .then(res => res.json())\n .then((res) => {\n this.setState({\n singleBeer: res.data.beer,\n singleBeerLoaded: true,\n })\n console.log({ 'Single ApiResult': res });\n console.log({ 'state after': this.state });\n })\n .catch(err => console.log(err));\n }",
"async function changeStatus() {\n const url = `https://wjrocketapi.azurewebsites.net/api/Elevator/${id}`\n const someData = {\n \"status\": \"Active\"\n } \n const putMethod = {\n method: 'PUT',\n headers: {\n 'Content-type': 'application/json; charset=UTF-8' \n },\n body: JSON.stringify(someData)\n }\n fetch(url, putMethod)\n }",
"getPipelineInfoById(id) {\n let url = API.pipeline + \"/pipeline/findById?id=\" + id;\n let self = this;\n Axios.get(url).then((response) => {\n console.log(response);\n if (response.status === 200) {\n self.setState({\n pipelineInfo: response.data\n });\n self.getRun(response.data.name + \"_\" + response.data.createTime + \"_\" + response.data.creator)\n }\n })\n }",
"function updateAPIStatusofCheckedItem(status, id) {\n console.log('updateAPIStatusofCheckedItem ran');\n\n const params = {\n apikey: apikey, \n todo_id: id,\n status: status\n }\n\n const updateStatusURL = \"http://beta.dorisapp.com/api/1_0/tasks/update_status.json\";\n const queryURL = formatAddItemQuery(params);\n const fullURL = updateStatusURL + '?' + queryURL;\n\n fetch(CORS+fullURL, {\n method: 'POST'\n })\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .catch(err => {\n alert(`Something went wrong: ${err.message}`)\n });\n}",
"setScheduleStatus(id) {\n\n let statusToSet = this.state.scheduleIsOn ? 'enabled' : 'disabled';\n\n /**\n * REST call to change the status of a schedule to enabled/disabled.\n */\n fetch('http://192.168.0.21/api/CeyiFspaKI7cxGvtu9uOLJmQgOmAZuoUyMaxwETp/schedules/' + id, {\n method: 'PUT',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n 'status': statusToSet\n })\n });\n }",
"_requestRubric(id) {\n\t\t\tthis.$.ajaxRequest.url = this.url+\"/getrubric/\"+id;\n\t\t\tthis.$.ajaxRequest.method = \"GET\";\n\t\t\tthis.$.ajaxRequest.generateRequest().completes.then((req) => {this.setRubric(req.response)});\n\t\t}",
"async loadEncounters(){\n const encodedId = encodeURIComponent(this.state.uniqueId)\n //get call here\n const response = await fetch(api+'/'+encodedId)\n const encounters = await response.json();\n this.setState({wsencounters:encounters['encounters']})\n }",
"onUpdateInscription() {\n\n let param = {'ID_inscription': this.props.inscription.ID_inscription,\n 'ID_depart': this.state.ID_depart,\n 'ID_weapon': this.state.ID_weapon,\n 'ID_category' : this.state.ID_category};\n\n this.inscription.updateInscription(param, () => this.props.update());\n this.props.handleClose(\"open_edit\");\n }",
"_defaultLoad() {\n // loading\n this._loading(true);\n\n // variable\n const myInput = {\n PotentialObjId: this.state.PotentialCusId\n }\n\n // call API\n api.getDetailPoCus(myInput, (success, result, msg) => {\n this._loading(false);\n if (success) {\n this.setState({\n data: {\n ...this.state.data,\n ...result[0],\n }\n }, () => this._registerMenu());\n\n } else {\n this._error(msg);\n }\n });\n }",
"_loadDeployDetail() {\n // loading\n this._loading(true);\n\n // variable\n const { SupID } = this.state;\n\n // call API\n api.getDeployDetail(SupID, (success, result, msg) => {\n this._loading(false);\n \n if (success) {\n \n this.setState({\n data: {\n ...this.state.data,\n ...result[0],\n }\n });\n\n } else {\n this._error(msg);\n }\n });\n }",
"fetch(data){\n this.setState({\n fetching: true\n });\n let id = data.id;\n\n Backend.request(\"out=article_info&id=\" + id, null, this.parse.bind(this));\n }",
"populateComponent(URLPath) {\n // create a variable for the URL, this is tailored according to the ID property (updated on click), passed as argument of the function\n const URLCard = `https://api.pokemontcg.io/v1/cards/${URLPath}`;\n\n // create an object in which to include data from the API call\n let card = {};\n\n // fetch the information from the URLCard\n // return value: the data\n fetch(URLCard)\n // format the data to work with a JSON object\n // argument: data from the request\n // return value: json object\n .then((response) => {\n return response.json();\n })\n // retrieve from the JSON object the information required for the project\n // argument: json object\n // logic: copy the object found under json.card, which details the properties of the specific card, in the created variable\n .then((json) => {\n card = Object.assign({}, json.card);\n console.log(card);\n })\n // update the state of the application with the retrieved data\n // the card property of the state now holds an object with information on the specific card\n .then(() => {\n this.setState({\n card: card\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets a boolean preference if it is not already set | function betterdouban_setBooleanPreferenceIfNotSet(preference, value) {
// If the preference is not set
if(!betterdouban_isPreferenceSet(preference)) {
betterdouban_getPreferencesService().setBoolPref(preference, value);
}
} | [
"function betterdouban_setBooleanPreference(preference, value) {\n // If the preference is set\n if(preference) {\n betterdouban_getPreferencesService().setBoolPref(preference, value);\n }\n}",
"function rosterprocessor_setBooleanPreferenceIfNotSet(preference, value)\n{\n // If the preference is not set\n if(!rosterprocessor_isPreferenceSet(preference))\n {\n Components.classes[\"@mozilla.org/preferences-service;1\"].getService(Components.interfaces.nsIPrefService).getBranch(\"\").setBoolPref(preference, value);\n }\n}",
"function rosterprocessor_setBooleanPreference(preference, value)\n{\n // If the preference is set\n if(preference)\n {\n Components.classes[\"@mozilla.org/preferences-service;1\"].getService(Components.interfaces.nsIPrefService).getBranch(\"\").setBoolPref(preference, value);\n }\n}",
"SetProceduralBoolean() {}",
"SetBool() {}",
"function setBool(key, value) {\r var existing = isBoolSet(key);\r try {\r store(key, (value != null && Boolean(value)));\r } \r catch (e) {\r \r }\r return existing;\r}",
"setDoSomething(booleanValue) {\n this.doSomething = booleanValue;\n }",
"function betterdouban_isPreferenceSet(preference) {\n\n // If the preference is set\n if(preference) {\n return betterdouban_getPreferencesService().prefHasUserValue(preference);\n }\n \n return false;\n}",
"function preferenceCheckboxInteraction() {\n var checkBox = jQuery('#scannerCheckBox');\n setPreference = checkBox.is(\":checked\");\n if (setPreference === true) {\n window.localStorage.setItem('scanPref', 'true');\n } else {\n window.localStorage.setItem('scanPref', 'false');\n }\n}",
"function setPlanningPref() {\n var planningPref = $('input[name=\"planning-checkbox\"]:checked').val();\n\n if (planningPref == 'planning-opted-out') {\n sessionStorage.planningPref = \"false\";\n } else {\n sessionStorage.planningPref = \"true\";\n }\n}",
"togglePreferences(){\n this.setState({preference: !this.state.preference});\n }",
"function betterdouban_getBooleanPreference(preference, userPreference) {\n // If the preference is set\n if(preference) {\n // If not a user preference or a user preference is set\n if(!userPreference || betterdouban_isPreferenceSet(preference)) {\n try {\n return betterdouban_getPreferencesService().getBoolPref(preference);\n } catch(exception) {\n // Do nothing\n }\n }\n }\n \n return false;\n}",
"setToggled() {\n this.toggled = !!this.getPropValue(\"confirm\");\n }",
"function defineBooleanProperty(/**String*/ name)\n{\n\tdefineProperty(name, false, function() branch.getBoolPref(name),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(newValue) branch.setBoolPref(name, newValue));\n}",
"setFlag(){\n\t\tthis.hasFlag = !this.hasFlag;\n\t}",
"function betterdouban_setStringPreferenceIfNotSet(preference, value) {\n // If the preference is not set\n if(!betterdouban_isPreferenceSet(preference)) {\n betterdouban_setStringPreference(preference, value);\n }\n}",
"function rosterprocessor_setStringPreferenceIfNotSet(preference, value)\n{\n // If the preference is not set\n if(!rosterprocessor_isPreferenceSet(preference))\n {\n rosterprocessor_setStringPreference(preference, value);\n }\n}",
"disallowSetPref() {\n this.disallowSetPref_ = true;\n }",
"initBooleanValue() {\n if (!this.is_hidden && this.value === undefined) {\n let value = false;\n\n if (this.field.options.default !== undefined) {\n value = this.field.options.default;\n }\n\n this.setValueInStore(value);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to display the available shows | function _displayAvailableShows() {
try {
state.shows.map((show, index) => {
console.log(`${index + 1}. ${show.name}`);
})
} catch (e) {
console.log('Failed to list shows');
}
} | [
"function displayShows(shows) {\n for (show of shows) {\n const name = show.name;\n const images = show.image;\n let thumbnail = images === null ? null : images.medium;\n createThumbnail(name, thumbnail);\n console.log(`${name} for ${thumbnail}`);\n }\n }",
"function displayShows() {\n var results = arguments;\n\n //Iterates through arguments by 2 as two consecutive elements in the array\n //belong to one show (first is show information, second is cast information)\n for (var i = 0; i < results.length; i+=2) {\n var show = results[i][0];\n var cast = results[i+1][0];\n\n var castText = '';\n\n //Iterates through cast\n for (var j = 0; j < cast.length; j++) {\n castText += (cast[j].person.name + '; ');\n }\n\n var table = $('table');\n table.append('<tr>' +\n '<td>' + show.name + '</td>' +\n '<td><a href=\"' + show.url + '\">'+ show.url +'</a></td>' +\n '<td>' + show.summary + '</td>' +\n '<td>' + castText + '</td>' +\n '<td>' + randomizeShowClip(show.name) + '</td>' +\n '</tr>'\n );\n }\n}",
"function loadShows() {\n\tfor (var i=0;i<items.length/2;i++) {\n\t\tvar object = get_one_recommended_show(i);\n\n\t\titems[i+items.length/2].children[0].children[1].children[0].innerHTML = object.name;\n\n\t\t// Set link to go to the indiviual title page\n\t\t$(items[i+items.length/2]).attr(\"href\", \"title/title.php?id=\" + object.id + \"&type=show\");\n\n\t\t// Apply imdb poster image\n\t\tapplyImdbThumbnail(items[i+items.length/2].children[0].children[0].children[0], false, object.id);\n\t}\n}",
"function setup() {\n displayAllShows(allShows);\n}",
"function showAll()\n{\n\tshowCountry = \"All\";\n\tshowPurpose = \"All\";\n\tshowOrb = \"All\";\n}",
"function displayShows (show) {\n \n // create Card\n const cardEl = document.createElement('div');\n cardEl.classList.add('card');\n shows.appendChild(cardEl);\n\n // create Date Wrapper\n const dateWrapEl = document.createElement('div');\n dateWrapEl.classList.add('date');\n cardEl.appendChild(dateWrapEl);\n\n // create Card Date Label\n const dateLabelEl = document.createElement('h5');\n dateLabelEl.classList.add('card__label', 'card__label--margin');\n dateLabelEl.innerText = 'DATE';\n dateWrapEl.appendChild(dateLabelEl);\n\n // create Card Date\n const dateEl = document.createElement('h2');\n dateEl.classList.add('card__text-title');\n dateEl.innerText = show.date;\n dateWrapEl.appendChild(dateEl);\n\n // create Venue Wrapper\n const venueWrapEl = document.createElement('div');\n venueWrapEl.classList.add('venue');\n cardEl.appendChild(venueWrapEl);\n\n // create Card Venue Label\n const venueLabelEl = document.createElement('h5');\n venueLabelEl.classList.add('card__label');\n venueLabelEl.innerText = 'VENUE';\n venueWrapEl.appendChild(venueLabelEl);\n\n // create Card Venue\n const venueEl = document.createElement('p');\n venueEl.classList.add('card__text');\n venueEl.innerText = show.venue;\n venueWrapEl.appendChild(venueEl);\n\n // create Location Wrapper\n const locationWrapEl = document.createElement('div');\n locationWrapEl.classList.add('venue');\n cardEl.appendChild(locationWrapEl);\n\n // create Card Location Label\n const locationLabelEl = document.createElement('h5');\n locationLabelEl.classList.add('card__label');\n locationLabelEl.innerText = 'LOCATION';\n locationWrapEl.appendChild(locationLabelEl);\n\n // create Card Location\n const locationEl = document.createElement('p');\n locationEl.classList.add('card__text');\n locationEl.innerText = show.location;\n locationWrapEl.appendChild(locationEl);\n\n // create Card Button\n const buttonEl = document.createElement('button');\n buttonEl.classList.add('button');\n buttonEl.setAttribute('type', 'button');\n buttonEl.innerText = 'BUY TICKETS';\n cardEl.appendChild(buttonEl);\n}",
"function showList() {\n\tEquipmentList = getList(\"/equipment\");\n\tshowTable(EquipmentList, 'equipment');\n}",
"function showEnsFilters() {\t\r\n\r\n}",
"function showResults() {}",
"async function searchForShowAndDisplay() {\n const term = $(\"#searchForm-term\").val();\n const shows = await getShowsByTerm(term);\n\n // $episodesArea.hide();\n populateShows(shows);\n}",
"function showRSSmw() {\n\n text = \"Showing RSS values in milli watts\" + \"<br>\";\n\n text = text + \"<ol> \";\n\n for (var i = 0; i < 15; i++) {\n text = text + \"<li> \";\n for (var j = 0; j < 23; j++) {\n text = text + mwrss[i][j] + \" ; \";\n }\n text = text + \"</li> \";\n }\n text = text + \"</ol> \";\n document.getElementById(\"mwrssshow\").innerHTML = text;\n\n var x = document.getElementById(\"mwrssshow\");\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n\n } else {\n x.style.display = \"none\";\n }\n}",
"function showRSSmw() {\r\n\r\n text = \"Showing RSS values in milli watts\" + \"<br>\";\r\n\r\n text = text + \"<ol> \";\r\n\r\n for (var i = 0; i < 15; i++) {\r\n text = text + \"<li> \";\r\n for (var j = 0; j < 23; j++) {\r\n text = text + mwrss[i][j] + \" ; \";\r\n }\r\n text = text + \"</li> \";\r\n }\r\n text = text + \"</ol> \";\r\n document.getElementById(\"mwrssshow\").innerHTML = text;\r\n\r\n var x = document.getElementById(\"mwrssshow\");\r\n if (x.style.display === \"none\") {\r\n x.style.display = \"block\";\r\n\r\n } else {\r\n x.style.display = \"none\";\r\n }\r\n}",
"async function searchForShowAndDisplay() {\n const term = $(\"#searchForm-term\").val();\n const shows = await getShowsByTerm(term);\n\n $episodesArea.hide();\n populateShows(shows);\n}",
"function showEvents() {\r\n /** check if organizer is switched on */\r\n if (!switchOrganizer) {\r\n switchedOffOrganizerMessage();\r\n return;\r\n }\r\n\r\n /** check if there are any events in the localStorage */\r\n if (checkAvailability('events') === false) {\r\n console.log(noEventsAvailable);\r\n return;\r\n }\r\n\r\n let archieve = arguments[0];\r\n console.log('Events list: ');\r\n getEvents().forEach(function (item) {\r\n /** check which events to show */\r\n if (archieve === undefined || archieve === '') {\r\n /** shows all events */\r\n printEvents(item);\r\n } else {\r\n /** shows only active/archieved events */\r\n if (item.archieve === archieve) {\r\n printEvents(item);\r\n }\r\n }\r\n });\r\n}",
"function showItems() {\n\t\tstorageStatsPanel.Hide();\n\t\tstorageItemsPanel.Reveal();\n\t}",
"function displayShow(number, arr, index) {\n let createDateTitle = elementCreator(\"p\", \"shows-section__date--title\");\n addInnerText(createDateTitle, \"DATE\");\n nodeParentAppender(\".shows-section__container\", number, createDateTitle);\n createDateTitle.classList.add(\"shows-section__hidden\");\n\n let createDate = elementCreator(\"p\", \"shows-section__date\");\n nodeParentAppender(\".shows-section__container\", number, createDate);\n \n let createVenueTitle = elementCreator(\"p\", \"shows-section__venue--title\");\n addInnerText(createVenueTitle, \"VENUE\");\n nodeParentAppender(\".shows-section__container\", number, createVenueTitle);\n createVenueTitle.classList.add(\"shows-section__hidden\");\n\n let createVenue = elementCreator(\"p\", \"shows-section__venue\");\n nodeParentAppender(\".shows-section__container\", number, createVenue);\n\n let createLocationTitle = elementCreator(\"p\", \"shows-section__location--title\");\n addInnerText(createLocationTitle, \"LOCATION\");\n nodeParentAppender(\".shows-section__container\", number, createLocationTitle);\n createLocationTitle.classList.add(\"shows-section__hidden\");\n\n let createLocation = elementCreator(\"p\", \"shows-section__location\");\n nodeParentAppender(\".shows-section__container\", number, createLocation);\n\n let button = elementCreator(\"button\", \"shows-section__button\");\n addInnerText(button, \"BUY TICKETS\");\n nodeParentAppender(\".shows-section__container\", number, button);\n\n createDate.innerText = arr[index][\"date\"];\n createVenue.innerText = arr[index][\"place\"];\n createLocation.innerText = arr[index][\"location\"];\n}",
"function computeDisplayInfos() {\n // Sections display info\n var sections = [];\n\n $('.section').each(function(index) {\n var node = $(this);\n\n sections.push({\n top: node.hasClass('hidden') ? Number.MAX_VALUE : node.position().top,\n node: node,\n type: app.data.sections[index].type\n });\n });\n\n // Videos in Sequence\n var inlineVideos = [];\n\n var $window = $(window),\n windowWidth = $window.width(),\n windowHeight = $window.height(),\n headerHeight = _header.getHeight();\n\n app.display = {\n browserWidth: windowWidth,\n windowWidth: windowWidth - (app.isInBuilder ? $('.section-builder-panel').width() : 0),\n windowHeight: windowHeight,\n headerHeight: headerHeight,\n sectionHeight: windowHeight - headerHeight,\n storyHeight: $('body').height(),\n scrollTop: app.display ? app.display.scrollTop : 0,\n sections: sections,\n inlineVideos: inlineVideos\n };\n }",
"show() {\n\t\tthis.forEach(pokemon => pokemon.show())\n\t\tconsole.log(`----------------\\nTotal in list: ${this.length}\\n`);\n\t}",
"function showAll() {\n $list.each(function() {\n $(this).show();\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for setting up the incidence slider, required by JQueryUI to attach handlers | function setIncidentsSlider() {
var handleA = $(".incidents-rate-slider.lower-handle");
var handleB = $(".incidents-rate-slider.upper-handle");
$('.incidents-slider').slider({
create: function (e, ui) {
handleA.text(0);
handleB.text(1000);
},
slide: function (e, ui) {
if (ui.values[0] == ui.values[1])
return false;
if ($(ui.handle).hasClass("upper-handle")) {
handleB.text(ui.value);
maxIncidents = ui.value
}
else {
handleA.text(ui.value);
minIncidents = ui.value
}
},
orientation: 'horizontal',
range: true,
min: 0,
max: 1000,
step: 10,
values: [0, 1000],
animate: true
});
} | [
"function setupUI() {\n\t\t\tconsole.log(\"Setting up the UI listeners\");\n\t\t\t// when the slider state changes it sends a message to spacebrew\n\t\t\t$(\".slider\").bind( \"change\", function(event, ui) {\n\t\t\t\tif (values[event.target.id] != event.target.value) {\n\t\t\t\t\tsb.send(event.target.id, \"range\", event.target.value);\n\t\t\t\t\tvalues[event.target.id] = event.target.value;\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function setupUI() {\n\tconsole.log(\"Setting up the UI listeners\");\n\t// when the slider state changes it sends a message to spacebrew\n\t$(\".slider\").bind( \"change\", function(event, ui) {\n\t\tif (values[event.target.id] != event.target.value) {\n\t\t\tsb.send(event.target.id, \"range\", event.target.value);\n\t\t\tvalues[event.target.id] = event.target.value;\n\t\t}\n\t});\n}",
"function prepareSlider() {\n var slider = new Slider(\"#reputationSlider\");\n}",
"function initSlider(){\n\t$('.slider').slider({\n\t\torientation: 'vertical',\n\t\trange: [0, gradientSize],\n\t\tvalues: handleArray,\n\t\tstart: function( event, ui) {\n\t\t\tappTooltips('hide-handle');\n\t\t},\n\t\tstop: function( event, ui ) {\n\t\t\tupdateAfterArrayChanges();\n\t }\n\t});\n}",
"function setupUI()\r\n{\r\n textSize(12)\r\n constraintsSlider = createSlider(1, 4, 1, 0.1)\r\n constraintsSlider.style('width', '300px')\r\n constraintsSlider.position(50, sliderY)\r\n\r\n desiredXSlider = createSlider(100, 600, desiredX, 1)\r\n desiredXSlider.style('width', '300px')\r\n desiredXSlider.position(380, sliderY)\r\n}",
"function initSliderIndicator(){\n caret = jQuery('#solutions-slider-indicator');\n moveSliderIndicator();\n}",
"function _initSliders()\r\n{\r\n\t// add key listeners for input fields\r\n\t\r\n\t$(\"#weight_slider_field\").keypress(_keyPressListener);\r\n\t$(\"#affinity_slider_field\").keypress(_keyPressListener);\r\n\t\r\n\t// show gene filtering slider\t\r\n\t$(\"#weight_slider_bar\").slider(\r\n\t\t{value: ALTERATION_PERCENT,\r\n\t\tstop: _weightSliderStop,\r\n\t\tslide: _weightSliderMove});\r\n\t\r\n\t// set max alteration value label\r\n\t//$(\"#weight_slider_area .slider-max label\").text(\r\n\t//\t_maxAlterationPercent.toFixed(1));\r\n\t\r\n\t// show affinity slider (currently disabled)\r\n//\t$(\"#affinity_slider_bar\").slider(\r\n//\t\t{value: WEIGHT_COEFF * 100,\r\n//\t\tchange: _affinitySliderChange,\r\n//\t\tslide: _affinitySliderMove});\r\n}",
"function updateIncidenceSlider(valA, valB){\n $('.incidents-slider').slider(\"values\", 0, valA)\n $(\".incidents-rate-slider.lower-handle\").text(valA)\n $('.incidents-slider').slider(\"values\", 1, valB)\n $(\".incidents-rate-slider.upper-handle\").text(valB)\n}",
"function _initSlider ()\n{\n $(_selById(Y2K_SLIDER)).slider({ \n from: 1800, \n to: 2000, \n heterogeneity: ['25/1850', '75/1950'], \n scale: [1800, 1825, 1850, 1875, 1900, 1925, 1950, 1975, 2000], \n limits: false, \n step: 1, \n dimension: '', \n callback: function( value ){ toggleMapMarkers(); } \n }); \n}",
"function component_slider(event,ui) {\n\t var sname = $(this).slider(\"option\",\"schematic\");\n\n\t // set value of specified component\n\t var cname = $(this).slider(\"option\",\"component\");\n\t var pname = $(this).slider(\"option\",\"property\");\n\t var suffix = $(this).slider(\"option\",\"suffix\");\n\t if (typeof suffix != \"string\") suffix = \"\";\n\n\t var v = ui.value;\n\t $(this).slider(\"value\",v); // move slider's indicator\n\n\t var choices = $(this).slider(\"option\",\"choices\");\n\t if (choices instanceof Array) v = choices[v];\n\n\t // selector may match several schematics\n\t $(\".\" + sname).each(function(index,element) {\n\t\t element.schematic.set_property(cname,pname,v.toString() + suffix);\n\t\t})\n\n\t // perform requested analysis\n\t var analysis = $(this).slider(\"option\",\"analysis\");\n\t if (analysis == \"dc\")\n\t\t$(\".\" + sname).each(function(index,element) {\n\t\t\telement.schematic.dc_analysis();\n\t\t })\n\n\t return false;\n\t}",
"function init_slider() {\n var sld = new dhtmlxSlider('slider', 330);\n sld.setImagePath(\"/images/\")\n sld.init();\n var disco = new PeriodicalExecuter(reset_palette, 1);\n disco.stop();\n\n sld.attachEvent(\"onSlideEnd\",function(val){\n disco.stop();\n if (val > 0) {\n disco = new PeriodicalExecuter(reset_palette, 50/val);\n }\n }) \n}",
"function setupSlider(){\n var handle = $( \"#custom-handle\" );\n $( \"#slider\" ).slider({\n max: 0,\n step: 5,\n min: -50,\n value: 0,\n range: \"max\",\n create: function() {\n handle.text( \"(-5,0)s\" );\n },\n slide: function( event, ui ) {\n if (refresh){\n $(\"#pause-btn\").trigger( \"click\" );\n }\n handle.text( \"(\"+(ui.value-5)+\",\"+(ui.value)+\")s\");\n var period = (ui.value / -5);\n timeline(period)\n }\n });\n }",
"function startSlider_() {\n\t\t\n\t slider_ = new HSlider({\n\t name: \"slider_widget_\" + utils.makeId(),\n\t\t minimum: min,\n\t maximum: max,\n\t value: value,\n\t intermediateChanges: true,\n\t onChange: onchangeEvent\n\t },sliderNodeId);\t\t\t\n\t slider_ && slider_.startup();\n\t sliderValues && sliderValues.startup();\n\t sliderRuler && sliderRuler.startup();\n\t \n\t // Add a debounce call which is delayed out past the main throttled event, such that it will will ensure\n\t // the onchange throttler doesn't prevent final values from being managed\n\t slider_.own(on(slider_,\"change\",debounce(onchangeEvent,75)));\n\t \n\t enabled_ = true;\n\t}",
"createUI(container) {\n var html = '<div class=\"ui item\" sliderName=\"' + this.displayName + '\">';\n html += '<div class=\"content\">';\n html += '<div class=\"header\">' + this.displayName + '</div>';\n html += '<div class=\"parameter\" sliderName=\"' + this.displayName + '\">';\n html += '<div class=\"paramLabel\">' + this.displayName + '</div>';\n html +=\n '<div class=\"paramSlider\" sliderName=\"' + this.displayName + '\"></div>';\n html +=\n '<div class=\"paramInput ui inverted transparent input\" sliderName=\"' +\n this.displayName +\n '\"><input type=\"text\"></div>';\n html += '</div>';\n\n // we need a sub list here\n html +=\n '<div class=\"ui horizontal fitted inverted divider\">Component Sliders</div><div class=\"ui list\"></div>';\n\n html += '</div></div>';\n\n container.append(html);\n\n var sectionID = '.item[sliderName=\"' + this.displayName + '\"] .ui.list';\n $(sectionID).transition('hide');\n\n $('.item[sliderName=\"' + this.displayName + '\"] .divider').click(\n function() {\n $(sectionID).transition('fade down');\n }\n );\n\n // event bindings\n var s = '.paramSlider[sliderName=\"' + this.displayName + '\"]';\n var i = '.paramInput[sliderName=\"' + this.displayName + '\"] input';\n\n let self = this;\n\n // event bindings\n $(s).slider({\n orientation: 'horizontal',\n range: 'min',\n max: 1,\n min: 0,\n step: 0.001,\n value: this.value,\n //stop: function (event, ui) { highLevelSliderChange(name, ui); },\n slide: function(event, ui) {\n $(i).val(String(ui.value.toFixed(3)));\n for (var id in this.subSliders) {\n this.subSliders[id].refreshUI();\n }\n },\n change: function(event, ui) {\n self.sliderCallback(ui);\n }\n });\n\n $(i).val(String(this.value.toFixed(3)));\n\n // input box events\n $(i).blur(function() {\n var data = parseFloat($(this).val());\n $(s).slider('value', data);\n });\n\n $(i).keydown(function(event) {\n if (event.which != 13) return;\n\n var data = parseFloat($(this).val());\n $(s).slider('value', data);\n });\n\n // add the subslider elements\n for (var id in this.subSliders) {\n this.subSliders[id].createUI(\n $('.item[sliderName=\"' + this.displayName + '\"] .list')\n );\n }\n }",
"function initializeUI() {\n\t\t// Create the slider.\n\t\ttarget.append($(\"<div></div>\")\n\t\t\t.attr({id: \"stream-annotator-tool-slider\", type: \"range\", min: \"0\", max: duration, step: step, value: 0})\n\t\t\t);\n\t\t$(\"div#stream-annotator-tool-slider\").slider({min: 0, max: duration, step: step, value: 0});\n\t\t// Create the canvas for labels\n\t\ttarget.append($(\"<canvas></canvas>\")\n\t\t\t.attr({id: \"stream-annotator-tool-labels\", width: duration})\n\t\t);\n\t\t// Initialize canvas tools\n\t\tcanvas = $(\"canvas#stream-annotator-tool-labels\").get(0);\n\t\tcontext = canvas.getContext(\"2d\");\n\t\t// Create the range control\n\t\ttarget.append($(\"<div></div>\")\n\t\t\t.attr({id: \"stream-annotator-tool-range\"})\n\t\t);\n\t\t$(\"div#stream-annotator-tool-range\").append($(\"<div></div>\")\n\t\t\t.attr({id: \"stream-annotator-tool-range-arrow\"})\n\t\t);\n\t\t// Create the buttons\n\t\ttarget.append($(\"<div></div>\")\n\t\t\t.attr({id: \"stream-annotator-labels-div\"})\n\t\t);\n\t\tvar labelsTarget = $(\"div#stream-annotator-labels-div\");\n\t\t\n\t\tfor (var i = 0; i < labels.length; i++) {\n\t\t\tlabels[i].font = labels[i].font ? labels[i].font : \"black\";\n\t\t\tvar label = labelsTarget.append($(\"<a></a>\")\n\t\t\t\t.addClass(\"stream-annotator-label\")\n\t\t\t\t.css({\"background-color\": labels[i].color, \"color\": labels[i].font})\n\t\t\t\t.html(labels[i].name)\n\t\t\t\t.append($(\"<span></span>\")\n\t\t\t\t\t.addClass(\"stream-annotator-hidden\")\n\t\t\t\t\t.html(labels[i].labelid)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t}",
"function initializeSliders() {\n\tupdateSilderLabel(minBPMRange, maxBPMRange, MinBPMValue, MaxBPMValue);\n\tupdateSilderLabel(minYearRange, maxYearRange, currentMinYear, currentMaxYear);\n\n\n}",
"function createSliders() {\n $(createETASlider);\n $(createModelScaleSlider);\n}",
"createUI(container) {\n var html = '<div class=\"ui item\" sliderName=\"' + this.displayName + '\">';\n html += '<div class=\"content\">';\n html += '<div class=\"header\">' + this.displayName + '</div>';\n\n // dropdown menu location\n html += '<div class=\"ui selection dropdown sortModes\"></div>';\n\n html += '<div class=\"parameter\" sliderName=\"' + this.displayName + '\">';\n html += '<div class=\"paramLabel\">' + this.displayName + ' Amount</div>';\n html +=\n '<div class=\"paramSlider\" sliderName=\"' + this.displayName + '\"></div>';\n html +=\n '<div class=\"paramInput ui inverted transparent input\" sliderName=\"' +\n this.displayName +\n '\"><input type=\"text\"></div>';\n html += '</div>';\n\n html += '<div class=\"parameter\" sliderName=\"' + this.displayName + '-str\">';\n html += '<div class=\"paramLabel\">' + this.displayName + ' Strength</div>';\n html +=\n '<div class=\"paramSlider\" sliderName=\"' +\n this.displayName +\n '-str\"></div>';\n html +=\n '<div class=\"paramInput ui inverted transparent input\" sliderName=\"' +\n this.displayName +\n '-str\"><input type=\"text\"></div>';\n html += '</div>';\n\n // we need a sub list here\n html +=\n '<div class=\"ui horizontal fitted inverted divider\">Component Sliders</div><div class=\"ui list\"></div>';\n\n html += '</div></div>';\n\n container.append(html);\n\n this.populateDropdown();\n\n var sectionID = '.item[sliderName=\"' + this.displayName + '\"] .ui.list';\n $(sectionID).transition('hide');\n\n $('.item[sliderName=\"' + this.displayName + '\"] .divider').click(\n function() {\n $(sectionID).transition('fade down');\n }\n );\n\n // event bindings\n var s = '.paramSlider[sliderName=\"' + this.displayName + '\"]';\n var i = '.paramInput[sliderName=\"' + this.displayName + '\"] input';\n\n let self = this;\n\n // event bindings\n $(s).slider({\n orientation: 'horizontal',\n range: 'min',\n max: 1,\n min: 0,\n step: 0.001,\n value: this.value,\n //stop: function (event, ui) { highLevelSliderChange(name, ui); },\n slide: function(event, ui) {\n $(i).val(String(ui.value.toFixed(3)));\n for (var id in this.subSliders) {\n this.subSliders[id].refreshUI();\n }\n },\n change: function(event, ui) {\n self.sliderCallback(ui);\n }\n });\n\n $(i).val(String(this.value.toFixed(3)));\n\n // input box events\n $(i).blur(function() {\n var data = parseFloat($(this).val());\n $(s).slider('value', data);\n });\n\n $(i).keydown(function(event) {\n if (event.which != 13) return;\n\n var data = parseFloat($(this).val());\n $(s).slider('value', data);\n });\n\n var s2 = '.paramSlider[sliderName=\"' + this.displayName + '-str\"]';\n var i2 = '.paramInput[sliderName=\"' + this.displayName + '-str\"] input';\n\n // event bindings\n $(s2).slider({\n orientation: 'horizontal',\n range: 'min',\n max: 1,\n min: 0,\n step: 0.001,\n value: this.value,\n //stop: function (event, ui) { highLevelSliderChange(name, ui); },\n slide: function(event, ui) {\n $(i2).val(String(ui.value.toFixed(3)));\n for (var id in this.subSliders) {\n this.subSliders[id].refreshUI();\n }\n },\n change: function(event, ui) {\n self.sliderCallback(ui);\n }\n });\n\n $(i2).val(String(1));\n $(s2).slider('value', 1);\n\n // input box events\n $(i2).blur(function() {\n var data = parseFloat($(this).val());\n $(s2).slider('value', data);\n });\n\n $(i2).keydown(function(event) {\n if (event.which != 13) return;\n\n var data = parseFloat($(this).val());\n $(s2).slider('value', data);\n });\n\n // add the subslider elements\n this.createSubSliderUI();\n }",
"function createSliders() {\n // Slider for the hue\n iElement.find('#hueSlider').slider({\n value: 0,\n min: 0,\n max: 1000,\n step: 1,\n orientation: 'vertical',\n change: hueSliderChanged,\n slide: hueSliderSlide\n });\n\n // Slider for the transparency\n iElement.find('#aSlider').slider({\n value: 255,\n min: 0,\n max: 255,\n step: 1,\n change: aSliderChanged,\n slide: aSliderSlide\n });\n\n // Slider for red\n iElement.find('#rSlider').slider({\n value: 0,\n min: 0,\n max: 255,\n step: 1,\n change: rSliderChanged,\n slide: rSliderSlide\n });\n\n // Slider for green\n iElement.find('#gSlider').slider({\n value: 0,\n min: 0,\n max: 255,\n step: 1,\n change: gSliderChanged,\n slide: gSliderSlide\n });\n\n // Slider for blue\n iElement.find('#bSlider').slider({\n value: 0,\n min: 0,\n max: 255,\n step: 1,\n change: bSliderChanged,\n slide: bSliderSlide\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function resetLoading() used here to reset the loading of the progress bar, when the redux return response. | resetLoading() {
this.setState({
startLoading: false,
completeLoading: false,
});
} | [
"function clearLoading() {\n\t\tvar loading = $i(\"infiniLoading\");\n\t\tloading.className = \"text-center hidden\";\n\t}",
"function reset () {\n setProperty('progress', 0);\n loadNewLabelOntoPanorama();\n }",
"reset() {\n this.progress = 0;\n this.progressWidth = this.progress;\n this.start = false;\n this.done = false;\n }",
"function resetLoadingStateTimer() {\n if (busy_state_timeout) {\n clearTimeout(busy_state_timeout);\n } else {\n busy_state_timeout = setTimeout(\n function() {\n releaseLoadingState(loading_class);\n },\n release_time\n );\n }\n }",
"function resetProgress() {\r\n\t// reset progress indicator to 0\r\n\t$(\"#upload_progress\").width(0);\r\n\r\n\t// reset progress array\r\n\toverallProgress = {};\r\n\toverallProgress.globalBytesSent = 0;\r\n\toverallProgress.globalBytesTotal = 0;\r\n\t\r\n}",
"cancel() {\n this.loadQueue = [];\n this.loading.clear();\n }",
"resetProgressBar_() {\n this.currentTime(0);\n const {\n durationDisplay,\n remainingTimeDisplay\n } = this.controlBar || {};\n if (durationDisplay) {\n durationDisplay.updateContent();\n }\n if (remainingTimeDisplay) {\n remainingTimeDisplay.updateContent();\n }\n }",
"resetProgress({state, commit, dispatch}, payload = {currentTime: 0, duration: 0}) {\n\t\t\t\t\tlet current = parseInt(payload.currentTime) || 0,\n\t\t\t\t\t\ttiming = parseInt(payload.duration) || 0;\n\n\t\t\t\t\tstate.songState.playingProgress = current/timing;\n\t\t\t\t\tstate.songState.current = current;\n\t\t\t\t\tstate.songState.timing = timing;\n\t\t\t\t\tif (current >= timing && timing>0) {\n\t\t\t\t\t\tdispatch('playSong', 'next');\n\t\t\t\t\t\tcommit('pruneCurrentTime', 0);\n\t\t\t\t\t}\n\t\t\t\t}",
"function clearLoading(n) {\n var loadobj = document.getElementById('loading');\n if (loadobj != null) {\n loadobj.parentNode.removeChild(loadobj);\n }\n loadScrolls(n);\n pageProgress();\n}",
"resetProgression(state) {\n state.progression = [];\n }",
"function reset_progress() {\n set_progress_percentage(0);\n $('#progress-text').empty();\n}",
"function removeLoading(){\n\t\t\t$wrapper.removeClass(o.loadingClass);\n\t\t\t$moreBtn.removeClass(o.btnLoadingClass);\n\t\t}",
"async function removeLoadingStatus(data) {\r\n setLoadingStatus(false);\r\n return data;\r\n }",
"function decrLoading() {\n loading--;\n loaded++;\n }",
"function progressbarReset() {\r\n progressScore = 0;\r\n progressBar.style.width = 0;\r\n}",
"function _loadingInactive() {\n\t\t\tloading.active = false;\n\t\t}",
"stopLoading() {\n this.set('_loadingCounter', Math.max(0, this.get('_loadingCounter') - 1));\n this.debug('stopped loading', this.get('_loadingCounter'));\n }",
"function clearLoadingScreen(){\n $('.pianoWrapper').style.display = \"initial\";\n $('.loadingScreen').style.display = \"none\";\n\n console.log(\"loading done\");\n }",
"function unsetLoading() {\n $('.cities-partial').removeClass('loading');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When the component mounts, create the d3 line chart and then update the popup | componentDidMount() {
this.createLineChart()
this.props.update()
} | [
"createLineChart() {\n const popupWidth = this.profileDiv.clientWidth\n const popupHeight = this.profileDiv.clientHeight\n // Set the dimensions of the canvas / graph\n const margin = { top: 10, right: 20, bottom: 40, left: 50 }\n if (this.props.popupType === \"modal\") {\n margin.left = 70\n margin.bottom = 60\n }\n const width = popupWidth - margin.left - margin.right\n const height = popupHeight - margin.top - margin.bottom\n const xAxisLabel = {\n x: width / 2,\n y: height + margin.top + 25\n }\n if (this.props.popupType === \"modal\") {\n xAxisLabel.y += 10\n }\n const yAxisLabel = {\n x: 0 - height / 2,\n y: 0 - margin.left + 5\n }\n if (this.props.popupType === \"modal\") {\n yAxisLabel.y += 5\n }\n /**\n * Scale Functions\n * - Create the functions that accept a profile's data and scale each value\n * according to the size of the popup\n *\n * Y scale is normalized across all profiles and therefore the y axis\n * remains consistent in popups, while x values are stretched according to each profile\n * and will therefore vary depending on the profile being viewed\n */\n const x = scaleLinear().range([width, 0])\n const y = scaleLinear()\n .domain([\n CONFIG.profileSummaryStatistics.yMin,\n CONFIG.profileSummaryStatistics.yMax\n ])\n .range([height, 0])\n // Define the axes\n const xAxis = axisBottom(x).ticks(5)\n const yAxis = axisLeft(y).ticks(5)\n /**\n * Define the Lines\n * - ValueLine is the actual profile line\n * - michigan_avg, michigan_high, michigan_low are the lines that describe lake michigan avg lake levels\n */\n const valueline = line()\n .x(d => x(d.x))\n .y(d => y(d.y))\n const michiganAvg = line()\n .x(d => x(d.x))\n .y(() => y(CONFIG.lakeMichiganWaterLevel.avg))\n // Adds the svg canvas\n const svg = select(this.profileDiv)\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\")\n // get the profile's data from it's json file\n json(this.props.jsonLocation, (error, data) => {\n const sortedData = data.sort((a, b) => descending(a.x, b.x))\n x.domain(extent(sortedData, d => d.x))\n svg\n .append(\"path\")\n .attr(\"class\", \"lake-stats michigan-avg\")\n .attr(\"d\", michiganAvg(sortedData))\n // Add the valueline path.\n svg\n .append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"d\", valueline(sortedData))\n // Add the X Axis\n svg\n .append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis)\n svg\n .append(\"text\")\n .attr(\n \"transform\",\n \"translate(\" + xAxisLabel.x + \" ,\" + xAxisLabel.y + \")\"\n )\n .style(\"text-anchor\", \"middle\")\n .attr(\"class\", \"axis-label\")\n .text(\"Distance (ft)\")\n // Add the Y Axis\n svg\n .append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis)\n // text label for the y axis\n svg\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", yAxisLabel.y)\n .attr(\"x\", yAxisLabel.x)\n .attr(\"dy\", \"1em\")\n .attr(\"class\", \"axis-label\")\n .style(\"text-anchor\", \"middle\")\n .text(\"Altitude (ft)\")\n })\n }",
"function initLineGraph(){\n if(lg){\n lg.remove();\n }\n lg = d3.select(\"#line-graph\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n}",
"updateSingleArticlePlot(dom, data) {\n\n // Update x axis\n this.updateXAxis(dom);\n\n // Update y axis\n this.updateYAxis(data);\n\n // Update highlighted events\n this.updateHighlightedEvents();\n\n // Remove color legend\n d3.select(\"#color-legend\")\n .style(\"display\", \"none\");\n\n // Remove previous lines\n d3.selectAll(\".line\")\n .remove();\n\n // Generate new line\n let line = d3.line()\n .x(d => this.xScale(d.peak_date))\n .y(d => this.yScale(d.view_count))\n .curve(d3.curveMonotoneX);\n\n // Animate addition of new line\n const path = this.focus_area.append(\"path\")\n .attr(\"d\", line(data))\n .attr(\"class\", \"line\");\n\n const totalLength = path.node().getTotalLength();\n\n path.attr(\"stroke-dasharray\", totalLength + \" \" + totalLength)\n .attr(\"stroke-dashoffset\", totalLength)\n .transition()\n .duration(1000)\n .attr(\"stroke-dashoffset\", 0);\n\n\n // Update circles\n let circles = this.focus_area.selectAll(\"circle\")\n // Bind each svg circle to a\n // unique data element\n .data(data, d => d.article_id);\n\n // Update()\n circles.transition()\n .attr(\"cx\", d => this.xScale(d.peak_date))\n .attr(\"cy\", d => this.yScale(d.view_count));\n\n\n // Enter() \n circles.enter()\n .append(\"circle\")\n .attr(\"id\", d => \"article_\" + d.article_id)\n .attr(\"r\", 0)\n .attr(\"cx\", d => this.xScale(d.peak_date))\n .attr(\"cy\", d => this.yScale(d.view_count))\n .attr(\"fill\", \"#a50f15\")\n // Tooltip behaviour\n .on(\"mouseover\", this.onMouseOverCircle)\n .on(\"mouseout\", this.onMouseOutCircle)\n .transition()\n .attr(\"r\", 2);\n\n // Exit()\n circles.exit()\n .transition()\n .attr(\"r\", 0)\n .remove();\n }",
"function updateLine() {\n d3.selectAll('.line-chart').remove();\n svg_line = d3.select(\"#lines\").append(\"svg\")\n .attr('class', 'line-chart')\n .attr(\"width\", width_line + margin_line.left + margin_line.right)\n .attr(\"height\", height_line + margin_line.top + margin_line.bottom)\n .append(\"g\")\n .attr(\"transform\",\n \"translate(\" + margin_line.left + \",\" + margin_line.top + \")\");\n}",
"function interaction(){\n selectValue = d3.select('#d3-dropdown').property('value')\n makelinechart(selectValue, data)\n }",
"function componentLineChart () {\n\n /* Default Properties */\n var width = 400;\n var height = 400;\n var transition = { ease: d3.easeLinear, duration: 0 };\n var colors = palette.categorical(3);\n var colorScale = void 0;\n var xScale = void 0;\n var yScale = void 0;\n var dispatch = d3.dispatch(\"customValueMouseOver\", \"customValueMouseOut\", \"customValueClick\", \"customSeriesMouseOver\", \"customSeriesMouseOut\", \"customSeriesClick\");\n var classed = \"lineChart\";\n\n /**\n * Initialise Data and Scales\n *\n * @private\n * @param {Array} data - Chart data.\n */\n function init(data) {\n var _dataTransform$summar = dataTransform(data).summary(),\n rowKeys = _dataTransform$summar.rowKeys,\n valueMax = _dataTransform$summar.valueMax;\n\n var valueExtent = [0, valueMax];\n\n // TODO: Use dataTransform() to calculate date domains?\n var dateDomain = d3.extent(data[0].values, function (d) {\n return d.key;\n });\n\n if (typeof colorScale === \"undefined\") {\n colorScale = d3.scaleOrdinal().domain(rowKeys).range(colors);\n }\n\n if (typeof xScale === \"undefined\") {\n xScale = d3.scaleTime().domain(dateDomain).range([0, width]);\n }\n\n if (typeof yScale === \"undefined\") {\n yScale = d3.scaleLinear().domain(valueExtent).range([height, 0]).nice();\n }\n }\n\n /**\n * Constructor\n *\n * @constructor\n * @alias lineChart\n * @param {d3.selection} selection - The chart holder D3 selection.\n */\n function my(selection) {\n init(selection.data());\n selection.each(function () {\n\n // Line generation function\n var line = d3.line().curve(d3.curveCardinal).x(function (d) {\n return xScale(d.key);\n }).y(function (d) {\n return yScale(d.value);\n });\n\n // Line animation tween\n var pathTween = function pathTween(data) {\n var interpolate = d3.scaleQuantile().domain([0, 1]).range(d3.range(1, data.length + 1));\n return function (t) {\n return line(data.slice(0, interpolate(t)));\n };\n };\n\n // Update series group\n var seriesGroup = d3.select(this);\n seriesGroup.classed(classed, true).attr(\"id\", function (d) {\n return d.key;\n }).on(\"mouseover\", function (d) {\n dispatch.call(\"customSeriesMouseOver\", this, d);\n }).on(\"click\", function (d) {\n dispatch.call(\"customSeriesClick\", this, d);\n });\n\n // Create series group\n var seriesLine = seriesGroup.selectAll(\".seriesLine\").data(function (d) {\n return [d];\n });\n\n seriesLine.enter().append(\"path\").attr(\"class\", \"seriesLine\").attr(\"stroke-width\", 1.5).attr(\"stroke\", function (d) {\n return colorScale(d.key);\n }).attr(\"fill\", \"none\").merge(seriesLine).transition().duration(transition.duration).attrTween(\"d\", function (d) {\n return pathTween(d.values);\n });\n\n seriesLine.exit().transition().style(\"opacity\", 0).remove();\n });\n }\n\n /**\n * Width Getter / Setter\n *\n * @param {number} _v - Width in px.\n * @returns {*}\n */\n my.width = function (_v) {\n if (!arguments.length) return width;\n width = _v;\n return this;\n };\n\n /**\n * Height Getter / Setter\n *\n * @param {number} _v - Height in px.\n * @returns {*}\n */\n my.height = function (_v) {\n if (!arguments.length) return height;\n height = _v;\n return this;\n };\n\n /**\n * Color Scale Getter / Setter\n *\n * @param {d3.scale} _v - D3 color scale.\n * @returns {*}\n */\n my.colorScale = function (_v) {\n if (!arguments.length) return colorScale;\n colorScale = _v;\n return my;\n };\n\n /**\n * Colors Getter / Setter\n *\n * @param {Array} _v - Array of colours used by color scale.\n * @returns {*}\n */\n my.colors = function (_v) {\n if (!arguments.length) return colors;\n colors = _v;\n return my;\n };\n\n /**\n * X Scale Getter / Setter\n *\n * @param {d3.scale} _v - D3 scale.\n * @returns {*}\n */\n my.xScale = function (_v) {\n if (!arguments.length) return xScale;\n xScale = _v;\n return my;\n };\n\n /**\n * Y Scale Getter / Setter\n *\n * @param {d3.scale} _v - D3 scale.\n * @returns {*}\n */\n my.yScale = function (_v) {\n if (!arguments.length) return yScale;\n yScale = _v;\n return my;\n };\n\n /**\n * Dispatch Getter / Setter\n *\n * @param {d3.dispatch} _v - Dispatch event handler.\n * @returns {*}\n */\n my.dispatch = function (_v) {\n if (!arguments.length) return dispatch();\n dispatch = _v;\n return this;\n };\n\n /**\n * Dispatch On Getter\n *\n * @returns {*}\n */\n my.on = function () {\n var value = dispatch.on.apply(dispatch, arguments);\n return value === dispatch ? my : value;\n };\n\n return my;\n }",
"initD3TsLine() {\n\n const self = this;\n\n // Component definition\n self.d3.o.tsLine = {\n color: \"blue\",\n o: self.d3.o.graph.append(\"path\")\n .attr(\"class\", \"tsLine\"),\n // Sets up a D3 scale for timestamps (will be used as horizontal)\n timeScale: self.d3.t.timeScale,\n // Sets up a D3 scale for values (will be used as vertical)\n valueScale: self.d3.t.valueScale\n };\n\n /**\n * Set the coordinates of the line corresponding to the visible graph part being shown\n */\n self.d3.o.tsLine.line = d3.line()\n .curve(d3.curveBasis)\n .x(function (d, i) {\n return self.d3.o.tsLine.timeScale(self.d3.v.rawTimestamps[i]);\n })\n .y(function (d) {\n return self.d3.o.tsLine.valueScale(d);\n });\n\n /**\n * Apply a quick update of the object tsLine\n *\n * @param {number} duration transition duration\n * @param {boolean} tagOld indicate if the object shall be tagged as \"old data\"\n */\n self.d3.o.tsLine.quickUpdate = function (duration, tagOld = false) {\n\n let strokeColor = self.d3.o.tsLine.color;\n if (tagOld) {\n strokeColor = \"grey\";\n }\n\n // UPDATE\n self.d3.o.tsLine.o\n .attr(\"transform\", \"translate(-\" + self.d3.c.marginSide + \" -\" + self.d3.c.marginTopBot + \")\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", strokeColor)\n .attr(\"stroke-width\", \"1px\")\n .transition().duration(duration)\n .attr(\"d\", function () {\n return self.d3.o.tsLine.line(self.d3.v.rawValues);\n });\n };\n\n /**\n * Apply a full update of the object tsLine\n * @param duration {number} transition duration\n * @param keepX {boolean} indicating if the scaling of X has to be updated\n * @param keepY {boolean} indicating if the scaling of Y has to be updated\n */\n self.d3.o.tsLine.fullUpdate = function (duration, keepX, keepY) {\n\n if (!keepX) {\n self.d3.o.tsLine.timeScale.domain(d3.extent(self.d3.v.rawTimestamps));\n }\n if (!keepY) {\n self.d3.o.tsLine.valueScale.domain([self.d3.v.minVal, self.d3.v.maxVal]);\n }\n\n\n // Refresh data values\n self.d3.o.tsLine.o\n .data(self.d3.o.tsLine.line(self.d3.v.rawValues));\n\n // EXIT old data\n self.d3.o.tsLine.o\n .exit()\n .remove();\n\n self.d3.o.tsLine.quickUpdate(duration, false);\n\n // ENTER\n self.d3.o.tsLine.o\n .enter()\n .attr(\"d\", function () {\n return self.d3.o.tsLine.line(self.d3.v.rawValues);\n })\n .attr(\"transform\", \"translate(-\" + self.d3.c.marginSide + \" -\" + self.d3.c.marginTopBot + \")\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", self.d3.o.tsLine.color)\n .attr(\"stroke-width\", \"1px\");\n };\n }",
"function refreshVisualization() {\n\n // if our graph shell hasn't been rendered (first time loading data), do so\n if (isUndefined(SVG)) {\n renderVisualization();\n }\n\n SVG.append('path')\n .attr('transform', buildTranslation(Padding.left, Padding.top))\n .attr('class', 'line-graph')\n .attr('d', Plotter(Data.Values))\n .attr('stroke-linejoin', 'round');\n }",
"renderChart() {\n // There is nothing to do if the element hasn't been inserted yet\n if (!this.element) return;\n\n // First, create the axes to get the dimensions of the resulting\n // svg elements\n this.mountD3Elements();\n\n run.next(() => {\n // Then, recompute anything that depends on the dimensions\n // on the dimensions of the axes elements\n this.notifyPropertyChange('xAxisHeight');\n this.notifyPropertyChange('yAxisWidth');\n\n // Since each axis depends on the dimension of the other\n // axis, the axes themselves are recomputed and need to\n // be re-rendered.\n this.mountD3Elements();\n if (this.get('isActive')) {\n this.updateActiveDatum(this.get('latestMouseX'));\n }\n });\n }",
"render() {\n\n let metricDataSet = [];\n let metricList = [];\n \n if(this.props.measurement != null && this.props.measurement != undefined && this.props.measurement.length != 0) {\n for(var index in this.props.measurement) {\n metricDataSet = this.createGraphData(index);\n metricList.push(metricDataSet);\n }\n \n return (\n <div>\n <div style = {{ display: 'flex' }}>\n <XYPlot yPadding = {10} width = {1500} height = {1000}>\n <HorizontalGridLines />\n <VerticalGridLines />\n <XAxis title = \"X Axis\" tickFormat = {function tickFormat(d) {\n const date = new Date(d);\n return date.toLocaleTimeString();\n }} />\n <YAxis title = \"YAxis\" />\n {\n metricList.map((dataset, index) => {\n return <LineSeries data = {dataset} key = {index} />\n })\n }\n </XYPlot>\n </div>\n </div>\n );\n } else {\n return(\n <div>\n Select Metric from Dropdown\n </div>\n );\n }\n }",
"componentDidUpdate() {\n d3.select(this.refs.xAxis).transition().call(this.xAxis);\n d3.select(this.refs.yAxis).transition().call(this.yAxis);\n }",
"lineChart() {\n if (this._lineChart === undefined) {\n this._windowWidth = window.innerWidth\n this._lineChart = new LineChart(this.store(), 60, \"[data-viz='wrapper']\", \"[data-viz='tooltip']\")\n }\n return this._lineChart\n }",
"function loadChart() {\n\t\n\td3.select('#TimeLineDIV')\n\t\t\t.datum(TheApp.getData())\n\t\t\t.call(timeline);\n\t\n\td3.select('#TimeLineHandlerDIV')\n\t\t\t.datum(TheApp.getData())\n\t\t\t.call(theContext);\t\t\n\t\n\t\n\td3.select('#FocusDIV')\n\t\t\t.datum(TheApp.getData())\n\t\t\t.call(focus);\n\t\n\tmap.initialize(TheApp.getData());\n\ttheNotes.initialize(TheApp.getData());\n\t\n\t\n}",
"componentDidMount() {\n this.svg = d3.select(`#${this.getDivId()}`).append('svg')\n }",
"function makeLineGraph() {\n\n // Clear out the current html in the line graph svg\n svgLineGraph.html(\"\");\n\n // Filter data based on selected country\n let countryData = allYearsData.filter((row) => row[\"location\"] == selectedCountry);\n\n // Get all the years for the given country\n let timeData = countryData.map((row) => +row[\"time\"]);\n\n // Get the population data for the given country\n let populationData = countryData.map((row) => +row[\"pop_mlns\"]);\n\n let minMax = findMinMax(timeData, populationData)\n\n let funcs = drawAxes(minMax, \"time\", \"pop_mlns\", svgLineGraph, {min: 100, max: 950}, {min: 100, max: 750});\n plotLineGraph(funcs, countryData, selectedCountry)\n }",
"updateLineChart(mapClick) {\n let that = this;\n that.deleteLineChart();\n // Find the max production for the selected crop over all years\n let years = that.data.max_element_vals_for_each_crop[that.cropVis.selected_crop][\"Production\"];\n let cropElementMax = 0;\n for (let year in years) {\n let thisValue = +years[year];\n if (thisValue > cropElementMax) {\n cropElementMax = thisValue;\n }\n }\n let valueScale = d3.scaleLinear().domain([0, cropElementMax]).range([that.height, that.margin.top]);\n\n // Create y axis\n let unitCompressionFactor = (10 ** (String(Math.trunc(cropElementMax)).length - 1));\n let yAxisScale = d3.scaleLinear().domain([0, cropElementMax]).range([that.height, that.margin.top]).nice();\n let yAxis = d3.axisLeft().scale(yAxisScale).tickFormat(function (d) {\n return d / (unitCompressionFactor);\n });\n d3.select(\"#line_chart_svg\")\n .append(\"g\")\n .attr(\"id\", \"lineChartYAxis\")\n .attr(\"transform\", \"translate(\" + that.margin.left + \",\" + that.margin.top + \")\")\n .call(yAxis);\n d3.select(\"#line_chart_svg\")\n .append(\"text\")\n .text(\"Units: \" + unitCompressionFactor.toExponential() + \" tonnes\")\n .attr(\"x\", that.margin.left)\n .attr(\"y\", that.margin.top + 10)\n .attr(\"id\", \"lineUnitsKey\");\n\n //Prepare data to bind\n let selected_countries_data = {};\n for (let c of that.cropVis.selected_countries) {\n selected_countries_data[c] = that.data.countries[c];\n }\n let year_data = {};\n for (let c in selected_countries_data) {\n year_data[c] = [];\n for (let year = 1961; year <= 2014; year++) {\n let value = selected_countries_data[c][that.cropVis.selected_crop][\"Production\"][\"y\" + String(year)];\n if (value == \"\") {\n value = 0;\n }\n else if (Number.isNaN(value)) {\n console.log(value);\n }\n year_data[c].push([year, value]);\n }\n }\n let lineChartSVG = d3.select(\"#line_chart_svg\")\n .append(\"g\")\n .attr(\"id\", \"line_chart_group\")\n .attr(\"transform\", \"translate(\" + that.margin.left + \",\" + that.margin.top + \")\");\n\n const lineTransition = d3.transition()\n .ease(d3.easeLinear)\n .duration(3000);\n\n let i = 1;\n for (let c in year_data) {\n let path = lineChartSVG.append(\"path\");\n path.datum(year_data[c])\n .attr(\"d\", d3.line()\n .x(function (d) {\n let x = that.yearScale(d[0]);\n if (Number.isNaN(x) || x == undefined) {\n return that.yearScale(1961);\n }\n else {\n return x;\n }\n })\n .y(function (d) {\n let y = valueScale(d[1]);\n if (Number.isNaN(y) || y == undefined) {\n return valueScale(0);\n }\n else {\n return y;\n }\n })\n )\n .classed(\"line\", true)\n .attr(\"id\", function () {\n return c.replace(/ /g, \"_\") + \"_line\";\n })\n .style(\"stroke\", function () {\n return that.cropVis.worldMap.selectedCountryColorScheme(i);\n })\n .on(\"mouseover\", function () {\n let country = c.replace(/ /g, \"_\");\n d3.select(this).classed(\"mouseoverLine\", true);\n d3.select(\"#\" + country + \"_rect\").classed(\"mouseoverRect\", true);\n })\n .on(\"mouseout\", function () {\n let country = c.replace(/ /g, \"_\");\n d3.select(this).classed(\"mouseoverLine\", false);\n d3.select(\"#\" + country + \"_rect\").classed(\"mouseoverRect\", false);\n })\n .append(\"title\")\n .text(function () {\n return c;\n });\n if (mapClick) {\n // Only animate the latest line and only if it's a new country\n if (i == that.cropVis.selected_countries.size && !that.alreadyExistingCountries.has(c)) {\n path.attr(\"stroke-dashoffset\", 2500)\n .attr(\"stroke-dasharray\", 2500)\n .transition(lineTransition)\n .attr(\"stroke-dashoffset\", 0);\n }\n }\n else {\n // Animate all lines\n path.attr(\"stroke-dashoffset\", 2500)\n .attr(\"stroke-dasharray\", 2500)\n .transition(lineTransition)\n .attr(\"stroke-dashoffset\", 0);\n }\n that.alreadyExistingCountries.add(c);\n i++;\n for (let country of that.cropVis.selected_countries) {\n country = country.replace(/ /g, \"_\");\n d3.select(\"#\" + country + \"_rect\")\n .on(\"mouseover\", function () {\n d3.select(this).classed(\"mouseoverRect\", true);\n d3.select(\"#\" + country + \"_line\").classed(\"mouseoverLine\", true);\n })\n .on(\"mouseout\", function () {\n d3.select(this).classed(\"mouseoverRect\", false);\n d3.select(\"#\" + country + \"_line\").classed(\"mouseoverLine\", false);\n });\n }\n }\n }",
"function initLine(data){\n\n var initData;\n\n // Set default\n Object.values(data).forEach(function(value){\n if(value.name == \"Nederland\"){\n initData = [value]\n }\n })\n\n var width = 500;\n var height = 400;\n var margin = 80;\n\n var duration = 250;\n\n var lineOpacity = \"0.25\";\n var lineOpacityHover = \"0.85\";\n var otherLinesOpacityHover = \"0.1\";\n var lineStroke = \"1.5px\";\n var lineStrokeHover = \"2.5px\";\n\n var circleOpacity = '0.85';\n var circleOpacityOnLineHover = \"0.25\"\n var circleRadius = 3;\n var circleRadiusHover = 6;\n\n /* Scale */\n var xScale = d3v5.scaleLinear()\n .domain(d3v5.extent(initData[0].values, d => d.x))\n .range([0, width-margin]);\n\n var yScale = d3v5.scaleLinear()\n .domain([0, d3v5.max(initData[0].values, d => d.y)])\n .range([height-margin, 0]);\n\n /* Add SVG */\n var svg = d3v5.select(\".prognose\").append(\"svg\")\n .attr(\"class\", \"svg_prognose\")\n .attr(\"width\", (width+margin)+\"px\")\n .attr(\"height\", (height+margin)+\"px\")\n .append('g')\n .attr(\"transform\", `translate(${margin}, ${margin})`);\n\n // Add a line to the svg\n var line = d3v5.line()\n .x(d => xScale(d.x))\n .y(d => yScale(d.y));\n\n let lines = svg.append('g')\n .attr('class', 'lines');\n\n lines.selectAll('.line-group')\n .data(initData).enter()\n .append('g')\n .attr('class', 'line-group')\n .on(\"mouseover\", function(d) {\n svg.append(\"text\")\n .attr(\"class\", \"title-text\")\n .style(\"fill\", \"steelblue\")\n .text(d.name)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"x\", (width-margin) / 1.5)\n .attr(\"y\", 100);\n })\n .on(\"mouseout\", function(d) {\n svg.select(\".title-text\").remove();\n })\n .append('path')\n .attr('class', 'line')\n .attr('d', d => line(d.values))\n .style('stroke', \"steelblue\")\n .style('opacity', lineOpacity)\n .on(\"mouseover\", function(d) {\n d3v5.selectAll('.line')\n \t\t\t\t\t.style('opacity', otherLinesOpacityHover);\n d3v5.selectAll('.circle')\n \t\t\t\t\t.style('opacity', circleOpacityOnLineHover);\n d3v5.select(this)\n .style('opacity', lineOpacityHover)\n .style(\"stroke-width\", lineStrokeHover)\n .style(\"cursor\", \"pointer\");\n })\n .on(\"mouseout\", function(d) {\n d3v5.selectAll(\".line\")\n \t\t\t\t\t.style('opacity', lineOpacity);\n d3v5.selectAll('.circle')\n \t\t\t\t\t.style('opacity', circleOpacity);\n d3v5.select(this)\n .style(\"stroke-width\", lineStroke)\n .style(\"cursor\", \"none\");\n });\n\n let circles = svg.append('g')\n .attr('class', 'circles');\n\n // Add circles to the line\n circles.selectAll(\"circle\")\n .data(initData[0].values).enter()\n .append(\"g\")\n .attr(\"class\", \"circletext\")\n .on(\"mouseover\", function(d) {\n d3v5.select(this)\n .style(\"cursor\", \"pointer\")\n .append(\"text\")\n .attr(\"class\", \"text\")\n .text(`${d.y}`)\n .attr(\"x\", d => xScale(d.x) + 5)\n .attr(\"y\", d => yScale(d.y) - 10)\n })\n .on(\"mouseout\", function(d) {\n d3v5.select(this)\n .style(\"cursor\", \"none\")\n .transition()\n .duration(duration)\n .selectAll(\".text\").remove();\n })\n .append(\"circle\")\n .attr(\"class\", \"circles\")\n .attr(\"cx\", d => xScale(d.x))\n .attr(\"cy\", d => yScale(d.y))\n .attr(\"r\", circleRadius)\n .style(\"fill\", \"steelblue\")\n .style('opacity', circleOpacity)\n .on(\"mouseover\", function(d) {\n d3v5.select(this)\n .transition()\n .duration(duration)\n .attr(\"r\", circleRadiusHover);\n })\n .on(\"mouseout\", function(d) {\n d3v5.select(this)\n .transition()\n .duration(duration)\n .attr(\"r\", circleRadius);\n });\n\n // Add axis\n var xAxis = d3v5.axisBottom(xScale)\n .ticks(5)\n .tickFormat(d3v5.format(\"d\"));\n var yAxis = d3v5.axisLeft(yScale).ticks(5);\n\n // Add text\n svg.append(\"g\")\n .attr(\"class\", \"x-axis\")\n .attr(\"transform\", `translate(0, ${height-margin})`)\n .call(xAxis);\n\n svg.append(\"g\")\n .attr(\"class\", \"y-axis\")\n .call(yAxis)\n\n svg.append(\"text\")\n .attr(\"x\", width / 3)\n .attr(\"h\", 10)\n .attr(\"class\", \"titleScatter\")\n .text(\"Prognose for \" + initData[0].name)\n\n svg.append('text')\n .attr(\"x\", -260)\n .attr(\"y\", -60)\n .attr(\"transform\", \"rotate(-90)\")\n .text(\"Number of people with dementia\")\n\n svg.append(\"text\")\n .attr(\"x\", 350)\n .attr(\"y\", 360)\n .text(\"Years\");\n}",
"function activateChart() {\n drawChart(store, xChoice.getValue(), yChoice.getValue(), 'PlotContainer');\n //updatePlots('PlotContainer');\n }",
"function redrawLineChart() {\n\n setChartParameters();\n\n svg.selectAll(\"g.y.axis\").call(yAxisGen);\n svg.selectAll(\"g.x.axis\").call(xAxisGen);\n\n dataGroup.forEach(function (d, i) {\n console.log(d);\n svg.select(\".\" + pathClass + d.key )\n .attr('d', lineFun(d.values))\n \n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write coordinates to file | function updateCoords(){
storage.write('coords.json', coords);
} | [
"function saveXY() {\n var posList = {};\n // select each node - get its shortNm and its position transform\n d3.selectAll(\".node\").each(function(d) {\n // un-project coords\n posList[d.shortNm] = proj.invert([d.x, d.y]); });\n var dummy = document.createElement(\"a\");\n var encodedUri = encodeURI(\n \"data:text/json;charset=utf-8,\" + JSON.stringify(posList));\n dummy.setAttribute(\"href\", encodedUri);\n dummy.setAttribute(\"download\", \"xycoords.json\");\n document.body.appendChild(dummy);\n dummy.click(); // This will download the data file\n}",
"function writeMultipoint(coords, i) {\n // Length of multipoint record\n var contentLength = 40 + coords.length * 16;\n if (is3D) {\n contentLength += 32 + coords.length * 16;\n }\n var totalLength = contentLength + 8;\n\n var featureExtent = coords.reduce(function (extent, c) {\n return ext.enlarge(extent, c);\n }, ext.blank());\n\n // Write entry to index file.\n shxView.setInt32(shxI, shxOffset / 2); // Offset in shx file.\n shxView.setInt32(shxI + 4, totalLength / 2); // Record length.\n shxI += 8;\n shxOffset += totalLength;\n\n // Write record to shape file.\n shpView.setInt32(shpI, i); // Record number\n shpView.setInt32(shpI + 4, contentLength / 2); // Record length (in 16 bit words);\n shpView.setInt32(shpI + 8, TYPE, true); // Record type. MULTIPOINT=8,MULTIPOINTZ=18\n shpView.setFloat64(shpI + 12, featureExtent.xmin, true); // Bounding box.\n shpView.setFloat64(shpI + 20, featureExtent.ymin, true);\n shpView.setFloat64(shpI + 28, featureExtent.xmax, true);\n shpView.setFloat64(shpI + 36, featureExtent.ymax, true);\n shpView.setInt32(shpI + 44, coords.length, true); // Number of points.\n shpI += 48;\n\n // Write points.\n var zMin = Number.MAX_VALUE;\n var zMax = -Number.MAX_VALUE;\n var mMin = Number.MAX_VALUE;\n var mMax = -Number.MAX_VALUE;\n coords.forEach(function (p, i) {\n if ((coords[2] || 0) < zMin) {\n zMin = coords[2] || 0;\n }\n\n if ((coords[2] || 0) > zMax) {\n zMax = coords[2] || 0;\n }\n\n if ((coords[3] || 0) < mMin) {\n mMin = coords[3] || 0;\n }\n\n if ((coords[3] || 0) > mMax) {\n mMax = coords[3] || 0;\n }\n\n shpView.setFloat64(shpI, p[0], true); // X\n shpView.setFloat64(shpI + 8, p[1], true); // Y\n shpI += 16;\n });\n\n if (is3D) {\n // Write z value range\n shpView.setFloat64(shpI, zMin, true);\n shpView.setFloat64(shpI + 8, zMax, true);\n shpI += 16;\n\n // Write z values.\n coords.forEach(function (p, i) {\n shpView.setFloat64(shpI, p[2] || 0, true);\n shpI += 8;\n });\n\n // Write m value range.\n shpView.setFloat64(shpI, mMin, true);\n shpView.setFloat64(shpI + 8, mMax, true);\n shpI += 16;\n\n // Write m values;\n coords.forEach(function (p, i) {\n shpView.setFloat64(shpI, p[3] || 0, true);\n shpI += 8;\n });\n }\n }",
"function GenerateCoordinatesCSV(file) {\r\n\t//var activeDoc = app.activeDocument;\r\n\tvar layers = app.activeDocument.layers;\r\n\tvar len = layers.length;\r\n\r\n\tvar fout = File( file );\r\n\tfout.open( \"w\" );\r\n\t\r\n\tvar CSVText = \"\";\r\n \r\n\tfor (var i = 0; i < len; i++) {\r\n\t\tif (layers[i].visible && layers[i].kind != LayerKind.TEXT) {\r\n\t\t\tvar suffix = layers[i].name.slice(4);\r\n\t\t\tvar prefix = layers[i].name.slice(0, 3);\r\n\t\r\n\t\t\tvar xPos = layers[i].bounds[0]; \r\n\t\t\tvar yPos = layers[i].bounds[1];\r\n\t\t\t\r\n\t\t\tif (HalfSize == true) {\r\n\t\t\t\txPos = Math.floor(xPos * 0.5);\r\n\t\t\t\tyPos = Math.floor(yPos * 0.5);\r\n\t\t\t}\r\n\r\n\t \t\tvar filePath = layers[i].name;\r\n\t \t\tif (CSVText == \"\") {\r\n\t\t\t\tCSVText += filePath;\r\n\t\t\t} else {\r\n\t\t\t\tCSVText += \";\" + filePath;\r\n\t\t\t}\r\n\t\t\tCSVText += \";\" + xPos;\r\n\t\t\tCSVText += \";\" + yPos;\r\n\t\t\t//CSVText += \"\\n\";\r\n\t\t}\r\n\t}\r\n\tfout.writeln(CSVText);\r\n\tfout.close();\r\n}",
"function saveToFile(latLng, edges) {\n var path = '/tmp/' + String(latLng.lat) + 'x' + String(latLng.lng) + '.json';\n fs.writeFile(path, JSON.stringify(edges, null, '\\t'), function(err) {\n if (err)\n console.log(err);\n else\n console.log(\"saved tmp data to:\", path);\n });\n}",
"function savePoints() {\n var csvContent = \"data:text/csv;charset=utf-8,\";\n controlPoints.forEach(function (point, index) {\n dataString = point.x.toFixed(2) + ',' + point.y.toFixed(2) + ',' + point.z.toFixed(2);\n csvContent += dataString + '\\n';\n });\n var encodedUri = encodeURI(csvContent);\n var link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"control_points.csv\");\n document.body.appendChild(link);\n link.click();\n}",
"function writeLocation(latitude,longitude) {\n lines = [];\n // read router.conf into array\n lineReader.eachLine('/home/pi/dev/rasBuoy/node/router/router.conf', function(line, last) {\n lines.push(line);\n if (last) {\n var writeData = \"\";\n // find and modify lat/long\n for (var i = 0; i < lines.length; i++) {\n if (lines[i].indexOf(\"LATITUDE\") > -1) {\n lines[i] = \"LATITUDE=\"+latitude;\n }\n if (lines[i].indexOf(\"LONGITUDE\") > -1) {\n lines[i] = \"LONGITUDE=\"+longitude;\n }\n // append line to write data\n writeData += lines[i]+\"\\n\"\n }\n // write data to router.conf\n fs.writeFile('/home/pi/dev/rasBuoy/node/router/router.conf', writeData, function(err){\n if(err){console.log(err);}\n });\n return false; // stop reading\n }\n });\n}",
"function writeToWindow(points) {\n\n \t\t\tvar str = '';\n \t\t\tvar ide = this.world.children[0];\n var radii = [];\n var angles = [];\n\n var keys = [];\n\n for(var key of points.keys()) {\n keys.push(key);\n }\n\n keys.sort(function(a,b){return a - b});\n\n for(var j = 0; j < keys.length; j++) {\n var values = points.get(keys[j]);\n for(var k = 0; k < values.length; k++) {\n radii.push(keys[j]);\n angles.push(values[k]);\n }\n }\n\n for (var i = 0; i < radii.length; i++) {\n\n str += radii[i] + \",\" + angles[i];\n if (i !== radii.length - 1) {\n str += '\\n';\n }\n }\n ide.saveFileAs(str, 'data:text/csv', ide.projectName + ' csvData');\n \t\t}",
"saveGrid(file) {\n\t\tlet data = this.rows + ' ' + this.cols;\n\n\t\t// TO DO: append the values in this.grid to data\n for(let i = 0; i < this.rows; i++){\n for(let j = 0; j < this.cols; j++){\n data += \" \" + this.grid[i][j];\n }\n }\n\t\tdata += '\\n';\n\t\tfs.writeFileSync(file,data);\n\t}",
"function writeToFile(fileName, data) {\n \n}",
"function writeToFile() {\n\tFS.root.getFile(filename,{create : true},gotFileEntryforWriter,failed);\n \n}",
"function writeFile(fileName, numbers) {\n fs.writeFileSync(fileName, numbers);\n }",
"function writePosition(x,y){\n //first refer to the point and set the value\n database.ref('ball/position').set({\n 'x':position.x+x,\n 'y':position.y+y\n })\n}",
"function writePosition(x,y){\n//set puts a new value at the place referred in the database\n database.ref('ball/position').set({\n'x':position.x+x,\n'y':position.y+y,\n }) \n}",
"function saveMarkersToFile(){\n\t// Create saveable objects\n\tvar objectsToSave = [];\n\t$.each(markers, function(index, value){\n\t\tobjectsToSave.push({name: value.name, position: value.position});\n\t});\n\t\n\t// Serialize Array to JSON\n\tvar serializedMarkers = JSON.stringify(objectsToSave);\n\t\n\t// Start ajax request which calls php filewriter function (Javascript can't access filesystem)\n\t$.ajax({\n\t\turl: \"scripts/php/fwrite.php\",\n\t\tdata: { obj: serializedMarkers },\n\t\tdataType: \"json\",\n\t\tcache: false,\n\t\tasync: true,\n\t\ttype: 'post',\n\t\ttimeout : 5000,\n\t});\n}",
"function saveFractionalCoordinate() {\r\n\twarningMsg(\"Make sure you had selected the model you would like to export.\");\r\n\r\n\tif (selectedFrame == null)\r\n\t\tgetUnitcell(1);\r\n\r\n\tvar x = \"var cellp = [\" + roundNumber(_cell.a) + \", \" + roundNumber(_cell.b)\r\n\t+ \", \" + roundNumber(_cell.c) + \", \" + roundNumber(alpha) + \", \"\r\n\t+ roundNumber(beta) + \", \" + roundNumber(gamma) + \"];\"\r\n\t+ 'var cellparam = cellp.join(\" \");' + 'var xyzfrac = '\r\n\t+ selectedFrame + '.label(\"%a %16.9[fxyz]\");'\r\n\t+ 'var lista = [cellparam, xyzfrac];'\r\n\t+ 'WRITE VAR lista \"?.XYZfrac\" ';\r\n\tsetV(x);\r\n}",
"function writeLocationCall(lat,long) {\n \n}",
"function saveToFile(nodes) {\n //Only keep the needed values\n var nodes_minimal = [];\n nodes.forEach(function (d) {\n nodes_minimal.push({\n id: d.id,\n community: d.community,\n degree: d.degree,\n x_fixed: roundTo(d.x_fixed, 2),\n y_fixed: roundTo(d.y_fixed, 2)\n });\n }); //forEach\n\n var graph = _babel_runtime_corejs2_core_js_json_stringify__WEBPACK_IMPORTED_MODULE_3___default()(nodes_minimal);\n\n var file = new Blob([graph], {\n type: 'text/plain'\n });\n var a = document.createElement('a');\n a.href = URL.createObjectURL(file);\n a.download = 'constellation-node-locations.json';\n a.click();\n } //function saveToFile",
"function writeN() {\n var file = require(\"Storage\").open(\"choozi.txt\",\"w\");\n file.write(N);\n}",
"function saveCell(x, y)\n{\n var nname = dname + \"_\" + (x + 0) + \"_\" + (y + 0);\n\n doc.exportDocument (new File(dir + \"/\" + nname + \".png\"), ExportType.SAVEFORWEB, options);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the file browser | openFileBrowser(){
$(this.refs.image).click();
} | [
"openFileBrowser() {\n // Open the upload file browser\n\t\tthis.refs.inputFile.click();\n }",
"openFileBrowser() {\n this.$refs.files.click();\n }",
"function openFileChooser() {\n fileRef.current.click();\n }",
"exploreFile(fileHash) {\n if (fileHash) {\n const ipfsPath = \"https://ipfs.io/ipfs/:hash\".replace(\":hash\", fileHash); \n window.open(ipfsPath, \"_blank\");\n }\n }",
"open() {\n\t\tlocalStorage.setItem('target_input', this.getElement().dataset.filemanagerInput);\n\t\tlocalStorage.setItem('target_preview', this.getElement().dataset.filemanagerPreview);\n\t\twindow.open('/laravel-filemanager?type=' + this.resolveType(), 'FileManager', 'width=900,height=900');\n\t}",
"openFileBrowser() {\n dialog.showOpenDialog(\n { properties: [\"openDirectory\"] },\n this.configureProject\n );\n }",
"open(url) {\n let command;\n switch (process.platform) {\n case 'darwin':\n command = 'open';\n break;\n case 'win32':\n command = 'explorer.exe';\n break;\n case 'linux':\n command = 'xdg-open';\n break;\n default:\n error('Can not open browser');\n return;\n }\n spawn(command, [url]);\n }",
"function open_file_function(evt) {\n // print_both('From gui_example.js sending a request to main.js via ipc');\n // ipc.send('open_json_file');\n\n var path = open_file_path;\n //handle for different os \n //if (macOS) { path = './' }\n //if (linux) { }\n\n openExplorer(path, err => {\n if (err) {\n log_error(\"ELECTRON: Error requesting OS to open a file explorer to recording archive: \" + err);\n }\n else {\n //Do Something\n }\n });\n}",
"open() {\n browser.url(this.url);\n }",
"open() {\n browser.url(this.url);\n }",
"function openFileDialog() {\n \n // Simulate a click on the actual file input.\n $('#file-input').click()\n}",
"function openFileExplorerWhite() {\n var input = document.getElementById(\"inputFileWhite\");\n input.click();\n}",
"function openFile(filepath) {\n\n // Open file\n var fid = fm.open(filepath);\n var file = fm.getFile(fid);\n\n // If the file exists\n if(fid != undefined) {\n\n // Create a new tab if this file has not already been opened\n pm.registerTab(fid, file);\n pm.renderTab(fid, file);\n\n // Add event listeners to tab\n addTabEventListeners(fid);\n\n // Mark this tab as active\n tabActive(fid);\n\n // Let this tab be annotated\n enableTabAnnotations(fid);\n\n // Log opened file\n console.log(\"Opened: \" + fm.getFilename(fid));\n\n // Switch to this file if it is already open\n } else {\n fm.files.forEach(function(el, i, arr) {\n if(fm.getFilepath(i) == filepath) tabActive(i);\n });\n }\n}",
"open() {\n browser.url(this.url);\n }",
"function openUploader() {\n\tif (!uploader) {\n\t\tinitUploader();\n\t}\n\tuploader.onchange = readUploader;\n\tuploader.click();\n}",
"function openFile() {\n dialog.showOpenDialog(\n {\n properties: [\"openFile\"],\n filters: [{ name: \"Warc\", extensions: [\"gz\", \"warc\", \"arc\", \"warcgz\", \"har\"] }]\n },\n function(filename) {\n if (filename && filename.toString().match(/\\.w?arc(\\.gz)?|\\.har$/)) {\n ipcRenderer.send(\"open-warc\", filename.toString());\n } else if (filename) {\n window.alert(\"Sorry, only WARC or ARC files (.warc, .warc.gz, .arc, .arc.gz) or HAR (.har) can be opened\");\n }\n }\n );\n}",
"openFile(filename) {\n let pane = new FilePane(filename);\n this.addPane(pane);\n return pane.openFile();\n }",
"open () {\n const askFilepath = () => {\n const filepath = dialog.showOpenDialog(this.win, {\n title: translate(\"dialog-open\"),\n properties: ['openFile'],\n defaultPath: this.defaultPath\n });\n return filepath[0];\n };\n const filepath = askFilepath();\n if (!filepath) {\n return Promise.resolve(false);\n }\n return this.load(filepath);\n }",
"function viewHtml() {\n var entry = ProjectManager.getSelectedItem();\n if (entry === undefined) {\n entry = DocumentManager.getCurrentDocument().file;\n }\n var path = entry.fullPath;\n var w = window.open(path);\n w.focus();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Functions that roll a stat and determines the modifier and puts them into a box | function statOne() {
var finalStatOne = statNumber()
var finalMod = modifier(finalStatOne)
firstStat.textContent = finalStatOne;
modOne.textContent = finalMod;
rollButton1.style.display = "none";
counter++
counterCheck()
} | [
"function updateModifiers(){\r\n\r\n\t\t\tdocument.getElementById(\"strModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"strTotal\").textContent))); \r\n\t\t\tdocument.getElementById(\"dexModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"dexTotal\").textContent)));\r\n\t\t\tdocument.getElementById(\"staModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"staTotal\").textContent)));\r\n\t\t\tdocument.getElementById(\"intModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"intTotal\").textContent)));\r\n\t\t\tdocument.getElementById(\"wisModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"wisTotal\").textContent)));\r\n\t\t\tdocument.getElementById(\"chaModifier\").textContent = addPlus(getModFromStat(parseInt(document.getElementById(\"chaTotal\").textContent)));\r\n\t\t}",
"function getModifier(stat){\n\n\tif(stat > 30)\n\t\tstat = 30;\n\tif(stat < 0)\n\t\tstat = 0;\n\n\tvar mod = Math.floor((stat-10)/2);\n\n\treturn mod;\n}",
"function stat_modifier_generator(stat) {\r\n if (3 >= stat) {\r\n statModifier = -4;\r\n } else if (5 >= stat) {\r\n statModifier = -3;\r\n } else if (7 >= stat) {\r\n statModifier = -2;\r\n } else if (9 >= stat) {\r\n statModifier = -1;\r\n } else if (11 >= stat) {\r\n statModifier = 0;\r\n } else if (13 >= stat) {\r\n statModifier = 1;\r\n } else if (15 >= stat) {\r\n statModifier = 2;\r\n } else if (17 >= stat) {\r\n statModifier = 3;\r\n } else if (19 >= stat) {\r\n statModifier = 4;\r\n } else if (20 >= stat) {\r\n statModifier = 5;\r\n }\r\n return statModifier;\r\n}",
"function createStatBox() {\n\t//grab the area to work with\n\tvar stat_div = document.getElementById('statDisplay');\n\t//need a player line display\n\tstat_div.innerHTML = \"<div id='line_assignment'> </div>\"; //player line assignment will go here\n\t\n\t//need a player stat display\n\tvar traits = skills;\n\tvar player_stats = \"<div id='player_stats'><table cellpadding='0'><tr>\";\n\tplayer_stats += \"<td>POS</td><td>HD</td>\";\n\tfor (var i=0; i<traits.length; ++i){\n\t\tplayer_stats += \"<td>\"+traits[i]+\"</td>\";\n\t}\n\tplayer_stats += \"</tr>\";\n\tplayer_stats += \"<tr>\";\n\tplayer_stats += \"<td><input type='text' readonly='readonly' name='player.POS' id='player.POS' size='3'</td></td><td><input type='text' readonly='readonly' name='player.HD' id='player.HD' size='3'</td></td>\";\n\tfor (var i=0; i<traits.length; ++i){\n\t\tplayer_stats += \"<td><input type='text' readonly='readonly' name='player.\"+traits[i]+\"' id='player.\"+traits[i]+\"' size='2'</td>\";\n\t}\n\tplayer_stats += \"</tr>\";\n\t\n\t//need a line average (merged with above to perserve spacing)\n\tplayer_stats += \"<tr><td> </td><td> </td>\";\n\tfor (var i=0; i<traits.length; ++i){\n\t\tplayer_stats += \"<td>\"+traits[i]+\"</td>\";\n\t}\n\tplayer_stats += \"</tr>\";\n\tplayer_stats += \"<tr>\";\n\tplayer_stats += \"<td colspan='2'>Line Average</td>\";\n\tfor (var i=0; i<traits.length; ++i){\n\t\tplayer_stats += \"<td><input type='text' readonly='readonly' name='avg.\"+traits[i]+\"' id='avg.\"+traits[i]+\"' size='2'</td>\";\n\t}\n\tplayer_stats += \"</tr></table></div>\";\n\t\n\t//print it all\n\tstat_div.innerHTML += player_stats;\n\tstat_div.innerHTML += \"<br/><br/>\";\n}",
"function addStat(event, stat) {\n\tvar points = 1\n\tif (event.shiftKey) { points = 10 }\n\tif (event.ctrlKey) { points = 100 }\n\tif (character.statpoints < points) { points = character.statpoints }\n\tif (character.statpoints >= points) {\n\t\tif (stat == \"btn_strength\") {\t\tcharacter.strength += points;\tcharacter.strength_added += points; }\n\t\telse if (stat == \"btn_dexterity\") {\tcharacter.dexterity += points;\tcharacter.dexterity_added += points; }\n\t\telse if (stat == \"btn_vitality\") {\tcharacter.vitality += points;\tcharacter.vitality_added += points; }\n\t\telse if (stat == \"btn_energy\") {\tcharacter.energy += points;\tcharacter.energy_added += points; }\n\t\tcharacter.statpoints -= points\n\t\tupdateAllEffects()\n\t}\n}",
"function newLevel() {\n text = \"Level \" + (level + 1);\n textAlpha = 1.0;\n createAsteroidBelt();\n}",
"function returnAbilityScoreModifier(stat) {\n //Math.sign() will add +/-\n return Math.floor((stat - 10) / 2);\n}",
"function updateDice(){\r\n var grandTotal = 0, linebreak;\r\n for (var i = 0; i < dice.length; i++){\r\n document.getElementById(dice[i].name + 'Total').innerHTML=dice[i].total;\r\n \r\n // document.getElementById(dice[i].name + 'Quantity').innerHTML=dice[i].qty;\r\n // Set text of individual roll buttons \r\n // document.getElementById(dice[i].name + 'Roll').innerHTML='Roll ' + dice[i].qty+dice[i].name; \r\n if(dice[i].modifier > 0){\r\n document.getElementById(dice[i].name + 'Roll').innerHTML='Roll ' +dice[i].qty+dice[i].name + '+'+dice[i].modifier;\r\n } else if (dice[i].modifier <0){\r\n document.getElementById(dice[i].name + 'Roll').innerHTML='Roll ' + dice[i].qty+dice[i].name +dice[i].modifier;\r\n } else {\r\n document.getElementById(dice[i].name + 'Roll').innerHTML='Roll ' + dice[i].qty+dice[i].name;\r\n }\r\n\r\n\r\n\r\n //set critHit and critMiss values\r\n var hit = document.getElementById(dice[i].name + 'CritHit');\r\n if (dice[i].critHits===0){\r\n hit.innerHTML = '';\r\n } else {\r\n hit.innerHTML = dice[i].critHits;\r\n }\r\n\r\n var miss = document.getElementById(dice[i].name + 'CritMiss');\r\n if (dice[i].critMiss===0){\r\n miss.innerHTML = '';\r\n } else {\r\n miss.innerHTML = dice[i].critMiss; \r\n }\r\n\r\n\r\n\r\n //modify crit hit/miss box colors \r\n if (dice[i].critHits >0){\r\n hit.style.background= 'lightblue';\r\n hit.style.color = 'white';\r\n hit.style.border = '1px solid white'\r\n } else {\r\n hit.style.background= 'black';\r\n hit.style.color = 'lightblue';\r\n hit.style.border = '1px solid lightblue'\r\n }\r\n\r\n if (dice[i].critMiss >0){\r\n miss.style.background= 'red';\r\n miss.style.color = 'black';\r\n miss.style.border = '1px solid black'\r\n } else {\r\n miss.style.background= 'black';\r\n miss.style.color = 'lightblue';\r\n miss.style.border = '1px solid lightblue'\r\n }\r\n\r\n //increase grand total \r\n grandTotal += dice[i].total;\r\n //set modifier value \r\n // document.getElementById(dice[i].name + 'Mod').innerHTML = dice[i].modifier;\r\n }\r\n document.getElementById('allResults').innerHTML =grandTotal;\r\n document.getElementById('d2Total').innerHTML = dice[0].total;\r\n\r\n}",
"function Health_Armor(){\n\n //------------------------------\n //Variable\n //------------------------------\n var me = Entity.GetLocalPlayer();\n var health = Entity.GetProp(me,\"CBasePlayer\", \"m_iHealth\");\n var armor = Entity.GetProp(Entity.GetLocalPlayer(), \"CCSPlayerResource\", \"m_iArmor\");\n var Armor_text = \"\" + armor;\n var Health_text = \"\" + health;\n var x = UI.GetValue([\"Visuals\", \"Cyberpunk\", \"Cyberpunk\", \"Health_Armor_X\"]);\n var y = UI.GetValue([\"Visuals\", \"Cyberpunk\", \"Cyberpunk\", \"Health_Armor_Y\"]);\n //------------------------------\n //Render\n //------------------------------\n\n if(health == \"m_iHealth\" || armor == \"m_iArmor\"){\n Health_text = \"0\";\n Armor_text = \"0\";\n }\n\n if(iAlpha > 1){\n iAlpha--;\n }\n\n if(getExp > Levelexp){\n getExp = 0;\n Level ++;\n Levelexp = Levelexp + 2;\n }\n\n //Shadows\n Render.FilledRect( x+40, y+12, 223, 10, [ 155, 51, 47, 102 ]);\n if(health <=100){\n Render.FilledRect( x+40, y+12, (health * 2.23), 10, [ 234, 89, 82, 102 ]);\n }else{\n Render.FilledRect( x+40, y+12, 223, 10, [ 234, 89, 82, 102 ]);\n } \n Render.FilledRect( x+40, y+6, 223, 3, [ 47, 81, 79, 102 ]);\n Render.FilledRect( x+40, y+6, (armor * 2.23), 3, [ 139, 200, 191, 102 ]);\n Render.String( x+280, y+13, 0, Health_text, [222, 79, 70, 102], def_font(25));\n if(health <=1000){\n Render.String( x+320, y+9, 0, Armor_text, [139, 200, 191, 102], def_font(19));\n }else{\n Render.String( x+330, y+9, 0, Armor_text, [139, 200, 191, 102], def_font(19));\n }\n Render.FilledRect(x+6, y+6, 2, 21, [59, 153, 163, 102]);\n Render.FilledRect(x+32, y+6, 2, 27, [59, 153, 163, 102]);\n Render.FilledRect(x+6, y+6, 27, 2, [59, 153, 163, 102]);\n Render.FilledRect(x+16, y+33, 18, 2, [59, 153, 163, 102]);\n Render.Line( x+6, y+26, x+15, y+34, [59, 153, 163, 102]);\n Render.Line( x+7, y+26, x+16, y+34, [59, 153, 163, 102]);\n\n\n //Display Health\n Render.FilledRect( x+34, y+6, 223, 10, [ 155, 51, 47, 255 ]); //Health Background Color\n\n if(health <=100){\n Render.FilledRect( x+34, y+6, (health * 2.23), 10, [ 234, 89, 82, 255 ]);\n }else{\n Render.FilledRect( x+34, y+6, 223, 10, [ 234, 89, 82, 255 ]);\n } \n\n //Display Armor\n Render.FilledRect( x+34, y, 223, 3, [ 47, 81, 79, 255 ]); //Armor Background Color\n Render.FilledRect( x+34, y, (armor * 2.23), 3, [ 139, 200, 191, 255 ]); //Armor Color\n\n //Display Remaining Health and Armor\n Render.String( x+274, y+7, 0, Health_text, [222, 79, 70, 255], def_font(25));//Remaining Health\n\n if(health <=1000){\n Render.String( x+314, y+3, 0, Armor_text, [139, 200, 191, 255], def_font(19));\n }else{\n Render.String( x+324, y+3, 0, Armor_text, [139, 200, 191, 255], def_font(19));\n }\n\n //Level Framework\n Render.FilledRect(x, y, 2, 21, [59, 153, 163, 255]);//Left\n Render.FilledRect(x+26, y, 2, 27, [59, 153, 163, 255]);//Right\n Render.FilledRect(x, y, 27, 2, [59, 153, 163, 255]);//Top\n Render.FilledRect(x+10, y+27, 18, 2, [59, 153, 163, 255]);//Bottom\n Render.Line( x, y+20, x+9, y+28, [59, 153, 163, 255]);//Angled\n Render.Line( x+1, y+20, x+10, y+28, [59, 153, 163, 255]);//Angledx2\n\n //Display Level\n Render.String( x+14, y+5, 1, \"\"+Level, [139, 200, 191, 255], def_font(17));\n Render.String( x+34 , y+21, 0, 'You Kill Player! Get 1 Exp! ', [139, 200, 191, iAlpha], def_font(17)); \n\n //BetterUI and Better Colors API\n //Create dragging properties.\n const window_area = area.new(x, y, 200, 32);\n const mouse_pos = point.new(Input.GetCursorPosition()[0], Input.GetCursorPosition()[1]);\n if (Input.IsKeyPressed(1) && UI.IsMenuOpen())\n {\n if (area.in_bounds(window_area, mouse_pos))\n {\n UI.SetValue([\"Visuals\", \"Cyberpunk\", \"Cyberpunk\", \"Health_Armor_X\"], mouse_pos.x - 100);\n UI.SetValue([\"Visuals\", \"Cyberpunk\", \"Cyberpunk\", \"Health_Armor_Y\"], mouse_pos.y - 10);\n }\n }\n\n //Check Localplayer\n if (!Entity.IsValid(Entity.GetLocalPlayer())) return;\n\n}",
"statEffect(target, statName, stageChange, chance = 100) {\n if (chance == null) {\n chance = 100;\n }\n let cutoff = Math.floor(Math.random() * 100);\n if (chance >= cutoff && \"mist\" in target.status == false) {\n if (statName == \"Attack\") {\n var stat = target.attack;\n }\n else if (statName == \"Defense\") {\n var stat = target.defense;\n }\n else if (statName == \"Special Attack\") {\n var stat = target.specialAttack;\n }\n else if (statName == \"Special Defense\") {\n var stat = target.specialDefense;\n }\n else if (statName == \"Speed\") {\n var stat = target.speed;\n }\n else if (statName == \"Evasion\") {\n var stat = target.evasion;\n }\n else {\n return \"Invalid Stat\";\n } \n \n // Check that stage value is between -6 and 6\n stat[1] += stageChange;\n if (stat[1] < -6) {\n stat[1] = -6;\n }\n else if (stat[1] > 6) {\n stat[1] = 6;\n }\n\n // Determine multiplier based on stage value\n if (stat[1] == -6) {\n stat[0] = Math.floor(stat[2] * 25 / 100);\n }\n else if (stat[1] == -5) {\n stat[0] = Math.floor(stat[2] * 28 / 100);\n }\n else if (stat[1] == -4) {\n stat[0] = Math.floor(stat[2] * 33 / 100);\n }\n else if (stat[1] == -3) {\n stat[0] = Math.floor(stat[2] * 40 / 100);\n }\n else if (stat[1] == -2) {\n stat[0] = Math.floor(stat[2] * 50 / 100);\n }\n else if (stat[1] == -1) {\n stat[0] = Math.floor(stat[2] * 66 / 100);\n }\n else if (stat[1] == 0) {\n stat[0] = stat[2];\n }\n else if (stat[1] == 1) {\n stat[0] = Math.floor(stat[2] * 150 / 100);\n }\n else if (stat[1] == 2) {\n stat[0] = Math.floor(stat[2] * 200 / 100);\n }\n else if (stat[1] == 3) {\n stat[0] = Math.floor(stat[2] * 250 / 100);\n }\n else if (stat[1] == 4) {\n stat[0] = Math.floor(stat[2] * 300 / 100);\n }\n else if (stat[1] == 5) {\n stat[0] = Math.floor(stat[2] * 350 / 100);\n }\n else if (stat[1] == 6) {\n stat[0] = Math.floor(stat[2] * 400 / 100);\n }\n let message = this.stageMessage(target, statName, stageChange);\n return message;\n }\n else {\n return \"\";\n }\n }",
"function drinkPotion() {\n // Adjust the hero's stat by the potion's modifier\n hero[currentPotion.stat] += currentPotion.mod;\n\n // If the stat becomes negative, set it to zero\n if (hero[currentPotion.stat] < 0) {\n hero[currentPotion.stat] = 0;\n }\n\n // Update the correct stat change area\n let spanId = \"#\" + currentPotion.stat + \"Change\";\n\n // How much did the stat change by?\n let changeText = currentPotion.mod;\n\n // Prepand a \"+\" in front of positive numbers\n if (changeText > 0) {\n changeText = \"+\" + changeText;\n }\n\n // Put the text in the span\n $(spanId).text(changeText);\n\n // Rehide the prompt area\n $(\"#prompt\").hide();\n\n\n // Update the screen with the drawHero function\n drawHero();\n}",
"function hitBox() {}",
"setPatrol () {\n if (this.alerted) {\n if (this.x > this.player.x) {\n this.shamble({ direction: 'left' });\n this.direction = 'left';\n } else {\n this.shamble({ direction: 'right' });\n this.direction = 'right';\n }\n } else {\n if (!this.behaviorDuration || this.behaviorDuration <= this.game.time.now) {\n // Set a duration for a new behavior\n this.behaviorDuration = this.game.time.now + 5000;\n // Stand when 0, walk when 1\n this.behavior = Math.round(Math.random());\n // Walk left when 0, walk right when 1\n this.direction = Math.round(Math.random()) === 0 ? 'left' : 'right';\n }\n if (this.behaviorDuration > this.game.time.now) {\n if (this.behavior === 1) {\n if (this.direction === 'left') {\n this.shamble({ direction: 'left' });\n } else {\n this.shamble({ direction: 'right' });\n }\n } else {\n this.frameName = 'idle';\n }\n }\n }\n }",
"function passLevel () {\n\n // draw prompt box with a transparent fill\n\n ctx.rect(40, 100, 430, 300);\n ctx.fillStyle = \"rgba(0,0,0,0.75)\";\n ctx.fill();\n\n // set number to reflect level passed\n\n var displayLevel = player.level -1;\n\n // set content, text style, colour, and size\n\n ctx.font = \"50px Impact\";\n ctx.fillStyle = \"yellow\";\n ctx.fillText(\"YOU PASSED LEVEL\", 80, 170);\n\n // set content, text style, and size\n\n ctx.font = \"80px Impact\";\n ctx.fillText(displayLevel, 235, 260);\n\n // set content, text style, colour, and size\n\n ctx.font = \"40px Impact\";\n ctx.fillStyle = \"#7ACC52\";\n ctx.fillText(\"Press the Spacebar\", 95, 320);\n\n // set text size\n\n ctx.font = \"40px Impact\";\n\n // change words 'final' and 'next' depending on level passed\n\n if(player.level === 4) {\n\n ctx.fillText(\"for the FINAL level !\", 110, 365);\n\n } else {\n\n ctx.fillText(\"for the next level !\", 110, 365);\n\n }\n\n }",
"changeStat(stat, change, revert) {\n change = change / 100;\n switch(stat) {\n case 'strength':\n if(revert) {\n this.conditions.statReductions.strength += (100 - (100 * change));\n this.stats.strength /= change;\n }\n else {\n this.conditions.statReductions.strength -= (100 - (100 * change));\n this.stats.strength *= change;\n }\n case 'wisdom':\n if(revert) {\n this.conditions.statReductions.wisdom += (100 - (100 * change));\n this.stats.wisdom /= change;\n }\n else {\n this.conditions.statReductions.wisdom -= (100 - (100 * change));\n this.stats.wisdom *= change;\n }\n case 'defense':\n if(revert) {\n this.conditions.statReductions.defense += (100 - (100 * change));\n this.stats.defense /= change;\n }\n else {\n this.conditions.statReductions.defense -= (100 - (100 * change));\n this.stats.defense *= change;\n }\n case 'resilience':\n if(revert) {\n this.conditions.statReductions.resilience += (100 - (100 * change));\n this.stats.resilience /= change;\n }\n else {\n this.conditions.statReductions.resilience -= (100 - (100 * change));\n this.stats.resilience *= change;\n }\n case 'dexterity':\n if(revert) {\n this.conditions.statReductions.dexterity += (100 - (100 * change));\n this.stats.dexterity /= change;\n }\n else {\n this.conditions.statReductions.dexterity -= (100 - (100 * change));\n this.stats.dexterity *= change;\n }\n case 'evasion':\n if(revert) {\n this.conditions.statReductions.evasion += (100 - (100 * change));\n this.stats.evasion /= change;\n }\n else {\n this.conditions.statReductions.evasion -= (100 - (100 * change));\n this.stats.evasion *= change;\n }\n case 'maxHealth':\n if(revert) {\n this.conditions.statReductions.maxHealth += (100 - (100 * change));\n this.stats.maxHealth /= change;\n }\n else {\n this.conditions.statReductions.maxHealth -= (100 - (100 * change));\n this.stats.maxHealth *= change;\n }\n //Kept for potential % Health abilities (change > 100 for healing)\n case 'currentHealth':\n this.stats.currentHealth = this.stats.currentHealth * change;\n break;\n case 'luck':\n if(revert) {\n this.conditions.statReductions.luck += (100 - (100 * change));\n this.stats.luck /= change;\n }\n else {\n this.conditions.statReductions.luck -= (100 - (100 * change));\n this.stats.luck *= change;\n }\n break;\n case 'speed':\n if(revert) {\n this.conditions.statReductions.speed += (100 - (100 * change));\n this.stats.speed /= change;\n }\n else {\n this.conditions.statReductions.speed -= (100 - (100 * change));\n this.stats.speed *= change;\n }\n break;\n }\n }",
"function wrongHitMsg(hitEnemy)\r\n{\r\n if(hitEnemy.trashType == trash[0]){ //if textile\r\n var textileString = \"You're using the wrong weapon! Only 15% of used clothing in the USA is recycled, leaving landfills full of clothes that could've been recycled! Use the up/down keys to switch to the correct weapon.\";\r\n textBox.textContent = textileString;\r\n }\r\n else if(hitEnemy.trashType == trash[1]){ //else if recyclable\r\n textBox.textContent = \"You're using the wrong weapon! Improperly recycling prevents resources from being reused which hurts the enviroment! Use the up/down keys to switch to the correct weapon.\";\r\n }\r\n else if(hitEnemy.trashType == trash[2]){ //else if compose\r\n textBox.textContent = \"You're using the wrong weapon! Not composting leads to increased waste in landfills! Use the up/down keys to switch to the correct weapon.\";\r\n }\r\n else if(hitEnemy.trashType == trash[3]){ //else if landfill\r\n textBox.textContent = \"You're using the wrong weapon! Trash can contaminate other items being recycled or composted which compromises our sustainability mission! Use the up/down keys to switch to the correct weapon.\";\r\n }\r\n}",
"function GenerateStatblock() {\n if (!confirm(\"Generate Statblock will replace your current Statblock textfield with information from your character sheet.\\n\\nAre you sure to continue?\")) return;\n \n // Declares optional elements in the Statblock\n var pic = \"\";\n var dr = \"\";\n var armor1 = \"\";\n var armor2 = \"\";\n var armor3 = \"\";\n var armor4 = \"\";\n var ac = \"\";\n var actype = \"\";\n var w1 = \"\";\n var w2 = \"\";\n var w3 = \"\";\n var w1n = \"\";\n var w2n = \"\";\n var w3n = \"\";\n\n var finalStat = \"\"; // Output String.\n var statArray = new Array(); // Array of Information.\n statArray = [\n String(sheet().PicURL.value),\n String(sheet().Name.value), //01\n \"SheetURL\", // This is defined by a string separately.\n String(sheet().Gender.value),\n String(sheet().Alignment.value),\n String(sheet().Race.value), //05\n String(sheet().Class.value),\n String(sheet().Level.value),\n String(sheet().Init.value),\n String(sheet().HPWounds.value),\n String(sheet().HP.value), //10\n String(sheet().DamageRed.value),\n String(sheet().Armor1Name.value),\n String(sheet().Armor1Special.value),\n String(sheet().Armor2Name.value),\n String(sheet().Armor2Special.value), //15\n String(sheet().Armor3Name.value),\n String(sheet().Armor3Special.value),\n String(sheet().Armor4Name.value),\n String(sheet().Armor4Special.value),\n String(sheet().AC.value), //20\n String(sheet().ACArmor.value),\n String(sheet().ACShield.value),\n String(sheet().ACOther.value),\n String(sheet().ACDex.value),\n String(sheet().ACSize.value), //25\n String(sheet().ACDeflect.value),\n String(sheet().ACNat.value),\n String(sheet().ACMisc.value),\n String(sheet().Fort.value),\n String(sheet().Reflex.value), //30\n String(sheet().Will.value),\n String(sheet().Weapon1Special.value),\n String(sheet().Weapon1.value),\n String(sheet().Weapon1AB.value),\n String(sheet().Weapon1Damage.value), //35\n String(sheet().Weapon11Crit.value),\n String(sheet().Weapon1Ammo.value),\n String(sheet().Weapon2Special.value),\n String(sheet().Weapon2.value),\n String(sheet().Weapon2AB.value), //40\n String(sheet().Weapon2Damage.value),\n String(sheet().Weapon21Crit.value),\n String(sheet().Weapon2Ammo.value),\n String(sheet().Weapon3Special.value),\n String(sheet().Weapon3.value), //45\n String(sheet().Weapon3AB.value),\n String(sheet().Weapon3Damage.value),\n String(sheet().Weapon31Crit.value),\n String(sheet().Weapon3Ammo.value),\n String(sheet().Weapon4Special.value), //50\n String(sheet().Weapon4.value),\n String(sheet().Weapon4AB.value),\n String(sheet().Weapon4Damage.value),\n String(sheet().Weapon41Crit.value),\n String(sheet().Weapon4Ammo.value), //55\n String(sheet().MBAB.value),\n String(sheet().Str.value),\n String(sheet().Dex.value),\n String(sheet().Con.value),\n String(sheet().Int.value), //60\n String(sheet().Wis.value),\n String(sheet().Cha.value),\n String(sheet().StrTemp.value),\n String(sheet().DexTemp.value),\n String(sheet().ConTemp.value), //65\n String(sheet().IntTemp.value),\n String(sheet().WisTemp.value),\n String(sheet().ChaTemp.value),\n String(sheet().Speed.value),\n String(sheet().TouchAC.value), //70\n String(sheet().FFAC.value),\n String(sheet().text1.value), //This is Condition and Effects.\t\t\n String(sheet().text2.value), //This is Additional Info\n String(sheet().StrMod.value),\n String(sheet().DexMod.value),\t//75\n String(sheet().ConMod.value),\n String(sheet().IntMod.value),\n String(sheet().WisMod.value),\n String(sheet().ChaMod.value),\n String(sheet().Skill29Mod.value),\t//80\n String(sheet().Skill39Mod.value),\n String(sheet().Armor1Bonus.value),\n String(sheet().Armor2Bonus.value),\n String(sheet().Armor3Bonus.value),\n String(sheet().Armor4Bonus.value)];\t//85\t \t\n\n\n // ***** Produce the URL link of the character sheet.\t \n statArray[2] = \"http://www.4ibw.com/profiler/view.php?id=\" + String(sheet().id.value);\n\n // ***** Parse the information into individual parts. Checking for empty values. Clan some stats and prep them for Stat Block.\n\n // ***** Picture *****\n if (statArray[0] == \" \") pic = \"\";\n else pic = \"[IMGL]\" + statArray[0] + \"[/IMGL] \";\n\n // ***** Hit Points *****\n if (statArray[9] == \" \") statArray[9] = statArray[10];\n\n if (statArray[9] / statArray[10] < 0.5) chp = \"[COLOR='RED'][B] \" + statArray[9] + \"[/B][/COLOR]\";\n else {\n chp = \"[COLOR='GREEN'][B] \" + statArray[9] + \"[/B][/COLOR]\";\n }\n\n // ***** Damage Reduction *****\t\n\n if (statArray[11] == \" \") dr = \"\";\n else dr = \", [B]DR[/B] \" + statArray[11];\n\n // ***** Armor *****\t\t\n\n if (statArray[12] == \"\") armor1 = \"\";\n else {\n \tarmor1 = \"[B]Armor Slot 1:[/B] \" + statArray[13] + \" \" + statArray[12] + \" [B]AC Bonus:[/B] (\" + statArray[82] + \")\\n\";\n }\n\n if (statArray[14] == \"\") armor2 = \"\";\n else {\n \tarmor2 = \"[B]Armor Slot 2:[/B] \" + statArray[15] + \" \" + statArray[14] + \" [B]AC Bonus:[/B] (\" + statArray[83] + \")\\n\";\n }\n\n if (statArray[16] == \"\") armor3 = \"\";\n else {\n \tarmor3 = \"[B]Armor Slot 3:[/B] \" + statArray[17] + \" \" + statArray[16] + \" [B]AC Bonus:[/B] (\" + statArray[84] + \")\\n\";\n }\n\n if (statArray[18] == \"\") armor4 = \"\";\n else {\n \tarmor4 = \"[B]Armor Slot 4:[/B] \" + statArray[19] + \" \" + statArray[18] + \" [B]AC Bonus:[/B] (\" + statArray[85] + \")\\n\";\n }\n\n // ***** AC *****\t\t\n\n if (statArray[70] != \" \") statArray[70] = \", [B]Touch:[/B] \" + statArray[70];\n else statArray[70] = \"\";\n\n if (statArray[71] != \" \") statArray[71] = \", [B]Flat-footed:[/B] \" + statArray[71] + \" (\" + statArray[75] + \" Dex)\";\n else statArray[71] = \"\";\n\n // ***** Weapons *****\n\n if (statArray[37] != \" \") statArray[37] = \" (\" + statArray[37] + \") \";\n\n if (statArray[43] != \" \") statArray[43] = \" (\" + statArray[43] + \") \";\n\n if (statArray[49] != \" \") statArray[49] = \" (\" + statArray[49] + \") \";\n\n if (statArray[55] != \" \") statArray[55] = \" (\" + statArray[55] + \") \";\n\n w1n = String(statArray[32] + \" , \" + statArray[33] + statArray[37]);\n w2n = String(statArray[38] + \" , \" + statArray[39] + statArray[43]);\n w3n = String(statArray[44] + \" , \" + statArray[45] + statArray[49]);\n w4n = String(statArray[50] + \" , \" + statArray[51] + statArray[55]);\n\n if (statArray[33] == \"\") w1 = \"\";\n else {\n w1 = \"[B]Weapon Slot 1:[/B] \" + w1n + \"[B]Attack/Damage: [/B]\" + statArray[34] + \" (\" + statArray[35] + \", \" + statArray[36] + \")\\n\";\n }\n\n if (statArray[39] == \"\") w2 = \"\";\n else {\n w2 = \"[B]Weapon Slot 2:[/B] \" + w2n + \"[B]Attack/Damage: [/B]\" + statArray[40] + \" (\" + statArray[41] + \", \" + statArray[42] + \")\\n\";\n }\n\n if (statArray[45] == \"\") w3 = \"\";\n else {\n w3 = \"[B]Weapon Slot 3:[/B] \" + w3n + \"[B]Attack/Damage: [/B]\" + statArray[46] + \" (\" + statArray[47] + \", \" + statArray[48] + \")\\n\";\n }\n\n if (statArray[51] == \"\") w4 = \"\";\n else {\n w4 = \"[B]Weapon Slot 1:[/B] \" + w4n + \"[B]Attack/Damage: [/B]\" + statArray[52] + \" (\" + statArray[53] + \", \" + statArray[54] + \")\\n\";\n }\n\n // ***** Conditions and Additional Information *****\n\n if (statArray[72] != \" \") statArray[72] = \"[B]Conditions:[/B] \" + statArray[72] + \"\\n\";\n else {\n statArray[72] = \"[B]Conditions:[/B] None \\n\";\n }\n\n if (statArray[73] != \" \") statArray[73] = \"[B]Additional Information:[/B] \" + statArray[73] + \"\\n\";\n else {\n statArray[73] = \"[B]Additional Information:[/B] None \\n\";\n }\n\n // ***** Construct the Statblock *****\n\n finalStat = String(\n //pic + \n\t//\"[URL=\" + statArray[2] + \"][B][SIZE=+1]\" + statArray[1] + \"[/SIZE][/B][/URL]\\n\" + \n\t//statArray[3] + \" \" + statArray[4] + \" \" + statArray[5] + \" \" + statArray[6] + \", [B]Level:[/B] \" + statArray[7] + \", [B]Init:[/B] \" + statArray[8] + \", [B]HP:[/B] \" + chp + \"/\" + statArray[10] + dr + \", [B]Speed:[/B] \" + statArray[69] + \"\\n\" + \n\t//\"[B]AC:[/B] \" + statArray[20] + statArray[70] + statArray[71] + \", [B]Fort:[/B] \" + statArray[29] + \", [B]Ref:[/B] \" + statArray[30] + \", [B]Will:[/B] \" + statArray[31] + \", [B]Base Attack Bonus[/B] \" + statArray[56] + \"\\n\"\t+ \n\t//w1 + \n\t//w2 + \n\t//w3 + \n\t//w4 + \n\t//armor1 + \n\t//armor2 + \n\t//armor3 + \n\t//armor4 +\n //\"[B]Abilities:[/B] Str \" + statArray[57] + \", Dex \" + statArray[58] + \", Con \" + statArray[59] + \", Int \" + statArray[60] + \", Wis \" + statArray[61] + \", Cha \" + statArray[62] + \"\\n\" + \n\t//statArray[72] + \n\t//statArray[73]);\n\n\t\"[SPOILERBUTTON='Short Statblock for \" + statArray[1] + \"']\" + \"\\n\" + \n\t\"[FIELDSET='Quick Stats for \" + statArray[1] + \"']\" + pic + \"[URL=\" + statArray[2] + \"][B][SIZE=+1]\" + statArray[1] + \"[/SIZE][/B][/URL] \" + statArray[3] + \" \" + statArray[4] + \" \" + statArray[5] + \" \" + statArray[6] + \", [B]Level:[/B] \" + statArray[7] + \"\\n\" +\n\t\"[B]Abilities:[/B] Str \" + statArray[57] + \" (\" + statArray[74] + \")\" + \", Dex \" + statArray[58] + \" (\" + statArray[75] + \")\" + \", Con \" + statArray[59] + \" (\" + statArray[76] + \")\" + \", Int \" + statArray[60] + \" (\" + statArray[77] + \")\" + \", Wis \" + statArray[61] + \" (\" + statArray[78] + \")\" + \", Cha \" + statArray[62] + \" (\" + statArray[79] + \")\" + \n\t\"[hr][/hr]DEFENSE[hr][/hr]\" +\n\t\"[B]AC:[/B] \" + statArray[20] + statArray[70] + statArray[71] + \"\\n\" +\n\t\"[B]Skills:[/B] Listen (\" + statArray[80] + \") Spot (\" + statArray[81] + \") [B]Init:[/B] \" + statArray[8] + \" \" + \" [B]Speed:[/B] \" + statArray[69] + dr + \"\\n\" +\n\t\"[B]HP:[/B] \" + chp + \"/\" + statArray[10] + \"\\n\" +\n\t\"[B]Fort:[/B] \" + statArray[29] + \", [B]Ref:[/B] \" + statArray[30] + \", [B]Will:[/B] \" + statArray[31] + \"\\n\" + \n\tarmor1 + \n\tarmor2 + \n\tarmor3 + \n\tarmor4 +\n\t\"[hr][/hr]OFFENSE[hr][/hr]\" + \n\t\"[B]Base Attack Bonus[/B] \" + statArray[56] + \"\\n\"\t+\n\tw1 + \n\tw2 + \n\tw3 + \n\tw4 + \n\t\"[hr][/hr]NOTES[hr][/hr]\" + \n\tstatArray[72] + \n\tstatArray[73] +\n\t\"[/FIELDSET][/SPOILERBUTTON]\");\t\n\t\n // ***** Output the Statblock *****\n\n sheet().statsummary.value = finalStat;\n}",
"function updateTertiaryStats() {\n\tvar c = character;\n\tdocument.getElementById(\"poison_reduction\").innerHTML = Math.min(75,c.poison_length_reduced); if (c.poison_length_reduced > 0) { document.getElementById(\"poison_reduction\").innerHTML += \"%\" }\n\tdocument.getElementById(\"curse_reduction\").innerHTML = Math.min(75,c.curse_length_reduced); if (c.curse_length_reduced > 0) { document.getElementById(\"curse_reduction\").innerHTML += \"%\" }\n\tvar thorns = c.thorns_reflect;\n\tif (c.thorns_reflect == 0) { thorns = Math.floor(c.thorns_lightning + c.thorns + c.level*c.thorns_per_level) } else { thorns += \"%\"; if (c.thorns > 0 || c.thorns_per_level > 0) { thorns += (\" +\"+Math.floor(c.thorns_lightning + c.thorns + c.level*c.thorns_per_level)) } }\n\tdocument.getElementById(\"thorns\").innerHTML = thorns\n\tvar lightRadius = \"\";\n\tif (c.light_radius > 0) { lightRadius = \"+\"+c.light_radius + \" to Light Radius<br>\" } else if (c.light_radius < 0) { lightRadius = c.light_radius + \" to Light Radius<br>\" } else { lightRadius = \"\" }\n\tdocument.getElementById(\"light_radius\").innerHTML = lightRadius\n\tif (c.slower_stam_drain > 0) { document.getElementById(\"slower_stam_drain\").innerHTML = \"+\"+c.slower_stam_drain+\"% Slower Stamina Drain<br>\" } else { document.getElementById(\"slower_stam_drain\").innerHTML = \"\" }\n\tif (c.heal_stam > 0 || c.heal_stam_per_level > 0) { document.getElementById(\"heal_stam\").innerHTML = \"Heal Stamina +\" + Math.floor(c.heal_stam + c.level*c.heal_stam_per_level)+\"%<br>\" } else { document.getElementById(\"heal_stam\").innerHTML = \"\" }\n\tvar enemyDef = \"\";\n\tif (c.enemy_defense != 0 || c.target_defense != 0) { enemyDef += (Math.min(99,(c.enemy_defense + c.target_defense))+\"%\"); if (c.enemy_defense_flat != 0 || c.monster_defense_per_hit != 0) { enemyDef += \", \" } }\n\tif (c.enemy_defense_flat != 0) { enemyDef += c.enemy_defense_flat; if (c.monster_defense_per_hit != 0) { enemyDef += \", \" } }\n\tif (c.monster_defense_per_hit != 0) { enemyDef += (c.monster_defense_per_hit+\" per hit\") }\n\tif (enemyDef == \"\") { enemyDef = \"0\"}\n\tdocument.getElementById(\"enemy_defense\").innerHTML = enemyDef\n\tvar enemyBlind = \"\";\n\tif (c.blind_on_hit > 0) { enemyBlind = \"Hit Blinds Target\"; if (c.blind_on_hit > 1) { enemyBlind += (\" +\"+c.blind_on_hit+\"<br>\"); } else { enemyBlind += \"<br>\" } }\n\tdocument.getElementById(\"blind_on_hit\").innerHTML = enemyBlind\n\tif (c.flee_on_hit > 0) { document.getElementById(\"flee_on_hit\").innerHTML = \"Hit Causes Monster to Flee \" + Math.min(100,c.flee_on_hit) + \"%<br>\" } else { document.getElementById(\"flee_on_hit\").innerHTML = \"\" }\n\tif (c.discount > 0) { document.getElementById(\"discount\").innerHTML = \"Vendor Prices Reduced by \" + c.discount + \"%<br>\" } else { document.getElementById(\"discount\").innerHTML = \"\" }\n\t\n\tif (c.itd > 0) { document.getElementById(\"itd\").innerHTML = \"Ignore Target Defense<br>\" } else { document.getElementById(\"itd\").innerHTML = \"\" }\n\tif (c.pmh > 0) { document.getElementById(\"pmh\").innerHTML = \"Prevent Monster Heal<br>\" } else { document.getElementById(\"pmh\").innerHTML = \"\" }\n\tif (c.cbf > 0) { document.getElementById(\"cbf\").innerHTML = \"Cannot Be Frozen<br>\" }\n\telse if (c.half_freeze > 0) { document.getElementById(\"cbf\").innerHTML = \"Half Freeze Duration<br>\" }\n\telse { document.getElementById(\"cbf\").innerHTML = \"\" }\n\tif (c.knockback > 0) { document.getElementById(\"knockback\").innerHTML = \"Knockback<br>\" } else { document.getElementById(\"knockback\").innerHTML = \"\" }\n\tif (c.melee_splash > 0) { document.getElementById(\"melee_splash\").innerHTML = \"Melee Attacks deal Splash Damage<br>\" } else { document.getElementById(\"melee_splash\").innerHTML = \"\" }\n\tif (c.slows_target > 0 || c.slow_enemies > 0) { document.getElementById(\"slow_target\").innerHTML = \"Targets Slowed \" + (c.slows_target + c.slow_enemies)+\"%<br>\" } else { document.getElementById(\"slow_target\").innerHTML = \"\" }\n\tif (c.freezes_target > 1) { document.getElementById(\"freezes_target\").innerHTML = \"Freezes Target +\" + c.freezes_target + \"<br>\" }\n\telse if (c.freezes_target > 0) { document.getElementById(\"freezes_target\").innerHTML = \"Freezes Target<br>\" }\n\telse { document.getElementById(\"freezes_target\").innerHTML = \"\" }\n\tif (c.peace > 0) { document.getElementById(\"peace\").innerHTML = \"Slain Monsters Rest in Peace<br>\" } else { document.getElementById(\"peace\").innerHTML = \"\" }\n\tif (c.glow > 0) { document.getElementById(\"glow\").innerHTML = \"Character is Glowing<br>\" } else { document.getElementById(\"glow\").innerHTML = \"\" }\n\tvar statlines = \"\";\n\tif (c.fade > 0) { statlines += \"Character is Faded<br>\" }\n\tif (c.all_skills_ember > 0) { statlines += \"+\"+c.all_skills_ember+\" to All Skills when 5 Ember Charges are active<br>\" }\n\tif (c.bonus_sanctuary_rate > 0) { statlines += \"+\"+c.bonus_sanctuary_rate+\"% Increased Sanctuary Area Damage Rate<br>\" }\n\tif (c.summon_damage > 0) { statlines += \"Summons deal +\"+c.summon_damage+\"% Increased Damage<br>\" }\n\tif (c.summon_defense > 0) { statlines += \"Summons have +\"+c.summon_defense+\"% Enhanced Defense<br>\" }\n\tif (c.bonus_corpse_explosion > 0) { statlines += \"Corpse Explosion deals +\"+c.bonus_corpse_explosion+\"% of Maximum Corpse life<br>\" }\n\tif (c.phys_Lightning_Surge > 0) { statlines += \"Lightning Surge Deals \"+c.phys_Lightning_Surge+\"% Extra Damage As Physical<br>\" }\n\tif (c.extraValkyrie > 0) { statlines += \"Can Summon One Additional Valkyrie<br>\" }\n\tif (c.extraGrizzly > 0) { statlines += \"Can Summon One Additional Grizzly Bear<br>\" }\n\tif (c.extraFireGolem > 0) { statlines += \"Can Summon One Additional Fire Golem<br>\" }\n\tif (c.extraHydra > 0) { statlines += \"Can Summon One Additional Hydra<br>\" }\n\tif (c.radius_FreezingArrow > 0) { statlines += \"+\"+c.radius_FreezingArrow+\"% to Freezing Arrow Radius<br>\" }\n\tif (c.explosive_attack > 0) { statlines += \"Fires Explosive Arrows or Bolts<br>\" }\n\tif (c.magic_attack > 0) { statlines += \"Fires Magic Arrows<br>\" }\n\tif (c.reset_cooldown_on_kill > 0) { statlines += c.reset_cooldown_on_kill+\"% Chance to Reset Skill Cooldown on Kill<br>\" }\n\tif (c.cdr_on_striking > 0) { statlines += \"Gain \"+c.cdr_on_striking+\"% Reduced Skill Cooldown For 4 Seconds On Striking<br>\" }\n\tif (c.reanimate > 0) { statlines += c.reanimate+\"% Reanimate As: Returned<br>\" }\n\tif (c.half_Battle_Orders > 0 && c.class_name != \"Barbarian\") { statlines += \"Battle Order's life and mana bonuses are halved<br>\" }\n\tif (c.extra_Bone_Spears > 0) { statlines += \"Bone Spear fires \"+c.extra_Bone_Spears+\" Additional Projectiles<br>\" }\n\tif (c.extra_conversion_Magic_Arrow > 0) { statlines += \"+\"+c.extra_conversion_Magic_Arrow+\"% Magic Arrow Damage Converted to Magic<br>\" }\n\tif (c.extra_arrows_Ice_Arrow > 0) { statlines += \"Ice Arrow fires \"+c.extra_arrows_Ice_Arrow+\" Additional Arrows<br>\" }\n\tif (c.extra_arrows_Cold_Arrow > 0) { statlines += \"Cold Arrow fires \"+c.extra_arrows_Cold_Arrow+\" Additional Projectiles<br>\" }\n\tif (c.extra_arrows_Magic_Arrow > 0) { statlines += \"Magic Arrow fires \"+c.extra_arrows_Magic_Arrow+\" Additional Arrows<br>\" }\n\tif (c.extra_arrows_Fire_Arrow > 0) { statlines += \"Fire Arrow fires \"+c.extra_arrows_Fire_Arrow+\" Additional Arrows<br>\" }\n\tif (c.experience > 0) { statlines += \"+\"+c.experience+\"% Experience Gained<br>\" }\n\tif (c.ctc_temp1 > 0) { statlines += \"10% chance to cast level 15 Nova on striking<br>\" }\n\tif (c.ctc_temp2 > 0) { statlines += \"25% chance to cast level 5 Static Field when struck<br>\" }\n\tdocument.getElementById(\"statlines\").innerHTML = statlines\n\tupdateCTC()\n\tupdateChargeSkills()\n}",
"function getModifier(adventure)\r\n{\r\n\tvar modifier = 0;\r\n\t\r\n\tmodifier += victoryStat;\r\n\t\r\n\tif (arrAdventureLewd[adventure] == 1) // Negative stat applies penalty if relevant, small bonus if not relevant\r\n\t\tmodifier -= getStat('lewd');\r\n\telse\r\n\t\tmodifier += getStat('lewd') / 4;\r\n\t\r\n\tif (arrAdventureMight[adventure] == 1) // Positive stat applies bonus if relevant, small penalty if not relevant\r\n\t\tmodifier += getStat('might');\r\n\telse\r\n\t\tmodifier -= getStat('might') / 4;\r\n\t\r\n\treturn modifier;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this takes the first array of words and calculates the number of unique words by looping through the array and creating a new array of words that dont already exist in the new array. | function uniqueWordsFunc(wordArray2){
var uniqueArray = [];
for (var i = 0; i<wordArray2.length; i=i+1) {
if (uniqueArray.indexOf(wordArray2[i]) == -1) {
uniqueArray.push(wordArray2[i]);
}
}
var numUWords = uniqueArray.length;
uniqueAnswer(numUWords);
} | [
"function countUniqueWords(array) {\n var uniqueWordsCounter = 0;\n for (i=0; i<array.length; i++) {\n if (array[i] !== array[i+1]) {\n uniqueWordsCounter++;\n }\n };\n return uniqueWordsCounter;\n}",
"function uniqueWordsCount(text) {\n // split text into an array\n var words = text.split(/\\s+/);\n // create an empty temp array \n var temp = [];\n // loop through array of words\n for (var i = 0; i < words.length; i++) {\n // check if the word is in the temp array\n var findResult = temp.find(function(word) {\n return word === words[i];\n });\n // add missing word to temp array\n if(findResult === undefined) {\n temp.push(words[i]);\n }\n }\n // return length of temp array\n return temp.length;\n}",
"function findUnique(wordsArr) {}",
"function getUniqueWordCount(words){\n\n\tvar uniqueWords = [];\n\tfor (var i=0; i < words.length; i++){\n\t\tif (words[i] !== \"\" && \n\t\t\tuniqueWords.indexOf(words[i]) === -1){\n\t\t\tuniqueWords.push(words[i])\n\t\t}\n\t}\n\treturn uniqueWords.length;\n\n}",
"function uniqueWordCount(arr) {\n\t\t\t// create a word dictionary with counts of unique words\n\t\t\tvar wordDict = {};\n\t\t\tfor (var n=1; n<arr.length; n++) {\n\t\t\t\tif (arr[n] in wordDict) {\n\t\t\t\t\twordDict[arr[n]] += 1;\n\t\t\t\t} else {\n\t\t\t\t\twordDict[arr[n]] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// delete this superfluous value at start of hash\n\t\t\tdelete wordDict[\"\"]; \n\n\t\t\tconsole.log(wordDict);\n\n\t\t\treturn Object.keys(wordDict).length;\n\t\t} // end of uniqueWordCount() function",
"function uniqueWordCount(scrubbedText) {\n var uniqueWords = [];\n for (i = 0; i < scrubbedText.length; i++) {\n if (uniqueWords.indexOf(scrubbedText[i]) === -1) {\n uniqueWords.push(scrubbedText[i]);\n } \n }\n return uniqueWords.length;\n}",
"function findUnique(wordsArr) {\n //\n if(wordsArr.length < 1 || wordsArr == undefined)\n return false\n \n function howManyTimes (arr, word) {\n let count = 0;\n\n for(let el of arr){\n if(el === word) \n count ++\n }\n return count\n\n }\n const result = wordsArr.map((Oneword) => {\n return howManyTimes(wordsArr, Oneword) \n }).indexOf(1)\n\n let wordFinal = wordsArr[result];\n\n return wordFinal\n\n}",
"function uniques(words) {\r\n let uniquewords = [];\r\n for(let i=0; i<words.length;i++) {\r\n if(!uniquewords.includes(words[i]))\r\n uniquewords.push(words[i]);\r\n }\r\n return uniquewords;\r\n}",
"function findUnique(wordsArr) {\n //\n}",
"function uniqueFinder(){\n var unique = {};\n for(i = 0; i < wordCount; i++){\n if(txtArray[i] in unique){\n unique[txtArray[i]]++;\n } else {\n unique[txtArray[i]] = 1;\n }\n }\n return unique;\n }",
"function uniqueWordCount(text) {\r\n\t\t\tvar wordCount = [];\r\n\t\t\ttext = text.split(' ');\r\n\t\t\tfor (var i = 0; i < text.length; i++) {\r\n\t\t\t\tif (wordCount.indexOf(text[i]) == -1) {\r\n\t\t\t\t\twordCount.push(text[i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn wordCount.length;\r\n\t\t}",
"function wordFrequency(wordArray){\n var newArray = [], wordObj;\n wordArray.forEach(function (word) {\n wordObj = newArray.filter(function (w){\n return w.text == word;\n });\n if (wordObj.length) {\n wordObj[0].size += 1;\n } else {\n newArray.push({text: word, size: 1});\n }\n });\n return newArray;\n }",
"function findUniq(arr) {\n var word = [];\n var res = \"\"\n var uniq = [...new Set(arr.join(\"\").toLowerCase())].map(n=>(word = arr.filter(v=>v.indexOf(n) != -1),word.length==1) ? res = word.join(\"\") : n);\n // var uniq = [...new Set(arr.join(\"\").toLowerCase())].map(n=> {\n // console.log(`n1: ${n}`);\n // console.log(arr.filter(v=>v.indexOf(n) != -1));\n // if (word = arr.filter(v=>v.indexOf(n) != -1), word.length==1) { // The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.\n // console.log(word);\n // res = word.join(\"\")\n // } else {\n // n;\n // }\n\n // })\n return res;\n}",
"function findUnique(wordsArr) {\n\n// let noDuplicate =[];\n\n// for (i=0;i<string.length;i++){\n// if(string[i]!=noDuplicate){\n\n// noDuplicate=string[i];\n// }\n// else{\n// return noDuplicate;\n// }\n\n// }\n// }\n \n// }\n}",
"function findUnique(wordsArr) {\n\n if(!wordsArr.length){\n return false\n }else{\n \n let uniqueArr =[]\n let firstWord\n \n wordsArr.forEach(word => {\n \n if(!uniqueArr.includes(word)){\n uniqueArr.push(word)\n \n \n }else{\n uniqueArr.splice(uniqueArr.indexOf(word),1)\n }\n \n })\n return uniqueArr[0]\n }\n\n}",
"getArrayOfAllAndUniqueWords(arrayOfTweets) {\n let set = new Set()\n var punct = ['.',',', '!', ':', ';', '?']\n arrayOfTweets.forEach((tweet) => {\n let words = tweet.split(\" \")\n words.forEach((word) => {\n if(word.length > 0) {\n //assumes that punctuation is at the end of a word and not\n //separated by a space.\n var lastChar = word[word.length-1]\n //checks is a word contains punctuation\n if(punct.indexOf(lastChar) > -1) {\n //this methods adds a word and its period if it exists\n //to the containers\n this.processPunctuation(word, set, lastChar)\n }\n else {\n this.rawText.push(word)\n set.add(word)\n }\n }\n })\n })\n this.uniqueWords = Array.from(set)\n }",
"function countDuplicates(arr) {\n\t\t\n\t\tvar countDup = arr.reduce(function (prev, cur) {\n\t\tprev[cur] = (prev[cur] || 0) + 1;\n\t\treturn prev;\n\t\t}, {});\n\t\t\n\t\tvar wordsSorted = Object.keys(countDup).sort(function (a, b) {\n\t\t\treturn countDup[b] - countDup[a];\n\t\t});\n\t\n\tif (wordsSorted.length > 3)\n\t\twordsSorted = wordsSorted.slice(0, 3);\n\t\treturn wordsSorted;\n\t}",
"function countUniqueValues2(array){\n if (array.length == 0){\n return 0;\n }\n let i = 0;\n let j = 1;\n for (j = 1; j < array.length; j++){\n if (array[i] != array[j])\n array[++i] = array[j];\n }\n return array.slice(0, i+1);\n}",
"function removeBasicWords(array){\n var badWordsArray = ['the', \" \", \"\", 'of', 'and', 'a', \"remix\", \"digital\", \"remastered\"];\n\n array.forEach(function(val){\n if (badWordsArray.indexOf(val) == -1 && val.length > 1) {\n goodWordsArray.push(val);\n }\n });\n goodWordsArray = sortWordFrequency(count(goodWordsArray));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
There should be some discussion over how far the lookDistance should be. We should determine how many elements the average user is going to be seeing on their screen along with how much time is reasonable to sort. | function walkSort(indexLatSorted, indexLngSorted, unsortedArray, lookDistance) {
var sortedArray = [];
var index, secIndex, choice, startElem;
var holderTypeIndex = [];
var choices_1 = []
var choices_2 = [];
// Too many index's this is impossible to read
index = 0;
while (true) {
choices_1 = [];
choices_2 = [];
startElem = unsortedArray[indexLatSorted[index]];
for (var i = -lookDistance; i <= lookDistance; i++) {
if (i !== 0 && index + i >= 0) {
choices_1[i] = (index + i < indexLatSorted.length - 1) ? unsortedArray[indexLatSorted[index + i]] : undefined;
}
}
secIndex = indexLngSorted.indexOf(indexLatSorted[index]);
for (i = -lookDistance; i <= lookDistance; i++) {
if (i !== 0 && secIndex + i >= 0) {
choices_2[i] = (secIndex + i < indexLngSorted.length - 1) ? unsortedArray[indexLngSorted[secIndex + i]] : undefined;
}
}
choice = choose(choices_1, choices_2, startElem, lookDistance);
// Remove start element from sorted arrays and place in holder array
holderTypeIndex.push(getHolder(startElem));
indexLatSorted.splice(index, 1);
indexLngSorted.splice(secIndex, 1);
if (indexLatSorted.length === 1) {
break;
}
if (choice.choiceGroup === 1) {
i = parseInt(choice.i, 10);
index = (i < 0) ? index + i : index + i - 1;
} else if (choice.choiceGroup === 2) {
i = parseInt(choice.i, 10);
index = (i < 0) ? indexLatSorted.indexOf(indexLngSorted[secIndex + i]) : indexLatSorted.indexOf(indexLngSorted[secIndex + i - 1]);
}
if (index === -1) console.error('The next element was not found');
}
holderTypeIndex.push(getHolder(unsortedArray[indexLatSorted[0]])); // add the last element
holderTypeIndex.forEach(function (e, j, arr) {
e.marker = markerGroups[e.type][e.index];
sortedArray.push(e);
});
return sortedArray;
} | [
"function distance() {\n // Store the live distance of each number with the mouse position in an array\n for (let i = 0; i < NUMBER_PAGES; i++) {\n let d = Math.hypot(event.clientX - numCenter[i].x, event.clientY - numCenter[i].y);\n mouseHypo.push(d);\n }\n // Calculate the smallest value at every movement and display the according frame\n let smallestValue = Math.min.apply(Math, mouseHypo);\n closest = mouseHypo.indexOf(smallestValue);\n animate();\n // Change the background accordingly too\n numHover();\n // Empty every time the mouse moves again to get the updated value at the right index\n mouseHypo = [];\n}",
"function sortSize(){}",
"function SortByDistance( candidates, target){\n\n // save the pixels values of candidates\n savePixels = [];\n candidates.forEach(function (i) {\n savePixels.push(\n {index: i , values:[pixels[i], pixels[i+1],pixels[i+2],pixels[i+3] ]}\n )\n })\n\n\n var referenceIdx = target ; //2*width*height + width*2; // center of image normally\n\n // Creat order list of luminance and distance\n indexDistancePairs = [] ;\n indexLuminacePairs = [] ;\n candidates.forEach( function (item) {\n\n indexDistancePairs.push(\n {index: item, distance: DistancePower(item, referenceIdx)} );\n\n indexLuminacePairs.push(\n {index: item, luminance: getRelativeLuminance(item)});\n });\n\n indexDistancePairs.sort(function(a, b) {\n return a.distance - b.distance;\n })\n\n indexLuminacePairs.sort(function (a,b) {\n return a.luminance - b.luminance;\n })\n\n\n // now the lowest luminance will take the position with the shortest distance\n\n for(var i = 0; i < indexDistancePairs.length ; i++ ){\n\n var dIdx = indexDistancePairs[i].index ;\n var lIdx = indexLuminacePairs[i].index;\n\n var found = savePixels.find( function (j) {\n return j.index == lIdx;\n })\n\n pixels[dIdx] = found.values[0];\n pixels[dIdx + 1] = found.values[0+1];\n pixels[dIdx + 2] = found.values[0+2];\n pixels[dIdx + 3] = found.values[0+3];\n\n\n }\n\n\n\n\n\n/*\n\n indexDistancePairs.forEach( function (i) {\n console.log(i);\n })\n\n indexLuminacePairs.forEach( function (i) {\n console.log(i);\n })\n\n savePixels.forEach(function (i) {\n console.log(i);\n })\n\n*/\n}",
"function chose_to_render()\n {\n distance_table=[];\n planets.forEach(function(planet, index, array)\n {\n distance_table.push([planet,count_distance(planet,\"all\")]);\n });\n distance_table=distance_table.sort(function(a, b){return a[1]-b[1]});\n return [distance_table[0][0],distance_table[1][0]];\n }",
"function SortDistance() {\n let sorthightolow = document.getElementById(\"pricehightolow\");\n let sortlowtohigh = document.getElementById(\"pricelowtohigh\");\n let sortdistance = document.getElementById(\"distancesort\");\n\n sortdistance.style.border = \"2px solid #70ad4d\";\n sortdistance.color = \"#70ad4d\";\n\n sorthightolow.style.border = \"1px solid #d8d8d8\";\n sorthightolow.color = \"#9b9b9b\";\n\n sortlowtohigh.style.border = \"1px solid #d8d8d8\";\n sortlowtohigh.color = \"#9b9b9b\";\n\n let distancesortedarray = carslist.sort(function (a, b) {\n return a.carpickupplace - b.carpickupplace;\n });\n\n showCars(distancesortedarray);\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}",
"sortByDistance() {\n let reports = this.state.reports.sort((a, b) => ListOfReports.distance(this.state.latitude, this.state.longitude, a.latitude, a.longitude, 'K') -\n ListOfReports.distance(this.state.latitude, this.state.longitude, b.latitude, b.longitude, 'K'));\n this.setState({ reports });\n console.log('Sorting by distance', reports);\n }",
"function sortLowHighDist(a,b){ return parseInt($(a).data(\"distance\")) - parseInt($(b).data(\"distance\")); }",
"sortRetailersByDistance() {\n var $retailers = $('.retailer-item');\n var $retailerList = $retailers.find('.retailer-item-li');\n\n $retailerList.detach().sort(function (a, b) {\n var aDistance = parseInt($(a).find('.retailer-distance').text());\n var bDistance = parseInt($(b).find('.retailer-distance').text());\n return (aDistance > bDistance) ? (aDistance < bDistance) ? 1 : 0 : -1;\n });\n $retailers.append($retailerList);\n }",
"function showTopDistances() {\n fetchedStores.sort((a, b) => (a.distance > b.distance) ? 1 : ((b.distance > a.distance) ? -1 : 0));\n var div = document.querySelector(\"#topDistances\");\n div.innerHTML = \"\";\n var p = document.createElement(\"p\");\n p.innerHTML = \"<strong>Top 5 nearest stores:</strong>\";\n div.appendChild(p);\n var table = document.createElement(\"table\");\n var header = document.createElement(\"tr\");\n header.innerHTML = `<th>Shop Name</th>\n <th>Address</th> \n <th>Distance</th>\n <th>Duration</th>\n `;\n table.appendChild(header);\n filteredStores = [];\n for (var i = 0; i <= 4; i++) {\n var row = document.createElement(\"tr\");\n row.innerHTML = `<td>${fetchedStores[i].name}</td>\n <td>${fetchedStores[i].address}</td> \n <td>${fetchedStores[i].distance}</td>\n <td>${fetchedStores[i].duration}</td>`\n \n table.appendChild(row);\n filteredStores.push(fetchedStores[i]);\n }\n div.appendChild(table);\n}",
"cutTime() {\n let t = 0;\n this._list.forEach(function(ed) {\n if (ed.action == 0) {\n t += ed.end - ed.start;\n }\n });\n return t;\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 }",
"calculateDistance() {}",
"timeElapsed() \n{\n var arr = [];\n var start = 0, stop = 0;\n\n arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];\n start = this.getNanoSec();\n this.binarySearch(arr);\n stop = this.getNanoSec();\n var binarySearch = stop - start;\n console.log(\"Time required for binarySearch \", binarySearch, \" nanosec\");\n \n var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];\n start = this.getNanoSec();\n this.bubbleSort(arr);\n stop = this.getNanoSec();\n var bubbleSort = stop - start;\n console.log(\"Time required for bubbleSort \", bubbleSort, \"nanosec\");\n \n var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];\n start = this.getNanoSec();\n this.insertion(arr);\n stop = this.getNanoSec();\n var insertionSort = stop - start;\n console.log(\"Time required for insertionsort \", insertionSort, \" nanoseconds\");\n \n var arr = [\"abc\", \"xyz\", \"bc\", \"bdc\", \"aaa\"];\n start = this.getNanoSec();\n this.bubbleString(arr);\n stop = this.getNanoSec();\n var bubbleString = stop - start;\n console.log(\"Time required for bubblesort for String \", bubbleString, \" nanosecond\");\n\n var arr = [\"abc\", \"xyz\", \"bc\", \"bdc\", \"aaa\"];\n start = this.getNanoSec();\n this.insertionString(arr);\n stop = this.getNanoSec();\n var insertion = stop - start;\n console.log(\"Time required for insertion sort for String \", insertion, \" nanosecond\");\n \n var arr = [\"abc\", \"xyz\", \"bc\", \"bdc\", \"aaa\"];\n start = this.getNanoSec();\n this.binaryString(arr);\n stop = this.getNanoSec();\n var binary = stop - start;\n console.log(\"Time required for bubble sort for String \", binary, \" nanosecond\");\n \n // create the list and add all values and their type\n var masterList =\n\n [ { type: \"binary search \", time: binarySearch }, \n { type: \"bubble sort \", time: bubbleSort },\n { type: \"insertion sort \", time: insertionSort }, \n { type: \"binary for String \", time: binary }, \n { type: \"bubble for String \", time: bubbleString },\n { type: \"insertion for String\", time: insertion }\n ];\n \n //sort the list in decending order\n masterList.sort(function (a, b) { return b.time - a.time });\n \n console.log(\"the time in descending order is \");\n console.log(\"Time for \" + masterList[0].type + \" is \" + masterList[0].time);\n console.log(\"Time for \" + masterList[1].type + \" is \" + masterList[1].time);\n console.log(\"Time for \" + masterList[2].type + \" is \" + masterList[2].time);\n console.log(\"Time for \" + masterList[3].type + \" is \" + masterList[3].time);\n console.log(\"Time for \" + masterList[4].type + \" is \" + masterList[4].time);\n console.log(\"Time for \" + masterList[5].type + \" is \" + masterList[5].time);\n \n }",
"estimatedCompleteness() {\n // const manhattanDistance = ([x1, y1], [x2, y2]) => Math.abs(x2-x1) + Math.abs(y2-y1);\n // const maxStepsCountForPosition = i => 'fuck you'; // todo: for 4x4 field return one of {10, 13, 16}\n // const estimatedStepsCountForValue = (value, currentPos) => 'magic'; \n \n // const maxStepsCountTotal = this.map((_, pos) => maxStepsCountForPosition).reduce((s, v) => s+v, 0);\n // const stepsLeft = this.map((value, pos) => estimatedStepsCountForValue(value, pos)).reduce((s, v) => s+v, 0);\n // return 1.0 - stepsLeft / maxStepsCountTotal;\n\n const indexValueDiffSum = this\n // zero is empty cell, it must be on last position\n .map((value, index) => index-(value === 0 ? (this.length-1) : value-1))\n .reduce((sum, diff) => sum+Math.abs(diff), 0);\n\n // powering resulting value return more 'native' feeling values\n return Math.pow(1.0 - indexValueDiffSum / (14*this.length), 4);\n }",
"StopwatchSearchAndSort(arr) {\n\n //binary search\n\n var start = this.stopwatchmill()\n var temp = this.sortarrayInt(arr)\n var stop = this.stopwatchmill()\n var totaltime1 = stop - start;\n console.log(\"Binary Search take \" + totaltime1 + \" millsecond to exicute the code\");\n console.log();\n\n\n //bubble Sort\n var start = this.stopwatchmill()\n var temp = this.bubbleSortInt(arr)\n var stop = this.stopwatchmill()\n var totaltime2 = stop - start;\n console.log(\"Bubble Sort take \" + totaltime2 + \" millsecond to exicute the code\");\n console.log();\n\n\n\n\n //insertion sort\n\n var start = this.stopwatchmill()\n var temp = this.insertionSortInt(arr)\n var stop = this.stopwatchmill()\n var totaltime3 = stop - start;\n console.log(\"Insertion Sort take \" + totaltime3 + \" millsecond to exicutethe code\");\n\n\n\n\n}",
"function calculateDistance() {}",
"function distanceCovered()\n{\n\tlet distanceCovered = 0, partialDistance;\n\n\tfor (let routeNumber = 0; routeNumber < userHistory.length - 1; routeNumber++) {\n\t\tpartialDistance = google.maps.geometry.spherical.computeDistanceBetween(userHistory[routeNumber].latLng, userHistory[routeNumber + 1].latLng);\n\t\tdistanceCovered += partialDistance;\n\t}\n\treturn distanceCovered;\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is to track the Start download of Akamaiurls. We need a seperate method as to track the Type | function trackDownloads(downloadType, fileType, fileName){
try{
if(fileType!=undefined && fileType!=null && fileType!=''){
riaTrackDownloadsLink(fileType+" : "+downloadType, fileName);
}else{
riaTrackDownloadsLink(downloadType, fileName);
}
}catch(e){
//do nothing.
}
} | [
"function onStartedDownload(id) {\n console.log(`Started downloading: ${id}`);\n}",
"updateDownloadStat(type) {\n browser.runtime.sendMessage({\n action: 'updateDownloadedStat',\n args: type,\n });\n }",
"startTracking() {\n HyperTrack.onTrackingStart();\n }",
"function FullyDownloaded() {\n}",
"function trackDownload(txt) {\n var s = s_gi(s_account);\n s.linkTrackVars='prop18,eVar18,event17';\n s.linkTrackEvents='event17';\n s.eVar18=s.prop18=txt;\n s.events='event17';\n s.tl(this,'d',prop18);\n}",
"function iv_doTracking (trackStr, url, prop, linkType, linkName, gs, el ) {\r\n if (linkType == null || linkType == \"\") { linkType = \"o\"; }\r\n if (linkName == null || linkName == \"\") { linkName = \"Downloaded File\"; }\r\n \r\n if (prop != null && prop != \"\"){\r\n prop=prop.replace(/s_prop/, \"s_iv.prop\"); \r\n }\r\n\r\n if (prop == null || prop == \"\") { prop = \"s_iv.eVar13\"; } else if (prop == \"s.prop30\" || prop == \"s_prop30\") { prop = \"s_iv.eVar13\"; } \r\n\r\n if (s_account == \"nbcuglobal\") { s_account = \"nbcuivsites\";}\r\n var s_iv=s_gi(s_account);\r\n\r\n // Lets check if this is exit link or not\r\n var is_exit_link = true;\r\n if(typeof s_iv.linkInternalFilters != \"undefined\" && typeof el != \"undefined\"){\r\n target_anchor = null;\r\n if(el.tagName == \"A\"){\r\n target_anchor = el;\r\n }else{\r\n tmp_parent_element = (window.event) ? el.parentElement : el.parentNode;\r\n target_anchor = (tmp_parent_element.tagName == \"A\") ? tmp_parent_element : null;\r\n }\r\n\r\n if(target_anchor != null && typeof target_anchor.href != \"undefined\"){\r\n var iv_internal_links = s_iv.linkInternalFilters.split(\",\");\r\n for(int_link_count=0; int_link_count < iv_internal_links.length; int_link_count++){\r\n if(target_anchor.href.indexOf(iv_internal_links[int_link_count]) >= 0){\r\n is_exit_link = false;\r\n break;\r\n }\r\n }\r\n }\r\n }else{\r\n is_exit_link = false;\r\n }\r\n\r\n s_iv.eVar13 = trackStr;\r\n if(!is_exit_link){\r\n s_iv.tl(this,linkType,linkName);\r\n }\r\n\r\n redirectUrl = url;\r\n if (url != null && url != \"\") { \r\n setTimeout(\"document.location.replace(redirectUrl)\", 1000 );\r\n }\r\n return true;\r\n}",
"BeginDownload(IUnknown, IUnknown, Variant) {\n\n }",
"function _initAutoTracker() {\n var aSETTINGS = {\n DEBUGGING_MODE: false,\n TRACK_OUTBOUND_DOWNLOADS: true,\n TRACK_OUTBOUND_EMAILS: true,\n DOWNLOADS_EXTs: oCONFIG.EXTS,\n WEBSITE_HOSTNAME: oCONFIG.HOST_DOMAIN_OR,\n EMAIL_CATEGORY: 'Mailto',\n DOWNLOADS_CATEGORY: 'Downloads',\n TELEPHONE_CATEGORY: 'Telephone Clicks',\n OUTBOUND_LINK_CATEGORY: 'Outbound',\n OUTBOUND_DOWNLOAD_CATEGORY: 'Outbound Downloads',\n OUTBOUND_EMAIL_CATEGORY: 'Outbound MailTo',\n };\n var _allDocLinks = document.getElementsByTagName('a');\n\n for (var iki = 0; iki < _allDocLinks.length; iki++) {\n try {\n var _ThisLink = _allDocLinks[iki].getAttribute('href');\n var _thisObject = _allDocLinks[iki];\n var _thisHostName = _thisObject.hostname;\n var _thisPathName = _thisObject.pathname;\n var _thisProtocol = _thisObject.protocol;\n if (!_thisHostName.match(/(.*)\\.(.*)\\.(.*)/g)) {\n _thisHostName = 'www.' + _thisHostName;\n }\n var _completeURL = _thisProtocol + \"//\" + _thisHostName + _thisPathName;\n if (_thisHostName != '' && _thisPathName != '' && _thisHostName != 'www.') { /* Major Case (Link) #1*/\n if (_thisHostName.toLowerCase().indexOf(aSETTINGS.WEBSITE_HOSTNAME) > -1) { /* Minor Case - Internal Link #1/1 */\n _isDownload(_thisPathName, aSETTINGS.DOWNLOADS_EXTs) == true ? _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.DOWNLOADS_CATEGORY, _getDownloadExt(_thisPathName, aSETTINGS.DOWNLOADS_EXTs), _completeURL, 0) : false;\n } else { /* Minor Case - Externak Link (Outbound) #1/2 */\n _isDownload(_thisPathName, aSETTINGS.DOWNLOADS_EXTs) && aSETTINGS.TRACK_OUTBOUND_DOWNLOADS == true ? _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.OUTBOUND_DOWNLOAD_CATEGORY, _getDownloadExt(_thisPathName, aSETTINGS.DOWNLOADS_EXTs), _completeURL, 0) : _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.OUTBOUND_LINK_CATEGORY, _thisHostName, _thisPathName, 0);\n }\n } else { /* Major Case (Email & Telephone) #2 */\n if (_isEmailAddr(_ThisLink)) {\n var _thisEmailAddress = _getEmailAddr(_ThisLink);\n var _thisEmailHost = _getEmailAddrHost(_thisEmailAddress);\n if (aSETTINGS.WEBSITE_HOSTNAME.replace('www.', '') == _thisEmailHost) {\n _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.EMAIL_CATEGORY, _thisEmailAddress, '', 0);\n } else if (_thisEmailHost.indexOf(aSETTINGS.WEBSITE_HOSTNAME) > -1) {\n _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.EMAIL_CATEGORY, _thisEmailAddress, '', 0);\n } else if (aSETTINGS.TRACK_OUTBOUND_EMAILS) {\n _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.OUTBOUND_EMAIL_CATEGORY, _thisEmailAddress, '', 0);\n }\n\n } else if (_isTelNum(_ThisLink)) {\n _addEventListener(_thisObject, aSETTINGS.DEBUGGING_MODE, aSETTINGS.TELEPHONE_CATEGORY, _getTelNum(_ThisLink), '', 0);\n\n }\n\n }\n } catch (ePR) { }\n }\n\n\n}",
"function launchURL(url)\n{\n console.log(\"Reading FASTQ from \" + url + \"...\");\n ga(\"send\", \"event\", \"launch\", \"url_load\", url);\n\n document.querySelector(\".spinner\").style.display = \"block\";\n document.querySelector(\".footer\").style.display = \"none\";\n document.querySelector(\".loadingfile\").style.display = \"block\";\n document.querySelector(\".loadingfile\").innerHTML = \"Loading file...\"\n document.querySelector(\".containerMain\").style.display = \"none\";\n\n setTimeout(function()\n {\n var request = new XMLHttpRequest();\n request.open(\"GET\", url, true);\n request.setRequestHeader(\"Range\", \"bytes=0-10000000\");\n request.responseType = \"blob\";\n request.onload = function()\n {\n console.log(\"[launchURL] Loaded file of size \" + Math.round(request.response.size/1024/1024*100)/100 + \"MB.\")\n ga(\"send\", \"event\", \"launch\", \"url_loaded\", url, request.response.size);\n // Convert Blob to File\n var blob = request.response;\n blob.lastModifiedDate = new Date();\n blob.name = url.split(\"/\").reverse()[0];\n // Launch\n launch(blob);\n };\n request.send();\n\n }, 150);\n}",
"function startTracking() {\n\t tracking.startTracking();\n\t }",
"function downloadFinished(){\n}",
"function HttpDownloadProgressEvent() { }",
"start() {\n // Ignore if already downloading\n if (this._status === status.downloading) return;\n\n this._request = Http(this.url, res => {\n // Handle incorrect responses\n // This error event might be emitted before the start event. This\n // can't be helped since the reponse it self is wrong.\n if (res.statusCode !== 200) {\n this._handleError(\n new Error(\n `Server responded with ${res.statusCode}: ${\n res.statusMessage\n }`\n )\n );\n // Download failed\n return;\n }\n\n // Store a reference to res\n this._response = res;\n\n let fileName = this._response.headers[\"content-disposition\"];\n // Extract filename from header. Assumption is that the\n // header is exactly as returned by the http service.\n // Might throw errors for other headers\n fileName = fileName.replace(`inline; filename=\"`, \"\");\n // Remove trailing double quote\n fileName = fileName.slice(0, fileName.length - 1);\n // Remove percent encoded characters\n fileName = decodeURIComponent(fileName);\n\n // Get full file path\n let filePath = Path.join(this.directory, fileName);\n\n // Get unused filename\n UnusedFileName(filePath)\n .then(unusedpath => {\n // Assign the file name to instance\n this._filepath = unusedpath;\n })\n .then(() => {\n // No point wrapping this in promise. Communication with\n // outside world occurs through events\n\n // Extract file size from header\n this._size = parseInt(\n this._response.headers[\"content-length\"],\n 10\n );\n // Keep track of bytes downloaded\n this._bytesDownloaded = 0;\n\n // We emit start event now. Note that there might be an\n // error event after this point. But the start event is\n // emitted to notify the user about the resolved filename\n // and size of file. Moreover it makes sense to have error\n // events after the start event\n this.emit(\n events.start,\n this._filepath,\n this._size,\n this.url\n );\n this._status = status.downloading;\n\n // Create a write stream. If directory does not exist or\n // permission not given then error will be thrown\n this._fileStream = Fs.createWriteStream(this._filepath, {\n flags: \"wx\"\n })\n .on(\"error\", err => {\n // Send error with user friendly message\n this._handleError(new Error(\"Writing to file\"));\n })\n .on(\"open\", () => {\n // add event listeners to res only after file has been\n // successfully opened. This ensures that events are\n // emitted only if fileStream opened successfully\n this._response.on(\"data\", chunk => {\n this._bytesDownloaded += chunk.length;\n this._progress(chunk.length);\n });\n\n // Pipe data to write stream i.e. write to file\n this._response.pipe(this._fileStream);\n })\n .on(\"finish\", () => {\n this._finish();\n });\n });\n });\n\n this._request.on(\"error\", err => {\n this._handleError(err);\n });\n }",
"function webtrekkLinkTrack() {\n if (typeof wt !== 'undefined') {\n wt.linkTrackInit();\n }\n }",
"function trackingClickout(item) {\nvar regexp = /clickout_(.*)/,\nmatch = regexp.exec(item.attr('class')),\nurl = item.attr('href'),\ntoplineHeadline = $('.detail_headline').text(),\ndomain = 'unknown';\nif (match) {\ndomain = match[1];\n} else {\nvar linkTitle = $(this).attr('title');\nvar idx = linkTitle.indexOf('[' + message('link.neuesFenster') + ']');\nif (idx != -1) {\nvar dmatch = url.match(/:\\/\\/(www\\.)?(.[^/:]+)/);\nif (dmatch != null) {\ndomain = dmatch[2];\n}\n}\n}\nBR.Tracking.track({\nelementName: 'Link',\nid: 'oz',\ntitle: domain,\nnsType: 'clickout',\naction: 'Link-Clickout',\ntrackingType: 'click',\ntoplineHeadline: toplineHeadline + ' auf ' + (domain.charAt(0).toUpperCase() + domain.slice(1)) + ' empfehlen.',\nurl: url\n}); // ivw, ati\n}",
"function startCheckingUrl() {\r\n\t\ttimeout = setTimeout(timeoutHandler, timeoutLength);\r\n\t}",
"function download_torrent_files(properties) {\n\n setTimeout(function() {\n\n var url = properties.get('download_url');\n\n var rand = 0;\n\n if(torrents[url]) {\n\n delete torrents[url];\n\n var files = btapp.get('torrent').get(properties.get('hash')).get('file');\n\n _gaq.push(['_trackEvent', 'Added', 'Torrent', 'Files', files.length]);\n\n files.each(function(file) {\n\n var streaming_url = file.get('properties').get('streaming_url') + '&service=DOWNLOAD';\n\n if(!isMac()) {\n\n streaming_url = streaming_url.replace('127.0.0.1', '127.0.0.' + (((++rand) % 10) + 1));\n\n }\n\n var name = file.get('properties').get('name');\n\n streaming_urls[streaming_url] = name;\n\n queue_tab_creation(streaming_url);\n\n });\n\n\n\n var uses = (jQuery.jStorage.get('uses') || 0) + 1;\n\n jQuery.jStorage.set('uses', uses);\n\n _gaq.push(['_trackEvent', 'Stream', 'Torrent', 'Uses', uses]);\n\n console.log(uses + ' uses so far.');\n\n if(uses == 4) {\n\n var w = 440;\n\n var h = 220;\n\n var left = (screen.width/2)-(w/2);\n\n var top = (screen.height/2)-(h/2);\n\n chrome.windows.create({\n\n url: chrome.extension.getURL('purchase.html'),\n\n width: w,\n\n height: h,\n\n left: left,\n\n top: top,\n\n focused: true,\n\n type: 'popup'\n\n }, function() {\n\n });\n\n } else {\n\n check_tab_queue();\n\n }\n\n }\n\n }, 1);\n\n }",
"function startDownloadProccess ( index ) {\n var downloadParams = {url : downloadQueryList[index].url, conflictAction : \"overwrite\"};\n toggleTotalDownloadAllSongs ( false );\n chrome.downloads.download ( downloadParams, function ( downloadId ) {\n chromeCurrentDownloadId = downloadId;\n } );\n}",
"OnStartRunningUrl(aUrl) {\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the plural function used by ICU expressions to determine the plural case to use for a given locale. | function getLocalePluralCase(locale){var data=findLocaleData(locale);return data[18/* PluralCase */];} | [
"function getLocalePluralCase$1(locale) {\n var data = findLocaleData$1(locale);\n return data[18 /* PluralCase */];\n }",
"function getLocalePluralCase(locale) {\n var data = findLocaleData(locale);\n return data[18 /* PluralCase */];\n}",
"function getLocalePluralCase(locale) {\n var data = findLocaleData(locale);\n return data[LocaleDataIndex.PluralCase];\n }",
"function getLocalePluralCase(locale) {\n const data = findLocaleData(locale);\n return data[LocaleDataIndex.PluralCase];\n}",
"function pluralRule(number, localeCode) {\n\t // modern browsers have this functionality built-in\n\t var rules = 'Intl' in window && Intl.PluralRules && new Intl.PluralRules(localeCode);\n\n\t if (rules) {\n\t return rules.select(number);\n\t } // fallback to basic one/other, as in English\n\n\n\t if (number === 1) return 'one';\n\t return 'other';\n\t }",
"function getPluralName(count, locale) {\n var ruleKey = PLURAL_RULE_KEYS_BY_LOCALE[locale] || DEFAULT_PLURAL_RULE_KEY;\n var rule = PLURAL_RULES[ruleKey];\n return PLURAL_NAMES[rule(count)];\n}",
"function pluralRule(number, localeCode) {\n\n // modern browsers have this functionality built-in\n const rules = 'Intl' in window && Intl.PluralRules && new Intl.PluralRules(localeCode);\n if (rules) {\n return rules.select(number);\n }\n\n // fallback to basic one/other, as in English\n if (number === 1) return 'one';\n return 'other';\n }",
"function getPluralFn(lang) {\n return PLURALS[lang] || DEFAULT_PLURAL_FN;\n}",
"function getPluralCategory(value,cases,ngLocalization,locale){var key=\"=\"+value;if(cases.indexOf(key)>-1){return key;}key=ngLocalization.getPluralCategory(value,locale);if(cases.indexOf(key)>-1){return key;}if(cases.indexOf('other')>-1){return'other';}throw new Error(\"No plural message found for value \\\"\"+value+\"\\\"\");}",
"function _plural (s) {\n return _singular(s) + 's';\n }",
"computePluralName(singular) {\n var plural;\n if (singularName.endsWith('y')) {\n // remove y and add ie\n plural = singular.substring(0,singular.length-1) +\"ie\";\n } else {\n plural = singular;\n }\n plural = plural.toLowerCase();\n plural = plural + 's';\n return plural;\n }",
"function plural(count) {\n if(count == 1) {\n return \"\";\n }\n else {\n return \"es\";\n }\n}",
"computePluralName(singular) {\n var plural;\n if (singular.endsWith('y')) {\n // remove y and add ie\n plural = singular.substring(0,singular.length-1) +\"ie\";\n } else {\n plural = singular;\n }\n plural = plural.toLowerCase();\n plural = plural + 's';\n return plural;\n }",
"function pluralize(str) {\n return inflected.pluralize(str);\n}",
"pluralize(name) {\n const plural = this.pluralNames[name];\n if (plural) {\n return plural;\n }\n // singular and plural are the same\n if (uncountable.indexOf(name.toLowerCase()) >= 0) {\n return name;\n // vowel + y\n }\n else if (/[aeiou]y$/.test(name)) {\n return name + 's';\n // consonant + y\n }\n else if (name.endsWith('y')) {\n return name.substring(0, name.length - 1) + 'ies';\n // endings typically pluralized with 'es'\n }\n else if (/[s|ss|sh|ch|x|z]$/.test(name)) {\n return name + 'es';\n }\n else {\n return name + 's';\n }\n }",
"computePluralName(singular) {\n var plural;\n if (singular.endsWith('y')) {\n // remove y and add ie\n plural = singular.substring(0,singular.length-1) +\"ie\";\n plural = plural.toLowerCase();\n }\n plural = plural + 's';\n return plural;\n }",
"function definePluralFn(locales, fn) {\n for (var i = 0, len = locales.length; i < len; i++) {\n PLURALS[locales[i]] = fn;\n }\n}",
"function plural(nCount, strNonPlural, strPlural)\r\n{\r\n if (nCount == 1 || nCount == -1)\r\n return strNonPlural;\r\n else\r\n return strPlural;\r\n}",
"pluralize (noun, count) {\r\n if (count === 0) {\r\n return `no ${noun.plural()}`;\r\n }\r\n else if (count === 1) {\r\n return noun;\r\n }\r\n return noun.plural();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called in response to failure to initialize on Signiant.mst.initialize | function reInitializeFailure() {
console.log("Re-Initialize Signiant App Failed, retrying");
alert("Signiant App Connection Lost, Retrying...");
reInitializeApp();
} | [
"function _onFailedInit() {\n\t\t_settings.onFail();\n\t}",
"function onInitializeFail( ecode )\n {\n console.log( \"CLIENT ERROR: \" + ecode );\n }",
"function validateInitialization() {\n if (!isInitialized) {\n throw new Error ('MobileServiceSyncContext is being used before it is initialized');\n }\n }",
"function onInitFailure(errorCode, errorString) {\n alert('Init failed: ' + errorString);\n\t\n\tshowLoadingLayer(false);\n}",
"function onDefaultInitFailure(response){\n \tWL.Logger.error(\"Client init failed. \" + response.errorMsg);\n \tshowWidgetContent();\n var callbackName = errorCodeCallbacks[response.errorCode]; \n if (callbackName && initOptions[callbackName]){\n\t\t\tinitOptions[callbackName](response);\n } else {\n showDialog(WL.ClientMessages.wlclientInitFailure, response.userMsg ? response.userMsg : WL.ClientMessages.unexpectedError, response.recoverable);\n }\n }",
"function onDefaultInitFailure(response) {\n\t\tif (response.errorCode == WL.ErrorCode.CONNECTION_IN_PROGRESS) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tWL.Logger.error(\"Client init failed. \" + response.errorMsg);\n\t\tvar errMsg = (response.errorMsg == WL.ClientMessages.authFailure ? response.errorMsg : WL.ClientMessages.unexpectedError);\n\t\tshowWidgetContent();\n\t\tvar callbackName = errorCodeCallbacks[response.errorCode];\n\t\tif (callbackName && initOptions[callbackName]) {\n\t\t\tinitOptions[callbackName](response);\n\t\t} else {\n\t\t\tshowDialog(WL.ClientMessages.wlclientInitFailure, response.userMsg ? response.userMsg : errMsg, response.recoverable, true, response);\n\t\t}\n\t}",
"function myInitError()\n{\n myErrorNumber = '0';\n myErrorDiagnostic = myGetDiagnostic(myErrorNumber);\n}",
"init (){ throw new Error('Program: must override this method.') }",
"function MobileAwareness_init()\r\n{\r\n\t// CHOICE:\r\n\t// - Initialize with callback, and handle security events in callback; or\r\n\t// - Initialize without a callback, and use polling-based queries to get results\r\n\r\n\t// WITH CALLBACK:\r\n\tvar res = MobileAwareness_init_internal(MobileAwareness_callback);\r\n\t// WITHOUT CALLBACK:\r\n\t//var res = MobileAwareness_init_internal(null);\r\n\r\n\t// HANDLE ERROR:\r\n\tif( res != 0 ){\r\n\t\t// For debugging:\r\n\t\tkony.print(\"ERROR - MobileAwareness did not initialize correctly\");\r\n\r\n\t\tif( res == -2 ){\r\n\t\t\t// License issue (expired, not licensed for this app, etc.)\r\n\t\t\t// ... TODO: put your error handling code here\r\n\t\t}\r\n\t\telse if( res == -3 ){\r\n\t\t\t// Security issue -- internal tampering detected\r\n\t\t\t// ... TODO: put your error handling code here\t\r\n\t\t}\r\n\t\telse {\r\n\t\t\t// General/unspecified internal error\r\n\t\t\t// ... TODO: put your error handling code here\r\n\t\t}\r\n\t}\r\n}",
"initialize(){}",
"function onFail(){\n\t\t \tgame.init();\n\t\t }",
"_checkIfInitialized() {\n if (!this._initialized) {\n throw new Error('Blockchain is not initialized!');\n }\n }",
"function initialize() {\n // Alert of invalid token\n if (!$stateParams.token) {\n // Avoid this page if no token in url\n $state.go('home');\n } else { // Validate token\n // Validate token\n Authentication.token($stateParams.token)\n .then(validateCompleted)\n .catch(validateFailed);\n }\n\n // If token is valid close loading and continue\n function validateCompleted(data) {\n // If user logged then logut before continue\n if (Authentication.user) {\n Authentication.logout();\n }\n // Reset button text\n vm.buttonText = 'Reset';\n }\n\n // If token is invalid alert error and go home\n function validateFailed(data) {\n Alert.display('Error', 'Password reset token is invalid or has expired').result\n .then(goBack)\n .catch(goBack);\n }\n\n // return to home\n function goBack() {\n $state.go('home');\n }\n }",
"checkInit() {\n if (!this.cfgObj) {\n throw new Error(\"Project Config not initialized\");\n }\n }",
"function checkInit(sData) {\n if (!bInitialized) {\n sData += '<br><b>Error:</b>Illegal Function call before LMSInitialize.<br>';\n sLastError = '301';\n }\n return sData;\n}",
"async _initializeState() {\n try {\n const { accounts, chainId, isUnlocked, networkVersion } = (await this.request({\n method: 'metamask_getProviderState',\n }));\n // indicate that we've connected, for EIP-1193 compliance\n this.emit('connect', { chainId });\n this._handleChainChanged({ chainId, networkVersion });\n this._handleUnlockStateChanged({ accounts, isUnlocked });\n this._handleAccountsChanged(accounts);\n }\n catch (error) {\n this._log.error('MetaMask: Failed to get initial state. Please report this bug.', error);\n }\n finally {\n this._state.initialized = true;\n this.emit('_initialized');\n }\n }",
"function check_init(self) {\n if (self.__init__) {\n self.__init__.apply(self, arguments);\n }\n else {\n throw '__init__() missing. did you miss the keyword \"new\"?';\n }\n }",
"function _init() {\n }",
"function notifyFailure(appInitializationFailedRequest) {\n internalAPIs_1.ensureInitialized();\n communication_1.sendMessageToParent(appInitialization.Messages.Failure, [\n appInitializationFailedRequest.reason,\n appInitializationFailedRequest.message,\n ]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function that accepts a name and returns the name as first name and last name. Remove the middle name, if there is one. This function should still work if there is no middle name. If the string has only one name, e.g. "Adele", it should return that name If there are multiple middle names this function should still work. Example: shortenName(Morty Antoine Smith") should return "Morty Smith" shortenName(Morty Smith") should return "Morty Smith" shortenName(Morty") should return "Morty" shortenName(Morty Antoine Fred Bacon Smith") should return "Morty Smith" Edit only the code between the lines (below) | function removeMiddleName(string) {
let arrayString = string.split(" ");
let first = arrayString[0];
let last = arrayString[arrayString.length-1];
let firstLast = first +" " + last;
if (arrayString.length === 1){
return first;
}
else{
return firstLast;
}
} | [
"function middleName(firstName, middleName, lastName) {\n\tif (middleName === null) {\n\t\treturn firstName + ' ' + lastName;\n\t} else {\n\t\treturn firstName + ' ' + middleName + ' ' + lastName;\n\t}\n}",
"function getMidddelName(fullname){\n let middleName = fullname.trim();\n middleName = middleName.split(\" \");\n // If fullname includes \"\", ignore that name and make middlename none\n if (fullname.includes(' \"')) {\n middleName = \"\"; \n } else if (middleName.length > 2) { // if fullname is longer than 2, make second name middlename\n middleName = middleName[1];\n middleName = middleName.substring(0,1).toUpperCase() + middleName.substring(1).toLowerCase();\n } else{\n middleName = \"\";\n }\n return middleName;\n}",
"function abbreviateName (first, middle, last) {\n return first [0] + middle [0] + last [0];\n}",
"getShortname() {\n const fullname = this.getFullname();\n\n if(!fullname) {\n return '';\n }\n\n const nameParts = fullname.split(' ');\n const surname = nameParts[0];\n const name = nameParts[1] || null;\n const patronymic = nameParts[2] || null;\n\n let shortName = surname + ' ';\n\n if(name && name.slice) {\n shortName += name.slice(0, 1) + '.';\n }\n\n if(patronymic && patronymic.slice) {\n shortName += patronymic.slice(0, 1) + '.';\n }\n\n return shortName;\n }",
"function abbreviate(firstName, lastName) {}",
"function getNewFirstName(firstName, lastName) {\r\n let newFirstName = firstName.substring(0,3) + lastName.substring(0,2).toLowerCase();\r\n return newFirstName;\r\n\r\n}",
"function jediName(firstName, lastName){\n return lastName.substring(0,3) + firstName.substring(0,2);\n}",
"function getFullName(firstName, lastName, middleName = \"\") {\n //return firstName + \" \" + middleName + \" \" + lastName;\n return `${firstName} ${middleName} ${lastName}`;\n}",
"function getNewFirstName(firstName, lastName) {\n return firstName.substr(0, 3) + lastName.substr(0, 2);\n}",
"function parseAndDisplayName(fullname) {\n\n let firstName = \"\",\n lastName = \"\",\n middleName = \"\";\n let pos = fullname.indexOf(\" \");\n let pos2 = fullname.lastIndexOf(\" \");\n\n if (pos != -1) {\n firstName = fullname.substring(0, pos);\n if (pos != pos2) {\n middleName = fullname.substring(pos + 1, pos2);\n lastName = fullname.substring(pos2 + 1);\n } else {\n\n lastName = fullname.substring(pos + 1);\n }\n\n } else {\n firstName = fullname;\n lastName = \"\";\n }\n console.log(\"First Name: \" + firstName);\n\n if (middleName != \"\")\n console.log(\"Middle Name: \" + middleName);\n if (lastName != \"\")\n console.log(\"Last Name: \" + lastName);\n}",
"function abbreviate(firstName, lastName) {\n firstName = firstName.toUpperCase();\n lastName = lastName.toUpperCase();\n let initialsName = firstName.slice(0, 1) + lastName.slice(0, 1);\n\n return initialsName;\n}",
"function getFirstName(fullname){\n let firstName = fullname.trim();\n // If fullname includes a space, firstname is what comes before that first space\n if (fullname.includes(\" \")) {\n firstName = firstName.substring(0, firstName.indexOf(\" \"));\n firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase();\n } else {\n // if fullname only has one name - no space\n firstName = firstName;\n }\n return firstName;\n}",
"function getFullName(firstName,lastName, middleName=\"\"){\nreturn `${firstName} ${middleName} ${lastName}`\n}",
"function jediName(firstName, lastName) {\n const name = `${lastName.slice(0, 3)}${firstName.slice(0,2)}`;\n return name;\n}",
"function getFullName(firstName, lastName) {\n return firstName + ' ' + lastName;\n}",
"function getNewFirstName() {\r\nreturn firstName.substring(0,3) + lastName.substring(0,2).toLowerCase();\r\n}",
"function getNewFirstName() {\n return firstName.substring(0,3) + lastName.substring(0,2).toLowerCase();\n}",
"function getFirstName(name){\n var firstName = name.split(' ')[0];\n firstName = firstName[0].toUpperCase()+ firstName.substr(1);\n return firstName;\n}",
"function getFirstName( anyName )\r\n{\r\n var firstSpace = 0;\r\n var returnName = '';\r\n \r\n firstSpace = anyName.indexOf(' ');\r\n \r\n if (firstSpace > 1)\r\n returnName = anyName.substring(0, firstSpace);\r\n else\r\n returnName = anyName;\r\n //console.log('getFirstName = '+ returnName);\r\n return returnName;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets if the provided structure is a NamedNodeStructure. | static isNamed(structure) {
switch (structure.kind) {
case StructureKind_1.StructureKind.Enum:
case StructureKind_1.StructureKind.Interface:
case StructureKind_1.StructureKind.JsxAttribute:
case StructureKind_1.StructureKind.Namespace:
case StructureKind_1.StructureKind.TypeAlias:
case StructureKind_1.StructureKind.TypeParameter:
case StructureKind_1.StructureKind.ShorthandPropertyAssignment:
return true;
default:
return false;
}
} | [
"function isNamedNode(obj) {\n return isTerm(obj) && obj.termType === 'NamedNode';\n}",
"static hasName(structure) {\r\n return typeof structure.name === \"string\";\r\n }",
"static isJsxTagNamed(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JsxSelfClosingElement;\r\n }",
"static isNameable(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Class:\r\n case StructureKind_1.StructureKind.Function:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isBindingNamed(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Parameter:\r\n case StructureKind_1.StructureKind.VariableDeclaration:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"function isNode(element) {\n\t\treturn element.attr('metadata/name');\n\t}",
"static isPropertyNamed(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.EnumMember:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n case StructureKind_1.StructureKind.PropertySignature:\r\n case StructureKind_1.StructureKind.PropertyAssignment:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"function Xml_IsNodeName(objNode, strName)\r\n{\r\n return objNode.nodeName == strName;\r\n}",
"static hasName(node) {\r\n // this method is manually maintained\r\n if (node.getName == null)\r\n return false;\r\n return typeof node.getName() === \"string\";\r\n }",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }",
"static isNamespace(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.Namespace;\r\n }",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }",
"static isJsxTagNamedNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JsxClosingElement:\r\n case typescript_1.SyntaxKind.JsxOpeningElement:\r\n case typescript_1.SyntaxKind.JsxSelfClosingElement:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isTyped(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.Parameter:\r\n case StructureKind_1.StructureKind.PropertySignature:\r\n case StructureKind_1.StructureKind.VariableDeclaration:\r\n case StructureKind_1.StructureKind.TypeAlias:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"hasName(){\n\t\treturn utils.isString(this.name);\n\t}",
"findNodeByName(name) {\n var n;\n for (n = 0; n < this.nodeList.length; ++n) {\n if (this.nodeList[n].name === name) {\n break;\n } \n }\n if (n === this.nodeList.length) {\n return undefined;\n }\n return this.nodeList[n];\n }",
"static isJsxElement(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JsxElement;\r\n }",
"function isFatTree(topologyName) {\n return topologyName.indexOf(\"Fat-tree\") >= 0 || topologyName.indexOf(\"fat-tree\") >= 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
scrolls to the previous Pokemon in the list | prevPoke(){
//checks to see variable representing the pokemon's position is at the first pokemon in the array
if(this.current == 0){
//cycles to the last position in the array if it is currently in the first position
this.current = this.pokes.length-1;
}
else{
//otherwise go to the previous array postion
this.current--;
}
//call function to load attributes for that pokemon
this.loadPoke();
} | [
"function prevItem()\r\n{\r\n\tif(index > 0)\r\n\t{\r\n\t\tindex -= 1;\r\n\t\t$.scrollTo(itemJumps[index], 600, { offset: jumpOffset-32 });\r\n\t}\r\n\t\r\n\tconsole.log(\"GAH: jumping to PREVIOUS item\");\r\n}",
"prev () {\n this.gotoItem(this.currentItem - this.slidesToScroll)\n }",
"prev() {\n\t\tthis.gotoItem(this.currentItem - this.slideToScroll);\n\t}",
"scrollPrev() {\n this.scrollTo(this.state.startIndex - 1);\n }",
"function gotoPreviousObject(event) {\n var objPos = getPreviousObjectPosition(window.pageYOffset);\n if (objPos) {\n window.scrollTo(0, objPos);\n } // else no object found\n }",
"gotoPrevHit() {\n const me = this;\n\n if (!me.found || !me.found.length) return;\n\n const grid = me.grid,\n fromCell = grid.focusedCell || grid.lastFocusedCell,\n currentIndex = fromCell ? grid.store.indexOf(fromCell.id) : 0,\n found = me.found;\n\n for (let i = found.length - 1; i--; i >= 0) {\n const hit = found[i];\n if (hit.index < currentIndex) {\n me.gotoHit(i);\n break;\n }\n }\n }",
"function prevSlide() {\n if (currentIndex > 0) {\n scrollTo(currentIndex - 1);\n }\n }",
"function goPrevious() {\n goto(currentIndex - 1, \"\", true);\n}",
"scrollPrevious() {\n if (this.scrollCurrentPosition > 0) {\n this.scrollCurrentPosition--;\n this.cardsScroll.style.left = `-${this.scrollCurrentPosition * this.stepSize}px`;\n }\n this.showControls();\n }",
"function gotoPrevious() {\n var currentIndex = findCurrentIndexInList();\n if (currentIndex == -1)\n return;\n var previousIndex = currentIndex - 1;\n // If next is == -1 then loop to length\n if (previousIndex == -1) {\n previousIndex = activeList.members.length - 1;\n }\n gotoItemInActiveList(previousIndex);\n}",
"function goPrevious() {\n slideTo(currentIndex - 1);\n }",
"nextPoke(){\n\t\t//first checks to see if its at the last pokemon in the array\n\t\tif(this.current == this.pokes.length - 1){ \n\t\t\t//if it is, the variable representing the position of the pokemon in the array cycles back to zero\n\t\t\tthis.current = 0; \n\t\t}\n\t\telse{\n\t\t\t//if it's not the last position in the array it simply goes to the next one\n\t\t\tthis.current++; \n\t\t}\n\t\t//then calls the function to load those attributes\n\t\tthis.loadPoke();\n\t}",
"gotoPrevHit() {\n let me = this,\n grid = me.grid,\n currentId = grid._focusedCell ? grid._focusedCell.id : grid.lastFocusedCell.id,\n currentIndex = grid.store.indexOf(currentId) || 0,\n found = me.found,\n prevHit;\n\n if (!found.length) return;\n\n for (let i = found.length - 1; i--; i >= 0) {\n if (found[i].index < currentIndex) {\n prevHit = found[i];\n break;\n }\n }\n\n if (prevHit) {\n grid.focusCell({\n columnId: me.columnId,\n id: prevHit.id\n });\n } else {\n me.gotoLastHit();\n }\n }",
"gotoPrevHit() {\n let me = this,\n grid = me.grid,\n currentId = grid._focusedCell ? grid._focusedCell.id : grid.lastFocusedCell.id,\n currentIndex = grid.store.indexOf(currentId) || 0,\n found = me.found,\n prevHit;\n if (!found.length) return;\n\n for (let i = found.length - 1; i--; i >= 0) {\n if (found[i].index < currentIndex) {\n prevHit = found[i];\n break;\n }\n }\n\n if (prevHit) {\n grid.focusCell({\n columnId: me.columnId,\n id: prevHit.id\n });\n } else {\n me.gotoLastHit();\n }\n }",
"function jumpToPrevious(){\n if(indexCardInFocus==1){\n indexCardInFocus=16;\n }else if(indexCardInFocus!=0){\n indexCardInFocus--;\n }\n if (indexCardInFocus==0){\n indexCardInFocus=1;\n }\n while(!document.querySelector(`li[tabIndex='${indexCardInFocus}']`)){\n if (indexCardInFocus==1){\n indexCardInFocus=17;\n }\n indexCardInFocus--;\n }\n}",
"searchPrev(){\n this.searchIndex--;\n this.searchMovie();\n this.$nextTick(function(){\n scrollRight(\"search_display\");\n });\n }",
"prev() {\n this._historyIndex -= 1;\n this._selectItem(this._historyIndex);\n }",
"function scrollCarouselPrevious() {\n\t\tvar currentId = getCarouselIdFromUrl();\n\t\tvar previousId = currentId-1;\n\n\t\tloadCarouselPage(previousId);\n\t}",
"function prevPic() {\n\n let height = $('.comic-page-container').outerHeight(true);\n if (did_scroll) {\n did_scroll = false;\n let pos = $('#read-area').scrollTop();\n current_page_idx = Math.ceil(pos / height);\n }\n current_page_idx--;\n if (current_page_idx < 0) current_page_idx = 0;\n\n if ($(\"#\" + page_id_list[current_page_idx]).offset() !== undefined ) {\n scrollToPage(current_page_idx);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the axes of the graph, as well as the unit markers and grid lines. Finally, label all of the unit markers. | drawAxes() {
this.context.fillStyle = DEFAULT_PLOT_PARAMETERS.color;
if(this.drawYAxis) {
assert(this.range.x.min <= 0 && this.range.y.max >= 0,
'Cannot draw the y axis as it is out of range.')
let labelWidth = this.context.measureText('y').width;
//has to be fudged to look right
let labelPosY = 0;
let labelPosX = this.center.x - (labelWidth / 2);
this.context.fillText('y', labelPosX, labelPosY);
this._drawLine(this.center.x, LABELHEIGHT + AXIS_ARROW_LENGTH, this.center.x,
this.height, 2);
this.context.beginPath();
this.context.lineWidth = 1;
this.context.moveTo(this.center.x, LABELHEIGHT);
this.context.lineTo(this.center.x + 5, LABELHEIGHT + AXIS_ARROW_LENGTH);
this.context.lineTo(this.center.x - 5, LABELHEIGHT + AXIS_ARROW_LENGTH);
this.context.fill();
if(this.drawYUnits) {
let stepSize = this.stepY;
let i = stepSize.times(Math.ceil(this.drawRegion.bottom / stepSize.approx));
for(; i.lessThan(this.drawRegion.top); i = i.plus(stepSize)) {
if(!(i.equal(0))) {
let yPos = this.center.y - i.approx * this.unitSize.y;
this._drawLine(this.center.x, yPos, this.center.x + 6, yPos, 2);
i.draw(this.context, {top: yPos, right: this.center.x});
if(this.drawGrid) {
this._drawLine(0, yPos, this.width - LABELWIDTH, yPos, 1,
[5, 5]);
}
}
}
}
}
if(this.drawXAxis) {
assert(this.range.y.min <= 0 && this.range.y.max >= 0,
'Cannot draw the x axis as it is out of range.')
let labelWidth = this.context.measureText('x').width;
//has to be fudged to look right
let labelPosY = this.center.y - FONTSIZE / 2;
let labelPosX = this.width - (LABELWIDTH / 2) - (labelWidth / 2);
this.context.fillText('x', labelPosX, labelPosY);
this._drawLine(0, this.center.y, this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y, 2);
this.context.beginPath();
this.context.lineWidth = 1;
this.context.moveTo(this.width - LABELWIDTH, this.center.y);
this.context.lineTo(this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y + 5);
this.context.lineTo(this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y - 5);
this.context.fill();
if(this.drawXUnits) {
let stepSize = this.stepX;
let xMin = this.range.x.min
let i = stepSize.times(Math.ceil(this.drawRegion.left / stepSize.approx));
for(; i.lessThan(this.drawRegion.right); i = i.plus(stepSize)) {
if(!(i.equal(0))) {
let xPos = this.center.x + i.approx * this.unitSize.x;
//are any of the labels fractions? if step is an integer,
//or an integral multiple of pi, then no.
if(stepSize.approx === parseInt(stepSize.approx)) {
var areFractions = false;
} else {
let stepSizeDivPi = stepSize.divide(new Rational("pi"));
if(stepSizeDivPi.approx === parseInt(stepSizeDivPi.approx)) {
var areFractions = false;
} else {
var areFractions = true;
}
}
this._drawLine(xPos, this.center.y, xPos, this.center.y - 6, 2);
let labelYPos = this.center.y + MARKING_PADDING_TOP;
if(i.greaterThan(0)) {
i.draw(this.context, {top: labelYPos, left: xPos}, areFractions);
} else if(i.lessThan(0)) {
i.draw(this.context, {top: labelYPos, right: xPos}, areFractions);
}
if(this.drawGrid) {
this._drawLine(xPos, LABELHEIGHT, xPos, this.height, 1,
[5, 5]);
}
}
}
}
}
//draw origin
if(this.drawOrigin) {
let origin = new Rational(0);
origin.draw(this.context, {top: this.center.y, right: this.center.x});
}
} | [
"function drawAxisLabelMarkers() {\n context.lineWidth = \"2.0\";\n // draw y axis\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace, cMargin);\n // draw x axis\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace + cWidth, cMarginHeight);\n context.lineWidth = \"1.0\";\n drawMarkers();\n}",
"function drawAxes() {\n\t//draw axes\n\tvar ctx = c.getContext(\"2d\");\n\tctx.lineWidth = 1;\n\tctx.beginPath();\n\tctx.moveTo(axesOffset, axesOffset);\n\tctx.lineTo(axesOffset, canvasHeight - axesOffset);\n\tctx.lineTo(canvasWidth - axesOffset, canvasHeight - axesOffset);\n\tctx.strokeStyle = \"#000000\";\n\tctx.stroke();\n\t\n\t//draw interval markers\n\tvar markLength = 5;\n\txInterval = xMax / numAxisMarkers;\n\tyInterval = yMax / numAxisMarkers;\n\tctx.font = \"12px Courier\";\n\tctx.fillStyle = \"#000000\";\n\t\n\t//x axis interval markers\n\tfor (var i = 1; i < numAxisMarkers + 1; i++) {\n\t\tctx.beginPath();\n\t\tctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);\n\t\tctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - markLength); //5 = marker length\n\t\tctx.stroke();\n\t\tctx.textAlign = \"center\";\n\t\tctx.fillText(Number((i * xInterval).toFixed(3)), axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset + 12); //12 is text offset\n\t\t\n\t\t//draw the grid if enabled\n\t\tif (showGrid) {\n\t\t\tctx.save();\n\t\t\tctx.globalAlpha = alpha;\n\t\t\tctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);\n\t\t\tctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - graphWidth);\n\t\t\tctx.stroke();\n\t\t\tctx.restore();\n\t\t}\n\t}\n\t\n\t//y axis interval markers\n\tfor (var i = 1; i < numAxisMarkers + 1; i++) {\n\t\tctx.beginPath();\n\t\tctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\tctx.lineTo(axesOffset + markLength, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers))); //5 = marker length\n\t\tctx.stroke();\n\t\tctx.textAlign = \"right\";\n\t\tctx.fillText(Number((i * yInterval).toFixed(3)), axesOffset - 4, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)) + 3); //4 and 3 are text offset\n\t\t\n\t\t//draw the grid if enabled\n\t\tif (showGrid) {\n\t\t\tctx.save();\n\t\t\tctx.globalAlpha = alpha;\n\t\t\tctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\t\tctx.lineTo(axesOffset + graphHeight, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\t\tctx.stroke();\n\t\t\tctx.restore();\n\t\t}\n\t}\n\t//draw \"0\" at origin\n\tctx.fillText(\"0\", axesOffset - 4, canvasHeight - axesOffset + 4);\n}",
"function drawAxisLabelMarkers() {\r\n context.lineWidth = \"2.0\";\r\n // draw y axis\r\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace, cMargin);\r\n // draw x axis\r\n drawAxis(cMarginSpace, cMarginHeight, cMarginSpace + cWidth, cMarginHeight);\r\n context.lineWidth = \"1.0\";\r\n drawMarkers();\r\n}",
"function drawAxisMarkers() {\n var markerStep = maximumDataValueY / totalLabelOnXYAxis;\n // On Y Axis\n for (var i = 0; i <= totalLabelOnXYAxis; i++) {\n var markerVal = i * markerStep;\n var markerValHt = i * barHeight - 30;\n markerValHt = parseInt(chartHeight - markerValHt);\n draw.line(50, markerValHt, 400, markerValHt).stroke({\n width: .5\n });\n var text = draw.text(markerVal.toString() + yUnit).move(0, markerValHt);\n text.font({\n family: 'Helvetica',\n size: 11\n })\n }\n\n var markerStep = maximumDataValueX / totalLabelOnXYAxis;\n // On X Axis.\n for (var i = 0; i <= totalLabelOnXYAxis; i++) {\n var markerVal = i * markerStep;\n var markerValWidth = parseInt(i * barWidth + marginPx);\n draw.line(markerValWidth, 280, markerValWidth, 250).stroke({\n width: .5\n });\n var text = draw.text(markerVal.toString() + xUnit).move(markerValWidth, 280);\n text.font({\n family: 'Helvetica',\n size: 11\n })\n }\n // Draws the unit measurement label on each axis. Example: ft, miles, years, %\n draw.text(yAxisLabel)\n draw.text(xAxisLabel).move(marginPx + chartWidth, 240)\n }",
"draw_axes () {\n let canvas = this.layers.get(CONST.CHART_LAYER_AXES);\n\n // Draw axes\n let ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n ctx.strokeStyle = CONST.WHITE;\n ctx.lineWidth = 3;\n\n ctx.beginPath();\n ctx.moveTo(0, canvas.height-this.chart_padding_x_axis);\n ctx.lineTo(canvas.width - this.chart_padding_y_axis, canvas.height-this.chart_padding_x_axis);\n ctx.lineTo(canvas.width - this.chart_padding_y_axis, 0);\n ctx.stroke();\n\n this.draw_axes_labels();\n }",
"drawLabelsAndAxis() {\n\t\t// Loop around the dataSet and write labels\n\t\tvar index = 0;\n\t\tfor (index = 0; index < this.getDataSet().length; index++) {\n\t\t\tthis.drawLabelLevel1(index);\n\t\t\tthis.drawLabelLevel2(index);\n\t\t\tthis.drawAxis(index);\n\t\t}\n\t}",
"function drawAxesLabels() {\n plotContainer.append('text')\n .attr('x', (msm.width - 2 * msm.marginAll) / 2 - 130)\n .attr('y', msm.marginAll / 2 + 10)\n .style('font-size', '14pt')\n .text(\"Pokemon: Special Defense vs Total Stats\");\n\n plotContainer.append('text')\n .attr('x', (msm.width - 2 * msm.marginAll) / 2 - 10)\n .attr('y', msm.height - 10)\n .style('font-size', '10pt')\n .text(\"Special Defense\");\n\n plotContainer.append('text')\n .attr('transform', 'translate( 15,' + (msm.height / 2 + 30) + ') rotate(-90)')\n .style('font-size', '10pt')\n .text(\"Total Stats\");\n}",
"function draw_axes(ctx) {\n const xm = g_eye == EYE_LEFT ? 1 : -1 ; \n\n const x_axis_y = g_cy +28*g_d2p; // virtual pixels\n const y_axis_x = g_cx -35*g_d2p; // virtual pixels\n const tick_len = 1.0 * g_d2p; // virtual pixels\n\n // draw axes\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"black\";\n ctx.lineWidth=1;\n ctx.moveTo(scale(g_cx - 27*g_d2p), yscale(x_axis_y)); // x-axis\n ctx.lineTo(scale(g_cx + 27*g_d2p), yscale(x_axis_y));\n ctx.moveTo(scale(y_axis_x), yscale(g_cy -27*g_d2p)); // y-axis\n ctx.lineTo(scale(y_axis_x), yscale(g_cy +27*g_d2p)); \n\n ctx.font= scale(20) + \"px Arial\";\n ctx.textBaseline=\"middle\"; \n for (i = -27 ; i <= 27 ; i += 6) {\n // x-ticks\n const x = scale(g_cx + i*g_d2p);\n ctx.moveTo(x, yscale(x_axis_y)); \n ctx.lineTo(x, yscale(x_axis_y + tick_len));\n ctx.textAlign = \"center\"; // below?\n ctx.fillText(i, x, yscale(x_axis_y + tick_len + 20/2));\n\n // y-ticks\n const y = yscale(g_cy + i*g_d2p);\n ctx.moveTo(scale(y_axis_x - tick_len), y); \n ctx.lineTo(scale(y_axis_x) , y);\n ctx.textAlign = \"right\";\n ctx.fillText(-i, scale(y_axis_x - tick_len), y);\n }\n ctx.stroke();\n\n // axis sliders\n ctx.beginPath();\n ctx.font = scale(20) + \"px Arial\";\n ctx.fillStyle = \"purple\";\n ctx.strokeStyle = \"purple\";\n ctx.textBaseline=\"middle\"; \n\n // draw ONHX slider \n var tx = scale(g_cx + xm * g_onhx * g_d2p);\n var ty = yscale(x_axis_y + 4.0 * g_d2p);\n ctx.font = scale(18) + \"px Arial\";\n ctx.textAlign = \"center\";\n ctx.fillText(\"ONH \" + xm * g_onhx, tx, ty + yscale(1.0 * g_d2p));\n ctx.moveTo(tx, ty);\n ctx.lineTo(tx, yscale(x_axis_y));\n ctx.stroke();\n g_regions.push([tx, ty, REGION_ONHX]);\n\n // draw ONHY slider \n tx = scale(y_axis_x - 3.0 * g_d2p);\n ty = yscale(g_cy + g_d2p * g_onhy);\n ctx.textAlign = \"right\";\n ctx.fillText(\"ONH \" + g_onhy, tx, ty);\n ctx.moveTo(tx, ty);\n ctx.lineTo(scale(y_axis_x), ty);\n ctx.stroke();\n g_regions.push([tx, ty, REGION_ONHY]);\n\n ctx.closePath();\n}",
"drawAxes() {\n this.drawLabels([\n { label: LightTypes.A, column: 9 },\n { label: LightTypes.B, column: 10 },\n ])\n \n let colLabels = new Array(8).fill(null).map((_, i) => ({ label: `${i + 1}`, column: i }))\n this.drawLabels(colLabels)\n \n this.ctx.beginPath()\n this.ctx.strokeStyle = \"black\"\n this.ctx.moveTo(0, this.maxDrawH * 1.01)\n this.ctx.lineTo(this.w, this.maxDrawH * 1.01)\n this.ctx.moveTo(8 * this.barColumnW + this.barColumnW / 2, this.h)\n this.ctx.lineTo(8 * this.barColumnW + this.barColumnW / 2, 0)\n this.ctx.stroke()\n }",
"function update_axes ()\n\t{\n\t var viewBox;\t\t/* Axis viewBox */\n\t var plotWidth;\t\t/* Plot width, SVG coordinates */\n\t var plotHeight;\t\t/* Plot height, SVG coordinates */\n\t var axisWidth;\t\t/* Axis width, SVG coordinates */\n\t var axisHeight;\t\t/* Axis height, SVG coordinates */\n\t var cart;\t\t\t/* Limits of plot in Cartesian\n\t\t\t\t\t coordinates */\n\t var xForm;\t\t\t/* Transform to rotate y axis title */\n\t var lbl;\t\t\t/* Label text element */\n\t var bbox;\t\t\t/* Bounding box for lbl */\n\n\t plotWidth = plot.width.baseVal.value;\n\t plotHeight = plot.height.baseVal.value;\n\t cart = get_cart();\n\n\t /* Update font size and padding */\n\t lbl = document.getElementsByClassName(\"xAxisLabel\")[0];\n\t bbox = lbl.getBBox();\n\t font_sz = bbox.height;\n\t pad = xAxis.height.baseVal.value - tick_len - font_sz;\n\n\t /* Restore x axis position and update viewBox */\n\t xAxis.setAttribute(\"x\", xAxisSVGX);\n\t xAxisSVGY = plotSVGY + plotHeight;\n\t xAxis.setAttribute(\"y\", xAxisSVGY);\n\t axisWidth = plotWidth + xOverHang;\n\t axisHeight = xAxis.viewBox.baseVal.height;\n\t xAxis.setAttribute(\"width\", axisWidth);\n\t xAxisClip.setAttribute(\"y\", xAxisSVGY);\n\t xAxisClip.setAttribute(\"width\", axisWidth);\n\t viewBox = xAxisSVGX;\n\t viewBox += \" \" + xAxisSVGY;\n\t viewBox += \" \" + axisWidth;\n\t viewBox += \" \" + axisHeight;\n\t xAxis.setAttribute(\"viewBox\", viewBox);\n\t xTitle.setAttribute(\"x\", xAxisSVGX + axisWidth / 2.0);\n\t xTitle.setAttribute(\"y\", xAxisSVGY + axisHeight + pad + font_sz);\n\n\t /* Create new labels for x axis */\n\t mk_labels(cart.left, cart.rght, apply_x_coords, plotWidth / 4);\n\n\t /* Restore y axis position and update viewBox */\n\t yAxis.setAttribute(\"y\", yAxisSVGY);\n\t axisWidth = yAxis.viewBox.baseVal.width;\n\t axisHeight = plotHeight + yOverHang;\n\t yAxis.setAttribute(\"height\", axisHeight);\n\t yAxisClip.setAttribute(\"height\", axisHeight);\n\t viewBox = yAxis.viewBox.baseVal.x;\n\t viewBox += \" \" + yAxisSVGY;\n\t viewBox += \" \" + axisWidth;\n\t viewBox += \" \" + axisHeight;\n\t yAxis.setAttribute(\"viewBox\", viewBox);\n\t xForm = yTitleXForm.transform.baseVal.getItem(0).matrix;\n\t xForm.f = yAxisSVGY + axisHeight / 2.0;\n\n\t /* Create new labels for y axis */\n\t mk_labels(cart.btm, cart.top, apply_y_coords, plotHeight / 4);\n\t}",
"function drawAxisLabels(){\n fill(0);\n textSize(13);\n textAlign(CENTER, CENTER);\n text(\"Magnitude\", 50, (y_top+y_bot)/2);\n textAlign(CENTER);\n text(\"Date\", (x_left+x_right)/2, y_bot+40);\n\n}",
"function drawLabels(){\t\t\n\t\t\t/**\n\t\t\t * Construct fixed width label boxes, which can be styled easily. \n\t\t\t */\n\t\t\tvar noLabels = 0;\n\t\t\tfor(var i = 0; i < xaxis.ticks.length; ++i){\n\t\t\t\tif (xaxis.ticks[i].label) {\n\t\t\t\t\t++noLabels;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar xBoxWidth = plotWidth / noLabels;\n\t\t\tvar html = '<div style=\"font-size:smaller;color:' + options.grid.color + '\">';\n\t\t\t/**\n\t\t\t * Add xlabels.\n\t\t\t */\n\t\t\tfor(var j = 0, tick = null; j < xaxis.ticks.length; ++j){\n\t\t\t\ttick = xaxis.ticks[j];\n\t\t\t\tif(!tick.label) continue;\n\t\t\t\thtml += '<div style=\"position:absolute;top:' + (plotOffset.top + plotHeight + options.grid.labelMargin) + 'px;left:' + (plotOffset.left + tHoz(tick.v) - xBoxWidth/2) + 'px;width:' + xBoxWidth + 'px;text-align:center\" class=\"flotr-grid-label\">' + tick.label + \"</div>\";\n\t\t\t}\n\t\t\t\n\t\t\t/**\n\t\t\t * Add ylabels.\n\t\t\t */\n\t\t\tfor(var k = 0, tick = null; k < yaxis.ticks.length; ++k){\n\t\t\t\ttick = yaxis.ticks[k];\n\t\t\t\tif (!tick.label || tick.label.length == 0) continue;\n\t\t\t\thtml += '<div style=\"position:absolute;top:' + (plotOffset.top + tVert(tick.v) - labelMaxHeight/2) + 'px;left:0;width:' + labelMaxWidth + 'px;text-align:right\" class=\"flotr-grid-label\">' + tick.label + \"</div>\";\n\t\t\t}\n\t\t\thtml += '</div>';\t\t\n\t\t\ttarget.insert(html);\n\t\t}",
"drawAxisLabelMarkers(arrData) {\n\n this.context.lineWidth = '2.0';\n\n // draw y axis\n this.drawAxis(this.cMarginSpace, this.cMarginHeight, this.cMarginSpace, this.cMargin);\n\n // draw x axis\n this.drawAxis(this.cMarginSpace, this.cMarginHeight, this.cMarginSpace + this.cWidth, this.cMarginHeight);\n\n this.context.lineWidth = '1.0';\n\n this.drawMarkers(arrData);\n\n }",
"function render(){\n reset();\n _innerG.attr('transform', \"translate(\" + _chart.x() + \",\" + _chart.y() + \")\");\n _labelG.attr('transform', \"translate(\" + _chart.x() + \",\" + _chart.y() + \")\");\n drawLabels();\n drawPixels();\n }",
"function drawAxesTitles(){\n //Draw x axis title label\n ctx.fillText(xAxisTitle, xPos + graphWidth/2 , yPos + graphHeight + fontSize*3);\n ctx.save();\n \n //Draw y axis title label\n ctx.translate(xPos - fontSize*3, yPos + graphHeight/2);\n ctx.rotate(3*Math.PI/2);\n ctx.fillText(yAxisTitle, 0, 0);\n //ctx.fillText(\"Y-Axis Title\", xPos - 36, yPos + graphHeight/2);\n ctx.restore();\n console.log(\"Y-Axis is drawn\");\n }",
"function drawMarkers() {\r\n var numMarkers = parseInt(maxDataValue / totLabelsOnYAxis);\r\n context.textAlign = \"right\";\r\n context.fillStyle = \"#000\"; ;\r\n\r\n // Y Axis\r\n for (var i = 0; i <= totLabelsOnYAxis; i++) {\r\n markerVal = i * numMarkers;\r\n markerValHt = i * numMarkers * cHeight;\r\n var xMarkers = cMarginSpace - 5;\r\n var yMarkers = cMarginHeight - (markerValHt / maxDataValue);\r\n context.fillText(markerVal, xMarkers, yMarkers, cSpace);\r\n }\r\n\r\n // X Axis\r\n context.textAlign = 'center';\r\n for (var i = 0; i < totalBars; i++) {\r\n// arrval = Months[i].split(\",\");\r\n arrval = percents[i].split(\",\");\r\n\r\n name = arrval[0];\r\n\r\n\r\n markerXPos = cMarginSpace + bMargin + (i * (bWidth + bMargin)) + (bWidth / 2);\r\n markerYPos = cMarginHeight+13;\r\n context.fillText(name, markerXPos, markerYPos, bWidth);\r\n }\r\n context.save();\r\n // Add Y Axis title\r\n context.translate(cMargin, cHeight / 2);\r\n context.rotate(Math.PI * -90 / 180);\r\n context.fillText('', 0, 0);\r\n context.restore();\r\n // Add X Axis Title\r\n context.fillText('', cMarginSpace + (cWidth / 2), cMarginHeight + 30);\r\n}",
"function redrawAxes() {\r\n xAxis.scale(xScale)\r\n yAxis.scale(yScale)\r\n\r\n plotXAxis.call(xAxis);\r\n plotYAxis.call(yAxis);\r\n\r\n plotXAxis.selectAll('line').style({\r\n 'fill': 'none',\r\n 'stroke': '#dbdbdb',\r\n 'shape-rendering': 'crispEdges'\r\n })\r\n\r\n var lastBBox;\r\n var rotateLabels = false;\r\n\r\n plotXAxis.selectAll('text').style({\r\n 'text-anchor': 'middle'\r\n })\r\n .attr('transform', 'rotate(0)');\r\n\r\n plotXAxis.selectAll('text').each(function () {\r\n\r\n var currentBBox = this.getBoundingClientRect();\r\n\r\n if (lastBBox == undefined) {\r\n lastBBox = currentBBox;\r\n } else if (lastBBox.right > currentBBox.left - 2) {\r\n rotateLabels = true;\r\n return false;\r\n } else {\r\n lastBBox = currentBBox;\r\n }\r\n });\r\n\r\n if (rotateLabels == true) {\r\n plotXAxis.selectAll('text').style({\r\n 'text-anchor': 'end'\r\n })\r\n .attr('dx', '-.2em')\r\n .attr('dy', '.4em')\r\n .attr('transform', 'rotate(-65)');\r\n }\r\n\r\n plotYAxis.selectAll('line').style({\r\n 'fill': 'none',\r\n 'stroke': '#dbdbdb',\r\n 'shape-rendering': 'crispEdges'\r\n })\r\n\r\n }",
"function drawAxes(svg) {\n // Note: scales must be updated first\n let leftAxis = d3.axisLeft(yScale);\n let bottomAxis = d3.axisBottom(xScale);\n if (useGrid) {\n leftAxis.tickSize(-1 * (width - margin.right - margin.left - chartPadding/2));\n bottomAxis.tickSize(-1 * (height - margin.top - margin.bottom - chartPadding));\n }\n svg.append(\"g\")\n .attr('id', 'yAxis')\n .attr('transform', translate(margin.left - 10, margin.top))\n .call(leftAxis);\n svg.append(\"g\")\n .attr('id', 'xAxis')\n .attr(\"transform\", translate(margin.left, height - margin.bottom))\n .call(bottomAxis);\n\n // Draw the titles\n let labels = svg.append('g')\n .attr('id', 'labels');\n\n let xTitle = svg.attr(xTitleAttr);\n labels.append('text')\n .text(xTitle)\n .style('fill', 'black')\n .style('font-size', '0.8rem')\n .attr('id', 'xTitle')\n .attr('text-anchor', 'middle')\n .attr(\"transform\", translate(width / 2 , height - margin.bottom))\n .attr('x', 0)\n .attr('y', +35);\n\n let yTitle = svg.attr(yTitleAttr);\n let rotateGroup = labels.append('g')\n .attr('id', 'group-yTitle')\n .attr(\"transform\", translate(margin.left , ((height-margin.bottom - margin.top) / 2) + margin.top));\n\n rotateGroup.append('text')\n .text(yTitle)\n .style('fill', 'black')\n .style('font-size', '0.8rem')\n .attr('id', 'yTitle')\n .attr('text-anchor', 'middle')\n .attr('transform', \"rotate(-90)\")\n // .attr('x', -10)\n .attr('y', -45);\n }",
"function draw_axes() {\n\t\t// Open the path to start drawing\n\t\tcontext.beginPath();\n\t\t\n\t\t// Start the path at the top of the y-axis\n\t\tcontext.moveTo(40, graph_properties.top_gap);\n\t\t\n\t\t// Draw the rest of the path\n\t\tcontext.lineTo(40, 344);\n\t\tcontext.lineTo(490, 344);\n\t\tcontext.lineTo(490, 339);\n\t\t\n\t\t// Set the color of the axes and slap 'em in\n\t\tcontext.strokeStyle = graph_properties.axes_color;\n\t\tcontext.stroke();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets or sets the series legend item badge templae. | get legendItemBadgeTemplate() {
return this.i.legendItemBadgeTemplate;
} | [
"get legendItemTemplate() {\r\n return this.i.legendItemTemplate;\r\n }",
"_getLegendItem(target) {\n const item = target.get('parent');\n if (item && (item.name === 'legendGroup')) {\n return item;\n }\n return null;\n }",
"getLegend ()\n {\n return (this._legend);\n }",
"get badge() {\n const text = this.metadata?.annotations?.[CLUSTER_BADGE.TEXT];\n\n if (!text) {\n return undefined;\n }\n\n const color = this.metadata?.annotations[CLUSTER_BADGE.COLOR] || '#7f7f7f';\n const iconText = this.metadata?.annotations[CLUSTER_BADGE.ICON_TEXT] || '';\n\n return {\n text,\n color,\n textColor: textColor(parseColor(color)),\n iconText: iconText.substr(0, 2)\n };\n }",
"get legend() {\n if (this.i.legend != null)\n return this.i.legend.externalObject;\n }",
"get legend() {\n return this._getOption('legend');\n }",
"get actualItemTextColor() {\n return brushToString(this.i.e6);\n }",
"function di_getLegendObject()\n{\n var chartLegend = {\n align: \"center\",\n backgroundColor: \"#ffffff\",\n borderColor: \"#909090\",\n borderRadius: 5,\n borderWidth: 1,\n enabled: true,\n floating: false, \n itemWidth: null,\n layout: \"horizontal\", \n lineHeight: 8,\n margin: 15,\n reversed: false,\n shadow: false,\n itemStyle: {},\n symbolPadding: 5,\n symbolWidth: 10,\n verticalAlign: \"bottom\",\n width: null,\n x:0,\n y:0\n };\n return chartLegend;\n}",
"get badgeDot() {\n return this._badgeDot;\n }",
"get legendItemVisibility() {\r\n return this.i.legendItemVisibility;\r\n }",
"get itemDisabledTextColor() {\n return brushToString(this.i.hr);\n }",
"get negativeMarkerBrush() {\r\n return brushToString(this.i.fg);\r\n }",
"function LegendItem() {\n var _this;\n\n _this = _ComponentInterface.call(this) || this;\n _this._stateCosmetics = {};\n _this._legendState = [];\n return _this;\n }",
"populateLegend() {\n this.dom.chartData[1].querySelector('.label').innerText = this.chartData.data[0].label;\n this.dom.chartData[1].querySelector('.label').style.color = this.chartData.data[0].color;\n this.dom.chartData[1].querySelector('.percentage').innerText = (this.chartData.data[0].quantity * 100) / (this.chartData.data[0].quantity + this.chartData.data[1].quantity) + '%';\n this.dom.chartData[1].querySelector('.quantity').innerText = this.chartData.data[0].quantity.toLocaleString() + this.chartData.unit;\n this.dom.chartData[0].querySelector('.label').innerText = this.chartData.data[1].label;\n this.dom.chartData[0].querySelector('.label').style.color = this.chartData.data[1].color;\n this.dom.chartData[0].querySelector('.percentage').innerText = (this.chartData.data[1].quantity * 100) / (this.chartData.data[0].quantity + this.chartData.data[1].quantity) + '%';\n this.dom.chartData[0].querySelector('.quantity').innerText = this.chartData.data[1].quantity.toLocaleString() + this.chartData.unit;\n }",
"get negativeMarkerBrush() {\n return brushToString(this.i.fg);\n }",
"get minorTickBrush() {\n return brushToString(this.i.ia);\n }",
"get itemHoverTextColor() {\n return brushToString(this.i.ht);\n }",
"get outlinedItemTextColor() {\n return brushToString(this.i.h2);\n }",
"legendHandler(e, legendItem) {\n let index = legendItem.datasetIndex;\n let ci = this.chart;\n let meta = ci.getDatasetMeta(index);\n\n meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;\n chart.metas[index] = meta.hidden;\n\n ci.update({\n \"duration\": 0,\n \"lazy\": true,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LOAD HUD DATA this will copy a huds config.json to ~/.linuxsystemhud/hdef/ reseting it to default | function resetHudDef(hudid){
let src = path.join(appdata.huds, hudid, "config.json")
let dest = path.join( appdata.hdef, hudid + ".json")
// if hud config is not in appdata.huds then check node_modules
if (!fs.existsSync(src)){
src = path.join(__dirname, 'node_modules', hudid, "config.json")
}
if (!fs.existsSync(src)){
console.log(`LSH:resetHudDef(${hudid}) ERROR: file not found`);
return
}
fs.copyFileSync(src,dest )
} | [
"function loadHudData() {\n console.log(\"LSH: Begin loading hud definitions \");\n let filelist, hpath\n // Load all the default (built-in) huds\n hpath = path.join(__dirname, 'node_modules')\n config.default_huds.forEach((hudid, i) => {\n if (!fs.existsSync( path.join(appdata.hdef, hudid+\".json\") )){\n resetHudDef(hudid)\n }\n HDEF[hudid] = JSON.parse( fs.readFileSync( path.join(appdata.hdef, hudid+\".json\") , 'utf8' ) )\n HDEF[hudid].path = path.join(hpath, hudid)\n });\n\n // search ~/.linux-system-hud/huds/ for any other huds or overrides of the defaults\n hpath = appdata.huds\n filelist = fs.readdirSync( hpath , { withFileTypes:true })\n for (let i = 0; i < filelist.length; i++) {\n //console.log(filelist[i]);\n if (filelist[i].isDirectory()) {\n let hudid = filelist[i].name\n if ( fs.existsSync( path.join( hpath , hudid , \"config.json\" ) ) ){\n console.log(\"LSH: found hud folder \", hudid);\n if (!fs.existsSync( path.join(appdata.hdef, hudid+\".json\") )){\n resetHudDef(hudid)\n }\n HDEF[hudid] = JSON.parse( fs.readFileSync( path.join(appdata.hdef, hudid+\".json\") , 'utf8' ) )\n HDEF[hudid].path = path.join(hpath, hudid)\n\n }\n }\n }\n\n console.log(\"LSH: Finished loading hud definitions\");\n // create all active huds\n for (let id in HDEF){\n if (HDEF[id].active === true){\n setTimeout(() => {\n createHud(id);\n }, 500);\n\n }\n }\n}",
"function saveHudConfig(hudid){\n fs.writeFileSync(path.join(appdata.hdef , `${hudid}.json`), JSON.stringify(HDEF[hudid],null,4) ) //\n}",
"load() {\n if (this.__data) {\n // Bot data has already been loaded\n return;\n }\n\n // On error, silently replace with empty data\n try {\n let contents = fs.readFileSync(__dirname + '/../.data/data.json', 'utf8');\n this.__data = JSON.parse(contents);\n } catch (err) {\n // File access or malformed JSON error\n this.__data = {};\n }\n }",
"function createHud(hudid) {\n console.log(\"LSH: createHud() \", hudid);\n // Create the browser window.\n if ( HUD[hudid]) {\n console.log(`LSH: hud ${hudid} already exists`);\n return;\n }\n //reference this huds definition\n let hdef = HDEF[hudid]\n // setup values to check\n let show_win = true\n let paint_win = true\n let skip_taskbar = true\n let transparent_win = false\n let resizable_win = hdef.resizable\n let framed_win = hdef.frame\n if (hdef.hud_type === \"normal\" && hdef.is_hidden === true){ show_win = false }\n if (hdef.hud_type === \"freestyle\" && hdef.show_on_startup === false || hdef.hud_type === \"background\") {\n show_win = false\n //paint_win = false\n }\n if (hdef.hud_type === \"freestyle\" ){ skip_taskbar = false }\n // setup for transparent window if enabled\n if (hdef.transparent === true && args.includes(\"-t\") ) {\n console.log(\"LSH: Creating transparent window\");\n transparent_win = true\n resizable_win = false\n framed_win = false\n }\n\n HUD[hudid] = {}\n HUD[hudid].focus = false\n HUD[hudid].win = new BrowserWindow({\n x:hdef.x,\n y:hdef.y,\n width: hdef.width,\n height: hdef.height,\n transparent:transparent_win,\n frame:framed_win,\n show:show_win,\n skipTaskbar:skip_taskbar,\n paintWhenInitiallyHidden:paint_win, // maybe don't need this\n resizable:resizable_win,\n webPreferences: {\n contextIsolation: false,\n preload: path.join(hdef.path , 'preload.js')\n\n },\n icon: path.join(hdef.path, 'assets/icon.png')\n })\n HUD[hudid].winid = HUD[hudid].win.getNativeWindowHandle().readUInt32LE()\n console.log(`LSH: ${hudid} native window id: `, HUD[hudid].winid);\n // hide the default electron menu\n HUD[hudid].win.setMenuBarVisibility(false)\n // set skiptaskbar\n HUD[hudid].win.setSkipTaskbar(skip_taskbar)\n // load the html of the hud or specified url.\n if (hdef.load_url === null){\n HUD[hudid].win.loadFile( path.join(hdef.path ,`index.html`) )\n } else {\n HUD[hudid].win.loadURL( hdef.load_url )\n }\n\n HUD[hudid].views = {}\n // check for and load browser views\n if (hdef.browser_views.length > 0){\n hdef.browser_views.forEach((bv, i) => {\n let setin = false\n if (i = 0 && hdef.load_browser_view === true ) { setin = true }\n if (bv.auto_load === true || setin === true){\n createBrowserView(hudid,bv, setin)\n }\n });\n }\n\n // Open the DevTools.\n if ( hdef.open_dev_tools === true ) {\n HUD[hudid].win.webContents.openDevTools({mode:\"detach\"})\n }\n\n // set always on top\n if ( hdef.always_on_top === true ) {\n HUD[hudid].win.setAlwaysOnTop(true)\n }\n\n\n\n HUD[hudid].win.webContents.on(\"did-finish-load\",() =>{\n console.log(`LSH: hud ${hudid} did-finish-load`);\n HUD[hudid].ready = true\n // send the hud it's config definition\n HUD[hudid].win.webContents.send(\"from_mainProcess\",{type:\"config_definition\", data:HDEF[hudid]})\n hudSendPositionSize(hudid)\n if (hdef.hud_type === \"normal\" ){ checkHudsReady(hudid) }\n\n })\n\n HUD[hudid].win.on(\"blur\",() =>{\n //console.log(`HUD ${hudid} is blurred`);\n HUD[hudid].focus = false\n if (config.autohide === true ) {\n if ( hdef.hud_type === \"normal\" || hdef.hud_type === \"freestyle\" ){\n setTimeout(checkAllBlurred,config.autohide_delay)\n }\n }\n\n })\n HUD[hudid].win.on(\"focus\",() =>{\n //console.log(`HUD ${hudid} is focused`);\n HUD[hudid].focus = true\n if ( hdef.hud_type === \"normal\" ) {\n focused_hud = hudid\n }\n\n })\n HUD[hudid].win.on(\"resize\",() =>{\n //console.log(`HUD ${hudid} is resize`);\n hudSendPositionSize(hudid)\n })\n HUD[hudid].win.on(\"move\",() =>{\n //console.log(`HUD ${hudid} is move`);\n hudSendPositionSize(hudid)\n })\n HUD[hudid].win.on(\"closed\",() =>{\n destroyHud(hudid)\n\n })\n\n\n}",
"function clearHealthData() {\n PreferencesManager.setViewState(HEALTH_DATA_STATE_KEY, {});\n //clear the performance related health data also\n PerfUtils.clear();\n }",
"function loadHds () {\n\tvar input = this;\n\n\tvar components = input.value.split(\"/\");\n \tif (components.length < 2) components = input.value.split(\"\\\\\");\n d3.select(\"input#filename\").attr(\"value\",components [components.length-1]);\n var fileobj = input.files[0];\n\n var reader = new FileReader();\n\n // Closure to capture the file information.\n reader.onload = (function (theFile) {\n return function (e) {\n var text = e.target.result;\n var json = JSON.parse(text);\n var hds = HalfedgeDS.fromJSON(json);\n\n\t\t\tsvg.selectAll (\"g#main g\").remove();\n\n hdsDraw(hds);\n annotateHdsPolygonSides(hds);\n push_history();\n\t\t\tconfigureButtons ();\n\n // clear the input element so that a new load on the same file will work\n input.value = \"\";\n };\n }) (fileobj);\n\n // Read in the file as a data URL.\n reader.readAsText(fileobj);\n}",
"function create_HUD()\n\t{\n\t\thud = new Entity()\n\t\t\t.add(\n\t\t\t\tnew HUD()\n\t\t\t\t\t.watch(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdrone: drone.get( Drone ),\n\t\t\t\t\t\t\tstation: station\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t);\n\t}",
"function initGameData() {\n //Load shapes\n if (!shapeMatrix) {\n Utility.loadJson(\"../src/data/shapeMatrix\").then(json => shapeMatrix = json);\n }\n //Load images\n if (!colors) {\n Utility.loadJson(\"../src/data/colors\").then(json => colors = json);\n }\n //Load init game data\n if (!dropIntervall) {\n Utility.loadJson(\"../src/data/initData\").then((json) => {\n //Initialize data\n dropIntervall = json.dropInterval;\n currentTime = json.currentTime;\n scoreBorder = json.scoreBorder;\n player = json.player;\n direction = json.direction;\n gameIsOver = json.gameIsOver;\n gameIsRunning = json.gameIsRunning;\n });\n }\n}",
"function extract_HUD_data( csv_string )\n{\n\t//HUD data\n\tvar HUD_data = {\n\t\t'last_scan_time' : -1,\n\t\t'num_scanned_ips' : 0,\n\t\t'num_hosts_found' : 0,\n\t\t'open_telnet' : 0,\n\t\t'open_ssh' : 0,\n\t\t'os_found' : 0,\n\t\t'mac_found' : 0,\n\t\t'vendor_found' : 0,\n\t\t'num_complete' : 0\n\t};\n\n\t//console.log(csv_string);\n\tvar lines = csv_string.split('\\n');\n\tfor(var i = 0;i < lines.length;i++){\n\t\tline = lines[i];\n\n\t\t//scan hud data\n\t\tif (line.slice(0,4) == \"scan\"){\n\n\t\t\t//scan_data = line.split(',')\n\t\t\tvar scan_data = line.split(',');\n\n\t\t\t//console.log(line);\n\t\t\t//console.log(scan_data[1]);\n\n\t\t\t//HUD_data['num_scanned_ips'] += int(scan_data[1])\n\t\t\tHUD_data['num_scanned_ips'] += parseInt(scan_data[1]);\n\n\t\t\t//HUD_data['num_hosts_found'] += int(scan_data[2])\n\t\t\tHUD_data['num_hosts_found'] += parseInt(scan_data[2]);\n\n\t\t\t//HUD_data['last_scan_time'] = scan_data[3]\n\t\t\tHUD_data['last_scan_time'] = parseInt(scan_data[3]);\n\t\t}\n\n\t\t//extract host information\n\t\t//if (line[:4] == \"host\"){\n\t\tif (line.slice(0,4) == \"host\"){\n\n\t\t\tvar host_data = line.split(',');\n\n\t\t\tvar telnet = parseInt(host_data[5]);\n\t\t\tvar ssh = parseInt(host_data[6]);\n\n\t\t\tHUD_data['open_telnet'] += telnet;\n\t\t\tHUD_data['open_ssh'] += ssh;\n\n\t\t\tif (host_data[3] !== \"NULL\")\n\t\t\t\tHUD_data['mac_found'] += 1;\n\t\t\tif (host_data[4] !== \"NULL\")\n\t\t\t\tHUD_data['vendor_found'] += 1;\n\t\t\tif (host_data[7] !== \"NULL\")\n\t\t\t\tHUD_data['os_found'] += 1;\n\t\t}\n\n\t}\n\n\t//#convert unix time stamp to datetime\n\tHUD_data['last_scan_time'] = timestamp_to_datetime(HUD_data['last_scan_time']);\n\n\t//return HUD_data\n\treturn HUD_data;\n}",
"function onHealthUpdate() {\n\ttry {\n\n\t\thealthDatas = [];\n\t\tif (OS_IOS) {\n\t\t\tcommonFunctions.openActivityIndicator(commonFunctions.L('activityLoading', LangCode));\n\t\t\thealthKitAuthorization();\n\t\t\tgetValuesFromHealthKit();\n\t\t} else {\n\t\t\tgoogleFitDataAndroid();\n\t\t}\n\t} catch(ex) {\n\t\tcommonFunctions.handleException(\"healthdatas\", \"onHealthUpdate\", ex);\n\t}\n}",
"static update() {\n HUD.instance.update();\n }",
"static load (\n platform,\n environment) {\n platform = platform || 'windows'\n environment = environment || 'stage'\n\n let configData\n let testData\n\n try {\n const cdFile = path.join(configPath, `cd_${platform}_${environment}.yml`)\n configData = yaml.safeLoad(fs.readFileSync(cdFile, 'utf8'))\n } catch (e) {\n console.log(`Unable to load ${platform} config data for ${environment}!`)\n throw e\n }\n\n try {\n const tdFile = path.join(configPath, `td_${environment}.yml`)\n testData = yaml.safeLoad(fs.readFileSync(tdFile, 'utf8'))\n } catch (e) {\n console.log(`Unable to load ${environment} test data!`)\n throw e\n }\n\n try {\n TestData.data = _.merge(configData, testData)\n TestData.clientPathname = TestData.getClientPathName(\n TestData.data[`gshare_client`])\n } catch (e) {\n console.log('Unable to load test data!')\n console.log(e)\n }\n }",
"function loadData() {\n if (!fs.existsSync(appdata + 'data/')) {\n console.warn(\"Init: dir 'data/' doesn't exist, creating new directory...\");\n fs.mkdirSync(appdata); /* /forge */\n fs.mkdirSync(appdata + 'data'); /* /forge/data */\n console.info(\"Created data directory at '\" + appdata + \"data/\" + \"'\");\n } else {\n console.info(\"Init: loading previous data from disk...\");\n fromDisk(\"items.json\", true).then(nDiskItems => {\n if (nDiskItems === null)\n console.warn(\"Init: file 'items.json' missing from disk, ignoring...\");\n else\n items = nDiskItems;\n\n fromDisk(\"smelted_items.json\", true).then(nDiskSmeltedItems => {\n if (nDiskSmeltedItems === null)\n console.warn(\"Init: file 'smelted_items.json' missing from disk, ignoring...\");\n else\n itemsSmelted = nDiskSmeltedItems;\n\n if (itemsSmelted[0] && typeof itemsSmelted[0] === \"string\") {\n // DB uses the old smelt format, wipe smelts from memory + disk to avoid conflicts\n while (itemsSmelted.length) itemsSmelted.pop();\n toDisk(\"smelted_items.json\", \"[]\", false).then(smeltWritten => {\n console.log(\"Smelt database wiped!\");\n });\n }\n\n if (itemsSmelted.length > 1) {\n // Check for the 'missing addy' bugged items and remove them\n for (let i=0; i<itemsSmelted.length; i++) {\n if (!itemsSmelted[i].address) {\n itemsSmelted.splice(i, 1);\n }\n }\n }\n\n fromDisk(\"pending_items.json\", true).then(nDiskPendingItems => {\n if (nDiskPendingItems === null)\n console.warn(\"Init: file 'pending_items.json' missing from disk, ignoring...\");\n else\n itemsToValidate = nDiskPendingItems;\n\n fromDisk(\"unsigned_items.json\", true).then(nDiskUnsignedItems => {\n if (nDiskUnsignedItems === null)\n console.warn(\"Init: file 'unsigned_items.json' missing from disk, ignoring...\");\n else\n unsignedItems = nDiskUnsignedItems;\n \n console.info(\"Init: loaded from disk:\\n- Items: \" + items.length + \"\\n- Pending Items: \" + itemsToValidate.length + \"\\n- Smelted Items: \" + itemsSmelted.length + \"\\n- Unsigned Items: \" + unsignedItems.length);\n });\n });\n });\n });\n }\n}",
"function setupHud() {\n setAttributes(\"antialias\", true)\n easycam = createEasyCam()\n document.oncontextmenu = function() {\n return false\n }\n\n // set initial camera state\n easycam.setState(state, 1000) // animate to state in 1 second\n easycam.state_reset = state // state to use on reset\n\n // use the loaded font\n textFont(f)\n textSize(16)\n}",
"function reload_dungeon_configuration(id){\r\n\t\tif(entered_guide.id == id){\r\n\t\t\tconst s = dispatch.settings.dungeons.findIndex(s => s.id == id);\r\n\t\t\tif(dispatch.settings.dungeons[s] !== undefined){\r\n\t\t\t\tentered_guide.settings = dispatch.settings.dungeons[s];\r\n\t\t\t} else {\r\n\t\t\t\tentered_guide.settings = default_dungeon_settings;\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function onHealthUpdate() {\n\ttry {\n\t\tTi.API.info('healthDataRefresh');\n\t\thealthDatas = [];\n\t\tif (OS_IOS) {\n\t\t\tcommonFunctions.openActivityIndicator(commonFunctions.L('activityLoading', LangCode));\n\t\t\thealthKitAuthorization();\n\t\t\tgetValuesFromHealthKit();\n\t\t} else {\n\t\t\tgoogleFitDataAndroid();\n\t\t}\n\t} catch(ex) {\n\t\tcommonFunctions.handleException(\"healthdatas\", \"onHealthUpdate\", ex);\n\t}\n}",
"async loadPerformanceHistory() {\n let rawFile = null;\n try {\n rawFile = await fse.readFile(this.hardConfigs.heatmapDataFile, 'utf8');\n } catch (error) { }\n\n const setFile = async () => {\n try {\n await fse.writeFile(this.hardConfigs.heatmapDataFile, '[]');\n this.perfSeries = [];\n } catch (error) {\n console.error(`Unable to create stats_heatmapData_v1 with error: ${error.message}`);\n process.exit();\n }\n };\n\n if (rawFile !== null) {\n try {\n const heatmapData = JSON.parse(rawFile);\n if (!Array.isArray(heatmapData)) throw new Error('data is not an array');\n if (!validatePerfCacheData(heatmapData)) throw new Error('invalid data in cache');\n this.perfSeries = heatmapData.slice(-this.hardConfigs.performance.lengthCap);\n } catch (error) {\n console.warn(`Failed to load stats_heatmapData_v1 with message: ${error.message}`);\n console.warn('Since this is not a critical file, it will be reset.');\n await setFile();\n }\n } else {\n await setFile();\n }\n }",
"async function load() {\n await Datas.Settings.read();\n await Datas.Systems.read();\n //RPM.gameStack.pushTitleScreen();\n //RPM.datasGame.loaded = true;\n Manager.GL.initialize();\n Manager.GL.resize();\n Manager.Stack.requestPaintHUD = true;\n}",
"function loadHups()\n{\n\t//1. Kijk in de LocalStorage\n\tloadHupsFromLocalStorage();\n\n\t//2. JSON van de Server inladen\n\turl = 'http://fietsenvoor.nl/themes/fietsenvoor/hups.json';\n\n\trequest(url);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by LUFileParsernewEntityType. | exitNewEntityType(ctx) {
} | [
"exitElementType(ctx) {\n\t}",
"exitType_definition(ctx) {\n\t}",
"exitNewEntityDefinition(ctx) {\n\t}",
"exitParse(ctx) {\n\t}",
"exitNested_table_type_def(ctx) {\n\t}",
"exitTypeName(ctx) {\n\t}",
"exitType_declaration(ctx) {\n\t}",
"exitRecord_type_def(ctx) {\n\t}",
"exitCompilationUnit(ctx) {\n\t}",
"exitEntityDefinition(ctx) {\n\t}",
"exitCreateType(ctx) {\n\t}",
"exitObject_type_def(ctx) {\n\t}",
"exitType_body(ctx) {\n\t}",
"exitNewEntitySection(ctx) {\n\t}",
"exitEntityDeclaration(ctx) {\n\t}",
"exitAgType(ctx) {\n }",
"exitCompile_type_clause(ctx) {\n\t}",
"exitNewEntityLine(ctx) {\n\t}",
"exitSimpleTypeId(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all cells surrounding the one at (row, col) | function getAllAdjacentCells(row, col) {
var cells = [];
for (var dir = 0; dir < 6; dir++) {
cells.push(getAdjacentCell(row, col, dir));
}
return cells;
} | [
"adjacentCells(row, col) {\n return [\n [row - 1, col - 1], // top-left\n [row - 1, col], // top\n [row - 1, col + 1], // top-right\n [row, col - 1], // left\n [row, col + 1], // right\n [row + 1, col - 1], // bottom-left\n [row + 1, col], // bottom\n [row + 1, col + 1], // bottom-right\n ].filter(\n ([r, c]) => 0 <= r && r < this.numRows && 0 <= c && c < this.numCols\n )\n }",
"function getCellsAround(cell) {\n\t\t\tvar cells = [];\n\n\t\t\t_.forEach(_.range(-1, 2), function (i) {\n\t\t\t\t_.forEach(_.range(-1, 2), function (j) {\n\t\t\t\t\tvar row = self.state.board[cell.row + i];\n\t\t\t\t\tvar col = cell.col + j;\n\n\t\t\t\t\t// cell validation.\n\t\t\t\t\t(_.isUndefined(row) || _.isUndefined(row[col])) ? _.noop() : cells.push(row[col]);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treturn cells;\n\t\t}",
"function getAdjacentCells () { \n\tfor (let i = 0; i < cols; i++) {\n\t\tfor (let j = 0; j < rows; j++) {\n\t\t\tgrid[i][j].countMines(); \n\t\t}\t\t\n\t}\n}",
"surroundingCells(fn) {\n\t\tconst movements = [-1,0,1];\n\n\t\t// Each surrounding cell\n\t\tmovements.forEach(xdir => {\n\t\t\tmovements.forEach(ydir => {\n\t\t\t\tif(xdir !== 0 || ydir !==0) {\n\t\t\t\t\tlet xcoord = this.x + xdir;\n\t\t\t\t\tlet ycoord = this.y + ydir;\n\n\t\t\t\t\tconst coord = this.game.getIndexFromCoords(xcoord, ycoord);\n\n\t\t\t\t\t// If it's a valid board location\n\t\t\t\t\tif(xcoord >= 0 && xcoord < this.game.width // x bounds check\n\t\t\t\t\t\t&& ycoord >= 0 && ycoord < this.game.height // y bounds check\n\t\t\t\t\t\t){\n\t\t\t\t\t\tfn(this.game.board[coord], coord);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t});\n\t}",
"function getSurroundingCells(cell){\r\n\t\t// ORDER: [if upward then: below; else: above], [left], [right]\r\n\t\tvar surroundingCellsPos = [\r\n\t\t\t{x: cell.x, y: cell.y + ((cell.upward) ? 1 : -1)},\r\n\t\t\t{x: cell.x - 1, y: cell.y},\r\n\t\t\t{x: cell.x + 1, y: cell.y}\r\n\t\t];\r\n\r\n\t\t// find each pos from gridData\r\n\t\t// if found then add to result list\r\n\t\tvar result = [];\r\n\t\tfor (let i=0; i < surroundingCellsPos.length; i++){\r\n\t\t\tvar pos = surroundingCellsPos[i];\r\n\t\t\t\r\n\t\t\tfor (let j=0; j < gridData.length; j++){\r\n\t\t\t\tvar c = gridData[j];\r\n\t\t\t\t// found it?\r\n\t\t\t\tif (c.x === pos.x && c.y === pos.y){\r\n\t\t\t\t\tresult.push(c);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"findAroundCells(cell) {\n let rows = this.state.rows;\n\n for (let row = -1; row <= 1; row++) {\n for (let col = -1; col <= 1; col++) {\n //check edge case, actual edge cases\n if (cell.y + row >= 0 && cell.x + col >= 0) {\n if (\n cell.y + row < rows.length &&\n cell.x + col < rows[0].length\n ) {\n //open the tiles continuously\n if (\n !(rows[cell.y + row][cell.x + col].hasMine) &&\n !(rows[cell.y + row][cell.x + col].isOpen)\n ) {\n this.openOrFlag(rows[cell.y + row][cell.x + col]);\n }\n }\n }\n }\n }\n }",
"function get_cell(row, col)\n{\n return $('div').eq(row * SZ + col);\n}",
"cellsIntersectingWith(box) {\n var cells = []\n var start = this.cellFromPoint(point(box.x, box.y))\n var end = this.cellFromPoint({x: box.x + box.width,\n y: box.y + box.height})\n\n for (var x = start.x; x <= end.x; ++x)\n for (var y = start.y; y <= end.y; ++y)\n cells.push({x,y})\n\n return cells\n }",
"static getCellAtCoords(eventXScreen, eventYScreen) {\n var currCell = document.elementFromPoint(eventXScreen, eventYScreen);\n\n if (!currCell) throw new Error(\"Unable to locate cell\");\n\n //sometimes gets rows or legospace\n for(let i=0; i<10; i++) {\n if (!currCell.className.match(/cell/)) {\n eventYScreen -= (i * 5); // - some amount from y to avoid landing on the row border, or lego face\n currCell = document.elementFromPoint(eventXScreen, eventYScreen);\n } else {\n break;\n }\n }\n\n //verify a cell //would be better to use jquery's parents()\n if (!currCell.className.match(/cell/) || !currCell.parentNode.parentNode.className.match(/plane-x/)) {\n console.log(\"not at cell\");\n console.dir(currCell);\n throw new Error(\"Unable to find cell\");\n }\n\n // currCell.style.backgroundColor = \"yellow\";\n var xPlaneCell = currCell.className.match(/cell-(\\d+)/)[1]\n var xPlaneRow = currCell.parentNode.className.match(/row-(\\d+)/)[1]\n return [currCell, xPlaneCell, xPlaneRow];\n }",
"getNeighbors(row, col) {\n let neighbors = [];\n if (this.i - 1 >= 0) //up\n neighbors.push([this.i - 1, this.j]);\n if (this.j - 1 >= 0) //left\n neighbors.push([this.i, this.j - 1]);\n if (this.i + 1 < row) //down\n neighbors.push([this.i + 1, this.j]);\n if (this.j + 1 < col) //right\n neighbors.push([this.i, this.j + 1]);\n return neighbors;\n }",
"function getAdjacentCells(thisCellRow, thisCellCol){\n //console.log('getAdjacentCells(' + thisCellRow + ', ' + thisCellCol + ')');\n\n // Collect a reference to the requested cell\n var thisCell = $('.cell[data-row=\"'+thisCellRow+'\"][data-col=\"'+thisCellCol+'\"]', fieldMapEventGrid);\n\n // Define the positions of adjacent cells to the current\n var thisUpCellPos = [(thisCellRow - 1), thisCellCol];\n var thisRightCellPos = [thisCellRow, (thisCellCol + 1)];\n var thisBottomCellPos = [(thisCellRow + 1), thisCellCol];\n var thisLeftCellPos = [thisCellRow, (thisCellCol - 1)];\n var adjacentCellPositions = [thisUpCellPos, thisRightCellPos, thisBottomCellPos, thisLeftCellPos];\n\n //console.log('thisUpCellPos', thisUpCellPos);\n //console.log('thisRightCellPos', thisRightCellPos);\n //console.log('thisBottomCellPos', thisBottomCellPos);\n //console.log('thisLeftCellPos', thisLeftCellPos);\n //console.log('adjacentCellPositions', adjacentCellPositions);\n\n // Return the collected adjacent cells\n return adjacentCellPositions;\n\n}",
"function neighbouringCells(cell) {\n var x = getX(cell);\n var y = getY(cell);\n\n return [\n createCell((x - 1), (y - 1), false, true),\n createCell((x ), (y - 1), false, true),\n createCell((x + 1), (y - 1), false, true),\n createCell((x - 1), (y ), false, true),\n createCell((x + 1), (y ), false, true),\n createCell((x - 1), (y + 1), false, true),\n createCell((x ), (y + 1), false, true),\n createCell((x + 1), (y + 1), false, true)\n ];\n }",
"function getCellFromPoint( p ) {\n\t\tvar i, j;\n\t\t\n\t\tvar cellW = worldRect.width / (NUMBER_OF_COLS-1);\n\t\tvar cellH = worldRect.height / (NUMBER_OF_ROWS);\n\t\t\n\t\texitLoop: for( i = 0; i < NUMBER_OF_ROWS; i++ ) {\n\t\t\tfor( j = 0; j < NUMBER_OF_COLS-1; j++ ) {\n\t\t\t\tif( p.x > j * cellW && p.x < j * cellW + cellW && p.y > i * cellH && p.y < i * cellH + cellH ) {\n\t\t\t\t\tbreak exitLoop;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn { x: j, y: i };\n\t}",
"function insideCells(row, col){\r\n if(0 > row || row >= rows) return false;\r\n if(0 > col || col >= cols) return false;\r\n return true;\r\n}",
"neighbors (row, column) {\n let leftColumn = column - 1\n let rightColumn = column + 1\n let upRow = row - 1\n let downRow = row + 1\n \n // Wrap around edges\n if (leftColumn < 1) leftColumn = this.cols\n if (rightColumn > this.cols) rightColumn = 1\n if (upRow < 1) upRow = this.rows\n if (downRow > this.rows) downRow = 1\n \n // neighbors\n return [\n this.cell(upRow, leftColumn),\n this.cell(upRow, column),\n this.cell(upRow, rightColumn),\n this.cell(row, leftColumn),\n this.cell(row, rightColumn),\n this.cell(downRow, leftColumn),\n this.cell(downRow, column),\n this.cell(downRow, rightColumn)\n ]\n }",
"function findCellAt(grid, x, y){\n//I think this can be optimized by dividing the mouse's x and y positions by the cell's size. this would give you the inicies of the cell you're on.\n\tfor(var i =0;i<grid.length;i++){\n\t\tfor(var k=0;k<grid[i].length;k++){\n\t\t\t//here we find this cells max boundries \n\t\t\tvar cellXmin = grid[i][k].x;\n\t\t\tvar cellXmax = grid[i][k].x + grid[i][k].w;\n\t\t\tvar cellYmin = grid[i][k].y;\n\t\t\tvar cellYmax = grid[i][k].y + grid[i][k].h;\n\t\t\t\n\t\t\t//if the passed in x and y are within the height and width of this cell's x and y, its a match.\n\t\t\tif((x >= cellXmin && x <= cellXmax) && (y >= cellYmin && y <= cellYmax)){\n\t\t\t\treturn grid[i][k];\n\t\t\t}\n\t\t}\n\t}\n}",
"function getCell(x, y)\n{\n if(x >= BOARD_ROW_LENGTH) { x = 0; }\n if(y >= BOARD_COL_LENGTH) { y = 0; }\n if(x < 0) { x = BOARD_ROW_LENGTH -1; }\n if(y < 0) { y = BOARD_COL_LENGTH -1; }\n\n return $(cells[y * BOARD_COL_LENGTH + x]);\n}",
"function neighbors(col, row) {\n ret = Array();\n\n if (empty_cell(col, row))\n return ret;\n \n CLR = get_color(col, row);\n\n if (col > 0 && (prev_col = get_left_col(col)) >= 0 && get_color(prev_col, row) == CLR) \n ret.push(get_cell(prev_col, row));\n\n if (col+1 < COLS && (next_col = get_right_col(col)) && get_color(next_col, row) == CLR)\n ret.push(get_cell(next_col, row));\n\n if (row+1 < ROWS && get_color(col, row+1) == CLR)\n ret.push(get_cell(col, row+1));\n\n if (row > 0 && get_color(col, row-1) == CLR)\n ret.push(get_cell(col, row-1));\n\n return ret;\n}",
"function getLivingCells() {\n let livings = [];\n for (let i = 0; i < nr_Rows * zoom; i++) {\n for (let j = 0; j < nr_Cols * zoom; j++) {\n if (matrix[i][j] === 1) {\n livings.push([i, j]);\n }\n }\n }\n return livings;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set policy group id value | function setPolicyGroupValue() {
for (var i = 0; i < RESOURCES_1.length; i++) {
if (RESOURCES_1[i].policyGroupId !== undefined && RESOURCES_1[i].policyGroupId !== '') {
$('#uritemplate_policyGroupId' + i).val(RESOURCES_1[i].policyGroupId);
}
}
} | [
"function assignGroupId(id){\r\n\t\tgroup.id = id;\r\n\t}",
"setGroupId(aGroupId) {\n this.group_id = aGroupId;\n }",
"setGroupId(aGroupId) {\n this.group_id = aGroupId;\n }",
"function setupPolicyGroups(postData, policyGroupId) {\n postData.uritemplate_policyGroupIds = '['+policyGroupId+']';\n postData.uritemplate_policyGroupId0 = policyGroupId;\n postData.uritemplate_policyGroupId1 = policyGroupId;\n postData.uritemplate_policyGroupId2 = policyGroupId;\n postData.uritemplate_policyGroupId3 = policyGroupId;\n postData.uritemplate_policyGroupId4 = policyGroupId;\n }",
"setDomGroup( prop, val ) {\n if ( this.group ) {\n this.group.setAttribute( prop, val );\n }\n }",
"setGroup(group) { \r\n this.group = group; // a real implementation may need to do more than just this\r\n }",
"setGroup(group) { \n this.group = group; // a real implementation may need to do more than just this\n }",
"function set_id(value, dimension_id){\n the_product_id = value;\n the_dimension_id = dimension_id;\n}",
"set _id(value) {\n this.__id = value;\n }",
"function SetPrimaryGroupForPerson(group_name, user_id) {\n return new Promise(resolve => {\n // Establish client POSTGRESQL\n const client = PostgreSQL.CreateClient();\n client.connect(function(err) {\n if (err) throw err;\n // update primary group column in table for user_id\n client.query('UPDATE ' + TABLE_NAME + ' SET primary_group=$1 WHERE person_id=$2;',\n [group_name, user_id],\n function(err, res) {\n if (err) throw err;\n client.end(function(err) {\n if (err) throw err;\n resolve('primary group set');\n });\n });\n });\n });\n}",
"async function configurationPolicyGroupPut() {\n const subscriptionId = process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const vpnServerConfigurationName = \"vpnServerConfiguration1\";\n const configurationPolicyGroupName = \"policyGroup1\";\n const vpnServerConfigurationPolicyGroupParameters = {\n isDefault: true,\n policyMembers: [\n {\n name: \"policy1\",\n attributeType: \"RadiusAzureGroupId\",\n attributeValue: \"6ad1bd08\",\n },\n {\n name: \"policy2\",\n attributeType: \"CertificateGroupId\",\n attributeValue: \"red.com\",\n },\n ],\n priority: 0,\n };\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.configurationPolicyGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n vpnServerConfigurationName,\n configurationPolicyGroupName,\n vpnServerConfigurationPolicyGroupParameters\n );\n console.log(result);\n}",
"function setID(newid) {\r\n id = newid;\r\n }",
"nextID() {\n this._ctx.groupCount++;\n this._ctx.currentID = `${this._ctx.groupID}-${this._ctx.groupCount}`;\n return this._ctx.currentID;\n }",
"function setOrModifyParameterGroup(template) {\n // Set new_menu parameter group\n template.parameterGroups['new_menu'] = {\n description: 'Description of the group.',\n parameters: {\n pumpkin_spice_season: {\n defaultValue: {\n value: 'A Gryffindor must love a pumpkin spice latte.'\n },\n conditionalValues: {\n android_en: {\n value: 'A Droid must love a pumpkin spice latte.'\n },\n },\n description: 'Description of the parameter.',\n },\n },\n };\n}",
"function setMyId(value) {\n _myId = value;\n}",
"setGroupName(aGroupName) {\nthis.group_name = aGroupName;\n}",
"setID(e, o) {\n e.setAttribute('id', this.formatID(o));\n }",
"function setGroup() {\n\n var input = prompt('Enter a group name.');\n\n if(input === null) {\n return;\n }\n\n group = (input === '') ? 'None' : input;\n\n notify('success', 'Group succesfully changed to ' + group);\n\n plotInterpretations();\n\n}",
"set(group) {\n this._group = group;\n if (group) {\n group.add(this);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update .dotenv file with db config values consumed by the app wide config located at server/config/database.js | _updateDotEnv() {
let template = null;
if (program.helpers.isRelationalDB(this.answers.database)) {
template = this.templatePath('dotenv/sql.stub');
} else if (this.answers.database === 'mongodb') {
template = this.templatePath('dotenv/mongo.stub');
}
let dest = this.destinationPath('.dotenv');
let dotenv = program.helpers.readTpl(this, template, {answers: this.answers});
this.fs.write(dest, `${this.read(dest)}\n${dotenv}\n`);
} | [
"function updateConfig() {\n var savConf = {};\n savConf.env = appConfig.env;\n savConf.database = appConfig.database;\n savConf.http = appConfig.http;\n fs.writeFile(appConfigFile, JSON.stringify(savConf));\n}",
"static configureEnvironment(){\n dotenv.config({ path: './settings.env' }); \n }",
"function setEnv(name, version, path) {\n db.set(`config.env.${name}`, {\n version: version,\n path: path\n }).write()\n}",
"async function build_dotenv() {\n dbg.log0('UPGRADE: generating dotenv file in the new version directory');\n const old_env = dotenv.parse(await fs.readFileAsync(`/data/.env`));\n const new_env_defaults = process.env.container === 'docker' ?\n await fs.readFileAsync(`${CORE_DIR}/src/deploy/NVA_build/env.orig`) :\n await fs.readFileAsync(`${NEW_VERSION_DIR}/src/deploy/NVA_build/env.orig`);\n const new_env = Object.assign(\n dotenv.parse(new_env_defaults),\n _.pick(old_env, DOTENV_VARS_FROM_OLD_VER),\n );\n\n dbg.log0('UPGRADE: generating .env file for new version:', new_env);\n\n await fs.writeFileAsync(`/data/.env`, dotenv.stringify(new_env));\n}",
"static getDatabaseConfig() {\n return {\n LOCAL: 'local',\n DEVELOPMENT: 'development',\n STAGING: 'staging',\n PRODUCTION: 'production',\n environment: {\n 'local': {config: 'mongodb://localhost:27017/tutorial-local'},\n 'development': {config: 'mongodb://localhost:27017/tutorial-develop'},\n 'staging': {config: 'mongodb://localhost:27017/tutorial-staging'},\n 'production': {config: 'mongodb://localhost:27017/tutorial-production'}\n }\n };\n }",
"static async loadConnectionConfig() {\n const yaml = await fs.readFileSync('./config/mongodb.yml', 'utf-8')\n const config = jsYaml.safeLoad(yaml)\n\n let database = {}\n switch (process.env.NODE_ENV) {\n case 'test':\n database = config.test\n break\n case 'dev':\n database = config.dev\n break\n case 'prod':\n database = config.prod\n break\n default:\n database = config.dev\n break\n }\n return database\n }",
"function saveEnv() {\n\tlet content = \"\";\n\tfor(const key in envConfig) {\n\t\tif(content !== \"\") content += \"\\n\";\n\t\tcontent += `${key}=${envConfig[key].includes(\" \") ? `\"${envConfig[key]}\"` : envConfig[key]}`;\n\t}\n\ttry {\n\t\tfs.writeFileSync(path.resolve(__dirname, \"../.env\"), content);\n\t} catch(e) {\n\t\tconsole.error(`Unable to Save to File: ${e}`);\n\t\tprocess.exit(1);\n\t}\n}",
"function loadEnvironment() {\n const APP_LOGLEVEL = process.env.APP_LOGLEVEL;\n const DB_URI = process.env.DB_URI;\n const DB_USER = process.env.DB_USER;\n const DB_PASS = process.env.DB_PASS;\n\n if (DB_URI) {\n logger.info('env: DB_URI=' + DB_URI);\n db.config.uri = DB_URI;\n }\n\n if (DB_USER) {\n logger.info('env: DB_USER=' + DB_USER);\n db.config.options.user = DB_USER;\n }\n\n if (DB_PASS) {\n logger.info('env: DB_PASS=' + DB_PASS);\n db.config.options.pass = DB_PASS;\n }\n\n if (APP_LOGLEVEL) {\n if (!(APP_LOGLEVEL in logger.Level)) {\n logger.warn('Invalid log level specified: ' + APP_LOGLEVEL);\n } else {\n logger.info('env: APP_LOGLEVEL=' + APP_LOGLEVEL);\n logger.setLogLevel(APP_LOGLEVEL);\n }\n }\n}",
"_loadEnvValues() {\n this.debugLog(`${this.msgPrefix} Load Environmental Variables`);\n const envPrefix = [];\n this.envPrefix.forEach(prefix => {\n envPrefix.push(prefix.toLowerCase())\n });\n\n for (let entry in this.env) {\n const entrylc = entry.toLowerCase();\n envPrefix.forEach(prefix => {\n if (entrylc.startsWith(prefix)) {\n this.mongoEnv[entrylc.substr(prefix.length)] = {\n key: entry, name: entry.substr(prefix.length), value: this.env[entry]\n };\n }\n })\n }\n this.debugLog(`${this.msgPrefix} MongoEnv: ${JSON.stringify(this.mongoEnv, null, 4, 4)}`);\n }",
"function setConfigDbValues (next) {\n db.config.find({}, function (err, dbItems) {\n if (err) return next(err)\n dbItems.forEach(function (item) {\n var configItem = ConfigItem.findOneByKey(item.key)\n if (configItem) configItem.setDbValue(item.value)\n })\n next()\n })\n}",
"function env() {\n var e;\n try {\n e = fs.readFileSync('.env', { encoding: 'utf-8' }).split('\\n');\n } catch (b) {\n return;\n }\n for (var i = 0; i < e.length; i++) {\n process.env[e[i].split('=')[0].trim()] = e[i].split('=')[1].trim();\n }\n}",
"function setProductionConfig(){\n DatabaseConfig.port = 35747;\n DatabaseConfig.host = 'ds035747.mongolab.com';\n DatabaseConfig.name = 'eventful';\n DatabaseConfig.user = 'eventuser';\n DatabaseConfig.pass = 'event1234';\n\n EnvConfig.port = 80;\n}",
"function config() {\n let {\n NODE_ENV: env,\n PERCY_DISABLE_DOTENV: disable\n } = process.env; // don't load dotenv files when disabled\n\n if (disable) return;\n let paths = [env && `.env.${env}.local`, // .env.local is not loaded in test environments\n env === 'test' ? null : '.env.local', env && `.env.${env}`, '.env'].filter(Boolean);\n\n for (let path of paths) {\n dotenv.config({\n path\n });\n }\n}",
"loadConfig() {\n this._config = _.extend(\n require('./../config/env/all'),\n require('./../config/env/' + this.env) || {}\n );\n }",
"registerDotEnv() {\n Dotenv.config(this.config.dotenv || {})\n }",
"function loadDotEnv() {\n if (process.env.NODE_ENV !== 'production') {\n debug(serverName + ' server Not in prod. Loading local .env file.');\n require('dotenv').load();\n debug('Loaded .env file OK. Node env: ' + process.env.NODE_ENV);\n }\n else {\n debug(serverName + ' server Running in PRODUCTION environment');\n }\n}",
"_updateDotProject() {\n program.config(this).set(`database:${this.answers.identifier}`, {\n identifier: this.answers.identifier,\n database: this.answers.database\n });\n }",
"function loadDevEnvVariables() {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const dotenv = require('dotenv');\n const filePath = path_1.default.join(__dirname, '..', '..', '.env');\n const env = dotenv.config({ path: filePath }).parsed;\n forceEnvVar(env, 'ALGOLIA_API_KEY');\n forceEnvVar(env, 'ALGOLIA_BASE_URL');\n}",
"async loadEnvFile() {\n\t\tif (this.flags.env || this.flags.envfile) {\n\t\t\ttry {\n\t\t\t\tconst dotenv = await import(\"dotenv\");\n\n\t\t\t\tif (this.flags.envfile) dotenv.config({ path: this.flags.envfile });\n\t\t\t\telse dotenv.config();\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"The 'dotenv' package is missing! Please install it with 'npm install dotenv --save' command.\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch All Tax Groups | getTaxGroups(){
var that = this;
var reqQuery = {};
reqQuery['userdetails'] = getUserDetails();
const request = new Request(`${process.env.API_HOST}/ManageTaxes.svc/GetTaxGroups/json`, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(reqQuery)
});
fetch(request)
.then(function(response) {
if(response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
that.setState({
taxGroupList: data.taxGroupList
});
});
} | [
"async getAllGroups() {\n log('get all groups ....');\n return this.api.get('/api/1.0/tags', {\n params: {\n company: this.companyId,\n token: this.token,\n limit: LIMIT,\n },\n }).then((response) => response.data.data).catch((error) => {\n log(error.response.data.message, true);\n });\n }",
"function notesFetchAllCalcGroups() {\n itemDB.open(databaseName, version, datastoreName, \"\", properties, true, function (result) {\n let db = result;\n itemDB.fetchAll(db, datastoreName, function (myRecords) {\n buildCalcGroups(myRecords, groupPropertyName);\n });\n });\n}",
"function getTaxonomies() {\n\n angular.forEach(service.allowedTaxonomies, function(taxonomy) {\n\n //Create vars that can be used as keys\n var taxonomyLabel = taxonomy + '_label';\n var taxonomyEnabled = taxonomy + '_enabled';\n var taxonomyWeight = taxonomy + '_weight';\n\n _promises.push(\n service.single(taxonomy).then(\n // Success Function\n function(data) {\n if(data.data.count > 0) {\n service.taxonomies[taxonomy] = {\n id: taxonomy,\n terms: data.data.data,\n label: siteService.settings[taxonomyLabel] || taxonomy,\n enabled: siteService.settings[taxonomyEnabled],\n weight: Number(siteService.settings[taxonomyWeight])\n };\n }\n },\n // Fail Function\n function(data) {\n console.log('Error retrieving data for:' . taxonomy);\n console.log('See release notes for version 1.2. New/additional taxonomies are available to configure.');\n }\n )\n );\n\n });\n\n return $q.all(_promises).then(function() {\n return service.taxonomies;\n });\n\n }",
"getTaxableEntities () {\n API.TaxableEntities.GetTaxableEntities().then(response => {\n this.setTaxableEntities(response)\n })\n }",
"getCreepsByGroups() {\n return this.getCreepsBy(['group']);\n }",
"function getTermSets() {\r\n var deferred = $.Deferred();\r\n var context = SP.ClientContext.get_current();\r\n var session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);\r\n //Name of the Term Store from which to get the Terms. \r\n var termStore = session.getDefaultSiteCollectionTermStore();\r\n // var termStoreGroup = termStore.getSiteCollectionGroup(siteURL);\r\n //Name of the Term Group from which to get the Term sets.\r\n var termStoreGroup = termStore.getGroup(\"c36a38d6-e852-4e84-b38d-24a889d58bfb\")\r\n //getting all the termsets of a particular group\r\n var parentTermSets = termStoreGroup.get_termSets();\r\n context.load(parentTermSets);\r\n context.executeQueryAsync(function onSuccess() {\r\n deferred.resolve(parentTermSets);\r\n }, function (sender, args) {\r\n deferred.reject(args.get_message());\r\n });\r\n return deferred.promise();\r\n}",
"async function getGroups() {\n let groups = [];\n\n let i = 1;\n let pageCount = 0;\n do {\n const group = await getGroup(i);\n\n if (group != null) {\n pageCount = group.pageCount;\n groups.push(group.entities);\n }\n\n i++;\n }\n while (i <= pageCount);\n\n groups\n .flat(1)\n .filter((value) => value != null)\n .forEach((value) => { groupsMap[value.name] = value; });\n\n //Cloning the internal representation to keep the data immutable\n return { ...groupsMap };\n}",
"function getAllGroups() {\n customerService.getAllGroups().then(function (data) {\n if (data) {\n $scope.groups = data;\n }\n });\n\n }",
"getRootGroupingRecords() {\n return new Promise(resolve => {\n const set = new Set();\n const result = [];\n\n if (!this.groupingOrder.hasItems) {\n resolve(result);\n }\n\n const grouping = this.groupingOrder.firstItem;\n\n for(let dataItem of this.data) {\n const value = dataItem[grouping.field];\n\n if (set.has(value)) {\n continue;\n }\n\n let groupingRecord = null;\n\n if (this.filter) {\n if (this.filter.allow(dataItem)) {\n groupingRecord = new GroupingRecord(dataItem, 0, grouping.field, value);\n }\n }\n else {\n groupingRecord = new GroupingRecord(dataItem, 0, grouping.field, value);\n }\n\n if (groupingRecord) {\n groupingRecord.value = value;\n groupingRecord.index = 0;\n set.add(value);\n result.push(groupingRecord);\n }\n }\n\n resolve(result);\n });\n }",
"async function getAll() {\n try {\n const groupsCollection = await groups();\n const allGroup = groupsCollection.find({}).toArray();\n return allGroup;\n } catch (e) {\n throw `` + e;\n }\n}",
"groups (options) {\n return api('GET', `/node_group/self?page=${options.groupsPage}&perPage=${options.perPage}`, options)\n }",
"getTaxableEntities () {\n return this.taxableEntities\n }",
"function getAllCustomerByGroup() {\n return datacontext.get('Customer/GetAllCustomerByGroup');\n }",
"function retrieveAccountGroups() {\n account.getGroups(function(err, groups) {\n groups.each(function(err, group) {\n console.log(group);\n })\n });\n\n //finish quickstart:\n cleanup();\n}",
"function getGroups() {\n $.get(\"/api/groups\", renderGroupList);\n }",
"getAllMembershipGroupRequests(group) {\n return this.#fetchAdvanced(this.#getAllMembershipGroupRequestsURL(group)).then((responseJSON) => {\n let groupBOs = MembershipBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(groupBOs);\n })\n })\n }",
"function obtenerNombresGrupos(){\n var gruposNombreID=[];\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n var groups= JSON.parse(this.responseText);\n gruposNombreID=_.map(groups,(grupo)=>({\n 'id': grupo.id,\n 'nombre': grupo.name\n }));\n }\n };\n xhttp.open(\"GET\", \"https://hypothes.is/api/groups?limit=200\", false);\n xhttp.setRequestHeader(\"Authorization\", \"Bearer 6879-Q--ve1yLCItODnHueg4py6UT-qqq93bk-xgvra0-BVA\");\n xhttp.send();\n\n return gruposNombreID;\n}",
"getGroups() {\n return httpService(`${config.dbApiUrl}/groups`, 'GET');\n }",
"getEntitiesByGroup(group) {\n if(this._groups.hasOwnProperty(group)) {\n return this._groups[group];\n }\n return [];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attaches the error to the voice connection | _attachErrorEvent() {
this._oConnection.onEvent("error", function(err) {
logger.error("VoiceConnection error: ", err);
this.play(); //Try to play the next song on error
}.bind(this));
this._oConnection.onEvent("failed", function(err) {
logger.error("VoiceConnection failed: ", err);
this.play(); //Try to play the next song on error
}.bind(this));
this._bErrorEventAttached = true;
} | [
"audioOnError() {\n clearTimeout(this.loadTimeoutFn);\n this.triggerEvent('error');\n this.next({'type': 'ended'});\n }",
"onSpeechError(event) {\n this.dispatchEvent(event);\n }",
"function onPlayerError(errorCode) {}",
"function AudioError() {\n this.code = null,\n this.message = \"\";\n}",
"function emitError (message) {\n open = false;\n omxplayer.emit('error', message);\n\n }",
"onAudioError(errMsg, currentPlayId, audioLists, audioInfo) {\n console.error(\n \"audio load error\",\n errMsg,\n currentPlayId,\n audioLists,\n audioInfo\n );\n }",
"onAudioLoadError(e) {\n console.error(\"audio load err\", e);\n }",
"onAudioLoadError(e) {\n console.error('audio load err', e)\n }",
"function onError() {\n throw new Error(\"There has been a problem accessing the webcam and microphone\");\n}",
"function forwardError (err) {\n\t clientRequest.emit('error', err);\n\t }",
"function onConnectionError(err) {\n errorImmediateHandle = setImmediate(self.emit.bind(self), 'error', err);\n }",
"function onSoundLoadError() { }",
"function cambiarAudioError(){\n\taudioElement.setAttribute('src', '../assets/audio/mpyc2/m8/error.mp3');\n\taudioElement.play();\n\taudioElement.controls = true;\n\t$('.subs').show();\n\t$('.subs-panel').html('Parece que hay un error en el archivo. Ayúdame a completar la frase. Usa tu teclado!.');\n\taudioElement.onpause = function(){\n\t\t/*$('.subs').hide();\n\t\taudioElement.controls = true;*/\n\t}\n\n}",
"_onPeerError (peer, error) {\n peer._emit('error', error)\n }",
"onNetworkingError(error) {\n this.emit('error', error);\n }",
"onAudioUrlFailed() {\n var {videoId} = this.props;\n this.setState({error: true});\n errors.set(videoId, true);\n\n // alert user that this track is not available\n AlertIOS.alert(\n en_US.ERROR,\n en_US.PLAYLIST_VIDEO_COMPONENT_NOT_AVAILABLE\n );\n }",
"function setOpponentError(error){\n opponentError = error;\n }",
"function onPlayerError(errorCode) {\n //console.log(\"An error occured of type:\" + errorCode);\n}",
"sendVoiceErrorMessage(toast) {\n toast.open({\n duration: 5000,\n message: `Olivia's voice cannot load, her voice is now the default english one.`,\n position: 'is-top',\n type: 'is-danger'\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a turn: 0) Wait for users to confirm the next game 1) Identify the user with the current turn 2) Draw the card 3) Find the rule for the card 4) Act on the rule 5) End the turn | function takeTurn () {} | [
"function nextTurn() {\r\n\t//switches turn\r\n\tturn = !turn;\r\n\r\n\t//it will reset the hand\r\n\thand.resetHand();\r\n\r\n\t//it will call the checkCheck function with the new turn and input that to the method kingInCheck\r\n\thand.kingInCheck(checkCheck(turn)); //checks if the king is in check or not\r\n\r\n\t//checks if there is insufficient material to get checkmate\r\n\tinsuffMat();\r\n\r\n\t//draws the new state of the background and hand\r\n\tdraw();\r\n}",
"function aiTurn(){\n\tif(turnCount > 0){\n\t\tif(difficulty == 'easy'){\n\t\t\teasyShot();\n\t\t}else if(difficulty == 'medium'){\n\t\t\tmediumShot();\n\t\t}else if(difficulty == 'hard'){\n\t\t\thardShot();\n\t\t}\n\t\tturnDone = 1;\n\t\tchangeTurn();\n\t\tconfirmChange();\n\t}\n}",
"function doTurn () {\n rollDice();\n move();\n combat();\n getCoins();\n buyHealth();\n printStatus();\n}",
"async function takeTurn () {}",
"function userTurn(event){\n let i = gameBoard.indexOf(event.target.id);\n gameBoard[i] = user.symbol;\n (event.target).textContent = user.symbol;\n let win;\n win = checkWin(gameBoard, user.symbol);\n let tie = checkTie();\n if(win === null && tie === false){\n if(mode === \"easy\"){\n setTimeout( () => {\n aiTurn(easyPlay());\n }, 500);\n } else if(mode === \"medium\"){\n let play = mediumPlay();\n setTimeout( () => {\n aiTurn(play);\n }, 500); \n } else if(mode === \"hard\"){\n let play = bestSpot();\n setTimeout( () => {\n aiTurn(play);\n }, 500); \n }\n } \n if(win != null){\n gameOver(win);\n }\n if(win === null & tie === true){\n gameOver(\"tie\");\n }\n}",
"function nextTurn(time) {\n \n drawingUser = currentlyDrawingUser();\n timer.setTimer(time / 1000, gameState.turn_length / 100);\n if (drawingUser) {\n \n artPad.locked = true;\n hideTools();\n unhideChatInput();\n \n for (var i = 0; i < gameState.udata.length; i++) {\n if (gameState.udata[i].drawing) {\n gameState.udata[i].drawing = false;\n }\n if (gameState.udata[i].uid == drawingUser.uid) {\n gameState.udata[i].drawing = true;\n }\n }\n \n \n if (time !== undefined) {\n setTimeout(pingServer, time * 1000);\n } else {\n setTimeout(pingServer, gameState.turn_length * 10 + 500);\n }\n setTimeout(pingServer, gameState.turn_length * 10 + 500);\n \n if (drawingUser.uid == artPad.localUser.id) {\n artPad.locked = false;\n unhideTools();\n hideChatInput();\n updateColor(artPad.localUser.brushColor);\n updateSize();\n updateAlpha();\n }\n \n }\n leaveIdleState();\n showOnline();\n}",
"function _takeTurn() {\n var pot = [],\n playerOneCard,\n playerTwoCard,\n winner;\n\n _turn++;\n\n playerOneCard = _playerOne.playCard();\n playerTwoCard = _playerTwo.playCard();\n\n pot = _addToPot(pot, playerOneCard);\n pot = _addToPot(pot, playerTwoCard);\n\n _log(\n _playerOne.name +\n \" played the \" +\n playerOneCard.rank +\n \" of \" +\n playerOneCard.suit +\n \".\"\n );\n _log(\n _playerTwo.name +\n \" played the \" +\n playerTwoCard.rank +\n \" of \" +\n playerTwoCard.suit +\n \".\"\n );\n\n _settle(pot, playerOneCard, playerTwoCard);\n }",
"function fleeToCar(){\n \n if(turn==1){fleeToCar1=true; player1Fleeing=true;}\n if(turn==2){fleeToCar2=true; player2Fleeing=true;}\n actionsChoosen++; //Let the system know the player has choosen an action\n \n }",
"function nextTurn() {\n console.log ('nextTurn called');\n if(currentPlayer.name === \"Computer\" && difficultyLevel === \"easy\") {\n changePlayerHeader();\n setTimeout(easyComputerTurn, 1500);\n\n }\n else if(currentPlayer.name === \"Computer\" && difficultyLevel === \"impossible\") {\n changePlayerHeader();\n setTimeout(aiTurn, 500);\n }\n else {\n changePlayerHeader();\n }\n}",
"function doUserTurn() {\n\t\tfirstMove = false;\n\t\tdisplayWinner();\n\t\t$('.gameSquare').on('click', function() {\n\t\t\t//Prevents clicking on the button if it's already disabled\n\t\t\tif(!$(this).hasClass('disabled')){\n\t\t\t\tvar coords;\n\t\t\t\t$(this).addClass('disabled');\n\t\t\t\tcoords = this.id.split('');\n\t\t\t\tgameBoard[coords[1]][coords[2]] = playerChoice;\n\t\t\t\t$(this).text(playerChoice);\n\t\t\t\tdoAITurn();\n\t\t\t}\n\t\t});\n\t}",
"function nextTurn() {\n\n betweenTurns = false;\n stop = false;\n\n if ( (learnMode == false) && (round < 6) ) { // disable pause during Learn Mode and hard difficulty\n pauseButton.disabled = false;\n pauseButton.classList.remove('frozen');\n pauseButton.classList.add('hover');\n }\n\n player1Bar.classList.remove('frozen');\n player2Bar.classList.remove('frozen');\n if (lineCounter != 0) {\n energy1.restore();\n energy2.restore();\n }\n\n // if Player 1's turn\n if (playerTurn == 1) {\n player1Turn();\n }\n\n // if Player 2's turn\n else {\n player2Turn();\n }\n}",
"handleNextTurn(){\n }",
"function evaluateTurn() {\n // pasted from homework need to fix\n if (userChoice === computerChoice) {\n console.log('itsa tie oops')\n outcome = \"It's a tie.\"\n changeStatus()\n } else {\n if (userChoice === \"rock\") {\n if (computerChoice === \"paper\") {\n console.log(\"player B wins!\")\n outcome = \"The bot won.\"\n changeStatus()\n scoreboardComputer()\n }\n else {\n console.log(\"player A wins!\")\n outcome = \"You win!\"\n changeStatus()\n scoreboardUser()\n }\n }\n\n if (userChoice === \"scissors\") {\n if (computerChoice === \"rock\") {\n console.log(\"player B wins!\")\n outcome = \"The bot won.\"\n changeStatus()\n scoreboardComputer()\n }\n else {\n console.log(\"player A wins!\")\n outcome = \"You win!\"\n changeStatus()\n scoreboardUser()\n }\n }\n\n if (userChoice === \"paper\") {\n if (computerChoice === \"scissors\") {\n console.log(\"player B wins!\")\n outcome = \"The bot won.\"\n changeStatus()\n scoreboardComputer()\n }\n else {\n console.log(\"player A wins!\")\n outcome = \"You win!\"\n changeStatus()\n scoreboardUser()\n }\n }\n }\n\n }",
"function makeMove() {\n if(turn == \"player\" && gameStatus == \"ongoing\" && playerFirstMove == true){\n playerPosition = \"p\"+(1+rollValue);\n var toGo = document.getElementsByClassName(playerPosition);\n $(toGo).attr(\"id\",\"user\");\n playerFirstMove = false\n cardOptions();\n turn = \"enemy\";\n begin.textContent=\"Roll dice for enemy move\";\n }else if(turn == \"player\" && gameStatus == \"ongoing\") {\n $(\"#user\").removeAttr(\"id\");\n playerPosition = parseInt(playerPosition.substr(1));\n if((playerPosition+rollValue)>40){\n playerPosition = \"p\"+((playerPosition+rollValue)-40);\n playerCash += 200;\n playerUpdate(\"You passed go! Collect $200\")\n updateCash();\n }else{\n playerPosition = \"p\"+(playerPosition+rollValue);\n }\n var toGo = document.getElementsByClassName(playerPosition);\n $(toGo).attr(\"id\",\"user\")\n cardOptions();\n turn = \"enemy\";\n begin.textContent=\"Roll dice for enemy move\";\n }else if(turn == \"enemy\" && gameStatus == \"ongoing\" && enemyFirstMove == true) {\n enemyPosition = \"p\"+(1+rollValue);\n var toGo = document.getElementsByClassName(enemyPosition);\n $(toGo).attr(\"id\",\"enemy\");\n enemyFirstMove = false\n cardOptions();\n executeEnemyStrategies();\n turn = \"player\";\n begin.textContent=\"Your roll\";\n }else if(turn == \"enemy\" && gameStatus == \"ongoing\") {\n $(\"#enemy\").removeAttr(\"id\");\n enemyPosition = parseInt(enemyPosition.substr(1));\n if((enemyPosition+rollValue)>40){\n enemyOfferOptions()\n enemyPosition = \"p\"+((enemyPosition+rollValue)-40);\n enemyCash += 200\n updateCash();\n enemyUpdate(\"Enemy passed go! Collect $200\")\n }else{\n enemyPosition = \"p\"+(enemyPosition+rollValue);\n }\n var toGo = document.getElementsByClassName(enemyPosition);\n $(toGo).attr(\"id\",\"enemy\")\n cardOptions();\n executeEnemyStrategies();\n turn = \"player\";\n begin.textContent=\"Your roll\";\n }\n}",
"takeTurn(board) {\n }",
"turnTaken(turn, resultingBoard) {\n }",
"function beginTurn() {\n // Sets turn variables\n currentTurn++;\n resourcePool = 0;\n attackPool = 0;\n \n // Reveals the top card of the villain deck\n addToEventQueue( numUpdateSteps + 80, drawFromVillainDeck );\n}",
"function chckForWin() {\n // Defined within TacProcHndlr\n // The key: chkWin...\n // Called from moveHandlr...\n console.log('TacProcHndlr: chckForWin...');\n\n // Called upon every cell-click event\n // to see whether a \"terminal state\" \n // has been acheaved...\n \n\n // \"this\" is TacProcHndlr...\n\n const winArr = this.cllsWnScr;\n\n let ptrnWin = [];\n\n let notDraw = TacAppHndlr.flgGo;\n // var isItAI = TacAppHndlr.flgAI;\n\n // Flag indicating extended game is active...\n const isItDie = TacAppHndlr.diceFlg;\n\n if (!isItDie) {\n // If the game has not been extended yet, \n // that is, the dice were not rolled...\n\n ptrnWin = collectInfoOrig();\n \n } else {\n // Extended game is activated...\n\n ptrnWin = collectInfoExt();\n\n }\n\n \n if (!isItDie) {\n // Checking for a winner in simple game...\n\n isThereWin(ptrnWin, '111', '222');\n\n } else {\n // Checking for a winner in the extended game...\n\n isThereWin(ptrnWin, '1111', '2222');\n\n }\n\n // Check if the game is over due to a draw...\n notDraw = this.rmMvs(winArr);\n\n if (notDraw) {\n // There are available moves...\n // Proceed with the game...\n\n // If the Player 1, \"X\", is a computer,\n // and it is its turn...\n\n if (\n TacAppHndlr.flgGo &&\n TacAppHndlr.flgAI &&\n TacAppHndlr.flgMov_2 &&\n TacAppHndlr.gmProc.currPlayer === true\n ) {\n // Run minimax evaluation for current state of the board...\n this.thrdPlsMvAI();\n\n // Switch to Player 2, \"O\"...\n // moveHandlr takes care of it...\n // TacAppHndlr.gmProc.currPlayer = false;\n }\n\n } else {\n\n // This is the draw case...\n alert(msg_3);\n alert(msg_4);\n }\n\n // Update flag to proceed or restart...\n TacAppHndlr.flgGo = notDraw;\n\n }",
"function nextMove() { //whenever click on any square will trigger this function\n\n // If there is already a winner ...\n if(winner != null) { // this run each time there is a click ........ if the winner is not equal t null then someone has already wn the game. but if its not true it will run the else if.\n setMessage(turn + \"already won.\") // maybe be in correct but who cares at this moment because this shit works.\n } else if(this.innerText == '') {\n // If there isn't a winner and the square is free ...\n //if its an empty space then its the other persons turn if not then you cant use it.\n this.innerText = turn; //fills square with the 'X' or 'O' depending on 'turn'.\n moves++; // increment move count by 1, equivlent to moves = moves + 1;\n switchTurn(); // utilises the switchturn function call and takes from X-0-X\n} else { // If there isn't a winner but the square isn't free ...\n setMessage('Pick another square');``\n } ///next move determining the next player. based on the calls from the function to next move we highlight this with the setmessage function from a visual aspect. we are playing turn into the square and turn will be whoever x or o whoevers turn it will be.\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.