query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Transforms an RDF term to the internal representation of a term, assuming it is not a variable, which would be an expression (internally).
function transformRDFTermUnsafe(term) { return transformTerm({ term, type: 'expression', expressionType: 'term', }); }
[ "transformRDFTermUnsafe(term) {\n return this.transformTerm({\n term,\n type: sparqlalgebrajs_1.Algebra.types.EXPRESSION,\n expressionType: sparqlalgebrajs_1.Algebra.expressionTypes.TERM,\n });\n }", "function RDFMakeTerm(formula,val, canonicalize) {\n if (typeof val != 'object') { \n\t if (typeof val == 'string')\n\t return new $rdf.Literal(val);\n if (typeof val == 'number')\n return new $rdf.Literal(val); // @@ differet types\n if (typeof val == 'boolean')\n return new $rdf.Literal(val?\"1\":\"0\", undefined, \n $rdf.Symbol.prototype.XSDboolean);\n\t else if (typeof val == 'number')\n\t return new $rdf.Literal(''+val); // @@ datatypes\n\t else if (typeof val == 'undefined')\n\t return undefined;\n\t else // @@ add converting of dates and numbers\n\t throw \"Can't make Term from \" + val + \" of type \" + typeof val; \n }\n return val;\n}", "function termToId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return `_:${term.value}`;\n case 'Variable': return `?${term.value}`;\n case 'DefaultGraph': return '';\n case 'Literal': return `\"${term.value}\"${\n term.language ? `@${term.language}` :\n (term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : '')}`;\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${\n escapeQuotes(termToId(term.subject))\n } ${\n escapeQuotes(termToId(term.predicate))\n } ${\n escapeQuotes(termToId(term.object))\n }${\n ((0,_N3Util__WEBPACK_IMPORTED_MODULE_1__.isDefaultGraph)(term.graph)) ? '' : ` ${termToId(term.graph)}`\n }>>`;\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}", "function termToId(term) {\n if (typeof term === 'string') return term;\n if (term instanceof Term && term.termType !== 'Quad') return term.id;\n if (!term) return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode':\n return term.value;\n case 'BlankNode':\n return `_:${term.value}`;\n case 'Variable':\n return `?${term.value}`;\n case 'DefaultGraph':\n return '';\n case 'Literal':\n return `\"${term.value}\"${term.language ? `@${term.language}` : term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : ''}`;\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${escapeQuotes(termToId(term.subject))} ${escapeQuotes(termToId(term.predicate))} ${escapeQuotes(termToId(term.object))}${(0, _N3Util.isDefaultGraph)(term.graph) ? '' : ` ${termToId(term.graph)}`}>>`;\n default:\n throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}", "function termToId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return `_:${term.value}`;\n case 'Variable': return `?${term.value}`;\n case 'DefaultGraph': return '';\n case 'Literal': return `\"${term.value}\"${\n term.language ? `@${term.language}` :\n (term.datatype && term.datatype.value !== N3DataFactory_xsd.string ? `^^${term.datatype.value}` : '')}`;\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${\n escapeQuotes(termToId(term.subject))\n } ${\n escapeQuotes(termToId(term.predicate))\n } ${\n escapeQuotes(termToId(term.object))\n }${\n (isDefaultGraph(term.graph)) ? '' : ` ${termToId(term.graph)}`\n }>>`;\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n}", "function termToId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH$1.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return `_:${term.value}`;\n case 'Variable': return `?${term.value}`;\n case 'DefaultGraph': return '';\n case 'Literal': return `\"${term.value}\"${\n term.language ? `@${term.language}` :\n (term.datatype && term.datatype.value !== xsd$1.string ? `^^${term.datatype.value}` : '')}`;\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${\n escapeQuotes(termToId(term.subject))\n } ${\n escapeQuotes(termToId(term.predicate))\n } ${\n escapeQuotes(termToId(term.object))\n }${\n (isDefaultGraph(term.graph)) ? '' : ` ${termToId(term.graph)}`\n }>>`;\n default: throw new Error(`Unexpected termType: ${term.termType}`);\n }\n }", "function termToId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term && term.termType !== 'Quad')\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return '_:' + term.value;\n case 'Variable': return '?' + term.value;\n case 'DefaultGraph': return '';\n case 'Literal': return '\"' + term.value + '\"' +\n (term.language ? '@' + term.language :\n (term.datatype && term.datatype.value !== N3DataFactory_xsd.string ? '^^' + term.datatype.value : ''));\n case 'Quad':\n // To identify RDF* quad components, we escape quotes by doubling them.\n // This avoids the overhead of backslash parsing of Turtle-like syntaxes.\n return `<<${\n escapeQuotes(termToId(term.subject))\n } ${\n escapeQuotes(termToId(term.predicate))\n } ${\n escapeQuotes(termToId(term.object))\n }${\n (isDefaultGraph(term.graph)) ? '' : ` ${termToId(term.graph)}`\n }>>`;\n default: throw new Error('Unexpected termType: ' + term.termType);\n }\n}", "fromTerm(original) {\n // TODO: remove nasty any casts when this TS bug has been fixed:\n // https://github.com/microsoft/TypeScript/issues/26933\n switch (original.termType) {\n case 'NamedNode':\n return this.namedNode(original.value);\n case 'BlankNode':\n return this.blankNode(original.value);\n case 'Literal':\n if (original.language) {\n return this.literal(original.value, original.language);\n }\n if (!original.datatype.equals(Literal_1.Literal.XSD_STRING)) {\n return this.literal(original.value, this.fromTerm(original.datatype));\n }\n return this.literal(original.value);\n case 'Variable':\n return this.variable(original.value);\n case 'DefaultGraph':\n return this.defaultGraph();\n case 'Quad':\n return this.quad(this.fromTerm(original.subject), this.fromTerm(original.predicate), this.fromTerm(original.object), this.fromTerm(original.graph));\n }\n }", "fromTerm(original) {\n // TODO: remove nasty any casts when this TS bug has been fixed:\n // https://github.com/microsoft/TypeScript/issues/26933\n switch (original.termType) {\n case 'NamedNode':\n return this.namedNode(original.value);\n case 'BlankNode':\n return this.blankNode(original.value);\n case 'Literal':\n if (original.language) {\n return this.literal(original.value, original.language);\n }\n if (!original.datatype.equals(Literal_1.Literal.XSD_STRING)) {\n return this.literal(original.value, this.fromTerm(original.datatype));\n }\n return this.literal(original.value);\n case 'Variable':\n return this.variable(original.value);\n case 'DefaultGraph':\n return this.defaultGraph();\n case 'Quad':\n return this.quad(this.fromTerm(original.subject), this.fromTerm(original.predicate), this.fromTerm(original.object), this.fromTerm(original.graph));\n }\n }", "toLiteral(value) {\n if (typeof value === 'undefined' || value === null) {\n throw (new Error(`RDFEnvironment.toLiteral: invalid value: '${value}' of type '${typeof value}'`));\n } else if (value instanceof Term) { // this is already a Term instance\n return (value);\n } else {\n var type = typeof(value);\n var converter = null;\n switch (type) {\n case 'object':\n converter = Literal.toLiteral[value.constructor.name];\n if (converter) {\n return (converter(value));\n }\n break;\n default:\n converter = Literal.toLiteral[type];\n if (converter) {\n var literal = converter(value);\n return (literal);\n }\n }\n throw (new Error(`RDFEnvironment.toLiteral: invalid value: '${value}' of type '${typeof value}'`));\n }\n }", "function toId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term)\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return '_:' + term.value;\n case 'Variable': return '?' + term.value;\n case 'DefaultGraph': return '';\n case 'Literal': return '\"' + term.value + '\"' +\n (term.language ? '@' + term.language :\n (term.datatype && term.datatype.value !== xsd.string ? '^^' + term.datatype.value : ''));\n default: throw new Error('Unexpected termType: ' + term.termType);\n }\n }", "function toId(term) {\n if (typeof term === 'string')\n return term;\n if (term instanceof Term)\n return term.id;\n if (!term)\n return DEFAULTGRAPH.id;\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value;\n case 'BlankNode': return '_:' + term.value;\n case 'Variable': return '?' + term.value;\n case 'DefaultGraph': return '';\n case 'Literal': return '\"' + term.value + '\"' +\n (term.language ? '@' + term.language :\n (term.datatype && term.datatype.value !== xsd.string ? '^^' + term.datatype.value : ''));\n default: throw new Error('Unexpected termType: ' + term.termType);\n }\n}", "function toId (term) {\n if (typeof term === 'string') {\n return term\n }\n if (term && !term.equals(DEFAULTGRAPH) && term.id) {\n return term.id\n }\n if (!term) {\n return DEFAULTGRAPH.value\n }\n\n // Term instantiated with another library\n switch (term.termType) {\n case 'NamedNode': return term.value\n case 'BlankNode': return `_:${term.value}`\n case 'Variable': return `?${term.value}`\n case 'DefaultGraph': return ''\n case 'Literal':\n const datatype = term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : ''\n const language = term.language ? `@${term.language}` : datatype\n\n return `\"${term.value}\"${language}`\n default: throw new Error(`Unexpected termType: ${term.termType}`)\n }\n}", "termToString(term) {\n switch (term.termType) {\n case 'NamedNode':\n return `<${term.value}>`;\n case 'BlankNode':\n return `_:${term.value}`;\n case 'Literal':\n let suffix = '';\n if (term.language)\n suffix = `@${term.language}`;\n else if (term.datatype.value !== 'http://www.w3.org/2001/XMLSchema#string')\n suffix = `^^<${term.datatype.value}>`;\n return `\"${term.value.replace(/\"/g, '\\\\\"')}\"${suffix}`;\n default:\n throw new Error(`Could not convert a term of type ${term.termType}`);\n }\n }", "termToString(term) {\n // Determine escaped value\n let { value } = term;\n if (NEEDS_ESCAPE.test(value))\n value = value.replace(ESCAPE_ALL, escapeCharacter);\n\n switch (term.termType) {\n case 'NamedNode':\n return `<${value}>`;\n\n case 'BlankNode':\n return `_:${value}`;\n\n case 'Literal':\n // Determine optional language or datatype\n let suffix = '';\n if (term.language)\n suffix = `@${term.language}`;\n else if (term.datatype.value !== 'http://www.w3.org/2001/XMLSchema#string')\n suffix = `^^<${term.datatype.value}>`;\n return `\"${value}\"${suffix}`;\n\n default:\n throw new Error(`Could not convert a term of type ${term.termType}`);\n }\n }", "function termFromId(id, factory) {\n factory = factory || DataFactory;\n\n // Falsy value or empty string indicate the default graph\n if (!id)\n return factory.defaultGraph();\n\n // Identify the term type based on the first character\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n case '_':\n return factory.blankNode(id.substr(2));\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory)\n return new Literal(id);\n // Literal without datatype or language\n if (id[id.length - 1] === '\"')\n return factory.literal(id.substr(1, id.length - 2));\n // Literal with datatype or language\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1),\n id[endPos + 1] === '@' ? id.substr(endPos + 2)\n : factory.namedNode(id.substr(endPos + 3)));\n case '<':\n const components = quadId.exec(id);\n return factory.quad(\n termFromId(unescapeQuotes(components[1]), factory),\n termFromId(unescapeQuotes(components[2]), factory),\n termFromId(unescapeQuotes(components[3]), factory),\n components[4] && termFromId(unescapeQuotes(components[4]), factory)\n );\n default:\n return factory.namedNode(id);\n }\n }", "function termFromId(id, factory) {\n factory = factory || DataFactory; // Falsy value or empty string indicate the default graph\n\n if (!id) return factory.defaultGraph(); // Identify the term type based on the first character\n\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n\n case '_':\n return factory.blankNode(id.substr(2));\n\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory) return new Literal(id); // Literal without datatype or language\n\n if (id[id.length - 1] === '\"') return factory.literal(id.substr(1, id.length - 2)); // Literal with datatype or language\n\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1), id[endPos + 1] === '@' ? id.substr(endPos + 2) : factory.namedNode(id.substr(endPos + 3)));\n\n case '<':\n const components = quadId.exec(id);\n return factory.quad(termFromId(unescapeQuotes(components[1]), factory), termFromId(unescapeQuotes(components[2]), factory), termFromId(unescapeQuotes(components[3]), factory), components[4] && termFromId(unescapeQuotes(components[4]), factory));\n\n default:\n return factory.namedNode(id);\n }\n} // ### Constructs an internal string ID from the given term or ID string", "function termFromId(id, factory) {\n factory = factory || DataFactory;\n\n // Falsy value or empty string indicate the default graph\n if (!id)\n return factory.defaultGraph();\n\n // Identify the term type based on the first character\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n case '_':\n return factory.blankNode(id.substr(2));\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory)\n return new Literal(id);\n // Literal without datatype or language\n if (id[id.length - 1] === '\"')\n return factory.literal(id.substr(1, id.length - 2));\n // Literal with datatype or language\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1),\n id[endPos + 1] === '@' ? id.substr(endPos + 2)\n : factory.namedNode(id.substr(endPos + 3)));\n case '<':\n const components = quadId.exec(id);\n return factory.quad(\n termFromId(unescapeQuotes(components[1]), factory),\n termFromId(unescapeQuotes(components[2]), factory),\n termFromId(unescapeQuotes(components[3]), factory),\n components[4] && termFromId(unescapeQuotes(components[4]), factory)\n );\n default:\n return factory.namedNode(id);\n }\n}", "function termFromId(id, factory) {\n factory = factory || DataFactory;\n\n // Falsy value or empty string indicate the default graph\n if (!id) return factory.defaultGraph();\n\n // Identify the term type based on the first character\n switch (id[0]) {\n case '?':\n return factory.variable(id.substr(1));\n case '_':\n return factory.blankNode(id.substr(2));\n case '\"':\n // Shortcut for internal literals\n if (factory === DataFactory) return new Literal(id);\n // Literal without datatype or language\n if (id[id.length - 1] === '\"') return factory.literal(id.substr(1, id.length - 2));\n // Literal with datatype or language\n const endPos = id.lastIndexOf('\"', id.length - 1);\n return factory.literal(id.substr(1, endPos - 1), id[endPos + 1] === '@' ? id.substr(endPos + 2) : factory.namedNode(id.substr(endPos + 3)));\n case '<':\n const components = quadId.exec(id);\n return factory.quad(termFromId(unescapeQuotes(components[1]), factory), termFromId(unescapeQuotes(components[2]), factory), termFromId(unescapeQuotes(components[3]), factory), components[4] && termFromId(unescapeQuotes(components[4]), factory));\n default:\n return factory.namedNode(id);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
splits the phrase in words
function toSplit(phrase){ var cut = phrase.split(" "); return cut; }
[ "split(phrase) {\n return phrase.toLowerCase().split(/\\s+/g);\n }", "function _splitWords(text) {\n\t\t\treturn text.split(/\\s+/);\n\t\t}", "function _splitWords(text) {\n\t\treturn text.split(/\\s+/);\n\t}", "function splitText(t) {\n return t.split(\"|\")\n .map(function (el) {\n return el.split(\" \");\n })\n .reduce(function (words, sentence) {\n words.push(\"\");\n for (var i = 0; i < sentence.length; i++) {\n words.push(sentence[i]);\n }\n return words;\n });\n}", "tokenize(text) {\n text = text.toLowerCase();\n const phrases = [ text ];\n let matches = text.match(/\\s+/);\n let i = -1;\n if (matches && matches[0]) {\n i = matches.index + matches[0].length;\n }\n let ctr = 0;\n while (i !== -1 && ctr < 4) { // insert 4 more phrases\n text = text.substring(i);\n phrases.push(text);\n matches = text.match(/\\s+/);\n if (matches && matches[0]) {\n i = matches.index + matches[0].length;\n } else {\n i = -1;\n }\n ++ctr;\n }\n\n return phrases;\n }", "words(string){\n const wrds = string.split(' ');\n return wrds\n }", "words(string){\n return string.split(' ');\n }", "breakingTheWord() {\n const newWord = this.word;\n return newWord.split(\"\");\n }", "function splitIntoWords(msg){\n words = []; //bye bye all of the words ):\n //hello new words!\n var i =0;\n var tmpWord = \"\";\n while (msg.charAt(i) != \"\"){ //runs as trough all of the content of msg\n if (isSpace(msg.charAt(i)) ){\n \n if (legalWord(tmpWord)){\n words[words.length] = tmpWord \n }\n tmpWord = \"\";\n \n }else{ //if char is not a space (space is not just space) char\n tmpWord +=msg.charAt(i);\n \n }\n \n i++;\n }\n //last word\n if (legalWord(tmpWord)){\n words[words.length] = tmpWord\n }\n \n}", "function wordSplit() {\n\twordLetters = currentWord.split(\"\");\n}", "function getWords(text) {\n if (text.length > 0){\n return text.split(' ');\n } else return []\n}", "function splitwords(txt) {\r\n return txt.split(/\\s+/)\r\n .filter(function(i) {\r\n return i!==\"\";\r\n });\r\n}", "words(str){\n return str.trim().split(\" \");\n }", "function splitIntoWords(text) {\n return text.toLowerCase().split(/[^a-z0-9]/).filter(e => e);\n}", "words(string){\n let words = string.split(' ');\n return words;\n }", "function getWordsFromText(text) {\n\t //var pattern = /[\\wА-Яа-я]+/g;\n //return text.match(pattern);\n return text.split(\" \");\n }", "function splitWord(word){\n word = word.trim();\n var words = [\"\",\"\"];\n var location = 0;\n var caps = 0;\n var len = word.length;\n\n for(var i = 0; i < len; i++){\n if(word[i] == word[i].toUpperCase()){\n if(caps >= 1){\n location = i;\n \n break;\n }\n else{\n caps++;\n }\n } \n }\n \n words[0] = word.substr(0, location);\n words[1] = word.substr(location);\n \n return words;\n \n}", "function splitWords(input) {\n\treturn input.trim().split(/[ _-]|(?<=[a-z])(?=[A-Z])/);\n}", "words(str) {\n return str.split(\" \");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This helper function takes an individual quote object and turns it into an li. Called on the initial render and whenever we post a quote.
function renderQuote(quote){ return `<li class='quote-card'> <blockquote class="blockquote"> <p class="mb-0">${quote.quote}</p> <footer class="blockquote-footer">${quote.author}</footer> <br> <button data-like-id=${quote.id} class='btn-success'>Likes: <span>${quote.likes.length}</span></button> <button data-delete-id=${quote.id} class='btn-danger'>Delete</button> </blockquote> </li>` }
[ "function formatQuoteList(quote) {\n return `\n <blockquote class=\"blockquote\">\n <p class=\"mb-0\">${quote.quote}</p>\n <footer class=\"blockquote-footer\">${quote.author}</footer>\n <br>\n <button class='btn-success' success_id=${quote.id}>Likes: <span>${quote.likes}</span></button>\n <button class='btn-danger' danger_id=${quote.id}>Delete</button>\n </blockquote>\n `\n}", "function appendQuotes(quotes){\n output = ''\n\n for(quote of quotes){\n output += `<li>\"${quote.quote}\" by: ${quote.author}</li>`;\n }\n $('#quoteList').append(output);\n}", "function buildQuoteCard(quote) {\n const newQuote = document.createElement('li')\n newQuote.className = 'quote-card'\n \n const quoteBlock = document.createElement('BLOCKQUOTE')\n quoteBlock.className = 'blockquote'\n \n const createP = document.createElement('p')\n createP.className = 'mb-0'\n createP.innerText = quote.quote\n \n const createFooter = document.createElement('FOOTER')\n createFooter.className = 'blockquote-footer'\n createFooter.innerText = quote.author\n \n const likeBtn = document.createElement('button')\n likeBtn.className = 'btn-success'\n likeBtn.innerText = \"Likes:\"\n likeBtn.span = 0\n \n const deleteBtn = document.createElement('button')\n deleteBtn.className = 'btn-danger'\n deleteBtn.innerText = \"Delete\"\n \n newQuote.appendChild(quoteBlock)\n newQuote.appendChild(createP)\n newQuote.appendChild(createFooter)\n newQuote.appendChild(likeBtn)\n newQuote.appendChild(deleteBtn)\n quoteList.appendChild(newQuote)\n\n //deletes the quote - refers to \"deleteQuote\" method above\n deleteBtn.addEventListener(\"click\", () => {\n deleteQuote(quote);\n newQuote.remove();\n });\n }", "function newQuote(x) {\n var listItem = document.createElement(\"div\");\n \n listItem.innerText=x\n listItem.setAttribute(\"id\", \"listItem\")\n \n $(\"#quoteList\").append(listItem);\n \n}", "function buildCard(quote) {\n //creating the HTML elements\n let li = document.createElement('li')\n let blockquote = document.createElement('blockquote')\n let p = document.createElement('p')\n let footer = document.createElement('footer')\n let br = document.createElement('br')\n\n //get the data for the text to populate the card\n let {author, id, quote:text} = quote\n\n //adding tags to the elements\n li.className = 'quote-card'\n li.id = `li-${id}`\n blockquote.className = 'blockquote'\n blockquote.id = `block-${id}`\n p.className = 'mb-0'\n footer.className = 'blockquote-footer'\n\n //add text data to the card elements\n p.textContent = text\n footer.textContent = author\n\n //building the card\n blockquote.append(p, footer, br)\n li.append(blockquote)\n quoteList.append(li)\n likeButton(quote)\n deleteButton(quote)\n}", "function showQuote(quote){\n const li = document.createElement(\"li\")\n li.className = \"blockquote\"\n const blockquote = document.createElement(\"blockquote\")\n blockquote.className = \"blockquote\"\n const p = document.createElement(\"p\")\n p.className = \"mb-0\"\n p.innerText = quote.quote\n const footer = document.createElement(\"footer\")\n footer.className = \"blockquote-footer\"\n footer.innerText = quote.author\n const br = document.createElement(\"br\")\n const likeBtn = document.createElement(\"button\")\n likeBtn.innerText = \"Likes:\"\n likeBtn.className = \"btn-success\"\n const span = document.createElement(\"span\")\n span.innerText = quote.likes.length\n // LIKE FUNCITONALITY \n likeBtn.addEventListener(\"click\", () => {\n fetch(LIKES_URL, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n }, \n body: JSON.stringify({\n quoteId: quote.id, \n // createdAt: \"SOMENUMBERS\"\n })\n }) \n .then (resp => resp.json())\n .then (newLike => {\n // quote.likes.push(newLike)\n // span.innerText = quote.likes.length\n fetch(\"http://localhost:3000/likes?quoteId=\" + quote.id)\n .then(resp => resp.json())\n .then(likes => span.innerText = likes.length)\n })\n })\n likeBtn.append(span)\n const dltBtn = document.createElement(\"button\")\n dltBtn.innerText = \"Delete\"\n dltBtn.className = \"btn-danger\"\n // DELETE FUNCTIONALITY\n dltBtn.addEventListener(\"click\", ()=>{\n fetch(QUOTES_URL + \"/\" + quote.id, {\n method: \"DELETE\"\n })\n .then(resp => resp.json())\n .then(dltedQuote => li.remove())\n })\n const editBtn = document.createElement(\"button\")\n editBtn.innerText = \"Edit\"\n const editDiv = document.createElement(\"div\")\n const editFormHTML = \n `<form id=\"edit-quote-${quote.id}-form\">` +\n '<div class=\"form-group\">' +\n '<label for=\"new-quote\">Edit Quote</label>' +\n `<input name=\"quote\" type=\"text\" class=\"form-control\" id=\"edit-quote-${quote.id}\" placeholder=\"Learn. Love. Code.\">` +\n '</div>' +\n '<div class=\"form-group\">' +\n '<label for=\"Author\">Author</label>' +\n `<input name=\"author\" type=\"text\" class=\"form-control\" id=\"edit-author-${quote.id}\" placeholder=\"Flatiron School\">` +\n '</div>' +\n '<button type=\"submit\" class=\"btn btn-primary\">Update</button>' +\n '<br><br>' +\n '</form>' \n editDiv.innerHTML = editFormHTML\n editDiv.style.display = \"none\"\n // EDIT FUNCTIONALITY\n editBtn.addEventListener(\"click\", ()=>{\n editDiv.style.display = \"block\"\n const editForm = document.querySelector(`#edit-quote-${quote.id}-form`)\n const editQuoteField = document.querySelector(`#edit-quote-${quote.id}`)\n editQuoteField.value = quote.quote\n const editAuthorField = document.querySelector(`#edit-author-${quote.id}`)\n editAuthorField.value = quote.author\n editForm.addEventListener(\"submit\", ()=> {\n event.preventDefault()\n fetch(QUOTES_URL + \"/\" + quote.id, {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n }, \n body: JSON.stringify({\n quote: editQuoteField.value,\n author: editAuthorField.value\n })\n })\n .then (resp => resp.json())\n .then (updatedQuote => {\n quote = updatedQuote\n p.innerText = quote.quote\n footer.innerText = quote.author\n form.reset()\n editDiv.style.display = \"none\"\n })\n })\n\n })\n blockquote.append(p, footer, br, editDiv, likeBtn, dltBtn, editBtn)\n li.append(blockquote)\n list.append(li)\n }", "function updateQuotesPage(quotes) {\n\t\toutput.innerHTML = '';\n\t\tmessage = '<h2>Quotes</h2><ol>';\n for (var i = 0, count = quotes.length; i < count; i++) {\n \t\tmessage += '<li>' + quotes[i] + '</li>';\n }\n message += '</ol>';\n output.innerHTML = message;\n} // End of updateQuotesPage() function.", "function saveQuotes() {\n getSavedArr = JSON.parse(localStorage.getItem(\"savedQuote\"));\n listQuote = getSavedArr.quotetext;\n listQuoteEl = $(\"<p>\").text(listQuote);\n lineBreak = $(\"<br>\");\n listAuthor = \"-\" + getSavedArr.author;\n listAuthorEl = $(\"<p>\").text(listAuthor);\n horizontalRule = $(\"<hr>\");\n // --------------TWITTER <a> button----------------\n const q = $(quote);\n const currentPageUrl = window.location.href;\n let clickToTweetBtn = $(\"<a>\");\n let tweetableUrl = makeTweetableUrl(q.text(), currentPageUrl);\n clickToTweetBtn.text(\"Click to Tweet\");\n clickToTweetBtn.attr(\"href\", tweetableUrl);\n clickToTweetBtn.on(\"click\", onClickToTweet);\n // --------------END TWITTER <a> button-------------\n newListItem = $(\"<li>\");\n newListItem.append(\n listQuote,\n lineBreak,\n listAuthor,\n lineBreak,\n clickToTweetBtn,\n horizontalRule\n );\n $(\"#list\").prepend(newListItem);\n }", "function displayQuote() {\n var currentQuote = quoteArray.shift();\n\n if (currentQuote !== undefined) {\n document.getElementById(\"quote\").innerHTML = currentQuote[0].content;\n document.getElementById(\"quote\").innerHTML += \"<p id=\\\"author\\\">\" + currentQuote[0].title + \"</p>\";\n var tweetString = currentQuote[0].content.replace(/<(?:.|\\n)*?>/gm, '') + \" - \" + currentQuote[0].title;\n updateTweet(tweetString);\n // Only want to set new colour upon changing quote.\n loadColourData();\n } else {\n document.getElementById(\"quote\").innerHTML = \"Quote Loading...\";\n }\n\n loadQuoteData();\n}", "function displayQuote() {\n let quoteList = $quoteList;\n while (quoteList.hasChildNodes()) {\n quoteList.removeChild(quoteList.lastChild);\n }\n for (let i = 0; i < quoteResult.length; i++) {\n let newDiv = document.createElement(\"div\");\n newDiv.addEventListener(\"click\", function() {\n addToBlacklist(this.innerText);\n this.style.display = \"none\";\n });\n let newContent = document.createTextNode(quoteResult[i]);\n newDiv.appendChild(newContent);\n quoteList.appendChild(newDiv);\n }\n}", "function listItemGenerator(post){\n let li = document.createElement('li');\n let liData = `${post.id}. ${post.title}(${post.userId})`;\n li.innerHTML = liData;\n li.className = listItemClassNames;\n return li;\n}", "function renderQuotes(quotes) {\n quotes.forEach(quote => {\n buildCard(quote)\n })\n}", "function displayQuote (){\n let quoteContent = quotes;\n while (quoteContent.hasChildNodes()) {\n quoteContent.removeChild(quoteContent.lastChild);\n }\n for (let i = 0; i < quoteResult.length; i++) {\n let newDiv = document.createElement(\"div\");\n let newContent = document.createTextNode(quoteResult[i]);\n newDiv.appendChild(newContent);\n quoteContent.appendChild(newDiv);\n }\n}", "render() {\n return (\n <div>\n {this.state.quotes.map(q => {\n return (\n <Quote quote={q} likeQuote={this.likeQuote} />\n )\n })}\n </div>\n )\n }", "function addQuote(quote) {\n\n //The games_id comes from the props (either an onClick from GamesView, or from the URL)\n let newQuote = { quote, games_id };\n\n //Post the quote to the database\n let options = {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(newQuote)\n };\n\n //Fetch the updated list (after waiting that it updates)\n fetch(\"/quotes\", options)\n .then(result => result.json())\n //When submitted, the page redirects to this route, which uses a prop.\n .then(history.push(`/quoteandchar/${games_id}`))\n .catch(err => {\n console.log(\"error!\", err.message);\n });\n }", "function newQuote(quote) {\n\tquotes.push(quote);\n\tdocument.querySelector(\".quote q\").innerText = quote;\n}", "function writeLiHtml(storyObj, isFavList){\n\t\tvar domainUrl = extractDomain(storyObj.url);\n\t\t/*\n\t\t\tfor Hacker News api, time is in unix format\n\t\t\tand stored in .time property\n\t\t\tdisplay time 'ago' posted\n\t\t*/\n\t\tif (!isFavList){\n\t\t\tvar timestamp = new Date(storyObj.time*1000);\n\t\t\tvar now = new Date().getTime();\n\t\t\tvar timeAgo = timeDifference(now, timestamp);\n\t\t}\n\t\t/*\n\t\t\tfor favorite list for heroku api,\n\t\t\ttime is stored in .created_at property\n\t\t\tdiplay time favorited\n\t\t*/\n\t\telse {\n\t\t\tvar timeAdded = new Date(storyObj.created_at);\n\t\t\tvar month = timeAdded.getMonth() + 1;\n\t\t\tvar day = timeAdded.getDay();\n\t\t\tvar year = timeAdded.getFullYear();\n\t\t}\n\t\tvar liHtml = `\n\t\t\t<li \n\t\t\t\tdata-by=\"${storyObj.by}\" \n\t\t\t\tdata-id=\"`;\n\t\tif (!isFavList){\n\t\t\tliHtml += storyObj.id;\n\t\t}\n\t\telse {\n\t\t\tliHtml += storyObj.story_id;\n\t\t}\n\t\tliHtml +=`\"\n\t\t\t\tdata-title=\"${storyObj.title}\"\n\t\t\t\tdata-url=\"${storyObj.url}\" `;\n\t\tif (isFavList) {\n\t\t\tliHtml += `data-ajaxId=\"${storyObj.id}\"`;\n\t\t}\n\t\tliHtml += `>\n\t\t\t\t<span>\n\t\t\t\t\t<span class=\"star glyphicon `;\n\t\tif (!isFavList){\n\t\t\tliHtml += `glyphicon-star-empty`;\n\t\t}\n\t\t//display the filled in star for favorite list\n\t\telse {\n\t\t\tliHtml += `glyphicon-star`;\n\t\t}\n\t\tliHtml += `\" aria-hidden=\"true\"></span> \n\t\t\t\t</span> \n\t\t\t\t<span class='name'>\n\t\t\t\t\t<a href='${storyObj.url}' target='_blank'>\n\t\t\t\t\t\t${storyObj.title}\n\t\t\t\t\t</a>\n\t\t\t\t</span>\n\t\t\t\t<span class='url'>\n\t\t\t\t\t\t(${domainUrl})\n\t\t\t\t</span><br>\n\t\t\t\t<span class=\"postInfo\">\n\t\t\t\t\tby ${storyObj.by}`; \n\t\tif (!isFavList){\n\t\t\tliHtml += \" \" + timeAgo;\n\t\t}\n\t\telse {\n\t\t\tliHtml += `; Favorited: ${month}/${day}/${year}`;\n\t\t}\n\t\tliHtml += `\n\t\t\t\t</span>\n\t\t\t</li>\n\t\t`;\n\t\t$ol.append(liHtml);\n\n\t\t//hide favorite star icons if not logged in\n\t\tif (!loggedIn){\n\t\t\t$('.star').hide();\n\t\t}\n\t}", "renderQuotes() {\n return this\n .state\n .quotes\n .map(quote => (<Panel quote={quote} key={quote._id} getQuotes={this.getQuotes}/>));\n }", "function appendQuote(object) {\n quoteHtml.innerHTML = ''; //\n //create h4 tags so it implements \n const quote = document.createElement('h4');\n const span = document.createElement('span');\n span.textContent = object.quote;\n quote.appendChild(span);\n return quoteHtml.appendChild(quote);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets validation messages from a validation response object.
function getMessages(result) { let messages = []; if (result.messages) { messages = [...messages, ...result.messages]; } if (result.schemaValidationMessages) { messages = [ ...messages, ...result.schemaValidationMessages.map((m) => `${m.level}: ${m.message}`), ]; } return messages; }
[ "function validateGetSmsResponse(response) {\n\tnotEqual(response[\"InboundSmsMessageList\"], undefined, \"InboundSmsMessageList\");\n\tisml = response[\"InboundSmsMessageList\"];\n\tif (isml != null) {\n\t\tnotEqual(isml[\"TotalNumberOfPendingMessages\"], undefined, \"TotalNumberOfPendingMessages\");\n\t\tnotEqual(isml[\"NumberOfMessagesInThisBatch\"], undefined, \"NumberOfMessagesInThisBatch\");\n\t\tnotEqual(isml[\"ResourceUrl\"], undefined, \"ResourceUrl\");\t\t\n\t\tnotEqual(isml[\"InboundSmsMessage\"], undefined, \"InboundSmsMessage\");\t\t\t\t\n\t}\t\n}", "function get_error_messages(err, rules) {\n\t\tif (typeof(err) == 'object') {\n\t\t\tvar errors = {};\n\t\t\tfor (var field in err) {\n\t\t\t\terrors[field] = {};\n\t\t\t\tvar error_message = '';\n\t\t\t\tif (rules[field][err[field]]['error_message']) {\n\t\t\t\t\terror_message = rules[field][err[field]]['error_message'];\n\t\t\t\t}\n\t\t\t\terrors[field][err[field]] = error_message;\n\t\t\t}\n\t\t\treturn errors;\n\t\t}\n\t\treturn err;\n\t}", "function _mapMessagesFromResponse(response) {\n if(response.data) {\n var messages = response.data.messages;\n for(var index=0; index < messages.length; index++) {\n _messages.push(messages[index]);\n }\n }\n }", "function __getValidationErrors () {\n\n return __validator_errors;\n\n }", "function getLocalizedMessages(){\n if(responseIsReady()){\n localizedMessages += getRawResponse();\n }\n}", "function Fev_GetInvalidValidatorErrorMessages()\n{\n\tvar i, j;\n\tvar msgArray = new Array();\n\tif (!Page_IsValid)\n\t{\n\t\tfor (i = 0; i < Page_Validators.length; i++)\n\t\t{\n\t\t\tif (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == \"string\")\n\t\t\t{\n\t\t\t\tvar msg = Page_Validators[i].errormessage;\n\t\t\t\tvar b = false;\n\t\t\t\tfor (j = 0; j < msgArray.length; j++)\n\t\t\t\t{\n\t\t\t\t\tif (msgArray[j] == msg)\n\t\t\t\t\t{\n\t\t\t\t\t\tb = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t\tif (!b)\n\t\t\t\t{\n\t\t\t\t\tmsgArray[msgArray.length] = msg;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t}\n\treturn msgArray;\n}", "get validationMessage() { \n\t\treturn this.#internals.validationMessage; \n\t}", "parseErrors(response, req, res) {\n if (!response.meta.messages) response.meta.messages = [];\n\n if (res.locals.messages) {\n let errors = [];\n\n // first get and format all errros:\n res.locals.messages.forEach(m => {\n if (m.status == 'danger' || m.status == 'error') {\n errors.push(req.we.utils._.merge({\n status: res.statusCode,\n title: m.message\n }, m.extraData));\n } else {\n // others messages like success goes in meta object\n response.meta.messages.push(m);\n }\n\n });\n\n\n if (errors && errors.length) {\n response.errors = errors;\n }\n }\n }", "validationErrors(errors) {\n let messages = [];\n for(let i in errors) {\n let error = errors[i];\n\n let parts =i.split('.');\n\n if(parts.length === 1) {\n if(messages[i] === undefined) {\n messages[i] = null;\n }\n\n messages[i + '_error'] = error[0];\n }\n else if (parts.length === 2) {\n let name = parts[0] + '_error';\n let index = parts[1];\n\n if(messages[name] === undefined) {\n messages[name] = [];\n }\n\n if(messages[name][index] === undefined) {\n messages[name][index] = null;\n }\n\n messages[name][index] = error[0];\n }\n }\n\n for(let name in messages) {\n this[name] = messages[name];\n }\n }", "getValidationMessage(){\n\t\treturn this.validationMessage;\n\t}", "getFailedValidations() {\n\t\treturn this.failedValidations\n\t}", "getErrors(component) {\n if (component != null) {\n const { validatorsErrors, validatorsError } = component.props;\n const { errors } = component.state;\n\n if (errors && errors.length) {\n // On map les erreurs\n return errors.map((error) => {\n // Sur les messages indiqués dans le composant\n // ou le message global\n return validatorsErrors[error] ? validatorsErrors[error] : validatorsError;\n });\n }\n }\n\n return [];\n }", "function getErrorMessage(response) {\n if (validator.isNonNullObject(response) &&\n 'error' in response &&\n validator.isNonEmptyString(response.error.message)) {\n return response.error.message;\n }\n return null;\n}", "get validationMessage() {\n return this.elementInternals ? this.elementInternals.validationMessage : this.proxy.validationMessage;\n }", "function getErrorMessages(type){\n\t\t\t\tvar messages = [];\n\t\t\t\tvar validationMessages = getErrorMessage(type);\n\t\t\t\tvar customMessages = getCustomValidationMessages(type);\n\t\t\t\t\n\t\t\t\tif(validationMessages){\n\t\t\t\t\tmessages = messages.concat(validationMessages);\n\t\t\t\t}\n\t\t\t\tif(customMessages){\n\t\t\t\t\tmessages = messages.concat(customMessages);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn messages;\n\t\t\t}", "validate() {\n if (!isObject(this.$transformedResponse)) {\n throw new Error('The transformed response must be an object.');\n }\n\n each(this.$required, key => {\n if (!(key in this.$transformedResponse)) {\n throw new Error(`\"${key}\" is a required property and does not exist in the tranformed response.`);\n }\n });\n }", "function prepareValidationErrors(){\n \n return context.getVariable(\"flow.myapi.error.errors\")|| [] ;\n \n}", "_validateAndReturnMessage(text) {\n if (this.props.validations) {\n var validations = this.props.validations;\n for (let i = 0; i < validations.length; i++) {\n var message = validations[i](text);\n if (message)\n return message;\n }\n }\n return null;\n }", "get validationMessage() {\n return supportsElementInternals ? this.elementInternals.validationMessage : this.proxy.validationMessage;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a custom button control to add to Google Maps
function customGoogleMapsButton(text, action) { var controlDiv = document.createElement('div'); var controlUI = document.createElement('div'); controlUI.style.backgroundColor = 'white'; controlUI.style.backgroundClip = 'padding-box'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; controlUI.style.color = 'rgb(86, 86, 86)'; controlUI.style.border = '1px solid rgba(0, 0, 0, 0.15)'; controlUI.style.borderBottomLeftRadius = '2px'; controlUI.style.borderRadius = '2px'; controlUI.style.margin = '5px'; controlUI.style.boxShadow = '0px 1px 4px -1px rgba(0, 0, 0, 0.3)'; controlDiv.appendChild(controlUI); var controlText = document.createElement('div'); controlText.style.padding = '1px 6px'; controlText.innerHTML = text; controlUI.appendChild(controlText); google.maps.event.addDomListener(controlUI, 'click', action); return controlDiv; }
[ "function addGeoLocationButton() {\r\n\t\t\tif (_geoBtn)\r\n\t\t\t// already added\r\n\t\t\t\treturn;\r\n\r\n\t\t\tvar onClickEvent = function (evt) {\r\n\t\t\t\t_plugIn.setMapCentreByGeo();\r\n\t\t\t};\r\n\r\n\t\t\t_geoBtn = createControlButton(\r\n\t\t\t\tBUTTONS.Geo,\r\n\t\t\t\tgm.ControlPosition.TOP_LEFT,\r\n\t\t\t\t\"mapsed-geo-button\",\r\n\t\t\t\tonClickEvent\r\n\t\t\t);\r\n\r\n\t\t} // addGeoLocationButton", "function createControlButton(buttonText, ctrlPos, addClass, onClickEvent) {\r\n\t\t\tvar btn = null,\r\n\t\t\t\t\tmarkUp = \"\",\r\n\t\t\t\t\tclasses = \"\",\r\n\t\t\t\t\ttooltip = \"\"\r\n\t\t\t;\r\n\r\n\t\t\tif (addClass && addClass.length > 0) {\r\n\t\t\t\tclasses = \" class='\" + addClass + \"' \";\r\n\t\t\t}\r\n\r\n\t\t\t// see if there's a tooltip added\r\n\t\t\tif (buttonText && buttonText.length > 0) {\r\n\t\t\t\tvar arrSplit = buttonText.split(\"|\");\r\n\t\t\t\tbuttonText = arrSplit[0];\r\n\t\t\t\ttooltip = (arrSplit.length > 1 ? \" title='\" + arrSplit[1] + \"'\" : \"\");\r\n\t\t\t}\r\n\r\n\t\t\tvar markUp =\r\n\t\t\t\t\"<button \"\r\n\t\t\t\t+ classes\r\n\t\t\t\t+ tooltip\r\n\t\t\t\t+ \">\"\r\n\t\t\t\t+ buttonText\r\n\t\t\t\t+ \"</button>\"\r\n\t\t\t;\r\n\r\n\t\t\tbtn = _plugIn.addMapControl(markUp, ctrlPos);\r\n\r\n\t\t\t// and wire up the onclick event handler\r\n\t\t\tif (onClickEvent) {\r\n\t\t\t\t// wire up the click event handler\r\n\t\t\t\tbtn.on(\"click\", onClickEvent);\r\n\t\t\t}\r\n\r\n\t\t\treturn btn;\r\n\r\n\t\t} // createControlButton", "function CustomControl(controlDiv, map) {\n\n //Add POI button\n var addPOIButton = document.createElement('button');\n addPOIButton.setAttribute(\"class\", \"controlUI\");\n addPOIButton.title = ADD_NEW_POI;\n controlDiv.appendChild(addPOIButton);\n\n //Marker icon\n var marker = document.createElement('span');\n marker.setAttribute(\"class\", \"glyphicon glyphicon-map-marker\");\n addPOIButton.appendChild(marker);\n\n // Setup the click event listeners\n var buttonActive = false;\n google.maps.event.addDomListener(addPOIButton, 'click', function() {\n\n buttonActive = !buttonActive;\n\n if(buttonActive){\n addPOIButton.setAttribute(\"class\", \"controlUIactive\");\n addPOIButton.title = CANCEL_ADD_NEW_POI;\n google.maps.event.addListener(map, 'click', function(event) {\n $('#myModal').modal({backdrop: \"static\"});\n $('#latitude').val(event.latLng.lat());\n $('#longitude').val(event.latLng.lng());\n });\n } else {\n addPOIButton.setAttribute(\"class\", \"controlUI\");\n addPOIButton.title = ADD_NEW_POI;\n google.maps.event.clearListeners(map, 'click');\n }\n });\n\n //Add Waypoint button\n var addWaypointButton = document.createElement('button');\n addWaypointButton.setAttribute(\"class\", \"controlUI\");\n addWaypointButton.title = 'Új kereszteződés hozzáadása';\n controlDiv.appendChild(addWaypointButton);\n\n //Waypoint icon\n var waypoint = document.createElement('span');\n waypoint.setAttribute(\"class\", \"glyphicon glyphicon-tags\");\n addWaypointButton.appendChild(waypoint);\n\n // Setup the click event listeners\n var waypointButtonActive = false;\n google.maps.event.addDomListener(addWaypointButton, 'click', function() {\n\n waypointButtonActive = !waypointButtonActive;\n\n if(waypointButtonActive){\n addWaypointButton.setAttribute(\"class\", \"controlUIactive\");\n addWaypointButton.title = 'Kereszteződés hozzáadás elvetése';\n google.maps.event.addListener(map, 'click', function(event) {\n //todo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n $('#waypointModal').modal({backdrop: \"static\"});\n $('#waypointLatitude').val(event.latLng.lat());\n $('#waypointLongitude').val(event.latLng.lng());\n });\n } else {\n addWaypointButton.setAttribute(\"class\", \"controlUI\");\n addWaypointButton.title = 'Új kereszteződés hozzáadása';\n google.maps.event.clearListeners(map, 'click');\n }\n });\n\n\n // Add Route button\n var addRouteButton = document.createElement('button');\n addRouteButton.setAttribute(\"class\", \"controlUI\");\n addRouteButton.title = 'Új út hozzáadása';\n controlDiv.appendChild(addRouteButton);\n\n //Route icon\n var route = document.createElement('span');\n route.setAttribute(\"class\", \"glyphicon glyphicon-road\");\n addRouteButton.appendChild(route);\n\n //Route button handler\n var routeButtonActive = false;\n google.maps.event.addDomListener(addRouteButton, 'click', function() {\n\n \trouteButtonActive = !routeButtonActive;\n\n if(routeButtonActive){\n \troutePointCounter = 0;\n addRouteButton.setAttribute(\"class\", \"controlUIactive\");\n addRouteButton.title = 'Út hozzáadás elvetése';\n initPoly();\n poly.setMap(map);\n map.addListener('click', addLatLng);\n //controlDiv.appendChild(addRouteReadyButton);\n } else {\n poly.setMap(null);\n poly = null;\n //controlDiv.removeChild(addRouteReadyButton);\n addRouteButton.setAttribute(\"class\", \"controlUI\");\n addRouteButton.title = 'Új út hozzáadása';\n google.maps.event.clearListeners(map, 'click');\n }\n });\n\n //Add route ready button\n //var addRouteReadyButton = document.createElement('button');\n //addRouteReadyButton.setAttribute(\"class\", \"controlUI\");\n //addRouteReadyButton.title = 'Út kész!';\n\n //var routeReady = document.createElement('span');\n //routeReady.setAttribute(\"class\", \"glyphicon glyphicon-ok\");\n //addRouteReadyButton.appendChild(routeReady);\n\n //google.maps.event.addDomListener(addRouteReadyButton, 'click', routeReadyFunc);\n\n}", "function initializeMapButtons(map) {\n var controlDiv = document.createElement('DIV');\n var control = new UploadButton(controlDiv, map);\n\n controlDiv.index = 1;\n map.controls[google.maps.ControlPosition.BOTTOM].push(controlDiv);\n}", "function initDropButton() {\n // Create a div that holds the cow-dropping button.\n var cowBtnContainer = document.createElement('div');\n cowBtnContainer.style.padding = \"10px 10px 0px 0px\";\n\n\n // Set the CSS for the button's border.\n var cowBtnBorder = document.createElement('div');\n //cowBtnBorder.style.backgroundColor = 'rgba(43, 132, 237, 1.0)';\n cowBtnBorder.style.cursor = 'pointer';\n cowBtnBorder.style.textAlign = 'center';\n cowBtnContainer.appendChild(cowBtnBorder);\n\n // Set the CSS for the button's interior content.\n cowBtnText = document.createElement('div');\n //cowBtnText.style.color = '#fff';\n cowBtnText.className = \"mapBtn\";\n cowBtnText.style.fontFamily = 'Arial,sans-serif';\n cowBtnText.style.fontSize = '16px';\n cowBtnText.style.lineHeight = '38px';\n cowBtnText.style.paddingLeft = '10px';\n cowBtnText.style.paddingRight = '10px';\n cowBtnText.style.borderRadius = '10px';\n cowBtnText.style.boxShadow = '0 2px 6px rgba(0, 0, 0, 0.3)';\n cowBtnText.innerHTML = 'Drop a Cow!';\n cowBtnBorder.append(cowBtnText);\n\n // Inserts the finished button to the right-center area of the map.\n googleMapObject.controls[google.maps.ControlPosition.LEFT].push(cowBtnContainer);\n\n // Setup the map listener for the button.\n google.maps.event.addDomListener(cowBtnContainer, 'click', dropTextListener);\n}", "function addLocateButton()\n{\n\tif(!navigator.geolocation)\n\t{\n\t\t// button should not be added if feature is not supported by browser\n\t\treturn;\n\t}\n\n\tbuttontag = document.createElement('button');\n\tbuttontag.title = WHERE_AM_I_HOVER_TEXT;\n\tbuttontag.innerHTML = WHERE_AM_I_TEXT;\n\n\t$(buttontag).bind('click', showMyLocation);\n\n\t$('#map_toolbar').prepend(buttontag);\n}", "function initCenterMapButton() {\n\n // Create the DIV to hold the control and call the CenterControl() constructor\n // passing in this DIV.\n var centerControlDiv = document.createElement('div');\n var centerControl = new CenterControl(centerControlDiv, map);\n\n centerControlDiv.index = 1;\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);\n}", "function BusinessControl(controlDiv, map){\n\t \n\t controlDiv.style.padding = '1px';\n\t \n\t var controlUI = document.createElement('div');\n\t controlUI.style.textAlign = 'center';\n\t controlUI.title = 'Elige solo los negocios';\n\t controlDiv.appendChild(controlUI);\n\n\t //Set CSS for the control interior\n\t var controlText = document.createElement('div');\n\t controlText.style.fontFamily = 'Arial, sans-serif';\n\t controlText.style.fontSize = '12px';\n\t controlText.style.paddingLeft = '4px';\n\t controlText.style.paddingRight = '4px';\n\t controlText.innerHTML = '<button type=\"button\" class=\"btn btn-danger btn-sm\"> <b>Negocios</b> </button>';\n\t controlUI.appendChild(controlText);\n\n\t //Setup the click event listeners\n\t google.maps.event.addDomListener(controlUI,'click',function(){\n\t\t \n\t\t firstRun=false;\n\t\t legend=[];\n\t\t if(markers!=0){\n\t\t for(var i=0; i<markers.length; i++){\n\t\t\t markers[i].setMap(null);\n\t\t }\n\t\t markers=[];\n\t\t }\n\t\t for (var key in icons) {\n\t\t if(icons[key].type === 'business'){\n\t\t addMarker(icons[key]);\n\t\t legend.push(icons[key]);\n\t\t }else{/*Do nothing*/}\n\t\t }\n\t\t CreateLegend();\n\t });\n\t }", "function OtherControl(controlDiv, map){\n\t controlDiv.style.padding = '1px';\n\t \n\t var controlUI = document.createElement('div');\n\t controlUI.style.textAlign = 'center';\n\t controlUI.title = 'Elige otros negocios ';\n\t controlDiv.appendChild(controlUI);\n\n\t //Set CSS for the control interior\n\t var controlText = document.createElement('div');\n\t controlText.style.fontFamily = 'Arial, sans-serif';\n\t controlText.style.fontSize = '12px';\n\t controlText.style.paddingLeft = '4px';\n\t controlText.style.paddingRight = '4px';\n\t controlText.innerHTML = '<button type=\"button\" class=\"btn btn-danger btn-sm\"> <b> Otros</b> </button>';\n\t controlUI.appendChild(controlText);\n\n\t //Setup the click event listeners\n\t google.maps.event.addDomListener(controlUI,'click',function(){\n\t\t firstRun=false;\n\t\t legend=[];\n\t\t if(markers!=0){\n\t\t for(var i=0; i<markers.length; i++){\n\t\t\t markers[i].setMap(null);\n\t\t }\n\t\t markers=[];\n\t\t }\n\t\t for (var key in icons) {\n\t\t if(icons[key].type === 'other'){\n\t\t addMarker(icons[key]);\n\t\t legend.push(icons[key]);\n\n\t\t }else{/*Do nothing*/}\n\t\t }\n\t\t CreateLegend();\n\n\t });\n\t }", "function createButton(bot)\n {\n var butu='<div class=\"leaflet-control-container\" >'+\n '<div class=\"leaflet-top leaflet-right\">'+\n '<div class=\"leaflet-control-zoom leaflet-bar leaflet-control\">'+\n '<button type=\"button\" id='+bot+'>Resizer</button>'+\n '</div>'+\n '</div>'+\n '</div>' ;\n $('#'+id).append(butu);\n $('#'+bot).click(function () {\n mymap.setView([52.03222, 16.52344], 1.5);\n });\n }", "function AddControl(controlDiv, map) {\n\n // Set CSS for the control border.\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = '#fff';\n controlUI.style.border = '2px solid #fff';\n controlUI.style.borderRadius = '3px';\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n controlUI.style.cursor = 'pointer';\n controlUI.style.marginTop = '10px';\n controlUI.style.marginRight = '13px';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Create new point on map (for authenticated users)';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior.\n var controlText = document.createElement('div');\n controlText.style.color = 'rgb(25,25,25)';\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlText.style.fontSize = '14px';\n controlText.style.lineHeight = '35px';\n controlText.style.paddingLeft = '5px';\n controlText.style.paddingRight = '5px';\n controlText.innerHTML = '<img src=\"static/icons/plus.svg\" alt=\"Add new point\"></img>';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners.\n controlUI.addEventListener('click', function () {\n if (document.getElementById('logoutElem')) {\n map.setOptions({ draggableCursor: 'copy' });\n google.maps.event.addListenerOnce(map, \"click\", function (event) {\n history.pushState(null, null, \"/places/new\");\n google.maps.event.addListenerOnce(infowindow, 'closeclick', (function () {\n return function () {\n history.pushState(null, null, \"/\");\n }\n })());\n map.setOptions({ draggableCursor: 'auto' });\n var latitude = event.latLng.lat();\n var longitude = event.latLng.lng();\n var latLng = event.latLng;\n var infoNewPlaceContentElem = document.getElementById('newPlaceForm');\n infoNewPlaceContentHTML = infoNewPlaceContentElem.innerHTML;\n infoNewPlaceContentHTML.className = 'new-place-visible';\n infoNewPlaceContent = infoNewPlaceContentHTML;\n console.log(infoNewPlaceContent);\n infowindow.setContent(infoNewPlaceContent);\n infowindow.setPosition(latLng);\n infowindow.open(map);\n document.getElementById(\"newPlaceLat\").value = latitude;\n document.getElementById(\"newPlaceLng\").value = longitude;\n\n });\n } else {\n var loginButton = document.getElementById('loginElem');\n loginButton.click();\n }\n\n });\n}", "function initOptionsButton() {\n // Create a div that holds the options button.\n var optionsContainer = document.createElement('div');\n optionsContainer.style.padding = \"10px 0px 0px 10px\";\n optionsContainer.className = \"options\";\n\n // Set the CSS for the button's border.\n var optionsBorder = document.createElement('div');\n optionsBorder.style.cursor = 'pointer';\n optionsBorder.style.textAlign = 'center';\n optionsBorder.style.borderRadius = '20%';\n optionsContainer.appendChild(optionsBorder);\n\n // Set the CSS for the button's interior content.\n var optionsImg = document.createElement('img');\n optionsImg.className = \"mapBtn\";\n optionsImg.style.boxShadow = '0 2px 6px rgba(0, 0, 0, 0.3)';\n optionsImg.style.borderRadius = '30%';\n optionsImg.style.padding = \"4px 4px 4px 4px\";\n optionsImg.setAttribute('src', 'img/options.png');\n optionsBorder.appendChild(optionsImg);\n\n // Inserts the finished button to the right-bottom area of the map.\n googleMapObject.controls[google.maps.ControlPosition.LEFT].push(optionsContainer);\n\n // Setup the map listener for the button.\n google.maps.event.addDomListener(optionsContainer, 'click', function(event) {\n return showOptions();\n });\n\n // Setup type filter button for clicks.\n $(\"#types-button\").click(function() {\n if ($(\"#types-filter\").hasClass(\"active\")) {\n $(\"#types-filter\").removeClass(\"active\");\n } else {\n $(\"#types-filter\").addClass(\"active\");\n }\n });\n}", "function _init_control(){\n try{\n self.mapView = Map.createView({\n filter_class:'Map',\n type:'Map',\n mapType: Map.STANDARD_TYPE,\n animate:true,\n regionFit:true\n });\n win.add(self.mapView);\n\n //tom tom button\n self.tomtomButton = Ti.UI.createButton({\n backgroundImage:self.get_file_path('image','tomtom.png'),\n width:60,\n height:60,\n bottom:10+self.tool_bar_height,\n right:10,\n color:self.font_color,\n font:{\n fontSize:self.font_size,\n fontWeight:self.font_weight\n },\n opacity:0.9\n });\n win.add(self.tomtomButton);\n\n self.tomtomButton.addEventListener('click',function(){\n _event_for_tomtom_btn_click();\n }); \n }catch(err){\n self.process_simple_error_message(err,window_source+' - _init_control');\n return;\n }\n }", "function createMapBtn(building, address, id) {\n loadMap(building, address, id);\n let mapButton = document.createElement('button');\n mapButton.textContent = \"Open Map\";\n mapButton.classList.add('btn', 'small-btn', 'map-btn');\n mapButton.id = `map-btn-${id}`;\n mapButton.addEventListener('click', (e) => {\n openMap(building, `map-${id}`);\n });\n return mapButton;\n}", "onAdd(map) {\n this._map = map;\n let _this = this;\n this._btn = document.createElement('button');// create the button\n this._btn.type = 'button';\n this._btn.innerHTML = \"SAT\";\n this._btn.id = 'satbtn';\n this._btn.className =\"controltext\";\n this._btn['aria-label'] = 'Toggle Imagery';//not sure\n this._btn.onclick = function () { //when the button is clicked\n var satstatus = map.getLayoutProperty(\n \"mapbox-satellite\", \"visibility\"\n );\n \n if (satstatus==\"visible\") {// if the panel is showing then run this\n map.setLayoutProperty(\"mapbox-satellite\",\"visibility\", \"none\");\n // map.setLayoutProperty(\"background\",\"visibility\", \"visible\");\n document.querySelector(\"#satbtn\").style.background = \"#0f1f3d\";\n\n } else {\n map.setLayoutProperty(\"mapbox-satellite\",\"visibility\",\"visible\");\n // map.setLayoutProperty(\"background\",\"visibility\", \"none\");\n document.querySelector(\"#satbtn\").style.background = \"white\";\n\n \n }\n };\n this._container = document.createElement('div');// create a div\n this._container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group';\n this._container.appendChild(this._btn);\n return this._container;\n }", "function addRefreshMapControl(){\n\n L.easyButton('glyphicon glyphicon-refresh', //Css class\n function (){ }, //onClick function\n 'Reset App', //Title\n map, //map control ref\n 'btnResetMap', //id\n '/mapfolio/#/default' //a href (optional)\n )\n\n }", "function FoodControl(controlDiv, map){\n\t \n\t controlDiv.style.padding = '1px';\n\t \n\t var controlUI = document.createElement('div');\n\t controlUI.style.textAlign = 'center';\n\t controlUI.title = 'Elige solo los negocios de alimentos';\n\t controlDiv.appendChild(controlUI);\n\n\t //Set CSS for the control interior\n\t var controlText = document.createElement('div');\n\t controlText.style.fontFamily = 'Arial, sans-serif';\n\t controlText.style.fontSize = '12px';\n\t controlText.style.paddingLeft = '4px';\n\t controlText.style.paddingRight = '4px';\n\t controlText.innerHTML = '<button type=\"button\" class=\"btn btn-danger btn-sm\"> <b>Alimentos</b> </button>';\n\t controlUI.appendChild(controlText);\n\n\t //Setup the click event listeners\n\t google.maps.event.addDomListener(controlUI,'click',function(){\n\t\t \n\t\t firstRun=false;\n\t\t legend=[];\n\t\t if(markers!=0){\n\t\t for(var i=0; i<markers.length; i++){\n\t\t\t markers[i].setMap(null);\n\t\t }\n\t\t markers=[];\n\t\t }\n\t\t for (var key in icons) {\n\t\t if(icons[key].type === 'food'){\n\t\t addMarker(icons[key]);\n\t\t legend.push(icons[key]);\n\t\t }else{/*Do nothing*/}\n\t\t }\n\t\t CreateLegend();\n\t });\n\t }", "function createMyLocationIcon(){\n\tvar controlDiv = document.createElement('div');\n\n\t// Styles for image icon.\n\tmyLocationIcon = document.createElement('div');\n\tmyLocationIcon.style.cursor = 'pointer';\n\tmyLocationIcon.style.backgroundImage = \"url(images/my_location.png)\";\n\tmyLocationIcon.style.height = '28px';\n\tmyLocationIcon.style.width = '25px';\n\tmyLocationIcon.style.marginRight = '11px';\n\tmyLocationIcon.style.marginTop = '5px';\n\tmyLocationIcon.style.marginBottom = '1px';\n\tmyLocationIcon.title = 'Go to my current location';\n\tcontrolDiv.appendChild(myLocationIcon);\n\n\t// Place the icon on the map (RIGHT_BOTTOM).\n\tmap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);\n}", "function AllControl(controlDiv, map){\n\t controlDiv.style.padding = '1px';\n\t \n\t var controlUI = document.createElement('div');\n\t controlUI.style.textAlign = 'center';\n\t controlUI.title = 'Ver todos los negocios ';\n\t controlDiv.appendChild(controlUI);\n\n\t //Set CSS for the control interior\n\t var controlText = document.createElement('div');\n\t controlText.style.fontFamily = 'Arial, sans-serif';\n\t controlText.style.fontSize = '12px';\n\t controlText.style.paddingLeft = '4px';\n\t controlText.style.paddingRight = '4px';\n\t controlText.innerHTML = '<button type=\"button\" class=\"btn btn-danger btn-sm\"> <b> Todos</b> </button>';\n\t controlUI.appendChild(controlText);\n\n\t //Setup the click event listeners\n\t google.maps.event.addDomListener(controlUI,'click',function(){\n\t\t firstRun=false;\n\t\t legend=[];\n\t\t if(markers!=0){\n\t\t for(var i=0; i<markers.length; i++){\n\t\t\t markers[i].setMap(null);\n\t\t }\n\t\t markers=[];\n\t\t }\n\n\t\t for (var key in icons) {\n\t\t if(key!=='_id'){\n\t\t\t addMarker(icons[key]);\n\t\t\t legend.push(icons[key]);\n\t\t }\n\n\t\t }\n\t\t CreateLegend();\n\t });\n\t }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve a relation proxy out of the cache here. Relation proxies must be cached to allow them to maintain state without being created unnessesarily.
resolveRelationProxy(RelationProxyClass, destinationReference, options) { // TODO: Support parallel relation proxies. // XXX: Bad import. const { Model } = require('./model'); // Unpack the foreign key from the provided options set. const {fk: foreignKeyAttribute, ...remainingOptions} = options; // Resolve a unique cache key for this relationship. const cacheKey = [ RelationProxyClass.name, destinationReference.prototype instanceof Model ? destinationReference._schema.collection : destinationReference, foreignKeyAttribute || '<inherent>' ].join('_'); // Check the on-model cache and populate if nessesary. const cache = this.model._relationalSet.proxyCache; if (!cache[cacheKey]) cache[cacheKey] = RelationProxyClass.fromModel( this.model, destinationReference, foreignKeyAttribute, remainingOptions ); // Return the relation proxy. return cache[cacheKey]; }
[ "createLazyRelationsWrapper() {\n return new LazyRelationsWrapper(this);\n }", "cacheRelatedRecord(record, id, name, uncacheId = null) {\n const me = this,\n cache = me.relationCache[name] || (me.relationCache[name] = {});\n\n if (uncacheId !== null) {\n me.uncacheRelatedRecord(record, name, uncacheId);\n }\n\n if (id != null) {\n // Only include of not already in relation cache, which might happen when removing and re-adding the same instance\n ArrayHelper.include(cache[id] || (cache[id] = []), record);\n }\n }", "cacheRelatedRecord(record, id, name, uncacheId = null) {\n const me = this,\n cache = me.relationCache[name] || (me.relationCache[name] = {});\n\n if (uncacheId !== null) {\n me.uncacheRelatedRecord(record, name, uncacheId);\n }\n\n if (id) {\n // Only include of not already in relation cache, which might happen when removing and re-adding the same instance\n ArrayHelper.include(cache[id] || (cache[id] = []), record);\n }\n }", "function resolve(item) {\n return lodash.find(relations, function(relation) {\n return item.keyAttributes.type === 'relation'\n && item.keyAttributes.ref === relation['@id'];\n });\n }", "makeRelatable(result, model) {\n return new Proxy(result, {\n get(target, name) {\n if(name in target) return target[name]\n if(getTableName(name) in target) return target[getTableName(name)]\n\n let instance = new model(result)\n if(name in instance) return instance[name]().result()\n }\n })\n }", "_eagerLoadHelper(response, relationName, handled, options) {\n const relatedModels = this.pushModels(relationName, handled, response);\n const relatedData = handled.relatedData;\n\n // If there is a response, fetch additional nested eager relations, if any.\n if (response.length > 0 && options.withRelated) {\n const relatedModel = relatedData.createModel();\n\n // If this is a `morphTo` relation, we need to do additional processing\n // to ensure we don't try to load any relations that don't look to exist.\n if (relatedData.type === 'morphTo') {\n const withRelated = this._filterRelated(relatedModel, options);\n if (withRelated.length === 0) return;\n options = _.extend({}, options, {withRelated: withRelated});\n }\n return new EagerRelation(relatedModels, response, relatedModel).fetch(options).return(response);\n }\n }", "_initializeRelationshipPayloads(relInfo) {\n var lhsKey = relInfo.lhs_key;\n var rhsKey = relInfo.rhs_key;\n var existingPayloads = this._cache[lhsKey];\n\n if (relInfo.hasInverse === true && relInfo.rhs_isPolymorphic === true) {\n existingPayloads = this._cache[rhsKey];\n\n if (existingPayloads !== undefined) {\n this._cache[lhsKey] = existingPayloads;\n return existingPayloads;\n }\n }\n\n // populate the cache for both sides of the relationship, as they both use\n // the same `RelationshipPayloads`.\n //\n // This works out better than creating a single common key, because to\n // compute that key we would need to do work to look up the inverse\n //\n var cache = this._cache[lhsKey] = new RelationshipPayloads(relInfo);\n\n if (relInfo.hasInverse === true) {\n this._cache[rhsKey] = cache;\n }\n\n return cache;\n }", "function cached_relationship_object(element, creation_callback) {\n\t\tvar el = $(element);\n\n\t\tif ( ! el.data('relationship-object')) {\n\t\t\tel.data('relationship-object', creation_callback(el));\n\t\t}\n\n\t\treturn el.data('relationship-object');\n\t}", "getData(options, isForcedReload = false) {\n //TODO(Igor) flushCanonical here once our syncing is not stupid\n var record = this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null;\n\n if (this.shouldMakeRequest()) {\n var promise = void 0;\n\n if (this.link) {\n promise = this._fetchLink(options);\n } else {\n promise = this._fetchRecord(options);\n }\n\n promise = promise.then(() => handleCompletedFind(this), e => handleCompletedFind(this, e));\n\n promise = promise.then(internalModel => {\n return internalModel ? internalModel.getRecord() : null;\n });\n\n this.fetchPromise = promise;\n this._updateLoadingPromise(promise);\n }\n\n if (this.isAsync) {\n if (this._promiseProxy === null) {\n var _promise = proxyRecord(this.inverseInternalModel);\n this._updateLoadingPromise(_promise, record);\n }\n\n return this._promiseProxy;\n } else {\n (true && !(record === null || !record.get('isEmpty') || isForcedReload) && Ember.assert(\"You looked up the '\" + this.key + \"' relationship on a '\" + this.internalModel.modelName + \"' with id \" + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)', record === null || !record.get('isEmpty') || isForcedReload));\n\n return record;\n }\n }", "eagerFetch(relationName, handled, options) {\n const relatedData = handled.relatedData;\n\n // skip eager loading for rows where the foreign key isn't set\n if (relatedData.parentFk === null) return;\n\n if (relatedData.type === 'morphTo') {\n return this.morphToFetch(relationName, relatedData, options);\n }\n\n return handled.sync({ ...options, parentResponse: this.parentResponse })\n .select()\n .tap((response) => this._eagerLoadHelper(\n response, relationName, handled, _.omit(options, 'parentResponse')\n ));\n }", "relation(name) {\n if (this._relationships[name]) {\n return this._relationships[name];\n }\n if (!this._relations[name]) {\n throw new Error(\"Relationship `\" + name + \"` not found.\");\n }\n var config = extend({}, {\n name: name,\n conventions: this._conventions\n }, this._relations[name]);\n\n var relationship = config.relation;\n var relation = this.classes()[config['relation']];\n\n delete config.relation;\n return this._relationships[name] = new relation(config);\n }", "getData(isForcedReload = false) {\n //TODO(Igor) flushCanonical here once our syncing is not stupid\n var record = this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null;\n\n if (this.shouldMakeRequest()) {\n var promise = void 0;\n\n if (this.link) {\n promise = this._fetchLink();\n } else {\n promise = this._fetchRecord();\n }\n\n promise = promise.then(() => handleCompletedFind(this), e => handleCompletedFind(this, e));\n\n promise = promise.then(internalModel => {\n return internalModel ? internalModel.getRecord() : null;\n });\n\n this.fetchPromise = promise;\n this._updateLoadingPromise(promise);\n }\n\n if (this.isAsync) {\n if (this._promiseProxy === null) {\n var _promise = proxyRecord(this.inverseInternalModel);\n this._updateLoadingPromise(_promise, record);\n }\n\n return this._promiseProxy;\n } else {\n (true && !(record === null || !record.get('isEmpty') || isForcedReload) && Ember.assert(\"You looked up the '\" + this.key + \"' relationship on a '\" + this.internalModel.modelName + \"' with id \" + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)', record === null || !record.get('isEmpty') || isForcedReload));\n\n return record;\n }\n }", "function get() {\n\t return proxy;\n\t }", "function get(){return proxy;}", "populate() {\n let cacheModel = this.cacheModel();\n if (!this.value || !this.cacheModel()) {\n return null;\n }\n let {alias, result} = this.value;\n if (!alias) {\n return result;\n }\n\n let aliasPaths = this.shape(result);\n if (!aliasPaths) {\n return cacheModel.fromCache(alias, result);\n } else {\n let populated = clone(result);\n for (let path of aliasPaths) {\n let key = pathValue(result, path);\n setValueByPath(populated, path, cacheModel.fromCache(alias, key));\n }\n return populated;\n }\n }", "_findRemoteSideOn(model, ifUnloaded=false) {\n // Determine the class of the remote side.\n // XXX: Ugly child-class awareness.\n const HostClass = this instanceof OneSideRelationProxy ?\n ManySideRelationProxy : OneSideRelationProxy;\n\n // Resolve the remote side.\n const remoteSide = HostClass.findOnModel(\n model, this.host.constructor, this.sourceAttribute\n );\n // Ensure we found a remote relation proxy in an appropriate load\n // state.\n if (!remoteSide || (!remoteSide.loaded && !ifUnloaded)) return null;\n\n return remoteSide;\n }", "loadRel() {\n return this._followRelService(this.rel, this.method);\n }", "retrieveProxy(proxyName) {\n return this.model.retrieveProxy(proxyName);\n }", "uncacheRelatedRecord(record, name = null, id = null) {\n const me = this;\n\n function remove(relationName, relatedId) {\n const cache = me.relationCache[relationName],\n oldCache = cache && cache[relatedId];\n\n // When unjoining a record from a filtered store the relationCache will also be filtered\n // and might give us nothing, in which case we have nothing to clean up and bail out\n if (oldCache) {\n const uncacheIndex = oldCache.indexOf(record);\n uncacheIndex >= 0 && oldCache.splice(uncacheIndex, 1);\n\n if (oldCache.length === 0) {\n delete cache[relatedId];\n }\n }\n }\n\n if (id !== null) {\n remove(name, id);\n } else {\n if (record.meta.relationCache) {\n Object.entries(record.meta.relationCache).forEach(([relationName, relatedRecord]) => {\n const relatedId = relatedRecord && relatedRecord.id;\n\n remove(relationName, relatedId);\n });\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show or hide all blocks with a class name
function setBlockVisibility(class_name, show) { var blocks = document.getElementsByClassName(class_name); for(var i = 0; i < blocks.length; i++) { if(show) { blocks[i].style.display = ''; } else { blocks[i].style.display = 'none'; window.clearAllErrors(blocks[i]); } } }
[ "function setBlockVisibility(class_name, show) {\n var blocks = document.getElementsByClassName(class_name);\n for (var i = 0; i < blocks.length; i++) {\n if (show) {\n blocks[i].style.display = \"\";\n } else {\n blocks[i].style.display = \"none\";\n window.clearAllErrors(blocks[i]);\n }\n }\n }", "function display_block_class(class_to_display)\n\t\t\t\t\t{\t\t\t\n\t\t\t\t\t\t$('.'+class_to_display).css('display', 'block');\n\t\t\t\t\t\t\n\t\t\t\t\t}", "function hideByClass(class_name)\n{\n\tvar elements = $class(class_name);\n\tvar n = elements.length;\n\tfor(var i = 0 ; i < n; i++)\n\t{\n\t\tvar el = elements[i];\n\t\tel.style.display = \"none\";\n\t}\t\n}", "function show_class_elements(class_name){\n var array = document.getElementsByClassName(class_name)\n for (var i = array.length - 1; i >= 0; i--) {\n array[i].style.display = \"block\"\n }\n }", "function hideByClass(class_name) {\n elements = document.getElementsByClassName(class_name);\n for(var i = 0; i < elements.length; i++) {\n hide(elements[i]);\n }\n}", "function toggle_visibility(classname) { $(\".\"+classname).toggle(); }", "function block(blockList) {\n if (blockList == null) {\n $(\".noSpoilersHidden\").removeClass(\"noSpoilersHidden\").show();\n } else {\n for (i = 0; i < blockList.length; ++i) {\n $(\":contains(\"+blockList[i]+\"):not(:has(div))\").removeClass(\"noSpoilersHidden\").addClass(\"noSpoilersTemp\");\n }\n $(\".noSpoilersHidden\").removeClass(\"noSpoilersHidden\").show();\n $(\".noSpoilersTemp\").removeClass(\"noSpoilersTemp\").addClass(\"noSpoilersHidden\").hide();\n }\n}", "function hide_class_elements(class_name) {\n var array = document.getElementsByClassName(class_name)\n for (var i = array.length - 1; i >= 0; i--) {\n array[i].style.display = \"none\"\n };\n }", "function hideByClassName(className) {\n var elements = document.getElementsByClassName(\"hide-me\");\n for (var i = 0; i < elements.length; i++) {\n elements[i].style.display = \"none\";\n }\n}", "function hideByClasses(classMain, hideClass)\r\n{\r\n $(\".\" + classMain).each(function(){\r\n var element = $(this);\r\n if(element.hasClass(hideClass)){\r\n element.css(\"display\", \"none\");\r\n }\r\n \r\n });\r\n}", "function displayByClassName(cName, mode){\n\tvar elem, i;\n\telem=document.getElementsByClassName(cName);\n\tfor (i=0; i<elem.length; i++) {\n\t\tif ( mode ) {\n\t\t\telem[i].style.display = \"block\";\n\t\t}\n\t\telse {\n\t\t\telem[i].style.display=\"none\";\n\t\t}\n\t}\n}", "function showClassElements(className) {\n var elements = document.getElementsByClassName(className);\n for (i = 0; i < elements.length; i++) \n elements[i].style.display = 'inline-block'\n}", "function DisplayContent(DisplayClass) {\n let x = document.getElementsByClassName(DisplayClass);\n for(let i = 0; i<x.length; i++) {\n x[i].classList.remove('hidden');\n x[i].classList.add('non-hidden');\n }\n}", "function hideByClassName (className) {\n\n}", "static show (...els) {\n for (const el of els) el.classList.remove('d-hide')\n }", "function showRabbit(){\n let theClass = rabbit.classList.contains('hide');\n if(theClass){\n rabbit.classList.remove('hide')\n rabbit.classList.add('show');\n }\n else{\n rabbit.classList.remove('show')\n rabbit.classList.add('hide');\n }\n}", "function toggleClassElements(classname) {\n var x = document.getElementsByClassName(classname);\n for (var i = 0; i < x.length; i++) {\n if (x[i].style.display === 'none') {\n x[i].style.display = 'block';\n } else {\n x[i].style.display = 'none';\n }\n }\n}", "function showBlocks() {\n\n\n headBlocksGame.classList.add('no-click');\n\n // creat forEach for add class in all bloks\n blocks.forEach(block => {\n \n // add class active.\n block.classList.add('active');\n });\n \n // waiteng timeng.\n setTimeout(() =>{\n \n // remove stop clickeng after 1s.\n headBlocksGame.classList.remove('no-click');\n\n // creat forEach for remove class in all bloks\n blocks.forEach(block => {\n \n // remove class active.\n block.classList.remove('active');\n });\n\n },2000)\n}", "function hideClassElements(classname) {\n var x = document.getElementsByClassName(classname);\n for (var i = 0; i < x.length; i++) {\n x[i].style.display = 'none';\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates the "Link" element on the page, appending the lat and lng
function updateLink() { if(document.getElementById("link_span").childElementCount > 0) { var url = parseURL(document.getElementById("link_span").firstChild.href); url.params["lat"] = unsafeWindow._c09.getCenter().lat(); url.params["lng"] = unsafeWindow._c09.getCenter().lng(); url.params["zoom"] = unsafeWindow._c09.getZoom(); var newUrl = url.protocol+"://"+url.host+"/?"; for(key in url.params) { newUrl += key+"="+url.params[key]+"&"; } console.log(newUrl); document.getElementById("link_span").firstChild.href = newUrl; } }
[ "function updateLinkHereText() {\n \n let loc = window.location;\n let center = map.getCenter();\n let link = \tloc.protocol + \"//\" + loc.hostname + loc.pathname + \"?r=\" +\n\tshowrouteParams.roots[0];\n if (showrouteParams.connected) {\n\tlink += \"&cr\";\n }\n link += \"&lat=\" + center.lat + \"&lon=\" + center.lng +\n\t\"&zoom=\" + map.getZoom();\n\n document.getElementById(\"linkheretext\").innerHTML = link;\n}", "function fillEventLocation(location) {\r\n //google maps search with this link\r\n //https://www.google.com/maps/search/app+state/\r\n var locationContent = \"\";\r\n locationContent += '<a href=\"https://www.google.com/maps/search/' + location +' \" target=\"_blank\">' + location + '</a>';\r\n $('#locationLink').append(locationContent);\r\n}", "function makeMapLink(latitude, longitude) {\n $('#map').html('');\n $('#map').append(`<p><a id=\"google-maps-link\" href=\"http://maps.google.com/maps?z=12&t=m&q=${latitude},${longitude}\" target=\"_blank\">Google Maps</a></p>`);\n}", "function makeLink() {\n // var a=\"http://www.geocodezip.com/v3_MW_example_linktothis.html\"\n var url = window.location.pathname;\n var a = url.substring(url.lastIndexOf(\n '/') + 1) + \"?lat=\" +\n map.getCenter()\n .lat()\n .toFixed(6) + \"&lng=\" +\n map.getCenter()\n .lng()\n .toFixed(6) +\n \"&zoom=\" + map.getZoom() +\n \"&type=\" +\n MapTypeId2UrlValue(map.getMapTypeId());\n if (filename !=\n \"TrashDays40.xml\") a +=\n \"&filename=\" + filename;\n document.getElementById(\n \"link\")\n .innerHTML =\n '<a href=\"' + a +\n '\">Link to this page<\\/a>';\n }", "function updatePrint() {\n\tvar latLng = map.getCenter();\n\tvar lat = latLng.lat();\n\tvar lng = latLng.lng();\n\tvar params = getHashParams();\n\tvar location = \"\";\n\tvar loc = \"\";\n\tfor(var x = 0; x < params.length; x++) {\n\t\tif (params[x] == \"loc\") { loc = params[++x]; break; } \n\t}\n\t$(\"#printA\").attr(\"href\", \"print.php?lat=\"+lat+\"&lng=\"+lng+\"&loc=\"+loc);\n}", "function initLink() {\n\t$(\"#linkA\").click(function() {\t\t\n\t\tvar latLng = map.getCenter();\n\t\tvar lat = latLng.lat();\n\t\tvar lng = latLng.lng();\n\t\tvar params = getHashParams();\n\t\tvar location = \"\";\n\t\tvar loc = \"\";\n\t\tfor(var x = 0; x < params.length; x++) {\n\t\t\tif (params[x] == \"loc\") {\n\t\t\t\tloc = params[++x];\n\t\t\t\tbreak;\n\t\t\t} \n\t\t}\n\t\tprompt(\"Copy and Paste\", \"http://\" + window.location.hostname + window.location.pathname + \"#lat/\" + lat + \"/lng/\" + lng + \"/loc/\" + loc );\n\t});\n}", "function fillGalleryData(data){\n \n const galleryName = document.getElementById('galleryName'); //grabs the gallery name element\n const nativeName = document.getElementById('nativeName'); //grabs the native name element\n const cityName = document.getElementById('cityName'); //grabs the city name element\n const address = document.getElementById('address'); //grabs the address element\n const country = document.getElementById('country'); //grabs the country element\n const link = document.getElementById('website'); //grabs the link element\n \n \n const lati = data.Latitude; //variable to hold latitude of the location of the gallery\n const longi = data.Longitude; //variable to hold longitude of the location of the gallery\n map.setCenter(new google.maps.LatLng(lati, longi)); //sets the location of the map using the location \n\n galleryName.textContent = data.GalleryName; //changes text content to the gallery name\n nativeName.textContent = data.GalleryNativeName; //changes text content to the native name \n cityName.textContent = data.GalleryCity; //changes text content to the city name\n address.textContent = data.GalleryAddress; //changes text content to the address\n country.textContent = data.GalleryCountry; //changes text content to the country \n link.setAttribute('href', data.GalleryWebSite); //sets the link to the galleries website \n link.textContent = data.GalleryWebSite; //changes text content to the galleries website \n \n\n\n\n }", "function transformPageRallyPoint_addCoordsForOwnVillageReinfsAway() {\r\n\tvar ownReinfsLinks = xpathEvaluate('//div[@id=\"lmid2\"]/table/tbody/tr[1]/td[@class=\"b\"]/a');\r\n\tfor(var i=0; i<ownReinfsLinks.snapshotLength; i++) {\r\n\t\tvar currentLink = ownReinfsLinks.snapshotItem(i);\r\n\t\tvar coordZ = getParamFromUrl(currentLink.href, \"d\");\r\n\t\tvar readableCoords = coordZToXYReadableString(coordZ);\r\n\t\tcurrentLink.firstChild.innerHTML += \" \" + \"<span class='QPcoords2'>\" + readableCoords + \"</span>\";\r\n\t}\r\n}", "function buildLink(url, urlType, maxZoom, params) {\n\nvar goog_namespace = require('./google.js');\nvar xyz = goog_namespace.parseXYZFromUrl(window.location.href);\n\n // Coordinates\n var x = xyz[0]; // lon\n var y = xyz[1]; // lat\n var z = xyz[2]; // zoom\n\n // var xmin = this.map.getBounds().getWest();\n // var ymin = this.map.getBounds().getSouth();\n // var xmax = this.map.getBounds().getEast();\n // var ymax = this.map.getBounds().getNorth();\n var xmin = '';\n var ymin = '';\n var xmax = '';\n var ymax = '';\n\n//window.screen.availWidth\n//window.screen.availHeight\n\n // Current zoom or max zoom\n z = (typeof maxZoom != 'undefined' && z > maxZoom) ? maxZoom : zoom = z;\n\n switch (urlType) {\n case 'default':\n url += '?lat=' + y + '&lon=' + x + '&zoom=' + z + '&' + params;\n break;\n case 'default_z':\n url += '?lat=' + y + '&lon=' + x + '&z=' + z + '&' + params;\n break;\n case 'gc':\n url += '?lat=' + y + '&lng=' + x + '&z=' + z;\n break;\n case 'gc_zoom':\n url += '#lat=' + y + '&lng=' + x + '&zoom=' + z;\n break;\n case 'open_signal':\n url += '?lat=' + y + '&lng=' + x + '&initZoom=' + z;\n break;\n case 'hash':\n url += '#map=' + z + '/' + y + '/' + x;\n break;\n case 'hash2':\n url += y + ',' + x + '/' + z;\n break;\n case 'input_user':\n var user = prompt('What is your OSM user name ?');\n url += '?lat=' + y + '&lon=' + x + '&zoom=' + z + '&u=' + user;\n break;\n case 'bbox':\n url += '?bbox=' + ymin + ',' + xmin + ',' + ymax + ',' + xmax;\n break;\n case 'josm':\n url += '?left=' + xmin + '&right=' + xmax + '&top=' + ymax + '&bottom=' + ymin;\n break;\n case 'c2c':\n var centerPoint = merc.forward([x, y]);\n url += '?map_y=' + centerPoint[1] + '&map_x=' + centerPoint[0] + '&map_zoom=' + z;\n break;\n case 'wikimapia':\n url += '#lat=' + y + '&lon=' + x + '&z=' + z + params;\n break;\n case 'googlemaps':\n url += '@' + y + ',' + x + ',' + z + 'z';\n break;\n case 'flickr':\n url += '?fLat=' + y + '&fLon=' + x + '&zl=' + z;\n break;\n case 'panoramio':\n z = 17 - z;\n url += '#lt=' + y + '&ln=' + x + '&z=' + z;\n break;\n case 'wikiloc':\n url += '#lt=' + y + '&ln=' + x + '&z=' + z;\n break;\n default: // Same as default type\n url += '?lat=' + y + '&lon=' + x + '&zoom=' + z;\n }\n window.open(url, '_blank');\n}", "function update()\n{\n var xhr,\n url;\n \n // clear any existing markers\n map.clearOverlays();\n\n // get map's bounds\n var bounds = map.getBounds();\n \n // query for the five cities in the view\n // instantiate XMLHttpRequest object\n try {\n xhr = new XMLHttpRequest();\n } catch (e) {\n xhr = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n // handle old browsers\n if (xhr === null) {\n alert(\"Ajax not supported by your browser!\");\n return;\n }\n \n url = \"proxy.php?sw=\" +\n bounds.getSouthWest().lat() + \",\" + bounds.getSouthWest().lng() +\n \"&ne=\" +\n bounds.getNorthEast().lat() + \",\" + bounds.getNorthEast().lng();\n\n xhr.onreadystatechange = function() {\n var infos,\n xhtml,\n i,\n articles,\n j;\n \n if (xhr.readyState === 4) {\n document.getElementById(\"progress\").style.display = \"none\";\n if (xhr.status === 200) {\n infos = eval(\"(\" + xhr.responseText + \")\");\n for (i = 0; i < infos.length; i++) {\n articles = \"\";\n for (j = 0; j < infos[i].articles.length; j++) {\n articles += (\"<li>\" + \n \"<a href='\" + infos[i].articles[j].link + \"'>\" +\n infos[i].articles[j].title +\n \"</a>\" +\n \"</li>\");\n }\n addMarker(\n new GLatLng(infos[i].Latitude, infos[i].Longitude),\n \"<b>\" + infos[i].City + \", \" + infos[i].State + \"</b>\" +\n \"<br />\" +\n \"<ul>\" +\n articles +\n \"</ul>\"\n );\n }\n } else {\n alert(\"Error with Ajax call!\");\n }\n }\n };\n xhr.open(\"GET\", url, true);\n xhr.send(null);\n document.getElementById(\"progress\").style.display = \"block\";\n\n // mark home if within bounds\n if (bounds.containsLatLng(home))\n {\n // prepare XHTML\n var xhtml = \"<b>Home Sweet Home</b>\";\n\n // add marker to map\n addMarker(home, xhtml);\n }\n\n // TODO: contact proxy, add markers\n}", "function printLatLong(lat, long) {\n document.getElementById(\"lat\").innerHTML += lat + \"<br/>\";\n document.getElementById(\"long\").innerHTML += long + \"<br/>\";\n}", "function debugUpdateCenter() {\r\n\tdocument.getElementById(\"debug_lat\").innerHTML = lat;\r\n\tdocument.getElementById(\"debug_lng\").innerHTML = lng;\r\n}", "function linkToNearesList(){\n if (homeCoordinatesSet()) {\n document.location.href = http+\"://www.geocaching.com/seek/nearest.aspx?lat=\"+(getValue(\"home_lat\")/10000000)+\"&lng=\"+(getValue(\"home_lng\")/10000000)+\"&dist=25&disable_redirect\";\n }\n }", "function linkToNearesListWo(){\n if (homeCoordinatesSet()) {\n document.location.href = http+\"://www.geocaching.com/seek/nearest.aspx?lat=\"+(getValue(\"home_lat\")/10000000)+\"&lng=\"+(getValue(\"home_lng\")/10000000)+\"&dist=25&f=1&disable_redirect\";\n }\n }", "function addGoToMapLink() {\n var a = document.createElement(\"a\");\n a.innerHTML = \"На карту\";\n a.target = \"_blank\";\n var tbl = document.getElementsByTagName(\"div\")[0].getElementsByTagName(\"center\")[0].getElementsByTagName(\"table\")[\n document.getElementsByTagName(\"div\")[0].getElementsByTagName(\"center\")[0].getElementsByTagName(\"table\").length - 2];\n var xyReg = /x:(\\d+) y:(\\d+)/; //cell coords example: x:424 y:270\n var xy = tbl.rows[tbl.rows.length / 2 - 0.5].cells[tbl.rows[0].cells.length / 2 - 0.5].getElementsByTagName(\"img\")[0].getAttribute(\"tooltip\").match(xyReg);\n a.href = \"http://dragonmap.ru/mortal?x=\" + xy[1] + \"&y=\" + xy[2];\n document.getElementsByTagName(\"div\")[0].getElementsByTagName(\"center\")[0].getElementsByTagName(\"table\")[0]\n .rows[0].cells[1].appendChild(document.createTextNode(\" / \"));\n document.getElementsByTagName(\"div\")[0].getElementsByTagName(\"center\")[0].getElementsByTagName(\"table\")[0]\n .rows[0].cells[1].appendChild(a);\n }", "function generateGoogleLink() {\n\n /* https://www.google.com/maps/dir/Gulistan-e-Johar,+Karachi/Gulshan-e-Iqbal,+Karachi/ */\n\n var link = \"https://www.google.com/maps/dir/\";\n var city = \",+Karachi/\";\n\n var src = document.getElementById(\"source\")[document.getElementById(\"source\").value];\n var dest = document.getElementById(\"dest\")[document.getElementById(\"dest\").value];\n\n link += src.innerHTML.replace(/ /g, '+') + city;\n link += dest.innerHTML.replace(/ /g, '+') + city;\n\n document.getElementById(\"googleLink\").href = link;\n}", "function updateMeta() {\n var latlng = pin.getPosition(); // returns a latlong object.\n radius = circle.getRadius(),\n formattedRadius = (Math.round(radius*100)/100) + 'm',\n geocoder = new google.maps.Geocoder();\n\n document.getElementById('latlng').innerHTML = latlng.toString();\n document.getElementById('radius').innerHTML = formattedRadius;\n\n // translate the latlong into a real world address.\n geocoder.geocode({ latLng: latlng },\n function(results, status) {\n // if the translation call was successful, update the ui.\n if (status == google.maps.GeocoderStatus.OK) {\n document.getElementById('address').innerHTML = results[0].formatted_address;\n } else {\n document.getElementById('address').innerHTML = '';\n }\n }\n );\n }", "function locateMe() {\n\t// function on success\n\tfunction success(position) {\n const latitude = position.coords.latitude;\n const longitude = position.coords.longitude;\n\n// set values in map and map link\n\tvar newmap = document.getElementById('map');\n\tvar openmapLink = document.getElementById('maplink');\n\tnewmap.style.width = '30%';\n\tnewmap.style.height = '30%';\n\tnewmap.style.float = 'center';\n\topenmapLink.style.display='block';\n\t// create a map\n\tvar googlemap = new google.maps.Map(newmap, {\n\tcenter: {lat: latitude, lng: longitude},\n\tzoom: 8\n\t\t});\n\topenmapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;\n\topenmapLink.textContent = 'View On Open Map';\n }\n\n// when not able to retrieve location\n function error() {\n alert('Unable to retrieve your location');\n }\n// getting location co-ordinates using geolocation\n if(!navigator.geolocation) {\n alert('Geolocation is not supported by your browser')\t;\n } else {\n navigator.geolocation.getCurrentPosition(success, error);\n }\n}", "function get_link_google_map(){\n map_src = \"https://www.google.com/maps/embed/v1/place?q=\"+$(\"#promotion_street_address_1\").val()\n +\" \"\n +$(\"#promotion_city\").val();\n map_src += \"&key=\"+google_map_key+\"\";\n $(\"#promotion_google_map_link\").val(map_src);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: handleTopic description: Handle message received
handleTopic(topic, msg) { this.logger.debug("[" + this.name + "] wheel position sensor handleTopic: topic = " + topic + ", msg = " + msg) if (topic === this.subTopic) { var wheel_position = parseInt(msg) var valid = true if (this.simulator) valid = this.simulator.valid(wheel_position) if (isNaN(wheel_position) || !valid || wheel_position > this.max_position || wheel_position < this.min_position) { this.logger.error("Invalid wheel position received: " + msg) } else { this.position = wheel_position if (this.simulator) this.simulator.value = wheel_position this.logger.info("Setting wheel position: " + wheel_position) } } }
[ "function do_topic_handler(error, subscription, topic, message) {\r\n if (!error) {\r\n try {\r\n let parsed_message_object = JSON.parse(message.toString());\r\n parse_do_topic(topic, parsed_message_object);\r\n } catch (error) {\r\n log.error(topic, error);\r\n }\r\n }\r\n}", "function onMqttMessage(topic, message){\n //console.log(\"Mqtt message with topic: \" + topic);\n //console.log(\"Message: \" + message);\n\n var regInfoMsg = new RegExp('P_Stats/.*/info');\n var regNoteMsg = new RegExp('P_Action/note/.*');\n\n if(regInfoMsg.test(topic)){\n console.log('Info message.');\n try {\n var json = JSON.parse(message);\n patientInfo[json['pid']] = json;\n } catch(e){\n console.log(e);\n }\n } else if (regNoteMsg.test(topic)) {\n console.log('Note message');\n // TODO: process note message\n } else {\n console.log('other message with topic: ' + topic);\n console.log(message);\n }\n}", "_onMessage(topicUint8Array, messageUint8Array) {\n const topic = topicUint8Array.toString();\n let message\n if (messageUint8Array.length > 0) {\n message = JSON.parse(messageUint8Array.toString());\n } else {\n message = undefined;\n }\n \n if (this._watches.has(topic)) {\n const subscription = this._watches.get(topic);\n subscription.lastValue = message;\n for (const callback of subscription.callbacks) {\n callback(topic, message);\n }\n }\n }", "onUserGameInput(topic, message) {\n let input = this.parseJson(message);\n console.log(`[Broker] received message (topic: ${topic})`);\n // console.log(input);\n if (input) {\n if (topic == this.mqtt.adminTopic) {\n this.handleAdminInput(input);\n }\n } else if (topic == this.mqtt.topics.replicated) {\n this.mqtt.log(\"the given input was invalid\");\n }\n }", "function HandleTopicPage()\n{\n\tvar textarea = GetMessageEditingBox();\n\t\n\tif (textarea == null)\n\t{\n\t\t// Il n'y a pas de \"fast answer\" sur cette page\n\t}\n\telse\n\t{\n\t\t// Pages de topic\n\t\t\n\t\tLoadSmileyStats();\n\t\t\n\t\tChangeFastAnswerValidationButtonAction();\n\t\t\n\t\tif (sm_fast_reply)\n\t\t{\n\t\t\tShowFavoriteSmileysPanel(true);\n\t\t}\n\t\t\n\t\tif (sm_fav_world)\n\t\t{\n\t\t\tAddScanSmileysFeature();\n\t\t}\n\t\t\n\t\tModifyValidateFastEdit();\n\t}\n}", "function topic_event( event ) {\n let topic = event.target.getAttribute( \"data-on\"+event.type+\"-topic\" );\n\n if (typeof topic === \"string\") {\n let cancel = event.target.getAttribute( \"data-on\"+event.type+\"-cancel\" );\n\n if (cancel === null) {\n cancel = true;\n } else {\n switch (cancel) {\n case \"0\":\n case \"no\":\n case \"false\":\n cancel = false;\n break;\n case \"preventDefault\":\n cancel = 'preventDefault';\n break;\n default:\n cancel = true;\n break;\n }\n }\n\n if (event.target.hasAttribute( \"data-on\"+event.type+\"-message\" )) {\n let msg = event.target.getAttribute( \"data-on\"+event.type+\"-message\" );\n if (typeof msg === \"string\") {\n msg = JSON.parse(msg);\n }\n } else {\n let attrs = event.target.attributes;\n msg = {};\n for (let i = attrs.length - 1; i >= 0; i--) {\n msg[attrs[i].name] = attrs[i].value;\n }\n }\n let options = {\n cancel: cancel\n }\n if (event.target.hasAttribute( \"data-on\"+event.type+\"-response-topic\" )) {\n options.response_topic = event.target.getAttribute( \"data-on\"+event.type+\"-response-topic\" )\n }\n cotonic.ui.on(topic, msg, event, options);\n\n if(event.type === \"submit\" && event.target.getAttribute(\"data-onsubmit-reset\") !== null) {\n event.target.reset();\n }\n }\n }", "processTopicMessage (topic, message) {\n\t\tconsole.debug('Processing topic ' + topic + ' message', message)\n\n\t\tif (this.topicProcessors[topic]) {\n\t\t\tthis.topicProcessors[topic](message, topic)\n\t\t\treturn\n\t\t}\n\n\t\tconsole.warn('No processor registered for topic ' + topic + ', dropping message')\n\t}", "processMqttMessage(topic, message) {\n const path = topic.split('/');\n if (path.pop() === 'cmd') {\n const keyValuePairs = message.split('|') || [''];\n const command = getUltralightCommand(keyValuePairs[0]);\n const deviceId = path.pop();\n const result = keyValuePairs[0] + '| ' + command;\n\n if (!IoTDevices.notFound(deviceId)) {\n IoTDevices.actuateDevice(deviceId, command);\n const topic = '/' + DEVICE_API_KEY + '/' + deviceId + '/cmdexe';\n MQTT_CLIENT.publish(topic, result + OK);\n }\n }\n }", "handleSubmitTopic (topic) {\n this.handleStateChange('formActive', false)\n this.handleStateChange('topicName', '')\n this.props.addTopic(topic)\n }", "function echo_topic(topic) {\n listener.unsubscribe(); // unsubscribe from old topic\n var text = document.getElementById('echo'); // html block to echo to\n text.innerHTML = topic + ':'; // initialize text to <topic name>:\n clearTimeout(echo_timeout); // clear timer to grey out text\n text.style.color = \"#fda\"; // set text to black\n listener.name = topic;\n listener.subscribe(function(message) {\n // callback function\n text.innerHTML = (topic + ':\\n' + JSON.stringify(message, null, 4));\n clearTimeout(echo_timeout);\n text.style.color = \"#fda\"\n echo_timeout = setTimeout(echo_old, 2000);\n });\n }", "function onMessageAuthBroker(topic, message) {\r\n console.info(\"Received message\");\r\n message = message.toString();\r\n console.debug(message);\r\n try {\r\n const { app_id, data } = JSON.parse(message);\r\n\r\n // TODO: select different transformers based on the \"topic\" variable\r\n // ** Additional topics need to be subscribed to in onConnectAuthBroker()\r\n const blobs = IR_Convert(app_id, data);\r\n\r\n // Write the finished data transformation to the nifi broker\r\n console.info(\"Writing to nifi output stream\");\r\n nifiBroker.publish(config.NIFI_BROKER_TOPIC, JSON.stringify(blobs));\r\n } catch(err) {\r\n console.error(\"ERROR IN INGEST TRANSFORMATION\");\r\n console.error(err);\r\n }\r\n}", "function topicChanged( topic, room, user ) {\n}", "processCommand(message, topic) {\n if (topic == this.commandTopic_light) {\n this.setSwitchState(message)\n } else if (topic == this.commandTopic_brightness) {\n this.setSwitchLevel(message)\n } else {\n debug('Received unknown command topic '+topic+' for switch: '+this.deviceId)\n }\n }", "function publishMessage(topic, payload, eventCallback){\r\n\r\n\tvar params = {\r\n\t\ttopic: topic, /* required */\r\n\t\t//payload: new Buffer('...') || payload,\r\n\t\tpayload: payload,\r\n\t\tqos: 1\r\n\t};\r\n\t\tiotdata.publish(params, function(err, data) {\r\n\t\tif (err) console.log(err, err.stack); // an error occurred\r\n\t\telse console.log(data); \r\n\t\t\r\n\t\teventCallback(data); \r\n\t});\r\n\r\n\r\n}", "function onMessage(data) {\n let message\n try {\n message = JSON.parse(data.content.toString())\n } catch(e) {\n console.error('[AMQP] - Error parsing message... ', data)\n }\n\n console.log('[AMQP] - Message incoming... ', message)\n channelWrapper.ack(data)\n if (!message) {\n return\n }\n // Actions here\n switch (message.taskName) {\n case 'getNotes': \n main();\n break\n\n // case 'other': \n // // do another thing....\n // break\n\n default:\n console.error('No task was found with name => '+message.taskName)\n }\n}", "addTopic(topic) {\n if(topic in this.listeners) return;\n var listener = new ROSLIB.Topic({\n ros : ros,\n name : topic,\n messageType : 'rosgraph_msgs/Log'\n });\n this.listeners[topic] = listener;\n var that = this;\n listener.subscribe(function(message) {\n var realLevel = parseInt(Math.log2(message.level))\n var visibility = that.query === '' || (message.name + ' ' + message.msg).indexOf(that.query) !== -1;\n $('<div></div>').text(message.msg).prepend('<b>' + message.name + '</b> ').css({\n 'background': that.BGCOLORS[realLevel],\n 'color': that.FGCOLORS[realLevel],\n 'padding': '5pt',\n 'margin-top': '3pt',\n 'margin-bottom': '3pt',\n 'margin-left': '15pt',\n 'margin-right': '15pt',\n 'font-size': '10pt',\n 'display': (visibility ? '':'none'),\n 'font-family': 'Titillium Web,sans-serif',\n }).appendTo(that.logBoxNode);\n while(that.logBoxNode.children().length > 512) {\n that.logBoxNode.children().first().hide().remove();\n }\n that.logBoxNode[0].scrollTop = that.logBoxNode[0].scrollHeight;\n });\n }", "function handleIncomingAlarm(topic, doc) {\n var text, msg;\n try { \n text = JSON.parse(doc);\n msg = 'Severity ' + text.Severity + ' alarm - ' + text.AlarmDescription;\n activeChannels.forEach(function(id) {\n bot.say({text: msg, channel: id});\n });\n }\n catch(e) { console.log('Parsing error: ', e); }\n}", "function handleSensorMessage(topic, message) {\n\tvar MSGObj = JSON.parse(message);\n\tvar topArr = topic.split(\"/\");\n\tvar sensor = new Sensor(topArr[2], topArr[3], true, topArr[5]);\n\tif (MSGObj.content === \"activation\") {\n\t\tif (!isSensorActivated(sensor)) {\n\t\t\tsensorList.push(sensor);\n\t\t}\n\t} else if (MSGObj.content === \"alert\") {\n\t\tif (isSensorActivated(sensor)) {\n\t\t\tvar jsObj = { // A single sensor has been triggered\n\t\t\t\ttype: 201,\n\t\t\t\ttimestamp: new Date(),\n\t\t\t\tcontent: `${sensor.room}/${sensor.position}/${sensor.type}`,\n\t\t\t};\n\t\t\tconsole.log(jsObj);\n\t\t\tclient.publish(\"p2/alarmy/\", JSON.stringify(jsObj));\n\n\t\t\t// Global alarm is triggered\n\t\t\tif(alarmStatus === true && alarmTriggered === false){\n\t\t\t\tvar jsObj = {\n\t\t\t\t\ttype: 200,\n\t\t\t\t\ttimestamp: new Date(),\n\t\t\t\t\tcontent: `${sensor.room}/${sensor.position}/${sensor.type}`,\n\t\t\t\t};\n\t\t\t\twebsocketConnection.send(JSON.stringify(jsObj));\n\t\t\t\talarmTriggered = true;\n\t\t\t\talarmHistory.push(jsObj);\n\t\t\t\tfs.writeFileSync(alarmHistoryFile,JSON.stringify(alarmHistory));\n\t\t\t}\n\t\t}\n\t}\n}", "processCommand(message, topic) {\n if (topic == this.commandTopic_fan) {\n this.setFanState(message)\n } else if (topic == this.commandTopic_speed) {\n this.setFanLevel(message)\n } else {\n debug('Somehow received unknown command topic '+topic+' for fan Id: '+this.deviceId)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a collection and the restoreJSON structure, looks up the definitions and invokes define() on them.
function restoreCollection(collection, restoreJSON) { const definitions = getDefinitions(restoreJSON, collection._collectionName); console.log(`Defining ${definitions.length} ${collection._collectionName} documents.`); _.each(definitions, definition => collection.define(definition)); }
[ "function getDefinitions(restoreJSON, collection) { //\n return _.find(restoreJSON.collections, function (obj) { // 16\n return obj.name === collection; // 16\n }).contents; // 16\n} /** // 17\n * Given a collection and the restoreJSON structure, looks up the definitions and invokes define() on them. //\n * @param collection The collection to be restored. //\n * @param restoreJSON The structure containing all of the definitions. //\n */ //", "function restoreCollection(collection, restoreJSON) {\n const definitions = getDefinitions(restoreJSON, collection._collectionName);\n console.log(`Defining ${definitions.length} ${collection._collectionName} documents.`); // eslint-disable-line\n _.each(definitions, definition => collection.define(definition));\n}", "function restoreCollection(collection, restoreJSON) {\n console.log(`the collection name is ${collection._name}`);\n const definitions = getDefinitions(restoreJSON, collection._name);\n console.log(`Defining ${definitions.length} ${collection._name} documents.`);\n _.each(definitions, definition => collection.insert(definition));\n}", "function getDefinitions(restoreJSON, collection) {\n return _.find(restoreJSON.collections, obj => obj.name === collection).contents;\n}", "collectionAndSchema(collection, callback) {\n this.collection(collection, (err, list) => {\n if (err) {\n callback('Collection not found.');\n } else {\n const uiSchema = this.uiSchema();\n const map = this.mapSettings();\n const data = {\n schema: list,\n uiSchema: uiSchema[collection],\n map,\n };\n callback(null, data);\n }\n });\n }", "async function loadExtraDefinitions(schemas, entries){\n \n //Get all the schemas that have a default value for type. Only the generic defenitions schema does not have that.\n\tlet retreivedItems = schemas.find({ \"jsonObject.properties.type.default\": { $exists: true } });\n\tlet genericProperties = schemas.findOne({ \"jsonObject.generalProperties\": { $eq: true } });\n\tlet genericDefinitions = schemas.findOne({ \"jsonObject.generalDefinitions\": { $eq: true } });\n \n let schema, schemaJSONObj, type, IDListOfType;\n for (let i = 0, amountOfSchemas = retreivedItems.length; i < amountOfSchemas; i++) { //Loop over the actual schemas, not generaldefinition\n schema = retreivedItems[i];\n schemaJSONObj = schema.jsonObject;\n type = schemaJSONObj.properties.type.default; //Get the type from the default value of the type property in the schema\n schemaJSONObj.definitions = {...schemaJSONObj.definitions, ...genericDefinitions.jsonObject}; //Load the general properties as definitions\n IDListOfType = await getIDListOfTypeFromCollection(type, entries, true); //Get all the id's of every item of this type\n // Save the list as a definition to the schema, just in case there's a use for it.\n schemaJSONObj.definitions[type] = { \"type\": \"string\", \"description\": \"The id of another entry\", \"enum\": IDListOfType };\n if(schemaJSONObj.properties[\"copy-from\"]){\n schemaJSONObj.properties[\"copy-from\"].enum = IDListOfType; //If there's a copy-from then the id list of this type goes here.\n }\n \n //The schema can include a request to add the list of id's of a certain type.\n if(schemaJSONObj.get_ids_of_type){\n let ids = schemaJSONObj.get_ids_of_type;\n let c, definition, oneOf, one, defType, displayKey;\n \n //Loop over all the requested types that the schema wants id's from. Usually only one\n for (let x = 0, idsLen = ids.length; x < idsLen; x++) {\n defType = ids[x].type;\n displayKey = ids[x].display_key;\n IDListOfType = await getTypeFromCollection(defType, entries, false, displayKey); //Get all the id's of every item of type ids[x]\n if(IDListOfType.length < 1){ \n console.log(\"Tried to get list of ids for type \\\"\" + ids[x] + \"\\\" but got nothing\")\n continue;\n }\n definition = schemaJSONObj.definitions[defType]; //Get the currently defined definition from the schema\n \n if (typeof definition[\"oneOf\"] === 'undefined'){\n if(definition.type == \"array\") {\n c = definition.items.enum; //Save the list that's already defined in the schema.\n definition.items.enum = c.concat(IDListOfType.filter((item) => c.indexOf(item) < 0)); //Merge the two lists and put it back into the enumeration.\n } else { //assume string\n c = definition.enum; //Save the list that's already defined in the schema.\n definition.enum = c.concat(IDListOfType.filter((item) => c.indexOf(item) < 0)); //Merge the two lists and put it back into the enumeration.\n }\n } else {\n oneOf = definition[\"oneOf\"];\n for (let i = 0, oneOfLen = oneOf.length; i < oneOfLen; i++) {\n one = oneOf[i];\n if(one.type == \"array\") {\n c = one.items.enum; //Save the list that's already defined in the schema.\n one.items.enum = c.concat(IDListOfType.filter((item) => c.indexOf(item) < 0)); //Merge the two lists and put it back into the enumeration.\n } else { //assume string\n c = one.enum; //Save the list that's already defined in the schema.\n one.enum = c.concat(IDListOfType.filter((item) => c.indexOf(item) < 0)); //Merge the two lists and put it back into the enumeration.\n }\n }\n }\n schemaJSONObj.definitions[defType] = definition;\n }\n }\n \n //The schema can include a request include properties from generalproperties.json.\n //In contrast to generalDefinitions, these become properties of the schema itself.\n if(schemaJSONObj.include_properties){\n let includes = schemaJSONObj.include_properties;\n let property, propertyOrder, genericProperty;\n \n //Loop over the properties and add them to the schema\n for (let x = 0, gLen = includes.length; x < gLen; x++) {\n property = includes[x].property;\n propertyOrder = includes[x].propertyOrder;\n \n if(property){\n genericProperty = genericProperties.jsonObject[property]; //Get the property from the generic property list\n if(genericProperty){\n schemaJSONObj.properties[property] = genericProperty; //Add it to the schema\n if(propertyOrder){\n schemaJSONObj.properties[property].propertyOrder = propertyOrder; //set the property order if it was noted.\n }\n }\n }\n }\n }\n \n schemaJSONObj = await recursiveSetProperties(schemaJSONObj, entries, schemaJSONObj);\n }\n}", "function resolveCollectionDefinition(doc, oldDoc, collectionDefinition, itemPrefix) {\n if (utils.isValueNullOrUndefined(collectionDefinition)) {\n return [ ];\n } else {\n if (typeof collectionDefinition === 'function') {\n var fnResults = collectionDefinition(doc, oldDoc);\n\n return resolveCollectionItems(fnResults, itemPrefix);\n } else {\n return resolveCollectionItems(collectionDefinition, itemPrefix);\n }\n }\n }", "function loadCollections(collections, target) {\n let items = [];\n target.timing = {};\n _.forEach(collections, function (item, key) {\n let checkModel = _modelsPath + key + '.json';\n // if we have model & file does't exist — we create new file\n !h.isValidPath(checkModel) && h.writeToFile(checkModel);\n // load collections to memory\n items[key] = require(checkModel);\n // save read file time\n target.timing[key] = Date.now();\n });\n target.Models = items;\n return target;\n}", "function loadCollections(callback) {\n var dn = 'collections/';\n\n // load our documents\n function loadViewsAndDocuments(c, callback) {\n\n c\n .loadViews(function(err) {\n if (err) {\n global.logger.log('error',\n 'Database.loadViewsAndDocuments - ', err);\n callback(err);\n return;\n }\n Array.from(c.views.values()).forEach(function(v) {\n self.views.set(v.getId(), v);\n });\n\n global.logger\n .log(\n 'debug',\n 'Database.loadViewsAndDocuments: Loaded views ',\n c.getId());\n\n c\n .loadDocuments(\n Array.from(c.views.values()),\n function(err) {\n if (err) {\n global.logger\n .log(\n 'error',\n 'Database.loadViewsAndDocuments - loadDocuments ',\n err);\n callback(err);\n return;\n }\n global.logger\n .log(\n 'debug',\n 'Database.loadViewsAndDocuments: Documents completed ',\n c.getId());\n callback();\n\n });\n\n });\n }\n\n // we are going to call this function when we are done loading\n // and do some final initialization\n function doneLoading(err) {\n if (err) {\n global.logger.log('error', 'Database.loadCollections', err);\n callback(err);\n return;\n }\n\n // sort by priority. The priority is used when there are lookups\n // happening\n // in the views. If you need a collection in your view, the priority\n // ensures it gets loaded beforehand\n\n //self.collections.sort(function(a, b) {\n // return a._identity._priority ? a._identity._priority - b._identity._priority : 1;\n //});\n self.collections = new Map(Array.from(self.collections.entries()).sort(function(a, b) {\n return a[1]._identity._priority ? a[1]._identity._priority - b[1]._identity._priority : 1;\n }));\n\n // lets initialize the hash while we are here\n //self.collections.forEach(function(c) {\n // self._collectionsHash[c.getId()] = c;\n //});\n\n if (global.logger.level === 'debug') {\n global.logger.log('debug',\n 'Database.loadCollections - now views then docs');\n }\n // now load documents and views\n // do this in sequential order\n async\n .eachSeries(\n Array.from(self.collections.values()),\n loadViewsAndDocuments,\n function(err) {\n if (err) {\n global.logger.log('error',\n 'Database.loadCollections', err);\n callback(err);\n return;\n }\n global.logger\n .log('debug',\n 'Database.loadCollections - now done with docs and views!!');\n callback();\n });\n }\n\n // grab all the collections from the file system\n self.cfs.list(dn, function(err, files) {\n if (err) {\n global.logger.log('error',\n 'Database.loadCollections - listObjects ', err);\n callback(err);\n return;\n }\n global.logger.log('debug', 'Database.loadCollections ' + JSON.stringify(files));\n\n // ok, for each one we are going to load it\n // when we are done with all of them, do\n // \"doneLoading\"\n async.each(files, function(item, callback) {\n global.logger.log('debug',\n 'Database.loadCollections - fetching ' + item);\n self.cfs.get(item, function(err, data) {\n if (err) {\n global.logger.log('error',\n 'Database.loadCollections - getObject ', err);\n callback(err);\n return;\n }\n global.logger.debug('debug',\n 'Database.loadCollections - creating Collection:',\n data);\n var c = new Collection(self, data);\n\n // store\n // it\n // in\n // our\n // hashes\n self.collections.set(c.getId(), c);\n callback();\n\n });\n }, doneLoading);\n\n });\n }", "compileCollections () {\n console.info('DynamicCollectionManager.compileCollections');\n DynamicCollections.find({}).forEach((collection) => {\n try {\n // Compile\n DynamicCollectionManager.compileCollection(collection);\n \n // Run the transformations\n \n } catch (e) {\n console.error('DynamicCollectionManager.compileCollections failed to compile collection:', collection, e);\n }\n })\n }", "#createCollections() {\n Object.entries(this.types).forEach(([, { Model, storeName }]) => {\n this[storeName] = new Collection(storeName, Model, this.idb);\n });\n }", "async allButterCollections(actions) {\n const collection = await this.client.content.retrieve(this.options.collections)\n const { data } = collection.data;\n const contentType = actions.addCollection({\n typeName: this.createTypeName('collection')\n });\n contentType.addNode({\n data\n })\n }", "function resolveRoleCollectionDefinition(doc, oldDoc, rolesDefinition) {\n return resolveCollectionDefinition(doc, oldDoc, rolesDefinition, 'role:');\n }", "function loadCollection(name, options, callback){\n\t\t\n\t\tvar self = this;\n\t\tself.db.collectionNames(self.changeCollectionPrefix+self.collectionName, function (err, names) {\n\t\t\tvar found = false;\n\t\t\t\n\t\t\tfor(var i=0;i<names.length;i++){\n\t\t\t\tif(self.datbaseName+'.'+self.changeCollectionPrefix+self.collectionName){\n\t\t\t\t\tfound = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t\tif(!found){\n\t\t\t\t//create the changes collection\n\t\t\t\t\n\t\t\t\tself.db.createCollection(self.changesCollectionPrefix+self.collectionName, options,function(err, coll){\n\t\t\t\t\tif(err){\n\t\t\t\t\t\tthrow new Error(err);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(callback){\n\t\t\t\t\t\tcallback(false, coll)\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}else{\n\t\t\t\tself.db.collection(name, function(err, coll){\n\t\t\t\t\tif(err){\n\t\t\t\t\t\tthrow new Error(err);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(callback){\n\t\t\t\t\t\tcallback(err, coll);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}", "set(newCollection) {\n this.args.model.relationships[this.args.reflectionName] = newCollection\n }", "function collect(collection_name) {\n eval(collection_name + \" = new Meteor.Collection('\" + collection_name.toLowerCase() + \"');\" );\n}", "function loadFromJsonFile() {\n collections.forEach(function(collection) {\n var mongoClient = new MongoClient(new Server('localhost', 27017));\n var db;\n mongoClient.open(function (err, mongoClient) {\n db = mongoClient.db(dbName);\n db.createCollection(collection, {\n strict: true,\n capped: false,\n size: 5242880,\n autoIndexId: true,\n w: 1\n }, function (err, collectionFromDB) {\n if (err) {\n console.log(err);\n } else {\n var parsedJSON = require('./data/' + collection + '.json');\n for (var i = 0; i < parsedJSON.length; i++) {\n collectionFromDB.insert(parsedJSON[i], {}, function (colerr, result) {\n });\n }\n }\n console.log('Loaded ' + collection + '.json to db ' + dbName);\n db.close();\n mongoClient.close();\n });\n });\n });\n}", "resolveAllOfInDefinitions() {\n let self = this;\n let spec = self.specInJson;\n let definitions = spec.definitions;\n let modelNames = Object.keys(self.specInJson.definitions);\n modelNames.map(function (modelName) {\n let model = definitions[modelName];\n let modelRef = '/definitions/' + modelName;\n return self.resolveAllOfInModel(model, modelRef);\n });\n return Promise.resolve(self);\n }", "_parseCollection()\n {\n var that = this;\n fs.readFile(this.option.path, 'utf8', function (err, data) {\n if (err) throw err;\n that.collection = JSON.parse(data);\n that._serveCollection();\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the two sprites overlap
spriteOverlap(a, b) { let ab = a.getBounds(); let bb = b.getBounds(); return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height; }
[ "function checkOverlap(spriteA, spriteB){\n var boundsA = spriteA.getBounds();\n var boundsB = spriteB.getBounds();\n return Phaser.Rectangle.intersects(boundsA,boundsB);\n}", "function overlap(obj1, obj2) {\n var right1 = obj1.x + obj1.width;\n var right2 = obj2.x + obj2.width;\n var left1 = obj1.x;\n var left2 = obj2.x;\n var top1 = obj1.y;\n var top2 = obj2.y;\n var bottom1 = obj1.y + obj1.height;\n var bottom2 = obj2.y + obj2.height;\n\n if (left1 < right2 && left2 < right1 && top1 < bottom2 && top2 < bottom1) {\n return true;\n }\n return false;\n }", "isColliding(spriteA, spriteB) {\n const boundsA = spriteA.getBounds();\n const boundsB = spriteB.getBounds();\n //sprites are only colliding if their top parts are touching\n boundsA.scale(1, 0.5);\n boundsB.scale(1, 0.5);\n const shadowBoundsA = boundsA.clone();\n const shadowBoundsB = boundsB.clone();\n shadowBoundsA.y = (spriteA.state === __WEBPACK_IMPORTED_MODULE_1__HeroStates__[\"a\" /* default */].JUMP_STATE || spriteA.state === __WEBPACK_IMPORTED_MODULE_1__HeroStates__[\"a\" /* default */].JUMP_ATTACK_STATE)\n ? spriteA.jump.timeline[0].vStart.y : shadowBoundsA.y;\n shadowBoundsB.y = (spriteB.state === __WEBPACK_IMPORTED_MODULE_1__HeroStates__[\"a\" /* default */].JUMP_STATE || spriteB.state === __WEBPACK_IMPORTED_MODULE_1__HeroStates__[\"a\" /* default */].JUMP_ATTACK_STATE)\n ? spriteB.jump.timeline[0].vStart.y : shadowBoundsB.y;\n //check sprite itself and its shadow\n return Phaser.Rectangle.intersects(boundsA, boundsB) && Phaser.Rectangle.intersects(shadowBoundsA, shadowBoundsB);\n }", "isOverlap(obj1, obj2) {\n return ((obj1.location.x + obj1.width) >= obj2.location.x\n && (obj1.location.y + obj1.height) >= obj2.location.y\n && obj1.location.x <= (obj2.location.x + obj2.width)\n && obj1.location.y <= (obj2.location.y + obj2.height));\n }", "function overlap(obj1, obj2) {\n return obj1.pos.x + obj1.size.x > obj2.pos.x &&\n obj1.pos.x < obj2.pos.x + obj2.size.x &&\n obj1.pos.y + obj1.size.y > obj2.pos.y &&\n obj1.pos.y < obj2.pos.y + obj2.size.y;\n}", "function spriteCollision(sprite1, sprite2) {\r\n\t\tif (sprite1.remove == false && sprite2.remove == false) {\r\n\t\t\tif (sprite1.x - sprite1.clip.width * sprite1.anchor.x < sprite2.x + sprite2.clip.width - sprite2.clip.width * sprite2.anchor.x &&\r\n\t\t\t\tsprite1.x + sprite1.clip.width - sprite1.clip.width * sprite1.anchor.x > sprite2.x - sprite2.clip.width * sprite2.anchor.x &&\r\n\t\t\t\tsprite1.y - sprite1.clip.height * sprite1.anchor.y < sprite2.y + sprite2.clip.height - sprite2.clip.height * sprite2.anchor.y &&\r\n\t\t\t\tsprite1.clip.height + sprite1.y - sprite1.clip.height * sprite1.anchor.y > sprite2.y - sprite2.clip.height * sprite2.anchor.y) {\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function spriteCollision(sprite1, sprite2) {\r\n\t\tif (sprite1.remove == false && sprite2.remove == false) {\r\n\t\t\tif (sprite1.x - sprite1.clip.width * sprite1.anchor.x < sprite2.x + sprite2.clip.width - sprite2.clip.width * sprite2.anchor.x &&\r\n\t\t\t\tsprite1.x + sprite1.clip.width - sprite1.clip.width * sprite1.anchor.x > sprite2.x - sprite2.clip.width * sprite2.anchor.x &&\r\n\t\t\t\tsprite1.y - sprite1.clip.height * sprite1.anchor.y < sprite2.y + sprite2.clip.height - sprite2.clip.height * sprite2.anchor.y&&\r\n\t\t\t\tsprite1.clip.height + sprite1.y - sprite1.clip.height * sprite1.anchor.y > sprite2.y - sprite2.clip.height * sprite2.anchor.y ) {\r\n\t\t\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function overlap(actor1, actor2) {\n \n // Evaluates to true if the actors touch each other\n return actor1.pos.x + actor1.size.x > actor2.pos.x &&\n actor1.pos.x < actor2.pos.x + actor2.size.x &&\n actor1.pos.y + actor1.size.y > actor2.pos.y &&\n actor1.pos.y < actor2.pos.y + actor2.size.y;\n}", "isOverlapping(other) {\n const trueCardWidth = (CARD_WIDTH * CardCoordinate.cardScale()) / CardCoordinate.coordSize();\n const trueCardHeight = (CARD_HEIGHT * CardCoordinate.cardScale()) / CardCoordinate.coordSize();\n const overlappingX = other.x > (this.x - trueCardWidth) && other.x < (this.x + trueCardWidth);\n const overlappingY = other.y > (this.y - trueCardHeight) && other.y < (this.y + trueCardHeight);\n\n return overlappingX && overlappingY;\n }", "function overlap(a, b) {\n return a.pox > b.pox - a.w && a.pox < b.pox + b.w && a.poy > b.poy - a.h && a.poy < b.poy + b.h;\n}", "function overlap(object1, object2)\n{\n var hb1 = object1.getHitBox();\n var hb2 = object2.getHitBox();\n \n /* Checks the rectangle sides for overlap */\n if(hb1.x - hb1.width/2 < hb2.x + hb2.width/2 && \n hb1.x + hb1.width/2 > hb2.x - hb2.width/2 &&\n hb1.y - hb1.height/2 < hb2.y + hb2.height/2 && \n hb1.y + hb1.height/2 > hb2.y - hb2.height/2) {\n return true;\n }\n else {\n return false;\n }\n}", "function overlapping(x1, y1, w1, h1, x2, y2, w2, h2) \n{\n if ( y1 + h1 > y2 &&\n y1 < y2 + h2 &&\n x1 + w1 > x2 &&\n x1 < x2 + w2 )\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "var overlap(Actor other) {\n var overlap = super.overlap(other);\n if(overlap==null || active==null || other.active==null) {\n return overlap;\n }\n //\n // TODO: add in code here that determines\n // the varersection povar for the two\n // sprites, and checks the mask to see\n // whether both have non-zero alph there.\n //\n return overlap;\n }", "overlap(x, y) {\n if (x > this.x - this.image.width / 2 &&\n x < this.x + this.image.width / 2 &&\n y > this.y - this.image.height / 2 &&\n y < this.y + this.image.height) {\n\n return true\n\n } else {\n return false;\n }\n }", "function spriteOverlapsPoint(sprite, x, y) {\n var minX = sprite.x;\n var maxX = sprite.x + sprite.image.width;\n var minY = sprite.y;\n var maxY = sprite.y + sprite.image.height;\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) {\n return true;\n }\n return false;\n}", "isCollision(otherSprite) {\n return false;\n }", "function overlap(obj1, obj2) {\n return (obj1.x + obj1.boundingBox.x + obj1.boundingBox.width > obj2.x + obj2.boundingBox.x && obj1.x + obj1.boundingBox.x < obj2.x + obj2.boundingBox.x + obj2.boundingBox.width && obj1.y + obj1.boundingBox.y + obj1.boundingBox.height > obj2.y + obj2.boundingBox.y && obj1.y + obj1.boundingBox.y < obj2.y + obj2.boundingBox.y + obj2.boundingBox.height);\n}", "overlap(x, y) {\n\t\treturn (x >= this.x && x <= this.x + this.width &&\n\t\t\t\ty >= this.y + this.y_offset && y <= this.y + this.y_offset + this.height)\n\t}", "function check(sprite1, sprite2) {\n if(sprite1.x < sprite2.x + sprite2.width &&\n sprite1.x + sprite1.width > sprite2.x &&\n sprite1.y < sprite2.y + sprite2.height &&\n sprite1.height + sprite1.y > sprite2.y){\n if(sprite2.texture == block_to_press_down){\n //stage.removeChild(sprite2);\n gameLose();\n }\n else if(sprite2.texture == block_to_press_up){\n sprite2.texture = block_to_press_down;\n }\n return true;\n }\n else return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_readForwardPath` reads a '!' path
_readForwardPath(token) { var subject, predicate, object = this._blank(); // The next token is the predicate if ((predicate = this._readEntity(token)) === undefined) return; // If we were reading a subject, replace the subject by the path's object if (this._predicate === null) subject = this._subject, this._subject = object; // If we were reading an object, replace the subject by the path's object else subject = this._object, this._object = object; // Emit the path's current quad and read its next section this._emit(subject, predicate, object, this._graph); return this._readPath; }
[ "_readForwardPath(token) {\n let subject, predicate;\n const object = this._blankNode();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readForwardPath(token) {\n let subject, predicate;\n\n const object = this._blankNode(); // The next token is the predicate\n\n\n if ((predicate = this._readEntity(token)) === undefined) return; // If we were reading a subject, replace the subject by the path's object\n\n if (this._predicate === null) subject = this._subject, this._subject = object; // If we were reading an object, replace the subject by the path's object\n else subject = this._object, this._object = object; // Emit the path's current quad and read its next section\n\n this._emit(subject, predicate, object, this._graph);\n\n return this._readPath;\n }", "_readForwardPath(token) {\n let subject, predicate;\n const object = this._blankNode();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readForwardPath(token) {\n var subject, predicate, object = this._blank();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readForwardPath(token) {\n var subject, predicate, object = this._blankNode();\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's object\n if (this._predicate === null)\n subject = this._subject, this._subject = object;\n // If we were reading an object, replace the subject by the path's object\n else\n subject = this._object, this._object = object;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readBackwardPath(token) {\n var subject = this._blank(),\n predicate,\n object; // The next token is the predicate\n\n\n if ((predicate = this._readEntity(token)) === undefined) return; // If we were reading a subject, replace the subject by the path's subject\n\n if (this._predicate === null) object = this._subject, this._subject = subject; // If we were reading an object, replace the subject by the path's subject\n else object = this._object, this._object = subject; // Emit the path's current quad and read its next section\n\n this._emit(subject, predicate, object, this._graph);\n\n return this._readPath;\n }", "_readBackwardPath(token) {\n const subject = this._blankNode();\n let predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readBackwardPath(token) {\n var subject = this._blank(), predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readBackwardPath(token) {\n const subject = this._blankNode();\n let predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "_readBackwardPath(token) {\n const subject = this._blankNode();\n\n let predicate, object; // The next token is the predicate\n\n if ((predicate = this._readEntity(token)) === undefined) return; // If we were reading a subject, replace the subject by the path's subject\n\n if (this._predicate === null) object = this._subject, this._subject = subject; // If we were reading an object, replace the subject by the path's subject\n else object = this._object, this._object = subject; // Emit the path's current quad and read its next section\n\n this._emit(subject, predicate, object, this._graph);\n\n return this._readPath;\n }", "_getPathReader(afterPath) {\n this._afterPath = afterPath;\n return this._readPath;\n }", "_readBackwardPath(token) {\n var subject = this._blankNode(), predicate, object;\n // The next token is the predicate\n if ((predicate = this._readEntity(token)) === undefined)\n return;\n // If we were reading a subject, replace the subject by the path's subject\n if (this._predicate === null)\n object = this._subject, this._subject = subject;\n // If we were reading an object, replace the subject by the path's subject\n else\n object = this._object, this._object = subject;\n // Emit the path's current quad and read its next section\n this._emit(subject, predicate, object, this._graph);\n return this._readPath;\n }", "function fetchRelativePath(path) {\n return path;\n }", "function convertPathToForwardSlash(path) {\n return path.replace(/\\\\/g, '/');\n }", "function convertPathToForwardSlash(path) {\n return path.replace(/\\\\/g, '/');\n}", "function pathAccessible(path) {\n return (0, rxjs_1.defer)(() => isPathAccessible(path)).pipe((0, operators_1.map)(exists => exists ? (0, path_1.normalize)(path) : ''));\n}", "resolvePath(path){\n\t\tif (path.length > 1 && path.charAt(path.length - 1) === \"/\"){\n\t\t\tpath = path.slice(0, path.length - 1);\n\t\t}\n\t\treturn path;\n\t}", "function parse(p, follow) {\n return new Promise((resolve, reject) => {\n if (follow === true) {\n fs.readlink(p, (err, target) => {\n return err !== null\n ? reject(err)\n : resolve(path.parse(path.resolve(p, target)))\n })\n } else {\n resolve(path.parse(p))\n }\n })\n}", "pathRef(editor, path) {\n var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};\n var {\n affinity = \"forward\"\n } = options;\n var ref2 = {\n current: path,\n affinity,\n unref() {\n var {\n current\n } = ref2;\n var pathRefs = Editor.pathRefs(editor);\n pathRefs.delete(ref2);\n ref2.current = null;\n return current;\n }\n };\n var refs = Editor.pathRefs(editor);\n refs.add(ref2);\n return ref2;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is where the two read stream tasks are built, individually asynTasks will be the two functions that will be invoked added one at a time, each time this function is invoked msg holds the parameters k is the key value for the files in msg. listParams is where the files will go so that they can be sent to the service. callback is the callback that async forces so that it can control the async functions that it is invoking.
function addTask(asyncTasks, msg, k, listParams, node) { asyncTasks.push(function(callback) { var buffer = msg.params[k]; temp.open({ suffix: '.' + fileType(buffer).ext }, function(err, info) { if (err) { node.status({ fill: 'red', shape: 'ring', text: 'unable to open image stream' }); node.error('Node has been unable to open the image stream', msg); return callback('open error on ' + k); } stream_buffer(info.path, msg.params[k], function() { listParams[k] = fs.createReadStream(info.path); callback(null, k); }); }); }); }
[ "readFiles(files, callback) {\n return new Promise((resolve) => {\n async_1.map(files, fs_1.readFile, (error, buffer) => {\n if (error) {\n throw error;\n }\n if (buffer) {\n buffer.forEach((bf, index) => __awaiter(this, void 0, void 0, function* () {\n bf && (yield callback(files[index], bf.toString()));\n if (index === files.length - 1) {\n resolve();\n }\n }));\n }\n });\n });\n }", "function callback_files_test(){\r\n console.log(\"Running callback_files_test()\");\r\n var results = [];\r\n for(var f in files){\r\n //queue up all the file calls\r\n open_file(files[f],(data) => {\r\n results.push(data); //push data read in\r\n console.log(\"Finished reading: \" + data);\r\n });\r\n }\r\n\r\n //print the result - how to fix? with promises\r\n print_string_array(results);\r\n}", "function readFilesAndPassThem (files) {\n var i = 0;\n var fileInfos = [];\n\n function readNextFile () {\n if (i < files.length) {\n readFileIntoMemory(files[i], function (fileInfo) {\n addFileExtension(fileInfo);\n fileInfos.push(fileInfo);\n i++;\n readNextFile();\n });\n } else { // when ready, pass the array to callback\n $scope.onUpload(fileInfos);\n }\n }\n readNextFile();\n }", "function multiTaskHandler(mthModContructor, tasksList){\n var mth, syncTasks, asyncTasks, mthModule = {}, additionalTasks = [], _return; \n mth = this;\n\n //use mthModConstructon to create mthModule \n if(typeof mthModContructor === 'function'){ \n mthModContructor.apply(mthModule, []);\n _return = mthModule._return; \n }\n \n tasksList = tasksList || {};\n syncTasks = tasksList.syncTasks || Object.getOwnPropertyNames(mthModule);\n asyncTasks = tasksList.asyncTasks || []; \n \n //remove _return from tasksList\n var r = syncTasks.indexOf('_return')\n if(r > -1){syncTasks.splice(r, 1)} \n \n function taskRunner(mainCallback, mthModule, syncTasks, asyncTasks){ \n //console.log('_startTasks callBack: ' + mainCallback.toString()) \n\n var taskRunner, i;\n mainCallback = mainCallback || function(){}\n taskRunner = this; \n\n if (syncTasks.indexOf('_endTasks') === -1) {syncTasks.push('_endTasks')}\n if (asyncTasks.indexOf('_startTasks') === -1) {asyncTasks.unshift('_startTasks')}\n\n mthModule._endTasks = function(err, results){\n if(typeof mainCallback === 'function'){\n if(err || results){\n mainCallback(err, results)\n }else\n if(typeof _return === 'function'){\n mainCallback(err, _return())\n }else{\n mainCallback();\n } \n }\n \n i = 0;\n return\n }\n\n mthModule._startTasks = function(callBack){ \n callBack()\n } \n\n i = 0;\n //execute each task (function) in the syncTasks array/object\n taskRunner.execSync = function(){ \n var fn = mthModule[syncTasks[i]]; \n \n function cb(err){ \n if(err){ \n if(typeof mainCallback === 'function'){mainCallback(err)}\n return false\n }\n\n i++\n \n taskRunner.execSync(); \n } \n\n return fn(cb, mthModule._endTasks); \n }\n \n //create a new instance\n taskRunner.execAsync = function(){\n var cb_counter = 0, return_val; \n \n for (var i = 0; i < asyncTasks.length; i++) { \n tasks_fn(asyncTasks[i]); \n }\n\n function tasks_fn(taskName){ \n var fn = mthModule[taskName] \n\n function cb(err){\n if(err){ \n if(typeof mainCallback === 'function'){mainCallback(err)}\n return false\n }\n //add the results to the correct property of the results obj \n cb_counter++; \n\n //after running async tasks run sync tasks\n if(cb_counter >= asyncTasks.length){ \n taskRunner.execSync(); \n }\n }\n\n return_val = fn(cb, mthModule._endTasks); \n } \n\n return return_val\n }\n\n return taskRunner \n }\n\n function isValidTaskList(tasksNames){\n\n if(!(tasksNames instanceof Array)){\n throw 'tasksJS ERROR: setTasks & setTasksAsync functions must pass an array of strings'\n }\n\n for (var i = 0; i < tasksNames.length; i++) {\n if(!(mthModule[tasksNames[i]])){\n return false\n } \n }\n return true\n }\n \n mth.setTasks = function(syncList){ \n syncList = (syncList) ? Array.from(syncList) :Object.getOwnPropertyNames(mthModule);\n\n if(isValidTaskList(syncList)){\n //creates an new instance of tasks if contstructor was passed on init\n if(typeof mthModContructor === 'function'){\n return new multiTaskHandler(mthModContructor, {syncTasks:syncList}) ; \n }else{\n syncTasks = syncList;\n }\n }else{\n throw 'tasksJS ERROR: multiTaskHandler Class ---> Invalid taskList!!!';\n } \n }\n \n mth.setTasksAsync = function(asyncList, syncList){\n syncList = (syncList) ? Array.from(syncList) : [];\n asyncList = (asyncList) ? Array.from(asyncList) :Object.getOwnPropertyNames(mthModule);\n \n if(isValidTaskList(asyncList) && isValidTaskList(syncList)){\n //creates an new instance of tasks if contstructor was passed on init\n if(typeof mthModContructor === 'function'){\n return new multiTaskHandler(mthModContructor, {syncTasks:syncList, asyncTasks:asyncList}) ; \n }else{\n syncTasks = syncList;\n asyncTasks = asyncList;\n }\n }else{\n throw 'tasksJS ERROR: multiTaskHandler Class ---> Invalid taskList!!!';\n } \n }\n\n mth.runTasks = function(){\n var args = [], callBack, i = 1, _mthModule = {};\n //seperate the callBack from the remaining arguments\n if(typeof arguments[0] === 'function'){\n callBack = arguments[0]; \n }\n\n for (i; i < arguments.length; i++) {\n args.push(arguments[i])\n } \n \n if (args.length > 0 && typeof mthModContructor === 'function'){\n //create new instance of the mthModule with new args\n mthModContructor.apply(_mthModule, args);\n }else{\n _mthModule = mthModule;\n }\n \n //add additional tasks to mthModule\n for (var i = 0; i < additionalTasks.length; i++) {\n _mthModule[additionalTasks[i].name] = additionalTasks[i].fn \n } \n\n //create new instance of the taskRunner to run methods on the mthModule\n return new taskRunner(callBack, _mthModule, syncTasks, asyncTasks).execAsync(); \n }\n \n mth.addTask = function(name, fn){\n name = name || randomStr();\n additionalTasks.push({name:name, fn:fn})\n\n if(syncTasks.indexOf('_endTasks') === syncTasks.length - 1){\n syncTasks.pop();\n syncTasks.push(name);\n syncTasks.push('_endTasks');\n }else{\n syncTasks.push(name); \n }\n \n return mth\n }\n\n mth.addTaskAsync = function(name, fn){\n name = name || randomStr();\n additionalTasks.push({name:name, fn:fn})\n asyncTasks.push(name);\n return mth \n }\n //tasks an array of random fns to add to syncTasks list\n mth.addMultiTask = function(tasksArr){\n for (var i = 0; i < tasksArr.length; i++) {\n mth.addTask(null, tasksArr[i]);\n }\n return mth\n }\n //tasks an array of random fns to add to asyncTasks list\n mth.addMultiTaskAsync = function(tasksArr){\n for (var i = 0; i < tasksArr.length; i++) {\n mth.addTaskAsync(null, tasksArr[i]);\n } \n return mth\n }\n\n //if mth is initialzed without a construnction don't add setArgs fn\n if(typeof mthModContructor === 'function'){\n mth.setArgs = function(){\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n //overwrite mthModule with new one with args\n mthModContructor.apply(mthModule, args);\n return mth\n } \n }\n \n\n //a subscription will exect the syncTasks every x seconds\n mth.createSubscription = function(seconds){\n \n var subscription = function(){\n var runningSub;\n \n var interval = (seconds) ? seconds * 1000: 1000;\n \n this.start = function(){ \n var args = [], callBack, i = 1, _mthModule = {};\n //seperate the callBack from the remaining arguments\n if(typeof arguments[0] === 'function'){\n callBack = arguments[0]; \n }\n\n for (i; i < arguments.length; i++) {\n args.push(arguments[i]);\n } \n \n if (args.length > 0 && typeof mthModContructor === 'function'){\n //create new mthModule with new args\n mthModContructor.apply(_mthModule, args);\n }else{\n _mthModule = mthModule;\n }\n \n //use setInterval to run taskRunner on repeat \n runningSub = setInterval(new taskRunner(callBack, _mthModule, syncTasks, asyncTasks).execAsync, interval); \n }\n\n this.end = function(){ \n clearInterval(runningSub);\n }\n } \n\n return new subscription()\n } \n \n return mth\n }", "function readFiles(dirname, onFileContent, onError) {\n fs.readdir(dirname, function(err, folders) {\n if (err) {\n console.log(err);\n onError(err);\n\n return;\n }\n var data = {}; // object containing all text files results\n if (folders.length == 0) {\n \tonFileContent(undefined);\n }\n console.log(folders);\n // Read all files in the directory\n folders.forEach(function(folder) {\n //console.log(folder);\n fs.readdir(dirname + folder, function(err, filenames) {\n if (err) {\n console.log(err);\n onError(err);\n return;\n }\n if (filenames.length == 0){\n data[folder] = {};\n }\n filenames.forEach(function(filename) {\n fs.readFile(dirname + folder + '/' + filename, 'utf-8', function(err, content){\n var contents_array = content.split('\\n'); // Split text files by new line\n var i = 0; // Check if all files have been processed\n var content_object = {}; // object containing results for 1 text file\n for (var key in contents_array){\n var data_array = contents_array[key].split(','); // Get each field\n content_object[i] = {time:data_array[0], packetID:data_array[1], function:data_array[2], action:data_array[3]};\n i = i+1;\n }\n data[folder] = content_object;\n if (Object.keys(data).length == folders.length) {\n console.log(data);\n onFileContent(data);\n }\n });\n //console.log(data);\n });\n //console.log(filename);\n \t /* var contents_array = content.split('\\n'); // Split text files by new line\n var i = 0; // Check if all files have been processed\n var content_object = {}; // object containing results for 1 text file\n for (var key in contents_array){\n \tvar data_array = contents_array[key].split(','); // Get each field\n \tcontent_object[i] = {time:data_array[0], packetID:data_array[1], function:data_array[2], action:data_array[3]};\n \ti = i+1;\n }\n data[filename] = content_object; // Insert the textfile into the array we are passing on\n \n // If every text file has been processed, send the object to call back.\n if (Object.keys(data).length == filenames.length) {\n \tonFileContent(data);\n }*/\n });\n });\n });\n}", "function readFileWaterfall(req, res) {\n async.waterfall([\n readFirstFile,\n readSecondFile,\n readThirdFile,\n ], function (err, fulllContent) {\n if (err) {\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n const response = {\n statusCode: 200,\n message: success,\n data: {\n fromAsyncWaterfall: fulllContent.toString()\n }\n }\n res.json(response);\n });\n\n function readFirstFile(callback) {\n fs.readFile(\"./files/\" + req.params.one + \".txt\", {}, (err, contentOne) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, contentOne);\n });\n }\n\n function readSecondFile(passedData, callback) {\n fs.readFile(\"./files/\" + req.params.two + \".txt\", {}, (err, contentTwo) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, passedData + contentTwo);\n });\n }\n\n function readThirdFile(passedData, callback) {\n fs.readFile(\"./files/\" + req.params.three + \".txt\", {}, (err, contentThree) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, passedData + contentThree);\n });\n }\n}", "function onListingCompleted(callback) {\n console.log('Finish getting all the meta data from dropbox server / Start making directory')\n makeDirectory((err_makeFile) => {\n if (err_makeFile) {\n callback(err_makeFile)\n } else {\n middleware.getUnbackupedFiles(allFiles, (err_getFiles, res_files) => {\n if (err_getFiles) {\n console.log(err_getFiles)\n callback(err_getFiles, null)\n } else {\n // console.log(res_files)\n let totalNumberOfFiles = res_files.length;\n if (totalNumberOfFiles == 0) {\n callback(null, 'No need to backup')\n return\n }\n let numberOfSuccess = 0;\n for (let i = 0; i < res_files.length; i ++) {\n // console.log(res_files[i].fullPath)\n downloadFileSingle(res_files[i].fullPath, (error, localDownloadedPath) => {\n if (error) {\n console.error('Error downloading the file. something is wrong!')\n callback(error, 'Error downloading the file. something is wrong!')\n } else {\n numberOfSuccess ++;\n // console.log('File: -' + res_files[i].fullPath + '- index: ' + numberOfSuccess + '/' + totalNumberOfFiles)\n res_files[i].localPath = localDownloadedPath\n // localFiles.push(localDownloadedPath)\n if (numberOfSuccess >= totalNumberOfFiles) {\n console.log('Finish saving dropbox files to local!')\n // middleware.backupFilesToSendspace(localFiles, callback)\n middleware.backupFilesToSendspace(res_files, callback)\n }\n }\n })\n }\n }\n })\n }\n })\n}", "stream_files(filter) {\r\n return observable((next, complete, error) => {\r\n //let obs_files = dir_contents(this.path);\r\n /*\r\n obs_files.on('next', data => {\r\n if (data instanceof File) {\r\n\r\n } else {\r\n\r\n }\r\n })\r\n */\r\n\r\n (async () => {\r\n let files = await dir_contents(this.path, {\r\n filter: filter\r\n });\r\n\r\n //console.log('files', files);\r\n for (let file of files) {\r\n // output stream...\r\n\r\n if (file instanceof File) {\r\n //console.log('pre pr');\r\n let pr = new Promise((solve, jettison) => {\r\n //console.log('file.path', file.path);\r\n var readStream = fs.createReadStream(file.path);\r\n next({\r\n stream: readStream,\r\n file: file\r\n });\r\n readStream.on('data', function (chunk) {\r\n //data += chunk;\r\n }).on('end', function () {\r\n //console.log(data);\r\n\r\n solve();\r\n });\r\n });\r\n await pr;\r\n }\r\n }\r\n complete();\r\n })();\r\n\r\n return [];\r\n })\r\n }", "function readFileSeries(req, res) {\n async.series([\n function (callback) {\n fs.readFile(\"./files/\" + req.params.one + \".txt\", {}, (err, contentOne) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, contentOne);\n })\n },\n function (callback) {\n fs.readFile(\"./files/\" + req.params.two + \".txt\", {}, (err, contentTwo) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, contentTwo);\n })\n },\n function (callback) {\n fs.readFile(\"./files/\" + req.params.three + \".txt\", {}, (err, contentThree) => {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n callback(null, contentThree);\n })\n }\n ],\n // Callback\n function (err, results) {\n if (err) {\n console.log(err.message);\n const response = {\n statusCode: 400,\n error: err,\n data: null\n }\n res.json(response);\n }\n const response = {\n statusCode: 200,\n message: success,\n data: {\n fromAsyncSeries: results.toString()\n }\n }\n res.json(response);\n });\n}", "function getFileList(sort_order, callback) {\n\n const args = {\n sort_order\n };\n\n // Make the call to the server,\n query('getFileList', args, callback);\n\n}", "function read_pubkeys (cb) {\n var pgm = service + '.read_pubkeys: ' ;\n var group_debug_seq ;\n if (!cb) cb = function() {} ;\n\n group_debug_seq = MoneyNetworkAPILib.debug_group_operation_start() ;\n MoneyNetworkAPILib.debug_group_operation_update(group_debug_seq, {msgtype: 'pubkeys'}) ;\n encrypt2.get_session_filenames({group_debug_seq: group_debug_seq}, function (this_session_filename, other_session_filename, unlock_pwd2) {\n var pgm = service + '.read_pubkeys get_session_filenames callback 1: ' ;\n var pgm2, w2_query_4, debug_seq ;\n pgm2 = MoneyNetworkAPILib.get_group_debug_seq_pgm(pgm, group_debug_seq) ;\n console.log(pgm2 + 'this_session_filename = ' + this_session_filename + ', other_session_filename = ' + other_session_filename) ;\n w2_query_4 =\n \"select \" +\n \" json.directory,\" +\n \" substr(json.directory, 1, instr(json.directory,'/')-1) as hub,\" +\n \" substr(json.directory, instr(json.directory,'/data/users/')+12) as auth_address,\" +\n \" files_optional.filename, keyvalue.value as modified \" +\n \"from files_optional, json, keyvalue \" +\n \"where files_optional.filename like '\" + other_session_filename + \"-i.%' \" +\n \"and json.json_id = files_optional.json_id \" +\n \"and keyvalue.json_id = json.json_id \" +\n \"and keyvalue.key = 'modified' \" +\n \"order by files_optional.filename desc\" ;\n console.log(pgm2 + 'w2 query 4 = ' + w2_query_4) ;\n debug_seq = MoneyNetworkAPILib.debug_z_api_operation_start(pgm, 'w2 query 4', 'dbQuery', null, group_debug_seq) ;\n ZeroFrame.cmd(\"dbQuery\", [w2_query_4], function (res) {\n var pgm = service + '.read_pubkeys dbQuery callback 2: ' ;\n var pgm2, prefix, other_user_path, inner_path, re, i ;\n MoneyNetworkAPILib.debug_z_api_operation_end(debug_seq, (!res || res.error) ? 'Failed. error = ' + JSON.stringify(res) : 'OK. Returned ' + res.length + ' rows');\n pgm2 = MoneyNetworkAPILib.get_group_debug_seq_pgm(pgm, group_debug_seq) ;\n prefix = \"Error. MN-W2 session handshake failed. \" ;\n // console.log(pgm + 'res = ' + JSON.stringify(res)) ;\n if (!res || res.error) {\n console.log(pgm2 + prefix + 'cannot read pubkeys message. dbQuery failed with ' + JSON.stringify(res)) ;\n console.log(pgm2 + 'query = ' + w2_query_4) ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, JSON.stringify(res)) ;\n return cb(status.sessionid) ;\n }\n // check optional filename. pubkeys message from mn is an -i (internal) optional file\n re = /^[0-9a-f]{10}-i\\.[0-9]{13}$/ ;\n console.log(pgm2 + 'old res.length = ' + res.length) ;\n for (i=res.length-1 ; i >= 0 ; i--) {\n if (!res[i].filename.match(re)) res.splice(i,1) ;\n }\n console.log(pgm2 + 'new res.length = ' + res.length) ;\n if (res.length == 0) {\n console.log(pgm2 + prefix + 'pubkeys message was not found') ;\n console.log(pgm2 + 'w2 query 4 = ' + w2_query_4) ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message was not found (dbQuery)') ;\n return cb(status.sessionid) ;\n }\n\n // mark file as read. generic process_incoming_message will not process this file\n MoneyNetworkAPILib.wait_for_file(res[0].filename) ;\n\n // first message. remember path to other session user directory. all following messages must come from same user directory\n other_user_path = 'merged-' + get_merged_type() + '/' + res[0].directory + '/' ;\n encrypt2.setup_encryption({other_user_path: other_user_path}) ;\n\n // read file\n inner_path = other_user_path + res[0].filename ;\n // console.log(pgm + inner_path + ' z_file_get start') ;\n z_file_get(pgm, {inner_path: inner_path, required: true, group_debug_seq: group_debug_seq}, function (pubkeys_str) {\n var pgm = service + '.read_pubkeys z_file_get callback 3: ' ;\n var pgm2, pubkeys, now, content_signed, elapsed, error ;\n pgm2 = MoneyNetworkAPILib.get_group_debug_seq_pgm(pgm, group_debug_seq) ;\n // console.log(pgm + 'pubkeys_str = ' + pubkeys_str) ;\n if (!pubkeys_str) {\n console.log(pgm2 + prefix + 'read pubkeys failed. file + ' + inner_path + ' was not found') ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message was not found (fileGet)') ;\n return cb(status.sessionid) ;\n }\n // check pubkeys message timestamps. must not be old or > now.\n now = Math.floor(new Date().getTime()/1000) ;\n content_signed = res[0].modified ;\n // file_timestamp = Math.floor(parseInt(res[0].filename.substr(11))/1000) ;\n elapsed = now - content_signed ;\n if (elapsed < 0) {\n console.log(pgm2 + prefix + 'read pubkeys failed. file + ' + inner_path + ' signed in the future. elapsed = ' + elapsed) ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message signed in the future') ;\n return cb(status.sessionid) ;\n }\n if (elapsed > 60) {\n console.log(pgm2 + prefix + 'read pubkeys failed. file + ' + inner_path + ' is too old. elapsed = ' + elapsed) ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message is old') ;\n status.sessionid = null ;\n return cb(status.sessionid) ;\n }\n // console.log(pgm2 + 'timestamps: file_timestamp = ' + file_timestamp + ', content_signed = ' + content_signed + ', now = ' + now) ;\n try {\n pubkeys = JSON.parse(pubkeys_str) ;\n }\n catch (e) {\n console.log(pgm2 + prefix + 'read pubkeys failed. file + ' + inner_path + ' is invalid. pubkeys_str = ' + pubkeys_str + ', error = ' + e.message) ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message is invalid. ' + e.message) ;\n return cb(status.sessionid) ;\n }\n error = MoneyNetworkAPILib.validate_json(pgm, pubkeys) ;\n if (error) {\n console.log(pgm2 + prefix + 'invalid pubkeys message. error = ' + error) ;\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'pubkeys message is invalid. ' + error) ;\n return cb(status.sessionid) ;\n }\n if (pubkeys.msgtype != 'pubkeys') {\n console.log(pgm2 + prefix + 'First message from MN was NOT a pubkeys message. message = ' + JSON.stringify(pubkeys) );\n status.sessionid = null ;\n MoneyNetworkAPILib.debug_group_operation_end(group_debug_seq, 'not a pubkey message. msgtype = ' + JSON.stringify(pubkeys.msgtype)) ;\n return cb(status.sessionid);\n }\n console.log(pgm2 + 'OK. received public keys from MN') ;\n console.log(pgm2 + 'MN public keys: pubkey2 = ' + pubkeys.pubkey2 + ', pubkey = ' + pubkeys.pubkey) ;\n encrypt2.setup_encryption({pubkey: pubkeys.pubkey, pubkey2: pubkeys.pubkey2}) ;\n // mark file as read.\n\n // return W2 public keys to MN session for full end2end encryption between the 2 sessions\n console.log(pgm + 'Return W2 public keys to MN for full end-2-end encryption') ;\n write_pubkeys(group_debug_seq, cb) ;\n\n }) ; // z_file_get callback 3\n\n }) ; // dbQuery callback 2\n\n\n }) ; // get_session_filenames callback 1\n\n } // read_pubkeys", "function getListOfBatchFiles(callback) {\n\ttry{\n\t\tvar configObject = new configuration();\n\t\tvar instance = new cybersourceRestApi.TransactionBatchesApi(configObject);\n\n\t\tvar startTime = '2019-09-01T20:34:24.000Z';\n\t\tvar endTime = '2019-09-30T23:27:25.000Z';\n \n\t\tconsole.log('\\n*************** Retrieve list of batch file ********************* ');\n\n\t\tinstance.getTransactionBatches(startTime, endTime, function (error, data, response) {\n\t\t\tif (error) {\n\t\t\t\tconsole.log('\\nError in retrieve list of batch file : ' + JSON.stringify(error));\n\t\t\t}\n\t\t\telse if (data) {\n\t\t\t\tconsole.log('\\nData of retrieve list of batch file : ' + JSON.stringify(data));\n\t\t\t}\n\t\t\tconsole.log('\\nResponse of retrieve list of batch file : ' + JSON.stringify(response));\n\t\t\tconsole.log('\\nResponse Code of retrieve list of batch file : ' + JSON.stringify(response['status']));\n\t\t\tcallback(error, data);\n\t\t});\n\n\t} catch (error) {\n\t\tconsole.log(error);\n\t}\n}", "function readAllTasks(callback) {\n var taskArray = [];\n\n // fetches set of tasks ids\n client.smembers(\"idSet\", function(err, reply) {\n\n var replyLength = reply.length;\n\n if (replyLength > 0) {\n\n reply.forEach(function(key) {\n\n // for each id return all hash info\n client.hgetall(key, function(err, reply) {\n taskArray.push(reply);\n\n if (taskArray.length === replyLength) {\n callback(null, taskArray);\n }\n });\n });\n } else {\n callback(null, taskArray);\n }\n });\n}", "function run(data, ack){\n console.log(JSON.stringify(data));\n data.data.forEach(function(file){\n var req = http.request({\n host: 'localhost', // This must be changed to be dynamic so it can run from multiple locations\n path: '/shellscripts/'+escape(file.originalname),\n port: '3000', // This also is not a constant value that must be changed to be dynamic \n method: 'GET'\n }, function(res){\n console.log('data');\n var data = '';\n res.on('data', function(chunk){\n data += chunk;\n });\n\n res.on('end', function(){\n console.log( '<<<<<<<<<<<<<==='+ file.originalname + '===>>>>>>>>>>>>>');\n console.log(data);\n // Here you would do logic to write the file to storage and create a Promise or Observable that \n // is triggered when all the files are written. \n });\n });\n req.end();\n });\n ack();\n // After all the data is written and processed this is called to acknowlege with the RabbitMQ server that \n // the operation is a success\n}", "function multiLoadFiles(func, files) {\n const n = files.length;\n let transaction = new DecaMultiFileLoader(n);\n\n for(let i = 0; i < n; ++i)\n {\n let file_info = files[i];\n let f_ref = file_info[0];\n let f_type = file_info[1];\n let f_process = file_info[2];\n\n if(f_process === null)\n f_process = (x) => x;\n\n if(typeof f_ref === 'string') // url\n {\n $.get(f_ref, (data, textStatus, jqXHR) => {\n console.log('Loaded: ', f_ref, ' Status: ', textStatus);\n\n transaction.data[i] = data;\n transaction.reader[i] = null;\n transaction.is_loaded[i] = true;\n processTransaction(func, transaction);\n })\n }\n else\n {\n if(!(f_ref instanceof File))\n {\n f_ref.file(f=>{f_ref=f;},e=>{f_ref=null;})\n }\n\n let reader = new FileReader();\n transaction.reader[i] = reader;\n\n reader.onloadend = function() {\n transaction.data[i] = f_process(reader.result);\n transaction.reader[i] = null;\n transaction.is_loaded[i] = true;\n processTransaction(func, transaction);\n }\n reader.onerror = function() {\n transaction.data[i] = data;\n transaction.reader[i] = null;\n transaction.is_loaded[i] = true;\n processTransaction(func, transaction);\n }\n\n if(f_type === 'array_buffer')\n reader.readAsArrayBuffer(f_ref);\n else if(f_type === 'text')\n reader.readAsText(f_ref)\n else\n throw Error(`unknown f_type == ${f_type}`)\n }\n }\n}", "function receiveFileList(data) {\n\t//console.log('Received: ' + data);\n\tif (data != 'R51end:') {\n\t\ttemplateFiles.push(data);\n\t\tclient.write('R5$VIDEO:');\n\t} else if (data == 'R51end:') {\n\t\tdisplayTemplateFiles();\n\t}\n\n}", "function getFilesInTask(taskDir, forEach, callBack, afterTimeX) {\n // get each subdirectory in the task file path\n var subDirs = getDirectories(taskDir);\n subDirs.sort(function(a, b) {\n if (a > b) return -1;\n if (a < b) return 1;\n return 0;\n });\n // for each subdir get the ones after timeX\n for (var sub = 0; sub < subDirs.length && (subDirs[sub] > afterTimeX || !afterTimeX); sub++) {\n // then get each file in those sub dirs\n var timeDir = path.resolve(taskDir + '/' + subDirs[sub]);\n if (fs.existsSync(timeDir)) {\n var timeStampFiles = fs.readdirSync(timeDir);\n var files = [];\n for (var tFile = 0; tFile < timeStampFiles.length; tFile++) {\n if (!fs.lstatSync(path.resolve(timeDir + '/' + timeStampFiles[tFile])).isDirectory())\n files.push({\n name: timeStampFiles[tFile],\n timeStamp: subDirs[sub]\n });\n }\n // get all the messages in that timedirectory\n var messages = {};\n var messagePath = path.resolve(timeDir + '/messages/' + getRequesterMsgFileName());\n if (fs.existsSync(messagePath))\n messages.requester = fs.readFileSync(messagePath, 'utf8');\n messagePath = path.resolve(timeDir + '/messages/' + getWorkerMsgFileName());\n if (fs.existsSync(messagePath))\n messages.worker = fs.readFileSync(messagePath, 'utf8');\n messagePath = path.resolve(timeDir + '/messages/' + getSubmissionMsgFileName());\n if (fs.existsSync(messagePath))\n messages.submission = fs.readFileSync(messagePath, 'utf8');\n forEach(subDirs[sub], files || [], messages || null);\n }\n }\n return callBack();\n}", "function module1(folderpath, io_path, connection, callback) {\n async.waterfall([\n // SETUP: find files, connect, create userid, create io, insert io (result = [batches, null, null], returns batches)\n function setup(cb) {\n async.parallel([\n // Find the json files to be processed (returns batches)\n function find_files(pcb) {\n fs.readdir(folderpath, function(err, result) {\n if (err) {\n console.log('Error at find_files().')\n pcb(err)\n } else {\n let json_filepaths = []\n for (filename of result) { \n if (filename.endsWith('.json')) {\n json_filepaths.push(folderpath + '/' + filename)\n }\n }\n \n const batches = []\n const num_batches = Math.floor(json_filepaths.length / batch_size)\n for (let i = 0; i < num_batches; i ++) {\n batches.push(json_filepaths.slice(0, batch_size))\n json_filepaths.splice(0, batch_size)\n }\n batches.push(json_filepaths)\n \n console.log('Sorted folder: ' + folderpath + ': found ' + batches.length + ' batches.')\n pcb(null, batches)\n }\n })\n },\n // Create userid_table (returns null)\n function create_uuid(pcb) {\n create_table(userid_table, userid_example, userid_unique_keys, connection, (err, result) => {\n if (err) {\n console.log('Failed to create table: ' + userid_table)\n pcb(err)\n } else {\n console.log('Finished creating table: ' + userid_table)\n pcb(null)\n }\n })\n },\n // Submodule 1: create io, insert io (returns null)\n function submodule1(pcb) {\n async.waterfall([\n // Create io table.\n function create_io(sm_wcb) {\n create_table(io_table, io_example, undefined, connection, (err, result) => {\n if (err) {\n console.log('Failed to create table: ' + io_table)\n sm_wcb(err)\n } else {\n console.log('Finished creating table: ' + io_table)\n sm_wcb(null)\n }\n })\n },\n // Insert io file.\n function insert_io(sm_wcb) {\n read_csvfile(io_path, (err, result) => {\n if (err) {\n sm_wcb(err)\n } else { \n const headers = ['application', '_ID']\n const data = result.slice(1)\n const new_data = []\n for (d of data) {\n nd = []\n if (d[1]) {\n nd.push(d[1])\n } else {\n nd.push(d[0])\n }\n nd.push(d[3])\n new_data.push(nd)\n }\n const io_write = make_obj(headers, new_data)\n insert_table(io_write, io_table, connection, undefined, undefined, (err) => {\n if (err) {\n sm_wcb(err)\n } else {\n sm_wcb(null)\n }\n })\n }\n })\n }\n ], \n function (err) {\n if (err) {\n pcb(err)\n } else {\n pcb(null)\n }\n })\n }\n ], \n function (err, result) {\n if (err) {\n cb(err)\n } else {\n cb(null, result[0])\n }\n })\n },\n // Process batches (returns null)\n function process(batches, cb) {\n const pool = mysql.createPool({\n conncetionLimit: batches.length,\n host: 'localhost',\n port: '3306',\n database: 'LBLR_data',\n user: 'root',\n password: 'raceboorishabackignitedrum',\n })\n \n async.map(batches, \n (datum, map_callback) => {\n console.log(datum)\n batch(datum, userid_table, 0, connection, (err) => {\n if (err) {\n map_callback(err)\n }\n else {\n map_callback(null)\n }\n })\n },\n (err, result) => {\n if (err) {\n cb(err)\n }\n else {\n const select_query = \"SELECT * FROM \" + userid_table\n connection.query(select_query, (err, result, fields) => {\n if (err) {\n cb(err)\n } else {\n cb(null, result)\n }\n })\n }\n }\n )\n },\n\n // Drop io_table (returns null)\n function drop_io(output, cb) {\n drop_table(io_table, connection, (err, result) => {\n if (err) {\n console.log('Error dropping: ' + io_table)\n cb(err)\n } else {\n console.log('Dropped: ' + io_table)\n cb(null, output)\n }\n })\n },\n ], \n function (err, output) {\n if (err) {\n console.log('\\n\\t Trying to cleanup module 1\\n')\n cleanupTables(connection, (cleanErr) => {\n if (cleanErr) {\n console.log('Cleanup Error', cleanErr)\n }\n else {\n close_connection(connection, (conErr) => {\n if (conErr) {\n console.log('Close Connection Error', conErr)\n }\n else {\n callback(err)\n }\n })\n }\n })\n } else {\n module2(output, connection, callback)\n }\n })\n}", "createStreams (callback) {\n\t\tthis.myFileStreams = [];\n\t\tthis.foreignFileStreams = [];\n\t\tthis.myChannelStreams = [];\n\t\tthis.foreignChannelStreams = [];\n\t\tthis.myDirectStreams = [];\n\t\tthis.foreignDirectStreams = [];\n\t\tconst teamInfo = [\n\t\t\t{ team: this.team, repo: this.repo, users: this.users },\n\t\t\t{ team: this.foreignTeam, repo: this.foreignRepo, users: this.foreignUsers }\n\t\t];\n\t\tBoundAsync.forEachSeries(\n\t\t\tthis,\n\t\t\tteamInfo,\n\t\t\tthis.createStreamsInTeam,\n\t\t\tcallback\n\t\t);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use reduce to group an array of objects on a specified key
function groupByKey(array, key = "key") { return array.reduce((actual, current) => { if (actual[current.key] === undefined) { actual[current.key] = []; } actual[current.key].push(current); return actual; }, {}); }
[ "function groupBy(array, key) {\n return array.reduce((result, currentValue) => {\n (result[currentValue[key]] = result[currentValue[key]] || []).push(\n currentValue\n );\n return result;\n }, {}); \n}", "groupBy( arrayOfObjects, key ) {\n\n return _.groupBy(arrayOfObjects, key);\n\n }", "function groupObjects(element, key) {\n\treturn element.reduce(function(new_element, index) {\n\t\t(new_element[index[key]] = new_element[index[key]] || []).push(index);\n\t\t\treturn new_element;\n\t\t}, {});\n\t}", "function groupBy(xs, key) {\n return xs.reduce(function(rv, x) {\n (rv[x[key]] = rv[x[key]] || []).push(x);\n return rv;\n }, {});\n}", "function groupByArray(xs, key) {\n return xs.reduce(function (rv, x) {\n const v = key instanceof Function ? key(x) : x[key]\n if (v !== undefined) {\n const el = rv.find((r) => r && r.key === v)\n if (el) {\n el.values.push(x)\n } else {\n rv.push({ key: v, values: [x] })\n }\n }\n return rv\n }, [])\n}", "function test23_9() {\n let people = [\n {name: 'Alice', age: 21},\n {name: 'Max', age: 20},\n {name: 'Jane', age: 20}\n ];\n\n function groupBy(objectArray, property) {\n return objectArray.reduce(function (acc, obj) {\n let key = obj[property];\n if (!acc[key]) {\n acc[key] = [];\n }\n acc[key].push(obj);\n return acc;\n }, {});\n }\n\n var groupedPeople = groupBy(people, 'age');\n console.log(groupedPeople);\n // groupedPeople is:\n // {\n // 20: [\n // { name: 'Max', age: 20 },\n // { name: 'Jane', age: 20 }\n // ],\n // 21: [{ name: 'Alice', age: 21 }]\n // }\n}", "function loomGroupBy(array, key, sumKey) {\n // Return the end result\n return array.reduce((result, currentValue) => {\n // If a value is already present for key, add to it. Else insert the current value as a seed.\n result[currentValue[key]] = (result[currentValue[key]] || 0) + currentValue[sumKey]\n // Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate\n return result;\n }, {}); // empty object is the initial value for result object\n }", "function groupBy(array, property) {\n return array.reduce(function (acc, item) {\n var key = item[property];\n if (Reflect.has(acc, key) && Array.isArray(acc[key])) {\n acc[key].push(item);\n } else {\n acc[key] = [item];\n }\n return acc;\n }, {});\n}", "function groupBy(data_array, property) {\r\n return data_array.reduce(function (accumulator, current_object) {\r\n let key = current_object[property];\r\n if (!accumulator[key]) {\r\n accumulator[key] = [];\r\n }\r\n accumulator[key].push(current_object);\r\n return accumulator;\r\n }, {});\r\n }", "function groupBy(array, fn) {\n const group = {};\n array.forEach(element => {\n const key = fn(element);\n if (!(key in group)) {\n group[key] = [];\n }\n group[key].push(element);\n });\n return group;\n}", "function groupBy(arrayOfObjects, filterProperty, sumsProperty) {\n\t\t\treturn arrayOfObjects.reduce(function(resultArray, oneObject) {\n\t\t\t\tvar key = oneObject[filterProperty];\n\t\t\t\tif (!resultArray[key]) {\n\t\t\t\t\tresultArray[key] = 0;\n\t\t\t\t}\n\t\t\t\tresultArray[key] += oneObject[sumsProperty];\n\t\t\t\treturn resultArray;\n\t\t\t}, {});\n\t\t}", "groupBy(groupFn) {\n return this.andThen(state => Object.assign(state, { value: state.value.reduce(reduceFn, {}) }));\n function reduceFn(groups, b) {\n const key = groupFn(b);\n if (!(key in groups))\n groups[key] = [];\n groups[key].push(b);\n return groups;\n }\n }", "function groupByProperty (items, propName) {\n let tracker = [];\n let result = items.reduce((acc, entry) => {\n // do we have this in the tracker?\n if (tracker.indexOf(entry[propName]) === -1) {\n // add to tracker...\n tracker.push(entry[propName]);\n // create entry in output\n acc.push({group: entry[propName], entries: [entry]});\n } else {\n // it's in the acc, so get it and push the\n let group = findBy(acc, 'group', entry[propName]);\n group.entries.push(entry);\n }\n return acc;\n }, []);\n return result;\n}", "function groupReduce(groupFn, reduceFn, reduceInit, iter) {\n let result = {};\n // stringifying and parsing reduceInit to make a fresh deep copy of\n // reduceInit for each group\n let initString = JSON.stringify(reduceInit)\n for (let elem of iter) {\n let group = groupFn(elem);\n if (! (group in result)) result[group] = JSON.parse(initString);\n result[group] = reduceFn(result[group], elem);\n }\n return result;\n}", "function groupBy(list, field) {\n return list.reduce( (groups, record) => {\n if (groups[record[field]] === undefined) {\n groups[record[field]] = [];\n }\n //console.log(\"Record:\", record)\n //console.log(\"Field:\", record[field])\n //console.log(\"Keys:\", Object.getOwnPropertyNames(record));\n groups[record[field]].push(record);\n return groups;\n }, {})\n\n}", "function groupByProp(data, triplesFormat, propIndex, valueProp) {\n triplesFormat = triplesFormat || ['subject', 'predicate', 'object'];\n var settingsObj = {\n triplesFormat: triplesFormat,\n groupProp: triplesFormat[(propIndex || 0)],\n valueProp: valueProp,\n keys: [],\n fields: [],\n mappings: {},\n data: []\n }; \n //reducer //initial object acts as prev in the reducer\n return data.reduce(tripleAccumulator, settingsObj);\n }", "function groupBy(arr, callback){\n const returnObj = {};\n arr.map( elem => {\n const returnVal = callback(elem);\n if(!returnObj[returnVal]){\n let valueArr = []\n valueArr.push(elem);\n returnObj[returnVal] = valueArr;\n \n } else {\n returnObj[returnVal].push(elem)\n }\n })\n return returnObj\n}", "function group(foods) {\n return foods.reduce((accumulator, currentValue) => {\n accumulator[currentValue.type] = accumulator[currentValue.type] || [];//TODO what is this?\n accumulator[currentValue.type].push(currentValue.food);\n return accumulator;\n }, {});\n}", "function group_by(arr_objs, params){\n\t\tvar keys = params.keys;\n\t\tvar arr_fields_concat = params.concats;\n\n\t\tif((keys != undefined) && (arr_fields_concat != undefined)){\n\t\t\tvar new_arr = [];\n\t\t\t\tfor (var i = 0; i < arr_objs.length; i++) {\n\n\t\t\t\t\tvar obj_values = collect_values(arr_objs[i], keys);\n\t\t\t\t\tvar values = [];\n\t\t\t\t\tfor (var k = 0; k < keys.length; k++) {\n\t\t\t\t\t\tvalues.push(obj_values[keys[k]].value);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar index = index_in_arrjsons(new_arr, keys, values);\n\t\t\t\t\tif (index == -1) {\n\t\t\t\t\t\tfor (var j = 0; j < arr_fields_concat.length; j++) {\n\t\t\t\t\t\t\tvar elem = arr_objs[i];\n\t\t\t\t\t\t\tif (arr_objs[i].hasOwnProperty(arr_fields_concat[j])) {\n\t\t\t\t\t\t\t\telem[arr_fields_concat[j]] = {\"concat-list\": [elem[arr_fields_concat[j]]]};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnew_arr.push(elem);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else {\n\t\t\t\t\t\tfor (var j = 0; j < arr_fields_concat.length; j++) {\n\t\t\t\t\t\t\tif (arr_objs[i].hasOwnProperty(arr_fields_concat[j])) {\n\t\t\t\t\t\t\t\tvar elem = arr_objs[i][arr_fields_concat[j]];\n\n\t\t\t\t\t\t\t\tvar index_concat_list = index_in_arrjsons(new_arr[index][arr_fields_concat[j]][\"concat-list\"], [\"value\"], [elem.value]);\n\t\t\t\t\t\t\t\tif(index_concat_list == -1){\n\t\t\t\t\t\t\t\t\tnew_arr[index][arr_fields_concat[j]][\"concat-list\"].push(elem);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn new_arr;\n\t\t\t}\n\t\t\treturn arr_objs;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide default properties to dimensions that have a single role bound to it, by using the role's properties. The order of application is not relevant. TODO: this is being repeated for !prebound! dimensions
function applySingleRoleDefaults() { def.eachOwn(singleRoleByDimName, function(r, n) { complexTypeProj.setDimDefaults(n, r.dimensionDefaults); }, this); }
[ "getDefaultRole( role ) {\n return store.getters.getDefaultRole( role );\n }", "applyDefault () {\n this.targetMorph[this.accessor] = PROP_CONFIG[this.selectedProp].defaultValue; // eslint-disable-line no-use-before-define\n }", "setDefaultDimensions(dimensions) {\n Logger_1.LOG(`Received default dimensions`, dimensions);\n this.defaultDimensions = dimensions;\n }", "_extendDefaults() {\n this._props = {\n ...this._defaults,\n ...this._o\n };\n }", "defaultRole () {\n if (this.roleId) {\n return ContributorRoleDefinitions.findOne(this.roleId)\n }\n }", "_applyConstraints(props) {\n // Ensure zoom is within specified range\n const {maxZoom, minZoom, zoom} = props;\n props.zoom = Object(math_gl__WEBPACK_IMPORTED_MODULE_0__[\"clamp\"])(zoom, minZoom, maxZoom);\n\n // Ensure pitch is within specified range\n const {maxPitch, minPitch, pitch} = props;\n props.pitch = Object(math_gl__WEBPACK_IMPORTED_MODULE_0__[\"clamp\"])(pitch, minPitch, maxPitch);\n\n Object.assign(props, Object(viewport_mercator_project__WEBPACK_IMPORTED_MODULE_3__[\"normalizeViewportProps\"])(props));\n\n return props;\n }", "setDefaultProps(props) {\n\t\tEntity.applyDefaultProps(Entity.defaults, props);\n\t}", "__applyDefaultProps(props, defaultProps) {\n for (let propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }", "_initOverrideProps() {\n const definitions = this._settings.schema.definitions;\n const overidesSchema = definitions.cssOverrides.properties;\n Object.keys(overidesSchema).forEach(key => {\n // override validation is against the CSS property in the description\n // field. Example: for key ui-font-family, .description is font-family\n this._overrideProps[key] = overidesSchema[key].description;\n });\n }", "_applyConstraints(props) {\n // Ensure zoom is within specified range\n const {maxZoom, minZoom, zoom} = props;\n props.zoom = zoom > maxZoom ? maxZoom : zoom;\n props.zoom = zoom < minZoom ? minZoom : zoom;\n\n return props;\n }", "constructor() {\n // Don't forget to call super for the inherited properties\n // set the new 'adminLevel' and 'role' properties\n }", "function initProperties() {\r\n // initialize the property behaviours\r\n jQuery('#size').val(defaultSize);\r\n sizeB = changeB(sizeE,'size');\r\n insertValueB(liftB(function(size){return size+'px'},sizeB),\r\n 'size-example','style','height');\r\n \r\n jQuery('#color').val(defaultColor);\r\n colorB = changeB(colorE,'color');\r\n insertValueB(colorB,'color-example','style','backgroundColor');\r\n \r\n jQuery('#fill').val(defaultFill);\r\n fillB = changeB(fillE,'fill');\r\n insertValueB(fillB,'fill-example','style','backgroundColor');\r\n \r\n my.sizeB = sizeB;\r\n my.colorB = colorB;\r\n my.fillB = fillB;\r\n }", "function adjustDefaultDimensions(){\n\tadjustOverlayDimensions();\n\tadjustDisplayDimensions();\n\tadjustDescriptionDisplaySettings();\n\tassignNavigationHoverHandlers();\n\tadjustTileHovers();\n\tclickingAllowed = true;\n}", "function createRoleConfig(role) {\n var roleConfig = {};\n roleConfig[\"cardinality\"] = role.getInverseRole().isMany() ? \"N\" : \"1\";\n var roleProviderConfig = {};\n if (bridgeEntity) {\n var bridgeRole = role === assoc.getRole1() ? bridgeEntity.getRole1() : bridgeEntity.getRole2();\n roleProviderConfig[\"websql.bridgeColumnName.\" + bridgeRole.getInverseEntity().getKeyAttribute().getName()] = bridgeRole.getForeignKeyName();\n } else {\n if (role.isForeignKey()) {\n roleProviderConfig[\"websql.collapsedSide\"] = true;\n roleProviderConfig[\"websql.columnName.\" + role.getInverseEntity().getKeyAttribute().getName()] = role.getForeignKeyName();\n }\n }\n roleConfig[\"provider\"] = roleProviderConfig;\n return roleConfig;\n }", "_populateFromDefaultConfig() {\n this._createDefaultServerURL();\n\n // Populate fields that can be cached.\n for (let prop in this.cachedConfigDefaults) {\n Object.defineProperty(this, prop, {\n get: this._cacheGet.bind(this, prop, this.cachedConfigDefaults[prop]),\n set: this._cacheSet.bind(this, prop)\n });\n }\n\n // Populate fields that won't be cached.\n Object.assign(this, this.configDefaults);\n }", "function getDefaultRoles() {\n\t\treturn DEFAULT_ROLES;\n\t}", "function getDefaultProps() {\n return {\n ...AreaSeries.defaultProps,\n areaStyle: {},\n markStyle: {}\n };\n}", "addDefaultPermisionRole() {\n this.handler.addPermission(`${core_1.Names.uniqueId(this)}:Permissions`, {\n principal: new iam.ServicePrincipal('apigateway.amazonaws.com'),\n sourceArn: this.authorizerArn,\n });\n }", "assignProperties() {\n this.assignComponentProperties(this.properties, ['name', 'value', 'unwind', 'required', 'readOnly', 'disabled']);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Example quadtree: 1011 0111 1010 0111 Binary String: 1011011110100111 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1001 1111 1001 1011 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0 0 1 1 0 0 1 1 0 1 1 Path: 0 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 00 01 02 03 .... .... .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 000 001 002 003 020 021 022 023 030 031 032 033
function quadtree(img, sRow, sCol, path, lvl, numOfCols, parent) { var isSame = true; var startColor = img[sRow][sCol]; var binStr = ""; var rows = sRow + numOfCols; var cols = sCol + numOfCols; for (var i = sRow; i < rows; i++) { for (var j = sCol; j < cols; j++) { var cellColor = img[i][j]; binStr += cellColor; if (startColor != cellColor) { isSame = false; } } } if (isSame) { addSiblings(parent); return { binStr: binStr, path: path, lvl: lvl, children: [], parent: parent, siblings: 0 }; } else { var child = { binStr: binStr, path: path, lvl: lvl, children: [], parent: parent, siblings: 0 }; addSiblings(parent); var halfCols = Math.floor(numOfCols / 2); lvl++; child.children.push(quadtree(img, sRow, sCol, path + "0", lvl, halfCols, child)); child.children.push(quadtree(img, sRow, halfCols, path + "1", lvl, halfCols, child)); child.children.push(quadtree(img, sRow + halfCols, sCol, path + "2", lvl, halfCols, child)); child.children.push(quadtree(img, sRow + halfCols, sRow + halfCols, path + "3", lvl, halfCols, child)); return child; } }
[ "function decodeTreeString(treeString, Theta, phi, headAngle, start, r) {\n let i = 0;\n let current = start;\n let vertices = []; // array of vertices to be returned\n while( i != treeString.length ) {\n // base cases -> F, +, -, &, *\n if( treeString[i] == \"F\" ) {\n vertices.push(current); // current\n // calculate next by spherical -> cartesian coordinates\n let nextX = current[0] + r * (Math.sin(toRadians(Theta)) * Math.cos(toRadians(phi)));\n let nextY = current[1] + r * (Math.sin(toRadians(Theta)) * Math.sin(toRadians(phi)));\n let nextZ = current[2] + r * Math.cos(toRadians(Theta));\n \n let next = vec3(nextX, nextY, nextZ);\n vertices.push(next); // next\n current = next; // move current position to end of new branch\n i += 1;\n } else if( treeString[i] == \"+\" ) {\n Theta += headAngle;\n i += 1;\n } else if( treeString[i] == \"-\" ) {\n Theta -= headAngle;\n i += 1;\n } else if( treeString[i] == \"*\" ) {\n phi += headAngle;\n i += 1;\n } else if( treeString[i] == \"&\" ) {\n phi -= headAngle;\n i += 1;\n } else if( treeString[i] == \"[\") {\n // string to be recursed on\n let recurseString = \"\";\n i += 1;\n let depth = 1;\n // exit loop once matching bracket is found\n while( depth != 0 ) {\n if( treeString[i] == \"[\" ) {\n depth += 1;\n } else if( treeString[i] == \"]\" ) {\n depth -= 1;\n }\n recurseString += treeString[i];\n i += 1; \n }\n // while loop leaves the trailing ']' bracket so \n // slice used to remove this last bracket to recurse on \n // interior string\n recurseString = recurseString.slice(0, -1);\n\n let recurseVertices = decodeTreeString(recurseString, Theta, phi, headAngle, current, r);\n // put together total vertices with vertices from recursion\n vertices = vertices.concat(recurseVertices);\n }\n }\n return vertices;\n}", "function QuadTree(x, y, w, h, options) {\n\n var maxc = 25\n var leafratio = 0.5\n if( options ) {\n if( typeof options.maxchildren == 'number' )\n if( options.maxchildren > 0 )\n maxc = options.maxchildren\n if( typeof options.leafratio == 'number' )\n if( options.leafratio >= 0 )\n leafratio = options.leafratio\n }\n\n // test for deep equality for x,y,width,height\n function isequal(o1, o2) {\n if( o1.x == o2.x &&\n o1.y == o2.y &&\n o1.width == o2.width &&\n o1.height == o2.height )\n return true\n return false\n }\n\n // create a new quadtree node\n function createnode(x, y, w, h) {\n return {\n x: x,\n y: y,\n width: w,\n height: h,\n c: [],\n l: [],\n n: []\n }\n }\n\n // root node used by this quadtree\n var root = createnode(x, y, w, h)\n\n // calculate distance between two points\n function distance(x1, y1, x2, y2) {\n return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))\n }\n\n // calculate distance between a point and a line (segment)\n function distancePL(x, y, x1, y1, dx1, dy1, len1 ) {\n if( !len1 ) // in case length is not provided, assume a line\n len1 = -1\n\n // x = x1 + s * dx1 + t * dy1\n // y = y1 + s * dy1 - t * dx1\n // x * dy1 - y * dx1 = x1 * dy1 - y1 * dx1 +\n // t * ( dy1 * dy1 + dx1 * dx1 )\n var t = dx1 * dx1 + dy1 * dy1\n if( t == 0 )\n return null\n else {\n t = ( x * dy1 - y * dx1 - x1 * dy1 + y1 * dx1 ) / t\n if( Math.abs(dx1) > Math.abs(dy1) )\n var s = ( x - x1 - t * dy1 ) / dx1\n else\n var s = ( y - y1 + t * dx1 ) / dy1\n if( ( s >= 0 && s <= len1 ) || len1 < 0 )\n return {\n s: s,\n t: t,\n x: x1 + s * dx1,\n y: y1 + s * dy1,\n dist: Math.abs(t)\n }\n else if( s < 0 ) {\n var dist = distance(x, y, x1, y1)\n return {\n s: s,\n dist: dist\n }\n } else {\n var dist = distance(x, y,\n x1 + len1*dx1,\n y1 + len1*dy1)\n return {\n s: s,\n dist: dist\n }\n }\n }\n }\n\n // does a line and a rectangle overlap ?\n function overlap_line(o1, o2, buf) {\n if( !o1 || !o2 )\n return true\n var dist = distancePL(o2.x + 0.5 * o2.width,\n o2.y + 0.5 * o2.height,\n o1.x, o1.y, o1.dx, o1.dy, o1.dist)\n if( dist ) {\n dist.dist -= buf\n if( dist.dist < 0 )\n return true\n if( dist.dist * dist.dist <= o2.width * o2.width + o2.height * o2.height )\n return true\n }\n return false\n }\n\n // do two rectangles overlap ?\n function overlap_rect(o1, o2, buf) {\n if( !o1 || !o2 )\n return true\n if( o1.x + o1.width < o2.x - buf ||\n o1.y + o1.height < o2.y - buf ||\n o1.x - buf > o2.x + o2.width ||\n o1.y - buf > o2.y + o2.height )\n return false\n return true\n }\n\n function isleaf(node, obj) {\n\n var leaf = false\n if( obj.width * obj.height > node.width * node.height * leafratio )\n leaf = true\n\n if( obj.x < node.x ||\n obj.y < node.y ||\n obj.x + obj.width > node.x + node.width ||\n obj.y + obj.height > node.y + node.height )\n leaf = true\n\n var childnode = null\n for( var ni = 0; ni < node.n.length; ni++ )\n if( overlap_rect(obj, node.n[ni], 0) ) {\n if( childnode ) { // multiple hits\n leaf = true\n break\n } else\n childnode = node.n[ni]\n }\n\n return { leaf: leaf,\n childnode: childnode }\n }\n\n // put an object to one of the child nodes of this node\n function put_to_nodes(node, obj) {\n var leaf = isleaf(node, obj)\n if( leaf.leaf )\n node.l.push(obj)\n else if( leaf.childnode )\n put(leaf.childnode, obj)\n else\n return\n }\n\n function update_coords(obj, updatedcoords) {\n obj.x = ((typeof updatedcoords.x == 'number') ? updatedcoords.x : obj.x)\n obj.y = ((typeof updatedcoords.y == 'number') ? updatedcoords.y : obj.y)\n obj.width = ((typeof updatedcoords.width == 'number') ? updatedcoords.width : obj.width)\n obj.height = ((typeof updatedcoords.height == 'number') ? updatedcoords.height : obj.height)\n }\n\n function update(node, obj, attr, updatedcoords) {\n if( typeof attr == 'object' && typeof updatedcoords == 'undefined' ) {\n updatedcoords = attr\n attr = false\n }\n\n if( typeof updatedcoords == 'undefined' )\n return false\n\n if( !attr )\n attr = false\n else if( typeof attr != 'string' )\n attr = 'id'\n\n var count = 0\n for( var ci = 0; ci < node.c.length; ci++ )\n if( ( attr && node.c[ci][attr] == obj[attr] ) ||\n ( !attr && isequal(node.c[ci], obj) ) ) {\n\n // found the object to be updated\n var orig = node.c[ci]\n update_coords(orig, updatedcoords)\n\n if( orig.x > node.x + node.width ||\n orig.y > node.y + node.height ||\n orig.x + orig.width < node.x ||\n orig.y + orig.height < node.y ) {\n\n // this object needs to be removed and added\n removeItems(node.c, ci, 1)\n put(root, orig)\n } // updated object is still inside same node\n\n return true\n }\n\n for( var ci = 0; ci < node.l.length; ci++ )\n if( ( attr && node.l[ci][attr] == obj[attr] ) ||\n ( !attr && isequal(node.l[ci], obj) ) ) {\n\n var orig = node.l[ci]\n update_coords(orig, updatedcoords)\n\n // found the object to be updated\n if( orig.x > node.x + node.width ||\n orig.y > node.y + node.height ||\n orig.x + orig.width < node.x ||\n orig.y + orig.height < node.y ) {\n\n // this object needs to be removed and added\n removeItems(node.l, ci, 1)\n put(root, orig)\n } // updated object is still inside same node\n\n return true\n }\n\n var leaf = isleaf(node, obj)\n if( !leaf.leaf && leaf.childnode )\n if( update(leaf.childnode, obj, attr) )\n return true\n return false\n }\n\n // remove an object from this node\n function remove(node, obj, attr) {\n if( !attr )\n attr = false\n else if( typeof attr != 'string' )\n attr = 'id'\n\n var count = 0\n for( var ci = 0; ci < node.c.length; ci++ )\n if( ( attr && node.c[ci][attr] == obj[attr] ) ||\n ( !attr && isequal(node.c[ci], obj) ) ) {\n count++\n removeItems(node.c, ci, 1)\n ci--\n }\n\n for( var ci = 0; ci < node.l.length; ci++ )\n if( ( attr && node.l[ci][attr] == obj[attr] ) ||\n ( !attr && isequal(node.l[ci], obj) ) ) {\n count++\n removeItems(node.l, ci, 1)\n ci--\n }\n\n var leaf = isleaf(node, obj)\n if( !leaf.leaf && leaf.childnode )\n return count + remove(leaf.childnode, obj, attr)\n return count\n }\n\n // put an object to this node\n function put(node, obj) {\n\n if( node.n.length == 0 ) {\n node.c.push(obj)\n\n // subdivide\n if( node.c.length > maxc ) {\n var w2 = node.width / 2\n var h2 = node.height / 2\n node.n.push(createnode(node.x, node.y, w2, h2),\n createnode(node.x + w2, node.y, w2, h2),\n createnode(node.x, node.y + h2, w2, h2),\n createnode(node.x + w2, node.y + h2, w2, h2))\n for( var ci = 0; ci < node.c.length; ci++ )\n put_to_nodes(node, node.c[ci])\n node.c = []\n }\n } else\n put_to_nodes(node, obj)\n }\n\n // iterate through all objects in this node matching given overlap\n // function\n function getter(overlapfun, node, obj, buf, strict, callbackOrArray) {\n for( var li = 0; li < node.l.length; li++ )\n if( !strict || overlapfun(obj, node.l[li], buf) )\n if( typeof callbackOrArray == 'object' )\n callbackOrArray.push(node.l[li])\n else if( !callbackOrArray(node.l[li]) )\n return false\n for( var li = 0; li < node.c.length; li++ )\n if( !strict || overlapfun(obj, node.c[li], buf) )\n if( typeof callbackOrArray == 'object' )\n callbackOrArray.push(node.c[li])\n else if( !callbackOrArray(node.c[li]) )\n return false\n for( var ni = 0; ni < node.n.length; ni++ ) {\n if( overlapfun(obj, node.n[ni], buf) ) {\n if( typeof callbackOrArray == 'object' )\n callbackOrArray.concat(getter(overlapfun, node.n[ni], obj, buf, strict, callbackOrArray))\n else if( !getter(overlapfun, node.n[ni], obj, buf, strict, callbackOrArray) )\n return false\n }\n }\n return true\n }\n\n // iterate through all objects in this node matching the given rectangle\n function get_rect(node, obj, buf, callbackOrArray) {\n return getter(overlap_rect, node, obj, buf, true, callbackOrArray)\n }\n\n // iterate through all objects in this node matching the given\n // line (segment)\n function get_line(node, obj, buf, callbackOrArray) {\n return getter(overlap_line, node, obj, buf, false, callbackOrArray)\n }\n\n // iterate through all objects in this node matching given\n // geometry, either a rectangle or a line segment\n function get(node, obj, buf, callbackOrArray) {\n if( (typeof buf == 'function' || typeof buf == 'object') && typeof callbackOrArray == 'undefined' ) {\n callbackOrArray = buf\n buf = 0\n }\n if( typeof callbackOrArray == 'undefined' ) {\n callbackOrArray = []\n buf = 0\n }\n if( obj == null )\n get_rect(node, obj, buf, callbackOrArray)\n else if( typeof obj.x == 'number' &&\n typeof obj.y == 'number' &&\n !isNaN(obj.x) && !isNaN(obj.y) ) {\n if( typeof obj.dx == 'number' &&\n typeof obj.dy == 'number' &&\n !isNaN(obj.dx) && !isNaN(obj.dy) )\n get_line(node, obj, buf, callbackOrArray)\n else if( typeof obj.width == 'number' &&\n typeof obj.height == 'number' &&\n !isNaN(obj.width) && !isNaN(obj.height) )\n get_rect(node, obj, buf, callbackOrArray)\n }\n if( typeof callbackOrArray == 'object' )\n return callbackOrArray\n }\n\n // return the object interface\n return {\n get: function(obj, buf, callbackOrArray) {\n return get(root, obj, buf, callbackOrArray)\n },\n put: function(obj) {\n put(root, obj)\n },\n update: function(obj, attr, updatedcoords) {\n return update(root, obj, attr, updatedcoords)\n },\n remove: function(obj, attr) {\n return remove(root, obj, attr)\n },\n clear: function() {\n root = createnode(x, y, w, h)\n }\n }\n}", "split() {\n // Bitwise or [html5rocks]\n let subWidth = this.bounds.width / 2;\n let subHeight = this.bounds.height / 2;\n\n this.nodes[0] = QuadTree(\n 0,\n {\n x: this.bounds.x + subWidth,\n y: this.bounds.y,\n width: subWidth,\n height: subHeight,\n },\n level + 1\n );\n\n this.nodes[1] = QuadTree(\n 0,\n {\n x: this.bounds.x,\n y: this.bounds.y,\n width: subWidth,\n height: subHeight,\n },\n level + 1\n );\n\n this.nodes[2] = QuadTree(\n 0,\n {\n x: this.bounds.x,\n y: this.bounds.y + subHeight,\n width: subWidth,\n height: subHeight,\n },\n level + 1\n );\n\n this.nodes[3] = QuadTree(\n 0,\n {\n x: this.bounds.x + subWidth,\n y: this.bounds.y + subHeight,\n width: subWidth,\n height: subHeight,\n },\n level + 1\n );\n }", "function calcTree() {\n // resets the treeVertices array each time a new tree is calculated\n treeVertices = [];\n let treeString = createTreeString(\"F\", n);\n treeVertices = decodeTreeString(treeString, Theta, phi, headAngle, vec3(0,0,0), r);\n \n // finds the farthest away point/vertex and scales\n // the tree to fit on the canvas\n let vMax = 0;\n for( let i = 0; i < treeVertices.length; i++ ) {\n vMax = Math.max(vMax, findLength(treeVertices[i]))\n }\n vMax /= 1.6\n for( let j = 0; j < treeVertices.length; j++ ) {\n treeVertices[j] = vec3(\n treeVertices[j][0] / vMax,\n treeVertices[j][1] / vMax - 0.9,\n treeVertices[j][2] / vMax\n );\n }\n\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, flatten(treeVertices));\n}", "function quads() {\n var boxes = [];\n\n function processNode(node, extent, depth) {\n if (Array.isArray(node)) {\n processSplit(node, extent, depth);\n }\n }\n\n function processSplit(node, extent, depth) {\n var lo = extent[0],\n hi = extent[1],\n mp = [lo[0] + hi[0] >> 1, lo[1] + hi[1] >> 1];\n\n var e = [[lo, mp], [[mp[0], lo[1]], [hi[0], mp[1]]], [[lo[0], mp[1]], [mp[0], hi[1]]], [mp, hi]];\n for (var i = 0; i < 4; ++i) {\n boxes.push(e[i]);\n e[i].depth = depth;\n if (node[i]) processNode(node[i], e[i], depth + 1);\n }\n }\n\n if (quad.root()) {\n // add quadtree root extents\n boxes.push(quad.extent().slice());\n // recurse to process quadtree content\n processNode(quad.root(), quad.extent(), 1);\n }\n\n qg.html('').selectAll('rect').data(boxes).enter().append('rect').attr('x', function (q) {\n return q[0][0] + 0.5;\n }).attr('y', function (q) {\n return q[0][1] + 0.5;\n }).attr('width', function (q) {\n return q[1][0] - q[0][0];\n }).attr('height', function (q) {\n return q[1][1] - q[0][1];\n }).style('fill', 'none').style('stroke', '#ddd').style('line-width', 0.5);\n\n return obj;\n }", "function QuadTree(x, y, w, h, options) {\n\t\n\t if( typeof x != 'number' || isNaN(x) )\n\t x = 0;\n\t if( typeof y != 'number' || isNaN(y) )\n\t y = 0;\n\t if( typeof w != 'number' || isNaN(w) )\n\t w = 10;\n\t if( typeof h != 'number' || isNaN(h) )\n\t h = 10;\n\t \n\t var maxc = 25;\n\t var leafratio = 0.5;\n\t if( options ) {\n\t if( typeof options.maxchildren == 'number' )\n\t if( options.maxchildren > 0 )\n\t maxc = options.maxchildren;\n\t if( typeof options.leafratio == 'number' )\n\t if( options.leafratio >= 0 )\n\t leafratio = options.leafratio;\n\t }\n\t\n\t // validate an input object\n\t function validate(obj) {\n\t if( !obj )\n\t return false;\n\t if( typeof obj.x != 'number' ||\n\t typeof obj.y != 'number' ||\n\t typeof obj.w != 'number' ||\n\t typeof obj.h != 'number' )\n\t return false;\n\t if( isNaN(obj.x) || isNaN(obj.y) ||\n\t isNaN(obj.w) || isNaN(obj.h) )\n\t return false;\n\t if( obj.w < 0 || obj.h < 0 )\n\t return false;\n\t return true;\n\t }\n\t\n\t // test for deep equality for x,y,w,h\n\t function isequal(o1, o2) {\n\t if( o1.x == o2.x &&\n\t o1.y == o2.y &&\n\t o1.w == o2.w &&\n\t o1.h == o2.h )\n\t return true;\n\t return false;\n\t }\n\t\n\t // create a new quadtree node\n\t function createnode(x, y, w, h) {\n\t return {\n\t x: x,\n\t y: y,\n\t w: w,\n\t h: h,\n\t c: [],\n\t l: [],\n\t n: []\n\t }\n\t }\n\t\n\t // root node used by this quadtree\n\t var root = createnode(x, y, w, h);\n\t\n\t // calculate distance between two points\n\t function distance(x1, y1, x2, y2) {\n\t return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));\n\t }\n\t \n\t // calculate distance between a point and a line (segment)\n\t function distancePL(x, y, x1, y1, dx1, dy1, len1 ) {\n\t if( !len1 ) // in case length is not provided, assume a line \n\t len1 = -1;\n\t \n\t // x = x1 + s * dx1 + t * dy1\n\t // y = y1 + s * dy1 - t * dx1\n\t // x * dy1 - y * dx1 = x1 * dy1 - y1 * dx1 + \n\t // t * ( dy1 * dy1 + dx1 * dx1 )\n\t var t = dx1 * dx1 + dy1 * dy1;\n\t if( t == 0 )\n\t return null;\n\t else {\n\t t = ( x * dy1 - y * dx1 - x1 * dy1 + y1 * dx1 ) / t;\n\t if( Math.abs(dx1) > Math.abs(dy1) )\n\t var s = ( x - x1 - t * dy1 ) / dx1;\n\t else\n\t var s = ( y - y1 + t * dx1 ) / dy1;\n\t if( ( s >= 0 && s <= len1 ) || len1 < 0 )\n\t return {\n\t s: s,\n\t t: t,\n\t x: x1 + s * dx1,\n\t y: y1 + s * dy1,\n\t dist: Math.abs(t)\n\t };\n\t else if( s < 0 ) { \n\t var dist = distance(x, y, x1, y1);\n\t return {\n\t s: s,\n\t dist: dist\n\t };\n\t } else {\n\t var dist = distance(x, y,\n\t x1 + len1*dx1, \n\t y1 + len1*dy1);\n\t return {\n\t s: s,\n\t dist: dist\n\t };\n\t }\n\t }\n\t }\n\t \n\t // does a line and a rectangle overlap ?\n\t function overlap_line(o1, o2, buf) {\n\t if( !o1 || !o2 )\n\t return true;\n\t var dist = distancePL(o2.x + 0.5 * o2.w,\n\t o2.y + 0.5 * o2.h,\n\t o1.x, o1.y, o1.dx, o1.dy, o1.dist);\n\t if( dist ) {\n\t dist.dist -= buf;\n\t if( dist.dist < 0 )\n\t return true;\n\t if( dist.dist * dist.dist <= o2.w * o2.w + o2.h * o2.h )\n\t return true;\n\t }\n\t return false;\n\t }\n\t\n\t // do two rectangles overlap ?\n\t function overlap_rect(o1, o2, buf) {\n\t if( !o1 || !o2 )\n\t return true;\n\t if( o1.x + o1.w < o2.x - buf ||\n\t o1.y + o1.h < o2.y - buf ||\n\t o1.x - buf > o2.x + o2.w ||\n\t o1.y - buf > o2.y + o2.h )\n\t return false;\n\t return true;\n\t }\n\t\n\t function isleaf(node, obj) {\n\t\n\t var leaf = false;\n\t if( obj.w * obj.h > node.w * node.h * leafratio )\n\t leaf = true;\n\t\n\t if( obj.x < node.x ||\n\t obj.y < node.y ||\n\t obj.x + obj.w > node.x + node.w ||\n\t obj.y + obj.h > node.y + node.h )\n\t leaf = true;\n\t\n\t var childnode = null;\n\t for( var ni = 0; ni < node.n.length; ni++ )\n\t if( overlap_rect(obj, node.n[ni], 0) ) {\n\t if( childnode ) { // multiple hits\n\t leaf = true;\n\t break;\n\t } else\n\t childnode = node.n[ni];\n\t }\n\t \n\t return { leaf: leaf,\n\t childnode: childnode };\n\t }\n\t\n\t // put an object to one of the child nodes of this node\n\t function put_to_nodes(node, obj) {\n\t var leaf = isleaf(node, obj);\n\t if( leaf.leaf )\n\t node.l.push(obj);\n\t else if( leaf.childnode )\n\t put(leaf.childnode, obj);\n\t else\n\t return;\n\t }\n\t \n\t function update_coords(obj, updatedcoords) {\n\t obj.x = ((typeof updatedcoords.x == 'number') ? updatedcoords.x : obj.x);\n\t obj.y = ((typeof updatedcoords.y == 'number') ? updatedcoords.y : obj.y);\n\t obj.w = ((typeof updatedcoords.w == 'number') ? updatedcoords.w : obj.w);\n\t obj.h = ((typeof updatedcoords.h == 'number') ? updatedcoords.h : obj.h);\n\t }\n\t\n\t function update(node, obj, attr, updatedcoords) {\n\t if( typeof attr == 'object' && typeof updatedcoords == 'undefined' ) {\n\t updatedcoords = attr;\n\t attr = false;\n\t }\n\t\n\t if( !validate(obj) || typeof updatedcoords == 'undefined' )\n\t return false;\n\t\n\t if( !attr )\n\t attr = false;\n\t else if( typeof attr != 'string' )\n\t attr = 'id';\n\t\n\t var count = 0;\n\t for( var ci = 0; ci < node.c.length; ci++ )\n\t if( ( attr && node.c[ci][attr] == obj[attr] ) ||\n\t ( !attr && isequal(node.c[ci], obj) ) ) {\n\t\n\t // found the object to be updated\n\t var orig = node.c[ci];\n\t update_coords(orig, updatedcoords);\n\t \n\t if( orig.x > node.x + node.w ||\n\t orig.y > node.y + node.h ||\n\t orig.x + orig.w < node.x ||\n\t orig.y + orig.h < node.y ) {\n\t\n\t // this object needs to be removed and added\n\t node.c.splice(ci, 1);\n\t put(root, orig);\n\t } // updated object is still inside same node\n\t \n\t return true;\n\t }\n\t \n\t for( var ci = 0; ci < node.l.length; ci++ )\n\t if( ( attr && node.l[ci][attr] == obj[attr] ) ||\n\t ( !attr && isequal(node.l[ci], obj) ) ) {\n\t \n\t var orig = node.l[ci];\n\t update_coords(orig, updatedcoords);\n\t \n\t // found the object to be updated\n\t if( orig.x > node.x + node.w ||\n\t orig.y > node.y + node.h ||\n\t orig.x + orig.w < node.x ||\n\t orig.y + orig.h < node.y ) {\n\t\n\t // this object needs to be removed and added \n\t node.l.splice(ci, 1);\n\t put(root, orig);\n\t } // updated object is still inside same node\n\t \n\t return true;\n\t }\n\t\n\t var leaf = isleaf(node, obj);\n\t if( !leaf.leaf && leaf.childnode )\n\t if( update(leaf.childnode, obj, attr) )\n\t return true;\n\t return false;\n\t }\n\t\n\t // remove an object from this node\n\t function remove(node, obj, attr) {\n\t if( !validate(obj) )\n\t return 0;\n\t\n\t if( !attr )\n\t attr = false;\n\t else if( typeof attr != 'string' )\n\t attr = 'id';\n\t\n\t var count = 0;\n\t for( var ci = 0; ci < node.c.length; ci++ )\n\t if( ( attr && node.c[ci][attr] == obj[attr] ) ||\n\t ( !attr && isequal(node.c[ci], obj) ) ) {\n\t count++;\n\t node.c.splice(ci, 1);\n\t ci--;\n\t }\n\t\n\t for( var ci = 0; ci < node.l.length; ci++ )\n\t if( ( attr && node.l[ci][attr] == obj[attr] ) ||\n\t ( !attr && isequal(node.l[ci], obj) ) ) {\n\t count++;\n\t node.l.splice(ci, 1);\n\t ci--;\n\t }\n\t\n\t var leaf = isleaf(node, obj);\n\t if( !leaf.leaf && leaf.childnode )\n\t return count + remove(leaf.childnode, obj, attr);\n\t return count;\n\t }\n\t\n\t // put an object to this node\n\t function put(node, obj) {\n\t\n\t if( !validate(obj) )\n\t return;\n\t\n\t if( node.n.length == 0 ) {\n\t node.c.push(obj);\n\t \n\t // subdivide\n\t if( node.c.length > maxc ) {\n\t var w2 = node.w / 2;\n\t var h2 = node.h / 2;\n\t node.n.push(createnode(node.x, node.y, w2, h2),\n\t createnode(node.x + w2, node.y, w2, h2),\n\t createnode(node.x, node.y + h2, w2, h2),\n\t createnode(node.x + w2, node.y + h2, w2, h2));\n\t for( var ci = 0; ci < node.c.length; ci++ ) \n\t put_to_nodes(node, node.c[ci]);\n\t node.c = [];\n\t }\n\t } else \n\t put_to_nodes(node, obj);\n\t }\n\t\n\t // iterate through all objects in this node matching given overlap\n\t // function\n\t function getter(overlapfun, node, obj, buf, strict, callbackOrArray) {\n\t for( var li = 0; li < node.l.length; li++ )\n\t if( !strict || overlapfun(obj, node.l[li], buf) )\n\t if( typeof callbackOrArray == 'object' )\n\t callbackOrArray.push(node.l[li]);\n\t else if( !callbackOrArray(node.l[li]) )\n\t return false;\n\t for( var li = 0; li < node.c.length; li++ )\n\t if( !strict || overlapfun(obj, node.c[li], buf) )\n\t if( typeof callbackOrArray == 'object' )\n\t callbackOrArray.push(node.c[li]);\n\t else if( !callbackOrArray(node.c[li]) )\n\t return false;\n\t for( var ni = 0; ni < node.n.length; ni++ ) {\n\t if( overlapfun(obj, node.n[ni], buf) ) {\n\t if( typeof callbackOrArray == 'object' )\n\t callbackOrArray.concat(getter(overlapfun, node.n[ni], obj, buf, strict, callbackOrArray));\n\t else if( !getter(overlapfun, node.n[ni], obj, buf, strict, callbackOrArray) )\n\t return false;\n\t }\n\t }\n\t return true;\n\t }\n\t\n\t // iterate through all objects in this node matching the given rectangle\n\t function get_rect(node, obj, buf, callbackOrArray) {\n\t return getter(overlap_rect, node, obj, buf, true, callbackOrArray);\n\t }\n\t\n\t // iterate through all objects in this node matching the given\n\t // line (segment)\n\t function get_line(node, obj, buf, callbackOrArray) {\n\t return getter(overlap_line, node, obj, buf, false, callbackOrArray);\n\t }\n\t\n\t // iterate through all objects in this node matching given\n\t // geometry, either a rectangle or a line segment\n\t function get(node, obj, buf, callbackOrArray) {\n\t\n\t if( (typeof buf == 'function' || typeof buf == 'object') && typeof callbackOrArray == 'undefined' ) {\n\t callbackOrArray = buf;\n\t buf = 0;\n\t }\n\t if( typeof callbackOrArray == 'undefined' ) {\n\t callbackOrArray = [];\n\t buf = 0;\n\t }\n\t if( obj == null )\n\t get_rect(node, obj, buf, callbackOrArray);\n\t else if( typeof obj.x == 'number' &&\n\t typeof obj.y == 'number' &&\n\t !isNaN(obj.x) && !isNaN(obj.y) ) {\n\t if( typeof obj.dx == 'number' &&\n\t typeof obj.dy == 'number' &&\n\t !isNaN(obj.dx) && !isNaN(obj.dy) )\n\t get_line(node, obj, buf, callbackOrArray);\n\t else if( typeof obj.w == 'number' &&\n\t typeof obj.h == 'number' &&\n\t !isNaN(obj.w) && !isNaN(obj.h) )\n\t get_rect(node, obj, buf, callbackOrArray);\n\t }\n\t if( typeof callbackOrArray == 'object' ) \n\t return callbackOrArray;\n\t }\n\t\n\t // return the object interface\n\t return {\n\t get: function(obj, buf, callbackOrArray) {\n\t return get(root, obj, buf, callbackOrArray);\n\t },\n\t put: function(obj) {\n\t put(root, obj);\n\t },\n\t update: function(obj, attr, updatedcoords) {\n\t return update(root, obj, attr, updatedcoords);\n\t },\n\t remove: function(obj, attr) {\n\t return remove(root, obj, attr);\n\t },\n\t clear: function() {\n\t root = createnode(x, y, w, h);\n\t },\n\t stringify: function() {\n\t var strobj = {\n\t x: x, y: y, w: w, h: h,\n\t maxc: maxc, \n\t leafratio: leafratio,\n\t root: root\n\t };\n\t try {\n\t return JSON.stringify(strobj);\n\t } catch(err) {\n\t // could not stringify\n\t // probably due to objects included in qtree being non-stringifiable\n\t return null; \n\t }\n\t },\n\t parse: function(str) {\n\t if( typeof str == 'string' )\n\t str = JSON.parse(str);\n\t \n\t x = str.x;\n\t y = str.y;\n\t w = str.w;\n\t h = str.h;\n\t maxc = str.maxc;\n\t leafratio = str.leafratio;\n\t root = str.root;\n\t }\n\t };\n\t}", "function QuadTree (points) {\n this.root = null;\n this.size = 0;\n if(points == null || points.length == 0)\n return;\n points.sort(function(p,q) {\n if(p.getPosition().lat() < q.getPosition().lat()) return -1;\n if(p.getPosition().lat() > q.getPosition().lat()) return 1;\n if(p.getPosition().lng() > q.getPosition().lng()) return -1;\n if(p.getPosition().lng() < q.getPosition().lng()) return 1;\n return 0;\n }); \n var depth = 0;\n while(this.bstIterate(points, 0, points.length, depth)) \n \tdepth++;\n \n}", "function QuadTree(data) {\n var i, cols;\n\n /* do some input checking */\n if (!data)\n throw new Error('data is required');\n\n if (!Array.isArray(data) ||\n !Array.isArray(data[0]))\n throw new Error('data must be scalar field, i.e. array of arrays');\n\n if (data.length < 2)\n throw new Error('data must contain at least two rows');\n\n /* check if we've got a regular grid */\n cols = data[0].length;\n\n if (cols < 2)\n throw new Error('data must contain at least two columns');\n\n for (i = 1; i < data.length; i++) {\n if (!Array.isArray(data[i]))\n throw new Error('Row ' + i + ' is not an array');\n\n if (data[i].length != cols)\n throw new Error('unequal row lengths detected, please provide a regular grid');\n }\n\n /* create pre-processing object */\n this.data = data;\n /* root node, i.e. entry to the data */\n this.root = new TreeNode(data, 0, 0, data[0].length - 1, data.length - 1);\n }", "function Tree(h,edgeStr,internalStr){\n\n buf=new Array(h);\n var n_X,n_space,i,tree=\"\";\n buf=[h];\n n_X=1; \n n_space=h-2;\n buf[0]=\"\\xa0\".repeat(n_space)+edgeStr+\"<br>\";\n for(i=1;i<h;i++){\n buf[i]=\"\\xa0\".repeat(n_space) + internalStr.repeat(n_X)+\"<br>\";\n n_X=n_X+2;\n n_space-=1;\n }\n for(i=0;i<h;i++){\n tree+=buf[i];\n }\n console.log(tree.replace(/<br>/g,\"\\n\"));\n document.getElementById(\"demo\").innerHTML=\"<span style=\\\"color:green;font-size: 1em; font-family:'Courier New', Courier, mono;\\\">\"+tree+\"<\\/span>\";\n}", "function QuadTree(x, y, size, level, father){\n //x y is from top-left point of the square\n //size is both length and height since all \n //trees are square\n //vars\n this.x = x;\n this.y = y;\n this.size = size;\n this.level = level + 1 || 0;\n this.max = 3;\n this.objects = [];\n this.father = father;\n //methods\n this.splitRegion = function(){\n //counterclockwise, top-right is i\n this.nodes = [new QuadTree(this.x + this.size / 2, this.y, this.size / 2, this.level, this),\n new QuadTree(this.x, this.y, this.size / 2, this.level, this),\n new QuadTree(this.x, this.y + this.size / 2, this.size / 2, this.level, this),\n new QuadTree(this.x + this.size / 2, this.y + this.size / 2, this.size / 2, this.level, this)\n ];\n return this.nodes;\n };\n this.deleteRegion = function(){\n //actually delete all sub-region of father\n delete this.nodes;\n };\n this.sortRegion = function(object){\n //check if object is object\n if (typeof(object) !== \"object\"){\n return \"nil\";\n }\n //get one of the region i ii iii iv from x,y \n //return accordingly, 0 1 2 3\n //halfpoint of quadtree, both x and y\n let halfPoint = x + size / 2;\n //check collision\n let colliXAxis = collisionRectLine(object, 0, halfPoint, canvasSize, halfPoint);\n let colliYAxis = collisionRectLine(object, halfPoint, 0, halfPoint, canvasSize);\n if (colliXAxis || colliYAxis){\n return 'both';\n }\n //check if object x is more than halfpoint\n if (object.x > halfPoint){\n //check if y is larger than halfpoint\n if (object.y > halfPoint){\n //if so, belong to iv\n return 3;\n }else{//if y is not larger than halfpoint\n //if y plus height is larget than halfpoint\n if (object.y + object.height > halfPoint){\n //belongs to both i and iv\n return \"both\";\n }else{//else, belongs to i\n return 0;\n }\n }\n }else{//x is less than halfpoint\n //check if length cross the halfpoint\n if (object.x + object.length > halfPoint){\n //if so, it belongs to both\n return \"both\";\n }else{//if doesn't cross halfpoint\n //check if y larger than halfpoint\n if (object.y > halfPoint){\n //if so, belongs to iii\n return 2;\n }else{//y is not larget than halfpoint\n //check if y and height is larger than half point\n if (object.y + object.height > halfPoint){\n //belongs to both ii and iii\n return \"both\";\n }else {//not crossing halfpoint at all\n //belongs to ii\n return 1;\n }\n }\n }\n }\n };\n //add object into tree\n this.addObject = function(object, region){\n //default region\n if (!region){\n region = this;\n }\n let obj = object;\n let end = false;\n //looping through stems to find a region to fit in\n while(end === false){\n //get location\n let location = region.sortRegion(obj);\n //check if obj can be sort into a location\n if (typeof(location) === \"number\"){\n //if so, then find the next location/region\n //if smaller region exist\n if (region.nodes){\n region = region.nodes[location];\n }else{//smaller region doesn't exist\n //end the while loop\n end = true;\n }\n }else{//if not, then push it into the array\n //end the while loop\n end = true;\n }\n //if match found\n if (end === true){\n //push into this region\n region.objects.push(obj);\n obj.stem = region;\n //check if region is overflowing max # of objects\n if (region.objects.length > region.max){\n //split region\n region.splitRegion();\n //store and clear region objects\n let objArr = region.objects;\n region.objects = [];\n //loop through the objs\n for (let ii = 0; ii < objArr.length; ii ++){\n let obj = objArr[ii];\n let loc = region.sortRegion(obj);\n if (loc === \"both\"){//if both region\n //push to this region\n region.objects.push(obj);\n obj.stem = region;\n }else{\n //push to corresponding subregion\n region.nodes[loc].objects.push(obj);\n obj.stem = region.nodes[loc];\n }\n }\n }\n }\n }\n };\n //separate into 4 regions if primal\n if (this.level === 0){\n this.splitRegion();\n //update objects in region method\n this.addAllObject = function(collector){\n //clear objects first\n this.clearObject();\n //collect all the objects\n collector = collector || folder;\n let objList = collector.getAll();\n //loop throught all the objects\n for(let i = 0; i < objList.length; i ++){\n let obj = objList[i];\n let region = this;\n region.addObject(obj, region);\n }\n };\n this.clearObject = function(){\n //clean up everything in this object\n this.deleteRegion();\n this.splitRegion();\n this.objects = [];\n };\n }\n}", "function buildTreeFromStringArr(stringArr = []) {\n const binaryTree = new BinaryTree();\n\n const root = parseArg([...stringArr].shift().trim());\n\n if (root === NaN || root === '') return binaryTree;\n const lines = [...stringArr];\n\n binaryTree.addRoot(root);\n\n while (lines.length > 0) {\n const valueString = lines.shift();\n\n const values = valueString.trim().split(/\\s+/)\n .map((val) => {\n return { value: parseArg(val), idx: valueString.indexOf(val) };\n });\n\n const connections = lines.shift();\n\n const leaves = lines[0];\n\n if (connections) {\n for (let i = 0; i < values.length; i++) {\n const node = binaryTree.findNode(values[i].value);\n\n const leftBound = i === 0 ? 0: values[i - 1].idx + 1;\n\n const rightBound = i === values.length - 1 ?\n leaves.length :\n values[i + 1]?.idx + 1;\n const connectionRange = connections.slice(leftBound, rightBound);\n\n const leftIdx = connectionRange.indexOf('/');\n\n const rightIdx = connectionRange.indexOf('\\\\');\n\n const left = leftIdx !== -1 && leftIdx < values[i].idx;\n\n const right = rightIdx !== -1 && rightIdx > values[i].idx;\n\n if (left) {\n const range = leaves.slice(leftBound, values[i].idx);\n\n const leaf = parseArg(range.trim());\n\n node.addLeft(leaf);\n }\n\n if (right) {\n const range = leaves.slice(values[i].idx + 1, rightBound);\n\n const leaf = parseArg(range.trim());\n\n node.addRight(leaf);\n }\n }\n }\n }\n return binaryTree;\n}", "function makeTree(node, triangle){\n //first we need to check if there are children or not at this node level\n if (node.hasChildren === false ){//&& node.leafNode === false) {\n //if this is false, we know we have to split it up into 8 octants\n //the new length of the line segment will be half as long as the current\n //1 goes to .5, .5 goes to .25, etc\n var childLength = node.length * .5;\n /*\n the min values represent the lowest bound of the new octant\n each dimension will be split between\n node.minX to node.minX + childlength\n and\n node.minX + childlength to node.maxX\n\n The 8 child nodes are created to reflect the 8 different octant cases:\n */\n node.children.push(new Node(node.currentDepth, childLength, node.xMin, node.xMin + childLength, node.yMin, node.yMin + childLength, node.zMin, node.zMin + childLength)); //0x to 0y to 0z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin, node.xMin + childLength, node.yMin, node.yMin + childLength, node.zMin + childLength, node.zMax)); //0x to 0y to .5z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin, node.xMin + childLength, node.yMin + childLength, node.yMax, node.zMin, node.zMin + childLength)); //0x to .5y to 0z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin, node.xMin + childLength, node.yMin + childLength, node.yMax, node.zMin + childLength, node.zMax)); //0x to .5y to .5z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin + childLength, node.xMax, node.yMin, node.yMin + childLength, node.zMin, node.zMin + childLength)); //.5x to 0y to 0z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin + childLength, node.xMax, node.yMin, node.yMin + childLength, node.zMin + childLength, node.zMax)); //.5x to 0y to .5z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin + childLength, node.xMax, node.yMin + childLength, node.yMax, node.zMin, node.zMin + childLength)); //.5x to .5y to 0z\n node.children.push(new Node(node.currentDepth, childLength, node.xMin + childLength, node.xMax, node.yMin + childLength, node.yMax, node.zMin + childLength, node.zMax)); //.5x to .5y to .5z\n node.hasChildren = true;\n }\n\n //by now, the current node has children created or it is determined that the node in question already has children\n //we can now check them all to see which ones the triangle falls into\n var xOverlap;\n var yOverlap;\n var zOverlap;\n\n for (var j = 0; j < node.children.length; j++) {\n xOverlap = false;\n yOverlap = false;\n zOverlap = false;\n //does the triangle's xmin fall between the octant's xmin and xmax?\n if (triangle.minX > node.children[j].xMin && triangle.minX < node.children[j].xMax) {\n xOverlap = true;\n }\n //does the triangle's xmax fall between the octant's xmin and xmax?\n if (triangle.maxX > node.children[j].xMin && triangle.maxX < node.children[j].xMax) {\n xOverlap = true;\n }\n //does the triangle's ymin fall between the octant's ymin and ymax?\n if (triangle.minY > node.children[j].yMin && triangle.minY < node.children[j].yMax) {\n yOverlap = true;\n }\n //does the triangle's ymax fall between the octant's ymin and ymax?\n if (triangle.maxY > node.children[j].yMin && triangle.maxY < node.children[j].yMax) {\n yOverlap = true;\n }\n //does the triangle's zmin fall between the octant's zmin and zmax?\n if (triangle.minZ > node.children[j].zMin && triangle.minZ < node.children[j].zMax) {\n zOverlap = true;\n }\n //does the triangle's zmax fall between the octant's zmin and zmax?\n if (triangle.maxZ > node.children[j].zMin && triangle.maxZ < node.children[j].zMax) {\n zOverlap = true;\n }\n\n //in order to determine if there is any overlap, we must have at least 1 min or max of each dimension have \"overlap\" in each dimension\n //if this occurs, we need to go down to the next level of octants\n if (xOverlap && yOverlap && zOverlap) {\n if (node.currentDepth < treeDepth) {\n makeTree(node.children[j], triangle);\n } else {\n //if we've gotten this far, we know the node is a leaf node that has an overlapping triangle\n node.leafNode = true;\n node.triangles.push(triangle);\n //if the maximum level of nodes is reached, then we return.\n return;\n }\n }\n }\n node.leafNode = false;\n}", "function QuadTree(pLevel, pBounds)\n{\n\tvar MAX_OBJECTS = 10;\n\tvar MAX_LEVELS = 5;\n\n\tvar level;\n\tvar objects;\n\tvar bounds;\n\tvar nodes;\n\n\t/* Stuff set by the 'constructor' */\n\tthis.init = function(){\n\t\tlevel = pLevel;\n\t\tobjects = new Array();\n\t\tbounds = pBounds;\n\t\tnodes = new Array(4);\n\t};\n\n\t/* Clears the quadtree */\n\tthis.clear = function(){\n\t\tobjects.clear();\n\n\t\tfor(var i = 0; i < nodes.length; i++){\n\t\t\tif(nodes[i] != null){\n\t\t\t\tnodes[i].clear();\n\t\t\t\tnodes[i] = null;\n\t\t\t}\n\t\t}\n\t};\n\n\t/* Split the quadtree */\n\tthis.split = function(){\n\t\tvar subWidth = (bounds.getWidth() / 2);\n\t\tvar subHeight = (bounds.getHeight() / 2);\n\t\tvar x = bounds.getX();\n\t\tvar y = bounds.getY();\n\n\t\tnodes[0] = new QuadTree(level + 1, new Rectangle(x + subWidth, y, subWidth, subHeight));\n\t\tnodes[1] = new QuadTree(level + 1, new Rectangle(x, y, subWidth, subHeight));\n\t\tnodes[2] = new QuadTree(level + 1, new Rectangle(x, y + subHeight, subWidth, subHeight));\n\t\tnodes[3] = new QuadTree(level + 1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight)); \n\t};\n\n\t/* Get the index of the parent node */\n\tthis.getIndex = function(pRect){\n\t\tvar index = -1;\n\t\tvar verticalMidpoint = bounds.getX() + (bounds.getWidth() / 2);\n\t\tvar horizontalMidpoint = bounds.getY() + (bounds.getHeight() / 2);\n\n\t\tvar topQuad = (pRect.getY() < horizontalMidpoint && pRect.getHeight() < horizontalMidpoint);\n\t\tvar bottomQuad = (pRect.getY() > horizontalMidpoint);\n\n\t\tif(pRect.getX() < verticalMidpoint && pRect.getX() + pRect.getWidth() < verticalMidpoint){\n\t\t\tif(topQuad){\n\t\t\t\tindex = 1;\n\t\t\t}else if(bottomQuad){\n\t\t\t\tindex = 2;\n\t\t\t}\n\t\t}else if(pRect.getX() > verticalMidpoint){\n\t\t\tif(topQuad){\n\t\t\t\tindex = 0;\n\t\t\t}else if(bottomQuad){\n\t\t\t\tindex = 3;\n\t\t\t}\n\t\t}\n\t\treturn index;\n\t};\n\n\t/* Insert objects into the QuadTree */\n\tthis.insert = function(pRect){\n\t\tif(nodes[0] != null){\n\t\t\tvar index = getIndex(pRect);\n\t\t\tif(index != -1){\n\t\t\t\tnodes[index].insert(pRect);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tobjects.push(pRect);\n\t\tif(objects.length > MAX_OBJECTS && level < MAX_LEVELS){\n\t\t\tif(nodes[0] == null){\n\t\t\t\tthis.split();\t//this refers to this.insert() ?\n\t\t\t}\n\t\t\tvar i = 0;\n\t\t\twhile(i < objects.length){\n\t\t\t\tvar index = getIndex(objects[i]);\n\t\t\t\tif(index != -1){\n\t\t\t\t\tnodes[index].insert(objects.splice(i,1)[0]);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/* Return all objects */\n\tthis.retrieve = function(returnObjects, pRect){\n\t\tvar index = getIndex(pRect);\n\t\tif(index != -1 && nodes[0] != null){\n\t\t\tnodes[index].retrieve(returnObjects,pRect);\n\t\t}\n\t\treturnObjects.push(objects);\n\n\t\treturn returnObjects;\n\t};\n\n\t/* Constructor call */\n\tthis.init();\n}", "static deserialize(stringTree) {\n\n const arrayTree = stringTree.split(\",\")\n const newTree = new BinaryTree( new BinaryTreeNode(Number(arrayTree.shift())) )\n const queue = new Queue()\n\n queue.enqueue(newTree.root)\n\n while(arrayTree.length) {\n const node = queue.dequeue()\n const leftVal = arrayTree.shift()\n const rightVal = arrayTree.shift()\n\n if(leftVal.length) {\n node.left = new BinaryTreeNode(Number(leftVal))\n queue.enqueue(node.left)\n }\n if(rightVal.length) {\n node.right = new BinaryTreeNode(Number(rightVal))\n queue.enqueue(node.right)\n }\n }\n\n return newTree\n }", "function PreorderTraversal(strArr) {\n\n // build the BT\n let inorArray = []\n for (var i = 0; i < strArr.length; i++) {\n inorArray.push(0);\n }\n console.log(inorArray)\n var rootIdx = Math.floor(strArr.length / 2)\n console.log(\"Root idx \", rootIdx)\n\n // start pushing the left into mid of array\n console.log(\"str[0] \", strArr[0])\n inorArray[0] = strArr[0];\n\n // [ 0, 0, 0, 0, 0, 0, '5', 0, 0, 0, 0, 0, 0]\n // result \n // current [[\"5\",] [\"2\", \"6\"], [ \"1\", \"9\", \"#\", \"8\"[6]], [\"#\", \"#\", \"#\", \"#\", \"4\", \"#\"[12]] , \"#\", \"#\", \"#\", \"#\", \"4\", \"#\", \"#\", \"#\", \"#\", \"#\", \"4\", \"#\", ]\n // [ 0 1. 2. 3 4. 5. 6 7. 8. 9. 10. 11]\n // 5 2 1 # # 9 # # 6 # 8 4 #\n //preorder - root, left, right ( 2k-1, 2k)\n\n //0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 6, 11 ,12 \n\n /**\n * [\"5\",] \n *. [\"2\", \"6\"], \n * [ \"1\", \"9\", \"#\", \"8\"[6]], \n * [\"#\", \"#\", \"#\", \"#\", \"4\", \"#\"[12]] , \n * [\"#\", \"#\", \"#\", \"#\", \"4\", \"#\", \"#\", \"#\", \"#\", \"#\", \"4\", \"#\" ]\n */\n\n /**\n* [\"5\",] \n*. [\"2\", \"6\"], \n* [\"1\", \"9\", \"#\", \"8\"[6]], \n* [\"#\", \"#\", \"#\", \"#\", \"4\", \"#\"[12]] , \n*/\n\n // [5, 2,1, ##, 9, ##, 6, #, 8, 4, #\n\n\n // spit into layers\n\n console.log(inorArray)\n // code goes here \n return inorArray;\n\n}", "subdivide(){\n\n\n this.divided = true;\n x = this.boundary.x;\n y = this.boundary.y;\n w = this.boundary.w / 2;\n h = this.boundary.h / 2;\n\n\n this._ne = new QuadTree(new Rectangle(x + w, y, w, h), this._config, this._points.slice());\n this._nw = new QuadTree(new Box(x, y, w, h), this._config, this._points.slice());\n this._se = new QuadTree(new Box(x + w, y + h, w, h), this._config, this._points.slice());\n this._sw = new QuadTree(new Box(x, y + h, w, h), this._config, this._points.slice());\n\n // We empty this node points\n this._points.length = 0;\n this._points = [];\n\n\n //algoritmo\n QuadTree qt_northeast, qt_northwest, qt_southeast, qt_southwest;\n\n //1.- Se crean cuatro QuadTrees, uno por cada cuadrante (qt_northeast, qt_northwest,\n //qt_southeast, qt_southwest) tener cuidado con el tamaño (boundary) de cada Quadtree.\n //2.- Asignar los QuadTree creados a cada hijo (this.northeast, this.northwest,\n //this.southeast, this.southwest), ejemplo:\n // this.northeast = qt_northeast;\n this.northeast = qt_northeast\n this.northeast = qt_northeast\n this.northeast = qt_northeast\n\n\n //3.- Cambiar el flag this.divided a true\n }", "split() {\n const x = this.bounds.x;\n const y = this.bounds.y;\n const halfWidth = this.bounds.width/2;\n const halfHeight = this.bounds.height/2;\n \n this.nodes[0] = new Quadtree(this.level+1, new Rect(x, y+halfHeight, halfWidth, halfHeight));\n this.nodes[1] = new Quadtree(this.level+1, new Rect(x, y, halfWidth, halfHeight));\n this.nodes[2] = new Quadtree(this.level+1, new Rect(x+halfWidth, y, halfWidth, halfHeight));\n this.nodes[3] = new Quadtree(this.level+1, new Rect(x+halfWidth, y+halfHeight, halfWidth, halfHeight));\n }", "function binaryTreeDrawItmes(placeId, input) {\n var radius = 30;\n // Delta height between levels (calculate from center of the circle)\n var levelHeight = 4 * radius;\n var totalLevels = Math.floor(Math.log(input.length) / Math.log(2)) + 1;\n // The paper's height must bigger than levelHeight * (totalLevels - 1) + radius * 2 \n var paperHeight = levelHeight * (totalLevels - 1) + radius * 2 + 10 * radius;\n // The paper's width must bigger than 2*r*Math.pow(2,level-1)\n // So that there will not be overlap.\n var tempWidth1 = 2 * radius * Math.pow(2, totalLevels - 1);\n var tempWidth2 = input.length * 2 * radius;\n var paperWidth = (tempWidth1 >= tempWidth2 ? tempWidth1 : tempWidth2) + 2 * radius;\n var paper = Raphael(placeId, paperWidth, paperHeight);\n // Add sets into setArr\n var items = [];\n var level = 0;\n for (var j = 0; j < input.length; ++j) {\n // level starts from zero\n level = Math.floor(Math.log(j + 1) / Math.log(2));\n // Calculate its x position\n // 1. Find the index and the x of the first node in that level\n var firstIndex = Math.pow(2, level) - 1;\n var firstX = 1 / Math.pow(2, level + 1);\n // 2. Calculate the delta propotion between each node in that level\n var deltaX = 1 / Math.pow(2, level);\n // 3. Calculate the final x, 1/2, 1/4, 1/8 ... \n var posX = paperWidth * (firstX + deltaX * (j - firstIndex));\n var posY = 2 * radius + levelHeight * level;\n var circle = paper.circle(posX, posY, radius).attr({ fill: \"#487B7B\", stroke: \"#306E12\", \"stroke-width\": 5, \"stroke-opacity\": 0.5 });\n var text = paper.text(posX, posY,\n input[j]).attr({ \"font-family\": \"arial\", \"font-size\": radius, fill: \"white\" });\n var card = paper.set();\n card.push(circle);\n card.push(text);\n items.push(card);\n }\n // Draw links between each node\n for (var i = 0; i < input.length; i++) {\n var leftIndex = 2 * i + 1;\n var rightIndex = 2 * i + 2;\n var leftPath = null;\n var rightPath = null;\n // Link left one\n if (leftIndex < input.length) {\n leftPath = connectTreeNodes(items[i], items[leftIndex], paper, radius);\n };\n // Link right one\n if (rightIndex < input.length) {\n rightPath = connectTreeNodes(items[i], items[rightIndex], paper, radius);\n }\n // Store objects in items\n items[i].leftConn = leftPath;\n items[i].rightConn = rightPath;\n }\n return {\n paper: paper,\n items: items\n };\n}", "function levelorderTraversal(root) {\nvar strings4mNode=new Array();\nvar nodeParent=new Array();\nvar idNo=1;\n////alert(\"AA\");\n// Initialize queue to contain root element\nvar q1 = [root];\n// While there are elements in the queue\nwhile(q1.length) {\n var q2 = [];\n \n // For each element in queue\n for(var i=0; i<q1.length; i++) {\n if(q1[i].parentNode.visId==undefined && q1[i].parentNode.nodeName==\"HTML\"){\n \tq1[i].parentNode.visId=0;\n \t returnStuff=getDOMCoords(q1[i].parentNode);\n \tallNodes.push(new Node(q1[i].parentNode.getAttribute('arktos'),\"notPresent\",q1[i].parentNode.nodeName,q1[i].parentNode.visId,-1,q1[i].parentNode.nodeType,returnStuff[0],returnStuff[1],(returnStuff[0]+returnStuff[2]),(returnStuff[1]+returnStuff[3]),0,getElementXPath(q1[i]),11111111,1));\n }\n if(q1[i].parentNode.visId==undefined && q1[i].parentNode.nodeName==\"BODY\"){\n returnStuff=getDOMCoords(q1[i].parentNode);\n \n \tq1[i].parentNode.visId=1;\n \t\n \tvar n=new Node(q1[i].parentNode.getAttribute('arktos'),\"notPresent\",q1[i].parentNode.nodeName,q1[i].parentNode.visId,-1,q1[i].parentNode.nodeType,returnStuff[0],returnStuff[1],(returnStuff[0]+returnStuff[2]),(returnStuff[1]+returnStuff[3]),0,getElementXPath(q1[i]),11111111,1);\n \tn.addParent(0);\n \t\n \t\tallNodes.push(n);\n \t\t\n \tidNo++;\n }\n else if(q1[i].nodeName==\"#text\"){\n\t try{\n\t\t if(strings4mNode[q1[i].parentNode.visId]!=null){\n\t\t strings4mNode[q1[i].parentNode.visId]+=q1[i].nodeValue;\n\t\t }\n\t\t else{\n\t\t\t strings4mNode[q1[i].parentNode.visId]=q1[i].nodeValue;\n\t\t }\n\t\t var insNode=-1;\n\t\t for(var x=0;x<allNodes.length;x++){\n\t\t\t if(allNodes[x].getId()==q1[i].parentNode.visId){\n\t\t\t\t insNode=x;\n\t\t\t\t break;\n\t\t\t }\n\t\t }\n\t\t nodeParent[q1[i].parentNode.visId]=allNodes[x];\n\t }\n\t catch(e){\n//\t alert(\"XX after visId\"+q1[i].nodeName);\n\t }\n }\n else{\n q1[i].visId=idNo;\n var clickVar=1;\n if(checkIsClickable(q1[i])=='-1')\n {\n \tclickVar=0;\n }\n returnStuff=getDOMCoords(q1[i]);\n \tvar style = getStyle(q1[i],\"z-index\");\n \tvar zIndexVal=-1111111;\n \tvar visiblityVar=checkIsVisible(q1[i]);\n\t\t\tif(style){ //null check\n\t\t\t\tzIndexVal = parseInt(style); //getPropertyValue(\"z-index\");\n\t\t\t\tif(isNaN(zIndexVal)){\n\t\t\t\t\tzIndexVal = 0;\n\t\t\t\t}\n\t\t\t}\n\n\ttry{\n \t\tvar n=new Node(q1[i].getAttribute('arktos'),q1[i].id,q1[i].nodeName,q1[i].visId,-1,q1[i].nodeType, returnStuff[0],returnStuff[1],(returnStuff[0]+returnStuff[2]),(returnStuff[1]+returnStuff[3]),clickVar,getElementXPath(q1[i]),zIndexVal,visiblityVar);\n\t}catch(e){\n\t\t// For handling comment tags that do not have an arktos id\n \t\tvar n=new Node(0,q1[i].id,q1[i].nodeName,q1[i].visId,-1,q1[i].nodeType, returnStuff[0],returnStuff[1],(returnStuff[0]+returnStuff[2]),(returnStuff[1]+returnStuff[3]),clickVar,getElementXPath(q1[i]),zIndexVal,visiblityVar);\n\t}\n \tn.addParent(q1[i].parentNode.visId);\n \t\n \t\tallNodes.push(n);\n \n idNo++;\n }\n \n //\n // Do something with node q[i]\n //\n // Create new queue with childnodes of elements in queue\n for(var j=0; j<q1[i].childNodes.length; j++)\n q2.push(q1[i].childNodes[j]);\n }\n q1 = q2;\n}\n\t\tfor(var x=0;x<nodeParent.length;x++)\n\t\t{\n\t\t\tif(nodeParent[x]!=null)\n\t\t\t{\n\t\t\t\tvar crc=0;\n\t\t\t\tif(strings4mNode[x].length>10240){\n\t\t\t\t\tvar currLocStart=0;\n\t\t\t\t\tvar currLocEnd=10240;\n\t\t\t\t\twhile(strings4mNode[x].length>0){\n\t\t\t\t\t\tcrc+=Crc32Str(strings4mNode[x].substring(0,10240));\n\t\t\t\t\t\tstrings4mNode[x]=strings4mNode[x].substring(10240);\n\t\t\t\t\t}\n\t\t\t\t\tnodeParent[x].addChildHash(Hex32(crc));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\tnodeParent[x].addChildHash(Hex32(Crc32Str(strings4mNode[x])));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RedSandHashHandler Returns an associative array of anchors present in the document.
getDocumentAnchors() { let anchors = []; for (let i = 0; i < document.anchors.length; i++) { anchors[this.hashSeparator + document.anchors[i].name] = true; } return anchors; }
[ "function getAnchors() {\n\t\t// get all anchors in document\n\t\tvar anchorTags = document.getElementsByTagName(\"a\");\n\n\t\t// array will store all anchors with href attribute \"section\"\n\t\tvar anchorsWithHrefSection = [];\n\n\t\tfor(var i = 0; i < anchorTags.length; i++) {\n\t\t\tif(anchorTags[i].getAttribute(\"href\").indexOf(\"section\", 1)) {\n\t\t\t\tanchorsWithHrefSection.push(anchorTags[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn anchorsWithHrefSection;\n\t}", "get anchors(){\n\t\t//readonly attribute sequence<XRAnchor> anchors;\n\t\tlet results = []\n\t\tfor(let value of this._session.reality._anchors.values()){\n\t\t\tresults.push(value)\n\t\t}\n\t\treturn results\n\t}", "cacheAnchors() {\n const elements = document.querySelectorAll('[data-anchor]');\n\n for (let i = 0, len = elements.length; i < len; i += 1) {\n const el = elements[i];\n const name = el.dataset.anchor;\n\n if (!ANCHORS[name]) {\n ANCHORS[name] = [];\n }\n\n ANCHORS[name].push(el);\n }\n }", "processCurrentURIHash()\n {\n let anchors = this.getDocumentAnchors();\n\n if (anchors[window.location.hash] === undefined)\n {\n // Return associative array\n return this.hash2Object(window.location.hash);\n }\n\n return undefined;\n }", "function matchAllAnchors (criteria) {\n var anchors = document.getElementsByTagName('a');\n var anchorArray = [];\n var criteriaCodes = [];\n criteria.forEach((item) => {\n criteriaCodes.push(item.code)\n })\n for (var item of anchors) {\n if (item.title) {\n var letterArray = item.title.split('');\n criteria.forEach((obj) => {\n var anchorObj\n if (letterArray[0] === obj.code) {\n anchorObj = {\n anchor: item,\n meta: obj\n }\n anchorArray.push(anchorObj)\n } else if (letterArray.join(\"\").toLowerCase().startsWith(\"trading\")) {\n // Special case to highlight tasks starting with \"trading\"\n anchorObj = {\n anchor: item,\n meta: {\n highlight: \"background-color\",\n color: {\n standard: \"#a2e8c3\",\n hover: \"#a2e8c3\"\n }\n }\n }\n anchorArray.push(anchorObj)\n } else if (letterArray.join(\"\").toLowerCase().startsWith(\"reminder\")) {\n // Special case to highlight tasks starting with \"reminder\"\n anchorObj = {\n anchor: item,\n meta: {\n highlight: \"background-color\",\n color: {\n standard: \"#0000A0\",\n hover: \"#0000A0\"\n }\n }\n }\n anchorArray.push(anchorObj)\n }\n })\n }\n }\n return anchorArray;\n }", "function extractAnchorFileHashes (transactions, prefix) {\n var hashes = [];\n for (var i = 0; i < transactions.length; i++) {\n var tx = transactions[i];\n var outputs = tx.outputs;\n\n for (var j = 0; j < outputs.length; j++) {\n var script = outputs[j].script;\n\n if (!script || !script.isDataOut()) {\n continue; // no data in the script\n }\n\n var data = script.getData().toString();\n if (data.startsWith(prefix)) {\n hashes.push(data.slice(prefix.length));\n }\n }\n }\n return hashes;\n}", "getLinkAnchors(mode) {\n return [];\n }", "function anchors(photos, options) {\n return $.map(photos.photo, function(photo) {\n var photo_anchor = $(anchor(image(photo, options.display_size), photo, options.link_to_size));\n photo_anchor.data(\"photo\", photo);\n return photo_anchor;\n });\n }", "function getAnchorsURL(){\r\n var section;\r\n var slide;\r\n var hash = window.location.hash;\r\n\r\n if(hash.length){\r\n //getting the anchor link in the URL and deleting the `#`\r\n var anchorsParts = hash.replace('#', '').split('/');\r\n\r\n //using / for visual reasons and not as a section/slide separator #2803\r\n var isFunkyAnchor = hash.indexOf('#/') > -1;\r\n\r\n section = isFunkyAnchor ? '/' + anchorsParts[1] : decodeURIComponent(anchorsParts[0]);\r\n\r\n var slideAnchor = isFunkyAnchor ? anchorsParts[2] : anchorsParts[1];\r\n if(slideAnchor && slideAnchor.length){\r\n slide = decodeURIComponent(slideAnchor);\r\n }\r\n }\r\n\r\n return {\r\n section: section,\r\n slide: slide\r\n };\r\n }", "function getAnchorsURL(){\r\n var section;\r\n var slide;\r\n var hash = window.location.hash;\r\n\r\n if(hash.length){\r\n //getting the anchor link in the URL and deleting the `#`\r\n var anchorsParts = hash.replace('#', '').split('/');\r\n\r\n //using / for visual reasons and not as a section/slide separator #2803\r\n var isFunkyAnchor = hash.indexOf('#/') > -1;\r\n\r\n section = isFunkyAnchor ? '/' + anchorsParts[1] : decodeURIComponent(anchorsParts[0]);\r\n\r\n var slideAnchor = isFunkyAnchor ? anchorsParts[2] : anchorsParts[1];\r\n if(slideAnchor && slideAnchor.length){\r\n slide = decodeURIComponent(slideAnchor);\r\n }\r\n }\r\n\r\n return {\r\n section: section,\r\n slide: slide\r\n }\r\n }", "function getAnchorsURL(){\n var section;\n var slide;\n var hash = window.location.hash;\n\n if(hash.length){\n //getting the anchor link in the URL and deleting the `#`\n var anchorsParts = hash.replace('#', '').split('/');\n\n //using / for visual reasons and not as a section/slide separator #2803\n var isFunkyAnchor = hash.indexOf('#/') > -1;\n\n section = isFunkyAnchor ? '/' + anchorsParts[1] : decodeURIComponent(anchorsParts[0]);\n\n var slideAnchor = isFunkyAnchor ? anchorsParts[2] : anchorsParts[1];\n if(slideAnchor && slideAnchor.length){\n slide = decodeURIComponent(slideAnchor);\n }\n }\n\n return {\n section: section,\n slide: slide\n };\n }", "function address(digests) {\r\n\t var sponge = new Curl(27);\r\n\t sponge.absorb(digests, 0, digests.length);\r\n\t var addressTrits = new Int8Array(Curl.HASH_LENGTH);\r\n\t sponge.squeeze(addressTrits, 0, addressTrits.length);\r\n\t return addressTrits;\r\n\t}", "links() {\n let self=this;\n return self._links.keys();\n }", "function getAnchorsURL(){\n var section;\n var slide;\n var hash = window.location.hash;\n\n if(hash.length){\n //getting the anchor link in the URL and deleting the `#`\n var anchorsParts = hash.replace('#', '').split('/');\n\n //using / for visual reasons and not as a section/slide separator #2803\n var isFunkyAnchor = hash.indexOf('#/') > -1;\n\n section = isFunkyAnchor ? '/' + anchorsParts[1] : decodeURIComponent(anchorsParts[0]);\n\n var slideAnchor = isFunkyAnchor ? anchorsParts[2] : anchorsParts[1];\n if(slideAnchor && slideAnchor.length){\n slide = decodeURIComponent(slideAnchor);\n }\n }\n\n return {\n section: section,\n slide: slide\n }\n }", "function getAnchorsURL() {\n var section;\n var slide;\n var hash = window.location.hash;\n\n if (hash.length) {\n //getting the anchor link in the URL and deleting the `#`\n var anchorsParts = hash.replace('#', '').split('/');\n\n //using / for visual reasons and not as a section/slide separator #2803\n var isFunkyAnchor = hash.indexOf('#/') > -1;\n\n section = isFunkyAnchor ? '/' + anchorsParts[1] : decodeURIComponent(anchorsParts[0]);\n\n var slideAnchor = isFunkyAnchor ? anchorsParts[2] : anchorsParts[1];\n if (slideAnchor && slideAnchor.length) {\n slide = decodeURIComponent(slideAnchor);\n }\n }\n\n return {\n section: section,\n slide: slide\n };\n }", "function headerAnchors() {\n var headers = document.querySelectorAll('h2, h3, h4, h5, h6');\n if (headers) {\n for (var h = 0; h < headers.length; h++) {\n var id = headers[h].id;\n if (id) {\n var a = document.createElement('a');\n a.role = 'link';\n a.className = 'h-anchor';\n a.href = document.location.origin + document.location.pathname.replace(/\\/$/gi, '') + '#' + id;\n a.target = '_self';\n var icon = document.createElement('i');\n icon.className = 'ms-Icon ms-Icon--Link';\n a.appendChild(icon);\n headers[h].append(a);\n }\n }\n }\n }", "function highlightAnchor()\r\n{\r\n\tvar urlstr = doc.location.href;\r\n\tvar id = getUrlParam(urlstr,\"anchor\"); //IE8\r\n\tif (id==\"\") //IE6!\r\n\t{\r\n\t\tvar pos = urlstr.indexOf('#');\r\n\t\tif (pos!=-1)\r\n\t\t\tid = urlstr.substring(pos+1);\r\n\t}\r\n\tif (id==\"\") return;\r\n\r\n\tvar els = document.getElementsByTagName(\"A\");\r\n\tfor(i=0;i<els.length;i++)\r\n\t{\r\n\t\tif (els[i].name==id && els[i].href==\"\")\r\n\t\t{\r\n\t\t\thightlightRow(els[i]);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\t\r\n}", "function get_anchor_len() {\n C.log(D.anchors.length);\n}", "function _xrefArray()\r\n{\r\n\tvar linkMap = new Array();\r\n\t\r\n\t// TODO find missing links (Nucleotide Sequence Database)\r\n\t//linkMap[\"refseq\"] =\t\"http://www.genome.jp/dbget-bin/www_bget?refseq:\";\r\n\tlinkMap[\"refseq\"] = \"http://www.ncbi.nlm.nih.gov/protein/\";\r\n\tlinkMap[\"entrez gene\"] = \"http://www.ncbi.nlm.nih.gov/gene?term=\";\t\r\n\tlinkMap[\"hgnc\"] = \"http://www.genenames.org/cgi-bin/quick_search.pl?.cgifields=type&type=equals&num=50&search=\" + ID_PLACE_HOLDER + \"&submit=Submit\";\r\n\tlinkMap[\"uniprot\"] = \"http://www.uniprot.org/uniprot/\";\r\n linkMap[\"uniprotkb\"] = \"http://www.uniprot.org/uniprot/\";\r\n linkMap[\"chebi\"] = \"http://www.ebi.ac.uk/chebi/advancedSearchFT.do?searchString=\" + ID_PLACE_HOLDER + \"&queryBean.stars=3&queryBean.stars=-1\";\r\n\tlinkMap[\"pubmed\"] = \"http://www.ncbi.nlm.nih.gov/pubmed?term=\";\r\n\tlinkMap[\"drugbank\"] = \"http://www.drugbank.ca/drugs/\" + ID_PLACE_HOLDER;\r\n linkMap[\"kegg\"] = \"http://www.kegg.jp/dbget-bin/www_bget?dr:\" + ID_PLACE_HOLDER;\r\n linkMap[\"kegg drug\"] = \"http://www.kegg.jp/dbget-bin/www_bget?dr:\" + ID_PLACE_HOLDER;\r\n linkMap[\"chebi\"] = \"http://www.ebi.ac.uk/chebi/searchId.do?chebiId=CHEBI%3A\" + ID_PLACE_HOLDER;\r\n linkMap[\"chemspider\"] = \"http://www.chemspider.com/Chemical-Structure.\" + ID_PLACE_HOLDER + \".html\";\r\n linkMap[\"kegg compund\"] = \"http://www.genome.jp/dbget-bin/www_bget?cpd:\" + ID_PLACE_HOLDER;\r\n linkMap[\"doi\"] = \"http://www.nature.com/nrd/journal/v10/n8/full/nrd3478.html?\";\r\n linkMap[\"nci_drug\"] = \"http://www.cancer.gov/drugdictionary?CdrID=\" + ID_PLACE_HOLDER;\r\n linkMap[\"national drug code directory\"] = \"http://www.fda.gov/Safety/MedWatch/SafetyInformation/SafetyAlertsforHumanMedicalProducts/ucm\" + ID_PLACE_HOLDER + \".htm\";\r\n linkMap[\"pharmgkb\"] = \"http://www.pharmgkb.org/gene/\" + ID_PLACE_HOLDER;\r\n linkMap[\"pubchem compund\"] = \"http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=\" + ID_PLACE_HOLDER + \"&loc=ec_rcs\";\r\n linkMap[\"pubchem substance\"] = \"http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?sid=\" + ID_PLACE_HOLDER + \"&loc=ec_rss\";\r\n linkMap[\"pdb\"] = \"http://www.rcsb.org/pdb/explore/explore.do?structureId=\" + ID_PLACE_HOLDER;\r\n linkMap[\"bindingdb\"] = \"http://www.bindingdb.org/data/mols/tenK3/MolStructure_\" + ID_PLACE_HOLDER + \".html\";\r\n linkMap[\"genbank\"] = \"http://www.ncbi.nlm.nih.gov/nucleotide?term=\" + ID_PLACE_HOLDER;\r\n linkMap[\"iuphar\"] = \"http://www.iuphar-db.org/DATABASE/ObjectDisplayForward?objectId=\" + ID_PLACE_HOLDER;\r\n linkMap[\"drugs product database (dpd)\"] = \"http://205.193.93.51/dpdonline/searchRequest.do?din=\" + ID_PLACE_HOLDER;\r\n linkMap[\"guide to pharmacology\"] = \"http://www.guidetopharmacology.org/GRAC/LigandDisplayForward?ligandId=\" + ID_PLACE_HOLDER;\r\n linkMap[\"nucleotide sequence database\"] = \"\";\r\n\t\r\n\treturn linkMap;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renders a table of items starting with the specified index in the item list
function renderItemsStartingAt(elem$, data, index) { if (data && data.items && index < data.items.length) { // render items elem$.empty(); var opt = elem$.data('gw2items_options') || {}; for (var i = index; i < data.items.length && (i - index) < opt.pageSize; i++) { fetchItem(data.items[i], function(item) { if (item && item.item_id) { var itemrow$ = $('<tr class="item-rarity-' + item.rarity.toLowerCase() + ' item-type-' + item.type.toLowerCase() + '" id="item_' + item.item_id + '"><td>' + item.item_id + '</td><td><a href="#" rel="' + item.item_id + '">' + item.name + '</a> ' + createChatTag(item.item_id) + '</td><td>' + (item.level > 0 ? item.level : '&nbsp;') + '</td></tr>'); elem$.append(itemrow$); itemrow$.find('a').click(function(evt) { evt.preventDefault(); renderItemDetail($(this).attr('rel'), opt.details, opt.insertAt); }); } }); } } }
[ "renderItemByIndex(index) {\n if (this.itemsList.length <= 0) {\n var blankItem = {\n Name: \"--\",\n CurrentPrice: \"N/A\",\n LowestPrice: \"N/A\",\n HighestPrice: \"N/A\",\n Date: \"--\",\n Status: \"N/A\",\n Url: null\n };\n\n this.renderItem(blankItem);\n return;\n }\n \n if (index == null || index < 0) {\n index = 0;\n }\n\n this.renderItem(this.itemsList[index]);\n }", "function itemTable() { }", "display(indices, id) {\n var list = [];\n\n for (var i = 0; i < this.array.length; i++) {\n var color = \"red\";\n if (indices.includes(i)) {\n color = \"blue\";\n }\n list.push(React.createElement(Item, {num: this.array[i], key: this.array[i] + \" \" + i, color: color}));\n }\n if (!id) {\n id = 'tableBody'\n }\n ReactDOM.render(\n list,\n document.getElementById(id)\n );\n }", "function renderTableRow(itemName,totalcost,index) {\n var tr_node = document.createElement(\"tr\");\n var th_node = document.createElement(\"th\");\n th_node.setAttribute('scope',\"row\");\n th_node.innerText =index;\n \n var td_item = document.createElement(\"td\");\n td_item.innerText =itemName;\n\n // var td_count = document.createElement(\"td\");\n // td_count.innerText=counter;\n var td_total = document.createElement(\"td\");\n td_total.innerText=totalcost;\n\n tr_node.appendChild(th_node);\n tr_node.appendChild(td_item);\n // tr_node.appendChild(td_count);\n tr_node.appendChild(td_total);\n\n return tr_node;\n\n}", "function printRow(orders, indexes, itemType) {\n for (var i = 0; i < indexes.length; i++) { // for each item in {type}list\n var order = orders[indexes[i]] // find specific order\n // determine unit\n if (order.unit === \"box\") {\n unit = \"Boxes\";\n }\n if (order.unit === \"bag\") {\n unit = \"Bags\";\n }\n if (order.unit === \"each\") {\n unit = \"Each\";\n }\n // print itemtype, unit, and quantity\n document.getElementById('table').innerHTML +=\n \"<tr>\" +\n \"<td class=\\\"col-md-9\\\"><em>\" + itemType + \"</em></td>\" +\n \"<td class=\\\"col-md-9\\\"><em>\" + unit + \"</em></td>\" +\n \"<td class=\\\"col-md-1\\\" style=\\\"text-align: center\\\">\" + order.quantity + \"</td>\" +\n \"</tr>\";\n }\n}", "function renderList(items, header, parent, childIndex)\n{\n var tBody = document.createElement(\"tbody\");\n var tRow = document.createElement(\"tr\");\n var newCell;\n var i = 0;\n\n // Create the header row and append it to the table\n for (var headerProp in header)\n {\n newCell = document.createElement(\"th\");\n newCell.innerHTML = header[headerProp];\n tRow.appendChild(newCell);\n }\n tBody.appendChild(tRow);\n\n // Create a new row for each entry in the array\n for (i = 0; i < items.length; i++)\n {\n tRow = document.createElement(\"tr\");\n //tableRow.setAttribute('data-href', 'javascript:openCaseForm(' + items[i].name + ');');\n\n // Iterate through each object in the header and add the correct data from the case\n for (var propertyValue in header)\n {\n newCell = document.createElement(\"td\");\n newCell.innerHTML = items[i][propertyValue];\n tRow.appendChild(newCell);\n }\n tBody.appendChild(tRow);\n }\n parent.replaceChild(tBody, parent.childNodes[childIndex])\n}", "function renderIndex(indexData) {\n\tvar indexContainer = document.getElementById(\"indexTable\");\n\tindexContainer.innerHTML = \"\";\n\tvar indexString = \"\";\n\tindexString = \"<tr><th>Name</th><th>Email</th><th>URL</th></tr>\";\n\tfor(i = 0; i < indexData.length; i++) {\n\t\tindexString += \"<tr><td>\" + indexData[i].Name + \"</td><td>\" + indexData[i].Email + \"</td><td>\" + indexData[i].ContactURL + \"</td></tr>\";\n\t}\n\tindexContainer.insertAdjacentHTML('beforeend', indexString);\n\tindexContainer.style.visibility = \"visible\";\n}", "render() {\n return (\n <table>\n <TodosListHeader />\n <tbody>\n {this.renderItems()}\n </tbody>\n </table>\n );\n }", "render () {\n // Map each item to a table header element\n const items = this.props.items.map(\n (item) => <th key={item}>{item}</th>\n );\n return (\n <thead>\n <tr key={'header'}>\n {items}\n </tr>\n </thead>\n )\n }", "function showItemTable() {\r\n connection.query('SELECT * from products', function (err, results) {\r\n if (err) throw err;\r\n var table = new Table({\r\n head: ['id', 'item', 'price', 'quantity'],\r\n colWidths: [5, 70, 13, 10]\r\n });\r\n for (var i = 0; i < results.length; i++) {\r\n table.push(\r\n [(JSON.parse(JSON.stringify(results))[i][\"item_id\"]), (JSON.parse(JSON.stringify(results))[i][\"product_name\"]),\r\n (\"$ \" + JSON.parse(JSON.stringify(results))[i][\"price\"]), (JSON.parse(JSON.stringify(results))[i][\"stock_quantity\"])]);\r\n }\r\n console.log(colors.red('_______________________________________________________________________________________________________'));\r\n console.log(\"\\n\" + table.toString());\r\n console.log(colors.red('_______________________________________________________________________________________________________'));\r\n console.log(\"\");\r\n });\r\n}", "function displayTable()\n{\n var textTable = \"<table class=\\\"table\\\"><caption>Items</caption>\";\n textTable += \"<thead><tr><th>#</th><th>Item</th>\";\n textTable += \"</tr></thead><tbody>\";\n for(var i = 0; i < items.length; i++)\n {\n textTable += \"<tr><td>\" + i + \"</td>\";\n textTable += \"<td>\" + items[i] + \"</td>\";\n textTable += \"</tr>\";\n }\n textTable += \"</tbody></table>\"\n $(\"#tableContainer\").html(textTable);\n}", "createDataItem(item, index){\n if(item.image){\n // If we don't have a path, grey out the image\n if(item.path === \"\") {return <td key={index}><img className=\"tableImageNoLink\" src={item.image} alt=\"\"/></td>}\n else { return<td key={index}><a href={item.path} target=\"_blank\" rel=\"noopener noreferrer\"><img className=\"tableImageWithLink\" src={item.image} alt=\"\"/></a></td>}\n }\n\n // For objects passed that contain a link and a text value. Creates a hyperlink to the dest\n if(item.text){\n return<td key={index}><a href={item.path} target=\"_blank\" rel=\"noopener noreferrer\">{item.text}</a></td>\n }\n\n if(item.length > 25){return <CollapsableText key={item} text={item} numOfChars={25}/>}\n\n return<td key={index}>{item}</td>\n }", "_renderItem(item,index)\n {\n \treturn(\n \t\t<ListItem item={item.item}/>\n \t\t)\n }", "function generateItemHtml(index, itemObj){\n\tvar html = '<div data-pos=\"{2}\" onclick=\"displayItem(this)\" class=\"item\"><img src=\"{3}\" width=\"50\" height=\"50\" style=\"float: left\" />'+\n\t\t'<div><p>{0}</p><p>&pound;{1}</p></div></div>'; //CReate the HTMLs\n\thtml = html.format(itemObj.name, itemObj.price.toFixed(2), index, itemObj.small_image);//Format the html\n\treturn html;//Return it\n}", "render() {\n // console.log(this.store.cartItems);\n // let tbody = this.root.querySelector('tbody');\n // tbody.innerHTML = `<tr class=\"item\">\n // <td><p>'items.date'</p></td>\n // <td>'items.imgsrc'<br />'items.name'</td>\n // <td>'items.customer'</td>\n // <td>'items.status'</td>\n // </tr>`;\n }", "function Table(props) {\n\n return (\n\n <table className=\"table\">\n <thead>\n <tr>\n <th scope=\"col\">#</th>\n <th scope=\"col\">Last name</th>\n <th scope=\"col\">First Name</th>\n <th scope=\"col\">Location</th>\n <th scope=\"col\">Picture</th>\n <th scope=\"col\">Gender</th>\n </tr>\n </thead>\n <tbody>\n {props.randList.map((item, index) => (\n <tr key={index}>\n <th scope=\"row\">{index + 1}</th>\n <td>{item.name.last}</td>\n <td>{item.name.first}</td>\n <td>{item.location.city}, {item.location.state}, {item.location.country}</td>\n <td><img src={item.picture.thumbnail} alt=\"thumbnail\" /></td>\n <td>{item.gender}</td>\n </tr>\n ))}\n </tbody>\n </table>\n )\n}", "function renderResults(){\n for (var i=0; i<allItems.length; i++){\n allItems[i].tabulateResults();\n }\n}", "function renderSingle(index) {\n toDoApp.listView.render(listsData.getData().lists[index]);\n renderButtons();\n }", "render () {\n // Put the rows inside a table body\n return (\n <tbody>\n {this.props.items}\n </tbody>\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Registration tag and/or a Newsletter tag customerID: required for Registration. ID of Customer to register. customerEmail: required for Newsletters. Optional for Registration. customerCity: optional. City of Customer that placed this order customerState: optional. State of Customer that placed this order customerZIP: optional. Zipcode of Customer that placed this order newsletterName: required for Newsletters. The name of the Newsletter. subscribe: required for Newsletters. Either "Y" or "N" returns nothing, causes a document.write of an image request for this tag.
function cmCreateRegistrationTag(customerID, customerEmail, customerCity, customerState, customerZIP, customerNum, customerType, zone, newsletterName, subscribe) { var cm = new _cm("tid", "2", "vn2", "e3.1"); cm.cd = customerID; cm.em = customerEmail; cm.sa = customerState; cm.ct = customerCity; cm.zp = customerZIP; cm.rg1 = customerNum; cm.rg2 = customerType; cm.rg3 = zone; if (newsletterName && subscribe) { cm.nl = newsletterName; cm.sd = subscribe; } if (cmGomezKeynoteFlag == "0") { cm.writeImg(); } }
[ "function cmCreateRegistrationTag(customerID, customerEmail, customerCity, customerState, customerZIP, newsletterName, subscribe, customerCountry, attributes) {\n\tcmMakeTag([\"tid\",\"2\",\"cd\",customerID,\"em\",customerEmail,\"ct\",customerCity,\"sa\",customerState,\"zp\",customerZIP,\"nl\",newsletterName,\"sd\",subscribe,\"cy\",customerCountry,\"cmAttributes\",attributes]);\n}", "function cmCreateRegistrationTag(customerID, customerEmail, customerCity,\n customerState, customerZIP, newsletterName,\n subscribe, gender, country, currency) {\n var cm = new _cm(\"tid\", \"2\", \"vn2\", \"e4.0\");\n cm.cd = customerID;\n cm.em = customerEmail;\n cm.sa = customerState;\n cm.ct = customerCity;\n cm.zp = customerZIP;\n cm.gd = gender;\n cm.cy = country;\n cm.rg11 = currency;\n\n if (newsletterName && subscribe) {\n cm.nl = newsletterName;\n cm.sd = subscribe;\n }\n\n cm.writeImg();\n}", "function cmCreateRegistrationTag(customerID, customerEmail, customerCity,\n\t\t\t\tcustomerState, customerZIP, newsletterName, \n\t\t\t\tsubscribe) {\n\tvar cm = new _cm(\"tid\", \"2\", \"vn2\", \"e3.1\");\n\tcm.cd = customerID;\n\tcm.em = customerEmail;\n\tcm.sa = customerState;\n\tcm.ct = customerCity;\n\tcm.zp = customerZIP;\n\n\tif (newsletterName && subscribe) {\n\t\tcm.nl = newsletterName;\n\t\tcm.sd = subscribe;\n\t}\n\t\n\tcm.writeImg();\n}", "function cmCreateRegistrationTag(customerID, customerEmail, customerCity,\r\n\t\t\t\tcustomerState, customerZIP, newsletterName, \r\n\t\t\t\tsubscribe) {\r\n\tcmMakeTag([\"tid\",\"2\",\"cd\",customerID,\"em\",customerEmail,\"ct\",customerCity,\"sa\",customerState,\"zp\",customerZIP,\"nl\",newsletterName,\"sd\",subscribe]);\r\n}", "function cmCreateOrderTag(orderID, orderTotal, orderShipping, customerID, \n\t\t\t customerCity, customerState, customerZIP) {\n\tvar cm = new _cm(\"tid\", \"3\", \"vn2\", \"e3.1\");\n\tcm.on = orderID;\n\tcm.tr = orderTotal;\n\tcm.osk = getOSK();\n\tcm.sg = orderShipping;\n\tcm.cd = customerID;\n\tcm.sa = customerState;\n\tcm.ct = customerCity;\n\tcm.zp = customerZIP;\t\t\n\tcm.rf = myNormalizeURL(document.referrer, false);\n\tif (cmGomezKeynoteFlag == \"0\")\n\t{\n\t\tcm.writeImg();\n\t}\n}", "function cmCreateOrderTag(orderID, orderTotal, orderShipping, customerID, \n\t\t\t customerCity, customerState, customerZIP) {\n\tvar cm = new _cm(\"tid\", \"3\", \"vn2\", \"e3.1\");\n\tcm.on = orderID;\n\tcm.tr = orderTotal;\n\tcm.osk = getOSK();\n\tcm.sg = orderShipping;\n\tcm.cd = customerID;\n\tcm.sa = customerState;\n\tcm.ct = customerCity;\n\tcm.zp = customerZIP;\n\n\tcm.writeImg();\n}", "function createCustomer(form, callback) {\n stripe.customers.create({\n email: form.stripeEmail,\n source: form.stripeToken,\n metadata: {\n customer_phone: form.customer_phone\n }\n }, function(err, customer) {\n if (err) {\n console.log(err)\n }\n callback(null, customer);\n })\n}", "createStripeCustomer(email) {\n return API.post(\"notes\", \"/createCustomer\", {\n body: email\n });\n }", "function cmCreateOrderTag(orderID, orderTotal, orderShipping, customerID, \r\n\t\t\t customerCity, customerState, customerZIP, queueCartFlag) {\r\n\t\r\n\t\tvar cm = new _cm(\"tid\", \"3\", \"vn2\", \"e4.0\");\r\n\t\tcm.on = orderID;\r\n\t\tcm.tr = orderTotal;\r\n\t\tcm.osk = cmShopSKUs;\r\n\t\tcm.sg = orderShipping;\r\n\t\tcm.cd = customerID;\r\n\t\tcm.sa = customerState;\r\n\t\tcm.ct = customerCity;\r\n\t\tcm.zp = customerZIP;\r\n\r\n\t\tcm.or1 = queueCartFlag;\r\n\r\n\t\tcm.writeImg();\r\n\t\r\n}", "function createSubscription(customer_id) {\n let options = {\n user : {\n customer_id: customer_id,\n professional_id: req.session.professional\n },\n plan: req.body.plan_id\n }\n Subscription.createSubscription(options, function(error, subscription){\n if(error){\n next(error)\n }else {\n res.redirect('/subscription/thanks/'+subscription.id);\n }\n\n })\n }", "function createCommReg(customer, dateEffective, zee, state, sendemail, customer_status) {\n customer_comm_reg = nlapiCreateRecord('customrecord_commencement_register');\n customer_comm_reg.setFieldValue('custrecord_date_entry', getDate());\n customer_comm_reg.setFieldValue('custrecord_comm_date', dateEffective);\n customer_comm_reg.setFieldValue('custrecord_comm_date_signup', dateEffective);\n customer_comm_reg.setFieldValue('custrecord_customer', customer);\n if (sendemail == 'T') {\n customer_comm_reg.setFieldValue('custrecord_salesrep', nlapiGetUser());\n } else {\n customer_comm_reg.setFieldValue('custrecord_salesrep', 109783);\n }\n //Franchisee\n customer_comm_reg.setFieldValue('custrecord_std_equiv', 1);\n if (role != 1000) {\n customer_comm_reg.setFieldValue('custrecord_franchisee', zee);\n }\n\n customer_comm_reg.setFieldValue('custrecord_wkly_svcs', '5');\n customer_comm_reg.setFieldValue('custrecord_in_out', 2); // Inbound\n //Scheduled\n customer_comm_reg.setFieldValue('custrecord_state', state);\n if (sendemail == 'T') {\n if (nlapiGetFieldValue('custpage_closed_won') == 'T') {\n customer_comm_reg.setFieldValue('custrecord_trial_status', 9);\n } else {\n customer_comm_reg.setFieldValue('custrecord_trial_status', 10);\n }\n\n if (!isNullorEmpty(nlapiGetFieldValue('custpage_salesrecordid'))) {\n customer_comm_reg.setFieldValue('custrecord_commreg_sales_record', parseInt(nlapiGetFieldValue('custpage_salesrecordid')));\n }\n\n } else {\n customer_comm_reg.setFieldValue('custrecord_trial_status', 9);\n }; // Price Increase\n if (customer_status != 13) {\n customer_comm_reg.setFieldValue('custrecord_sale_type', $('#commencementtype option:selected').val())\n } else {\n customer_comm_reg.setFieldValue('custrecord_sale_type', $('#commencementtype option:selected').val())\n }\n\n var commRegID = nlapiSubmitRecord(customer_comm_reg);\n\n return commRegID;\n}", "function createOvervyooCustomer(customer,createCustomerResponse)\n{\n\t//Check if the request is valid\n\tvar errorMessage=[];\n\tif (!isValidCustomer(customer,errorMessage))\n\t{\n\t\t//Bad request\n\t\tsendError(createCustomerResponse,400,errorMessage);\n\t\treturn;\n\t}\n\t\n\t//Sign the request\n\tsignOvervyooRequest(customer);\n\t\n\t//Add the data to the form\n\tvar form = new FormData();\n\tfor(var attributename in customer){\n\t\tconsole.log(\"Adding to form: \" +attributename+\"=\"+customer[attributename]);\n\t\tform.append(attributename,customer[attributename]);\n\t}\n\n\t//Send the request. Pass the response from the original customer to the callback\n\tvar r = request.post('http://api.overvyoo.com/partner_api/customers', function(err, res, body) {\n\t\tcreateCustomerCallBack(err,res,body,createCustomerResponse);\n\t});\n\t\n\tr._form = form; \n\n}", "function createCustomer() {\n if (_use_$resources_()) {//resource .save\n if ($scope.customer.$save) {\n $scope.customer.$save(_fn_success_put_post, _fn_error);\n return;\n }\n\n _res.post($scope.customer, _fn_success_put_post, _fn_error);\n } else {\n //Use $http request\n $http.post(_URL_, $scope.customer).success(_fn_success_put_post).error(_fn_error);\n }\n }", "function stripeApiCreateCustomer (req) {\n return stripe.customers.create({\n description: 'Customer for johndoe@gmail.com',\n source: req.body.userCardDetails.id\n })\n}", "async function createCustomer() {\n\n}", "static createCustomer({ name, email, token }) {\n return stripe.customers.create({\n description: name,\n email,\n source: token // obtained with Stripe.js\n });\n }", "function createCustomer(firstName, lastName, streetNum, streetName, city, state, zip) {\n var cust = {\n \"first_name\": firstName,\n \"last_name\": lastName,\n \"address\":\n {\n \"street_number\": streetNum,\n \"street_name\": streetName,\n \"city\": city,\n \"state\": state,\n \"zip\": zip\n }\n }\n $.ajax({\n url: 'http://api.reimaginebanking.com/customers/59ebc981b390353c953a15c1/accounts?key=a67096375bcf4a60ab80d781a3fabcbc',\n headers: {\n \"Accept\":\"application/json\",\n \"Content-Type\":\"application/json\"\n },\n data: JSON.stringify(cust),\n dataType: \"json\",\n async: false,\n type: 'POST'\n });\n}", "function createStripeSubscription(req, res, next) {\n console.log(\"body\", req.body);\n stripe.customers.create(\n {\n card: req.body.stripeToken,\n email: req.user.email,\n plan: config.stripe.plan,\n quantity: req.user.blogs.length,\n description: \"Blot subscription\"\n },\n function(err, customer) {\n if (err) return next(err);\n\n User.set(req.user.uid, { subscription: customer.subscription }, next);\n }\n );\n}", "function cmCreateOrderTag(orderID,orderTotal,orderShipping,customerID,customerCity,customerState,customerZIP,paymentType,shippingMethod) {\r\n\tvar pattern = /[^0-9\\.]/gi;\r\n orderShipping = orderShipping.toString().replace(pattern, \"\");\r\n\torderTotal = orderTotal.toString().replace(pattern, \"\");\r\n\tcmMakeTag([\"tid\",\"3\",\"osk\",__skuString,\"on\",orderID,\"tr\",orderTotal,\"sg\",orderShipping,\"cd\",customerID,\"ct\",customerCity,\"sa\",customerState,\"zp\",customerZIP,\"or1\",paymentType,\"or2\",shippingMethod]);\r\n\t__skuString = \"\";\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or sets the direction in which selection occurred.
get selectionDirection() { return this.getInput().selectionDirection; }
[ "getDirection() {\n // Try to move the selection forward or backward, check whether it got bigger or smaller (then\n // restore it).\n for (let direction of [forward, backward]) {\n var change;\n if (change = this.extendByOneCharacter(direction)) {\n this.extendByOneCharacter(this.opposite[direction]);\n if (change > 0) {\n return direction;\n } else {\n return this.opposite[direction];\n }\n }\n }\n return forward;\n }", "get direction() {\n\t\treturn this.__direction;\n\t}", "setDirection() {\n let direction = 0;\n let node = this._path[0];\n let center = grid_1.default.getNodeCenter(node.row, node.column);\n if (this._coordinate.y === center.y) {\n direction = this._coordinate.x < center.x ? direction_1.Direction.RIGHT : direction_1.Direction.LEFT;\n }\n else if (this._coordinate.x === center.x) {\n direction = this._coordinate.y < center.y ? direction_1.Direction.DOWN : direction_1.Direction.UP;\n }\n else {\n //correct current coordinate to prevent number precision error\n this._coordinate = grid_1.default.getNodeCenter(this._row, this._column);\n this.setDirection();\n return;\n }\n if (this.isValidDirection(direction)) {\n this._direction = direction;\n }\n }", "get_direction() {\r\n return this.pman.direction_current;\r\n }", "function getDirectionOfChange () {\n let dropdown = browser.$('select#id_direction_of_change')\n let changeDir = dropdown.getValue()\n if (changeDir === 1) { return 'none' }\n if (changeDir === 2) { return 'pos' }\n if (changeDir === 3) { return 'neg' }\n}", "getTravelDirection(){\n\t\treturn (this.prevX > this.x) ? 'left' : 'right';\n\t\t\n\t}", "getCurrentDirection() {\n return this.current;\n }", "getDirection(){\n let v = this.getVector();\n let dir = v.direction();\n return dir\n }", "function setDirectionOfChange (dir = 'none') {\n let val\n if (dir === 'none') { val = 1 }\n if (dir === 'pos') { val = 2 }\n if (dir === 'neg') { val = 3 }\n browser.$('select#id_direction_of_change').selectByValue(val)\n}", "set direction(value) {\n this._direction = value;\n }", "get scrollDirection() {\n return this._getOption('scrollDirection');\n }", "static getDirection() {\n return document.querySelector('html').dir;\n }", "getDirectionAngle() {\n return Utils.getAngle(this.position, this.prevPosition);\n }", "SetDirection(direction) {\n let new_dir = null;\n if (direction.localeCompare(this.upDir) == 0 || direction.localeCompare(this.downDir) == 0) {\n if (direction.localeCompare(this.direction) != 0 ) {\n new_dir = direction;\n }\n if (this.updateField instanceof Function) {\n this.updateField({\n field: this.field,\n value: new_dir\n });\n }\n } else {\n console.error('Trying to set wrong direction');\n }\n }", "function setSortDirection(dir) {\n\t\tvar tgtSelect = this.selectTarget.getElement();\n\t\tif (tgtSelect) {\n\t\t\tvar changed = false;\n\t\t\tfor( var i = 0; i < tgtSelect.options.length; i++ ) {\n\t\t\t\tif (tgtSelect.options[i].selected) {\n\t\t\t\t\tvar orderColumn = this.getTargetItem(tgtSelect.options[i].value);\n\t\t\t\t\tif (orderColumn.dir != dir) {\n\t\t\t\t\t\t/* change sort direction of selection */\n\t\t\t\t\t\torderColumn.dir = dir;\n\t\t\t\t\t\t/* replace in target select */\n\t\t\t\t\t\ttgtSelect.options[i].text = orderColumn.getLabel();\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttgtSelect.selectedIndex = -1;\n\t\t\tif (changed) {\n\t\t\t\t/* update hiddeninput */\n\t\t\t\tthis.setHiddenInputSelected();\n\t\t\t\t/* handle changes */\n\t\t\t\tthis.targetItemsChanged();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "get direction() {\n // http://www.w3.org/International/questions/qa-scripts\n // Arabic, Hebrew, Farsi, Pashto, Urdu\n var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];\n return (rtlList.indexOf(gLanguage) >= 0) ? 'rtl' : 'ltr';\n }", "function getSlideDirection(objItem){\n\t\t\n\t\tvar slides = t.getSlidesReference();\n\t\t\n\t\t//validate if the item is not selected already\n\t\tvar currentIndex = slides.objCurrentSlide.data(\"index\");\n\t\tvar nextIndex = objItem.index;\n\t\t\n\t\tvar direction = \"left\";\n\t\tif(currentIndex > nextIndex)\n\t\t\tdirection = \"right\";\n\t\t\t\t\n\t\treturn(direction);\n\t}", "function getReadingDirection( elem ) {\n if ( typeof elem === 'undefined' )\n elem = $(self.util.svgRoot).find('.selected');\n var attr = $(elem).closest('.TextLine').attr('custom');\n if ( typeof attr === 'undefined' ||\n ! attr.match(/readingDirection: *[lrt]t[rlb] *;/) ) {\n attr = $(elem).closest('.TextRegion').attr('readingDirection');\n if ( typeof attr !== 'undefined' )\n return attr.replace(/(.).+-to-(.).+/,'$1t$2');\n return 'ltr';\n }\n return attr.replace(/.*readingDirection: *([lrt]t[rlb]) *;.*/,'$1');\n }", "getScrollDirection() {\n let xDiff = this.tStart[0] - this.tMove[0]\n let yDiff = this.tStart[1] - this.tMove[1]\n // Converting both the difference in to positive number\n // and calculating which is higher. We can't always drag in a straight line\n // This is necessary to calculate or guess the user slided direction\n\n // Horizontal difference is more than the vertical difference\n // Then the we try to move left or right\n if (Math.abs(xDiff) > Math.abs(yDiff)) {\n // Sliding in the left direction\n if (xDiff > 0) {\n return \"L\";\n }\n // Sliding in the right direction\n else if (xDiff < 0) {\n return \"R\";\n }\n }\n else {\n // Sliding in the Up direction\n if (yDiff > 0) {\n return \"U\";\n }\n // Sliding in the Down direction\n if (yDiff < 0) {\n return \"D\";\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the HTTP Cloud Function to create a pdf. Either AUTH the page with REST or SDK
function getPdf(auth) { if (!auth) { auth = "sdk"; } //custom api to make PDF var pdfURL = 'https://us-central1-hello-firebase-ea30c.cloudfunctions.net/api/pdf?auth=' + auth; //If we are running on local host, then hit the local host API if (location.host == "localhost:5000") { pdfURL = 'http://localhost:5001/hello-firebase-ea30c/us-central1/api/pdf?auth=' + auth; } $('.loading').show(); $.get(pdfURL).then(function (result) { console.log(result); var docRef = firebase.storage().ref(result.path); return docRef.getDownloadURL() .then(function (url) { $('.loading').hide(); render('<b>Authed via ' + auth + '</b>'); render('<a href="' + url + '" target="new">Click here to view the generated PDF</a>'); render('<a href="' + result.url + '" target="new">Click here to view the pre authed source HTML page</a>'); }); }) .fail(function (error) { $('.loading').hide() render(error); }) }
[ "function createPDFPost(req, res) {\n\n let filePath = req.file.path;\n let fileName = req.file.filename;\n\n try {\n // Initial setup, create credentials instance.\n const credentials = PDFToolsSdk.Credentials\n .serviceAccountCredentialsBuilder()\n .fromFile(\"pdftools-api-credentials.json\")\n .build();\n\n // Create an ExecutionContext using credentials and create a new operation instance.\n const executionContext = PDFToolsSdk.ExecutionContext.create(credentials),\n createPdfOperation = PDFToolsSdk.CreatePDF.Operation.createNew();\n\n // Set operation input from a source file.\n const input = PDFToolsSdk.FileRef.createFromLocalFile(filePath);\n createPdfOperation.setInput(input);\n\n // Execute the operation and Save the result to the specified location.\n createPdfOperation.execute(executionContext)\n .then((result) => {\n\n result.saveAsFile(`output/createPDFFromDOCX-${Math.random() * 120}.pdf`)\n\n //download the file\n res.redirect('/?response=PDF Successfully created')\n })\n .catch(err => {\n if (err instanceof PDFToolsSdk.Error.ServiceApiError\n || err instanceof PDFToolsSdk.Error.ServiceUsageError) {\n console.log('Exception encountered while executing operation', err);\n } else {\n console.log('Exception encountered while executing operation', err);\n }\n });\n } catch (err) {\n console.log('Exception encountered while executing operation', err);\n }\n\n}", "function pdfMaker(){\n\n}", "function makePdf(id) {\n\t$.get('/pdf?id=' + id, function(data) {\n\t\tconsole.log('Sent call to make PDF.');\n\t});\n}", "function uploadAndSend(error, data){\n interfax.documents.create(\n 'test.pdf',\n Buffer.byteLength(data)\n ).then(function(document){\n upload(0, document, data);\n });\n}", "function createAndDownloadPdf() {\n fetch(`/api/invoices/${invoiceId}/pdf`)\n .then(res => res.blob())\n .then(data => {\n const pdfBlob = new Blob([data], { type: 'application/pdf' })\n saveAs(pdfBlob, `Invoice${invoiceId}.pdf`)\n })\n}", "function createPdf (response) {\n return new Promise((resolve, reject) => {\n pdf(response.options).from(response.path).to(response.pathToPdf, () => {\n winston.log('info', `Create new file ${response.pathToPdf}`);\n resolve(response);\n });\n });\n}", "function createPDF() {\n doc.create();\n }", "bookingListsPdfGen(req, res) {\n (async () => {\n const browser = await puppeteer.launch();\n const page = await browser.newPage();\n\n // As protection page we need to authorization from system\n // Navigate to login page for authorize\n await page.goto(`http://localhost:8000/admin/login`, {\n waitUntil: \"networkidle0\"\n });\n await page.type(\"#email\", process.env.EMAIL);\n await page.type(\"#password\", process.env.PASSWORD);\n await page.click(\"#submit\");\n\n // End authorization\n\n // Navigate to page that need to create pdf\n await page.goto(`http://localhost:8000/admin/bookings-pdf-template`, {\n waitUntil: \"networkidle2\"\n });\n\n // #Save to server use this\n // const pdf = await page.pdf({\n // path: `booking-info-${id}.pdf`,\n // format: \"A4\"\n // });\n\n const pdf = await page.pdf({\n format: \"A4\",\n landscape: false,\n printBackground: true\n });\n\n await res.type(\"application/pdf\");\n await res.send(pdf);\n\n await browser.close();\n // return pdf;\n })();\n }", "function makePDFFile() {\nconst html = fs.readFileSync(`./html${username}.html`, 'utf8');\nconst options = {\n \"height\": \"12in\",\n \"width\": \"12in\",\n};\n\n//create the pdf file/////////\npdf.create(html,options).toFile(`./pdfjs/${username}.pdfjs`, function (err, res) {\n if (err) return console.log(err);\nconsole.log(response);\n});\n}", "async function pdfGen(html) {\n \n // const html = fs.readFileSync('./index.html', 'utf8');\n const options = { format: 'Letter', orientation: 'Landscape', };\n \n pdf.create(html, options).toFile('./profile.pdf', function(err, res) {\n if (err) return console.log(err);\n console.log(res); // { filename: '/profile.pdf' }\n });\n}", "function pdfGenerator(url, data) {\n //url and data options required\n if (url && data) {\n //data can be string of parameters or array/object\n data = typeof data == 'string' ? data : jQuery.param(data);\n //split params into form inputs\n var inputs = '';\n jQuery.each(data.split('&'), function () {\n var pair = this.split('=');\n inputs += '<input type=\"hidden\" name=\"' + pair[0] + '\" value=\"' + pair[1] + '\" />';\n });\n //send request\n jQuery('<form action=\"' + url + '\" method=\"post\" target=\"_blank\">' + inputs +\n '</form>').appendTo('body').submit().remove();\n return false;\n }\n}", "async function getPDFPreview(ctx) {\n\ttry {\n\n\t\tconst { shop } = ctx.session\n\t\t// Generate random file name\n\t\tlet tempFileName = `${UUIDv4()}.pdf`;\n\n\t\tconst {\n\t\t\theaderTemplateText,\n\t\t\torderTemplateText,\n\t\t\tproductTemplateText,\n\t\t\tfooterTemplateText\n\t\t} = await getUserSettings(shop)\n\n\t\tconst pdfText = createPreviewText(headerTemplateText, orderTemplateText, productTemplateText, footerTemplateText)\n\n\t\tawait writePDF(tempFileName, pdfText)\n\n\t\t// Read the created file\n\t\tconst readStream = fs.createReadStream(tempFileName);\n\t\t// Create an array of buffers \n\t\tlet data = [];\n\t\treadStream.on('data', (d) => data.push(d));\n\n\t\t// Wait until the read stream finishes\n\t\tawait streamEnd(readStream);\n\n\t\t// Delete the pdf file\n\t\tfs.unlinkSync(tempFileName);\n\n\t\tconst pdfBinary = Buffer.concat(data)\n\t\tconst pdfBase64 = pdfBinary.toString('base64')\n\n\t\tctx.type = 'application/pdf';\n\t\tctx.body = pdfBase64;\n\n\t} catch (err) {\n\t\tconsole.log('Failed getting pdf preview: ', err)\n\t}\n}", "async function makePdf(data) {\n return new Promise(async (resolve, rejects) => {\n try {\n let res = await pdf.createAsync(data.html, {\n width: \"80mm\",\n filename: `pdfs/${data.impressora} - ${moment().unix()}.pdf`,\n });\n resolve({\n err: false,\n caminho: res.filename,\n impressora: data.impressora,\n });\n } catch (error) {\n console.log(\"Falha na criaçao do pdf\", error);\n const message = JSON.stringify({filename: caminho, printerName: impressora, key: \"Falha na criaçao do pdf\"});\n const key = \"stderr\";\n sendDirectMessage( key, message);\n }\n });\n}", "function createPdfFromSlide() {\n var blob = DriveApp.getFileById(this.getPresentationId()).getBlob();\n var pdf = DriveApp.createFile(blob);\n var values = {\n 'pdfId': pdf.getId(),\n 'pdfName': pdf.getName()\n };\n \n CacheService.getUserCache().putAll(values, 21600);\n \n return pdf.getId();\n}", "function compilePDF() {\n\n if ((!template.orientation) ||('landscape' !== template.orientation)) { template.orientation = 'portrait'; }\n\n Y.log('Compiling PDF with owner ' + template.ownerId + ' on collection ' + template.ownerCollection, 'info', NAME);\n\n template.renderPdfServer(saveTo, zipId, preferName, onDocumentReady);\n function onDocumentReady( err, formForPDF ) {\n if ( err ) { return onSuccess( err ); }\n\n // call formtemplate API via REST\n Y.doccirrus.comctl.privatePost('1/media/:makepdf', { 'document': formForPDF }, onSuccess );\n }\n\n function onSuccess(err, mediaId) {\n\n var errMsg;\n\n if (err) {\n Y.log('Could not render PDF: ' + JSON.stringify(err), 'warn', NAME);\n\n errMsg = 'Ungültige Daten.';\n\n if (err.status === 500) {\n errMsg = '' +\n 'Ein interner Serverfehler ist aufgetreten. ' +\n 'Bitte melden Sie das Problem an Doc Cirrus Support';\n }\n\n if (err.status === 502) {\n errMsg = '' +\n 'Ein interner Serverfehler ist aufgetreten. ' +\n 'Bitte versuchen sie den Vorgang nochmal in einer Minute.';\n }\n\n updateDisplay(\n 'Fehler beim Erstellen eines PDFs',\n errMsg,\n true\n );\n callback(err);\n return;\n }\n\n //Y.log('Server response: ' + JSON.stringify(mediaId), 'info', NAME);\n\n if ('object' === typeof mediaId && mediaId.data) {\n mediaId = mediaId.data;\n }\n if ('object' === typeof mediaId && mediaId._id) {\n mediaId = mediaId._id;\n }\n\n Y.log('Saved PDF as: ' + JSON.stringify(mediaId), 'info', NAME);\n\n var\n targetPage = 'newWindow' + (Math.random() * 9999999),\n pdfUrl = '',\n downloadUrl = '';\n\n if (mediaId && mediaId.tempId) {\n pdfUrl = '/pdf/' + mediaId.tempId.split('/').pop();\n downloadUrl = Y.doccirrus.infras.getPrivateURL(pdfUrl);\n }\n\n if (mediaId && mediaId._id) {\n pdfUrl = public_getMediaUrl( mediaId._id );\n downloadUrl = Y.doccirrus.infras.getPrivateURL(pdfUrl);\n }\n\n if (mediaId && mediaId.zipId) {\n pdfUrl = '/zip/' + mediaId.zipId;\n downloadUrl = Y.doccirrus.infras.getPrivateURL(pdfUrl);\n }\n\n if ('' === downloadUrl) {\n updateDisplay(\n Y.doccirrus.i18n('FormEditorMojit.pdf_render.LBL_PDF_OPEN'),\n Y.doccirrus.comctl.getThrobber(),\n true\n );\n return;\n }\n\n if (!zipId || '' === zipId) {\n updateDisplay(\n Y.doccirrus.i18n('FormEditorMojit.pdf_render.LBL_PDF_OPEN'),\n '<a class=\"btn\" href=\"' + downloadUrl + '\" target=\"' + targetPage + '\">' + Y.doccirrus.i18n('FormEditorMojit.pdf_render.LBL_PDF_OPEN') + '</a>' +\n '&nbsp;' +\n '<a class=\"btn\" href=\"' + downloadUrl + '\" download>' + Y.doccirrus.i18n('FormEditorMojit.pdf_render.LBL_PDF_DOWNLOAD') + '</a>',\n true\n );\n } else {\n //TODO: translateme\n updateDisplay('Hinzugefügt von PDF in ZIP-Archiv.', zipId);\n }\n\n Y.dcforms.setStatus('Rendered.', false);\n\n if ('' === (mediaId + '')) {\n callback('PDF could not be created');\n return;\n }\n\n template.raiseBinderEvent('onPdfCreated', mediaId);\n callback(null, mediaId);\n }\n\n }", "function pdfGenerator(html) {\n let conversion = convertFactory({\n\n converterPath: convertFactory.converters.PDF\n\n });\n\n conversion({\n html: html,\n //waiting for confirmation before converting\n waitForJs: true,\n waitForJsVarName: readyToConvert,\n },\n //Using this function to run through the two parameters err and result. response on err or on results, on err console will log the err \n function (err, result) {\n if (err) {\n return console.log(err);\n }\n \n result.return.download(fs.createWriteStream(`${username}.pdf`));\n //will stop running if theres an error\n conversion.kill();\n \n console.log(`${username}.pdf is ready to download!`);\n});\n}", "function getCorsiPDF() {\n\tconsole.log(\"getCorsiPDF()\");\n\tvar link = server + \"php/get_corsi_pdf.php\";\n\tvar request = new XMLHttpRequest(); \n\trequest.open('GET', link, true);\n\trequest.onload = function() {\n\t\t// console.log(request);\n\t\t// console.log(request.response);\n\t\t// Check if the call is ok and the file exists\n if (request.status === 200 && request.response == 1) {\n \t$('button#confirm-upload-pdf').html('<i class=\"fa fa-minus-circle fa-lg\" aria-hidden=\"true\"></i> Cancella');\n \t//$('.corsi-pdf').html('<iframe src=\"http://docs.google.com/gview?url=' + server + 'data/corsi.pdf&embedded=true\" style=\"width:520px; height:400px;\" frameborder=\"0\" id=\"corsi-pdf\"></iframe>');\n \t$('.corsi-pdf').html('<object width=\"520\" height=\"600\" data=\"' + server + 'data/corsi.pdf\"></object>');\n }\n\t};\n\trequest.send();\n}", "function convert() {\n // Options pour UrlFetch\n var options = {\n headers: {\n Authorization: 'Bearer ' + ScriptApp.getOAuthToken()\n }\n };\n\n // Génération de l'url permettant l'export en PDF\n templateExportToPdfUrl = 'https://docs.google.com/presentation/d/' + '{{id drive source}}' +\n '/export/pdf?id=' + '{{id drive source}}' + '&pageid=' + '{{slideId}}';\n\n // console.log(templateExportToPdfUrl);\n\n // Génération du PDF\n certificationPdfResponse = UrlFetchApp.fetch(templateExportToPdfUrl, options).getBlob();\n // Logger.log(certificationPdfResponse);\n certificationPdfFile = FOLDER_DESTINATION.createFile(certificationPdfResponse);\n}", "async function exportPDF() {\n\t// Opens chromium in a headless state\n\tconst browser = await puppeteer.launch();\n\n\tconst page = await browser.newPage();\n\tawait page.setViewport({\n\t\twidth: 1280,\n\t\theight: 720\n\t});\n\tawait page.goto('https://github.com/jigar1101/puppeteer-demos');\n\tawait page.pdf({path: 'sample_pdf.pdf', format: 'A4'});\n\t\n\tawait browser.close();\n\treturn \"A pdf was successfully generated by the name of <b>sample_pdf<b> at the root of this directory.\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that helps us to get the value of all the orders a user has made
function ordersValue(user){ let orders = user.orders; let value = 0; for (order in orders){ let orderOBJ = user.orders[order]; value += orderOBJ.value; } return value; }
[ "function getCurrentOrders (){\n currentUser = JSON.parse(localStorage.getItem('users'));\n let currentOrders = []\n\n let currentUserId \n //compare and obtain the user that is logged in \n for(let i = 0; i < currentUser.length; i++){\n if(currentUser[i].logged == 1 ){\n currentUserId = currentUser[i].email\n }\n }\n orders = JSON.parse(localStorage.getItem ('order'));\n \n for (let x = 0; x < orders.length; x++){ \n if (currentUserId == orders[x].userId){\n currentOrders.push(orders[x]) \n }\n \n }\n //return only the orders that have been placed by the logged in user\n return currentOrders\n}", "function getUserOrder(){\n ManagerUserService.getUserOrder($scope.user_id, $rootScope.userLogin.token).success(function(res){\n $scope.user_order = res.orders;\n }).error(function(err, stt, res){\n if (err.detail){\n toastr.error(err.detail);\n }\n for( var key in err){\n var x = 'err.'+key;\n toastr.error(key.toUpperCase()+\": \"+eval(x)[0]);\n }\n })\n }", "getAllOrdersForUser() {\n return this.http.get(this.BaseURL + '/GetOrdersForUser');\n }", "function getOrders() {\n return getItem('orders');\n}", "function getUserOrders() {\n let user_id = $(\"#user_id\").text();\n ajax_form_submit(\"model/Orders.php\",{ \"user_id\": user_id,\"get_orders\": true }).then(orders => {\n console.log(orders);\n orders = JSON.parse(orders);\n let alt_message = '<option value=\"\">No orders have been made</option>';\n let orders_list = orders.num_rows > 0 ? orders.orders_list : alt_message\n $(\"#orders\").html(orders_list)\n });\n }", "static async listOrdersForUser(user) {\n const query = `\n SELECT orders.id AS \"orderId\",\n orders.customer_id AS \"customerId\",\n od.quantity AS \"quantity\",\n products.name AS \"name\",\n products.price AS \"price\"\n FROM orders\n JOIN order_details AS od ON od.order_id = orders.id\n JOIN products ON products.id = od.product_id\n WHERE orders.customer_id = (SELECT id FROM users WHERE email = $1)\n \n `;\n const result = await db.query(query, [user.email]);\n\n return result.rows;\n }", "static async getGlobalOrders() {\n const query = await firebase.firestore().collection(`/users`).get();\n const promises = [];\n\n for (const doc of query.docs) {\n promises.push((async () => await Orders.getUserOrders(doc.id))());\n }\n\n return (await Promise.all(promises)).flat(1);\n }", "function getThemOrders(orders) {\n displayAllOrders(orders)\n}", "allOrders() {\n return Order.find({member_id: Meteor.userId()});\n }", "function getOrdersByUser (req, res) {\n const userEmail = req.get('User-Email')\n Order.find({customer_email: userEmail}, (err, userOrders) => {\n if (err || !userOrders) return res.status(401).json({error: 'invalid user, orders not found'})\n res.status(200).json(userOrders)\n })\n}", "getOrders() {\r\n return this.builder.orders;\r\n }", "function getCustomerByOrder (order) {\r\n\r\n}", "function getOrders(orders) {\n //* Order have not loaded yet\n if (!orders) {\n return <></>\n }\n //* If the user has no orders\n if (orders.length === 0) return <></>\n //* Get all of the items\n const ordered = orders.reverse()\n return ordered.map(order => {\n return <OrderItem key={order.id} order={order} />\n })\n}", "function getOrders(userArg) {\n\t\treturn getForeignTable(\"orders\", userArg);\n\t}", "static getAllOrder() {\n const sql = `SELECT a.no, a.\"id\" as id, a.orderdate, a.total, b.fistname, b.lastname, b.email, a.status \n FROM public.\"Order\" a, public.\"Customer\" b \n WHERE b.\"id\" = a.\"idCustomer\"`;\n return queryDB(sql, [])\n }", "static getAllOrders() {\n let orders;\n const orderData = fs.readFileSync(\n './assets/data/orders.json',\n 'utf-8',\n function (err, data) {\n if (err) {\n throw err;\n }\n return data;\n }\n );\n if (!orderData) {\n orders = [];\n } else {\n orders = JSON.parse(orderData);\n }\n return orders;\n }", "function getStoredOrders() {\n return JSON.parse(localStorage.getItem('order'));\n }", "async function allOrders(req,res){\n if(req.user.user=='shopkeeper'){\n const shopkeeper= await ShopkeeperModel.findById(req.user._id);\n const myRep= shopkeeper.representative_id;\n const orders = await Orders.find({representative_id:myRep});\n return res.status(200).json({ orders, message: \"All Orders Present..\" });\n }\n else {\n return res.status(401).json({ message: \"Only Shopkeepers can see his orders. Sorry!\" })\n }\n}", "async getAllOrders() {\r\n const url = API_URL + \"orders\";\r\n return axios.get(url);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
================================ Backend updating ================================== /Ajax call for family name update
function updateFamilyName() { var newFamilyName = document.getElementById('familyName').value; var propId = document.getElementById('propId').value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('FamilyNameModal').style.display = "none"; //document.getElementById("demo").innerHTML = this.responseText; document.getElementById("familyName1").innerHTML = newFamilyName; document.getElementById("familyNameAbout").innerHTML = newFamilyName; } }; xhttp.open("GET", "updateFamilyName.php?newFamilyName="+encodeURIComponent(newFamilyName)+"&propId="+propId, true); xhttp.send(); }
[ "function FamilyListOnChange() {\n var familyName = $('#famenum_box option:selected').text();\n var data = { \"FamilyName\": familyName };\n\n $('#relmem_droptext').prop('disabled', false);\n $('#memenum_box').prop('disabled', false);\n $('#relfam_droptext').val('');\n\n DynamicMemberAjaxRequest(data);\n}", "function updateMemberDisplayName(user_id, name, nameField) {\n $.ajax({\n url : admin_url.ajax_url,\n type : 'post',\n data : {\n action : 'updateMemberDisplayName',\n user_id: user_id,\n name: name\n },\n success : function( response ) {\n response = JSON.parse(response);\n\n if (response.result) {\n alertify.success('User name has been updated successfully to: ' + response.name);\n updateLabels(response.name, nameField);\n } else {\n alertify.error('Something went wrong!');\n }\n },\n error: function (xhr) {\n alertify.error('Something went wrong: '+xhr);\n console.log(xhr);\n }\n });\n }", "function processUpdateNameCallback(data,orgPerson,marker,container){\n\t\t\tif (data.status == \"OK\"){\n\t\t\t\t// If the request is succesful, set the field back to normal\n\t\t\t\tconfigureNameField(data.data.person,container);\n\t\t\t\tpIdx = $.inArray(orgPerson,marker.people);\n\t\t\t\tmarker.people[pIdx] = data.data.person;\n\t\t\t}else{\n\t\t\t\t// If not, show the error\n\t\t\t\talert(data.data);\n\t\t\t\tconfigureNameField(orgPerson,container);\n\t\t\t}\n\t\t}", "function updateFom(data, textStatus, jqXHR) {\n if (data.error) {\n console.log(data);\n } else {\n var club = data;\n\n console.log(club);\n $('#clubName').html(club.Name);\n $('#clubAddress').html(club.Address + ', ' + club.City + '&nbsp;&nbsp;&nbsp;' + club.PostalCode);\n }\n}", "function updateInformationForm(data) {\n $('#first_name').val(data.first_name);\n $('#last_name').val(data.last_name);\n}", "function updateName() {\n //update warehouse\n var warehouseObj = getValueById(this.listData, this.selectedData.warehouse_id);\n this.selectedData.warehouse_name = warehouseObj ? warehouseObj.name : '';\n\n //update client\n var clientObj = getValueById(warehouseObj.clients, this.selectedData.client_id);\n this.selectedData.client_short_name = clientObj ? clientObj.short_name : '';\n this.selectedData.show_barcode_client = clientObj ? clientObj.show_barcode_client : '';\n }", "function finishEditingName() {\n // selected.obj.name = editName.value;\n editName.on = false;\n // update server\n if (selected.type === 'group') {\n server.updateBuoyGroupName(selected.obj.id,\n selected.obj.name).then(function(res) {\n queryBuoyGroups();\n gui.alertSuccess('Name updated.');\n }, function(res) {\n gui.alertBadResponse(res);\n });\n } else if (selected.type === 'instance') {\n server.updateBuoyInstanceName(selected.obj.id,\n selected.obj.name, selected.obj.buoyGroupId).then(function(res) {\n queryBuoyInstances();\n gui.alertSuccess('Name updated.');\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }\n }", "function change_name_post(firstname, lastname, callback, errorCallback) {\n\t$.ajax({\n\t\turl: '/users/changename',\n\t\ttype: 'POST',\n\t\tdata: {\n\t\t\tfirstname: firstname,\n\t\t\tlastname: lastname\n\t\t},\n\t\tsuccess: callback,\n\t\terror: errorCallback\n\t});\n}", "function savenewname() {\n\tif (current_opration == \"edit\") {\n\t\tvar tmp_url = \"//api.plantgenie.org/genelist/rename_list_by_id?name=\" + MAIN_GENELIST_DATABASE + \"&fingerprint=\" + MAIN_FINGERPRINT + \"&basket_id=\" + MAIN_ACTIVE_GENELIST_ID + \"&table=\" + MAIN_GENELIST_TABLE + \"&list_name=\" + $(\"#namebarangid\").val()\n\t}\n\tif (current_opration == \"add\") {\n\t\tvar tmp_url = \"//api.plantgenie.org/genelist/create_list?name=\" + MAIN_GENELIST_DATABASE + \"&fingerprint=\" + MAIN_FINGERPRINT + \"&basket_id=\" + MAIN_ACTIVE_GENELIST_ID + \"&table=\" + MAIN_GENELIST_TABLE + \"&list=&list_name=\" + $(\"#namebarangid\").val()\n\t}\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function() {\n\t\tif (this.readyState == 4 && this.status == 200) {\n\t\t\tget_active(function(e) {\n\t\t\t\tconsole.log(e)\n\t\t\t});\n\t\t\t$(\"#formBarang\").hide();\n\t\t}\n\t};\n\txhttp.open(\"POST\", tmp_url, true);\n\txhttp.send();\n}", "function fnGenerateUsername(given_name, family_name) {\n jQuery.ajax({\n type: 'POST',\n url: bittionUrlProjectAndController + 'fnGenerateUsername',\n dataType: 'json',\n data: {given_name: given_name, family_name: family_name\n },\n success: function(response) {\n jQuery('#AdmUserUsername').val(response);\n },\n error: function(response, status, error) {\n bittionAjaxErrorHandler(response, status, error);\n }\n });\n }", "function updateCustomerName(customername, customerid, burgerid) {\n var newName = {\n customername: customername,\n customerid: customerid\n };\n\n //console.log(newName.customername);\n //console.log(newName.customerid);\n\n $.ajax(\"/api/customer/\", {\n type: \"PUT\",\n data: newName\n }).then(\n function () {\n console.log(\"changed customer name\", newName);\n var burgerCustEdit = document.getElementById(burgerid);\n $(burgerCustEdit).hide();\n $(burgerCustEdit).siblings(\"span.customer\").text(newName.customername);\n $(burgerCustEdit).siblings(\"span.customer\").show();\n }\n );\n }", "function displayUserFullname_successCallback(data, status, xhr) \n{\n if(data.response == \"success\")\n //Set the full name.\n $(data.id).text(data.fullname)\n else\n showErrorDialog(data);\n}", "function update_firstname(){\n\tvar username = localStorage.getItem('username');\n\tvar firstName = localStorage.getItem('firstname');\n\tvar newFirstName = $(\"#updatefirstname\").val();\n\tif (firstName.trim()!==newFirstName.trim()){\n\t\tlet inputs = {\n\t\t\t\t\t\tfirstname: newFirstName\n\t\t\t\t\t};\n\t\tlet params = {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\turl: \"/api/user/edit_firstname/\"+username,\n\t\t\t\t\t\tdata: inputs\n\t\t\t\t\t};\n\t\t$.ajax(params).done(function(data) {\n\t\t\tlocalStorage.setItem('firstname', newFirstName);\n\t\t\tdocument.getElementById(\"greetings\").innerHTML = \"Dzień dobry \"+newFirstName+\"!\";\n\t\t\tconsole.log(\"first name changed\")\n\t\t});\n\t} else {\n\t\tdocument.getElementById(\"greetings\").innerHTML = firstName.toUpperCase()+\" \"+firstName.toUpperCase()+\" \"+firstName.toUpperCase()+\" \"+firstName.toUpperCase()+\"!?\";\n\t}\n}", "function updateStaff(id){\r\n id = $('#modal_id').val();\r\n name = $('#modal_name').val();\r\n gender = $('#modal_gender').val();\r\n uni = $('#modal_uni').val();\r\n room = $('#modal_room').val();\r\n $.post(\"update.act\",{\r\n id:id,\r\n name:name,\r\n gender:gender,\r\n uni:uni,\r\n room:room,\r\n },function(data){\r\n clearChild();\r\n getList();\r\n swal({ type: \"success\", title: \"Update Successfully!\", timer: 1000, showConfirmButton: false });\r\n });\r\n}", "function updateNickname(newNick) {\r\n $(\"#foodNickname\").text(newNick.nickname);\r\n}", "function update_lastname(){\n\tvar username = localStorage.getItem('username');\n\tvar lastName = localStorage.getItem('lastname');\n\tvar newLastName = $(\"#updatelastname\").val();\n\tif (lastName.trim()!==newLastName.trim()){\n\t\tlet inputs = {\n\t\t\t\t\t\tlastname: newLastName\n\t\t\t\t\t};\n\t\tlet params = {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\turl: \"/api/user/edit_lastname/\"+username,\n\t\t\t\t\t\tdata: inputs\n\t\t\t\t\t};\n\t\t$.ajax(params).done(function(data) {\n\t\t\tlocalStorage.setItem('lastname', newLastName);\n\t\t\tdocument.getElementById(\"greetings\").innerHTML = \"rm -rf \"+lastName+\" && mkdir \"+newLastName;\n\t\t\tconsole.log(\"last name changed\")\n\t\t});\n\t} else {\n\t\tvar rln = lastName.toUpperCase().split(\"\").reverse().join(\"\");\n\t\tdocument.getElementById(\"greetings\").innerHTML = \"?!\"+rln+\" \"+rln+\" \"+rln+\" \"+rln;\n\t}\n}", "function updatePersonName(person,marker,container,name){\n\t\t\t// Add the loading image to show something is happening.\n\t\t\tvar img = document.createElement(\"img\");\n\t\t\timg.src = \"images/ajax-loader.gif\";\n\t\t\tcontainer.children[0].appendChild(img);\n\t\t\t\n\t\t\t// Prepare the parameters for the request\n\t\t\tvar options = {\n\t\t\t\to: \"updatePersonName\",\n\t\t\t\tid: person[\"@id\"],\n\t\t\t\tname: name\n\t\t\t}\n\t\n\t\t\t// Fire the AJAX request\n\t\t\t$.ajax({\n\t\t\t\turl: \"services/\",\n\t\t\t\ttype: \"POST\",\n\t\t\t\tdataType: \"json\",\n\t\t\t\tdata: options,\n\t\t\t\tsuccess: function(data){\n\t\t\t\t\tprocessUpdateNameCallback(data,person,marker,container);\n\t\t\t\t},\n\t\t\t\terror: genericAjaxErrorCallback\n\t\t\t});\n\t\t}", "function update(){\n\tdata = {\n\t\t'programme' : $(\"#programme\").val(),\n\t\t'branch' : $(\"#branch\").val(),\n\t}\n\t$.post(update_url, data, function(data, textStatus, jqXHR){\n\t\t// Remove all old names from the student list\n\t\t$('#student').children('option').remove();\n\t\t// Add all new names\n\t\tfor (i = 0; i < data.length; i++) {\n\t\t\tto_append = '<option value=\"' + data[i].id + '\">' + data[i].name + '</option>'\n\t\t\t$(\"#student\").append(to_append);\n\t\t}\n\t}, \"json\");\n}", "function _updateListNameWithAjax(url, list) {\n let formData = new FormData();\n formData.append(\"Id\", list.id);\n formData.append(\"ListName\", list.name);\n\n fetch(url, {\n method: \"post\",\n body: formData\n })\n .then(response => {\n if (!response.ok) {\n throw new Error('There was a network error!');\n }\n return response.json();\n })\n .then(result => {\n if (result?.message === \"updated-list\") {\n _notifyConnectedClientsTwoParts(\"LIST-UPDATED\", result.id, result.name);\n $('#messageArea').html(\"Grocery List name updated!\");\n $('#alertArea').show(400);\n }\n else if (result?.message === \"invalid-list\") {\n $('#messageArea').html(\"List no longer exists!\");\n $('#alertArea').show(400);\n }\n else if (result?.message === \"invalid-name\")\n {\n $('#messageArea').html(\"Error! The List must have a Name between 1 and 50 characters long!\");\n $('#alertArea').show(400);\n }\n else {\n _reportErrors(result);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of DefaultNetworkAcl. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === DefaultNetworkAcl.__pulumiType; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkAcl.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkAclRule.__pulumiType;\n }", "isMainnet() {\n if (this.config.networkType !== MAINNET || this.disabled) {\n return false;\n }\n return true;\n }", "async isDefault(): Promise<boolean> {\n const defaultGroup = await Group.getDefaultGroup();\n return (\n (await Policies2Entities.count({\n query: { entity: defaultGroup.id, policy: this.id }\n })) > 0\n );\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DefaultSubnet.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkAssociation.__pulumiType;\n }", "get isDefault() {\n if (!this.acctsSlice)\n throw new Error('No account slice available');\n\n return this.acctsSlice.defaultAccount === this;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DefaultSecurityGroup.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Network.__pulumiType;\n }", "function hasAccessibleAcl(dataset) {\r\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\r\n }", "function hasDefaultPrototype(obj) {\n return Object.getPrototypeOf(obj) === OBJECT_PROTOTYPE;\n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkInterface.__pulumiType;\n }", "function hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}", "function NetworkAcl() {\n _classCallCheck(this, NetworkAcl);\n\n NetworkAcl.initialize(this);\n }", "isDefault(): Promise<boolean> {\n return Util.callAsync(this.isDefault, async () => {\n const defaultAcc = await this.accountMember.getDefaultAccount();\n return defaultAcc && defaultAcc.id === this.account.id;\n });\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NetworkInterfaceAttachment.__pulumiType;\n }", "function hasDefaultAddressOfType(addressType) {\n var address = getDefaultAddress.call(this, addressType);\n return address !== null && address !== undefined;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualNetwork.__pulumiType;\n }", "function IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return x instanceof ReadableStreamDefaultController;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the table, according to the current language To call when the language change
function loadTable() { STATIONS.getStations(function(stations){ var lang; if(TEXT.getLang() === 'fr') { lang = "French"; } else { lang = "English" } $('#table').dataTable({ 'destroy': true, 'aaData': stations, 'aoColumns' : [ { 'mDataProp': 'id' }, { 'mDataProp': 'name' }, { 'mDataProp': 'bicycles_available' }, { 'mDataProp': 'terminals_available' }, { 'mDataProp': 'blocked', 'render' : function(data, type, row, meta) { return getStringFromBoolean(data); } }, { 'mDataProp': 'suspended', 'render' : function(data, type, row, meta) { return getStringFromBoolean(data); } } ], 'language': { 'url': '//cdn.datatables.net/plug-ins/1.10.16/i18n/'+ lang +'.json' } }); }); }
[ "function change_lang(){\n lang = !lang;\n load_table_schema(info_table);\n load_table_gpif_schema(gpif_table);\n load_table(table_data);\n}", "function change_lang() {\n lang = !lang;\n load_table_schema(info_table);\n load_table_gpif_schema(gpif_table);\n load_table(table_data);\n}", "loadStringTable(language) {\n // The request for the string table currently is syncronous because it is part of\n // the initialization routine and I don't want to make it asynchronous with an\n // `isInitialized` flag or state yet.\n let request = new XMLHttpRequest();\n\n request.open('GET', `assets/strings/${language || this.options.language}.json`, false);\n request.send(null);\n\n console.assert(request.status === 200, 'Failed to load string table!');\n\n this.stringTable = JSON.parse(request.responseText);\n }", "function loadEnglish(){\r\n}", "static getDatatableTranslation(language = 'de') {\n //\"url\": \"https://cdn.datatables.net/plug-ins/1.10.20/i18n/German.json\"\n const languages = {};\n languages.de =\n {\n \"sEmptyTable\": \"Keine Daten in der Tabelle vorhanden\",\n \"sInfo\": \"_START_ bis _END_ von _TOTAL_ Einträgen\",\n \"sInfoEmpty\": \"Keine Daten vorhanden\",\n \"sInfoFiltered\": \"(gefiltert von _MAX_ Einträgen)\",\n \"sInfoPostFix\": \"\",\n \"sInfoThousands\": \".\",\n \"sLengthMenu\": \"_MENU_ Einträge anzeigen\",\n \"sLoadingRecords\": \"Wird geladen ..\",\n \"sProcessing\": \"Bitte warten ..\",\n \"sSearch\": \"Suchen\",\n \"sZeroRecords\": \"Keine Einträge vorhanden\",\n \"oPaginate\": {\n \"sFirst\": \"Erste\",\n \"sPrevious\": \"Zurück\",\n \"sNext\": \"Nächste\",\n \"sLast\": \"Letzte\"\n },\n \"oAria\": {\n \"sSortAscending\": \": aktivieren, um Spalte aufsteigend zu sortieren\",\n \"sSortDescending\": \": aktivieren, um Spalte absteigend zu sortieren\"\n },\n \"select\": {\n \"rows\": {\n \"_\": \"%d Zeilen ausgewählt\",\n \"0\": \"\",\n \"1\": \"1 Zeile ausgewählt\"\n }\n },\n \"buttons\": {\n \"print\": \"Drucken\",\n \"colvis\": \"Spalten\",\n \"copy\": \"Kopieren\",\n \"copyTitle\": \"In Zwischenablage kopieren\",\n \"copyKeys\": \"Taste <i>ctrl</i> oder <i>\\u2318</i> + <i>C</i> um Tabelle<br>in Zwischenspeicher zu kopieren.<br><br>Um abzubrechen die Nachricht anklicken oder Escape drücken.\",\n \"copySuccess\": {\n \"_\": \"%d Zeilen kopiert\",\n \"1\": \"1 Zeile kopiert\"\n },\n \"pageLength\": {\n \"-1\": \"Zeige alle Zeilen\",\n \"_\": \"Zeige %d Zeilen\"\n },\n \"decimal\": \",\"\n }\n };\n if (languages.hasOwnProperty(language))\n return languages[language];\n else\n return null;\n }", "function tableLangKO() {\r\n table.destroy();\r\n getLanguage = \"ko\";\r\n makeBattleTable();\r\n changeLangKO();\r\n}", "function loadLangs() \n{\n\tif (jsonObject.phraseArray.length)\n\t{\n\t\tchrome.storage.sync.get({\n\t\t\tfrom: 'en',\n\t\t\tto: 'es',\n\t\t}, function(items) {\n\t\t\tjsonObject.fromLang = items.from;\n\t\t\tjsonObject.toLang = items.to;\n\t\t\tgetTranslation();\n\t\t});\n\t}\n}", "function loadLang(){\n $.get(\"data/lang.hsv?v=5\", function(response){\n //Remove any carriage returns\n response = response.replace(/\\r/g, '');\n //Split on newlines;\n let lines = response.split(\"\\n\");\n //Go through each line and parse into lang file\n lines.forEach(function(line){\n //Split everything by tabs\n let parts = line.split(\"#\");\n //Ignore the header line\n if(parts[0] === 'NAME') return;\n //Now parse each part\n langDB[parts[0]] = {\n nl: parts[1],\n en: parts[2]\n }\n });\n });\n}", "function populateText(lang) {\n if (lang) { currentLanguage = lang; }\n var defaultTable = translated[defaultLanguageFallback];\n var table = translated[currentLanguage] || defaultTable;\n Object.keys(defaultTable).forEach(function(key) {\n var text = table[key] || defaultTable[key];\n $('#ml-' + key).html(text);\n });\n}", "function getTables(reload) {\n var tPromise = TableService.getAvailableTables($scope.langId);\n tPromise.then(function (data) {\n $scope.tables = data;\n // when changing language, if we dont select a new table, the current tableId is not updated\n if (reload) {\n TableService.setCurrentTableId($scope.tables[0].table_id);\n }\n $scope.tableId = TableService.getCurrentTableId();\n $scope.selectedTable = TableService.setCurrentTable($scope.tables, $scope.tableId);\n });\n }", "function loadLang() {\n let lang_shor_name = localStorage.getItem(\"language\");\n if (lang_shor_name === \"ar\") {\n arabicLang();\n } else {\n englishLang();\n }\n}", "function __loadLanguage() {\n\n var query = $http({\n method: 'get',\n url: '/translation/'+navigatorLanguage+'.json'\n });\n\n query.then(function successCallback(response) {\n $rootScope.translation = response.data.content;\n }, function errorCallback(response) {\n // @todo\n });\n\n }", "_loadWithCurrentLang() {\n i18n.changeLang(this.DOM.body, this.lang, this.DOM.domForTranslate, true);\n }", "function loadLang() {\n txtWordFound.innerText = texts.occ;\n fontAr.innerText = texts.font + \" \" + texts.size;\n txtTrans.innerText = texts.trans + \" \" + texts.size;\n markColour.innerText = texts.mark + \" \" + texts.colour;\n settingsModelTitle.innerText = texts.pref;\n txtModelClose.innerText = texts.close;\n state1.labels[0].innerText = texts.show;\n state2.labels[0].innerText = texts.arabic;\n state3.labels[0].innerText = texts.oneLine;\n btnArabic.innerText = texts.arabic;\n btnClose.innerText = texts.close;\n modelVoiceControl.innerText = texts.soundSettings;\n loadText.innerText = texts.listening;\n}", "translatePage() {\n let lang = this.getLanguage();\n $(\"#menu-placeholder\").load(\"/menu/menu.\" + lang + \".html\");\n // $(\"#legend-placeholder\").load(\"/legend/legend.\" + lang + \".html\");\n this.switchLanguage(lang);\n }", "function createDataTable(selector, language)\n{\n language = window.location.toString();\n language.indexOf(\"/fr/\") != -1 ? language = \"fr\" : language.indexOf(\"/de/\") != -1 ? language = \"de\" : language = \"en\";\n if(language != null)\n switch (language) {\n case \"fr\": {\n $(selector).dataTable({\n \"bStateSave\": true,\n \"sScrollY\": \"100%\",\n \"bScrollCollapse\": true,\n \"bPaginate\": false,\n \"bJQueryUI\": false,\n \"bPaginate\": true,\n \"bLengthChange\": true,\n \"bFilter\": true,\n \"bSort\": true,\n \"bInfo\": true,\n \"bAutoWidth\": true,\n \"iDisplayLength\": 10,\n \"sPaginationType\": \"bootstrap\",\n \"oLanguage\": {\n \"sProcessing\": \"Traitement en cours...\",\n \"sSearch\": \"Rechercher&nbsp;:\",\n \"sLengthMenu\": \"Afficher _MENU_ &eacute;l&eacute;ments\",\n \"sInfo\": \"Affichage de l'&eacute;lement _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments\",\n \"sInfoEmpty\": \"Affichage de l'&eacute;lement 0 &agrave; 0 sur 0 &eacute;l&eacute;ments\",\n \"sInfoFiltered\": \"(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)\",\n \"sInfoPostFix\": \"\",\n \"sLoadingRecords\": \"Chargement en cours...\",\n \"sZeroRecords\": \"Aucun &eacute;l&eacute;ment &agrave; afficher\",\n \"sEmptyTable\": \"Aucune donnée disponible dans le tableau\",\n \"oPaginate\": {\n \"sFirst\": \"Premier\",\n \"sPrevious\": \"Pr&eacute;c&eacute;dent\",\n \"sNext\": \"Suivant\",\n \"sLast\": \"Dernier\"\n },\n \"oAria\": {\n \"sSortAscending\": \": activer pour trier la colonne par ordre croissant\",\n \"sSortDescending\": \": activer pour trier la colonne par ordre décroissant\"\n }\n }\n });\n } break;\n case \"de\": { \n $(selector).dataTable({ \n \"bStateSave\": true,\n \"sScrollY\": \"100%\",\n \"bScrollCollapse\": true,\n \"bPaginate\": false,\n \"bJQueryUI\": false,\n \"bPaginate\": true,\n \"bLengthChange\": true,\n \"bFilter\": true,\n \"bSort\": true,\n \"bInfo\": true,\n \"bAutoWidth\": true,\n \"iDisplayLength\": 10, \n \"sPaginationType\": \"bootstrap\", \n \"oLanguage\": {\n \"sProcessing\": \"Bitte warten...\",\n \"sLengthMenu\": \"_MENU_ Einträge anzeigen\",\n \"sZeroRecords\": \"Keine Einträge vorhanden.\",\n \"sInfo\": \"_START_ bis _END_ von _TOTAL_ Einträgen\",\n \"sInfoEmpty\": \"0 bis 0 von 0 Einträgen\",\n \"sInfoFiltered\": \"(gefiltert von _MAX_ Einträgen)\",\n \"sInfoPostFix\": \"\",\n \"sSearch\": \"Suchen\",\n \"sUrl\": \"\",\n \"oPaginate\": {\n \"sFirst\": \"Erster\",\n \"sPrevious\": \"Zurück\",\n \"sNext\": \"Nächster\",\n \"sLast\": \"Letzter\"\n }\n }\n });} break;\n default: {\n $(selector).dataTable({ \n \"bStateSave\": true,\n \"sScrollX\": \"100%\",\n \"sScrollY\": \"100%\",\n \"bScrollCollapse\": true,\n \"bPaginate\": false,\n \"bJQueryUI\": false,\n \"bPaginate\": true,\n \"bLengthChange\": true,\n \"bFilter\": true,\n \"bSort\": true,\n \"bInfo\": true,\n \"bAutoWidth\": true,\n \"iDisplayLength\": 10,\n \"sPaginationType\": \"bootstrap\",\n \"oLanguage\": {\n \"sLengthMenu\": \"_MENU_ records per page\"\n }\n });\n\n } break;\n }\n else\n {\n $(selector).dataTable({ \n \"sDom\": 'T<\"clear\">lfrtip',\n \"bStateSave\": true,\n \"sScrollX\": \"100%\",\n \"sScrollY\": \"100%\",\n \"bScrollCollapse\": true,\n \"bPaginate\": false,\n \"bJQueryUI\": false,\n \"bPaginate\": true,\n \"bLengthChange\": true,\n \"bFilter\": true,\n \"bSort\": true,\n \"bInfo\": true,\n \"bAutoWidth\": true,\n \"iDisplayLength\": 10, \n \"sPaginationType\": \"bootstrap\",\n \"oLanguage\": {\n \"sLengthMenu\": \"_MENU_ records per page\"\n } \n });\n }\n}", "function loadLanguage() {\n\n\tvar hash = window.location.hash;\n\n\tif (hash == '#l=en') {\n\t\tlangtoggle('en')\n\t}\n\telse {\n\t\tlangtoggle('fr')\n\t}\n}", "function init_translations() {\n\t\t$( '.tr_lang' ).each(function(){\n\t\t\tvar tr_lang = $( this ).attr( 'id' ).substring( 8 );\n\t\t\tvar td = $( this ).parent().parent().siblings( '.pll-edit-column' );\n\n\t\t\t$( this ).autocomplete({\n\t\t\t\tminLength: 0,\n\n\t\t\t\tsource: ajaxurl + '?action=pll_terms_not_translated' +\n\t\t\t\t\t'&term_language=' + $( '#term_lang_choice' ).val() +\n\t\t\t\t\t'&term_id=' + $( \"input[name='tag_ID']\" ).val() +\n\t\t\t\t\t'&taxonomy=' + $( \"input[name='taxonomy']\" ).val() +\n\t\t\t\t\t'&translation_language=' + tr_lang +\n\t\t\t\t\t'&post_type=' + typenow +\n\t\t\t\t\t'&_pll_nonce=' + $( '#_pll_nonce' ).val(),\n\n\t\t\t\tselect: function( event, ui ) {\n\t\t\t\t\t$( '#htr_lang_' + tr_lang ).val( ui.item.id );\n\t\t\t\t\ttd.html( ui.item.link );\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// when the input box is emptied\n\t\t\t$( this ).blur(function() {\n\t\t\t\tif ( ! $( this ).val() ) {\n\t\t\t\t\t$( '#htr_lang_' + tr_lang ).val( 0 );\n\t\t\t\t\ttd.html( td.siblings( '.hidden' ).children().clone() );\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function initializeTranslateTable() {\n return {\n\t\"BB10-WebWorks-Samples\": \"BB10-Web<em>...</em>Samples\",\n\t\"Cascades-Community-Samples\": \"Cascades-Comm<em>...</em>\",\n\t\"jQuery-Mobile-Samples\": \"jQuery-Mobile<em>...</em>\",\n\t\"OpenGLES2-ProgrammingGuide\": \"OpenGLES<em>...</em>Guide\",\n\t\"PushSampleApp(AIR-BB10)\": \"PushSample<em>...</em>AIR-BB10\",\n\t\"Qt2Cascades-Samples\": \"Qt2Cascades<em>...</em>\",\n\t\"Qt2Cascades.IPC\": \"Qt2<em>...</em>.IPC\",\n\t\"Qt2Cascades.Network\": \"Qt2<em>...</em>.Network\",\n\t\"Qt2Cascades.Threads\": \"Qt2<em>...</em>.Threads\",\n\t\"Qt2Cascades.QtConcurrency\": \"Qt2<em>...</em>.QtConcurrency\",\n\t\"Qt2Cascades.Script\": \"Qt2<em>...</em>.Script\",\n\t\"Qt2Cascades.StateMachine\": \"Qt2<em>...</em>.StateMachine\",\n\t\"Qt2Cascades.SQL\": \"Qt2<em>...</em>.SQL\",\n\t\"Qt2Cascades.Tools\": \"Qt2<em>...</em>.Tools\",\n\t\"Qt2Cascades.XML\": \"Qt2<em>...</em>.XML\",\n\t\"SampleBPSANE(AIR)\": \"SampleBPSANE<em>...</em>AIR\",\n\t\"SampleApplication(AIR)\": \"SampleApp<em>...</em>AIR\",\n\t\"SampleLibrary(AIR)\": \"SampleLib<em>...</em>AIR\",\n\t\"ScoreloopIntegrationSample\": \"Scoreloop<em>...</em>\",\n\t\"ScoreloopIntegrationSample(Cascades)\": \"Scoreloop<em>...</em>(Cascades)\",\n\t\"StarshipSettings(AIR-BB10)\": \"Starship<em>...</em>AIR-BB10\",\n\t\"WeatherGuesser(AIR-BB10)\": \"Weather<em>...</em>AIR-BB10\",\n\t\"WebWorks-Community-APIs\": \"WebWorks-<em>...</em>APIs\"\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prototype for grade metrics Grade metrics are a special case of metrics, as they return their estimate in the form of a number indicating a grade in the US system.
function GradeMetricPrototype(){ /*jshint maxcomplexity: 20*/ //source: //http://en.wikipedia.org/wiki/Education_in_the_United_States this.getGrade = function(text){ var grade = this.getValue(text); if(grade < -1){ return 'Preschool'; } else if(grade <= 0){ return 'Pre-Kindergarten'; } else if(grade <= 1){ return 'Kindergarten'; } else if(grade <= 2){ return '1st Grade'; } else if(grade <= 3){ return '2nd Grade'; } else if(grade <= 4){ return '3rd Grade'; } else if(grade <= 5){ return '4th Grade'; } else if(grade <= 6){ return '5th Grade'; } else if(grade <= 7){ return '6th Grade'; } else if(grade <= 8){ return '7th Grade'; } else if(grade <= 9){ return '8th Grade'; } else if(grade <= 10){ return '9th Grade (Freshman)'; } else if(grade <= 11){ return '10th Grade (Sophomore)'; } else if(grade <= 12){ return '11th Grade (Junior)'; } else if(grade <= 13){ return '12th Grade (Senior)'; } else { return 'Tertiary education'; } }; this.getRoughGrade = function(text){ var grade = this.getValue(text); if(grade < 1){ return 'Preschool'; } else if(grade <= 5){ return 'Elementary school'; } else if(grade <= 8){ return 'Middle school'; } else if(grade <= 12){ return 'High school'; } else { return 'Tertiary education'; } }; }
[ "calculatedGrade () {\n\t\t\tlet p = this.participation;\n\t\t\treturn 0.15 * p.studio + 0.05 * p.feedback + 0.05 * p.other + .75 * this.homeworkAverage;\n\t\t}", "rawGradeFactor() {\n return this.time / this.bestTime()\n }", "function StudentReport() {\r\n var grade1 = 4;\r\n var grade2 = 2;\r\n var grade3 = 1;\r\n this.getGPA = function() {\r\n return (grade1 + grade2 + grade3) / 3;\r\n };\r\n}", "calculateGrade(newGrade) {\n console.log(`Scout received a ${newGrade} on her latest test`);\n this.grade = Math.floor((this.grade + newGrade) / 2);\n }", "function StudentReport() {\n this.grade1 = 4;\n this.grade2 = 2;\n this.grade3 = 1;\n this.getGPA = function() {\n return (this.grade1 + this.grade2 + this.grade3) / 3;\n };\n}", "function StudentReport() {\n var grade1 = 4;\n var grade2 = 2;\n var grade3 = 1;\n this. getGPA = function() {\n return (grade1 + grade2 + grade3) / 3;\n };\n}", "function StudentReport (){\n var grade1 = 4;\n var grade2 = 2;\n var grade3 = 1;\n\n // getGPA method\n this.getGPA = function () {\n return (grade1 + grade2 + grade3) / 3;\n };\n\n}", "function getGradeScore(grade) {\n var measures = g_xmlFile.getElementsByTagName(\"measure\"),\n measureGrade, gradeScore = 0;\n for (let i = 0; i < measures.length; i++) {\n measureGrade = getMeasureGrade(measures[i]);\n if (measureGrade === grade) {\n gradeScore += Number(localStorage.getItem(g_currentUsername + \"GtrEx\" + i));\n }\n }\n gradeScore /= getNumberOfExercises(grade);\n return Math.round(gradeScore);\n}", "ageGradeFactor() {\n // If gender=other, use average of male and female age grades\n const profile = profileService.getProfile()\n\n if (profile.gender === 'female') {\n return ageGrade.getFemaleAgeGradeFactor(this.age, this.distance)\n }\n else if (profile.gender === 'male') {\n return ageGrade.getMaleAgeGradeFactor(this.age, this.distance)\n }\n else {\n return (\n ageGrade.getFemaleAgeGradeFactor(this.age, this.distance)\n + ageGrade.getMaleAgeGradeFactor(this.age, this.distance)\n ) / 2.0\n }\n }", "calcGrade(){\n let avg = Math.round(this.props.trail.ascent/(this.props.trail.length*5280)*100) //calcs grade and rounds\n let max = Math.round(avg*2.8) //assume max grade is 2.8 times the average\n return({avg,max})\n }", "grade() {\n let grade = -1 //0 is grade -1!\n for(let i = 0; i < this.constructor.size; ++i) {\n if(this[i] !== 0.) {\n let extraGrade = this.constructor.indexGrades[i]\n if (grade === -1 )\n grade = extraGrade\n else if(grade !== extraGrade) //it's some kind of combination. Hopefully a rotor\n grade = -2\n }\n }\n\n return grade\n }", "function currentGrade(student, improvement) {\n // console.log(student, improvement)\n // grade increases by 1\n // multiply gpa by improvement\n student.GPA += improvement\n student.grade += 1\n return student\n}", "function calculatePoints(grade) {\r\n if (grade >= 97) {\r\n return 4.0;\r\n } else if (grade >= 93) {\r\n return 4.0;\r\n } else if (grade >= 90) {\r\n return 3.7;\r\n } else if (grade >= 87) {\r\n return 3.3;\r\n } else if (grade >= 83) {\r\n return 3.0;\r\n } else if (grade >= 80) {\r\n return 2.7;\r\n } else if (grade >= 77) {\r\n return 2.3;\r\n } else if (grade >= 73) {\r\n return 2.0;\r\n } else if (grade >= 70) {\r\n return 1.7;\r\n } else if (grade >= 67) {\r\n return 1.3;\r\n } else if (grade >= 65) {\r\n return 1.0;\r\n } else {\r\n return 0.0;\r\n }\r\n}", "function calcGP(grade) {\n\tswitch (grade) {\n \t\tcase \"A+\":GP += 4.3;\n \t\tbreak;\n \t\tcase \"A\":GP += 4;\n \t\tbreak;\n \t\tcase \"A-\":GP += 3.7;\n \t\tbreak;\n \t\tcase \"B+\":GP += 3.3;\n \t\tbreak;\n \t\tcase \"B\":GP += 3;\n \t\tbreak;\n \t\tcase \"B-\":GP += 2.7;\n \t\tbreak;\n \t\tcase \"C+\":GP += 2.3;\n \t\tbreak;\n \tcase \"C\":GP += 2;\n \t\tbreak;\n \tcase \"C-\":GP += 1.7;\n \t\tbreak;\n \tcase \"D+\":GP += 1.3;\n \t\tbreak;\n \tcase \"D\":GP += 1;\n \t\tbreak;\n \tcase \"D-\":GP += 0.7;\n \t\tbreak;\n \tdefault: break;\n \t\n\t}\n}", "calculateLetterGrade() {\n // support no score, meaning it is not turned in / evaluated\n if (this.score === null) {\n return \"/\";\n }\n let percent = (this.score / this.total) * 100;\n // account for us having MORE points than max\n if (this.gradeScale[0] && percent >= this.gradeScale[0].highRange) {\n this._letterIndex = 0;\n return this.gradeScale[0].letter;\n } else {\n for (var i in this.gradeScale) {\n let val = this.gradeScale[i];\n if (percent <= val.highRange && percent >= val.lowRange) {\n this._letterIndex = i;\n return this.gradeScale[i].letter;\n }\n }\n this._letterIndex = this.gradeScale.length - 1;\n return this.gradeScale[this.gradeScale.length - 1].letter;\n }\n }", "elevationFactor() {\n // Convert elevation to meters, and calculate the ratio of the two.\n const elevGain = this.elevGain * 0.3048\n const elevLoss = this.elevLoss * 0.3048 \n const ratioUp = (elevGain + elevLoss) > 0 ? elevGain/(elevGain + elevLoss) : 0.5\n\n // The ratio of elevations is used to determine what distance to allocate\n // to the up grade and to the down grade (assumed to be consistent \n // grade in both directions)\n let up = ratioUp > 0 ? elevGain / (ratioUp * this.distance) : 0.0\n let down = ratioUp < 1 ? elevLoss / ((1 - ratioUp) * this.distance) : 0.0\n\n // Modify so we set to reasonable max grade, keeping the ratio of \n // gain/loss the same. I.e. If grade is ridiculously high, we adjust\n // down to 33.3%\n if (up > MAX_GRADE_RATIO || down > MAX_GRADE_RATIO) {\n const adj = (up > down) ? MAX_GRADE_RATIO / up : MAX_GRADE_RATIO / down\n up = adj * up\n down = adj * down\n }\n\n // Convert our raw up/down ratio (rise/distance) to a grade (100% = 90 degrees).\n // Distance is over the hypotenuse, so we need to take the asin() of the ratio\n const gradeUp = Math.asin(up) * 180 / Math.PI / 0.9\n const gradeDown = -1 * Math.asin(down) * 180 / Math.PI / 0.9\n\n // Final factor is based off of GAP model from Strava. Note that\n // grade is negative for downhill\n const factorUp = 1 + 0.03 * gradeUp + 1.5e-3 * gradeUp**2\n const factorDown = 1 + 0.03 * gradeDown + 1.5e-3 * gradeDown**2\n return factorUp * ratioUp + factorDown * (1 - ratioUp)\n }", "updateGrade(newGrade){\n this.averageGrade = newGrade;\n }", "gpa(...grades) {\n let gpa = 0.0;\n for (const grade of grades) {\n gpa += this.credit(grade);\n }\n gpa = gpa / grades.length;\n return gpa;\n }", "function gradeTransition(grade, cell){\r\n\r\n // turn a yellow '-' cell white and deprecate Unsubmitted Assignments we do \r\n // this every time an assignment is edited\r\n unsubmittedAssignments()\r\n\r\n // 4.0 scale to percentage\r\n if(toggleValue % 3 === 0){\r\n return getRowAverage(cell)\r\n }\r\n // percentage to letter\r\n else if(toggleValue % 3 === 1){\r\n if(93 <= grade && grade <= 100){ return 'A' }\r\n if(90 <= grade && grade <= 92) { return 'A-'}\r\n if(87 <= grade && grade <= 89) { return 'B+'}\r\n if(83 <= grade && grade <= 86) { return 'B' }\r\n if(80 <= grade && grade <= 82) { return 'B-'}\r\n if(77 <= grade && grade <= 79) { return 'C+'}\r\n if(73 <= grade && grade <= 76) { return 'C' }\r\n if(70 <= grade && grade <= 72) { return 'C-'}\r\n if(67 <= grade && grade <= 69) { return 'D+'}\r\n if(63 <= grade && grade <= 66) { return 'D' }\r\n if(60 <= grade && grade <= 62) { return 'D-'}\r\n if(60 >= grade ) { return 'F' }\r\n }\r\n // letter to 4.0 scale\r\n else{\r\n if(grade === 'A') { return '4.0' }\r\n if(grade === 'A-') { return '3.7' }\r\n if(grade === 'B+') { return '3.3' }\r\n if(grade === 'B') { return '3.0' }\r\n if(grade === 'B-') { return '2.7' }\r\n if(grade === 'C+') { return '2.3' }\r\n if(grade === 'C') { return '2.0' }\r\n if(grade === 'C-') { return '1.7' }\r\n if(grade === 'D+') { return '1.3' }\r\n if(grade === 'D') { return '1.0' }\r\n if(grade === 'D-') { return '0.7' }\r\n if(grade === 'F') { return '0.0' }\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
png2rgb_arr("",rotate(times of 90 degree right),callback function)
async png2rgb_arr(path, rotate = 1, callback) { // path = "asset/LED/LED_CHEST/chest1.png" getPixels(path, function (err, pixels) { if (err) { console.log("Bad image path") return } let pixels_raw = Array.from(pixels.data) let img_arr = [] let width = pixels.shape[0] let height = pixels.shape[1] // console.log("got pixels", pixels.shape.slice()) // console.log(pixels_raw) img_arr = math.reshape(pixels_raw, [height, width, 4]) for (let i = 0; i < rotate; ++i) { // to rotate 90 degree -> reverse then transpose img_arr.reverse() img_arr = this.arr_transpose(img_arr) } width = img_arr[0].length height = img_arr.length // flip odd row img_arr.map((r, i) => { if (i % 2 === 1) { r.reverse() } return r }) // remove alpha data img_arr.map((r) => r.map((p) => { p.pop() return p })) callback(img_arr.flat(3)) }) }
[ "async png2rgb_arr(path, rotate = 1, callback) {\n // path = \"asset/LED/LED_CHEST/chest1.png\"\n getPixels(path, function (err, pixels) {\n if (err) {\n console.log(\"Bad image path\");\n return;\n }\n let pixels_raw = Array.from(pixels.data);\n\n let img_arr = [];\n let width = pixels.shape[0];\n let height = pixels.shape[1];\n // console.log(\"got pixels\", pixels.shape.slice())\n // console.log(pixels_raw)\n img_arr = math.reshape(pixels_raw, [height, width, 4]);\n\n for (let i = 0; i < rotate; ++i) {\n // to rotate 90 degree -> reverse then transpose\n img_arr.reverse();\n img_arr = this.arr_transpose(img_arr);\n }\n\n width = img_arr[0].length;\n height = img_arr.length;\n\n // flip odd row\n img_arr.map((r, i) => {\n if (i % 2 === 1) {\n r.reverse();\n }\n return r;\n });\n // remove alpha data\n img_arr.map((r) =>\n r.map((p) => {\n p.pop();\n return p;\n })\n );\n\n callback(img_arr.flat(3));\n });\n }", "rotateBitmap (bitmap) {\n var newBitmap = [];\n for (var x = 0; x < 5; x++) {\n for (var y = 0; y < 5; y++) {\n newBitmap[x*5+y] = bitmap[y*5+4-x]\n }\n }\n return newBitmap\n }", "function rotateColor(rgb){\n\t\tvar rgbNuevo = [];\n\t\trgbNuevo.push(rgb[2]);\n\t\trgbNuevo.push(rgb[0]);\n\t\trgbNuevo.push(rgb[1]);\n\n\t\treturn rgbNuevo;\n\t}", "function rotateImage(a) {\n for (let i = 0; i < a.length; i++) {\n for (let j = i; j < a[i].length; j++) {\n [a[i][j], a[j][i]] = [a[j][i], a[i][j]];\n }\n a[i].reverse()\n }\n\n return a\n}", "function rotate90(src, callback){\n\n var img = new Image()\n\n img.src = src\n\n img.onload = function() {\n\n var canvas = document.createElement('canvas')\n\n canvas.width = img.height\n\n canvas.height = img.width\n\n canvas.style.position = \"absolute\"\n\n var ctx = canvas.getContext(\"2d\")\n\n ctx.translate(img.height, img.width / img.height)\n\n ctx.rotate(Math.PI / 2)\n\n ctx.drawImage(img, 0, 0)\n\n callback(canvas.toDataURL(\"image/jpeg\"))\n\n }\n\n}", "function rotateImage(a) {\n let n = a.length;\n // first we turn the rows into columns and the columns into rows\n for (let row = 0; row < n; row++) {\n for (let col = row; col < a[row].length; col++) {\n let temp = a[row][col];\n a[row][col] = a[col][row];\n a[col][row] = temp;\n }\n }\n // then all we have to do is swap the first column with the last column\n for (let row = 0; row < n; row++) {\n for (let col = 0; col < Math.floor(n / 2); col++) {\n let temp = a[row][n - 1 - col];\n a[row][n - 1 - col] = a[row][col];\n a[row][col] = temp;\n }\n }\n return a;\n}", "function imageRotation(x, y) {\n// x is the x-direction length of image\n// y is the y-direction length of image\n\nfor(var i = 0; x > i; i++) {\n\tfor (var j = 0; y >j; j++) {\n\t\timage[i + 2, j] = image [i, j];\n\t\timage[i+2, j +2] = image [i+2, j];\n\t\timage[i, j + 2] = image [i+2, j+2];\n\t\timage[i, j] = image [i, j + 2];\n\t}\n}\n}", "rotateTexture(degree) {\n if (!this.loaded)\n return;\n\n // clone the texture array\n this.textureArray = this.textureArray.slice(0);\n\n switch (degree % 360) {\n case 0:\n break;\n\n default:\n case 90:\n for (let i = 0; i < this.textureArray.length; i += 2) {\n let t = this.textureArray[i];\n this.textureArray[i] = this.textureArray[i + 1];\n this.textureArray[i + 1] = 1 - t;\n }\n break;\n\n case 180:\n for (let i = 0; i < this.textureArray.length; i += 2) {\n this.textureArray[i] = 1 - this.textureArray[i];\n this.textureArray[i + 1] = 1 - this.textureArray[i + 1];\n }\n break;\n\n case 270:\n for (let i = 0; i < this.textureArray.length; i += 2) {\n let t = this.textureArray[i];\n this.textureArray[i] = 1 - this.textureArray[i + 1];\n this.textureArray[i + 1] = t;\n }\n break;\n }\n }", "function rotateButtonImageColors() {\n function rgbRng() {\n let randomRgbNr = Math.floor(Math.random() * 255) + 0;\n return randomRgbNr;\n };\n let rgb1 = rgbRng();\n let rgb2 = rgbRng();\n let rgb3 = rgbRng();\n setTimeout(() => {\n buttonImage.style.color = `rgb(${rgb1}, ${rgb2}, ${rgb3}`;\n }, 1500);\n setTimeout(() => {\n rotateButtonImageColors();\n }, 1500);\n}", "function rotateGrid(array) {\n let output = [];\n \n \n\n \n}", "function rotate90(array) {\n if (array.length === 0) return console.log('Array is empty');\n let result = [];\n for (let index = 0; index < array[0].length; index++) {\n result.push(new Array());\n }\n\n for (let idx = 0; idx < array[0].length; idx++) {\n for (let idxTwo = array.length - 1; idxTwo >= 0; idxTwo--) {\n result[idx].push(array[idxTwo][idx]);\n }\n }\n\n\n return result;\n}", "function rotateCounterClockwise(arr){\n // add whatever parameters you deem necessary - good luck!\n let newArr =[];\n \n for(let i=0; i < arr.length; i++){\n let temp = [];\n for(let j=0; j < arr.length; j++){\n temp.push(arr[j][i]);\n }\n newArr.push(temp);\n }\n \n return newArr.reverse();\n}", "function rotateArray(rotateCount) {\n\tfor (var i = 0; i < rotateCount; i++) {\n\t\tgrid = rotateArrayToRightOnce(grid);\n\t}\n\t\n\t \n/*\n * function: rotateArrayToRightOnce \n * input : array\n * output : void \n * description: rotate the cooresponding array once \n */\n\tfunction rotateArrayToRightOnce(array) { // es6 map映射函数:遍历每个值和索引,然后对每个值和索引条用回调函数\n\t\treturn array.map((row, rowIndex) => { // 箭头函数\n\t\t\treturn row.map((item, columnIndex) => {\n\t\t\t\treturn array[3 - columnIndex][rowIndex];\n\t\t\t})\n\t\t})\n\t}\n}", "function cellColorYaxisRotationFunction(cL, cellLocation, matrixDimension, topArr, frontArr, bottomArr, backArr, colorFace) {\n \t //Define variables and array\n var i, j, k, temp, tempVar;\n \nfor (k=0; k< 6; k++) {\t\n // put color for each cell j is row and i is cols of matrix first cell is 0,0\n\ttempVar = -1;\n for (j = 0; j < matrixDimension; j++) {\n for (i = 0; i < matrixDimension; i++) {\n temp = (j+1)*10+(i+1);\n\t\t \n\t\t\t\t\t tempVar = tempVar + 1;\t\t\t\t\t\n\t\t\t\t\t if(k==0) tempColor= backArr[tempVar];\n\t\t\t\t\t\t else\n\t\t\t\t\t\t if(k==1) continue;\n\t\t\t\t\t\t else if(k==2) tempColor= frontArr[tempVar];\n\t\t\t\t\t\t else if(k==3) continue;\n\t\t\t\t\t\t else if(k==4) tempColor= topArr[tempVar];\n\t\t\t\t\t\t\t else tempColor = bottomArr[tempVar];\n\t\t\t\t\t\t\t \n\t\t\t\t\t $(\"#\"+cL[k]+temp).css(\"background-color\", colorFace[tempColor]); \n } \n }\t\t\t\t\t\t\t\t\t\n }\n \n\t\t\t\t\t\t\t\t\t\t }", "async function imgRotate(name, angle) { \n const image = await Jimp.read \n(name); \nconst imgName = name.slice(0,-4) + \"_rr_\" + angle + \".jpg\"\n// rotate Function having rotation angle as a parameter, mode and error handling callback function \n image.rotate(angle, Jimp.RESIZE_BEZIER, function(err){ \n if (err) throw err; \n }) \n .write(imgName); \n return name + \" rotated by \" + angle + \" degrees: \" + imgName;\n}", "function generate360array() {\n var g360a = [];\n for (var i = 0; i < totalColorWheelSteps; i++) {\n g360a[i] = i;\n }\n return g360a;\n }", "generateRotations(size) {\n const tl = `0,0 0,${size} ${size},0`;\n const br = `${size},${size} 0,${size} ${size},0`;\n const tr = `0,0 ${size},${size} ${size},0`;\n const bl = `0,0 ${size},${size} 0,${size}`\n return [\n [tl, br],\n [tr, bl],\n [br, tl],\n [bl, tr],\n ];\n }", "function rotate(arr) {\n var a = arr.shift();\n arr.push(a);\n return arr;\n}", "rotateBoard() {\n //rotate board conter clockwise\n this.board = this.board.map((col, i) =>\n this.board.map((row) => row[3 - i])\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search object with the same store id and then item id and push it to bowl array
function searchProduct(itemstore, itemid){ for(var i = 0; i < jsonArr.length; i++){ if(jsonArr[i]._id === itemstore){ for(var j = 0; j < jsonArr[i].items.length; j++){ if(jsonArr[i].items[j]._id === itemid){ jsonArr[i].items[j].number = 0; return jsonArr[i].items[j]; } } } } }
[ "checkIfSearchResultExistInMyReads(searchResult) {\n this.state.bookListMyReads.map((myBook) => {\n searchResult.map((searchBook) => {\n if (myBook.id === searchBook.id) {\n searchBook.shelf = myBook.shelf;\n }\n })\n })\n return searchResult;\n }", "function finditembyid (id) {\n\n\tfor (var i = 0; i < food_pickup.length; i++) {\n\n\t\tif (food_pickup[i].id == id) {\n\t\t\treturn food_pickup[i];\n\t\t}\n\t}\n\n\treturn false;\n}", "addToRecent(p) {\n console.log(p);\n let found = false;\n for (let value of this.recentViewedProducts) {\n if (value.id == p.id) {\n found = true;\n }\n }\n if (found == false) {\n this.recentViewedProducts.push(p);\n this.storage.set('recentViewedProducts', this.recentViewedProducts);\n }\n }", "getBasketItem(id) {\n for(let i = 0; i < this.basket.length; ++i) {\n if(this.basket[i].id == id) {\n return JSON.parse(JSON.stringify(this.basket[i]));\n }\n }\n }", "find(id) {\r\n if(id) {\r\n return this.shoeList.find(element => {\r\n return element.id === id;\r\n });\r\n }else {\r\n return this.shoeList;\r\n }\r\n }", "albumWithTrackId(id){\r\n return this.albums.find((alb) => alb.containTrack(id));\r\n }", "static findItemById(id) {\n let foundItem = null;\n data.items.forEach((item) => {\n if (item.id === id) {\n foundItem = item;\n }\n });\n return foundItem;\n }", "function matchesId(item, index, array) {\n if (item.id === id) {\n return item;\n }\n }", "meals(){\n const neighborhoodMealIds =[];\n this.deliveries().forEach(function(delivery){\n neighborhoodMealIds.push(delivery.mealId)\n });\n let uniqueNeighborhoodMealIds = [...new Set(neighborhoodMealIds)]\n return store.meals.filter(meal => uniqueNeighborhoodMealIds.includes(meal.id))\n }", "artistWithTrackId(id, artistas){\r\n return artistas.find((art) => art.containTrackId(id));\r\n }", "searchByWeight( weightToSearch ) {\n let itemId = this.ItemNotFound;\n let list = this.state[this.townName];\n \n for( let indx=0; indx<list.length; ++indx ) {\n if( list[indx].weight.toString() === weightToSearch ) {\n itemId = list[indx].id;\n break;\n }\n }\n console.log('searchByWeight :',itemId);\n\n return itemId;\n }", "findItem(itemName){\n let { name, list, earnings} = this\n const item = list.find((item) => item.title === itemName && item.store === name);\n return item\n }", "addExtraItemById(id) {\n console.log(`Adding #{id}`)\n this.brave.extraItems.push(\n this.props.itemData.data[id]\n )\n }", "completeBravery() {\n\n let hasShoes = this.brave.items.find(\n (id)=> this.props.itemData.ubrave.boots.includes(id)\n )\n if(!hasShoes){\n console.log(\"No shoes\")\n }\n\n if(!hasShoes && this.brave.items.length < this.maxItems) {\n console.log(\"added shoe\")\n this.addShoe()\n }\n\n this.fillWithItems();\n }", "artistaWithAlbumId(id, artistas){\r\n return artistas.find((art) => art.containAlbumId(id));\r\n }", "function checkForDuplicates(items, item){\n let obj = items.find(obj => (obj.id === item.id)&&(obj.color === item.color));\nif ( obj ) {\n console.log('you already have the same item in the same color');\n var index = items.indexOf(obj);\n console.log(index);\n items[index].qty += 1;\n} else {\n items.push(item);\n console.log('new item was added to your carts');\n}\n}", "function findItem(id){\n for(let i = 0; i < window.catalog.length; i++){\n if(id === window.catalog[i].id){\n return i;\n }\n }\n}", "searchByName( nameToSearch ) {\n let itemId = this.ItemNotFound;\n let list = this.state[this.townName];\n let nameToSearchLowerCase = nameToSearch.toLocaleLowerCase();\n let nameToSearchSplit = nameToSearchLowerCase.split(' ');\n let name0ToSearch = nameToSearchSplit[0];\n let name1ToSearch = nameToSearchSplit[1];\n \n \n for( let indx=0; indx<list.length; ++indx ) {\n let name = list[indx].name.toString().toLocaleLowerCase();\n let nameSplit= name.split(' ');\n let name0 = nameSplit[0];\n let name1 = nameSplit[1];\n \n if( name0ToSearch && name1ToSearch && nameToSearchLowerCase === name ) {\n itemId = list[indx].id;\n break;\n } else\n if( !name1ToSearch && name0ToSearch && (name0 === name0ToSearch || name1 === name0ToSearch) ) {\n itemId = list[indx].id;\n break;\n }\n }\n console.log('searchByName :',itemId);\n \n return itemId;\n }", "addShelf(searchedBook) {\n let hasShelf = this.props.books.filter(book => book.id === searchedBook.id);\n return hasShelf.length ? hasShelf[0].shelf : \"none\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
functions fill trialLeft box with hearts
function addHearts(){ $("#trialsLeft").empty(); for(i = 0; i < trialsLeft; i++){ $("#trialsLeft").append('<img src="images/heart.png" class="life">'); } }
[ "function addHearts() {\r\n\t\t$(\"#trialsLeft\").empty();\r\n\t\tfor (i = 0; i < trialsLeft; i++) {\r\n\t\t\t$(\"#trialsLeft\").append('<img src=\"Images/Srce.png\" class=\"life\">');\r\n\t\t}\r\n\t}", "function addHearts(){\n $(\"#trailsLeft\").empty(); //Make trialsLeft div empty before adding any hearts otherwise heats will keep increasing instead of decreasing\n \n //Now add the hearts\n for(i= 0; i < trialsLeft; i++){\n $(\"#trailsLeft\").append('<img src=\"images/heart.png\" class=\"life\">');\n }\n } //end of addHearts() function", "function addHearts() {\n $(\"#trialsLeft\").empty();\n for(var i = 0; i < trialsLeft; i++) {\n $(\"#trialsLeft\").append(\"<img src='pics/heart.png' class='hearts'>\");\n }\n}", "function addHearts() {\n\t\t$(\"#heartsLeft\").empty();\n\t\tfor(let i = 0; i < heartsLeft; i++) {\n\t\t\t$(\"#heartsLeft\").append(' <img src=\"images/heart.png\" class=\"hearts\"> ');\n\t\t}\n\t}", "function risingHearts()\n {\n var ox = 0\n var oy = 80\n\n var w = document.body.clientWidth - ox - 200\n var h = window.innerHeight - oy - 200\n\n var newInterval = Util.random(200, 2000)\n\n animationID = window.setInterval(function()\n {\n var x = Util.random(ox, ox + w)\n var y = Util.random(oy + h - 100, oy + h)\n\n var heart = createHeart()\n heart.style.fontSize = Util.random(100, 400) + '%'\n heart.style.left = x + 'px'\n heart.style.top = y + 'px'\n\n var riseInterval = Util.random(10, 50)\n var rise = Util.random(h / 4, h)\n var drift = Util.random(-1, 1)\n var i = 0\n var id = window.setInterval(function()\n {\n i++\n if (Util.random(1, 100) <= 1) {\n drift = (drift == Util.random(-1, 1) ? 1 : 0)\n }\n\n x = Math.min(Math.max(x + drift, ox), ox + w)\n\n heart.style.left = x + 'px'\n heart.style.top = (y - i) + 'px'\n\n if (i < rise / 4) {\n heart.style.opacity = (4 * i / rise) + ''\n } else if (i < rise / 2 ) {\n heart.style.opacity = '1'\n } else {\n heart.style.opacity = (1 - (2 * i - rise) / rise ) + ''\n }\n\n if (i >= rise) {\n window.clearInterval(id)\n document.body.reriseChild(heart)\n }\n }, riseInterval)\n }, newInterval)\n }", "function stuffChest(chest, item, count) {\r\n for (var i = 0; i < 27; i++) {\r\n setChest(chest, i, item, count)\r\n }\r\n}", "function initialHearts() {\n let heartsBox = document.getElementsByClassName(\"hearts\")[0];\n for (let i = 0; i < hearts; i++) {\n let heart = document.createElement(\"span\");\n heart.innerHTML = heartAltCode;\n heartsBox.appendChild(heart);\n }\n}", "function stuffChest(chest, item, count) {\n for (var i = 0; i < 27; i++) {\n setChest(chest, i, item, count)\n }\n}", "function countHearts() {\n\t\t$(\"#hearts\").html(\"\");\n\t\tfor (let i = 0; i < fullHearts; i++) {\n\t\t\t$(\"#hearts\").append('#');\n\t\t}\n\t\tfor (let j = 0; j < emptyHearts; j++) {\n\t\t\t$(\"#hearts\").append('*');\n\t\t}\n\n\t}", "function drawHearts(){\r\n var context = document.getElementById('canvas1').getContext(\"2d\");\r\n context.clearRect(0, 0, 600, 60);\r\nfor (var h = 1; h <= guessesRemaining; h++){\r\n drawHeart(h)\r\n \r\n}\r\n}", "function drawLeftBench() {\n offsetY = 40;\n \n let total = that.equalBenches ? equalBenchLeft : left.total;\n seatShapes = seatShapes.concat(\n drawBench(rows, leftCols, offsetX, offsetY, left.seats)\n );\n }", "function fillUpChest(pt, item, amount) {\n for (var i = 0; i < 27; i++) {\n Level.setChestSlot(pt[0], pt[1], pt[2], i, item[0], item[1], amount);\n }\n}", "function drawLeftArm() {\n\tlet colorPalette = {\n\t\tcolorFrom: backgroundBluesPalette[0],\n\t\tcolorTo: backgroundBluesPalette[5],\n\t\tstrokeWeight: 4,\n\t\tcolorLerp: 0.2\n\t};\n\n\t// stroke(129, 217, 235);\n\tstrokeWeight(4);\n\tstroke(backgroundBluesPalette[0]);\n\t//bezier(500, 400, 550, 435, 585, 450, 715, 360);\n\n\tlet leftArmCoordinates = {\n\t\txBegin: 460,\n\t\tyBegin: 415,\n\t\txControl1: 550,\n\t\tyControl1: 435,\n\t\txControl2: 585,\n\t\tyControl2: 450,\n\t\txEnd: 715,\n\t\tyEnd: 360\n\t};\n\n\tleftArmCoordinates.xBegin = leftArmCoordinates.xBegin + getRandomInt(-7, 7); \n\tleftArmCoordinates.yBegin = leftArmCoordinates.yBegin + getRandomInt(-5, 5);\n\tleftArmCoordinates.xEnd = leftArmCoordinates.xEnd + getRandomInt(-10, 10);\n\tleftArmCoordinates.yEnd = leftArmCoordinates.yEnd + getRandomInt(-20, 20);\n\n\tleftArmCoordinates.xControl1 = leftArmCoordinates.xControl1 + getRandomInt(-12, 12); \n\tleftArmCoordinates.yControl1 = leftArmCoordinates.yControl1 + getRandomInt(-11, 11);\n\tleftArmCoordinates.xControl2 = leftArmCoordinates.xControl2 + getRandomInt(-6, 6); \n\tleftArmCoordinates.yControl2 = leftArmCoordinates.yControl2 + getRandomInt(-4, 4);\n\n\t// drawing points to give some depth\n\n\t// the last params chosen so to have an animation that looks good (no special logic here)\n\t// but renders impossible to rather use calls in a loop\n\tcolorPalette.colorLerp = 0.5;\n\tcolorPalette.strokeWeight = 1;\n\tdrawPoints(leftArmCoordinates.xBegin, leftArmCoordinates.yBegin,\n\t\tleftArmCoordinates.xControl1, leftArmCoordinates.yControl1,\n\t\tleftArmCoordinates.xControl2, leftArmCoordinates.yControl2,\n\t\tleftArmCoordinates.xEnd, leftArmCoordinates.yEnd,\n\t\t120, 80, colorPalette, 1);\n\n\tcolorPalette.colorLerp = 0.2;\n\tcolorPalette.strokeWeight = 2;\n\tdrawPoints(leftArmCoordinates.xBegin + 10, leftArmCoordinates.yBegin + 5,\n\t\tleftArmCoordinates.xControl1, leftArmCoordinates.yControl1,\n\t\tleftArmCoordinates.xControl2, leftArmCoordinates.yControl2,\n\t\tleftArmCoordinates.xEnd + 5, leftArmCoordinates.yEnd + 5,\n\t\t240, 40, colorPalette, 1);\n\n\tcolorPalette.colorLerp = 0.10;\n\tcolorPalette.strokeWeight = 3;\n\tdrawPoints(leftArmCoordinates.xBegin + 10, leftArmCoordinates.yBegin + 5,\n\t\tleftArmCoordinates.xControl1, leftArmCoordinates.yControl1,\n\t\tleftArmCoordinates.xControl2, leftArmCoordinates.yControl2,\n\t\tleftArmCoordinates.xEnd + 5, leftArmCoordinates.yEnd + 5,\n\t\t300, 30, colorPalette, 1);\n\n\t// draw shaping line\n\n\t// the last params chosen so to have an animation that looks good (no special logic here)\n\t// but renders impossible to rather use calls in a loop\n\tcolorPalette.colorLerp = 0;\n\tcolorPalette.strokeWeight = 4;\n\tdrawNoiseLine(leftArmCoordinates.xBegin, leftArmCoordinates.yBegin,\n\t\tleftArmCoordinates.xControl1, leftArmCoordinates.yControl1,\n\t\tleftArmCoordinates.xControl2, leftArmCoordinates.yControl2,\n\t\tleftArmCoordinates.xEnd, leftArmCoordinates.yEnd,\n\t\t20, 60, colorPalette, 1);\n\n\tcolorPalette.strokeWeight = 2;\n\tdrawNoiseLine(leftArmCoordinates.xBegin + 10, leftArmCoordinates.yBegin + 5,\n\t\tleftArmCoordinates.xControl1, leftArmCoordinates.yControl1,\n\t\tleftArmCoordinates.xControl2, leftArmCoordinates.yControl2,\n\t\tleftArmCoordinates.xEnd + 5, leftArmCoordinates.yEnd + 5,\n\t\t5, 120, colorPalette, 1);\n}", "function growingHearts()\n {\n var ox = 0\n var oy = 80\n\n var w = document.body.clientWidth - ox - 200\n var h = window.innerHeight - oy - 200\n\n var newInterval = Util.random(200, 2000)\n\n animationID = window.setInterval(function()\n {\n\n var heart = createHeart()\n heart.style.fontSize = '0%'\n heart.style.left = Util.random(ox, ox + w) + 'px'\n heart.style.top = Util.random(oy, oy + h) + 'px'\n\n var growInterval = Util.random(10, 50)\n var size = Util.random(50, 1000)\n var i = 0\n var id = window.setInterval(function()\n {\n i += 20\n heart.style.fontSize = i + '%'\n\n if (i < size / 2 ) {\n heart.style.opacity = '1'\n } else {\n heart.style.opacity = (1 - (2 * i - size) / size ) + ''\n }\n\n if (i >= size) {\n window.clearInterval(id)\n document.body.removeChild(heart)\n }\n }, growInterval)\n }, newInterval)\n }", "function leftRight() {\nbackground(250);\n \nfor(var i = 0; i < democrats.length; i++){\n var rand1 = random(0,575);\n var rand2 = random(50,600);\n fill(2,27,189);\n voteCount = countDemVotes(democrats[i]);\n //changes size of vote depending on total number of votes\n if(voteCount > 50){\n textSize(35);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 40) {\n textSize(30);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 30){\n textSize(25);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 20){\n textSize(20);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 10){\n textSize(15);\n text(democrats[i], rand1 , rand2);\n }else{\n textSize(10);\n text(democrats[i], rand1 , rand2);\n }\n }\n \nfor(var j = 0; j < republicans.length; j++){\n var rand3 = random(575,1200);\n var rand4 = random(50,600);\n fill(254,1,3);\n voteCount = countRepVotes(republicans[j]);\n //changes size of vote depending on total number of votes\n if(voteCount > 50){\n textSize(35);\n text(republicans[j], rand3 , rand4);\n }else if(voteCount > 40) {\n textSize(30);\n text(republicans[j], rand3 , rand4);\n }else if(voteCount > 30){\n textSize(25);\n text(republicans[j], rand3 , rand4);\n }else if(voteCount > 20){\n textSize(20);\n text(republicans[j], rand3 , rand4);\n }else if(voteCount > 10){\n textSize(15);\n text(republicans[j], rand3 , rand4);\n }else{\n textSize(10);\n text(republicans[j], rand3 , rand4);\n }\n}\n}", "function generateseatrow(xstart, ystart, downorright, numberofseats) {\n for (var i = 0; i < numberofseats; i++) {\n orangeBoxMade = false;\n redBoxMade = false;\n var box = map.getContext(\"2d\");\n boxes[boxnumberid] = [\n [xstart, ystart],\n [xstart + 30, ystart],\n [xstart + 30, ystart + 30],\n [xstart, ystart + 30], boxnumberid\n ];\n if (localStorage.getItem(seatTakenStorage) !== null) {\n console.log(localStorage.getItem(seatTakenStorage));\n for (var j = 0; j < localStorage.getItem(seatTakenStorage).length; j++) {\n if (redBoxMade === false) {\n if (JSON.parse(localStorage.getItem(seatTakenStorage))[j] == boxnumberid) {\n box.beginPath();\n box.fillStyle = \"black\";\n box.rect(xstart, ystart, 30, 30);\n box.lineWidth = 2;\n box.fillStyle = \"red\";\n box.fillRect(xstart, ystart, 30, 30);\n box.fillStyle = \"black\";\n box.font = \"12pt Arial\";\n box.fillText(boxnumberid, xstart + 2, ystart + 20);\n box.strokeStyle = 'black';\n box.stroke();\n boxnumberid += 1;\n redBoxMade = true;\n }\n }\n }\n }\n if ((localStorage.getItem(seatChosenStorage) !== null) && (redBoxMade === false)) {\n for (var h = 0; h < localStorage.getItem(seatChosenStorage).length; h++) {\n if (orangeBoxMade === false) {\n if (JSON.parse(localStorage.getItem(seatChosenStorage))[h] == boxnumberid) {\n box.beginPath();\n box.fillStyle = \"black\";\n box.rect(xstart, ystart, 30, 30);\n box.lineWidth = 2;\n box.fillStyle = \"orange\";\n box.fillRect(xstart, ystart, 30, 30);\n box.fillStyle = \"black\";\n box.font = \"12pt Arial\";\n box.fillText(boxnumberid, xstart + 2, ystart + 20);\n box.strokeStyle = 'black';\n box.stroke();\n boxnumberid += 1;\n orangeBoxMade = true;\n }\n }\n }\n }\n if ((orangeBoxMade === false) && (redBoxMade === false)) {\n box.beginPath();\n box.fillStyle = \"black\";\n box.rect(xstart, ystart, 30, 30);\n box.lineWidth = 2;\n box.fillStyle = \"green\";\n box.fillRect(xstart, ystart, 30, 30);\n box.fillStyle = \"black\";\n box.font = \"12pt Arial\";\n box.fillText(boxnumberid, xstart + 2, ystart + 20);\n box.strokeStyle = 'black';\n box.stroke();\n boxnumberid += 1;\n }\n if (downorright === \"right\") {\n xstart += 30;\n ystart += 0;\n }\n else if (downorright === \"down\") {\n xstart += 0;\n ystart += 30;\n }\n }\n }", "function newHand(){\n // re enable's spot 1 if a tile was dropped on it\n $(\"#spot1\").droppable(\"enable\");\n\n //disables all other spots so they may be enabled with the enableNext() function\n for(var i = 2; i<8;i++){\n $(\"#spot\" + i).droppable(\"disable\");\n }\n\n deleteTiles(); // Delete used Tiles\n countTotalScore();// updates total score\n\n spot1Score=0;\n spot2Score=0;\n spot3Score=0;\n spot4Score=0;\n spot5Score=0;\n spot6Score=0;\n spot7Score=0;\n wordScore=0;// reset all values to 0 for new hand\n updateWordScore(); // update word score to be 0 after resetting\n\n //calculate how many new tiles are needed\n var leftovers=0;\n leftovers = parseInt($('div.onRack').length);\n var newTilesNeeded = (7 - leftovers);\n\n // generating new tiles based off the leftovers\n for(var i=0;i<newTilesNeeded;i++){\n console.log(\"TilesLeft: \" + tilesLeft);\n if (tilesLeft < 1){\n alert(\"No more tiles left to pull, click restart game to begin a new game!\")\n return;\n }\n else {\n tilesLeft--;\n }\n updateTilesRemaining();\n randTileGen ();\n }\n}// end of newHand()", "function drawPlayerHands(gameContainer) {\r\n for (var i = 0; i < players.length; i++) {\r\n var playerNum = i+1;\r\n var player = players[i];\r\n var text = new PIXI.Text(\"Player \" + playerNum + \" - \" + player.role, {font:\"20px Arial\", fill:\"black\"});\r\n var roleColorSquare = new PIXI.Graphics();\r\n roleColorSquare.beginFill(roleColors[player.role]);\r\n\r\n //roleColorSquare.lineStyle(1, 0x000000);\r\n roleColorSquare.drawRect(0, 0, 20, 20);\r\n //treasureSquare.hitArea = treasureSquare.getBounds();\r\n var background = new PIXI.Graphics();\r\n background.beginFill(0xc8c8c8);\r\n background.drawRect(0, 0, 400, 65);\r\n background.interactive = true;\r\n background.hitArea = background.getBounds();\r\n\r\n // player 1\r\n if (i == 0) {\r\n text.position.x = 5;\r\n text.position.y = height - text.height - 70;\r\n roleColorSquare.position.x = text.position.x + text.width + 5;\r\n roleColorSquare.position.y = text.position.y;\r\n player.hand.position.x = 5;\r\n player.hand.position.y = (height-65);\r\n }\r\n // player 2\r\n else if (i == 1) {\r\n text.position.x = width - text.width - 5;\r\n text.position.y = height - text.height - 70;\r\n roleColorSquare.position.x = text.position.x - roleColorSquare.width - 5;\r\n roleColorSquare.position.y = text.position.y;\r\n player.hand.position.x = width - 385;\r\n player.hand.position.y = (height-65);\r\n }\r\n // player 3\r\n else if (i == 2) {\r\n text.position.x = 5;\r\n text.position.y = 70;\r\n roleColorSquare.position.x = text.position.x + text.width + 5;\r\n roleColorSquare.position.y = text.position.y;\r\n player.hand.position.x = 5;\r\n player.hand.position.y = 5;\r\n }\r\n // player 4\r\n else if (i == 3) {\r\n text.position.x = width - text.width - 5;\r\n text.position.y = 70;\r\n roleColorSquare.position.x = text.position.x - roleColorSquare.width - 5;\r\n roleColorSquare.position.y = text.position.y;\r\n player.hand.position.x = width - 385;\r\n player.hand.position.y = 5;\r\n }\r\n background.position.x = player.hand.position.x;\r\n background.position.y = player.hand.position.y;\r\n gameContainer.addChild(text);\r\n gameContainer.addChild(roleColorSquare);\r\n gameContainer.addChild(background);\r\n gameContainer.addChild(player.hand);\r\n\r\n }\r\n}", "function undoHearts() {\n \n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set input values functionality
function setInputValues() { var stateFilter = settings['state-date'] || settings['state-record']; if (stateFilter) { if ('date' === stateFilter['type']) { if (stateFilter['operands'].hasOwnProperty('value')) { if ('>' === stateFilter['operator'] || '=' === stateFilter['operator']) { lower.formatToUtc(stateFilter['operands']['value'], true); upper.setData(''); } else if ('<' === stateFilter['operator']) { upper.formatToUtc(stateFilter['operands']['value'], true); lower.setData(''); } } else { lower.formatToUtc(stateFilter['operands']['lower'], true); upper.formatToUtc(stateFilter['operands']['upper'], true); } dateSelector.selectOption('title'); dateSelector.enableOptions(); } else if ('number' === stateFilter['type']) { if (stateFilter['operands'].hasOwnProperty('value')) { if ('>' === stateFilter['operator'] || '=' === stateFilter['operator']) { lower.setData(stateFilter['operands']['value']); upper.setData(''); } else if ('<' === stateFilter['operator']) { upper.setData(stateFilter['operands']['value']); lower.setData(''); } } else { lower.setData(stateFilter['operands']['lower']); upper.setData(stateFilter['operands']['upper']); } } $filterLink.addClass('filtered'); clearBtn.getElement().prop('disabled', false); } }
[ "fillInValues() {\r\n this.findViewElements();\r\n this.nameInput.value = this.catName;\r\n let n = (this.optionValues.length < this.optionInputs.length)\r\n ? this.optionValues.length : this.optionInputs.length;\r\n for (let i = 0; i < n; ++i) {\r\n this.optionInputs[i].value = this.optionValues[i];\r\n }\r\n }", "set input_value(i) {\r\n //\r\n //Convert the value to a js object which has the following \r\n //format '[\"address\", \"text\"]'(taking care of a null value)\r\n const [address, text] = i === null\r\n ? [null, null]\r\n // \r\n //The value of a url must be of type string otherwise \r\n //there is a mixup datatype\r\n : JSON.parse(i.trim());\r\n //\r\n //Set the inputs \r\n this.href.value = address;\r\n this.text.value = text;\r\n }", "function setvalues(val, i, input){\n let values = state.inputValue\n values[i] = val\n setInputState({ \n inputValue: values,\n activeInput: input\n })\n }", "setInputValue(value) {\n\t\tthis._input.value = value;\n\t}", "function setInputValue(obj,value) {\n\tvar use_default=(arguments.length>1)?arguments[1]:false;\n\tif(isArray(obj)&&(typeof(obj.type)==\"undefined\")){\n\t\tfor(var i=0;i<obj.length;i++){setSingleInputValue(obj[i],value);}\n\t\t}\n\telse{setSingleInputValue(obj,value);}\n\t}", "function handleSettingInput(e) {\n !inputArr.length\n ? helpers.settingInput(e, setFirstInput, firstInput)\n : helpers.settingInput(e, setSecondInput, secondInput);\n }", "function setInputFieldValues(planetName_val,\n aphelion_val, perihelion_val,\n orbital_period_d_val, orbital_period_y_val,\n surface_area_val, surface_area_exp_val,\n volume_val, volume_exp_val,\n mass_val, mass_exp_val,\n temp_val,\n imgSymbolURL_val, imgURL_val,\n info_val) {\n planetName.value = planetName_val;\n aphelion.value = aphelion_val;\n perihelion.value = perihelion_val;\n orbital_period_d.value = orbital_period_d_val;\n orbital_period_y.value = orbital_period_y_val;\n surface_area.value = surface_area_val;\n surface_area_exp.value = surface_area_exp_val;\n volume.value = volume_val;\n volume_exp.value = volume_exp_val;\n mass.value = mass_val;\n mass_exp.value = mass_exp_val;\n temp.value = temp_val;\n imgSymbolURL.value = imgSymbolURL_val;\n imgURL.value = imgURL_val;\n info.value = info_val;\n }", "function changeInputValues(){\n document.getElementById(\"titleInput\").value = title;\n document.getElementById(\"inputAddress\").value = address;\n document.getElementById(\"inputCity\").value = city;\n document.getElementById(\"inputProvince\").value = province;\n document.getElementById(\"inputPostalCode\").value = inputPostalCode;\n document.getElementById(\"payAmountInput\").value = payAmount;\n document.getElementById(\"descriptionInput\").value = description;\n document.getElementById(\"tagList\").value = tags;\n}", "function setValue(input, num){\n input.value = num;\n}", "updateInputValue() {\n var tag = this.get('tag'),\n option = this.get('option'),\n answer = tag.get('answer') || [];\n\n option.set('value', answer);\n }", "_onChange() {\n this.set('_inputValue', this.get('value'));\n }", "function inputValues() {\n this.run = function() {\n pageVariables.inputForm = [];\n formFunctions();\n };\n}", "function setupValue(pos, len, xxxvalue,xxxaction){\r\n\tvar elements=hatsForm.elements;\r\n\tvar elementNext,eName,eType,pool;\r\n\tfor (var i=0,iL=elements.length; i<iL; ++i){\r\n\t\telementNext=elements[i];\r\n\t\teName=elementNext.name;\r\n\t\teType=elementNext.type;\r\n\t\tif ((eType==\"text\") || (eType==\"textarea\") || (eType==\"password\") || (eType==\"hidden\") || (eType==\"checkbox\") || (eType==\"radio\")){\r\n\t\t\tif (eName!=null){\r\n\t\t\t\tif (eName.length>0){\r\n\t\t\t\t\tpool = eName.split(\"_\");\r\n\t\t\t\t\tif (pool.length==3){\r\n\t\t\t\t\t\tif (pool[0].indexOf(\"in\")!=-1){\r\n\t\t\t\t\t\t\tif (pool[1] == pos){\r\n\t\t\t\t\t\t\t\telementNext.value = xxxvalue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvar_setupValuepos=pos;\r\n\tvar_setupValuexxxaction=xxxaction;\r\n}", "function updateValues() {\r\n\r\n // uptate inputs values\r\n for (let key in inputsProperties) {\r\n inputs[key].value = converter[key].toString();\r\n }\r\n\r\n // change tool tip color to match the base color \r\n toolTipText.style.backgroundColor = rainbowWindow.baseColorString;\r\n toolTipArrow.style.borderRightColor = rainbowWindow.baseColorString;\r\n }", "setFormValues() {\n let me = $(this);\n let controls = me.find('[property]');\n //let objDef = null;\n let obj;\n if (this.isClone) {\n obj = new flexygo.obj.Entity(this.objectname);\n obj.read();\n }\n for (let i = 0; i < controls.length; i++) {\n let propName = $(controls[i]).attr('property');\n let ctl = $(controls[i])[0];\n if (ctl && ctl.setValue) {\n let value = this.data[propName].DefaultValue;\n if (typeof this.data[propName].Value != 'undefined') {\n value = this.data[propName].Value;\n }\n //if (objDef && typeof objDef[propName] != 'undefined') {\n // value = objDef[propName]\n //}\n if (obj && obj.data && obj.data[propName]) {\n ctl.setValue((value || obj.data[propName].Value), this.data[propName].Text);\n }\n else {\n ctl.setValue((value), this.data[propName].Text);\n }\n }\n }\n }", "set value(value) {\n this.setRequiredChildProperty(this.inputSlot, 'value', value);\n }", "setDisplayValueFromCurrentInputValue() {\n this.setValueByInputValue(this.get(\"input_value\"));\n }", "function setInputs () {\n // the innerText of the last recording punch format \"{punchtype} at hh:mm:ss\"..thats why splitting at getting the first element gives up the last punch type\n let lastPunchType = doc.getElementById(LAST_RECORDED_PUNCH).innerText.split(\" \")[0].toLowerCase(); \n let defaultPunchType = lastPunchType == \"in\" ? 2 : 1; // \"2\" => \"out\" and \"1\" => \"in\" .. so if we were last in we should default punch type to out and vice verse\n\n doc.getElementById(PUNCH_TYPE_INPUT).value = defaultPunchType;\n // set the time reporting code to regular\n doc.getElementById(TIME_REPORTING_INPUT).value = \"00REG\";\n \n // one source requires that the input is focused in order to record the input\n doc.getElementById(TIME_REPORTING_INPUT).focus();\n doc.getElementById(PUNCH_TYPE_INPUT).focus();\n }", "setEventInput (event) {\n const { id, value, name } = event.target;\n const inputKey = id || name;\n this.setInput(inputKey, value);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function which writes all completed tasks
static _writeAllCompletedTasks() { this._tasks.forEach((task, taskName) => { if (task && task.state === TaskWriterState.ClosedUnwritten) { this._writeTask(taskName, task); } }); }
[ "function tasksComplete() {}", "function doneTasks() {\n\n\t\tif (doneTasksBuffer.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet title = (doneTasksBuffer.length === 1) ?\n\t\t\t'Task finished' :\n\t\t\tdoneTasksBuffer.length + ' tasks finished'\n\n\t\tnotify('done', title, doneTasksBuffer.join(', '));\n\n\t\tdoneTasksBuffer = [];\n\t\tdoneTasksFn = null;\n\n\t}", "_handle_allDone() {\n this._collector.allDone();\n }", "function writeCompletedTask(task, completed_tasks_file, ready_cb) {\n var old_headers = {}, new_headers = [];\n for (var k in task) {\n new_headers[k] = 1;\n }\n\n var parser = makeParser();\n parser\n .on('readable', function() {\n var record;\n while (record = parser.read()) {\n for (var k in record) {\n old_headers[k] = 1;\n }\n }\n })\n .on('finish', function() {\n // Merge old & new headers.\n var num_old_headers = 0;\n for (var k in old_headers) {\n num_old_headers++;\n new_headers[k] = 1;\n }\n var ordered_cols = [];\n for (var k in new_headers) {\n ordered_cols.push(k);\n }\n ordered_cols.sort();\n\n var new_line = [];\n for (var i = 0; i < ordered_cols.length; i++) {\n var k = ordered_cols[i];\n new_line.push(k in task ? task[k] : '');\n }\n\n var to_write = '';\n if (num_old_headers == 0) {\n to_write += quoteLine(ordered_cols);\n }\n to_write += '\\n' + quoteLine(new_line);\n\n fs.appendFile(completed_tasks_file, to_write, function(e) {\n assert.ifError(e);\n ready_cb();\n });\n });\n\n fs.createReadStream(completed_tasks_file).pipe(parser);\n}", "_impl_allDone() {\n this._emit('allDone');\n }", "async function doAll () {\n await init()\n await writeTasks()\n}", "function deleteAllCompletedTasks() {\n\n for (var i = tasks.length; i--;) {\n\n if (tasks[i].complete === true) {\n\n tasks.splice(i, 1);\n\n }\n\n }\n\n displayTasks(tasks);\n\n }", "function writeTasks (blockBlobs) {\n\t return blockBlobs.map((blockBlob) => {\n\t return (cb) => {\n\t writeBlock(blockBlob, (err, meta) => {\n\t if (err) {\n\t return cb(err)\n\t }\n\t\n\t if (push) {\n\t const read = push\n\t push = null\n\t read(null, meta)\n\t return cb()\n\t }\n\t\n\t written.push(meta)\n\t cb()\n\t })\n\t }\n\t })\n\t }", "function writeTasks (blockBlobs) {\n return blockBlobs.map((blockBlob) => {\n return (cb) => {\n writeBlock(blockBlob, (err, meta) => {\n if (err) {\n return cb(err)\n }\n\n if (push) {\n const read = push\n push = null\n read(null, meta)\n return cb()\n }\n\n written.push(meta)\n cb()\n })\n }\n })\n }", "async function doAll () {\n await init()\n await writeTasks()\n}", "runTasks() {\n\t\t// array of tasks to be finished \n\t\t// (to avoid mutating runningIds while iterating on it, by calling finishTask())\n\t\tlet toFinish = [];\n\n\t\ttry {\n\t\t\tfor (const id of this.runningIds) {\n\t\t\t\tconst _task = this.tasks[id];\n\n\t\t\t\tconst remainingSteps = _task.nextStep();\n\t\t\t\tconsole.log(\"T | RUNNING: \\t\\t\" + _task.name + \"\\t\\tid: \" + id + \"\\t\\tRemaining: \" + remainingSteps);\n\n\t\t\t\tif (remainingSteps == 0) toFinish.push(id);\t\t\t// task should be finished\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow \"runTasks error: \" + error;\n\t\t}\n\n\t\t// finish tasks added to toFinish\n\t\ttoFinish.forEach(id => {\n\t\t\tif (!this.finishTask(id))\n\t\t\t\tconsole.log(\"T | ERROR: Couldn't finish \" + id);\n\t\t});\n\t}", "_onTasksDone() {\n // meant to be implemented by subclass if needed\n }", "function writeTasks(blockBlobs) {\n return blockBlobs.map(function (blockBlob) {\n return function (cb) {\n writeBlock(blockBlob, function (err, meta) {\n if (err) {\n return cb(err);\n }\n\n if (push) {\n var read = push;\n push = null;\n read(null, meta);\n return cb();\n }\n\n written.push(meta);\n cb();\n });\n };\n });\n }", "onCompleteAll() {\n this.uploadCompleted = true;\n this.progress = false;\n let body = '<ul>';\n this.artifactoryNotifications.clear();\n if (this.errorQueue.length) {\n this.errorQueue.forEach((error)=> {\n body += '<li>\"' + error.item.file.name + '\" ' + error.response.error + '</li>'\n })\n body += '</ul>';\n this.artifactoryNotifications.createMessageWithHtml({type: 'error', body: body, timeout: 10000});\n this.deployMultiUploader.clearQueue();\n this.errorQueue = [];\n }\n else if (this.onSuccess && typeof this.onSuccess === 'function') {\n this.artifactoryNotifications.createMessageWithHtml({type: 'success', body: `Successfully deployed ${this.multiSuccessMessageCount} files`});\n this.onSuccess();\n }\n }", "function writeDone() {\n}", "function gotTasks(status) {\n var queue = d3.queue(10);\n\n // Handle each finished task\n status.forEach(function(finishedTask) {\n log.info(\n '[%s] %s',\n finishedTask.env.MessageId,\n JSON.stringify({\n outcome: tasks.report(finishedTask.outcome),\n reason: finishedTask.reason,\n duration: Math.ceil(finishedTask.duration / 1000),\n pending: Math.ceil(finishedTask.pending / 1000)\n })\n );\n queue.defer(messages.complete, finishedTask);\n });\n\n queue.awaitAll(function(err) {\n if (err) log.error(err);\n completedTasks(status);\n });\n }", "async waitUntilDone() {\n await Promise.all(this.taskQueue);\n }", "async _write() {\n if (this._writing) return;\n\n // Loop because items may get pushed onto queue while we're writing\n while (this._queue) {\n let q = this._queue;\n const {resolve, reject} = q;\n delete this._queue;\n this._writing = true;\n try {\n // Slice to most recent CLEAR action\n const clearIndex = q.reduce ((a, b, i) => b[0] === CLEAR ? i : a, -1);\n if (clearIndex >= 0) q = q.slice(clearIndex + 1);\n\n // Compose JSON to write\n const json = q.map(action => JSON.stringify(action)).join('\\n');\n\n if (clearIndex >= 0) {\n // If CLEAR, start with new file\n this._nBytes = 0;\n if (!json) {\n await fs.unlink(this.filepath);\n } else {\n const tmpFile = `${this.filepath}.tmp`;\n await fs.writeFile(tmpFile, json + '\\n');\n await fs.rename(tmpFile, this.filepath);\n }\n } else if (json) {\n await fs.appendFile(this.filepath, json + '\\n');\n }\n\n this._nBytes += json.length;\n resolve();\n } catch (err) {\n if (err.code == 'ENOENT') {\n // unlinking non-existent file is okay\n resolve(err);\n } else {\n reject(err);\n }\n } finally {\n this._writing = false;\n }\n }\n }", "function AllDone(){\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function sorts cities or other objects my name alphabetically INNER FUNCTION CALLS: none
function sortByName(object, className) { object.sort(function (a, b) { if (className == 'warehouse' || className == 'projecteq') return a.city.name > b.city.name; else return a.name > b.name; }); return object; }
[ "function sortBasedonCity(address){\n address.sort(function (x, y) {\n let a = x.City.toUpperCase(),\n b = y.City.toUpperCase();\n return a == b ? 0 : a > b ? 1 : -1;\n });\n Display(address);\n}", "function SortByName(a, b){\n\n var aName = a.country.toLowerCase();\n var bName = b.country.toLowerCase(); \n \n return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));\n}", "function SortByCity()\n{\n let sortedArray = contactsArray;\n sortedArray.sort((a,b) => a.city.toLowerCase().localeCompare(b.city.toLowerCase()));\n console.log(\"\\n\\nPrinting sorted array by city : \");\n sortedArray.forEach(p => console.log(\"\\n\"+p.toString()));\n}", "function sortByName(object, className)\n{\n\tobject.sort(\n\tfunction(a, b)\n\t{\n\t\tif(className==\"warehouse\" || className==\"projecteq\")\n\t\t\treturn a.city.name > b.city.name;\n\t\telse\n\t\t\treturn a.name > b.name;\n\t\t\t}\n\t);\n\treturn object;\n}", "function SortByCity()\n{\n let sortedArray = addressBook;\n sortedArray.sort((a,b) => a.city.toLowerCase().localeCompare(b.city.toLowerCase()));\n console.log(\"\\n\\nPrinting sorted array by city : \");\n sortedArray.forEach(p => console.log(p.toString()));\n}", "function sortByName()\n {\n Places.sort(function(a,b)\n {\n return a.name.localeCompare(b.name)\n });\n }", "function sortByCity(a, b) {\n const aCity = a.city.toLowerCase();\n const bCity = b.city.toLowerCase();\n return ((aCity < bCity) ? -1 : ((aCity > bCity) ? 1 : 0));\n}", "function smallCityNameByState() {\n const results = [];\n const treatedCities = outOldCityName();\n for (let state of globalStates) {\n const cities = treatedCities.filter((city) => {\n return city.Estado === state.ID;\n });\n cities.sort((a, b) => {\n return b.Nome.length - a.Nome.length || a.Nome.localeCompare(b.Nome);\n });\n results.push({ Nome: cities[0].Nome, Sigla: state.Sigla });\n }\n\n results.forEach((city) => {\n console.log(`${city.Nome} - ${city.Sigla}`);\n });\n}", "function populateCity() {\n const suggestions = document.querySelector(\".filteredCity\");\n suggestions.innerHTML = \"\";\n cities.sort((a, b) => {\n if (a.name < b.name) {\n return -1;\n } else if (a.name > b.name) {\n return 1;\n }\n else {\n return 0;\n }\n });\n\n cities.forEach(city => {\n let option = document.createElement('li');\n let link = document.createElement('a');\n link.textContent = city.AsciiName;\n link.href = \"http://localhost/Web2Assignment2/single-city.php?cityCode=\" + city.CityCode;\n option.appendChild(link);\n suggestions.appendChild(option);\n })\n }", "function bigCityNameByState() {\n const results = [];\n const treatedCities = outOldCityName();\n for (let state of globalStates) {\n const cities = treatedCities.filter((city) => {\n return city.Estado === state.ID;\n });\n cities.sort((a, b) => {\n return a.Nome.length - b.Nome.length || a.Nome.localeCompare(b.Nome);\n });\n results.push({ Nome: cities[0].Nome, Sigla: state.Sigla });\n }\n\n results.forEach((city) => {\n console.log(`${city.Nome} - ${city.Sigla}`);\n });\n}", "function sortByName() {\n sortBy = \"Name\";\n cards.sort((a, b) => (a.carName.toLowerCase() > b.carName.toLowerCase() ? 1 : -1));\n document.getElementById(\"sortbyprice\").classList.remove(\"active-control\");\n document.getElementById(\"sortbyname\").classList.add(\"active-control\");\n renderCards();\n}", "sortDataByName(data) {\r\n data.sort((a,b) => {\r\n if (a.companyName.toLowerCase() < b.companyName.toLowerCase()) return -1;\r\n if (a.companyName.toLowerCase() > b.companyName.toLowerCase()) return 1;\r\n return 0;\r\n });\r\n return data;\r\n }", "createCityArr() {\n let result = []\n for (city in zonesObj){\n result = result.concat(zonesObj[city])\n }\n this.cityArr = result.sort()\n }", "function sort_by_name() {\n if (sorted === 'name_asc') {\n persons.sort(function(a, b){\n return a.name.toLowerCase() < b.name.toLowerCase();\n });\n sorted = 'name_dsc';\n } else if (sorted === 'name_dsc') {\n sort_by_id();\n } else {\n persons.sort(function(a, b){\n return a.name.toLowerCase() > b.name.toLowerCase();\n });\n sorted = 'name_asc';\n }\n localStorage.setItem('person', JSON.stringify(persons));\n render_entries(pagenumber);\n}", "function sortName() {\n $.each( data, function( key, value ) {\n data.sort(function(a,b){\n // First convert strint to lower case\n // then compare and sort\n var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()\n if (nameA < nameB)\n return -1 \n if (nameA > nameB)\n return 1\n return 0\n });\n });\n render(data);\n}", "function sortByName(){\n self.sortBy = sortBy.teamName;\n sort(teamsData);\n }", "function sortCars() {\n cars.sort();\n loadCars();\n}", "function sortStudentCollectionByNameAscending() {\n\n view_clearViewTable();\n model_getAllStudentDataSortedByType(\"name\", -1);\n view_setNameSortStateCaretUp();\n\n}", "function sortByName()\n\t{\n\t\tvar filterHotel = getSorted('.list-hotels .hotel', 'data-name');\n\t\t\t$('.list-hotels').children().remove();\n\t\t\t$('.list-hotels').append(filterHotel);\n\t\t\t\n\t\tfunction getSorted(selector, attrName) {\n\t\t\treturn $($(selector).toArray().sort(function(a, b){\n\t\t\t\tvar aVal = a.getAttribute(attrName),\n\t\t\t\t\tbVal = b.getAttribute(attrName);\n\t\t\t\t\treturn (aVal.localeCompare(bVal));\n\t\t\t}));\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
middleware for checking image_url
function bodyHasImageUrl (req, res, next) { const { data : {image_url} = {}} = req.body; if(image_url && image_url != ""){ return next(); } next({ status: 400, message: "Dish must include an image_url", }); }
[ "function validateImageURL(image_url){\n \n }", "function imageUrlPropertyExists(req, res, next) {\n const { data: { image_url } = {} } = req.body;\n if (image_url) {\n return next();\n }\n next({\n status: 400,\n message: `Dish must include a image_url.`,\n });\n}", "function imageUrlPropertyIsEmpty(req, res, next) {\n const { data: { image_url } = {} } = req.body;\n if (image_url === \"\") {\n next({\n status: 400,\n message: `Dish must include a image_url.`,\n });\n }\n return next();\n}", "_imageExists(imageUrl){\n let http = new XMLHttpRequest();\n http.open('HEAD', imageUrl, false);\n http.send();\n return http.status !== 404;\n }", "function isImage(url) {\n\t\treturn settings.photo || settings.photoRegex.test(url);\n\t}", "function checkImage(input) {\n\n}", "function isImage(settings, url) {\n return settings.get('photo') || settings.get('photoRegex').test(url);\n }", "function isUrl(imgSrc){\n if (imgSrc.startsWith(\"http\")){\n return true;\n }\n else{\n return false;\n }\n}", "function imageUrlHandler() {\n function sanitize(src) {\n return buildImageUrl(unescape(src));\n }\n return { sanitize };\n}", "function isResource(request) {\n return request.url.match(/\\/imgs\\/.*$/) && request.method === 'GET';\n}", "function urlImgValid(_url) {\n \tif(_url == \"../img/error-img.png\") {\n \t\treturn false;\n \t}\n\n \treturn true;\n}", "function isImageURL(url) { return url.match(/\\.(jpeg|jpg|gif|png|tiff|bmp)$/) != null; }", "checkURL() {\n const url = document.getElementById('url').value; // User's url input\n // e.preventDefault();\n\n if (url.match(/\\.(jpeg|jpg|gif|png)$/) === null || url === '' || url.length === 0) { // If url is invalid, alert appears\n alert(\"Invalid Image!\");\n } else { // If url is valid, create gif\n this.createGif(url);\n }\n }", "function isServerlessFunctionImage(config) {\r\n return config.image ? true : false;\r\n}", "function isValidImage(images, allowed) {\n\n\n\n\n}", "function addImageValidation(req, res, next) {\n log.info(\"Add Image Validation Starts\");\n if(req.user.roles[0] === \"reviewer\" || req.user.roles[0] === \"admin\") {\n log.error(\"Image Upload Failed - Error: Unauthorized user\");\n res.status(200).send({'error': 'Unauthorized user'});\n } else {\n db.productDetail.findOne({productID: req.query.productId}, function(err, product) {\n if(err || !product) {\n next();\n } else if(product) {\n var userId = req.user._id.toString();\n if(userId !== product.supplier.toString() && userId !== product.designer.toString() && userId !== product.reviewer.toString()) {\n log.error(\"Add Image Failed - Error: Unauthorized user\");\n res.status(200).send({'error': 'Not authorized to update this product'});\n } else if(product.status === statusMapper.approved) {\n log.error(\"Add Image Failed - Error: Product is approved already\");\n res.status(200).send({'error': 'Approved product cannot be updated'});\n } else {\n next();\n }\n }\n });\n }\n log.info(\"Add Image Validation Ends\");\n}", "test() {\n return this.urlFromRequest().href.match(restaurantImageUrlRegex);\n }", "function imageExists(image_url){\r\n var http = new XMLHttpRequest();\r\n http.open('HEAD', image_url, false);\r\n http.send();\r\n return http.status != 404;\r\n}", "function check_name(req, res, next) {\n imageName = (req.body && req.body.image_sha1) || req.headers['ocra-image-sha1'];\n\n if (imageName != null) {\n next();\n } else {\n logError(\"'ocra-image-sha1' not present. Cannot proceed\");\n res.end(\"'ocra-image-sha1' not present. Cannot proceed\", 401);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function to get the div inside the EgCard tag.
getComponent() { return this.querySelector("div"); }
[ "function demoCardSubDivs(){\n\n}", "function getCardElement(cardType) {\n\treturn $('.open .fa-' + cardType).parent();\n}", "function div(content){ return elem(\"div\", content); }", "function cardSpanFromCard(card) {\n return document.getElementsByClassName(`${card.suit} ${card.rank}`)[0]\n}", "get horseCard_Jersey() {return browser.element(\"//android.widget.HorizontalScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.widget.Button/android.view.ViewGroup\");}", "get horseCard_Place() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[8]/android.widget.TextView[1]\");}", "function detailsDiv(){\n\t\treturn activeDiv.substr( 0, 6 ) + '_card_details';\n\t}", "get horseCard_RaceCard_Class() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[3]\");}", "function GetDivChart() {\n return $(\"#ana-GraphicCard-\" + _config.canvasId + \" .ana-GraphicCard-chart\");\n }", "get horseCard_RaceCard_Jockey() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[6]\");}", "function getCardItems($) {\n // Find all the items that containg Card Image: OR Card Image Iframe:\n // Case insensitive\n // This will include any Content Item that includes this string\n // even if it isn't meant to be a card\n var cardRE = new RegExp(\"(card image) ?(iframe)?:\", \"i\");\n\n var bbItems = jQuery(tweak_bb.page_id + \" > \" + tweak_bb.row_element)\n .children(\".details\")\n .children(\".vtbegenerated\")\n .filter(function () {\n return this.innerHTML.match(cardRE);\n // SKETCHY TODO\n //return match = this.innerHTML.match(cardRE);\n });\n\n var cards = extractCardsFromContent(bbItems);\n\n return cards;\n}", "function getComicShowDiv(){\n return document.getElementById('comic-show-page')\n}", "function getArticleElement() {\n return document.getElementById('WizClipperGroup');\n }", "function GetDivLoader() {\n return $(\"#ana-GraphicCard-\" + _config.canvasId + \" .ana-GraphicCard-loader\");\n }", "function getClassFromCard(card){\n return card[0].firstChild.className;\n }", "get div() {\n if (this.position == -1) {\n return $(`#${this.divName2}`);\n } else {\n return $(`#forth_feature_${this.position}`);\n }\n }", "function getCardItems($) {\n\t// Find all the items that containg Card Image: OR Card Image Iframe:\n\t\n\tvar bbItems = jQuery(tweak_bb.page_id + \" > \" +tweak_bb.row_element).children(\".details\").children('.vtbegenerated').filter(\n\t function( index ) {\n\t if ( $(this).filter(\":contains('Card Image:')\").length==1 ) {\n\t return true;\n\t } \n\t if ( $(this).filter(\":contains('Card Image Iframe:')\").length==1 ) {\n\t return true;\n\t } \n\t return false;\n\t } );\n\t \n\tvar cards = extractCardsFromContent( bbItems);\n\t\n\treturn cards;\n}", "function getPopupContainer(){\n return document.querySelector('div[id^=\"mount\"] > div > div:nth-child(1) > div > div:nth-child(7) > div');\n}", "get horseCard_Last5() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[6]/android.widget.TextView[1]\");}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total quantity of items. Arguments: items the items in the Bag
function getTotalQuantity(items) { return _.reduce(items, function(memo, item) { return memo + item.quantity; }, 0); }
[ "function getTotalItemCount(){\n var total_item_count = 0;\n for(var i =0; i < cart_items.length; i++){\n total_item_count += cart_items[i][1];\n }\n return total_item_count;\n}", "itemTotal(items) {\n let total = 0;\n for (let i = 0; i < items.length; i++) {\n total += items[i].price * items[i].quantity;\n }\n return total;\n }", "function _calculateTotalItems(items) {\n\n if (!items || !items.hasOwnProperty('total_count')) {\n return 0;\n }\n\n // Note: GitHub will return a maximum of 1,000 items for any search\n return (items.total_count > 1000) ? 1000 : items.total_count;\n }", "function totalNumberOfItems(numbOfItemsInCart){\n //takes in the shopping cart as input\n //returns the total number all item quantities\n //return the sum of all of the quantities from each item type\n var totItems = 0;\n for (let i = 0; i < numbOfItemsInCart.items.length; i++) {\n totItems += numbOfItemsInCart.items[i].quantity;\n }\n return totItems;\n}", "function countTotalItemsInCart(){\n\t\t\tvar total=0;\n\t\t\tfor(var i in cart){\n\t\t\t\ttotal=total+parseInt(cart[i].count);\n\t\t\t}\n\t\t\treturn total;\n\t\t}", "itemsCount() {\n return this._checkoutProducts\n .map((checkoutProduct) => checkoutProduct.count)\n .reduce((totalCount, count) => totalCount + count, 0);\n }", "function getTotalPrice(items) {\n return _.reduce(items, function(memo, item) {\n return memo + item.quantity * item.price;\n }, 0);\n }", "function num_items_inCart(c) {\n c.item_count;\n}", "getTotal() {\n let q = this.getItemCount();\n let p = 0;\n\n while (q--) {\n p += basket[q].price;\n }\n\n return p;\n }", "removedItemsQuantity() {\n\n\t\tlet quantity = 0;\n\t\tconst basketItems = BasketItemStore.getAll();\n\t\tconst removedItemId = this.props.item.id;\n\n\t\tbasketItems.map((item, i) => {\n\n\t\t\tif ( item.id == removedItemId ) {\n\t\t\t\tquantity += item.orderQuantity;\n\t\t\t}\n\n\t\t});\n\n\t\treturn quantity;\n\n\t}", "get totalItems() {\n\t\treturn this._cart.data.length\n\t}", "function numberOfItemsInCart(cart){\n\tvar n = 0;\n\tfor (i in cart['products']){\n\t\tn+=cart['products'][i]['quantity'];\n\t}\n\treturn n;\n}", "function getItemCount(cart) {\n let q = 0;\n cart.filter((cartItem) => cartItem.inCart === true).forEach(cartItem => {\n q += parseInt(cartItem.quantity);\n });\n return q;\n }", "calculateTotalItemsInCart() {\n const totalItems = this.state.cart.reduce((total, current) => total + parseInt(current.quantity), 0);\n return isNaN(totalItems) || totalItems === '' ? 0 : totalItems;\n }", "findTotalQuantity() {\n return this.cartItems.map(a => a.quantity).reduce((a, b) => a + b, 0);\n }", "function renderTotalQuantityAndPrice(items) {\n var totalQuantity = getTotalQuantity(items);\n\n // show bag count when quantity is positive\n if (totalQuantity > 0) {\n $bagCount.addClass('visible');\n } else {\n $bagCount.removeClass('visible');\n }\n\n $bagCount.text(totalQuantity);\n $bagTotal.text('$' + getTotalPrice(items) + '.00');\n }", "function quantity() {\n for (i = 0; i < shoppingCart.length; i++) {\n var item = shoppingCart[i];\n total = total + item.quantity;\n }\n return total;\n }", "function countQuantity() {\n var sum = 0;\n for (var i in cart) {\n sum += cart[i].quantity;\n }\n return sum;\n}", "getTotal() {\n\t\t\tlet itemCount = this.getItemCount(),\n\t\t\t\t\ttotal = 0;\n\n\t\t\twhile(itemCount--) {\n\t\t\t\ttotal += basket[itemCount].price;\n\t\t\t}\n\t\t\treturn total;\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns players with more turnovers than assists
function turnovers(arr){ var players = []; arr.forEach(function turn(element){ if(element.turnovers > element.assists){ players.push(element.name); } }); return players; }
[ "function moreTurnoversThanAssists() {\n console.log(\"* Players with more turnovers than assists:\");\n allPlayers.forEach(function(player) {\n if (player.turnovers > player.assists) {\n console.log(player.name);\n }\n });\n}", "function playerWithMoreTurnoverThanAssists(players) {\n\tvar theBadPlayers = players.filter(function(player){\n\t\treturn player.turnovers > player.assists;\n\t});\n\treturn theBadPlayers;\n}", "function playerMoreTurnThanAssist() {\n\n\t// Find player with more turnovers than assists\n\tfunction moreTurnThanAssist(player) {\n\t\treturn (player.assists < player.turnovers) === true; \n\t}\n\n\t// Generate array of players with more turnovers than assists\n\tvar badPlayers = players.filter(moreTurnThanAssist).map(getName);\n\n\t// Print result\n\tconsole.log(\"* Players with more turnovers than assists: \");\n\tbadPlayers.forEach(function(ele) { console.log(\" \" + ele)});\n\n}", "isTournamentOver() {\n return this.players.length === (this.donePlayers.length + this.badPlayers.length);\n }", "function nonGuardPlayerWithMostAssists(players) {\n\tvar thePlayer = players.filter(function(player){\n\t\treturn player.position !== 'G';\n\t}).reduce(function(maxPlayer, nextPlayer){\n\t\tif (maxPlayer.assists < nextPlayer.assists) maxPlayer = nextPlayer;\n\t\treturn maxPlayer;\n\t}, players[0]);\n\treturn thePlayer.name + \" with \" + thePlayer.assists;\n}", "getRemainingOpponents(player) {\n return this.players.reduce((opponentList, opponent) => {\n let match = this.getMatch(player, opponent);\n if (!match && opponent !== player) {\n return opponentList.concat(opponent);\n } else {\n return opponentList;\n }\n }, []);\n }", "isSeriesOver(gameResults, numGames) {\n let p1WinCount = gameResults\n .filter(gameResult => (gameResult.winner === this.player1.getId()))\n .length;\n let p2WinCount = gameResults.length - p1WinCount;\n return p1WinCount > numGames / 2 || p2WinCount > numGames / 2;\n }", "_gameIsOver() {\n return this._players.filter(p => p.cardCount === 0).length === this._numPlayers - 1;\n }", "function nonGuardMostAssists() {\n\n\t// Helper functions\n\tfunction notGuard(player) { return player.position !== 'G' };\n\tfunction assists(player) { return player.assists };\n\n\t// Call helper to find player with most assists\n\tvar mostAssistsPlayer = players.filter(notGuard).reduce( function(assistsPlayer, player) {\n\t\tif (player.assists > assistsPlayer.assists) {\n\t\t\tassistsPlayer.name = player.name; \n\t\t\tassistsPlayer.assists = player.assists\n\t\t}\n\t\treturn assistsPlayer;\n\t}, assistsPlayer = {name:'', assists:0});\n\n\t// Print result\n\tconsole.log(\"* Non guard player with most assists: %s with %d assists\", mostAssistsPlayer.name, mostAssistsPlayer.assists);\n}", "getWinners(){\n let winners = [];\n if(this.highScore()>=this.winningScore){\n _.each(this.players, player => {\n if(player.score===this.highScore())\n winners.push(player.playerName);\n });\n }\n return winners;\n }", "function teamsWithMoreThanThreePlayers() {\n setTeams(teams.filter((team) => team.players.length > 3));\n }", "function winningTeam() {\n const homeTeamStats = Object.values(homeTeam().players);\n const awayteamStats = Object.values(awayTeam().players);\n const homePoints = homeTeamStats.reduce((a, b) => a + b.points, 0);\n const awayPoints = awayteamStats.reduce((a, b) => a + b.points, 0);\n return homePoints > awayPoints ? homeTeam().teamName : awayTeam().teamName;\n}", "getOpponentCount(){\n return this.getOpponents()\n .filter( o => o.isAlive() )\n .length;\n }", "function countSetsPerPlayer(match) {\n let player1SetsWon = 0;\n let player2SetsWon = 0;\n\n match.sets.forEach(set => {\n //player1 has more points\n if (set.player1 - 1 > set.player2) {\n player1SetsWon++;\n }\n //player2 has more points\n if (set.player1 < set.player2 - 1) {\n player2SetsWon++;\n }\n });\n\n return { player1: player1SetsWon, player2: player2SetsWon };\n}", "function getWinners(outcome) {\n let winners = [];\n let bestScore = null;\n players.forEach(function (player) {\n const score = scorePicks(player.picks, outcome);\n if (scoreIsBetter(bestScore, score)) {\n winners = [player]; // winners is a list of just this one player\n bestScore = score;\n }\n else if (bestScore === score) { // tied, so add this player to the winners list\n winners.push(player);\n }\n });\n return winners;\n }", "function filterByNoOfAwardsxTeamxAge(awrd, tm, ag){\n var newlst = []\n for (const prop in players){\n if (players[prop].team==tm && players[prop].age < ag){\n // for (const aw in players[prop].awards){\n if (players[prop].awards.length>=awrd)\n newlst.push(players[prop])\n // }\n }\n }\n return newlst\n}", "function checkTheWinner(players) {\n const scores = [];\n const winners = [];\n\n players.map(player => scores.push(player.score));\n\n const winnerScore = Math.max(...scores);\n\n players.map(player => {\n if(player.score == winnerScore) {\n winners.push(player);\n }\n });\n\n return winners;\n}", "function MoreThanOnePlayerActive(players, owed)\n{\n\tlet active = 0;\n\t\n\tfor(let i = 0, n = players.length; i < n; i++)\n\t{\n\t\tif(players[i].hand.length > 0 || i == owed)\n\t\t{\n\t\t\tif(++active == 2)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}", "function nonGuardMostAssists() {\n var nonGuards = [];\n var playerWithMostAssists = null;\n var mostAssists = 0;\n\n nonGuards = allPlayers.filter(function(player) {\n if (player.position !== \"G\") {\n return player;\n }\n });\n\n nonGuards.forEach(function(player) {\n if (mostAssists < player.assists) {\n mostAssists = player.assists;\n playerWithMostAssists = player;\n }\n });\n console.log(\"* Non guard player with most assists: \"+ playerWithMostAssists.name + \" with \" + playerWithMostAssists.assists);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns Cloak service data path.
getDataPath() { const validApp = process.type === 'renderer' ? remote.app : app let configFolder = path.join(validApp.getPath('appData'), configFolderName) if (getOS() === 'linux') { configFolder = path.join(validApp.getPath('home'), '.CloakCoin') } return configFolder }
[ "dataPath() {\n return this.config(\"paths.data\");\n }", "getDataPath(filename) {\n return path.resolve(`${os.homedir()}/.json_config/robinhood/${filename}.json`);\n }", "function datafilePath() {\n return path.resolve(__dirname, DOWNLOAD_STATS_FILENAME);\n}", "function ___R$$priv$project$rome$$internal$core$common$constants_ts$getDataDirectory() {\n\t\tconst XDG_DATA_HOME = ___R$$priv$project$rome$$internal$core$common$constants_ts$getEnvironmentDirectory(\n\t\t\t\"XDG_DATA_HOME\",\n\t\t\t\"rome\",\n\t\t);\n\t\tif (XDG_DATA_HOME !== undefined) {\n\t\t\treturn XDG_DATA_HOME;\n\t\t}\n\n\t\tif (process.platform === \"win32\") {\n\t\t\treturn ___R$$priv$project$rome$$internal$core$common$constants_ts$getLocalAppDataDir().append(\n\t\t\t\t\"Data\",\n\t\t\t);\n\t\t}\n\n\t\tif (process.platform === \"darwin\") {\n\t\t\treturn ___R$project$rome$$internal$path$constants_ts$HOME_PATH.append(\n\t\t\t\t\"Library\",\n\t\t\t\t\"Rome\",\n\t\t\t);\n\t\t}\n\n\t\treturn ___R$project$rome$$internal$path$constants_ts$HOME_PATH.append(\n\t\t\t\".local\",\n\t\t\t\"share\",\n\t\t\t\"rome\",\n\t\t);\n\t}", "function baseDir () {\n return _path.join(__dirname, '/../.data/')\n}", "fullPath() {\n return path.join(env.localStoragePath, this.containerName);\n }", "get path () {\n const { app, service } = data;\n\n if (!service || !app || !app.services) {\n return null;\n }\n\n return Object.keys(app.services)\n .find(path => app.services[path] === service);\n }", "get path() {\n var app = data.app,\n service = data.service;\n\n if (!service || !app || !app.services) {\n return null;\n }\n\n return Object.keys(app.services).find(function (path) {\n return app.services[path] === service;\n });\n }", "get path() {\n var app = data.app,\n service = data.service;\n\n\n if (!service || !app || !app.services) {\n return null;\n }\n\n return Object.keys(app.services).find(function (path) {\n return app.services[path] === service;\n });\n }", "function GetApiPath() {\n return '/api/data/v9.0/';\n }", "get path() {\n var { app: app, service: service } = data;\n\n if (!service || !app || !app.services) {\n return null;\n }\n\n return Object.keys(app.services).find(function (path) {\n return app.services[path] === service;\n });\n }", "function getDataPath(fileName) {\n return path.join(process.cwd(), 'data', fileName ? fileName : '');\n}", "get dataDir() { return path.join(this.userLocalDir, 'CMakeTools'); }", "function CalculateCouchData() {\n return path.join(__dirname, './CouchSurfing/Couch.json');\n}", "get path() {\n const { app, service } = data;\n if (!service || !app || !app.services) {\n return null;\n }\n return Object.keys(app.services)\n .find(path => app.services[path] === service);\n }", "get heartbeatPath() {\n const environment = this.services.get(environment_1.IEnvironmentService);\n return path.join(environment.userDataPath, \"heartbeat\");\n }", "getOldDataPath(filename) {\n return path.resolve(`${os.homedir()}/node_json_db/${filename}.json`);\n }", "get _dsComponentPath() {\n const { name, patternType } = this.props;\n const { APP_DESIGN_SYSTEM } = this.particleApp;\n\n return join(APP_DESIGN_SYSTEM, PATTERNS_FOLDER, patternType, name);\n }", "appDataFolder() {\n const rootAppDataFolder = process.env.APPDATA || \n (\n process.platform == 'darwin' ? \n path.join(process.env.HOME, 'Library', 'Preferences') :\n path.join('/var', 'local')\n );\n\n return path.join(rootAppDataFolder, 'RedCarpet');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a date. Selects the last instance of the subform class and removes it.
function removeDate() { let $removedForm = $(".subform").last(); let removedIndex = parseInt($removedForm.attr("data-index")); $removedForm.remove(); }
[ "removeDate(){\n\t\tthis.date = null;\n\t}", "function remDate(obj){\n console.log(\"remove date\");\n $(obj).parent().parent().remove(); \n $(obj).parent().parent().find(\"input[name*='cr_date_submit_']\").val('false');\n}", "function removeDateInput(date) {\n inputs = document.querySelectorAll('input.date')\n inputs.forEach((input) => {\n if (input.value === date) {\n form.removeChild(input)\n console.log(\"selection removed\", input.value)\n }\n })\n}", "function removeTime() {\n let $parent = $(this).parent();\n let $removedOption = $parent.find(\"input[type=time]\").last();\n \n $removedOption.remove();\n\n}", "function removeGroupByDate() {\n $('#views-form-content-hub-discovery-default').find('.content-hub-group-date').remove();\n }", "function deleteTimeFields() {\n const parentElement = this.parentElement;\n\n parentElement.remove();\n}", "removeDate(date) {\n\t\tthis.dates = this.dates.filter(time => date.valueOf() != time)\n\t\tthis.setNumbers()\n\t}", "function EWSRP_RemoveDayInstance()\n{\n var instList, selIdx;\n\n this.GetControl(\"RP_AP_DAYVAL\").style.display = \"none\";\n\n instList = this.GetControl(\"RP_AP_INSTLST\");\n selIdx = instList.selectedIndex;\n\n if(selIdx === -1)\n instList.selectedIndex = 0;\n else\n {\n if(this.GetControl(\"RP_AP_DAY\").disabled === \"\")\n this.DayInstanceList.splice(selIdx, 1);\n else\n this.DayList.splice(selIdx, 1);\n\n instList.remove(selIdx);\n\n if(selIdx < instList.options.length)\n instList.selectedIndex = selIdx;\n else\n if(instList.options.length !== 0)\n instList.selectedIndex = instList.options.length - 1;\n else\n this.GetControl(\"RP_AP_DELINST\").disabled = this.GetControl(\"RP_AP_CLRINST\").disabled = \"disabled\";\n }\n}", "function cancelDate(element) {\n $(element).parents('.date-form').siblings('.editable-field').show();\n $(element).parents('.form-inline').remove();\n }", "function removeDate() {\n var idx = dates.indexOf(document.getElementById(\"calendar\").value);\n if(idx != -1) {\n dates.splice(idx, 1);\n displayDates();\n }\n }", "removeBack() {\n if(this._days.length > 0) {\n this._days.pop();\n }\n }", "function removeDateTime() {\n dateAndTime.className = 'hidden';\n }", "clearDate() {\n this.set('date', null);\n }", "function onHealthLogDateRemove() {\n self.editHealthlog.nextVisitDate = null;\n }", "function appointDateGroup(){\n $(\"#AppointmentDate\").parent().find(\"span.help-inline\").remove();\n}", "function removeFormAddChildComment() {\n lastFormAddChildComment.remove();\n lastFormAddChildComment = undefined;\n}", "undoAddDate(type, e){\n e.preventDefault();\n if(type === 'exclude'){\n let newExcludes = this.props.calendarForm.excludeDates;\n if(newExcludes.length !== 0){\n newExcludes.pop();\n this.props.setCalExcludeDates(newExcludes);\n }\n }\n else if(type === 'include'){\n let newIncludes = this.props.calendarForm.includeDates;\n if(newIncludes.length !== 0){\n newIncludes.pop();\n this.props.setCalIncludeDates(newIncludes);\n }\n }\n }", "removeForm() {\n let index = FORMSET_BODY.children.length -1;\n let child = FORMSET_BODY.children[index];\n\n if (child) {\n FORMSET_BODY.removeChild(child);\n }\n\n FORMSET.querySelector('[name=\"form-TOTAL_FORMS\"]').value = index;\n this.updateButton();\n }", "function removeTimeFields() {\n $('.time_field').remove();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if the player is still alive
function CheckAlive() { if(this.currentHealth <= 0) { Die(); } }
[ "function isPlayerAlive(){\n if(app.player.health < 1){\n app.playerAlive = false;\n } else{\n app.playerAlive = true;\n }\n}", "function isAlive(activePlayer) {\n if (activePlayer.health > 0) {\n return true;\n }\n return false ;\n}", "isPlayerDead() {\n \n return !this.player.exist;\n }", "function isAlive() {\n\treturn (health > 0);\n}", "checkIfDeadPlayerNearby(){\n\t\tif(!this.player.dead){\t\t\t\t\t\n\t\t\tif(Math.abs(Phaser.Point.distance(this.player.position, this.otherPlayer.position)) < 64 && this.otherPlayer.dead){\n\t\t\t\tthis.player.resurrectText.setText(\"Press Resurrect Key\");\n\t\t\t\tif(this.player.keys.Resurrect.isDown){\t\n\t\t\t\t\tthis.player.resurrecting = true;\n\t\t\t\t\tthis.resurrectTimer.add(3500, this.resurrectPlayer, this, this.otherPlayer, this.player);\t\n\t\t\t\t\tthis.resurrectTimer.start();\t\n\t\t\t\t\tthis.player.resurrectText.setText(Math.floor(this.resurrectTimer.duration/1000) + 1);\t\t\n\t\t\t\t} else {\n\t\t\t\t\tthis.resurrectTimer.stop();\n\t\t\t\t\tthis.player.resurrecting = false;\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t} else {\n\t\t\t\tthis.player.resurrectText.setText(\" \");\n\t\t\t}\t\t\n\t\t}\n\t}", "function isOpponentAlive(){\n if(app.opponent.health < 1){\n app.opponentAlive = false;\n } else{\n app.opponentAlive = true;\n }\n}", "playerDead() {\n\n return this.player.isDead();\n }", "checkAlive()\n { \n if(this.isAlive === false)\n {\n this.enemyLevel++;//increases what level enemy the player is on \n this.reset();//reset the enemy \n return false;//retrun that the enemy is dead\n }\n return true;\n }", "function checkPlayerCondition() {\r\n\r\n\tif (player.health < 1) {\r\n\t\tplayer.lives--;\r\n\t\tplayer.initCheckpoint();\r\n\t}\r\n\r\n\tif (player.y > 1350) {\r\n\t\t\r\n\t\tSounds.yell.play();\r\n\t\tplayer.lives--;\r\n\t\tplayer.grounded = true;\r\n\t\tplayer.airborne = false;\r\n\t\tplayer.jumping = false;\r\n\t\tplayer.velY = 0;\r\n\t\tplayer.health = 3;\r\n\t\t\r\n\t\tif (player.lives > 0) {\r\n\t\t\tplayer.init(-25, 546);\r\n\t\t}\r\n\r\n\t\r\n\t}\r\n\t\r\n\tif (player.lives < 1) {\r\n\t\tplayer.init(-200,-200);\r\n\t\tgameOver = true;\r\n\t}\r\n\r\n}", "function checkStatus(character){ \n if(character.live==false){\n character.changeAnimation('dead');\n character.dying-=1;\n reviveAfterMusic(character);\n\n }\n if(character.live==false && character.liveNumber==0){\n gameConfig.status=\"gameover\";\n mario_gameover.play();\n }\n\n}", "checkIfAlive() {\n if (this.health < 0.1 && this.health > 0) { //check if its alive or not\n this.spyGone = true;\n }\n }", "everyoneDead(){\r\n\t\tfor(let i=0; i<this.n; i++){\r\n\t\t\tif(this.players[i].game.alive == true){\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true\r\n\t}", "function checkPlayerDie() {\n\tif (gameChar_y > height) {\n\t\tlives -= 1;\n\t\tstartGame();\n\t\tsplashSound.play();\n\t}\n}", "playerVisible() {\n // Player entity blinks at 2 cycles per second\n const blinkState = Math.floor(this.timeSinceReset * 4 % 2) == 0;\n return this.state != this.states.running || blinkState || this.playerInputAllowed();\n }", "function checkPlayerDied()\n{\n if(gameChar_y > height)\n {\n if(lives > 0)\n {\n lives -= 1;\n startGame();\n }\n else\n {\n isLost = true; \n }\n }\n \n}", "gameEnded() {\n if (this.turnLeft === 0) {\n return true;\n } else if (Character.findPlayersStillAlive().length < 2) {\n return true;\n }\n }", "function checkIfPlayerIsPlaying(){\n\t\n\tvar tempPlayer = getPlayerById(conectedUser.id);\n\tif(tempPlayer.playNow==1){\n\t\treturn true; // Player is now playing\n\t}\n\telse{\n\t\treturn false;\n\t}\n}", "function checkActive() {\n var here;\n if (active === undefined) {\n return false;\n }\n \n function playerHere(player) {\n return _.any(here, function (uuid) {\n return player === uuid;\n });\n }\n \n // make sure a challenger hasn't left\n if (active.player1 !== '' && active.player2 !== '') {\n here = main.uuids();\n \n if (!playerHere(active.player1) || !playerHere(active.player2)) {\n return false;\n }\n }\n return true;\n }", "function checkLives() {\n ctx.drawImage(gnomesplosion, gnome_x - 30, gnome_y - 60, 200, 200);\n gnomehurtSound.play();\n setTimeout(function () {\n invincibility = false;\n }, 1000);\n lives -= 1;\n invincibility = true;\n if (lives > 0) {\n reset();\n } else if (lives === 0) {\n themeSound.stop();\n gameoverSound.play();\n alive = false;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates a space with a grid of objects from 0,0 to 1,1. Width, height indicate the number of cells in the appropriate dimension
function populateGrid(space, width, height) { var distX = 1.0 / width; var distY = 1.0 / height; var xpos, ypos; var x,y; ypos = 0; for (y=0; y<height; ++y) { xpos = 0; for (x=0; x<width; ++x) { space.addObject({ x: xpos, y: ypos }, makeSpaceLocation({ x: xpos, y: ypos, width: distX, height: distY })); xpos += distX; } ypos += distY; } }
[ "function Grid(width, height){\n this.space = new Array(width*height);\n this.width = width;\n this.height = height;\n}", "function Grid(width, height) {\n this.space = new Array(width * height);\n this.width = width;\n this.height = height;\n}", "function fillGrid()\n{\n for(let i=0;i<VCells;i++)\n {\n for(let j=0;j<hCells;j++)\n {\n grid.push(new square(j*blockSize,i*blockSize));\n }\n }\n}", "function createGrid(width, height) {\n var grid = createArray(width, height);\n for(var x = 0; x < width; x++) {\n for(var y = 0; y < height; y++) {\n //default each cell to having all four walls up\n grid[x][y] = new Cell(x, y, true, true, true, true);\n }\n }\n return grid;\n }", "constructor(width=4, height=3){\r\n\t\tthis.width=width; //Length of the 'cells' array\r\n\t\tthis.height=height; //Length of the arrays within the 'cells' array\r\n\r\n\t\tthis.cells=[]; //A two dimensional array containing Cell objects that represent the grid\r\n\t\tfor(let x=0;x<this.width;x++){\r\n\t\t\tthis.cells.push([]);\r\n\t\t\tfor(let y=0;y<this.height;y++){\r\n\t\t\t\t/*\r\n\t\t\t\t\tCreates a new Cell with the current Grid as its parent grid, and its x and y\r\n\t\t\t\t\tcoordinates within the current Grid's 'cells' 2D array.\r\n\t\t\t\t*/\r\n\t\t\t\tthis.cells[x].push(new Cell(this, x, y));\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function makeGrid() {\r\n\tfor(let i=0;i<width;i++){\r\n\t\tcell[i]=[];\r\n\t\tfor(j=0;j<width;j++){\r\n\t\t\tcell[i][j]=cellObject.cell;\r\n\t\t}\r\n\t}\r\n\treturn cell;\r\n}", "function createGrid(width, height) {\n\n}", "create() {\n for (let r = 1; r < 5; r++) {\n this.grid[r] = [];\n for (let c = 1; c < 5; c++) {\n this.createEmptyTile(r, c);\n }\n }\n }", "function makeGrid() {\r\n if (!gridPresent){\r\n for (let i = 0; i < rows; i++) {\r\n for (let j = 0; j < columns; j++) {\r\n blocks.push(new Block(spaceX/2 + dimension * (j + 0.05), spaceY/2 + dimension * (i + 0.05)));\r\n }\r\n }\r\n } else {\r\n for (let i = 0; i < rows; i++) {\r\n for (let j = 0; j < columns; j++) {\r\n blocks[i * columns + j].update(i, j);\r\n }\r\n }\r\n }\r\n\r\n}", "function createGrid() {\n for(let row = 0; row < num_rows; row++) {\n nodes[row] = [];\n for(let col = 0; col < num_cols; col++) {\n nodes[row][col] = {\n x: col *(rectWidth + 1),\n y: row * (rectHeight + 1),\n state: STATE.EMPTY,\n prevState: STATE.EMPTY, // used for when the start/end nodes are being moved\n weight: 0\n };\n }\n }\n nodes[startNode.row][startNode.col].state = STATE.START;\n nodes[finishNode.row][finishNode.col].state = STATE.FINISH;\n}", "constructor (size) {\n\n var i,j;\n var grid = [];\n\n //Initialize each space to 0\n for (i=0; i<size; i++) {\n\n var row = [];\n\n for (j=0; j<size; j++) {\n row.push(0);\n }\n\n grid.push(row);\n }\n\n this.grid = grid;\n this.size = size;\n\n }", "function populateGameGrid(grid) {\n for (var i = 0; i < NUM_ROWS; i += 1) {\n for (var j = 0; j < NUM_COLS; j += 1) {\n grid[i][j] = new Cell();\n grid[i][j].yPosition = i * CELL_SIZE;\n grid[i][j].xPosition = j * CELL_SIZE;\n }\n }\n }", "prepareGrid() {\n this.cells = new Array(this.columns)\n for (var x = 0; x < this.cells.length; x++) {\n this.cells[x] = new Array(this.rows);\n for (var y = 0; y < this.cells[x].length; y++) {\n this.cells[x][y] = new Cell(x, y);\n }\n }\n }", "function populateGameGrid(grid) {\r\n\r\n for (var i = 0; i < NUM_ROWS; i += 1) {\r\n for (var j = 0; j < NUM_COLS; j += 1) {\r\n //fills all grid with initial cells\r\n grid[i][j] = new Cell();\r\n //x position match x coordinates\r\n grid[i][j].xPosition = j * CELL_SIZE;\r\n //y position match y coordinates\r\n grid[i][j].yPosition = i * CELL_SIZE;\r\n }\r\n\r\n } \r\n\r\n }", "function initialize(){\n for(var i = 0; i < num_cells; ++i){\n for(var j = 0; j < num_cells; ++j){\n var cell = {\n xpos : (j*cell_size_px)+vert_margin,\n ypos : (i*cell_size_px)+horiz_margin,\n collisions : 0,\n index : (num_cells * i) + j\n };\n cells.push(cell);\n //document.writeln(\"x: \" + cell.xpos + \"y: \" + cell.ypos);\n }\n }\n drawGrid();\n d3.interval(updateGrid,2000);\n}", "createGrid () {\n const cells = []\n\n // Creates one column of cells after the other, from left to right.\n for (let x = 0; x < this._gridWidth; x++) {\n // Adds a blank column of cells.\n cells.push([])\n\n // Creates all cells in a column, from top to bottom.\n for (let y = 0; y < this._gridHeight; y++) {\n cells[x].push(\n new Cell(this._scene, this.getWorldX(x), this.getWorldY(y), x, y)\n )\n }\n }\n\n return cells\n }", "function initGrid( cellCount ) {\n for( let i = 0; i < cellCount; i++ ) {\n grid[i] = []; \n\n for( let j = 0; j < cellCount; j++ ) {\n let x = j * Cell.size;\n let y = i * Cell.size;\n\n let cell = Cell.create( x, y );\n\n if( i === 0 && j === 7 ) {\n cell.state = 1;\n }\n\n cell.draw();\n\n grid[i][j] = cell;\n }\n }\n }", "function createGrid() {\n grid = new Array(numCols);\n\n for (let i = 0; i < grid.length; ++i) {\n grid[i] = new Array(numRows);\n\n // Creates Cell objects, randomized dead or alive\n for (let j = 0; j < grid[i].length; ++j) {\n let status = floor(random(2)); // dead or alive\n \n grid[i][j] = new Cell(i * CELL_DIMENSION, j * CELL_DIMENSION, CELL_DIMENSION - 1, status);\n }\n }\n}", "function setGrid(width,height){\n\tbd.cellWidth = bd.width/width;\n\tbd.cellHeight = bd.height/height;\n\tbd.x = width;\n\tbd.y = height;\n\n\tctx.clearRect(0,0,bd.width,bd.height);\n\t//Initalizes the state array and the neighbor array\n\tstate\t = new Array(width);\n\tneighbor = new Array(width);\n\tfor(var x = 0; x < width; x ++){\n\n\t\tstate[x] \t= new Array(height);\n\t\tneighbor[x] = new Array(height);\n\n\t\tfor(var y = 0; y < height; y ++){\n\t\t\tif(random && Math.random()>0.5)\n\t\t\t\tstate[x][y] = true;\n\t\t\telse state[x][y] = false;\n\t\t\t\tneighbor[x][y] = 0;\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the dice text for the display bar.
function getDiceText() { var dicetext = ""; var dicearray = new Array(); for(var i = 0; i < CurrentDiceGroup.dicegroup.length; i++) { var s = CurrentDiceGroup.dicegroup[i].sides; if(dicearray[s] == 'undefined' || dicearray[s] == null) { dicearray[s] = 0; } dicearray[s] += 1; } for(var sides = 0; sides < dicearray.length; sides++) { if(dicearray[sides] != 'undefined' && dicearray[sides] != null) { dicetext += (dicearray[sides] == 1) ? "" : dicearray[sides]; dicetext += 'D'+sides+','; } } dicetext = dicetext.replace(/,\s*$/,""); return dicetext; }
[ "function diceRollLogRender(table) {\n //calculate totals for checking: totals, relative, expected, deviation\n var diceTotals = new Array(0, 0, 0, 0);\n var diceSides = 0;\n //count the number of dice sides\n for (var i = 0; i < diceRollLog.length; i++) {\n //check all items in array that have value (0 is ignored)\n if (diceRollLog[i] != null && diceRollLog[i] != 0) {\n diceSides++;\n }\n }\n //display results for dice throws, they are indexed in array\n for (var i = 0; i < diceRollLog.length; i++) {\n if (diceRollLog[i] != null && diceRollLog[i] != 0) {\n //double checking sums\n diceTotals[0] += diceRollLog[i]; //total throws\n diceTotals[1] += (diceRollLog[i] * 100) / (diceRollThrows); //relative throws for each\n diceTotals[2] += (100 / diceSides); //expected for this dice throw\n diceTotals[3] += (((diceRollLog[i] * 100) / (diceRollThrows)) - 100 / diceSides); //deviation to expected\n\n //create new row and cells\n var row = table.insertRow(table.rows.length);\n //insert 5 cells\n insertCells(row, 5);\n //display results for single dice result\n row.cells[0].innerHTML = \"<b>\" + i + \"</b>\";\n row.cells[1].innerHTML = diceRollLog[i];\n row.cells[2].innerHTML = \"<b>\" + ((diceRollLog[i] * 100) / (diceRollThrows)).toFixed(2) + \"%</b>\";\n row.cells[3].innerHTML = (100 / diceSides).toFixed(2) + \"%\";\n row.cells[4].innerHTML = (((diceRollLog[i] * 100) / (diceRollThrows)) - 100 / diceSides).toFixed(2) + \"p.p.\";\n }\n }\n //insert totals row\n var row = table.insertRow(table.rows.length);\n //insert 5 cells\n insertCells(row, 5);\n //display total results for double checking\n row.cells[0].innerHTML = \"<b>Total</b>\";\n row.cells[1].innerHTML = diceTotals[0];\n row.cells[2].innerHTML = \"<b>\" + diceTotals[1].toFixed(2) + \"%</b>\";\n row.cells[3].innerHTML = diceTotals[2].toFixed(2) + \"%\";\n row.cells[4].innerHTML = Math.abs(diceTotals[3].toFixed(2)) + \"p.p.\";\n}", "function drawEggs() {eggsCountText.innerHTML = numeral(eggs).format('0.00a');}", "function drawGold() {goldCountText.innerHTML = numeral(gold).format('0.00a');}", "function convertDice() {\n $('.six-sided-die').each(function () {\n var $die = $(this);\n //It does something strange when I try to use the :not selector,\n // So go old school\n if ($die.hasClass('fate-die')) {\n return;\n }\n var count = $('.dot:contains(\"•\")', $die).length;\n $die.empty();\n $die.attr('data-d6-roll', count);\n\n var $face = $('<span>')\n .css('display', 'table-cell')\n .css('vertical-align', 'middle');\n\n if (count < 3) {\n $face.html('&minus;');\n if (fudgeConfig.useColors()) {\n $die.css('color', fudgeConfig.minusColor());\n }\n $die.empty().append($face);\n $die.addClass('fate-roll-minus');\n $die.attr('data-fate-roll', -1);\n } else if (count > 4) {\n $face.html('+');\n if (fudgeConfig.useColors()) {\n $die.css('color', fudgeConfig.plusColor());\n }\n $die.empty().append($face);\n $die.addClass('fate-roll-plus');\n $die.attr('data-fate-roll', 1);\n } else {\n $die.text(' ');\n $die.attr('data-fate-roll', 0);\n }\n\n $die.css('display', 'table');\n $die.css('text-align', 'center');\n $die.css('font-size', '30px');\n $die.css('font-weight', 'bold');\n\n //Add class to prevent re-processing\n $die.addClass('fate-die');\n });\n }", "toConsoleString() {\n const FACE_DOWN = '\\u001b[31m';\n const RESET = '\\u001b[0m';\n let ret = '';\n ret += this.hand.length > 0 ? UNICODE_FACE_DOWN + ' ' : ' ';\n ret += this.waste.length > 0 ?\n toUnicode(this.waste[this.waste.length - 1]) + ' ' : ' ';\n ret += ' '.repeat(this.rules.tableauSize - SUITS.length);\n SUITS.forEach(suit => {\n ret += this.foundation[suit] >= 0 ? toUnicode(\n VALUES[this.foundation[suit]] + suit\n ) + ' ' : ' ';\n });\n ret += '\\n';\n const tableauHeight = Math.max.apply(\n Math, this.tableau.map(c => c.faceDown.length + c.faceUp.length)\n );\n for (let i = 0; i < tableauHeight; i++) {\n ret += '\\n ';\n for (let j = 0; j < this.tableau.length; j++) {\n\tconst faceDownLength = this.tableau[j].faceDown.length;\n\tconst faceUpLength = this.tableau[j].faceUp.length;\n\tif (i < faceDownLength) {\n\t ret +=\n\t FACE_DOWN + toUnicode(this.tableau[j].faceDown[i]) + RESET + ' ';\n\t} else if (i < faceDownLength + faceUpLength) {\n\t ret += toUnicode(this.tableau[j].faceUp[i - faceDownLength]) + ' ';\n\t} else {\n\t ret += ' ';\n\t}\n }\n }\n return ret;\n }", "function rollDiePoolAndDisplayResults() {\n const printedDieResults = document.getElementById('printed_die_results');\n var printedDieResultsText = printedDieResults.textContent;\n if (printedDieResultsText.length > 0) {\n\tprintedDieResultsText += GROUP_ROLL_SPLIT;\n }\n var newPrintedResults = '';\n for (const die of diePool) {\n const min = die[0];\n const max = die[1];\n const dieResult = getRandomInt(min, max);\n updateDieStats(dieResult);\n\tif (newPrintedResults.length > 0) {\n\t\tnewPrintedResults += INDIVIDUAL_ROLL_SPLIT;\n\t}\n\tnewPrintedResults += dieResult;\n }\n printedDieResults.textContent = (printedDieResultsText + newPrintedResults);\n}", "_showResultAsHTML(total, d6Rolls, dieRollsPerSkill, extraD4Rolls) \n {\n let log = `<div class='result'><b>D6 Roll:</b>\\n<br/>\\n`;\n\n // For the D6 rolls, first check for a botch and return immediately if so.\n if (DieRoll.isBotch(d6Rolls)) {\n log += `<div>${d6Rolls[0]} + ${d6Rolls[1]} (<b class='botch'>Botch!</b>)</div></div>`;\n return log;\n }\n\n // Format the D6 rolls.\n console.assert(d6Rolls.length % 2 === 0, \"Uneven number of d6 rolls\");\n let d6Results = DieRoll.group(2, d6Rolls).map(roll => {\n let doubleStr = (roll[0] === roll[1] ? \" (Double!)\" : \"\");\n return `${roll[0]} + ${roll[1]}${doubleStr}`;\n });\n log += \"<div>\";\n log += d6Results.join(\", \");\n let d6Total = d6Rolls.reduce((x, y) => x + y);\n log += `&nbsp;&nbsp;= ${d6Total}</div>\\n`;\n\n // Add the stat if necessary.\n if (this.stat) {\n log += `<b>Stats:</b><br/><div>${this.stat.name} = ${this.stat.value}</div>\\n`;\n }\n\n // Now add the skill rolls.\n let skills = this.skills;\n if (skills.length > 0) {\n log += \"<b>Skills:</b><br/>\\n<div>\";\n let skillLines = skills.map(skill => {\n console.assert(skill.name, `Skill ${skill} has no name`);\n\n let rollsForSkill = [];\n if (dieRollsPerSkill[skill.name]) {\n rollsForSkill = dieRollsPerSkill[skill.name];\n }\n\n let specStr = \"\", finalTotal = 0, specs = this.specialties[skill.name];\n if (specs) {\n specStr = specs.map(s => `<br/><span>(+ ${s.name} = ${s.value})</span>`)\n .join(\"\");\n }\n finalTotal += rollsForSkill.reduce((x, y) => x + y);\n let rollsText = rollsForSkill.map(e => e.toString()).join(\" + \");\n let safeName = DieRoll.sanitiseHTML(skill.name);\n if (rollsForSkill.isEmpty) { \n // Zero-level skills. Don't show the rolls as there aren't any.\n return `${safeName} (${rollsForSkill.length}) = ${finalTotal} ${specStr}`;\n } else {\n return `${safeName} (${rollsForSkill.length}) = ${rollsText} = ${finalTotal} ${specStr}`;\n }\n });\n log += skillLines.join(\"<br/>\\n\");\n\n if (this.addTick) {\n console.assert(skills.length === 1, \"AddTick set and \" + skills.length + \" skills\");\n if (skills[0].ticks === 19) {\n let skill = skills[0];\n log += `<div style='font-weight: bold; color: blue'>\nSkill ${skill.name} levelled up to ${skill.value + 1}!\n</div>`;\n }\n }\n log += \"</div>\\n\";\n }\n\n // Add extra d4s.\n if (this.extraD4s !== 0) {\n let extraD4Text = extraD4Rolls.map(r => r.toString()).join(\" + \");\n let extraD4Value = extraD4Rolls.reduce((x, y) => x + y, 0);\n log += `<b>Extra D4s:</b><br/>\\n<div>${extraD4Text} = ${extraD4Value}</div>\\n`;\n }\n\n // Add any final adds.\n if (this.adds !== 0) {\n log += `<b>Adds:</b><br/>\\n<div>${this.adds}</div><br/>\\n`;\n }\n log += `<br/><hr/>\\n<b>Total = ${total}</b></div>`;\n return log;\n }", "toString() {\n // map to array of [k,v] arrays\n let entries = [...this.letterCounts];\n\n // sorting array: first by count and then alphabetically\n entries.sort((a, b) => {\n if (a[1] === b[1]) {\n return a[0] < b[0] ? -1 : 1;\n } else {\n return b[1] - a[1];\n }\n });\n\n // converting counts to %\n for (let entry of entries) {\n entry[1] = entry[1] / this.totalLetters * 100;\n }\n\n // disregard an entry if it is less than 1%\n entries = entries.filter(entry => entry[1] >= 1);\n\n // converting each entry to the line of text\n let lines = entries.map(\n ([l, n]) => `${l}: ${'#'.repeat(Math.round(n))} ${n.toFixed(2)}`\n );\n\n // concatenate lines, separated with newline character\n return lines.join('\\n');\n }", "FormatText(d) {\n let count = 0;\n while (Math.abs(d) >= 1000) {\n d /= 1000;\n count++;\n }\n while (Math.abs(d) < 1 && d !== 0) {\n d *= 1000;\n count--;\n }\n const f = d3.format('.2f');\n let suffix;\n switch (count) {\n case -1:\n suffix = 'm';\n break;\n case -2:\n suffix = 'u';\n break;\n case -3:\n suffix = 'p';\n break;\n case 1:\n suffix = 'K';\n break;\n case 2:\n suffix = 'M';\n break;\n case 3:\n suffix = 'G';\n break;\n default:\n suffix = '';\n }\n let formattedText = f(d) + suffix + ' ';\n\n const info = this.infoService.getSensor();\n if (info !== undefined && info.units !== null) {\n if (info.units === '$') {\n formattedText = '$' + formattedText;\n } else {\n formattedText = formattedText + info.units;\n }\n }\n return formattedText;\n }", "function inline_roll(roll_text) {\n\n //console.log(\"roll_text:\" + roll_text);\n var result = \"\";\n\n // identify roll type\n roll_type = roll_text.match(inline_roll_match);\n roll_description = roll_text.substring(0, roll_type.index).trim();\n roll_text_without = roll_text.replace(roll_type,\"\");\n roll_type = roll_type[0].replace(\":\",\"\").replace(\" \",\"\").replace(\")\",\"\").replace(\"(\",\"\").replace(\"d\",\"\").replace(\"D\",\"\");\n\n // attempt to pull integer out of it, if not, send back source string\n try {\n roll_type = parseInt(roll_type);\n } catch(e) {\n return roll_text;\n }\n\n // roll a random 1 - roll_type\n var rand = Math.ceil(Math.random() * roll_type);\n\n // find that number with a period afterwards, capture next non-whitespace character through until next decimal number detected.\n roll_text_without = roll_text_without.replace(rand,\"<*>\");\n\n // regex match for indicator string <*> to the next decimal, caputring\n roll_text_without = roll_text_without.match(indicator_match);\n result = roll_text_without[1].replace(/^\\s+/, '').replace(/\\s+$/, '').replace(/[;,.]$/, '');\n\n // return display in a clear format\n return \"(d\" + roll_type + \") \" + roll_description + \": \" + result;\n}", "function displayDiceByColor(data) {\n let dice = JSON.parse(data);\n\n //hiding the section with all dice\n display.classList.remove('hidden');\n //showing the section with dice sorted by color\n allDice.classList.add('hidden');\n\n //inserting dice data\n display.innerHTML = `<h2>${dice[0].color}</h2>`;\n for (let i = 0; i < dice.length; i++) {\n display.innerHTML += `<article class=\"product\">\n <a href=\"./product-detail?id=${dice[i].id}\"><img src=\"./Views${dice[i].photo}\" alt=\"${dice[i].name}\"></a> \n <h3>${dice[i].name}</h3><span>${dice[i].price} €</span></article>`;\n }\n\n }", "function drawBarsAround(string){ \n return \"\\u2502\"+string+\"\\u2502\";\n}", "function inline_roll(roll_text) {\n\n var result = \"\";\n\n // identify roll type\n roll_type = roll_text.match(inline_roll_match);\n roll_description = roll_text.substring(0, roll_type.index).trim();\n roll_text_without = roll_text.replace(roll_type,\"\");\n roll_type = roll_type[0].replace(\":\",\"\").replace(\" \",\"\").replace(\")\",\"\").replace(\"(\",\"\").replace(\"d\",\"\").replace(\"D\",\"\");\n\n // attempt to pull integer out of it, if not, send back source string\n try {\n roll_type = parseInt(roll_type);\n } catch(e) {\n return roll_text;\n }\n\n // roll a random 1 - roll_type\n var rand = Math.ceil(Math.random() * roll_type);\n\n // find that number with a period afterwards, capture next non-whitespace character through until next decimal number detected.\n roll_text_without = roll_text_without.replace(rand,\"<*>\");\n\n // regex match for indicator string <*> to the next decimal, capturing\n roll_text_without = roll_text_without.match(indicator_match);\n result = roll_text_without[1].replace(/^\\s+/, '').replace(/\\s+$/, '').replace(/[;,.]$/, '');\n\n // return display in a clear format\n return \"(d\" + roll_type + \") \" + roll_description + \": \" + result;\n}", "function Dices() {\n let diceRoll = [\" \", \" \"];\n let outCome = [0, 0];\n for (let roll = 0; roll < 2; roll++) {\n outCome[roll] = Math.floor((Math.random() * 6) + 1);\n switch (outCome[roll]) {\n case checkRange(outCome[roll], 1, 1):\n diceRoll[roll] = \"1\";\n one++;\n break;\n case checkRange(outCome[roll], 2, 2):\n diceRoll[roll] = \"2\";\n two++;\n break;\n case checkRange(outCome[roll], 3, 3):\n diceRoll[roll] = \"3\";\n three++;\n break;\n case checkRange(outCome[roll], 4, 4):\n diceRoll[roll] = \"4\";\n one++;\n four;\n case checkRange(outCome[roll], 5, 5):\n diceRoll[roll] = \"5\";\n five++;\n break;\n case checkRange(outCome[roll], 6, 6):\n diceRoll[roll] = \"6\";\n six++;\n break;\n }\n }\n return diceRoll;\n }", "function showEaten() {\n textSize(25);\n textAlign(CENTER, CENTER);\n textFont(\"monospace\");\n fill(253, 139, 255);\n text(`Eaten: ${eatenCounter}`, 500, 50);\n}", "format(value, options = {}) {\n //convert value into bigger units if available\n let steps = this.unitData.steps\n while (\n value >= this.scaleData.step &&\n steps + 1 < this.scaleData.prefixes.length\n ) {\n value /= this.scaleData.step\n steps += 1\n }\n const displayUnit = this.scaleData.prefixes[steps] + this.unitData.base\n\n //round value down like printf(\"%.2f\")\n value = Math.round(value * 100) / 100\n\n if (displayUnit == \"\") {\n return value.toString()\n } else {\n //if possible, join with narrow no-break space instead of regular space\n const space = options.ascii ? \" \" : \"\\u202F\"\n return value + space + displayUnit\n }\n }", "function buildString() {\n\t// fill thisRoll with zeros\n\tfor (var r = 0; r < numPlayers; r++) {\n\t\tthisRoll[r] = 0;\n\t}\n\t\n\t// stores the HTML string\n\tvar str = \"\";\n\t\n\t// keeps track of which team names have been used\n\tvar teamIndex = 0;\n\t\n\t// build the string piece by piece\n\tfor (var d = 0; d < dice_volume; d++) {\n\t\t// store the number at location d in the dice matrix\n\t\tvar thisSpace = diceMatrix[d];\n\t\t\n\t\t// add appropriate image (1-6 = dice) or empty space (0 = empty space)\n\t\tstr += \"<div id='space\" + d + \"' style='height: 90px; width: 65px; float: left;'>\" + dice[thisSpace];\n\t\t\n\t\t// if there is a die in this space..\n\t\tif (thisSpace > 0) {\n\t\t\t// if there was previously a tie..\n\t\t\tif (winners.length > 0) {\n\t\t\t\t// assign a winning team name\n\t\t\t\tstr += \"<br><center>\" + teams[winners[teamIndex]] + \"</center></div>\";\n\t\t\t\t\n\t\t\t\t// store die number in array\n\t\t\t\tthisRoll[winners[teamIndex]] = thisSpace;\n\t\t\t} else if (first_roll == true) { // otherwise (and it's still the first roll)..\n\t\t\t\t// assign next team name\n\t\t\t\tstr += \"<br><center>\" + teams[teamIndex] + \"</center></div>\";\n\t\t\t\t\n\t\t\t\t// store die number in array\n\t\t\t\tthisRoll[teamIndex] = thisSpace;\n\t\t\t}\n\t\t\t\n\t\t\t// increment index\n\t\t\tteamIndex++;\n\t\t} else { // otherwise..\n\t\t\t// finish the string without a team name\n\t\t\tstr += \"</div>\";\n\t\t}\n\t}\n\t\n\t// reset winners\n\twinners = [];\n\t\n\t//populate dice area\n\t$(\"#dice_area\").html(str);\n}", "function happinessIcon(happiness) {\n if (happiness >= 1 && happiness <= 8) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #002400'><b> Near perfect</b></span></p></li>\";\n } else if (happiness > 8 && happiness <= 20) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #006d00'><b> Extremely good</b></span></p></li>\";\n } else if (happiness > 20 && happiness <= 36) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color:#00b600 '><b> Very good</b></span></p></li>\";\n } else if (happiness > 36 && happiness <= 48) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #24ff24'><b> Good</b></span></p></li>\";\n } else if (happiness > 48 && happiness <= 61) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #6dff6d'><b> Quite well</b></span></p></li>\";\n } else if (happiness > 61 && happiness <= 74) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color:#b6ffb6 '><b> Ok</b></span></p></li>\";\n } else if (happiness > 74 && happiness <= 87) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #ffb6b6'><b> Not so well</b></span></p></li>\";\n } else if (happiness > 87 && happiness <= 92) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #ff6d6d'><b> Kind of bad</b></span></p></li>\";\n } else if (happiness > 92 && happiness <= 107) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #ff2424'><b> Bad</b></span></p></li>\";\n } else if (happiness > 107 && happiness <= 118) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #b60000'><b> Very bad</b></span></p></li>\";\n } else if (happiness > 118 && happiness <= 131) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #6d0000'><b> Extremely bad</b></span></p></li>\";\n } else if (happiness > 131 && happiness <= 143) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #240000'><b> Super bad</b></span></p></li>\";\n } else if (happiness > 143 && happiness <= 156) {\n happiness = \"<li><p>World Happiness Index(2018): \" + numeral(happiness).format('0o') + \"<span style='color: #000000'><b> Worst of the worst</b></span></p></li>\";\n } else {\n happiness = \"<li><p>World Happiness Index(2018): Geen data beschikbaar</p></li>\";\n }\n return happiness;\n}", "function formatRound() {\n if(game.round < 10) {\n $('#round').text('0' + game.round);\n } else {\n $('#round').text(game.round);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current read index.
getReadIndex() { return this._readIndex; }
[ "getReadIndex() {\r\n return this._readIndex;\r\n }", "function getIndex() {\n return internal.index;\n }", "async getCurentIndex() {\n\n this.check()\n return await this.storage.loadIndex()\n }", "getIndex() {\n return this.indexBuffer;\n }", "function getIndex() {\n\treturn fileStorage.getIndex()\n}", "function returnIndex() {\n\t return index;\n\t }", "getIndex() {\n\t\t\tconst {overrides} = this.impl;\n\t\t\tif (overrides !== undefined) {\n\t\t\t\treturn overrides.getIndex(this);\n\t\t\t}\n\n\t\t\treturn this.currentToken.start;\n\t\t}", "function getCurrentPageIdx() {\n if (did_scroll && $(\"#read-view\").css('display') !== \"none\") {\n did_scroll = false;\n let height = $('.comic-page-container').outerHeight(true);\n let pos = $('#read-area').scrollTop();\n current_page_idx = Math.ceil(pos / height);\n }\n return current_page_idx;\n}", "function curIndex() {\n return sections.index(sections.filter('.current'));\n }", "function getActiveDocumentIndex(){\r\n var ref = new ActionReference();\r\n ref.putEnumerated( charIDToTypeID(\"Dcmn\"), charIDToTypeID(\"Ordn\"), charIDToTypeID(\"Trgt\") );\r\n return desc = executeActionGet(ref).getInteger(stringIDToTypeID('itemIndex'))-1;\r\n}", "function curIndex() {\r\n return sections.index(sections.filter('.current'));\r\n }", "function getActiveIndex() {\n return parseInt(config.active_index);\n }", "get index() {\n\t\treturn parseInt(this.getAttribute('index'));\n\t}", "function getCurrentIndex() {\n return Math.floor(freq(1, 1) * STATE.participants.length);\n}", "function getActiveIndex() {\n return parseInt(_config2.default.active_index);\n }", "async getDefaultIndex() {\n const { log } = this;\n const doc = await this._read();\n const defaultIndex = get(doc, ['_source', 'defaultIndex']);\n log.verbose('uiSettings.defaultIndex: %j', defaultIndex);\n return defaultIndex;\n }", "async getOpenLedgerSequence() {\n const getFeeResponse = await this.getFee();\n return getFeeResponse.getLedgerCurrentIndex();\n }", "get IdxOffset() { return this.native.IdxOffset; }", "read() {\n const indexFilePath = Files.gitletPath('index');\n return Util.lines(fs.existsSync(indexFilePath) ? Files.read(indexFilePath) : '\\n')\n .reduce((idx, blobStr) => {\n const blobData = blobStr.split(/ /);\n idx[Index.key(blobData[0], blobData[1])] = blobData[2];\n return idx;\n }, {});\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes BS inputs for class "bsNum[dpm]", where dpm: 0 0 DP; 1 1 DP; 2m 2DP, nmin 999 999 999 999 999.99.
function bsIniInpNum(pUsedDpm, pParent) { $.each(pUsedDpm.split(","), function (idx, dpm) { var dp = parseInt(dpm.charAt(0)); var ndef = {decPl: dp, frmOnIni: true}; if (dpm.length > 1) { nmins = "-999999999999999"; if (dp > 0) { nmins = nmins + ".9"; for (i = 1; i < dp; i++) { nmins = nmins + "9"; } ndef.nmin = parseFloat(nmins); } else { ndef.nmin = parseInt(nmins); } } if (pParent == null) { $(".bsNum" + dpm).bsInpNum(ndef); } else { $("#" + pParent).find(".bsNum" + dpm).bsInpNum(ndef); } }); }
[ "function initializeNumber(){\n pNmbrArr.push(phoneNmbr.slice(0,1) + \"32\");\n pNmbrArr.push(phoneNmbr.slice(1,4));\n pNmbrArr.push(phoneNmbr.slice(4,6));\n pNmbrArr.push(phoneNmbr.slice(6,8));\n pNmbrArr.push(phoneNmbr.slice(8,10));\n }", "function init() {\n\tmainDigits.push(new digit(W / 2 - digitWidth - padding * 2, H / 2 - 25, 20, 5, 5));\n\tmainDigits.push(new digit(W / 2 - padding * 2, H / 2 - 25, 20, 5, 5));\n\tmainDigits.push(new digit(W / 2 + digitWidth, H / 2 - 25, 20, 5, 5));\n\tmainDigits.push(new digit(W / 2 + digitWidth * 2 + padding, H / 2 - 25, 20, 5, 5));\n\n\tbreakDigits.push(new digit(W / 2 - digitWidth - padding * 2, H / 2 + digitWidth, 5, 1, 5));\n\tbreakDigits.push(new digit(W / 2 - padding * 2, H / 2 + digitWidth, 5, 1, 5));\n\tbreakDigits.push(new digit(W / 2 + digitWidth, H / 2 + digitWidth, 5, 1, 5));\n\tbreakDigits.push(new digit(W / 2 + digitWidth * 2 + padding, H / 2 + digitWidth, 5, 1, 5));\n\n\tinitTime();\n}", "function SegNumField(json_init, update_init) {\n\tGridField.call(this, json_init, update_init);\n\t// Set all segmented number attributes\n\tthis.field_type = 'int'; // has changed, before it was seg_num\n\tthis.grid_class = 'num_div';\n\t\n\tthis.type = 'int'; //has changed, before it was string\t\n\tthis.data_uri = \"numbers\";\n\tthis.cf_advanced = {flip_training_data : false, eigenvalues : 13}; // TODO: remove hardcoded value?\n\tthis.cf_map = {\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \n\t\t\t\t\t\"5\":\"5\", \"6\":\"6\", \"7\":\"7\", \"8\":\"8\", \"9\":\"9\"};\n\t\n\tif (json_init) {\n\t\tthis.border_offset = json_init.border_offset;\n\t\tthis.param = json_init.param;\n\t\tthis.dot_width = json_init.dot_width;\n\t\tthis.dot_height = json_init.dot_height;\n\t} else {\n\t\t// set the class of the grid elements\n\t\tthis.ele_class = 'num';\n\t\t\n\t\t// TODO: allow user to modify the borders of grid elements?\n\t\tthis.border_offset = 2;\n\n\t\t// number size\n\t\tthis.element_width = ($(\"#seg_num_size\").val() == 'small') ? SEG_NUM_SMALL[0] : \n\t\t\t\t\t\t\t($(\"#seg_num_size\").val() == 'medium') ? SEG_NUM_MEDIUM[0] : SEG_NUM_LARGE[0];\n\t\tthis.element_height = ($(\"#seg_num_size\").val() == 'small') ? SEG_NUM_SMALL[1] : \n\t\t\t\t\t\t\t($(\"#seg_num_size\").val() == 'medium') ? SEG_NUM_MEDIUM[1] : SEG_NUM_LARGE[1];\n\t\t\n\t\t// inner dot size\n\t\tthis.dot_width = ($(\"#dot_size\").val() == 'small') ? DOT_SMALL : \n\t\t\t\t\t\t\t($(\"#dot_size\").val() == 'medium') ? DOT_MEDIUM : DOT_LARGE;\n\t\tthis.dot_height = ($(\"#dot_size\").val() == 'small') ? DOT_SMALL : \n\t\t\t\t\t\t\t($(\"#dot_size\").val() == 'medium') ? DOT_MEDIUM : DOT_LARGE;\n\t\t\n\t\t// number of rows is hardcoded to 1\n\t\t// for number fields\n\t\tthis.num_rows = 1;\n\t\t\t\t\t\t\t\n\t\tthis.param = this.num_rows * this.num_cols;\n\t}\n}", "constructor() {\n this.inputWeights = [];\n this.bias = [];\n }", "function FormNumField(json_init, update_init) {\n\tFormField.call(this, json_init, update_init);\n\t/* Set all segmented number attributes. */\n\tthis.field_type = 'form_num';\n\t\n\t// set the grid class\n\tthis.grid_class = 'num_div';\n\t\n\t// TODO: find out what these values should actually be\n\tthis.type = 'string';\t\t\n\tthis.data_uri = \"numbers\";\n\tthis.cf_advanced = {flip_training_data : false, eigenvalues : 13}; // TODO: remove hardcoded value?\n\tthis.cf_map = {\"0\":\"0\", \"1\":\"1\", \"2\":\"2\", \"3\":\"3\", \"4\":\"4\", \n\t\t\t\t\t\"5\":\"5\", \"6\":\"6\", \"7\":\"7\", \"8\":\"8\", \"9\":\"9\"};\n\t\n\tif (!json_init) {\n\t\t// set the class of the grid elements\n\t\tthis.ele_class = 'num';\n\t\t\n\t\t// TODO: allow user to modify the borders of grid elements?\n\t\tthis.border_offset = 2;\n\n\t\t// number size\n\t\tthis.element_width = ($(\"#form_num_size\").val() == 'small') ? SEG_NUM_SMALL[0] : \n\t\t\t\t\t\t\t($(\"#form_num_size\").val() == 'medium') ? SEG_NUM_MEDIUM[0] : SEG_NUM_LARGE[0];\n\t\tthis.element_height = ($(\"#form_num_size\").val() == 'small') ? SEG_NUM_SMALL[1] : \n\t\t\t\t\t\t\t($(\"#form_num_size\").val() == 'medium') ? SEG_NUM_MEDIUM[1] : SEG_NUM_LARGE[1];\n\t\t\n\t\t// inner dot size\n\t\tthis.dot_width = ($(\"#form_num_dot_size\").val() == 'small') ? DOT_SMALL : \n\t\t\t\t\t\t\t($(\"#form_num_dot_size\").val() == 'medium') ? DOT_MEDIUM : DOT_LARGE;\n\t\tthis.dot_height = ($(\"#form_num_dot_size\").val() == 'small') ? DOT_SMALL : \n\t\t\t\t\t\t\t($(\"#form_num_dot_size\").val() == 'medium') ? DOT_MEDIUM : DOT_LARGE;\n\t\t\n\t\t// the horizontal spacing between the edges of numbers\n\t\tthis.num_dx = parseInt($(\"#form_num_dx\").val());\n\t\t\n\t\t// the horizontal spacing between the edges of groups\n\t\tthis.group_dx = parseInt($(\"#form_num_group_dx\").val()) + 8;\n\t\t\n\t\t/*\tEach index corresponds to each group (index = 0 --> group 1, index = 1 --> group 1, etc.).\n\t\t\tThe value at each index corresponds to the number of segmented numbers in that group.\n\t\t\t(group_sizes[0] = 3 --> size of group 1 is 3, etc.)\n\t\t*/\n\t\tvar group_sizes = [];\n\t\t\n\t\t$(\".num_groups\").each(function() {\n\t\t\tgroup_sizes.push(parseInt($(this).val()));\n\t\t});\n\t\t\n\t\t// stores the size of each respective group of numbers\n\t\tthis.group_sizes = group_sizes;\n\t\t\n\t\tthis.delim_type = $(\"#delim_type\").val();\n\t\t\t\t\n\t\t// number of columns\n\t\tthis.num_cols = $(\"#num_col_form_num\").val();\n\t}\n}", "init() {\n // Initialize weights matrix and bias vector\n this.w = NN_vec2D.randomNormal(this.noOutputs, this.noInputs);\n this.b = NN_vec1D.zeros(this.noOutputs);\n }", "setupInitialValues() {\n this.__xSpacingInput.value = \"1.0\";\n this.__ySpacingInput.value = \"1.0\";\n\n this.__xDimInput.value = 5;\n this.__yDimInput.value = 1;\n }", "function pbditinit() {\n\t$('#' + latest_audit).val('');\n\t$('#' + annualized_vat).val('');\n\t$(\"#\" + pat).val(\"\");\n\t$(\"#\" + remuneration).val(\"\");\n\t$(\"#\" + interest_on_capital).val(\"\");\n\t$(\"#\" + tax).val(\"\");\n\t$(\"#\" + pbt).text('');\n\t$(\"#\" + pbdit).text('');\n\t$(\"#\" + pbdit_margin_calc).text('');\n\t$(\"#\" + depreciation).val(\"\");\n\t$(\"#\" + interest).val(\"\");\n\t$(\"#\" + pbdit_margin_input).text('');\n\tdata[latest_audit] = \"\";\n\tdata[annualized_vat] = \"\";\n\tdata[pat] = '';\n\tdata[remuneration] = '';\n\tdata[interest_on_capital] = '';\n\tdata[tax] = '';\n\tdata[pbt] = 0.00;\n\tdata[depreciation] = '';\n\tdata[interest] = '';\n\tdata[pbdit] = 0.00;\n\tdata[pbdit_margin_calc] = 0.00;\n\tdata[pbdit_margin_input] = 0.00;\n\tif(current != 1 && current != 5)\n\t\txl2g.evalAllTargets();\n}", "init(){\n\n // create a list of values\n if( this.def.values instanceof Array ) {\n this.values = this.def.values;\n } else {\n\n this.values = [];\n\n if( this.role == Constants.ROLE.DIM ) {\n\n // dimensions are subsequent\n let val = 0;\n while( this.values.length < this.def.values ) {\n this.values.push( val++ );\n }\n\n } else {\n\n // measurements are chosen at random\n\n // first value is random\n let val = +this.getRandomValue();\n this.values.push( val );\n\n // fill up the remainder\n while( this.values.length < this.def.values ) {\n const change = Math.round( (2 * Math.random() - 1) * this.def.change );\n val = Math.max( this.def.min, Math.min( this.def.max, val + change ) );\n this.values.push( val );\n }\n\n }\n\n }\n\n // map to ArbNumber object\n this.values = this.values.map( v => ArbNumber( v ) );\n\n // reset the remaining variables\n this.reset();\n\n }", "init() {\n // Initialize weights matrix and bias vector\n this.w = NN_vec2D.randomNormal(this.noCategories, this.noInputs);\n this.b = NN_vec1D.zeros(this.noCategories);\n }", "function NBIModel()\n{\n // force parameters\n this.params = null;\n this.m1=0;\n this.m2=0;\n this.m3=0;\n this.mm1rs2;\n this.mm2rs2;\n this. mm3rs2;\n this.eps1;\n this.eps2;\n\n\n this.pn = 0;\n this.pn1 = 0;\n this.pn2 = 0;\n\n\n // temporary storage arrays dependent on n\n this.r22;\n this.r21;\n this.r1;\n this.r2;\n this.rn;\n this.a1;\n this.a2;\n this.a3;\n this.ival11 = null;\n this.ival22 = null;\n this.ivaln = null;\n this.df_force11 = null;\n this.df_force22 = null;\n this.df_forcen = null;\n this.c3n = null;\n\n // temporary storage independent of n\n this.xn = new Array(6);\n this.xp = 0.0;\n this.yp = 0.0;\n this.zp = 0.0;\n this.vxp = 0.0;\n this.vyp = 0.0;\n this.vzp = 0.0;\n\n\n /**\n * Sets the simulation parameters to this model.\n */\n this.setParameters = function(p)\n {\n this.params = p;\n\n if(this.params != null)\n {\n this.m1 = this.params.mass1;\n this.m2 = this.params.mass2;\n this.m3 = this.params.mass2;\n this.mm1rs2 = -this.m1*rs_internal2;\n this.mm2rs2 = -this.m2*rs_internal2;\n this.mm3rs2 = -this.m3*rs_internal2;\n this.eps1 = this.params.epsilon1 * this.params.epsilon1;\n this.eps2 = this.params.epsilon2 * this.params.epsilon2;\n this.pn = this.params.n;\n this.pn1 = this.params.n1;\n this.pn2 = this.params.n2;\n this.rrout1 = this.params.rout1;\n this.rrout2 = this.params.rout2;\n //if(rad != null)\n //{\n //initDistribution();\n //}\n }\n\n }\n\n\n /** \n * Initialize temporary storage.\n */\n this.initVars = function(n)\n {\n this.r22 = new Array(n);\n this.r21 = new Array(n);\n this.r1 = new Array(n);\n this.r2 = new Array(n);\n this.rn = new Array(n);\n this.a1 = new Array(n);\n this.a2 = new Array(n);\n this.a3 = new Array(n);\n \n this.ival11 = new Array(n);\n this.ival22 = new Array(n);\n this.ivaln = new Array(n);\n\n this.df_force11 = new Array(n);\n this.df_force22 = new Array(n);\n this.df_forcen = new Array(n);\n\n this.c3n = new Array(n);\n for(var i=0; i<n; i++)\n {\n this.r22[i]=0;\n this.r21[i]=0;\n this.r1[i]=0;\n this.r2[i]=0;\n this.rn[i]=0;\n this.a1[i]=0;\n this.a2[i]=0;\n this.a3[i]=0;\n \n this.ival11[i]=0;\n this.ival22[i]=0;\n this.ivaln[i]=0;\n\n this.df_force11[i]=0;\n this.df_force22[i]=0;\n this.df_forcen[i]=0;\n\n this.c3n[i]=0;\n }\n this.initDistribution();\n }\n\n /** \n * Cleanup temporary storage.\n */\n this.deallocateVars = function()\n {\n this.r22 = null;\n this.r21 = null;\n this.r1 = null;\n this.r2 = null;\n this.rn = null;\n this.a1 = null;\n this.a2 = null;\n this.a3 = null;\n \n this.ival11 = null;\n this.ival22 = null;\n this.ivaln = null;\n\n this.df_force11 = null;\n this.df_force22 = null;\n this.df_forcen = null;\n\n this.c3n = null;\n }\n\n /**\n * Build an n-body halo/disk/bulge\n */\n this.initDistribution = function()\n {\n if(this.isInit) return;\n this.isInit = true;\n\n var rmax;\n var mold, dmold, mtotal, mtot;\n var rscale;\n var dx, x;\n var alphahalo, qhalo, gammahalo, mhalo, rchalo, rhalo, epsilon_halo;\n var zdisk, zdiskmass, hdisk, zdiskmax;\n var hbulge, mbulge;\n var rho_tmp;\n var G, factor;\n var r, m, pi;\n var p1, rd, rho_local;\n var p, rr, dr, rh, dp, mnew, dm;\n var acc_merge, rad_merge, acc;\n var xmax;\n\n var j, nmax, k, nmerge, ntotal, jj;\n\n rad = new Array(nnn);\n rho_halo = new Array(nnn);\n mass_halo = new Array(nnn);\n rho_disk = new Array(nnn);\n mass_disk = new Array(nnn);\n rho_bulge = new Array(nnn);\n mass_bulge = new Array(nnn);\n rho_total = new Array(nnn);\n mass_total = new Array(nnn);\n masses = new Array(nnn);\n radius = new Array(nnn);\n density = new Array(nnn);\n vr2 = new Array(nnn);\n vr = new Array(nnn);\n new_vr2 = new Array(nnn);\n new_vr = new Array(nnn);\n acceleration = new Array(nnn);\n acceleration_particle = new Array(nnn);\n new_mass = new Array(nnn);\n new_rho = new Array(nnn);\n phi = new Array(nnn);\n\n // set the constant for dynamical friction\n lnl = 0.00;\n \n // set ln(Lambda) to match value used in Galaxy Zoo: Mergers \n lnl = 0.001;\n\n // set up the parameters for the halo\n mhalo = 5.8;\n rhalo = 10.0;\n rchalo = 10.0;\n gammahalo = 1.0;\n epsilon_halo = 0.4;\n pi = Math.PI;\n\n // derive additional constants\n qhalo = gammahalo / rchalo;\n alphahalo = 1.0 / ( 1.0 - sqrtpi * qhalo * Math.exp(qhalo*qhalo) * (1.0 - this.erf(qhalo)) );\n\n // set the integration limits and zero integration constants\n rmax = 20;\n nmax = 2000;\n dr = rmax / nmax;\n mold = 0;\n\n rscale = 5;\n ntotal = nnn;\n\n // set the limits for integration, and zero integration constants\n k = nmax / 2;\n dx = 1.0 / k;\n x = 0.0;\n dmold = 0.0;\n mtot = 0.0;\n m = 0.0;\n G = 1;\n\n /////\n // set the fundamental disk parameters\n zdisk = 0.2;\n zdiskmax = 3.5;\n hdisk = 1.0;\n\n\n /////\n // set the fundamental bulge parameters\n hbulge = 0.2;\n mbulge = 0.3333;\n\n\n ///////////////////////////////////////////////3\n ///// set up the radius array\n for(j = 0; j<nmax; j++)\n {\n x = x + dx;\n rad[j]= x * rchalo;\n }\n\n ///////////////////////////////////////////////3\n /////\n\n dr = rad[1] - rad[0];\n dx = dr / rchalo;\n\n for(j =0; j<nmax; j++)\n {\n // set the position\n r = rad[j];\n x = r / rchalo;\n\n // calculate the local rho based\n rho_tmp = alphahalo / (2*sqrtpi*sqrtpi*sqrtpi ) * (Math.exp(-x*x) / (x*x + qhalo*qhalo));\n\n // renormalize for the new halo size\n rho_tmp = rho_tmp / ( rchalo * rchalo * rchalo);\n\n // calculate mass in local shell, and update total mass\n dm = rho_tmp * 4 * pi * r * r *dr;\n mtot = mtot + dm;\n\n // store values in an array\n rho_halo[j] = rho_tmp * mhalo;\n mass_halo[j] = mtot * mhalo;\n }\n\n /////\n // now calculate the potential\n for(j = 0; j<nmax; j++)\n {\n r = rad[j];\n m = mass_halo[j];\n p1 = -G * m / r;\n phi[j] = p1;\n }\n\n\n ///////////////////////////////////////////////3\n // disk model\n\n /////\n // loop over the distribution\n\n for(j=0; j<nmax; j++)\n {\n // set the radius\n rd = rad[j];\n\n // find the local density in the disk\n rho_local = Math.exp(-rd/hdisk)/ (8*pi*hdisk*hdisk);\n rho_disk[j] = rho_local;\n\n // find the mass in the spherical shell\n mnew = 4 * pi * rho_local * rd *rd * dr;\n\n mass_disk[j] = mnew + mold;\n mold = mass_disk[j];\n }\n\n ///////////////////////////////////////////////3\n // bulge model\n\n /////\n // loop over the distribution\n mold = 0.0;\n for(j=0; j<nmax; j++)\n {\n // set the radius\n rd = rad[j];\n\n // find the local density in the disk\n rho_local = Math.exp(-rd*rd/(hbulge*hbulge));\n rho_bulge[j] = rho_local;\n\n // find the mass in the spherical shell\n mnew = 4 * pi * rho_local * rd *rd * dr;\n\n mass_bulge[j] = mnew + mold;\n mold = mass_bulge[j];\n }\n\n // renormalize distribution\n factor = mbulge / mass_bulge[nmax-1];\n for(j=0; j<nmax; j++)\n {\n mass_bulge[j] = mass_bulge[j] * factor;\n rho_bulge[j] = rho_bulge[j] * factor;\n }\n\n\n dr = rad[1] - rad[0];\n\n //////////////////////////////////////////////////\n j = 0;\n mass_total[j]= (mass_halo[j] + mass_disk[j] + mass_bulge[j]);\n r = rad[j];\n rho_total[j] = mass_total[j] / (4.0/3.0 * pi * r * r * r);\n dr = rad[1] - rad[0];\n\n for(j = 1; j<nmax; j++)\n {\n r = rad[j];\n mass_total[j]= (mass_halo[j] + mass_disk[j] + mass_bulge[j]);\n\n dm = mass_total[j] - mass_total[j-1];\n rho_total[j] = dm / (4 * pi * r * r * dr);\n }\n\n //////////////////////////////////////////////\n // find the velocity dispersion v_r**2\n\n masses = mass_total;\n radius = rad;\n density = rho_total;\n\n\n for(j=0; j<nmax; j++)\n {\n p = 0.0;\n rr = radius[j];\n dr = radius[nmax-1] / nmax;\n\n for(jj = j; jj<nmax; jj++)\n {\n m = masses[jj];\n rh = density[jj];\n rr = rr + dr;\n\n dp = rh * G * m / (rr*rr) * dr;\n p = p + dp;\n }\n\n vr2[j] = 1/density[j] * p;\n vr[j] = Math.sqrt(vr2[j]);\n }\n\n //////////////////////////////////////////////\n // find the velocity dispersion v_r**2\n masses = mass_total;\n radius = rad;\n density = rho_total;\n\n for(j=0; j<nmax; j++)\n {\n p = 0.0;\n rr = radius[j];\n dr = radius[nmax-1] / nmax;\n for(jj = j; jj<nmax; jj++)\n {\n m = masses[jj];\n rh = density[jj];\n rr = rr + dr;\n dp = rh * G * m / (rr*rr) * dr;\n p = p + dp;\n }\n\n vr2[j] = 1/density[j] * p;\n vr[j] = Math.sqrt(vr2[j]);\n }\n\n //////////////////////////////////////////////\n // find the accelerations felt by the particles and center of mass\n masses = mass_total;\n radius = rad;\n density = rho_total;\n\n for(j=0; j<nmax; j++)\n {\n rr = radius[j];\n m = masses[j];\n acceleration[j] = G * m / (rr*rr);\n acceleration_particle[j] = acceleration[j];\n }\n\n //acceleration_particle = acceleration;\n nmerge = 50;\n acc_merge = acceleration[nmerge];\n rad_merge = rad[nmerge];\n\n for(j=0; j<nmerge; j++)\n {\n rr = radius[j];\n m = masses[j];\n\n // smoothed acceleration\n acc = G * m / (rr*rr + .1* (rad_merge -rr));\n acceleration_particle[j] = acc;\n }\n\n //////////////////////////////////////////////\n // rederive the masses from the new particle acceleration\n radius = rad;\n dr = rad[1] - rad[0];\n\n // find the accelerations felt by the particles and center of mass\n radius = rad;\n\n for(j = 0; j<nmax; j++)\n {\n rr = radius[j];\n new_mass[j] = rr*rr * acceleration_particle[j] / G;\n new_rho[j] = new_mass[j] / (4 * pi * rr * rr * dr);\n }\n\n\n //////////////////////////////////////////////\n // find the velocity dispersion v_r**2 using the new density and masses\n\n masses = new_mass;\n radius = rad;\n density = new_rho;\n\n\n for(j=0; j<nmax; j++)\n {\n p = 0.0;\n rr = radius[j];\n dr = radius[nmax-1] / nmax;\n\n for(jj=j; jj<nmax; jj++)\n {\n m = masses[jj];\n rh = density[jj];\n rr = rr + dr;\n dp = rh * G * m / (rr*rr) * dr;\n p = p + dp;\n }\n\n new_vr2[j] = 1/density[j] * p;\n new_vr[j] = Math.sqrt(new_vr2[j]);\n }\n\n\n //////////////////////////////////////////////\n // extend the values to large rmax\n for(j=nmax; j<ntotal; j++)\n {\n mass_total[j] = mass_total[nmax-1];\n mass_halo[j] = mass_halo[nmax-1];\n mass_disk[j] = mass_disk[nmax-1];\n mass_bulge[j] = mass_bulge[nmax-1];\n new_mass[j] = new_mass[nmax-1];\n\n rho_total[j] = 0.0;\n new_rho[j] = 0.0;\n\n vr[j] = 1e-6;\n vr2[j] = 1e-6;\n new_vr[j] = 1e-6;\n new_vr2[j] = 1e-6;\n\n m = mass_total[nmax-1];\n rr = rad[nmax-1] + dr*(j - nmax);\n rad[j] = rr;\n acc = G * m / (rr*rr);\n acceleration_particle[j] = acc;\n acceleration[j] = acc;\n }\n\n //////////////////////////////////////////////\n // normalize to the unit mass\n\n for(j=0; j<ntotal; j++)\n {\n mass_total[j] = mass_total[j] / 7.13333;\n mass_halo[j] = mass_halo[j] / 7.13333;\n mass_disk[j] = mass_disk[j] / 7.13333;\n mass_bulge[j] = mass_bulge[j] / 7.13333;\n new_mass[j] = new_mass[j] / 7.13333;\n\n rho_total[j] = rho_total[j] / 7.13333;\n new_rho[j] = new_rho[j] / 7.13333;\n\n vr[j] = vr[j] / 7.13333;\n vr2[j] = vr2[j] / 7.13333;\n new_vr[j] = new_vr[j] / 7.13333;\n new_vr2[j] = new_vr2[j] / 7.13333;\n\n rad[j] = rad[j];\n\n acceleration_particle[j] = acceleration_particle[j] / 7.13333;\n acceleration[j] = acceleration[j] / 7.13333;\n }\n\n pscale = 1.0;\n\n tmpdfind = pscale*rs_internal/rmax_scale*nnn;\n } // end initDistribution\n\n /**\n * Determine the index to use for interpolating the force.\n */\n this.dfIndex = function( rin, rs)\n {\n var ival = 0;\n //double tmp = rin*pscale*rs_internal/rmax_scale;\n var tmp = rin*tmpdfind;\n //tmp = tmp*nnn + 1;\n ival = Math.floor(tmp);\n ival = Math.min(ival, nnn-1);\n //ival = min(int( (rin * pscale * rs_internal/ rmax_scale) * nnn + 1), nnn)\n/*\n ival--; // java is 0-based\n if(ival < 0)\n {\n ival = 0;\n }\n*/\n\n return ival;\n }\n \n /**\n * Computes the error function. Based on code from Numerical Recipies and the following URL: \n * http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html\n * fractional error in math formula less than 1.2 * 10 ^ -7.\n * although subject to catastrophic cancellation when z in very close to 0\n * from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2\n */\n this.erf = function(z) \n {\n var t = 1.0 / (1.0 + 0.5 * Math.abs(z));\n\n // use Horner's method\n var ans = 1 - t * Math.exp( -z*z - 1.26551223 +\n t * ( 1.00002368 +\n t * ( 0.37409196 + \n t * ( 0.09678418 + \n t * (-0.18628806 + \n t * ( 0.27886807 + \n t * (-1.13520398 + \n t * ( 1.48851587 + \n t * (-0.82215223 + \n t * ( 0.17087277))))))))));\n if (z >= 0) return ans;\n else return -ans;\n }\n\n /**\n * Compute the circular velocity for a particle at a distance r from the specified mass.\n * The rout scale of the disk and softening length, eps, are provided.\n */\n this.circularVelocity = function(mass, r, rout, eps)\n {\n var ftotal = 0;\n\n var ival = this.dfIndex(r, rout);\n\n ftotal = mass * acceleration_particle[ival] * rs_internal * rs_internal;\n\n var v = Math.sqrt(ftotal*r);\n\n return v;\n }\n\n /**\n * For the given particle positions and velocities, calculate the accelerations.\n */\n this.diffeq = function(x,f)\n {\n//Prof.startCall(\"diffeq\");\n var tmp1, tmp2, tmp3, tmp4, tmp5;\n tmp1=tmp2=tmp3=0;\n var n = x.length;\n var i = 0;\n\n var df_sigma = 0;\n var df_rho = 0;\n var c1 = 0;\n var c2 = 0;\n var xvalue = 0;\n var v1 = 0;\n var v21 = 0;\n\n for(i=0; i<6; i++)\n {\n this.xn[i] = x[n-1][i];\n }\n\n xp = this.xn[0]; yp = this.xn[1]; zp = this.xn[2];\n vxp = this.xn[3]; vyp = this.xn[4]; vzp = this.xn[5];\n\n tmp4 = xp*xp+yp*yp+zp*zp;\n\n // distance between the two galaxies - the tidal force\n tmp5 = Math.sqrt(tmp4);\n\nvar iv1 = 0;\nvar iv2 = 0;\nvar ivn = 0;\nvar df1 = 0;\nvar df2 = 0;\nvar dfn = 0;\nvar tx = null;\nvar r22d = 0;\nvar r21d = 0;\nvar aa1 = 0;\nvar aa2 = 0;\nvar aa3 = 0;\n\n\n\n\n // get the forces, sigma and rho, and rescale them\n //ivaln[0] = dfIndex(rn[0],rrout2);\n ivn = this.dfIndex(tmp5,rrout2);\n\n df_sigma = new_vr2[ivn] * rs_internal2;\n df_rho = new_rho[ivn] * rs_internal3;\n\n // df\n v21 = vxp*vxp + vyp*vyp + vzp*vzp;\n v1 = Math.sqrt(v21);\n\n xvalue = v1 / df_sigma;\n c1 = this.erf(xvalue) - 2.0 * xvalue / sqrtpi * Math.exp(-xvalue*xvalue);\n\n // df formula with G=1\n c2 = 4.0 * Math.PI * this.m2 * lnl / v21;\n for(i=0; i<n; i++)\n {\n this.c3n[i] = 0;\n }\n\n\n for(i=this.pn1; i<n; i++)\n {\n this.c3n[i] = c1 * c2 * df_rho;\n }\n\nvar tf = null;\nvar tv1 = 1.0/v1;\nvar c3tv = 0;\nvar dv = 0;\n ivn = this.dfIndex(tmp5, rrout2);\n\n for(i=0; i<n; i++)\n {\n // distance between the companion and the particle\n tx = x[i];\n\n //tmp1 = (x[i][0]-xp);\n //tmp2 = (x[i][1]-yp);\n //tmp3 = (x[i][2]-zp);\n tmp1 = (tx[0]-xp);\n tmp2 = (tx[1]-yp);\n tmp3 = (tx[2]-zp);\n //r22[i] = tmp1*tmp1 + tmp2*tmp2 + tmp3*tmp3;\n r22d = tmp1*tmp1 + tmp2*tmp2 + tmp3*tmp3;\n\n // distance between the main galaxy and the particle\n //tmp1 = x[i][0];\n //tmp2 = x[i][1];\n //tmp3 = x[i][2];\n tmp1 = tx[0];\n tmp2 = tx[1];\n tmp3 = tx[2];\n //r21[i] = tmp1*tmp1 + tmp2*tmp2 + tmp3*tmp3;\n r21d = tmp1*tmp1 + tmp2*tmp2 + tmp3*tmp3;\n\n //r2[i] = Math.sqrt(r22[i]);\n //r1[i] = Math.sqrt(r21[i]);\n //r2[i] = Math.sqrt(r22d);\n //r1[i] = Math.sqrt(r21d);\n //rn[i] = tmp5;\n\n r22d = Math.sqrt(r22d);\n r21d = Math.sqrt(r21d);\n //r2[i] = r22d;\n //r1[i] = r21d;\n //rn[i] = tmp5;\n\n\n //ival11[i] = dfIndex(r1[i], rrout1);\n //ival22[i] = dfIndex(r2[i], rrout2);\n //ivaln[i] = dfIndex(rn[i], rrout2);\n //iv1 = dfIndex(r1[i], rrout1);\n //iv2 = dfIndex(r2[i], rrout2);\n //ivn = dfIndex(rn[i], rrout2);\n //iv1 = dfIndex(r21d, rrout1);\n //iv2 = dfIndex(r22d, rrout2);\n //ivn = dfIndex(tmp5, rrout2);\n\n dv = r21d*tmpdfind;\n iv1 = Math.round(dv); if(iv1>nnm1)iv1=nnm1;\n dv = r22d*tmpdfind;\n iv2 = Math.round(dv); if(iv2>nnm1)iv2=nnm1;\n\n //df_force11[i] = acceleration_particle[ival11[i]] * rs_internal2;\n //df_force22[i] = acceleration_particle[ival22[i]] * rs_internal2;\n //df_forcen[i] = acceleration_particle[ivaln[i]] * rs_internal2;\n //df1 = acceleration_particle[iv1] * rs_internal2;\n //df2 = acceleration_particle[iv2] * rs_internal2;\n //dfn = acceleration_particle[ivn] * rs_internal2;\n\n //a1[i] = -m1 * df_force11[i];\n //a2[i] = -m2 * df_force22[i];\n //a3[i] = -m3 * df_forcen[i];\n //a1[i] = -m1 * df1;\n //a2[i] = -m2 * df2;\n //a3[i] = -m3 * dfn;\n //a1[i] = acceleration_particle[iv1]*mm1rs2;\n //a2[i] = acceleration_particle[iv2]*mm2rs2;\n //a3[i] = acceleration_particle[ivn]*mm3rs2;\n aa1 = acceleration_particle[iv1]*this.mm1rs2;\n aa2 = acceleration_particle[iv2]*this.mm2rs2;\n aa3 = acceleration_particle[ivn]*this.mm3rs2;\n\n //tmp1 = a1[i]/r1[i];\n //tmp2 = a2[i]/r2[i];\n //tmp3 = a3[i]/rn[i];\n tmp1 = aa1/r21d;\n tmp2 = aa2/r22d;\n tmp3 = aa3/tmp5;\n c3tv = this.c3n[i]*tv1;\n\n //f[i][0] = x[i][3];\n //f[i][1] = x[i][4];\n //f[i][2] = x[i][5];\n\n //f[i][3] = tmp1*x[i][0] + tmp2*(x[i][0]-xn[0]) + tmp3*xn[0] - c3n[i] * xn[3] / v1;\n //f[i][4] = tmp1*x[i][1] + tmp2*(x[i][1]-xn[1]) + tmp3*xn[1] - c3n[i] * xn[4] / v1;\n //f[i][5] = tmp1*x[i][2] + tmp2*(x[i][2]-xn[2]) + tmp3*xn[2] - c3n[i] * xn[5] / v1;\n\n tf = f[i];\n //tx = x[i];\n tf[0] = tx[3];\n tf[1] = tx[4];\n tf[2] = tx[5];\n\n tf[3] = tmp1*tx[0] + tmp2*(tx[0]-this.xn[0]) + tmp3*this.xn[0] - this.xn[3] * c3tv;\n tf[4] = tmp1*tx[1] + tmp2*(tx[1]-this.xn[1]) + tmp3*this.xn[1] - this.xn[4] * c3tv;\n tf[5] = tmp1*tx[2] + tmp2*(tx[2]-this.xn[2]) + tmp3*this.xn[2] - this.xn[5] * c3tv;\n }\n\n// redo acceleration for last particle\nr22d=1.0;\ntmp2 = aa2/r22d;\n tf[3] = tmp1*tx[0] + tmp2*(tx[0]-this.xn[0]) + tmp3*this.xn[0] - this.xn[3] * c3tv;\n tf[4] = tmp1*tx[1] + tmp2*(tx[1]-this.xn[1]) + tmp3*this.xn[1] - this.xn[4] * c3tv;\n tf[5] = tmp1*tx[2] + tmp2*(tx[2]-this.xn[2]) + tmp3*this.xn[2] - this.xn[5] * c3tv;\n\n\n//Prof.endCall(\"diffeq\");\n }\n\n /**\n * Calculate the acceleration felt by the secondary galaxy in orbit around the primary.\n */\n this.diffq1 = function(x,f)\n {\n var r21, r1, a1, a2, at;\n var c1, c2, c3, v21, v1, xvalue;\n\n var ival, ival2;\n var df_force1, df_force2;\n var df_sigma, df_rho;\n\n var i;\n var rr, rlocal, ivalue, dr, mmm, dm;\n\n r21 = x[0]*x[0] + x[1]*x[1] + x[2]*x[2];\n r1 = Math.sqrt(r21);\n\n // get the index for the calculations\n ival = this.dfIndex(r1, rrout1 );\n ival2 = this.dfIndex(r1, rrout2 );\n\n // get the forces, sigma and rho, and rescale them\n df_force1 = acceleration_particle[ival] * rs_internal * rs_internal;\n df_force2 = acceleration_particle[ival2]* rs_internal * rs_internal;\n\n df_sigma = new_vr2[ival] * rs_internal * rs_internal;\n df_rho = new_rho[ival] * ( rs_internal * rs_internal * rs_internal );\n\n // interpolated forces\n a1 = -this.m1 * df_force1;\n a2 = -this.m2 * df_force2;\n at = a1 + a2;\n\n // df\n v21 = x[3]*x[3] + x[4]*x[4] + x[5]*x[5];\n v1 = Math.sqrt(v21);\n\n xvalue = v1 / df_sigma;\n c1 = this.erf(xvalue) - 2.0 * xvalue / sqrtpi * Math.exp(-xvalue*xvalue);\n\n // df formula with G=1\n c2 = -4.0 * Math.PI * this.m2 * lnl / v21;\n c3 = c1 * c2 * df_rho;\n\n f[0] = x[3];\n f[1] = x[4];\n f[2] = x[5];\n\n f[3] = at * x[0]/r1 - c3 * x[3]/v1;\n f[4] = at * x[1]/r1 - c3 * x[4]/v1;\n f[5] = at * x[2]/r1 - c3 * x[5]/v1;\n }\n}", "function init(){\n var params = d3.select('#init_params').property('value');\n let p = params.split(\" \").map((val) => parseInt(val));\n trace = [];\n breaks = [];\n memo_table = {};\n log = {};\n send_to_debugger({'cmd': 'init', memsize:10000, params: p});\n isFinished = false;\n}", "function initBid() {\n Bid.Code = '';\n Bid.Date = '';\n Bid.TypeId = '';\n Bid.Type = '';\n Bid.PreparedById = '';\n Bid.PreparedByName = '';\n Bid.ParticularId = '';\n Bid.ParticularName = '';\n Bid.ProjectTypeId = '';\n Bid.ProjectTypeName = '';\n Bid.TotalArea = '';\n Bid.DirectCost = '';\n Bid.ExtendedCost = '';\n Bid.SellingCost = '';\n Bid.SubmissionDate = '';\n Bid.Duration = '';\n Bid.ClientId = '';\n Bid.ClientName = '';\n Bid.Remark = '';\n Bid.StatusId = '';\n Bid.StatusName = '';\n Bid.PrebidDatetimeConference = '';\n Bid.PrebidVenueConference = '';\n Bid.SiteDatetimeInspection = '';\n Bid.SiteVenueInspection = '';\n Bid.SubmissionCourier = '';\n Bid.SubmissionEmail = '';\n Bid.SubmissionHardcopy = '';\n Bid.ValidityOfBid = '';\n Bid.BidDocumentAmount = '';\n}", "function bottomDischargeCalculations(){\r\n\t//1. Assign 0 if input left blank\r\n\tvar assign_zero = [$bottomSpoutDiameter, $bottomSpoutLength];\r\n\t$.each(assign_zero, (index, $item) => {\r\n\t\tassignDefaultIfNull($item, 0);\r\n\t});\r\n\t\r\n\t//2. Unit MF\r\n\tmultiplyAccordingToUnit[$bottomSpoutDiameter, $bottomSpoutLength];\r\n}", "function staticBBSInit() {\r\n // Clear the picture when it starts\r\n for(var i = 0; i < gridSize; ++i) {\r\n for(var j = 0; j < gridSize; ++j) {\r\n colorConfiguration[i][j] = staticBBSBox;\r\n }\r\n }\r\n\r\n // Prepare for the simulation on circuit\r\n circuitLength = 4 * gridSize;\r\n staticBBSCarrier = 0;\r\n\r\n // Array Construction\r\n staticBBSCircuit = [];\r\n circuitFormerConfig = [];\r\n staticBBSCircuit.length = circuitLength;\r\n circuitFormerConfig.length = circuitLength;\r\n for(var i = 0; i < circuitLength; ++i){\r\n if(myRand() < paramLambda) {\r\n staticBBSCircuit[i] = staticBBSBall;\r\n }\r\n else {\r\n staticBBSCircuit[i] = staticBBSBox;\r\n }\r\n }\r\n\r\n // Run the simulation for one time to set circuitFormerConfig\r\n staticBBSSimulate();\r\n\r\n // Update of colorConfiguration should begin at i = 0 , j = 0\r\n staticBBSTargetI = 0;\r\n staticBBSTargetJ = 0;\r\n staticBBSTime = 0;\r\n}", "function buildNums(){\n let defVals = [2,4,9,10,25,100]\n let goalInit = 228\n for(let i=0; i<6; i++){\n inp = document.createElement('input')\n inp.type='number'\n $('#nums').append(inp)\n inp.classList.add(\"numinp\");\n // inp.classList.add(\"text-secondary\");\n if(i< defVals.length )\n inp.placeholder = defVals[i]\n\n }\n $(\"#goal\").val(goalInit)\n}", "init() {\n this.inputAdapters.forEach(value => value.init())\n }", "function initialize() {\r\n // Set boundaries based on the activation function\r\n if (activationFunction=='tanh') {\r\n minWeight = -2;\r\n maxWeight = +2;\r\n minBias = -5;\r\n maxBias = +5;\r\n } else if (activationFunction=='sigmoid') {\r\n minWeight = -1;\r\n maxWeight = +1;\r\n minBias = -1;\r\n maxBias = +1;\r\n } else {\r\n // Or throw an error if the activation function is unknown\r\n throw new Error('Activation function not supported.');\r\n }\r\n\r\n // Set (random) bias;\r\n if (biasAndWeights == undefined) {\r\n granularityBias = getRandomBits();\r\n } else {\r\n granularityBias = biasAndWeights[0];\r\n }\r\n realBias = translateGranularityToRealNumber(granularityBias, minBias, maxBias);\r\n\r\n // Set (random) weights\r\n for (let i=0; i<inputs; i++) {\r\n let granularityWeight;\r\n if (biasAndWeights == undefined) {\r\n granularityWeight = getRandomBits();\r\n } else {\r\n granularityWeight = biasAndWeights[i+1];\r\n }\r\n granularityWeights.push( granularityWeight );\r\n realWeights.push( translateGranularityToRealNumber(granularityWeight, minWeight, maxWeight) );\r\n }\r\n }", "constructor(baseNum, direct=false) {\n\t\tif(direct) {\n\t\t\tthis.value = baseNum;\n\t\t}\n\t\tif(typeof baseNum == \"number\" || typeof baseNum == \"string\") {\n\t\t\tthis.value = [new Decimal(baseNum)];\n\t\t} else if(baseNum instanceof Array) {\n\t\t\tthis.value = [];\n\t\t\tfor(var i of baseNum) {\n\t\t\t\tif(typeof i == \"number\") {\n\t\t\t\t\tthis.value.push(new Decimal(i));\n\t\t\t\t} else if(i instanceof Decimal) {\n\t\t\t\t\tthis.value.push(i);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (baseNum instanceof Decimal) {\n\t\t\tthis.value = [baseNum];\n\t\t} else {\n\t\t\tthis.value = [new Decimal(0)];\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an array of combined MedEntries and MedOrders not every MedEntry will have a MedOrder associated with it (e.g. for each object in the resulting array, 'homeMed' will be defined but 'ehrMed' may be undefined)
function mapMedEntries(medEntries, medOrders) { var medOrderIdMap = {}; for (var i = 0; i < medOrders.length; i++) { var value = medOrders[i]; medOrderIdMap[value.id] = value; } var temp = []; for (var j = 0; j < medEntries.length; j++) { var medEntry = medEntries[j]; var medOrder = medOrderIdMap[medEntry.medication_order_id]; temp.push({ homeMed: medEntry, ehrMed: medOrder }); } return temp; }
[ "function getMediansArray(medians) {\n return Object.keys(medians).map((key) => {\n return {name: key, value: medians[key]};\n });\n}", "function getMediasForId () {\r\n let mediasForId = [];\r\n for (let media of medias) {\r\n if (media.photographerId == id) {\r\n mediasForId.push(media);\r\n }\r\n }\r\n return mediasForId;\r\n}", "function findMedOrders(patient_id) {\n // get MedicationOrder/Medication models from FHIR\n var url = app.config.get('proxy_fhir') + '/MedicationOrder?_include=MedicationOrder:medication&_format=json&_count=50&patient=' + patient_id;\n app.logger.verbose('Making request to FHIR server: GET', url);\n\n return HTTP.read(url).then(function (value) {\n var fhirData = JSON.parse(value);\n // NOTE: the input for TranScript API should have the medication name in MedicationOrder.medicationReference.display\n // however, we can't be sure our FHIR data is formed like that\n // so, we loop through all MedicationOrders and the Medications they refer to, setting the attribute manually\n var medNameMap = {};\n var medOrders = [];\n for (var i = 0; i < fhirData.entry.length; i++) {\n var resource = fhirData.entry[i].resource;\n if (resource.resourceType === 'Medication') {\n if (resource.id && resource.code && resource.code.text) {\n medNameMap[resource.id] = resource.code.text;\n }\n } else if (resource.resourceType === 'MedicationOrder') {\n delete resource.meta; // delete unneeded metadata attribute\n medOrders.push(resource);\n }\n }\n for (var j = 0; j < medOrders.length; j++) {\n var medOrder = medOrders[j];\n if (medOrder.medicationReference && medOrder.medicationReference.reference) {\n var medId = medOrder.medicationReference.reference.split('/')[1];\n medOrder.medicationReference.display = medNameMap[medId];\n }\n }\n return medOrders;\n }, function (err) {\n throw new Error('Error when contacting FHIR server: ' + err.message);\n });\n}", "function flatCraftList(hortiItems){\n let flastList=[];\n hortiItems.map(tab=>{\n tab.items.map(horti=>{\n if(horti.craftedMods){\n horti.craftedMods.map(craft=>{\n flastList.push(craft);\n })\n }\n })\n });\n return flastList;\n}", "function medicationsQuery(medications) {\n\tlet buildArray = [];\n\tlet queryArray = [];\n\tconst aricept = ['%donepezil%', '%aricept%', '%cholinesterase%'];\n\tconst exelon = ['%rivastigmine%', '%exelon%', '%cholinesterase%'];\n\tconst razadyne = ['%galantamine%', '%razadyne%', '%cholinesterase%'];\n\tconst namenda = ['%memantine%', '%namenda%'];\n\n\tif (medications.acceptableTime === 'Yes'){\n\t\tif (medications.list.indexOf('Aricept (generic name: donepezil)') > -1) {\n\t\t\tbuildArray = buildArray.concat(aricept);\n\t\t};\n\t\tif (medications.list.indexOf('Exelon (generic name: rivastigmine)') > -1) {\n\t\t\tbuildArray = buildArray.concat(exelon);\n\t\t};\n\t\tif (medications.list.indexOf('Razadyne (generic name: galantamine)') > -1) {\n\t\t\tbuildArray = buildArray.concat(razadyne);\n\t\t};\n\t\tif (medications.list.indexOf('Namenda (generic name: memantine)') > -1) {\n\t\t\tbuildArray = buildArray.concat(namenda);\n\t\t};\n\t}\n\n\t//removes duplicates\n\tbuildArray.forEach(element => {\n\t\tif (queryArray.indexOf(element) === -1) {\n\t\t\tqueryArray.push(element);\n\t\t}\n\t})\n\n\tif (queryArray.length === 0) {\n\t\tqueryArray = ['']\n\t}\n\treturn queryArray;\n}", "function getUserMedications() {\n // Hard-code in medications for now\n user.assignMedication(medicationList[0]);\n user.assignMedication(medicationList[1]);\n return user.getMedications();\n}", "function obtenerMediaMasAlta(arrayEquipos) {\n let arrayMedias = new Array(arrayEquipos.length);\n for (let i = 0; i < arrayMedias.length; i++) {\n arrayMedias[i] = arrayEquipos[i].media;\n }\n arrayMedias.sort(function(a, b) {\n return a - b;\n });\n return arrayMedias[arrayMedias.length - 1];\n}", "function obtenerEdadesYMedias(datosJugador) {\r\n\t\tvar edadesMedias = new Array(); \r\n\t\tvar mediasEdad = new Array(); \r\n\t\tvar mediasEdadSuperior = new Array();\r\n\t\t\r\n\t\t// Obtenemos las edades y la media real.\r\n\t\tvar edad = parseInt(datosJugador[\"edad\"]);\r\n\t\tvar edadSemanas = parseInt(datosJugador[\"edadSemanas\"]);\r\n\t\tvar mediaReal = parseFloat(datosJugador[\"mediareal\"]);\r\n\r\n\t\t// Obtenemos las medias reales a buscar para la edad del jugador.\r\n\t\tmediasEdad[0] = truncar(mediaReal);\r\n\t\tif (redondear(mediaReal, 0) != mediasEdad[0]) {\r\n\t\t\tmediasEdad[1] = redondear(mediaReal, 0); \r\n\t\t}\r\n\t\tedadesMedias[edad] = mediasEdad;\r\n\t\t\r\n\t\t// Si procede, obtenemos las medias reales a buscar para la edad del jugador reondeada.\r\n\t\tif (edadSemanas > 28) {\r\n\t\t\tmediasEdadSuperior[0] = truncar(mediaReal);\r\n\t\t\tif (redondear(mediaReal, 0) != mediasEdadSuperior[0]) {\r\n\t\t\t\tmediasEdadSuperior[1] = redondear(mediaReal, 0); \r\n\t\t\t}\r\n\t\t\tedadesMedias[edad+1] = mediasEdadSuperior;\r\n\t\t}\r\n\t\t\r\n\t\treturn edadesMedias;\t\r\n\t}", "function extraerMediasExactasPortero(html) {\r\n\t\tvar mediasExactas = new Array();\r\n\t\tmediasExactas[\"calidad\"] = extraerMediaExactaStat(\"calidad\", html);\r\n\t\tmediasExactas[\"resistencia\"] = extraerMediaExactaStat(\"resistencia\", html);\r\n\t\tmediasExactas[\"velocidad\"] = extraerMediaExactaStat(\"velocidad\", html);\r\n\t\tmediasExactas[\"pase\"] = extraerMediaExactaStat(\"pase\", html);\r\n\t\tmediasExactas[\"entradas\"] = extraerMediaExactaStat(\"entradas\", html);\r\n\t\tmediasExactas[\"agresividad\"] = extraerMediaExactaStat(\"agresividad\", html);\r\n\t\tmediasExactas[\"remate\"] = extraerMediaExactaStat(\"agilidad\", html);\r\n\t\tmediasExactas[\"tiro\"] = extraerMediaExactaStat(\"paradas\", html);\r\n\t\tmediasExactas[\"conduccion\"] = extraerMediaExactaStat(\"faltas\", html);\r\n\t\tmediasExactas[\"desmarque\"] = extraerMediaExactaStat(\"penaltys\", html);\r\n\t\tmediasExactas[\"mediareal\"] = calcularMediaRealJugador(mediasExactas);\r\n\t\treturn mediasExactas;\r\n\t}", "function filterIngredientsAndMeasures(meal) {\n\n\tlet list = {};\n\tlet entriesMeal = Object.entries(meal);\n\tlet ingredientsAndMesures = entriesMeal.filter(value => {\n\t\treturn value[0].startsWith('strIngredient') && value[1] !== '';\n\t}).forEach((ingredient, idx) => {\n\t\tlet nameIngredient = ingredient[1];\n\t\tlet measureIngredient = meal[`strMeasure${idx + 1}`];\n\t\tlist[nameIngredient] = measureIngredient;\n\t});\n\n\treturn list;\n\n}", "function ingredientUnit() {\n let arIngredients = [];\n let arValues = [];\n // Loop through all recipes\n for (let i = 0; i < arList.length; i++) {\n const thisRecipe = arList[i];\n const ingredientList = thisRecipe.ingredient;\n for (let j = 0; j < ingredientList.length; j++) {\n const thisIngredient = ingredientList[j];\n const thisUnit = thisIngredient.unit;\n if (thisUnit) {\n arIngredients.push(thisUnit);\n }\n const thisAmmount = ingredientList[j].amount;\n if (thisAmmount) {\n arValues.push(thisAmmount);\n }\n }\n }\n arIngredients = arIngredients.filter(onlyUnique);\n arIngredients.sort();\n console.log(arIngredients);\n arValues = arValues.filter(onlyUnique);\n arValues.sort();\n console.log(arValues);\n }", "getEntries() {\n return this.getOrder().pipe(filter((order) => !!(order === null || order === void 0 ? void 0 : order.entries)), map((order) => order.entries.filter((entry) => entry.entryNumber !== -1 && entry.cancellableQuantity > 0)));\n }", "function formatLatestMeals(recipeArr) {\n if (recipeArr && recipeArr.length) {\n return recipeArr.reduce((returnArr, recipe) => {\n const {\n idMeal: recipeId,\n strMeal: recipeTitle,\n strInstructions: recipeInstructions,\n strMealThumb: recipeImageUrl,\n strIngredient1: ingredient1,\n strIngredient2: ingredient2,\n strIngredient3: ingredient3,\n strIngredient4: ingredient4,\n strIngredient5: ingredient5,\n strIngredient6: ingredient6,\n strIngredient7: ingredient7,\n strIngredient8: ingredient8,\n strIngredient9: ingredient9,\n strIngredient10: ingredient10,\n strIngredient11: ingredient11,\n strIngredient12: ingredient12,\n strIngredient13: ingredient13,\n strIngredient14: ingredient14,\n strIngredient15: ingredient15,\n strIngredient16: ingredient16,\n strIngredient17: ingredient17,\n strIngredient18: ingredient18,\n strIngredient19: ingredient19,\n strIngredient20: ingredient20,\n } = recipe;\n\n const ingredientArr = [\n ingredient1,\n ingredient2,\n ingredient3,\n ingredient4,\n ingredient5,\n ingredient6,\n ingredient7,\n ingredient8,\n ingredient9,\n ingredient10,\n ingredient11,\n ingredient12,\n ingredient13,\n ingredient14,\n ingredient15,\n ingredient16,\n ingredient17,\n ingredient18,\n ingredient19,\n ingredient20,\n ];\n\n const recipeObj = {\n recipeId,\n recipeTitle,\n recipeInstructions,\n recipeImageUrl,\n ingredientArr,\n };\n\n returnArr.push(recipeObj);\n return returnArr;\n }, []);\n }\n\n return [];\n}", "get avgOrderDims(){\n var output = { tW: 0, tL: 0, tH: 0, avgW: 0, avgL: 0, avgH: 0, tO: 0 };\n for(var index in this.orders){\n output.tH += (this.orders[index].height * this.orders[index].quantity);\n output.tW += (this.orders[index].width * this.orders[index].quantity);\n output.tL += (this.orders[index].length * this.orders[index].quantity);\n output.tO += this.orders[index].quantity;\n }\n output.avgH = output.tH / output.tO;\n output.avgW = output.tW / output.tO;\n output.avgL = output.tL / output.tO;\n return output;\n }", "getEntries() {\r\n return this.getOrder().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((order) => !!(order === null || order === void 0 ? void 0 : order.entries)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((order) => order.entries.filter((entry) => entry.entryNumber !== -1 && entry.cancellableQuantity > 0)));\r\n }", "function returnOtherDiagrams() {\n let list = [];\n Object.entries(diagramms).forEach(([key, value]) => {\n if (key != diagramInfos.displayedDiagram) {\n list.push(key);\n }\n });\n return list;\n}", "function mergeDuplicateOrganismData(allDisplayData) {\n const mergedDuplicates = [];\n for(const organismData of allDisplayData) {\n const existingData = mergedDuplicates\n .find((element) => element.name === organismData.name);\n\n /**\n * Add organismData's sightings to the existing sightings of that\n * organism in mergedDuplicates\n */\n if (existingData != undefined) {\n existingData.sightings.push(...organismData.sightings);\n } else {\n /**\n * Not a duplicate organism; add all of its data to the\n * mergedDuplicates array\n */\n mergedDuplicates.push(organismData);\n }\n }\n\n return mergedDuplicates;\n }", "atoms() {\n return this.signatures()\n .filter(sig => !sig.isSubset())\n .map(sig => sig.atoms())\n .reduce((acc, cur) => acc.concat(cur), []);\n }", "function groupQueries(arr) {\n\n\t\tvar curr_mediaquery = {};\n\t\tvar result = [];\n\n\t\tif (arr.length > 0) {\n\n\t\t\tcurr_mediaquery.query = arr[0][0]\n\t\t\tcurr_mediaquery.rules = \"\"\n\n\t\t\tfor (var i = 0, len = arr.length; i < len; i++) {\n\n\t\t\t\tif (arr[i][0] === curr_mediaquery.query) {\n\n\t\t\t\t\tcurr_mediaquery.rules += arr[i][1]\n\t\t\t\t}\n\t\t\t\telse {\n\n\t\t\t\t\tresult.push(jQuery.extend({},curr_mediaquery))\n\t\t\t\t\tcurr_mediaquery.query = arr[i][0]\n\t\t\t\t\tcurr_mediaquery.rules = arr[i][1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult.push(curr_mediaquery)\n\t\t\t//the last media-query needs to be pushed after the loop\n\t\t}\n\t\telse {\n\n\t\t\tresult = null\n\t\t}\n\n\t\treturn result\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update current user online status
function updateUserOnlineStatus() { var userParam = JSON.parse(Auth.isLoggedIn()); if(userParam) { var data = { currentUser: userParam[0].id }; var config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } }; UsersService.post('online/update', JSON.stringify(data), config) .then(function (data, status, headers, config) { if (data.status == 200) { //update current user online status getOnlineUser($scope) } }) , function (error) { }; } }
[ "function updateOnline(username, online) {\n return User.update({ username: username }, { online: online });\n}", "function updateUsersActivity() {\n SBF.updateUsersActivity(agent_online ? SB_ACTIVE_AGENT['id'] : -1, activeUser() != false ? activeUser().id : -1, function (response) {\n if (response == 'online') {\n if (!SBChat.user_online) {\n $(conversations_area).find('.sb-conversation .sb-top > .sb-labels').prepend(`<span class=\"sb-status-online\">${sb_('Online')}</span>`);\n SBChat.user_online = true;\n }\n } else {\n $(conversations_area).find('.sb-conversation .sb-top .sb-status-online').remove();\n SBChat.user_online = false;\n }\n });\n }", "function updateUsersOnlineStatus(name){\n var findUser = allChatUsers.filter(e => e.name == name);\n \n //Look if name is found in socketIDAndUserName list, if found\n if(Object.values(socketIDAndUserName).includes(name)){\n //then user is online\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = true;\n findUser[0].isOnline = true;\n }\n else{//offline\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = false;\n findUser[0].isOnline = false;\n }\n\n //DONE Broadcast users online status and broadcast global changed\n broadcastUserStatusChanged(name);\n\n updateGlobalUsers();//UNFIN?\n }", "function onOnline()\n {\n onlineStatus = '<b>online</b>';\n }", "function updateUsersOnline () {\n io.emit('usersOnline', clients)\n }", "function check_user_online(user_id)\n{\n\n}", "function setOnline() {\n\tsocket.emit('setOnline', userID);\n\taskForUsers();\n}", "set isOnline (value) {\n this._isOnline = value\n this.emit('isOnline')\n }", "function changeStatusUser(status, user) {\n users.forEach(item => {\n if (item.nickname === user.nickname) {\n if (status == 'online' && item.status == 'just appeared') {\n item.status = status;\n item.color = '#00b75d';\n io.emit('user online', user);\n }\n else if (status == 'just left' && (item.status == 'online' || item.status == 'just appeared')) {\n item.status = status;\n item.color = 'red';\n io.emit('user just left', user);\n }\n else if (status == 'offline' && item.status == 'just left') {\n item.status = status;\n item.color = '#2b1111';\n io.emit('user offline', user);\n }\n }\n });\n }", "updateUserStatus(state, data) {\n state.userStatus = data;\n }", "function setLastOnline() {\n let today = new Date();\n activeProfile.lastOnline = new Date(today.getTime());\n // Set profile object to save changes in monthlyIn/Out && balance.\n setValue(userStorage, activeProfile.name, JSON.stringify(activeProfile));\n}", "function markInactive() {\n try {\n console.log('in markInactive ');\n model.$where('( ISODate() - this.updatedAt ) > 10 * 60000 && this.status == \"login\" ')\n .exec(function (err, users) {\n if (err) console.log('error at markInactive()' + err);\n if (users === 'undefined') {\n console.log('no logged on user at markInactive()'); return;\n }\n else {\n users.forEach(function (usr) {\n console.log('updating => ' + usr);\n if ((new Date() - usr.updatedAt) > 20 * 60000)\n model.findOneAndUpdate({ _id: usr._id }, { status: 'disconnected' }, function (err, data) {\n console.log('updated => ' + data);\n });\n else\n model.findOneAndUpdate({ _id: usr._id }, { status: 'inactive' }, function (err, data) {\n console.log('updated => ' + data);\n });\n });\n }\n });\n }//end try\n catch (err) {\n console.log(err);\n }\n }", "function updateOnlineCount() {\n wss.broadcast({\n id: uuidV1(),\n type: \"onlineUsers\",\n onlineUsers: wss.clients.size\n });\n}", "function updateOnlineStatus(event) {\n if (!navigator.onLine) {\n alert('Internet access is not possible!')\n }\n }", "updateFriendStatus(state, payload) {\n if(state.friends[payload.userId]) {\n state.friends[payload.userId].online = payload.online\n }\n }", "function updateStatus(req, res){\n\tvar leaderObject = req.swagger.params.leader.value;\n\tvar update = \"UPDATE \" + constants.CLIENT_USER +\n\t \t \" SET \" + constants.IS_ACTIVE + \" = \" + !leaderObject.active +\n\t \t \" WHERE \" + constants.USER_ID + \" = ?\";\n\tvar query = \"SELECT *, NULL AS \" + constants.PWD + \", DATE_FORMAT( \" + constants.DOB + \", '%d/%m/%Y') AS \"+ constants.DOB \n\t\t\t\t\t\t\t\t\t\t\t\t\t + \", DATE_FORMAT( \" + constants.CREATE_DATE + \", '%d/%m/%Y') AS \"+ constants.CREATE_DATE \t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t + \", DATE_FORMAT( \" + constants.UPDATE_DATE + \", '%d/%m/%Y') AS \"+ constants.UPDATE_DATE +\t\n \" FROM \" + constants.CLIENT_USER +\n \" WHERE \" + constants.USER_ID + \" = ?\"; \t \n\tdbConfig.query(update, [leaderObject.user_id], function(err, rows){\n\t\tif(rows && rows.affectedRows > 0){\n\t\t\tdbConfig.query(query, [leaderObject.user_id], function(err, rows){\n\t\t\t\tif(rows && rows.length > 0){\n\t\t\t\t\tres.json({returnCode: constants.SUCCESS_CODE, message: \"Updated status of leader \" + leaderObject.user_id + \" to \" + !leaderObject.active +\".\", data: {user: rows[0]}});\t\n\t\t\t\t}else{\n\t\t\t\t\tres.json(myUtils.createDatabaseError(err));\n\t\t\t\t}\n\t\t\t});\n\t\t}else if(err){\n\t\t\tres.json(myUtils.createDatabaseError(err));\n\t\t}else{\n\t\t\tres.json(myUtils.createErrorStr(\"user_id: \" + leaderObject.user_id + \" does not exist!\", constants.ERROR_CODE));\n\t\t}\n\t});\n}", "SET_CURRENT_USER_STATUS(state, status) {\n state.currentUser.loggedIn = status;\n }", "_online() {\n // if we've requested to be offline by disconnecting, don't reconnect.\n if (this.currentStatus.status != \"offline\") this.reconnect();\n }", "async setUserStatus(_, {\n id,\n pending\n }, {\n pool,\n req\n }) {\n verifyJwt(req)\n //set online to 'true' when setting pending as 'false' and vice versa\n let online = pending === \"true\" ? \"false\" : \"true\"\n\n try {\n await pool.query(`update users set pending = $2, online = $3 where id = $1`, [id, pending, online])\n\n return {\n message: \"User successfully updated\"\n }\n } catch (err) {\n throw new Error(err.message)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess the specified template, parsing embedded "properties", "scripts", "code" as well as "conditions" and "where" elements. Return a "root" template that is ready to process.
function preProcessTemplate(template) { // Generate the ID base var baseid = (new Date()).getTime(); // Establish the template "lookup" template.properties = new Object(); template.scripts = new Object(); template.code = new Object(); template.conditions = new Object(); template.wheres = new Object(); // Establish the pre-processed template.pre = template.raw; // Indexes used for parsing var begin, end; // Loop over all the script segements while ((begin = template.pre.indexOf('{{')) >= 0) { // Generate a new key var key = '_k1_' + (baseid++).toString(); // Determine the end end = template.pre.indexOf('}}', begin); // Extract the script var script = template.pre.slice(begin, end + 1); // Return the string with the item replaced template.pre = [template.pre.slice(0, begin), key, template.pre.slice(end + 2)].join(''); // Add the property into the lookup template.scripts[key] = script.trim(); } // Loop over all the property segments while ((begin = template.pre.indexOf('[')) >= 0) { // Generate a new key var key = '_k1_' + (baseid++).toString(); // Determine the end end = template.pre.indexOf(']', begin); // Extract the property var property = template.pre.slice(begin, end + 1); // Return the string with the item replaced template.pre = [template.pre.slice(0, begin), key, template.pre.slice(end + 1)].join(''); // Add the property into the lookup template.properties[key] = property.trim(); } // Loop over all the free-code segments while ((begin = template.pre.indexOf('{')) >= 0) { // Generate a new key var key = '_k1_' + (baseid++).toString(); // Determine the end end = template.pre.indexOf('}', begin); // Extract the property var code = template.pre.slice(begin, end + 1); // Return the string with the item replaced template.pre = [template.pre.slice(0, begin), key, template.pre.slice(end + 1)].join(''); // Add the property into the lookup template.code[key] = code.trim(); } // Define parse function this.parsePropCodes = function (name) { var codes = new Object(); begin = 0; // Loop over all the condition= while ((begin = template.pre.indexOf(name, begin)) >= 0) { // Move past the whitespace while ((isWhitespace(template.pre.charAt(begin)) == false) && (template.pre.charAt(begin) != "=")) begin++; // Move past the whitespace while (isWhitespace(template.pre.charAt(begin)) == true) begin++; // If we hit an = if (template.pre.charAt(begin) == "=") { // Increment begin++; // Move past the whitespace while (isWhitespace(template.pre.charAt(begin)) == true) begin++; // If we hit a ' or " if ((template.pre.charAt(begin) == "\"") || (template.pre.charAt(begin) == "\'")) { // Get the break var brk = template.pre.charAt(begin); // Increment begin++; // Determine the end end = template.pre.indexOf(brk, begin); // Generate a new key var key = '_k1_' + (baseid++).toString(); // Extract the snippet var code = template.pre.slice(begin, end); // Return the string with the item replaced template.pre = [template.pre.slice(0, begin), key, template.pre.slice(end)].join(''); // Add the property into the lookup codes[key] = code.trim(); } } } // Return return codes; } // Define parse "special" function this.parseSpecialElements = function (name) { begin = 0; // Loop over all the condition= while ((begin = template.pre.indexOf('<', begin)) >= 0) { var start = begin; var tag = ''; var isclose = false; // Increment begin++; // Move past the whitespace while (isWhitespace(template.pre.charAt(begin)) == true) begin++; // Determine if this is a close tag if (template.pre.charAt(begin) == '/') { begin++; isclose = true; } // Move past the whitespace while (isWhitespace(template.pre.charAt(begin)) == true) begin++; // Parse the tag while ((isWhitespace(template.pre.charAt(begin)) == false) && (template.pre.charAt(begin) != '>')) { tag += template.pre.charAt(begin); begin++; } // If the tag matches the name if (tag.toLowerCase() == name.toLowerCase()) { // Replace the tag template.pre = [template.pre.slice(0, start), '<' + ((isclose == true) ? '/' : '') + 'div _ktype="' + name.toUpperCase() + '"', template.pre.slice(begin)].join(''); } } // Return return; } // Replace "condition" and "where" template.conditions = this.parsePropCodes("condition"); template.wheres = this.parsePropCodes("where"); // Replace the "special" elements this.parseSpecialElements('if'); this.parseSpecialElements('elseif'); this.parseSpecialElements('else'); this.parseSpecialElements('for'); this.parseSpecialElements('with'); this.parseSpecialElements('nth'); this.parseSpecialElements('first'); this.parseSpecialElements('last'); // Replace all "src" and "href" references template.pre = replaceAll(template.pre, "src", "_src", true); template.pre = replaceAll(template.pre, "href", "_href", true); // Wrap the pre-processed template template.pre = '<div>' + template.pre + '</div>'; // Return return template; }
[ "function processTemplate(template, model) {\n\n // Establish the current \"view\" model\n template.view = bindView(template.root.scripts, model, template.dom);\n\n var replace = [];\n\n // Loop over the template constructs\n for (var i = 0; i < template.dom.children.length; i++) {\n\n // Acces the child\n var child = template.dom.children[i];\n\n // Access the node name\n var name = getNodeName(child);\n\n // Process the construct node types\n if (name == \"IF\")\n replace.push({ p: child.parentNode, r: child, w: processIF(template, child) });\n else if (name == \"FOR\")\n replace.push({ p: child.parentNode, r: child, w: processFOR(template, child) });\n else if (name == \"WITH\")\n replace.push({ p: child.parentNode, r: child, w: processWITH(template, child) });\n else if (hasTemplateContent(child) == true) {\n\n // Evaluate the template with the array object instance and add the result to the \"add\" collection\n child.innerHTML = processTemplate(openSubTemplate(child, template), template.view);\n\n }\n\n }\n\n // Replace the nodes\n for (var ri = 0; ri < replace.length; ri++)\n replaceNode(replace[ri].p, replace[ri].r, replace[ri].w);\n\n // Access the \"raw\" html template\n var html = template.dom.innerHTML;\n\n // Loop over the \"code\" snipptes processing\n for (var codeID in template.root.code) {\n\n // If the text contains the code,\n if (html.indexOf(codeID) >= 0) {\n\n // Access the \"code\"\n var code = template.root.code[codeID];\n\n // Trim the { and }\n code = code.substring(1, code.length - 1);\n\n // Replace with the value\n html = replaceKey(html, codeID, (new Function(code)).call(template.view));\n\n }\n\n }\n\n // Loop over the \"property\" processing\n for (var propertyID in template.root.properties) {\n\n // If the text contains the property,\n if (html.indexOf(propertyID) >= 0) {\n\n // Access the \"property\"\n var property = template.root.properties[propertyID];\n\n // Trim the [ and ] and whitespace\n property = property.substring(1, property.length - 1).trim();\n\n // Replace with the value\n if (property == \"#\")\n html = replaceKey(html, propertyID, template.index);\n else if (property == \"##\")\n html = replaceKey(html, propertyID, template.count);\n else if (property == \"$\")\n html = replaceKey(html, propertyID, template.str);\n else\n html = replaceKey(html, propertyID, parseValue(template.view, property));\n\n }\n\n }\n\n // Replace all \"src\" and \"href\" references\n html = replaceAll(html, \"_src\", \"src\", true);\n html = replaceAll(html, \"_href\", \"href\", true);\n\n // Return\n return html;\n\n }", "function preprocessTemplates (tree) {\n tree = filterTemplates(tree, {\n extensions: ['hbs', 'handlebars'],\n compileFunction: 'Ember.Handlebars.compile'\n })\n \n return tree\n}", "supplant(template, json) {\n\t\tif (template && template.nodeType === Node.ELEMENT_NODE) {\n\t\t\ttemplate = template.innerHTML;\n\t\t}\n\n\t\tvar re = /{{([^{{}}]*)}}/g,\n\t\t\treExp = /(^( )?(if|for|else|elseif|switch|case|break|\\/if|\\/for|\\/else))(.*)?/g,\n\t\t\treExp2 = /(^( )?(\\/if|\\/for|\\/else))(.*)?/g,\n\t\t\tcode = 'var r=[];\\n',\n\t\t\tcursor = 0,\n\t\t\tmatch;\n\n\t\tvar add = function (line, js) {\n\t\t\tif (js) {\n\t\t\t\tif (line.match(reExp)) {\n\n\t\t\t\t\tswitch (match[1].split(' ')[0]) {\n\t\t\t\t\t\tcase 'if':\n\t\t\t\t\t\tcase 'for':\n\t\t\t\t\t\tcase 'switch':\n\t\t\t\t\t\t\tcode += line + '{' + '\\n'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'else':\n\t\t\t\t\t\t\tcode += '} else {' + '\\n'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'elseif':\n\t\t\t\t\t\t\tcode += '} else if' + line.slice(6) + '{' + '\\n'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'case':\n\t\t\t\t\t\t\tcode += line + ':' + '\\n'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase '/if':\n\t\t\t\t\t\tcase '/for':\n\t\t\t\t\t\t\tcode += '}' + '\\n'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tcode += line + '\\n'\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tcode += 'r.push(' + line + ');\\n';\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcode += line != '' ? 'r.push(\"' + line.replace(/\"/g, '\\\\\"') + '\");\\n' : '';\n\t\t\t}\n\n\t\t\treturn add;\n\t\t}\n\n\t\twhile (match = re.exec(template)) {\n\t\t\tadd(template.slice(cursor, match.index))(match[1], true);\n\t\t\tcursor = match.index + match[0].length;\n\t\t}\n\n\t\tadd(template.substr(cursor, template.length - cursor));\n\n\t\tcode += 'return r.join(\"\");';\n\t\treturn new Function(' with (this) { ' + code.replace(/[\\r\\t\\n]/g, '') + '}').apply(json);\n\t}", "function preprocessHtmlTemplates(code) {\n let targetAst;\n let preprocessed;\n let templates = {\n _classes: [],\n _preprocess: true,\n _transformed: [],\n preprocessed: preprocessedTemplates,\n };\n try {\n targetAst = espree.parse(code, espreeModuleOptionsFull);\n let licenseComments = targetAst.comments.map(comment => comment.type === 'Block' ? '/*' + comment.value + '*/' : '//' + comment.value).filter(comment => comment.indexOf('@license') >= 0);\n //console.log(JSONstringify(targetAst, null, 2));\n traverseAst(targetAst, templates);\n if (templates._transformed.length > 0) {\n preprocessed = licenseComments.join('\\n') + '\\n' + escodegen.generate(targetAst, compact ? escodegenOptionsCompact : escodegenOptions);\n if (!preprocessed.endsWith('\\n')) {\n preprocessed += '\\n';\n }\n }\n else {\n // no transformation if unnecessary\n preprocessed = code;\n }\n }\n catch (e) {\n throw e;\n }\n return preprocessed;\n}", "function pre_compile_templates(){\n var pretemplates = jQuery('.cf-editor-template');\n for( var t = 0; t < pretemplates.length; t++){\n compiled_templates[pretemplates[t].id] = Handlebars.compile( pretemplates[t].innerHTML );\n }\n\n}", "resolveRootAndTemplate() {\n const key = Object.keys(this.template).shift();\n this.root = Template.resolveStringNumber(this.resolveElement(key, this.template), this.template);\n \n if (Util.isFunction(this.template[key])) {\n this.template = this.template[key].call(this.root, this.root);\n } else {\n this.template = this.template[key];\n }\n }", "function preprocess (str) {\n let rt = ''\n let sBlocks = [] // svelte blocks\n let toCloseSBlocks\n let tab\n let inTag\n let blockIndent = -1 // normal pug plain text block\n\n // func to close svelte blocks which are outdented\n let closeSBlocks = () => {\n for (let e of toCloseSBlocks) {\n rt += `${e.indent}| {/${e.type}}\\n`\n sBlocks.pop()\n }\n }\n\n // make sure template ends with newline\n str[str.length - 1] === '\\n' || (str += '\\n')\n\n // process line by line\n let lines = str.match(/^.*$/gm)\n for (let i in lines) {\n let line = lines[i]\n let cap = line.match(/^([ \\t]*)(.*)$/)\n let indent = cap[1]\n let lineData = cap[2]\n\n // blank line\n if (/^\\s*$/.test(line) && i < lines.length - 1) {\n rt += '\\n'\n continue\n }\n\n // try to init tab size\n if (!tab) {\n if (indent[0] === ' ') tab = 2\n else if (indent[0] === '\\t') tab = 1\n }\n\n // correct indent and set up\n // the svelte blocks to be closed\n toCloseSBlocks = []\n for (let e of sBlocks) {\n if (indent > e.indent)\n indent = indent.slice(tab)\n else\n toCloseSBlocks.unshift(e)\n }\n\n // if currently inside a block:\n // just copy paste\n if (blockIndent !== -1) {\n if (indent > blockIndent) {\n rt += line + '\\n'\n continue\n } else { blockIndent = -1 }\n }\n\n // if currently inside a tag:\n // fix svelte typed attributes and\n // check if tag end\n if (inTag) {\n let data = parseTagEnd(lineData)\n let attrs = parseAttrs(data.attrs)\n rt += indent + attrs + data.post + '\\n'\n data.hasTagEnd && (inTag = false)\n data.hasBlock && (blockIndent = indent.slice(tab))\n continue\n }\n\n // if it's a tag:\n // fix svelte typed attributes and\n // check if the tag extends to next lines\n let data = parseTag(lineData)\n if (data) {\n closeSBlocks()\n\n let attrs = parseAttrs(data.attrs)\n rt += indent + data.pre + attrs + data.post + '\\n'\n data.hasTagEnd || (inTag = true)\n data.hasBlock && (blockIndent = indent)\n continue\n }\n\n // if it's a svelte block:\n // change block to pug plain text and\n // add to block stack if needed\n data = parseSBlock(lineData)\n if (data) {\n if (data.newSBlock) {\n closeSBlocks()\n sBlocks.push({\n type: data.type,\n indent\n })\n }\n rt += indent + '| ' + lineData + '\\n'\n continue\n }\n\n // if it's another pug object:\n // just copy paste\n rt += line + '\\n'\n\n // check if it's a plain text block\n _block.test(lineData) && (blockIndent = indent)\n }\n\n return rt\n}", "function convertTemplate(src) {\r\n function processString(src) {\r\n var code = [], cap;\r\n while(src) {\r\n if (src.match(/^{{IF[\\s\\S]*?{{ENDIF}}/)) {\r\n var sub_src = src.match(/^{{IF[\\s\\S]*?{{ENDIF}}/);\r\n if (cap = /^{{IF ([\\s\\S]*?)}}([\\s\\S]*?){{ELSE}}([\\s\\S]*?){{ENDIF}}/.exec(sub_src)) {\r\n code.push('(x.'+cap[1]+'?'+processString(cap[2])+':'+processString(cap[3])+')');\r\n } else if (cap = /^{{IF ([\\s\\S]*?)}}([\\s\\S]*?){{ENDIF}}/.exec(sub_src)) {\r\n code.push('(x.'+cap[1]+'?'+processString(cap[2])+\":'')\");\r\n } else {\r\n throw new Error('Failed to process template: invalid {{IF}} expression');\r\n }\r\n } else if (cap = /^{{(?!\\^)(?!@)(.*?)}}/.exec(src)) {\r\n code.push('x.'+cap[1]);\r\n } else if (cap = /^{{\\^\\^(.*?)}}/.exec(src)) {\r\n code.push('escape(x.'+cap[1]+',true)');\r\n } else if (cap = /^{{\\^(.*?)}}/.exec(src)) {\r\n code.push('escape(x.'+cap[1]+')');\r\n } else if (cap = /^{{@(.*?)}}/.exec(src)) {\r\n code.push('mangle(x.'+cap[1]+')');\r\n } else if (cap = /^\\n/.exec(src)) {\r\n code.push(\"'\\\\n'\");\r\n } else if (cap = /^.+?(?={{|\\n|$)/.exec(src)) {\r\n code.push(\"'\" + cap[0] + \"'\");\r\n } else {\r\n throw new Error('Failed to process template');\r\n }\r\n if (cap[0].length == 0) {\r\n throw new Error('Failed to consume a token');\r\n }\r\n src = src.slice(cap[0].length);\r\n }\r\n return code.join('+');\r\n }\r\n var prefix = '';\r\n if (src.match(/{{\\^/)) { // add escape code if needed\r\n prefix = prefix + 'escape=' + escape.toString().replace(/\\/\\/.*/g, '').replace(/\\s+/g, '').replace(/var/g,'var ').replace('return','return ') + ';';\r\n }\r\n if (src.match(/{{@/)) { // add mangle code if needed\r\n prefix = prefix + 'mangle=' + mangle.toString().replace(/\\/\\/.*/g, '').replace(/\\s+/g, '').replace(/var/g,'var ').replace('return','return ') + ';';\r\n }\r\n var fx = prefix + 'return ' + processString(src.replace(/'/g,\"\\\\'\"));\r\n return new Function('x', fx);\r\n }", "function parseTemplate(delims) {\n var oldprevChar = prevChar; // record old previous char\n var ts = inPtr-2; // record entry point for later rewinding\n var tn = parseTemplateIdentifier(); // get template name\n var args;\n var tc; // actual code to insert\n if (tn=='#expr') {\n args = parseTemplateArgs(false); // and parse any arguments\n tc = expandExpr(args[1]);\n } else if (tn=='#if') {\n // if is special; we cannot evaluate all the arguments\n // until we know the result of the first\n tc=expandIf();\n } else if (tn=='#ifeq') {\n // ifeq is special; we cannot evaluate all the arguments\n // until we know the result of the first two\n tc=expandIfeq();\n } else if (tn=='#switch') {\n // switch is special; we cannot evaluate all the arguments\n // until we know the result of the first \n tc=expandSwitch();\n } else if (tn=='#lc') {\n // lowercase argument\n args = parseTemplateArgs(true);\n if (args[1])\n tc = args[1].toLowerCase();\n else \n tc = '';\n } else if (tn=='#uc') {\n // lowercase argument\n args = parseTemplateArgs(true);\n if (args[1])\n tc = args[1].toUpperCase();\n else \n tc = '';\n } else { // user template invocation\n args = parseTemplateArgs(true); // and parse any arguments\n tc = templates[tn];\n if (!tc) // missing template throw new Error('Missing template: '+tn);\n tc = '<font color=\"red\" title=\"No template definition for '+tn.replace(/\\\"/g,'%22')+'\">'+tn+'</font>';\n else {\n tc = substitute(tc,args);\n tc = evalTemplateBody(tc); // evaluate\n }\n }\n //alert('Expanded('+tn+') to \"'+tc+'\"');\n\n // idea: insert template body, args-substituted, in place\n // of the template call, and let parsing continue\n // from our current spot.\n prevChar='';\n nextChar=oldprevChar;\n inValue = inValue.substr(0,ts)+tc+inValue.substr(inPtr);\n if (inValue.length>100000) { // sanity check\n inPtr=inValue.substr(0,ts).length+tc.length;\n return '**Infinite recursion?**';\n } else {\n inPtr=ts;\n }\n return ''; // nothing to add to current output\n}", "beforeParseTemplate(){}", "function processTemplate() {\n var taTemplate = document.getElementById(\"taTemplate\");\n var taOutput = document.getElementById(\"taOutput\");\n\n var template = JSON.parse(taTemplate.value);\n\n var newJSON = generateJSON(template);\n\n taOutput.value = JSON.stringify(newJSON, null, 4);\n return false;\n}", "visitNormalTemplateBody(ctx) {\n const result = new analyzerResult_1.AnalyzerResult();\n for (const templateStr of ctx.templateString()) {\n result.union(this.visit(templateStr.normalTemplateString()));\n }\n return result;\n }", "function prepareTemplates(preload) {\n if (preload) {\n return gulp.src(['app/**/*.pre.html', 'app/**/**/*.pre.html'])\n .pipe(replace('@version@', v))\n .pipe(htmlmin({collapseWhitespace: true, removeComments: true}))\n .pipe(rename(function(opt) {\n opt.basename = opt.basename.split(\".\")[0];\n return opt;\n }))\n .pipe(angularTemplateCache());\n } else {\n return gulp.src([]);\n }\n}", "function _init() {\n var scripts,\n script,\n attribute,\n i;\n scripts = document.getElementsByTagName(TEMPLATE_PARSE_TAG);\n i = scripts.length;\n while (i > 0) {\n script = scripts[i];\n if (script !== undefined) {\n attribute = script.getAttribute('type');\n if (attribute && attribute.valueOf() === TEMPLATE_PARSE_TYPE) {\n // finally, if found the script tag for a template,\n // now strap it from the script tag and store it in the\n ki.helper.logInfo('Logging template...');\n ki.helper.logDir(script);\n // templates are properties of the template object\n _registerTemplate(script.id, script.innerHTML);\n }\n }\n i--;\n }\n }", "scanTemplateElement() {\n\t let startLocation = this.getLocation();\n\t let start = this.index;\n\t while (this.index < this.source.length) {\n\t let ch = this.source.charCodeAt(this.index);\n\t switch (ch) {\n\t case 0x60:\n\t {\n\t // `\n\t // don't include the traling \"`\"\n\t let slice = this.getSlice(start, startLocation);\n\t this.index++;\n\t return {\n\t type: _tokenizer.TokenType.TEMPLATE,\n\t tail: true,\n\t interp: false,\n\t slice: slice\n\t };\n\t }\n\t case 0x24:\n\t // $\n\t if (this.source.charCodeAt(this.index + 1) === 0x7B) {\n\t // {\n\t // don't include the trailing \"$\"\n\t let slice = this.getSlice(start, startLocation);\n\t this.index += 1;\n\t return {\n\t type: _tokenizer.TokenType.TEMPLATE,\n\t tail: false,\n\t interp: true,\n\t slice: slice\n\t };\n\t }\n\t this.index++;\n\t break;\n\t case 0x5C:\n\t // \\\\\n\t {\n\t let octal = this.scanStringEscape(\"\", null)[1];\n\t if (octal != null) {\n\t throw this.createILLEGAL();\n\t }\n\t break;\n\t }\n\t default:\n\t this.index++;\n\t }\n\t }\n\n\t throw this.createILLEGAL();\n\t }", "function prepareTemplate(templateText) {\n Handlebars.registerHelper(\"processCommentBody\", processCommentBody);\n Handlebars.registerHelper(\"layoutChildren\", layoutComments);\n Handlebars.registerHelper(\"parseMSDate\", parseMSDate);\n Handlebars.registerHelper(\"isBookmarked\", isBookmarked);\n Handlebars.registerHelper(\"isCurrentUser\", isCurrentUser);\n Handlebars.registerHelper(\"isUserLoggedIn\", isUserLoggedIn);\n Handlebars.registerHelper(\"isLiked\", isLiked);\n commentTemplate = Handlebars.compile(templateText);\n}", "function compile(markup) {\n // ===== nested function =======\n function parseFn(match, htmltagtype, tagtype, optimization, forvar, expr, offset, string) {\n nestedTmpls.push(new Template('string', string.substring(parseLoc, offset)));\n parseLoc = offset + match.length;\n\n if (tagtype === undefined || tagtype === 'text' || tagtype === 'html') {\n nestedTmpls.push(new Template(tagtype || 'html', fnFromString(expr), htmltagtype));\n } else if (tagtype === 'if' || tagtype.substring(0,3) === 'for') {\n stack.push(current);\n current = new Template(tagtype === 'if' ? 'if' : 'for', fnFromString(expr), htmltagtype);\n if (tagtype !== 'if') {\n current.forvar = forvar;\n current.useOptimizations = optimization === '*';\n }\n nestedTmpls.push(current);\n nestedTmpls = current.tmplList;\n } else if (tagtype === '/if' || tagtype === '/for') {\n if (current.type !== tagtype.substring(1))\n console.log('Error, found a mismatched closing tag of type <' + tagtype +\n '> when expecting </' + current.type + '>');\n current = stack.pop();\n nestedTmpls = current.tmplList;\n } else {\n console.log('Error, found unrecognized tagtype of <' + tagtype + '>');\n }\n\n return match;\n }\n // ===== end nested function ===\n\n var root, current, nestedTmpls, stack = [], parseLoc = 0;\n root = new Template('root', null, 'div');\n stack.push(root);\n current = root;\n nestedTmpls = root.tmplList;\n markup.replace(rParse, parseFn);\n nestedTmpls.push(new Template('string', markup.substring(parseLoc, markup.length)));\n return root;\n}", "async function parseTemplate(unparsed, options) {\n const OPEN = options.delimiters.open;\n const CLOSE = options.delimiters.close;\n const COMMENT = options.delimiters.comment;\n const ESCAPE = options.delimiters.escape;\n const UNESCAPE = options.delimiters.unescape;\n const IMPORT = options.delimiters.import;\n let parsed;\n let i = 0;\n let length = unparsed.length;\n parsed = \"with($locals||{}){$buffer.push(`\";\n for (; i < length; ++i) {\n let c = unparsed[i];\n if (unparsed.slice(i, i + OPEN.length) === OPEN) {\n i += OPEN.length;\n switch (unparsed[i]) {\n case COMMENT:// Comments -- output nothing\n tagContents(COMMENT + CLOSE);\n break;\n case ESCAPE:// Output escaped value\n ++i;\n parsed += \"`,$xml(\";\n parsed += tagContents();\n parsed += \"),`\";\n break;\n case UNESCAPE:// Output unescaped value\n ++i;\n parsed += \"`,(\";\n parsed += tagContents();\n parsed += \"),`\";\n break;\n case IMPORT:// Include another file\n ++i;\n parsed += \"`,`\";\n // Cache the previous values\n const importContents = tagContents().split(\"|\");\n const templateName = importContents[0].trim();\n const locals = importContents[1] && importContents[1].trim() || \"$locals\";\n // Read the next template using the new values\n const unparsedImport = await getTemplate(templateName, options);\n parsed += \"`);(function($buffer,$locals){\" + unparsedImport + \"})($buffer,\" + locals + \");$buffer.push(`\";\n break;\n default:\n parsed += \"`);\";\n parsed += tagContents();\n parsed += \";$buffer.push(`\";\n break;\n }\n }\n else if (c === \"\\\\\") {\n // Backslashes need to be escaped\n parsed += \"\\\\\\\\\";\n }\n else if (c === \"`\") {\n // Backticks need to be escaped as that the character that we are using to surround our string literals\n // We chose them as backtick string literals are containing raw newline characters\n parsed += \"\\\\`\";\n }\n else if (c === \"$\") {\n // Since backtick string literals in javascript support interpolation, we need to escape the dollar sign\n parsed += \"\\\\$\";\n }\n else {\n parsed += c;\n }\n }\n parsed += \"`);}\";\n return parsed;\n function tagContents(endTag = CLOSE) {\n let end = unparsed.indexOf(endTag, i);\n if (end < 0) {\n throw new Error(\"Could not find matching close tag '\" + endTag + \"'.\");\n }\n let result = unparsed.substring(i, end);\n // Move the cursor to the end of the tag\n i = end + endTag.length - 1;\n return result;\n }\n}", "function tryTemplate(cursor)\n{\n var line = cursor.line;\n var column = cursor.column;\n var result = -2;\n\n if (isStringOrComment(line, column))\n return result; // Do nothing for comments and strings\n\n // Check for 'template' keyword at line start\n var currentString = document.line(line);\n var prevWord = document.wordAt(line, column - 1);\n dbg(\"tryTemplate: prevWord='\"+prevWord+\"'\");\n dbg(\"tryTemplate: prevWord.match=\"+prevWord.match(/\\b[A-Za-z_][A-Za-z0-9_]*/));\n // Add a closing angle bracket if a prev word is not a 'operator'\n // and it looks like an identifier or current line starts w/ 'template' keyword\n var isCloseAngleBracketNeeded = (prevWord != \"operator\")\n && (currentString.match(/^\\s*template\\s*<$/) || prevWord.match(/\\b[A-Za-z_][A-Za-z0-9_]*/))\n && (column == document.lineLength(line) || document.charAt(cursor).match(/\\W/))\n ;\n if (isCloseAngleBracketNeeded)\n {\n document.insertText(cursor, \">\");\n view.setCursorPosition(cursor);\n }\n else if (justEnteredCharIsFirstOnLine(line, column, '<'))\n {\n result = tryIndentRelativePrevNonCommentLine(line);\n }\n // Add a space after 2nd '<' if a word before is not a 'operator'\n else if (document.charAt(line, column - 2) == '<')\n {\n if (document.wordAt(line, column - 3) != \"operator\")\n {\n // Looks like case 3...\n // 0) try to remove '>' if user typed 'some<' before\n // (and closing '>' was added by tryTemplate)\n if (column < document.lineLength(line) && document.charAt(line, column) == '>')\n {\n document.removeText(line, column, line, column + 1);\n addCharOrJumpOverIt(line, column - 2, ' ');\n view.setCursorPosition(line, column + 1);\n column = column + 1;\n }\n // add a space after operator<<\n document.insertText(line, column, \" \");\n }\n else\n {\n document.insertText(line, column, \"()\");\n view.setCursorPosition(line, column + 1);\n }\n }\n else\n {\n cursor = tryJumpOverParenthesis(cursor); // Try to jump out of parenthesis\n tryAddSpaceAfterClosedBracketOrQuote(cursor);\n }\n return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
arrange pieces and display them
function arrange() { for(var i = 0; i < 15; ++i) { pieces[i].element.style.left = pieces[i].col*100 + "px"; pieces[i].element.style.top = pieces[i].row*100 + "px"; } }
[ "function displaynextPiece(){\n\n nextBoard.innerHTML = \"\";\n \n nextPiece.shape.forEach((element, index) =>{\n element.forEach((piece, idx)=>{\n if(piece!==0){\n const block = document.createElement('div');\n block.classList.add('block');\n block.classList.add(`${nextPiece.color}`);\n block.style.gridRowStart = nextPiece.coordinates.y + index;\n block.style.gridColumnStart = nextPiece.coordinates.x + idx;\n nextBoard.appendChild(block);\n }\n })\n })\n }", "displayPieces() {\n for (var i = 0; i < 8; i++) {\n for (var j = 0; j < 8; j++) {\n if (this.piecePositions[j][i] != null) {\n image(\n this.piecePositions[j][i],\n 8 + SQUARE_SIZE + i * SQUARE_SIZE,\n 7 + SQUARE_SIZE + j * SQUARE_SIZE,\n 50,\n 50\n );\n }\n }\n }\n\n this.pawnToQueen()\n }", "renderPieces () {\n\t\tfor ( let i = 0; i < this.model.getPiecesLength(); i++ ) {\n\t\t\tthis.view.renderPiece( i, this.model.baseNumber, this.model.getPieceSize() );\n\t\t}\n\n\t\t// The pieces are in the DOM, it is time to add event to them.\n\t\tthis.view.bindSelectPieceToMove( this.selectPieceToMove.bind( this ) );\n\t}", "function disp_piece(what, where, appear)\n{\n var ob;\n\n if (!where)\n\twhere = 'main';\n\n if (!what)\n\tif (where == 'main')\n\t what = cur_piece;\n\telse\n\t what = next_piece;\n\n if (where == 'next')\n\tfor (var y = 0; y < 4; y++)\n\t for (var x = 0; x < 4; x++)\n\t\tif ((ob = nextfield[x][y])) {\n\t\t edje_object_signal_emit(ob, \"play,cube,disappear\", \"js\");\n\t\t nextfield[x][y] = null;\n\t\t}\n\n\n for (var y = 0; y < what.h; y++)\n\tfor (var x = 0; x < what.w; x++)\n\t if (what.shape[y][x] == XXX) {\n\t\tvar bonus = null;\n\t\tvar crado = null;\n\n\t\tif (where == 'main') {\n\t\t if (what.bonus.type && what.bonus.x == x && what.bonus.y == y)\n\t\t\tbonus = what.bonus.type;\n\t \n\t\t if (what.crado.type && what.crado.x == x && what.crado.y == y)\n\t\t\tcrado = what.crado.type;\n\n\t\t set_block(what.x + x, what.y + y, what.color, bonus, crado, where, appear);\n\t\t} else {\n\t\t set_block(x, y, what.color, null, null, where, appear);\n\t\t}\n\t }\n}", "displayPiece(){\n board.innerHTML = \"\";\n \n currentPiece.shape.forEach((element, index) =>{\n element.forEach((piece, idx)=>{\n if(piece!==0){\n const block = document.createElement('div');\n block.classList.add('block');\n block.classList.add(`${currentPiece.color}`);\n block.style.gridRowStart = currentPiece.coordinates.y + index;\n block.style.gridColumnStart = currentPiece.coordinates.x + idx;\n board.appendChild(block);\n }\n })\n })\n\n this.totalBoardValue.forEach((element, index) => {\n element.forEach((piece , idx) =>{\n \n if(piece !== 0){\n const block = document.createElement('div');\n block.classList.add(`block`);\n\n if(this.totalBoardColor[index][idx])\n block.classList.add(`${this.totalBoardColor[index][idx]}`);\n\n block.style.gridRowStart = 1 + index;\n block.style.gridColumnStart = 1 + idx;\n board.appendChild(block);\n }})\n \n });\n \n }", "function placePieces() {\r\n clearBoard();\r\n for (i = 0; i < 8; i++) {\r\n for (j = 0; j < 8; j++) {\r\n if (!pieces[i][j]) {\r\n continue;\r\n }\r\n let curPiece = document.createElement(\"img\");\r\n curPiece.className = \"Piece\";\r\n let pname = pieceName[pieces[i][j].piece];\r\n curPiece.id = pname + i + j;\r\n curPiece.src = \"Images/\" + colorName[pieces[i][j].color] + \"-\" + pname + \".png\";\r\n squares[i][j].appendChild(curPiece);\r\n }\r\n }\r\n}", "getArrangement () {\n const { boardEl } = this.props ();\n const pieces = boardEl.getElementsByClassName ('piece'); \n const whiteArrangement = [], blackArrangement = []; \n\n Array.from (pieces).forEach (piece => { \n const p = Array.from(piece.parentElement.classList).find (c => c !== 'square'); \n const color = p.split ('-')[0];\n const name = p.split ('-')[1];\n const alias = this.translateNameToAlias (name);\n const position = piece.parentElement.id.split (\"-\")[2];\n\n if (color === 'white') {\n whiteArrangement.push (`${alias}${position}`);\n }\n else if (color === 'black') {\n blackArrangement.push (`${alias}${position}`);\n } \n }); \n return { whiteArrangement, blackArrangement};\n }", "renderManualScreen(){\n let container = document.createElement(\"div\");\n container.classList.add(\"manual-screen\");\n\n this.piecesNames.map((a, i) => {\n //create a wrapper div for each pair img/name\n let imgNameDiv = document.createElement(\"div\");\n imgNameDiv.classList.add(\"manual-screen-wrap\");\n //creates a div with the name of the piece\n let divName = document.createElement(\"div\");\n divName.classList.add(\"manual-screen-name\");\n divName.innerHTML = this.piecesNames[i];\n\n //creates an image element and adds a class\n let image = new Image();\n image.classList.add(\"manual-screen-img\");\n image.src = this.piecesSrc[i][i];\n\n //appends the img and the text to the container\n imgNameDiv.appendChild(image);\n imgNameDiv.appendChild(divName);\n container.appendChild(imgNameDiv);\n })\n\n this.mainContainer.appendChild(container);\n }", "function layoutBoard()\n{\n puzzlePieces = $$('#puzzlearea div');\n var idCounter = 0;\n puzzlePieces.each(function(element)\n {\n element.addClassName('puzzlepiece');\n element.id = idCounter;\n arrangeTiles(element, idCounter);\n BOARD[idCounter] = 1;\n idCounter++;\n });\n BOARD[15] = 0; // Empty tile.\n}", "function formatPuzzle(pc) {\n\tlet pi = display.puzzleIntro;\n\tlet pd = display.puzzleDescription;\n\tlet sd = display.suspectDisplay;\n\tlet pt = display.puzzleTitle;\n\tlet ld = display.latexDisplay;\n\tpt.innerHTML = pc.puzzleTitle()\n\tpd.innerHTML = pc.cluesDisplay();\n\tld.innerHTML = pc.cluesLatex();\n\tsd.innerHTML = pc.suspectsDisplay();\n\tpi.innerHTML = pc.puzzleIntro();\n\tlet solD = display.solutionDisplay;\n\tsolD.innerHTML =\"\";\n}", "function makePuzzlePieces() {\n // Makes an array of left and right pieces containers names\n let piecesContainer = [\"leftSidePieces\", \"rightSidePieces\"];\n // Based on the puzzle chosen, gets the pieces of that puzzle from Json file\n for (let p = 0; p < puzzles.length; p++) {\n if (puzzleId === puzzles[p].id) {\n // Gets pieces images from Json file and assigns them to an array\n for (let j = 0; j < numPieces; j++) {\n let pieceImage = puzzles[p].pieces[j];\n allPiecesImgAddress.push(pieceImage);\n }\n }\n }\n // Gets the first image address length and assigns to a variable\n firstPieceLength = allPiecesImgAddress[0].length;\n\n // Makes two columns of puzzle pieces and displays them on the sides\n let numPiecesToShow = 0;\n let totalNumPiecesToShow = 24;\n let numPiecesContainers = 2;\n\n // Makes two columns of puzzle pieces\n for (var g = 0; g < numPiecesContainers; g++) {\n // Creates puzzle pieces\n for (let i = numPiecesToShow; i < totalNumPiecesToShow; i++) {\n // Defines a vertical rectangular area of display for the pieces\n displayableAreaHeight = Math.floor(($('.columns').height() / 2));\n displayableAreaWidth = Math.floor($('.columns').width() / 4.5);\n\n // According to the column chosen increases or decreases left border value\n if (g === 0) {\n borderLeft = -30;\n } else if (g === 1) {\n borderLeft = +30;\n }\n\n // Generates random x and y position\n let randPosX = borderLeft + Math.floor((Math.random() * (displayableAreaWidth)));\n let randPosY = Math.floor((Math.random() * (displayableAreaHeight)));\n\n // Gets random image from the array and assigns to the html element\n let pieceImgAddress = getRandomElement(allPiecesImgAddress);\n // Gets the number embeded in the image address in order to be used in the piece id name\n let pieceId = findPieceId(pieceImgAddress);\n // Creates the piece\n let piece = $('<img>').attr({\n id: `piece${pieceId}`,\n src: `${pieceImgAddress}`\n }).appendTo(`#${piecesContainer[g]}`);\n piece.css({\n \"width\": \"4.5vw\",\n \"left\": `${randPosX}px`,\n \"top\": `${randPosY}px`,\n \"position\": \"relative\"\n });\n // Makes it draggable\n piece.draggable();\n // makes an array of pieces\n puzzlePieces.push(piece);\n // Removes the current image from the images array so that it won't be used again\n removeRandomElement(pieceImgAddress);\n }\n // Goes for the next column\n numPiecesToShow += 24;\n totalNumPiecesToShow += 24;\n }\n}", "function auto_arrange() {\n\tpos = jQuery(\"#compoundarea\").offset();\n\tjQuery(\".compound\").each(function() {\n\t\tjQuery(this).css('left', pos.left).css('top', pos.top);\n\t\tpos.left += 215;\n\t\tif (pos.left > jQuery(window).width() - 215) {\n\t\t\tpos.left = jQuery(\"#compoundarea\").offset().left;\n\t\t\tpos.top += 310;\n\t\t}\n\t});\n\tjQuery(\"#compoundarea\").css('height', pos.top + 310);\n}", "function arrangeBoard() {\n\tgBoard = buildBoard();\n\trenderBoard(gBoard);\n\taddPassages(generateNum(1, 3));\n}", "display() {\n\t\tthis.scene.pushMatrix();\n\t\tvar currMaterial = this.scene.pushMaterial(this.material);\n\t\tvar currTexture = this.scene.pushTexture(this.texture);\n\n\t\tcurrMaterial.setTexture(currTexture);\n\t\tcurrMaterial.setTextureWrap('REPEAT', 'REPEAT');\n\t\tcurrMaterial.apply();\n\n\t\tthis.scene.gameOrchestrator.logPicking();\n\t\tfor (let i = 0; i < this.tiles.length; i++) {\n\t\t\tif (this.scene.gameOrchestrator.animator.currentState === this.scene.gameOrchestrator.animator.states.playing)\n\t\t\t\tthis.scene.registerForPick(i + 1, this.tiles[i]);\n\t\t\tthis.tiles[i].display();\n\t\t}\n\t\tthis.scene.clearPickRegistration();\n\n\n\t\tlet pieceXscale = 0.1;\n\t\tlet pieceYscale = 0.01;\n\t\tlet pieceZscale = 0.25;\n\n\t\tlet unusedPieces = 0;\n\t\tfor (let i = 0; i < this.whitePieces.length; i++) {\n\t\t\tthis.scene.pushMatrix();\n\t\t\tif (this.whitePieces[i].getTile() === null) {\n\t\t\t\tthis.scene.translate(2, pieceYscale / 2 + (pieceYscale + 0.001) * unusedPieces, 1);\n\t\t\t\tunusedPieces++;\n\t\t\t}\n\t\t\tthis.whitePieces[i].display();\n\t\t\tthis.scene.popMatrix();\n\t\t}\n\t\tunusedPieces = 0;\n\t\tfor (let i = 0; i < this.blackPieces.length; i++) {\n\t\t\tthis.scene.pushMatrix();\n\t\t\tif (this.blackPieces[i].getTile() === null) {\n\t\t\t\tthis.scene.translate(2, pieceYscale / 2 + (pieceYscale + 0.001) * unusedPieces, -1);\n\t\t\t\tunusedPieces++;\n\t\t\t}\n\t\t\tthis.blackPieces[i].display();\n\t\t\tthis.scene.popMatrix();\n\t\t}\n\n\t\tthis.scene.popTexture();\n\t\tthis.scene.popMaterial();\n\t\tthis.scene.popMatrix();\n\t}", "display() {\n this.scene.pushMatrix();\n\n // Display tile itself\n this.selected ? this.selectedMaterial.apply() : this.material.apply()\n this.plane.display();\n \n if (this.selected)\n this.scene.translate(0,0.2,0);\n\n // Display pieces\n this.scene.pushMatrix();\n for (let i = 0; i < this.pieces.length; i++) {\n this.pieces[i].display();\n this.scene.translate(0, 0.2, 0);\n }\n this.scene.popMatrix();\n\n this.scene.popMatrix();\n }", "function setupPieces(puzzle) {\n\t\tpuzzle.innerHTML = \"\";\n\t\tfor (var i = 1; i <= 15; i++) {\n\t\t\tvar piece = document.createElement(\"div\");\n\t\t\tpiece.className = \"piece normal\";\n\t\t\tpiece.id = \"x\" + i;\n\t\t\tpiece.innerHTML = i;\n\t\t\tpiece.onmouseover = mouseOver;\n\t\t\tpiece.onmouseout = mouseOut;\n\t\t\tpuzzle.appendChild(piece);\n\t\t}\n\n\t}", "display(width, height) {\n const scene = this.orchestrator.getScene();\n\n // compute scale values along x and z directions, in order for the tiles to fit in the given width and height\n const widthScale = width / this.nColumns;\n const heightScale = height / this.nRows;\n\n scene.pushMatrix();\n\n // center and scale board\n scene.translate(- width / 2, 0, - height / 2);\n scene.scale(widthScale, 1, heightScale);\n scene.translate(0.5, 0, 0.5);\n\n // display octagon tiles\n this.octagonTiles.forEach(row => {\n row.forEach(tile => {\n tile.display();\n });\n });\n\n // display square tiles\n this.squareTiles.forEach(row => {\n row.forEach(tile => {\n tile.display();\n });\n });\n\n // display animated pieces\n this.animatedPieces.forEach(piece => {\n piece.display();\n });\n\n // remove animated pieces whose animation has ended\n this.animatedPieces = this.animatedPieces.filter(piece => {\n return !piece.isAnimOver();\n });\n\n\n // displays containers of pieces (place from where new pieces magically appear from)\n const xDif = this.nColumns / 4;\n\n scene.pushMatrix();\n scene.translate(- xDif - 1, 0, 4 * this.nRows / 5 - 0.5);\n scene.graph.templates['pieceContainer'].display();\n scene.graph.templates['octagonPiece'][1].display();\n scene.popMatrix();\n\n\n scene.pushMatrix();\n scene.translate(this.nColumns + xDif, 0, this.nRows / 5 - 0.5);\n scene.graph.templates['pieceContainer'].display();\n scene.graph.templates['octagonPiece'][2].display();\n scene.popMatrix();\n\n scene.popMatrix();\n }", "function drawPieces() {\n\tfor (var row = 0; row < 8; row ++) {\n\t\tfor (var col = 0; col < 8; col ++) {\n\t\t\tif (chess.board[row][col]) {\n\t\t\t\tdrawPiece(chess.board[row][col], row, col);\n\t\t\t}\n\t\t}\n\t}\n\t// Apply rotation if needed\n\tif (chess.options.whiteOnTop) updateTransform();\n}", "function addPieces() {\n\t\tvar bitmap;\n\t\t// blue pieces\n\t\tbitmap = drawPieces(\"blue1\", 508, 249, 55, 550, false);\n\t\tbitmap = drawPieces(\"blue1\", 508, 249, 55, 550, false);\n\t\tbitmap = drawPieces(\"blue2\", 559, 249, 55, 570, false);\n\t\tbitmap = drawPieces(\"blue2\", 559, 249, 55, 570, false);\n\t\tbitmap = drawPieces(\"blue3\", 610, 249, 55, 590, false);\n\t\tbitmap = drawPieces(\"blue3\", 610, 249, 55, 590, false);\n\n\t\t// pink and orange pieces\n\t\tbitmap = drawPieces(\"pink1\", 740, 249, 112, 550, false);\n\t\tbitmap = drawPieces(\"pink1\", 740, 249, 112, 550, false);\n\t\tbitmap = drawPieces(\"orange2\", 740, 312, 112, 570, false);\n\t\tbitmap = drawPieces(\"orange2\", 740, 312, 112, 570, false);\n\n\t\t// green pieces\n\t\tbitmap = drawPieces(\"green1\", 508, 312, 112, 590, false);\n\t\tbitmap = drawPieces(\"green1\", 508, 312, 112, 590, false);\n\t\tbitmap = drawPieces(\"green1\", 508, 312, 112, 590, false);\n\t\tbitmap = drawPieces(\"green2\", 559, 312, 55, 610, false);\n\t\tbitmap = drawPieces(\"green2\", 559, 312, 55, 610, false);\n\t\tbitmap = drawPieces(\"green2\", 559, 312, 55, 610, false);\n\t\tbitmap = drawPieces(\"green3\", 610, 312, 112, 610, false);\n\t\tbitmap = drawPieces(\"green3\", 610, 312, 112, 610, false);\n\t\tbitmap = drawPieces(\"green4\", 662, 312, 55, 630, false);\n\t\tbitmap = drawPieces(\"green4\", 662, 312, 55, 630, false);\n\n\t\t// corner pieces\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\t\tbitmap = drawPieces(\"cornerblue\", 499, 466, 175, 565, false);\n\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\t\tbitmap = drawPieces(\"cornerred\", 583, 466, 255, 565, false);\n\n\t\t// loop and tunnels\n\t\tbitmap = drawPieces(\"loop\", 708, 398, 345, 570, false);\n\t\tbitmap = drawPieces(\"tunnelred\", 672, 443, 0, 0, false);\n\t\tbitmap = drawPieces(\"tunnelpurple\", 672, 465, 0, 0, false);\n\t\t\n\t\t// start and end\n\t\tbitmap = drawPieces(\"start\", 499, 371, 0, 0, false);\n\t\tbitmap = drawPieces(\"end\", 583, 371, 0, 0, false);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the given date as a String formatted as hh:MM:ss
function getTimeString(date) { var hh = ('0' + date.getHours()).slice(-2); var mm = ('0' + date.getMinutes()).slice(-2); var ss = ('0' + date.getSeconds()).slice(-2); return hh + ':' + mm + ':' + ss; }
[ "function dateToString(date) {\n return ((60 * date.getHours()) + date.getMinutes()) + \":\" + date.getSeconds();\n}", "function getTimeString(date) {\n\treturn ('0' + date.getHours()).slice(-2) + \":\" + ('0' + date.getMinutes()).slice(-2) + \":\" + ('0' + date.getSeconds()).slice(-2);\n}", "function date_to_time_str(date) {\n var hours = date.getHours();\n var period = (hours < 12 ? 'am' : 'pm');\n hours = (hours % 12) || 12;\n var minutes = date.getMinutes();\n minutes = (minutes < 10) ? ('0' + minutes) : minutes;\n\n return hours + ':' + minutes + ' ' + period;\n}", "function getTimeStr() {\n var dateObj = new Date();\n var hh = dateObj.getHours();\n var mm = dateObj.getMinutes();\n var timeStr = prepad(hh, 2) + prepad(mm, 2);\n return timeStr;\n}", "function formatTime(date) {\n var hour = date.getHours();\n var minute = date.getMinutes();\n\n hour = (hour < 10 ? '0' : '') + hour.toString();\n minute = (minute < 10 ? '0' : '') + minute.toString();\n\n return hour + ':' + minute;\n}", "function fmtDate(date){\n var res = \"\";\n res = date.substring(0,4)+\"/\"+date.substring(4,6)+\"/\"+date.substring(6,8);\n res = res + \" 06:00:00\";\n return res;\n }", "function getFormattedTime() {\n let time = new Date()\n return strftime(\"%Y-%m-%d %H:%M\", time)\n}", "function formatTimeToHHMMSSString(time) {\n return fillBeginingZero(time.getHours()) + \":\" + fillBeginingZero(time.getMinutes()) + \":\" + fillBeginingZero(time.getSeconds());\n}", "function getFormattedDateTimeHHMMSS(dateObj) {\n var d = new Date(dateObj);\n return getFormattedDate(d) + ' ' + getFormattedTimeHHMMSS(d);\n}", "function getTimeToString(date) {\n const str = date.toLocaleTimeString();\n const array = str.split(\":\").map(str => str.length === 1 ? `0${str}` : str);\n const stringTime = `${array[0]}:${array[1]}`;\n return stringTime;\n }", "function formatTime(date) {\n var hours = String(date.getHours());\n var minutes = String(date.getMinutes());\n\n if (hours.length === 1) {\n hours = '0' + hours;\n }\n\n if (minutes.length === 1) {\n minutes = '0' + minutes;\n }\n\n console.log(hours + ':' + minutes);\n}", "function dateToTimeString(date) {\n\tif (date == null) {\n\t\treturn '';\n\t}\n\t\n\tif (isInvalidDate(date)) {\n\t\treturn 'Invalid Date';\n\t}\n\t\n\tvar hours = date.getHours();\n\tvar minutes = date.getMinutes();\n\tvar minuteString = minutes > 9 ? minutes.toString() : '0' + minutes.toString();\n\t\n\tif (hours > 12) {\n\t\treturn (hours - 12) + ':' + minuteString + ' PM';\n\t} else if (hours == 0) {\n\t \treturn 12 + ':' + minuteString + ' AM';\n\t} else if (hours == 12) {\n\t\treturn 12 + ':' + minuteString + ' PM';\n\t} else {\n\t\treturn hours + ':' + minuteString + ' AM';\n\t}\n}", "_formattedTimeForLogging(date) {\n return colors.datetime(\n ('0' + date.getHours()).slice(-2) +\n ':' +\n ('0' + date.getMinutes()).slice(-2) +\n ':' +\n ('0' + date.getSeconds()).slice(-2));\n }", "formatHHMMSS(value) {\n const date = new Date(value)\n if (value && !isNaN(date)) {\n const hours = date.getHours()\n const minutes = date.getMinutes()\n const seconds = date.getSeconds()\n return this.formatNumber(hours, true) + ':' +\n this.formatNumber(minutes, true) + ':' +\n this.formatNumber(seconds, true)\n }\n return ''\n }", "getFriendlyTime(date) {\n return date.toISOString().replace('T', ' ').slice(0, 19);\n }", "get dateString() {\n var d = new Date();\n\n return `${(\"00\" + (d.getDate())).slice(-2)}/` +\n `${(\"00\" + d.getMonth()).slice(-2)}/` +\n `${d.getFullYear()} - ` +\n `${(\"00\" + d.getHours()).slice(-2)}:` +\n `${(\"00\" + d.getMinutes()).slice(-2)}:` +\n `${(\"00\" + d.getSeconds()).slice(-2)}`;\n }", "function displayDateTime () {\n return `${day}/${month}/${year} ${hour}:${minutes}`;\n}", "timeToString(time) {\n const hour = (time.hour < 10) ? \"0\"+time.hour : time.hour\n const minutes = (time.minutes < 10) ? \"0\"+time.minutes : time.minutes\n const seconds = (time.seconds < 10) ? \"0\"+time.seconds : time.seconds\n return minutes+\":\"+seconds\n //return hour+\":\"+minutes+\":\"+seconds\n }", "function formatTime (date) {\n var mm = '' + date.getMinutes();\n return `${date.getHours()}:${!mm[1] ? '0':''}${mm}`;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes macros against the active keys. Each macro's key combo is checked and if found to be satisfied, the macro's key names are injected into active keys.
function executeMacros() { var mI, combo, kI; for(mI = 0; mI < macros.length; mI += 1) { combo = parseKeyCombo(macros[mI][0]); if(activeMacros.indexOf(macros[mI]) === -1 && isSatisfiedCombo(combo)) { activeMacros.push(macros[mI]); for(kI = 0; kI < macros[mI][1].length; kI += 1) { addActiveKey(macros[mI][1][kI]); } } } }
[ "function prepareMacros(dict_macros, opts) {\n var macros = {};\n\n // expand a `{NAME}` macro which exists inside a `[...]` set:\n function expandMacroInSet(i) {\n var k, a, m;\n if (!macros[i]) {\n m = dict_macros[i];\n\n if (m.indexOf('{') >= 0) {\n // set up our own record so we can detect definition loops:\n macros[i] = {\n in_set: false,\n elsewhere: null,\n raw: dict_macros[i]\n };\n\n for (k in dict_macros) {\n if (dict_macros.hasOwnProperty(k) && i !== k) {\n // it doesn't matter if the lexer recognized that the inner macro(s)\n // were sitting inside a `[...]` set or not: the fact that they are used\n // here in macro `i` which itself sits in a set, makes them *all* live in\n // a set so all of them get the same treatment: set expansion style.\n //\n // Note: make sure we don't try to expand any XRegExp `\\p{...}` or `\\P{...}`\n // macros here:\n if (XRegExp._getUnicodeProperty(k)) {\n // Work-around so that you can use `\\p{ascii}` for a XRegExp slug, a.k.a.\n // Unicode 'General Category' Property cf. http://unicode.org/reports/tr18/#Categories,\n // while using `\\p{ASCII}` as a *macro expansion* of the `ASCII`\n // macro:\n if (k.toUpperCase() !== k) {\n m = new Error('Cannot use name \"' + k + '\" as a macro name as it clashes with the same XRegExp \"\\\\p{..}\" Unicode \\'General Category\\' Property name. Use all-uppercase macro names, e.g. name your macro \"' + k.toUpperCase() + '\" to work around this issue or give your offending macro a different name.');\n break;\n }\n }\n\n a = m.split('{' + k + '}');\n if (a.length > 1) {\n var x = expandMacroInSet(k);\n assert(x);\n if (x instanceof Error) {\n m = x;\n break;\n }\n m = a.join(x);\n }\n }\n }\n }\n\n var mba = setmgmt.reduceRegexToSetBitArray(m, i, opts);\n\n var s1;\n\n // propagate deferred exceptions = error reports.\n if (mba instanceof Error) {\n s1 = mba;\n } else {\n s1 = setmgmt.bitarray2set(mba, false);\n\n m = s1;\n }\n\n macros[i] = {\n in_set: s1,\n elsewhere: null,\n raw: dict_macros[i]\n };\n } else {\n m = macros[i].in_set;\n\n if (m instanceof Error) {\n // this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!\n return new Error(m.message);\n }\n\n // detect definition loop:\n if (m === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n }\n\n return m;\n }\n\n function expandMacroElsewhere(i) {\n var k, a, m;\n\n if (macros[i].elsewhere == null) {\n m = dict_macros[i];\n\n // set up our own record so we can detect definition loops:\n macros[i].elsewhere = false;\n\n // the macro MAY contain other macros which MAY be inside a `[...]` set in this\n // macro or elsewhere, hence we must parse the regex:\n m = reduceRegex(m, i, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);\n // propagate deferred exceptions = error reports.\n if (m instanceof Error) {\n return m;\n }\n\n macros[i].elsewhere = m;\n } else {\n m = macros[i].elsewhere;\n\n if (m instanceof Error) {\n // this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!\n return m;\n }\n\n // detect definition loop:\n if (m === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n }\n\n return m;\n }\n\n function expandAllMacrosInSet(s) {\n var i, x;\n\n // process *all* the macros inside [...] set:\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n x = expandMacroInSet(i);\n assert(x);\n if (x instanceof Error) {\n return new Error('failure to expand the macro [' + i + '] in set [' + s + ']: ' + x.message);\n }\n s = a.join(x);\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n function expandAllMacrosElsewhere(s) {\n var i, x;\n\n // When we process the remaining macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will expand any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n // These are all submacro expansions, hence non-capturing grouping is applied:\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n x = expandMacroElsewhere(i);\n assert(x);\n if (x instanceof Error) {\n return new Error('failure to expand the macro [' + i + '] in regex /' + s + '/: ' + x.message);\n }\n s = a.join('(?:' + x + ')');\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n var m, i;\n\n if (opts.debug) console.log('\\n############## RAW macros: ', dict_macros);\n\n // first we create the part of the dictionary which is targeting the use of macros\n // *inside* `[...]` sets; once we have completed that half of the expansions work,\n // we then go and expand the macros for when they are used elsewhere in a regex:\n // iff we encounter submacros then which are used *inside* a set, we can use that\n // first half dictionary to speed things up a bit as we can use those expansions\n // straight away!\n for (i in dict_macros) {\n if (dict_macros.hasOwnProperty(i)) {\n expandMacroInSet(i);\n }\n }\n\n for (i in dict_macros) {\n if (dict_macros.hasOwnProperty(i)) {\n expandMacroElsewhere(i);\n }\n }\n\n if (opts.debug) console.log('\\n############### expanded macros: ', macros);\n\n return macros;\n}", "function checkMacros() {\n\n\t_.each(macros,function(macroName){\n\n\t\tvar macro = findObjs({_type: \"macro\", name: macroName})[0];\n \tvar playerList = findObjs({_type: \"player\"});\n\t\tvar playerID = playerList[0].id;\n\t\tvar GMFound = false;\n\t\t\n\t\t_.find(playerList,function(player){ \n var thisID = player.id;\n if(playerIsGM(thisID)){\n playerID = thisID;\n return thisID;\n }\n });\n\t\t\n var GMid = playerID;\n\n\t\tif(!macro) {\n\t\t\tswitch(macroName) {\n\t\t\t\tcase \"Saves\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n break;\n\t\t\t\tcase \"ScatterDie\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ScatterDie ?{Ballistic Skill|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToPen\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToWound\":\n\t\t\t\t\tcreateObj('macro', {name: macroName, action: \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\", visibleto: \"all\", playerid: GMid, istokenaction: false});\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n \n\t\t\tswitch(macroName) {\n\t\t\t\tcase \"Saves\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k Saves ?{Roll How Many Dice?|0} ?{Saves on a What?|0} ?{Feel No Pain of?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ScatterDie\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ScatterDie ?{Ballistic Skill|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ScatterDie ?{Ballistic Skill|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToPen\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ToHitToPen ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Strength?|0} ?{Against Armor?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"ToHitToWound\":\n\t\t\t\t\tif (macro.get(\"action\") != \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\") {\n\t\t\t\t\t\tmacro.set(\"action\", \"!40k ToHitToWound ?{Roll How Many Dice?|0} ?{Hits on a What?|0} ?{Wounds on a What?|0}\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t});\n}", "function pruneMacros() {\n\t\tvar mI, combo, kI;\n\t\tfor(mI = 0; mI < activeMacros.length; mI += 1) {\n\t\t\tcombo = parseKeyCombo(activeMacros[mI][0]);\n\t\t\tif(isSatisfiedCombo(combo) === false) {\n\t\t\t\tfor(kI = 0; kI < activeMacros[mI][1].length; kI += 1) {\n\t\t\t\t\tremoveActiveKey(activeMacros[mI][1][kI]);\n\t\t\t\t}\n\t\t\t\tactiveMacros.splice(mI, 1);\n\t\t\t\tmI -= 1;\n\t\t\t}\n\t\t}\n\t}", "function keymap(bindings, platform) {\n return [handleKeyEvents, keymaps.of(buildKeymap(bindings, platform))];\n} /// Run the key handlers registered for a given scope. Returns true if", "function checkMacros() {\n const playerList = findObjs({ _type: 'player', _online: true });\n const gm = playerList.find((player) => {\n return playerIsGM(player.id) === true;\n });\n const macroArr = [\n {\n name: 'PaladinAuraHelp',\n action: `${apiCall} help`\n },\n {\n name: 'PaladinAuraToggle',\n action: `${apiCall}`\n },\n {\n name: 'PaladinAuraConfig',\n action: `${apiCall} config`\n }\n ];\n macroArr.forEach((macro) => {\n const macroObj = findObjs({\n _type: 'macro',\n name: macro.name\n })[0];\n if (macroObj) {\n if (macroObj.get('visibleto') !== 'all') {\n macroObj.set('visibleto', 'all');\n toChat(`**Macro '${macro.name}' was made visible to all.**`, true);\n }\n if (macroObj.get('action') !== macro.action) {\n macroObj.set('action', macro.action);\n toChat(`**Macro '${macro.name}' was corrected.**`, true);\n }\n }\n else if (gm && playerIsGM(gm.id)) {\n createObj('macro', {\n _playerid: gm.id,\n name: macro.name,\n action: macro.action,\n visibleto: 'all'\n });\n toChat(`**Macro '${macro.name}' was created and assigned to ${gm.get('_displayname') + ' '.split(' ', 1)[0]}.**`, true);\n }\n });\n }", "static fireMatchingAction(keys, isFocused) {\n // Figure out the LATEST active action with the LONGEST set of matching keys.\n let bestMatch, bestMatchLength = 0;\n for (let id in Action.ACTIVE_ACTIONS) {\n const action = Action.ACTIVE_ACTIONS[id];\n const match = action.matchKeys(keys, isFocused);\n if (match && match.length >= bestMatchLength) {\n bestMatch = action;\n bestMatchLength = match.length;\n }\n }\n\n if (!bestMatch) return false;\n\n try {\n bestMatch.execute();\n return true;\n } catch (e) {\n console.error(`Error firing action ${bestMatch.id}`, e);\n throw e;\n }\n }", "static updateMacros() {\n let macros = game.macros.filter(e => e.visible);\n\n macros.forEach((macro) => {\n let data = duplicate(macro);\n data.command = data.command.replace(/game\\.questlog\\./g, 'QuestLog.');\n data.command = data.command.replace(/game\\.quests\\./g, 'Quests.');\n\n macro.update(data);\n });\n }", "static updateShortcutMacros() {\n let players = findObjs({\n _type: 'player'\n });\n let gms = _.filter(players, player => {\n return playerIsGM(player.get('_id'));\n });\n\n let macrosNames = _.keys(MACRO_SHORTCUTS);\n _.each(macrosNames, name => {\n let macro = findObjs({\n _type: 'macro',\n name\n })[0];\n\n let action = MACRO_SHORTCUTS[name].replace('EFFECT_NAME',\n AreasOfEffect.Macros.getEffectNamePrompt());\n\n if(macro)\n macro.set('action', action);\n else {\n createObj('macro', {\n _playerid: gms[0].get('_id'),\n name,\n action,\n visibleto: 'all'\n });\n }\n });\n }", "function generateCompletionKeys(keysToCheck) {\n var splitHash = splitKeyQueue(keysToCheck || keyQueue);\n command = splitHash.command;\n count = splitHash.count;\n\n var completionKeys = singleKeyCommands.slice(0);\n\n if (getActualKeyStrokeLength(command) == 1)\n {\n for (var key in Commands.keyToCommandRegistry)\n {\n var splitKey = splitKeyIntoFirstAndSecond(key);\n if (splitKey.first == command)\n completionKeys.push(splitKey.second);\n }\n }\n\n return completionKeys;\n}", "function enableKeys() {\n active = true;\n _(keys).each(function(key) {\n key.enable();\n });\n api.alert(\"Phoenix\", 0.5);\n}", "defineKeys() {\n if (arguments.length <= 1) {\n throw new Error('Too few arguments');\n }\n\n if (arguments.length % 3 != 1) {\n throw new Error('Wrong number of arguments');\n }\n\n // key mode is the first arg\n const key = this.key;\n const ext = this.ext;\n const args = Array.prototype.slice.call(arguments);\n const keyMode = args[0];\n\n // the rest are the pair of key bindings\n args.splice(0, 1);\n const makeHandler = function(command){\n return function(args) {\n ext.exec(command, args);\n }\n };\n\n for(var i = 0; i < args.length; i+=3) {\n const keyStroke = args[i];\n const command = args[i+1];\n const desc = args[i+2];\n key.defineKey([keyMode], keyStroke, makeHandler(command), desc);\n }\n }", "function _triggerKeyupEvents(key = false) {\n\t\t_KeyboardUpUIBoxes.eachItem(function(uiBoxData) {\n\t\t\tif( uiBoxData.box.hasKey(key) ) {\n\t\t\t\tuiBoxData.callback(key);\n\t\t\t}\n\t\t});\n\t}", "static installMacros() {\n let players = findObjs({\n _type: 'player'\n });\n\n const Commands = CustomStatusMarkers.Commands;\n\n // Create the macro, or update the players' old macro if they already have it.\n _.each(players, player => {\n _installMacro(player, 'CustomStatusMarkersMenu', Commands.MENU_CMD);\n _installMacro(player, 'CustomStatusMarkersToggle', Commands.SET_MARKER_CMD + ' ' + _getEffectNamePrompt());\n _installMacro(player, 'CustomStatusMarkersToggleCount', Commands.SET_MARKER_COUNT_CMD + ' ' + _getEffectNamePrompt() + ' ?{count}');\n _installMacro(player, 'CustomStatusMarkersToggleTint', Commands.SET_MARKER_TINT_CMD + ' ' + _getEffectNamePrompt() + ' ?{color}');\n });\n }", "async _runMacro(macro) {\n let subCommandsStatus = [];\n for (let line of macro.subCommands) {\n line = parseConstants(line, this.constants);\n line = parseMacroSubCommand(line, macro.args);\n subCommandsStatus.push(await this._execute(line));\n }\n return subCommandsStatus;\n }", "function setAvailableKeys() {\n for (var x = 0; x < vm.inputActions.length; x++) {\n var selectedAction = vm.inputActions[x];\n selectedAction.keys = getAvailableKeys(selectedAction.key);\n }\n }", "function expandMacros(src, macros, opts) {\n var expansion_count = 0;\n\n // By the time we call this function `expandMacros` we MUST have expanded and cached all macros already!\n // Hence things should be easy in there:\n\n function expandAllMacrosInSet(s) {\n var i, m, x;\n\n // process *all* the macros inside [...] set:\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n x = m.in_set;\n\n assert$1(x);\n if (x instanceof Error) {\n // this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!\n throw x;\n }\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join(x);\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n function expandAllMacrosElsewhere(s) {\n var i, m, x;\n\n // When we process the main macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will expand any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n // These are all main macro expansions, hence CAPTURING grouping is applied:\n x = m.elsewhere;\n assert$1(x);\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join('(' + x + ')');\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n\n // When we process the macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will have expanded any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n var s2 = reduceRegex(src, null, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);\n // propagate deferred exceptions = error reports.\n if (s2 instanceof Error) {\n throw s2;\n }\n\n // only when we did expand some actual macros do we take the re-interpreted/optimized/regenerated regex from reduceRegex()\n // in order to keep our test cases simple and rules recognizable. This assumes the user can code good regexes on his own,\n // as long as no macros are involved...\n //\n // Also pick the reduced regex when there (potentially) are XRegExp extensions in the original, e.g. `\\\\p{Number}`,\n // unless the `xregexp` output option has been enabled.\n if (expansion_count > 0 || (src.indexOf('\\\\p{') >= 0 && !opts.options.xregexp)) {\n src = s2;\n } else {\n // Check if the reduced regex is smaller in size; when it is, we still go with the new one!\n if (s2.length < src.length) {\n src = s2;\n }\n }\n\n return src;\n}", "function expandMacros(src, macros, opts) {\n var expansion_count = 0;\n\n // By the time we call this function `expandMacros` we MUST have expanded and cached all macros already!\n // Hence things should be easy in there:\n\n function expandAllMacrosInSet(s) {\n var i, m, x;\n\n // process *all* the macros inside [...] set:\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n var x = m.in_set;\n\n assert(x);\n if (x instanceof Error) {\n // this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!\n throw x;\n }\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join(x);\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n function expandAllMacrosElsewhere(s) {\n var i, m, x;\n\n // When we process the main macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will expand any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n // These are all main macro expansions, hence CAPTURING grouping is applied:\n x = m.elsewhere;\n assert(x);\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join('(' + x + ')');\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n\n // When we process the macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will have expanded any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n var s2 = reduceRegex(src, null, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);\n // propagate deferred exceptions = error reports.\n if (s2 instanceof Error) {\n throw s2;\n }\n\n // only when we did expand some actual macros do we take the re-interpreted/optimized/regenerated regex from reduceRegex()\n // in order to keep our test cases simple and rules recognizable. This assumes the user can code good regexes on his own,\n // as long as no macros are involved...\n //\n // Also pick the reduced regex when there (potentially) are XRegExp extensions in the original, e.g. `\\\\p{Number}`,\n // unless the `xregexp` output option has been enabled.\n if (expansion_count > 0 || (src.indexOf('\\\\p{') >= 0 && !opts.options.xregexp)) {\n src = s2;\n } else {\n // Check if the reduced regex is smaller in size; when it is, we still go with the new one!\n if (s2.length < src.length) {\n src = s2;\n }\n }\n\n return src;\n}", "function expandMacros(src, macros, opts) {\n var expansion_count = 0;\n\n // By the time we call this function `expandMacros` we MUST have expanded and cached all macros already!\n // Hence things should be easy in there:\n\n function expandAllMacrosInSet(s) {\n var i, m, x;\n\n // process *all* the macros inside [...] set:\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n x = m.in_set;\n\n assert(x);\n if (x instanceof Error) {\n // this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!\n throw x;\n }\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join(x);\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n function expandAllMacrosElsewhere(s) {\n var i, m, x;\n\n // When we process the main macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will expand any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n if (s.indexOf('{') >= 0) {\n for (i in macros) {\n if (macros.hasOwnProperty(i)) {\n m = macros[i];\n\n var a = s.split('{' + i + '}');\n if (a.length > 1) {\n // These are all main macro expansions, hence CAPTURING grouping is applied:\n x = m.elsewhere;\n assert(x);\n\n // detect definition loop:\n if (x === false) {\n return new Error('Macro name \"' + i + '\" has an illegal, looping, definition, i.e. it\\'s definition references itself, either directly or indirectly, via other macros.');\n }\n\n s = a.join('(' + x + ')');\n expansion_count++;\n }\n\n // stop the brute-force expansion attempt when we done 'em all:\n if (s.indexOf('{') === -1) {\n break;\n }\n }\n }\n }\n\n return s;\n }\n\n // When we process the macro occurrences in the regex\n // every macro used in a lexer rule will become its own capture group.\n //\n // Meanwhile the cached expansion will have expanded any submacros into\n // *NON*-capturing groups so that the backreference indexes remain as you'ld\n // expect and using macros doesn't require you to know exactly what your\n // used macro will expand into, i.e. which and how many submacros it has.\n //\n // This is a BREAKING CHANGE from vanilla jison 0.4.15!\n var s2 = reduceRegex(src, null, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);\n // propagate deferred exceptions = error reports.\n if (s2 instanceof Error) {\n throw s2;\n }\n\n // only when we did expand some actual macros do we take the re-interpreted/optimized/regenerated regex from reduceRegex()\n // in order to keep our test cases simple and rules recognizable. This assumes the user can code good regexes on his own,\n // as long as no macros are involved...\n //\n // Also pick the reduced regex when there (potentially) are XRegExp extensions in the original, e.g. `\\\\p{Number}`,\n // unless the `xregexp` output option has been enabled.\n if (expansion_count > 0 || src.indexOf('\\\\p{') >= 0 && !opts.options.xregexp) {\n src = s2;\n } else {\n // Check if the reduced regex is smaller in size; when it is, we still go with the new one!\n if (s2.length < src.length) {\n src = s2;\n }\n }\n\n return src;\n}", "static installMacros() {\n let players = findObjs({\n _type: 'player'\n });\n\n const Commands = MarchingOrder.Commands;\n\n // Create the macro, or update the players' old macro if they already have it.\n _.each(players, player => {\n _installMacro(player, 'MarchingOrderMenu', Commands.MENU_CMD);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7.3 Operations on Objects 7.3.1 Get (O, P) just use o.p or o[p] 7.3.2 GetV (V, P)
function GetV(v, p) { var o = ToObject(v); return o[p]; }
[ "function GetV(v, p) { // eslint-disable-line no-unused-vars\n\t\t// 1. Assert: IsPropertyKey(P) is true.\n\t\t// 2. Let O be ? ToObject(V).\n\t\tvar o = ToObject(v);\n\t\t// 3. Return ? O.[[Get]](P, V).\n\t\treturn o[p];\n\t}", "function GetV(v, p) { // eslint-disable-line no-unused-vars\n\t// 1. Assert: IsPropertyKey(P) is true.\n\t// 2. Let O be ? ToObject(V).\n\tvar o = ToObject(v);\n\t// 3. Return ? O.[[Get]](P, V).\n\treturn o[p];\n}", "function Get(O, P) {\n /** 1. Let desc be the result of calling the [[GetProperty]] internal method of O with property name P. */\n desc := GetProperty(O, P);\n\n /** 2. If desc is undefined, return undefined. */\n if (desc = undefined) {\n return undefined;\n };\n\n /** 3. If IsDataDescriptor(desc) is true, return desc.[[Value]]. */\n if (IsDataPropertyDescriptor(desc)) {\n return desc.Value\n }\n /** 4. Otherwise, IsAccessorDescriptor(desc) must be true so, let getter be desc.[[Get]]. */\n else {\n getter := desc.Get;\n\n /** 5. If getter is undefined, return undefined. */\n if (getter = undefined) {\n return undefined\n };\n\n /** 6. Return the result calling the[[Call]] internal method of getter providing O as the this value and providing no arguments. */\n return Call(getter, O)\n }\n}", "function GetProperty (O, P) {\n /** 1. Let prop be the result of calling the [[GetOwnProperty]] internal method of O with property name P. */\n prop := GetOwnProperty(O, P);\n\n /** 2. If prop is not undefined, return prop. */\n if (!(prop = undefined)) {\n return prop\n };\n\n /** 3. Let proto be the value of the [[Prototype]] internal property of O. */\n proto := O.Prototype;\n\n /** 4. If proto is null, return undefined. */\n if (proto = null) {\n return undefined\n };\n\n /** 5. Return the result of calling the [[GetProperty]] internal method of proto with argument P. */\n return GetProperty(proto, P)\n}", "value(p,v) {\n\t\tif (v) this.#value[p] = v;\n\t\treturn this.#value[p];\n\t}", "function get(target, propertyKey /* , receiver */) {\n var receiver = arguments.length < 3 ? target : arguments[2];\n var desc, proto;\n if (_anObject(target) === receiver) return target[propertyKey];\n if (desc = _objectGopd.f(target, propertyKey)) return _has(desc, 'value')\n ? desc.value\n : desc.get !== undefined\n ? desc.get.call(receiver)\n : undefined;\n if (_isObject(proto = _objectGpo(target))) return get(proto, propertyKey, receiver);\n }", "function get(object, prop) {\n var propVal = null;\n if (object.hasOwnProperty(prop)) {\n propVal = object[prop];\n }\n else if (typeof object[\"get\"] == \"function\") {\n propVal = object.get(prop);\n }\n return propVal;\n }", "function getProperty(o, s) {\n s = s.replace(/\\[(\\w+)\\]/g, '.$1'); // convert indexes to properties\n s = s.replace(/^\\./, ''); // strip a leading dot\n var a = s.split('.');\n while (a.length) {\n var n = a.shift();\n if (n in o) {\n o = o[n];\n } else {\n return;\n }\n }\n return o;\n}", "function get(target, propertyKey /* , receiver */) {\n var receiver = arguments.length < 3 ? target : arguments[2];\n var desc, proto;\n if (_anObject(target) === receiver) return target[propertyKey];\n if (desc = _objectGopd.f(target, propertyKey)) return _has(desc, 'value')\n ? desc.value\n : desc.get !== undefined\n ? desc.get.call(receiver)\n : undefined;\n if (_isObject(proto = _objectGpo(target))) return get(proto, propertyKey, receiver);\n}", "function PrivateFieldGet(P, O) {\r\n const field = PrivateFieldFind(P, O);\r\n if (!field) {\r\n throw new TypeError(\r\n `Cannot read private member ${P.description} from an object ` +\r\n `whose class did not declare it`\r\n );\r\n }\r\n return field[\"[[PrivateFieldValue]]\"];\r\n}", "function get(obj, path) {\n var tmp = obj;\n for (var _i = 0, path_2 = path; _i < path_2.length; _i++) {\n var part = path_2[_i];\n tmp = tmp[part];\n if (!tmp) {\n return undefined;\n }\n }\n return tmp;\n}", "function searchGet(key, obj)\n{\n obj || (obj=this);\n\n var value;\n var Key=key.charAt(0).toUpperCase() + key.substring(1);\n var accessor;\n\n if((accessor=(\"get\" + Key)) in obj)\n {\n var fn=obj[accessor];\n\n value=fn.call(obj);\n }\n // else if((\"is\" + Key) in obj)\n // {\n // value=obj.isKey();\n // }\n // else if((\"_\" + key) in obj)\n // {\n // value=obj[\"_\" + key];\n // }\n // else if((\"_is\" + Key) in obj)\n // {\n // value=obj[\"_is\" + key];\n // }\n // else// if((key in obj))\n // {\n // value=obj[key];\n // }\n else {\n value=ivarGet(key, obj);\n }\n\n return value;\n}", "function get(object, key) {\n return object[key];\n}", "function get(object, name) {\n return object[name];\n}", "function prop(name, obj) {\r\n return obj[name]\r\n}", "function prop(key, index, data) {\n return _this.getProperty(key, data, index);\n }", "get p() { return this.p_val;}", "getPropertyValue(object, key, opId) {\n if (object instanceof Table) {\n return object.byId(key)\n } else if (object instanceof Text) {\n return object.get(key)\n } else {\n return object[CONFLICTS][key][opId]\n }\n }", "get(prop) {\n return this.data[prop];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the key should be vertical or horizontal
function getKeyOrientation() { var keyOrientation; if (width > Configuration.SMALL_BREAKPOINT && options.keyType == "scalar") { keyOrientation = "vertical"; } else { keyOrientation = "horizontal"; } return keyOrientation; }
[ "get isHorizontal() {\n return true;\n }", "get isHorizontal() {\n return true;\n }", "function isHorizontal(dir){return dir==='left-to-right'||dir==='right-to-left';}", "determineOrientation(event) {\n var key = event.keyCode;\n var vertical = this.tablist.getAttribute('aria-orientation') == 'vertical';\n var proceed = false;\n\n if (vertical) {\n if (key === keys.up || key === keys.down) {\n event.preventDefault();\n proceed = true;\n };\n }\n else {\n if (key === this.keys.left || key === this.keys.right) {\n proceed = true;\n };\n };\n\n if (proceed) {\n this.switchTabOnArrowPress(event);\n };\n }", "isDirectionKey(i) {\n return i === 'ArrowUp' || i === 'ArrowDown' || i === 'ArrowRight' || i === 'ArrowLeft' || i === 'Tab';\n }", "function checkControlOrientation(scope){\n scope.control.isVertical = scope.control.height > scope.control.width;\n scope.control.isHorizontal = !scope.control.isVertical;\n\n if (scope.view.turnView){\n scope.control.isVertical = !scope.control.isVertical;\n scope.control.isHorizontal = !scope.control.isHorizontal;\n }\n }", "function key(key){\r\n\t\r\n\tswitch(key)\r\n\t{\r\n\t\r\n\t\tcase \"left arrow\": this.code=37; break;\r\n\t\tcase \"up arrow\": this.code=38; break; \r\n\t\tcase \"right arrow\": this.code=39; break; \r\n\t\tcase \"down arrow\": this.code=40; break; \r\n\t\tcase \"x\": this.code=88; break;\r\n\t\tcase \"y\": this.code=89; break;\r\n\t\tcase \"z\": this.code=90; break;\r\n\t\t\r\n\t default: this.code=0;\r\n\t}\r\n\tif (keys[this.code]) return true;\r\n\t\r\n\t\r\n}", "function getRealDirection(key) {\n if (key === up_key)\n return 'UP';\n if (key === down_key)\n return 'DOWN';\n if (key === left_key || typeof (key) === 'undefined')\n return 'LEFT';\n if (key === right_key)\n return 'RIGHT';\n}", "function isHorizontal(dir) {\r\n return dir === 'left-to-right' || dir === 'right-to-left';\r\n }", "orientation(newX, newY, oldX, oldY) {\n if (newY > oldY) return 'up'\n if (newY < oldY) return 'down'\n if (newX > oldX) return 'right'\n return 'left'\n }", "function isHorizontal(dir) {\n return dir === 'left-to-right' || dir === 'right-to-left';\n }", "_isParentVertical() {\n return this._parentMenu?.orientation === 'vertical';\n }", "getOrientation(tiles) {\n let [firstTileRow, firstTileCol] = tiles[0];\n let [isHorizontal, isVertical] = [true, true];\n for (let i = 1; i < tiles.length; i++) {\n let [row, col] = tiles[i];\n if (row !== firstTileRow) {\n isHorizontal = false;\n }\n if (col !== firstTileCol) {\n isVertical = false;\n }\n }\n if (isHorizontal || isVertical) {\n return isHorizontal ? 'horizontal' : 'vertical';\n }\n else {\n return '';\n }\n }", "function determineOrientation(event) {\n var key = event.keyCode;\n var vertical = tablist.getAttribute('aria-orientation') == 'vertical';\n var proceed = false;\n\n if (vertical) {\n if (key === keys.up || key === keys.down) {\n event.preventDefault();\n proceed = true;\n };\n } else {\n if (key === keys.left || key === keys.right) {\n proceed = true;\n };\n };\n\n if (proceed) {\n switchTabOnArrowPress(event);\n };\n }", "get __shouldPosition() {\n return (this.horizontalAlign || this.verticalAlign) &&\n (this.horizontalAlign !== 'center' || this.verticalAlign !== 'middle');\n }", "checkKeys() {\n if (this.gui.isKeyPressed(\"KeyD\")) {\n this.camera.rotate(CGFcameraAxis.Y, -0.05);\n }\n if (this.gui.isKeyPressed(\"KeyA\")) {\n this.camera.rotate(CGFcameraAxis.Y, 0.05);\n }\n if (this.gui.isKeyPressed(\"KeyW\")) {\n this.camera.rotate(CGFcameraAxis.X, -0.05);\n }\n if (this.gui.isKeyPressed(\"KeyS\")) {\n this.camera.rotate(CGFcameraAxis.X, 0.05);\n }\n }", "static get horizontal() { return this.rtl; }", "_getLayoutType() {\n const that = this,\n orientation = that.orientation,\n inverted = that.inverted,\n rightToLeft = that.rightToLeft;\n\n that._normalLayout = orientation === 'horizontal' && ((!inverted && !rightToLeft) || (rightToLeft && inverted)) ||\n orientation === 'vertical' && inverted;\n }", "get a11yKeyIsPressed() {\n return this.f6KeyIsPressed ||\n this.upArrowKeyIsPressed ||\n this.downArrowKeyIsPressed ||\n this.tabKeyIsPressed ||\n this.tildeKeyIsPressed ||\n this.lKeyIsPressed;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
enters current date to html inputs
function enterCurrentDateToHTML() { currentDate = Date.now(); dateIn.value = date; }
[ "function currentDate() {\n\n var today = new Date();\n\n var dd = today.getDate();\n\n var mm = today.getMonth() + 1;\n var yyyy = today.getFullYear();\n if (dd < 10) {\n dd = '0' + dd;\n }\n\n if (mm < 10) {\n mm = '0' + mm;\n }\n\n today = yyyy + '-' + mm + '-' + dd;\n\n var dateInput = document.getElementById(\"pickupDate\");\n dateInput.value = today;\n}", "function setTheDate() {\r\n 'use strict';\r\n $(\"today\").value = month + \"/\" + day + \"/\" + year;\r\n}", "function setDate()\n{\n var today = new Date();\n var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();\n\n document.getElementsByClassName(\"form-date\").value = date;\n}", "function setCurrentDate(field){\n var now = new Date();\n var day = (\"0\" + now.getDate()).slice(-2);\n var month = (\"0\" + (now.getMonth() + 1)).slice(-2);\n var today = now.getFullYear()+\"-\"+(month)+\"-\"+(day);\n $(field).val(today);\n}", "function updateInputValue() {\n inputField.value = formatDate(currentDateTime, 'full');\n }", "function insertCurrentDate(id) {\n\t$('#'+id).val(getCurrentDate());\n}", "function today() {\n\t\t\t var date1 = new Date().toISOString().substring(0, 10),\n\t\t\t field = document.querySelector('#lobsterDate');\n\t\t\t field.value = date1;\n\t\t\t\t var date2 = new Date().toISOString().substring(0, 10),\n\t\t\t field = document.querySelector('#fishDate');\n\t\t\t field.value = date2;\t\t\t\n\t\t\t}", "function set_todays_date() {\n // Set today's date\n const zeropadding = (n) => (n < 10 ? `0${n}` : `${n}`);\n const date = new Date();\n const month = zeropadding(date.getMonth() + 1);\n const day = zeropadding(date.getDate());\n const year = date.getFullYear();\n const date_input = document.getElementById('date');\n date_input.value = `${year}-${month}-${day}`;\n}", "function initDateInput() {\n\tlet dateInput = document.getElementById(\"dateInput\");\n\tlet d = new Date();\n\tdateInput.value = d.getFullYear() + \"-\" +\n\t\tlz(Number(d.getMonth()+1)) + \"-\" +\n\t\tlz(d.getDate());\n}", "setTodayDate(dateObj){\n const dateField = document.querySelector('.date-field');\n let month = this.padZero(dateObj.month);\n let day = this.padZero(dateObj.day);\n dateField.value = `${dateObj.year}-${month}-${day}`;\n }", "function _updateDate($this) {\n\n function _suffix(n) { // returns the appropriate suffix\n return [null, 'st', 'nd', 'rd', 'th'][n] || \"th\";\n }\n\n var data = $this.data(store);\n\n $this.html(months[month].toProperCase() + \" \" + day + _suffix(day) + \", \" + year); // Visible date\n\n var datetime = year+\"/\"+_zeroPad(month+1, 2)+\"/\"+day;\n $this.attr(\"datetime\", datetime); // Tag's date\n data.$input.val(datetime.replace(/\\//g, \"-\")); // Hidden input's date\n }", "function editEnterDate() {\n\t\t\treturn this.editEnter('date');\n\t\t}", "function dateInput() {\n var e = document.createElement('input');\n e.type = 'text';\n e.size = '6';\n e.style.cssText = 'margin-top: 1px;' +\n 'margin-left: 5px;' +\n 'display: table-cell;' +\n 'vertical-align: top;';\n e.value = dateString(-1); // yesterday\n return e;\n }", "function myDate() \n\t\t{\n\t\t\tvar d = new Date();\n\t\t\t//The current date is saved to the date string\n\t\t\tdocument.getElementById(\"date\").innerHTML = d.toDateString();\n\t\t}", "function _updateDate($this) {\n\n function _suffix(n) { // returns the appropriate suffix\n return [null, 'st', 'nd', 'rd', 'th'][n] || \"th\";\n }\n\n var data = $this.data(store);\n\n $this.html(months[month].toProperCase() + \" \" + day + _suffix(day) + \", \" + year); // Visible date\n\n var datetime = year + \"/\" + _zeroPad(month + 1, 2) + \"/\" + day;\n $this.attr(\"datetime\", datetime); // Tag's date\n data.$input.val(datetime.replace(/\\//g, \"-\")); // Hidden input's date\n }", "function GetCurrDate(objId)\r\n{\r\n var today = new Date().getFullYear() + \"-\";\r\n if ( new Date().getMonth() < 9 )\r\n {\r\n today += \"0\" + ( new Date().getMonth() + 1 );\r\n }\r\n else\r\n {\r\n today += new Date().getMonth() + 1;\r\n }\r\n today += \"-\";\r\n if ( new Date().getDate() < 10 )\r\n {\r\n today += \"0\" + new Date().getDate();\r\n }\r\n else\r\n {\r\n today += new Date().getDate();\r\n }\r\n document.getElementById(objId).value = today;\r\n}", "function initDate(){\n var date = new Date();\n var day = date.getDate();\n var month = date.getMonth() + 1;\n var year = date.getFullYear();\n\n if (month < 10) month = \"0\" + month;\n if (day < 10) day = \"0\" + day;\n\n var today = year + \"-\" + month + \"-\" + day; \n $(\"#story-date\").attr(\"value\", today);\n}", "function getSelectedDate() {\n\tvar year = document.querySelector('form [name=\"year\"]').value;\n\tvar month = document.querySelector('form [name=\"month\"]').value;\n\tif(month < 10) month = '0' + month;\n\tvar day = document.querySelector('form [name=\"day\"]').value;\n\tif(day < 10) day = '0' + day;\n\treturn year + '-' + month + '-' + day;\n}", "function fillEntryDate() {\n document.getElementById('entry-date').innerHTML = `Date: ${newDate}`;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predefined classes ////////////////////////////////////////////////////////////////////////////// Monad
function base$GHC$Base$Monad(return_,bind_){ this.return_ = return_, this.bind_ = bind_; }
[ "function Monad(){}", "static of(val) {\n return new Monad(val)\n }", "function Motors(numsOrObjects) {\n\t if (!(this instanceof Motors)) {\n\t return new Motors(numsOrObjects);\n\t }\n\n\t Object.defineProperty(this, \"type\", {\n\t value: Motor\n\t });\n\n\t Collection.call(this, numsOrObjects);\n\t}", "function Monad(name, context, root) {\n this.name = name;\n this.root = root || SCRIPT_BASE_URL;\n this.afterRenderCalls = {};\n\n if (context) {\n this.context = context;\n }\n }", "function isMonad(v) {\n\tvar fmFunc = (\n\t\t(\n\t\t\tv &&\n\t\t\t(typeof v == \"object\" || isFunction(v))\n\t\t) ?\n\t\t\tgetMonadFlatMap(v) :\n\t\t\tundefined\n\t);\n\n\treturn !!(\n\t\t// was a flatMap/bind/chain function found?\n\t\tfmFunc &&\n\n\t\t// but make sure it's not one of the known built-in\n\t\t// prototype methods\n\t\t!builtInFunctions.has(fmFunc) &&\n\n\t\t// also try to avoid any unknown built-in prototype\n\t\t// methods\n\t\t(\n\t\t\t!((fmFunc.toString() || \"\").includes(\"[native code]\")) ||\n\t\t\t((fmFunc.name || \"\").startsWith(\"bound\"))\n\t\t)\n\t);\n}", "function monad(unit){\n return function unit(value){\n var monad = Object.create(null)\n monad.bind = function(func){ return func(value) }\n return monad ;\n }\n}", "function ClassManager() {}", "function AJAXMONAD() {\n\n\tvar prototype = Object.create(null);\n\n\tfunction unit(value) {\n\t\tvar monad = Object.create(prototype);\n\t\tmonad.bind = function(func, args) {\n\t\t\treturn func(value, ...args);\n\t\t};\n\t\treturn monad;\n\t}\n\n\tunit.lift = function(name, func) {\n\t\tprototype[name] = function(...args) {\n\t\t\t// 'this' is the monad\n\t\t\treturn unit(this.bind(func, args));\n\t\t}\n\t\treturn unit;\n\t};\n\n\treturn unit;\n\n}", "function OpenClass(pkg, meta, that){\n $init$OpenClass();\n if (that===undefined)that=new OpenClass.$$;\n that._pkg = pkg;\n var _mm=meta.$$metamodel$$;\n if (_mm === undefined) {\n //it's a metamodel\n that.meta=meta;\n that.tipo=_findTypeFromModel(pkg,meta);\n _mm = that.tipo.$$metamodel$$;\n if (typeof(_mm)==='function') {\n _mm=_mm();\n that.tipo.$$metamodel$$=_mm;\n }\n } else {\n //it's a type\n that.tipo = meta;\n if (typeof(_mm)==='function') {\n _mm=_mm();\n meta.$$metamodel$$=_mm;\n }\n that.meta = get_model(_mm);\n }\n that.name_=_mm.d[_mm.d.length-1];\n that.toplevel_=_mm.$cont===undefined;\n ClassDeclaration$meta$declaration(that);\n return that;\n}", "function isMonad(m) {\n return isApplicative(m)\n && hasAlg('chain', m)\n}", "function DMObj() {}", "function motors() {\n\n }", "function klass(spec) {\n\t\tvar spec = spec || {};\n\t\tvar that;\n\t\tif(spec.meta) {\n\t\t\tthat = new SmalltalkMetaclass();\n\t\t} else {\n\t\t\tthat = new (klass({meta: true})).fn;\n\t\t\tthat.klass.instanceClass = that;\n\t\t\tthat.className = spec.className;\n\t\t\tthat.klass.className = that.className + ' class';\n\t\t}\n\n\t\tthat.fn = spec.fn || function(){};\n\t\tthat.superclass = spec.superclass;\n\t\tthat.iVarNames = spec.iVarNames || [];\n that.toString = function() {return 'Smalltalk ' + that.className};\n\t\tif(that.superclass) {\n\t\t\tthat.klass.superclass = that.superclass.klass;\n\t\t}\n\t\tthat.pkg = spec.pkg;\n\t\tthat.fn.prototype.methods = {};\n\t\tthat.fn.prototype.inheritedMethods = {};\n\t\tthat.fn.prototype.klass = that;\n\n\t\treturn that;\n\t}", "map(f) {\n return Monad.of(f(this.___value))\n }", "bindClasses() {\n }", "function Motor() {\r\n\t\tthis.mod = false;\t\t// motor was changed?\r\n\t\tthis.speed = 0;\r\n\t\tthis.dir = 1;\t\t\t// -1 (back), 0 (stop), 1 (forward)\r\n\t\tthis.sync = -10;\t\t// -10 = no change, -1 = no-sync, [0-3] = sync with M1-M4\r\n\t\tthis.dist = -10;\t\t// -10 = no change, 0 = no distance limit, >0 = distance limit\r\n\t\tthis.modified =\t\t\tfunction() {this.mod = true;}\r\n\t\tthis.transmitted =\t\tfunction() {this.mod = false; this.sync = -10; this.dist = -10;}\r\n\t\tthis.init =\t\t\t\tfunction() {this.speed = 0; this.dir = 1; this.sync = -10; this.dist = -10;}\r\n\t}", "function GeneratorClass () {}", "function klass(spec) {\n\t\tvar spec = spec || {};\n\t\tvar that;\n\t\tif(spec.meta) {\n\t\t\tthat = new SmalltalkMetaclass();\n\t\t} else {\n\t\t\tthat = new (klass({meta: true})).fn;\n\t\t\tthat.klass.instanceClass = that;\n\t\t\tthat.className = spec.className;\n\t\t\tthat.klass.className = that.className + ' class';\n\t\t}\n\n\t\tthat.fn = spec.fn || function(){};\n\t\tthat.superclass = spec.superclass;\n\t\tthat.iVarNames = spec.iVarNames || [];\n\t\tif(that.superclass) {\n\t\t\tthat.klass.superclass = that.superclass.klass;\n\t\t}\n\t\tthat.pkg = spec.pkg;\n\t\tthat.fn.prototype.methods = {};\n\t\tthat.fn.prototype.inheritedMethods = {};\n\t\tthat.fn.prototype.klass = that;\n\n\t\treturn that;\n\t}", "function Model() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
viewPoint is an x,y array [x,y] returns an x,y array of the corresponding world point
GetWorldPoint(viewPoint) { let worldx = this.wo.dx + viewPoint[0]/this.zoom.now; let worldy = this.wo.dy + viewPoint[1]/this.zoom.now; return [worldx,worldy]; }
[ "GetViewPoint(worldPoint)\n {\n let viewx = (worldPoint[0]-this.wo.dx)*this.zoom.now;\n let viewy = (worldPoint[1]-this.wo.dy)*this.zoom.now;\n return [viewx,viewy];\n }", "function getViewPoint(x, y) {\n const view = document.getElementById('viewbox');\n const svg = document.getElementById('map');\n const pt = svg.createSVGPoint();\n pt.x = x, pt.y = y;\n return pt.matrixTransform(view.getScreenCTM().inverse());\n}", "WorldToViewportPoint() {}", "ViewportToWorldPoint() {}", "worldToScreenCoordinates(point) {\n return this.screen.worldToScreenCoordinates(point);\n }", "function screenToWorldCoords(point)\n{\n return point.add(scrollPoint);\n}", "function getXY(evt) {\n let canvas = getCanvas();\n let rect = canvas.getBoundingClientRect();\n let x = evt.clientX - rect.left;\n let y = evt.clientY - rect.top;\n let s2w = _model.viewport.getXform(_rhino3dm.CoordinateSystem.Screen, _rhino3dm.CoordinateSystem.World)\n let world_point = _rhino3dm.Point3d.transform([x, y, 0], s2w);\n s2w.delete();\n return [world_point[0], world_point[1]];\n}", "get viewPos() {\n this.__update();\n xeogl.math.transformPoint3(this.scene.camera.viewMatrix, this.worldPos, this._viewPos);\n return this._viewPos;\n }", "screenToWorldCoordinates(point) {\n return this.screen.screenToWorldCoordinates(point);\n }", "getElementCoordinates(point) {\n const projected = point.clone().project(this.camera);\n const widthHalf = this.renderContainer.offsetWidth / 2;\n const heightHalf = this.renderContainer.offsetHeight / 2;\n return new __WEBPACK_IMPORTED_MODULE_1_three__[\"Vector2\"](projected.x * widthHalf + widthHalf, -(projected.y * heightHalf) + heightHalf);\n }", "static adjust_point(view, [px, py]) {\n const scale = 2 ** view.scale;\n return [\n (px - view.origin[0]) * scale + view.width / 2,\n (py - view.origin[1]) * scale + view.height / 2,\n ];\n }", "function getWorldCoords(evt)\n{\n return screenToWorldCoords(clickPoint(evt));\n}", "function toViewboxCoords( point ) {\n if ( ! svgRoot )\n return false;\n if ( typeof point.pageX !== 'undefined' ) {\n point = newSVGPoint(point.pageX, point.pageY);\n }\n return point.matrixTransform(svgRoot.getScreenCTM().inverse());\n }", "worldToScreen(x, y) {\n if (y === undefined) {\n y = x.y;\n x = x.x;\n }\n\n let M = this.ctx.getTransform();\n\n let ret = {\n x: x * M.a + y * M.c + M.e,\n y: x * M.b + y * M.d + M.f,\n };\n\n return ret;\n }", "function projectPoint(modelViewMatrix, projMatrix, viewport, src, dest) {\n\tif (!dest)\n\t\tdest = new Float32Array(3);\n\n\t_v0[0] = src[0]; _v0[1] = src[1]; _v0[2] = src[2]; _v0[3] = 1;\n\n\t// transform point from model space to clip space\n\ttransformVector4(modelViewMatrix, _v0, _v1);\n\ttransformVector4(projMatrix, _v1, _v0);\n\n\t/* to normalized device coordinates */\n\t_v0[0] /= _v0[3];\n\t_v0[1] /= _v0[3];\n\t_v0[2] /= _v0[3];\n\n\t/* to window coordinates */\n\tdest[0] = viewport[0] + 0.5 * (1 + _v0[0]) * viewport[2];\n\tdest[1] = -viewport[1] + 0.5 * (1 - _v0[1]) * viewport[3];\n\tdest[2] = 0.5 * (1 + _v0[2]);\n\n\treturn dest;\n}", "canvasToWorldCoordinates(p) {\r\n\t\tlet m = MathTools.inverseMatMul(this.camera.t, [\r\n\t\t\t[p.x-window.innerWidth/2+this.camera.x],\r\n\t\t\t[window.innerHeight-(p.y+window.innerHeight/2)+this.camera.y]\r\n\t\t])\r\n\t\treturn {\r\n\t\t\tx: m[0][0],\r\n\t\t\ty: m[1][0]\r\n\t\t}\r\n\t}", "function getWorldCoords(evt)\n{\n return SideScroll.screenToWorldCoords(clickPoint(evt));\n}", "function toScreenCoords( point ) {\n if ( ! svgRoot )\n return false;\n point = newSVGPoint(point.x, point.y);\n return point.matrixTransform(svgRoot.getScreenCTM());\n }", "function View(world, vector) {\r\n this.world = world;\r\n this.vector = vector;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
kill appropriate menu's, if we are getting here via the hideMenu() funciton then kill all the menu's this is known from the passed value 'apocolypse'
function killMenu(apocolypse) { if(apocolypse=="all")menuKillHolder=menuDisplayHolder; var menuKillArray = menuKillHolder.split(","); //loop and kill //we start at 1 because the zero'th element should be the root for(iloop=1;iloop<menuKillArray.length;iloop++) { if(menuKillArray[iloop]!="null") { if(eval("document."+menuKillArray[iloop])){ eval("document."+menuKillArray[iloop]+".visibility='hide';"); } } }//end loop //if we are completely out, clear both array's and set flag to new if(apocolypse=="all") { menuDisplayHolder = ""; menuKillHolder = ""; flagMenuSwitch = "new"; } }//end kill menu function
[ "function hideMenu()\n{\n\t\t\n\t\t//set a timeout and then kill all the menu's\n\t\t//we will check in menuHandler() to see if some stay lit.\n\t\tmenuTimeout= setTimeout(\"killMenu('all');\",800);\n\t\t\n\t\tflagMenuSwitch=\"off\";\n\t\t\n}//end hideMenu() function", "function closeAllMenus(){\n closeMenu(\"divMenuHelp\");\n closeMenu(\"divMenuOpt\");\n closeMenu(\"divMenuGame\"); }", "function cancelAll() {\n\tkeepMenu();\n\tmenuReady = false;\n}", "function closeAllMenus() {\r\n hideOverlay();\r\n closeMobileCart();\r\n closeMobileCustomerMenu();\r\n closeMobileMainMenu();\r\n closeFilterMenu();\r\n}", "function stopall() {\n clearTimeout(menu_close_timeout);\n}", "function cancelMenu() {\n state.done = true;\n if (state.currentPlayback) {\n state.currentPlayback.stop(function(err) {\n // ignore errors\n });\n }\n\n // remove listeners as future calls to playIntroMenu will create new ones\n channel.removeListener('ChannelDtmfReceived', cancelMenu);\n channel.removeListener('StasisEnd', cancelMenu);\n }", "HideMenus() {\n this.HideMenuSubs();\n this.HideMenusAuds();\n }", "function removeall_menu()\r\n{\r\n\tchrome.contextMenus.removeAll();\r\n\tCommInfo.menuid_map={};\r\n\tcreate_top_menu();\r\n}", "function hideMenu() {\n\t\tmenu.Hide();\n\t\ttileTouchController.enableInput();\n\t\tcameraMovement.enableInput();\n\t}", "function cleanMenu(menu) {\n var i;\n for (i = 0; i < commands.length; i++) {\n menu.removeMenuItem(commands[i]);\n }\n }", "function closeOtherMenus() {\n if ($(openMenus).length) {\n $(openMenus).each(function() {\n methods.closeMenu.apply($(this), [true]);\n });\n }\n }", "function st_flush_menuByClick() {\n\n\t\tm('#menu-responsive').remove();\n\t\tm('#menu-box').stop(true, false).removeAttr('style').removeClass('resp-menu-opened');\n\t\tm('#menu-select').removeClass('resp-menu-opened');\n\n\t}", "function closeAllMenu(){\n\t//menuView1.close();\n\tmenuView2.close();\n\t//darkScreen.fadeOut();\n}", "function hideAllContextMenus() {\n if(hasClass(main_menu, \"hide-main-menu\")) {\n removeClass(main_menu, \"hide-main-menu\");\n }\n\n if(hasClass(color_menu, \"hide-menu\")) {\n removeClass(color_menu, \"hide-menu\");\n }\n\n if(hasClass(paragraph_menu, \"hide-menu\")) {\n removeClass(paragraph_menu, \"hide-menu\");\n }\n }", "function closeMenu() {\n g_IsMenuOpen = false;\n}", "function killHideTknMenu() {\n if (BD18.tknMenu.timeoutID) {\n window.clearTimeout(BD18.tknMenu.timeoutID);\n }\n}", "function HideMenus() {\n HideMenuSubs();\n HideMenusAuds();\n }", "kill()\n\t{\n\t\tfor (let id in this.tabs)\n\t\t{\n\t\t\tlet t = this.tabs[id];\n\t\t\t\n\t\t\t// Remove all tab classes we might have set\n\t\t\tthis.rem_class(t.tab, this.tab_class);\n\t\t\tthis.rem_class(t.tab, this.tab_active);\n\t\t\tthis.rem_class(t.tab, this.tab_hidden);\n\t\t\t\n\t\t\t// Remove button classes we might have set\n\t\t\tthis.rem_class(t.btn, this.btn_class);\n\t\t\tthis.rem_class(t.btn, this.btn_active);\n\n\t\t\t// Remove the button event listerner\n\t\t\tt.btn.removeEventListener(\"click\", t.evt);\n\t\t}\n\n\t\t// Forget all about the tabs and current tab\n\t\tthis.tabs = {};\n\t\tthis.curr = null;\n\t\t\n\t\t// Remove class from nav\n\t\tthis.rem_class(this.tnav, this.nav_class);\n\n\t\t// Remove the \"set\" marker from the tab nav element\n\t\tthis.tnav.removeAttribute(this.attr + \"-set\");\n\t}", "closeMenu() {\n if (!this.isClosed()) {\n this.close();\n $gameBattleMap.absPause = false;\n $gameBattleMap.requestAbsMenu = false;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I attach click handlers to eventsummary items to show their details
function attachEventSummaryClickHandler(){ $( '.event-summary' ).off(); $( '.event-summary' ).click(function(event) { var event_uid = $( this ).attr( 'data-event_uid' ); showEventDetails( event_uid ); }); }
[ "function attachClickEventItemDetails(){\n\t// click function for item details\t\n\t$(\".termnode-item-number-moredetails\").click(function() {\n\n\t\tvar detailContainer = $(this).prev(\".termnode-item-moredetails-container\");\n\t\t\n\t\tif(detailContainer.css(\"display\") == \"none\") { \n\t\t\tdetailContainer.fadeIn();\n\t\t\t$(this).html(\"- show <strong>less</strong>\");\n\t\t} else { \n\t\t\tdetailContainer.hide(); \n\t\t\t$(this).html(\"+ show <strong>more</strong>\");\n\t\t}\n\t});\n}", "function task_detail_listener() {\n $task_detail_trigger.on('click', function () {\n var $this = $(this);\n var $item = $this.parent().parent();\n var index = $item.data('index');\n show_task_detail(index);\n })\n }", "function handleDetailsClick() {\n var $this = $(this),\n $icon = $this.find('i'),\n $container = $this.parents('.results-container'),\n $tbody = $container.find('tbody');\n if ($tbody.hasClass('hidden')) {\n $tbody.removeClass('hidden');\n $icon.removeClass('fa-plus').addClass('fa-minus');\n } else {\n $tbody.addClass('hidden');\n $icon.removeClass('fa-minus').addClass('fa-plus');\n }//end if/else\n }", "on_desklet_clicked(event) {\n this.retrieveEvents();\n }", "function summaryAddLinksHandler()\n\t{\n\t\tvar $summaryAddLinks = $('.configurator-summary-article__link');\n\n\t\t$summaryAddLinks.on('click', function(e){\n\t\t\te.preventDefault();\n\t\t\tvar $$tabTargetIndex = $(this).data('stepTabIndex');\n\t\t\tvar $accordionItemTargetindex = $(this).data('itemIndex');\n\n\t\t\tswitchStepTab($tabTargetIndex);\n\t\t\topenAccordionItemByIndex($tabTargetIndex, $accordionItemTargetindex);\n\t\t});\n\t}", "eventListenerTakeToEventDetails() {\n let eventDivs = document.getElementsByClassName('eventDiv');\n\n for (var i = 0; i < eventDivs.length; i++) {\n eventDivs[i].addEventListener('click', function () {\n location.href = 'details.html';\n });\n }\n }", "function detailView(e){\n\t\t\tindex= $(e.currentTarget).attr('id');\n\t\t\tvar header= $(e.currentTarget).text();\n\t\t\tvar index_contents = feedContentsJson[index].feedContent;\n\t\t\t$('#m_feed_header').text(header);\n\t\t\t$('#detail_feed_content').html(index_contents);\n\t\t\ttau.changePage('#page_detail_feed');\n\t\t}", "function onSummaryEntryLinkClick(){\n\t// Close the summary dialog\n\n\t$(\"#entryDetailsModal\").modal(\"show\");\n\n\n\t// Emulate the effects of a closed details dialog\n\tonDetailsModalHidden();\n\n\t// Get the ID of the entry link\n\tvar id = $(this).data(\"id\");\n\n\t// Trigger the usual handler\n\tdisplayModalEntryDetails(id);\n\n\t// Return false to prevent the default handler for hyperlinks\n\treturn false;\n}", "function doShowEventItemListOnEventEditPage() {\r\n //display free items for event\r\n showFreeItemList();\r\n\r\n //display joined items for event\r\n showJoinedItemList();\r\n\r\n}", "function clickEvents(event){\n if(event.type === 'click'){\n if(event.target.tagName === 'SPAN'){\n if(event.target.classList.contains('closeTODO')){\n if(event.target.parentElement.classList.contains('checked')){\n event.target.parentElement.style.display = 'none';\n itemCountSpan.textContent = parseInt(itemCountSpan.textContent) - 1;\n }\n else{\n event.target.parentElement.style.display = 'none';\n uncheckedCountSpan.textContent = parseInt(uncheckedCountSpan.textContent) - 1;\n itemCountSpan.textContent = parseInt(itemCountSpan.textContent) - 1;\n }\n }\n }\n if(event.target.tagName === 'LI'){\n if(!event.target.classList.contains('checked')){\n event.target.classList.add('checked');\n uncheckedCountSpan.textContent = parseInt(uncheckedCountSpan.textContent) - 1;\n }\n }\n }\n\n if(event.type === 'dblclick'){\n if(event.target.tagName === 'LI'){\n event.target.classList.remove('checked');\n uncheckedCountSpan.textContent = parseInt(uncheckedCountSpan.textContent) + 1;\n }\n }\n\n if(event.type === 'mouseover'){\n if(event.target.tagName === 'LI'){\n event.target.classList.add('icon');\n }\n }\n}", "_handleClick(event) {\n if (!event.graphic.attributes) {\n return;\n }\n\n // Show the info window for our point\n this._map.infoWindow.setTitle(event.graphic.attributes.title);\n this._map.infoWindow.setContent(event.graphic.attributes.details);\n\n // Call all the click handlers\n this._clickHandlers.forEach(f => f(event));\n\n $(this._map.infoWindow.domNode).find('.actionList').addClass('hidden'); //massive hack to remove the Zoom To actionlist dom.\n this._map.infoWindow.show(event.mapPoint); //show the popup, callsbacks will fill data as it comes in\n }", "function showEventDetails(event) {\n //Clear the details div\n this.clearDetailsDiv();\n\n //Show the details div\n document.getElementById(\"ONEUPGRID_details\").style.top = \"75px\";\n\n //Set the details div state\n this.detailsDivState = 1;\n\n //Populate the Title div details - title, location, and map div\n document.getElementById(\"ONEUPGRID_details_title_h1\").innerText = event.title;\n document.getElementById(\"ONEUPGRID_details_title_h2\").innerText = event.location1 + \", \" + event.location2;\n\n //Populate the Info Div\n document.getElementById(\"ONEUPGRID_details_category_div\").innerHTML = \"<b>Category: </b>\" + Utilities.getCategoryStringFromId(event.category);\n document.getElementById(\"ONEUPGRID_details_cost_div\").innerHTML = \"<b>Cost: </b>\" + event.cost;\n document.getElementById(\"ONEUPGRID_details_transportation_div\").innerHTML = \"<b>Getting There: </b>\" + event.transportation;\n document.getElementById(\"ONEUPGRID_details_description_div\").innerHTML = event.description;\n\n //Populate the Tips Div\n var tipsListElement = document.getElementById(\"ONEUPGRID_details_tips_ul\");\n\n //For each tip\n for (var i = 0; i < this.getEventById(this.selectedEventId).tips.length; i++) {\n var tempLi = document.createElement(\"li\");\n tempLi.innerText = this.getEventById(this.selectedEventId).tips[i];\n tipsListElement.appendChild(tempLi);\n }\n\n //Populate the Third Party Tip Providers\n this.populateTipsActions();\n\n //If necessary, populate the website link\n if (this.getEventById(this.selectedEventId).website != null) {\n var websiteButton = document.createElement(\"div\");\n websiteButton.id = \"ONEUPGRID_details_website\";\n websiteButton.classList.add(\"ONEUPGRID_details_title_action_div\");\n websiteButton.innerText = \"View Website\";\n document.getElementById(\"ONEUPGRID_details_title_div\").appendChild(websiteButton);\n this.AttachOnClick(websiteButton, \"ONEUPGRID_details_actions_link_click\");\n }\n }", "onDetailsClicked_() {\n assert(!!this.apn);\n this.closeMenu_();\n this.dispatchEvent(new CustomEvent('show-apn-detail-dialog', {\n composed: true,\n bubbles: true,\n detail: /** @type {!ApnEventData} */ ({\n apn: this.apn,\n // Only allow editing if the APN is a custom APN.\n mode: this.apn.id ? ApnDetailDialogMode.EDIT : ApnDetailDialogMode.VIEW,\n }),\n }));\n }", "addBusinessDetailsListeners() {\n const this_ = this;\n $('.card-track-inner').on(\n 'click',\n '.detailsBtnCard',\n this.getBtnAndShowDetails\n );\n $('.card-track-inner').on(\n 'dblclick',\n '.my-card.mr-card',\n this.getBtnAndShowDetails\n );\n }", "function AuraInspectorEventLog_OnEventClick(eventInfo) {\n // No id specified\n if (!eventInfo.detail) {\n return;\n }\n\n var card = document.getElementById(event.detail.eventId);\n\n if (!card) {\n return;\n } else {\n var button = card.previousElementSibling;\n button.value = 'ON';\n\n card.setAttribute('collapsed', 'false');\n card.scrollIntoView({ block: 'end', behavior: 'smooth' });\n\n //var newEvent = new Event('highlightCard');\n //card.dispatchEvent(newEvent);\n card.highlight();\n }\n }", "function onMainClick() {\n detailsView = new DetailsView();\n \n // Create the details view and set its content.\n detailsView.SetContent(\n \"\", // Item's displayed website/news source.\n undefined, // Time created\n \"details.xml\", // The XML file\n false, // Whether time is shown as absolute time\n 0); // Content layout flags\n\n // Set a reference to the \"closeDetailsView\" function in the detailsViewData\n detailsView.detailsViewData.putValue(\"closeDetailsView\", closeDetailsView);\n \n // Show the details view \n plugin.ShowDetailsView(detailsView, // The DetailsView object\n strings.DETAILS_VIEW_TITLE, // The title\n gddDetailsViewFlagNone, // Flags\n onDetailsViewFeedback); // The handler to call when details view closes\n}", "function attachStatisticsClickEvents() {\r\n $('#numbersTableContainer').on('click', '.cursor-pointer',function () { \r\n sortClick(this);\r\n });\r\n $('#starsTableContainer').on('click', '.cursor-pointer',function () { \r\n sortClick(this);\r\n });\r\n }", "function onListItemClick(e) {\n\n //scrollToTop(e);\n var\n target = Spektral.getTarget(e),\n targetID = Spektral.getTargetID(e),\n cat = Spektral.getParent(target).id,\n num = Spektral.stripString(targetID, \"item\");\n }", "function details(){\n $(\".table.collections .collection td\").click(function() {\n if(!$(this).hasClass(\"list-options\")) {\n window.location.href = $(this).parent().data('url');\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`_setBase` sets the base IRI to resolve relative IRIs
_setBase(baseIRI) { if (!baseIRI) { this._base = ''; this._basePath = ''; } else { // Remove fragment if present var fragmentPos = baseIRI.indexOf('#'); if (fragmentPos >= 0) baseIRI = baseIRI.substr(0, fragmentPos); // Set base IRI and its components this._base = baseIRI; this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI : baseIRI.replace(/[^\/?]*(?:\?.*)?$/, ''); baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i); this._baseRoot = baseIRI[0]; this._baseScheme = baseIRI[1]; } }
[ "_setBase (baseIRI) {\n if (!baseIRI)\n baseIRI = null;\n\n // baseIRI '#' check disabled to allow -x 'data:text/shex,...#'\n // else if (baseIRI.indexOf('#') >= 0)\n // throw new Error('Invalid base IRI ' + baseIRI);\n\n // Set base IRI and its components\n if (this.base = baseIRI) {\n this._basePath = baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(schemeAuthority);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }", "_setBase(baseIRI) {\n if (!baseIRI)\n this._base = null;\n else {\n // Remove fragment if present\n var fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }", "_setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n }\n else {\n // Remove fragment if present\n var fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }", "_setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n } else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0) baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI : baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }", "_setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n } else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0) baseIRI = baseIRI.substr(0, fragmentPos); // Set base IRI and its components\n\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI : baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }", "function setBase(n){\n\treleaseData.base = n\n\treturn n\n}", "function setBaseURI(uri) {\n _baseURI = uri;\n}", "function _prependBase(base, iri) {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n // already an absolute IRI\n if(iri.indexOf(':') !== -1) {\n return iri;\n }\n\n // parse base if it is a string\n if(_isString(base)) {\n base = jsonld.url.parse(base || '');\n }\n\n // parse given IRI\n var rel = jsonld.url.parse(iri);\n\n // start hierarchical part\n var hierPart = (base.protocol || '');\n if(rel.authority) {\n hierPart += '//' + rel.authority;\n } else if(base.href !== '') {\n hierPart += '//' + base.authority;\n }\n\n // per RFC3986 normalize\n var path;\n\n // IRI represents an absolute path\n if(rel.pathname.indexOf('/') === 0) {\n path = rel.pathname;\n } else {\n path = base.pathname;\n\n // append relative path to the end of the last directory from base\n if(rel.pathname !== '') {\n path = path.substr(0, path.lastIndexOf('/') + 1);\n if(path.length > 0 && path.substr(-1) !== '/') {\n path += '/';\n }\n path += rel.pathname;\n }\n }\n\n // remove slashes and dots in path\n path = _removeDotSegments(path, hierPart !== '');\n\n // add query and hash\n if(rel.query) {\n path += '?' + rel.query;\n }\n if(rel.hash) {\n path += rel.hash;\n }\n\n var rval = hierPart + path;\n\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n}", "function _prependBase(base, iri) {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n // already an absolute IRI\n if(iri.indexOf(':') !== -1) {\n return iri;\n }\n\n // parse base if it is a string\n if(_isString(base)) {\n base = jsonld.url.parse(base || '');\n }\n\n // parse given IRI\n var rel = jsonld.url.parse(iri);\n\n // per RFC3986 5.2.2\n var transform = {\n protocol: base.protocol || ''\n };\n\n if(rel.authority !== null) {\n transform.authority = rel.authority;\n transform.path = rel.path;\n transform.query = rel.query;\n } else {\n transform.authority = base.authority;\n\n if(rel.path === '') {\n transform.path = base.path;\n if(rel.query !== null) {\n transform.query = rel.query;\n } else {\n transform.query = base.query;\n }\n } else {\n if(rel.path.indexOf('/') === 0) {\n // IRI represents an absolute path\n transform.path = rel.path;\n } else {\n // merge paths\n var path = base.path;\n\n // append relative path to the end of the last directory from base\n if(rel.path !== '') {\n path = path.substr(0, path.lastIndexOf('/') + 1);\n if(path.length > 0 && path.substr(-1) !== '/') {\n path += '/';\n }\n path += rel.path;\n }\n\n transform.path = path;\n }\n transform.query = rel.query;\n }\n }\n\n // remove slashes and dots in path\n transform.path = _removeDotSegments(transform.path, !!transform.authority);\n\n // construct URL\n var rval = transform.protocol;\n if(transform.authority !== null) {\n rval += '//' + transform.authority;\n }\n rval += transform.path;\n if(transform.query !== null) {\n rval += '?' + transform.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n}", "function _prependBase(base, iri) {\r\n // skip IRI processing\r\n if(base === null) {\r\n return iri;\r\n }\r\n // already an absolute IRI\r\n if(iri.indexOf(':') !== -1) {\r\n return iri;\r\n }\r\n\r\n // parse base if it is a string\r\n if(_isString(base)) {\r\n base = jsonld.url.parse(base || '');\r\n }\r\n\r\n // parse given IRI\r\n var rel = jsonld.url.parse(iri);\r\n\r\n // per RFC3986 5.2.2\r\n var transform = {\r\n protocol: base.protocol || ''\r\n };\r\n\r\n if(rel.authority !== null) {\r\n transform.authority = rel.authority;\r\n transform.path = rel.path;\r\n transform.query = rel.query;\r\n } else {\r\n transform.authority = base.authority;\r\n\r\n if(rel.path === '') {\r\n transform.path = base.path;\r\n if(rel.query !== null) {\r\n transform.query = rel.query;\r\n } else {\r\n transform.query = base.query;\r\n }\r\n } else {\r\n if(rel.path.indexOf('/') === 0) {\r\n // IRI represents an absolute path\r\n transform.path = rel.path;\r\n } else {\r\n // merge paths\r\n var path = base.path;\r\n\r\n // append relative path to the end of the last directory from base\r\n if(rel.path !== '') {\r\n path = path.substr(0, path.lastIndexOf('/') + 1);\r\n if(path.length > 0 && path.substr(-1) !== '/') {\r\n path += '/';\r\n }\r\n path += rel.path;\r\n }\r\n\r\n transform.path = path;\r\n }\r\n transform.query = rel.query;\r\n }\r\n }\r\n\r\n // remove slashes and dots in path\r\n transform.path = _removeDotSegments(transform.path, !!transform.authority);\r\n\r\n // construct URL\r\n var rval = transform.protocol;\r\n if(transform.authority !== null) {\r\n rval += '//' + transform.authority;\r\n }\r\n rval += transform.path;\r\n if(transform.query !== null) {\r\n rval += '?' + transform.query;\r\n }\r\n if(rel.fragment !== null) {\r\n rval += '#' + rel.fragment;\r\n }\r\n\r\n // handle empty base\r\n if(rval === '') {\r\n rval = './';\r\n }\r\n\r\n return rval;\r\n}", "setBase(base) {\n if(typeof base !== 'string') { throw 'InvalidBase' }\n\n if(_debug === true) {\n console.log(\"debug is set to \", _debug);\n console.log('setting base to', base)\n }\n\n _options.base = base;\n\n if(_debug === true) {\n console.log('options: ', base)\n }\n }", "function setApiBaseUri(baseUri) {\n apiBaseUri = baseUri;\n }", "setBase() {\n const {base, baseBlock} = this.__getTariffDOM();\n this.__setChecked(baseBlock, base);\n }", "function resolveIRI(iri) {\r\n // Strip off possible angular brackets\r\n if (iri[0] === '<')\r\n iri = iri.substring(1, iri.length - 1);\r\n // Return absolute IRIs unmodified\r\n if (/^[a-z]+:/.test(iri))\r\n return iri;\r\n if (!Parser.base)\r\n throw new Error('Cannot resolve relative IRI ' + iri + ' because no base IRI was set.');\r\n if (!base) {\r\n base = Parser.base;\r\n basePath = base.replace(/[^\\/:]*$/, '');\r\n baseRoot = base.match(/^(?:[a-z]+:\\/*)?[^\\/]*/)[0];\r\n }\r\n switch (iri[0]) {\r\n // An empty relative IRI indicates the base IRI\r\n case undefined:\r\n return base;\r\n // Resolve relative fragment IRIs against the base IRI\r\n case '#':\r\n return base + iri;\r\n // Resolve relative query string IRIs by replacing the query string\r\n case '?':\r\n return base.replace(/(?:\\?.*)?$/, iri);\r\n // Resolve root relative IRIs at the root of the base IRI\r\n case '/':\r\n return baseRoot + iri;\r\n // Resolve all other IRIs at the base IRI's path\r\n default:\r\n return basePath + iri;\r\n }\r\n }", "function setRuleBase(newRuleBase) {\n\truleBase = newRuleBase;\n}", "function _removeBase(base, iri) {\n // skip IRI processing\n if (base === null) {\n return iri;\n }\n\n if (_isString(base)) {\n base = jsonld.url.parse(base || '');\n }\n\n // establish base root\n var root = '';\n if (base.href !== '') {\n root += (base.protocol || '') + '//' + (base.authority || '');\n } else if (iri.indexOf('//')) {\n // support network-path reference with empty base\n root += '//';\n }\n\n // IRI not relative to base\n if (iri.indexOf(root) !== 0) {\n return iri;\n }\n\n // remove root from IRI and parse remainder\n var rel = jsonld.url.parse(iri.substr(root.length));\n\n // remove path segments that match (do not remove last segment unless there\n // is a hash or query)\n var baseSegments = base.normalizedPath.split('/');\n var iriSegments = rel.normalizedPath.split('/');\n var last = rel.fragment || rel.query ? 0 : 1;\n while (baseSegments.length > 0 && iriSegments.length > last) {\n if (baseSegments[0] !== iriSegments[0]) {\n break;\n }\n baseSegments.shift();\n iriSegments.shift();\n }\n\n // use '../' for each non-matching base segment\n var rval = '';\n if (baseSegments.length > 0) {\n // don't count the last segment (if it ends with '/' last path doesn't\n // count and if it doesn't end with '/' it isn't a path)\n baseSegments.pop();\n for (var i = 0; i < baseSegments.length; ++i) {\n rval += '../';\n }\n }\n\n // prepend remaining segments\n rval += iriSegments.join('/');\n\n // add query and hash\n if (rel.query !== null) {\n rval += '?' + rel.query;\n }\n if (rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if (rval === '') {\n rval = './';\n }\n\n return rval;\n }", "_resolveIRI (iri) {\n switch (iri[0]) {\n // An empty relative IRI indicates the base IRI\n case undefined: return this.base;\n // Resolve relative fragment IRIs against the base IRI\n case '#': return this.base + iri;\n // Resolve relative query string IRIs by replacing the query string\n case '?': return this.base.replace(/(?:\\?.*)?$/, iri);\n // Resolve root-relative IRIs at the root of the base IRI\n case '/':\n // Resolve scheme-relative IRIs to the scheme\n return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri);\n // Resolve all other IRIs at the base IRI's path\n default: {\n return this._removeDotSegments(this._basePath + iri);\n }\n }\n }", "function resolveIRI(iri) {\n\t // Strip off possible angular brackets\n\t if (iri[0] === '<') iri = iri.substring(1, iri.length - 1);\n\t // Return absolute IRIs unmodified\n\t if (/^[a-z]+:/.test(iri)) return iri;\n\t if (!Parser.base) throw new Error('Cannot resolve relative IRI ' + iri + ' because no base IRI was set.');\n\t if (!base) {\n\t base = Parser.base;\n\t basePath = base.replace(/[^\\/:]*$/, '');\n\t baseRoot = base.match(/^(?:[a-z]+:\\/*)?[^\\/]*/)[0];\n\t }\n\t switch (iri[0]) {\n\t // An empty relative IRI indicates the base IRI\n\t case undefined:\n\t return base;\n\t // Resolve relative fragment IRIs against the base IRI\n\t case '#':\n\t return base + iri;\n\t // Resolve relative query string IRIs by replacing the query string\n\t case '?':\n\t return base.replace(/(?:\\?.*)?$/, iri);\n\t // Resolve root relative IRIs at the root of the base IRI\n\t case '/':\n\t return baseRoot + iri;\n\t // Resolve all other IRIs at the base IRI's path\n\t default:\n\t return basePath + iri;\n\t }\n\t }", "function resolveIRI(iri) {\n // Strip off possible angular brackets\n if (iri[0] === '<')\n iri = iri.substring(1, iri.length - 1);\n // Return absolute IRIs unmodified\n if (/^[a-z]+:/.test(iri))\n return iri;\n if (!Parser.base)\n throw new Error('Cannot resolve relative IRI ' + iri + ' because no base IRI was set.');\n if (!base) {\n base = Parser.base;\n basePath = base.replace(/[^\\/:]*$/, '');\n baseRoot = base.match(/^(?:[a-z]+:\\/*)?[^\\/]*/)[0];\n }\n switch (iri[0]) {\n // An empty relative IRI indicates the base IRI\n case undefined:\n return base;\n // Resolve relative fragment IRIs against the base IRI\n case '#':\n return base + iri;\n // Resolve relative query string IRIs by replacing the query string\n case '?':\n return base.replace(/(?:\\?.*)?$/, iri);\n // Resolve root relative IRIs at the root of the base IRI\n case '/':\n return baseRoot + iri;\n // Resolve all other IRIs at the base IRI's path\n default:\n return basePath + iri;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a function that counts the number of syllables a word has. Each syllable is separated with a dash .
function numberSyllables(word) { word = word.split('-') console.log(word.length); }
[ "syllableCounter(input) {\n let sylCount = 0;\n const inputArr = input.split(' ');\n inputArr.forEach((word) => {\n // stop spaces from adding to count\n const trimmed = word.replace('&nbsp;', '');\n if (trimmed !== '') {\n sylCount += Syllable(trimmed);\n }\n });\n return sylCount;\n }", "function numberSyllables(word) {\n\tlet sylables = 1\n\tfor(let i = 0; i< word.length; i++){\n\t\tif(word[i] === '-'){\n\t\t\tsylables++\n\t\t}\n\t}\n\treturn sylables\n}", "function numberSyllables(word) {\n let count = 1;\n for (let i = 0; i <= word.length - 1; i++) {\n if (word[i] == \"-\") {\n count += 1;\n }\n }\n return count;\n}", "function countSyllables(text){\n var words = text.split(/[\\.\\!\\?, ]+/g);\n var sylcount = 0;\n for (var w = 0; w < words.length; w++) {\n var word = words[w].trim()\n // pass on a zero length token\n if (word.length == 0){\n continue;\n // add 1 if it's a 1-3 character word \n } else if (word.length > 0 && word.length <= 3) {\n sylcount += 1;\n // else use the calculator\n } else {\n sylcount += (count_syllables(word)[0]); //0=min syls, 1=max syls\n }\n }\n console.log('syllable count', sylcount, 'for text:', text);\n return sylcount;\n}", "function numberSyllables(word) {\n\tconst regex = /-/g;\n\tconst found = (word.match(regex) || []).length + 1;\n\treturn found;\n}", "function countSyllablesAndPolys (wordList) {\n let syllablesTotal = 0, polysTotal = 0;\n wordList.forEach((word) => {\n if (word === \"'\"||word===\"’\") {return;} //bandaid solution.\n if (word.length <= 2) {syllablesTotal += 1; return;} //quick return on short words\n let syllables = 0;\n if (word.endsWith(\"s'\")||word.endsWith(\"s’\")) {word.slice(-1);} //ending with s'\n if (word.endsWith(\"s's\")||word.endsWith(\"s’s\")) {word.slice(-1,-3);} //ending with s's\n const cEndings = word.match(/(?<=\\w{3})(side|\\wess|(?<!ed)ly|ment|ship|board|ground|(?<![^u]de)ville|port|ful(ly)?|berry|box|nesse?|such|m[ae]n|wom[ae]n|horse|anne)s?$/mi);\n if (cEndings) {word = word.replace(cEndings[0],\"\\n\" + cEndings[0]);} //Splits into two words and evaluates them as such\n const cBeginnings = word.match(/^(ware|side|p?re(?!ach|agan|al|au))/mi);\n if (cBeginnings) {word = word.replace(cBeginnings[0],\"\"); syllables++;}\n const esylp = word.match(/ie($|l|t|rg)|([cb]|tt|pp)le$|phe$|kle(s|$)|[^n]scien|sue|aybe$|[^aeiou]shed|[^lsoai]les$|([^e]r|g)ge$|(gg|ck|yw|etch)ed$|(sc|o)he$|seer|^re[eiuy]/gmi);\n if (esylp) {syllables += esylp.length;} //E clustered positive\n const esylm = word.match(/every|some([^aeiouyr]|$)|[^trb]ere(?!d|$|o|r|t|a[^v]|n|s|x)|[^g]eous|niet/gmi);\n if (esylm) {syllables -= esylm.length;} //E clustered negative\n const isylp = word.match(/rie[^sndfvtl]|(?<=^|[^tcs]|st)ia|siai|[^ct]ious|quie|[lk]ier|settli|[^cn]ien[^d]|[aeio]ing$|dei[tf]|isms?$/gmi);\n if (isylp) {syllables += isylp.length;} //I clustered positive\n const osylp = word.match(/nyo|osm(s$|$)|oinc|ored(?!$)|(^|[^ts])io|oale|[aeiou]yoe|^m[ia]cro([aiouy]|e)|roe(v|$)|ouel|^proa|oolog/gmi);\n if (osylp) {syllables += osylp.length;} //O clustered positive\n const osylm = word.match(/[^f]ore(?!$|[vcaot]|d$|tte)|fore|llio/gmi);\n if (osylm) {syllables -= osylm.length;} //O clustered negative\n const asylp = word.match(/asm(s$|$)|ausea|oa$|anti[aeiou]|raor|intra[ou]|iae|ahe$|dais|(?<!p)ea(l(?!m)|$)|(?<!j)ean|(?<!il)eage/gmi);\n if (asylp) {syllables += asylp.length;} //A clustered positive\n const asylm = word.match(/aste(?!$|ful|s$|r)|[^r]ared$/gmi);\n if (asylm) {syllables -= asylm.length;} //A clustered negative\n const usylp = word.match(/uo[^y]|[^gq]ua(?!r)|uen|[^g]iu|uis(?![aeiou]|se)|ou(et|ille)|eu(ing|er)|uye[dh]|nuine|ucle[aeiuy]/gmi);\n if (usylp) {syllables += usylp.length;} //U clustered positive\n const usylm = word.match(/geous|busi|logu(?!e|i)/gmi);\n if (usylm) {syllables -= usylm.length;} //U clustered negative\n const ysylp = word.match(/[ibcmrluhp]ya|nyac|[^e]yo|[aiou]y[aiou]|[aoruhm]ye(tt|l|n|v|z)|dy[ae]|oye[exu]|lye[nlrs]|(ol|i|p)ye|aye(k|r|$|u[xr]|da)|saye\\w|wy[ae]|[^aiou]ying/gmi);\n if (ysylp) {syllables += ysylp.length;} //Y clustered positive\n const ysylm = word.match(/arley|key|ney$/gmi);\n if (ysylm) {syllables -= ysylm.length;}\n const essuffix = word.match(/((?<!c[hrl]|sh|[iszxgej]|[niauery]c|do)es$)/gmi);\n if (essuffix) {syllables--;}//es suffix\n const edsuffix = word.match(/([aeiouy][^aeiouyrdt]|[^aeiouy][^laeiouyrdtbm]|ll|bb|ield|[ou]rb)ed$|[^cbda]red$/gmi);\n if (edsuffix) {syllables--}\n const csylp = word.match(/chn[^eai]|mc|thm/gmi);\n if (csylp) {syllables += csylp.length;} //Consonant clustered negative\n const eVowels = word.match(/[aiouy](?![aeiouy])|ee|e(?!$|-|[iua])/gmi);\n if (eVowels) {syllables += eVowels.length;} //Applicable vowel count (all but e at end of word)\n if (syllables <= 0) {syllables = 1;} //catch-all\n if (word.match(/[^aeiou]n['’]t$/i)) {syllables ++;} //ending in n't, but not en't\n if (word.match(/en['’]t$/i)) {syllables --;} //ending in en't\n if (syllables >= 3) {polysTotal++;}\n syllablesTotal += syllables;\n });\n return [syllablesTotal, polysTotal];\n }", "function countSyllables(phonemes) {\n let count = 0;\n phonemes.forEach(function(pho) {\n if (pho.match(/\\d/)) {\n count++;\n }\n });\n return count;\n}", "function syllable(value) {\n\t var count = 0;\n\t var index;\n\t var length;\n\t var singular;\n\t var parts;\n\t var addOne;\n\t var subtractOne;\n\n\t if (value.length === 0) {\n\t return count\n\t }\n\n\t // Return early when possible.\n\t if (value.length < 3) {\n\t return 1\n\t }\n\n\t // If `value` is a hard to count, it might be in `problematic`.\n\t if (own.call(problematic$2, value)) {\n\t return problematic$2[value]\n\t }\n\n\t // Additionally, the singular word might be in `problematic`.\n\t singular = pluralize(value, 1);\n\n\t if (own.call(problematic$2, singular)) {\n\t return problematic$2[singular]\n\t }\n\n\t addOne = returnFactory(1);\n\t subtractOne = returnFactory(-1);\n\n\t // Count some prefixes and suffixes, and remove their matched ranges.\n\t value = value\n\t .replace(EXPRESSION_TRIPLE, countFactory(3))\n\t .replace(EXPRESSION_DOUBLE, countFactory(2))\n\t .replace(EXPRESSION_SINGLE, countFactory(1));\n\n\t // Count multiple consonants.\n\t parts = value.split(/[^aeiouy]+/);\n\t index = -1;\n\t length = parts.length;\n\n\t while (++index < length) {\n\t if (parts[index] !== '') {\n\t count++;\n\t }\n\t }\n\n\t // Subtract one for occurrences which should be counted as one (but are\n\t // counted as two).\n\t value\n\t .replace(EXPRESSION_MONOSYLLABIC_ONE, subtractOne)\n\t .replace(EXPRESSION_MONOSYLLABIC_TWO, subtractOne);\n\n\t // Add one for occurrences which should be counted as two (but are counted as\n\t // one).\n\t value\n\t .replace(EXPRESSION_DOUBLE_SYLLABIC_ONE, addOne)\n\t .replace(EXPRESSION_DOUBLE_SYLLABIC_TWO, addOne)\n\t .replace(EXPRESSION_DOUBLE_SYLLABIC_THREE, addOne)\n\t .replace(EXPRESSION_DOUBLE_SYLLABIC_FOUR, addOne);\n\n\t // Make sure at least on is returned.\n\t return count || 1\n\n\t // Define scoped counters, to be used in `String#replace()` calls.\n\t // The scoped counter removes the matched value from the input.\n\t function countFactory(addition) {\n\t return counter\n\t function counter() {\n\t count += addition;\n\t return ''\n\t }\n\t }\n\n\t // Define scoped counters, to be used in `String#replace()` calls.\n\t // The scoped counter does not remove the matched value from the input.\n\t function returnFactory(addition) {\n\t return returner\n\t function returner($0) {\n\t count += addition;\n\t return $0\n\t }\n\t }\n\t}", "function numOfSyllables(layout){\n var match = layout.match(/\\d/g);\n if(match == null) return 0;\n return match.length;\n}", "function findSyllableCount(word, syllaArray){\n var count = 0;\n\n for (var syllable = 0; syllable < syllaArray.length; syllable++){\n\n // checks that syllables array isn't empty (as in the case of 10, 13 syllable words)\n if (syllaArray[syllable] !== undefined){\n\n // stores # of syllables in word based on index of element where word is found\n if (syllaArray[syllable].indexOf(word) > -1){\n count = syllable;\n }\n }\n }\n return count;\n}", "function countSyllables(word) {\n var syl = 0;\n var vowel = false;\n //check each word for vowels (don't count more than one vowel in a row)\n for (var i = 0; i < word.length; i++) {\n if (isVowel(word.charAt(i)) && (vowel == false)) {\n vowel = true;\n syl++;\n } else if (isVowel(word.charAt(i)) && (vowel == true)) {\n vowel = true;\n } else {\n vowel = false;\n }\n }\n \n var tempChar = word.charAt(word.length-1);\n //check for an 'e' at the end, as long as its not a word with one syllable\n //this is something we would need to change if we wanted this to analyze more than one word.\n if ((tempChar == 'e' || tempChar == 'E') && syl != 1) {\n syl--;\n }\n return syl;\n}", "function countSyllables(word) {\n var syl = 0;\n var vowel = false;\n\n //check each word for vowels (don't count more than one vowel in a row)\n for (var i = 0; i < word.length; i++) {\n if (isVowel(word.charAt(i)) && (vowel == false)) {\n vowel = true;\n syl++;\n } else if (isVowel(word.charAt(i)) && (vowel == true)) {\n vowel = true;\n } else {\n vowel = false;\n }\n }\n\n var tempChar = word.charAt(word.length-1);\n //check for an 'e' at the end, as long as its not a word with one syllable\n //this is something we would need to change if we wanted this to analyze more than one word.\n if ((tempChar == 'e' || tempChar == 'E') && syl != 1) {\n syl--;\n }\n return syl;\n}", "function countSyllables(str) {\n\tstr = str.toLowerCase();\n\tlet n = str.length;\n\tlet x = Math.floor(n/2);\n\tlet count = 0;\t\n\tfor (let i=0; i<=x; i++) { //##style02-----> (let i=x; i>0; i--) \n\t\tlet left = str.slice(0,i);\n\t\tlet right = str.slice(i,i*2);\n\t\tif ( (n % i === 0) && ( left === right ) ){\n\t\t\tcount = i;\n\t\t\ti = x;\t//##style02-----> i = 0; \n\t\t}\n\t\t// console.log(n,x,i,left,right);\n\t}\t\n\treturn count === 0 ? (n > 1)? 1:0 : str.length / count;\n}", "function countSyllables(word) {\n var syl = 0;\n var vowel = false;\n var length = word.length;\n\n // Check each word for vowels (don't count more than one vowel in a row)\n for (var i = 0; i < length; i++) {\n if (isVowel(word.charAt(i)) && (vowel == false)) {\n vowel = true;\n syl++;\n } else if (isVowel(word.charAt(i)) && (vowel == true)) {\n vowel = true;\n } else {\n vowel = false;\n }\n }\n\n var tempChar = word.charAt(word.length-1);\n // Check for 'e' at the end, as long as not a word w/ one syllable\n if (((tempChar == 'e') || (tempChar == 'E')) && (syl != 1)) {\n syl--;\n }\n return syl;\n}", "function syllables(word){\n return RiTa.getSyllables(word);\n}", "function createSyllableObj(data){ \n var lines = data.split(\"\\n\");\n lines.forEach(function(line){ \n var word= /\\w+(-||')?\\w+(\\(\\d\\))?/.exec(line)[0];\n if(line.match(/\\d(?!\\)) ?/g)){\n var syllables= line.match(/\\d(?!\\)) ?/g).length;\n \t syllableMap[word]= syllables; \n }\n \t else\n syllableMap[word]= 0;\n }); \n\n}", "function checkSyllables(word){\n\tvar arr=word.split(\"-\");\n\tif(arr.length<=2){\n\t\treturn 300;\n\t}else if(arr.length==3){\n\t\treturn 400;\n\t}else if(arr.length>3){\n\t\treturn 500;\n\t}\n}", "function charFreq(string){\n \n\n\n}", "function syllableCount(phonemeLayout) {\n\tif(typeof(phonemeLayout) === 'undefined') {\n\t\treturn 0;\n\t}\n\tvar numSyllArr = phonemeLayout.match(/\\d/g);\n\tif(numSyllArr === null) {\n\t\treturn 0;\n\t}\n\treturn numSyllArr.length; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate user's token and set a new password for the user as specified
function resetUserPassword(req, res, next){ /* * NOTE: parseValidateToken Must be called before this function in the * router in order to confirm that the token is valid. */ User.findOne({ _id: req.token.userID, email: req.token.userEmail }, function(err, user){ // If an error occured with finding a user or the user is not verified if (req.token.type !== 'reset' || err || !user.isVerified){ return res.status(500).send( utils.errorResponse('ER_SERVER', err) ); } // Update the userr's password user.password = req.body.password; user.save(function(err){ // If an error occured with saving the user if (err){ return res.status(500).send( utils.errorResponse('ER_SERVER', err) ); } return res.sendStatus(200); }); }); }
[ "changeUserPassword (callback) {\n\t\tconst passwordData = {\n\t\t\texistingPassword: this.data.password,\n\t\t\tnewPassword: RandomString.generate(12)\n\t\t};\n\t\tthis.data.password = passwordData.newPassword; // use this for the login request\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'put',\n\t\t\t\tpath: '/password',\n\t\t\t\tdata: passwordData,\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}", "function setPassword (user, cb) {\n \n}", "static resetUserPassword(req, res) {\n // auth_token is sent over from the application in the request body and new password is provided\n const { auth_token, password } = req.body;\n const { valid, message } = validatePassword(password);\n // find by auth_token as it is unique\n if (valid === true) {\n User.findOne({\n where: {\n auth_token: auth_token\n },\n attributes: [\n 'id',\n 'name',\n 'email',\n 'salt',\n 'auth_token_valid_to'\n ]\n })\n .then(userData => {\n // checking if there is a user by that authentication token\n if (userData !== undefined && userData !== null) {\n // get stored salt and the date to which the token is valid\n const salt = userData.get('salt');\n const tokenDate = userData.get('auth_token_valid_to');\n // checks if the token is still valid\n if (tokenDate > getCurrentDateInteger()) {\n const { hashedPassword } = hashing(password, salt);\n\n // changing password\n userData.set({\n password: hashedPassword\n });\n // storing the updated object to the DB\n userData.save();\n\n res.status(200).send({\n success: true,\n message: 'Password has been reset',\n data: userData\n })\n } else {\n res.status(500).send({\n success: false,\n message: \"Token has expired\"\n })\n }\n } else {\n res.status(500).send({\n success: false,\n message: \"User under the token doesn't exist\"\n })\n }\n })\n } else {\n res.status(500).send({\n success: valid,\n message: message\n })\n }\n }", "async changePassword() {\n \n // .......... authority judge\n \n \n const user = this.ctx.request.body;\n const result = await this.service.users.update(user);\n\n // user doesn't exist\n if (result.code >= 400) {\n this.ctx.body = result;\n return;\n }\n\n // modify user's password successed\n this.ctx.body = this.service.util.generateResponse(200, `set user's password successed`); \n }", "async authorizeCreatePassword(req, res, next) {\n const token = req.token\n const { user } = await authorizeToken(token, 'createPassword')\n req.self = user\n next()\n }", "function YNetwork_set_userPassword(newval)\n { var rest_val;\n rest_val = newval;\n return this._setAttr('userPassword',rest_val);\n }", "async function set_new_user_password_hash(env) {\n try {\n env.auth.new_user.password.hash = await crypto.hash_gen(\n env.auth.new_user.password.plaintext\n );\n }\n catch (e) {\n http.send(env,\n http.status.INTERNAL_SERVER_ERROR,\n { desc:'Unable to generate password hash', error: e }\n );\n }\n}", "updatePassword(userId, newHashedPwd, currentResumeLoginToken) {\n var user = this.Users.findOne(userId);\n if (!user)\n throw new Error('User not found');\n \n user.services.password.bcrypt = newHashedPwd;\n delete user.services.password.reset;\n this.Users.update(user);\n \n this.removeOtherHashedLoginTokens(userId,currentResumeLoginToken);\n \n }", "function set_user_password(env, password) {\n env.auth.user.password = { plaintext: password };\n}", "set_userPassword(newval)\n {\n this.liveFunc.set_userPassword(newval);\n return this._yapi.SUCCESS;\n }", "function set_new_user_password(env, password) {\n init_new_user_storage(env);\n env.auth.new_user.password = { plaintext: password };\n}", "function setPassword() {\n postPassword(\n success = function () {\n console.log('Password set');\n setPermissions();\n },\n error = null,\n email,\n password);\n }", "static changePassword(req, res) {\n if (!req.body.password) {\n return res.status(400).end();\n }\n\n req.user.password = req.body.password;\n req.user.save(err => res.status(200).send());\n }", "async resetPassword(parent, args, ctx, info) {\n // 1. check if the passwords match\n if (args.password !== args.confirmPassword) {\n throw new Error(\"Yo Passwords don't match!\");\n }\n // 2. check if its a legit reset token\n // 3. Check if its expired\n const [user] = await ctx.db.query.users({\n where: {\n resetToken: args.resetToken,\n resetTokenExpiry_gte: Date.now() - 3600000\n }\n });\n if (!user) {\n throw new Error('This token is either invalid or expired!');\n }\n\n const sizedFields = {\n password: {\n min: 8,\n max: 72\n }\n };\n\n const tooSmallField = Object.keys(sizedFields).find(\n field =>\n 'min' in sizedFields[field] &&\n args.password.trim().length < sizedFields[field].min\n );\n const tooLargeField = Object.keys(sizedFields).find(\n field =>\n 'max' in sizedFields[field] &&\n args.password.trim().length > sizedFields[field].max\n );\n\n if (tooSmallField) {\n throw new Error(\n `Must be at least ${sizedFields[tooSmallField].min} characters long`\n );\n }\n if (tooLargeField) {\n throw new Error(\n `Must be at most ${sizedFields[tooLargeField].max} characters long`\n );\n }\n\n if (args.password.search(/[a-z]/) == -1) {\n throw new Error('Your password needs at least one lower case letter. ');\n }\n\n if (args.password.search(/[A-Z]/) == -1) {\n throw new Error('Your password needs at least one upper case letter. ');\n }\n\n if (args.password.search(/[0-9]/) == -1) {\n throw new Error('password needs a number.');\n }\n // 4. Hash their new password\n const password = await bcrypt.hash(args.password, 10);\n // 5. Save the new password to the user and remove old resetToken fields\n const updatedUser = await ctx.db.mutation.updateUser({\n where: { email: user.email },\n data: {\n password,\n resetToken: null,\n resetTokenExpiry: null\n }\n });\n // 6. Generate JWT\n const token = jwt.sign({ userId: updatedUser.id }, process.env.APP_SECRET);\n // 7. Set the JWT cookie\n ctx.response.cookie('token', token, {\n domain: domain,\n httpOnly: true,\n maxAge: 1000 * 60 * 60 * 24 * 365\n });\n // 8. return the new user\n return updatedUser;\n }", "setToken(password){\n this.token = new Buffer(`${this.user}:${password}`).toString('base64')\n return this.token\n }", "async function authUser({username, password, token }) {\n // token auth\n if(token){\n try{\n const {id: userId , passwordUpdatedAt} = jwt.verify(token, JWT_SECRET)\n const user = users.find(u=> {\n return u.id === userId && u.passwordUpdatedAt === passwordUpdatedAt\n })\n if(!user){\n return false\n }\n return redactUserInfo(user)\n } catch(e) {\n console.log(e)\n return false\n }\n \n }\n \n \n // check that password hasn't changed since token was created\n \n // password auth\n const user = users.find(u => u.username === username)\n if(!user){\n return false\n }\n \n \n const passwordMatches = await bcrypt.compare(password, user.hashedPassword)\n if(!passwordMatches){\n \n return false\n }\n }", "resetPassword(token) {\n\n\t}", "setPassword(user, newPassword) {\n user.passwordHash = bcrypt.hashSync(newPassword);\n }", "updateUserPassword(context, password) {\n return client.post(\n window.Urls.change_password(),\n {\n new_password1: password,\n new_password2: password,\n },\n {\n headers: {\n 'Content-type': 'application/form-url-encode',\n },\n }\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ecma International makes this code available under the terms and conditions set forth on (the "Use Terms"). Any redistribution of this code must retain the above copyright and this notice and otherwise comply with the Use Terms. / es5id: 15.10.6.29e1 description: > RegExp.prototype.exec the removed step 9.e won't affected current algorithm includes: [runTestCase.js]
function testcase() { var str = "Hello World!"; var regObj = new RegExp("World"); var result = false; result = regObj.exec(str).toString() === "World"; return result; }
[ "function testRegExp() {}", "function FUNC_NAME(rx, S, lengthS, replaceValue\n#ifdef SUBSTITUTION\n , firstDollarIndex\n#endif\n )\n{\n // 21.2.5.2.2 RegExpBuiltinExec, step 4.\n var lastIndex = ToLength(rx.lastIndex);\n\n // 21.2.5.2.2 RegExpBuiltinExec, step 5.\n // Side-effects in step 4 can recompile the RegExp, so we need to read the\n // flags again and handle the case when global was enabled even though this\n // function is optimized for non-global RegExps.\n var flags = UnsafeGetInt32FromReservedSlot(rx, REGEXP_FLAGS_SLOT);\n\n // 21.2.5.2.2 RegExpBuiltinExec, steps 6-7.\n var globalOrSticky = !!(flags & (REGEXP_GLOBAL_FLAG | REGEXP_STICKY_FLAG));\n\n if (globalOrSticky) {\n // 21.2.5.2.2 RegExpBuiltinExec, step 12.a.\n if (lastIndex > lengthS) {\n if (globalOrSticky)\n rx.lastIndex = 0;\n\n // Steps 12-16.\n return S;\n }\n } else {\n // 21.2.5.2.2 RegExpBuiltinExec, step 8.\n lastIndex = 0;\n }\n\n#if !defined(SHORT_STRING)\n // Step 11.a.\n var result = RegExpMatcher(rx, S, lastIndex);\n\n // Step 11.b.\n if (result === null) {\n // 21.2.5.2.2 RegExpBuiltinExec, steps 12.a.i, 12.c.i.\n if (globalOrSticky)\n rx.lastIndex = 0;\n\n // Steps 12-16.\n return S;\n }\n#else\n // Step 11.a.\n var result = RegExpSearcher(rx, S, lastIndex);\n\n // Step 11.b.\n if (result === -1) {\n // 21.2.5.2.2 RegExpBuiltinExec, steps 12.a.i, 12.c.i.\n if (globalOrSticky)\n rx.lastIndex = 0;\n\n // Steps 12-16.\n return S;\n }\n#endif\n\n // Steps 11.c, 12-13.\n\n#if !defined(SHORT_STRING)\n // Steps 14.a-b.\n assert(result.length >= 1, \"RegExpMatcher doesn't return an empty array\");\n\n // Step 14.c.\n var matched = result[0];\n\n // Step 14.d.\n var matchLength = matched.length;\n\n // Step 14.e-f.\n var position = result.index;\n\n // Step 14.l.iii (reordered)\n // To set rx.lastIndex before RegExpGetFunctionalReplacement.\n var nextSourcePosition = position + matchLength;\n#else\n // Steps 14.a-d (skipped).\n\n // Step 14.e-f.\n var position = result & 0x7fff;\n\n // Step 14.l.iii (reordered)\n var nextSourcePosition = (result >> 15) & 0x7fff;\n#endif\n\n // 21.2.5.2.2 RegExpBuiltinExec, step 15.\n if (globalOrSticky)\n rx.lastIndex = nextSourcePosition;\n\n var replacement;\n // Steps g-j.\n#if defined(FUNCTIONAL)\n replacement = RegExpGetFunctionalReplacement(result, S, position, replaceValue);\n#elif defined(SUBSTITUTION)\n replacement = RegExpGetSubstitution(result, S, position, replaceValue, firstDollarIndex);\n#else\n replacement = replaceValue;\n#endif\n\n // Step 14.l.ii.\n var accumulatedResult = Substring(S, 0, position) + replacement;\n\n // Step 15.\n if (nextSourcePosition >= lengthS)\n return accumulatedResult;\n\n // Step 16.\n return accumulatedResult + Substring(S, nextSourcePosition, lengthS - nextSourcePosition);\n}", "function exec(regex, fn, string) {\n let data;\n\n // If string looks like a regex result, get rest of string\n // from latest index\n if (typeof string !== 'string' && string.input !== undefined && string.index !== undefined) {\n data = string;\n string = data.input.slice(\n string.index\n + string[0].length\n + (string.consumed || 0)\n );\n }\n\n // Look for tokens\n const tokens = regex.exec(string);\n if (!tokens) { return; }\n\n const output = fn(tokens);\n\n // If we have a parent tokens object update its consumed count\n if (data) {\n data.consumed = (data.consumed || 0)\n + tokens.index\n + tokens[0].length\n + (tokens.consumed || 0) ;\n }\n\n return output;\n}", "function testcase() {\n var s = Object.prototype.toString.call(RegExp.prototype);\n return s === '[object Object]';\n }", "function CreateRegExpStringIterator(R, S, global, fullUnicode) { // eslint-disable-line no-unused-vars\n\t// 22.2.7.2 The %RegExpStringIteratorPrototype% Object\n\tvar RegExpStringIteratorPrototype = {}\n\n\t// 22.2.7.2.1 %RegExpStringIteratorPrototype%.next ( )\n\tCreateMethodProperty(RegExpStringIteratorPrototype, 'next', function next() {\n\t\t// 1. Let closure be a new Abstract Closure with no parameters that captures R, S, global, and fullUnicode and performs the following steps when called:\n\t\t// 1.a. Repeat,\n\t\t// 2. Return ! CreateIteratorFromClosure(closure, \"%RegExpStringIteratorPrototype%\", %RegExpStringIteratorPrototype%).\n\n\t\tif (this['[[Done]]'] === true) {\n\t\t\treturn CreateIterResultObject(undefined, true);\n\t\t}\n\n\t\t// 1.a.i. Let match be ? RegExpExec(R, S).\n\t\tvar match = RegExpExec(R, S);\n\t\t// 1.a.ii. If match is null, return undefined.\n\t\tif (match === null) {\n\t\t\tthis['[[Done]]'] = true;\n\t\t\treturn CreateIterResultObject(undefined, true);\n\t\t}\n\t\t// 1.a.iii. If global is false, then\n\t\tif (global === false) {\n\t\t\t// 1.a.iii.1. Perform ? Yield(match).\n\t\t\t// 1.a.iii.2. Return undefined.\n\t\t\tvar result = CreateIterResultObject(match, false);\n\t\t\tthis['[[Done]]'] = true;\n\t\t\treturn result;\n\t\t}\n\t\t// 1.a.iv. Let matchStr be ? ToString(? Get(match, \"0\")).\n\t\tvar matchStr = ToString(Get(match, '0'));\n\t\t// 1.a.v. If matchStr is the empty String, then\n\t\tif (matchStr === '') {\n\t\t\t// 1.a.v.1. Let thisIndex be ℝ(? ToLength(? Get(R, \"lastIndex\"))).\n\t\t\tvar thisIndex = ToLength(Get(R, 'lastIndex'));\n\t\t\t// 1.a.v.2. Let nextIndex be ! AdvanceStringIndex(S, thisIndex, fullUnicode).\n\t\t\tvar nextIndex = AdvanceStringIndex(S, thisIndex, fullUnicode);\n\t\t\t// 1.a.v.3. Perform ? Set(R, \"lastIndex\", 𝔽(nextIndex), true).\n\t\t\tR.lastIndex = nextIndex;\n\t\t}\n\t\t// 1.a.vi. Perform ? Yield(match).\n\t\treturn CreateIterResultObject(match, false);\n\t});\n\n\t// 22.2.7.2.2 %RegExpStringIteratorPrototype% [ @@toStringTag ]\n\tObject.defineProperty(RegExpStringIteratorPrototype, Symbol.toStringTag, {\n\t\tconfigurable: true,\n\t\tenumerable: false,\n\t\twritable: false,\n\t\tvalue: 'RegExp String Iterator'\n\t});\n\n\tCreateMethodProperty(RegExpStringIteratorPrototype, Symbol.iterator, function iterator() {\n\t\t\treturn this;\n\t\t}\n\t);\n\n\treturn RegExpStringIteratorPrototype;\n}", "function createJSRegExp($3ja,$3jb){\n if($3jb===undefined){$3jb=m$3g8.getEmpty();}\n //Switch statement at regexp.ceylon (8:1-18:1)\n var $3jc=$3ja;\n if(m$3g8.is$($3ja,{t:m$3g8.$_String})) {\n /*BEG dynblock*/\n return RegExp((typeof RegExp==='undefined'||RegExp===null?m$3g8.throwexc(m$3g8.Exception(\"Undefined or null reference: RegExp\"),'11:17-11:22','regexp.ceylon'):RegExp)($3jc,(function(){\n //SpreadOp at regexp.ceylon (11:35-11:47)\n var $3jd=[];\n var $3je=$3jb.iterator();\n var $3jf;\n while(($3jf=$3je.next())!==m$3g8.getFinished()){\n $3jd.push($3jf.string);\n }\n return m$3g8.sequence($3jd,{Element$sequence:{t:m$3g8.$_String},Absent$sequence:{t:m$3g8.Null}})||m$3g8.getEmpty();\n }())));\n /*END dynblock*/\n }else if(m$3g8.is$($3ja,{t:JSString})) {\n /*BEG dynblock*/\n return RegExp((typeof RegExp==='undefined'||RegExp===null?m$3g8.throwexc(m$3g8.Exception(\"Undefined or null reference: RegExp\"),'16:17-16:22','regexp.ceylon'):RegExp)($3jc.$_native,(function(){\n //SpreadOp at regexp.ceylon (16:42-16:54)\n var $3jg=[];\n var $3jh=$3jb.iterator();\n var $3ji;\n while(($3ji=$3jh.next())!==m$3g8.getFinished()){\n $3jg.push($3ji.string);\n }\n return m$3g8.sequence($3jg,{Element$sequence:{t:m$3g8.$_String},Absent$sequence:{t:m$3g8.Null}})||m$3g8.getEmpty();\n }())));\n /*END dynblock*/\n }//End switch statement at regexp.ceylon (8:1-18:1)\n}", "function RegularExpression(){}", "function createRegExpRestore(){if(internals.disableRegExpRestore){return function(){/* no-op */};}var regExpCache={lastMatch:RegExp.lastMatch||'',leftContext:RegExp.leftContext,multiline:RegExp.multiline,input:RegExp.input},has=false;// Create a snapshot of all the 'captured' properties\nfor(var i=1;i<=9;i++){has=(regExpCache['$'+i]=RegExp['$'+i])||has;}return function(){// Now we've snapshotted some properties, escape the lastMatch string\nvar esc=/[.?*+^$[\\]\\\\(){}|-]/g,lm=regExpCache.lastMatch.replace(esc,'\\\\$&'),reg=new List();// If any of the captured strings were non-empty, iterate over them all\nif(has){for(var _i=1;_i<=9;_i++){var m=regExpCache['$'+_i];// If it's empty, add an empty capturing group\nif(!m)lm='()'+lm;// Else find the string in lm and escape & wrap it to capture it\nelse{m=m.replace(esc,'\\\\$&');lm=lm.replace(m,'('+m+')');}// Push it to the reg and chop lm to make sure further groups come after\narrPush.call(reg,lm.slice(0,lm.indexOf('(')+1));lm=lm.slice(lm.indexOf('(')+1);}}var exprStr=arrJoin.call(reg,'')+lm;// Shorten the regex by replacing each part of the expression with a match\n// for a string of that exact length. This is safe for the type of\n// expressions generated above, because the expression matches the whole\n// match string, so we know each group and each segment between capturing\n// groups can be matched by its length alone.\nexprStr=exprStr.replace(/(\\\\\\(|\\\\\\)|[^()])+/g,function(match){return'[\\\\s\\\\S]{'+match.replace('\\\\','').length+'}';});// Create the regular expression that will reconstruct the RegExp properties\nvar expr=new RegExp(exprStr,regExpCache.multiline?'gm':'g');// Set the lastIndex of the generated expression to ensure that the match\n// is found in the correct index.\nexpr.lastIndex=regExpCache.leftContext.length;expr.exec(regExpCache.input);};}", "function Regexp() {}", "function exec(regex) {\r\r\n\t\treturn regex.exec(Detectizr.browser.userAgent);\r\r\n\t}", "function native__LazyAllMatchesIterator__computeNextMatch(regExp, str) {\n var re = this.re;\n if (re === null) return $Dart$Null;\n var m = re.exec(str);\n if (m == null) {\n this.re = null;\n return $Dart$Null;\n }\n var match = native_JSSyntaxMatch__new(regExp, str);\n match.match_ = m;\n match.lastIndex_ = re.lastIndex;\n return match;\n}", "function testInvalidEscapeSequence() {\n\tvar input = fs.readFileSync(\"../TestCases/gitHub#65-backslash_invalidEscapeSequence.js\", { encoding:\"utf8\"});\n\tvar options = {\n\t\twithMath : false,\n\t\thash2DContext : false,\n\t\thashWebGLContext : false,\n\t\thashAudioContext : false,\n\t\tcontextVariableName : false,\n\t\tcontextType : parseInt(0),\n\t\treassignVars : false,\n\t\tvarsNotReassigned : [],\n\t\tcrushGainFactor : parseFloat(2),\n\t\tcrushLengthFactor : parseFloat(1),\n\t\tcrushCopiesFactor : parseFloat(0),\n\t\tcrushTiebreakerFactor : parseInt(1),\n\t\twrapInSetInterval : false,\n\t\ttimeVariableName : \"\",\n\t\tuseES6 : true\n\t};\n\t\n\tvar output = RegPack.packer.runPacker(input, options);\n\t\n\t// Expected result : the regular expression decodes correctly and matches the original code\n\tassert.notEqual(output[0].result[1][2].indexOf(\"Final check : passed\"), -1);\n\tassert.notEqual(output[0].result[2][2].indexOf(\"Final check : passed\"), -1);\n\n\t// Expected result : the output from each stage has backslashes escaped\n\tassertAllBackslashesDoubled(output[0].result[0][1]);\n\tassertAllBackslashesDoubled(output[0].result[1][1]);\n\tassertAllBackslashesDoubled(output[0].result[2][1]);\n}", "function exec(regex) {\n\t\treturn regex.exec(Detectizr.browser.userAgent);\n\t}", "function testcase() {\n\n // objects inherit the default valueOf() method from Object\n // that simply returns itself. Since the default valueOf() method\n // does not return a primitive value, ES next tries to convert the object\n // to a number by calling its toString() method and converting the\n // resulting string to a number.\n var fromIndex = {\n toString: function () {\n return '2';\n }\n };\n var targetObj = new RegExp();\n\n return [0, true, targetObj, 3, false].lastIndexOf(targetObj, fromIndex) === 2 &&\n [0, true, 3, targetObj, false].lastIndexOf(targetObj, fromIndex) === -1;\n }", "exec(regex) {\n\n\t\treturn regex.exec(this.browser.userAgent);\n\t}", "function RegExpLiteralExpression() {\n}", "function makeRegExp() {\n return new RegExp([].reduce.call(arguments, (acc, x) => acc + x.source, ''));\n}", "function StringMatcher() {}", "function testIncorrectReplacement() {\n\tvar input = fs.readFileSync(\"../TestCases/gitHub#73-backslash_unexpandedToken.js\", { encoding:\"utf8\"});\n\tvar options = {\n\t\twithMath : false,\n\t\thash2DContext : false,\n\t\thashWebGLContext : false,\n\t\thashAudioContext : false,\n\t\tcontextVariableName : false,\n\t\tcontextType : parseInt(0),\n\t\treassignVars : false,\n\t\tvarsNotReassigned : [],\n\t\tcrushGainFactor : parseFloat(2),\n\t\tcrushLengthFactor : parseFloat(1),\n\t\tcrushCopiesFactor : parseFloat(0),\n\t\tcrushTiebreakerFactor : parseInt(1),\n\t\twrapInSetInterval : false,\n\t\ttimeVariableName : \"\",\n\t\tuseES6 : true\n\t};\n\t\n\tvar output = RegPack.packer.runPacker(input, options);\n\t\n\t// Expected result : the regular expression decodes correctly and matches the original code\n\tassert.notEqual(output[0].result[1][2].indexOf(\"Final check : passed\"), -1);\n\tassert.notEqual(output[0].result[2][2].indexOf(\"Final check : passed\"), -1);\n\n\t// Expected result : the output from each stage has backslashes escaped\n\tassertAllBackslashesDoubled(output[0].result[0][1]);\n\tassertAllBackslashesDoubled(output[0].result[1][1]);\n\tassertAllBackslashesDoubled(output[0].result[2][1]);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function named `countOdds` that accepts an array of numbers and returns the number of odd numbers in the array. countOdds([1, 2, 3]) // 2 countOdds([4, 6, 8, 10]) // 0 countOdds([1, 2, 1, 1]) // 3
function countOdds(arr) { var numberOfOdds = 0; arr.forEach(function (element) { if (element % 2 !== 0) { numberOfOdds++; } }); return numberOfOdds; }
[ "function countOdds(arr) {\n var count = 0;\n for(var i=0;i<arr.length;i++) {\n if(arr[i] % 2 !== 0) {\n count++;\n }\n }\n return count;\n}", "function countsOdds(array){\n var total = 0;\n for (var i = 0; i < array.length; i++){\n if (array[i] % 2 != 0) {\n total ++;\n }\n }\n return total;\n}", "function countOdds(arr){\n var count = 0;\n arr.forEach(function(element, i){\n if(element % 2 !== 0){\n count += 1;\n }\n })\n return count;\n}", "function numOddValues (array) {\n let numOfOdds = 0;\n for (let i = 0; i < array.length; i++) {\n if (array[i] % 2 !== 0) {\n numOfOdds += 1;\n }\n }\n return numOfOdds;\n}", "function evenOddCount(arr)\n{\n var even = 0;\n var odd = 0;\n for(var i = 0;i < arr.length; i++ )\n {\n if(arr[i] % 2 == 0)\n {\n even++;\n odd = 0;\n if(even == 3)\n console.log(\"Even more so!\");\n }\n else\n {\n odd++;\n even = 0;\n if(odd == 3)\n console.log(\"That's odd!\");\n }\n }\n}", "function countEvenOdd() {\n let numbers = [100, 20, 33, 45, 44, 37, 10, 2, 3, 5, 15, 12, 31, 32, 88, 94, 61, 63, 77, 66, 27, 1, 7, 8, 9];\n let evenCount = 0;\n let oddCount = 0;\n for (let i = 0; i < numbers.length; i++) {\n //check if odd or even\n if (numbers[i] % 2 === 0) {\n evenCount++;\n } else {\n oddCount++;\n }\n }\n // return [evenCount, oddCount];\n console.log('number of even numbers is ', evenCount);\n console.log('number of odd numbers is ', oddCount);\n}", "function how_many_even(array){\n var count = 0;\n for(idx = 0; idx < array.length; idx++){\n if(is_even(array[idx])){\n count++;\n }\n }\n return count;\n}", "function sumOdds(numbers) {\n let odds = [];\n for (let i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2 === 1) odds.push(numbers[i]);\n }\n return odds.reduce((a, b) => a + b, 0);\n}", "function how_many_even(arr){\n let cnt = 0;\n for(let i = 0; i < arr.length; i++){\n if(is_even(arr[i])){\n cnt++;\n }\n }\n return cnt;\n}", "function evenOdd(array){\n\n \n let nnumberEven= 0\n let nnumberodd= 0\n\n for (let i = 0; i < array.length; i++){\n\n if(array[i] %2 === 0)\n {\n nnumberEven++;\n }\n else{\n nnumberodd++;\n }\n }\n\n \n console.log(\"number of odd element :\" + nnumberodd)\n console.log(\"number of even element :\" + nnumberEven)\n}", "function countEvensAndOdds(arr) {\n\tvar count = {\n\t\toddCount: 0,\n\t\tevenCount: 0\n\t};\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tif (arr[i] % 2 === 0) {\n\t\t\tcount.evenCount += 1;\n\t\t} else {\n\t\t\tcount.oddCount += 1;\n\t\t}\n\t}\n\treturn count;\n}", "function sumOdds(numbers) {\n let oddNums = 0;\n for (let i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2 === 1) {\n oddNums += numbers[i];\n }\n }\n\n return oddNums;\n}", "function evensAndOdds(arr){\n var oddCount = 0\n var evenCount = 0\n for(var i =0; i < arr.length; i++) {\n if (arr[i] % 2 != 0) {\n oddCount++\n evenCount = 0\n if (oddCount == 3) {\n console.log(\"That's odd!\")\n oddCount = 0\n }\n } else {\n evenCount++\n oddCount = 0\n if (evenCount == 3) {\n console.log(\"Even more so!\")\n evenCount = 0\n }\n }\n }\n}", "function sumOfOdd(array) {\n var sum = 0;\n for (i = 0; i < array.length; i++) {\n if (array[i] % 2 === 1) {\n sum += array[i];\n }\n }\n return sum;\n}", "function countOddsAndEvens(arr) {\n return {\n odds: arr.reduce((acc, curr) => { return curr % 2 === 0 ? acc + 1 : acc }, 0),\n evens: arr.reduce((acc, curr) => { return curr % 2 !== 0 ? acc + 1 : acc }, 0)\n }\n}", "function how_many_even(arr){\n\tvar count = 0;\n\tfor (var i = 0; i < arr.length; i++){\n\t\tif (is_even(arr[i]) == true){\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}", "function evensOdds(arr){\n odds = 0;\n evens = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 1){\n evens = 0;\n odds++;\n if(odds % 3 == 0){\n console.log(\"That's odd!\");\n odds = 0;\n }\n } \n else if(arr[i] % 2 == 0){\n odds = 0;\n evens++;\n if(evens % 3 == 0){\n console.log (\"Even more so!\");\n evens = 0;\n }\n }\n } \n}", "function oddSum(array) {\n\tvar sum = 0\n\tfor (var i = 0; i < array.length; i++) {\n\t\tif (isOdd(array[i])) {\n\t\t\tsum += array[i];\n\t\t}\n\t}\n\treturn sum;\n}", "function oddCount(n){\n let oddCount = 0;\n for (let i = 0; i < n; i++) {\n if (i % 2 !== 0) {\n oddCount += 1\n }\n }\n return oddCount;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lowercase all letters of a string if force=true, capitalize first letter
function ucfirst(str,force){ str=force ? str.toLowerCase() : str; return str.replace(/(\b)([a-zA-Z])/, function(firstLetter){ return firstLetter.toUpperCase(); }); }
[ "function capitalizeLetters(str) {}", "function autoEd_first2lower(str) {\n if (str != \"\") {\n var letter = str.substr(0, 1);\n return letter.toLowerCase() + str.substr(1, str.length);\n } else {\n return \"\";\n }\n}", "function InitializeFirstLetter(value){\n return value.substring(0,1).toUpperCase()+ value.substring(1,value.length).toLowerCase();\n}", "function capitalizeLetters(str) { }", "function titlecase(str){\n return str.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}", "capatilizeFirstLetter(desc){\n return (desc.charAt(0).toUpperCase() + desc.substr(1));\n }", "function capitalizeAllWords(string) {\n \n}", "function capitalize(str){return str.charAt(0).toUpperCase()+str.slice(1);}", "function first_letter_capitalize(name){\n return name.charAt(0).toUpperCase() + name.slice(1)\n }", "function lowercase(input) {}", "function checkFirstLetterCapitalized( word ){\n\n}", "CapitalizeFix (string) {\n string = string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n return string.replace(/(^|[\\s-'])\\S/g, function (match) {\n return match.toUpperCase();\n });\n }", "function setFirstCharToUpper(text) {\n return text.substr(0, 1).toUpperCase() + text.substr(1).toLowerCase()\n}", "function fn_CapitalizeFirstChar(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}", "function capitalize_first_letter(string)\n{\n return string.charAt(0).toUpperCase() + string.slice(1);\n}", "function initCaps(string) {\n return string.replace(/(^|\\s)([a-z])/g, function(m, p1, p2) {\n return p1 + p2.toUpperCase();\n });\n}", "function capitalizeWord(string) {\n \n}", "function capitalizeFirstLetter(str) {\n\n return str.replace(/\\w\\S*/g, function(text) {\n return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();\n });\n}", "function hToUpperFirstLetter(textToChange = \"\") {\n return textToChange.charAt(0).toUpperCase() + textToChange.slice(1);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
After 1.5 was released, the search box was moved into an optional toolbar item, with a different ID. This function keeps us compatible with both.
function findMailSearchBox() { var tb15Box = document.getElementById("searchBox"); if (tb15Box) { return tb15Box; } var tb2Box = document.getElementById("searchInput"); if (tb2Box) { return tb2Box; } // In later versions, it's possible that a user removed the search box from // the toolbar. return null; }
[ "function main_queryBarOnInput(element)\n{\n\tsearch_showAutocomplete(element.value);\n\tmain_loadBrowser();\n}", "function SearchBarClicked(id, defaultText, style) {\n var selectedElement = document.getElementById(id);\n if (selectedElement.value == defaultText) {\n selectedElement.value = \"\";\n selectedElement.className = style;\n }\n}", "function searchItems(){\n\t\n\t// Autocompleter for the search box\n\t// Initiated onload\n\t\n\n\tvar mAjax = new Ajax.Autocompleter(\n\t\t\"LN-toolbar-searchbox\", \n\t\t\"content_search\", \n\t\t\"/interface/show/search/\", \n\t\t{\n\t\t\tparamName: \"s\", \n\t\t\tminChars: 1,\n\t\t\ttokens: ',',\n\t\t\tindicator: 'spinner',\n\t\t\tupdateElement: function(item){\n\t\t\t\t\n\t\t\t}\n\t\t});\n\t\n}", "function initToolbar(searchTerm) {\n var url = \"toolbar/ui.html?searchTerm=\" + searchTerm;\n var iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"id\", \"augmentedSearch\");\n iframe.setAttribute(\"src\", chrome.runtime.getURL(url));\n iframe.setAttribute(\"style\", \"position: fixed; bottom: 0; left: 0; z-index: 10000; width: 100%; height: 200px;\");\n document.body.appendChild(iframe);\n\n return toolbarUI = {\n iframe: iframe, visible: true\n };\n}", "function _toolbar_action(strID)\r\n{\r\n\t//-- call code for form type\r\n\tapp._CURRENT_JS_WINDOW = window;\r\n\t_swdoc_pointer._process_form_toolbar_action(strID);\r\n}", "function _init_search_bar(){\n try{\n var flexSpace = Titanium.UI.createButton({\n systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE\n });\n\n self.searchBar = Ti.UI.createSearchBar({\n showCancel:false,\n hintText:'Search Client',\n autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,\n height:self.tool_bar_height,\n width:self.screen_width\n });\n \n var searchToolbar = Ti.UI.iOS.createToolbar({\n items:[flexSpace,self.searchBar,flexSpace],\n top:0,\n buttom:0,\n borderColor:self.tool_bar_color_in_ios_7,\n borderWidth:1\n });\n win.add(searchToolbar);\n\n self.searchBar.addEventListener('change',function(e){\n self.searchBar.showCancel = true;\n _search_text = e.value;\n _search_text = self.replace(_search_text,'\\\"','');//remove \" symbol\n _search_text = self.replace(_search_text,'\\'','');//remove ' symbol' \n self.display();\n });\n\n self.searchBar.addEventListener('return',function(e){\n self.searchBar.blur();\n self.searchBar.showCancel = false;\n _search_text = e.value;\n _search_text = self.replace(_search_text,'\\\"','');//remove \" symbol\n _search_text = self.replace(_search_text,'\\'','');//remove ' symbol' \n self.begin_download_more_jobs_by_scroll_down();\n });\n\n self.searchBar.addEventListener('cancel',function(e){\n self.searchBar.value = '';\n self.searchBar.blur();\n self.searchBar.showCancel = false;\n _search_text = '';\n self.display();\n });\n\n self.searchBar.addEventListener('focus', function(e){\n self.searchBar.showCancel = true;\n _selected_field_object = e.source;\n });\n\n self.searchBar.addEventListener('blur', function(e){\n self.searchBar.showCancel = false;\n _selected_field_object = null;\n }); \n }catch(err){\n self.process_simple_error_message(err,window_source+' - _init_search_bar');\n return;\n } \n }", "function searchBarFocus() {\n $ctrl.showCancel = true;\n }", "function renderSearchBar() {\n}", "function _init_search_bar(){\n try{\n var flexSpace = Titanium.UI.createButton({\n systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE\n });\n\n self.searchBar = Ti.UI.createSearchBar({\n showCancel:false,\n hintText:'Search Client',\n autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,\n height:self.tool_bar_height,\n width:self.screen_width\n });\n var searchToolbar = Ti.UI.iOS.createToolbar({\n items:[flexSpace,self.searchBar,flexSpace],\n top:0,\n buttom:0,\n borderColor:self.tool_bar_color_in_ios_7,\n borderWidth:1\n });\n win.add(searchToolbar);\n\n self.searchBar.addEventListener('change',function(e){\n self.searchBar.showCancel = true;\n _search_text = e.value;\n _search_text = self.replace(_search_text,'\\\"','');//remove \" symbol\n _search_text = self.replace(_search_text,'\\'','');//remove ' symbol' \n self.display();\n });\n\n self.searchBar.addEventListener('return',function(e){\n self.searchBar.blur();\n self.searchBar.showCancel = false;\n _search_text = e.value;\n _search_text = self.replace(_search_text,'\\\"','');//remove \" symbol\n _search_text = self.replace(_search_text,'\\'','');//remove ' symbol' \n self.begin_download_more_jobs_by_scroll_down();\n });\n\n self.searchBar.addEventListener('cancel',function(e){\n self.searchBar.value = '';\n self.searchBar.blur();\n self.searchBar.showCancel = false;\n _search_text = '';\n self.display();\n });\n\n self.searchBar.addEventListener('focus', function(e){\n self.searchBar.showCancel = true;\n _selected_field_object = e.source;\n });\n\n self.searchBar.addEventListener('blur', function(e){\n self.searchBar.showCancel = false;\n _selected_field_object = null;\n }); \n }catch(err){\n self.process_simple_error_message(err,window_source+' - _init_search_bar');\n return;\n } \n }", "function showFieldSearch() {\n var $toolbar = $('.fixed-table-toolbar');\n var $searchBox = $toolbar.find('div.search');\n if($searchBox.css('visibility') == 'hidden') {\n $searchBox.css('visibility', 'visible');\n } else {\n $searchBox.css('visibility', 'hidden'); \n }\n}", "function reset_tool_search(initValue) {\n // Function may be called in top frame or in tool_menu_frame;\n // in either case, get the tool menu frame.\n var tool_menu_frame = $(\"#galaxy_tools\").contents();\n if (tool_menu_frame.length === 0) {\n tool_menu_frame = $(document);\n // Remove classes that indicate searching is active.\n $(this).removeClass(\"search_active\");\n tool_menu_frame.find(\".toolTitle\").removeClass(\"search_match\");\n\n // Reset visibility of tools and labels.\n tool_menu_frame.find(\".toolSectionBody\").hide();\n tool_menu_frame.find(\".toolTitle\").show();\n tool_menu_frame.find(\".toolPanelLabel\").show();\n tool_menu_frame.find(\".toolSectionWrapper\").each(function() {\n if ($(this).attr(\"id\") !== \"recently_used_wrapper\") {\n // Default action.\n $(this).show();\n } else if ($(this).hasClass(\"user_pref_visible\")) {\n $(this).show();\n }\n });\n tool_menu_frame.find(\"#search-no-results\").hide();\n\n // Reset search input.\n tool_menu_frame.find(\"#search-spinner\").hide();\n if (initValue) {\n var search_input = tool_menu_frame.find(\"#tool-search-query\");\n search_input.val(\"search tools\");\n }\n }\n}", "get searchBar() {\n return document.getElementById(\"searchbar\");\n }", "function reset_tool_search( initValue ) {\n // Function may be called in top frame or in tool_menu_frame;\n // in either case, get the tool menu frame.\n var tool_menu_frame = $(\"#galaxy_tools\").contents();\n if (tool_menu_frame.length === 0) {\n tool_menu_frame = $(document);\n }\n\n // Remove classes that indicate searching is active.\n $(this).removeClass(\"search_active\");\n tool_menu_frame.find(\".toolTitle\").removeClass(\"search_match\");\n\n // Reset visibility of tools and labels.\n tool_menu_frame.find(\".toolSectionBody\").hide();\n tool_menu_frame.find(\".toolTitle\").show();\n tool_menu_frame.find(\".toolPanelLabel\").show();\n tool_menu_frame.find(\".toolSectionWrapper\").each( function() {\n if ($(this).attr('id') !== 'recently_used_wrapper') {\n // Default action.\n $(this).show();\n } else if ($(this).hasClass(\"user_pref_visible\")) {\n $(this).show();\n }\n });\n tool_menu_frame.find(\"#search-no-results\").hide();\n\n // Reset search input.\n tool_menu_frame.find(\"#search-spinner\").hide();\n if (initValue) {\n var search_input = tool_menu_frame.find(\"#tool-search-query\");\n search_input.val(\"search tools\");\n }\n}", "function toolbarItem( identifier, view, willBeInserted ) {\n}", "addSearchItems(menu, menuInfo) {\n if (!menuInfo.selectionText || menuInfo.selectionText.length < 1) {\n return menu;\n }\n\n let match = matchesWord(menuInfo.selectionText);\n if (!match || match.length === 0) {\n return menu;\n }\n\n if (process.platform === 'darwin') {\n let target = this.getWebContents();\n\n let lookUpDefinition = new MenuItem({\n label: this.stringTable.lookUpDefinition({word: truncateString(menuInfo.selectionText)}),\n click: () => target.showDefinitionForSelection()\n });\n\n menu.append(lookUpDefinition);\n }\n\n let search = new MenuItem({\n label: this.stringTable.searchGoogle(),\n click: () => {\n let url = `https://www.google.com/#q=${encodeURIComponent(menuInfo.selectionText)}`;\n\n //d(`Searching Google using ${url}`);\n shell.openExternal(url);\n }\n });\n\n menu.append(search);\n this.addSeparator(menu);\n\n return menu;\n }", "_onSearchClick() {\n this._commitSearch('*');\n }", "function reset_tool_search( initValue ) {\n // Function may be called in top frame or in tool_menu_frame; \n // in either case, get the tool menu frame.\n var tool_menu_frame = $(\"#galaxy_tools\").contents();\n if (tool_menu_frame.length === 0) {\n tool_menu_frame = $(document);\n }\n \n // Remove classes that indicate searching is active.\n $(this).removeClass(\"search_active\");\n tool_menu_frame.find(\".toolTitle\").removeClass(\"search_match\");\n \n // Reset visibility of tools and labels.\n tool_menu_frame.find(\".toolSectionBody\").hide();\n tool_menu_frame.find(\".toolTitle\").show();\n tool_menu_frame.find(\".toolPanelLabel\").show();\n tool_menu_frame.find(\".toolSectionWrapper\").each( function() {\n if ($(this).attr('id') != 'recently_used_wrapper') {\n // Default action.\n $(this).show();\n } else if ($(this).hasClass(\"user_pref_visible\")) {\n $(this).show();\n }\n });\n tool_menu_frame.find(\"#search-no-results\").hide();\n \n // Reset search input.\n tool_menu_frame.find(\"#search-spinner\").hide();\n if (initValue) {\n var search_input = tool_menu_frame.find(\"#tool-search-query\");\n search_input.val(\"search tools\");\n }\n}", "_onSearchChange(filter) {\n if (! filter) {\n for (const id in this._indexAssets) {\n this._indexAssets[id].element.hidden = false;\n }\n return;\n }\n\n const items = [];\n for (const id in this._indexAssets) {\n items.push([this._indexAssets[id].label.value, id]);\n }\n\n // TODO: use a class here instead of a global seach:items\n const results = editor.call('search:items', items, filter);\n for (const id in this._indexAssets) {\n if (results.indexOf(id) === -1) {\n this._indexAssets[id].element.hidden = true;\n } else {\n this._indexAssets[id].element.hidden = false;\n }\n }\n\n }", "get searchBox () { return $('#globalSearch') }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get logfile by logfile name. Return log data in an array
function getLogfile(logfileName){ var logFile = []; $.ajax({ type: "GET", url: 'backend/index.php', data: {key: '4me302A3', method:'logfile', value1:logfileName}, async: false, dataType: "json" }) .done(function(data){ logFile = data; }) .fail(function() { return "ajax get logfile error"; }); return createArr(logFile); }
[ "async function getLogs() {\n\tconst filenames = await fsp.readdir(path.resolve(__dirname, '../../logs'));\n\tconst logs = [];\n\tfor (const filename of filenames) {\n\t\tif (!filename.includes('.log')) continue;\n\t\tlogs.push({\n\t\t\tname: filename,\n\t\t\tdate: filename.substr(11, 10)\n\t\t});\n\t}\n\treturn logs;\n}", "function getLogData(filename, done) {\n readFile('/Users/Didi/Desktop/BuildFailures/' + filename, function(data) {\n var logs = [];\n data.match(/\\s*\"build_log\"\\s?: \".*\"/g).forEach(function(e){\n logs.push(e.match(/\\s*\"build_log\"\\s?: \"(.*)\"/)[1]);\n });\n\n\n//Get the build_log field from Buildfailures.txt file without using RegEx\n //var lines = data.split('\\n');\n //var keyword = '\"build_log\" : ', index;\n //lines.forEach(function(line){\n // index = line.indexOf(keyword);\n // if (index != -1) {\n // logs.push(line.slice(index + keyword.length, line.length - 2));\n // }\n //});\n\n done(logs);\n });\n}", "async function readLogs (filename) {\n try {\n // const { name } = this.validateFlags(flags)\n\n // this.log(`Opening file ${name}`);\n\n const data = await openLogFile(filename)\n\n for (let i = 0; i < data.length; i++) {\n const thisEntry = data[i]\n\n console.log(`${thisEntry.timestamp}: ${thisEntry.message}`)\n }\n } catch (err) {\n console.log('Error in readLogs(): ', err)\n }\n}", "function logNames(logs_config) {\n var path;\n var filelist = {};\n // iterate over specified sorts of logs\n for (var key in logs_config) {\n if (logs_config.hasOwnProperty(key)) {\n // get location\n path = logs_config[key]['location'];\n // get all files in the directory\n var cfiles = fs.readdirSync(path);\n // note\n // if type is 'dynamic', will watch changes in tail -f manner\n // if type is 'static' will just open log files in new window\n filelist[key] = {'type': logs_config[key]['type'],\n 'files': []};\n cfiles.forEach(function(file) {\n // file has right extension?\n var right_extension = false;\n for (var i = 0; i < logs_config[key]['extensions'].length; i++) {\n right_extension = right_extension || file.endsWith(logs_config[key]['extensions'][i]);\n }\n // push to filelist if has right extension and not invisible\n if (right_extension && !file.startsWith('.')) {\n filelist[key]['files'].push(file);\n }\n });\n }\n }\n\n return filelist;\n}", "function getLog(key){\n\tlet tmp = key.replace('log',''); //remove log prefix from the key to get the number\n\tlogNumber = Number(tmp); //parse the string into a number\n\tlocalforage.getItem('logs') //load the logs from memory\n\t.then((logs)=>{\n\t\tlet log = logs[key]; //get our log at the parameter key.\n\t\tconsole.log(log)\n\t\tfor(let field in log){ //itwerage over the fields of the log\n\t\t\tlet value = log[field];\n\t\t\tif(typeof value === \"string\") //if the field is a string, it goes to a text input\n\t\t\t\t$(`.${field}`).val(value);\n\t\t\telse if(value){ //or else it is a checkbox\n\t\t\t\t$(`input[val=${field}]`).prop('checked',true);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$(`input[val=${field}]`).prop('checked',false);\n\t\t\t}\n\t\t}\n\t})\n\n\treturn\n}", "function getFile(file_name) {\r\n\tvar file_aggregate = aggregate.getSelected();\r\n\t\r\n\tvar array;\r\n\t\r\n\t// iterates through file_data array looking for the correct file\r\n\t// the name and aggregate server as a unique ID for the file\r\n\tfor(i = 0; i < file_data.length; i++) {\r\n\t\tif(file_name == file_data[i].formatted &&\r\n\t\t file_aggregate == file_data[i].aggregate) {\r\n\t\t\t\r\n\t\t\tarray = file_data[i];\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn array;\r\n}", "function getLogByName(req,res){\n var name = req.query.name;\n\n // Read in the file they requested.\n fs.readFile(path.join(__dirname,'..',LOGS_PATH, name), 'utf8', function (err,data) {\n if (err) {\n return console.log(err);\n }\n // console.log('Read in: '+data);\n\n // Make sure there is data in the file. Otherwise, alert the user.\n if(data){\n jsonData = JSON.parse(data);\n var log = \"\";\n for (var i = 0; i< jsonData.length; i++) {\n log += jsonData[i].user + \": \" + jsonData[i].data + \"\\n\";\n }\n res.statusCode=200;\n res.header('Content-Disposition', \"filename=\" + name.substr(0, name.length-5) + \".txt\");\n res.header(\"Content-Type\", \"text/plain\");\n res.send(log);\n } else{\n res.statusCode=200;\n res.send('There were no messages in that file.');\n }\n});\n}", "function getLogEventStrings() {\n var eventsArr = [];\n var str = Logger.getLog();\n var arr = str.split(\"\\n\");\n// Logger.log(\"arr=\" + arr.length);\n for (var i in arr) {\n// Logger.log(\"arr[\" + i + \"]=\" + arr[i]);\n if ( arr[i].length > 0 ) {\n var regexResult = /.+?INFO: \\[EVENT\\] (.+)/.exec(arr[i]); //Is log string of [EVENT] type\n if (regexResult && regexResult[0].length>0) eventsArr.push(regexResult[1]);\n }\n }\n return eventsArr;\n}", "function getDomainLogFiles(domain) {\n const deferred = when.defer();\n const files = [];\n\n // check for standard log\n const pathname = path.join(getHomeDirectory(), 'access-logs', domain);\n fs.exists(pathname, (yes) => {\n if (yes) {\n files.push(new ScanFile(undefined, pathname, domain));\n }\n\n // check for secure log\n const sslPathname = pathname + '-ssl_log';\n fs.exists(sslPathname, (yes) => {\n if (yes) {\n files.push(new ScanFile(undefined, sslPathname, domain));\n }\n deferred.resolve(files);\n });\n });\n\n return deferred.promise;\n}", "function readLogFile(file) {\n file = file ? file : logFile;\n return file.read().text;\n }", "function getApiLogs(req, res) {\n // Get size of log file\n const { size } = fs.statSync(minecraftLogFile);\n // Get last 10000 bytes of logs\n const stream = fs.createReadStream(minecraftLogFile, {\n start: size - 10000,\n end: size\n });\n let logs = \"\";\n stream.on(\"data\", data => {\n logs += data;\n });\n // After all data is read,\n // send logs back\n stream.on(\"close\", () =>\n res.json({\n success: true,\n data: logs\n })\n );\n}", "function getLog(logName, section = null) {\n\n // create log file by logName if it does not exist\n // if (!logs[logName]) {\n // const primaryDrive = storage.getPrimaryDriveInConfig();\n // const logFolder = path.join(primaryDrive.mountPoint, config.get('/baseFolder'), config.get('/logFolder'));\n // const hasLogFolder = fs.existsSync(logFolder);\n // if (!hasLogFolder) {\n // mkdirp.sync(logFolder);\n // }\n\n // logs[logName] = loggers.createLogger(logName, logFolder, true);\n // }\n\n return {\n log: (...argsList) => logItem(logName, 'info', section, ...argsList),\n trace: (...argsList) => logItem(logName, 'trace', section, ...argsList),\n debug: (...argsList) => logItem(logName, 'debug', section, ...argsList),\n info: (...argsList) => logItem(logName, 'info', section, ...argsList),\n warn: (...argsList) => logItem(logName, 'warn', section, ...argsList),\n error: (...argsList) => logItem(logName, 'error', section, ...argsList),\n }\n\n}", "function getFileLog(file){\n file_log=[]\n return MIRESAdmin.firestore().collection(MIRESconfig.MIRES_storage_log).where('file_path','==',file).orderBy(\"timestamp\",\"asc\").get()\n .then(log => {\n if(log.empty){\n console.log(\"getFileLog function: there are no logs.\")\n return file_log;\n }\n else{\n log.forEach(row =>{\n file_log.push({\n id:row.id,\n file_path:row.data().file_path,\n generation: row.data().generation,\n type: row.data().type,\n transaction_id : row.data().transaction_id,\n });\n })\n return file_log;\n }\n }) .catch(err => {\n console.log(\"getFileLog function: \"+ err);\n }); \n}", "_readLogFile() {\n\t\tvar self = this;\n\t\tvar theLogs = fs.readFileSync(this.logFile, 'utf8').toString().split('##');\n\t\ttheLogs.shift();\n\t\t// Log to the console\n\t\ttheLogs.forEach(function (log) {\n\t\t\tself.atomToPhotoshopView._sendMessageToConsole(log);\n\t\t});\n\t}", "async getContainerLogData(id) {\n return readFile(this.getFileNameForContainer(id));\n }", "function getDataFromFile(file, name){\n var records = [];\n var content = fs.readFileSync(file).toString().split('\\n');\n content.forEach(function(data){\n records.push(data);\n });\n return records;\n}", "loadLogFile(logFile) {\n if (logFile) {\n this.setLoadFileStatus('Loading log...', true);\n var fileReader = new FileReader();\n fileReader.onerror = this.onLoadLogFileError.bind(this);\n\n if (logFile.name.toLowerCase().endsWith('.zip')) {\n fileReader.onload = this.onLoadZip.bind(this, logFile);\n fileReader.readAsArrayBuffer(logFile);\n } else {\n fileReader.onload = this.onLoadLogFile.bind(this, logFile);\n fileReader.readAsText(logFile);\n }\n }\n }", "function getDomainLogFiles(domain, cannonical) {\n var deferred = when.defer();\n var files = [];\n var filename, pathname;\n\n // check for standard log\n filename = path.join(CPANEL_PREFIX, domain);\n pathname = scanfile.getRootPathname(filename);\n fs.exists(pathname, function (yes) {\n if (yes) {\n files.push(new scanfile.ScanFile(filename, pathname, cannonical));\n }\n\n // check for secure log\n filename += '-ssl_log';\n pathname += '-ssl_log';\n fs.exists(pathname, function (yes) {\n if (yes) {\n files.push(new scanfile.ScanFile(filename, pathname, cannonical));\n }\n deferred.resolve(files);\n });\n });\n\n return deferred.promise;\n}", "getLogs(aId) {\n check(aId, String)\n\n return Logger.find({ aId }).fetch()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates URL instance as a protocol. This will be convenience when we need HTTP server as Story trigger. ( Object | String : from draft. ) > URL
generate_protocol(draft){ /* * { * story: "", * page: "", * premise: { * } * } */ let id = ""; let pf = "scene"; let rg = new RegExp("^" + pf + ":"); switch(true){ case typeof draft == "string": if(draft.match(rg)){ id = draft; }else{ id = pf + ":" + draft; } break; case draft === Object(draft): id = pf + ":" + draft.story + (draft.page && draft.page.length > 0 ? "@" + draft.page : "" ) + (draft.premise !== undefined ? "?" + ((o) => { return FM.ob.serialize(o).map((tpl) => { return tpl[0] + "=" + encodeURIComponent(tpl[1]); }).join("&"); })(draft.premise) : ""); break; } return new URL(id); }
[ "function makeUrl(protocol, host, resource, id) {\n return protocol + \"://\" + host + resource + id;\n}", "function url() {\n return from(String).format(JsonFormatTypes.URL);\n}", "function getUrl() {\n return url.format(this.urlObj);\n}", "function buildUrl (obj) {\n\t\treturn (obj.protocol || 'http') + '://' +\n\t\t\t (obj.host ||\n\t\t\t\tobj.hostname + (obj.port ? ':' + obj.port : '')) +\n\t\t\t (obj.pathname || '') +\n\t\t\t (obj.search ? '?' + formatQS(obj.search || '') : '') +\n\t\t\t (obj.hash ? '#' + obj.hash : '');\n\t}", "toURL() {\n throw new Error('Not implemented.');\n }", "getURL() { return Work.baseURL + this.url; }", "getReferringUrl() {}", "function generateUrl (protocol, urlPath) {\n return protocol === 'http' ? HTTP_SERVER_BASE + urlPath : HTTPS_SERVER_BASE + urlPath;\n}", "get protocol() {\n return this.parsedUrl.protocol;\n }", "get url() {\n\t\tif (this.path != '')\n\t\t\treturn `${this.host}/${this.path}/${this.document}`;\n\t\telse\n\t\t\treturn `${this.host}/${this.document}`;\n\t}", "function url ()\n\t\t\t{\n\t\t\t\treturn 'http://' + addParam( location.host + hash().replace(/#/,'') , d.param);\n\t\t\t}", "uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }", "function urlConverter(nombre){\n return \"https//www.\" + nombre + \".com\"\n}", "uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port && (\"wss\" === schema && Number(this.opts.port) !== 443 || \"ws\" === schema && Number(this.opts.port) !== 80)) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = (0, _yeast.yeast)();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = (0, _parseqs.encode)(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return schema + \"://\" + (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? \"?\" + encodedQuery : \"\");\n }", "static __createUrl(url,base){return new URL(url,base)}", "function setURL() {\n var proto;\n var url;\n var port;\n if (window.location.protocol == \"http:\") {\n proto = \"ws://\";\n port = \"8080\";\n } else {\n proto = \"wss://\";\n port = \"8443\";\n }\n\n url = proto + window.location.hostname + \":\" + port;\n\n return url;\n}", "uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = (0, yeast_1.default)();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = parseqs_1.default.encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }", "function setURL() {\n var proto;\n var url;\n var port;\n if (window.location.protocol == \"http:\") {\n proto = \"ws://\";\n port = \"8080\";\n } else {\n proto = \"wss://\";\n port = \"8443\";\n }\n\n url = proto + window.location.hostname + \":\" + port;\n return url;\n}", "createPath(protocol, host, port) {\n return (protocol + \"://\" + host + \":\" + port);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate backdrop based on sidenav state
function setBackdrop() { if (menuOpen) { backdrop.classList.remove('z-0'); backdrop.classList.remove('opacity-0'); backdrop.classList.add('opacity-50'); backdrop.classList.add('z-20'); } else { backdrop.classList.remove('z-20'); backdrop.classList.remove('opacity-50'); backdrop.classList.add('opacity-0'); backdrop.classList.add('z-0'); } }
[ "function sidenavOpen () {\n sidenavBar.style.transform = 'translateX(0%)'\n sidenavStatus = true\n}", "function w3_open() {\n if (mySidenav.style.display === 'block') {\n mySidenav.style.display = 'none';\n overlayBg.style.display = \"none\";\n } else {\n mySidenav.style.display = 'block';\n overlayBg.style.display = \"block\";\n }\n }", "_detectSidenav() {\n const sidenavElem = this.el.closest('.sidenav');\n\n if (sidenavElem) {\n this.isInSidenav = true;\n this.sidenavId = sidenavElem.id;\n }\n }", "function openNav() {\n sidenav.css(\"margin-left\", \"0\");\n sidenav.css(\"overflow\", \"auto\");\n backButton.addClass(\"active_background\");\n enableHamburger();\n menuOpen = true;\n}", "function deactivateSidenav() {\n self.activeSidenav = false; \n }", "function backdropOpen(element) {\n return element.style.display !== 'none' && element._isOpen;\n }", "openSidenav() {\n this._$log.debug(`openSidenav( )`);\n this._sideNav('primary').open();\n }", "function openNav() {\r\n document.getElementById(\"mySidenav\").style.width = \"390px\";\r\n document.getElementById(\"main\").style.marginLeft = \"390px\";\r\n document.body.style.backgroundColor = \"rgba(0,0,0,0.4)\";\r\n }", "toggleSidenav() {\n this.setState(prevState => {\n return { sidenavOpen: !prevState.sidenavOpen }\n })\n }", "function openNav() {\n document.getElementById(\"mySidenav\").style.width = \"250px\";\n document.getElementById(\"main\").style.marginLeft = \"250px\";\n document.body.style.backgroundColor = \"rgba(0,0,0,0.4)\";\n }", "function openNav() {\n\n document.getElementById(\"mySidenav\").style.width = \"250px\";\n document.getElementById(\"main\").style.marginLeft = \"250px\";\n // document.body.style.backgroundColor = \"rgba(0,0,0,0.4)\";\n\n}", "function openNav() {\n document.getElementById(\"mySidenav\").style.width = \"250px\";\n document.getElementById(\"main\").style.marginLeft = \"250px\";\n //document.body.style.backgroundColor = \"rgba(0,0,0,0.4)\";\n}", "toggleNavDrawer(state) {\n if (state.drawer.permanent) {\n state.drawer.permanent = false;\n localStorage.removeItem(\"drawer.permanent\");\n // set the clipped state of the drawer and toolbar\n state.drawer.clipped = true;\n localStorage.setItem(\"drawer.clipped\", state.drawer.clipped);\n }\n state.drawer.open = !state.drawer.open;\n }", "function openNav() {\n //$(\"#mySidenav\").style.width = \"250px\";\n $(\"#mySidenav\").css('width', '250px');\n //document.getElementById(\"main\").style.marginLeft = \"250px\";\n $('#mainContent').css('margin-right', '250px');\n //$('body').style.backgroundColor = \"rgba(0,0,0,0.4)\";\n $('body').css('background-color', 'rgba(0,0,0,0.4)');\n }", "_addActiveInSidenav() {\n if (this.childIsActive && this.isInSidenav) {\n const triggers = document.querySelectorAll('.sidenav .collapsible-trigger');\n triggers.forEach((trigger) => {\n if (trigger.dataset.target === this.el.id) {\n trigger.classList.add('active');\n }\n });\n\n this.el.classList.add('active');\n this.open();\n this.isActive = true;\n }\n }", "function isSideBarToggled(){\n return isOpen\n}", "_addActiveInSidenav() {\n if (this.childIsActive && this.isInSidenav) {\n const triggers = document.querySelectorAll('.sidenav .collapsible-trigger');\n triggers.forEach(trigger => {\n if (trigger.dataset.target === this.el.id) {\n trigger.classList.add('active');\n }\n });\n\n this.el.classList.add('active');\n this.open();\n this.isActive = true;\n }\n }", "function openNav() {\n document.getElementById(\"mySidenav\").style.width = \"250px\";\n document.getElementById(\"main\").style.marginLeft = \"250px\"; //this feature from w3\n document.body.style.backgroundColor = \"rgba(0,0,0,0.4)\";\n }", "toggleExchange(){\n this.$mdSidenav(\"exchange-sidenav\")\n .toggle()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Triggers the processing of the next request in dx_queue
function dxProcessRequestQueue() { if (dx_processing_queue) {return;} if (!navigator.onLine) { setItemInLocalStorage("dx_queue",JSON.stringify(dx_queue),2); showAlert(presentOfflineRequestQueuedMessage(),"info","OK",false); return; } if (dx_queue.length > 0) { let next_post = dx_queue.shift(); dxRequestInternalQueued(next_post.url,next_post.parameters,next_post.on_success,next_post.on_fail,next_post.trigger_element_id); } else { dx_processing_queue = false; } }
[ "function next()\n {\n var params = queue[0];\n\n // Replace or add the handler\n if(params.hasOwnProperty(\"success\")) callback = params.success;\n else callback = null;\n\n params.success = success;\n\n // Manage request timeout\n timeoutId = setTimeout(timeoutHandler, TIMEOUT);\n\n // Now we can perform the request\n $.ajax(params);\n }", "function processNextRequest() {\n if (requestInProgress || requestQueue.length === 0) {\n return;\n }\n requestInProgress = true;\n const nextRequest = requestQueue.shift();\n let newPayload;\n let path;\n switch (nextRequest.dataType) {\n case 'address' :\n path = 'addresses/billing';\n newPayload = boldAddress.getBillingAddress();\n break;\n case 'customer' :\n path = window.checkoutConfig.bold[nextRequest.dataType] ? 'customer' : 'customer/guest';\n newPayload = boldCustomer.getCustomer();\n break;\n }\n if (!newPayload || payloadCompare(newPayload, nextRequest.dataType)) {\n requestInProgress = false;\n processNextRequest();\n return;\n }\n $.ajax({\n url: client.url + path,\n type: window.checkoutConfig.bold[nextRequest.dataType] ? 'PUT' : 'POST',\n headers: {\n 'Authorization': 'Bearer ' + client.jwtToken,\n 'Content-Type': 'application/json',\n },\n data: JSON.stringify(newPayload)\n }).done(function (result) {\n window.checkoutConfig.bold[nextRequest.dataType] = result.data[nextRequest.dataType];\n nextRequest.resolve(result);\n requestInProgress = false;\n processNextRequest();\n }).fail(function (error) {\n nextRequest.reject(error);\n requestInProgress = false;\n processNextRequest();\n });\n }", "_processNextRequest() {\n if (this.isDestroyed) return;\n const requestEvt = this.queue[0];\n if (this.isOnline() && requestEvt && !requestEvt.firing) {\n if (requestEvt instanceof WebsocketSyncEvent) {\n if (this.socketManager && this.socketManager._isOpen()) {\n logger.debug(`Sync Manager Websocket Request Firing ${requestEvt.operation} on target ${requestEvt.target}`, requestEvt.toObject());\n this.requestManager.sendRequest(requestEvt._getRequestData(),\n result => this._xhrResult(result, requestEvt));\n requestEvt.firing = true;\n } else {\n logger.debug('Sync Manager Websocket Request skipped; socket closed');\n }\n } else {\n logger.debug(`Sync Manager XHR Request Firing ${requestEvt.operation} ${requestEvt.target}`, requestEvt.toObject());\n xhr(requestEvt._getRequestData(), result => this._xhrResult(result, requestEvt));\n requestEvt.firing = true;\n }\n } else if (requestEvt && requestEvt.firing) {\n logger.debug(`Sync Manager processNext skipped; request still firing ${requestEvt.operation} on target ${requestEvt.target}`,\n requestEvt.toObject());\n }\n }", "function callNextRequest() {\r\n\tif (requestHandlers.length !== 0 && nextHandlers.length === 0) {\r\n\t\tisHandlerProcessing=true;\r\n\t\tvar h=requestHandlers.shift();\r\n\t\th.handler(h);\r\n\t\tisHandlerProcessing=false;\r\n\t}\r\n}", "function requestqueue() {\n\t\t// If the queue is already running, abort.\n\t\tif(requesting) return;\n\t\trequesting = true;\n\t\tlink.request({\n\t\t\turl: \"api/events\",\n\t\t\tmethod: \"POST\",\n\t\t\tparams: {\n\t\t\t\tsid: gSessionID\n\t\t\t},\n\t\t\tcallback: queuecallback\n\t\t});\n\t}", "processNextFiles () {\n\t\tconsole.log('processing');\n\t\tthis.processingCount = 0;\n\t\tvar processing = [];\n\n\t\tfor (var i = 0; i < this.maxRequests; i++) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tprocessing.push(this.shiftQueue());\n\t\t\t}\n\t\t}\n\n\t\tprocessing.forEach(this.processFile.bind(this));\n\t}", "function processNext() {\n if (!ready || waitingForData || queue.length == 0) return;\n\n const entry = queue[0];\n\n if (entry.waitForInput) {\n waitingForData = true;\n port.write(entry.command);\n } else {\n port.write(entry.command);\n queue.shift(); // Remove processed entry\n entry.resolve();\n processNext();\n }\n}", "function next() {\n\t\t\t\tif (eventIDs.length) {\n\t\t\t\t\tsetTimeout(process, 1000);\n\t\t\t\t}\n\t\t\t}", "_makeNextRequest() {\n this._waiting = true;\n this._testem.emit(this._request, this._browserId);\n }", "function process_queue() {\n finish_last_action_msg();\n\n if (!queue.length) {\n if (!next_action()) {\n window.location.href = app_page_url;\n return;\n }\n }\n\n var request = queue.pop();\n if (!request) {\n process_queue();\n return;\n }\n\n add_action_msg(request.msg);\n if (request.type === 'file') {\n $.ajax({\n 'url': '',\n 'data': request.data,\n 'cache': false,\n 'contentType': false,\n 'processData': false,\n 'type': 'POST',\n 'success': process_queue\n });\n } else {\n $.post('', request.data, process_queue);\n }\n }", "function ProcessCommunicationsQueue() {\n\t\tif (Object.keys($tw.wiki.event_queue).length !== 0) {\n\t\t\t//send the next request if there is one and no request is currently pending\n\t\t\tif ($tw.wiki.event_queue[Object.keys($tw.wiki.event_queue)[0]].data) {\n\t\t\t\t$tw.wiki.CommunicationsHandler['request_bundle']($tw.wiki.event_queue[Object.keys($tw.wiki.event_queue)[0]].data);\n\t\t\t\tdelete $tw.wiki.event_queue[Object.keys($tw.wiki.event_queue)[0]];\n\t\t\t}\n\t\t}\n\t}", "function processNextRequest() {\n if (pendingPortRequest || !queuedPortRequests.length) {\n return;\n }\n pendingPortRequest = true;\n const { resolve, reject } = queuedPortRequests.shift();\n getPortPromise(false)\n .then(resolve)\n .catch(reject)\n .finally(() => {\n pendingPortRequest = false;\n processNextRequest();\n });\n }", "function sendRequest(next) {\n\t lastRequestTime = Date.now();\n\t next();\n\t }", "function doNext() {\n\t\t\tif (q) {\n\t\t\t\tq.pending = q.next = (!q.next && q.length) ?\n\t\t\t\t\tq.shift() : q.next;\n\t\t\t\tq.args = slice.call(arguments, 0);\n\t\t\t\tif (q.pending) {\n\t\t\t\t\tq.next = 0;\n\t\t\t\t\tq.pending.apply({}, [preventMultiCall(doNext)].concat(q.args));\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function processQueue() {\n\n\t// Iterates over the queue of messages.\n\tfor (let i = 0; i < queue.length; i++) {\n\n\t\t// Iterates over the targets.\n\t\tfor (let target of targets) {\n\n\t\t\t// If the target is busy, skip it.\n\t\t\tif (target.busy) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Marks the target as busy - from this\n\t\t\t// point forward, the target won't accept\n\t\t\t// any requests untill it's unmarked.\n\t\t\ttarget.busy = true;\n\n\t\t\t// Gets the current item out of the queue.\n\t\t\tlet item = queue.splice(i, 1)[0];\n\n\t\t\t// Mark the response, so we know which service\n\t\t\t// worker the request went to when it comes\n\t\t\t// back.\n\t\t\titem.res.setHeader('X-Target', i);\n\n\t\t\t// Sends the proxy request and exits the\n\t\t\t// loop.\n\t\t\tproxy.web(item.req, item.res, {\n\t\t\t\ttarget: target.host\n\t\t\t});\n\n\t\t\tbreak;\n\t\t}\n\t}\n}", "async processQueue() {\n // Only process if the shouldProcessQueue flag is set, and if the queue is\n // not empty.\n if (!this.shouldProcessQueue || this.queue.length === 0) {\n return;\n }\n\n const {\n action: {\n meta: {\n optimistic: { command }\n }\n },\n stateChange\n } = this.queue.shift();\n\n try {\n await this.api(...command);\n } catch (err) {\n console.warn(`Error calling API: ${JSON.stringify(err)}`);\n this.onError(err, stateChange);\n }\n await new Promise(resolve => setTimeout(resolve(), 500));\n this.processQueue();\n }", "function triggerMore(){\n if(!allCompleted()){\n let max = config.maxConcurrentRequests > avaiableQueue ? avaiableQueue : config.maxConcurrentRequests;\n for(let i=active.size; i < max; i++){\n triggerNext();\n }\n }\n}", "function processQueue() {\n // Iterates over the queue of messages.\n for (let i = 0; i < queue.length; i++) {\n // Iterates over the targets.\n for (let [targetIndex, target] of targets.entries()) {\n // If the target is busy, skip it.\n if (target.busy) {\n continue;\n }\n // Marks the target as busy - from this\n // point forward, the target won't accept\n // any requests until it's unmarked.\n target.busy = true;\n // Gets the current item out of the queue.\n let item = queue.splice(i, 1)[0];\n // Mark the response, so we know which service\n // worker the request went to when it comes\n // back.\n item.res.setHeader(\"X-Target\", targetIndex);\n // Sends the proxy request and exits the\n // loop.\n proxy.web(item.req, item.res, {\n target: target.host\n });\n break;\n }\n }\n }", "process(variable) {\n const processes = this.requestsQueue.get(variable);\n let nextProcess;\n // process request queue for the variable only if it is not empty\n if (!processes || !processes.length) {\n this.clear(variable);\n return;\n }\n // If only one item in queue\n if (processes.length === 1) {\n nextProcess = processes[0];\n if (nextProcess.active) {\n this.clear(variable);\n }\n else {\n nextProcess.active = true;\n nextProcess.resolve();\n }\n return;\n }\n switch (variable.inFlightBehavior) {\n case 'executeLast':\n for (let i = 0; i < processes.length - 2; i++) {\n this.rejectProcess(processes[i]);\n }\n processes.splice(0, processes.length - 1);\n this.process(variable);\n break;\n case 'executeAll':\n nextProcess = processes.splice(0, 1)[0];\n if (nextProcess.active) {\n nextProcess = processes.splice(0, 1)[0];\n }\n nextProcess.active = true;\n nextProcess.resolve();\n break;\n default:\n for (let i = 0; i < processes.length - 1; i++) {\n this.rejectProcess(processes[i]);\n }\n this.clear(variable);\n break;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of imports for the given array of nodes.
function packageImports(nodes) { var map = {}, imports = []; // Compute a map from name to node. nodes.forEach(function (d) { map[d.name] = d; }); // For each import, construct a link from the source to target node. nodes.forEach(function (d) { if (d.imports) d.imports.forEach(function (i) { imports.push({ source: map[d.name], target: map[i] }); }); }); return imports; }
[ "function packageImports(nodes) {\n var map = {},\n imports = [];\n\n // Compute a map from name to node.\n nodes.forEach(function (d) {\n map[d.name] = d;\n });\n\n // For each import, construct a link from the source to target node.\n nodes.forEach(function (d) {\n if (d.imports) d.imports.forEach(function (i) {\n imports.push({\n source: map[d.name],\n target: map[i]\n });\n });\n });\n\n return imports;\n }", "packageImports(nodes) {\n const map = {},\n imports = [];\n\n // Compute a map from name to node.\n nodes.forEach(function(d) {\n map[d.name] = d;\n });\n\n // For each import, construct a link from the source to target node.\n nodes.forEach(function(d) {\n if (d.imports) d.imports.forEach(function(i) {\n imports.push({source: map[d.name], target: map[i]});\n });\n });\n\n return imports;\n }", "function packageImports(nodes) {\r\n var map = {}, imports = [];\r\n // Compute a map from name to node.\r\n nodes.forEach(function (d) {\r\n map[d.data.name] = d;\r\n });\r\n // For each import, construct a link from the source to target node.\r\n nodes.forEach(function (d) {\r\n if (d.data.imports)\r\n d.data.imports.forEach(function (i) {\r\n imports.push(map[d.data.name].path(map[i]));\r\n });\r\n });\r\n return imports;\r\n }", "function packageImports(nodes) {\n var map = {},\n imports = [];\n\n // Compute a map from name to node.\n nodes.forEach(function(d) {\n map[d.data.name] = d;\n });\n\n // For each import, construct a link from the source to target node.\n nodes.forEach(function(d) {\n if (d.data.links) d.data.links.forEach(function(i) {\n imports.push(map[d.data.name].path(map[i]));\n });\n });\n\n return imports;\n }", "function packageImports(nodes) {\n var map = {}, imports = [];\n // Compute a map from name to node.\n nodes.forEach(function (d) {\n map[d.data.name] = d;\n });\n // For each import, construct a link from the source to target node.\n nodes.forEach(function (d) {\n if (d.data.imports)\n d.data.imports.forEach(function (i) {\n imports.push(map[d.data.name].path(map[i]));\n });\n });\n return imports;\n }", "function packageImports(nodes) {\n var map = {},\n imports = [];\n\n // Compute a map from name to node.\n nodes.forEach(function(d) {\n map[d.name] = d;\n });\n\n // For each import, construct a link from the source to target node.\n nodes.forEach(function(d) {\n if (d.imports) d.imports.forEach(function(i) {\n imports.push({source: map[d.name], target: map[i]});\n });\n });\n\n return imports;\n }", "function packageImports(nodes) {\n var map = {},\n imports = [];\n\n // Compute a map from name to node.\n nodes.forEach(function(d) {\n map[d.data.name] = d;\n });\n\n // For each import, construct a link from the source to target node.\n nodes.forEach(function(d) {\n if (d.data.imports) d.data.imports.forEach(function(i) {\n imports.push(map[d.data.name].path(map[i]));\n });\n });\n\n return imports;\n}", "function packageImports(nodes) {\r\n var map = {},\r\n imports = [];\r\n\r\n // Compute a map from name to node.\r\n nodes.forEach(function(d) {\r\n map[d.name] = d;\r\n });\r\n\r\n // For each import, construct a link from the source to target node.\r\n nodes.forEach(function(d) {\r\n if (d.imports) d.imports.forEach(function(i) {\r\n imports.push({source: map[d.name], target: map[i]});\r\n });\r\n });\r\n\r\n return imports;\r\n}", "function findImports(ast, filter) {\n if (typeof filter !== 'function') {\n filter = function (a) { return a };\n }\n\n if (ast.type === 'ImportDeclaration') {\n var id = ast.source.value;\n var filtered = filter(id);\n if (filtered) {\n return filtered;\n } else {\n return [];\n }\n } else if(ast.body && ast.body.forEach) {\n var result = [];\n ast.body.forEach(function(ast) {\n result = result.concat(findImports(ast, filter));\n });\n return result;\n } else {\n return [];\n }\n}", "function getImports(moduleTree) {\n\tvar imports = [];\n\n\tfunction addImport(name) {\n\t\tif ([].indexOf.call(imports, name) == -1) {\n\t\t\timports.push(name);\n\t\t}\n\t}\n\n\ttraverse(moduleTree, function(node) {\n\t\t// import {} from 'foo';\n\t\t// export * from 'foo';\n\t\t// export { ... } from 'foo';\n\t\tif (node.type == \"EXPORT_DECLARATION\") {\n\t\t\tif (node.declaration.moduleSpecifier) {\n\t\t\t\taddImport(node.declaration.moduleSpecifier.token.processedValue);\n\t\t\t}\n\t\t}\n\t\telse if (node.type == \"IMPORT_DECLARATION\") {\n\t\t\taddImport(node.moduleSpecifier.token.processedValue);\n\t\t}\n\t});\n\n\treturn imports;\n}", "function getImports(moduleTree) {\n var imports = [];\n\n function addImport(name) {\n if (indexOf.call(imports, name) == -1)\n imports.push(name);\n }\n\n traverse(moduleTree, function(node) {\n // import {} from 'foo';\n // export * from 'foo';\n // export { ... } from 'foo';\n // module x from 'foo';\n if (node.type == 'EXPORT_DECLARATION') {\n if (node.declaration.moduleSpecifier)\n addImport(node.declaration.moduleSpecifier.token.processedValue);\n }\n else if (node.type == 'IMPORT_DECLARATION')\n addImport(node.moduleSpecifier.token.processedValue);\n else if (node.type == 'MODULE_DECLARATION')\n addImport(node.expression.token.processedValue);\n });\n return imports;\n }", "get importsModules() {\n return this.importDeclarations\n .map(node => node && node.source && node.source.value)\n .filter(Boolean)\n }", "function findTslibImports(node) {\n const imports = [];\n ts.forEachChild(node, (child) => {\n if (child.kind === ts.SyntaxKind.ImportDeclaration) {\n const importDecl = child;\n if (isTslibImport(importDecl)) {\n const importClause = importDecl.importClause;\n const namespaceImport = importClause.namedBindings;\n imports.push(namespaceImport);\n }\n }\n });\n return imports;\n}", "function gatherImports(imports) {\n if (!imports) {\n return []\n }\n\n var dedupe = {};\n for (var i = 0; i < imports.length; i++) {\n dedupe[imports[i]] = true;\n }\n\n var result = [];\n for (var i in dedupe) {\n result.push(i);\n }\n\n return Util.sortPackages(result);\n}", "function getImports(moduleTree) {\n var imports = [];\n\n function addImport(name) {\n if ([].indexOf.call(imports, name) == -1)\n imports.push(name);\n }\n\n traverse(moduleTree, function(node) {\n // import {} from 'foo';\n // export * from 'foo';\n // export { ... } from 'foo';\n // module x from 'foo';\n if (node.type == 'EXPORT_DECLARATION') {\n if (node.declaration.moduleSpecifier)\n addImport(node.declaration.moduleSpecifier.token.processedValue);\n }\n else if (node.type == 'IMPORT_DECLARATION')\n addImport(node.moduleSpecifier.token.processedValue);\n else if (node.type == 'MODULE_DECLARATION')\n addImport(node.expression.token.processedValue);\n });\n return imports;\n}", "function nodesToArray(nodes) { // 9021\n var results = []; // 9022\n for (var i = 0; i < nodes.length; ++i) { // 9023\n results.push(nodes.item(i)); // 9024\n } // 9025\n return results; // 9026\n}", "getScriptImports() {\n let result = [];\n this.enumerateFiles((file) => {\n if (reflection_1.isBrsFile(file)) {\n result.push(...file.ownScriptImports);\n }\n else if (reflection_1.isXmlFile(file)) {\n result.push(...file.scriptTagImports);\n }\n });\n return result;\n }", "function listImports(source) {\n // Current idea here is to silence errors and let them rise in stylus's\n // renderer which has more handling so that the error message is more\n // meaningful and easy to understand.\n try {\n var ast = new Parser(source, { cache: false }).parse();\n } catch (e) {\n return [];\n }\n var importVisitor = new ImportVisitor(ast, {});\n importVisitor.visit(ast);\n return importVisitor.importPaths;\n}", "function getImportSourceNodes(source, yufkaOptions = {}) {\n /**\n * @types Map<string, acorn.Node[]>\n */\n const sources = new Map()\n\n yufka(source, yufkaOptions, node => {\n if (\n [\n 'ImportExpression',\n 'ImportDeclaration',\n 'ExportAllDeclaration',\n 'ExportNamedDeclaration'\n ].includes(node.type) &&\n node.source &&\n !node.source.value.startsWith('.')\n ) {\n const packageName = getPackageName(node.source.value)\n\n if (!sources.has(packageName)) {\n sources.set(packageName, [])\n }\n sources.get(packageName).push(node)\n }\n })\n\n return sources\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
functions for invoicedetails2.jsp For Listing Cart Items
function list_cart_items() { var location_id = document.getElementById("txt_location_id").value; var status = document.getElementById("txt_status").value; var cart_session_id = document.getElementById("txt_session_id").value; var vouchertype_id = document.getElementById("txt_vouchertype_id").value; var voucher_so_id = document.getElementById("txt_soid").value; if (voucher_so_id != '0') { showHintAccount('../accounting/invoice-details2.jsp?' + 'voucher_so_id=' + voucher_so_id + '&status=' + status + '&location_id=' + location_id + '&cart_session_id=' + cart_session_id + '&cart_vouchertype_id=' + vouchertype_id + '&list_cartitems=yes', 'invoice_details'); } else { showHintAccount('../accounting/invoice-details2.jsp?' + 'status=' + status + '&location_id=' + location_id + '&cart_session_id=' + cart_session_id + '&cart_vouchertype_id=' + vouchertype_id + '&list_cartitems=yes', 'invoice_details'); } }
[ "function list_cart_items() { \r\n\tvar location_id = CheckNumeric(document.getElementById(\"txt_location_id\").value); \r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n\tvar cart_session_id = CheckNumeric(document.getElementById(\"txt_session_id\").value); \r\n\t// From po,git,grn To git,grn,pr \r\n\tvar voucherclass_id = CheckNumeric(document.getElementById(\"txt_voucherclass_id\").value); \r\n\tvar vouchertype_id = CheckNumeric(document.getElementById(\"txt_vouchertype_id\").value); \r\n\tvar voucher_dcr_request_id = CheckNumeric(document.getElementById(\"txt_voucher_dcr_request_id\").value);\r\n\tvar voucher_dcr_id = CheckNumeric(document.getElementById(\"txt_voucher_dcr_id\").value); \r\n\tvar voucher_grn_return_id = CheckNumeric(document.getElementById(\"txt_voucher_grn_return_id\").value); \r\n\tshowHintFootable('../accounting/returns-details.jsp?cart_session_id='+ cart_session_id+'&status='+status+'&location_id='+location_id \r\n\t\t\t+ '&cart_vouchertype_id='+ vouchertype_id \r\n\t\t\t+ '&voucherclass_id='+ voucherclass_id \r\n\t\t\t+ '&voucher_dcr_request_id='+voucher_dcr_request_id+ '&voucher_dcr_id='+voucher_dcr_id+'&voucher_grn_return_id='+voucher_grn_return_id \r\n\t\t\t+ '&list_cartitems=yes', 'invoice_details'); \r\n}", "function list_cart_items() {\r\n\tvar location_id = CheckNumeric(document.getElementById(\"txt_location_id\").value);\r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n\tvar cart_session_id = CheckNumeric(document .getElementById(\"txt_session_id\").value);\r\n\t// From po,git,grn To git,grn,pr\r\n\tvar voucherclass_id = CheckNumeric(document .getElementById(\"txt_voucherclass_id\").value);\r\n\tvar vouchertype_id = CheckNumeric(document .getElementById(\"txt_vouchertype_id\").value);\r\n\tvar voucher_po_id = CheckNumeric(document .getElementById(\"txt_voucher_po_id\").value);\r\n\tvar voucher_git_id = CheckNumeric(document .getElementById(\"txt_voucher_git_id\").value);\r\n\tvar voucher_grn_id = CheckNumeric(document .getElementById(\"txt_voucher_grn_id\").value);\r\n\tshowHintFootable('../accounting/purchase-details.jsp?cart_session_id=' + cart_session_id \r\n\t\t\t+ '&status=' + status\r\n\t\t\t+ '&location_id=' + location_id\r\n\t\t\t+ '&cart_vouchertype_id=' + vouchertype_id\r\n\t\t\t+ '&voucherclass_id=' + voucherclass_id \r\n\t\t\t+ '&voucher_po_id=' + voucher_po_id\r\n\t\t\t+ '&voucher_git_id=' + voucher_git_id\r\n\t\t\t+ '&voucher_grn_id=' + voucher_grn_id \r\n\t\t\t+ '&list_cartitems=yes', 'po_details');\r\n}", "function view_cart() {\n\t\n\tvar self = this;\n\tvar eshop = self.module('eshop');\n\n\teshop.cart_list(self, function(products, price, count) {\n\t\tself.view('shoppingcart', { products: products, price: price, count: count });\n\t});\n}", "function showCartContent() {\n console.log(\"----- #items in cart = \" + cart.length);\n for (var i=0; i<cart.length; i++ )\n {\n console.log(\"id: \" + cart[i].id + \", name: \" + cart[i].name + \", price: \" + cart[i].price);\n }\n}", "function list_cart_items(){\r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n var session_id = document.getElementById(\"txt_session_id\").value;\r\n showHint('quote-details.jsp?status='+status+'&session_id='+session_id+'&list_cartitems=yes','quote_details');\r\n}", "function list_cart_items(){\r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n var session_id = document.getElementById(\"txt_session_id\").value;\r\n // //alert(session_id+\"==session_id\");\r\n showHint('bill-details.jsp?status='+status+'&session_id='+session_id+'&list_cartitems=yes','bill_details');\r\n}", "function listItems(cartObject, listArea, totalsArea) {\n\n var cartSubTotal = 0;//Reset cart subtotal to zero\n const salesTax = .06;//Initialize and define sales tax\n\n $(listArea).html(\"\");//If there is any existing HTML in the item list area, remove it.\n $(totalsArea).html(\"\");//If there is any existing HTML in the item totals area, remove it.\n\n cartObject.forEach(function(item) {//Again: we seem to be declaring variables for each iteration. Also, HTML DOM strings likely do not need to be defined as jQuery objects.\n\n let lineItemContainer = $('<div></div>');//Creates container for item name and price\n let lineItemPTag = $('<p>$' + item.price + ' - ' + item.name + '</p>');//Create HTML for price and description of added item\n\n lineItemContainer.append(lineItemPTag);//Add item and price to container\n\n $(listArea).append(lineItemContainer);//place item container in the HTML DOM\n\n cartSubTotal = cartSubTotal + item.price;//Add to cart sub-total\n\n });\n\n var taxAdded = cartSubTotal * salesTax;//Calculate added tax for order\n cartGrandTotal = cartSubTotal + taxAdded; //Grand total is sub-total including tax\n\n let subTotalPTag = $(\"<p>Sub Total: $\" + cartSubTotal.toFixed(2) + \"</p>\");//Create sub-total HTML\n let salesTaxPTag = $(\"<p>Tax: $\" + taxAdded.toFixed(2) + \"</p>\");//Create sales tax HTML\n let grandTotalPTag = $(\"<p>Grand Total: $\" + cartGrandTotal.toFixed(2) + \"</p>\");//Create grand total HTML\n\n $(totalsArea).append(subTotalPTag).append(salesTaxPTag).append(grandTotalPTag);//Add totals to container\n\n }", "function invokeItemPage(){\n addCart();\n displayCounter();\n addCartForItem('carrot');\n}", "function addItemToCart() {}", "function getCartData()\n{\n console.log(\"Getting cart content, #items = \" + cart.length);\n document.getElementById(\"numInCart\").innerHTML = cart.length;\n var row = \"\";\n for (var i=0; i<cart.length; i++ )\n {\n row += \"<tr><td>\" + cart[i].id +\"</td> <td>\" + cart[i].name + \"</td><td>\" + cart[i].price + \"</td></tr>\";\n }\n // load cart's item to modal cart\n document.getElementById(\"cart-content\").innerHTML = row;\n showCartContent();\n}", "function getCartItems(){\n return cart_items;\n}", "function showCart(){\n removeAllNodeFrom(cartPageSection);\n curCart.forEach(function(food, index){\n addToCartPage(food, index);\n });\n}", "goToCart() {\r\n if($('#attach-sidesheet-view-cart-button > span > input').isExisting()) {\r\n $('#attach-sidesheet-view-cart-button > span > input').click()\r\n }\r\n else {$('#nav-cart').click()\r\n }\r\n //let cartList = []\r\n //let numCartItems = this.countCartItems()\r\n return $('#activeCartViewForm > div.a-row.a-spacing-mini.sc-list-body.sc-java-remote-feature > div:nth-child(3) > div.sc-list-item-content > div > div.a-column.a-span10 > div > div > div.a-fixed-left-grid-col.a-col-right > ul > li:nth-child(1) > span > a').getAttribute('href').split('/')[5]\r\n }", "function loadCartContent() {\n // DVARS: Gets the information from the URL bar\n var formData = location.search.slice(1);\n formData = formData.replace(/\\+/g, \" \");\n formData = decodeURIComponent(formData);\n var formFields = formData.split(/[&=]/g);\n // DLOOP: Loops through the storeItems array\n for (var i = 0; i < storeItems.length; i++) {\n // DVARL: Gets the index of each item needed\n var currentItemID = storeItems[i][4],\n itemPriceIndex = formFields.indexOf(`${currentItemID}price`),\n itemQTYIndex = formFields.indexOf(`${currentItemID}qty`),\n itemEngravingIndex = formFields.indexOf(`${currentItemID}eng`);\n // DIFDO: If their is an item ordered then it display the item with its information\n if (formFields[itemQTYIndex + 1] != '0') {\n // DVARL: Creates a bunch of nodes and caculates out the item price\n var itemHTML = document.createElement('div'),\n nameHTML = document.createElement('h3'),\n imageHTML = document.createElement('img'),\n priceHTML = document.createElement('input'),\n qtyHTML = document.createElement('input'),\n engravingHTML = document.createElement('input'),\n itemsPrice = parseFloat(formFields[itemPriceIndex + 1].replace('$', \"\")) * parseFloat(formFields[itemQTYIndex + 1]);\n // DDOES: Edits the nameHTML and imageHTML to display the correct information\n nameHTML.textContent = storeItems[i][0];\n imageHTML.src = `Images/store/${storeItems[i][0]}/${storeItems[i][1][0]}`;\n // DDOES: Edits the priceHTML node\n priceHTML.type = \"text\";\n priceHTML.name = `${storeItems[i][4]}price`;\n priceHTML.classList = storeItems[i][4];\n priceHTML.id = \"itemPrice\";\n priceHTML.value = `$${itemsPrice.toFixed(2)}`;\n priceHTML.readOnly = \"readonly\";\n // DDOES: Edits the qtyHTML node\n qtyHTML.type = \"number\";\n qtyHTML.name = `${storeItems[i][4]}qty`;\n qtyHTML.classList = storeItems[i][4];\n qtyHTML.id = \"itemQty\";\n qtyHTML.min = 0;\n qtyHTML.value = formFields[itemQTYIndex + 1];\n qtyHTML.readOnly = \"readonly\";\n // DDOES: Edits the engravingHTML node\n engravingHTML.type = \"text\";\n engravingHTML.name = `${storeItems[i][4]}eng`;\n engravingHTML.id = \"itemEngraving\";\n engravingHTML.classList = storeItems[i][4];\n engravingHTML.maxLength = 10;\n engravingHTML.value = formFields[itemEngravingIndex + 1];\n engravingHTML.readOnly = \"readonly\";\n // DDOES: appends the nodes to their respective nodes\n itemHTML.appendChild(nameHTML);\n itemHTML.appendChild(imageHTML);\n itemHTML.appendChild(priceHTML);\n itemHTML.appendChild(qtyHTML);\n itemHTML.appendChild(engravingHTML);\n document.getElementById('cart').appendChild(itemHTML);\n };\n };\n // DVARL: Gets the information out of the formFields array and caculates values need to be applied\n var totalCountIndx = formFields.indexOf('tCount'),\n totalCostIndex = formFields.indexOf('tCost'),\n totalCostAmount = parseFloat(formFields[totalCostIndex + 1].replace('$', \"\")).toFixed(2),\n submitButton = document.createElement('input'),\n itemCount = document.createElement('input'),\n cost = document.createElement('input');\n // DDOES: Edits the submitButton node\n submitButton.type = \"submit\";\n submitButton.id = \"submitButton\";\n submitButton.value = \"Checkout\";\n submitButton.classList = \"button\";\n // DDOES: Edits the itemCount node\n itemCount.type = \"number\";\n itemCount.name = \"tCount\";\n itemCount.id = \"itemCount\";\n itemCount.value = formFields[totalCountIndx + 1];\n itemCount.readOnly = \"readonly\";\n // DDOES: Edits the cost node\n cost.type = \"text\";\n cost.name = \"tCost\";\n cost.id = \"itemCost\";\n cost.value = `$${totalCostAmount}`;\n cost.readOnly = \"readonly\";\n // DDOES: appends the nodes to their respective nodes\n document.getElementById('cart').appendChild(submitButton);\n document.getElementById('cart').appendChild(itemCount);\n document.getElementById('cart').appendChild(cost);\n}", "function storedisplay() {\n document.getElementById(\"cartsize\").innerHTML = cart.getsize().toString();\n document.getElementById(\"name1\").innerHTML = item1.getname();\n document.getElementById(\"name2\").innerHTML = item2.getname();\n document.getElementById(\"name3\").innerHTML = item3.getname();\n document.getElementById(\"name4\").innerHTML = item4.getname();\n document.getElementById(\"price1\").innerHTML = item1.getprice().toString();\n document.getElementById(\"price2\").innerHTML = item2.getprice().toString();\n document.getElementById(\"price3\").innerHTML = item3.getprice().toString();\n document.getElementById(\"price4\").innerHTML = item4.getprice().toString();\n}", "function updateCartPreview() {\n \t// Done: Get the item and quantity from the form\n\tvar divEl = document.getElementById(\"cartContents\");\n\tvar ulEl = document.createElement(\"ul\");\n\tfor(var i in Cart.currentCart) {\n\t\tvar liEl = document.createElement(\"li\");\n\t\tliEl.textContent = Cart.currentCart[i].name + \": \" + Cart.currentCart[i].quantity;\n\t\tulEl.appendChild(liEl); \n\t} // loop for each item in standing JS cart\n\t// Done: Add a new element to the cartContents div with that information\n\tdivEl.innerHTML = \"\"; \n\tdivEl.appendChild(ulEl); // now put it all on the page\n\n} // end function updateCartPreview", "displayCart() {\n console.log(\"items: \", _items.get(this));\n console.log(\"totalQty: \", _totalQty.get(this));\n console.log(\"totalPrice: \", _totalPrice.get(this));\n }", "function getItemsFromShoppingCart() {\n $.getJSON(getPanierRequest, function (data) {\n items = data;\n nbProducts = items.length;\n }).done(function () {\n addItemsToHtmlShopping();\n });\n }", "function displayCart() {\n // Get the contents of the cart from the cookie\n var cart, cartTable, cartTotal, i, newRow, newCell, message;\n\n cart = JSON.parse(Cookie.get(\"shoppingCart\"));\n if (!cart || cart.length === 0) {\n message = $(\"#message\");\n message.html(\"<p>Your shopping cart is empty, please add something to your cart before checking out</p>\");\n hideCartElements();\n return;\n }\n\t\t\n cartTable = $(\"#cartList\");\n cartTotal = 0;\n\n // Add a new row to the table for each item in the cart\n for (i = 0; i < cart.length; i += 1) {\n\t\t\t$(\"<tr><td>\" + cart[i].title + \"</td><td>\" + cart[i].price + \"</td></tr>\").appendTo(cartTable);\n cartTotal += parseFloat(cart[i].price);\n }\n\n // Add a last row for the total value of the cart\n\t\t$(\"<tr><td><strong>Total</strong></td><td><strong>\" + cartTotal.toFixed(2) + \"</strong></td></tr>\").appendTo(cartTable);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add two quaternions, returning the result in a new Quaternion
add(RHO) { return new Quaternion(this._w + RHO._w, this._x + RHO._x, this._y + RHO._y, this._z + RHO._z); }
[ "function multiplyQuaternions(quatDest, a, b) {\n // a.w*b + b.w*a + (a x b)\n quatDest.x = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y;\n quatDest.y = a.w*b.y + a.y*b.w + a.z*b.x - a.x*b.z;\n quatDest.z = a.w*b.z + a.z*b.w + a.x*b.y - a.y*b.x;\n \n // a.w*b.w - a.b\n quatDest.w = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z;\n }", "function\nadd_quats(q1, q2)\n{\n var t1 = [], t2 = [], t3 = [], tf = [];\n var dest = [];\n \n t1[0] = q1[0];\n t1[1] = q1[1];\n t1[2] = q1[2];\n \n t1 = vscale(t1, q2[3]);\n \n t2[0] = q2[0];\n t2[1] = q2[1];\n t2[2] = q2[2];\n\n t2 = vscale(t2, q1[3]);\n \n t3 = vcross(q2,q1);\n tf = vadd(t1, t2);\n tf = vadd(t3, tf);\n tf[3] = q1[3] * q2[3] - vdot(q1,q2);\n \n dest[0] = tf[0];\n dest[1] = tf[1];\n dest[2] = tf[2];\n dest[3] = tf[3];\n \n if (++count > RENORMCOUNT) {\n count = 0;\n dest = normalize_quat(dest);\n }\n return dest;\n}", "function quaternion_multiply(q1,q2) {\n let new_qi = q1[0]*q2[0]-q1[1]*q2[1]-q1[2]*q2[2]-q1[3]*q2[3];\n let new_qj = q1[0]*q2[1]+q1[1]*q2[0]+q1[2]*q2[3]-q1[3]*q2[2];\n let new_qk = q1[0]*q2[2]-q1[1]*q2[3]+q1[2]*q2[0]+q1[3]*q2[1];\n let new_qw = q1[0]*q2[3]+q1[1]*q2[2]-q1[2]*q2[1]+q1[3]*q2[0];\n\n return [new_qi, new_qj, new_qk, new_qw];\n}", "multiply(quat2) {\n let q1w = this.w, // a1\n q1x = this.x, // b1\n q1y = this.y, // c1\n q1z = this.z // d1\n\n let q2w = quat2.w, // a2\n q2x = quat2.x, // b2\n q2y = quat2.y, // c2\n q2z = quat2.z // d2\n\n this.x = q1x * q2w + q1w * q2x + q1y * q2z - q1z * q2y\n this.y = q1y * q2w + q1w * q2y + q1z * q2x - q1x * q2z\n this.z = q1z * q2w + q1w * q2z + q1x * q2y - q1y * q2x\n this.w = q1w * q2w - q1x * q2x - q1y * q2y - q1z * q2z\n }", "function delta(a, b) {\n // the quaternion q' = q1^(-1) * q2 can rotate from q1 orientation to the q2 orientation\n return multiply(inverse(a), b);\n}", "function lerpDualQuaternions (out, a, b, t) {\n out[0] = a[0] + t * (b[0] - a[0])\n out[1] = a[1] + t * (b[1] - a[1])\n out[2] = a[2] + t * (b[2] - a[2])\n out[3] = a[3] + t * (b[3] - a[3])\n\n out[4] = a[4] + t * (b[4] - a[4])\n out[5] = a[5] + t * (b[5] - a[5])\n out[6] = a[6] + t * (b[6] - a[6])\n out[7] = a[7] + t * (b[7] - a[7])\n return out\n}", "function quatMultiply(q1, q2) {\n\tif(!q1 || !q2) return;\n\n var a = q1[0],\n b = q1[1],\n c = q1[2],\n d = q1[3],\n e = q2[0],\n f = q2[1],\n g = q2[2],\n h = q2[3];\n\n return [\n a*e - b*f - c*g - d*h,\n b*e + a*f + c*h - d*g,\n a*g - b*h + c*e + d*f,\n a*h + b*g - c*f + d*e];\n\n}", "function applyQuaternionToVector( vector3 , quaternion ){\n\tvar vector3_quaternion = new SimpleQuaternion(vector3.x, vector3.y, vector3.z, 0);\n\tvar q = quaternion.copy();\n\tvar q_inv = quaternion.copy().conjugate();\n\tq.multiply(vector3_quaternion);\n\tq.multiply(q_inv);\n\tvar result_vector = new THREE.Vector3(q.x, q.y, q.z);\n\treturn result_vector;\n}", "function quaternion(v0, v1) {\r\n\r\n\t\tif (v0 && v1) {\r\n\t\t\t\r\n\t\t\t\tvar w = cross(v0, v1), // vector pendicular to v0 & v1\r\n\t\t\t\t\t\tw_len = Math.sqrt(dot(w, w)); // length of w \r\n\r\n\t\t\t\t\tif (w_len == 0)\r\n\t\t\t\t\t\treturn;\r\n\r\n\t\t\t\t\tvar theta = .5 * Math.acos(Math.max(-1, Math.min(1, dot(v0, v1)))),\r\n\r\n\t\t\t\t\t\tqi = w[2] * Math.sin(theta) / w_len; \r\n\t\t\t\t\t\tqj = - w[1] * Math.sin(theta) / w_len; \r\n\t\t\t\t\t\tqk = w[0]* Math.sin(theta) / w_len;\r\n\t\t\t\t\t\tqr = Math.cos(theta);\r\n\r\n\t\t\t\treturn theta && [qr, qi, qj, qk];\r\n\t\t}\r\n\t}", "rotationBetweenVectors(src, dst){\n let start = new THREE.Vector3();\n start.copy(src);\n start.normalize();\n\n let dest = new THREE.Vector3();\n dest.copy(dst);\n dest.normalize();\n\n let cosTheta = start.dot(dest);\n let rotationAxis = new THREE.Vector3();\n\n if(cosTheta < -1 + 0.001){\n //special case opposite directions\n rotationAxis.crossVectors(start, new THREE.Vector3(0.0,0.0,1.0));\n if(rotationAxis.lengthSq() < 0.01){\n //Parallel, try again\n rotationAxis.crossVectors(start, new THREE.Vector3(1.0,0.0,0.0));\n }\n rotationAxis.normalize();\n let ret = new THREE.Quaternion();\n ret.setFromAxisAngle(rotationAxis, Math.PI);\n return ret;\n }\n\n rotationAxis.crossVectors(start, dest);\n\n let s = Math.sqrt( (1 + cosTheta) * 2);\n let inverseS = 1 / s;\n\n return new THREE.Quaternion(rotationAxis.x * inverseS,\n rotationAxis.y * inverseS,\n rotationAxis.z * inverseS,\n s * 0.5);\n }", "function quaternion(v0, v1) {\n\n\tif (v0 && v1) {\n\t\t\n\t var w = cross(v0, v1), // vector pendicular to v0 & v1\n\t w_len = Math.sqrt(dot(w, w)); // length of w \n\n if (w_len == 0)\n \treturn;\n\n var theta = .5 * Math.acos(Math.max(-1, Math.min(1, dot(v0, v1)))),\n\n\t qi = w[2] * Math.sin(theta) / w_len; \n\t qj = - w[1] * Math.sin(theta) / w_len; \n\t qk = w[0]* Math.sin(theta) / w_len;\n\t qr = Math.cos(theta);\n\n\t return theta && [qr, qi, qj, qk];\n\t}\n}", "function quaternion(v0, v1) {\n\n if (v0 && v1) {\n \n var w = cross(v0, v1), // vector pendicular to v0 & v1\n w_len = Math.sqrt(dot(w, w)); // length of w \n\n if (w_len == 0)\n return;\n\n var theta = .5 * Math.acos(Math.max(-1, Math.min(1, dot(v0, v1)))),\n\n qi = w[2] * Math.sin(theta) / w_len,\n qj = - w[1] * Math.sin(theta) / w_len,\n qk = w[0]* Math.sin(theta) / w_len,\n qr = Math.cos(theta);\n\n return theta && [qr, qi, qj, qk];\n }\n }", "function QuaternionToAngleAxis(q, dest)\n{\n if (!dest) {\n dest = {};\n }\n\n q = QuaternionNormalize(q);\n\n var angle = 2.0 * Math.acos(q.w);\n var angleDeg = RadToDeg(angle);\n var s = Math.sqrt(1.0 - q.w * q.w);\n\n dest.w =\n angleDeg;\n if (s >= 0.001) {\n var scale = 1.0 / s;\n dest.x *= scale;\n dest.y *= scale;\n dest.z *= scale;\n }\n\n return dest;\n}", "function quatMultiply(q1, q2) {\r\n\t\tif(!q1 || !q2) return;\r\n\r\n\t\t\tvar a = q1[0],\r\n\t\t\t\t\tb = q1[1],\r\n\t\t\t\t\tc = q1[2],\r\n\t\t\t\t\td = q1[3],\r\n\t\t\t\t\te = q2[0],\r\n\t\t\t\t\tf = q2[1],\r\n\t\t\t\t\tg = q2[2],\r\n\t\t\t\t\th = q2[3];\r\n\r\n\t\t\treturn [\r\n\t\t\t a*e - b*f - c*g - d*h,\r\n\t\t\t b*e + a*f + c*h - d*g,\r\n\t\t\t a*g - b*h + c*e + d*f,\r\n\t\t\t a*h + b*g - c*f + d*e];\r\n\r\n\t}", "function rotatePByQuat(p, q){\n\tlet q_norm = q.clone().normalize();\n\tlet q_vec = new Vector3(q_norm.x, q_norm.y, q_norm.z, 0);\n\tlet q_vec_2 = q_vec.clone().multiplyScalar(2);\n\tlet t = q_vec_2.clone().cross(p);\n\n\tlet qw_times_t = t.clone().multiplyScalar(q_norm.w);\n\tlet p_plus_qw = p.clone().add(qw_times_t);\n\tlet cross_qvec_t = q_vec.clone().cross(t);\n\tlet result = p_plus_qw.clone().add(cross_qvec_t);\n\tlet rounded_x = roundUsing(Math.floor, result.x, 10);\n\tlet rounded_y = roundUsing(Math.floor, result.y, 10);\n\tlet rounded_z = roundUsing(Math.floor, result.z, 10);\n\treturn new Vector3(rounded_x, rounded_y, rounded_z);\n}", "applyQuat(quaternion) {\n const x = this.x, y = this.y, z = this.z;\n const qx = quaternion.elements[0], qy = quaternion.elements[1], qz = quaternion.elements[2], qw = quaternion.elements[3];\n\n // calculate quat * vector\n\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = - qx * x - qy * y - qz * z;\n\n // calculate result * inverse quat\n\n this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;\n this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;\n this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;\n\n return this;\n }", "static QuatRot(q1, p, q2) {\n return Vector.QuatMult(Vector.QuatMult(q1, p), q2);\n }", "slerp(q2, blend) {\n blend = Math.clamp(blend, 0, 1);\n\n // if either input is zero, return the other.\n if (this.lengthSq() === 0)\n {\n if (q2.lengthSq() === 0)\n {\n return Quaternion.identity;\n }\n return q2;\n }\n else if (q2.lengthSq() === 0)\n {\n return this;\n }\n\n\n let cosHalfAngle = this.w * q2.w + this.xyz.dot(q2.xyz);\n\n if (cosHalfAngle >= 1 || cosHalfAngle <= -1) {\n // angle = 0.0f, so just return one input.\n return this;\n }\n else if (cosHalfAngle < 0)\n {\n q2.xyz = q2.xyz.negate();\n q2.w = -q2.w;\n cosHalfAngle = -cosHalfAngle;\n }\n\n let blendA;\n let blendB;\n if (cosHalfAngle < 0.99)\n {\n // do proper slerp for big angles\n let halfAngle = Math.acos(cosHalfAngle);\n let sinHalfAngle = Math.sin(halfAngle);\n let oneOverSinHalfAngle = 1 / sinHalfAngle;\n blendA = Math.sin(halfAngle * (1 - blend)) * oneOverSinHalfAngle;\n blendB = Math.sin(halfAngle * blend) * oneOverSinHalfAngle;\n }\n else\n {\n // do lerp if angle is really small.\n blendA = 1 - blend;\n blendB = blend;\n }\n\n let resultVec3 = this.xyz.clone().multiplyScalar(blendA).add( q2.xyz.clone().multiplyScalar(blendB) );\n let resultW = blendA * this.w + blendB * q2.w;\n\n let result = new Quaternion(resultVec3.x, resultVec3.y, resultVec3.z, resultW);\n\n if (result.lengthSq() > 0) {\n return result;\n }\n else {\n return Quaternion.identity;\n }\n }", "applyRotation(q) // this * q * this.inverse(), i.e. apply this quaternion to another\n\t{\n\t\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
launches Google Map page of Okeanos Explorer into its own window instead of as a tab in the current window
function launchOEGoogleMap(okeanos) { var Win1 = open(okeanos,"OEGoogleMapWindow","height=800,width=1000,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes"); Win1.focus(); }
[ "function launchGoogleMap(gm) {\n var Win1 = open(gm,\"GoogleMapWindow\",\"height=800,width=950,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes\");\n Win1.focus();\n }", "function openPatrolMap() {\n window.open('http://map.sosarp.net/', '_blank');\n}", "police_maps_link() {\n window.open('https://maps.google.com/maps?q=police&t=&z=14&ie=UTF', '_blank');\n }", "function openGmaps(e) {\n const url = `https://maps.google.com/maps?q=loc:${e.latlng.lat},${e.latlng.lng}`;\n window.open(url, '_blank').focus();\n}", "function geourlNear() {\n\tvar button = document.getElementById(\"geourl-toolbarbutton\");\n\tvar destination = 'http://geourl.org/near?lat='+button.geourlvaluelat+'&long='+button.geourlvaluelong;\n const newTab = getBrowser().addTab(destination);\n\tgetBrowser().selectedTab = newTab;\n}", "function callSidemap(Adresse){\n MeineSidemap = window.open(\"http://slimou.de/WebSpace/Web-Programmierung/AbschlussPraese/xml/sidemap.xml\", \"Sidemap\", \"width=250px, height=750px, top=50px\");\n MeineSidemap.focus();\n}", "function createMapWizardWindow() {\n\t// Create the browser window.\n\tmapWizardWindow = new BrowserWindow({\n\t\twidth: 800,\n\t\theight: 600\n\t})\n\tmapWizardWindow.loadURL(url.format({\n\t\tpathname: path.join(__dirname, 'simSearcher/map.html'),\n\t\tprotocol: 'file:',\n\t\tslashes: true\n\t}))\n}", "function openInteractiveMap(){\nheight = navigator.appVersion.indexOf('Safari')>0?'411':'459';\nmapWindow = window.open('/en_AU/event_guide/interactive-map.html', \"InteractiveMap\", \"width=1000,\"+height+\",top=50,left=50,location=no,status=no,toolbar=no,resizable=no\");\n}", "function showGoogleMap() {\n\t\tsetGMapAndSearchBoxSize();\n\t\tdocument.getElementById(\"googlemapPortion\").style.visibility = 'visible';\n\t\tdocument.title = \"Vision Web Client\";\n\t}", "function openDefaultMap() {\r\n\t\t\r\n\t\tvar mapWin = GptUtils.popUp(mapViewerUrl, \r\n GptMapViewer.TITLE, \r\n GptMapViewer.dimensions.WIDTH, \r\n GptMapViewer.dimensions.HEIGHT);\r\n \r\n\t\treturn mapWin;\r\n\t}", "function openGWindow(gform){\n\tvar thislink=\"http://maps.google.com/maps?f=d&hl=en&saddr=\" + gform.saddr.value.replace(/ /g,\"+\") + \"&daddr=\" + gform.daddr.value.replace(/ /g,\"+\");\n\twindow.open(thislink,\"gwindow\", \"\", false);\n\treturn false;\n}", "function mGItemAddPage_show(){\r\n //show google map\r\n showGoogleMap();\r\n}", "function openStreetView() {// uses google maps URL's-cross platform // map_action=pano is street view // viewpoint finds closest street view pano to the coordinates\n var openStreetView = \"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=\" + destination.lat + \",\" + destination.lng;\n //launches google maps\n window.open(openStreetView);\n}", "function showMapcontextWindow() {\n $(\"#mapContextWindow\").dialog(\"open\");\n}", "function doMapClick()\n{\n\tvar list = null;\n\tvar map = null;\n\tvar tabs = null;\n\t\n\t// Debug\n\tconsole.log( 'Map.' );\n\t\n\t// Already viewing this tab\n\tif( this.className.indexOf( 'selected' ) >= 0 )\n\t{\n\t\tconsole.log( 'Already active.' );\n\t\treturn;\n\t}\n\t\n\t// Switch visual indicator\n\ttabs = document.querySelectorAll( '.header .tabs p' );\n\ttabs[0].classList.remove( 'selected' );\n\ttabs[1].classList.add( 'selected' );\n\t\n\t// Switch view\n\tmap = document.querySelector( '.map' );\n\tmap.style.visibility = 'visible';\n\t\n\tlist = document.querySelector( '.list' );\n\tlist.style.visibility = 'hidden';\t\n}", "function map () {\n // Create the browser window.\n startWin = new BrowserWindow({ width: screen_width, height: screen_height })\n // and load the index.html of the app.\n startWin.loadFile('map.html')\n // Open the DevTools.\n\n // Emitted when the window is closed.\n startWin.on('closed', () => {\n // Dereference the window object, usually you would store windows\n // in an array if your app supports multi windows, this is the time\n // when you should delete the corresponding element.\n startWin = null\n })\n}", "function openMaps() {// uses google maps URL's-cross platform // leave out origin to use current location // lat,lng destination // use placeID to get the address and name // travelmode Walk // starts right into navigation\nvar openDirections = \"https://www.google.com/maps/dir/?api=1&destination=\" + destination.lat + \",\" + destination.lng + \"&query_place_id=\" + destination.placeID + \"&travelmode=walking&dir_action=navigate\";\n//launches google maps\nwindow.open(openDirections);\n}", "goToWebsite(){\n this.openWebsite(this.mapPoint.website);\n }", "function showMap()\n{\n\tAlloy.createController('MapView').getView().open();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
obtener profesores correspodientes al inspector de curso, obtenemos los cursos asignados al inspector de curso, posteriormente obtenemos los profesores y materias que se dictan en dicho curso
static async getProfesoresForIc(idIc, idanio_lectivo) { //cursos para inspector de curso //let cursos = await db.query('SELECT idcurso FROM curso WHERE user_iduser = ? AND cur_estado = 1', [idIc]); let cursos = await Curso.getCursosForIc(idIc, idanio_lectivo); //Consulta para obtener las materias, cursos y profesores var sql = []; if (cursos.length > 0) { for (let index = 0; index < cursos.length; index++) { let mhc = await db.query(` SELECT idfuncionario, idmaterias_has_curso, profesor_idprofesor, fun_nombres, idmaterias, mat_nombre, cur_curso, idcurso FROM materias_has_curso INNER JOIN funcionario on funcionario.idfuncionario = materias_has_curso.profesor_idprofesor INNER JOIN materias on materias.idmaterias = materias_has_curso.materias_idmaterias INNER JOIN curso on curso.idcurso = materias_has_curso.curso_idcurso WHERE materias_has_curso.curso_idcurso = ? AND mat_has_cur_estado = 1 AND mat_has_curso_idanio_lectivo = ? `, [cursos[index].idcurso, idanio_lectivo]); if (mhc.length > 0) { mhc.forEach(element => { sql.push(element); }); } } } return sql //return cursos }
[ "function asociarSedeProfesor() {\n let codigoCursoActii = guardarSedeAsociar();\n\n let cursoActii = buscarCursoActiiPorCod(codigoCursoActii);\n\n let profesoresSeleccionados = guardarProfesoresAsociar();\n\n console.log(profesoresSeleccionados);\n\n\n let listaCursoActii = [];\n\n let sCodigo = cursoActii[0];\n let sNombreCurso = cursoActii[1];\n let nHoras = cursoActii[2];\n let nCosto = cursoActii[3];\n let bEstado = cursoActii[4];\n let CursosAsociadas = cursoActii[5]\n let profesoresAsociados = profesoresSeleccionados;\n let sFechaInicio = cursoActii[7];\n let sFechaFin = cursoActii[8];\n\n if (profesoresAsociados.length == 0) {\n swal({\n title: \"Asociación inválida\",\n text: \"No se le asignó ningun profesor al curso.\",\n buttons: {\n confirm: \"Aceptar\",\n },\n });\n } else {\n listaCursoActii.push(sCodigo, sNombreCurso, nHoras, nCosto, bEstado, CursosAsociadas, profesoresAsociados, sFechaInicio, sFechaFin);\n actualizarCursoActii(listaCursoActii);\n\n swal({\n title: \"Asociación registrada\",\n text: \"Se le asignó un curso de actualización a un profesor exitosamente.\",\n buttons: {\n confirm: \"Aceptar\",\n },\n });\n limpiarCheckbox();\n }\n}", "function mostrarProfesoresSede() {\n let cursoSelect = this.dataset.codigo;\n let cursoActii = buscarCursoActiiPorCod(cursoSelect);\n let listaProfesores = getListaProfesores();\n let listaCheckboxProfesores = document.querySelectorAll('#tblProfesores tbody input[type=checkbox]');\n let cedProfs = [];\n\n for (let i = 0; i < cursoActii[6].length; i++) {\n cedProfs.push(cursoActii[6][i]);\n }\n\n for (let j = 0; j < listaProfesores.length; j++) {\n for (let k = 0; k < cedProfs.length; k++) {\n if (listaProfesores[j][0] == cedProfs[k]) {\n listaCheckboxProfesores[j].checked = true;\n }\n }\n }\n verificarCheckCursos();\n}", "function determinarTipoProfesor(profesores) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla profesores\n for (var i = 0; i < profesores.length; i++) {\n //variables utilizadas para determinar los valores finales de\n //cada uno de los valores de la consulta cambiandolos por números\n var generoTupla, autoEvaluacionTupla, disciplinaTupla,\n pcTupla, habWebTupla, expWebTupla = 0;\n \n //se proporciona un número dependiendo del sexo del profesor\n //o si no quiere mostrarlo\n switch(profesores[i].b){\n case \"F\": \n generoTupla = 1;\n break;\n case \"M\": \n generoTupla = 2;\n break;\n case \"NA\": \n generoTupla = 3;\n break;\n }\n //se proporciona un número dependiendo de la autoEvalución del profesor\n //de 1 a 3\n switch(profesores[i].c){\n case \"B\": \n autoEvaluacionTupla = 1;\n break;\n case \"I\": \n autoEvaluacionTupla = 2;\n break;\n case \"A\": \n autoEvaluacionTupla = 3;\n break;\n }\n //se proporciona un número dependiendo de la disciplina del profesor\n //desde 1 a 3\n switch(profesores[i].e){\n case \"DM\": \n disciplinaTupla = 1;\n break;\n case \"ND\": \n disciplinaTupla = 2;\n break;\n case \"o\": \n disciplinaTupla = 3;\n break;\n } \n \n //se proporciona un número dependiendo de las habilidades con la computadora\n //del profesor de 1 a 3\n switch(profesores[i].f){\n case \"L\": \n pcTupla = 1;\n break;\n case \"A\": \n pcTupla = 2;\n break;\n case \"H\": \n pcTupla = 3;\n break;\n }\n \n //se proporciona un número dependiendo de la experiencia \n //utilizando tecnologías web para enseñanza del profesor\n //de 1 a 3\n switch(profesores[i].g){\n case \"N\": \n habWebTupla = 1;\n break;\n case \"S\": \n habWebTupla = 2;\n break;\n case \"O\": \n habWebTupla = 3;\n break;\n }\n \n //se proporciona un número dependiendo de la experiencia \n //del profesor para utilizar páginas web para enseñanza del profesor\n //de 1 a 3\n switch(profesores[i].h){\n case \"N\": \n expWebTupla = 1;\n break;\n case \"S\": \n expWebTupla = 2;\n break;\n case \"O\": \n expWebTupla = 3;\n break;\n } \n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow(profesores[i].a - (parseInt(document.getElementById('edad').value)), 2) + Math.pow(generoTupla - (parseInt(document.getElementById('genero').value)), 2) + \n Math.pow(autoEvaluacionTupla - (parseInt(document.getElementById('autoevaluacion').value)), 2) + Math.pow(profesores[i].d - (parseInt(document.getElementById('numeroVeces').value)), 2) +\n Math.pow(disciplinaTupla - (parseInt(document.getElementById('disciplina').value)), 2) + Math.pow(pcTupla - (parseInt(document.getElementById('habilidadPC').value)), 2) +\n Math.pow(habWebTupla - (parseInt(document.getElementById('habilidadWeb').value)), 2) + Math.pow(expWebTupla - (parseInt(document.getElementById('experienciaWeb').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n }\n }\n //salida en pantalla del tipo de profesor\n document.getElementById('mensaje5').innerHTML = 'El profesor es de tipo ' + profesores[numeroTupla].clase + ' en la posición '+profesores[numeroTupla].id+'.';\n}", "function cargarCgg_gem_perfil_profCtrls(){\n\t\tif(inRecordCgg_gem_perfil_prof){\n\t\t\tcbxCgnes_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGNES_CODIGO'));\n\t\t\ttxtCgppr_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGPPR_CODIGO'));\t\t\t\n\t\t\tcodigoEspecialidad = inRecordCgg_gem_perfil_prof.get('CGESP_CODIGO');\n\t\t\ttxtCgesp_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGESP_NOMBRE'));\n\t\t\tcodigoTitulo = inRecordCgg_gem_perfil_prof.get('CGTPR_CODIGO');\n\t\t\ttxtCgtpr_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGTPR_DESCRIPCION'));\t\t\t\n\t\t\tcbxCgmdc_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGMDC_CODIGO'));\n\t\t\tcodigoPersona = inRecordCgg_gem_perfil_prof.get('CRPER_CODIGO')\n\t\t\ttxtCrper_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CRPER_NOMBRES')+\" \"+inRecordCgg_gem_perfil_prof.get('CRPER_APELLIDO_PATERNO')+\" \"+inRecordCgg_gem_perfil_prof.get('CRPER_APELLIDO_MATERNO'));\t\t\t\n\t\t\tcodigoInstitucion = inRecordCgg_gem_perfil_prof.get('CGIEN_CODIGO');\n\t\t\ttxtCgien_codigo.setValue(inRecordCgg_gem_perfil_prof.get('CGIED_NOMBRE'));\t\t\t\n\t\t\tnumCgppr_nivel_aprobado.setValue(inRecordCgg_gem_perfil_prof.get('CGPPR_NIVEL_APROBADO'));\n\t\t\tdtCgppr_fecha_inicio.setValue((inRecordCgg_gem_perfil_prof.get('CGPPR_FECHA_INICIO'))||'');\n\t\t\tdtCgppr_fecha_fin.setValue((inRecordCgg_gem_perfil_prof.get('CGPPR_FECHA_FIN'))||'');\n\t\t\tchkCgppr_confirmado.setValue(inRecordCgg_gem_perfil_prof.get('CGPPR_CONFIRMADO'));\n\t\t\tdtCgppr_fecha_confirmacion.setValue(inRecordCgg_gem_perfil_prof.get('CGPPR_FECHA_CONFIRMACION')||new Date());\n\t\t\tchkCgppr_predeterminado.setValue(inRecordCgg_gem_perfil_prof.get('CGPPR_PREDETERMINADO'));\n\t\t\tisEdit = true;\n\t\t\t\n\t\t\tif (IN_PERSONA){\n\t\t\t\ttxtCrper_codigo.hidden = true;\n\t\t\t\tbtnCrper_codigoCgg_gem_perfil_prof.hidden=true;\n\t\t\t}else{\n\t\t\t\ttxtCrper_codigo.hidden = false;\n\t\t\t\tbtnCrper_codigoCgg_gem_perfil_prof.hidden=false;\n\t\t\t}\n\t\t\tif (inRecordCgg_gem_perfil_prof.get('CGPPR_NIVEL_APROBADO') > 0)\n {\n chkFormacionParcial.setValue(true);\n numCgppr_nivel_aprobado.enable();\n //numCgppr_nivel_aprobado.enable();\n }\n else\n {\n chkFormacionParcial.setValue(false);\n numCgppr_nivel_aprobado.disable();\n }\t\t\t\n\t}}", "function cobrosPendientesClienteLogueado(req, res) {\n var cliente = req.user.sub;\n var cundina = req.params.id;\n console.log(cliente);\n Pago.find({\n user: cliente,\n type: 'Cobro',\n cundina: cundina\n })\n .populate({ path: 'cundina' })\n .populate({ path: 'user' })\n .exec((err, pagos) => {\n if (err) return res.status(500).send({ message: `Error al obtener lo cobors de la cundina ${err}` });\n if (!pagos) return res.status(404).send({ message: `No se encontraron cobros para la cundina` });\n return res.status(200).send({ pagos: pagos });\n });\n}", "static getCursoConIC(idanio_lectivo) {\n return db.query(`\n SELECT\n curso.idcurso,\n curso.idcurso,\n curso.cur_curso,\n inspector.anio_lectivo_idanio_lectivo,\n inspector.tipo,\n inspector.idinspector,\n inspector.user_iduser,\n user.iduser,\n inspector.estado\n FROM\n inspector\n JOIN curso ON inspector.curso_idcurso = curso.idcurso\n JOIN user ON inspector.user_iduser = user.iduser\n WHERE\n inspector.anio_lectivo_idanio_lectivo = ?\n AND inspector.estado = 1 \n `, [idanio_lectivo]);\n }", "colaboradores(req, res) {\n return __awaiter(this, void 0, void 0, function* () {\n let listaColaboradores = [];\n let nombreColaborador;\n let apellidosColaborador;\n let idColaborador;\n const datos = yield database_1.default.query(\"SELECT * FROM amigo WHERE (idColaborador1=? OR idColaborador2=?) AND aceptado=1\", [req.session.idUserIniciado, req.session.idUserIniciado]);\n if (datos.length >= 1) {\n let aux = 0;\n for (let colaborador of datos) {\n nombreColaborador = yield database_1.default.query(\"SELECT nombre FROM colaborador WHERE idColaborador=?\", [colaborador.idColaborador]);\n apellidosColaborador = yield database_1.default.query(\"SELECT apellidos FROM colaborador WHERE idColaborador=?\", [colaborador.idColaborador]);\n idColaborador = yield database_1.default.query(\"SELECT idColaborador FROM colaborador WHERE idColaborador=?\", [colaborador.idColaborador]);\n listaColaboradores[aux] = {\n nombreColaborador,\n apellidosColaborador,\n idColaborador,\n };\n aux = aux + 1;\n }\n res.status(200).json(listaColaboradores);\n }\n else {\n res.status(204).send({ message: \"No se adquirieron colaboradores\" });\n }\n });\n }", "function obtenerMateriasDeCurso(idCurso) {\n return new Promise((resolve, reject) => {\n Curso.aggregate([\n {\n $match: {\n _id: mongoose.Types.ObjectId(idCurso),\n },\n },\n {\n $unwind: \"$materias\",\n },\n {\n $lookup: {\n from: \"materiasXCurso\",\n localField: \"materias\",\n foreignField: \"_id\",\n as: \"materiasDelCurso\",\n },\n },\n {\n $project: {\n \"materiasDelCurso.idMateria\": 1,\n },\n },\n ])\n .then((materiasDelCurso) => {\n let idsMateriasDelCurso = [];\n materiasDelCurso.forEach((objMateria) => {\n idsMateriasDelCurso.push(objMateria.materiasDelCurso[0].idMateria);\n });\n resolve(idsMateriasDelCurso);\n })\n .catch((err) => reject(err));\n });\n}", "function listarMedicoseAuxiliares(usuario, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select crmv, nomeMedico, telefoneMedico, emailMedico from Medico, Responsavel where Medico.Estado = Responsavel.Estado and Medico.Cidade = Responsavel.Cidade and Responsavel.idusuario = ?\", [usuario.idusuario], function(err, result){\n\t\t\t\tcon.release();\n\t\t\t\tres.json(result);\n\t\t\t});\n\t\t});\n\t}", "function getProm (){\n registros.forEach((value) => { \n let {alumno,nota1,nota2} = value\n let prom = GetPromedio(nota1,nota2);\n let status= GetStatus(prom)\n promedios.push(\n {\n alumno : alumno,\n promedio: prom,\n estado: status\n }\n )\n });\n console.log(promedios);\n}", "function getChoreListAndWelcomeUser(emmiter) {\n console.log(\"about to get chores, hour of the day is \" + current_hour + \", day of week is \" + current_day + \" tzOffset:\" + tzOffset);\n console.log(\" \" + new Date());\n dynamoChoresName = getTimeOfDay();\n todChores = dynamoChoresName + \"Chores.txt\";\n dynamoChores = emmiter.attributes[dynamoChoresName];\n console.log(dynamoChoresName + \" from dynamo got:\" + dynamoChores);\n if (typeof dynamoChores == \"undefined\") {\n console.log(\"did not find existing chore list for this user\");\n } else {\n chores = dynamoChores;\n maxChores = chores.length;\n console.log(\"found existing chore list for this user:\" + dynamoChores + \" going directly to askAboutAChore with \" + maxChores + \" chores\");\n askAboutAChore(buildWelcome(emmiter), emmiter);\n return;\n }\n getDefaultChoresFromS3AndWelcomeUser(todChores, emmiter);\n}", "function obtenerDatosSucursal(){\n cxcService.getCpcSucursalByIdSucursal({},{},atributosPerfil['sucursalPredeterminada'],serverConf.ERPCONTA_WS, function (response) {\n //exito\n console.info(\"emisionFacturaContrato: Sucursal preestablecida\",response.data);\n //$scope.sucursal = response.data;\n $scope.facturaEmitidaPojo.cpcFacturaEmitida.cpcDosificacion.cpcSucursal = response.data;\n //si la sucursal predeterminada no es la casa matriz obtener datos de la casa matriz\n if( $scope.facturaEmitidaPojo.cpcFacturaEmitida.cpcDosificacion.cpcSucursal .numeroSucursal>0) {\n $scope.mostrar.datosSucursal=true;\n obtenerCasaMatriz();\n }\n }, function (responseError) {\n //error\n });\n }", "getCursos(codigo) {\n try {\n // Recebendo lista de objetos cadastrados\n const objectData = db.getData(\"/curso/\");\n\n // Convertendo objeto em lista e retornando\n const listData = [];\n Object.keys(objectData).forEach(key => {\n const data = objectData[key];\n if (String(data.campusCodigo) === String(codigo)) listData.push(data);\n });\n\n return listData;\n\n } catch (error) {\n throw error;\n }\n }", "function infProyectoConocimiento(tipo, id, callback) {\n // primero obtener los registros pasando el id\n var connection = getConnection();\n var registros = null;\n var sql = \"SELECT\";\n sql += \" p.nombre AS proyecto,\";\n sql += \" cat.nombre AS ncategoria,\";\n sql += \" c.nombre AS nconocimiento,\";\n sql += \" t.nombre AS ntrabajador,\";\n sql += \" DATE_FORMAT(e.dFecha, '%d/%m/%Y') AS dFecha,\";\n sql += \" DATE_FORMAT(e.hFecha, '%d/%m/%Y') AS hFecha,\";\n sql += \" e.observaciones AS observaciones\";\n sql += \" FROM\";\n sql += \" evaluaciones AS e\";\n sql += \" LEFT JOIN asg_proyectos AS ap ON ap.asgProyectoId = e.asgProyectoId\";\n sql += \" LEFT JOIN proyectos AS p ON p.proyectoId = ap.proyectoId\";\n sql += \" LEFT JOIN conocimientos AS c ON c.conocimientoId = e.conocimientoId\";\n sql += \" LEFT JOIN trabajadores AS t ON t.trabajadorId = ap.trabajadorId\";\n sql += \" LEFT JOIN conocimientos_categorias AS cc ON cc.conocimientoId = c.conocimientoId\";\n sql += \" LEFT JOIN catconocimientos AS cat ON cat.catConocimientoId = cc.catConocimientoId\";\n if (id == 0) {\n sql += \" WHERE TRUE\";\n } else {\n sql += \" WHERE p.proyectoId = ?\";\n sql = mysql.format(sql, id);\n }\n sql += \" ORDER BY 1, 2, 3\";\n connection.query(sql, function (err, result) {\n if (err) {\n callback(err, null);\n return;\n }\n registros = infTipoProyectoConocimiento(tipo, result);\n callback(null, registros);\n });\n closeConnectionCallback(connection, callback);\n}", "function obtenerSolicitudesCorrelativo(req, res) {\n Solicitud.findOne({\n correlativo: req.params.correlativo\n }, (err, solicitud) => {\n if (err) return res.status(500).send({\n message: 'Error: Error en la peticion',\n Error: err\n });\n\n if (!solicitud) return res.status(404).send({\n message: 'Error: No hay solicitudes disponibles'\n });\n\n return res.status(200).send({\n solicitud\n });\n\n }).populate({ path: 'localID', select: 'capacidad text ubicacion nombre' })\n .populate({ path: 'administrador_sistema', select: 'nombre apellido usuario' });\n}", "function cargarCgg_dhu_seguimiento_profesionalCtrls(){\n if(inRecordCgg_dhu_seguimiento_profesional){\n txtCdspr_codigo.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_CODIGO'));\n txtCdbec_codigo.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDBEC_CODIGO'));\n numCdspr_anio.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_ANIO'));\n dtCdspr_fecha_ingreso.setValue(truncDate(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_FECHA_INGRESO')));\n txtCdspr_institucion.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_INSTITUCION'));\n txtCdspr_cargo.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_CARGO'));\n dtCdspr_fecha_salida.setValue(truncDate(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_FECHA_SALIDA')));\n txtCdspr_observaciones.setValue(inRecordCgg_dhu_seguimiento_profesional.get('CDSPR_OBSERVACIONES'));\n isEdit = true;\n habilitarCgg_dhu_seguimiento_profesionalCtrls(true);\n }}", "function proximasClases(datos){\n\n /*Variables para extraer los datos del objeto JSON*/ \n var nombre, h_inicio, h_fin, aula;\n \n /*Si existen clases para ese aula (hay datos), se crea el texto HMTL necesario*/ \n if(datos!=null){\n var texto = \"\";\n \n /*Se recorren una a una las tuplas recuperadas hasta un maximo de 2*/\n //for (var j=0; j<datos.length; j++) {\n for (var j=0; j<2; j++) {\n \t\t/*Se extrae la información de cada tupla*/\n \t\taula=datos[j].a_nombre;\n nombre=datos[j].nombre;\n \t\th_inicio=datos[j].hora_inicio;\n \t\th_fin=datos[j].hora_fin;\n \n \t\t/*Se elimina el final de la hora para mostrar solo hora y minutos (sin segundos)*/\n \t\tvar h_inicio_corta = quitarFinal(h_inicio, 3);\n \t\tvar h_fin_corta = quitarFinal(h_fin, 3);\n \t\t\n /*Si la asignatura tiene el nombre muy largo se pone la letra más pequeña*/\n if (nombre.length > 35){\n \t\t nombre = \"<small>\" + nombre + \"</small>\" ;\n \t\t}\n \t\t\n /*Si la clase esta en curso se pinta en rojo*/\n if(comprobarClaseEmpezada(h_inicio, h_fin) == 1){\n texto = texto + \"<span style=color:red> \" + h_inicio_corta + \" - \" + h_fin_corta + \": \" + nombre + \" </span></br>\";\n \n }/*Si no esta empezada se pinta en negro*/ \n else{\n \t\t texto = texto + \"<span style=color:black> \" + h_inicio_corta + \" - \" + h_fin_corta + \": \" + nombre + \" </span></br>\";\n }\n } /*Fin bucle for*/\n\n if(document.getElementById(aula) != null)\n document.getElementById(aula).innerHTML = texto;\n } /*Fin if*/\n \n }", "function getProfFromRec(req) {\n const prueb = Object.values(req.body);\n\n /*var result = Object.keys(req.body).map(function(key) {\n return [Number(key), req.body[key]];\n});*/\n console.log(\"esto desde el getfromrec\",req.body);\n const profesor = {\n //PREFERIBLEMNTE TENER EL MISMO ORDEN DE LAS COLUMNAS EN LA BD\n ced_prof: req.body.ced_profesor, //todo en minuscula sino agrega nada es porque debe estar en minuscula\n password: req.body.password,\n nombre: req.body.nombre,\n apellido: req.body.apellido,\n sexo: req.body.sexo,\n direccion: req.body.direccion,\n correo: req.body.correo,\n celular: req.body.celular,\n };\n return req.body;\n}", "static getCursosForIc(idic, idanio_lectivo) {\n return db.query(`\n SELECT\n curso.idcurso,\n curso.cur_curso,\n curso.cur_estado,\n nivel.niv_nivel\n FROM\n inspector\n JOIN \n curso ON inspector.curso_idcurso = curso.idcurso\n JOIN \n nivel ON nivel.idnivel = curso.nivel_idnivel\n WHERE\n inspector.anio_lectivo_idanio_lectivo = ?\n AND \n inspector.estado = 1\n AND\n inspector.user_iduser = ? `, [idanio_lectivo, idic]);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add application to auto launch program
function start_auto_launch() { var quarkclientAutoLauncher = new AutoLaunch({ name: 'QuarkClient', // path: '/Applications/QuarkClient.app', // path: '"C:\\Users\\C9G\\AppData\\Roaming\\uTorrent Web\\utweb.exe" /MINIMIZED', path: basepath + '\\quarkclient.exe', }); quarkclientAutoLauncher.enable(); quarkclientAutoLauncher.isEnabled() .then(function(isEnabled){ if(isEnabled){ return; } quarkclientAutoLauncher.enable(); }) .catch(function(err){ // handle error }); }
[ "function addtoStart() {\n\n const exeName = path.basename(process.execPath);\n app.setLoginItemSettings({\n openAtLogin: true,\n path: process.execPath,\n args: [\n '--processStart', \"${exeName}\",\n '--process-start-args', \"--hidden\"\n ]\n });\n}", "function autoLaunch() {\n\tconst appFolder = path.dirname(process.execPath)\n\tconst updateExe = path.resolve(appFolder, '..', 'Update.exe')\n\tconst exeName = path.basename(process.execPath)\n\t \n\tapp.setLoginItemSettings({\n\t openAtLogin: true,\n\t path: updateExe,\n\t args: [\n\t '--processStart', `\"${exeName}\"`,\n\t '--process-start-args', `\"--hidden\"`\n\t ]\n\t})\n}", "function installBKA(obj) {\n\tLaunchBar.execute(\"/usr/bin/open\",\"OpenFTDocAtLine.app\");\n}", "startApp() {\n\t\tconst manifest = this.manifest;\n\t\tlogger.debug('main->startApp');\n\t\tconst splashScreenImage = this.getManifestEntry('splashScreenImage');\n\t\tif (splashScreenImage) {\n\t\t\tconst manifestTimeout = this.getManifestEntry('splashScreenTimeout');\n\t\t\tMainWindowProcessManager.showSplashScreen(splashScreenImage, manifestTimeout)\n\t\t\t\t.catch(err => logger.error(`Unable to load splash screen ${err}`));\n\t\t}\n\n\t\t// https://docs.microsoft.com/en-us/windows/desktop/shell/appids\n\t\tthis.app.setAppUserModelId(this.getManifestEntry('startup_name.name') || 'sea');\n\t\tthis.app.manifest = manifest;\n\n\t\tPermissionsManager.setDefaultPermissions(manifest.electronAdapter.permissions);\n\t\tMainWindowProcessManager.setManifest(manifest);\n\n\t\tmanifest.main.icon = manifest.main.applicationIcon;\n\t\tlogger.log(`APPLICATION LIFECYCLE: Starting main application ${manifest.main.name}`);\n\t\tMainWindowProcessManager.createWindowProcess(manifest.main, manifest, null, (err, res) => {\n\t\t\tif (err) logger.error(`Failed to start main application ${err}`);\n\t\t\tlogger.log('APPLICATION LIFECYCLE: Main application started.');\n\t\t});\n\n\t\tthis.setContentSecurityPolicy();\n\t\tthis.setupChromePermissionsHandlers();\n\t}", "function launchApplication(){\r\n// launch outside application\r\n//shellRef.Run(\"C:\\\\windows\\\\gcviewer.jar\");\r\nshellRef.Run(\"gcviewer.jar\");\r\n}", "function LaunchNewProgram(application, args, url) {\n OverlayScreenForLaunch()\n $.ajax({\n url: \"/Action/Launch?detach=yes&name=\" + application + \"&args=\" + encodeURIComponent(args),\n success: function (data) {\n window.location = url;\n },\n error: function (xhr, ajaxOptions, thrownError) {\n RemoveScreenOverlay()\n },\n cache: false\n });\n}", "function LaunchProgram(application, url, args) {\n OverlayScreenForLaunch()\n $.ajax({\n url: \"/Action/Launch?name=\" + application + (args == null ? \"\" : \"&args=\" + encodeURIComponent(args)),\n success: function (data) {\n window.location = url;\n },\n error: function (xhr, ajaxOptions, thrownError) {\n RemoveScreenOverlay()\n },\n cache: false\n });\n}", "function launch() {}", "function manageStartup(enable) {\n let appLauncher = new AutoLaunch({\n // Change this to the name of the application or what\n // should appear in the startup menu.\n name: 'BB'\n });\n if (enable) {\n appLauncher.isEnabled().then(function(enabled){\n if(enabled) return;\n return appLauncher.enable();\n }).then(function(err){\n // If you want to remove all console output, remove lines that contain \"console.error(err)\"\n if (err !== undefined) console.error(err);\n });\n } else {\n appLauncher.isEnabled().then(function(enabled){\n if(!enabled) return;\n return appLauncher.disable();\n }).then(function(err){\n if (err !== undefined) console.error(err);\n }); \n }\n}", "function startApp() {\n\tinquirer\n\t\t.prompt([\n\t\t\t{\n\t\t\t\tname: 'startApp',\n\t\t\t\ttype: 'confirm',\n\t\t\t\tmessage: 'Would you like to assemble a team?',\n\t\t\t},\n\t\t])\n\t\t.then((res, err) => {\n\t\t\tif (err) console.error(err);\n\t\t\tif (res.startApp) {\n\t\t\t\taddManager();\n\t\t\t} else {\n\t\t\t\tprocess.exit();\n\t\t\t}\n\t\t});\n}", "_startApplication () {\r\n const pwdWindow = document.createElement('pwd-window')\r\n pwdWindow.setAttribute('name', this._title)\r\n const app = document.createElement(this._app)\r\n pwdWindow.appendChild(app)\r\n\r\n document.body.appendChild(pwdWindow)\r\n }", "function mainIntent(app)\n {\n app.ask('Polly want a cracker');\n }", "function doAppConfig(){\r\n\tvar params = {\"handle\":'',\"type\":\"application\",\"class\":\"appconfig\",\"do\":\"start\",\"title\":\"Par&aacute;metros de la empresa\",\"width\":\"750\",\"height\":\"500\",\"closable\":true,\"modal\":true };\r\n\texecuteApplication(params);\r\n}", "function startApp() {\n clear();\n startPrompt();\n}", "function makeApp(options) {\r\n var app;\r\n\r\n if (options.type && options.type.toLowerCase() === 'service') {\r\n // launch service\r\n } else {\r\n // launch GUI\r\n return new GUIApplication(options);\r\n }\r\n }", "function startApp() {\n\tswitch (arg_1) {\n\t\tcase 'spotify-this-song':\n\t\t\tgetMusic();\n\t\t\tbreak;\n\t\tcase 'my-tweets':\n\t\t\tgetTweets();\n\t\t\tbreak;\n\t\tcase 'movie-this':\n\t\t\tgetMovie();\n\t\t\tbreak;\n\t\tcase 'do-what-it-says':\n\t\t\treadRandom();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log('Wrong entry! Please try again.');\n\t}\n}", "function addCommand() {\n\n var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU),\n INSTALL_COMMAND_SCRIPT = \"file.installCommandScript\";\n\n CommandManager.register(Strings.CMD_LAUNCH_SCRIPT_MAC, INSTALL_COMMAND_SCRIPT, handleInstallCommand);\n menu.addMenuDivider();\n menu.addMenuItem(INSTALL_COMMAND_SCRIPT);\n }", "function autoLaunch() {\n const AutoLauncher = new AutoLaunch({\n name: 'Tiny-Timer',\n mac: {\n useLaunchAgent: true,\n },\n });\n\n AutoLauncher.isEnabled()\n .then((isEnable) => {\n if (!isEnable) {\n AutoLauncher.enable();\n } else {\n AutoLauncher.disable();\n }\n });\n}", "function createShortcuts (cb) {\n spawnUpdate(['--createShortcut', EXE_NAME], cb)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates an incoming bulk transfer prepare request and makes a callback to the originator with the result
async prepareBulkTransfer(bulkPrepareRequest, sourceFspId) { try { // retrieve bulk quote data const bulkQuote = await this._cache.get(`bulkQuotes_${bulkPrepareRequest.bulkQuoteId}`); if (!bulkQuote) { // Check whether to allow transfers without a previous quote. if (!this._allowTransferWithoutQuote) { throw new Error(`Corresponding bulk quotes not found for bulk transfers ${bulkPrepareRequest.bulkTransferId}`); } } // create an index of individual quote results indexed by transactionId for faster lookups const quoteResultsByTrxId = {}; if (bulkQuote && bulkQuote.mojaloopResponse && bulkQuote.mojaloopResponse.individualQuoteResults) { for (const quoteResult of bulkQuote.mojaloopResponse.individualQuoteResults) { quoteResultsByTrxId[quoteResult.transactionId] = quoteResult; } } // transfer fulfilments const fulfilments = {}; // collect errors for each transfer let individualTransferErrors = []; // validate individual transfer for (const transfer of bulkPrepareRequest.individualTransfers) { // decode ilpPacked for this transfer to get transaction object const transactionObject = this._ilp.getTransactionObject(transfer.ilpPacket); // we use the transactionId from the decoded ilpPacked in the transfer to match a corresponding quote const quote = quoteResultsByTrxId[transactionObject.transactionId] || null; // calculate or retrieve fulfilments and conditions let fulfilment = null; let condition = null; if (quote) { fulfilment = bulkQuote.fulfilments[quote.quoteId]; condition = quote.condition; } else { fulfilment = this._ilp.calculateFulfil(transfer.ilpPacket); condition = this._ilp.calculateConditionFromFulfil(fulfilment); } fulfilments[transfer.transferId] = fulfilment; // check incoming ILP matches our persisted values if (this._checkIlp && (transfer.condition !== condition)) { const transferError = this._handleError(new Error(`ILP condition in bulk transfers prepare for ${transfer.transferId} does not match quote`)); individualTransferErrors.push({ transferId: transfer.transferId, transferError }); } } if (bulkQuote && this._rejectTransfersOnExpiredQuotes) { const now = new Date(); const expiration = new Date(bulkQuote.mojaloopResponse.expiration); if (now > expiration) { // TODO: Verify and align with actual schema for bulk transfers error endpoint const error = Errors.MojaloopApiErrorObjectFromCode(Errors.MojaloopApiErrorCodes.QUOTE_EXPIRED); this._logger.error(`Error in prepareBulkTransfers: bulk quotes expired for bulk transfers ${bulkPrepareRequest.bulkTransferId}, system time=${now.toISOString()} > quote time=${expiration.toISOString()}`); return this._mojaloopRequests.putBulkTransfersError(bulkPrepareRequest.bulkTransferId, error, sourceFspId); } } if (individualTransferErrors.length) { // TODO: Verify and align with actual schema for bulk transfers error endpoint const mojaloopErrorResponse = { bulkTransferState: 'REJECTED', // eslint-disable-next-line no-unused-vars individualTransferResults: individualTransferErrors.map(({ transferId, transferError }) => ({ transferId, errorInformation: transferError, })) }; this._logger.push({ ...individualTransferErrors }).log('Error in prepareBulkTransfers'); this._logger.push({ ...individualTransferErrors }).log(`Sending error response to ${sourceFspId}`); return await this._mojaloopRequests.putBulkTransfersError(bulkPrepareRequest.transferId, mojaloopErrorResponse, sourceFspId); } // project the incoming bulk transfer prepare into an internal bulk transfer request const internalForm = shared.mojaloopBulkPrepareToInternalBulkTransfer(bulkPrepareRequest, bulkQuote, this._ilp); // make a call to the backend to inform it of the incoming bulk transfer const response = await this._backendRequests.postBulkTransfers(internalForm); if (!response) { // make an error callback to the source fsp return 'No response from backend'; } this._logger.log(`Bulk transfer accepted by backend returning homeTransactionId: ${response.homeTransactionId} for mojaloop bulk transferId: ${bulkPrepareRequest.bulkTransferId}`); // create a mojaloop transfer fulfil response const mojaloopResponse = { completedTimestamp: new Date(), bulkTransferState: 'COMMITTED', }; if (response.individualTransferResults && response.individualTransferResults.length) { // eslint-disable-next-line no-unused-vars mojaloopResponse.individualTransferResults = response.individualTransferResults.map((transfer) => { return { transferId: transfer.transferId, fulfilment: fulfilments[transfer.transferId], ...transfer.extensionList && { extensionList: { extension: transfer.extensionList, }, } }; }); } // make a callback to the source fsp with the transfer fulfilment return this._mojaloopRequests.putBulkTransfers(bulkPrepareRequest.bulkTransferId, mojaloopResponse, sourceFspId); } catch (err) { this._logger.push({ err }).log('Error in prepareBulkTransfers'); const mojaloopError = await this._handleError(err); this._logger.push({ mojaloopError }).log(`Sending error response to ${sourceFspId}`); return await this._mojaloopRequests.putBulkTransfersError(bulkPrepareRequest.bulkTransferId, mojaloopError, sourceFspId); } }
[ "setupSendCallback() {\n // the message was sent successfully, execute the callback\n const onDrain = () => {\n if (this.sentCallbackFn.length > 0) {\n const seqFn = this.sentCallbackFn.splice(0, 1)[0];\n if (\"function\" === typeof seqFn) {\n debug(\"executing send callback\");\n seqFn(this.transport);\n } else if (Array.isArray(seqFn)) {\n debug(\"executing batch send callback\");\n const l = seqFn.length;\n let i = 0;\n for (; i < l; i++) {\n if (\"function\" === typeof seqFn[i]) {\n seqFn[i](this.transport);\n }\n }\n }\n }\n };\n\n this.transport.on(\"drain\", onDrain);\n\n this.cleanupFn.push(() => {\n this.transport.removeListener(\"drain\", onDrain);\n });\n }", "_onBulkReadReady(...args) {\n executeSoon(() => {\n // Ensure the transport is still alive by the time this runs.\n if (this.active) {\n this.emit(\"bulkpacket\", ...args);\n this.hooks.onBulkPacket(...args);\n }\n });\n }", "async prepareTransfer(prepareRequest, sourceFspId) {\n try {\n\n // retrieve our quote data\n const quote = await this._cache.get(`quote_${prepareRequest.transferId}`);\n\n if(!quote) {\n // Check whether to allow transfers without a previous quote.\n if(!this._allowTransferWithoutQuote) {\n throw new Error(`Corresponding quote not found for transfer ${prepareRequest.transferId}`);\n }\n }\n\n // Calculate or retrieve fulfilment and condition\n let fulfilment = null;\n let condition = null;\n if(quote) {\n fulfilment = quote.fulfilment;\n condition = quote.mojaloopResponse.condition;\n }\n else {\n fulfilment = this._ilp.calculateFulfil(prepareRequest.ilpPacket);\n condition = this._ilp.calculateConditionFromFulfil(fulfilment);\n }\n\n // check incoming ILP matches our persisted values\n if(this._checkIlp && (prepareRequest.condition !== condition)) {\n throw new Error(`ILP condition in transfer prepare for ${prepareRequest.transferId} does not match quote`);\n }\n\n\n if (quote && this._rejectTransfersOnExpiredQuotes) {\n const now = new Date().toISOString();\n const expiration = quote.mojaloopResponse.expiration;\n if (now > expiration) {\n const error = Errors.MojaloopApiErrorObjectFromCode(Errors.MojaloopApiErrorCodes.QUOTE_EXPIRED);\n this._logger.error(`Error in prepareTransfer: quote expired for transfer ${prepareRequest.transferId}, system time=${now} > quote time=${expiration}`);\n return this._mojaloopRequests.putTransfersError(prepareRequest.transferId, error, sourceFspId);\n }\n }\n\n // project the incoming transfer prepare into an internal transfer request\n const internalForm = shared.mojaloopPrepareToInternalTransfer(prepareRequest, quote);\n\n // make a call to the backend to inform it of the incoming transfer\n const response = await this._backendRequests.postTransfers(internalForm);\n\n if(!response) {\n // make an error callback to the source fsp\n return 'No response from backend';\n }\n\n this._logger.log(`Transfer accepted by backend returning homeTransactionId: ${response.homeTransactionId} for mojaloop transferId: ${prepareRequest.transferId}`);\n\n // create a mojaloop transfer fulfil response\n const mojaloopResponse = {\n completedTimestamp: new Date(),\n transferState: 'COMMITTED',\n fulfilment: fulfilment,\n ...response.extensionList && {\n extensionList: {\n extension: response.extensionList,\n },\n },\n };\n\n // make a callback to the source fsp with the transfer fulfilment\n return this._mojaloopRequests.putTransfers(prepareRequest.transferId, mojaloopResponse,\n sourceFspId);\n }\n catch(err) {\n this._logger.push({ err }).log('Error in prepareTransfer');\n const mojaloopError = await this._handleError(err);\n this._logger.push({ mojaloopError }).log(`Sending error response to ${sourceFspId}`);\n return await this._mojaloopRequests.putTransfersError(prepareRequest.transferId,\n mojaloopError, sourceFspId);\n }\n }", "async prepareTransfer(prepareRequest, sourceFspId) {\n try {\n\n // retrieve our quote data\n const quote = await this._cache.get(`quote_${prepareRequest.transferId}`);\n\n if(!quote) {\n // Check whether to allow transfers without a previous quote.\n if(!this._allowTransferWithoutQuote) {\n throw new Error(`Corresponding quote not found for transfer ${prepareRequest.transferId}`);\n }\n }\n\n // Calculate or retrieve fulfilment and condition\n let fulfilment = null;\n let condition = null;\n if(quote) {\n fulfilment = quote.fulfilment;\n condition = quote.mojaloopResponse.condition;\n }\n else {\n fulfilment = this._ilp.calculateFulfil(prepareRequest.ilpPacket);\n condition = this._ilp.calculateConditionFromFulfil(fulfilment);\n }\n\n // check incoming ILP matches our persisted values\n if(this._checkIlp && (prepareRequest.condition !== condition)) {\n throw new Error(`ILP condition in transfer prepare for ${prepareRequest.transferId} does not match quote`);\n }\n\n\n if (quote && this._rejectTransfersOnExpiredQuotes) {\n const now = new Date().toISOString();\n const expiration = quote.mojaloopResponse.expiration;\n if (now > expiration) {\n const error = Errors.MojaloopApiErrorObjectFromCode(Errors.MojaloopApiErrorCodes.QUOTE_EXPIRED);\n this._logger.error(`Error in prepareTransfer: quote expired for transfer ${prepareRequest.transferId}, system time=${now} > quote time=${expiration}`);\n return this._mojaloopRequests.putTransfersError(prepareRequest.transferId, error, sourceFspId);\n }\n }\n\n // project the incoming transfer prepare into an internal transfer request\n const internalForm = shared.mojaloopPrepareToInternalTransfer(prepareRequest, quote);\n\n // make a call to the backend to inform it of the incoming transfer\n const response = await this._backendRequests.postTransfers(internalForm);\n\n if(!response) {\n // make an error callback to the source fsp\n return 'No response from backend';\n }\n\n this._logger.log(`Transfer accepted by backend returning homeTransactionId: ${response.homeTransactionId} for mojaloop transferId: ${prepareRequest.transferId}`);\n\n // create a mojaloop transfer fulfil response\n const mojaloopResponse = {\n completedTimestamp: new Date(),\n transferState: this._reserveNotification ? 'RESERVED' : 'COMMITTED',\n fulfilment: fulfilment,\n ...response.extensionList && {\n extensionList: {\n extension: response.extensionList,\n },\n },\n };\n\n // make a callback to the source fsp with the transfer fulfilment\n return this._mojaloopRequests.putTransfers(prepareRequest.transferId, mojaloopResponse,\n sourceFspId);\n }\n catch(err) {\n this._logger.push({ err }).log('Error in prepareTransfer');\n const mojaloopError = await this._handleError(err);\n this._logger.push({ mojaloopError }).log(`Sending error response to ${sourceFspId}`);\n return await this._mojaloopRequests.putTransfersError(prepareRequest.transferId,\n mojaloopError, sourceFspId);\n }\n }", "async function _submit_bulk_in_transfer(ep, len, buffer, transfer) {\n \n const LIBUSB_TRANSFER_COMPLETED = 0;\n const LIBUSB_TRANSFER_CANCELLED = 3;\n const LIBUSB_SUCCESS = 0;\n\n if(active_device === undefined) {\n console.warn(\"_submit_bulk_in_transfer called when active_device === undefined\");\n return false;\n }\n\n // perform the transfer\n let result;\n try {\n result = await active_device.transferIn(ep, len);\n } catch (error) {\n console.warn(\"transfer error in _submit_bulk_in_transfer\");\n return false;\n } \n\n // write the received data to the heap buffer\n let data = new Uint8Array(result.data.buffer);\n writeArrayToMemory(data, buffer);\n\n // set the transfer status to completed\n setValue(transfer+20, data.length, \"i32\"); // actualLength\n if(getValue(transfer+12, \"i32\") != LIBUSB_TRANSFER_CANCELLED) { // status\n setValue(transfer+12, LIBUSB_TRANSFER_COMPLETED, \"i32\"); // status\n }\n\n return LIBUSB_SUCCESS;\n}", "function getValidateResCB(reqId, shouldReadRes, expectedRes, successCounter) {\n return function validateResCB(res) {\n var key;\n\n if (typeof shouldReadRes !== \"boolean\" && typeof shouldReadRes !== \"string\") {\n shouldReadRes = JSON.stringify(shouldReadRes);\n }\n\n\n if (res.statusCode !== expectedRes.status) {\n console.log(reqId + \" FAILED: bad status: \" + res.statusCode + \" received\");\n return;\n }\n if (res.httpVersion !== expectedRes.version) {\n console.log(reqId + \" FAILED: bad version\");\n return;\n }\n\n for (key in expectedRes.extraHeaders) {\n if (expectedRes.extraHeaders.hasOwnProperty(key)) {\n if (JSON.stringify(res.headers[key]) !== JSON.stringify(expectedRes.extraHeaders[key])) {\n console.log(reqId + \" FAILED: bad header: \" + key);\n console.log(\"received \" + res.headers[key]);\n return;\n }\n }\n }\n\n if (res.headers[\"set-cookie\"] !== undefined) {\n LAST_COOKIE = res.headers[\"set-cookie\"].toString().split(\";\")[0];\n }\n\n if (typeof shouldReadRes === \"string\") {\n if (res.headers[\"content-length\"] !== shouldReadRes.length.toString()) {\n console.log(reqId + \" FAILED: bad content-length. \");\n console.log(\"received: \" + res.headers[\"content-length\"] + \" expected: \" +\n shouldReadRes.length);\n return;\n }\n }\n\n if (successCounter !== undefined) {\n successCounter.counter++;\n }\n\n console.log(reqId + \" PASSED\");\n\n if ((typeof shouldReadRes !== \"boolean\") || (shouldReadRes !== false)) {\n res.on(\"data\", function(chunk){\n var body = chunk.toString();\n if (typeof shouldReadRes === \"string\") {\n if (body !== shouldReadRes) {\n console.log(reqId + \" FAILED in validating chunk. read \" + body +\n \" instead of \" + shouldReadRes);\n }\n }\n });\n }\n }\n}", "function checkTransferResult( err, data ) {\n if( err ) {\n reportError( err, data.statusCode );\n return;\n }\n Y.log( 'patient transfer was successful, result:' + JSON.stringify( data ), 'debug', NAME );\n allDone( null, data.statusCode );\n }", "handleSendResult(err, bytes) {\n if (err) {\n debug('error', err);\n this.emit('error', err);\n }\n else {\n debug('sent', bytes);\n }\n }", "process(filter, callback) {\n this.setDataSource(filter);\n this.setDataExtracted(filter);\n\n this.dbFind(filter, function(err, datas) {\n if (err) {\n return callback(err);\n }\n\n async.eachLimit(datas, 1, (data, callback) => {\n this.postProcess(data, (err, datas) => {\n async.eachLimit(datas, 1, (data, callback) => {\n this.dbUpdate(data, {}, callback);\n }, callback);\n });\n }, callback);\n });\n }", "validateWhenGettingStreamed() {\n if (this.file.size > this.bytesLimit) {\n this.validated = true;\n this.reportError();\n }\n }", "_prepare() {\n this._calledGetCount = 0;\n this._commandBuffer = [];\n this._pendingResult = undefined;\n }", "function readyBulkUpload() {\n const bulkDropzone = new Dropzone(\"#bulkdropzone\", {\n url: \"/admin/bulk_upload\",\n autoProcessQueue: false,\n autoQueue: true,\n uploadMultiple: true,\n parallelUploads: 2,\n maxFiles: 100,\n ignoreHiddenFiles: true,\n // acceptedFiles: '*.jpg',\n previewsContainer: '#dz-preview-container',\n \n init: function() {\n var myDropzone = this;\n console.log('initialized bulk dropzone')\n var form = document.getElementById('bulkdropzone');\n form.addEventListener('submit', function(e) {\n e.preventDefault();\n myDropzone.processQueue();\n });\n \n this.on(\"addedfile\", file => {\n console.log(`File added: ${file.name}`);\n });\n this.on('sending', function(file, xhr, formData) {\n console.log('hey')\n });\n \n \n this.on(\"sendingmultiple\", function(file, xhr, formData) {\n console.log('send multiple')\n formData.append(\"site_id\", $('#myDropzoneForm_site_id').val());\n \n var reliable = $('#tpl').find('#reliable').is(':checked')\n var date = $('#tpl').find('#record_taken').val()\n var submittedAt = $('#tpl').find('#submitted_at').val()\n var typeName = $('#tpl').find('#type_name').val()\n \n var participantId = $('#tpl').find('#participant_id').val()\n var comment = $('#tpl').find('#comment').val()\n \n formData.append('reliable', reliable);\n formData.append('record_taken', date);\n formData.append('submitted_at', submittedAt);\n formData.append('type_name', typeName);\n formData.append('comment', comment);\n formData.append('participant_id', participantId);\n });\n \n this.on(\"successmultiple\", function(data,response) {\n $('#tpl').toggleClass('hidden')\n $('#response').toggleClass('hidden')\n \n var textnode = document.createTextNode(response);\n var div = document.getElementById('response')\n div.innerHTML += response.toString()\n });\n }\n });\n}", "function handleConverting(recovery_id,conversion_id) {\n\n console.log('Handling CONVERTING recovery task ' + recovery_id);\n\n function connectionCallback(err) {\n\n if (err) {\n console.log('Recovery management failed for task ' + recovery_id + \n ', Unable to connect to the database');\n \n db.disconnect();\n return;\n }\n \n // get progress of conversion task\n var ec2 = new AWS.EC2();\n \n var params = {\n ConversionTaskIds: [\n conversion_id\n ]\n };\n \n function describeConversionTasksCallback(err,data) {\n \n if (err) {\n console.log('DescribeConversionTasks error: ' + err,err.stack);\n db.disconnect();\n return;\n }\n \n var total_size = data.ConversionTasks[0].ImportInstance.Volumes[0].Image.Size;\n var conversion_state = data.ConversionTasks[0].State;\n\n if (conversion_state == 'completed') {\n \n // volume converted, move to next state\n var state_progress = 100; \n }\n else {\n \n // check conversion progress\n var status_message = data.ConversionTasks[0].StatusMessage;\n \n if (status_message == 'Pending') {\n \n // converting import into AMI volume, check number of bytes converted\n var bytes_converted = data.ConversionTasks[0].ImportInstance.Volumes[0].BytesConverted;\n var state_progress = Math.floor((bytes_converted / total_size) * 50); // 50% of conversion process\n }\n else {\n \n // conversion into AMI volume complete, check conversion percentage\n var percentage_converted = data.ConversionTasks[0].StatusMessage.split(\"Progress: \")[1];\n percentage_converted = Number(percentage_converted.split('%')[0]);\n var state_progress = Math.floor(percentage_converted / 2) + 50; \n }\n } // if (conversion_state)\n \n // query to run if conversion is not yet finished\n var qry = \"UPDATE reclodb.recovery SET state_progress = ? WHERE recovery_id = ?\";\n var params = [state_progress,recovery_id];\n \n if (state_progress == 100) {\n \n // import completed, move on to converted\n var recovery_state = 'converted';\n var total_progress = progress.converted;\n var new_state_progress = 0;\n \n qry = \"UPDATE reclodb.recovery SET state_progress = ?, recovery_state = ?, \" +\n \"total_progress = ? WHERE recovery_id = ?\";\n params = [new_state_progress, recovery_state, total_progress, recovery_id];\n }\n\n function updateImportProgressCallback(err,results) {\n \n if (err) {\n console.log('Recovery management failed for task ' + recovery_id + \n ', there was an error connecting to the database');\n \n db.disconnect();\n return;\n }\n \n console.log('Updated conversion progress for recovery ' + recovery_id);\n console.log('Total progress: ' + state_progress);\n \n db.disconnect(); \n \n } // updateImportProgressCallback\n db.query(qry,params,updateImportProgressCallback);\n \n } // describeConversionTasksCallback \n ec2.describeConversionTasks(params,describeConversionTasksCallback);\n }\n var db = new DBConnection();\n db.connect(connectionCallback.bind(db));\n}", "function passControl() {\n\n\t\t\thasControl = false;\n\n\t\t\tlog('-------- No more params allowed. --------');\n\t\t\tlog(' * NEXT :: Passing control to app...');\n\t\t\tconsole.timeEnd('streamingBodyParser waitTime');\n\n\t\t\t// Cancel max-wait timer \n\t\t\t// (since we could have gotten here via other means)\n\t\t\tclearTimeout(maxWaitTimer);\n\n\t\t\t// If request stream ends, whether it's because the request was canceled\n\t\t\t// the files finished uploading, or the response was sent, buffering stops,\n\t\t\t// since the UploadStream stops sending data\n\t\t\t\n\t\t\t// So we're good!\n\t\t\tnext();\n\t\t}", "function handleImporting(recovery_id,conversion_id) {\n\n console.log('Handling IMPORTING recovery task ' + recovery_id);\n\n if (conversion_id == 'tbd') {\n console.log('Import initializing. Cannot query progress yet');\n return;\n }\n\n // importing initialized, ready to monitor progress\n function connectionCallback(err) {\n\n if (err) {\n console.log('Recovery management failed for task ' + recovery_id + \n ', Unable to connect to the database');\n \n db.disconnect();\n return;\n }\n \n // get progress of import task\n var ec2 = new AWS.EC2();\n \n var params = {\n ConversionTaskIds: [\n conversion_id\n ]\n };\n \n function describeConversionTasksCallback(err,data) {\n \n if (err) {\n console.log('DescribeConversionTasks error: ' + err,err.stack);\n db.disconnect();\n return;\n }\n \n // update database with conversion progress\n var total_size = data.ConversionTasks[0].ImportInstance.Volumes[0].Image.Size;\n var status = data.ConversionTasks[0].ImportInstance.Volumes[0].Status; // as string\n \n if (status == 'completed') {\n \n // should never be anything but 'active' while in this state, but just in case\n var state_progress = 100; \n }\n else { \n \n var status_message = data.ConversionTasks[0].ImportInstance.Volumes[0].StatusMessage;\n var bytes_imported = Number(status_message.split(\"Downloaded \")[1]); // convert to integer\n var state_progress = Math.ceil((bytes_imported / total_size) * 100);\n }\n\n // query to run if importing is not yet finished\n var qry = \"UPDATE reclodb.recovery SET state_progress = ? WHERE recovery_id = ?\";\n var params = [state_progress,recovery_id];\n \n if (state_progress == 100) {\n \n // import completed, move on to converting\n var recovery_state = 'converting';\n var total_progress = progress.imported;\n var new_state_progress = 0;\n \n qry = \"UPDATE reclodb.recovery SET state_progress = ?, recovery_state = ?, \" +\n \"total_progress = ? WHERE recovery_id = ?\";\n params = [new_state_progress, recovery_state, total_progress, recovery_id];\n }\n\n function updateImportProgressCallback(err,results) {\n \n if (err) {\n console.log('Recovery management failed for task ' + recovery_id + \n ', there was an error connecting to the database');\n \n db.disconnect();\n return;\n }\n \n console.log('Updated import progress for recovery ' + recovery_id);\n console.log('Total progress: ' + state_progress);\n \n db.disconnect(); \n \n } // updateImportProgressCallback\n db.query(qry,params,updateImportProgressCallback);\n \n } // describeConversionTasksCallback \n ec2.describeConversionTasks(params,describeConversionTasksCallback);\n }\n var db = new DBConnection();\n db.connect(connectionCallback.bind(db));\n}", "incomingTransfers(params) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.request(\"incoming_transfers\", Object.assign({}, params));\n });\n }", "function transferComplete() {\r\n\tdata = request.response.data;\r\n\tcategories = request.response.categories;\r\n\tconsole.log(\"Transfer complete\");\r\n\tinit();\r\n}", "isValidPrepare(prepare) {\n return ChainUtil.verifySignature(\n prepare.publicKey,\n prepare.signature,\n prepare.blockHash\n );\n }", "collectInsert (readyCallback) {\n var itemDetails = {};\n\n for (var itemName in this.request.body) {\n // Ignoring some request fields\n if (this._ignoredRequestFieldsMap && this._ignoredRequestFieldsMap[itemName] != null) {\n continue;\n }\n\n itemDetails[itemName] = this.request.body[itemName];\n }\n\n readyCallback(null, itemDetails);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function formats the Predicate input. Comments are inline
function formatPredicate() { var str = gAppState.checkValue("predicateID", "predicateID2"); if (regexp.test(str) && !isBlankNode(str)) { return '<' + str + '>'; // Case: input is a uri. Solution: quote it } else if (str.charAt(0) == "#") { return '<' + str + '>'; // Case: input is an unquoted relative uri. Solution: quote it } else if (str.charAt(0) == '<' && str.charAt(1) == '#' && str.charAt(str.length - 1) == '>') { return str; // Case: input is already a relative uri. Solution: return it as is } else if (str.includes(":") || str.includes("<#")) { return str; // Case: input is a curie. Solution: return it as is } else if (str.charAt(0) == "?") { return str; // checks if input is a variable for deletion } else { if (str.charAt(0) == '<' && str.charAt(str.length - 1) == '>') { var newStr = str.slice(1, -1); // Case: input is quoted uri. Solution: must be unquotted to be recognize as a uri by regexp return formatPredicate(newStr); } else { return ':' + str; // Case: input is not a uri or a blank node. Solution: make it a relative uri } } }
[ "function EBX_PredicateEditor() {\n}", "_encodePredicate(predicate) {\n return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate);\n }", "_encodePredicate(predicate) {\n return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate);\n }", "_encodePredicate(predicate) {\n return predicate.value === rdf$1.type ? 'a' : this._encodeIriOrBlank(predicate);\n }", "function Format(o) {\n return o.Subject\n ? `(${o.Subject.name}, ${o.Predicate.name}, ${o.Object.toString()})`\n : `(${o.Predicate.name}, ${o.Object.toString()})`;\n}", "function description(state) {\n if(typeof state === \"object\") return \"<br>\" + state.join(\"<br>\");\n var descr = \"\";\n for(var i = 0, h = state.length - 1; h >= 0; --h) {\n var hex = parseInt(state[h], 16);\n if(hex & 1) descr += \"<br>\" + root.predicates[i]; ++i;\n if(hex & 2) descr += \"<br>\" + root.predicates[i]; ++i;\n if(hex & 4) descr += \"<br>\" + root.predicates[i]; ++i;\n if(hex & 8) descr += \"<br>\" + root.predicates[i]; ++i;\n }\n return descr;\n}", "function predicateSentence(predicate, argList) {\n var sentence = new Sentence;\n sentence.type = \"primitive\";\n sentence.subtype = \"predicate\";\n sentence.predicate = predicate;\n\n var i;\n\n for (i=0; i < argList.length; i++)\n sentence.argList[i] = toTerm(argList[i]);\n\n if (sentence.predicate.relationStyle) {\n sentence.name = argList[0].longName + \" \" + sentence.predicate.name + \" \" + argList[1].longName;\n sentence.longName = \"(\" + sentence.name + \")\";\n } else if (sentence.predicate.arity == 0) {\n sentence.name = sentence.predicate.name;\n sentence.longName = sentence.name;\n } else {\n var str = sentence.predicate.name + \"(\";\n for (i = 0; i < sentence.predicate.arity; i++ )\n str += toTerm(argList[i]).name + \", \";\n str = str.substring(0, str.length - 2);\n sentence.name = str + \")\";\n sentence.longName = sentence.name;\n }\n\n sentence.name = sentence.name;\n return sentence;\n}", "getRelatedPredicate(quad) {\n return `<${quad.predicate.value}>`;\n }", "function PredicateItem(predicate) {\n\n this.key = predicate;\n this.title = '<small>' + predicate.split(\":\")[0] + ':</small>' + predicate.split(\":\")[1];\n this.folder = false;\n this.lazy = false;\n this.extraClasses = \"predicateItem\";\n}", "function getSqlPredicate(p) {\n if (\"==\" in p) return \"(\" + p[\"==\"][0] + \"='\" + p[\"==\"][1] + \"')\";\n if (\"AND\" in p)\n return (\n \"(\" +\n getSqlPredicate(p[\"AND\"][0]) +\n \" AND \" +\n getSqlPredicate(p[\"AND\"][1]) +\n \")\"\n );\n if (\"OR\" in p)\n return (\n \"(\" +\n getSqlPredicate(p[\"OR\"][0]) +\n \" OR \" +\n getSqlPredicate(p[\"OR\"][1]) +\n \")\"\n );\n return \"\";\n}", "function buildWhereClause(predicate){\n var clause='';\n var clauseArray=[];\n for(var key in predicate){\n clause=\" \"+key+\"='\"+predicate[key]+\"' \";\n clauseArray.push(clause);\n }\n return clauseArray.join('AND');\n }", "function augmentFilter(condition) {\n return _.map(_.compact([condition, $(\"#complex-filter textarea\").val()]), function(x) { return \"(\" + x + \")\"; }).join(\" and \");\n}", "enterPredicateExpression(ctx) {\n\t}", "function fieldNameAndPredicateToSql(fieldName, predicate) {\n var columnName = fieldNameToColumnName(fieldName);\n var filters = predicateToFilterObjects(predicate);\n var filterStatements = _.map(filters, function(f) {\n // If a literal value is found it probably needs the column\n // name somewhere besides the LHS so we provide it via\n // an underscore template\n if (f.sql_template) {\n return _.template(f.sql_template, { 'column': columnName });\n } else {\n // if the column is an hstore field and the value is a\n // datestring literal the hstore field must be converted\n // from text to date before comparsion\n if (columnName.indexOf('->') !== -1 &&\n f.value.indexOf('(DATE') === 0) {\n columnName = format(\n \"to_date(%s::text, '%s')\",\n columnName, utils.DATETIME_FORMATS.date);\n }\n return columnName + ' ' + f.matcher + ' ' + f.value;\n }\n });\n return '(' + filterStatements.join(' AND ') + ')' ;\n}", "emitPredicateTriples(itemScope, predicates, object, reverse) {\n if (!itemScope.blockEmission) {\n for (const predicate of predicates) {\n if (reverse) {\n // Literals can not exist in subject position, so they must be ignored.\n if (object.termType !== 'Literal') {\n this.emitTriple(object, predicate, itemScope.subject);\n }\n }\n else {\n this.emitTriple(itemScope.subject, predicate, object);\n }\n }\n }\n }", "conditionSummary(condition) {\n const property = _.find(this.$store.state.recipeProperties, {value: condition.property})\n if (!property) {\n return `!!! ERROR !!! Invalid property: ${condition.property}`\n }\n\n const operator = _.find(property.operators, {value: condition.operator})\n if (!operator) {\n return `!!! ERROR !!! Invalid condition operator: ${condition.operator}`\n }\n\n let fieldText = property.text\n let operatorText = operator.text\n let valueText = condition.friendlyValue || condition.value\n\n // Has a suffix?\n const suffix = this.$store.state.user.profile.units == \"imperial\" ? property.impSuffix || property.suffix : property.suffix\n if (suffix) {\n valueText += ` ${suffix}`\n }\n\n // Boolean do not need the \"is\" text.\n if (property.type == \"boolean\") {\n return `${fieldText}: ${valueText}`\n }\n\n return `${fieldText} ${operatorText} ${valueText}`\n }", "_readPredicate(token) {\n const type = token.type;\n switch (type) {\n case 'inverse':\n this._inversePredicate = true;\n case 'abbreviation':\n this._predicate = this.ABBREVIATIONS[token.value];\n break;\n case '.':\n case ']':\n case '}':\n // Expected predicate didn't come, must have been trailing semicolon\n if (this._predicate === null)\n return this._error(`Unexpected ${type}`, token);\n this._subject = null;\n return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);\n case ';':\n // Additional semicolons can be safely ignored\n return this._predicate !== null ? this._readPredicate :\n this._error('Expected predicate but got ;', token);\n case '[':\n if (this._n3Mode) {\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject,\n this._subject = this._blankNode(), null);\n return this._readBlankNodeHead;\n }\n case 'blank':\n if (!this._n3Mode)\n return this._error('Disallowed blank node as predicate', token);\n default:\n if ((this._predicate = this._readEntity(token)) === undefined)\n return;\n }\n // The next token must be an object\n return this._readObject;\n }", "_readPredicate(token) {\n const type = token.type;\n switch (type) {\n case 'inverse':\n this._inversePredicate = true;\n case 'abbreviation':\n this._predicate = this.ABBREVIATIONS[token.value];\n break;\n case '.':\n case ']':\n case '}':\n // Expected predicate didn't come, must have been trailing semicolon\n if (this._predicate === null) return this._error(`Unexpected ${type}`, token);\n this._subject = null;\n return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);\n case ';':\n // Additional semicolons can be safely ignored\n return this._predicate !== null ? this._readPredicate : this._error('Expected predicate but got ;', token);\n case '[':\n if (this._n3Mode) {\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._subject = this._blankNode(), null);\n return this._readBlankNodeHead;\n }\n case 'blank':\n if (!this._n3Mode) return this._error('Disallowed blank node as predicate', token);\n default:\n if ((this._predicate = this._readEntity(token)) === undefined) return;\n }\n // The next token must be an object\n return this._readObject;\n }", "function sortSalaryCaret(predicate) {\n return '<i class=\"fa fa-fw\" ng-class=\"{\\'' + amntIcons.down + '\\': predicate===\\'salaryMaxInt\\', \\''\n + amntIcons.up + '\\': predicate===\\'salaryMinInt\\'}\"></i>';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds the implied classes (Object, IO, Integer, etc.) to our program node's class list
function addBuiltinObjects(programNode) { // Object class var objectClass = new CoolToJS.ClassNode('Object'); var abortMethodNode = new CoolToJS.MethodNode(); abortMethodNode.methodName = 'abort'; abortMethodNode.returnTypeName = 'Object'; abortMethodNode.parent = objectClass; objectClass.children.push(abortMethodNode); var typeNameMethodNode = new CoolToJS.MethodNode(); typeNameMethodNode.methodName = 'type_name'; typeNameMethodNode.returnTypeName = 'String'; typeNameMethodNode.parent = objectClass; objectClass.children.push(typeNameMethodNode); var copyMethodNode = new CoolToJS.MethodNode(); copyMethodNode.methodName = 'copy'; copyMethodNode.returnTypeName = 'SELF_TYPE'; copyMethodNode.parent = objectClass; objectClass.children.push(copyMethodNode); programNode.children.push(objectClass); // IO Class var ioClass = new CoolToJS.ClassNode('IO'); var outStringMethodNode = new CoolToJS.MethodNode(); outStringMethodNode.methodName = 'out_string'; outStringMethodNode.returnTypeName = 'SELF_TYPE'; outStringMethodNode.parameters.push({ parameterName: 'x', parameterTypeName: 'String' }); outStringMethodNode.parent = ioClass; ioClass.children.push(outStringMethodNode); var outIntMethodNode = new CoolToJS.MethodNode(); outIntMethodNode.methodName = 'out_int'; outIntMethodNode.returnTypeName = 'SELF_TYPE'; outIntMethodNode.parameters.push({ parameterName: 'x', parameterTypeName: 'Int' }); outIntMethodNode.parent = ioClass; ioClass.children.push(outIntMethodNode); var inStringMethodNode = new CoolToJS.MethodNode(); inStringMethodNode.methodName = 'in_string'; inStringMethodNode.returnTypeName = 'String'; inStringMethodNode.isAsync = true; inStringMethodNode.isInStringOrInInt = true; inStringMethodNode.parent = ioClass; ioClass.children.push(inStringMethodNode); var inIntMethodNode = new CoolToJS.MethodNode(); inIntMethodNode.methodName = 'in_int'; inIntMethodNode.returnTypeName = 'Int'; inIntMethodNode.isAsync = true; inIntMethodNode.isInStringOrInInt = true; inIntMethodNode.parent = ioClass; ioClass.children.push(inIntMethodNode); programNode.children.push(ioClass); // Int var intClass = new CoolToJS.ClassNode('Int'); programNode.children.push(intClass); // String var stringClass = new CoolToJS.ClassNode('String'); var lengthMethodNode = new CoolToJS.MethodNode(); lengthMethodNode.methodName = 'length'; lengthMethodNode.returnTypeName = 'Int'; lengthMethodNode.parent = stringClass; stringClass.children.push(lengthMethodNode); var concatMethodNode = new CoolToJS.MethodNode(); concatMethodNode.methodName = 'concat'; concatMethodNode.returnTypeName = 'String'; concatMethodNode.parameters.push({ parameterName: 's', parameterTypeName: 'String' }); concatMethodNode.parent = stringClass; stringClass.children.push(concatMethodNode); var substrMethodNode = new CoolToJS.MethodNode(); substrMethodNode.methodName = 'substr'; substrMethodNode.returnTypeName = 'String'; substrMethodNode.parameters.push({ parameterName: 'i', parameterTypeName: 'Int' }); substrMethodNode.parameters.push({ parameterName: 'l', parameterTypeName: 'Int' }); stringClass.parent = stringClass; stringClass.children.push(substrMethodNode); programNode.children.push(stringClass); // Bool var boolClass = new CoolToJS.ClassNode('Bool'); programNode.children.push(boolClass); }
[ "static register(cls) {\n this.NodeTypes.push(cls);\n }", "function add_classes(line, obj) {\n\t\tvar temp;\n\t\tvar classes = [];\n\t\t\n\t\tif ((temp = obj.object)) {\n\t\t if ((temp = temp.entstat)) {\n\t\t\tif (temp.vlan_tag_i_ds && Array.isArray(temp.vlan_tag_i_ds))\n\t\t\t classes = temp.vlan_tag_i_ds.slice();\n\t\t\tif (temp.port_vlan_id)\n\t\t\t classes.unshift(temp.port_vlan_id);\n\t\t }\n\t\t}\n\t\t/* We could fetch the existing classes */\n\t\tline.addClass(classes.join(' '));\n\t\taddTitle(line, classes.join(' '));\n\t }", "static registerClass(cls) {\n GraphTypes.push(cls);\n GraphMap[cls.graphdef().typeName] = cls;\n }", "function ClassManager() {}", "function classes() {\n\t\tvar clss = Array.prototype.slice.call(arguments);\n\t\tMaps.fillKeys(ephemeraMap.classMap, clss, true);\n\t\tcheckCommonSubstr(clss);\n\t\tPubSub.pub('aloha.ephemera.classes', {\n\t\t\tephemera: ephemeraMap,\n\t\t\tnewClasses: clss\n\t\t});\n\t}", "function exAddClass(node, name) {\n var list = node.classList;\n var parts = name.split(/\\s+/);\n for (var i = 0, n = parts.length; i < n; ++i) {\n if (parts[i])\n list.add(parts[i]);\n }\n}", "function writeNodeClasses(node) {\n for (var i in node.classList) { // classes\n addSelectorIfNodeMatchesRule(node, node.classList[i]);\n }\n addSelectorIfNodeMatchesRule(node, node.id); // id\n addSelectorIfNodeMatchesRule(node, node.localName); // tag name\n }", "function _applyClasses(e) {\n var bone = this,\n cls = _getCssClasses(bone);\n\n if(this.options.inheritClasses) {\n while(!!bone.type) {\n cls = cls.concat(_getCssClasses(bone));\n bone = Object.getPrototypeOf(bone);\n }\n }\n cls.sort();\n this.cls = _.uniq(cls);\n }", "function classes() {\n var clss = Array.prototype.slice.call(arguments);\n Maps.fillKeys(ephemeraMap.classMap, clss, true);\n checkCommonSubstr(clss);\n PubSub.pub('aloha.ephemera.classes', {\n ephemera:ephemeraMap,\n newClasses:clss\n });\n }", "function showClasses() {\n\tfor (var i = 0; i < OO.CT.length; i++) {\n\t\tOO.CT[i]._Class.toString();\n\t}\n}", "function _turboClasses()\n {\n var myArgs = Array.prototype.slice.call(arguments);\n _turboClassesAndAttributes(myArgs[0]);\n }", "_setupClasses() {\n const customClasses = getWithDefault(this, 'customClasses', {});\n var newClasses = smartExtend(customClasses, defaultCssClasses);\n set(this, 'classes', O.create(newClasses));\n }", "function DeclareClass(node, print) {\n this.push(\"declare class \");\n this._interfaceish(node, print);\n}", "addElementClasses() {\n\t\tvar classesToAdd = this.constructor.ELEMENT_CLASSES_MERGED;\n\t\tif (this.elementClasses) {\n\t\t\tclassesToAdd = classesToAdd + ' ' + this.elementClasses;\n\t\t}\n\t\tdom.addClasses(this.element, classesToAdd);\n\t}", "addClass(args) {\n\t\tlet className = args.className;\n\n\t\t// class\n\t\tthis.parentClassName = className;\n\t\tthis.classParent = new OntClass({\n\t\t\t\"className\": this.prefix + className + EnapsoLanguageOntology.SFX_CLASS,\n\t\t\t\"superClassName\": this.prefix + 'Class'\n\t\t});\n\t\t// give the class a name\n\t\tlet classNameRestriction = new OntValueRestriction({\n\t\t\tproperty: this.prefix + 'name',\n\t\t\tvalue: '\"' + this.parentClassName + '\"'\n\t\t});\n\t\tthis.classParent.addRestriction({ restriction: classNameRestriction });\n\n\t\t// constructor parent\n\t\tthis.constructorParent = new OntClass({\n\t\t\t\"className\": this.prefix + className + EnapsoLanguageOntology.SFX_CONSTRUCTOR,\n\t\t\t\"superClassName\": this.prefix + 'Constructor'\n\t\t});\n\t\t// add the methods restriction to the class\n\t\tlet hasConstructorsRestriction = new OntOnlyRestriction({\n\t\t\t\"property\": this.prefix + \"hasConstructors\",\n\t\t\t\"class\": this.constructorParent.getClassName(),\n\t\t});\n\t\tthis.classParent.addRestriction({ restriction: hasConstructorsRestriction });\n\n\t\t// method parent\n\t\tthis.methodParent = new OntClass({\n\t\t\t\"className\": this.prefix + className + EnapsoLanguageOntology.SFX_METHOD,\n\t\t\t\"superClassName\": this.prefix + 'Method'\n\t\t});\n\t\t// add the methods restriction to the class\n\t\tlet hasMethodsRestriction = new OntOnlyRestriction({\n\t\t\t\"property\": this.prefix + \"hasMethods\",\n\t\t\t\"class\": this.methodParent.getClassName(),\n\t\t});\n\t\tthis.classParent.addRestriction({ restriction: hasMethodsRestriction });\n\n\t\t// property parent\n\t\tthis.propertyParent = new OntClass({\n\t\t\t\"className\": this.prefix + className + EnapsoLanguageOntology.SFX_PROPERTY,\n\t\t\t\"superClassName\": this.prefix + 'Property'\n\t\t});\n\t\t// add the properties restriction to the class\n\t\tlet hasPropertiesRestriction = new OntOnlyRestriction({\n\t\t\t\"property\": this.prefix + \"hasProperties\",\n\t\t\t\"class\": this.propertyParent.getClassName(),\n\t\t});\n\t\tthis.classParent.addRestriction({ restriction: hasPropertiesRestriction });\n\n\t\tthis.instanceParent = new OntClass({\n\t\t\t\"className\": this.prefix + className + EnapsoLanguageOntology.SFX_INSTANCE,\n\t\t\t\"superClassName\": this.prefix + 'Instance'\n\t\t});\n\n\t\t// add a argument parent for this class\n\t\tthis.parentArgumentName = className + EnapsoLanguageOntology.SFX_ARGUMENT;\n\t\tthis.argumentParent = new OntClass({\n\t\t\t\"className\": this.prefix + this.parentArgumentName,\n\t\t\t\"superClassName\": this.prefix + 'Argument'\n\t\t});\n\n\t\t// add a result parent for this class\n\t\tthis.parentResultName = className + EnapsoLanguageOntology.SFX_RESULT;\n\t\tthis.resultParent = new OntClass({\n\t\t\t\"className\": this.prefix + this.parentResultName,\n\t\t\t\"superClassName\": this.prefix + 'Result'\n\t\t});\n\n\t\t// add a comment to the class if given\n\t\tif (args.comment) {\n\t\t\tthis.methodParent.addAnnotation({\n\t\t\t\tannotation: new OntComment({\n\t\t\t\t\tentity: this.methodParent.getClassName(),\n\t\t\t\t\tcomment: args.comment\n\t\t\t\t})\n\t\t\t});\n\t\t}\n\n\t\tthis.tripleStore.addTriples({ triples: this.classParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.constructorParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.methodParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.propertyParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.instanceParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.argumentParent.getTriples() });\n\t\tthis.tripleStore.addTriples({ triples: this.resultParent.getTriples() });\n\t}", "function visit(node) {\n // Only consider exported nodes\n if (!isNodeExported(node)) {\n return;\n }\n if (node.kind === ts.SyntaxKind.ClassDeclaration) {\n var classNode = node;\n var symbol = checker.getSymbolAtLocation(classNode.name);\n var typeArguments = nodeUtils_1.navigate(classNode, ts.SyntaxKind.HeritageClause, ts.SyntaxKind.ExpressionWithTypeArguments);\n var list = nodeUtils_1.getFlatChildren(typeArguments)\n .filter(function (i) { return i.kind === ts.SyntaxKind.Identifier; })\n .map(function (i) { return i.text; });\n nodeUtils_1.getFlatChildren(node).map(function (x) {\n if (x.kind === ts.SyntaxKind.StaticKeyword) {\n var defaultPropsNode = x.parent;\n if (defaultPropsNode.name.text === 'defaultProps') {\n var members_1 = checker.getTypeAtLocation(defaultPropsNode).members;\n Object.keys(members_1).map(function (name) {\n defaultProps[name] = members_1[name].valueDeclaration.getText().split(':').slice(1).join(':').trim();\n });\n }\n }\n });\n classes.push({\n name: symbol.name,\n comment: ts.displayPartsToString(symbol.getDocumentationComment()),\n extends: list.length > 0 ? list[0] : null,\n propInterface: list.length > 1 ? list[1] : null,\n });\n }\n if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {\n var interfaceDeclaration = node;\n if (interfaceDeclaration.parent === sourceFile) {\n var symbol = checker.getSymbolAtLocation(interfaceDeclaration.name);\n var type = checker.getTypeAtLocation(interfaceDeclaration.name);\n var members = type.getProperties().map(function (i) {\n var symbol = checker.getSymbolAtLocation(i.valueDeclaration.name);\n var prop = i.valueDeclaration;\n var typeInfo = getType(prop, i.getName());\n var name = i.getName();\n var typeAtLocation = prop.type ? checker.getTypeAtLocation(prop.type) : {};\n return {\n name: name,\n default: null,\n text: i.valueDeclaration.getText(),\n array: typeAtLocation.target && typeAtLocation.symbol.name === 'Array',\n type: typeInfo.type,\n values: typeInfo.values,\n isRequired: !prop.questionToken,\n comment: ts.displayPartsToString(symbol.getDocumentationComment()).trim(),\n };\n });\n var interfaceDoc = {\n name: symbol.getName(),\n comment: ts.displayPartsToString(symbol.getDocumentationComment()).trim(),\n members: members,\n };\n interfaces.push(interfaceDoc);\n }\n }\n else if (node.kind === ts.SyntaxKind.ModuleDeclaration) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n }", "function DeclareClass(node, print) {\n\t this.push(\"declare class \");\n\t this._interfaceish(node, print);\n\t}", "add(className) {\n if (this.includes(className)) {\n return Class.create(this.list);\n } else {\n return Class.create([...this.list, className]);\n }\n }", "function uuklassadd(node, // @param Node:\r\n classNames) { // @param String: \"class1 class2 ...\"\r\n // @return Node:\r\n node.className += \" \" + classNames; // [OPTIMIZED] // uutriminner()\r\n return node;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide the options list
hideOptions () { this.optionsWrapper.hide(); this.optionsWrapper.style.left = ""; }
[ "function hideOptionsList() {\n $options.removeClass('show');\n }", "function hideOptionList() {\n optionList.hide();\n select.removeClass('option-list-open');\n }", "function hideOptions() {\n $('.meeting-options, .local-user-name, .remote-user-name, .meeting-info, .kick').hide();\n }", "function HideOptions() {\n\t\t\t$('.hide-filters').slideUp(\"fast\");\n\t\t}", "async hideMoreOptions() {\n this.showMoreOption = false;\n }", "function hideForms(){\n [].forEach.call(allOptions, function (form) {\n if(form.id !== 'base-options'){\n form.style.display = 'none';\n }\n });\n }", "function hideOption(){\n\tdocument.getElementById(\"options\").style.visibility = \"hidden\";\n\t\n\t// uncheck and disable\n\tfor (var i = 0; i < document.forms[0].chkOption.length; i++){\n\t\tdocument.forms[0].chkOption[i].checked = false;\n\t\tdocument.forms[0].chkOption[i].disabled = true;\n\t}\n\t\n\torderSummary();\n}", "function hideKeyingOptions() {\n\t\tdebug('hiding keying options...');\n\n\t\t$keyingOption.find('option').each(function (i, el) {\n\t\t\tvar option = $(el).text();\n\n\t\t\tif (option !== keyedAlikeText) {\n\t\t\t\tdebug('removing option: ' + option);\n\t\t\t\t$(el).remove();\n\t\t\t}\n\t\t});\n\t}", "function MLSuperCombo$hideOptions() {\n this._hidden = true;\n this.el.classList.remove(COMBO_OPEN);\n this._comboList.dom.toggle(false);\n}", "hideFilterSelectOptions(){\n\n\t\t$('ul'+this.styles.filters_list+' li').each(function(){\n\n\t\t\tif($(this).data('type')!='text'){\n\t\t\t\t$(this).hide();\n\t\t\t}\t\n\n\t\t});\n\t}", "function hideOptions(widgetKey){\n\tif($(widgetKey+'_config')) $(widgetKey+'_config').setStyle({display: 'none'});\n\tif($(widgetKey+'_refresh')) $(widgetKey+'_refresh').setStyle({display: 'none'});\n\tif($(widgetKey+'_delete')) $(widgetKey+'_delete').setStyle({display: 'none'});\n}", "function hideListing(listName){\n\tvar list = listName.options;\t\n\tlist.selectedIndex = 0;\n\tfor(var i = 1; i < list.length; i++){ \n\t\tlist[i].hide();\n\t\tlist[i].disabled = true;\n\t}\n}", "function hideOptions() {\n\t\t\tif(elem.openedSelect){\n\t\t\t\t$('.' + settings.optionsClass).each(function(){\n\t\t\t\t\t$(this)\n\t\t\t\t\t\t.removeClass(settings.optionsClass)\n\t\t\t\t\t\t.addClass(settings.optionsHiddenClass);\n\t\t\t\t});\n\t\t\t\t$('.' + settings.selectActiveClass).each(function(){\n\t\t\t\t\t$(this).removeClass(settings.selectActiveClass);\n\t\t\t\t});\n\t\t\t\telem.openedSelect = false;\n\t\t\t}\n\t\t}", "function hideForAnswerScreen() {\n $(\".choices\").attr(\"style\", \"display: none\");\n }", "function hideOptions(event) {\n options.style.display = \"none\";\n optionsTrigger.style.display = \"block\";\n if (event) event.stopPropagation();\n}", "function wpi_hide_deposit_option() {\r\n jQuery('.wpi_hide_deposit_option').hide();\r\n }", "static hideAll() {\n super._hideButtons('choiceButtons');\n }", "function hideFilterMenuOption() {\n var vizContainer = this.parent,\n titleBar = vizContainer && vizContainer.titleBar,\n toolbarCfg = titleBar && titleBar.getMenuConfig();\n\n // Is there title bar?\n if (!toolbarCfg) {\n return;\n }\n\n // Filter out \"Use as filter\" option.\n toolbarCfg.menus = $ARR.filter(toolbarCfg.menus, function (item) {\n return item.cls !== 'uaf';\n });\n }", "function hideSwitcher() {\n $(Config.LIST_SWITCHER).hide();\n $(Config.LIST_INPUT).val('');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a file input to the upload form.
function addFile() { var name = "file-" + maxID++; var input = $('<input type="file">') .attr('name', name) .attr('id', name); var close = $('<a>') .addClass('close') .attr('href', 'javascript: removeFile("' + name + '")') .html('&times;'); var status = $('<span>') .addClass('file-status'); var inputDiv = $('<div>') .addClass('file-item') .append(input) .append(status) .append(close); console.log("Adding file input", input); $('#file-list').append(inputDiv); // Enable the upload button $('#submit-button').removeAttr('disabled'); }
[ "function uploadFile() {\r\n $(this).fileupload('add', {\r\n fileInput: $(this)\r\n });\r\n }", "function addFileInput($me) {\n var $files = $(\"input[type='file']\", \"#files_upload\");\n if ($files.length == 10) { return; }\n if(window.FormData !== undefined)\n {\n \t$($me).removeAttr(\"onchange\");\n }\n else\n {\n $($me).removeAttr(\"onchange\");\n var $newFile = $(\"<input type='file'>\").attr({\n \"name\": \"attach[]\",\n \"size\": 30,\n \"onchange\": \"addFileInput(this)\"\n });\n $(\"#files_upload\").append($newFile);\n }\n}", "function fileInputHandler(input) {\n if(input.files && input.files[0]) {\n document.getElementById(\"upload-form\").submit(); \n }\n}", "appendFileInput(filename){\n\n let fileInput = document.createElement(\"INPUT\");\n fileInput.setAttribute(\"type\", \"file\");\n fileInput.setAttribute(\"name\", \"attachments__c[]\");\n fileInput.setAttribute(\"id\", \"attachments__c[]\");\n fileInput.setAttribute(\"multiple\", true);\n fileInput.classList.add(\"upload\");\n\n this.uploadContainer.appendChild(fileInput);\n\n return fileInput;\n }", "function customFileInput() {\n for (const el of document.querySelectorAll('.custom-file > input[type=\"file\"]')) {\n el.addEventListener('change', () => {\n const fileLength = el.files.length\n let filename = fileLength ? el.files[0].name : 'Choose file'\n filename = fileLength > 1 ? fileLength + ' files' : filename // if more than one file, show '{amount} files'\n el.parentElement.querySelector('label').textContent = filename\n })\n }\n }", "function addInputToForm() {\n const form = document.body.querySelector(\"#picHolder\")\n let addInput2 = document.createElement(\"input\");\n addInput2.type = \"file\";\n addInput2.setAttribute('class','chosenPicture');\n addInput2.setAttribute('accept', 'image/*');\n addInput2.setAttribute('name', 'product');\n form.appendChild(addInput2);\n}", "function fileInput() {\n\t$('.upload-file').each(function () {\n\t\t$(this).filer({\n\t\t\tshowThumbs: true,\n\t\t\taddMore: true,\n\t\t\tallowDuplicates: false,\n\t\t\tlimit: 1\n\t\t});\n\t});\n}", "function createUploadInput() {\n var input = document.createElement('input');\n input.type = 'file';\n input.multiple = true;\n return input;\n }", "function createFileInput() {\n\tconst div = $('<div>').attr({\n\t\tid: 'js-file-input-container',\n\t\tclass: 'file-input-container'\n\t});\n\tdiv.append(\n\t\t'<div class=\"input-box\"><input type=\"file\" name=\"file\" id=\"file\"/><label for=\"file\" class=\"file-label\"><strong>Choose a file</strong><span class=\"box-dragndrop\"> or drag it here</span>.</label></div>'\n\t);\n\tdiv.append('<div class=\"box-uploading\">Uploading</div>');\n\tdiv.append('<div class=\"box-success\">Done!</div>');\n\tdiv.append('<div class=\"box-error\">Error!</div>');\n\t$('#js-input-container').append(div);\n\tcheckBrowserDragnDrop();\n}", "function addField(input) {\n var max_limit_for_file = 10000000; // do not allow files greater than 100MB\n if(input.files[0].size > max_limit_for_file){\n $(input).val('');\n alert(\"Your design file is greater than 10 MB and cannot be uploaded.\")\n }else{ \n console.log('add design field input');\n // remove the filefield of recently uploaded file and replace with existing file styling\n var filename = $(input).val().split('\\\\').pop(); \n console.log(filename);\n $(input).parents('fieldset').prepend('<label>'+filename+'</label>');\n $(input).hide();\n $(input).parent().hide();\n $(input).parents('fieldset').find('.destroy_design_file').val('0');\n $('.add_fields').click();\n }\n }", "addFile(fileName, contents) {\n this.formFields.push({name: `files[${fileName}]`, value: contents});\n if (fileName.endsWith('.js')) {\n this.addHead(`<script src=\"${fileName}\"></script>`);\n } else if (fileName.endsWith('.css')) {\n this.addHead(`<link href=\"${fileName}\" rel=\"stylesheet\">`);\n }\n return this;\n }", "addFileToForm(form, data, content, filename, path, prependApp = true) {\n if (path === TEMPLATE_PATH) {\n content = this.replaceExamplePlaceholderNames(data, filename, content);\n }\n else if (prependApp) {\n // tslint:disable-next-line:prefer-template\n filename = 'app/' + filename;\n }\n this.appendFormInput(form, `files[${filename}]`, this.appendCopyright(filename, content));\n }", "function createUploadInput() {\n let input = document.createElement('input');\n input.type = 'file';\n input.multiple = true;\n return input;\n }", "async upload_file(evt) {\r\n //\r\n //Test if all inputs are available, i.e., the file and its server path\r\n //\r\n //Get the file to post from the edit window\r\n //Get the only selected file\r\n const file = this.file_selector.files[0];\r\n //\r\n //Ensure that the file is selected\r\n if (file === undefined)\r\n throw new crud.crud_error('Please select a file');\r\n //\r\n //Get the sever folder\r\n const folder = this.input.value;\r\n //\r\n //Post the file to the server\r\n const { ok, result, html } = await server.post_file(file, folder);\r\n //\r\n //Flag the td inwhich the button is located as edited.\r\n if (ok) {\r\n crud.page.mark_as_edited(this.input);\r\n // \r\n //Update the input tag \r\n //\r\n //The full path of a local selection is the entered folder \r\n //plus the image/file name\r\n this.input.value += \"/\" + file.name;\r\n }\r\n //\r\n //Report any errors plus any buffered messages. \r\n else\r\n throw new crud.crud_error(html + result);\r\n }", "_addFile(container, event) {this.props.addFile(container, event.target.files[0]);}", "function UploadFile(parent_id, item = {}) {\n item.type = \"file\";\n item.id = item.id || \"{0}_{1}\".format(item.type, __INPUT_FILE++);\n Tag.call(this, parent_id, item);\n\n this.label_id = \"label_{0}\".format(this.id);\n this.fileType = item.fileType || \"Upload a file from here\";\n if (!this.needQuestion && this.star != \"\")\n this.fileType += this.star;\n this.label = item.label || this.fileType;\n this.icon = item.icon || \"cloud_upload\";\n this._style = 'style=\"position:absolute;top: 0;right: 0;width: 300px;height: 100%;z-index: 4;cursor: pointer;opacity: 0\"';\n\n this.html = this._generate();\n this.render();\n\n var label_id = this.label_id;\n document.getElementById(this.id).onchange = function() {\n document.getElementById(label_id).value = this.files[0].name;\n document.getElementById(label_id).textContent = this.files[0].name;\n };\n /*$(\"#{0}\".format(this.id)).change(function() {\n $(\"#{0}\".format(label_id)).val(this.files[0].name);\n $(\"#{0}\".format(label_id)).text(this.files[0].name);\n });*/\n }", "function addFile(file){\n\t\tif(filetype = validateType(file)){\n\t\t\tindex = Object.keys(files).length;\n\t\t\t\n\t\t\t//Set attributes of files\n\t\t\tfile[\"extension\"] = filetype;\n\t\t\tfile[\"uploaded\"] = false;\n\t\t\tfile[\"analyzed\"] = false;\n\t\t\tfile[\"index\"]\t = index;\n\t\t\t\n\t\t\t//Add the file to the end of the files array\n\t\t\tfiles[index] = file;\n\t\t\t\n\t\t\t//Add file to GUI\n\t\t\t$(\"ul\", upload_field).append(\"<li name=\\\"\"+index+\"\\\"><span>\"+file.name+\"</span><a class=\\\"delete\\\">delete</a></li>\");\n\t\t\t$(\"ul li[name='\"+index+\"'] a.delete\", upload_field).click(file, removeFile);\n\n\t\t\t//Checks if a file is an audio file\n\t\t\tfunction validateType(file){\n\t\t\t\tres = file.type.split(\"/\");\n\t\t\t\treturn (res[0] == \"audio\") ? res[1] : false;\n\t\t\t}\n\t\t}else{\n\t\t\tsetStatus(\"You can only add audio files\");\n\t\t}\n\t}", "createInput(architect) {\n let root = architect.createLabel(\"file-label file-label-container\");\n\n // Creating the html input element\n let input = architect.createInput(\"file-input\");\n input.setId(this.id);\n input.setRef(\"files\");\n let inputAttrs = {\n placeholder: this.placeholder,\n disabled: this.disabled || this.isUploading,\n validationScope: this.validationScope,\n type: \"file\",\n readonly: this.readonly,\n accept: this.accept\n };\n input.setAttrs(inputAttrs);\n input.addChange(this.handleFilesUpload);\n\n let fileCta = architect.createSpan(\"file-cta\");\n let fileIcon = architect.createSpan(\"file-icon\");\n let icon = architect.createIcon().setProps({\n icon: this.$thisvui.icons.upload,\n containerClass: this.getIconClasses,\n preserveDefaults: !this.overrideDefaults\n });\n let fileLabel = architect.createSpan(\"file-label\");\n let label = architect.createP();\n label.innerHTML(\n this.isInitialUpload\n ? this.label\n : `Uploading ${this.fileCount} files...`\n );\n let filename = architect.createSpan(\"file-name\");\n filename.innerHTML(this.fileName);\n\n fileIcon.addChild(icon);\n fileLabel.addChild(label);\n fileCta.addChild(fileIcon);\n fileCta.addChild(fileLabel);\n root.addChild(input);\n root.addChild(fileCta);\n root.addChild(filename, this.fileHasName);\n architect.addChild(root);\n }", "function attachFile() {\n self.uploadCtrl.triggerFileInput();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds item to list after return key is pressed
function addListAfterKeypress(event) { if (event.keyCode === 13) { createListElement(); } }
[ "function addListAfterKeypress(event) {\r\n\tif(inputLength() > 0 && event.which === 13) {\r\n\t\tcreateListElement();\r\n\t}\r\n}", "function addListAfterKeypress(event) {\n\tif (inputLength() > 0 && event.keyCode === 13) {\n\t\tcreateListElement();\n\t}\n}", "function addListAfterKeypress(event) {\r\n if(inputLength() > 0 && event.which === 13) {\r\n createListElement()}\r\n}", "function addListAfterKeypress(event) {\n if (inputLength() >0 && event.keyCode === 13) {\n createListElement();\n }\n}", "function listAddAfterEnter(e) {\r\n if (hasInput() && isEnter(e)) {\r\n addToList();\r\n }\r\n}", "function addItemAfterKeypress(event){\n\tif(inputLength() > 0 && event.keyCode == 13){\n\t\taddItem();\n\t}\n}", "function addLiAfterKeypress(event) {\n if(inputLength() > 0 && event.keyCode===13) {\n createListItem();\n }\n}", "function addListKeyPress(event) {\n if (inputlength() > 0 && event.which === 13) {\n addli();\n }\n}", "function listInputKeyUp(event) {\n var aimSetting = wunderlist.settings.getInt('add_item_method', 0);\n if (event.keyCode === 13 && aimSetting === 0) {\n wunderlist.timer.pause();\n listEventListener = true;\n var listElement = $(this).parent('a');\n var list_id = listElement.attr('id').replace('list', '');\n\n wunderlist.timer.resume();\n\n if (list_id != 'x'){\n saveList(listElement);\n } else{\n saveNewList(listElement);\n }\n }\n }", "function addLiAfterKeypress(event){\n if (inputLength() > 0 && event.key === 'Enter'){\n createLiElement();\n }\n}", "onNewToDoKeyDown(event) {\n if (event.keyCode === 13) {\n this.addToList();\n }\n }", "function addItemsEnterPress() {\n var key = (event.keyCode ? event.keyCode : event.which); // Enter button code = 13\n if (key == 13) {\n addItemsClick();\n }\n }", "function createListItemOnEnter(event){\n if( inputLength() > 0 && event.keyCode === 13){\n createListItem();\n }\n}", "function handleKeyDown(event) {\n if (event.key === 'Enter') {\n addItem();\n }\n }", "function addbyEnter(event) {\r\n\tif (inputValueLength() && event.keyCode === 13) \r\n\t{\r\n\tinputItemsName()\r\n\t}\r\n}", "function addListItem() {\n todoInputEl.addEventListener('keypress', function(event) {\n // if key pressing is 'enter' key? every key on keyboard has unique ascii code\n //console.log(event.keyCode); // find key code of pressing enter. // 13\n if (event.keyCode === 13) {\n let newListItem = createListItem(todoInputEl.value);\n let createDeleteButton();\n //console.log(todoInputEl.value); // when if statement true, console.log input\n todoListEl.appendChild(newListItem); // append adds to end of list\n // to make input on top of list:\n todoListEl.insertBefore(newListItem, todoListEl.childNodes[0]);\n todoInputEl.value = \"\"; // clears input box after user enters something\n }\n})\n}", "function addOnKeypress () {\n $('#userInput').keypress(function(event) {\n if(event.which === 13) {\n event.preventDefault();\n appendToDo();\n }\n });\n}", "function itemKeypress (event) {\n\tif (event.which === 13) {\n\t\tupdateItem.call(this);\n\t}\n}", "function itemKeypress() {\n //'13' represents the enter key\n if (event.which === 13) {\n updateItem.call(this);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called last in the success callback of the saveEntity() function, giving room for functionality that should be executed immediately after save
onAfterSaveEntity(data_obj) { //TODO: Override this as needed; }
[ "function onBeginSave() {\n console.log(\"onBeginSave\");\n postJsonData();\n}", "function doSave() {\n pendingSave = null\n if (dirty && !pendingPost) doPostContent()\n }", "function onSaveSuccess(data, response, xhr)\n\t{\n\t\t// update id's and scope in case they change\n\t\t// this happens when switching from global\n\t\t// to page specific fields (switching scope)\n\t\tthis.data.node.data = data;\n\t\tthis.data.node.data.originals = this.originals;\n\t\tthis.data.field = this.data.node.data;\n\n\t\tthis.view.empty();\n\t\tthis.view.append(this.renderField(this.data.field, true));\n\t\tthis.sidebar.layout.removeClass('saving');\n\t\tLiveUpdater.changedField(this.data.field);\n\t}", "handleSaveSuccess() {\n }", "onSaveUpdates() {\n\t\t\t\n\t\t\t// Some kind of bug here due to multiple components, this might be the best way around it\n\t\t\tif (!this._oODataModel.oMetadata) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._setBusy(true);\n\n\t\t\t// Submit changes*/\n\t\t\tthis._oODataModel.submitChanges({\n\t\t\t\tsuccess: (oData) => {\n\t\t\t\t\tthis._setBusy(false);\n\t\t\t\t\tthis._handleBatchResponseAndReturnErrorFlag(oData);\n\t\t\t\t\tthis._resetODataModel();\n\t\t\t\t},\n\t\t\t\terror: this._handleSimpleODataError.bind(this)\n\t\t\t});\n\n\t\t}", "callOnSaveCallback() {\n if(this.onSaveCallback != null)\n this.onSaveCallback();\n }", "function onSaveSuccess(data, response, xhr)\n\t{\n\t\tthis.sidebar.layout.removeClass('saving');\n\t\tthis.data.field = data.field;\n\t\tLiveUpdater.changedModel(this.data.field);\n\t}", "_markAsSaved() {\n // TODO: Note that this uses internal functions\n try {\n this._internalModel.send('willCommit');\n this._internalModel._attributes = {};\n this._internalModel.send('didCommit');\n } catch(e) {\n // Ignore if an error occurs, since this is quite hacky behavior anyhow\n // Especially an \"Attempted to handle event `didCommit` on ...\" error could occur\n }\n\n }", "_saveData() {\n \n // undo changes in case onBeforeSave is specified and returns false \n if (this.onBeforeSave && typeof this.onBeforeSave == \"function\")\n if (! this.onBeforeSave(this.dataModel)) {\n setTimeout(jQuery.unblockUI);\n this.dataModel.execute(true);\n return;\n }\n setTimeout(function(){jQuery.blockUI({message: bcdui.i18n.syncTranslateFormatMessage({msgid:\"bcd_Wait\"})})});\n this.dataModel.sendData();\n }", "onBeforeSaveEntity() {\n\t\tthis.resetValidation();\n\t\treturn this.validateEntity();\n\t}", "beforeSaveToDB()\n {\n }", "_markAsSaved() {\n // TODO: Note that this uses internal functions\n try {\n // In Ember Data 3.5+, this works a bit different\n // We differentiate by the existence of _recordData\n if (this._internalModel._recordData) {\n this._internalModel.adapterWillCommit();\n this._internalModel.adapterDidCommit();\n } else {\n this._internalModel.send('willCommit');\n this._internalModel._attributes = {};\n this._internalModel.send('didCommit');\n }\n } catch (e) {\n // Ignore if an error occurs, since this is quite hacky behavior anyhow\n // Especially an \"Attempted to handle event `didCommit` on ...\" error could occur\n }\n }", "onAfterLoadEntity(data_obj) {\n\t\t//TODO: Override this as needed;\n\t}", "function saveItem() {\n\t\t\t// here's some code for that\n\t\t}", "function saveSuccess() {\n $(\"#datum\").effect(\"highlight\", {}, 1500);\n \n if (frameworkId != null) {\n EcFramework.get(frameworkId, function (framework) {\n \tvar rulesDone = false;\n \tvar levelsDone = false;\n framework.addCompetency(data.id);\n data.levels(AppController.serverController.getRepoInterface(), function (level) {\n framework.addLevel(level.id);\n }, errorRetrievingLevels, function (levels) {\n framework.save(function (s) {\n \tif(rulesDone)\n\t ScreenManager.changeScreen(new FrameworkEditScreen({\n\t id: EcRemoteLinkedData.trimVersionFromUrl(frameworkId)\n\t }));\n \telse\n \t\tlevelsDone = true;\n }, errorSaving);\n });\n\n data.rollupRules(AppController.serverController.getRepoInterface(), function (rollupRule) {\n framework.addRollupRule(rollupRule.id);\n }, errorRetrievingRollupRules, function (rollupRules) {\n framework.save(function (s) {\n if(levelsDone)\n\t \tScreenManager.changeScreen(new FrameworkEditScreen({\n\t id: EcRemoteLinkedData.trimVersionFromUrl(frameworkId)\n\t }));\n else\n \trulesDone = true;\n }, errorSaving);\n });\n\n }, errorRetrieving);\n }\n }", "function handleArticleSave() {\n\n var articleToSave = $(this).parents('.article-holder').data();\n articleToSave.saved = true;\n\n $.ajax({\n method:'PATCH',\n url:'/api/headlines',\n data:articleToSave\n })\n .then(function(data) {\n\n if(data.ok) {\n initPage();\n }\n\n });\n\n }", "function saved(self) {\n var cbs;\n self._saving=false; // set zocci's saving status to false so future save operations will go through\n if (!self._resave.length) {\n return;\n }\n cbs=self._resave; // temporary list of callbacks\n self._resave=[]; // clear original callback list\n self.save(function(saved) {\n cbs.forEach(function(cb) {\n if (typeof cb==='function') {\n cb(saved);\n }\n });\n });\n}", "save () {}", "onSave() {\n throw new Error('Not implemented');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filtering function for the search by keywords feild, can be modifed for the "words get big for being popular shit."
function filterGallery(keywords) { var filteredGallery; //CR : if(keyWords.length === 0 ) return buildGallery(gImgs) if (keywords.length === 0) { buildGallery(gImgs); return; } var keywordsArr = keywords.split(" "); keywordsArr = keywordsArr.map(function (keyword) { return keyword.toLowerCase(); }); if (keywordsArr.length > 1) { filteredGallery = gImgs.filter(function (img) { var containsAllWords = false; for (var i = 0; i < keywordsArr.length; i++) { var word = keywordsArr[i]; if (img.keywords.includes(word)) { //can make search better by searching for a words within an item inside img.keywords containsAllWords = true; } else { containsAllWords = false; break; } } if (containsAllWords) return img; }); } else { filteredGallery = gImgs.filter(function (img) { // return (img.keywords.includes(keywordsArr[0])) if (img.keywords.includes(keywordsArr[0])) return img; }); } buildGallery(filteredGallery); }
[ "function keywordFilter(keyword) {\n keywords = [keyword]\n var filtered = data.filter(function(pub) {\n return pub.keywords.some(function(tag) {\n return keywords.includes(tag);\n });\n });\n data2 = filtered;\n previousYear = \"2005\";\n pubsPlot();\n pubsText();\n }", "function filterKeywords(feedconfig) {\n\n\n // Feedconfig\n if(!(feedconfig instanceof FeedConfig.FeedConfig))\n throw new Error('not a feedconfig');\n\n // console.log(feedconfig)\n\n var _gender = feedconfig.gender;\n var _age = feedconfig.age;\n var _tier = feedconfig.tier;\n\n\n // Build request\n var genderFilter;\n\n if(_gender == \"Men\") genderFilter = function(p) { return p.gender == 'M' }\n else if (_gender == \"Women\") genderFilter = function(p) { return p.gender == 'F' }\n else genderFilter = function(p) { return p.gender == 'F' || p.gender == 'M' }\n\n var ageFilter;\n\n if( _age =='18-' ) ageFilter = function(p) {return p.age <= 18}\n else if( _age == '24-') ageFilter = function(p) {return p.age >= 18 && p.age <= 24}\n else if( _age == '35-') ageFilter = function(p) {return p.age >= 25 && p.age <= 35}\n else if( _age == '40+') ageFilter = function(p) {return p.age >= 36}\n else ageFilter = function(p) { return p.age }\n\n var tierFilter;\n if(_tier == '1') tierFilter = function(p) {return p.tier == \"T1\"}\n else if(_tier == '2') tierFilter = function(p) {return p.tier == \"T2\"}\n else if(_tier == '3') tierFilter = function(p) {return p.tier == \"T3\"}\n else tierFilter = function(p) {return p.tier }\n\n\n // Filter words\n var results = words\n .filter( genderFilter)\n .filter( ageFilter )\n .filter( tierFilter );\n \n // console.log(results)\n return results\n\n}", "function KeywordFilter({keywords = [], keep = true}) {\n return {\n name: \"Keyword Filter\",\n func: (proxies) => {\n return proxies.map((proxy) => {\n const selected = keywords.some((k) => proxy.name.indexOf(k) !== -1);\n return keep ? selected : !selected;\n });\n },\n };\n }", "function keywordFilter(termstring, records, aliases) { // eslint-disable-line no-unused-vars\n terms = termstring.trim().split(/\\s+/);\n var patterns = {};\n for (var i = 0; i < terms.length; i++) {\n var subterms = terms[i].split(\":\");\n if (subterms.length > 1) {\n // we have a keyname - is it one we use the the records? if not it is part of the searchterm and the key is keywords\n if (subterms[0] in records[0]) { subterms = [subterms[0], subterms.slice(1).join(\":\")]; }\n else { subterms = [\"keywords\", subterms.slice(0).join(\":\")]; }\n } else { // no key - use keywords\n subterms.unshift(\"keywords\");\n }\n var not = subterms[1].indexOf(\"!\") === 0;\n if (not) { subterms[1] = subterms[1].substr(1); }\n\n if (subterms[1][0] != \"^\" && subterms[1].slice(-1) != \"$\") { // non pre-regexps - escape them\n subterms[1] = \"\\\\b\" + subterms[1].replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, \"\\\\$1\").replace(/\\x08/g, \"\\\\x08\"); // eslint-disable-line no-control-regex\n }\n var alias = aliases[subterms[0]];\n if (alias) { subterms[0] = alias; }\n if (patterns[subterms[0]] == undefined) { patterns[subterms[0]] = []; }\n patterns[subterms[0]].push({re: new RegExp(subterms[1] , \"i\"), not: not});\n }\n\n var result = [];\n rec: for (i = 0; i < records.length; i++) {\n var found = true;\n record = records[i];\n for (var key in patterns) {\n if (!found) { continue rec; } // stop testing if we know the rec is not going to make it\n var value = record[key];\n if (value == undefined) { continue rec; } // not found\n var type = typeof value;\n if (type === \"boolean\") { found = found && value != patterns[key][0][\"not\"]; continue; }\n if (type === \"string\") { value = [value]; }\n for (var h = 0; h < patterns[key].length; h++) {\n var pfound = false;\n for (var j = 0; j < value.length; j++) {\n if (pfound) { break; }\n pfound = pfound || patterns[key][h][\"re\"].test(value[j]);\n }\n found = found && (pfound != patterns[key][h][\"not\"]); // poor mans xor\n }\n }\n if (found) { result.push(i); }\n }\n return result;\n}", "function searchFilter(keyword) {\n return function(blog) {\n return blog.title.toLowerCase().includes(keyword.toLowerCase()) ||\n blog.body.toLowerCase().includes(keyword.toLowerCase()) || !keyword;\n }\n}", "getResultsByKeyword(keyword) {\r\n return this.results['all'].features.filter(feature => feature.properties.keywords.indexOf(keyword) > -1);\r\n }", "function keywordFilter(termstring, records, aliases) {\n var terms = unique(termstring.trim().split(/\\s+/));\n var patterns = {};\n for (var i = 0; i < terms.length; i++) {\n var subterms = terms[i].split(\":\");\n if (subterms.length == 1) {\n subterms.unshift(\"keywords\");\n }\n var not = subterms[1].indexOf(\"!\") === 0;\n if (not) { subterms[1] = subterms[1].substr(1); }\n\n // Finds the first operator specified\n var operator = compare.operators.find(function(op) {\n return subterms[1].indexOf(op) === 0;\n });\n\n if (operator) {\n subterms[1] = subterms[1].substr(operator.length);\n } else if (subterms[1][0] != \"^\" && subterms[1].slice(-1) != \"$\") { // non pre-regexps - escape them\n subterms[1] = \"\\\\b\" + subterms[1].replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, \"\\\\$1\").replace(/\\x08/g, \"\\\\x08\"); // eslint-disable-line no-control-regex\n }\n var alias = aliases[subterms[0]];\n if (alias) { subterms[0] = alias; }\n if (patterns[subterms[0]] == undefined) { patterns[subterms[0]] = []; }\n patterns[subterms[0]].push({re: new RegExp(subterms[1] , \"i\"), not: not, op: operator, value: subterms[1]});\n }\n var result = [];\n rec: for (i = 0; i < records.length; i++) {\n var found = true;\n record = records[i];\n for (var key in patterns) {\n if (!found) { continue rec; } // stop testing if we know the rec is not going to make it\n var value = record[key];\n if (value == undefined) { found = found && not; continue; } // not found\n var type = typeof value;\n if (type === \"boolean\") { found = found && value != patterns[key][0][\"not\"]; continue; }\n if (type === \"string\" || type == 'number') { value = [\"\"+value]; }\n for (var h = 0; h < patterns[key].length; h++) {\n var pfound = false;\n for (var j = 0; j < value.length; j++) {\n if (pfound) { break; }\n var p = patterns[key][h];\n if (p.op) {\n var values = p.value.split(\",\");\n pfound = compare(\"~\", values[0], values[1], value[j]);\n } else {\n pfound = patterns[key][h][\"re\"].test(value[j]);\n }\n }\n found = found && (pfound != patterns[key][h][\"not\"]); // poor mans xor\n }\n }\n if (found) { result.push(record); }\n }\n return result;\n}", "function filterByKeywords(results,keyword){\n var hasKeyword = [];\n results.forEach(function(item){\n var hasTheWord=false;\n item.keywords.forEach(function(word){\n if(word==keyword){\n hasTheWord = true;\n }\n });\n if(hasTheWord){\n hasKeyword.push(item);\n }\n });\n return hasKeyword;\n}", "function filterRelevant(movies, binWords){\r\n let relevant = movies.filter((m) => {\r\n for(let i = 0; i < m.keywords.length; i++){\r\n if(binWords.includes(m.keywords[i])){\r\n return true;\r\n } \r\n }\r\n return false;\r\n })\r\n\r\n return relevant.sort((a,b) => b.vote_average*b.vote_count - a.vote_average*a.vote_count).slice(0,500)\r\n}", "function filterkeywords(input) {\n\n var words = input.split(/[^0-9A-Za-z]+/);\n console.log(words);\n var stopWords = \"a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your\";\n\n // filter out the stopwords\n for (var i = 0; i < words.length; i++) {\n // case insensitive\n if (stopWords.match(\".*\\\\b\" + words[i].toLowerCase() + \"\\\\b.*\")) {\n console.log(words[i]);\n words[i] = null;\n }\n }\n\n words = words.filter(filternull);\n console.log(words.length);\n return words;\n }", "function displayKeywords() {\n keywordData.sort();\n\tvar checked;\n\tvar keyword;\n\tvar str = genKeywordEntry(\" checked\", 'no_keyword_filter', NO_KEYWORD_FILTER, 0);\n\tfor (i in keywordData) {\n if (keywordData.hasOwnProperty(i)) {\n var keywordObj = keywordData[i];\n keyword = keywordObj.keyword;\n checked = \"\";\n str += genKeywordEntry(checked, keyword, keyword, keywordObj.pubs.length);\n }\n }\n\t\n\t$(\"#filter\").html(str);\t\n}", "function _getSearchKeywords() {\r\n let title = $('#slideTitle').val();\r\n let body = $('#slideBody').html();\r\n // Formating search keywords. Replaces whitespace with '+'\r\n body = body.trim().replace(' ', '+');\r\n title = title.trim().replace(' ', '+');\r\n // formatting for keyword output.\r\n let results = body ? title + '+' + body : title\r\n return results;\r\n}", "function theStudentsSearching(keywords) {\n const searchresult = students.filter(searchFunction);\n keywords = keywords.toLowerCase();\n\n function searchFunction(student) {\n let firstnameLower = student.firstname.toLowerCase();\n let lastnameLower = student.lastname.toLowerCase();\n let houseLower = student.house.toLowerCase();\n\n if (firstnameLower.indexOf(keywords) > -1 || firstnameLower === keywords) {\n return true;\n } else if (lastnameLower.indexOf(keywords) > -1 || lastnameLower === keywords) {\n return true;\n } else if (houseLower.indexOf(keywords) > -1 || houseLower === keywords) {\n return true;\n } else {\n return false;\n }\n }\n\n //Rendering the ready-to-be-seen search result.//\n return searchresult;\n}", "function makesearchfilter(values) {\n// clean up values from automcomplete with (xx) at the end of the string \nvar values = values.split('(')[0] ;\n// REMOVE all the extra whitespaces \nvar values = values.replace(/\\s{2,}/g, ' ');\nvar curval = 'allText:(';\nvar pval = ' OR aprodno:(' ;\nvar cival = ' OR citems:(' ;\n// UPDATED FOR CONTAINING LOGIC\nif (mastcust !== '') { var cmval = ' OR citems:(' ; } else { var cmval = '' ; }\nvar rfqarray = values.split(\" \") ; // each word gets added\nvar fqarray = [] ; \n // clean up values in array if only one - don't loop \n for (var i = 0; i < rfqarray.length; i++) {\n fqvalx = AjaxSolr.Parameter.CleanValue(rfqarray[i])\n if (fqvalx !== '') {\n fqarray.push(rfqarray[i]);\n }\n }\nvar fcnt = fqarray.length - 1\n if (fcnt > 0) { \n for (var i = 0; i < fcnt; i++) {\n var fqvalx = AjaxSolr.Parameter.CleanValue(fqarray[i]) ; \n // fqarray[i] = fqarray[i].replace(/\\s+/g, ''); // removed blank spaces\n if (fqvalx !== '') {\n // solr doesn't do containing so add the * to the end for beginning with \n// djf - added it back solr does seem to use the * in front 10/23/17\n curval += '*' + fqvalx + '*' + ' AND ' ; \n pval += '*' + fqvalx + '*' + ' AND ' ;\n cival += intcust + '\\\\*' + fqvalx + '*' + ' AND ' ;\n if (mastcust !== '') { \n cmval += mastcust + '\\\\**' + fqvalx + '*' + ' AND ' ;\n }\n }\n }\n// add last value for each part of query\n var fqvalx = AjaxSolr.Parameter.CleanValue(fqarray[fcnt]) ; \n if (fqvalx !== '') {\n curval += '*' + fqvalx + '*' + ')';\n pval += '*' + fqvalx + '*' + ')';\n cival += intcust + '\\\\**' + fqvalx + '*' + ')';\n if (mastcust !== '') { \n cmval += mastcust + '\\\\**' + fqvalx + '*' + ')';\n }\n } else {\n curval += ')';\n pval += ')';\n cival += ')';\n if (mastcust !== '') { \n cmval += ')';\n } \n }\n } else { \n // for single item in search \n var fqvalx = AjaxSolr.Parameter.CleanValue(fqarray[fcnt]) ; \n if (fqvalx !== '') {\n curval += '*' + fqvalx + '*' + ')';\n pval += '*' + fqvalx + '*' + ')';\n cival += intcust + '\\\\**' + fqvalx + '*' + ')';\n if (mastcust !== '') { \n cmval += mastcust + '\\\\**' + fqvalx + '*' + ')';\n }\n }\n }\n \n sval = curval + pval + cival + cmval ;\n// added customer history search\n var shist = $(\"#shistflag\").is(':checked') ; \n if (shist) { \n var sval = '(' + sval + ') AND ( (customers:' + intcust + ') )' ;\n }\n// Added Customer Association Code Filters 8-29-16 \nif (custassoc) { \n var assoc = custassoc.split(\",\") ;\n var aval = '' ; \nfor (var i = 0, l = assoc.length; i < l; i++) {\n var assocA = assoc[i];\nif (assocA) { var aval = aval + assocA + ' OR ' ; }\n}\n var aval = aval + '99' ; \n var sval = '(' + sval + ') AND ( webprodassoc:(' + aval + ') )' ;\n}\n// Added categories filter\nvar catginfo = $(\"#categories\").val() ;\n if (catginfo) {\n var catginfo = catginfo + '|||' ;\n var sval = '(' + sval + ') AND ( (searchcat:' + catginfo + ') )' ;\n }\nreturn sval\n}", "filterTags() {\n const filter = this.filter.slice(1).toLowerCase();\n this.filteredTags = this.tags\n .filter((tag) => {\n return tag.textTag.indexOf(filter) !== -1 ||\n tag.title.toLowerCase().indexOf(filter) !== -1;\n })\n .slice(0, this.limit);\n }", "function filterPostByKeywordAnd(post, settings) {\n let filtered = false;\n let keywords = settings.keywordsAnd;\n if (keywords && keywords.length > 0) {\n const fullText = getFullText(post);\n keywords = keywords.map(keyword => keyword.toLowerCase());\n const foundKeyword = {};\n keywords.forEach((keyword) => {\n foundKeyword[keyword] = false;\n });\n keywords.forEach((keyword) => {\n if (fullText.indexOf(keyword) > -1) {\n foundKeyword[keyword] = true;\n }\n });\n filtered = keywords.reduce((accumulator, keyword) => foundKeyword[keyword] && accumulator, true);\n }\n return {\n filtered,\n reason: 'Keyword',\n };\n}", "function searchProducts(value) {\n if (value == \"\") { // search bar submitted with no input\n return \"\";\n } else {\n return allProducts.filter(product => product.keywords.includes(value.toLowerCase()));\n }\n}", "function filterByKeywords(planList, keywords) {\n return _.filter(planList, function(event) {\n if (!_.isEmpty(keywords)) {\n return _.some(keywords, function(keyword) {\n return _.some(event.keywords, function(eventKeyword) {\n return (eventKeyword.indexOf(keyword) != -1);\n })\n });\n } else {\n return false;\n }\n });\n}", "function searchKwons (database, currentUser, searchTerms) {\n function kwonContains (kwon, word) {\n return kwon.user.toLowerCase().indexOf(word) > -1\n || kwon.content.toLowerCase().indexOf(word) > -1;\n }\n\n return database.kwons;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getters are great getters are a function that doesn't take an argument and which should return something. In this case, we will use this to do the sorting of all the letter tuples in our memState and then return the result.
get results() { // Remember the comparator function? This is the same one, we're going to use it in the same way. let comparatorFunc = (arr1, arr2) => { if (arr1[1] === arr2[1]) { if (arr1[0] < arr2[0]) return -1; return 1; } return arr2[1] - arr1[1]; }; // Let's perform the same operation we did in the first solution, but this time within a class, acting on the memState object it contains. return Object.entries(this.memState).sort(comparatorFunc); }
[ "get sort() {\n return this.states.sort;\n }", "listOfPeopleInAlphabeticalOrderByName() {\n //this one is harder than i thought, haha.\n }", "function getAlphabetical() {\n try {\n test.integrationStore.getList(self.list, {}, { name: 1 }, function (list, error) {\n if (typeof error != 'undefined') {\n returnResponse(testNode, error);\n return;\n }\n // Verify each move returns true when move succeeds\n test.assertion(list.moveFirst(),'moveFirst');\n test.assertion(!list.movePrevious(),'movePrevious');\n test.assertion(list.get('name') == 'Al Pacino','AP');\n test.assertion(list.moveLast(),'moveLast');\n test.assertion(!list.moveNext(),'moveNext');\n test.assertion(list.get('name') == 'Tom Hanks','TH');\n returnResponse(testNode, true);\n });\n }\n catch (err) {\n returnResponse(testNode, err);\n return;\n }\n }", "sort() { \n let arr = this.names.sort();\n return arr;\n }", "getAlphabet() {\n return this._nfa.getAlphabet();\n }", "function getAlphabetical() {\n try {\n storeBeingTested.getList(test.list, {}, {name: 1}, function (list, error) {\n if (typeof error != 'undefined') {\n callback(error);\n return;\n }\n // Verify each move returns true when move succeeds\n test.shouldBeTrue(list.moveFirst(), 'moveFirst');\n test.shouldBeTrue(!list.movePrevious(), 'movePrevious');\n test.shouldBeTrue(list.get('name') == 'Al Pacino', 'AP');\n test.shouldBeTrue(list.moveLast(), 'moveLast');\n test.shouldBeTrue(!list.moveNext(), 'moveNext');\n test.shouldBeTrue(list.get('name') == 'Tom Hanks', 'TH');\n callback(true);\n });\n }\n catch (err) {\n callback(err);\n }\n }", "get sortedColumn() {\n return this.props.sortedColumn;\n }", "get sortBy(){return this._sortBy;}", "get list() {\n return Object.values(this.cache).sort((a, b) => {\n return this.sortfunction(a, b);\n });\n }", "alphabet() {\n return this._alphabet;\n }", "get the_letter()\n {\n return this._the_letter;\n }", "getAlphabet() {\n if (!this._alphabet) {\n this._alphabet = new Set();\n const table = this.getTransitionTable();\n for (const state in table) {\n const transitions = table[state];\n for (const symbol in transitions) if (symbol !== EPSILON_CLOSURE) {\n this._alphabet.add(symbol);\n }\n }\n }\n return this._alphabet;\n }", "function readOrderOfallCharactersFromPriority() {\r\n sortOrderFromPriority(allCharacters);\r\n readWhatCharacterIsInPlay();\r\n}", "sortStates() { this._states.sort(this._sortState, this); }", "sortedStates() {\n\t\tconst list = this._states.values();\n\t\treturn list.sort(function(a, b) {\n\t\t\treturn a.stateNumber - b.stateNumber;\n\t\t});\n\t}", "get sortingOrder() {}", "get sort() { return this._sort; }", "sortLeaderboard () {\n // Build the array to be sorted that will contain all the leaderboard information\n let sortedLeaderboard = []\n const leaderboard = this.state.leaderboard\n for (var key in leaderboard) {\n if (leaderboard.hasOwnProperty(key)) {\n if (this.checkFilters(leaderboard[key])) {\n sortedLeaderboard.push(leaderboard[key])\n }\n }\n }\n\n sortedLeaderboard.sort((a, b) => b.score - a.score)\n\n for (var i in sortedLeaderboard) {\n sortedLeaderboard[i].position = parseInt(i, 10) + 1\n }\n return sortedLeaderboard\n }", "getGuessedLetters() { \r\n return this.guessedLetters\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert a ratio to cents
function ratio_to_cents(input) { return decimal_to_cents(ratio_to_decimal(input)); }
[ "function ratio_to_cents(input) {\n return decimal_to_cents(ratio_to_decimal(input))\n}", "function toCents(priceEuro) {\n return Math.round(priceEuro * 100);\n}", "function covertCents(amount){\n return parseInt(amount*100);\n }", "function makesCents(amount) {\n return Math.round(parseInt(amount * 100));\n}", "function centsToRate (cents) { return cents ? Math.pow(2, cents / 1200) : 1 }", "function cents_to_decimal(input) {\n return Math.pow(2, parseFloat(input) / 1200.0);\n}", "function cents_to_decimal(input) {\n const inputfloat = parseFloat(input);\n if (Number.isNaN(inputfloat)) return NaN;\n return Decimal.pow(2, Decimal(input).div(1200)).toNumber();\n}", "function euroToDollar(euro) {\r\n return euro / changeRate;\r\n}", "function ratio_to_decimal(input) {\n if (isRatio(input)) {\n const [val1, val2] = input.split('/').map(Decimal);\n return val1.div(val2).toNumber();\n } else {\n alert('Invalid input: ' + input)\n return false\n }\n}", "function toDollarsAndCents(n) {\n\t\t var n = new String(n);\n //\t\t\t if (n.substring(0,1) == \"$\") {\n //\t\t\t \t n = n.substring(1,n.length);\n //\t\t\t }\n\t\t var s = \"\" + Math.round(n * 100) / 100;\n\t\t var i = s.indexOf('.');\n\t\t if (i < 0) {\n\t\t return s + \".00\";\n\t\t }\n\t\t var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3);\n\t\t if (i + 2 == s.length) {\n\t\t t += \"0\";\n\t\t }\n\t\t t = t;\n\t\t return t;\t\t \n\t }", "function toCurrency(val){\nval = (Math.round(parseFloat(\"0\"+val)*100))/100;\nsval = val.toString();\nvals = sval.split(\".\");\nif(vals[1]){\n cents = (vals[1]+\"00\").substring(0,2);\n}\nelse{\n cents=\"00\";\n}\ncurr = vals[0]+\".\"+cents;\nreturn curr;\n}", "function centsToFactor(cents) {\n return Math.pow(2, cents / 1200);\n}", "function line_to_cents(input) {\n return decimal_to_cents(line_to_decimal(input))\n}", "function cpa(cost, conversions){\n var costConv = cost/conversions;\n return costConv.toFixed(2);\n}", "function centsInDollar() {\n return 100;\n}", "function line_to_cents(input) {\n return decimal_to_cents(line_to_decimal(input));\n}", "function dollarsToPounds(dollar_amount_input){\n return dollar_amount_input * 0.5966\n}", "async function convertUSDToCents(value) {\n let valueAssign = value;\n valueAssign = `${valueAssign}`.replace(/[^\\d.-]/g, '');\n if (value && valueAssign.includes('.')) {\n valueAssign = valueAssign.substring(0, value.indexOf('.') + 3);\n }\n return valueAssign ? Math.round(parseFloat(valueAssign) * 100) : 0;\n}", "getMoneyRatio() {\n\t\tif(!this.props.randCountryInfo.dollarPrice) return 0; //error state\n\t\treturn this.props.myCountryInfo.dollarPrice / this.props.randCountryInfo.dollarPrice;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility for coercing a given item into an array.
function arrayify(item) { return [].concat(item); }
[ "function arrayFromValue(item) {\n return \n [item];\n}", "function makeIntoArray(item) {\n if ((typeof item == \"object\") && (item.constructor == Array)) { \n\treturn item;\n } else {\n\treturn [item];\n }\n}", "function toArray(item) {\n\n if (typeof item === 'object') {\n return _.toArray(item);\n }\n\n return [item];\n }", "function convertArrayLikeObject(obj){\n return Array.from(obj);\n}", "function castAsArray(arg) {\n if (!Array.isArray(arg)) {\n arg = [arg];\n }\n\n return arg;\n}", "function toArray(input) {\r\n if (Array.isArray(input)) {\r\n return input;\r\n }\r\n else {\r\n return [input];\r\n }\r\n}", "function toArray(input) {\n if (Array.isArray(input)) {\n return input;\n }\n else {\n return [input];\n }\n}", "function convertArrayLikeObject(arrayLikeObject){\n return Array.from(arrayLikeObject);\n}", "function toArray(input) {\n if (Array.isArray(input)) {\n return input;\n } else {\n return [input];\n }\n}", "function convertToArray(node) {\n\t\t\t\treturn Array.prototype.slice.call(node, 0);\n\t\t\t}", "_arr(x) {return typeof x === 'string' ? [x] : x}", "function toArray(value){if(isArray(value)){return value;}if(value!=null){return [value];}return [];}", "function getSubArrayByKey(item, key) {\n\tvar val = item[key];\n\tif(val == null) {\n\t\tval = new Array();\n\t}\n\treturn val;\n}", "function toArray(data) {\n return data instanceof Array ? data : [data];\n}", "function as_list(i) { return i instanceof Array ? i : [i]; }", "asArray() {\n this.validate();\n const val = this._captured[this.idx];\n if ((0, type_1.getType)(val) === 'array') {\n return val;\n }\n this.reportIncorrectType('array');\n }", "function array(value, arg, index) {\n return Array.isArray(value) ? value : [value];\n}", "function arrayFor(x) {\n\t\tvar y=x;\n\t\tif (x == null) {\n\t\t\ty = new Array(0);\n\t\t}\n\t\telse if (typeof x=='string' || !x.length) {\n\t\t\ty = new Array(1);\n\t\t\ty[0] = x;\n\t\t}\n\t\treturn y;\n}", "function toArray(obj) {\n\t return isArray(obj) ? obj : [obj];\n\t }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
stop function stop and clear watch
function stop() { clearInterval(watch); }
[ "stopWatch() {\n\t\tthis.watch.toggle(false);\n\t}", "stop() {\n // Przypisz flage running aby zatrzymac stoper\n this.running = false\n // Wyczysc interwal odwolujac sie do parametru watch\n clearInterval( this.watch )\n }", "function stopWatching() {\n\t\tif(watchID) geo.clearWatch(watchID);\n\t\twatchID = null;\n\t}", "stop() {\r\n this._stopTime = Date.now();\r\n }", "stop () {\n if (this._isWatching) {\n if (this._useWatchFile) {\n fs.unwatchFile(this._path, this._watchFunction);\n } else {\n this._watchObj.close();\n this._watchObj = null;\n }\n\n this._isWatching = false;\n }\n }", "stop() {\n this.clickStop();\n clearInterval(this.watch);\n }", "function stopWatch() {\n \n \t//EJERCICIO 1 (4)\n if (watchID) {\n navigator.compass.clearWatch(watchID);\n watchID = null;\n }\n }", "function stopWatch() {\n if (watchID) {\n navigator.compass.clearWatch(watchID);\n watchID = null;\n }\n }", "stopWatching() {\n if (!this.watcher) { return; }\n\n this.watcher.close();\n }", "function stopWatch() \n{\n if (watchIDC) \n {\n navigator.compass.clearWatch(watchID);\n watchIDC = null;\n }\n}", "function stopWatch() {\n if (watchID) {\n navigator.compass.clearWatch(watchID);\n watchID = null;\n }\n}", "stop() {\n //TODO: unsubscribe all\n }", "stop() {\n\t\tthis._stopAtNextUpdate = true;\n\t}", "function stopWatch() {\n if (watchID) {\n navigator.accelerometer.clearWatch(watchID);\n watchID = null;\n }\n \n\tdrawing = false;\n}", "function stop() {\n clearTimeout(t);\n }", "function stop() {\n $timeout.cancel(nextComoboTimer);\n $timeout.cancel(startTimeout);\n hitCallerService.stop();\n stopped = true;\n }", "function stop() {\n clockRun = false;\n clearInterval(clockControl);\n }", "_onStop() {\n\t\tthis._isWatching = false\n\t\tthis.dispatchEvent(new CustomEvent(ARKitWrapper.STOP_EVENT_NAME, {\n\t\t\tsource: this\n\t\t}))\n\t}", "stop () {\n this._watching = false;\n this._source.removeListener(this._onData);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updating the number of peers and getting stream from the peer on connecting to other peers Should be updated such that the current peer doesn't have his/her user media appended as a video element in the current page
function addPeer(){ var peerMediaElements = document.getElementById("peer-media-banner"); // peerNumUpdated = parseInt(peerNum)+1; var peerMediaDiv = document.createElement("div"); var peerMediaVideo = document.createElement("video"); peerMediaVideo.setAttribute("class", "z-depth-5"); var peerMediaSource = document.createElement("source"); peerMediaVideo.setAttribute("height", "150"); // peerMediaSource.src = "../bbb-cbr-1300-frag.mp4"; // to be updated with UserMedia peerMediaSource.id = "user-media-"+peerID; peerMediaVideo.appendChild(peerMediaSource); peerMediaDiv.setAttribute("class", "col s4"); peerMediaDiv.appendChild(peerMediaVideo); peerMediaElements.appendChild(peerMediaDiv); peersInRoom[peerNum].peerID = peerID; peerNum = peerNumUpdated; }
[ "function addPeer(){\n\tvar peerMediaElements = document.getElementById(\"peer-media-banner\");\n\t// peerNumUpdated = parseInt(peerNum)+1;\n\tvar peerMediaDiv = document.createElement(\"div\");\n\tvar peerMediaVideo = document.createElement(\"video\");\n\tpeerMediaVideo.setAttribute(\"class\", \"z-depth-5\");\n\tvar peerMediaSource = document.createElement(\"source\");\n\tpeerMediaVideo.setAttribute(\"height\", \"150\");\n\t// peerMediaSource.src = \"../bbb-cbr-1300-frag.mp4\"; // to be updated with UserMedia\n\tpeerMediaSource.id = \"user-media-\"+peerID;\n\tpeerMediaVideo.appendChild(peerMediaSource);\n\tpeerMediaDiv.setAttribute(\"class\", \"col s4\");\n\tpeerMediaDiv.appendChild(peerMediaVideo); \n\tpeerMediaElements.appendChild(peerMediaDiv);\n\tpeersInRoom[peerNum].peerID = peerID;\n\tpeerNum = peerNumUpdated;\n}", "function setupChannel(currentPeer){\n\tconsole.log(\"setup data channel\");\n\tpeerChannel[currentPeer].onopen = function(event){\n\t\tconsole.log(currentPeer);\n\t\tconsole.log(peerChannel[currentPeer]);\n\t\t// peerConnections.push(currentPeer); // updating the peer list\n\t\tconsole.log(peerConnections);\n\t\tconsole.log(peerNum.innerText);\n\t\tvar peerNumUpdated = 1+peerConnections.length;\n\t\tpeerNum.innerHTML = \"<b>\"+peerNumUpdated.toString()+\"</b>\";\n\t\tconsole.log(peerNum.innerText);\n\t};\n\n\tpeerChannel[currentPeer].onmessage = function (event) {\n\t\tconsole.log(\"message received\");\n\t\tif(typeof event.data == \"string\"){\n\t\t\tvar message = JSON.parse(event.data);\n\t\t\tconsole.log(message);\n\t\t\tif (message.event == \"pause\"){\n\t\t\t\tvid.pause();\n\t\t\t\tMaterialize.toast(message.peerID+\" paused the video\", 2000);\n\t\t\t}else{\n\t\t\t\tvid.play();\n\t\t\t\tMaterialize.toast(message.peerID+\" played the video\", 2000);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tvar streamReceived = event.data;\n\t\tconsole.log(streamReceived);\n\t\tvar streamSender = new Uint8Array(streamReceived.slice(0,1))[0];\n\t\tconsole.log(streamSender);\n\t\tvar chunkNum = new Uint16Array(streamReceived.slice(1,3));\n\t\tvar chunkBuffer = new Uint8Array(streamReceived.slice(3));\n\t\tconsole.log(chunkBuffer.byteLength);\n\t\tconsole.log(chunkNum);\n\t\tvar senderID = new Uint8Array(1);\n\t\tsenderID[0] = peerIDServer;\n\t\tconsole.log(peerIDServer);\n\t\tconsole.log(chunkNum[0]);\n\t\treadyChunk(chunkBuffer, chunkNum[0]);\n\t\tgotChunk(chunkBuffer ,chunkNum[0]);\n\t\t// var newStreamMessage = new Uint8Array(chunkBuffer.byteLength + chunkNum.byteLength + senderID.byteLength);\n\n\t\t// console.log(senderID.byteLength);\n\t\t// newStreamMessage.set(senderID);\n\t\t// console.log(1);\n\t\t// newStreamMessage.set(chunkNum);\n\t\t// console.log(2);\n\t\t// newStreamMessage.set(chunkBuffer);\n\t\t// console.log(3);\n\n\t\t// sendChunk(newStreamMessage);\n\t}\n}", "function cameraLink() \n{\n function reCount() {\n if (!isConnected()) return\n var participants = connection.getAllParticipants()\n var count = 0\n $.each(participants, (i,participantId)=>{\n if (connection.peers[participantId] \n && connection.peers[participantId].activeRoom == activeRoomID ) count += 1\n })\n if (refreshPeersCount(count)) \n toastr.info(count+' viewers', 'Peers count', {timeOut: 1000})\n connection.socket.emit('peers-info', {'cmd': 'room-count', 'roomid': activeRoomID, 'count': count});\n }\n\n if (connection.socket) {\n connection.socket.off('peers-info')\n connection.socket.on('peers-info', (data) => \n { \n if (data.cmd == 'stream-join') \n {\n if (connection.peers[data.userid]) {\n connection.peers[data.userid].activeRoom = data.room\n console.log(data.userid, \"joined room\", data.room)\n }\n reCount()\n }\n });\n }\n\n heartbeatInterval = setInterval(() => {\n connection.socket.emit('peers-info', {'cmd': 'heartbeat', 'roomid': activeRoomID});\n }, 2000)\n \n countInterval = setInterval(reCount, 5000) // also detect wild exit (does not triggers stream-join)\n}", "function connectToNewUser(userId, stream){\nconst call = myPeer.call(userId, stream)\nconst video = document.createElement('video')\ncall.on('stream', userVideoStream => {\n addVideoStream(video, userVideoStream)\n})\n//removing video after leaving\ncall.on('close', () =>{\n video.remove()\n})\n\n//connect user id to call\npeers[userId] = call\n}", "function renderRemote(id, stream) {\n var activeStreams;\n\n // create the peer videos list\n peerMedia[id] = peerMedia[id] || [];\n\n activeStreams = Object.keys(peerMedia).filter(function(id) {\n return peerMedia[id];\n }).length;\n\n console.log('current active stream count = ' + activeStreams);\n peerMedia[id] = peerMedia[id].concat(media(stream).render(remotes[activeStreams % 2]));\n}", "function connectToNewParticipant(userLink, stream) {\r\n//users can answer calls made to them\r\nconst call = peer.call(userLink, stream)\r\n// A video element is created for new partcipant\r\nconst video = document.createElement('video')\r\n//To recieve participants video stream\r\ncall.on('stream', userVideoStream => {\r\n //Adding the participants video \r\n addVideo(video, userVideoStream)\r\n})\r\n//Closing the call and removing the video stream\r\ncall.on('close', () => {\r\n video.remove()\r\n})\r\n\r\npeers[userLink] = call\r\n}", "set stream(stream) {\nthis._stream = stream;\n\nvar users = Users.getRemoteUsers();\nfor(var i=0; i<users.length; i++){\nusers[i].peerConnection.addStream(stream);\ntrace(\"Users\", \"Added local stream to peerConnection\", stream);\n}\n}", "function connecttonewuser(userid, stream)\n{\n const call= mypeer.call(userid,stream)\n const video = document.createElement('video')\n call.on('stream', uservideostream =>{\n addvideostream(video,uservideostream)\n })\n call.on('close', ()=>{\n video.remove()\n })\n\n peers[userid] = call;\n}", "function connetToNewUser(userID, stream) {\n //call \n const call = myPeer.call(userID, stream)\n // video element\n const video = document.createElement('video')\n // call return video stream of connected user\n\n call.on('stream', userVideoStream => {\n // pass user video to add on other user side\n addVideoStream(video, userVideoStream)\n })\n // when user disconnect call\n call.on('close', () => {\n video.remove()\n })\n // add all connected user to peers \n peers[userID] = call\n}", "function updateVolumeOfPeers() {\n\tfor (var i = 0; i < peer_client_ids.length; i++) {\n\t\tvar id = peer_client_ids[i];\n\t\tif (id != peer_id) {\n\t\t\tvar curr_conn = peer_connections[id];\n\t\t\t//curr_conn.send(JSON.stringify(saved_clients));\n\t\t}\n\t}\n}", "function connectToNewUser(userId, stream) {\n const call = myPeer.call(userId, stream)\n const video = document.createElement('video')\n video.classList.add(\"video\");\n \n call.on('stream', userVideoStream => {\n addVideoStream(video, userVideoStream)\n })\n call.on('close', () => {\n video.remove()\n })\n\n peers[userId] = call\n}", "function gotRemoteStream(event){\n\tconsole.log(event.track.kind);\n\tconsole.log(event.track.id);\n\tvar peerMediaVideo;\n\t// Removing the new temporary div(if made) made during setting up data channel\n\n\t// var peerMediaElements = document.getElementById(\"peer-media-banner\");\n\t// var peerMediaDiv = document.createElement(\"div\");\n\t// peerMediaVideo = document.createElement(\"video\");\n\t// peerMediaVideo.autoplay = true;\n\t// peerMediaVideo.setAttribute(\"class\", \"z-depth-5\");\n\t// peerMediaVideo.setAttribute(\"height\", \"150\");\n\t// peerMediaVideo.id = \"user-media-\"+currentPeer;\n\t// peerMediaDiv.setAttribute(\"class\", \"col s4\");\n\t// peerMediaDiv.appendChild(peerMediaVideo);\n\t// peerMediaElements.appendChild(peerMediaDiv);\n\t// peerMediaVideo.srcObject = event.streams[0];\n\n\tif(event.track.kind == \"audio\"){ // To avoid making two separate elements\n\t\ttry{\n\t\t\tconsole.log(\"removing\");\n\t\t\tpeerMediaVideo = document.getElementById(\"user-media-\"+currentPeer);\n\t\t\tconsole.log(peerMediaVideo);\n\t\t\tvar peerMediaElements = document.getElementById(\"peer-media-banner\");\n\t\t\tpeerMediaVideo.parentNode.parentNode.removeChild(peerMediaVideo.parentNode);\n\t\t}\n\t\tcatch(e){\n\t\t\tconsole.log(e);\n\t\t\tconsole.log(\"No pre existing element\");\n\t\t}\n\t\tvar peerMediaElements = document.getElementById(\"peer-media-banner\");\n\t\tvar peerMediaDiv = document.createElement(\"div\");\n\t\tpeerMediaVideo = document.createElement(\"video\");\n\t\tpeerMediaVideo.autoplay = true;\n\t\tpeerMediaVideo.setAttribute(\"class\", \"z-depth-5\");\n\t\tpeerMediaVideo.setAttribute(\"height\", \"150\");\n\t\tpeerMediaVideo.id = \"user-media-\"+currentPeer;\n\t\tpeerMediaDiv.setAttribute(\"class\", \"col s4\");\n\t\tpeerMediaDiv.appendChild(peerMediaVideo);\n\t\tpeerMediaElements.appendChild(peerMediaDiv);\n\t}else{\n\t\tvar peerMediaVideo = document.getElementById(\"user-media-\"+currentPeer);\n\t\twebcamStreams[currentPeer] = event.streams[0];\n\t\tconsole.log(peerMediaVideo);\n\t\tpeerMediaVideo.autoplay = true;\n\t\tpeerMediaVideo.srcObject = event.streams[0];\n\t}\n}", "startStreaming(\n magnetURI,\n currPlayer,\n nextPlayer,\n firstIteration,\n isPlay1Playing,\n isPlay2Playing,\n prevMagnetURI,\n renderTo) {\n\n const $play1 = this.$play1;\n const $play2 = this.$play2;\n const $play3 = this.$play3;\n\n let total = this.total;\n\n this.torrentInfo[firstIteration] += 1;\n\n let first = this.torrentInfo[firstIteration]\n\n if (!isPlay1Playing) {\n console.log('play1 playing')\n this.torrentInfo['isPlay1Playing'] = true;\n } else if (!isPlay2Playing) {\n console.log('play2 playing')\n this.torrentInfo['isPlay2Playing'] = true;\n } else {\n console.log('play3 playing')\n this.torrentInfo['isPlay1Playing'] = false;\n this.torrentInfo['isPlay2Playing'] = false;\n }\n\n // removes torrent \n if (this.torrentInfo[prevMagnetURI] !== 0) {\n\n // appends total uploaded to the value\n total['uploaded'] += this.client.get(this.torrentInfo[prevMagnetURI]).uploaded;\n\n this.client.remove(this.torrentInfo[prevMagnetURI], () => {\n console.log('Magnet Removed')\n })\n }\n\n\n this.torrentInfo[prevMagnetURI] = magnetURI;\n\n this.client.add(magnetURI, function (torrent) {\n /* Look for the file that ends in .webm and render it, in the future we can\n * add additional file types for scaling. E.g other video formats or even VR!\n */\n let file = torrent.files.find(function (file) {\n return file.name.endsWith('.webm')\n })\n\n // Stream the file in the browser\n if (first === 1) {\n window.setTimeout(() => file.renderTo(renderTo, { autoplay: true }), 7000);\n } else {\n file.renderTo(renderTo, { autoplay: false })\n }\n\n // listens for when torrents are done and appends total downloaded to menu\n torrent.on('done', function () {\n total['downloaded'] += torrent.downloaded;\n })\n\n // Trigger statistics refresh\n // setInterval(onProgress(torrent), 500);\n })\n\n // listen to when video ends, immediately play the other video\n currPlayer.onended = function () {\n currPlayer.pause();\n\n nextPlayer.play();\n\n nextPlayer.removeAttribute('hidden');\n\n currPlayer.setAttribute('hidden', true);\n };\n }", "function handleAddStream(data) {\n console.log(\"got stream from peer\");\n console.log(\"peer stream\", data.stream)\n console.log(\"my stream\", myStream)\n const peerStream = document.getElementById(\"peerFace\");\n peerStream.srcObject = data.stream;\n}", "connectToPeers() {\n peers.forEach((peer) => {\n const socket = new WebSocket(peer);\n socket.id = uuidv1();\n socket.on('open', () => this.connectSocket(socket));\n });\n }", "function updateViewerCount(peer){\n\tpresenter[peer].ws.send(JSON.stringify({\n\t\tid : 'updateViewers',\n\t\tlength: Object.keys(viewers[peer]).length\n\t}));\n\n\t//The timeout is to prevent race conditions of closing multiple sessions at the same time\n\tsetTimeout(function(){\n\t\tfor (var i in viewers[peer]) {\n\t\t\tvar viewer = viewers[peer][i];\n\t\t\tif (viewer.ws) {\n\t\t\t\tviewer.ws.send(JSON.stringify({\n\t\t\t\t\tid : 'updateViewers',\n\t\t\t\t\tlength: Object.keys(viewers[peer]).length\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t}, 300);\n}", "connectToPeers() {\n peers.forEach(peer => {\n\n //create new socket using particular peer \n const socket = new Websocket(peer);\n\n //on successfully opening a socket connection\n socket.on('open', () => {\n //handle connection\n this.connectSocket(socket);\n })\n })\n }", "function renderPeers(peers) {\n peersContainer.innerHTML = \"\";\n\n if (!peers) {\n // this allows us to make peer list an optional argument\n peers = hmsStore.getState(selectPeers);\n }\n\n peers.forEach((peer) => {\n if (peer.videoTrack) {\n const video = h(\"video\", {\n class: \"peer-video\" + (peer.isLocal ? \" local\" : \"\"),\n autoplay: true, // if video doesn't play we'll see a blank tile\n muted: true,\n playsinline: true\n });\n\n // this method takes a track ID and attaches that video track to a given\n // <video> element\n hmsActions.attachVideo(peer.videoTrack, video);\n\n const peerContainer = h(\n \"div\",\n {\n class: \"peer-container\"\n },\n video,\n h(\n \"div\",\n {\n class: \"peer-name\"\n },\n peer.name + (peer.isLocal ? \" (You)\" : \"\")\n )\n );\n\n peersContainer.append(peerContainer);\n }\n });\n}", "resetPeerConnection () {\n this.pc1.close();\n this.pc1 = null;\n this.ifShareScreen = false;\n if(this.pc) {\n this.pc.close();\n this.pc = null;\n }\n this.createRTCPeerConnectionForVideoCall()\n this.localStream.getTracks().forEach((track) => {\n this.pc.addTrack(track, this.localStream);\n })\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
backup file fail function
function failFileBackup(error) { var backupfailed = $.t('backupfailed'); console.error("PhoneGap Plugin: FileSystem: Message: Backup - file does not exists, isn't writeable or isn't readable. Error code: " + error.code); buttonStateBackRest("enable"); toast(backupfailed, 'short'); }
[ "function gameBackupPerform(){\r\n\t//Check if the backup exists\r\n\tfs.stat(gameLocation + gameBackupName, function(err, stat){\r\n\t\tif(err != null){\r\n\t\t\t//Perform the backup if the file does not exist\r\n\t\t\tfs.createReadStream(gameLocation + gameOriginalName).pipe(\r\n\t\t\t\tfs.createWriteStream(gameLocation + gameBackupName)\r\n\t\t\t);\r\n\t\t}\r\n\t});\r\n}", "function write_file_bak(file, data)\n{\n if (options['no-backup']) {\n write_file(file, data);\n return;\n }\n var old_data;\n try {old_data = read_file(file);}\n catch (e) {\n if (e.name != \"Error\" || e.message.substring(0,29) != \"read_file: error opening file\")\n throw e;\n }\n\n if (old_data)\n {\n if (old_data != data) {\n print(\"File \" + file + \" changed. saving backup.\");\n write_file(file + \"~\", old_data);\n write_file(file, data);\n }\n }\n else\n write_file(file, data);\n}", "backupConfig() {\n let file = fs_1.default.readFileSync(this.configFilePath);\n try {\n fs_1.default.writeFile(this.configFilePath + '.bak', file, 'utf-8', (err) => {\n if (err) {\n this.log.warn(\"Error making backup of config\");\n }\n else {\n this.log.debug(\"Made backup of config.json\");\n }\n });\n }\n catch (e) {\n return false;\n }\n }", "save() {\n let backupName = path.basename(this.filePath) + '.' + Date.now() + '.back'; \n let backupPath = path.join(path.dirname(this.filePath), backupName);\n\n fs.copyFileSync(this.filePath, backupPath);\n console.log('Save backed-up to \"' + backupPath + '\"');\n\n fs.writeFileSync(this.filePath, this.fileBuffer);\n }", "function failFileRestoreWall(error) {\n\tvar restorefavwallsfailed = $.t('restorefavwallsfailed');\n\twindow.wallRestoreFailed = true;\n\tconsole.error(\"PhoneGap Plugin: FileSystem: Message: Restore - file does not exists, isn't writeable or isn't readable. Error code: \" + error.code);\n\tbuttonStateBackRest(\"enable\");\n\ttoast(restorefavwallsfailed, 'short');\n}", "async backup() {\n const backupPath = this.filepath + `.backup`\n await fsprom.copyFile(this.filepath, backupPath)\n }", "function failFileRestoreRing(error) {\n\tvar restorefavringsfailed = $.t('restorefavringsfailed');\n\twindow.ringRestoreFailed = true;\n\tconsole.error(\"PhoneGap Plugin: FileSystem: Message: Restore - file does not exists, isn't writeable or isn't readable. Error code: \" + error.code);\n\tbuttonStateBackRest(\"enable\");\n\ttoast(restorefavringsfailed, 'short');\n}", "restoreBackupWaypointFile() {\n return new Promise((resolve, reject) => {\n try {\n // TODO - copied is always undefined?\n let copied = nova.fs.copy(\n this.waypointFilePath + \".bck\",\n this.waypointFilePath\n )\n resolve(true)\n } catch (_err) {\n log(\"STORAGE ERROR! Error 39\")\n log(_err)\n reject(_err)\n }\n })\n }", "backupWaypointFile() {\n return new Promise((resolve, reject) => {\n try {\n this.clearBackupWaypointFile()\n .then((message) => {\n // TODO - copied is always undefined?\n let copied = nova.fs.copy(\n this.waypointFilePath,\n this.waypointFilePath + \".bck\"\n )\n resolve(true)\n })\n .catch((_err) => {\n log(\"STORAGE ERROR! Error 40\")\n log(_err)\n reject(_err)\n })\n } catch (_err) {\n log(\"STORAGE ERROR! Error 41\")\n log(_err)\n reject(_err)\n }\n })\n }", "function backupDatabase() {\n // read current database\n fs.readFile(__dirname + \"/datastores/\" + db.getData(\"data_file\")[\"data_file\"] + \".json\",function(err,data) {\n if(err)\n console.log(err)\n else {\n // if there are no errors, create a new database with a date identifier appended to the file name\n var fname = \"feynmanDatabase-\" + moment().format(\"MM-DD-YY\")\n fs.writeFile(__dirname + \"/datastores/\" + fname + \".json\", data, function(erro) {\n if(erro)\n console.log(\"error : \" + erro)\n else\n console.log(\"success\")\n\n // update and load the database\n var main_db = new JsonDB(__dirname + \"/datastores/feynmanDatabase\", true, false)\n main_db.push(\"/data_file\", fname)\n db = new JsonDB(__dirname + \"/datastores/\" + fname, true, false)\n db.push(\"/data_file\", fname)\n console.log(fname)\n })\n }\n })\n}", "create_backup(file_path) {\r\n return this.call(\"/create_backup\", {file_path});\r\n }", "function MP3_Backup(){\r\n\tfs.writeFile(\"backup.ini\",JSON.stringify(MP3), function(err) {\r\n\t if(err) {\r\n\t return console.log(err);\r\n\t }\r\n\t});\r\n\tfs.writeFile(\"backup2.ini\",JSON.stringify(MP3), function(err) {\r\n\t if(err) {\r\n\t return console.log(err);\r\n\t }\r\n\t});\r\n}", "function createBackup (original, next) {\n fs.stat(backupFile, function (err, stat) {\n if (err) {\n fs.rename(originalFile, backupFile, function (err) {\n if (err) {\n return next('error: '.red + ' backup failed'.white);\n }\n next(null, original);\n });\n } else {\n next(null, original);\n }\n });\n}", "async backup() {\r\n execute(`echo 'y' | ${this.valheimServerScript} backup`, (err, stdout, stderr) => {\r\n if (err) {\r\n this.logger.log(err, 'error');\r\n } else {\r\n this.logger.log(stdout);\r\n this.logger.log(stderr, 'error');\r\n }\r\n });\r\n }", "async _automatedBackup(file) {\n\t\tconst fullpath = path.join(this.dirname, file);\n\n\t\tfs.access(fullpath, (error) => {\n\t\t\tif (error) return console.error(`Error while creating a new backup.\\n${fullpath}`);\n\n\t\t\tconst newPath = path.join('Backups/');\n\t\t\tthis._createDirIfNotExists(newPath);\n\n\t\t\tlet newFileLocation = `${newPath}Backup_${file}`;\n\t\t\tif (!fs.existsSync(newFileLocation)) {\n\t\t\t\tif (this.overwrite === true) {\n\t\t\t\t\tfs.copyFileSync(fullpath, newFileLocation);\n\t\t\t\t} else {\n\t\t\t\t\tfs.readdir(newPath, (error, files) => {\n\t\t\t\t\t\tif (error) throw new Error;\n\t\t\t\t\t\tfor (let i = 0; i < files.length; i++) {\n\t\t\t\t\t\t\tnewFileLocation = `${newPath}${i}_Backup_${file}`;\n\n\t\t\t\t\t\t\tfs.copyFileSync(file, newFileLocation);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (this.overwrite === true) {\n\t\t\t\t\tfs.copyFileSync(file, newFileLocation);\n\t\t\t\t} else {\n\t\t\t\t\tfs.readdir(newPath, (error, files) => {\n\t\t\t\t\t\tif (error) throw new Error;\n\t\t\t\t\t\tfor (let i = 0; i < files.length; i++) {\n\t\t\t\t\t\t\tnewFileLocation = `${newPath}${i}_Backup_${file}`;\n\n\t\t\t\t\t\t\tfs.copyFileSync(file, newFileLocation);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\t\n\t\t\t}\n\t\t});\n\t}", "function backup(){\n var output = fs.createWriteStream(backupPath + '/dataBackUp.zip');\n var archive = archiver('zip', {\n zlib: { level: 9 } // Sets the compression level.\n });\n output.on('close', function() {\n console.log(archive.pointer() + ' total bytes');\n console.log('archiver has been finalized and the output file descriptor has closed.');\n });\n output.on('end', function() {\n console.log('Data has been drained');\n });\n archive.on('error', function(err) {\n throw err;\n });\n archive.pipe(output);\n archive.directory(path, 'backUpData');\n archive.finalize();\n}", "function writeFailure() {\n}", "function backupDb() {\n try {\n fs.copyFileSync('./scandb.sqlite3', './scandb.sqlite3.bak' + (Date.now()));\n } catch (ex) {\n console.error(ex);\n throw new Error('Backup of database failed');\n }\n}", "function backupJson() {\n // Copy file\n fs.copyFile('./content/StaffRoomPres/StaffRoomPres.json', './content/StaffRoomPres/StaffRoomPresBackup.json', (err) => {\n if (err) {\n console.log(err); // console log error if failed\n } else {\n console.log('file backed up'); // console log if successful\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns a subclass of specified Set class and overrides the add() method of that class to apply the specified filter.
function filteredSetSubclass(superclass, filter) { var constructor = function() { // The subclass constructor superclass.apply(this, arguments); // Chains to the superclass }; var proto = constructor.prototype = inherit(superclass.prototype); proto.constructor = constructor; proto.add = function() { // Apply the filter to all arguments before adding any for(var i = 0; i < arguments.length; i++) { var v = arguments[i]; if (!filter(v)) throw("value " + v + " rejected by filter"); } // Chain to our superclass add implementation superclass.prototype.add.apply(this, arguments); }; return constructor; }
[ "function filterSetSubclass(superclass, filter) {\r\n\tvar constructor = function() {\r\n\t\tsuperclass.apply(this, arguments);\r\n\t};\r\n\tvar proto = constructor.prototype = inherit(superclass.prototype);\r\n\tproto.constructor = constructor;\r\n\tproto.add = function() {\r\n\t\t// Apply the filter to all arguments before adding any\r\n\t\tfor ( var i = 0; i < arguments.length; i++) {\r\n\t\t\tvar v = arguments[i];\r\n\t\t\tif (!filter(v))\r\n\t\t\t\tthrow (\"value \" + v + \" rejected by filter\");\r\n\t\t}\r\n\t\t// Chain to our superclass add implementation\r\n\t\tsuperclass.prototype.add.apply(this, arguments);\r\n\t};\r\n\treturn constructor;\r\n}", "function filteredSetSubclass(superclass, filter) {\n var constructor = function () {\n superclass.apply(this, arguments);\n };\n var proto = (constructor.prototype = inherit(superclass.prototype));\n proto.constructor = constructor;\n proto.add = function () {\n // Apply the filter to all arguments before adding any\n for (var i = 0; i < arguments.length; i++) {\n var v = arguments[i];\n if (!filter(v)) throw `value ${v} rejected by filter`;\n }\n // chain to our superclass add implementation.\n superclass.prototype.add.apply(this, arguments);\n };\n return constructor;\n}", "filterToInstanceSet(callback) {\n return new InstanceSet(this.classModel, [...this].filter(callback));\n }", "filterForInstancesInThisCollection() {\n if (this.classModel.abstract && !this.classModel.discriminated())\n return new InstanceSet(this.classModel);\n\n return this.filterToInstanceSet(instance => \n instance.classModel.collection === this.classModel.collection\n );\n }", "function filterAddFilter(filter)\r\n{\r\n this.FilterDefs.push(filter);\r\n return this;\r\n}", "function test() {\n var obj = {};\n class S extends Set {}\n var set = new S();\n\n set.add(123);\n set.add(123);\n\n return set.has(123);\n}", "addToSet(set, item) {\n if (!set.includes(item)) {\n set.push(item);\n }\n return set;\n }", "intersection(set) {\n let intersectionArray = set.toArray().filter((item) => (this.contains(item)));\n return new this.constructor(...intersectionArray);\n }", "add(filter) {\n const subscription = filter.changes.subscribe(() => this.resetPageAndEmitFilterChange([filter]));\n let hasUnregistered = false;\n const registered = new RegisteredFilter(filter, () => {\n if (hasUnregistered) {\n return;\n }\n subscription.unsubscribe();\n const matchIndex = this._all.findIndex(item => item.filter === filter);\n if (matchIndex >= 0) {\n this._all.splice(matchIndex, 1);\n }\n if (filter.isActive()) {\n this.resetPageAndEmitFilterChange([]);\n }\n hasUnregistered = true;\n });\n this._all.push(registered);\n if (filter.isActive()) {\n this.resetPageAndEmitFilterChange([filter]);\n }\n return registered;\n }", "function wrap(set) {\n return new NativeSet(set);\n }", "mapToInstanceSet(callback) {\n return new InstanceSet(this.classModel, [...this].map(callback));\n }", "function MySet() {\n var collection = [];\n this.has= function(element){\n return (collection.indexOf(element)!==-1);\n //if it doesn't return -1 its true\n }\n this.values = function(){\n return collection;\n }\n this.add = function(element){\n if(!this.has(element)){\n collection.push(element);\n return true;\n }\n //returns false if couldn't push\n return false;\n }\n //in es6 SET built in class, set is delete\n this.remove = function(element){\n if(this.has(element)){\n let index = collection.indexOf(element);\n collection.splice(index,1);\n return true;\n }\n return false;\n }\n this.size = function(){\n return collection.length;\n }\n this.union = function(otherSet){\n var unionSet = new mySet();\n var firstSet = this.values();\n var secondSet = otherSet.values();\n firstSet.forEach(el => unionSet.add(el));\n secondSet.forEach(el => unionSet.add(el));\n return unionSet;\n }\n this.intersection = function(otherSet){\n var intersectionSet = new mySet();\n var firstSet = this.values();\n firstSet.forEach(el => {\n if(otherSet.has(el)){\n intersectionSet.add(el);\n }\n });\n return intersectionSet;\n }\n this.difference = function(otherSet){\n var differenceSet = new mySet();\n var firstSet = this.values();\n firstSet.forEach(el => {\n if(!otherSet.has(el)){\n differenceSet.add(el);\n }\n });\n return differenceSet;\n }\n //tests to see if the current set is a subset of another set\n this.subset = function(otherSet){\n var firstSet = this.values();\n return firstSet.every(value=> otherSet.has(value));\n }\n}", "toSet() {\n return new Set(this._iterable);\n }", "union(set) {\n let unionArray = this.toArray().concat(set.toArray());\n return new AbstractSet(...unionArray);\n }", "function NonNullSet() {\n // Just chain to out superclass.\n // Invoke the superclass constructor as an ordinary function to initialize\n // the object that has been created by this constructor invocation.\n Set.apply(this, arguments);\n}", "addFilter(filter) {\n this.addFilterAt(filter, this._filters.length)\n }", "function mySet() {\n // the var collection will hold the set:\n var collection = [];\n \n // Returns true if element exists in collection already \n this.has = function(element) {\n return (collection.indexOf(element) !== -1)\n };\n \n // Returns all the values in the set\n this.values = function() {\n return collection;\n };\n \n // Adds an element to the set\n this.add = function(element) {\n if (!this.has(element)) {\n collection.push(element);\n return true;\n }\n return false;\n };\n \n // Removes an element from the set\n this.remove = function(element) {\n if (this.has(element)) {\n index = collection.indexOf(element);\n collection.splice(index, 1);\n return true;\n } else {\n return false;\n }\n };\n \n // this method will return the size of the collection\n this.size = function() {\n return collection.length;\n };\n \n // NON ES6 METHODS: \n // this method will return the union of two sets\n this.union = function(otherSet) {\n var unionSet = new mySet();\n var firstSet = this.value();\n var secondSet = otherSet.values();\n firstSet.forEach(function(e) {\n unionSet.add(e)\n });\n secondSet.forEach(function(e) {\n // NOTE: Remember that the add function checks for duplicates!\n unionSet.add(e);\n });\n return unionSet;\n };\n \n // Returns the intersection of two sets as a new set\n this.intersection = function(otherSet) {\n var intersectionSet = new mySet();\n var firstSet = this.values();\n \n firstSet.forEach(function(e) {\n if (otherSet.has(e)) {\n intersectionSet.add(e);\n }\n });\n \n return intersectionSet;\n }\n \n // Returns the difference of two sets as a new set\n this.difference = function (otherSet) {\n var differenceSet = new mySet();\n var firstSet = this.values();\n \n firstSet.forEach(function(e) {\n if (!otherSet.has(e)) {\n differenceSet.add(e);\n }\n });\n \n return differenceSet;\n };\n \n // Returns if the set is a subset of a different set\n this.subset = function(otherSet) {\n var firstSet = this.values;\n firstSet.every(function(value) {\n return otherSet.has(value);\n });\n };\n}", "static newFilter() {\n return new ODataFilter();\n }", "function PackagePrefilter () {\n /* inheritance */\n this.super();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads xlsx file and gets values from each cell
read(file) { var workbook = XLSX.readFile(file); var sheet_name_list = workbook.SheetNames; var data = {}; var letters = []; var moduleShortNameArray = []; sheet_name_list.forEach(function(y) { var worksheet = workbook.Sheets[y]; var headers = []; var column = 0; var enc_addr = XLSX.utils.encode_cell; var dec_range = XLSX.utils.decode_range; var range = dec_range(worksheet['!ref']); while (worksheet[enc_addr({c: column, r: 0})]) { headers.push((worksheet[enc_addr({c: column, r: 0})].v).replace(/ +/g, "")); column++ } for (var R = range.s.r +1; R <= range.e.r; ++R) { var record = []; data['row'+R] = {}; for (var C = range.s.c; C <= headers.length-1; ++C) { let cell_address = enc_addr({c: C, r: R}); let cell = worksheet[cell_address]; if (cell && typeof cell.v !== 'undefined') { var header = headers[R-1]; var value = cell.v; record.push(value); headers.map((header, index) => { data["row"+R][header] = record[index]; }) } } moduleShortNameArray.push(record[0].split('_').pop()); letters.push(record[0].charAt(0)); } }); this.uniqueRows = this.reducerFilter([], letters); this.uniqueModuleShortName = this.reducerFilter([], moduleShortNameArray); this.filterData(data); }
[ "getData(filepath, { sheetId = 0, startRow = 1 }) {\r\n let res = []\r\n let rowIndex = startRow + 1\r\n try {\r\n let workbook = xlsxReader.readFile(filepath)\r\n let worksheet = workbook.Sheets[workbook.SheetNames[sheetId]]\r\n // let ref = worksheet[\"!ref\"].split(':')\r\n // let len = parseInt(ref[1].replace(/[^\\d]/ig, ''))\r\n for (var i in worksheet) {\r\n if (i.indexOf('!') === -1) {\r\n let col = i.replace(/\\d/ig, '') + String(startRow)\r\n let row = parseInt(i.replace(/[^\\d]/ig, ''))\r\n if (row > startRow) {\r\n if (!res[row - rowIndex]) {\r\n res[row - rowIndex] = []\r\n }\r\n res[row - rowIndex].push({\r\n title: worksheet[col] ? worksheet[col].v : col,\r\n value: worksheet[i].v,\r\n origin: worksheet[i],\r\n })\r\n }\r\n }\r\n }\r\n return res\r\n } catch (e) {\r\n logger.error('getData error:' + e)\r\n return false\r\n }\r\n }", "function parseXSLX(path) {\n // Create an instance of workbook to load data into\n const workbook = new exceljs.Workbook();\n // Read the file\n workbook.xlsx.readFile(path)\n .then(function(book) {\n // Get reference to first worksheet\n var id_nums = [];\n const sheet = book.getWorksheet(1);\n // Log the values of first column \n id_nums = (sheet.getColumn(1).values);\n console.log(id_nums);\n });\n \n}", "static readData(filePath, sheetName, row, col) {\n let workBook = new excel.Workbook();\n return workBook.xlsx.readFile(filePath)\n .then(function() {\n //sheet obj\n let sheet = workBook.getWorksheet(sheetName);\n //row obj\n let rowObject = sheet.getRow(row);\n //cell obj\n let cellObject = rowObject.getCell(col);\n\n return cellObject.text;\n })\n }", "parseExcel()\n { \n console.log(\"parseEXCEL\");\n that = this;\n \n this.fileName = this.template.querySelector(\"input[type=file]\").files[0].name;\n var f = this.template.querySelector(\"input[type=file]\").files[0]\n var reader = new FileReader();\n reader.onload = function(e) {\n var data = new Uint8Array(e.target.result);\n var workbook = XLSX.read(data, {type: 'array'});\n\n var result = {};\n workbook.SheetNames.forEach(function(sheetName) {\n var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header:1,defval:\"\"});\n result = roa;\n });\n that.loadData(result);\n };\n\n reader.readAsArrayBuffer(f);\n \n }", "function readExcel() {\n return new Promise((resolve, reject) => {\n var workbook = new Excel.Workbook();\n workbook.xlsx.readFile(EXCEL_FILE).then(function() {\n var worksheet = workbook.getWorksheet(EXCEL_TAB);\n let tasks = [];\n worksheet.eachRow({ includeEmpty: false }, function(row, rowNumber) {\n if(rowNumber != 1) {\n tasks.push(row.values);\n }\n resolve(tasks);\n })\n })\n .catch(err => {\n console.error(err);\n reject(false);\n });\n })\n}", "function readAllCells() {\n\treturn new Promise(function(resolve, reject) {\n\t\tif(metaData._lastRowWritten < 2)\n\t\t\treturn resolve(cells);\n\t\tlet range = `Sheet1!A2:B${metaData._lastRowWritten}`;\n\t\tgapi.client.sheets.spreadsheets.values.get({ spreadsheetId: _sheetID, range: range})\n\t\t.then(function saveResult(result) {\n\t\t\tif(result && result.result.values) {\n\t\t\t\tcells = result.result.values;\n\t\t\t}\n\t\t\treturn resolve(cells);\n\t\t});\n\t});\n}", "function read_excel_file(filePath, callback){\n excelParser.parse({\n inFile: filePath,\n worksheet: 1,\n skipEmpty: false,\n },function(err, records){\n if (err) console.error(err);\n typeof callback === 'function' && callback(records);\n });\n}", "function sheetParse(number){\n console.log('Parsing xlsx ....');\n\n let worksheet = workbook.Sheets[sheetNamesList[number]];\n let data = [];\n\n for (cell in worksheet) {\n /* all keys that do not begin with \"!\" correspond to cell addresses */\n if(cell[0] === '!') continue;\n data.push(JSON.stringify(worksheet[cell].v));\n }\n\n // console.log(sheet_name_list[2] + \"!\" + z + \"=\" + JSON.stringify(worksheet[z].v));\n console.log('Parsing done!');\n return data;\n}", "static readDataProvider(filePath, sheetName, row, colName) {\n let workBook = new excel.Workbook();\n return workBook.xlsx.readFile(filePath)\n .then(function() {\n //sheet obj\n let sheet = workBook.getWorksheet(sheetName);\n //row obj\n let rowObject = sheet.getRow(row) + 2;\n //cell obj\n let cellObject = rowObject.getCell(col);\n\n return cellObject.text;\n })\n }", "function getSheetTargetData(sheet_name) {\n var wb = xlsx.readFile(path_target);\n var listSheetNames = wb.SheetNames;\n console.log('all sheetName is ...', listSheetNames);\n // list_sheet_name.forEach(function(sheet_name) {\n // get sheet \n var wsheet = wb.Sheets[sheet_name];\n // console.log('wsheet ...', wsheet);cls\n // get data 1.name 2.row and col\n var range_str = wsheet['!ref'];\n var cell_range = analysisCell(range_str);\n\n var col = 3; // row = 3\n for (var row = 0; row < cell_range.c; row++) {\n var xy = xlsx.utils.encode_cell({ r: row, c: col });\n // console.log('xy ...',xy);\n var cell = wsheet[xy];\n // console.log('cell row ...',cell)\n if (cell && cell.v) { // if have value than add to list\n var item_tar = { \"val\": cell.v, \"row\": row, \"col\": col };\n data_target.push(item_tar);\n }\n }\n}", "function ExcelData(ws) {\n var datas = xlsx.utils.sheet_to_json(ws);\n try {\n datas = datas.filter((item) => { return (item[\"Remark\"].toString().toUpperCase().trim() == \"DP\" || item[\"Remark\"].toString().toUpperCase().trim() == \"WD\"); });\n } catch (e) { \n throw { message: \"Invalid Value in Remark\" };\n }\n\n var dataTitle = Object.keys(datas[0]);\n if (!dataTitle.includes(\"No\") || !dataTitle.includes(\"CS\") || !dataTitle.includes(\"Acc\") || !dataTitle.includes(\"Nama\") || !dataTitle.includes(\"Username\") || !dataTitle.includes(\"Time\") || !dataTitle.includes(\"Remark\") || dataTitle.includes(\"__EMPTY_1\") || !matchBankTitle(dataTitle)) {\n throw { message: \"Invalid Data Format in Excell File \\nCheck the follow file in folder sample\" };\n }\n datas.map((data) => {\n if (data.CS) excelCss.push(data[\"CS\"].trim());\n if (data.Acc) excelAccs.push(data[\"Acc\"].trim());\n if (data.Username) excelUsers.push(data[\"Username\"].trim());\n });\n\n excelCss = UniqueArray(excelCss);\n excelAccs = UniqueArray(excelAccs);\n excelUsers = UniqueArray(excelUsers);\n\n return datas;\n}", "function getSheetValues() {\n var values = toWorksheet.getDataRange().getValues();\n return values;\n}", "function readExcelAsRows(path, sheetNumber) {\n var xls = new ActiveXObject('Excel.Application');\n xls.workbooks.open(path);\n\n var sheet = xls.sheets.item(sheetNumber || 1)\n\n var row = 1;\n var rows = [];\n var length;\n while (true) {\n var col = 1;\n\n if (sheet.cells(row,1).value == undefined)\n break;\n\n var currentRow = [];\n while (length != undefined ? col <= length : true) {\n var currentValue = sheet.cells(row,col).value;\n if (length == undefined && currentValue == undefined)\n break;\n\n currentRow.push(currentValue)\n col++;\n }\n\n if (length == undefined)\n length = currentRow.length\n\n rows.push(currentRow)\n row++;\n }\n\n return rows\n}", "function handleFile2(e) {\n\n currMthJson = [];\n var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer\n var f = document.getElementById(\"CurrFile\").files[0];\n var reader = new FileReader();\n reader.onload = function (e) {\n var data = e.target.result;\n if (!rABS) data = new Uint8Array(data);\n var workbook = XLSX.read(data, { type: rABS ? 'binary' : 'array' });\n \n var sheet_name = workbook.SheetNames[0];\n var worksheet = workbook.Sheets[sheet_name];\n var json_currentExcel = XLSX.utils.sheet_to_json(worksheet); \n currMthJson = json_currentExcel; \n };\n if (rABS) reader.readAsBinaryString(f);\n}", "function ReadDataFromExcel(FileName,DataHead,SheetName=null,Iteration=null)\n{\n var Excel, s;\n var returnValue\n Excel = Sys.OleObject(\"Excel.Application\")\n // Wait until Excel starts\n Excel.Visible = false\n Excel.Workbooks.Open(FileName)\n if(SheetName!=null)\n {\n var WorkSheetCount = Excel.ActiveWorkbook.Worksheets.Count\n for(let IterateSheets=0;IterateSheets<WorkSheetCount;IterateSheets++)\n {\n if(SheetName== Excel.ActiveWorkbook.Worksheets.Item(IterateSheets+1).Name)\n {\n Excel.ActiveWorkbook.Worksheets.Item(IterateSheets+1).Select(true) \n break\n }\n }\n }\n ColumnCnt= Excel.ActiveCell.CurrentRegion.Columns.Count\n var j=-1\n for (let i = 1;i<=ColumnCnt; i++)\n {\n if(Excel.ActiveSheet.Cells.Item(1,i).Value2==DataHead)\n {\n j=i\n break\n }\n }\n if(Iteration==null)\n {\n returnValue = Excel.ActiveSheet.Cells.Item((Project.TestItems.Current.Iteration+1),j).Value2\n }\n else\n {\n returnValue = Excel.ActiveSheet.Cells.Item((Iteration+2),j).Value2\n }\n \n Excel.ActiveWorkbook.Close()\n Excel =null\n return returnValue;\n}", "function read_row_values(row, worksheet) {\n var row_array = [];\n var row_ref = parseInt(row);\n var range = XLSX.utils.decode_range(worksheet['!ref']); // get the range\n for(var C = range.s.c; C <= range.e.c; ++C) {\n var cellref = XLSX.utils.encode_cell({c:C, r:row_ref});\n if(!worksheet[cellref]) continue; // if cell doesn't exist, move on\n var cell = worksheet[cellref];\n row_array.push(cell.w);\n }\n return row_array;\n}", "function getValuesFromSheet(sheet) {\n var range = sheet.getDataRange();\n var values = range.getValues();\n Logger.log('Read sheet: ' + sheet.getName() + ' rows=' + values.length + ' cols=' + values[0].length);\n return values;\n}", "function getValuesFromSheet(sheet) {\n var range = sheet.getDataRange();\n var values = range.getValues();\n Logger.log('Read sheet \"' + sheet.getName() + '\": rows=' + values.length + ' cols=' + values[0].length);\n return values;\n}", "function convert(sheet) {\n var result = [];\n var row;\n var rowNum;\n var colNum;\n var range = XLSX.utils.decode_range(sheet['!ref']);\n for(rowNum = range.s.r; rowNum <= range.e.r; rowNum++) {\n row = [];\n for(colNum = range.s.c; colNum <= range.e.c; colNum++) {\n var cell = sheet[XLS.utils.encode_cell({\n r: rowNum,\n c: colNum\n })];\n if(typeof cell === 'undefined') {\n row.push(\"\");\n } else row.push(cell.w);\n }\n result.push(row);\n }\n\n //do stuff with result | row count = rowNum | column count = colNum\n //previewValues(rowNum, colNum, result);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append a check box for each variable in data
function addVariableCheckBoxes(data) { var variableList = $(".variable-selection"); for(var variable in data) { if(isFinite(data[variable][0].value) && $.inArray(variable, calculatedValues) == -1 && $.inArray(variable, interventionVariables) == -1) addCheckBox(variableList, variable); } }
[ "function displayCheckboxes() {\n $('#checkbox').text('');\n\n for (let i = 0; i < ingredientsArray.length; i++) {\n let pContainer = $(\"<p class=label>\");\n let labelContainer = $(\"<label class=option>\");\n let inputContainer = $(\"<input type=checkbox>\");\n let spanContainer = $('<span>');\n\n pContainer.addClass('col s2')\n inputContainer.addClass('filled-in checked=\"unchecked\"');\n spanContainer.text(ingredientsArray[i]);\n inputContainer.attr('value', ingredientsArray[i]);\n\n $('#checkbox').append(pContainer);\n pContainer.append(labelContainer);\n labelContainer.append(inputContainer);\n labelContainer.append(spanContainer);\n\n }\n}", "function addCheckBox(variableList, variable) {\n var variableID = removeNonParsingChars(variable);\n \n data_names[variableID] = variable;\n\n var element = '<li>';\n element += '<input type=\"checkbox\" name=\"' + variableID\n + '\" id=\"variable\" >';\n element += '<span>' + variable + '</span>';\n element += '</li>';\n\n variableList.append(element);\n}", "function populateCheckBox(subj) {\r\n for(i=0; i<subj.length; i++) {\r\n addCheckBoxInput(subj[i])\r\n }\r\n}", "function showCheckBox(data) {\n \t// update checkboxes\n \tdojo.forEach(data, function(item){\n \t\t\t\t\titem.chkBoxUpdate = '<input type=\"checkbox\" align=\"center\" id=\"'+item.expdIdentifier+'\" onClick=\"getCheckedRows(this)\" />';\n \t\t\t\t\titem.chkBoxUpdate.id = item.expdIdentifier;\n \t\t\t\t});\n \t\n \t// Standard checkboxes\n \tdojo.forEach(data, function(item){\n \t\tif (item.includesStd == \"Y\"){\n \t\t\titem.chkBoxStd = '<input type=\"checkbox\" disabled align=\"center\" id=\"'+item.expdIdentifier+'cb'+'\" checked=\"checked\"/>';\n\t\t\t\t\t} else{\n\t\t\t\t\titem.chkBoxStd = '<input type=\"checkbox\" disabled align=\"center\" id=\"'+item.expdIdentifier+'cb'+'\"/>';\n\t\t\t\t\t}\n\t\t\t\t\titem.chkBoxStd.id = item.expdIdentifier + 'cb';\n\t\t\t\t});\n }", "function populateSearchList(data){\n var countryNames = d3.map(data, function(d){return d.Country;}).keys();\n var countrySearchList = $(\"#countrySearchList\");\n\n for (var i=0; i<countryNames.length; i++){\n countrySearchList.append(`\n <input class=\"countryCheckbox\" type=\"checkbox\" name=\"${countryNames[i]}\" value=\"${countryNames[i]}\"><span>${countryNames[i]}<br></span>`);\n }\n}", "function addFacetCheckboxes(element, questionNumber, actionNum, yesNoMaybe) {\n\tvar questionNumber = questionNumber + 1;\n\t\n\tvar facets = [\"Motivation\", \"Information Processing Style\", \"Computer Self-Efficacies\",\n\t\t\"Attitude Towards Risk\", \"Willingness to Tinker\"];\n\t\n\tfor (var facet = 0; facet < facets.length; facet++) {\n\t\t//Checkbox\n\t\t$(\"<input/>\", {\n\t\t\tid: \"S\" + numSubtasks + \"A\" + actionNum + \"Q\" + questionNumber + yesNoMaybe + \"F\" + facet,\n\t\t\ttype: \"checkbox\",\n\t\t\tvalue: facets[facet],\n\t\t}).appendTo(element);\n\t\n\t\t//Label for Checkbox\n\t\t$(\"<span/>\", { html: facets[facet] }).appendTo(element);\n\t\t\n\t\t$(\"<br>\").appendTo(element);\n\t}\n\t\n\t$(\"<br>\").appendTo(element);\n}", "function reRenderCheck(){\n for (var i = 0; i < selectedIngArr.length; i++){\n var checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.name = selectedIngArr[i];\n checkbox.value = selectedIngArr.length;\n checkbox.id = 'check' + selectedIngArr.length;\n checkbox.className = 'checkboxitem';\n var label = document.createElement('label');\n label.htmlFor = 'id';\n label.className = 'label';\n label.appendChild(document.createTextNode(selectedIngArr[i]));\n check.appendChild(checkbox);\n check.appendChild(label);\n }\n}", "function createCheckBoxes(){\n\tfor(var box of cuisineTypes){\n\t\tvar x = document.createElement(\"input\");\n\t\tvar label = document.createElement(\"label\");\n\t\tx.setAttribute(\"type\", \"checkbox\");\n\t\tx.setAttribute(\"name\", box + \"Check\");\n\t\tx.setAttribute(\"value\", box);\n\t\tx.setAttribute(\"onClick\",\"filterByCuisine(this)\");\n\t\tlabel.innerHTML = box;\n\t\tlabel.appendChild(x);\n\t\tdocument.getElementById(\"checkBoxArea\").appendChild(label);\n\t}\n}", "function generateFieldCheckBoxList() {\r\n\t\tlet div_start = '<div class=\"form-check form-check-inline\">';\r\n\t\tlet div_end = '</div>';\r\n\t\tlet html = '';\r\n\t\tgetFieldRefList().forEach(function(field) {\r\n\t\t\tlet input = '<input class=\"form-check-input\" type=\"checkbox\" value=\"'+field.code+'\" name=\"fields\" id=\"id_'+field.code+'\" '+(field.checked?'checked':'')+'>';\r\n\t\t\tlet label = '<label class=\"form-check-label\" for=\"id_'+field.code+'\">'+ field.libelle +'</label>';\r\n\t\t\thtml += div_start + input + label + div_end;\r\n\t\t});\r\n\t\t$('#fieldList').html(html);\r\n\t}", "function renderTypes() {\n for (var i = 0; i < place_types.length; i++) {\n $(\".js_types\").append(\"<input type=\\\"checkbox\\\" id=\\\"checkbox\" + place_types[i] + \"\\\" name=\\\"checkbox_input\" + place_types[i] + \"\\\" value=\\\"\" + place_types[i] + \"\\\" class=\\\"js_submit_type\\\"/>\\n <label for=\\\"checkbox\" + place_types[i] + \"\\\" class=\\\"js_type\\\">\" + place_types[i].replace('_', ' ') + \"</label><br>\");\n console.log('render types ran');\n }\n}", "function displayTagsPop(dataTags){\r\n // var data = JSON.parse(dataTags);\r\n\r\n let tagsFormBlock = document.getElementById(\"tag_form\");\r\n\r\n\r\n dataTags.forEach(tag => {\r\n\r\n let one_tag_input=document.createElement(\"input\");\r\n one_tag_input.setAttribute('type','checkbox');\r\n one_tag_input.setAttribute('id',\"popup_checkbox\"+tag['idTag']);\r\n one_tag_input.setAttribute('class',\"tag_checkbox\");\r\n one_tag_input.setAttribute('name',\"tag_form\");\r\n one_tag_input.setAttribute('value',tag['idTag']);\r\n\r\n let one_tag_label = document.createElement(\"label\");\r\n one_tag_label.setAttribute('for',\"popup_checkbox\"+tag['idTag']);\r\n one_tag_label.setAttribute('class',\"tag\");\r\n one_tag_label.innerHTML = tag['nomTag'];\r\n\r\n tagsFormBlock.appendChild(one_tag_input);\r\n tagsFormBlock.appendChild(one_tag_label);\r\n });\r\n}", "function add_checkboxes(self){\n self.checkboxes = {};\n self.tag.empty();\n var instance = self.app.instance;\n if(!instance) return;\n _.each(instance.root_signatures(), function(sig){\n var conf = self.app.theme.get_set_config(sig, instance, self.app.projection);\n var label= conf.label;\n var ckbox= mkSigCheckbox(label, _.partial(fireChanged, self));\n self.checkboxes[sig.typename] = ckbox;\n self.tag.append(ckbox);\n });\n }", "function showCheckboxResults(data, typeObject, dataCount) {\n if (typeObject.length === 0) {\n for (var i = 0; i < dataCount; i++) {\n dataR = data[i];\n createList(dataR);\n }\n } else {\n for (var i = 0; i < dataCount; i++) {\n dataR = data[i];\n\n typeObject.forEach(function (value, index, array) {\n if (dataR.type == value) {\n createList(dataR);\n }\n });\n }\n }\n}", "function insertCheckboxes() {\n let statBoxes = document.querySelectorAll('div[class^=\"gymContent\"] li');\n statBoxes.forEach(stat => {\n let statName = stat.className.split('_')[0];\n let checkbox = elementCreator('input', { type: 'checkbox', id: statName, name: statName, style: 'margin-right: 5px; vertical-align: middle' });\n let label = elementCreator('label', { for: statName, style: 'vertical-align: middle' }, '<b>Disable this stat?</b>');\n let checkboxWrapper = elementCreator('div', { style: 'margin: 5px' });\n checkboxWrapper.appendChild(checkbox);\n checkboxWrapper.appendChild(label);\n stat.querySelector('[class^=\"description\"]').append(checkboxWrapper);\n });\n}", "function initCheckboxes(){\n var checkboxes = [];\n for(var i = 0; i < allBooks.length; ++i){\n\n var checkbox = '<li class=\"list-group-item rounded-0\"><div class=\"custom-control custom-checkbox\"><input class=\"custom-control-input bookCheckbox\" id=\"check'+i+'\" type=\"checkbox\" value=\"'+allBooks[i].name+'\"><label class=\"cursor-pointer d-block custom-control-label\" for=\"check'+i+'\">'+allBooks[i].name +\" (\"+ allBooks[i].year + \") £\"+ allBooks[i].price+'</label></div></li>'\n\n checkboxes.push(checkbox);\n\n }\n return checkboxes;\n}", "function checkBoxList(){\r\n\t\t\t\t\t\tdocument.getElementById('check-list-box').innerHTML =''+\r\n\t\t\t\t\t\t\t'<li class=\"list-group-item\" id=\"'+placeTypes_all[0][0]+'\" data-checked=\"true\">'+\r\n\t\t\t\t\t\t\t'<img src=\"'+placeTypes_all[0][2]+'\" style=\"max-height: 20px; margin-right:10px; margin-left:10px;\" />'+\r\n\t\t\t\t\t\t\tplaceTypes_all[0][1]+'</li>';\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t//'<li class=\"list-group-item\" data-checked=\"true\">bar</li>';\r\n\t\t\t\t\t\tfor(i=1; i<placeTypes_all.length; i++){\r\n\t\t\t\t\t\t\tdocument.getElementById('check-list-box').innerHTML +=''+\r\n\t\t\t\t\t\t\t'<li class=\"list-group-item\" id=\"'+placeTypes_all[i][0]+'\">'+\r\n\t\t\t\t\t\t\t'<img src=\"'+placeTypes_all[i][2]+'\" style=\"max-height: 20px; margin-right:10px; margin-left:10px;\" />'+\r\n\t\t\t\t\t\t\tplaceTypes_all[i][1]+'</li>';\r\n\t\t\t\t\t\t}//for\r\n\t\t\t\t\t}//function", "function asunto_checkbox(data,asunto_id){\n var checkbox='<div class=\"form-group\" id=\"'+asunto_id+'\">'\n $.each(data,function(clave,value){\n checkbox+='<div class=\"checkbox\">'+\n '<label><input type=\"checkbox\" class=\"js_jpv_asunto_comunicaciones_ch\"'+\n ' name=\"asunto_'+value['id']+'\"'+\n ' grupo=\"asunto_'+asunto_id+'\"'+\n ' label=\"'+value['asunto']+'\"'+\n ' required=\"required\" mensaje=\"El Asunto \"'+\n ' name_text=\"'+value['name_text']+'\"'+\n ' tipo_campo=\"'+value['tipo_campo']+'\"'+\n ' value=\"'+value['id']+'\">'+value['asunto']+'</label>'+\n '</div>'\n })\n checkbox+='</div>'\n return checkbox\n }", "function fillBehaviorCheckList ()\n {\n for (var i = 0; i < catLadyBehaviors.length; i++) {\n var description = catLadyBehaviors[i].description;\n var points = catLadyBehaviors[i].pointValue;\n var option = '<div class=\"checkbox\"><label><input type= \"checkbox\" class= \"behavior-checklist\"value=\"' + points +'\">'\n + description + '</label></div>';\n console.log(option);\n $('#checklist').append(option);\n }\n }", "function printChecked() {\n checkedSet.forEach((data) => {\n display.innerHTML += data + \"&ThickSpace;\"\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when we know that cell r,c has value v, this affects the possible values of other cells in the same row, column, or box.
function Controller_PropagateCellChoice (r, c, v) { // no other cell can have the same value. // this function, applied to a cell, removes v as a possible value // of that cell (if the cell is not the one at r,c). // We're making good use of Javascript's ability to define functions // at run-time, and the use of closures. function noOtherCellCanHaveValue(cell) { if (! cell.atPos(r,c)) { cell.excludeValue(v); } } foreach (this.model.rowCells(r, c), noOtherCellCanHaveValue); foreach (this.model.columnCells(r,c),noOtherCellCanHaveValue); foreach (this.model.boxCells(r,c), noOtherCellCanHaveValue); // In addition, now that we have eliminated some possible // values from some cells, it may be the case that we can // find a set of two cells in a row, column, or box such // that the set of possible values in those two cells is // of length two. For example, we know that those two cells // contain 2 or 5, but we don't know which one has the 2 and // which has the 5. But regardless of that, we know that // 2 and 5 can't be anywhere else in the same row (column, etc) this.eliminateSets(2); }
[ "function noOtherCellCanHaveValue(cell) {\n if (! cell.atPos(r,c)) {\n cell.excludeValue(v);\n }\n }", "function cellsWithPossibleValue (cells, v) {\n return cells.removeIfNot(function (x) {return x.hasPossibleValue(v);});\n}", "validValue() {\n\n /*\n Test for checking if the value exists in the same row or column\n */\n for (let i = 0; i < 9; i++) {\n\n if(gridCells[this.r][i].value == this.value && this.c != i){\n return false;\n }\n\n if(gridCells[i][this.c].value == this.value && this.r != i){\n return false;\n }\n\n }\n\n\n\n /*\n Test for checking if the value exists in the same 9x9 square\n */\n\n let r = parseInt(this.r / 3) * 3;\n let c = parseInt(this.c / 3) * 3;\n\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n\n if(gridCells[(r+i)][c+j].value == this.value && gridCells[(r+i)][c+j] != this){\n return false;\n }\n }\n }\n return true;\n }", "setInitialPotentialValues() {\n // for each cell in the puzzle\n for (let iRow = 0; iRow < NUM_CELL_ROWS; iRow++) {\n for (let iCol = 0; iCol < NUM_CELL_COLS; iCol++) {\n let cell = this._cell(iRow, iCol);\n \n // set the potential value flags to true\n cell.setAllPotentialValues();\n \n // clear the flags for the final values found in the the cell's square\n let square = this._square(iRow, iCol);\n for (let iSquareRow = 0; iSquareRow < NUM_SQUARE_ROWS; iSquareRow++) {\n for (let iSquareCol = 0; iSquareCol < NUM_SQUARE_COLS; iSquareCol++) {\n let checkCell = square.cell(iSquareRow, iSquareCol);\n cell.clearPotentialValue(checkCell.value);\n }\n }\n \n // clear the flags for the final values found in the the cell's row\n for (let iCheckCol = 0; iCheckCol < NUM_CELL_COLS; iCheckCol++) {\n let checkCell = this._cell(iRow, iCheckCol);\n cell.clearPotentialValue(checkCell.value);\n }\n\n // clear the flags for the final values found in the the cell's column\n for (let iCheckRow = 0; iCheckRow < NUM_CELL_COLS; iCheckRow++) {\n let checkCell = this._cell(iCheckRow, iCol);\n cell.clearPotentialValue(checkCell.value);\n }\n }\n }\n }", "function one_value_cell_constraint(board) {\n\n\t// Set to false at the start of the loop\n\tupdated = false\n\n\t// Convert every gap into an array of possibilities\n\tfor (let r = 0; r < 9; r++) {\n\t\tfor (let c = 0; c < 9; c++) {\n\t\t\tif (board[r][c] == 0) {\n\t\t\t\tupdated = complete_cell(board, r, c) || updated\n\t\t\t}\n\t\t}\n\t}\n\n\t// Look out for any possibility that appears as a possibility\n\t// once-only in the row, column, or quadrant.\n\t// If it does, fill it in!\n\tfor (let r = 0; r < 9; r++) {\n\t\tfor (let c = 0; c < 9; c++) {\n\t\t\tif (Array.isArray(board[r][c])) {\n\t\t\t\tlet possibilities = board[r][c]\n\t\t\t\tupdated = appears_once_only(board, possibilities, get_row(board, r), r, c) ||\n\t\t\t\t\tappears_once_only(board, possibilities, get_column(board, c), r, c) ||\n\t\t\t\t\tappears_once_only(board, possibilities, get_square(board, square_coordinates[r][c]), r, c) || updated\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reinitialize gaps back to zero before ending\n\tfor (let r = 0; r < 9; r++) {\n\t\tfor (let c = 0; c < 9; c++) {\n\t\t\tif (Array.isArray(board[r][c])) {\n\t\t\t\tboard[r][c] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\treturn updated\n}", "function getPossibleValues(cells, row, column) {\n // find values already used in row, column or box\n let usedValues = new Set([]);\n for (let i = 0; i < 9; i++) {\n usedValues.add(cells[i][column]);\n usedValues.add(cells[row][i]);\n }\n\n for (let i = Math.floor(row / 3 ) * 3; i < Math.floor(row / 3) * 3 + 3; i++) {\n for (let j =Math.floor(column / 3) * 3; j < Math.floor(column / 3) * 3 + 3; j++) {\n usedValues.add(cells[i][j])\n }\n }\n\n // check diagonal values\n if (row === column) {\n for (let i = 0; i < 9; i++) {\n usedValues.add(cells[i][i])\n }\n }\n if (row + column === 8) {\n for (let i = 0; i < 9; i++) {\n usedValues.add(cells[i][8 - i])\n }\n } \n\n // find unused values\n let possibleValues = [];\n for (let i=0; i<10;i++) {\n if (!usedValues.has(i)) possibleValues.push(i);\n }\n\n return possibleValues;\n}", "clearPotentialValues(row, col, value) {\n // remove value from the cells' potential values in the square\n let square = this._square(row, col);\n for (let iSquareRow = 0; iSquareRow < NUM_SQUARE_ROWS; iSquareRow++) {\n for (let iSquareCol = 0; iSquareCol < NUM_SQUARE_COLS; iSquareCol++) {\n let cell = square.cell(iSquareRow, iSquareCol);\n cell.clearPotentialValue(value);\n }\n }\n \n // remove value from the cells' potential values in the row\n for (let iCheckCol = 0; iCheckCol < NUM_CELL_COLS; iCheckCol++) {\n let cell = this._cell(row, iCheckCol);\n cell.clearPotentialValue(value);\n }\n\n // remove value from the cells' potential values in the column\n for (let iCheckRow = 0; iCheckRow < NUM_CELL_COLS; iCheckRow++) {\n let cell = this._cell(iCheckRow, col);\n cell.clearPotentialValue(value);\n }\n }", "function getValidCellValues(cell) {\n\t// Use our initial allCells object that sets up the board\n\tvar tempFoundValues = new Array(); // Store all detected values from rows, columns, and subsquares\n\tvar tempValidValues = new Array(); // Store all VALID numbers for specific cell\n\t//var tempCheckArray = new Array();\n\tvar cellValue; // Temporarily store value detected inside a cell\n\n\t// Pass the cell (e.g., \"a2\"), value found (e.g., \"1\"), and an array to prevent duplicate data\n\tfunction checkArray(value,array) {\n\t\t// true = okay, add number to array!\n\t\t// false = nah, man. don't add it.\n\t\tif (typeof array == \"undefined\") {\n\t\t\t// If the initial array doesn't exist (e.g., no data), create it!\n\t\t\tvar array = new Array();\t\n\t\t}\n\n\t\tif (value == 0) {\n\t\t\t// Nothing detected in cell, let's not store this.\n\t\t\treturn false;\n\t\t} else if (!isNaN(Number(value)) && array.indexOf(Number(value)) === -1) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Look at the temp array generated by checkArray.\n\t// Now pull together a list of VALID values for numbers NOT in that array.\n\tfunction getValidValues(array) {\n\t\tvar tempValid = new Array();\n\t\tfor (i = 1; i <= 9; i++) {\n\t\t\tif (array.indexOf(i) === -1) {\n\t\t\t\t// The number i is not found. Add it to our new array.\n\t\t\t\ttempValid.push(i);\n\t\t\t}\n\t\t}\n\t\treturn tempValid;\n\t}\n\n\t// CHECK COLUMN: by looking at vertical column and looping over row values (e.g., \"a,b,c,d...\")\n\tvar column = cell.split(\"\"); // Split up our cell value (e.g. \"a1\"), so we can find which column we want to look at.\n\tcolumn = column[1];\n\tfor (i = 0; i <= 8 ; i++) {\n\t\tselectCell = rowLabels[i] + (column);\n\t\t//console.log(\"CELL \" + selectCell);\n\t\tcellValue = filledNumbers[selectCell]; // Get whatever value is stored in this specific cell\n\t\t//console.log(\"CELL VALUE \" + cellValue);\n\t\tif (checkArray(cellValue,tempFoundValues) == true) {\n\t\t\ttempFoundValues.push(cellValue);\n\t\t}\n\t}\t\n\n\t// CHECK ROW: by looking at horizontal row and looping over column values (e.g., 1,2,3,4,5)\n\t// VALIDATE ROW\n\tvar row = cell.split(\"\"); // Split up our cell value (e.g., \"a1\") so we can get the row.\n\trow = row[0];\n\tfor (var i = 1; i <= maxColumns; i++) {\n\t\tselectCell = row + i;\n\t\tcellValue = filledNumbers[selectCell]; // Get whatever value is stored in this specific cell\n\t\tif (checkArray(cellValue,tempFoundValues) == true) {\n\t\t\ttempFoundValues.push(cellValue);\n\t\t}\n\t}\n\n\t// CHECK SUBSQUARE: by looking at all cells located in this cell's subsquare\n\tvar tempGrid = findSquare(cell); // Find which sub square this cell is in.\n\tvar gridCells = subSquares[tempGrid]; // Get all cells in that subsquare.\n\tvar gridCount = gridCells.length;\n\n\tfor (i = 0; i < gridCount; i++) {\n\t\tselectCell = gridCells[i];\n\t\tcellValue = filledNumbers[selectCell];\n\t\tif (checkArray(cellValue,tempFoundValues) == true) {\n\t\t\ttempFoundValues.push(cellValue);\n\t\t}\n\t}\t\n\n\t/// WRITE STUFF BELOW TO STORE IN OBJECT!\n\t// We only want to track and store values for squares that are EMPTY!\n\tif (filledNumbers[cell] > 0) {\n\t\t// Do nothing, since there is already a value stored here!\n\t} else {\n\t\ttrackPossibleValues[cell] = getValidValues(tempFoundValues); // Store all possible values for this cell in our object.\n\t}\n\n\t///\n\t///\n\t//console.log(\"Valid #\\'s for \" + cell + \": \" + getValidValues(tempFoundValues));\n\treturn tempFoundValues; // Return the array\n\n}", "inBox(row, col, value){\n var boxCenterRow;\n var boxCenterCol;\n if (row < 3){\n boxCenterRow = 1;\n } else if (row < 6){\n boxCenterRow = 4;\n } else {\n boxCenterRow = 7;\n }\n if (col < 3){\n boxCenterCol = 1;\n } else if (col < 6){\n boxCenterCol = 4;\n } else {\n boxCenterCol = 7;\n }\n \n var cells2dnoasterisk = this.cells2d.map(row => {\n return row.map(cell => {\n return cell.replace(\"*\", \"\");\n })\n })\n\n if ( cells2dnoasterisk[boxCenterRow][boxCenterCol] === value.toString() // center cell\n || cells2dnoasterisk[boxCenterRow][boxCenterCol + 1] === value.toString() // above center\n || cells2dnoasterisk[boxCenterRow][boxCenterCol - 1] === value.toString() // below center\n || cells2dnoasterisk[boxCenterRow + 1][boxCenterCol] === value.toString() // right of center\n || cells2dnoasterisk[boxCenterRow - 1][boxCenterCol] === value.toString() // left of center\n || cells2dnoasterisk[boxCenterRow + 1][boxCenterCol + 1] === value.toString() // top right\n || cells2dnoasterisk[boxCenterRow + 1][boxCenterCol - 1] === value.toString() // top left\n || cells2dnoasterisk[boxCenterRow - 1][boxCenterCol + 1] === value.toString() // bottom right\n || cells2dnoasterisk[boxCenterRow - 1][boxCenterCol - 1] === value.toString() // bottom left\n ){\n return true;\n } else {\n return false;\n }\n\n }", "trySolveByCrossGroup(grid,r,c) {\n let sqrIndex = this.getIndex(r,c);\n let grpIndex = this.getGroupIndex(r, c);\n\n // Get all possible values not in Group, row, or Column.\n var indexSet = this.possibleValues.difference(new Set(this.getGroup(grid,r,c)));\n indexSet = indexSet.difference(new Set(this.getRow(grid,r)));\n indexSet = indexSet.difference(new Set(this.getCol(grid,c)));\n\n let rStart = Math.floor(grpIndex / 3) * 3;\n let cStart = (grpIndex % 3) * 3;\n\n for (let row = rStart; row < rStart + 3; row++) {\n for (let col = cStart; col < cStart + 3; col++) {\n let index = this.getIndex(row,col)\n \n // Only null value columns / rows can be a possible placement for indexSet, lets try to eliminate these options\n if (grid[index] === null &&\n this.getGroupIndex(row,col) === grpIndex &&\n index !== sqrIndex) \n {\n //console.log(\"Null Square: \" + row + ':' + col);\n let squareSet = new Set(this.getRow(grid,row))\n .union(new Set(this.getCol(grid,col)));\n\n indexSet = indexSet.intersection(squareSet); // non intersecting values cannot be placed reliably, filter possibles\n }\n }\n }\n\n if (indexSet.size === 1) {\n //console.log('Solved - ' + r + ':' + c + ' = ' + indexSet.getByIndex(0));\n grid[this.getIndex(r,c)] = indexSet.getByIndex(0);\n return true;\n } else {\n return false;\n }\n }", "sameCell(c) {\n return (this.row === c.row) && (this.col === c.col);\n }", "get_cell_value( c ){\r\n let cp, bit = 0;\r\n for( let i=0; i < 8; i++ ){\r\n cp = this.points[ c.corners[ i ] ]; // Corner Position \r\n if( cp.enabled ) bit += MarchingCubes.corner_bit[ i ]; // If on, Add its Bit Value\r\n }\r\n return bit;\r\n }", "function calculateCells()\n {\n var r, c, lr, lc;\n var vl;\n lr = lastRow;\n lc = lastCol;\n\n for (r = 0; r <= lr; r++)\n {\n for (c = 0; c <= lc; c++)\n {\n try\n {\n if (tb[gAdr(r, c)].flag != 0)\n {\n if (tb[gAdr(r, c)].formula.length > 0)\n {\n vl = cellFunctions(r, c);\n tb[gAdr(r, c)].value = vl;\n }\n }\n }\n catch (ex){}\n }\n }\n }", "function possible_values(cells, x, y, area) {\r\n //area = 0->all cases, 1 -> hori, 2 -> vert, 3 -> region\r\n var values=\"123456789\";\r\n if (area==1 || area==0) {\r\n for (var j=0;j<9;j++) {\r\n values=values.replace(cells[x][j].value,\"\");\r\n }\r\n }\r\n \r\n if(area==2 || area==0) {\r\n for (var i=0;i<9;i++) {\r\n values=values.replace(cells[i][y].value,\"\");\r\n }\r\n } \r\n \r\n if(area==3 || area==0) {\r\n var regionX=Math.floor(x/3)*3;\r\n var regionY=Math.floor(y/3)*3;\r\n for (var i=regionX;i<regionX+3;i++) {\r\n for (var j=regionY;j<regionY+3;j++) {\r\n values=values.replace(cells[i][j].value,\"\");\r\n }\r\n }\r\n }\r\n return values;\r\n}", "function checkVictory(cléIndex) {\n var currentColor = cellProperties[cléIndex].couleur;\n var currentCol = cellProperties[cléIndex].col;\n var currentRow = cellProperties[cléIndex].row;\n var tokenHorizontal = 0;\n var tokenVertical = 0;\n var tokenDiagonalPositive = 0;\n var tokenDiagonalNegative = 0;\n var emptyCellFound = 0;\n\n\n // horizontal \n // coté gauche(check les cases à gauche du jeton joué)\n if (currentCol > 1) {\n for (i = currentCol; i > 1; i--) {\n colTest = \"col\" + (i - 1);\n if (cellProperties[colTest + 'row' + currentRow].couleur === currentColor) {\n tokenHorizontal += 1;\n }\n if (cellProperties[colTest + 'row' + currentRow].couleur != currentColor) {\n break;\n }\n if (tokenHorizontal >= 3) {\n victoire = true;\n console.log(\"Victoire Horizontale\");\n break;\n }\n }\n }\n // coté droit(check les cases à droite du jeton joué)\n if (currentCol < x && tokenHorizontal < 3 && x - currentCol > (3 - tokenHorizontal)) {\n for (i = currentCol; i > 0; i++) {\n colTest = \"col\" + (i + 1);\n if (cellProperties[colTest + 'row' + currentRow].couleur === currentColor) {\n tokenHorizontal += 1;\n }\n if (cellProperties[colTest + 'row' + currentRow].couleur != currentColor) {\n break;\n }\n if (tokenHorizontal >= 3) {\n victoire = true;\n console.log(\"Victoire Horizontale\");\n break;\n }\n }\n }\n\n // vertical (check les cases sous le jeton joué)\n if (currentRow <= (y - 3)) {\n for (i = currentRow; i < y; i++) {\n rowTest = \"row\" + (i + 1);\n if (cellProperties[\"col\" + currentCol + rowTest].couleur === currentColor) {\n tokenVertical += 1;\n }\n if (cellProperties[\"col\" + currentCol + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenVertical >= 3) {\n victoire = true;\n console.log(\"Victoire Verticale\");\n break;\n }\n }\n }\n\n // diagonaux\n //diagonale positive\n // bas gauche (check les cases en bas à gauche en diagonale du jeton joué)\n if (currentRow < y && currentCol > 1) {\n for (i = currentRow, j = currentCol; i < y && j > 1; i++ , j--) {\n rowTest = \"row\" + (i + 1);\n colTest = \"col\" + (j - 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalPositive += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalPositive >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale+\");\n break;\n }\n }\n }\n //diagonale positive\n // haut droit (check les cases en haut à droite en diagonale du jeton joué)\n if (currentRow > 1 && currentCol < x && (x - currentCol) > (3 - tokenDiagonalPositive) && currentRow > (3 - tokenDiagonalPositive)) {\n for (i = currentRow, j = currentCol; i > 1 && j < x; i-- , j++) {\n rowTest = \"row\" + (i - 1);\n colTest = \"col\" + (j + 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalPositive += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalPositive >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale+\");\n break;\n }\n }\n }\n\n //diagonale negative\n // bas droite (check les cases en bas à droite en diagonale du jeton joué)\n if (currentRow < y && currentCol < x) {\n for (i = currentRow, j = currentCol; i < y && j < x; i++ , j++) {\n rowTest = \"row\" + (i + 1);\n colTest = \"col\" + (j + 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalNegative += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalNegative >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale-\");\n break;\n }\n }\n }\n\n // diagonale negative\n // haut gauche (check les cases en bas à droite en diagonale du jeton joué)\n if (currentRow > 1 && currentCol > 1 && (currentCol - 1) > (3 - tokenDiagonalNegative) && currentRow > (3 - tokenDiagonalNegative)) {\n for (i = currentRow, j = currentCol; i > 1 && j > 1; i-- , j--) {\n rowTest = \"row\" + (i - 1);\n colTest = \"col\" + (j - 1)\n\n if (cellProperties[colTest + rowTest].couleur === currentColor) {\n tokenDiagonalNegative += 1;\n }\n if (cellProperties[colTest + rowTest].couleur != currentColor) {\n break;\n }\n if (tokenDiagonalNegative >= 3) {\n victoire = true;\n console.log(\"Victoire Diagonale-\");\n break;\n }\n }\n }\n\n // vérification du match nul en cas de complétion de grille\n if (currentRow == 1 && !victoire) {\n for (i = 1; i <= x; i++) {\n colTest = \"col\" + (i);\n if (cellProperties[colTest + 'row1'].couleur == 0) {\n emptyCellFound += 1;\n break;\n }\n }\n if (emptyCellFound == 0) {\n console.log('Match Nul')\n matchNul = true;\n }\n }\n\n } // crochet fin de fonction condition de victoire", "function check_possible_values(){\n var temp_arr = [];\n data.cells.forEach(d => {\n temp_arr = []; d.possible_values = [];\n if(d.value == null){\n\n data.cells.forEach(d_ => {\n if(d_.row == d.row || d_.column == d.column || d_.square == d.square && d_.value != null){\n if( temp_arr.indexOf(d_.value) == -1 ){ temp_arr.push(d_.value); }\n }\n })\n\n d3.range(1,10).forEach(d_ => {\n if(temp_arr.indexOf(d_) == -1){ d.possible_values.push(d_); }\n })\n d.possible_values_len = d.possible_values.length;\n\n }\n })\n}", "function checkCellVal(cell) {\n\tvar row = $(cell).data(\"row\");\n\tvar col = $(cell).data(\"col\");\n\treturn(gameboard[row][col]);\n}", "isValidGuess(board, r, c, val) {\n // Check if val is in row 'r'.\n if (board[r].some(num => num == val)) return false;\n \n // Check if val is in column 'c'\n for (let row=0; row<9; ++row) {\n if (board[row][c] == val) return false\n }\n \n // Check if val is in sub-box.\n const row = Math.floor(r/3) * 3;\n const col = Math.floor(c/3) * 3;\n for (let rDelta=0; rDelta<3; ++rDelta) {\n for (let cDelta=0; cDelta<3; ++cDelta) {\n if (board[row + rDelta][col + cDelta] == val) return false;\n }\n }\n \n return true; // 'val' at position (r,c) meets all constraints.\n }", "function updateColorBoardCell(row, col, valid)\n{\n colorBoard[row][col] = valid;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matches this object against the operand tree, possibly updating the environment.
function lisp_match(obj, otree, env) { return lisp_class_of(obj).lisp_match(obj, otree, env); }
[ "objectMatches(object) {\n\t\treturn this.rootOperation.resolve([object]).length > 0;\n\t}", "visitEqualityExpression(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function branchTestMatch(expr, value)\n{\n if (type.isSameType(Array, true, expr))\n {\n return algorithm.every(expr, function(subExpr, index)\n {\n return branchTestMatch(subExpr, value[index]);\n });\n }\n else if (type.isSameType(Object, true, expr))\n {\n return algorithm.every(Object.keys(expr), function(key)\n {\n return branchTestMatch(expr[key], value[key]);\n });\n }\n else if (type.isType(expr)) // it's a type\n {\n return type.isSameType(expr, true, value);\n }\n return expr === value;\n}", "static alternateSytaxObjectProp(mode,path,root,val,obj) {\n\n var matched=[];\n\n var m = this.explainMatch(path.match(/^\\?\\(([^\\)]+)\\)\\]/), // looks for ?(....)]. Note the weekness - if )] is included in a string in the exopression then it will halt the match\n ['expression']);\n if (m) {\n var mexp = this.explainMatch(m.expression.match(/(\\S+)\\s*(==|!=|>=|>|<=|<|=~)\\s*(\\S[\\S\\s]*)/), // breaks the found expression into lhs op rhs\n ['lhs','op','rhs']); \n if (mexp) {\n this.log(\"Expression: \"+ mexp.lhs+\" \"+mexp.op+\" \"+mexp.rhs); \n path=path.slice(m[0].length);\n if (this.expevaluate(this.expval(mexp.lhs,obj),mexp.op,this.expval(mexp.rhs,obj))) { \n matched=matched.concat(this.captureOrMoveOn(mode,path,root,val,obj));\n }\n return mode=='set'?matched.length>0:matched;\n }\n }\n \n m = this.explainMatch(path.match(/^(?:\\*|(['\"])([\\$\\w]+)\\1)\\]/), // looks for either *] or 'property'] - ' and \" are suppported\"\n [,'property']);\n \n if (m) {\n path=path.slice(m.matched.length); \n if (m.matched.charAt(0)=='*') { \n this.log(\"Wild char property\");\n for (let index in obj) {\n matched=matched.concat(this.captureOrMoveOn(mode,path,root,val,obj,index));\n }\n }\n else\n {\n this.log(\"Property match: \"+m.property); \n if (typeof obj[m.property] != 'undefined') {\n matched=matched.concat(this.captureOrMoveOn(mode,path,root,val,obj,m.property)); \n }\n }\n } \n return mode=='set'?matched.length>0:matched;\n }", "contains(target) {\n console.log(target);\n console.log(this);\n console.log(this.value);\n const find = (t) => {\n // compare target to this.value\n // if target is === this.value return TRUE (base case)\n // if target is < this.value\n // if this.value.left\n // recurse with this.value.left\n // else return false;\n //\n // REFACTOR WITH SOME TERNARYS\n if (this.value === t) return true; // base case\n\n if (t < this.value) { // smaller than top of tree GO LEFT\n if (this.left) {\n return this.left.contains(t); // works back up the chain or tree\n }\n return false;\n } // bigger than top of tree GO RIGHT\n if (this.right) {\n return this.right.contains(t);\n }\n return false;\n };\n return find(target);\n }", "deepEquals(other) {\n let eq = false;\n if (!other) {\n eq = this.type === other.type;\n if (eq) {\n eq = this.children.length === other.children.length;\n if (this.type === expressionType_1.ExpressionType.And || this.type === expressionType_1.ExpressionType.Or) {\n // And/Or do not depand on order\n for (let i = 0; eq && i < this.children.length; i++) {\n const primary = this.children[0];\n let found = false;\n for (var j = 0; j < this.children.length; j++) {\n if (primary.deepEquals(other.children[j])) {\n found = true;\n break;\n }\n }\n eq = found;\n }\n }\n else {\n for (let i = 0; eq && i < this.children.length; i++) {\n eq = this.children[i].deepEquals(other.children[i]);\n }\n }\n }\n }\n return eq;\n }", "function operatorBranchedMatcher(valueSelector, matcher, isRoot) {\n // Each valueSelector works separately on the various branches. So one\n // operator can match one branch and another can match another branch. This\n // is OK.\n const operatorMatchers = Object.keys(valueSelector).map(operator => {\n const operand = valueSelector[operator];\n const simpleRange = ['$lt', '$lte', '$gt', '$gte'].includes(operator) && typeof operand === 'number';\n const simpleEquality = ['$ne', '$eq'].includes(operator) && operand !== Object(operand);\n const simpleInclusion = ['$in', '$nin'].includes(operator) && Array.isArray(operand) && !operand.some(x => x === Object(x));\n\n if (!(simpleRange || simpleInclusion || simpleEquality)) {\n matcher._isSimple = false;\n }\n\n if (hasOwn.call(VALUE_OPERATORS, operator)) {\n return VALUE_OPERATORS[operator](operand, valueSelector, matcher, isRoot);\n }\n\n if (hasOwn.call(ELEMENT_OPERATORS, operator)) {\n const options = ELEMENT_OPERATORS[operator];\n return convertElementMatcherToBranchedMatcher(options.compileElementSelector(operand, valueSelector, matcher), options);\n }\n\n throw new Error(\"Unrecognized operator: \".concat(operator));\n });\n return andBranchedMatchers(operatorMatchers);\n } // paths - Array: list of mongo style paths", "function ObjectMatcher() {}", "matches(otherInput) {\n return this === otherInput;\n }", "match(otherDot, varMap) {\n return this.tagValue === otherDot.tagValue && matchArguments(this.args, otherDot.args, varMap);\n }", "contains(target) {\n // LOGIC APPROACH: Establish all circumstances that will return 'true', then return 'false' for all other cases\n\n // CASE #1: Only 1 element in tree, and that element is equal to target\n if (this.value === target) {\n console.log('Case #1');\n return true;\n }\n // CASE #2 if this.left exists AND 'target' is equal to this.value somewhere in that tree, then return true.\n if (this.left && this.left.contains(target)) {\n console.log('Case #2');\n return true;\n }\n // CASE #3 if this.right exists AND 'target' is equal to this.value somewhere in that tree, then return true.\n if (this.right && this.right.contains(target)) {\n console.log('Case #3');\n return true;\n }\n return false;\n }", "function InstanceofExpression() {\n}", "matches(tree) {\r\n return this._matcher.match(tree, this).succeeded;\r\n }", "function doesObjMatchSearch(query, obj){\n var key;\n //find out what the first key is. we only allow you to use 1 search key.\n for(var keyx in query){\n key=keyx;\n }\n //depending on what the user wants in his params we check if our tree.json object match, if yes we return true.\n switch(key){\n case \"leafcolor\": \n var objValue = JSON.stringify(obj.leafColor);\n var queryValue = JSON.stringify(query.leafcolor);\n console.log(\"Do these match?: \"+objValue+\" AND \"+queryValue);\n if(objValue==queryValue){\n console.log(\"WE FOUND A MATCH!: \"+objValue+\" AND \"+queryValue);\n return true;\n }\n break;\n case \"barkcolor\": \n var objValue = JSON.stringify(obj.barkColor);\n var queryValue = JSON.stringify(query.barkcolor);\n console.log(\"Do these match?: \"+objValue+\" AND \"+queryValue);\n if(objValue==queryValue){\n console.log(\"WE FOUND A MATCH!: \"+objValue+\" AND \"+queryValue);\n return true;\n }\n break;\n case \"size\": \n var objValue = JSON.stringify(obj.size);\n var queryValue = JSON.stringify(query.size);\n console.log(\"Do these match?: \"+objValue+\" AND \"+queryValue);\n if(objValue==queryValue){\n console.log(\"WE FOUND A MATCH!: \"+objValue+\" AND \"+queryValue);\n return true;\n }\n break;\n case \"alive\": \n //the booleans are without the: \"\" so im adding them!\n var objValue = '\"'+JSON.stringify(obj.alive)+'\"';\n var queryValue = JSON.stringify(query.alive);\n console.log(\"Do these match?: \"+objValue+\" AND \"+JSON.stringify(query.alive));\n if(objValue == queryValue){\n console.log(\"WE FOUND A MATCH!: \"+objValue+\" AND \"+queryValue);\n return true;\n }\n break;\n }\n return false;\n}", "function OperatorNode(operator){\n var _obj = {};\n var _operator = operator || \"AND\";\n var _children = [];\n \n /**\n #### .operator([value])\n Gets or sets the operator associated with this node.\n **/\n _obj.operator = function(o){\n if(!arguments.length){ return _operator; }\n _operator = o;\n return _obj;\n };\n \n /**\n #### .addChild(node)\n Adds a child to this node. It can be another OperatorNode or a DataNode.\n **/\n _obj.addChild = function(n){\n _children.push(n);\n return _obj;\n };\n \n /**\n #### .children()\n Returns the children of this node\n **/\n _obj.children = function(){\n return _children;\n }\n \n \n /**\n #### .findDescendant(meta)\n Finds a descendant with the given metadata. Returns the node.\n **/\n _obj.findDescendant = function(m){\n \n \n };\n \n /**\n #### .removeDescendant(node)\n Removes a descendant from this operator.\n **/\n _obj.removeDescendant = function(n){\n \n };\n \n /**\n #### .clear()\n Removes any children from this node.\n **/\n _obj.clear = function(){\n _children = [];\n return _obj;\n }\n\n /**\n #### .pixelValue(element)\n Returns the calculated value for an element based on the subtree of this\n node. It is a value in the range [0,1].\n **/\n _obj.pixelValue = function(element){\n var curChild;\n if(_operator == \"AND\"){\n for(var i = 0 ; i < _children.length; i++){\n curChild = _children[i];\n if(curChild.data && curChild.data().has(element)){ return 0; }\n else if(curChild.pixelValue && curChild.pixelValue(element) == 0){ return 0; }\n }\n return 1;\n }\n else if(_operator == \"OR\"){\n var sum = 0;\n for(var i = 0; i < _children.length; i++){\n curChild = _children[i];\n if(curChild.data && curChild.data().has(element)){ sum += 1; }\n // TODO: What do you do with an OR of an OR? Do you add the\n // decimal or do you round it up?\n // else if(curChild.pixelValue && curChild.pixelValue(element) > 0){ sum += 1; }\n else if(curChild.pixelValue){ sum += curChild.pixelValue(element); }\n }\n return 1 - parseFloat(sum) / _children.length;\n }\n };\n \n /**\n #### .metadata()\n Returns the metadata of all children.\n **/\n _obj.metadata = function(){\n var meta = [];\n _obj.accept({\n visitPre: function(){ return; },\n visitPost: function(n){ if(n.meta){ meta.push(n.meta()); }}\n });\n return meta;\n };\n \n /**\n #### .accept(visitor)\n Implements the visitor pattern to allow various operations on this subtree.\n **/\n _obj.accept = function(v){\n v.visitPre(_obj);\n for(var i = 0; i < _children.length; i++){\n _children[i].accept(v);\n }\n v.visitPost(_obj);\n };\n \n return _obj;\n}", "match(expression, expNames) {\n /* Base SolutionPattern class always matches any expression object */\n return this.acceptMatch(expression, expNames);\n }", "matches(tree) {\n return this._matcher.match(tree, this).succeeded;\n }", "visitBinaryExpressionAtom(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function updateTree(operator) {\n\t\t//check if there are expr in parens or not\n\t\tvar workTree = mainTree;\n\t\tif(treeList.length != 0){\n\t\tworkTree = treeList[(treeList.length - 1)];\n\t\t}\n\n\t\tprecVal = precedence(workTree.operator, operator);\n\n\n\t\t//JSON.parse(JSON.stringify performs deep copies\n\t\t\t\n\t\tvar mainTreeClone = JSON.parse(JSON.stringify(workTree));\n\n\t\tif (precVal) {\n\t\t\t\n\t\t\tvar rnode = workTree;\n\t\n\n\t\t\twhile(rnode.operator != 0){\n\t\t\t\trnode = rnode.rhs;\n\t\t\t}\n\n\t\t\tif(!rnode.lhs.hasOwnProperty('operator')){\n\t\t\t\trnode.lhs = JSON.parse(JSON.stringify(numNode));\n\t\t\t}\n\n\t\t\trnode.operator = operator;\n\t\t\trnode.rhs = JSON.parse(JSON.stringify(nullTree));\n\n\t\t}\n\t\telse {\n\t\t\t//push the current number to the far right side, then add on top\n\t\t\tvar rnode = workTree;\n\t\n\t\t\t\n\t\t\twhile(rnode.rhs.operator != 0){\n\t\t\t\trnode = rnode.rhs;\n\t\t\t}\n\t\t\t\n\n\t\t\trnode.rhs = JSON.parse(JSON.stringify(numNode));\n\n\t\t\t//make a new clone thats updated\t\t\t\n\t\t\tmainTreeClone = JSON.parse(JSON.stringify(workTree));\n\n\t\t\t\n\n\t\t\tmainTree.lhs = mainTreeClone;\n\t\t\tmainTree.operator = operator;\n\t\t\tmainTree.rhs = JSON.parse(JSON.stringify(nullTree));\n\n\t\t\n\t\t}\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getNewLastName() This function returns the user's new last name. To do so, concatenate the first 2 letters of their mom's maiden name and the first 3 letters of the city where they were born.
function getNewLastName() { return momMaidenName.substring(0,1) + cityBorn.substring(0,2).toLowerCase(); }
[ "function getNewLastName(momMaidenName, cityBorn) {\n return momMaidenName.substr(0, 2) + cityBorn.substr(0, 3);\n}", "function getNewLastName(momMaidenName, cityBorn) {\r\n let newLastName = momMaidenName.substring(0,2) + cityBorn.substring(0,3).toLowerCase()\r\n return newLastName\r\n}", "function getNewLastName() {\r\n\r\n momMaidenName = readline.question(\"Mother's Maiden Name : \");\r\n\r\n cityBorn = readline.question(\"Hometown : \");\r\n\r\n return momMaidenName.substring(0, 2) + cityBorn.substring(0, 3).toLowerCase();\r\n}", "function getNewLastName() {\r\nreturn favoriteFruit.substring(0,2) + cityBorn.substring(0,3 ).toLowerCase();\r\n}", "function lastName() {\n\n\tlet last = [\"Parker\", \"Wayne\", \"Stevens\", \"Cooper\", \"Thomas\", \"Smith\", \"Peterson\", \"Brady\", \"Rogers\", \n\t\t\"Jordan\", \"Ewing\", \"Starks\", \"King\", \"Washington\", \"Cain\", \"Grayson\", \"Prince\", \"Gonzalez\",\n\t\t\"Gordon\", \"Jameson\", \"Holmes\", \"Cole\", \"Summers\", \"Connors\", \"Kent\", \"Morales\"];\n\n\t\treturn last[Math.floor(Math.random() * last.length)];\n}", "function getNewFirstName() {\n return firstName.substring(0,3) + lastName.substring(0,2).toLowerCase();\n}", "function replaceLastName(fullName, newLastName) {\n let lastNameStart = fullName.indexOf(\" \");\n let lastNameAll = fullName.substring(lastNameStart + 1);\n let newFullName = fullName.replace(lastNameAll, newLastName);\n return newFullName;\n}", "function getNewFirstName() {\r\nreturn firstName.substring(0,3) + lastName.substring(0,2).toLowerCase();\r\n}", "function replaceLastName(fullName, newLastName) {\n let oldLastName = getLastWordInPlaceName(fullName);\n // replace oldLastName with newLastName\n let newFullName = fullName.replace(oldLastName, newLastName);\n\n return newFullName;\n}", "function getNewFirstName(firstName, lastName) {\n return firstName.substr(0, 3) + lastName.substr(0, 2);\n}", "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 getLastName() {\n if ($.last_name) {\n return $.last_name.getValue().trim();\n }\n\n }", "function createFullName(firstname, lastname) {\n\treturn firstName + lastName;\n}", "function lastName(lastName){\r\n\r\n // this inner function has access to the outer function's variables, including the parameter\r\n\r\n return nameIntro + firstName + \" \" + lastName;\r\n }", "function jediName(firstName, lastName){\n return lastName.substring(0,3) + firstName.substring(0,2);\n}", "function getLastName(node) {\n lastName = node.querySelector('.blockquote-footer').textContent.split(' ').slice(-1)[0].toUpperCase()\n return lastName\n }", "function handleChangeOfLastName(e) {\n setLAST_NAME(e.target.value)\n\n }", "function capitalizeLastName(fullName) {\n let index = fullName.indexOf(\" \");\n let fullLastName = fullName.substring(index + 1);\n console.log(`fullLastName: ${fullLastName}`);// doe\n let newLastName = fullLastName[0].toUpperCase() + fullLastName.substring(1);\n console.log(`newLastName: ${newLastName}`); // Doe\n\n let capitalizeLastName = fullName.replace(fullLastName, newLastName\n );\n return capitalizeLastName; // John Smith\n}", "function getLastName() {\n\t\t\treturn JSON.parse(atob(getToken().split('.')[1])).lastName;\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
called by the silence and unsilence buttons.
function silenceAlarm(bool){ if ( bool ) { silence=true; $('#controlSilence').html('true'); alarmSound.stop(); alarmSound.isPlaying = false; //console.log(alarmSound.isPlaying); } else { silence=false; $('#controlSilence').html('false'); //console.log(alarmSound.isPlaying); if ( !alarmSound.isPlaying && booFault ){ alarmSound.isPlaying = true; alarmSound.play(); } } }
[ "function silenceEvents() {\n _silenceEvents = true;\n}", "function soundState(){\r\n\tsound_array.forEach(function(element){\r\n\t\tif(element.volume()!=0){ /*!element.mute()*/\r\n\t\t\tPizzicato.volume = 0; //element.mute(true);\r\n\t\t\telement.volume(0); //$('#muter').css(\"text-decoration\",\"line-through\");\r\n\t\t\t$('#muter').html('🔈');\r\n\t\t} else {\r\n\t\t\tPizzicato.volume = 0.05;\r\n\t\t\telement.volume(0.2); //element.mute(false);\r\n\t\t\t$('#muter').html('🔊'); //$('#muter').css(\"text-decoration\",\"none\");\r\n\t\t}\r\n\t})\r\n}", "silenceEvents() {\n index_2.silenceEvents();\n }", "function soundOnOff(){\n sound = !sound;\n hyperspaceToggleMute();\n update_dict_view();\n}", "function muteButtonPressed() {\n muteAudio();\n}", "function loopSilence(){\n\tsilencesamp.loop();\n\tsilencesamp.play();\n}", "waveGeneratorButtonSound( pressed ) {\n\n // no-op\n }", "function _stop(){\r\n\trecording = false;\r\n\tif (speechCount > 0){\r\n\t\tif(!isNoise){\r\n\t\t\t_sendMessage(NOISE);\r\n\t\t}\r\n\t\t_sendMessage(SILENCE);\r\n\t\tspeechCount = 0;\r\n\t\tsilenceCount = 0;\r\n\t\tlastInput = 0;\r\n\t\tblobSizeCount = 0;\r\n\t}\r\n\tisNoise = false;\r\n\t_sendMessage(STOPPED);\r\n}", "function silenceMode() {\n xapi.config.set('Audio Ultrasound MaxVolume', 0);\n xapi.config.set('Proximity Mode', 'off');\n xapi.config.set('Standby WakeupOnMotionDetection', 'off');\n xapi.command('Standby Activate');\n}", "function speechOn() {\n speaking = true;\n}", "static toggleMic () {\n debug('toggleMic');\n\n if (this.vaani.isSpeaking || this.vaani.isListening) {\n this.vaani.cancel();\n\n AppStore.state.standingBy.text = '';\n\n TalkieActions.setActiveAnimation('none');\n TalkieActions.setMode('none');\n\n return;\n }\n\n this.greetUser();\n }", "function muteSFX() {\n mute = true;\n}", "function resetStance() {\n\t\t\t/*jshint validthis:true */\n\t\t\tinAction = 0;\n\t\t\t$(this.element).hide();\n\t\t\tmations[facing][isRunning ? 'run' : 'stand'].show().motio('play');\n\t\t}", "function audioOff() {\n localStorage.setItem(\"audio\", \"off\");\n\n $(\"#audioOff\").removeClass(\"btn-secondary\").addClass(\"btn-danger\");\n $(\"#audioOn\").removeClass(\"btn-success\").addClass(\"btn-secondary\");\n hitSound.volume = 0;\n introMusic.volume = 0;\n gameTheme.volume = 0;\n}", "function resetIsPlayingInteractionSound() {\n isplayingInteractionSound = false;\n }", "function processMute (data) {\n setMute(data)\n}", "set silenceEvents(status) {\n eventStates.silenceEvents = status? true : false;\n }", "function handleMuteState() {\n if (notifications.getAudible()) {\n $(\".mute-notifications\").show();\n $(\".unmute-notifications\").hide();\n } else {\n $(\".mute-notifications\").hide();\n $(\".unmute-notifications\").show();\n }\n\n $(\".mute-notifications\").click(function() {\n notifications.setAudible(false);\n handleMuteState();\n });\n $(\".unmute-notifications\").click(function() {\n notifications.setAudible(true);\n handleMuteState();\n });\n }", "function silenceTimer() {\n silenceCount = setInterval(function () {\n if (!speechStopped) {\n console.log(\"The silence ended in under 3 seconds!\");\n silenceSeconds = -1;\n clearInterval(silenceCount);\n }\n else if (speechStopped) {\n silenceSeconds++;\n if (silenceSeconds > 3) {\n console.log(\"The silence lasted over 3 seconds!\");\n silenceSeconds = -1;\n\n speechEvents.stop();\n clearInterval(silenceCount);\n stopRecording();\n }\n }\n }, 1000);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Someone you follow creates a new location
function notifyFollowerNewLocation(message, next) { let seneca = this; Joi.validate(message.data, validation.notifyNewLocation, (err, data) => { if (err) { log.error(err, 'Validation failed of new locations notify service'); return next(err); } log.info('composing push-notifications for new location'); next(null, {ok: true}); // compose message let messageData = { message: data.user_name + ' hat eine neue Location erstellt.', entity: 'location', entity_id: data.location_id }; service.getFollowersByUserId(data.user_id, seneca) .then(follower => follower.map(o => o._id)) .then(follower => service.getDevices(follower, seneca)) .then(followerDevices => push.sendPush(followerDevices, messageData)) .catch(err=> log.error(err, 'Error executing notify new location service')); }); }
[ "function addLocation() {\n var newLocation = {\n \"name\":vm.locationName,\n \"userId\":user._id,\n \"lat\":vm.lat,\n \"lon\":vm.lon,\n \"webcamURL\":vm.webcamURL,\n \"status\":\"Open\",\n \"comments\":[]\n };\n\n delete newLocation._id;\n LocationService.createLocationForUser(user._id, newLocation)\n .then(function(response) {\n init();\n })\n }", "function addLocation() {\n var newLocation = {\n \"name\":vm.locationName,\n \"userId\":vm.userId,\n \"lat\":vm.lat,\n \"lon\":vm.lon,\n \"webcamURL\":vm.webcamURL,\n \"status\":vm.status,\n \"comments\":[]\n };\n\n LocationService.createLocationForUser(vm.userId, newLocation)\n .then(function(response) {\n init();\n })\n }", "async function createNewFollow() {\n await createFollow(follow);\n }", "createLocation(location, success, fail) {\n api.shared().post('/locations', location)\n .then(function (response) {\n success(response.data);\n })\n .catch(function (error) {\n console.log(error.response)\n fail(error.response.data);\n });\n }", "function actionOnAddLocation() { // TODO: Fix this for when all locations listed\n\tlet isListed = true;\n\tlet location = new Location(this.game);\n\twhile (isListed) {\n\t\tlocation = new Location(this.game);\n\t\tisListed = checkLocationRepeat(location);\n\t}\n\tcurrentLocationList.push(location);\n\taddLocationText(location);\n}", "async function createOneLocation(req, res) {\n\tconst { title, date } = req.body\n\tconst newLocation = {\n\t\ttitle,\n\t\tdate,\n\t}\n\n\ttry {\n\t\tconst createdLocation = await location.create({ data: newLocation })\n\t\tres.json({ createdLocation })\n\t} catch (error) {\n\t\tres.json({ error: error.message })\n\t}\n}", "function follow() {\n User.follow(User.getID(), vm.username);\n }", "async function handleCreateLocation() {\n const location = locationForm.values;\n await handleModalClose();\n await createLocation(location);\n await newLocations();\n }", "static async addUserWaypoint(lat, lon, index, ident) {\n await SimVar.SetSimVarValue('C:fs9gps:FlightPlanNewWaypointLatitude', 'degrees', lat);\n await SimVar.SetSimVarValue('C:fs9gps:FlightPlanNewWaypointLongitude', 'degrees', lon);\n\n if (ident) {\n await SimVar.SetSimVarValue('C:fs9gps:FlightPlanNewWaypointIdent', 'string', ident);\n }\n\n await SimVar.SetSimVarValue('C:fs9gps:FlightPlanAddWaypoint', 'number', index);\n }", "createLocation(e){\n e.preventDefault()\n const name = this.newLocationName.value\n const lat = this.newLocationLat.value\n const long = this.newLocationLong.value\n const photo = this.newLocationPhoto.value\n\n this.adapter.createLocation(name, lat, long, photo).then(location => {\n this.locations.push(new Location(location))\n this.resetField()\n this.render()\n this.likeListener()\n })\n }", "newLocationHandler() {\n var locationName = prompt('Wat is de naam van de nieuwe locatie?');\n\n if(locationName){\n Meteor.call('locations.insert', {\n title: locationName,\n imageUrl: '/files/IconsButtons/Location-26-512.png' // https://cdn2.iconfinder.com/data/icons/location-3/128/Location-26-512.png\n }, this.newLocationAdded.bind(this));\n }\n }", "function saveAndDrawLocation(e) {\n controller.message('Map click received at: ' + e.latlng, 2);\n\n // possible cool thing, create a popup that asks\n // if the user wants to create a node here\n //\n // popup.setLatLng(e.latlng)\n // .setContent(\"Are you sure you want to create a node at: \" + e.latlng.toString())\n // .openOn(map);\n\n // save a new marker to the database\n NarabaziLocation.save(\n // add a marker at the click location\n NarabaziLocation.create(e.latlng)\n );\n }", "_setLocation(location){\n this.location = location;\n this.notify(UpdateMessage.Relocated);\n }", "function followUser(screenName) {\n twitter.post('friendships/create', { screen_name: screenName }, function(err, resp) {\n if (err !== undefined) {\n writeLog('FAIL', `Follow user error for '${screenName}': ${err.message}`)\n } else {\n writeLog('INFO', `Follow user done for '${screenName}'`)\n }\n })\n}", "createLocation(location, success, fail) {\n api.shared().post('/locations', {\n country_code: location.country_code,\n city: location.city,\n latitude: location.latitude,\n longitude: location.longitude,\n place_id: location.place_id,\n is_day_time: location.is_day_time,\n day_time: location.day_time,\n is_night_time: location.is_night_time,\n night_time: location.night_time,\n })\n .then(function(response) {\n success(response.data);\n })\n .catch(function(error) {\n console.log(error.response)\n fail(error.response.data);\n });\n }", "function handleLocation(data) {\n\n var self = this;\n\n if (self.locationsById[data.locationId]) {\n self.locationsById[data.locationId].isMember = true;\n self.locationsById[data.locationId].members = data.members;\n sqlHelper.updateLocationsAndMembership([self.locationsById[data.locationId]], function (err) {\n if (err) {\n console.error(err);\n } else {\n console.log(\"Bot joined previously followed location and updated sql membership\\n\\tLocation: %j\", self.locationsById[data.locationId]);\n }\n });\n } else {\n console.log(\"New location found, performing location update (%j)\", data);\n self.locationUpdateTask.call(self);\n }\n}", "handleFollow() {\n // debugger\n if (this.props.session.id !== this.props.user.id) {\n const follow = {\n follower_id: this.props.session.id,\n following_id: this.props.user.id\n }\n\n this.props.createFollow(follow)\n } else {\n console.log(\"You cannot follow yourself -temp \")\n }\n }", "function onNewLocation() {\n\n //get a MapBox object with coordinates\n let liveLocation = liveLocationMarker.getLngLat();\n\n //Parse and create a Turf.js Point with the new location data\n let liveLng = liveLocation.lng;\n let liveLat = liveLocation.lat;\n\n //Send location to server\n socket.emit(\"new-location-from-phone\", { \"lng\": liveLng, \"lat\": liveLat });\n\n}", "function putPeopleLocation(server, db){\n\t\tvar putPeopleLocationChain = [\n\t\t\t\tplaceFromCoords(db),\n\t\t\t\tverifyPlace(db),\n\t\t\t\tupdatePerson(db),\n\t\t\t\tupdateOldPlace(db),\n\t\t\t\tupdateNewPlace(db),\n\t\t\t\tfinalize(db)\n\t\t];\n\n\t\tserver.put('/people/:uid', putPeopleLocationChain);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define sankey diagram class
function sankey(options) { //remove legend if (options.legend) { options.legend.enabled = false; } else { options.legend = { enabled: false }; } //declare needed variables let diagram = eve.initVis(options), currentSerie = diagram.series[0], totalMeasure = 0, maxNodeLength = 0, maxTextLength = 0, autoMarginSides = 0, autoMarginTop = 0, margin = { left: 0, top: 0, bottom: diagram.margin.bottom, right: 0 }, width = 0, height = 0, sankey = null, path = null, rects, axisLabels, labels, xPos = 0, yPos = 0, linkSVG = null, nodeSVG = null; //calculates scales and environmental variables function calculateScales() { //iterate nodes to create their colors diagram.data.nodes.forEach(function (n, i) { n.color = i >= e.colors.length ? e.randColor() : e.colors[i]; }); //set total measure totalMeasure = d3.sum(diagram.data.links, function (d) { return +d[currentSerie.measureField]; }); maxNodeLength = d3.max(diagram.data.nodes, function (d) { return d.name.toString().length; }); maxTextLength = maxNodeLength > totalMeasure.toString().length ? maxNodeLength : totalMeasure.toString().length; //set label font size if (currentSerie.labelFontSize === 'auto') currentSerie.labelFontSize = 11; //set label font color if (currentSerie.labelFontColor === 'auto') currentSerie.labelFontColor = '#333333'; //calculate auto margins autoMarginSides = 10; autoMarginTop = diagram.xAxis.labelFormat ? diagram.xAxis.labelFontSize * 2 : 10; margin.left = autoMarginSides; margin.right = autoMarginSides; margin.top = autoMarginTop + diagram.xAxis.labelFontSize; margin.bottom = autoMarginTop; //calculate dimension width = diagram.plot.width - margin.left - margin.right; height = diagram.plot.height - margin.top - margin.bottom; } //animates diagram function animateDiagram() { //animate links linkSVG .attr('opacity', diagram.animation.effect === 'add' ? 0 : 1) .transition().duration(diagram.animation.duration) .ease(diagram.animation.easing.toEasing()) .delay(function (d, i) { return i * diagram.animation.delay; }) .attr('opacity', 1) .attr('stroke', function (d) { return d.source.color; }) .attr('stroke-width', function (d) { return Math.max(1, d.dy); }); //animate nodes rects .attr('opacity', diagram.animation.effect === 'add' ? 0 : 1) .transition().duration(diagram.animation.duration) .ease(diagram.animation.easing.toEasing()) .delay(function (d, i) { return i * diagram.animation.delay; }) .attr('opacity', 1) .attr('transform', function (d) { return 'translate(0,0)'; }) .attr('height', function (d) { return Math.abs(d.dy); }) .attr('fill', function (d) { return d.color; }) .attr('stroke', function (d) { return d3.rgb(d.color).darker(2); }); //animate axis labels axisLabels .transition().duration(diagram.animation.duration) .ease(diagram.animation.easing.toEasing()) .delay(function (d, i) { return i * diagram.animation.delay; }) .attr('transform', function (d) { return 'translate(0,' + (-1 * (diagram.xAxis.labelFontSize / 2)) + ')'; }) //animate axis labels labels .style('text-anchor', function (d) { return (d.x < width / 2) ? 'start' : 'end'; }) .transition().duration(diagram.animation.duration) .ease(diagram.animation.easing.toEasing()) .delay(function (d, i) { return i * diagram.animation.delay; }) .attr('transform', function (d) { xPos = d.x < width / 2 ? (sankey.nodeWidth() + 5) : -5; yPos = (d.dy / 2); return 'translate(' + xPos + ',' + yPos + ')'; }) } //initializes diagram and draw links function initDiagram() { //set sankey function and create paths and links sankey = d3.sankey().nodeWidth(36).nodePadding(5).size([width, height]); path = sankey.link(); sankey.nodes(diagram.data.nodes).links(diagram.data.links).layout(32); //gets expressioned data value let getExpressionedDataValue = function (d) { let expValue = d.value; let children = (d.sourceLinks && d.sourceLinks.length) ? d.sourceLinks : d.targetLinks; if (children.length === 0) return expValue; switch (currentSerie.expression) { case "avg": { expValue = d.value / children.length; //get average value var avgValue = diagram.data.averages[d.name]; if (avgValue != null) expValue = avgValue; } break; case "min": { expValue = d3.min(children, function (v) { return v.value; }); //get average value var avgValue = diagram.data.averages[d.name]; if (avgValue != null) expValue = avgValue; } break; case "max": { expValue = d3.max(children, function (v) { return v.value; }); //get average value var avgValue = diagram.data.averages[d.name]; if (avgValue != null) expValue = avgValue; } break; } return expValue; }; //create links linkSVG = diagramG .append('g') .selectAll('.eve-sankey-link') .data(diagram.data.links) .enter().append('path') .attr('class', 'eve-sankey-link') .style('stroke-opacity', 0.5) .style('fill', 'none') .style('fill-opacity', 0) .attr('d', path) .attr('stroke', function (d) { return d.source.color; }) .attr('stroke-width', 1) .on('mousemove', function (d, i) { //show tooltip diagram.showTooltip(diagram.getContent(d, currentSerie, diagram.tooltip.format, d.source.name, d.target.name)); }) .on('mouseout', function (d, i) { //hide tooltip diagram.hideTooltip(); }) .sort(function (a, b) { return b.dy - a.dy; }); //create nodes nodeSVG = diagramG .append('g') .selectAll('.eve-sankey-node') .data(diagram.data.nodes) .enter().append('g') .attr('class', 'eve-sankey-node') .attr('transform', function (d) { xPos = d.x; yPos = (isNaN(d.y) ? 0 : d.y); return 'translate(' + xPos + ',' + yPos + ')'; }); //attach rectangles rects = nodeSVG.append('rect') .attr('width', sankey.nodeWidth()) .attr('height', 0) .style('stroke-width', 1) .attr('fill', function (d) { return d.color; }) .attr('stroke', function (d) { return d3.rgb(d.color).darker(0); }) .on('mousemove', function (d, i) { //update data value d.expressionedDataValue = getExpressionedDataValue(d); //show value diagram.showTooltip(diagram.getContent(d, currentSerie, (diagram.tooltip.format !== '' ? '{source}: {value}' : ''))); }) .on('mouseout', function (d, i) { //hide tooltip diagram.hideTooltip(); }); //attach axis labels axisLabels = nodeSVG.append('text') .style('fill', diagram.xAxis.labelFontColor) .style('font-size', diagram.xAxis.labelFontSize + 'px') .style('font-family', diagram.xAxis.labelFontFamily + ', Arial, Helvetica, Ubuntu') .style('font-style', diagram.xAxis.labelFontStyle === 'bold' ? 'normal' : diagram.xAxis.labelFontStyle) .style('font-weight', diagram.xAxis.labelFontStyle === 'bold' ? 'bold' : 'normal') .style('text-anchor', 'start') .text(function (d) { return diagram.getContent(d, currentSerie, diagram.xAxis.labelFormat); }); //attach labels labels = nodeSVG.append('text') .style('fill', currentSerie.labelFontColor) .style('font-size', currentSerie.labelFontSize + 'px') .style('font-family', currentSerie.labelFontFamily + ', Arial, Helvetica, Ubuntu') .style('font-style', currentSerie.labelFontStyle === 'bold' ? 'normal' : currentSerie.labelFontStyle) .style('font-weight', currentSerie.labelFontStyle === 'bold' ? 'bold' : 'normal') .style('text-anchor', 'start') .attr('dy', '.35em') .text(function (d) { return diagram.getContent(d, currentSerie, currentSerie.labelFormat); }); //attach drag nodeSVG.call(d3.drag() .subject(function (d) { return d; }) .on('start', function (d) { this.parentNode.appendChild(this); }) .on('drag', dragMove)); } //create inner function to handle drag move function dragMove(d) { //select current node d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")"); //relayout sankey sankey.relayout(); //update svg path linkSVG.attr("d", path); } //calculate environment calculateScales(); //create diagram g let diagramG = diagram.svg.append('g') .attr('class', 'eve-vis-g') .attr('transform', 'translate(' + diagram.plot.left + ',' + margin.top + ')'); //init diagram and animate initDiagram(); animateDiagram(); //update diagram diagram.update = function (data) { //set diagram data diagram.data = data; //recalculate scales calculateScales(); //remove g if (diagram.animation.effect) { //check whether the effect is fade if (diagram.animation.effect === 'fade') { //remove with transition diagramG.transition().duration(1000).style('opacity', 0).remove(); } else if (diagram.animation.effect === 'dim') { //remove with transition diagramG.style('opacity', 0.15); } else if (diagram.animation.effect === 'add') { //remove with transition diagramG.style('opacity', 1); } else { //remove immediately diagramG.remove(); } } else { //remove immediately diagramG.remove(); } //re-append g diagramG = diagram.svg.append('g') .attr('class', 'eve-vis-g') .attr('transform', 'translate(' + diagram.plot.left + ',' + margin.top + ')'); //animate diagram initDiagram(); animateDiagram(); }; //attach clear content method to chart diagram.clear = function () { //remove g from the content diagram.svg.selectAll('.eve-vis-g').remove(); }; //return abacus diagram return diagram; }
[ "function addClassDiagram() {\r\n\r\n\tclearModes();\r\n\tgraph.addCell( new uml.Class( {\r\n\t\tposition: { x: 100+createOffset , y: 100+createOffset },\r\n\t\tsize: { width: 180 , height: 50},\r\n\t\tname: propertyBox.get( 'klassenName' ),\r\n\t\tattributes: propertyBox.get( 'attribute' ),\r\n\t\tmethods: propertyBox.get( 'methoden' ),\r\n\t\tattrs: {\r\n\t\t\t'.uml-class-name-rect': {\r\n\t\t\t\tfill: propertyBox.get( 'farbePrimaer' ),\r\n\t\t\t\tstroke: '#fff',\r\n\t\t\t\t'stroke-width': 0.5\r\n\t\t\t},\r\n\t\t\t'.uml-class-attrs-rect, .uml-class-methods-rect': {\r\n\t\t\t\tfill: propertyBox.get( 'farbeSekundaer' ),\r\n\t\t\t\tstroke: '#fff',\r\n\t\t\t\t'stroke-width': 0.5\r\n\t\t\t}\r\n\t\t}\r\n\t}))\r\n\tcreateOffset = ( createOffset + 10 ) % 100;\r\n\tserialize();\r\n\r\n}", "function draw_sankey(params){\r\n\t// Problem: nutzt alte Version von d3: \r\n\t// Lösung: d3v3 manipuliert, anderer Funktionsaufruf\r\n\t \r\n\t console.log(params)\r\n\t params.units ? units = \" \" + params.units : units = \"\";\r\n\t \r\n\t //Added Content\r\n\t \r\n\t var margin = {top: 10, right: 10, bottom: 10, left: 10},\r\n\t\t\t\t\t\t\t\t\t width = params.width\r\n\t\t\t\t\t\t\t\t /* width = document.getElementById(\"inhalt\").offsetWidth */\r\n\t \r\n\t\t\t\t\t\t\t var height = params.height\r\n\t \r\n\t \r\n\t //hard code these now but eventually make available\r\n\t var formatNumber = d3v3.format(\"0,.0f\"), // zero decimal places\r\n\t\t format = function(d) { return formatNumber(d) + units; },\r\n\t\t color = d3v3.scale.category20();\r\n\t \r\n\t if(params.labelFormat){\r\n\t\t formatNumber = d3v3.format(\".2%\");\r\n\t }\r\n\t \r\n\t /* var svg = d3v3.select('#' + params.id).append(\"svg\")\r\n\t\t .attr(\"width\", params.width)\r\n\t\t .attr(\"height\", params.height); */\r\n\t \r\n\t // append the svg canvas to the page\r\n\t var svg = d3v3.select('#' + params.id)\r\n\t\t\t\t\t\t\t .attr(\"width\", width + margin.left + margin.right)\r\n\t\t\t\t\t\t\t .attr(\"height\", height + margin.top + margin.bottom)\r\n\t\t\t\t\t\t\t .append(\"g\")\r\n\t\t\t\t\t\t\t .attr(\"transform\", \r\n\t\t\t\t\t\t\t\t\t \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\t \r\n\t \r\n\t \r\n\t \r\n\t\t \r\n\t var sankey = d3.sankey()\r\n\t\t .nodeWidth(params.nodeWidth)\r\n\t\t .nodePadding(params.nodePadding)\r\n\t\t .layout(params.layout)\r\n\t\t .size([params.width,params.height]);\r\n\t\t \r\n\t var path = sankey.link();\r\n\t\t \r\n\t var data = params.data,\r\n\t\t links = [],\r\n\t\t nodes = [];\r\n\t\t \r\n\t //get all source and target into nodes\r\n\t //will reduce to unique in the next step\r\n\t //also get links in object form\r\n\t data.source.forEach(function (d, i) {\r\n\t\t nodes.push({ \"name\": data.source[i] });\r\n\t\t nodes.push({ \"name\": data.target[i] });\r\n\t\t links.push({ \"source\": data.source[i], \"target\": data.target[i], \"value\": +data.value[i] });\r\n\t }); \r\n\t \r\n\t //now get nodes based on links data\r\n\t //thanks Mike Bostock https://groups.google.com/d/msg/d3v3-js/pl297cFtIQk/Eso4q_eBu1IJ\r\n\t //this handy little function returns only the distinct / unique nodes\r\n\t nodes = d3v3.keys(d3v3.nest()\r\n\t\t\t\t\t .key(function (d) { return d.name; })\r\n\t\t\t\t\t .map(nodes));\r\n\t \r\n\t //it appears d3v3 with force layout wants a numeric source and target\r\n\t //so loop through each link replacing the text with its index from node\r\n\t links.forEach(function (d, i) {\r\n\t\t links[i].source = nodes.indexOf(links[i].source);\r\n\t\t links[i].target = nodes.indexOf(links[i].target);\r\n\t });\r\n\t \r\n\t //now loop through each nodes to make nodes an array of objects rather than an array of strings\r\n\t nodes.forEach(function (d, i) {\r\n\t\t nodes[i] = { \"name\": d };\r\n\t });\r\n\t \r\n\t sankey\r\n\t\t .nodes(nodes)\r\n\t\t .links(links)\r\n\t\t .layout(params.layout);\r\n\t\t \r\n\t var link = svg.append(\"g\").selectAll(\".link\")\r\n\t\t .data(links)\r\n\t .enter().append(\"path\")\r\n\t\t .attr(\"class\", \"link\")\r\n\t\t .attr(\"d\", path)\r\n\t\t .style(\"stroke-width\", function (d) { return Math.max(1, d.dy); })\r\n\t\t .sort(function (a, b) { return b.dy - a.dy; });\r\n\t \r\n\t link.append(\"title\")\r\n\t\t .text(function (d) { return d.source.name + \" → \" + d.target.name + \"\\n\" + format(d.value); });\r\n\t \r\n\t var node = svg.append(\"g\").selectAll(\".node\")\r\n\t\t .data(nodes)\r\n\t .enter().append(\"g\")\r\n\t\t .attr(\"class\", \"node\")\r\n\t\t .attr(\"transform\", function (d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; })\r\n\t .call(d3v3.behavior.drag()\r\n\t\t .origin(function (d) { return d; })\r\n\t\t .on(\"dragstart\", function () { this.parentNode.appendChild(this); })\r\n\t\t .on(\"drag\", dragmove));\r\n\t \r\n\t node.append(\"rect\")\r\n\t\t .attr(\"height\", function (d) { return d.dy; })\r\n\t\t .attr(\"width\", sankey.nodeWidth())\r\n\t\t .style(\"fill\", function (d) { return d.color = color(d.name.replace(/ .*/, \"\")); })\r\n\t\t .style(\"stroke\", function (d) { return d3v3.rgb(d.color).darker(2); })\r\n\t .append(\"title\")\r\n\t\t .text(function (d) { return d.name + \"\\n\" + format(d.value); });\r\n\t \r\n\t node.append(\"text\")\r\n\t\t .attr(\"x\", -6)\r\n\t\t .attr(\"y\", function (d) { return d.dy / 2; })\r\n\t\t .attr(\"dy\", \".35em\")\r\n\t\t .attr(\"text-anchor\", \"end\")\r\n\t\t .attr(\"transform\", null)\r\n\t\t .text(function (d) { return d.name; })\r\n\t .filter(function (d) { return d.x < params.width / 2; })\r\n\t\t .attr(\"x\", 6 + sankey.nodeWidth())\r\n\t\t .attr(\"text-anchor\", \"start\");\r\n\t \r\n\t \r\n\t \r\n\t\t // the function for moving the nodes\r\n\t function dragmove(d) {\r\n\t\t d3v3.select(this).attr(\"transform\", \r\n\t\t\t \"translate(\" + (\r\n\t\t\t\t\t\t d.x = Math.max(0, Math.min(params.width - d.dx, d3v3.event.x))\r\n\t\t\t\t\t ) + \",\" + (\r\n\t\t\t\t\t\t d.y = Math.max(0, Math.min(params.height - d.dy, d3v3.event.y))\r\n\t\t\t\t\t ) + \")\");\r\n\t\t\t sankey.relayout();\r\n\t\t\t link.attr(\"d\", path);\r\n\t\t }\r\n\t // to be specific in case you have more than one chart\r\n\t d3v3.selectAll('#main path.link')\r\n\t\t .style('stroke', function(d){\r\n\t\t //here we will use the source color\r\n\t\t //if you want target then sub target for source\r\n\t\t //or if you want something other than gray\r\n\t\t //supply a constant\r\n\t\t //or use a categorical scale or gradient\r\n\t\t return d.source.color;\r\n\t\t })\r\n\t\t//note no changes were made to opacity\r\n\t\t//to do uncomment below but will affect mouseover\r\n\t\t//so will need to define mouseover and mouseout\r\n\t\t//happy to show how to do this also\r\n\t\t// .style('stroke-opacity', .7)\r\n\r\n\t \r\n\t}", "function BpmnDiagrams(){//Code conversion for Bpmn Shapes\n//Start Region\n/** @private */this.annotationObjects={};//constructs the BpmnDiagrams module\n}", "function draw_sankey(params){\r\n\t\r\n\t// Problem: nutzt alte Version von d3: \r\n\t// Lösung: d3v3 manipuliert, anderer Funktionsaufruf\r\n\t \r\n\t console.log(params)\r\n\t params.units ? units = \" \" + params.units : units = \"\";\r\n\t \r\n\t \r\n\t \r\n\t var margin = {top: 10, right: 10, bottom: 10, left: 10},\r\n\t\t\t\t\t\t\t\t\t width = params.width\r\n\t\t\t\t\t\t\t\t \t \r\n\t\t\t\t\t\t\t var height = params.height\r\n\t \r\n\t \r\n\t //hard code these now but eventually make available\r\n\t var formatNumber = d3v3.format(\"0,.0f\"), // zero decimal places\r\n\t\t format = function(d) { return formatNumber(d) + units; },\r\n\t\t color = d3v3.scale.category10();\r\n\t \r\n\t if(params.labelFormat){\r\n\t\t formatNumber = d3v3.format(\".2%\");\r\n\t }\r\n\t \r\n\t // append the svg canvas to the page\r\n\t var svg = d3v3.select('#' + params.id)\r\n\t\t\t\t\t\t\t .attr(\"width\", width + margin.left + margin.right)\r\n\t\t\t\t\t\t\t .attr(\"height\", height + margin.top + margin.bottom)\r\n\t\t\t\t\t\t\t .append(\"g\")\r\n\t\t\t\t\t\t\t .attr(\"transform\", \r\n\t\t\t\t\t\t\t\t\t \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\t \r\n\t \r\n\t \r\n\t \t\t \r\n\t var sankey = d3.sankey()\r\n\t\t .nodeWidth(params.nodeWidth)\r\n\t\t .nodePadding(params.nodePadding)\r\n\t\t .layout(params.layout)\r\n\t\t .size([params.width,params.height]);\r\n\t\t \r\n\t var path = sankey.link();\r\n\t\t \r\n\t var data = params.data,\r\n\t\t links = [],\r\n\t\t nodes = [];\r\n\t\t \r\n\t //get all source and target into nodes\r\n\t //will reduce to unique in the next step\r\n\t //also get links in object form\r\n\t data.source.forEach(function (d, i) {\r\n\t\t nodes.push({ \"name\": data.source[i] });\r\n\t\t nodes.push({ \"name\": data.target[i] });\r\n\t\t links.push({ \"source\": data.source[i], \"target\": data.target[i], \"value\": +data.value[i] });\r\n\t }); \r\n\t \r\n\t //now get nodes based on links data\r\n\t //thanks Mike Bostock \r\n\t //this handy little function returns only the distinct / unique nodes\r\n\t nodes = d3v3.keys(d3v3.nest()\r\n\t\t\t\t\t .key(function (d) { return d.name; })\r\n\t\t\t\t\t .map(nodes));\r\n\t \r\n\t //it appears d3v3 with force layout wants a numeric source and target\r\n\t //so loop through each link replacing the text with its index from node\r\n\t links.forEach(function (d, i) {\r\n\t\t links[i].source = nodes.indexOf(links[i].source);\r\n\t\t links[i].target = nodes.indexOf(links[i].target);\r\n\t });\r\n\t \r\n\t //now loop through each nodes to make nodes an array of objects rather than an array of strings\r\n\t nodes.forEach(function (d, i) {\r\n\t\t nodes[i] = { \"name\": d };\r\n\t });\r\n\t \r\n\t sankey\r\n\t\t .nodes(nodes)\r\n\t\t .links(links)\r\n\t\t .layout(params.layout);\r\n\t\t \r\n\r\n\t\t //links\r\n\t var link = svg.append(\"g\").selectAll(\".link\")\r\n\t\t .data(links)\r\n\t .enter().append(\"path\")\r\n\t\t .attr(\"class\", \"link\")\r\n\t\t .attr(\"d\", path)\r\n\t\t .style(\"stroke-width\", function (d) { return Math.max(1, d.dy); })\r\n\t\t .sort(function (a, b) { return b.dy - a.dy; });\r\n\t \r\n\t\t //titel\r\n\t link.append(\"title\")\r\n\t\t .text(function (d) { return d.source.name + \" → \" + d.target.name + \"\\n\" + format(d.value); });\r\n\t\t \r\n\t\t //nodes\r\n\t var node = svg.append(\"g\").selectAll(\".node\")\r\n\t\t .data(nodes)\r\n\t .enter().append(\"g\")\r\n\t\t .attr(\"class\", \"node\")\r\n\t\t .attr(\"transform\", function (d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; })\r\n\t .call(d3v3.behavior.drag()\r\n\t\t .origin(function (d) { return d; })\r\n\t\t .on(\"dragstart\", function () { this.parentNode.appendChild(this); })\r\n\t\t .on(\"drag\", dragmove));\r\n\t \r\n\t \t//rectangles on nodes\r\n\t node.append(\"rect\")\r\n\t\t .attr(\"height\", function (d) { return d.dy; })\r\n\t\t .attr(\"width\", sankey.nodeWidth())\r\n\t\t .style(\"fill\", function (d) { return d.color = color(d.name.replace(/ .*/, \"\")); })\r\n\t\t \t\t .style(\"stroke\", function (d) { return d3v3.rgb(d.color).darker(2); })\r\n\t .append(\"title\")\r\n\t\t .text(function (d) { return d.name + \"\\n\" + format(d.value); });\r\n\t \r\n\t \t//title for nodes\r\n\t node.append(\"text\")\r\n\t\t .attr(\"class\", \"font-weight-bold\")\r\n\t\t .attr(\"x\", -6)\r\n\t\t .attr(\"y\", function (d) { return d.dy / 2; })\r\n\t\t .attr(\"dy\", \".35em\")\r\n\t\t .attr(\"text-anchor\", \"end\")\r\n\t\t .attr(\"transform\", null)\r\n\t\t .text(function (d) { return d.name; })\r\n\t .filter(function (d) { return d.x < params.width / 2; })\r\n\t\t .attr(\"x\", 6 + sankey.nodeWidth())\r\n\t\t .attr(\"text-anchor\", \"start\");\r\n\t \r\n\t\t // the function for moving the nodes\r\n\t function dragmove(d) {\r\n\t\t d3v3.select(this).attr(\"transform\", \r\n\t\t\t \"translate(\" + (\r\n\t\t\t\t\t\t d.x = Math.max(0, Math.min(params.width - d.dx, d3v3.event.x))\r\n\t\t\t\t\t ) + \",\" + (\r\n\t\t\t\t\t\t d.y = Math.max(0, Math.min(params.height - d.dy, d3v3.event.y))\r\n\t\t\t\t\t ) + \")\");\r\n\t\t\t sankey.relayout();\r\n\t\t\t link.attr(\"d\", path);\r\n\t\t }\r\n\r\n\t //Change color of the links\r\n\t d3v3.selectAll('#main path.link')\r\n\t\t .style('stroke', function(d){\r\n\t\t return d.source.color;\r\n\t\t })\r\n\t}", "function generateSankey() {\n d3.select(\"svg\").remove();\n\n var formatNumber = d3.format(\",.0f\"), // zero decimal places\n format = function (d) {\n return formatNumber(d) + \" \" + units;\n },\n color = d3.scale.category20();\n\n // append the svg canvas to the page\n var svg = d3.select(\"#chart\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", Math.abs(height + margin.top + margin.bottom))\n .append(\"g\")\n .attr(\"transform\",\n \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n // Set the sankey diagram properties\n var sankey = d3.sankey()\n .nodeWidth(36)\n .nodePadding(10)\n .size([width, height]);\n\n var path = sankey.link();\n var i = 1;\n var j = 2;\n\n\n var graph = records.graph;\n // return only the distinct / unique nodes\n graph.nodes = d3.keys(d3.nest()\n .key(function (d) {\n return d.name;\n })\n .map(graph.nodes));\n\n // loop through each link replacing the text with its index from node\n graph.links.forEach(function (d, i) {\n graph.links[i].source = graph.nodes.indexOf(graph.links[i].source);\n graph.links[i].target = graph.nodes.indexOf(graph.links[i].target);\n });\n\n //now loop through each nodes to make nodes an array of objects\n // rather than an array of strings\n graph.nodes.forEach(function (d, i) {\n graph.nodes[i] = {\"name\": d};\n });\n\n sankey\n .nodes(graph.nodes)\n .links(graph.links)\n .layout(32);\n\n\n // add in the links\n var link = svg.append(\"g\").selectAll(\".link\")\n .data(graph.links)\n .enter().append(\"path\")\n .attr(\"class\", function (d) {\n return \"link \" + d.flow;\n })\n // .attr(\"class\", \"link\")\n .attr(\"d\", path)\n .style(\"stroke-width\", function (d) {\n return Math.max(1, d.dy);\n })\n .sort(function (a, b) {\n return b.dy - a.dy;\n });\n\n // add the link titles\n link.append(\"title\")\n .text(function (d) {\n return d.source.name + \" → \" +\n d.target.name + \"\\n\" + d.flow + \"\\n\" + format(d.value);\n });\n\n // add in the nodes\n var node = svg.append(\"g\").selectAll(\".node\")\n .data(graph.nodes)\n .enter().append(\"g\")\n .attr(\"class\", function (d) {\n return \"node \" + d.flow;\n })\n .attr(\"transform\", function (d) {\n return \"translate(\" + d.x + \",\" + d.y + \")\";\n })\n .call(d3.behavior.drag()\n .origin(function (d) {\n return d;\n })\n .on(\"dragstart\", function () {\n this.parentNode.appendChild(this);\n })\n .on(\"drag\", dragmove));\n\n // add the rectangles for the nodes\n node.append(\"rect\")\n .attr(\"height\", function (d) {\n return Math.abs(d.dy);\n })\n .attr(\"width\", sankey.nodeWidth())\n .style(\"fill\", function (d) {\n return d.color = color(d.name.replace(/ .*/, \"\"));\n })\n .style(\"stroke\", function (d) {\n return d3.rgb(d.color).darker(2);\n })\n .append(\"title\")\n .text(function (d) {\n return d.name + \"\\n\" + format(d.value);\n });\n\n // add in the title for the nodes\n node.append(\"text\")\n .attr(\"x\", -6)\n .attr(\"y\", function (d) {\n return d.dy / 2;\n })\n .attr(\"dy\", \".15em\")\n .attr(\"text-anchor\", \"end\")\n .attr(\"transform\", null)\n .text(function (d) {\n return d.name;\n })\n .filter(function (d) {\n return d.x < width / 2;\n })\n .attr(\"x\", 6 + sankey.nodeWidth())\n .attr(\"text-anchor\", \"start\");\n\n // the function for moving the nodes\n function dragmove(d) {\n d3.select(this).attr(\"transform\",\n \"translate(\" + d.x + \",\" + (\n d.y = Math.abs(Math.max(0, Math.min(height - d.dy, d3.event.y)))\n ) + \")\");\n sankey.relayout();\n link.attr(\"d\", path);\n }\n }", "function gen_sankey(){\n var units = \"Connections\";\n var rect;\n \n // set the dimensions and margins of the graph\n var margin = {top: 10, right: 10, bottom: 10, left: 10},\n width = 450 - margin.left - margin.right,\n height = 304 - margin.top - margin.bottom;\n\n // format variables\n var formatNumber = d3.format(\",.0f\"), // zero decimal places\n format = function(d) { return formatNumber(d) + \" \" + units; },\n color = d3.scaleOrdinal(d3.schemeSet2 ); //schemeCategory20 /20c\n\n // Set tooltips\n sankey_tip = d3.tip()\n .attr('class', 'd3-tip')\n .offset([-10, 0])\n .html(function (d) {\n return \"<strong></strong><span class='details'>\" + (d.name ? d.name : d.source.name + \" → \" +\n d.target.name) + \"<br></span>\" +\n \"<strong>Nº Winners: </strong><span class='details'>\" + format(d.value) + \"</span>\";\n })\n \n sankey_colors=color;\n // append the svg object to the body of the page\n var svg = d3.select(\"#sankey_diagram\")\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\",\n \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n // Set the sankey diagram properties\n var sankey = d3.sankey()\n .nodeWidth(20)\n .nodePadding(40)\n .size([width, height]);\n\n var path = sankey.link();\n\n svg.call(sankey_tip);\n // load the data\n d3.json(\"data/sankeyTop5.json\", function(error, graph) {\n\n sankey.nodes(graph.nodes)\n .links(graph.links)\n .layout(32);\n\n // add in the links\n var link = svg.append(\"g\")\n .selectAll(\".link\")\n .data(graph.links)\n .enter().append(\"path\")\n .attr(\"class\", \"link\")\n .attr(\"d\", path)\n .attr(\"category\", function (d) { return d.source.name;})\n .attr(\"affiliationName\",function(d){ return d.target.name; })\n .attr(\"affiliationCountry\",function(d){\n if (d.target.country!=null)\n return d.target.country;\n })\n .style(\"stroke\", function(d) {return choose_sankey_color(d.target.name); })\n .style(\"stroke-width\", function(d) { return Math.max(1, d.dy); })\n .sort(function(a, b) { return b.dy - a.dy; })\n .on(\"mouseenter\", function (d) {\n cleanMouseEvent();\n //Opacity 0.5\n d3.selectAll(\"circle,rect,path\")\n .transition()\n .duration(700)\n .style(\"opacity\",0.2);\n\n //Change this\n sankey_tip.show(d);\n d3.select(this)\n .transition()\n .duration(700)\n .style(\"opacity\", 1)\n .style(\"stroke-opacity\",0.7);\n\n d3.select(\"#sankey_diagram\").selectAll(\"rect[affiliationName=\\'\" + d.target.name + \"\\']\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1);\n d3.select(\"#sankey_diagram\").selectAll(\"rect[affiliationName=\\'\" + d.source.name + \"\\']\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1);\n\n //Cleveland Plot\n d3.selectAll(\"circle[affiliation=\\'\" + d.target.name + \"\\']\").filter(\"circle[category =\\'\" + d.source.name + \"\\']\")\n .transition()\n .duration(700)\n .style('r',r*2);\n\n d3.selectAll(\"g.scatter_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n\n //Map\n d3.selectAll(\"path[country=\\'\" + d.target.country + \"\\']\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1)\n .style(\"stroke\", \"white\")\n .style(\"stroke-width\", 1.5);\n\n d3.selectAll(\"g.world_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n\n //Chord Chart\n d3.select(\"#chord\").selectAll(\"text\")\n .transition()\n .duration(700)\n .style(\"opacity\",0.2);\n\n d3.selectAll(\"g.chord_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n })\n .on(\"mouseout\", cleanMouseEvent);\n\n // add in the nodes\n var node = svg.append(\"g\").selectAll(\".node\")\n .data(graph.nodes)\n .enter().append(\"g\")\n .attr(\"class\", \"node\")\n .attr(\"transform\", function(d) {\n \t return \"translate(\" + d.x + \",\" + d.y + \")\"; })\n .call(d3.drag()\n .subject(function(d) { return d; })\n .on(\"start\", function() {\n this.parentNode.appendChild(this);\n })\n .on(\"drag\", dragmove));\n\n // add the rectangles for the nodes\n rect = node.append(\"rect\")\n .attr(\"height\", function(d) { return d.dy; })\n .attr(\"width\", sankey.nodeWidth())\n .attr(\"affiliationName\",function(d){ return d.name })\n .attr(\"affiliationCountry\",function(d){\n if (d.country!=null)\n return d.country;\n })\n .style(\"fill\", function(d) {return d.color = choose_sankey_color(d.name.replace(/ .*/, \"\")); })\n .style(\"stroke\", function(d) {return d3.rgb(d.color).darker(2); })\n .on(\"mouseenter\", function (d) {\n cleanMouseEvent();\n //Opacity 0.5\n d3.selectAll(\"circle,rect,path\")\n .transition()\n .duration(500)\n .style(\"opacity\", 0.2);\n\n //Change this\n sankey_tip.show(d);\n d3.select(this)\n .transition()\n .duration(700)\n .style(\"opacity\", 1);\n\n d3.select(\"#sankey_diagram\").selectAll(\"path[affiliationName=\\'\" + d.name + \"\\']\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1)\n .style(\"stroke-opacity\", 0.7);\n\n d3.selectAll(\"g.world_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n\n //Cleveland Plot\n d3.selectAll(\"circle[affiliation=\\'\" + d.name + \"\\']\")\n .transition()\n .duration(700)\n .style('r', r * 2);\n\n d3.select(\"#\" + d.name.toLowerCase()).selectAll(\"circle,rect\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1);\n\n d3.selectAll(\"g.scatter_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n\n //Map\n d3.selectAll(\"path[country=\\'\" + d.country + \"\\']\")\n .transition()\n .duration(700)\n .style(\"opacity\", 1)\n .style(\"stroke\", \"white\")\n .style(\"stroke-width\", 1.5);\n\n d3.selectAll(\"g.world_legend_color\").selectAll(\"*\")\n .style(\"opacity\", 0);\n\n //Chord Chart\n d3.select(\"#chord\").selectAll(\"text\")\n .transition()\n .duration(700)\n .style(\"opacity\",0.2);\n\n d3.selectAll(\"g.chord_legend_color\").selectAll(\"*\")\n .transition()\n .duration(700)\n .style(\"opacity\", 0);\n })\n .on(\"mouseout\", cleanMouseEvent);\n\n // add in the title for the nodes\n node.append(\"text\")\n .attr(\"x\", -6)\n .attr(\"y\", function(d) { return d.dy / 2; })\n .attr(\"dy\", \".35em\")\n .attr(\"text-anchor\", \"end\")\n .attr(\"transform\", null)\n .text(function(d) { return d.name; })\n .style(\"pointer-events\", \"none\")\n .filter(function(d) { return d.x < width / 2; })\n .attr(\"x\", 6 + sankey.nodeWidth())\n .attr(\"text-anchor\", \"start\");\n\n // the function for moving the nodes\n function dragmove(d) {\n d3.select(this).attr(\"transform\",\n \"translate(\" + (\n \t d.x = Math.max(0, Math.min(width - d.dx, d3.event.x))\n \t) + \",\" + (\n d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))\n ) + \")\");\n sankey.relayout();\n link.attr(\"d\", path);\n }\n });\n}", "function drawSankey()\n{\n sankey\n .nodes(d3.map(nodeMap))\n .links(totalLinks)\n .layout(32);\n\n drawConnections(totalLinks, \"link\");\n drawNodes(d3.values(nodeMap), \"node\")\n}", "function chartSankeyAdvanced (chart, datum) {\n var nodeConfig = datum.node || {};\n var linkConfig = datum.link || {};\n var nodeTooltipConfig = nodeConfig.tooltip || {};\n var linkTooltipConfig = linkConfig.tooltip || {}; // Chart Frame Config\n\n chart.chartFrame().chartPadding(0).size.conditionally(datum.size).padding.conditionally(datum.padding); // Node Tooltip Config\n\n chart.nodeTooltip().followMouse.conditionally(nodeTooltipConfig.followMouse).my.conditionally(nodeTooltipConfig.my).at.conditionally(nodeTooltipConfig.at).html.proxy(function (d) {\n var data = d.data;\n var value = d.value;\n\n if (data.tooltip !== undefined) {\n return data.tooltip;\n } else if (nodeTooltipConfig.html !== undefined) {\n return functor(nodeTooltipConfig.html)(data, value);\n }\n }); // Link Tooltip Config\n\n chart.linkTooltip().followMouse.conditionally(linkTooltipConfig.followMouse).my.conditionally(linkTooltipConfig.my).at.conditionally(linkTooltipConfig.at).html.proxy(function (d) {\n var data = d.data;\n var source = d.source.data;\n var target = d.target.data;\n\n if (data.tooltip !== undefined) {\n return data.tooltip;\n } else if (linkTooltipConfig.html !== undefined) {\n return functor(linkTooltipConfig.html)(data, source, target);\n }\n }); // Sankey Config\n\n var sankey = chart.sankey().nodeLabel(function (d) {\n return d.name;\n }).linkValue(function (d) {\n return d.value;\n }).nodeLabelWrapLength.conditionally(nodeConfig.labelWrapLength).nodeDraggableX.conditionally(nodeConfig.draggableX).nodeDraggableY.conditionally(nodeConfig.draggableY).nodeColor.proxy(function (d, i, k) {\n return d.color || functor(nodeConfig.color)(d, k);\n }).linkSourceColor.proxy(function (d, i, s) {\n return d.sourceColor || functor(linkConfig.sourceColor)(d, s);\n }).linkTargetColor.proxy(function (d, i, t) {\n return d.targetColor || functor(linkConfig.targetColor)(d, t);\n }); // D3 Sankey Config\n\n var d3Sankey$1 = sankey.sankey();\n\n if (nodeConfig.align !== undefined) {\n var nodeAlign = typeof nodeConfig.align === 'function' ? nodeConfig.align : d3Sankey.sankeyJustify;\n\n switch (nodeConfig.align) {\n case 'left':\n nodeAlign = d3Sankey.sankeyLeft;\n break;\n\n case 'right':\n nodeAlign = d3Sankey.sankeyRight;\n break;\n\n case 'center':\n nodeAlign = d3Sankey.sankeyCenter;\n break;\n }\n\n d3Sankey$1.nodeAlign(nodeAlign);\n }\n\n if (datum.iterations !== undefined) d3Sankey$1.iterations(datum.iterations);\n if (nodeConfig.padding !== undefined) d3Sankey$1.nodePadding(nodeConfig.padding);\n if (nodeConfig.sort !== undefined) d3Sankey$1.nodeSort(nodeConfig.sort === null ? null : function (a, b) {\n return nodeConfig.slice(0).sort(a.data, b.data);\n });\n return datum;\n}", "function BpmnDiagrams() {\n //Code conversion for Bpmn Shapes\n //Start Region\n /** @private */\n this.annotationObjects = {};\n //constructs the BpmnDiagrams module\n }", "function makeGraph() {\n \n }", "function initDiagram() {\n\n myDiagram =\n _G(go.Diagram, \"myDiagramDiv\", // create a Diagram for the DIV HTML element\n {\n // position the graph in the middle of the diagram\n initialContentAlignment: go.Spot.Center,\n // allow double-click in background to create a new node\n // \"clickCreatingTool.archetypeNodeData\": {\n // text: \"Node\",\n // color: \"white\"\n // },\n // allow Ctrl-G to call groupSelection()\n \"commandHandler.archetypeGroupData\": {\n text: \"Module\",\n isGroup: true,\n color: \"blue\"\n },\n // enable undo & redo\n \"undoManager.isEnabled\": true\n });\n // These nodes have text surrounded by a rounded rectangle\n // whose fill color is bound to the node data.\n // The user can drag a node by dragging its TextBlock label.\n // Dragging from the Shape will start drawing a new link.\n myDiagram.nodeTemplate =\n _G(go.Node, \"Auto\", {\n locationSpot: go.Spot.Center,\n desiredSize: new go.Size(100, 100)\n },\n _G(go.Shape, new go.Binding(\"figure\", \"fig\"), {\n fill: \"white\", // the default fill, if there is no data-binding\n portId: \"\",\n cursor: \"pointer\", // the Shape is the port, not the whole Node\n // allow all kinds of links from and to this port\n fromLinkable: true,\n fromLinkableSelfNode: false,\n fromLinkableDuplicates: false,\n toLinkable: true,\n toLinkableSelfNode: false,\n toLinkableDuplicates: false\n },\n new go.Binding(\"fill\", \"color\")),\n _G(go.Panel, \"Table\", {\n defaultAlignment: go.Spot.Left,\n margin: 4,\n cursor: \"move\"\n },\n _G(go.RowColumnDefinition, {\n column: 1,\n width: 4\n }),\n _G(go.TextBlock, {\n row: 0,\n column: 0,\n columnSpan: 3,\n alignment: go.Spot.Center\n }, {\n font: \"bold 12pt sans-serif\"\n },\n new go.Binding(\"text\", \"text\")),\n _G(go.TextBlock, \"Index: \", {\n row: 1,\n column: 0\n }, {\n font: \"bold 8pt sans-serif\"\n }),\n _G(go.TextBlock, {\n row: 1,\n column: 2\n }, {\n font: \"8pt sans-serif\"\n },\n new go.Binding(\"text\", \"key\")),\n _G(go.TextBlock, \"Title: \", {\n row: 2,\n column: 0\n }, {\n font: \"bold 8pt sans-serif\"\n }),\n _G(go.TextBlock, {\n row: 3,\n column: 0\n }, {\n font: \"8pt sans-serif\"\n },\n new go.Binding(\"text\", \"title\"))\n ), { // this tooltip Adornment is shared by all nodes\n toolTip: _G(go.Adornment, \"Auto\",\n _G(go.Shape, {\n fill: \"#FFFFCC\"\n }),\n _G(go.TextBlock, {\n margin: 4\n }, // the tooltip shows the result of calling nodeInfo(data)\n new go.Binding(\"text\", \"\", nodeInfo))\n ),\n // this context menu Adornment is shared by all nodes\n contextMenu: partContextMenu\n }\n );\n // The link shape and arrowhead have their stroke brush data bound to the \"color\" property\n myDiagram.linkTemplate =\n _G(go.Link, {\n toShortLength: 3,\n relinkableFrom: true,\n relinkableTo: true\n }, // allow the user to relink existing links\n _G(go.Shape, {\n strokeWidth: 2\n },\n new go.Binding(\"stroke\", \"color\")),\n _G(go.Shape, {\n toArrow: \"Standard\",\n stroke: null\n },\n new go.Binding(\"fill\", \"color\")), { // this tooltip Adornment is shared by all links\n toolTip: _G(go.Adornment, \"Auto\",\n _G(go.Shape, {\n fill: \"#FFFFCC\"\n }),\n _G(go.TextBlock, {\n margin: 4\n }, // the tooltip shows the result of calling linkInfo(data)\n new go.Binding(\"text\", \"\", linkInfo))\n ),\n // the same context menu Adornment is shared by all links\n contextMenu: partContextMenu\n }\n );\n // Define the appearance and behavior for Groups:\n function groupInfo(adornment) { // takes the tooltip or context menu, not a group node data object\n var g = adornment.adornedPart; // get the Group that the tooltip adorns\n var mems = g.memberParts.count;\n var links = 0;\n g.memberParts.each(function(part) {\n if (part instanceof go.Link) links++;\n });\n return \"Group \" + g.data.key + \": \" + g.data.text + \"\\n\" + mems + \" members including \" + links + \" links\";\n }\n // Groups consist of a title in the color given by the group node data\n // above a translucent gray rectangle surrounding the member parts\n myDiagram.groupTemplate =\n _G(go.Group, \"Vertical\", {\n selectionObjectName: \"PANEL\", // selection handle goes around shape, not label\n ungroupable: true\n }, // enable Ctrl-Shift-G to ungroup a selected Group\n _G(go.TextBlock, {\n font: \"bold 19px sans-serif\",\n isMultiline: false, // don't allow newlines in text\n editable: true // allow in-place editing by user\n },\n new go.Binding(\"text\", \"text\").makeTwoWay(),\n new go.Binding(\"stroke\", \"color\")),\n _G(go.Panel, \"Auto\", {\n name: \"PANEL\"\n },\n _G(go.Shape, \"Rectangle\", // the rectangular shape around the members\n {\n fill: \"rgba(128,128,128,0.2)\",\n stroke: \"gray\",\n strokeWidth: 3\n }),\n _G(go.Placeholder, {\n padding: 10\n }) // represents where the members are\n ), { // this tooltip Adornment is shared by all groups\n toolTip: _G(go.Adornment, \"Auto\",\n _G(go.Shape, {\n fill: \"#FFFFCC\"\n }),\n _G(go.TextBlock, {\n margin: 4\n },\n // bind to tooltip, not to Group.data, to allow access to Group properties\n new go.Binding(\"text\", \"\", groupInfo).ofObject())\n ),\n // the same context menu Adornment is shared by all groups\n contextMenu: partContextMenu\n }\n );\n // Define the behavior for the Diagram background:\n function diagramInfo(model) { // Tooltip info for the diagram's model\n return \"Model:\\n\" + model.nodeDataArray.length + \" nodes, \" + model.linkDataArray.length + \" links\";\n }\n // provide a tooltip for the background of the Diagram, when not over any Part\n myDiagram.toolTip =\n _G(go.Adornment, \"Auto\",\n _G(go.Shape, {\n fill: \"#FFFFCC\"\n }),\n _G(go.TextBlock, {\n margin: 4\n },\n new go.Binding(\"text\", \"\", diagramInfo))\n );\n // provide a context menu for the background of the Diagram, when not over any Part\n myDiagram.contextMenu =\n _G(go.Adornment, \"Vertical\",\n makeButton(\"Paste\",\n function(e, obj) {\n e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint);\n },\n function(o) {\n return o.diagram.commandHandler.canPasteSelection();\n }),\n makeButton(\"Undo\",\n function(e, obj) {\n e.diagram.commandHandler.undo();\n },\n function(o) {\n return o.diagram.commandHandler.canUndo();\n }),\n makeButton(\"Redo\",\n function(e, obj) {\n e.diagram.commandHandler.redo();\n },\n function(o) {\n return o.diagram.commandHandler.canRedo();\n })\n );\n}", "CreateLineup() {\n\n }", "subgraphAttrs() {\n this.command(`color=\"${Colors.groupBorder}\"`);\n this.command(`fontcolor=\"${Colors.groupLabel}\"`);\n }", "function ksfGraphTools()\n{\n\n}", "function SankeyDiagram(trips){\n\tconst seObj={}\n\tconst stSet = new Set();\n\ttrips.forEach(d=>{\n\t\tconst s=d.streetnames[0]\n\t\tconst e=d.streetnames[d.streetnames.length-1]\n\n\t\tif(!(s+'+'+e in seObj)){\n\t\t\tseObj[s+'+'+e]=1\n\t\t}else{\n\t\t\tseObj[s+'+'+e]+=1\n\t\t}\n\t\tstSet.add(s)\n\t\tstSet.add(e)\n\t})\n\n\tconst graph={'nodes':[],'links':[]};\n\t// const stArr=Array.from(stSet)\n\tconst setInd=new Set();\n\t\n\tObject.keys(seObj).forEach(d=>{\n\t\tif(seObj[d]>1){\n\t\t\tconst [s,e]=d.split('+');\n\t\t\tif(s!=e){\n\t\t\t\tgraph.links.push({'source':s,'target':e,'value':seObj[d]})\n\t\t\t\tsetInd.add(s)\n\t\t\t\tsetInd.add(e)\n\t\t\t}\t\n\t\t}\n\t})\n\n\tconst stArr=Array.from(setInd)\n\tstArr.forEach((s,i)=>{\n\t\tgraph.nodes.push({'node':i,'name':s})\n\t})\n\n\tgraph.links.forEach(d=>{\n\t\td.source=stArr.indexOf(d.source);\n\t\td.target=stArr.indexOf(d.target);\n\t})\n\t\t\n\tvar units = \"Widgets\";\n\t\t// set the dimensions and margins of the graph\n\tvar margin = {top: 10, right: 10, bottom: 10, left: 10},\n\twidth = 455 - margin.left - margin.right,\n\theight = 300 - margin.top - margin.bottom;\n\n\t// format variables\n\tvar formatNumber = d3.format(\",.0f\"), // zero decimal places\n\tformat = function(d) { return formatNumber(d) + \" \" + units; },\n\tcolor = d3.scaleOrdinal(d3.schemeCategory10);\n\n\t// append the svg object to the body of the page\n\tvar svg = d3.select(\"#rightside\").append(\"svg\")\n\t.attr(\"width\", 450)\n\t.attr(\"height\", 300)\n\t.append(\"g\")\n\t.attr(\"transform\", \n\t\t\"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\t// Set the sankey diagram properties\n\tvar sankey = d3.sankey()\n\t.nodeWidth(36)\n\t.nodePadding(40)\n\t.size([width, height]);\n\n\tvar path = sankey.link();\n\t\n\tsankey\n\t\t.nodes(graph.nodes)\n\t\t.links(graph.links)\n\t\t.layout(32);\n\n\t// add in the links\n\t\tvar link = svg.append(\"g\").selectAll(\".link\")\n\t\t\t.data(graph.links)\n\t\t.enter().append(\"path\")\n\t\t\t.attr(\"class\", \"link\")\n\t\t\t.attr(\"d\", path)\n\t\t\t.style(\"stroke-width\", function(d) { return Math.max(1, d.dy); })\n\t\t\t.sort(function(a, b) { return b.dy - a.dy; });\n\t\n\t// add the link titles\n\t\tlink.append(\"title\")\n\t\t\t.text(function(d) {\n\t\t\t\treturn d.source.name + \" → \" + \n\t\t\t\t\td.target.name + \"\\n\" + format(d.value); });\n\t\n\t// add in the nodes\n\t\tvar node = svg.append(\"g\").selectAll(\".node\")\n\t\t\t.data(graph.nodes)\n\t\t.enter().append(\"g\")\n\t\t\t.attr(\"class\", \"node\")\n\t\t\t.attr(\"transform\", function(d) { \n\t\t\t\treturn \"translate(\" + d.x + \",\" + d.y + \")\"; })\n\t\t\t.call(d3.drag()\n\t\t\t.subject(function(d) {\n\t\t\t\treturn d;\n\t\t\t})\n\t\t\t.on(\"start\", function() {\n\t\t\t\tthis.parentNode.appendChild(this);\n\t\t\t})\n\t\t\t.on(\"drag\", dragmove));\n\t\n\t// add the rectangles for the nodes\n\t\tnode.append(\"rect\")\n\t\t\t.attr(\"height\", function(d) { return d.dy; })\n\t\t\t.attr(\"width\", sankey.nodeWidth())\n\t\t\t.style(\"fill\", function(d) { \n\t\t\t\treturn d.color = color(d.name.replace(/ .*/, \"\")); })\n\t\t\t.style(\"stroke\", function(d) { \n\t\t\t\treturn d3.rgb(d.color).darker(2); })\n\t\t.append(\"title\")\n\t\t\t.text(function(d) { \n\t\t\t\treturn d.name + \"\\n\" + format(d.value); });\n\t\n\t// add in the title for the nodes\n\t\tnode.append(\"text\")\n\t\t\t.attr(\"x\", -6)\n\t\t\t.attr(\"y\", function(d) { return d.dy / 2; })\n\t\t\t.attr(\"dy\", \".35em\")\n\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t.attr(\"transform\", null)\n\t\t\t.text(function(d) { return d.name; })\n\t\t.filter(function(d) { return d.x < width / 2; })\n\t\t\t.attr(\"x\", 6 + sankey.nodeWidth())\n\t\t\t.attr(\"text-anchor\", \"start\");\n\t\n\t// the function for moving the nodes\n\t\tfunction dragmove(d) {\n\t\td3.select(this)\n\t\t\t.attr(\"transform\", \n\t\t\t\t\"translate(\" \n\t\t\t\t\t+ d.x + \",\" \n\t\t\t\t\t+ (d.y = Math.max(\n\t\t\t\t\t\t0, Math.min(height - d.dy, d3.event.y))\n\t\t\t\t\t) + \")\");\n\t\tsankey.relayout();\n\t\tlink.attr(\"d\", path);\n\t\t}\n}", "createConnections() {\n const self = this;\n const op = this.options;\n if (this.paths) {\n this.paths.attrs({\n 'd': (d, i) => {\n const data = {\n source: [0, op.boxheight * (d.i + 0.5 + op.offset)],\n target: [op.width, op.boxheight * (d.j + 0.5)] // + 2 allows small offset\n };\n return this.linkGen(data);\n },\n 'class': 'atn-curve'\n })\n .attr(\"src-idx\", (d, i) => d.i)\n .attr(\"target-idx\", (d, i) => d.j);\n }\n }", "function sankey(data){\n\n\tconst sankey = d3.sankey()\n\t\t.nodeId(d => d.name)\n\t\t.nodeWidth(nodeRect.width)\n\t\t.nodePadding(nodeRect.padding)\n\t\t.extent([[1, 5], [width - 1, height - 5]]);\n\n\treturn sankey({\n\t\t nodes: data.nodes.map(d => Object.assign({}, d)),\n\t\t links: data.links.map(d => Object.assign({}, d)),\n\t });\n}", "function sankeyShow(){\n\toptions = {\n\t\t\"align\": document.getElementById(\"sankeyAlign\").value,\n\t\t\"edgeColor\": document.getElementById(\"edgeColor\").value\n\t}\n\tsvg.remove();\n\tsvg = plotSankey(dom, csv, options);\n\tbtnSankeyHide.style.display = \"inline-block\";\n}", "constructor(data, map) {\n this.data = data;\n this.valueType = wedgeTypes[0].id;\n this.map = map;\n this.hierarchy = this.createHierarchy(this);\n this.drawSunburst();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a message from the database DELETE FROM messages WHERE msgid = ?;
async delete_message(msgid) { }
[ "function deleteMessage(){\r\n deleteMessageDB(id);\r\n}", "function delete_message(ID){\n\t db.transaction(function(tx) {\n\t \ttx.executeSql(\n\t \t\t\"DELETE FROM messages WHERE ID = ?)\", [ID], \n\t \t\tsuccess_message_delete, \n\t \t\terror_message_delete\n\t \t);\n\t });\t\n}", "function deleteMessage(message) {\n const params = new URLSearchParams();\n params.append('id', message.id);\n fetch('/delete-message', {method: 'POST', body: params});\n}", "async deleteMessage (message) {\n return this.updateMessage('(message deleted)', message, true)\n }", "function deleteMessage(id, callback) {\n }", "function delete_msg()\n{\n\tif (confirm(\"Are you sure that you want to delete msg with id \" + L_selected_msg_id + \" and code '\" + L_selected_msg_code + \"'\") == true) \n\t{\n\t\tif (confirm(\"Are you ABSOLUTELY sure that you want to delete msg with id \" + L_selected_msg_id + \" and code '\" + L_selected_msg_code + '\"') == true) \n\t\t{\n\t\t\t// do delete if running with gas database\n\t\t\tif (G_running_on_gas==true)\n\t\t\t{\n\t\t\t\tdb_delete_where (\"Messages\", \"ID\", L_selected_msg_id); \n\t\t\t}\n\t\t\t\n\t\t\t// else using SQL server\n\t\t\t{\n\t\t\t\t// construct the SQL delete command\n\t\t\t\tvar mysql = \"DELETE FROM \" + MSGS_TABLE + \" WHERE ID='\" + L_selected_msg_id + \"';\"; \n\t\t\t\tdo_sql (mysql, delete_msg1, \"\")\n\t\t\t\treturn; \t\n\t\t\t}\n\t\t} \n\t}\n}", "function message_del(argument) {\n var idMessage = argument.idMessage;\n var idTopic = argument.idTopic;\n var message = mongo.collection(('message' + idTopic));\n\n message.removeById(idMessage, function(error, results) {\n });\n}", "function queryDeleteMessage(db, messageID) {\n return new Promise((resolve, reject) => {\n db.query(Constant.SQL_DELETE_MESSAGE_BY_ID, [messageID], (err, results) => {\n if (err) {\n reject(err);\n }\n if (!results) {\n return resolve(false);\n }\n resolve(true);\n });\n });\n}", "function deleteMessage(reciept) {\n var deleteParams = {\n QueueUrl: queue_url,\n ReceiptHandle: reciept\n };\n sqs.deleteMessage(deleteParams, function(err, data) {\n if (err) console.log(\"Delete Error\", err);\n });\n}", "function deleteMessage(id) {\n MessageService.deleteMessage(id).\n success(function(data) {\n getMessages();\n AlertService.addAlert(\"warning\", \"Successfully Deleted Message\\n\" + message.name);\n }).\n error(errorCb);\n }", "function messageDelete(req, res, next){\n\n Chat\n .findById(req.params.chatId)\n .exec()\n .then(chat => {\n const message = chat.messages.id(req.params.messageId);\n if (message.sender !== req.user._id) return res.unauthorized();\n message.remove();\n chat.save();\n })\n .then(() => res.status(204).end())\n .catch(next);\n}", "function delete_message(message) {\n admin_bot._api('chat.delete', {\n \"token\": admin_settings.token,\n \"ts\": message.ts,\n \"channel\": message.channel,\n \"as_user\": true\n }).then(function(e) {\n console.log(e);\n });\n}", "deleteMessage(){\n this.server.post('/api/delete-message', (req, res) => {\n try {\n const bind = {\n id: req.body.id\n };\n \n if (!this.App.isNull(bind.id)) \n this.App.MessageOrm.deleteById({ id: bind.id });\n \n res.status(200).send('Ok!')\n }\n catch (err){\n this.App.throwErr(err, this.prefix);\n res.status(500).send(err.message)\n }\n })\n }", "removeMessage(id){\n this.messages.delete(id);\n }", "function deleteChat(id) {\n return db.query(('DELETE FROM chats WHERE id=?', id));\n}", "deleteMessage() {\n firebase.database().ref('comments/' + this.props.movieId + '/' + this.props.messageId).remove();\n }", "function deleteMsg(sqsMsg, callback)\n{\n var params = {\n QueueUrl: sqsUrl,\n ReceiptHandle: sqsMsg.ReceiptHandle\n };\n sqs.deleteMessage(params, callback);\n}", "async deleteMessagesOfUserFromLobby()\n\t{\n\t\tawait DB.q(`\n\t\t\tDELETE FROM c_messages\n\t\t\tWHERE created_by = ?\n\t\t\t\tAND lobby_id = ? ;\n\t\t`, [\n\t\t\tthis.user,\n\t\t\tthis.lobby,\n\t\t])\n\t}", "function deleteMessage(req, res, next) {\n User\n .findById(req.params.id)\n .populate('messages.from')\n .exec()\n .then(user => {\n const message = user.messages.id(req.params.messageId);\n if(!message.to.equals(req.currentUser._id)) {\n throw new Error('Unauthorized');\n }\n message.remove();\n return user.save;\n })\n .then(user => res.json(user))\n .catch(next);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Site hierarchy. Comma separated path. Exceptions: / will be set as "homepage". Any error page is set to "error".
function getHierarchy() { if (httpStatus == 404 || httpStatus == 500) { return "error"; } else if (directories[0] === "") { return "homepage"; } else { return directories.join(','); } }
[ "function set_hier1() {\r\n h1 = new String(document.location.host + document.location.pathname);\r\n if (h1.charAt(h1.length - 1) == \"/\") {\r\n var temp = new String();\r\n for (var i = 0; i < h1.length - 1; i++) {\r\n temp += h1.charAt(i);\r\n }\r\n h1 = temp;\r\n }\r\n var intMatch = h1.indexOf(\"/\");\r\n while (intMatch != -1) {\r\n h1 = h1.replace(\"/\", \"|\");\r\n intMatch = h1.indexOf(\"/\");\r\n }\r\n return h1;\r\n}", "function getSiteUrl() {\n var urlParts = $location.absUrl().toLowerCase().split('/');\n var result = urlParts[0] + \"/\";\n for (var i = 2; i < urlParts.length; i++) {\n if (urlParts[i] != 'surveyapp' &&\n urlParts[i] != 'pages' && urlParts[i] !== 'sitepages' &&\n urlParts[i] !== 'siteassets' && urlParts[i].indexOf('.aspx') < 0) {\n result += '/' + urlParts[i];\n } else {\n break;\n }\n }\n return result;\n }", "function getSiteNav(baseDir) {\n if (siteNav !== null) {\n return siteNav;\n }\n var baseConfig = getLocalDefaults(baseDir);\n var root = baseConfig['rootNav'];\n for (var i = 0; i < root.length; i++) {\n var section = root[i];\n if (section['folder']) {\n if (section['href'] === undefined) {\n section['href'] = '/' + section['folder'] + '/';\n }\n section['children'] = getNav(baseDir + '/' + section['folder']);\n }\n }\n siteNav = root;\n return siteNav;\n}", "mainPath(path) {\n\t\treturn this.siteDir + this.#formatPath(path);\n\t}", "function homePage() {\n var url = location.href.split(\"/\");\n url[url.length - 1] = \"index.html\";\n var finalUrl = \"\";\n for (var i = 0; i < url.length; i++) {\n finalUrl += (i != url.length - 1) ? url[i] + \"/\" : url[i];\n }\n location.href = finalUrl;\n}", "function findSiteTop() {\n var path = location.pathname.substr(0, location.pathname.lastIndexOf(\"/\"));\n var rootDir = \"htdocs\";\n var siteTop=\"\";\n var base = path.substr(path.lastIndexOf(\"/\") + 1);\n while (base != rootDir && base != \"\") {\n siteTop += \"../\";\n path = path.substr(0, path.lastIndexOf(\"/\"));\n base = path.substr(path.lastIndexOf(\"/\")+1);\n }\n if (base == \"\") {\n siteTop = \"http://www.cvrti.utah.edu/\";\n } \n return siteTop;\n}", "getSiteUrl() {\n const siteUrl = this.configManager.getConfig('crowi', 'app:siteUrl');\n if (siteUrl != null) {\n return pathUtils.removeTrailingSlash(siteUrl);\n }\n else {\n return '[The site URL is not set. Please set it!]';\n }\n }", "function getRootWebSitePath() {\n //thanks for code of Mr.AkramOnly\n var _location = document.location.toString();\n var applicationNameIndex = _location.indexOf('/', _location.indexOf('://') + 3);\n var applicationName = _location.substring(0, applicationNameIndex) + '/';\n var webFolderIndex = _location.indexOf('/', _location.indexOf(applicationName) + applicationName.length);\n var webFolderFullPath = _location.substring(0, webFolderIndex) + '/';\n\n return webFolderFullPath;\n}", "function getPortalPath(path)\n{\n var ret = null;\n var objs = SUFFIXHTMLS.split(\",\");\n for (var i = 0; i < objs.length; i++)\n {\n if (checkFileExists(path + objs[i]))\n {\n ret = path + objs[i];\n break;\n }\n }\n return ret;\n}", "function hardcodedPath() {\n if (pageData.path) {\n var pathInvariantMessage = '\\n Hardcoded paths are relative to the website root so must be prepended with a\\n forward slash. You set the path to \"' + pageData.path + '\" in \"' + parsedPath.path + '\"\\n but it should be \"/' + pageData.path + '\"\\n\\n See http://bit.ly/1qeNpdy for more.\\n ';\n (0, _invariant2.default)(pageData.path.charAt(0) === '/', pathInvariantMessage);\n }\n\n return pageData.path;\n }", "function checkIfSiteIsMain (path) {\n if(path === \"/\") {\n return true;\n } else {\n return false;\n }\n}", "function getUrlDirectory() {\n var url = window.location.href;\n var index = url.lastIndexOf(\"/\");\n if (index > -1) {\n url = url.substr(0, index);\n }\n return url;\n }", "function dotSwitch() {\n switch (location.pathname) {\n case \"/products\":\n return \"product catalog\";\n case \"/NewInvoice\":\n return \"newinvoice\";\n case \"/all-invoices\":\n return \"all-invoices\";\n case \"/customers\":\n return \"customers\";\n case \"/profile\":\n return \"profile\";\n default:\n return \"home\";\n }\n }", "function gotoSite(basePath, siteUrl)\n{\n if (siteUrl.indexOf(\"http\") == -1) \n {\n if (!siteUrl.startsWith(\"/\")) \n {\n siteUrl = \"http://\" + siteUrl;\n }\n else\n {\n siteUrl = basePath + siteUrl;\n siteUrl = siteUrl.replace(\"/content/\", \"/\");\n }\n }\n window.open(siteUrl, \"MySites\", \"location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes,status=yes,width=800,height=600\");\n //window.open(siteUrl, 'MySites', 'location=yes,menubar=yes,toolbar=yes,scrollbars=yes,status=yes,width=800,height=600');\n}", "function getUrlDirectory() {\n var url = window.location.href;\n var index = url.lastIndexOf(\"/\");\n if (index > -1) {\n url = url.substr(0, index);\n }\n\n return url;\n }", "static setPaths() {\n\t\tthis._url_app = this.dirname(import.meta.url);\n\t\tthis._url_page = this.dirname(location.href);\n\t}", "function generateBreadcrumbs (path){\n\t\t$(\"#perc-chart-breadcrumb-list\").html(\"\");\n\t\tbreadcrumbItems = [];\n\t\tbreadcrumbItems = path.split(\"/\");\n\t\tvar siteName = prefs.getString(SITE_NAME);\n\t\tif (siteName == \"@all\"){\n $(\"#perc-chart-breadcrumb-list\").append(' <li atitle = \"\" ><span id = \"perc-breadcrumb-items\" atitle = \"\">All Sites</span></li><span class = \"perc-breadcrumb-separator\" >&nbsp;>&nbsp;</span>');\t\t\t \t\n\t\t}\n\t\tvar pathValue = breadcrumbItems[0];\n\t\t\n\t\t$(\"#perc-yaxis-label\").html(\"\");\n\t\tif(breadcrumbItems[0] == \"\"){\n\t\t\t$(\".perc-breadcrumb-separator\").hide();\n\t\t\t$(\"#perc-yaxis-label\").append(\"Sites\");\n\t\t}\n\t\telse{\n\t\t\t$(\"#perc-yaxis-label\").append(\"Sections\");\n\t\t}\n\n\n\t\t$(\"#perc-chart-breadcrumb-list\").append('<li atitle = \"'+ breadcrumbItems[0] + '\" ><span id = \"perc-breadcrumb-items\" atitle = \"'+ breadcrumbItems[0] +'\">' +breadcrumbItems[0]+'</span></li>');\n\t\t\n\t\tfor (i=1; i< breadcrumbItems.length; i++)\n\t\t{\n\t\t\t pathValue += '/' + breadcrumbItems[i];\n\t\t\t$(\"#perc-chart-breadcrumb-list\").append(' <span>>&nbsp;</span><li atitle = \"'+ pathValue + '\" ><span id = \"perc-breadcrumb-items\" atitle = \"'+ pathValue +'\">' +breadcrumbItems[i]+'</span></li>');\t\n\t\t}\n\t}", "function obtenerURLWebRelative() {\n if (_spPageContextInfo.siteServerRelativeUrl[_spPageContextInfo.siteServerRelativeUrl.length - 1] == \"/\") {\n return _spPageContextInfo.siteServerRelativeUrl;\n } else {\n return _spPageContextInfo.siteServerRelativeUrl + \"/\";\n }\n}", "function getCurrentDomainSite() {\r\n\treturn document.domain+L_Menu_BaseUrl;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets new size of SVG after divs are resized
function updateSvgSize() { let g = document.getElementById('graph'); width = g.clientWidth; height = g.clientHeight; }
[ "function svgResized(w, h) {\n // not used now, but may be required later...\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 }", "function adjustSize() {\n var\n prevW = canvasW,\n prevH = canvasH;\n canvasW = $(svgContainer).innerWidth();\n canvasH = $(svgContainer).innerHeight();\n canvasR = canvasW / canvasH;\n boxW *= canvasW / prevW ;\n boxH *= canvasH / prevH ;\n svgRoot.setAttribute( 'width', canvasW );\n svgRoot.setAttribute( 'height', canvasH );\n //console.log('called adjustSize: '+canvasW+' '+canvasH);\n }", "function updateSVGSize() {\n\t\t\t\t\tvar svgWidth = $(window).innerWidth();\n\t\t\t\t\tvar svgHeight = $(window).innerHeight() - scope.$svg.offset().top + 8;\n\n\t\t\t\t\tscope.$svg.css('width', svgWidth + 'px');\n\t\t\t\t\tscope.$svg.css('height', svgHeight + 'px');\n\t\t\t\t}", "function resize() {\r\n var targetWidth = parseInt(container.style(\"width\"));\r\n svg.attr(\"width\", targetWidth);\r\n svg.attr(\"height\", Math.round(targetWidth / aspect));\r\n }", "function svgPlaceSize() {\n\t\t$(\"svg\").each(function(){\n\t\t\tvar allSvgHeight = $(this).parent().height(),\n\t\t\t\tallSvgWidth = $(this).parent().width();\n\n\t\t\tvar isIE = /*@cc_on!@*/false || !!document.documentMode;\n\t\t\tif(isIE == true){\n\t\t\t\tallSvgHeight = winWidth * 0.40;\n\t\t\t\t$(this).attr(\"width\",allSvgWidth);\n\t\t\t\t$(this).attr(\"height\",allSvgHeight);\n\t\t\t\t$(\".preloader svg\").attr(\"width\",allSvgWidth)\n\t\t\t\t$(\".preloader svg\").attr(\"height\",winWidth * 0.3)\n\t\t\t}\n\t\t});\n\n\t}", "function resize() {\n\t var targetWidth = parseInt(container.style(\"width\"));\n\t svgWidth = targetWidth / 2\n\t svg.attr(\"width\", svgWidth);\n\t svg.attr(\"height\", Math.round(svgWidth / (aspect)));\n }", "function resize() {\n const widthInPixels = window\n .getComputedStyle(container.node(), null)\n .getPropertyValue('width');\n var targetWidth = parseInt(widthInPixels);\n svg.attr('width', targetWidth);\n svg.attr('height', Math.round(targetWidth / aspect));\n }", "function resize() {\n var targetWidth = parseInt(container.style(\"width\"), 10);\n svg.attr(\"width\", targetWidth);\n svg.attr(\"height\", Math.round(targetWidth / aspect));\n }", "function resize() {\n var targetWidth = toInt(container.style('width'));\n svg.attr('width', targetWidth);\n svg.attr('height', Math.round(targetWidth / aspect));\n }", "function resize() {\n let targetWidth = parseInt(container.style(\"width\"));\n svg.attr(\"width\", targetWidth);\n svg.attr(\"height\", Math.round(targetWidth / aspect));\n }", "function resize() {\n let targetWidth = parseInt(container.style(\"width\"));\n svg.attr(\"width\", targetWidth);\n svg.attr(\"height\", Math.round(targetWidth / aspect));\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 }", "saveOriginalSize() {\n this.originalViewBox = this.svgNode.getAttribute('viewBox')\n this.originalHeight = this.svgNode.getAttribute('height')\n this.originalWidth = this.svgNode.getAttribute('width')\n }", "function resize_svg() {\n var width = parseInt(d3.select(rscape_svg_div_id + \" svg\").attr('width')),\n height = parseInt(d3.select(rscape_svg_div_id + \" svg\").attr('height')),\n min_rscape_height = 400,\n min_rscape_width = 400;\n\n if (width < min_rscape_width) {\n d3.select(rscape_svg_div_id + \" svg\").attr('width', min_rscape_width);\n }\n if (height < min_rscape_height) {\n d3.select(rscape_svg_div_id + \" svg\").attr('height', min_rscape_height);\n }\n\n panZoom.resize();\n panZoom.fit();\n panZoom.center();\n }", "function resize() {\n var svgRoot = document.documentElement;\n svgRoot.setAttribute('width', window.innerWidth);\n svgRoot.setAttribute('height', window.innerHeight);\n exports.update();\n }", "function resizeNodeSvg() {\n nodeSvg.css('width', \"calc(100% - \" + treeSvg.outerWidth() + \"px\");\n }", "function chart_resize(width)\n {\n if( $(elm).length )\n {\n var height = width * ratio;\n $(elm).attr(\"height\", height + \"px\");\n $(elm).attr(\"width\", width + \"px\");\n $(elm).width(width);\n $(elm).height(height);\n if( $(svg_elm).length )\n {\n $(svg_elm).attr(\"height\", height + \"px\");\n $(svg_elm).attr(\"width\", width + \"px\");\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters & Effects Functions
function filter(e){ if(e.target.classList.contains('filter-btn')){ switch(e.target.id){ // Blur Filter case 'blur-add': Caman('#canvas', image, function(){ this.stackBlur(2).render(); }); break; case 'blur-reduce': Caman('#canvas', image, function(){ this.stackBlur(-2).render(); }); break; // Brightness Filter case 'brightness-add': Caman('#canvas', image, function(){ this.brightness(5).render(); }); break; case 'brightness-reduce': Caman('#canvas', image, function(){ this.brightness(-5).render(); }); break; // Contrast Filter case 'contrast-add': Caman('#canvas', image, function(){ this.contrast(5).render(); }); break; case 'contrast-reduce': Caman('#canvas', image, function(){ this.contrast(-5).render(); }); break; // Saturation Filter case 'saturation-add': Caman('#canvas', image, function(){ this.saturation(5).render(); }); break; case 'saturation-reduce': Caman('#canvas', image, function(){ this.saturation(-5).render(); }); break; // Exposure Filter case 'expo-add': Caman('#canvas', image, function(){ this.exposure(10).render(); }); break; case 'expo-reduce': Caman('#canvas', image, function(){ this.exposure(-10).render(); }); break; // Gamma Filter case 'gamma-add': Caman('#canvas', image, function(){ this.gamma(1.1).render(); }); break; case 'gamma-reduce': Caman('#canvas', image, function(){ this.gamma(0.9).render(); }); break; // Invert Filter case 'invert-add': Caman('#canvas', image, function(){ this.invert().render(); }); break; case 'invert-reduce': Caman('#canvas', image, function(){ this.invert().render(); }); break; // Sepia Filter case 'sepia-add': Caman('#canvas', image, function(){ this.sepia(10).render(); }); break; case 'sepia-reduce': Caman('#canvas', image, function(){ this.sepia(-10).render(); }); break; // Hue Filter case 'hue-add': Caman('#canvas', image, function(){ this.hue(10).render(); }); break; case 'hue-reduce': Caman('#canvas', image, function(){ this.hue(-10).render(); }); break; // Vibrance Filter case 'vibrance-add': Caman('#canvas', image, function(){ this.vibrance(20).render(); }); break; case 'vibrance-reduce': Caman('#canvas', image, function(){ this.vibrance(-20).render(); }); break; // Noise Filter case 'noise-add': Caman('#canvas', image, function(){ this.noise(10).render(); }); break; // case 'noise-reduce': // Caman('#canvas', image, function(){ // this.noise(-10).render(); // }); break; // GreyScale Filter case 'grayscale-add': Caman('#canvas', image, function(){ this.greyscale().render(); }); break; // case 'grayscale-reduce': // Caman('#canvas', image, function(){ // this.greyscale().render(); // }); break; // default: console.log('Click Any Effect Or Filter'); } } }
[ "function SVGEffects(elem){var i;var len=elem.data.ef?elem.data.ef.length:0;var filId=createElementID();var fil=filtersFactory.createFilter(filId,true);var count=0;this.filters=[];var filterManager;for(i=0;i<len;i+=1){filterManager=null;if(elem.data.ef[i].ty===20){count+=1;filterManager=new SVGTintFilter(fil,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===21){count+=1;filterManager=new SVGFillFilter(fil,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===22){filterManager=new SVGStrokeEffect(elem,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===23){count+=1;filterManager=new SVGTritoneFilter(fil,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===24){count+=1;filterManager=new SVGProLevelsFilter(fil,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===25){count+=1;filterManager=new SVGDropShadowEffect(fil,elem.effectsManager.effectElements[i]);}else if(elem.data.ef[i].ty===28){// count += 1;\n filterManager=new SVGMatte3Effect(fil,elem.effectsManager.effectElements[i],elem);}else if(elem.data.ef[i].ty===29){count+=1;filterManager=new SVGGaussianBlurEffect(fil,elem.effectsManager.effectElements[i]);}if(filterManager){this.filters.push(filterManager);}}if(count){elem.globalData.defs.appendChild(fil);elem.layerElement.setAttribute('filter','url('+locationHref+'#'+filId+')');}if(this.filters.length){elem.addRenderableComponent(this);}}", "applyEffect(filter) {\n this.effects.push(filter)\n }", "function CustomFilter() {}", "function lsd_applyFilterState() {\n\tlsd_applyFilterState_withAnimation(200);\n}", "function SVGEffects(elem) {\n var i;\n var len = elem.data.ef ? elem.data.ef.length : 0;\n var filId = createElementID();\n var fil = filtersFactory.createFilter(filId, true);\n var count = 0;\n this.filters = [];\n var filterManager;\n for(i = 0; i < len; i += 1){\n filterManager = null;\n if (elem.data.ef[i].ty === 20) {\n count += 1;\n filterManager = new SVGTintFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 21) {\n count += 1;\n filterManager = new SVGFillFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 22) filterManager = new SVGStrokeEffect(elem, elem.effectsManager.effectElements[i]);\n else if (elem.data.ef[i].ty === 23) {\n count += 1;\n filterManager = new SVGTritoneFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 24) {\n count += 1;\n filterManager = new SVGProLevelsFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 25) {\n count += 1;\n filterManager = new SVGDropShadowEffect(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 28) // count += 1;\n filterManager = new SVGMatte3Effect(fil, elem.effectsManager.effectElements[i], elem);\n else if (elem.data.ef[i].ty === 29) {\n count += 1;\n filterManager = new SVGGaussianBlurEffect(fil, elem.effectsManager.effectElements[i]);\n }\n if (filterManager) this.filters.push(filterManager);\n }\n if (count) {\n elem.globalData.defs.appendChild(fil);\n elem.layerElement.setAttribute('filter', 'url(' + locationHref + '#' + filId + ')');\n }\n if (this.filters.length) elem.addRenderableComponent(this);\n }", "function SVGEffects(elem) {\n var i;\n var len = elem.data.ef ? elem.data.ef.length : 0;\n var filId = createElementID();\n var fil = filtersFactory.createFilter(filId);\n var count = 0;\n this.filters = [];\n var filterManager;\n for (i = 0; i < len; i += 1) {\n filterManager = null;\n if (elem.data.ef[i].ty === 20) {\n count += 1;\n filterManager = new SVGTintFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 21) {\n count += 1;\n filterManager = new SVGFillFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 22) {\n filterManager = new SVGStrokeEffect(elem, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 23) {\n count += 1;\n filterManager = new SVGTritoneFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 24) {\n count += 1;\n filterManager = new SVGProLevelsFilter(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 25) {\n count += 1;\n filterManager = new SVGDropShadowEffect(fil, elem.effectsManager.effectElements[i]);\n } else if (elem.data.ef[i].ty === 28) {\n // count += 1;\n filterManager = new SVGMatte3Effect(fil, elem.effectsManager.effectElements[i], elem);\n } else if (elem.data.ef[i].ty === 29) {\n count += 1;\n filterManager = new SVGGaussianBlurEffect(fil, elem.effectsManager.effectElements[i]);\n }\n if (filterManager) {\n this.filters.push(filterManager);\n }\n }\n if (count) {\n elem.globalData.defs.appendChild(fil);\n elem.layerElement.setAttribute('filter', 'url(' + locationHref + '#' + filId + ')');\n }\n if (this.filters.length) {\n elem.addRenderableComponent(this);\n }\n}", "function FilterChain () {\n}", "function processFilters() {\n\tif (isCanvasSupported())\n\t{\n\t\t// create working buffer outside the main loop so it's only done once\n\t\tvar buffer = document.createElement(\"canvas\");\n\t\t// get the canvas context\n\t\tvar c = buffer.getContext('2d');\n\t\n\t\t// only run if this browser supports canvas, obviously\n\t\tif (supports_canvas()) {\n\t\t\t// you can add or remove lines here, depending on which filters you're using.\n\t\t\taddFilter(\"filter-blur\", buffer, c);\n\t\t\taddFilter(\"filter-edges\", buffer, c);\n\t\t\taddFilter(\"filter-emboss\", buffer, c);\n\t\t\taddFilter(\"filter-greyscale\", buffer, c);\n\t\t\taddFilter(\"filter-matrix\", buffer, c);\n\t\t\taddFilter(\"filter-mosaic\", buffer, c);\n\t\t\taddFilter(\"filter-noise\", buffer, c);\n\t\t\taddFilter(\"filter-posterize\", buffer, c);\n\t\t\taddFilter(\"filter-sepia\", buffer, c);\n\t\t\taddFilter(\"filter-sharpen\", buffer, c);\n\t\t\taddFilter(\"filter-tint\", buffer, c);\n\t\t}\n\t}\n}", "function filter() {}", "function filterClearFn(evt){\n\t\t\t//Clear all filters\n\t\t\tTweenMax.staggerTo(allImages, 1, {alpha: 1, ease:Bounce.easeOut}, .01);\n\n\t\t\t//var selection = $(\"#drawing img, #water-color img, #oil img\").not(\".clear\");//Grab the images in the #drawing, #watercolor, and #oil divs that are not \"plus-3\"\n\t\t\t\n\t\t}", "function applyAndRender() {\n // Multiple TODOs: Call your apply function(s) here\n\n //applyFilter(reddify);\n //applyFilter(decreaseBlue);\n //applyFilter(increaseGreenByBlue);\n //applyFilterNoBackground(reddify);\n //applyFilterNoBackground(decreaseBlue);\n //applyFilterNoBackground(blackAndWhite);\n applyFilterNoBackground(grayify);\n\n // applyFilterSmudgeLeft(smudge);\n // applyFilterSmudgeRight(smudge);\n // applyFilterSmudgeDown(smudge);\n // applyFilterSmudgeUp(smudge);\n\n // do not change the below line of code\n render($(\"#display\"), image);\n}", "function activeFiltersFX1(cage,type){\n cage.d._filters = [ FILTERS.OutlineFilterx4 ]; // thickness, color, quality\n cage._filters = [ FILTERS.OutlineFilterx16 ];\n cage.Debug.bg._filters = [ FILTERS.OutlineFilterx16 ];\n cage.alpha = 1;\n }", "function effectsUtils()\n{\n}", "function FXAAFilter()\n{\n //TODO - needs work\n core.Filter.call(this,\n\n // vertex shader\n \"#define GLSLIFY 1\\nattribute vec2 aVertexPosition;\\nattribute vec2 aTextureCoord;\\n\\nuniform mat3 projectionMatrix;\\n\\nvarying vec2 v_rgbNW;\\nvarying vec2 v_rgbNE;\\nvarying vec2 v_rgbSW;\\nvarying vec2 v_rgbSE;\\nvarying vec2 v_rgbM;\\n\\nuniform vec4 filterArea;\\n\\nvarying vec2 vTextureCoord;\\n\\nvec2 mapCoord( vec2 coord )\\n{\\n coord *= filterArea.xy;\\n coord += filterArea.zw;\\n\\n return coord;\\n}\\n\\nvec2 unmapCoord( vec2 coord )\\n{\\n coord -= filterArea.zw;\\n coord /= filterArea.xy;\\n\\n return coord;\\n}\\n\\nvoid texcoords(vec2 fragCoord, vec2 resolution,\\n out vec2 v_rgbNW, out vec2 v_rgbNE,\\n out vec2 v_rgbSW, out vec2 v_rgbSE,\\n out vec2 v_rgbM) {\\n vec2 inverseVP = 1.0 / resolution.xy;\\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\\n v_rgbM = vec2(fragCoord * inverseVP);\\n}\\n\\nvoid main(void) {\\n\\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\\n\\n vTextureCoord = aTextureCoord;\\n\\n vec2 fragCoord = vTextureCoord * filterArea.xy;\\n\\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\\n}\",\n // fragment shader\n \"#define GLSLIFY 1\\nvarying vec2 v_rgbNW;\\nvarying vec2 v_rgbNE;\\nvarying vec2 v_rgbSW;\\nvarying vec2 v_rgbSE;\\nvarying vec2 v_rgbM;\\n\\nvarying vec2 vTextureCoord;\\nuniform sampler2D uSampler;\\nuniform vec4 filterArea;\\n\\n/**\\n Basic FXAA implementation based on the code on geeks3d.com with the\\n modification that the texture2DLod stuff was removed since it's\\n unsupported by WebGL.\\n \\n --\\n \\n From:\\n https://github.com/mitsuhiko/webgl-meincraft\\n \\n Copyright (c) 2011 by Armin Ronacher.\\n \\n Some rights reserved.\\n \\n Redistribution and use in source and binary forms, with or without\\n modification, are permitted provided that the following conditions are\\n met:\\n \\n * Redistributions of source code must retain the above copyright\\n notice, this list of conditions and the following disclaimer.\\n \\n * Redistributions in binary form must reproduce the above\\n copyright notice, this list of conditions and the following\\n disclaimer in the documentation and/or other materials provided\\n with the distribution.\\n \\n * The names of the contributors may not be used to endorse or\\n promote products derived from this software without specific\\n prior written permission.\\n \\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\\n \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\\n */\\n\\n#ifndef FXAA_REDUCE_MIN\\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\\n#endif\\n#ifndef FXAA_REDUCE_MUL\\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\\n#endif\\n#ifndef FXAA_SPAN_MAX\\n#define FXAA_SPAN_MAX 8.0\\n#endif\\n\\n//optimized version for mobile, where dependent\\n//texture reads can be a bottleneck\\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\\n vec2 v_rgbNW, vec2 v_rgbNE,\\n vec2 v_rgbSW, vec2 v_rgbSE,\\n vec2 v_rgbM) {\\n vec4 color;\\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\\n vec4 texColor = texture2D(tex, v_rgbM);\\n vec3 rgbM = texColor.xyz;\\n vec3 luma = vec3(0.299, 0.587, 0.114);\\n float lumaNW = dot(rgbNW, luma);\\n float lumaNE = dot(rgbNE, luma);\\n float lumaSW = dot(rgbSW, luma);\\n float lumaSE = dot(rgbSE, luma);\\n float lumaM = dot(rgbM, luma);\\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\\n \\n mediump vec2 dir;\\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\\n \\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\\n \\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\\n dir * rcpDirMin)) * inverseVP;\\n \\n vec3 rgbA = 0.5 * (\\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\\n \\n float lumaB = dot(rgbB, luma);\\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\\n color = vec4(rgbA, texColor.a);\\n else\\n color = vec4(rgbB, texColor.a);\\n return color;\\n}\\n\\nvoid main() {\\n\\n \\tvec2 fragCoord = vTextureCoord * filterArea.xy;\\n\\n \\tvec4 color;\\n\\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\\n\\n \\tgl_FragColor = color;\\n}\\n\"\n );\n\n}", "function filterChange() {\n // console.log('filterChange');\n\n SvgModule.Data.Tag.style.filter = Common.getFiltersCss(\n PageData.Controls.Brightness.value,\n PageData.Controls.Contrast.value,\n PageData.Controls.Hue.value,\n PageData.Controls.Saturation.value);\n}", "setFilter() {\n if (this.brokenness.lvl1.on) //Only process if brokenness lvl 1 has been toggled (meaning filter doesn't display at all unless at least lvl1 is true)\n {\n if (this.brokenness.lvl1.on && !this.brokenness.lvl2.on) //process only if brokenness lvl1 is turned on (if microaggression 1 has played), but not lvl2 yet.\n {\n //Set the filter values to the brokenness lvl1 values\n this.filter.threshold = this.brokenness.lvl1.filter.threshold;\n this.filter.triggerThreshold = this.brokenness.lvl1.filter.triggerThreshold;\n this.filter.timeApplied = this.brokenness.lvl1.filter.timeApplied;\n } else if (this.brokenness.lvl2.on && !this.brokenness.lvl3.on) //process only if brokenness lvl2 is turned on but not lvl3 yet.\n {\n //Set the filter values to the brokenness lvl2 values\n this.filter.threshold = this.brokenness.lvl2.filter.threshold;\n this.filter.triggerThreshold = this.brokenness.lvl2.filter.triggerThreshold;\n this.filter.timeApplied = this.brokenness.lvl2.filter.timeApplied;\n } else if (this.brokenness.lvl3.on && !this.brokenness.lvl4.on) //process only if brokenness lvl3 is turned on but not lvl4 yet.\n {\n //Set the filter values to the brokenness lvl2 values\n this.filter.threshold = this.brokenness.lvl3.filter.threshold;\n this.filter.triggerThreshold = this.brokenness.lvl3.filter.triggerThreshold;\n this.filter.timeApplied = this.brokenness.lvl3.filter.timeApplied;\n } else if (this.brokenness.lvl4.on && !this.brokenness.lvl5.on) //process only if brokenness lvl4 is turned on but not lvl5 yet.\n {\n //Set the filter values to the brokenness lvl2 values\n this.filter.threshold = this.brokenness.lvl4.filter.threshold;\n this.filter.triggerThreshold = this.brokenness.lvl4.filter.triggerThreshold;\n this.filter.timeApplied = this.brokenness.lvl4.filter.timeApplied;\n } else if (this.brokenness.lvl5.on) //process only if brokenness lvl5 is turned on\n {\n //Set the filter values to the brokenness lvl2 values\n this.filter.threshold = this.brokenness.lvl5.filter.threshold;\n this.filter.triggerThreshold = this.brokenness.lvl5.filter.triggerThreshold;\n this.filter.timeApplied = this.brokenness.lvl5.filter.timeApplied;\n }\n\n\n let changeFilter = random(); // let changeFilter be a random number between 0 and 1\n if (changeFilter < this.filter.triggerThreshold) { //Process only if the random changeFilter is smaller than the established threshold\n if (!this.filter.on) {\n this.filter.on = true //turn filter on and setTimeout to turn it off in 1000 milliseconds\n setTimeout(() => {\n this.filter.on = false\n }, this.filter.timeApplied)\n }\n }\n if (this.filter.on) { // If filter is on, apply filter\n filter(this.filter.mode, this.filter.threshold)\n }\n }\n }", "function createFilters() {\n\n}", "function setFilters() {} // 2042", "function filter(event) {\n Caman(filters, editedPhoto.src, function() {\n this.revert(false);\n this.brightness($brightnessSlider.val());\n this.contrast($contrastSlider.val());\n this.saturation($saturationSlider.val());\n this.render(function() {\n preview.src = filters.toDataURL();\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }