language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function constructCalendarData(academicYear, startDate, conditions, innerCall, index){
//DATA AND FUNCTIONS
var data = CreateCalendar(academicYear);
var setConditions = [];
if((typeof startDate == "undefined")||(typeof conditions == "undefined")){
var spareConditions = ["fallStartMon", "summerToFallMoreThanWeek", "convocationFriBeforeFirstID",
"extendedFallBreak", "commencementTueFri", "CesarChavezInSpringBreak", "limitWinterTenDays", "springAfterMLK"];
setConditions = spareConditions;
//spareConditions = TranslateConditions(spareConditions);
var spareStartDate = [];
spareStartDate.month = "AUG";
spareStartDate.dayNumber = 23;
data.candidateEntryData.startDate = spareStartDate;
}
else{
data.candidateEntryData.startDate = startDate;
data.candidateEntryData.conditions = conditions;
}
data.candidateEntryData.conditions = TranslateConditions(data.candidateEntryData.conditions);
ExecuteProgram(data.candidateEntryData, startDate, data.candidateEntryData.conditions);
if(!((typeof innerCall == "undefined")|| innerCall == true)){
var testPoss = getPossibilities(data.candidateEntryData);
//var success = applyPossibilities(data.candidateEntryData, testPoss);
//var success = getCalendarCount(data.candidateEntryData, testPoss);
//console.log(getEntryCount(academicYear, startDate, conditions));
var testGetByIndex = calendarByIndex(data.candidateEntryData, testPoss, index);
//var testGetByIndex = calendarByIndex(data.candidateEntryData, testPoss, 0);
//console.log(testGetByIndex);
return testGetByIndex;
}
else{
return data;
}
}//end creation of data | function constructCalendarData(academicYear, startDate, conditions, innerCall, index){
//DATA AND FUNCTIONS
var data = CreateCalendar(academicYear);
var setConditions = [];
if((typeof startDate == "undefined")||(typeof conditions == "undefined")){
var spareConditions = ["fallStartMon", "summerToFallMoreThanWeek", "convocationFriBeforeFirstID",
"extendedFallBreak", "commencementTueFri", "CesarChavezInSpringBreak", "limitWinterTenDays", "springAfterMLK"];
setConditions = spareConditions;
//spareConditions = TranslateConditions(spareConditions);
var spareStartDate = [];
spareStartDate.month = "AUG";
spareStartDate.dayNumber = 23;
data.candidateEntryData.startDate = spareStartDate;
}
else{
data.candidateEntryData.startDate = startDate;
data.candidateEntryData.conditions = conditions;
}
data.candidateEntryData.conditions = TranslateConditions(data.candidateEntryData.conditions);
ExecuteProgram(data.candidateEntryData, startDate, data.candidateEntryData.conditions);
if(!((typeof innerCall == "undefined")|| innerCall == true)){
var testPoss = getPossibilities(data.candidateEntryData);
//var success = applyPossibilities(data.candidateEntryData, testPoss);
//var success = getCalendarCount(data.candidateEntryData, testPoss);
//console.log(getEntryCount(academicYear, startDate, conditions));
var testGetByIndex = calendarByIndex(data.candidateEntryData, testPoss, index);
//var testGetByIndex = calendarByIndex(data.candidateEntryData, testPoss, 0);
//console.log(testGetByIndex);
return testGetByIndex;
}
else{
return data;
}
}//end creation of data |
JavaScript | function Day(dayNumber, dayOfWeek, type, term){
this.dayNumber = dayNumber;
this.dayOfWeek = DaysOfWeek[dayOfWeek];
this.type = DayTypes[type];
this.term = Terms[term];
} | function Day(dayNumber, dayOfWeek, type, term){
this.dayNumber = dayNumber;
this.dayOfWeek = DaysOfWeek[dayOfWeek];
this.type = DayTypes[type];
this.term = Terms[term];
} |
JavaScript | function Week(daySet, weekNumber, termWeek){
this.daySet = daySet;
this.weekNumber = weekNumber;
this.termWeek = termWeek; //counts the number
} | function Week(daySet, weekNumber, termWeek){
this.daySet = daySet;
this.weekNumber = weekNumber;
this.termWeek = termWeek; //counts the number
} |
JavaScript | function Month(weekSet, monthNumber, monthName, dayTypeCounters){
this.weekSet = weekSet;
this.monthNumber = monthNumber;
this.monthName = monthName;
this.dayTypeCounters = dayTypeCounters;
} | function Month(weekSet, monthNumber, monthName, dayTypeCounters){
this.weekSet = weekSet;
this.monthNumber = monthNumber;
this.monthName = monthName;
this.dayTypeCounters = dayTypeCounters;
} |
JavaScript | function ReturnData(guiTree, candidateEntryData, academicYear){
this.guiTree = guiTree;
this.candidateEntryData = candidateEntryData;
this.year = academicYear;
} | function ReturnData(guiTree, candidateEntryData, academicYear){
this.guiTree = guiTree;
this.candidateEntryData = candidateEntryData;
this.year = academicYear;
} |
JavaScript | function Day(dayNumber, dayOfWeek, type, term){
this.dayNumber = dayNumber;
this.dayOfWeek = DaysOfWeek[dayOfWeek];
this.type = DayTypes[type];
this.term = Terms[term];
} | function Day(dayNumber, dayOfWeek, type, term){
this.dayNumber = dayNumber;
this.dayOfWeek = DaysOfWeek[dayOfWeek];
this.type = DayTypes[type];
this.term = Terms[term];
} |
JavaScript | function Week(daySet, weekNumber, termWeek){
this.daySet = daySet;
this.weekNumber = weekNumber;
this.termWeek = termWeek; //counts the number
} | function Week(daySet, weekNumber, termWeek){
this.daySet = daySet;
this.weekNumber = weekNumber;
this.termWeek = termWeek; //counts the number
} |
JavaScript | function Month(weekSet, monthNumber, monthName, dayTypeCounters){
this.weekSet = weekSet;
this.monthNumber = monthNumber;
this.monthName = monthName;
this.dayTypeCounters = dayTypeCounters;
} | function Month(weekSet, monthNumber, monthName, dayTypeCounters){
this.weekSet = weekSet;
this.monthNumber = monthNumber;
this.monthName = monthName;
this.dayTypeCounters = dayTypeCounters;
} |
JavaScript | function ReturnData(guiTree, candidateEntryData){
this.guiTree = guiTree;
this.candidateEntryData = candidateEntryData;
this.year = academicYear;
} | function ReturnData(guiTree, candidateEntryData){
this.guiTree = guiTree;
this.candidateEntryData = candidateEntryData;
this.year = academicYear;
} |
JavaScript | next() {
let ret;
let rune;
if (this._nextRune !== null) {
rune = this._nextRune;
this._nextRune = null;
ret = { value: rune || undefined, done: !rune };
}
else {
ret = this._next();
rune = ret.value;
}
this.prevIndex = this.index;
this.index += rune ? rune.length : 0;
return ret;
} | next() {
let ret;
let rune;
if (this._nextRune !== null) {
rune = this._nextRune;
this._nextRune = null;
ret = { value: rune || undefined, done: !rune };
}
else {
ret = this._next();
rune = ret.value;
}
this.prevIndex = this.index;
this.index += rune ? rune.length : 0;
return ret;
} |
JavaScript | peek() {
if (this._nextRune === null) {
this._nextRune = this._next().value;
}
return this._nextRune;
} | peek() {
if (this._nextRune === null) {
this._nextRune = this._next().value;
}
return this._nextRune;
} |
JavaScript | diagnose(type, index) {
const diagnosis = new Diagnosis(type, index);
if (this._worstDiagnosis === null || type > this._worstDiagnosis.type) {
this._worstDiagnosis = diagnosis;
}
this._diagnoses.push(diagnosis);
} | diagnose(type, index) {
const diagnosis = new Diagnosis(type, index);
if (this._worstDiagnosis === null || type > this._worstDiagnosis.type) {
this._worstDiagnosis = diagnosis;
}
this._diagnoses.push(diagnosis);
} |
JavaScript | parseQuotedString() {
// TODO: Use some kind of stringbuilder? Can we just slice the original
// string instead?
let string = '';
let needBeQuoted = false;
for (const rune of this._reader) {
switch (rune) {
case '\\':
// Quoted pair
const quotedRune = this.parseQuotedPair();
string += `\\${quotedRune}`;
needBeQuoted = true;
// TODO: Do we need to track the element size?
break;
case '\r':
// Folding white space. Spaces are allowed as regular characters inside a quoted string - it's only FWS if we include '\t' or '\r\n'
// TODO: Consolidate reading the CRLF and handling its error
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case '\t':
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// Runs of FWS, comment, or CFWS that occur between lexical tokens in
// a structured header field are semantically interpreted as a single
// space character.
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// the CRLF in any FWS/CFWS that appears within the quoted-string [is]
// semantically "invisible" and therefore not part of the
// quoted-string
string += ' ';
this.diagnose(Constants.diagnoses.cfwsFWS);
this.parseFWS(rune);
// TODO: What's the impact of not doing this? Seems more conservative to do this
needBeQuoted = true;
break;
case '"':
// End of quoted string
if (needBeQuoted || !this._normalizeUnnecessaryQuoted || !string) {
return `"${string}"`;
}
return string;
default:
// QTEXT
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// qtext = %d33 / ; Printable US-ASCII
// %d35-91 / ; characters not including
// %d93-126 / ; "\" or the quote character
// obs-qtext
//
// obs-qtext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
const code = rune.codePointAt(0);
if ((code !== 127 && internals.c1Controls(code)) || code === 0 || code === 10) {
this.diagnose(Constants.diagnoses.errExpectingQTEXT);
}
else if (internals.c0Controls(code) || code === 127) {
this.diagnose(Constants.diagnoses.deprecatedQTEXT);
}
else if (internals.isSurrogate(code)) {
this.diagnose(Constants.diagnoses.errMalformedUnicode);
}
string += rune;
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// If the string can be represented as a dot-atom (that is, it contains
// no characters other than atext characters or "." surrounded by atext
// characters), then the dot-atom form SHOULD be used and the quoted-
// string form SHOULD NOT be used.
// TODO: Should we do something about ^ for e.g. normalization
}
}
this.diagnose(Constants.diagnoses.errUnclosedQuotedString);
return string;
} | parseQuotedString() {
// TODO: Use some kind of stringbuilder? Can we just slice the original
// string instead?
let string = '';
let needBeQuoted = false;
for (const rune of this._reader) {
switch (rune) {
case '\\':
// Quoted pair
const quotedRune = this.parseQuotedPair();
string += `\\${quotedRune}`;
needBeQuoted = true;
// TODO: Do we need to track the element size?
break;
case '\r':
// Folding white space. Spaces are allowed as regular characters inside a quoted string - it's only FWS if we include '\t' or '\r\n'
// TODO: Consolidate reading the CRLF and handling its error
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case '\t':
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// Runs of FWS, comment, or CFWS that occur between lexical tokens in
// a structured header field are semantically interpreted as a single
// space character.
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// the CRLF in any FWS/CFWS that appears within the quoted-string [is]
// semantically "invisible" and therefore not part of the
// quoted-string
string += ' ';
this.diagnose(Constants.diagnoses.cfwsFWS);
this.parseFWS(rune);
// TODO: What's the impact of not doing this? Seems more conservative to do this
needBeQuoted = true;
break;
case '"':
// End of quoted string
if (needBeQuoted || !this._normalizeUnnecessaryQuoted || !string) {
return `"${string}"`;
}
return string;
default:
// QTEXT
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// qtext = %d33 / ; Printable US-ASCII
// %d35-91 / ; characters not including
// %d93-126 / ; "\" or the quote character
// obs-qtext
//
// obs-qtext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
const code = rune.codePointAt(0);
if ((code !== 127 && internals.c1Controls(code)) || code === 0 || code === 10) {
this.diagnose(Constants.diagnoses.errExpectingQTEXT);
}
else if (internals.c0Controls(code) || code === 127) {
this.diagnose(Constants.diagnoses.deprecatedQTEXT);
}
else if (internals.isSurrogate(code)) {
this.diagnose(Constants.diagnoses.errMalformedUnicode);
}
string += rune;
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// If the string can be represented as a dot-atom (that is, it contains
// no characters other than atext characters or "." surrounded by atext
// characters), then the dot-atom form SHOULD be used and the quoted-
// string form SHOULD NOT be used.
// TODO: Should we do something about ^ for e.g. normalization
}
}
this.diagnose(Constants.diagnoses.errUnclosedQuotedString);
return string;
} |
JavaScript | parseDomainLiteral() {
let literal = '';
for (const rune of this._reader) {
switch (rune) {
case ']':
// End of domain literal
// TODO: what about if there are configured exclusions?
const worstDiagnosis = this._diagnoses.getWorstDiagnosis();
if (worstDiagnosis && worstDiagnosis.type >= Constants.categories.deprecated) {
// TODO: Is this "optimization" worthwhile when we want to report all the diagnoses?
// TODO: Should we have something generic that tells us whether to check a branch depending on whether we're in a report-all mode?
this.diagnose(Constants.diagnoses.rfc5322DomainLiteral);
}
else {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
//
// http://tools.ietf.org/html/rfc5321#section-4.1.3
// IPv4-address-literal = Snum 3("." Snum)
//
// IPv6-address-literal = "IPv6:" IPv6-addr
//
// General-address-literal = Standardized-tag ":" 1*dcontent
//
// Standardized-tag = Ldh-str
// ; Standardized-tag MUST be specified in a
// ; Standards-Track RFC and registered with IANA
//
// dcontent = %d33-90 / ; Printable US-ASCII
// %d94-126 ; excl. "[", "\", "]"
//
// Snum = 1*3DIGIT
// ; representing a decimal integer
// ; value in the range 0 through 255
//
// IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp
//
// IPv6-hex = 1*4HEXDIG
//
// IPv6-full = IPv6-hex 7(":" IPv6-hex)
//
// IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::"
// [IPv6-hex *5(":" IPv6-hex)]
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 6 groups in addition to the
// ; "::" may be present.
//
// IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal
//
// IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::"
// [IPv6-hex *3(":" IPv6-hex) ":"]
// IPv4-address-literal
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 4 groups in addition to the
// ; "::" and IPv4-address-literal may be present.
const matchesIP = internals.regex.ipV4.exec(literal);
let index = -1;
let addressLiteral = literal;
// Maybe extract the IPv4 part from the end of the address-literal
if (matchesIP) {
index = matchesIP.index;
if (index !== 0) {
// Convert IPv4 part to IPv6 format for further testing
addressLiteral = addressLiteral.slice(0, index) + '0:0';
}
}
if (index === 0) {
// We only see a valid IPv4 address, so we're done here
this.diagnose(Constants.diagnoses.rfc5321AddressLiteral);
}
else if (!addressLiteral.toLowerCase().startsWith('ipv6:')) {
this.diagnose(Constants.diagnoses.rfc5322DomainLiteral);
}
else {
const match = addressLiteral.slice(5);
const groups = match.split(':');
let maxGroups = internals.maxIPv6Groups;
index = match.indexOf('::');
// TODO: make this condition comprehensible
if (!~index) {
// Need exactly the right number of groups
if (groups.length !== maxGroups) {
// TODO: Fix the indices for these diagnoses
this.diagnose(Constants.diagnoses.rfc5322IPv6GroupCount);
}
}
else if (match.indexOf('::', index + 1) > 0) {
this.diagnose(Constants.diagnoses.rfc5322IPv62x2xColon);
}
else {
if (index === 0 || index === match.length - 2) {
// RFC 4291 allows :: at the start or end of an address with 7 other groups in addition
++maxGroups;
}
if (groups.length > maxGroups) {
this.diagnose(Constants.diagnoses.rfc5322IPv6MaxGroups);
}
else if (groups.length === maxGroups) {
// Eliding a single "::"
this.diagnose(Constants.diagnoses.deprecatedIPv6);
}
}
// IPv6 testing strategy
if (match[0] === ':' && match[1] !== ':') {
this.diagnose(Constants.diagnoses.rfc5322IPv6ColonStart);
}
else if (match[match.length - 1] === ':' && match[match.length - 2] !== ':') {
this.diagnose(Constants.diagnoses.rfc5322IPv6ColonEnd);
}
else if (internals.checkIpV6(groups)) {
this.diagnose(Constants.diagnoses.rfc5321AddressLiteral);
}
else {
this.diagnose(Constants.diagnoses.rfc5322IPv6BadCharacter);
}
}
}
return `${literal}]`;
case '\\':
this.diagnose(Constants.diagnoses.rfc5322DomainLiteralOBSDText);
const quotedRune = this.parseQuotedPair({ allowMalformedUnicode: true });
if (!quotedRune) {
break;
}
if (quotedRune.codePointAt(0) > 0x7f) {
this.diagnose(Constants.diagnoses.errExpectingQPair);
}
else {
literal += quotedRune;
}
break;
case '\r':
// Folding white space
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case ' ':
case '\t':
this.diagnose(Constants.diagnoses.cfwsFWS);
this.parseFWS(rune);
break;
default:
// DTEXT
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
const code = rune.codePointAt(0);
// '\r', '\n', ' ', and '\t' have already been parsed above
if ((code !== 127 && internals.c1Controls(code)) || code === 0 || code > 127 || rune === '[') {
// Fatal error
this.diagnose(Constants.diagnoses.errExpectingDTEXT);
break;
}
else if (internals.c0Controls(code) || code === 127) {
this.diagnose(Constants.diagnoses.rfc5322DomainLiteralOBSDText);
}
literal += rune;
}
}
// TODO: are there other diagnoses to consider here?
this.diagnose(Constants.diagnoses.errUnclosedDomainLiteral);
return literal;
} | parseDomainLiteral() {
let literal = '';
for (const rune of this._reader) {
switch (rune) {
case ']':
// End of domain literal
// TODO: what about if there are configured exclusions?
const worstDiagnosis = this._diagnoses.getWorstDiagnosis();
if (worstDiagnosis && worstDiagnosis.type >= Constants.categories.deprecated) {
// TODO: Is this "optimization" worthwhile when we want to report all the diagnoses?
// TODO: Should we have something generic that tells us whether to check a branch depending on whether we're in a report-all mode?
this.diagnose(Constants.diagnoses.rfc5322DomainLiteral);
}
else {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
//
// http://tools.ietf.org/html/rfc5321#section-4.1.3
// IPv4-address-literal = Snum 3("." Snum)
//
// IPv6-address-literal = "IPv6:" IPv6-addr
//
// General-address-literal = Standardized-tag ":" 1*dcontent
//
// Standardized-tag = Ldh-str
// ; Standardized-tag MUST be specified in a
// ; Standards-Track RFC and registered with IANA
//
// dcontent = %d33-90 / ; Printable US-ASCII
// %d94-126 ; excl. "[", "\", "]"
//
// Snum = 1*3DIGIT
// ; representing a decimal integer
// ; value in the range 0 through 255
//
// IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp
//
// IPv6-hex = 1*4HEXDIG
//
// IPv6-full = IPv6-hex 7(":" IPv6-hex)
//
// IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::"
// [IPv6-hex *5(":" IPv6-hex)]
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 6 groups in addition to the
// ; "::" may be present.
//
// IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal
//
// IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::"
// [IPv6-hex *3(":" IPv6-hex) ":"]
// IPv4-address-literal
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 4 groups in addition to the
// ; "::" and IPv4-address-literal may be present.
const matchesIP = internals.regex.ipV4.exec(literal);
let index = -1;
let addressLiteral = literal;
// Maybe extract the IPv4 part from the end of the address-literal
if (matchesIP) {
index = matchesIP.index;
if (index !== 0) {
// Convert IPv4 part to IPv6 format for further testing
addressLiteral = addressLiteral.slice(0, index) + '0:0';
}
}
if (index === 0) {
// We only see a valid IPv4 address, so we're done here
this.diagnose(Constants.diagnoses.rfc5321AddressLiteral);
}
else if (!addressLiteral.toLowerCase().startsWith('ipv6:')) {
this.diagnose(Constants.diagnoses.rfc5322DomainLiteral);
}
else {
const match = addressLiteral.slice(5);
const groups = match.split(':');
let maxGroups = internals.maxIPv6Groups;
index = match.indexOf('::');
// TODO: make this condition comprehensible
if (!~index) {
// Need exactly the right number of groups
if (groups.length !== maxGroups) {
// TODO: Fix the indices for these diagnoses
this.diagnose(Constants.diagnoses.rfc5322IPv6GroupCount);
}
}
else if (match.indexOf('::', index + 1) > 0) {
this.diagnose(Constants.diagnoses.rfc5322IPv62x2xColon);
}
else {
if (index === 0 || index === match.length - 2) {
// RFC 4291 allows :: at the start or end of an address with 7 other groups in addition
++maxGroups;
}
if (groups.length > maxGroups) {
this.diagnose(Constants.diagnoses.rfc5322IPv6MaxGroups);
}
else if (groups.length === maxGroups) {
// Eliding a single "::"
this.diagnose(Constants.diagnoses.deprecatedIPv6);
}
}
// IPv6 testing strategy
if (match[0] === ':' && match[1] !== ':') {
this.diagnose(Constants.diagnoses.rfc5322IPv6ColonStart);
}
else if (match[match.length - 1] === ':' && match[match.length - 2] !== ':') {
this.diagnose(Constants.diagnoses.rfc5322IPv6ColonEnd);
}
else if (internals.checkIpV6(groups)) {
this.diagnose(Constants.diagnoses.rfc5321AddressLiteral);
}
else {
this.diagnose(Constants.diagnoses.rfc5322IPv6BadCharacter);
}
}
}
return `${literal}]`;
case '\\':
this.diagnose(Constants.diagnoses.rfc5322DomainLiteralOBSDText);
const quotedRune = this.parseQuotedPair({ allowMalformedUnicode: true });
if (!quotedRune) {
break;
}
if (quotedRune.codePointAt(0) > 0x7f) {
this.diagnose(Constants.diagnoses.errExpectingQPair);
}
else {
literal += quotedRune;
}
break;
case '\r':
// Folding white space
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case ' ':
case '\t':
this.diagnose(Constants.diagnoses.cfwsFWS);
this.parseFWS(rune);
break;
default:
// DTEXT
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
const code = rune.codePointAt(0);
// '\r', '\n', ' ', and '\t' have already been parsed above
if ((code !== 127 && internals.c1Controls(code)) || code === 0 || code > 127 || rune === '[') {
// Fatal error
this.diagnose(Constants.diagnoses.errExpectingDTEXT);
break;
}
else if (internals.c0Controls(code) || code === 127) {
this.diagnose(Constants.diagnoses.rfc5322DomainLiteralOBSDText);
}
literal += rune;
}
}
// TODO: are there other diagnoses to consider here?
this.diagnose(Constants.diagnoses.errUnclosedDomainLiteral);
return literal;
} |
JavaScript | parseDomain() {
const elements = [];
let element = '';
let assertEnd = null;
for (const rune of this._reader) {
switch (rune) {
case '(':
// Comment
if (!element) {
// Comments at the start of the domain are deprecated in the text, comments at the start of a subdomain are obs-domain
// http://tools.ietf.org/html/rfc5322#section-3.4.1
this.diagnose(elements.length === 0 ? Constants.diagnoses.deprecatedCFWSNearAt : Constants.diagnoses.deprecatedComment);
}
else {
this.diagnose(Constants.diagnoses.cfwsComment);
// We can't start a comment mid-element, better be at the end
assertEnd = 'cfws';
}
this.parseComment();
break;
case '.':
if (assertEnd === 'literal') {
// TODO: This isn't quite the right diagnosis
this.diagnose(Constants.diagnoses.errDotAfterDomainLiteral);
}
// Next dot-atom element
if (!element) {
// Another dot, already? Fatal error.
this.diagnose(elements.length === 0 ? Constants.diagnoses.errDotStart : Constants.diagnoses.errConsecutiveDots);
}
else if (element[element.length - 1] === '-') {
// Previous subdomain ended in a hyphen. Fatal error.
this.diagnose(Constants.diagnoses.errDomainHyphenEnd, this._reader.prevIndex - 1);
}
else if (Punycode.toASCII(element).length > 63) {
// RFC 5890 specifies that domain labels that are encoded using the Punycode algorithm
// must adhere to the <= 63 octet requirement.
// This includes string prefixes from the Punycode algorithm.
//
// https://tools.ietf.org/html/rfc5890#section-2.3.2.1
// labels 63 octets or less
this.diagnose(Constants.diagnoses.rfc5322LabelTooLong);
}
// CFWS is OK again now we're at the beginning of an element (although
// it may be obsolete CFWS)
assertEnd = null;
elements.push(element);
element = '';
break;
case '[':
// Domain literal
// TODO: can we add a flag that returns the remainder once
// we fail the configured validity? That way we could
// support me@[127.0.0.1].no which would produce ".no" as
// the remainder.
if (element) {
elements.push(element);
element = '';
}
if (elements.length) {
this.diagnose(Constants.diagnoses.errExpectingATEXT);
}
else {
// Domain literal must be the only component
assertEnd = 'literal';
// TODO: what happens after this runs?
element += rune + this.parseDomainLiteral();
}
break;
case '\r':
// Folding white space
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case ' ':
case '\t':
if (!element) {
this.diagnose(elements.length === 0 ? Constants.diagnoses.deprecatedCFWSNearAt : Constants.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, so this better be the end
this.diagnose(Constants.diagnoses.cfwsFWS);
assertEnd = 'cfws';
}
this.parseFWS(rune);
break;
default:
// ATEXT
// RFC 5322 allows any atext...
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// But RFC 5321 only allows letter-digit-hyphen to comply with DNS rules
// (RFCs 1034 & 1123)
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// sub-domain = Let-dig [Ldh-str]
// Let-dig = ALPHA / DIGIT
// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
if (assertEnd) {
// We have encountered ATEXT where it is not valid
switch (assertEnd) {
case 'cfws':
this.diagnose(Constants.diagnoses.errATEXTAfterCFWS);
break;
default:
this.diagnose(Constants.diagnoses.errATEXTAfterDomainLiteral);
}
}
const code = rune.codePointAt(0);
if (internals.specials(code) || internals.c0Controls(code) || internals.c1Controls(code)) {
// Fatal error
this.diagnose(Constants.diagnoses.errExpectingATEXT);
}
else if (rune === '-') {
if (!element) {
this.diagnose(Constants.diagnoses.errDomainHyphenStart);
}
}
// TODO: Where did 192 come from?
else if (code < 48 || (code > 122 && code < 192) || (code > 57 && code < 65) || (code > 90 && code < 97)) {
// Check if it's a neither a number nor a latin/unicode letter
this.diagnose(Constants.diagnoses.rfc5322Domain);
}
element += rune;
}
}
if (element) {
elements.push(element);
}
if (!elements.length) {
this.diagnose(Constants.diagnoses.errNoDomain);
}
else if (!element) {
this.diagnose(Constants.diagnoses.errDotEnd);
}
else {
if (element[element.length - 1] === '-') {
// TODO: Fix the index on this
this.diagnose(Constants.diagnoses.errDomainHyphenEnd);
}
// Per RFC 5321, domain atoms are limited to letter-digit-hyphen, so we only need to check code <= 57 to check for a digit.
// This also works with i18n domains.
if (element.codePointAt(0) <= 57) {
this.diagnose(Constants.diagnoses.rfc5321TLDNumeric);
}
if (Punycode.toASCII(element).length > 63) {
this.diagnose(Constants.diagnoses.rfc5322LabelTooLong);
}
if (Punycode.toASCII(elements.join('.')).length > 255) {
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.2
// The maximum total length of a domain name or number is 255 octets.
this.diagnose(Constants.diagnoses.rfc5322DomainTooLong);
}
}
// TODO: Also validate minDomainAtoms, tldAllow/tldForbid
return { elements, domain: elements.join('.') };
} | parseDomain() {
const elements = [];
let element = '';
let assertEnd = null;
for (const rune of this._reader) {
switch (rune) {
case '(':
// Comment
if (!element) {
// Comments at the start of the domain are deprecated in the text, comments at the start of a subdomain are obs-domain
// http://tools.ietf.org/html/rfc5322#section-3.4.1
this.diagnose(elements.length === 0 ? Constants.diagnoses.deprecatedCFWSNearAt : Constants.diagnoses.deprecatedComment);
}
else {
this.diagnose(Constants.diagnoses.cfwsComment);
// We can't start a comment mid-element, better be at the end
assertEnd = 'cfws';
}
this.parseComment();
break;
case '.':
if (assertEnd === 'literal') {
// TODO: This isn't quite the right diagnosis
this.diagnose(Constants.diagnoses.errDotAfterDomainLiteral);
}
// Next dot-atom element
if (!element) {
// Another dot, already? Fatal error.
this.diagnose(elements.length === 0 ? Constants.diagnoses.errDotStart : Constants.diagnoses.errConsecutiveDots);
}
else if (element[element.length - 1] === '-') {
// Previous subdomain ended in a hyphen. Fatal error.
this.diagnose(Constants.diagnoses.errDomainHyphenEnd, this._reader.prevIndex - 1);
}
else if (Punycode.toASCII(element).length > 63) {
// RFC 5890 specifies that domain labels that are encoded using the Punycode algorithm
// must adhere to the <= 63 octet requirement.
// This includes string prefixes from the Punycode algorithm.
//
// https://tools.ietf.org/html/rfc5890#section-2.3.2.1
// labels 63 octets or less
this.diagnose(Constants.diagnoses.rfc5322LabelTooLong);
}
// CFWS is OK again now we're at the beginning of an element (although
// it may be obsolete CFWS)
assertEnd = null;
elements.push(element);
element = '';
break;
case '[':
// Domain literal
// TODO: can we add a flag that returns the remainder once
// we fail the configured validity? That way we could
// support me@[127.0.0.1].no which would produce ".no" as
// the remainder.
if (element) {
elements.push(element);
element = '';
}
if (elements.length) {
this.diagnose(Constants.diagnoses.errExpectingATEXT);
}
else {
// Domain literal must be the only component
assertEnd = 'literal';
// TODO: what happens after this runs?
element += rune + this.parseDomainLiteral();
}
break;
case '\r':
// Folding white space
const nextRune = this._reader.peek();
if (nextRune === '\n') {
this._reader.next();
}
else {
// Fatal error
this.diagnose(Constants.diagnoses.errCRNoLF);
// "Recover" from this fatal error by not consuming the next rune
}
// Fallthrough
case ' ':
case '\t':
if (!element) {
this.diagnose(elements.length === 0 ? Constants.diagnoses.deprecatedCFWSNearAt : Constants.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, so this better be the end
this.diagnose(Constants.diagnoses.cfwsFWS);
assertEnd = 'cfws';
}
this.parseFWS(rune);
break;
default:
// ATEXT
// RFC 5322 allows any atext...
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// But RFC 5321 only allows letter-digit-hyphen to comply with DNS rules
// (RFCs 1034 & 1123)
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// sub-domain = Let-dig [Ldh-str]
// Let-dig = ALPHA / DIGIT
// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
if (assertEnd) {
// We have encountered ATEXT where it is not valid
switch (assertEnd) {
case 'cfws':
this.diagnose(Constants.diagnoses.errATEXTAfterCFWS);
break;
default:
this.diagnose(Constants.diagnoses.errATEXTAfterDomainLiteral);
}
}
const code = rune.codePointAt(0);
if (internals.specials(code) || internals.c0Controls(code) || internals.c1Controls(code)) {
// Fatal error
this.diagnose(Constants.diagnoses.errExpectingATEXT);
}
else if (rune === '-') {
if (!element) {
this.diagnose(Constants.diagnoses.errDomainHyphenStart);
}
}
// TODO: Where did 192 come from?
else if (code < 48 || (code > 122 && code < 192) || (code > 57 && code < 65) || (code > 90 && code < 97)) {
// Check if it's a neither a number nor a latin/unicode letter
this.diagnose(Constants.diagnoses.rfc5322Domain);
}
element += rune;
}
}
if (element) {
elements.push(element);
}
if (!elements.length) {
this.diagnose(Constants.diagnoses.errNoDomain);
}
else if (!element) {
this.diagnose(Constants.diagnoses.errDotEnd);
}
else {
if (element[element.length - 1] === '-') {
// TODO: Fix the index on this
this.diagnose(Constants.diagnoses.errDomainHyphenEnd);
}
// Per RFC 5321, domain atoms are limited to letter-digit-hyphen, so we only need to check code <= 57 to check for a digit.
// This also works with i18n domains.
if (element.codePointAt(0) <= 57) {
this.diagnose(Constants.diagnoses.rfc5321TLDNumeric);
}
if (Punycode.toASCII(element).length > 63) {
this.diagnose(Constants.diagnoses.rfc5322LabelTooLong);
}
if (Punycode.toASCII(elements.join('.')).length > 255) {
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.2
// The maximum total length of a domain name or number is 255 octets.
this.diagnose(Constants.diagnoses.rfc5322DomainTooLong);
}
}
// TODO: Also validate minDomainAtoms, tldAllow/tldForbid
return { elements, domain: elements.join('.') };
} |
JavaScript | parse() {
const localParts = this.parseLocal();
const local = localParts.join('.');
// If there's no domain (i.e. there's no @-symbol) then there's no point
// in considering the rest. TODO: Maybe have parseLocal pushback the @?
if (this._diagnoses.hasDiagnosis(Constants.diagnoses.errNoDomain)) {
return null;
}
const { elements: domainParts, domain } = this.parseDomain();
const normalizedEmail = `${local}@${Punycode.toASCII(domain)}`;
// TODO: Should we normalize the domain one way or another?
const domainLength = /^[\x00-\x7f]+$/.test(domain) ? domain.length : Punycode.toASCII(domain).length;
const emailLength = Buffer.byteLength(local, 'utf8') + domainLength + 1;
// TODO: Add test for CFWS not impacting this?
if (emailLength > 254) {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Forward-path = Path
//
// Path = "<" [ A-d-l ":" ] Mailbox ">"
//
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3
// The maximum total length of a reverse-path or forward-path is 256 octets (including the punctuation and element separators).
//
// Thus, even without (obsolete) routing information, the Mailbox can only be 254 characters long. This is confirmed by this verified
// erratum to RFC 3696:
//
// http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
// However, there is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands of 254 characters. Since
// addresses that do not fit in those fields are not normally useful, the upper limit on address lengths should normally be considered
// to be 254.
this.diagnose(Constants.diagnoses.rfc5322TooLong);
}
return {
localParts,
local,
domainParts,
domain,
email: normalizedEmail
};
} | parse() {
const localParts = this.parseLocal();
const local = localParts.join('.');
// If there's no domain (i.e. there's no @-symbol) then there's no point
// in considering the rest. TODO: Maybe have parseLocal pushback the @?
if (this._diagnoses.hasDiagnosis(Constants.diagnoses.errNoDomain)) {
return null;
}
const { elements: domainParts, domain } = this.parseDomain();
const normalizedEmail = `${local}@${Punycode.toASCII(domain)}`;
// TODO: Should we normalize the domain one way or another?
const domainLength = /^[\x00-\x7f]+$/.test(domain) ? domain.length : Punycode.toASCII(domain).length;
const emailLength = Buffer.byteLength(local, 'utf8') + domainLength + 1;
// TODO: Add test for CFWS not impacting this?
if (emailLength > 254) {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Forward-path = Path
//
// Path = "<" [ A-d-l ":" ] Mailbox ">"
//
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3
// The maximum total length of a reverse-path or forward-path is 256 octets (including the punctuation and element separators).
//
// Thus, even without (obsolete) routing information, the Mailbox can only be 254 characters long. This is confirmed by this verified
// erratum to RFC 3696:
//
// http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
// However, there is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands of 254 characters. Since
// addresses that do not fit in those fields are not normally useful, the upper limit on address lengths should normally be considered
// to be 254.
this.diagnose(Constants.diagnoses.rfc5322TooLong);
}
return {
localParts,
local,
domainParts,
domain,
email: normalizedEmail
};
} |
JavaScript | function dateDiff(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
} | function dateDiff(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
} |
JavaScript | function createRow(searchValue) {
// $(".history").empty();
// for (var i = 0; i < history.length; i++) {
// console.log(searchValue)
var li = $("<button>");
li.addClass("list-group-item historyBtn list-group-item-action");
// li.attr("cityVal", searchValue);
li.text(searchValue);
$(".history").append(li);
} | function createRow(searchValue) {
// $(".history").empty();
// for (var i = 0; i < history.length; i++) {
// console.log(searchValue)
var li = $("<button>");
li.addClass("list-group-item historyBtn list-group-item-action");
// li.attr("cityVal", searchValue);
li.text(searchValue);
$(".history").append(li);
} |
JavaScript | function blank_cell_exists(){
for (cell of $('#board .col-xs-2')){
if (!$(cell).text()){
return true;
};
};
} | function blank_cell_exists(){
for (cell of $('#board .col-xs-2')){
if (!$(cell).text()){
return true;
};
};
} |
JavaScript | function handleMessage(message, port)
{
let tabId = port.sender.tab.id;
switch (message.event) {
case "Playing": {
playingTabs.addTab(tabId);
console.log(`Tab ${tabId} is now playing`);
break;
}
case "Stopped": {
playingTabs.removeTab(tabId);
console.log(`Tab ${tabId} is now stopped`);
break;
}
case "Update": {
if (tabId != playingTabs.getActiveTab())
return;
// Send update to Rich Presence
sendMessageToNativeApp({request: "Update", title: message.title, artist: message.artist, album: message.album, finishTimestamp: message.finishTimestamp});
console.log(`Tab ${tabId} Update: ${message.title}, ${message.artist}, ${message.album} , ${message.finishTimestamp}`)
break;
}
}
} | function handleMessage(message, port)
{
let tabId = port.sender.tab.id;
switch (message.event) {
case "Playing": {
playingTabs.addTab(tabId);
console.log(`Tab ${tabId} is now playing`);
break;
}
case "Stopped": {
playingTabs.removeTab(tabId);
console.log(`Tab ${tabId} is now stopped`);
break;
}
case "Update": {
if (tabId != playingTabs.getActiveTab())
return;
// Send update to Rich Presence
sendMessageToNativeApp({request: "Update", title: message.title, artist: message.artist, album: message.album, finishTimestamp: message.finishTimestamp});
console.log(`Tab ${tabId} Update: ${message.title}, ${message.artist}, ${message.album} , ${message.finishTimestamp}`)
break;
}
}
} |
JavaScript | function handleDisconnect(port)
{
// Remove the port from the ports dictionary
delete ports[port.sender.tab.id];
// Remove from playing tabs if necessary
playingTabs.removeTab(port.sender.tab.id);
// Close rich presence if no more tabs are open
if (Object.keys(ports).length <= 0)
closeRichPresence();
console.log(`Tab Disconnected: ${port.sender.tab.id}`);
} | function handleDisconnect(port)
{
// Remove the port from the ports dictionary
delete ports[port.sender.tab.id];
// Remove from playing tabs if necessary
playingTabs.removeTab(port.sender.tab.id);
// Close rich presence if no more tabs are open
if (Object.keys(ports).length <= 0)
closeRichPresence();
console.log(`Tab Disconnected: ${port.sender.tab.id}`);
} |
JavaScript | function locatePlayButton()
{
playButtonElement = document.getElementById('play-pause-button');
if (playButtonElement !== null) {
clearInterval(playButtonInterval);
const observer = new MutationObserver(startPlayingUpdate);
const options = {
attributes: true,
attributeFilter: ['title']
};
observer.observe(playButtonElement, options);
startPlayingUpdate();
}
} | function locatePlayButton()
{
playButtonElement = document.getElementById('play-pause-button');
if (playButtonElement !== null) {
clearInterval(playButtonInterval);
const observer = new MutationObserver(startPlayingUpdate);
const options = {
attributes: true,
attributeFilter: ['title']
};
observer.observe(playButtonElement, options);
startPlayingUpdate();
}
} |
JavaScript | function startPlayingUpdate(records = null, observer = null, overrideTimeout = false)
{
let attribute = playButtonElement.getAttribute('title');
let isCurrentlyPlaying = (attribute === 'Pause');
clearTimeout(playingTimeout);
// Leave if the value isn't different than our previous value
if (isPlaying === isCurrentlyPlaying)
return;
// This timeout serves to ensure that several quick changes to the playing
// value only result in a single update
if (!overrideTimeout) {
playingTimeout = setTimeout(finishPlayingUpdate, 500, isCurrentlyPlaying);
} else {
finishPlayingUpdate(isCurrentlyPlaying);
}
} | function startPlayingUpdate(records = null, observer = null, overrideTimeout = false)
{
let attribute = playButtonElement.getAttribute('title');
let isCurrentlyPlaying = (attribute === 'Pause');
clearTimeout(playingTimeout);
// Leave if the value isn't different than our previous value
if (isPlaying === isCurrentlyPlaying)
return;
// This timeout serves to ensure that several quick changes to the playing
// value only result in a single update
if (!overrideTimeout) {
playingTimeout = setTimeout(finishPlayingUpdate, 500, isCurrentlyPlaying);
} else {
finishPlayingUpdate(isCurrentlyPlaying);
}
} |
JavaScript | function finishPlayingUpdate(isCurrentlyPlaying)
{
isPlaying = isCurrentlyPlaying;
// Notify the background script of the new playing value
port.postMessage({event: isPlaying ? 'Playing' : 'Stopped'});
// If we have not found the song info elements yet
if (songInfoInterval === null)
songInfoInterval = setInterval(locateSongInfoElements, 500);
// Force update after playing is started
if (isPlaying)
forceUpdate();
} | function finishPlayingUpdate(isCurrentlyPlaying)
{
isPlaying = isCurrentlyPlaying;
// Notify the background script of the new playing value
port.postMessage({event: isPlaying ? 'Playing' : 'Stopped'});
// If we have not found the song info elements yet
if (songInfoInterval === null)
songInfoInterval = setInterval(locateSongInfoElements, 500);
// Force update after playing is started
if (isPlaying)
forceUpdate();
} |
JavaScript | function locateSongInfoElements()
{
// Locate elemenets on the DOM
let elements = document.getElementsByClassName('content-info-wrapper style-scope ytmusic-player-bar');
contentWrapper = elements.length > 0 ? elements[0] : null;
progressBarElement = document.getElementById('progress-bar');
// If the elements were found, bind mutation observers and force an update
if (contentWrapper !== null && progressBarElement !== null) {
clearInterval(songInfoInterval);
const contentObserver = new MutationObserver(startSongInfoUpdate);
const contentObserverOptions = {
subtree: true,
attributes: true,
attributeFilter: ['title']
};
contentObserver.observe(contentWrapper, contentObserverOptions);
const progressBarObserver = new MutationObserver(startSongInfoUpdate);
const progressBarOptions = {
attributes: true,
attributeFilter: ['value', 'aria-valuemax']
};
progressBarObserver.observe(progressBarElement, progressBarOptions);
startSongInfoUpdate();
}
} | function locateSongInfoElements()
{
// Locate elemenets on the DOM
let elements = document.getElementsByClassName('content-info-wrapper style-scope ytmusic-player-bar');
contentWrapper = elements.length > 0 ? elements[0] : null;
progressBarElement = document.getElementById('progress-bar');
// If the elements were found, bind mutation observers and force an update
if (contentWrapper !== null && progressBarElement !== null) {
clearInterval(songInfoInterval);
const contentObserver = new MutationObserver(startSongInfoUpdate);
const contentObserverOptions = {
subtree: true,
attributes: true,
attributeFilter: ['title']
};
contentObserver.observe(contentWrapper, contentObserverOptions);
const progressBarObserver = new MutationObserver(startSongInfoUpdate);
const progressBarOptions = {
attributes: true,
attributeFilter: ['value', 'aria-valuemax']
};
progressBarObserver.observe(progressBarElement, progressBarOptions);
startSongInfoUpdate();
}
} |
JavaScript | function startSongInfoUpdate(records = null, observer = null, overrideTimeout = false)
{
// Find the title and subtitle elements every time so they state accurate
let elements = contentWrapper.getElementsByClassName('title style-scope ytmusic-player-bar');
let titleElement = elements.length > 0 ? elements[0] : null;
elements = contentWrapper.getElementsByClassName('byline style-scope ytmusic-player-bar complex-string');
let subtitleElement = elements.length > 0 ? elements[0] : null;
let newTitle = titleElement !== null ? titleElement.getAttribute('title') : '';
let newSubtitle = subtitleElement !== null ? subtitleElement.getAttribute('title') : '';
let newValue = progressBarElement.getAttribute('value');
let newMaxValue = progressBarElement.getAttribute('aria-valuemax');
// Compute the new timestamp
let secondsLeft = newMaxValue - newValue;
let date = new Date();
let epochSeconds = Math.round(date.getTime() / 1000);
let newFinishTimestamp = epochSeconds + secondsLeft;
clearTimeout(songInfoTimeout);
// Leave if no song information actually changed or this is an advertisement
if ((title === newTitle &&
subtitle === newSubtitle &&
Math.abs(newFinishTimestamp - finishTimestamp) <= 2) ||
newSubtitle === 'Video will play after ad')
return;
if (!overrideTimeout) {
songInfoTimeout = setTimeout(finishSongInfoUpdate, 500, newTitle, newSubtitle, newFinishTimestamp);
} else {
finishSongInfoUpdate(newTitle, newSubtitle, newFinishTimestamp);
}
} | function startSongInfoUpdate(records = null, observer = null, overrideTimeout = false)
{
// Find the title and subtitle elements every time so they state accurate
let elements = contentWrapper.getElementsByClassName('title style-scope ytmusic-player-bar');
let titleElement = elements.length > 0 ? elements[0] : null;
elements = contentWrapper.getElementsByClassName('byline style-scope ytmusic-player-bar complex-string');
let subtitleElement = elements.length > 0 ? elements[0] : null;
let newTitle = titleElement !== null ? titleElement.getAttribute('title') : '';
let newSubtitle = subtitleElement !== null ? subtitleElement.getAttribute('title') : '';
let newValue = progressBarElement.getAttribute('value');
let newMaxValue = progressBarElement.getAttribute('aria-valuemax');
// Compute the new timestamp
let secondsLeft = newMaxValue - newValue;
let date = new Date();
let epochSeconds = Math.round(date.getTime() / 1000);
let newFinishTimestamp = epochSeconds + secondsLeft;
clearTimeout(songInfoTimeout);
// Leave if no song information actually changed or this is an advertisement
if ((title === newTitle &&
subtitle === newSubtitle &&
Math.abs(newFinishTimestamp - finishTimestamp) <= 2) ||
newSubtitle === 'Video will play after ad')
return;
if (!overrideTimeout) {
songInfoTimeout = setTimeout(finishSongInfoUpdate, 500, newTitle, newSubtitle, newFinishTimestamp);
} else {
finishSongInfoUpdate(newTitle, newSubtitle, newFinishTimestamp);
}
} |
JavaScript | function finishSongInfoUpdate(newTitle, newSubtitle, newFinishTimestamp)
{
// Update the stored song information
title = newTitle;
subtitle = newSubtitle;
finishTimestamp = newFinishTimestamp;
// Extract the artist and album from the subtitle
let artist = 'Unknown';
let album = 'Unknown';
let subtitleParts = subtitle.split('•');
if (subtitleParts.length > 0) {
artist = subtitleParts[0].trim();
if (subtitleParts.length > 1)
album = subtitleParts[1].trim();
}
// Notify the background script of the new song information
port.postMessage({event: 'Update', title: title, artist: artist, album: album, finishTimestamp: finishTimestamp});
} | function finishSongInfoUpdate(newTitle, newSubtitle, newFinishTimestamp)
{
// Update the stored song information
title = newTitle;
subtitle = newSubtitle;
finishTimestamp = newFinishTimestamp;
// Extract the artist and album from the subtitle
let artist = 'Unknown';
let album = 'Unknown';
let subtitleParts = subtitle.split('•');
if (subtitleParts.length > 0) {
artist = subtitleParts[0].trim();
if (subtitleParts.length > 1)
album = subtitleParts[1].trim();
}
// Notify the background script of the new song information
port.postMessage({event: 'Update', title: title, artist: artist, album: album, finishTimestamp: finishTimestamp});
} |
JavaScript | function loadPage(pageId) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(pageId).innerHTML = xmlhttp.responseText;
if (pageId == 'config')
generateRangeControls();
if (pageId == 'status') {
loadPage("annunciator");
}
if (pageId == 'dashboard') {
generateGauges();
}
}
};
xmlhttp.open("GET", pageId + ".htm", true);
xmlhttp.send();
} | function loadPage(pageId) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(pageId).innerHTML = xmlhttp.responseText;
if (pageId == 'config')
generateRangeControls();
if (pageId == 'status') {
loadPage("annunciator");
}
if (pageId == 'dashboard') {
generateGauges();
}
}
};
xmlhttp.open("GET", pageId + ".htm", true);
xmlhttp.send();
} |
JavaScript | function loadData(pageId) {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var root = xmlhttp.responseXML.firstChild;
for (var i = 0; i < root.childNodes.length; i++) {
var node = root.childNodes[i]; // scan through the nodes
if (node.nodeType == 1 && node.childNodes[0]) {
var name = node.nodeName;
var value = node.childNodes[0].nodeValue;
refreshGaugeValue(name, value);
if (name.indexOf('bitfield') == -1) { // a normal div/span to update
var target = document.getElementById(name);
if (!target) { // id not found, try to find by name
var namedElements = document.getElementsByName(name);
if (namedElements && namedElements.length)
target = namedElements[0];
}
if (target) { // found an element, update according to its type
if (target.nodeName.toUpperCase() == 'DIV' || target.nodeName.toUpperCase() == 'SPAN')
target.innerHTML = value;
if (target.nodeName.toUpperCase() == 'INPUT') {
target.value = value;
var slider = document.getElementById(name + "Level");
if (slider)
slider.value = value;
}
if (target.nodeName.toUpperCase() == 'SELECT') {
selectItemByValue(target, value);
}
}
} else { // an annunciator field of a bitfield value
updateAnnunciatorFields(name, value);
// updateAnnunciatorFields(name, Math.round(Math.random() * 100000));
}
}
}
if (pageId == 'config') {
refreshThrottleVisualization();
}
}
};
xmlhttp.open("GET", pageId + ".xml", true);
xmlhttp.send();
} catch (err) {
//
}
} | function loadData(pageId) {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var root = xmlhttp.responseXML.firstChild;
for (var i = 0; i < root.childNodes.length; i++) {
var node = root.childNodes[i]; // scan through the nodes
if (node.nodeType == 1 && node.childNodes[0]) {
var name = node.nodeName;
var value = node.childNodes[0].nodeValue;
refreshGaugeValue(name, value);
if (name.indexOf('bitfield') == -1) { // a normal div/span to update
var target = document.getElementById(name);
if (!target) { // id not found, try to find by name
var namedElements = document.getElementsByName(name);
if (namedElements && namedElements.length)
target = namedElements[0];
}
if (target) { // found an element, update according to its type
if (target.nodeName.toUpperCase() == 'DIV' || target.nodeName.toUpperCase() == 'SPAN')
target.innerHTML = value;
if (target.nodeName.toUpperCase() == 'INPUT') {
target.value = value;
var slider = document.getElementById(name + "Level");
if (slider)
slider.value = value;
}
if (target.nodeName.toUpperCase() == 'SELECT') {
selectItemByValue(target, value);
}
}
} else { // an annunciator field of a bitfield value
updateAnnunciatorFields(name, value);
// updateAnnunciatorFields(name, Math.round(Math.random() * 100000));
}
}
}
if (pageId == 'config') {
refreshThrottleVisualization();
}
}
};
xmlhttp.open("GET", pageId + ".xml", true);
xmlhttp.send();
} catch (err) {
//
}
} |
JavaScript | function formatMajorTickNumber(num) {
var r, isDec = false;
// First, force the correct number of digits right of the decimal.
if(config.majorTicksFormat.dec === 0) {
r = Math.round(num).toString();
} else {
r = num.toFixed(config.majorTicksFormat.dec);
}
// Second, force the correct number of digits left of the decimal.
if(config.majorTicksFormat["int"] > 1) {
// Does this number have a decimal?
isDec = (r.indexOf('.') > -1);
// Is this number a negative number?
if(r.indexOf('-') > -1) {
return '-' + [
config.majorTicksFormat["int"] + config.majorTicksFormat.dec + 2 + (isDec ? 1 : 0) - r.length
].join('0') + r.replace('-', '');
} else {
return [
config.majorTicksFormat["int"] + config.majorTicksFormat.dec + 1 + (isDec ? 1 : 0) - r.length
].join('0') + r;
}
} else {
return r;
}
} | function formatMajorTickNumber(num) {
var r, isDec = false;
// First, force the correct number of digits right of the decimal.
if(config.majorTicksFormat.dec === 0) {
r = Math.round(num).toString();
} else {
r = num.toFixed(config.majorTicksFormat.dec);
}
// Second, force the correct number of digits left of the decimal.
if(config.majorTicksFormat["int"] > 1) {
// Does this number have a decimal?
isDec = (r.indexOf('.') > -1);
// Is this number a negative number?
if(r.indexOf('-') > -1) {
return '-' + [
config.majorTicksFormat["int"] + config.majorTicksFormat.dec + 2 + (isDec ? 1 : 0) - r.length
].join('0') + r.replace('-', '');
} else {
return [
config.majorTicksFormat["int"] + config.majorTicksFormat.dec + 1 + (isDec ? 1 : 0) - r.length
].join('0') + r;
}
} else {
return r;
}
} |
JavaScript | doRequest(requestType, method, path, params = {}, onSuccess, onFailure) {
return dispatch => {
this._updateRequest(dispatch, requestType);
const onFetched = response => {
if (response.ok) {
if (onSuccess) {
// onSuccess function when provided is reponsible for:
// 1. Updating any record(s)
// 2. Afterwards onSuccess() must update the request info by calling:
// this._updateRequest(dispatch, requestType, response, null, data
onSuccess(dispatch, response);
} else {
this._updateRequest(dispatch, requestType, response, null, data);
}
} else {
// Request completed but the server responded with an error status code (4XX/5XX)
if (onFailure) {
// onFailure if provided, is reponsible for calling:
// this._updateRequest(dispatch, requestType, response)
onFailure(dispatch, requestType, response);
} else {
this._updateRequest(dispatch, requestType, response);
}
}
};
const onRequestFailure = error => {
// Request failed (could not reach the server, so no response will be available)
if (onFailure) {
// onFailure if provided, is response for calling this._updateRequest(dispatch, requestType, null, error)
onFailure(dispatch, requestType, null, error);
} else {
this._updateRequest(dispatch, requestType, null, error);
}
};
return Requests.doRequest(method, path, params).then(onFetched, onRequestFailure);
};
} | doRequest(requestType, method, path, params = {}, onSuccess, onFailure) {
return dispatch => {
this._updateRequest(dispatch, requestType);
const onFetched = response => {
if (response.ok) {
if (onSuccess) {
// onSuccess function when provided is reponsible for:
// 1. Updating any record(s)
// 2. Afterwards onSuccess() must update the request info by calling:
// this._updateRequest(dispatch, requestType, response, null, data
onSuccess(dispatch, response);
} else {
this._updateRequest(dispatch, requestType, response, null, data);
}
} else {
// Request completed but the server responded with an error status code (4XX/5XX)
if (onFailure) {
// onFailure if provided, is reponsible for calling:
// this._updateRequest(dispatch, requestType, response)
onFailure(dispatch, requestType, response);
} else {
this._updateRequest(dispatch, requestType, response);
}
}
};
const onRequestFailure = error => {
// Request failed (could not reach the server, so no response will be available)
if (onFailure) {
// onFailure if provided, is response for calling this._updateRequest(dispatch, requestType, null, error)
onFailure(dispatch, requestType, null, error);
} else {
this._updateRequest(dispatch, requestType, null, error);
}
};
return Requests.doRequest(method, path, params).then(onFetched, onRequestFailure);
};
} |
JavaScript | function Routes() {
return (
<Switch>
<Route exact path="/"><Home /></Route>
<Route exact path="/signup"> <Signup /></Route>
<Route exact path="/landing"> <Landing /></Route>
<Route> <NotFound /></Route>
</Switch>
)
} | function Routes() {
return (
<Switch>
<Route exact path="/"><Home /></Route>
<Route exact path="/signup"> <Signup /></Route>
<Route exact path="/landing"> <Landing /></Route>
<Route> <NotFound /></Route>
</Switch>
)
} |
JavaScript | function saveHospitalTest(patientNumber) {
let cookie = new Cookies();
let encrypt = new JSEncrypt();
let certified = confirmHospitalCertificate()
console.log(certified);
if (!certified) {
console.error("Hospital not certified.")
} else {
//save results
let results = getHospitalTest(patientNumber);
console.log('hospital test results:', results)
cookie.set('hospitalTestResults', results)
//encrypt results to send back to hospital
encrypt.setPrivateKey(cookie.get('healthPrivate'));
let encryptedResults = encrypt.encrypt(results);
return encryptedResults
}
} | function saveHospitalTest(patientNumber) {
let cookie = new Cookies();
let encrypt = new JSEncrypt();
let certified = confirmHospitalCertificate()
console.log(certified);
if (!certified) {
console.error("Hospital not certified.")
} else {
//save results
let results = getHospitalTest(patientNumber);
console.log('hospital test results:', results)
cookie.set('hospitalTestResults', results)
//encrypt results to send back to hospital
encrypt.setPrivateKey(cookie.get('healthPrivate'));
let encryptedResults = encrypt.encrypt(results);
return encryptedResults
}
} |
JavaScript | function App() {
//const [isAuthenticating, setIsAuthenticating] = useState(true);
const [isAuthenticated, userHasAuthenticated] = useState(false);
return (
<div className="App">
<AppContext.Provider value={{ isAuthenticated, userHasAuthenticated }}>
<CookiesProvider>
<Routes />
</CookiesProvider>
</AppContext.Provider>
</div>
);
} | function App() {
//const [isAuthenticating, setIsAuthenticating] = useState(true);
const [isAuthenticated, userHasAuthenticated] = useState(false);
return (
<div className="App">
<AppContext.Provider value={{ isAuthenticated, userHasAuthenticated }}>
<CookiesProvider>
<Routes />
</CookiesProvider>
</AppContext.Provider>
</div>
);
} |
JavaScript | total(){
// entradas - saidas
return Transaction.incomes() + Transaction.expenses()
// pq mais -+ = -
} | total(){
// entradas - saidas
return Transaction.incomes() + Transaction.expenses()
// pq mais -+ = -
} |
JavaScript | function reset() {
targetNumber = getRandomNumber(18, 120); //targetNumber is equal to the solution
//grabbing html and setting text content.
$("#number-to-guess").text(targetNumber);//that's why we get an interger here
console.log(targetNumber);
//running the function, they don't actually link to crystals yet.
randomNumber1 = getRandomNumber(1,12);
randomNumber2 = getRandomNumber(1,12);
randomNumber3 = getRandomNumber(1,12);
randomNumber4 = getRandomNumber(1,12);
console.log(randomNumber1);
console.log(randomNumber2);
console.log(randomNumber3);
console.log(randomNumber4);
total = 0;
$("#finalTotal").text(total);
} | function reset() {
targetNumber = getRandomNumber(18, 120); //targetNumber is equal to the solution
//grabbing html and setting text content.
$("#number-to-guess").text(targetNumber);//that's why we get an interger here
console.log(targetNumber);
//running the function, they don't actually link to crystals yet.
randomNumber1 = getRandomNumber(1,12);
randomNumber2 = getRandomNumber(1,12);
randomNumber3 = getRandomNumber(1,12);
randomNumber4 = getRandomNumber(1,12);
console.log(randomNumber1);
console.log(randomNumber2);
console.log(randomNumber3);
console.log(randomNumber4);
total = 0;
$("#finalTotal").text(total);
} |
JavaScript | function zoom(root, p) {
if (document.documentElement.__transition__) return;
tip.hide();
if (root.name !== p.name) {
updateText(root);
setFocus(root);
setTable(getMeta(root));
} else {
updateText(p);
setFocus(p);
setTable(getMeta(p));
}
// Rescale outside angles to match the new layout.
var enterArc,
exitArc,
outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);
function insideArc(d) {
return p.key > d.key ? {
depth: d.depth - 1,
x: 0,
dx: 0
} : p.key < d.key ? {
depth: d.depth - 1,
x: 2 * Math.PI,
dx: 0
} : {
depth: 0,
x: 0,
dx: 2 * Math.PI
};
}
function outsideArc(d) {
return {
depth: d.depth + 1,
x: outsideAngle(d.x),
dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)
};
}
center.datum(root);
// When zooming in, arcs enter from the outside and exit to the inside.
// Entering outside arcs start from the old layout.
if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);
path = path.data(partition.nodes(root).slice(1), function(d) {
return d.key;
});
// When zooming out, arcs enter from the inside and exit to the outside.
// Exiting outside arcs transition to the new layout.
if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);
d3.transition().duration(750).each(function() {
path.exit().transition()
.style("fill-opacity", function(d) {
return d.depth === 1 + (root === p) ? 1 : 0;
})
.attrTween("d", function(d) {
return arcTween.call(this, exitArc(d));
})
.remove();
path.enter().append("path")
.style("fill-opacity", function(d) {
return d.depth === 2 - (root === p) ? 1 : 0;
})
.style("fill", function(d) {
return d.fill;
})
.on("click", zoomIn)
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.each(function(d) {
this._current = enterArc(d);
})
path.transition()
.style("fill-opacity", 1)
.attrTween("d", function(d) {
return arcTween.call(this, updateArc(d));
});
});
} | function zoom(root, p) {
if (document.documentElement.__transition__) return;
tip.hide();
if (root.name !== p.name) {
updateText(root);
setFocus(root);
setTable(getMeta(root));
} else {
updateText(p);
setFocus(p);
setTable(getMeta(p));
}
// Rescale outside angles to match the new layout.
var enterArc,
exitArc,
outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);
function insideArc(d) {
return p.key > d.key ? {
depth: d.depth - 1,
x: 0,
dx: 0
} : p.key < d.key ? {
depth: d.depth - 1,
x: 2 * Math.PI,
dx: 0
} : {
depth: 0,
x: 0,
dx: 2 * Math.PI
};
}
function outsideArc(d) {
return {
depth: d.depth + 1,
x: outsideAngle(d.x),
dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)
};
}
center.datum(root);
// When zooming in, arcs enter from the outside and exit to the inside.
// Entering outside arcs start from the old layout.
if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);
path = path.data(partition.nodes(root).slice(1), function(d) {
return d.key;
});
// When zooming out, arcs enter from the inside and exit to the outside.
// Exiting outside arcs transition to the new layout.
if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);
d3.transition().duration(750).each(function() {
path.exit().transition()
.style("fill-opacity", function(d) {
return d.depth === 1 + (root === p) ? 1 : 0;
})
.attrTween("d", function(d) {
return arcTween.call(this, exitArc(d));
})
.remove();
path.enter().append("path")
.style("fill-opacity", function(d) {
return d.depth === 2 - (root === p) ? 1 : 0;
})
.style("fill", function(d) {
return d.fill;
})
.on("click", zoomIn)
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.each(function(d) {
this._current = enterArc(d);
})
path.transition()
.style("fill-opacity", 1)
.attrTween("d", function(d) {
return arcTween.call(this, updateArc(d));
});
});
} |
JavaScript | function updateResult (value) {
var x = value
, y = currentElement.functionLaw (value)
;
// change x with y
if (currentElement.name === "termistor") {
var aux = x;
x = y;
y = aux;
}
if ($(".add-points input").prop("checked")) {
var seriesObj = expGraph.series[0];
seriesObj.data.push([x, y]);
seriesObj.data.sort (function (a, b) {
return a[0] - b[0];
});
expGraph.drawSeries({},0);
}
$(".vol input").val(x.toFixed(2));
$(".amp input").val(y.toFixed(2));
} | function updateResult (value) {
var x = value
, y = currentElement.functionLaw (value)
;
// change x with y
if (currentElement.name === "termistor") {
var aux = x;
x = y;
y = aux;
}
if ($(".add-points input").prop("checked")) {
var seriesObj = expGraph.series[0];
seriesObj.data.push([x, y]);
seriesObj.data.sort (function (a, b) {
return a[0] - b[0];
});
expGraph.drawSeries({},0);
}
$(".vol input").val(x.toFixed(2));
$(".amp input").val(y.toFixed(2));
} |
JavaScript | function ClockWidget(DOMcontainer, opt) {
"use strict";
// TODO: set default background colors
this.DOMcontainer = DOMcontainer;
this.canvas = null;
this.ctx = this.initContext();
// construction params
this.alpha = opt.alpha;
this.alphaVal = String(opt.value);
this.anim = opt.anim;
this.animcolors = opt.animcolors;
// customizable params
var textureUrl = 'assets/clocktext.png';
if(opt.hasOwnProperty('texture')) {
textureUrl = opt.texture;
}
this.clockTexture = this.load_texture(textureUrl, true);
this.modelUrl = "assets/clock7.json";
if(opt.hasOwnProperty('mesh')) {
this.modelUrl = opt.mesh;
}
this.defaultBackground = [0.25490196, 0.23529411, 0.23137254];
if(opt.hasOwnProperty('background')) {
this.defaultBackground[0] = opt.background[0] / 255;
this.defaultBackground[1] = opt.background[1] / 255;
this.defaultBackground[2] = opt.background[2] / 255;
}
this.colors = [
[150, 132, 125 ],
[65, 60, 59 ],
[65, 60, 59 ],
[218, 200, 193 ],
[150, 132, 125 ],
[90, 78, 78 ],
[255, 38, 38 ],
[48, 48, 48 ],
/*
[150, 132, 125], // minutes handle
[218, 200, 193], // seconds handle
[65, 60, 59 ], // central small circle
[73, 67, 66 ], // central clock
[79, 73, 71 ], // outer circle
[88, 81, 79 ], // inner circle
[255, 230, 213], // little handle
[48, 48, 48 ], // bigger handle
*/
];
if(opt.hasOwnProperty('clockColors')) {
this.colors = [
opt.clockColors.minHandle,
opt.clockColors.secHandle,
opt.clockColors.circHandle,
opt.clockColors.display,
opt.clockColors.outerEdge,
opt.clockColors.innerEdge,
opt.clockColors.sec2Handle,
opt.clockColors.hourHandle
];
}
// drawing variables
this.deltatime = 0;
this.then = 0;
this.step = Float32Array.BYTES_PER_ELEMENT;
this.projection = mat4.create();
// we'll feed an array of model matrices for each part of the clock
this.model = [];
this.view = mat4.create();
// mouse move and clock variables
this.br = 0;
this.cync = 0;
this.cxnc = 0;
this.lastXnc = 0;
this.lastYnc = 0;
this.now = 0;
this.clockGeometry;
this.MainProgram;
this.OffscreenProgram;
this.OffscreenFBO;
this.loadClockGeometry();
window.addEventListener('resize', this.onResize.bind(this));
} | function ClockWidget(DOMcontainer, opt) {
"use strict";
// TODO: set default background colors
this.DOMcontainer = DOMcontainer;
this.canvas = null;
this.ctx = this.initContext();
// construction params
this.alpha = opt.alpha;
this.alphaVal = String(opt.value);
this.anim = opt.anim;
this.animcolors = opt.animcolors;
// customizable params
var textureUrl = 'assets/clocktext.png';
if(opt.hasOwnProperty('texture')) {
textureUrl = opt.texture;
}
this.clockTexture = this.load_texture(textureUrl, true);
this.modelUrl = "assets/clock7.json";
if(opt.hasOwnProperty('mesh')) {
this.modelUrl = opt.mesh;
}
this.defaultBackground = [0.25490196, 0.23529411, 0.23137254];
if(opt.hasOwnProperty('background')) {
this.defaultBackground[0] = opt.background[0] / 255;
this.defaultBackground[1] = opt.background[1] / 255;
this.defaultBackground[2] = opt.background[2] / 255;
}
this.colors = [
[150, 132, 125 ],
[65, 60, 59 ],
[65, 60, 59 ],
[218, 200, 193 ],
[150, 132, 125 ],
[90, 78, 78 ],
[255, 38, 38 ],
[48, 48, 48 ],
/*
[150, 132, 125], // minutes handle
[218, 200, 193], // seconds handle
[65, 60, 59 ], // central small circle
[73, 67, 66 ], // central clock
[79, 73, 71 ], // outer circle
[88, 81, 79 ], // inner circle
[255, 230, 213], // little handle
[48, 48, 48 ], // bigger handle
*/
];
if(opt.hasOwnProperty('clockColors')) {
this.colors = [
opt.clockColors.minHandle,
opt.clockColors.secHandle,
opt.clockColors.circHandle,
opt.clockColors.display,
opt.clockColors.outerEdge,
opt.clockColors.innerEdge,
opt.clockColors.sec2Handle,
opt.clockColors.hourHandle
];
}
// drawing variables
this.deltatime = 0;
this.then = 0;
this.step = Float32Array.BYTES_PER_ELEMENT;
this.projection = mat4.create();
// we'll feed an array of model matrices for each part of the clock
this.model = [];
this.view = mat4.create();
// mouse move and clock variables
this.br = 0;
this.cync = 0;
this.cxnc = 0;
this.lastXnc = 0;
this.lastYnc = 0;
this.now = 0;
this.clockGeometry;
this.MainProgram;
this.OffscreenProgram;
this.OffscreenFBO;
this.loadClockGeometry();
window.addEventListener('resize', this.onResize.bind(this));
} |
JavaScript | function searchUsers(searchString) {
var url = "/peoplepicker/find/" + searchString + window.location.search;
$.post(url)
.done(function (result) {
clearResultList();
var users = JSON.parse(result.data);
$.each(users, function (key, val) {
console.log(users[key]);
addUserToResult(users[key]);
});
console.log("done");
})
.fail(function(error) {
console.log("failed");
});
} | function searchUsers(searchString) {
var url = "/peoplepicker/find/" + searchString + window.location.search;
$.post(url)
.done(function (result) {
clearResultList();
var users = JSON.parse(result.data);
$.each(users, function (key, val) {
console.log(users[key]);
addUserToResult(users[key]);
});
console.log("done");
})
.fail(function(error) {
console.log("failed");
});
} |
JavaScript | function OfficeAMSSubSite_OverrideLinkToAppUrl() {
var appRootsiteUrl = _spPageContextInfo.siteAbsoluteUrl.replace(_spPageContextInfo.siteServerRelativeUrl, "/");
var value;
ctx = new SP.ClientContext(appRootsiteUrl);
rootWeb = ctx.get_web();
list = rootWeb.get_lists().getByTitle('SogetiSPPConfig');
ctx.load(list);
ctx.executeQueryAsync(function () {
// Get list items
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<Where><Eq><FieldRef Name=\'Title\' /><Value Type=\'Text\'>SubSiteAppUrl</Value></Eq></Where><ViewFields><FieldRef Name=\'Title\' /><FieldRef Name=\'Value\' /></ViewFields>');
items = list.getItems(camlQuery);
ctx.load(items);
ctx.executeQueryAsync(function () {
// Get items
listItemEnumerator = items.getEnumerator();
while (listItemEnumerator.moveNext()) {
var item = listItemEnumerator.get_current();
if (item.get_item('Title') === "SubSiteAppUrl") {
value = item.get_item('Value');
}
}
//Update create new site link point to our custom page.
var icon = document.getElementById('ctl00_onetidHeadbnnr2').src;
var link = document.getElementById('createnewsite');
var url = value + "?SPHostUrl=" + encodeURIComponent(_spPageContextInfo.webAbsoluteUrl) + "&IsDlg=0&SPHostLogoUrl=" + encodeURIComponent(icon);
if (link != undefined) {
// Could be get from SPSite root web property bag - now hardcdoded for demo purposes
link.href = url;
}
else if (window.location.href.toLowerCase().indexOf("mngsubwebs.aspx") > -1) {
var link1 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite');
var link2 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite_LinkImage');
var link3 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite_LinkText');
if (link1 != undefined) {
link1.href = url;
link2.href = url;
link3.href = url;
}
}
}, Function.createDelegate(this, this.OfficeAMSSubSite_QueryFailed));
}, Function.createDelegate(this, OfficeAMSSubSite_QueryFailed));
} | function OfficeAMSSubSite_OverrideLinkToAppUrl() {
var appRootsiteUrl = _spPageContextInfo.siteAbsoluteUrl.replace(_spPageContextInfo.siteServerRelativeUrl, "/");
var value;
ctx = new SP.ClientContext(appRootsiteUrl);
rootWeb = ctx.get_web();
list = rootWeb.get_lists().getByTitle('SogetiSPPConfig');
ctx.load(list);
ctx.executeQueryAsync(function () {
// Get list items
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<Where><Eq><FieldRef Name=\'Title\' /><Value Type=\'Text\'>SubSiteAppUrl</Value></Eq></Where><ViewFields><FieldRef Name=\'Title\' /><FieldRef Name=\'Value\' /></ViewFields>');
items = list.getItems(camlQuery);
ctx.load(items);
ctx.executeQueryAsync(function () {
// Get items
listItemEnumerator = items.getEnumerator();
while (listItemEnumerator.moveNext()) {
var item = listItemEnumerator.get_current();
if (item.get_item('Title') === "SubSiteAppUrl") {
value = item.get_item('Value');
}
}
//Update create new site link point to our custom page.
var icon = document.getElementById('ctl00_onetidHeadbnnr2').src;
var link = document.getElementById('createnewsite');
var url = value + "?SPHostUrl=" + encodeURIComponent(_spPageContextInfo.webAbsoluteUrl) + "&IsDlg=0&SPHostLogoUrl=" + encodeURIComponent(icon);
if (link != undefined) {
// Could be get from SPSite root web property bag - now hardcdoded for demo purposes
link.href = url;
}
else if (window.location.href.toLowerCase().indexOf("mngsubwebs.aspx") > -1) {
var link1 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite');
var link2 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite_LinkImage');
var link3 = document.getElementById('ctl00_PlaceHolderMain_MngSubwebToolBar_RptControls_newsite_LinkText');
if (link1 != undefined) {
link1.href = url;
link2.href = url;
link3.href = url;
}
}
}, Function.createDelegate(this, this.OfficeAMSSubSite_QueryFailed));
}, Function.createDelegate(this, OfficeAMSSubSite_QueryFailed));
} |
JavaScript | function formattedAuthorList(authorList) {
authorList = authorList.map(function(d) { return formattedAuthor(d); });
switch (authorList.length) {
case 0:
case 1:
case 2:
return authorList.join(" & ");
case 3:
case 4:
return authorList.slice(0,-1).join(", ") + " & " + authorList[authorList.length - 1];
default:
return authorList.slice(0,3).join(", ") + ", <em>et al</em>";
}
} | function formattedAuthorList(authorList) {
authorList = authorList.map(function(d) { return formattedAuthor(d); });
switch (authorList.length) {
case 0:
case 1:
case 2:
return authorList.join(" & ");
case 3:
case 4:
return authorList.slice(0,-1).join(", ") + " & " + authorList[authorList.length - 1];
default:
return authorList.slice(0,3).join(", ") + ", <em>et al</em>";
}
} |
JavaScript | function formattedAuthor(author) {
var given = (typeof author.given !== "undefined") ? author.given : "";
var family = (typeof author.family !== "undefined") ? author.family : "";
var name = [given, family].join(" ");
var name = (typeof author["ORCID"] !== "undefined") ? '<a href="/contributors/' + author["ORCID"].substring(7) + '">' + name + '</a>' : name;
return name;
} | function formattedAuthor(author) {
var given = (typeof author.given !== "undefined") ? author.given : "";
var family = (typeof author.family !== "undefined") ? author.family : "";
var name = [given, family].join(" ");
var name = (typeof author["ORCID"] !== "undefined") ? '<a href="/contributors/' + author["ORCID"].substring(7) + '">' + name + '</a>' : name;
return name;
} |
JavaScript | function formattedCreatorList(creatorList) {
creatorList = creatorList.map(function(d) { return formattedCreator(d); });
switch (creatorList.length) {
case 0:
case 1:
case 2:
return creatorList.join(" & ");
case 3:
case 4:
return creatorList.slice(0,-1).join(", ") + " & " + creatorList[creatorList.length - 1];
default:
return creatorList.slice(0,3).join(", ") + ", <em>et al</em>";
}
} | function formattedCreatorList(creatorList) {
creatorList = creatorList.map(function(d) { return formattedCreator(d); });
switch (creatorList.length) {
case 0:
case 1:
case 2:
return creatorList.join(" & ");
case 3:
case 4:
return creatorList.slice(0,-1).join(", ") + " & " + creatorList[creatorList.length - 1];
default:
return creatorList.slice(0,3).join(", ") + ", <em>et al</em>";
}
} |
JavaScript | function _hash(str) {
let h = 0x6a09e667 ^ str.length;
for (let i = 0; i < str.length; i += 1) {
h = Math.imul(h ^ str.charCodeAt(i), 0xcc9e2d51);
h = (h << 13) | (h >>> 19);
h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
h = (h ^= h >>> 16) >>> 0;
}
return h;
} | function _hash(str) {
let h = 0x6a09e667 ^ str.length;
for (let i = 0; i < str.length; i += 1) {
h = Math.imul(h ^ str.charCodeAt(i), 0xcc9e2d51);
h = (h << 13) | (h >>> 19);
h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
h = (h ^= h >>> 16) >>> 0;
}
return h;
} |
JavaScript | function slice(key, numShards) {
// strigify key if possible to allow for multiple input data types
let keyClean = key;
if (typeof key === 'object') {
keyClean = JSON.stringify(key);
} else if (key !== undefined) {
keyClean = key.toString();
}
const shardIndex = _hash(keyClean) % numShards;
return shardIndex;
} | function slice(key, numShards) {
// strigify key if possible to allow for multiple input data types
let keyClean = key;
if (typeof key === 'object') {
keyClean = JSON.stringify(key);
} else if (key !== undefined) {
keyClean = key.toString();
}
const shardIndex = _hash(keyClean) % numShards;
return shardIndex;
} |
JavaScript | function collapse_all(min_lines) {
var elts = document.getElementsByTagName("div");
for (var i=0; i<elts.length; i++) {
var elt = elts[i];
var split = elt.id.indexOf("-");
if (split > 0)
if (elt.id.substring(split, elt.id.length) == "-expanded")
if (num_lines(elt.innerHTML) > min_lines)
collapse(elt.id.substring(0, split));
}
} | function collapse_all(min_lines) {
var elts = document.getElementsByTagName("div");
for (var i=0; i<elts.length; i++) {
var elt = elts[i];
var split = elt.id.indexOf("-");
if (split > 0)
if (elt.id.substring(split, elt.id.length) == "-expanded")
if (num_lines(elt.innerHTML) > min_lines)
collapse(elt.id.substring(0, split));
}
} |
JavaScript | function urlify(string, prefix, target) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
if(isempty(prefix)){prefix = "";}
else{prefix += " ";}
if(isempty(target)){target = "self_";}
if(target != "blank_" || target != "self_"){target = "self_";}
return string.replace(urlRegex, function(url) {
return prefix + '<a href="' + url + '" target="' + target + '">' + url + '</a>';
});
} | function urlify(string, prefix, target) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
if(isempty(prefix)){prefix = "";}
else{prefix += " ";}
if(isempty(target)){target = "self_";}
if(target != "blank_" || target != "self_"){target = "self_";}
return string.replace(urlRegex, function(url) {
return prefix + '<a href="' + url + '" target="' + target + '">' + url + '</a>';
});
} |
JavaScript | function Menu() {
this.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#cecece;border-radius:2em;border-style:solid;border-width:0.2em;border-color:black;border-radius:1.5em;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
this.new = function(id, title, innerhtml) {
if(id != "demo"){if(isempty(id) || isempty(innerhtml)){error("values for Menu.new() can't be left undefined, empty or null!");return;}}
if(id == "demo"){title="Demo Menu - Title";innerhtml="This is the content of the menu.<br>You can add <b>HTML</b> <i>tags</i> <u>of</u> <sup>all</sup> <sub>sorts</sub> here,<br>like <button>Buttons</button> or <input type='text' placeholder='Inputs'> or even iframes:<br><iframe src='https://www.example.com'></iframe><br><br>";}
var menu = document.createElement("div");
menu.id="jsl_menu" + id;
menu.style=Menu.defaultstyling + "top:120vh;";
menu.innerHTML='<div class="menu_title" style="font-size:1.5em;text-align:center;padding:0.2em;">' + title + '</div><div style="height:1em;"></div><div class="menu_content" style="font-size:1em;text-align:center;padding:0.2em;">' + innerhtml + '</div><img style="z-index:0;position:absolute;top:0px;right:0px;width:2em;height:2em;cursor:pointer;border-radius:20vw;" title="Close" src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/raw_red.png" onclick="Menu.close(' + "'" + id + "'" + ');"></img><img style="z-index:1;position:absolute;top:0px;right:0px;width:2em;height:2em;cursor:pointer;border-radius:20vw;" title="Close" src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/whitex.png" onclick="Menu.close(' + "'" + id + "'" + ');"></img>';
document.body.appendChild(menu);
}
this.open = function(id) {
if(isempty(gebid("jsl_menu" + id))){error("you need to create the menu before you try to open it or you entered the wrong id");return;}
stylebid("jsl_menu" + id, Menu.defaultstyling + "top:15vh;left:17.5vw;");
document.addEventListener("keydown", function(e){if(e.keyCode == 27){Menu.close(id);}});
}
this.close = function(id) {
if(isempty(gebid("jsl_menu" + id))){error("you need to create the menu before you try to close it or you entered the wrong id");return;}
stylebid("jsl_menu" + id, Menu.defaultstyling + "top:120vh;");
}
this.theme = function(theme) {
if(theme == "light"){
Menu.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#cecece;border-radius:2em;border-style:solid;border-width:0.2em;border-color:black;border-radius:1.5em;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
}
else if(theme == "dark") {
Menu.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#353535;border-radius:2em;border-style:solid;border-width:0.2em;border-color:white;border-radius:1.5em;color:white;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
}
}
this.demonstrate = function() {
Menu.new('demo');
Menu.open('demo');
}
} | function Menu() {
this.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#cecece;border-radius:2em;border-style:solid;border-width:0.2em;border-color:black;border-radius:1.5em;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
this.new = function(id, title, innerhtml) {
if(id != "demo"){if(isempty(id) || isempty(innerhtml)){error("values for Menu.new() can't be left undefined, empty or null!");return;}}
if(id == "demo"){title="Demo Menu - Title";innerhtml="This is the content of the menu.<br>You can add <b>HTML</b> <i>tags</i> <u>of</u> <sup>all</sup> <sub>sorts</sub> here,<br>like <button>Buttons</button> or <input type='text' placeholder='Inputs'> or even iframes:<br><iframe src='https://www.example.com'></iframe><br><br>";}
var menu = document.createElement("div");
menu.id="jsl_menu" + id;
menu.style=Menu.defaultstyling + "top:120vh;";
menu.innerHTML='<div class="menu_title" style="font-size:1.5em;text-align:center;padding:0.2em;">' + title + '</div><div style="height:1em;"></div><div class="menu_content" style="font-size:1em;text-align:center;padding:0.2em;">' + innerhtml + '</div><img style="z-index:0;position:absolute;top:0px;right:0px;width:2em;height:2em;cursor:pointer;border-radius:20vw;" title="Close" src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/raw_red.png" onclick="Menu.close(' + "'" + id + "'" + ');"></img><img style="z-index:1;position:absolute;top:0px;right:0px;width:2em;height:2em;cursor:pointer;border-radius:20vw;" title="Close" src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/whitex.png" onclick="Menu.close(' + "'" + id + "'" + ');"></img>';
document.body.appendChild(menu);
}
this.open = function(id) {
if(isempty(gebid("jsl_menu" + id))){error("you need to create the menu before you try to open it or you entered the wrong id");return;}
stylebid("jsl_menu" + id, Menu.defaultstyling + "top:15vh;left:17.5vw;");
document.addEventListener("keydown", function(e){if(e.keyCode == 27){Menu.close(id);}});
}
this.close = function(id) {
if(isempty(gebid("jsl_menu" + id))){error("you need to create the menu before you try to close it or you entered the wrong id");return;}
stylebid("jsl_menu" + id, Menu.defaultstyling + "top:120vh;");
}
this.theme = function(theme) {
if(theme == "light"){
Menu.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#cecece;border-radius:2em;border-style:solid;border-width:0.2em;border-color:black;border-radius:1.5em;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
}
else if(theme == "dark") {
Menu.defaultstyling = "position:fixed;width:65vw;height:70vh;z-index:5000;background-color:#353535;border-radius:2em;border-style:solid;border-width:0.2em;border-color:white;border-radius:1.5em;color:white;filter:drop-shadow(0.2em 0.2em 0.2em rgba(0,0,0,0.6));";
}
}
this.demonstrate = function() {
Menu.new('demo');
Menu.open('demo');
}
} |
JavaScript | function Audio(){
this.new = function(id, src) {
if(id != "demo"){if(isempty(id) || isempty(src)){error("values for Audio.new() can't be left undefined, empty or null!");return;}}
if(id == "demo"){src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/fallingtree0.mp3";}
var audio = document.createElement("audio");
audio.id="jsl_audio" + id;
audio.innerHTML='<source src="' + src + '">';
audio.style="display:none;";
document.body.appendChild(audio);
}
this.play = function(id) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to play it or you entered the wrong id");return;}
gebid("jsl_audio" + id).play();
}
this.pause = function(id) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to pause it or you entered the wrong id");return;}
gebid("jsl_audio" + id).pause();
}
this.volume = function(id, volume) { // volume must be a float (between 0 and 1.0)
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to change the volume or you entered the wrong id");return;}
gebid("jsl_audio" + id).volume=volume;
}
this.loop = function(id, looping) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to activate/deactivate the looping attribute or you entered the wrong id");return;}
if(looping !== false && looping !== true){error("you need to enter either true or false in the Audio.loop() function");return;}
if(looping) gebid("jsl_audio" + id).setAttribute("loop", "true");
else gebid("jsl_audio" + id).removeAttribute("loop");
}
this.demonstrate = function() {
Audio.new('demo');
alert("This demo will create the audio, play the audio for 2 seconds, pause it for 2 seconds, play it again for 2 seconds, then reduce the volume to 0.1 for 4 seconds and then increase the volume to 1 for the rest of the audio");
Audio.play('demo');
setTimeout(function(){Audio.pause('demo')}, 2000);
setTimeout(function(){Audio.play('demo')}, 4000);
setTimeout(function(){Audio.volume('demo', 0.1)}, 6000);
setTimeout(function(){Audio.volume('demo', 1)}, 10000);
}
} | function Audio(){
this.new = function(id, src) {
if(id != "demo"){if(isempty(id) || isempty(src)){error("values for Audio.new() can't be left undefined, empty or null!");return;}}
if(id == "demo"){src="https://raw.githubusercontent.com/Sv443/TextAdventureGame/master/fallingtree0.mp3";}
var audio = document.createElement("audio");
audio.id="jsl_audio" + id;
audio.innerHTML='<source src="' + src + '">';
audio.style="display:none;";
document.body.appendChild(audio);
}
this.play = function(id) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to play it or you entered the wrong id");return;}
gebid("jsl_audio" + id).play();
}
this.pause = function(id) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to pause it or you entered the wrong id");return;}
gebid("jsl_audio" + id).pause();
}
this.volume = function(id, volume) { // volume must be a float (between 0 and 1.0)
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to change the volume or you entered the wrong id");return;}
gebid("jsl_audio" + id).volume=volume;
}
this.loop = function(id, looping) {
if(isempty(gebid("jsl_audio" + id))){error("you need to create the audio before you try to activate/deactivate the looping attribute or you entered the wrong id");return;}
if(looping !== false && looping !== true){error("you need to enter either true or false in the Audio.loop() function");return;}
if(looping) gebid("jsl_audio" + id).setAttribute("loop", "true");
else gebid("jsl_audio" + id).removeAttribute("loop");
}
this.demonstrate = function() {
Audio.new('demo');
alert("This demo will create the audio, play the audio for 2 seconds, pause it for 2 seconds, play it again for 2 seconds, then reduce the volume to 0.1 for 4 seconds and then increase the volume to 1 for the rest of the audio");
Audio.play('demo');
setTimeout(function(){Audio.pause('demo')}, 2000);
setTimeout(function(){Audio.play('demo')}, 4000);
setTimeout(function(){Audio.volume('demo', 0.1)}, 6000);
setTimeout(function(){Audio.volume('demo', 1)}, 10000);
}
} |
JavaScript | function copy(text) {
var copyelem = document.createElement("textarea");
copyelem.id="jsl_copyta";
copyelem.innerHTML=text;
document.body.appendChild(copyelem);
gebid("jsl_copyta").select();
document.execCommand("copy");
clearih("jsl_copyta");
clearoh("jsl_copyta");
} | function copy(text) {
var copyelem = document.createElement("textarea");
copyelem.id="jsl_copyta";
copyelem.innerHTML=text;
document.body.appendChild(copyelem);
gebid("jsl_copyta").select();
document.execCommand("copy");
clearih("jsl_copyta");
clearoh("jsl_copyta");
} |
JavaScript | function error(cause, contact) {
var r = Math.floor(Math.random() * errortitle.length);
if(isempty(contact)) contact = "";
else contact = "(" + contact + ") ";
alert(errortitle[r] + "The following error occured:\n\n" + cause + "\n\nPlease contact me " + contact + "with the above information and what you did before the error occured so I can fix it. Thanks!");
} | function error(cause, contact) {
var r = Math.floor(Math.random() * errortitle.length);
if(isempty(contact)) contact = "";
else contact = "(" + contact + ") ";
alert(errortitle[r] + "The following error occured:\n\n" + cause + "\n\nPlease contact me " + contact + "with the above information and what you did before the error occured so I can fix it. Thanks!");
} |
JavaScript | function changeSymbolNameForComparison(comparison) {
if (comparison == ORDERED_ASCENDING) {
return "arrow.up";
} else if (comparison == ORDERED_DESCENDING) {
return "arrow.down";
} else {
return null;
}
} | function changeSymbolNameForComparison(comparison) {
if (comparison == ORDERED_ASCENDING) {
return "arrow.up";
} else if (comparison == ORDERED_DESCENDING) {
return "arrow.down";
} else {
return null;
}
} |
JavaScript | function createSymbol(symbolName) {
const symbol = SFSymbol.named(symbolName);
symbol.applyFont(Font.systemFont(15));
return symbol;
} | function createSymbol(symbolName) {
const symbol = SFSymbol.named(symbolName);
symbol.applyFont(Font.systemFont(15));
return symbol;
} |
JavaScript | amountToDisplayStr(amount) {
if (!amount) {
if (this.state.decimal) {
return "0.";
} else if (this.state.decimalDigits) {
return (0).toFixed(this.state.decimalDigits);
}
return amount;
}
const { unitDivisor } = this.props;
let scaled = amount / unitDivisor;
if (this.state.decimal) {
return scaled.toFixed(0) + ".";
}
return scaled.toFixed(this.state.decimalDigits);
} | amountToDisplayStr(amount) {
if (!amount) {
if (this.state.decimal) {
return "0.";
} else if (this.state.decimalDigits) {
return (0).toFixed(this.state.decimalDigits);
}
return amount;
}
const { unitDivisor } = this.props;
let scaled = amount / unitDivisor;
if (this.state.decimal) {
return scaled.toFixed(0) + ".";
}
return scaled.toFixed(this.state.decimalDigits);
} |
JavaScript | push(task, forceQueuing) {
if (this.ready || forceQueuing) {
this.queue.push(task)
} else {
this.buffer.push(task)
}
} | push(task, forceQueuing) {
if (this.ready || forceQueuing) {
this.queue.push(task)
} else {
this.buffer.push(task)
}
} |
JavaScript | processBuffer () {
let i
this.ready = true
for (i = 0; i < this.buffer.length; i += 1) { this.queue.push(this.buffer[i]) }
this.buffer = []
} | processBuffer () {
let i
this.ready = true
for (i = 0; i < this.buffer.length; i += 1) { this.queue.push(this.buffer[i]) }
this.buffer = []
} |
JavaScript | function testPermutationsOnHTML(htmlText) {
// Load the stylesheet text via xml request
var permutations = [];
for (var i = 0; i < 10; ++i) {
var request = new XMLHttpRequest();
request.onload = function () {
permutations.push(this.responseText);
};
// Send a synchronous xml request
request.open('get', '../../csstests/' + i + '/css/ui-dark.css', false);
request.send();
}
// Test all permutations
var allResults = [];
for (var i = 1; i < permutations.length; ++i) {
var results = CSSDiff.diff(htmlText, permutations[0], permutations[i]);
allResults = allResults.concat(results);
console.log('tested permutation ', i);
}
return allResults;
} | function testPermutationsOnHTML(htmlText) {
// Load the stylesheet text via xml request
var permutations = [];
for (var i = 0; i < 10; ++i) {
var request = new XMLHttpRequest();
request.onload = function () {
permutations.push(this.responseText);
};
// Send a synchronous xml request
request.open('get', '../../csstests/' + i + '/css/ui-dark.css', false);
request.send();
}
// Test all permutations
var allResults = [];
for (var i = 1; i < permutations.length; ++i) {
var results = CSSDiff.diff(htmlText, permutations[0], permutations[i]);
allResults = allResults.concat(results);
console.log('tested permutation ', i);
}
return allResults;
} |
JavaScript | function validateResults(results) {
// If there are 0 differences between the CSS files, CSSDiff.diff will return
// an empty array. Unfortunately qunit can't handle no assertions being made during a test,
// so we have to assert *something* in that case to prevent an error.
if (results.length === 0) {
LiveUnit.Assert.areEqual(1, 1, 'Dummy assertion');
}
for (var i = 0; i < results.length; ++i) {
var result = results[i];
if (ignoredProperties.indexOf(result.property) >= 0) {
continue;
}
var message = '\n' + result.element.tagName.toLowerCase();
if (result.element.className) {
message += '\n.' + result.element.className.split(' ').join('\n.');
}
if (result.pseudo !== 'none') {
message += ':' + result.pseudo;
}
message += '\n' + result.property + ' is order dependent!\n';
LiveUnit.Assert.areEqual(result.expected, result.actual, message);
}
} | function validateResults(results) {
// If there are 0 differences between the CSS files, CSSDiff.diff will return
// an empty array. Unfortunately qunit can't handle no assertions being made during a test,
// so we have to assert *something* in that case to prevent an error.
if (results.length === 0) {
LiveUnit.Assert.areEqual(1, 1, 'Dummy assertion');
}
for (var i = 0; i < results.length; ++i) {
var result = results[i];
if (ignoredProperties.indexOf(result.property) >= 0) {
continue;
}
var message = '\n' + result.element.tagName.toLowerCase();
if (result.element.className) {
message += '\n.' + result.element.className.split(' ').join('\n.');
}
if (result.pseudo !== 'none') {
message += ':' + result.pseudo;
}
message += '\n' + result.property + ' is order dependent!\n';
LiveUnit.Assert.areEqual(result.expected, result.actual, message);
}
} |
JavaScript | function safeDispose(mediaPlayer) {
WinJS.Utilities.Scheduler.schedule(function () {
try {
mediaPlayer.dispose();
} catch (ex) { }
}, WinJS.Utilities.Scheduler.Priority.normal, this);
} | function safeDispose(mediaPlayer) {
WinJS.Utilities.Scheduler.schedule(function () {
try {
mediaPlayer.dispose();
} catch (ex) { }
}, WinJS.Utilities.Scheduler.Priority.normal, this);
} |
JavaScript | function VirtualizeContentsView_updateAriaMarkers(listViewIsEmpty, firstIndexDisplayed, lastIndexDisplayed) {
var that = this;
if (this._listView._isZombie()) {
return;
}
function getFirstVisibleItem() {
return that.items.itemAt(firstIndexDisplayed);
}
// At a certain index, the VDS may return null for all items at that index and
// higher. When this is the case, the end marker should point to the last
// non-null item in the visible range.
function getLastVisibleItem() {
for (var i = lastIndexDisplayed; i >= firstIndexDisplayed; i--) {
if (that.items.itemAt(i)) {
return that.items.itemAt(i);
}
}
return null;
}
this._listView._createAriaMarkers();
var startMarker = this._listView._ariaStartMarker,
endMarker = this._listView._ariaEndMarker,
firstVisibleItem,
lastVisibleItem;
if (firstIndexDisplayed !== -1 && lastIndexDisplayed !== -1 && firstIndexDisplayed <= lastIndexDisplayed) {
firstVisibleItem = getFirstVisibleItem();
lastVisibleItem = getLastVisibleItem();
}
if (listViewIsEmpty || !firstVisibleItem || !lastVisibleItem) {
setFlow(startMarker, endMarker);
this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1);
} else {
_ElementUtilities._ensureId(firstVisibleItem);
_ElementUtilities._ensureId(lastVisibleItem);
// Set startMarker's flowto
if (this._listView._groupsEnabled()) {
var groups = this._listView._groups,
firstVisibleGroup = groups.group(groups.groupFromItem(firstIndexDisplayed));
if (firstVisibleGroup.header) {
_ElementUtilities._ensureId(firstVisibleGroup.header);
if (firstIndexDisplayed === firstVisibleGroup.startIndex) {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleGroup.header.id);
} else {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id);
}
}
} else {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id);
}
// Set endMarker's flowfrom
_ElementUtilities._setAttribute(endMarker, "x-ms-aria-flowfrom", lastVisibleItem.id);
}
} | function VirtualizeContentsView_updateAriaMarkers(listViewIsEmpty, firstIndexDisplayed, lastIndexDisplayed) {
var that = this;
if (this._listView._isZombie()) {
return;
}
function getFirstVisibleItem() {
return that.items.itemAt(firstIndexDisplayed);
}
// At a certain index, the VDS may return null for all items at that index and
// higher. When this is the case, the end marker should point to the last
// non-null item in the visible range.
function getLastVisibleItem() {
for (var i = lastIndexDisplayed; i >= firstIndexDisplayed; i--) {
if (that.items.itemAt(i)) {
return that.items.itemAt(i);
}
}
return null;
}
this._listView._createAriaMarkers();
var startMarker = this._listView._ariaStartMarker,
endMarker = this._listView._ariaEndMarker,
firstVisibleItem,
lastVisibleItem;
if (firstIndexDisplayed !== -1 && lastIndexDisplayed !== -1 && firstIndexDisplayed <= lastIndexDisplayed) {
firstVisibleItem = getFirstVisibleItem();
lastVisibleItem = getLastVisibleItem();
}
if (listViewIsEmpty || !firstVisibleItem || !lastVisibleItem) {
setFlow(startMarker, endMarker);
this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1);
} else {
_ElementUtilities._ensureId(firstVisibleItem);
_ElementUtilities._ensureId(lastVisibleItem);
// Set startMarker's flowto
if (this._listView._groupsEnabled()) {
var groups = this._listView._groups,
firstVisibleGroup = groups.group(groups.groupFromItem(firstIndexDisplayed));
if (firstVisibleGroup.header) {
_ElementUtilities._ensureId(firstVisibleGroup.header);
if (firstIndexDisplayed === firstVisibleGroup.startIndex) {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleGroup.header.id);
} else {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id);
}
}
} else {
_ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id);
}
// Set endMarker's flowfrom
_ElementUtilities._setAttribute(endMarker, "x-ms-aria-flowfrom", lastVisibleItem.id);
}
} |
JavaScript | function VirtualizeContentsView_updateAriaForAnnouncement(item, count) {
if (item === this._listView.header || item === this._listView.footer) {
return;
}
var index = -1;
var type = _UI.ObjectType.item;
if (_ElementUtilities.hasClass(item, _Constants._headerClass)) {
index = this._listView._groups.index(item);
type = _UI.ObjectType.groupHeader;
_ElementUtilities._setAttribute(item, "role", this._listView._headerRole);
_ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex);
} else {
index = this.items.index(item);
_ElementUtilities._setAttribute(item, "aria-setsize", count);
_ElementUtilities._setAttribute(item, "aria-posinset", index + 1);
_ElementUtilities._setAttribute(item, "role", this._listView._itemRole);
_ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex);
}
if (type === _UI.ObjectType.groupHeader) {
this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1, index, index);
} else {
this._listView._fireAccessibilityAnnotationCompleteEvent(index, index, -1, -1);
}
} | function VirtualizeContentsView_updateAriaForAnnouncement(item, count) {
if (item === this._listView.header || item === this._listView.footer) {
return;
}
var index = -1;
var type = _UI.ObjectType.item;
if (_ElementUtilities.hasClass(item, _Constants._headerClass)) {
index = this._listView._groups.index(item);
type = _UI.ObjectType.groupHeader;
_ElementUtilities._setAttribute(item, "role", this._listView._headerRole);
_ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex);
} else {
index = this.items.index(item);
_ElementUtilities._setAttribute(item, "aria-setsize", count);
_ElementUtilities._setAttribute(item, "aria-posinset", index + 1);
_ElementUtilities._setAttribute(item, "role", this._listView._itemRole);
_ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex);
}
if (type === _UI.ObjectType.groupHeader) {
this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1, index, index);
} else {
this._listView._fireAccessibilityAnnotationCompleteEvent(index, index, -1, -1);
}
} |
JavaScript | function VirtualizeContentsView_createChunk(groups, count, chunkSize) {
var that = this;
this._listView._writeProfilerMark("createChunk,StartTM");
function addToGroup(itemsContainer, groupSize) {
var children = itemsContainer.element.children,
oldSize = children.length,
toAdd = Math.min(groupSize - itemsContainer.items.length, chunkSize);
_SafeHtml.insertAdjacentHTMLUnsafe(itemsContainer.element, "beforeend", _Helpers._repeat("<div class='win-container win-backdrop'></div>", toAdd));
for (var i = 0; i < toAdd; i++) {
var container = children[oldSize + i];
itemsContainer.items.push(container);
that.containers.push(container);
}
}
function newGroup(group) {
var node = {
header: that._listView._groupDataSource ? that._createHeaderContainer() : null,
itemsContainer: {
element: that._createItemsContainer(),
items: []
}
};
that.tree.push(node);
that.keyToGroupIndex[group.key] = that.tree.length - 1;
addToGroup(node.itemsContainer, group.size);
}
if (this.tree.length && this.tree.length <= groups.length) {
var last = this.tree[this.tree.length - 1],
finalSize = groups[this.tree.length - 1].size;
// check if the last group in the tree already has all items. If not add items to this group
if (last.itemsContainer.items.length < finalSize) {
addToGroup(last.itemsContainer, finalSize);
this._listView._writeProfilerMark("createChunk,StopTM");
return;
}
}
if (this.tree.length < groups.length) {
newGroup(groups[this.tree.length]);
}
this._listView._writeProfilerMark("createChunk,StopTM");
} | function VirtualizeContentsView_createChunk(groups, count, chunkSize) {
var that = this;
this._listView._writeProfilerMark("createChunk,StartTM");
function addToGroup(itemsContainer, groupSize) {
var children = itemsContainer.element.children,
oldSize = children.length,
toAdd = Math.min(groupSize - itemsContainer.items.length, chunkSize);
_SafeHtml.insertAdjacentHTMLUnsafe(itemsContainer.element, "beforeend", _Helpers._repeat("<div class='win-container win-backdrop'></div>", toAdd));
for (var i = 0; i < toAdd; i++) {
var container = children[oldSize + i];
itemsContainer.items.push(container);
that.containers.push(container);
}
}
function newGroup(group) {
var node = {
header: that._listView._groupDataSource ? that._createHeaderContainer() : null,
itemsContainer: {
element: that._createItemsContainer(),
items: []
}
};
that.tree.push(node);
that.keyToGroupIndex[group.key] = that.tree.length - 1;
addToGroup(node.itemsContainer, group.size);
}
if (this.tree.length && this.tree.length <= groups.length) {
var last = this.tree[this.tree.length - 1],
finalSize = groups[this.tree.length - 1].size;
// check if the last group in the tree already has all items. If not add items to this group
if (last.itemsContainer.items.length < finalSize) {
addToGroup(last.itemsContainer, finalSize);
this._listView._writeProfilerMark("createChunk,StopTM");
return;
}
}
if (this.tree.length < groups.length) {
newGroup(groups[this.tree.length]);
}
this._listView._writeProfilerMark("createChunk,StopTM");
} |
JavaScript | function VirtualizeContentsView_createChunkWithBlocks(groups, count, blockSize, chunkSize) {
var that = this;
this._listView._writeProfilerMark("createChunk,StartTM");
function addToGroup(itemsContainer, toAdd) {
var indexOfNextGroupItem;
var lastExistingBlock = itemsContainer.itemsBlocks.length ? itemsContainer.itemsBlocks[itemsContainer.itemsBlocks.length - 1] : null;
toAdd = Math.min(toAdd, chunkSize);
// 1) Add missing containers to the latest itemsblock if it was only partially filled during the previous pass.
if (lastExistingBlock && lastExistingBlock.items.length < blockSize) {
var emptySpotsToFill = Math.min(toAdd, blockSize - lastExistingBlock.items.length),
sizeOfOldLastBlock = lastExistingBlock.items.length,
indexOfNextGroupItem = (itemsContainer.itemsBlocks.length - 1) * blockSize + sizeOfOldLastBlock;
var containersMarkup = _Helpers._stripedContainers(emptySpotsToFill, indexOfNextGroupItem);
_SafeHtml.insertAdjacentHTMLUnsafe(lastExistingBlock.element, "beforeend", containersMarkup);
children = lastExistingBlock.element.children;
for (var j = 0; j < emptySpotsToFill; j++) {
var child = children[sizeOfOldLastBlock + j];
lastExistingBlock.items.push(child);
that.containers.push(child);
}
toAdd -= emptySpotsToFill;
}
indexOfNextGroupItem = itemsContainer.itemsBlocks.length * blockSize;
// 2) Generate as many full itemblocks of containers as we can.
var newBlocksCount = Math.floor(toAdd / blockSize),
markup = "",
firstBlockFirstItemIndex = indexOfNextGroupItem,
secondBlockFirstItemIndex = indexOfNextGroupItem + blockSize;
if (newBlocksCount > 0) {
var pairOfItemBlocks = [
// Use pairs to ensure that the container striping pattern is maintained regardless if blockSize is even or odd.
"<div class='win-itemsblock'>" + _Helpers._stripedContainers(blockSize, firstBlockFirstItemIndex) + "</div>",
"<div class='win-itemsblock'>" + _Helpers._stripedContainers(blockSize, secondBlockFirstItemIndex) + "</div>"
];
markup = _Helpers._repeat(pairOfItemBlocks, newBlocksCount);
indexOfNextGroupItem += (newBlocksCount * blockSize);
}
// 3) Generate and partially fill, one last itemblock if there are any remaining containers to add.
var sizeOfNewLastBlock = toAdd % blockSize;
if (sizeOfNewLastBlock > 0) {
markup += "<div class='win-itemsblock'>" + _Helpers._stripedContainers(sizeOfNewLastBlock, indexOfNextGroupItem) + "</div>";
indexOfNextGroupItem += sizeOfNewLastBlock;
newBlocksCount++;
}
var blocksTemp = _Global.document.createElement("div");
_SafeHtml.setInnerHTMLUnsafe(blocksTemp, markup);
var children = blocksTemp.children;
for (var i = 0; i < newBlocksCount; i++) {
var block = children[i],
blockNode = {
element: block,
items: _Helpers._nodeListToArray(block.children)
};
itemsContainer.itemsBlocks.push(blockNode);
for (var n = 0; n < blockNode.items.length; n++) {
that.containers.push(blockNode.items[n]);
}
}
}
function newGroup(group) {
var node = {
header: that._listView._groupDataSource ? that._createHeaderContainer() : null,
itemsContainer: {
element: that._createItemsContainer(),
itemsBlocks: []
}
};
that.tree.push(node);
that.keyToGroupIndex[group.key] = that.tree.length - 1;
addToGroup(node.itemsContainer, group.size);
}
if (this.tree.length && this.tree.length <= groups.length) {
var lastContainer = this.tree[this.tree.length - 1].itemsContainer,
finalSize = groups[this.tree.length - 1].size,
currentSize = 0;
if (lastContainer.itemsBlocks.length) {
currentSize = (lastContainer.itemsBlocks.length - 1) * blockSize + lastContainer.itemsBlocks[lastContainer.itemsBlocks.length - 1].items.length;
}
if (currentSize < finalSize) {
addToGroup(lastContainer, finalSize - currentSize);
this._listView._writeProfilerMark("createChunk,StopTM");
return;
}
}
if (this.tree.length < groups.length) {
newGroup(groups[this.tree.length]);
}
this._listView._writeProfilerMark("createChunk,StopTM");
} | function VirtualizeContentsView_createChunkWithBlocks(groups, count, blockSize, chunkSize) {
var that = this;
this._listView._writeProfilerMark("createChunk,StartTM");
function addToGroup(itemsContainer, toAdd) {
var indexOfNextGroupItem;
var lastExistingBlock = itemsContainer.itemsBlocks.length ? itemsContainer.itemsBlocks[itemsContainer.itemsBlocks.length - 1] : null;
toAdd = Math.min(toAdd, chunkSize);
// 1) Add missing containers to the latest itemsblock if it was only partially filled during the previous pass.
if (lastExistingBlock && lastExistingBlock.items.length < blockSize) {
var emptySpotsToFill = Math.min(toAdd, blockSize - lastExistingBlock.items.length),
sizeOfOldLastBlock = lastExistingBlock.items.length,
indexOfNextGroupItem = (itemsContainer.itemsBlocks.length - 1) * blockSize + sizeOfOldLastBlock;
var containersMarkup = _Helpers._stripedContainers(emptySpotsToFill, indexOfNextGroupItem);
_SafeHtml.insertAdjacentHTMLUnsafe(lastExistingBlock.element, "beforeend", containersMarkup);
children = lastExistingBlock.element.children;
for (var j = 0; j < emptySpotsToFill; j++) {
var child = children[sizeOfOldLastBlock + j];
lastExistingBlock.items.push(child);
that.containers.push(child);
}
toAdd -= emptySpotsToFill;
}
indexOfNextGroupItem = itemsContainer.itemsBlocks.length * blockSize;
// 2) Generate as many full itemblocks of containers as we can.
var newBlocksCount = Math.floor(toAdd / blockSize),
markup = "",
firstBlockFirstItemIndex = indexOfNextGroupItem,
secondBlockFirstItemIndex = indexOfNextGroupItem + blockSize;
if (newBlocksCount > 0) {
var pairOfItemBlocks = [
// Use pairs to ensure that the container striping pattern is maintained regardless if blockSize is even or odd.
"<div class='win-itemsblock'>" + _Helpers._stripedContainers(blockSize, firstBlockFirstItemIndex) + "</div>",
"<div class='win-itemsblock'>" + _Helpers._stripedContainers(blockSize, secondBlockFirstItemIndex) + "</div>"
];
markup = _Helpers._repeat(pairOfItemBlocks, newBlocksCount);
indexOfNextGroupItem += (newBlocksCount * blockSize);
}
// 3) Generate and partially fill, one last itemblock if there are any remaining containers to add.
var sizeOfNewLastBlock = toAdd % blockSize;
if (sizeOfNewLastBlock > 0) {
markup += "<div class='win-itemsblock'>" + _Helpers._stripedContainers(sizeOfNewLastBlock, indexOfNextGroupItem) + "</div>";
indexOfNextGroupItem += sizeOfNewLastBlock;
newBlocksCount++;
}
var blocksTemp = _Global.document.createElement("div");
_SafeHtml.setInnerHTMLUnsafe(blocksTemp, markup);
var children = blocksTemp.children;
for (var i = 0; i < newBlocksCount; i++) {
var block = children[i],
blockNode = {
element: block,
items: _Helpers._nodeListToArray(block.children)
};
itemsContainer.itemsBlocks.push(blockNode);
for (var n = 0; n < blockNode.items.length; n++) {
that.containers.push(blockNode.items[n]);
}
}
}
function newGroup(group) {
var node = {
header: that._listView._groupDataSource ? that._createHeaderContainer() : null,
itemsContainer: {
element: that._createItemsContainer(),
itemsBlocks: []
}
};
that.tree.push(node);
that.keyToGroupIndex[group.key] = that.tree.length - 1;
addToGroup(node.itemsContainer, group.size);
}
if (this.tree.length && this.tree.length <= groups.length) {
var lastContainer = this.tree[this.tree.length - 1].itemsContainer,
finalSize = groups[this.tree.length - 1].size,
currentSize = 0;
if (lastContainer.itemsBlocks.length) {
currentSize = (lastContainer.itemsBlocks.length - 1) * blockSize + lastContainer.itemsBlocks[lastContainer.itemsBlocks.length - 1].items.length;
}
if (currentSize < finalSize) {
addToGroup(lastContainer, finalSize - currentSize);
this._listView._writeProfilerMark("createChunk,StopTM");
return;
}
}
if (this.tree.length < groups.length) {
newGroup(groups[this.tree.length]);
}
this._listView._writeProfilerMark("createChunk,StopTM");
} |
JavaScript | function fibonacci(num) {
if (num <= 1) return 1;
//Using double minus here, to show that this is a number (for plus this isn't possible)
return fibonacci(num - 1) - -fibonacci(num - 2);
} | function fibonacci(num) {
if (num <= 1) return 1;
//Using double minus here, to show that this is a number (for plus this isn't possible)
return fibonacci(num - 1) - -fibonacci(num - 2);
} |
JavaScript | function Bot(username, hostname, password, channels, callback) {
var that = this;
EventEmitter.call(that);
create_client(username, hostname, password, channels, function(client) {
subscribe_events(client, that);
createPrototypes(client, that);
callback(that);
});
} | function Bot(username, hostname, password, channels, callback) {
var that = this;
EventEmitter.call(that);
create_client(username, hostname, password, channels, function(client) {
subscribe_events(client, that);
createPrototypes(client, that);
callback(that);
});
} |
JavaScript | function simplifyChanges(res) {
var changes = res.results.map(function (change) {
return {
id: change.id,
deleted: change.deleted,
changes: change.changes.map(function (x) {
return x.rev;
}).sort(),
doc: change.doc
};
});
// in CouchDB 2.0, changes is not guaranteed to be
// ordered
if (testUtils.isCouchMaster()) {
changes.sort(function (a, b) {
return a.id > b.id;
});
}
return changes;
} | function simplifyChanges(res) {
var changes = res.results.map(function (change) {
return {
id: change.id,
deleted: change.deleted,
changes: change.changes.map(function (x) {
return x.rev;
}).sort(),
doc: change.doc
};
});
// in CouchDB 2.0, changes is not guaranteed to be
// ordered
if (testUtils.isCouchMaster()) {
changes.sort(function (a, b) {
return a.id > b.id;
});
}
return changes;
} |
JavaScript | function rebuildDocuments(db, docs, callback) {
db.allDocs({ include_docs: true }, function (err, response) {
var count = 0;
var limit = response.rows.length;
if (limit === 0) {
bulkLoad(db, docs, callback);
}
response.rows.forEach(function (doc) {
db.remove(doc, function (err, response) {
++count;
if (count === limit) {
bulkLoad(db, docs, callback);
}
});
});
});
} | function rebuildDocuments(db, docs, callback) {
db.allDocs({ include_docs: true }, function (err, response) {
var count = 0;
var limit = response.rows.length;
if (limit === 0) {
bulkLoad(db, docs, callback);
}
response.rows.forEach(function (doc) {
db.remove(doc, function (err, response) {
++count;
if (count === limit) {
bulkLoad(db, docs, callback);
}
});
});
});
} |
JavaScript | function PatchedPouch(name, opts, callback) {
var db = new PouchDB(name, opts, callback);
var excluded = ['info'];
var dbInfo = db.info();
var dbType = db.type();
var doPromiseLog = false;
for (var key in db) {
if (key !== 'info' && typeof db[key] === 'function' &&
db[key]._isPromisingFunction) {
doPromiseLog = excluded.indexOf(key) < 0;
// Update attributes to communicate back to toPromise's logging.
utils.extend(db[key], {
_doPromiseLog: doPromiseLog,
_methodName: key,
_dbInfo: dbInfo,
_dbType: dbType
});
}
}
return db;
} | function PatchedPouch(name, opts, callback) {
var db = new PouchDB(name, opts, callback);
var excluded = ['info'];
var dbInfo = db.info();
var dbType = db.type();
var doPromiseLog = false;
for (var key in db) {
if (key !== 'info' && typeof db[key] === 'function' &&
db[key]._isPromisingFunction) {
doPromiseLog = excluded.indexOf(key) < 0;
// Update attributes to communicate back to toPromise's logging.
utils.extend(db[key], {
_doPromiseLog: doPromiseLog,
_methodName: key,
_dbInfo: dbInfo,
_dbType: dbType
});
}
}
return db;
} |
JavaScript | function onComplete() {
db.allDocs(function (err, res1) {
should.not.exist(err);
remote.allDocs(function (err, res2) {
should.not.exist(err);
res1.total_rows.should.equal(res2.total_rows);
done();
});
});
} | function onComplete() {
db.allDocs(function (err, res1) {
should.not.exist(err);
remote.allDocs(function (err, res2) {
should.not.exist(err);
res1.total_rows.should.equal(res2.total_rows);
done();
});
});
} |
JavaScript | function quadStripFaces(vertNum, reversed, offset1, offset2) {
let faces = [];
for (let quad=0; quad < vertNum-1; quad++) {
let v1 = offset1 + quad,
v2 = offset1 + quad + 1,
v3 = offset2 + quad + 1,
v4 = offset2 + quad;
if (!reversed) {
faces.push(new THREE.Face3(v1, v2, v3));
faces.push(new THREE.Face3(v3, v4, v1));
} else {
faces.push(new THREE.Face3(v1, v3, v2));
faces.push(new THREE.Face3(v3, v1, v4));
}
}
return faces;
} | function quadStripFaces(vertNum, reversed, offset1, offset2) {
let faces = [];
for (let quad=0; quad < vertNum-1; quad++) {
let v1 = offset1 + quad,
v2 = offset1 + quad + 1,
v3 = offset2 + quad + 1,
v4 = offset2 + quad;
if (!reversed) {
faces.push(new THREE.Face3(v1, v2, v3));
faces.push(new THREE.Face3(v3, v4, v1));
} else {
faces.push(new THREE.Face3(v1, v3, v2));
faces.push(new THREE.Face3(v3, v1, v4));
}
}
return faces;
} |
JavaScript | function area(p0, p1, p3) {
let p0To1 = point.sub(p1, p0);
let p0To3 = point.sub(p3, p0);
return vector.length(vector.cross(p0To1, p0To3));
} | function area(p0, p1, p3) {
let p0To1 = point.sub(p1, p0);
let p0To3 = point.sub(p3, p0);
return vector.length(vector.cross(p0To1, p0To3));
} |
JavaScript | function polygonSurfaceGeometry(vertices) {
let geom = new THREE.Geometry();
// set vertices
geom.vertices = vertices;
// set faces (GL_TRIANGLE_FAN)
const v0 = 0;
for (let v1=1, v2=2; v2 < vertices.length; v1++, v2++) {
geom.faces.push(new THREE.Face3(v0, v1, v2));
}
// set normals
geom.computeFaceNormals();
geom.computeVertexNormals();
// set bounding sphere
geom.computeBoundingSphere();
return geom;
} | function polygonSurfaceGeometry(vertices) {
let geom = new THREE.Geometry();
// set vertices
geom.vertices = vertices;
// set faces (GL_TRIANGLE_FAN)
const v0 = 0;
for (let v1=1, v2=2; v2 < vertices.length; v1++, v2++) {
geom.faces.push(new THREE.Face3(v0, v1, v2));
}
// set normals
geom.computeFaceNormals();
geom.computeVertexNormals();
// set bounding sphere
geom.computeBoundingSphere();
return geom;
} |
JavaScript | function WalkingDead (options) {
debug('WalkingDead', options);
if (!(this instanceof WalkingDead)) {
debug('not an instance');
return new WalkingDead(options);
}
events.EventEmitter.call(this);
this.walker = Walker(options);
this.walker.on('error', function (err) {
console.error(err);
});
} | function WalkingDead (options) {
debug('WalkingDead', options);
if (!(this instanceof WalkingDead)) {
debug('not an instance');
return new WalkingDead(options);
}
events.EventEmitter.call(this);
this.walker = Walker(options);
this.walker.on('error', function (err) {
console.error(err);
});
} |
JavaScript | function Walker (options) {
debug('Walker', options);
if (!(this instanceof Walker)) {
debug('not an instance');
return new Walker(options);
}
events.EventEmitter.call(this);
var self = this;
options = options || {};
options.agents = options.agents || [];
this.options = options;
/**
* Attach this method to an EventEmitter to trigger
* the walk() action.
*
* @api public
* @param {String} url
* @param {Function} cb
*/
this.onUrl = function (url, cb) {
debug('onUrl', url, typeof cb);
cb = (typeof cb === 'function' ? cb : noop);
self.walk(url, cb);
};
/**
* begins the walking proces if it hasn't already started
*/
this.onWalk = function () {
debug('onWalk');
if (self.walking()) return;
self.emit('walk');
function next () {
try {
var path = self.paths().shift();
debug('next', (typeof path, path ? path.url : undefined), (typeof path, path ? path.ua : undefined));
if (!path) return self.emit('done');
self.onWalking(path.url, path.ua);
path(function evaluate (err, zombie, status) {
try {
debug('evaluate', err, typeof zombie, status);
if (err) self.onError(err, path.url, path.ua, zombie, status);
self.onWalked(path.url, path.ua, zombie, status, next);
next();
}
catch(e) {
self.onError(e, (path ? path.url : null), (path ? path.ua : null), self.zombie(), status);
}
});
}
catch(e) {
self.onError(e, (path ? path.url : null), (path ? path.ua : null), self.zombie(), null);
}
}
next();
};
/**
* Called when we are walking a url
*
* @param {String} url
* @param {String} ua
*/
this.onWalking = function (url, ua) {
debug('onWalking', url, ua);
self._walking = true;
self.emit('walking', url, ua);
};
/**
* Called when we have walked a url
*
* @param {String} url
* @param {String} ua
* @param {Zombie} zombie
* @param {mixed} status
*/
this.onWalked = function (url, ua, zombie, status) {
debug('onWalked', url, ua, typeof zombie, status);
self._walking = self.paths().length ? true : false;
self.emit('walked', url, ua, zombie, status);
};
/**
* Called when we get an error
*
* @param {Error} err
* @param {String} url
* @param {String} ua
* @param {Zombie} zombie
* @param {mixed} status
*/
this.onError = function (err, url, ua, zombie, status) {
debug('onError', err, url, ua, typeof zombie, status);
self.emit('error', err, url, ua, zombie, status);
};
this._walking = false;
} | function Walker (options) {
debug('Walker', options);
if (!(this instanceof Walker)) {
debug('not an instance');
return new Walker(options);
}
events.EventEmitter.call(this);
var self = this;
options = options || {};
options.agents = options.agents || [];
this.options = options;
/**
* Attach this method to an EventEmitter to trigger
* the walk() action.
*
* @api public
* @param {String} url
* @param {Function} cb
*/
this.onUrl = function (url, cb) {
debug('onUrl', url, typeof cb);
cb = (typeof cb === 'function' ? cb : noop);
self.walk(url, cb);
};
/**
* begins the walking proces if it hasn't already started
*/
this.onWalk = function () {
debug('onWalk');
if (self.walking()) return;
self.emit('walk');
function next () {
try {
var path = self.paths().shift();
debug('next', (typeof path, path ? path.url : undefined), (typeof path, path ? path.ua : undefined));
if (!path) return self.emit('done');
self.onWalking(path.url, path.ua);
path(function evaluate (err, zombie, status) {
try {
debug('evaluate', err, typeof zombie, status);
if (err) self.onError(err, path.url, path.ua, zombie, status);
self.onWalked(path.url, path.ua, zombie, status, next);
next();
}
catch(e) {
self.onError(e, (path ? path.url : null), (path ? path.ua : null), self.zombie(), status);
}
});
}
catch(e) {
self.onError(e, (path ? path.url : null), (path ? path.ua : null), self.zombie(), null);
}
}
next();
};
/**
* Called when we are walking a url
*
* @param {String} url
* @param {String} ua
*/
this.onWalking = function (url, ua) {
debug('onWalking', url, ua);
self._walking = true;
self.emit('walking', url, ua);
};
/**
* Called when we have walked a url
*
* @param {String} url
* @param {String} ua
* @param {Zombie} zombie
* @param {mixed} status
*/
this.onWalked = function (url, ua, zombie, status) {
debug('onWalked', url, ua, typeof zombie, status);
self._walking = self.paths().length ? true : false;
self.emit('walked', url, ua, zombie, status);
};
/**
* Called when we get an error
*
* @param {Error} err
* @param {String} url
* @param {String} ua
* @param {Zombie} zombie
* @param {mixed} status
*/
this.onError = function (err, url, ua, zombie, status) {
debug('onError', err, url, ua, typeof zombie, status);
self.emit('error', err, url, ua, zombie, status);
};
this._walking = false;
} |
JavaScript | function wrapCallback(callback) {
return function parseResponse(err, res, body) {
if (err) {
return callback(err);
}
// Only application/json response should be decoded back to JSON
try {
body = JSON.parse(body);
} catch (err) {
console.log(err.message);
}
if (body.code) {
// Handle error response
err = new Error(body.message);
}
callback(err, res, body);
};
} | function wrapCallback(callback) {
return function parseResponse(err, res, body) {
if (err) {
return callback(err);
}
// Only application/json response should be decoded back to JSON
try {
body = JSON.parse(body);
} catch (err) {
console.log(err.message);
}
if (body.code) {
// Handle error response
err = new Error(body.message);
}
callback(err, res, body);
};
} |
JavaScript | function onOpen() {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Use in this spreadsheet', 'use')
.addToUi();
} | function onOpen() {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Use in this spreadsheet', 'use')
.addToUi();
} |
JavaScript | function use() {
var title = 'UKWA Google Sheets Functions';
var message = 'The functions WEBARCHIVE_STATUS_UKWA, WEBARCHIVE_STATUS_UKGWA and WEBARCHIVE_STATUS_IA are now available in ' +
'this spreadsheet. More information is available in the function help ' +
'box that appears when you start using them in a formula.';
var ui = SpreadsheetApp.getUi();
ui.alert(title, message, ui.ButtonSet.OK);
} | function use() {
var title = 'UKWA Google Sheets Functions';
var message = 'The functions WEBARCHIVE_STATUS_UKWA, WEBARCHIVE_STATUS_UKGWA and WEBARCHIVE_STATUS_IA are now available in ' +
'this spreadsheet. More information is available in the function help ' +
'box that appears when you start using them in a formula.';
var ui = SpreadsheetApp.getUi();
ui.alert(title, message, ui.ButtonSet.OK);
} |
JavaScript | function WEBARCHIVE_STATUS_UKGWA(input) {
console.log("Checking UKGWA...")
if(input == "") {
return "";
}
var url = "https://webarchive.nationalarchives.gov.uk/" + input;
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
return response.getResponseCode();
} | function WEBARCHIVE_STATUS_UKGWA(input) {
console.log("Checking UKGWA...")
if(input == "") {
return "";
}
var url = "https://webarchive.nationalarchives.gov.uk/" + input;
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
return response.getResponseCode();
} |
JavaScript | dispose() {
return new Promise((resolve, reject) => {
debug('Closing SSH connection')
if (this.connection.connected === false) {
debug('SSH connection already closed');
resolve('SSH session already closed');
return;
}
this.connection.on('closed', function(addr,err) {
if (err) {
debug('Error on SSH closed event!');
throw TypeError("issues");
reject();
} else {
debug('SSH session has been closed successfully');
resolve('SSH session has been closed successfully');
}
});
this.connection.close();
});
} | dispose() {
return new Promise((resolve, reject) => {
debug('Closing SSH connection')
if (this.connection.connected === false) {
debug('SSH connection already closed');
resolve('SSH session already closed');
return;
}
this.connection.on('closed', function(addr,err) {
if (err) {
debug('Error on SSH closed event!');
throw TypeError("issues");
reject();
} else {
debug('SSH session has been closed successfully');
resolve('SSH session has been closed successfully');
}
});
this.connection.close();
});
} |
JavaScript | function _resetForm( confirmed ) {
let message;
if ( !confirmed && form.editStatus ) {
message = t( 'confirm.save.msg' );
gui.confirm( message )
.then( confirmed => {
if ( confirmed ) {
_resetForm( true );
}
} );
} else {
_setDraftStatus( false );
form.resetView();
form = new Form( formSelector, {
modelStr: formData.modelStr,
external: formData.external
}, formOptions );
const loadErrors = form.init();
// formreset event will update the form media:
form.view.$.trigger( 'formreset' );
if ( records ) {
records.setActive( null );
}
if ( loadErrors.length > 0 ) {
gui.alertLoadErrors( loadErrors );
}
}
} | function _resetForm( confirmed ) {
let message;
if ( !confirmed && form.editStatus ) {
message = t( 'confirm.save.msg' );
gui.confirm( message )
.then( confirmed => {
if ( confirmed ) {
_resetForm( true );
}
} );
} else {
_setDraftStatus( false );
form.resetView();
form = new Form( formSelector, {
modelStr: formData.modelStr,
external: formData.external
}, formOptions );
const loadErrors = form.init();
// formreset event will update the form media:
form.view.$.trigger( 'formreset' );
if ( records ) {
records.setActive( null );
}
if ( loadErrors.length > 0 ) {
gui.alertLoadErrors( loadErrors );
}
}
} |
JavaScript | function _submitRecord() {
const redirect = settings.type === 'single' || settings.type === 'edit' || settings.type === 'view';
let beforeMsg;
let authLink;
let level;
let msg = '';
const include = {
irrelevant: false
};
form.view.$.trigger( 'beforesave' );
beforeMsg = ( redirect ) ? t( 'alert.submission.redirectmsg' ) : '';
authLink = `<a href="${settings.loginUrl}" target="_blank">${t( 'here' )}</a>`;
gui.alert( `${beforeMsg}<div class="loader-animation-small" style="margin: 40px auto 0 auto;"/>`, t( 'alert.submission.msg' ), 'bare' );
console.log("Form Data to Log");
console.log(form);
return new Promise( resolve => {
const record = {
'xml': form.getDataStr( include ),
'files': fileManager.getCurrentFiles(),
'instanceId': form.instanceID,
'deprecatedId': form.deprecatedID
};
if ( form.encryptionKey ) {
const formProps = {
encryptionKey: form.encryptionKey,
id: form.view.html.id, // TODO: after enketo-core support, use form.id
version: form.version,
};
resolve( encryptor.encryptRecord( formProps, record ) );
} else {
resolve( record );
}
} )
.then( connection.uploadRecord )
.then( result => {
result = result || {};
level = 'success';
if ( result.failedFiles && result.failedFiles.length > 0 ) {
msg = `${t( 'alert.submissionerror.fnfmsg', {
failedFiles: result.failedFiles.join( ', ' ),
supportEmail: settings.supportEmail
} )}<br/>`;
level = 'warning';
}
// this event is used in communicating back to iframe parent window
document.dispatchEvent( events.SubmissionSuccess() );
//clear the log if login.
if ( redirect ) {
if ( !settings.multipleAllowed ) {
const now = new Date();
const age = 31536000;
const d = new Date();
/**
* Manipulate the browser history to work around potential ways to
* circumvent protection against multiple submissions:
* 1. After redirect, click Back button to load cached version.
*/
history.replaceState( {}, '', `${settings.defaultReturnUrl}?taken=${now.getTime()}` );
/**
* The above replaceState doesn't work in Safari and probably in
* some other browsers (mobile). It shows the
* final submission dialog when clicking Back.
* So we remove the form...
*/
$( 'form.or' ).empty();
$( 'button#submit-form' ).remove();
d.setTime( d.getTime() + age * 1000 );
document.cookie = `${settings.enketoId}=${now.getTime()};path=/single;max-age=${age};expires=${d.toGMTString()};`;
}
msg += t( 'alert.submissionsuccess.redirectmsg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
setTimeout( () => {
location.href = decodeURIComponent( settings.returnUrl || settings.defaultReturnUrl );
}, 1200 );
} else {
msg = ( msg.length > 0 ) ? msg : t( 'alert.submissionsuccess.msg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
_resetForm( true );
}
} )
.catch( result => {
let message;
result = result || {};
console.error( 'submission failed', result );
if ( result.status === 401 ) {
message = t( 'alert.submissionerror.authrequiredmsg', {
here: authLink,
// switch off escaping just for this known safe value
interpolation: {
escapeValue: false
}
} );
} else {
message = result.message || gui.getErrorResponseMsg( result.status );
}
gui.alert( message, t( 'alert.submissionerror.heading' ) );
} );
} | function _submitRecord() {
const redirect = settings.type === 'single' || settings.type === 'edit' || settings.type === 'view';
let beforeMsg;
let authLink;
let level;
let msg = '';
const include = {
irrelevant: false
};
form.view.$.trigger( 'beforesave' );
beforeMsg = ( redirect ) ? t( 'alert.submission.redirectmsg' ) : '';
authLink = `<a href="${settings.loginUrl}" target="_blank">${t( 'here' )}</a>`;
gui.alert( `${beforeMsg}<div class="loader-animation-small" style="margin: 40px auto 0 auto;"/>`, t( 'alert.submission.msg' ), 'bare' );
console.log("Form Data to Log");
console.log(form);
return new Promise( resolve => {
const record = {
'xml': form.getDataStr( include ),
'files': fileManager.getCurrentFiles(),
'instanceId': form.instanceID,
'deprecatedId': form.deprecatedID
};
if ( form.encryptionKey ) {
const formProps = {
encryptionKey: form.encryptionKey,
id: form.view.html.id, // TODO: after enketo-core support, use form.id
version: form.version,
};
resolve( encryptor.encryptRecord( formProps, record ) );
} else {
resolve( record );
}
} )
.then( connection.uploadRecord )
.then( result => {
result = result || {};
level = 'success';
if ( result.failedFiles && result.failedFiles.length > 0 ) {
msg = `${t( 'alert.submissionerror.fnfmsg', {
failedFiles: result.failedFiles.join( ', ' ),
supportEmail: settings.supportEmail
} )}<br/>`;
level = 'warning';
}
// this event is used in communicating back to iframe parent window
document.dispatchEvent( events.SubmissionSuccess() );
//clear the log if login.
if ( redirect ) {
if ( !settings.multipleAllowed ) {
const now = new Date();
const age = 31536000;
const d = new Date();
/**
* Manipulate the browser history to work around potential ways to
* circumvent protection against multiple submissions:
* 1. After redirect, click Back button to load cached version.
*/
history.replaceState( {}, '', `${settings.defaultReturnUrl}?taken=${now.getTime()}` );
/**
* The above replaceState doesn't work in Safari and probably in
* some other browsers (mobile). It shows the
* final submission dialog when clicking Back.
* So we remove the form...
*/
$( 'form.or' ).empty();
$( 'button#submit-form' ).remove();
d.setTime( d.getTime() + age * 1000 );
document.cookie = `${settings.enketoId}=${now.getTime()};path=/single;max-age=${age};expires=${d.toGMTString()};`;
}
msg += t( 'alert.submissionsuccess.redirectmsg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
setTimeout( () => {
location.href = decodeURIComponent( settings.returnUrl || settings.defaultReturnUrl );
}, 1200 );
} else {
msg = ( msg.length > 0 ) ? msg : t( 'alert.submissionsuccess.msg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
_resetForm( true );
}
} )
.catch( result => {
let message;
result = result || {};
console.error( 'submission failed', result );
if ( result.status === 401 ) {
message = t( 'alert.submissionerror.authrequiredmsg', {
here: authLink,
// switch off escaping just for this known safe value
interpolation: {
escapeValue: false
}
} );
} else {
message = result.message || gui.getErrorResponseMsg( result.status );
}
gui.alert( message, t( 'alert.submissionerror.heading' ) );
} );
} |
JavaScript | function toggleHelp(help_icon) {
var help_text = $(help_icon.parentNode).find('.help_text');
if (help_text.length <= 0) {
help_text = $(help_icon.parentNode.parentNode).find('.help_text')
}
help_text.first().toggle(200);
$(help_icon).toggleClass("current");
} | function toggleHelp(help_icon) {
var help_text = $(help_icon.parentNode).find('.help_text');
if (help_text.length <= 0) {
help_text = $(help_icon.parentNode.parentNode).find('.help_text')
}
help_text.first().toggle(200);
$(help_icon).toggleClass("current");
} |
JavaScript | function escapeQuotes(text) {
var i = 0;
var text_array = text.split("'");
text = "";
for (i; i < text_array.length - 1; i++) {
text = text.concat(text_array[i], "\\'");
}
text = text.concat(text_array[text_array.length - 1]);
var text_array = text.split('"');
text = "";
for (i; i < text_array.length - 1; i++) {
text = text.concat(text_array[i], '\\"');
}
text = text.concat(text_array[text_array.length - 1]);
return text;
} | function escapeQuotes(text) {
var i = 0;
var text_array = text.split("'");
text = "";
for (i; i < text_array.length - 1; i++) {
text = text.concat(text_array[i], "\\'");
}
text = text.concat(text_array[text_array.length - 1]);
var text_array = text.split('"');
text = "";
for (i; i < text_array.length - 1; i++) {
text = text.concat(text_array[i], '\\"');
}
text = text.concat(text_array[text_array.length - 1]);
return text;
} |
JavaScript | function submitClearsDefaultValues(oid, default_text) {
var form = document.getElementById('deform');
default_text = escapeQuotes(default_text);
var submit_text = "if (document.getElementById('" + oid + "') != null && document.getElementById('" + oid + "').value == '" + default_text + "') {document.getElementById('" + oid + "').value = '';}";
if (form.getAttribute('onsubmit') != null) {
submit_text += form.getAttribute('onsubmit');
}
form.setAttribute('onsubmit', submit_text);
} | function submitClearsDefaultValues(oid, default_text) {
var form = document.getElementById('deform');
default_text = escapeQuotes(default_text);
var submit_text = "if (document.getElementById('" + oid + "') != null && document.getElementById('" + oid + "').value == '" + default_text + "') {document.getElementById('" + oid + "').value = '';}";
if (form.getAttribute('onsubmit') != null) {
submit_text += form.getAttribute('onsubmit');
}
form.setAttribute('onsubmit', submit_text);
} |
JavaScript | function hideDescriptions(hide) {
document.hide_descriptions = hide;
if (hide) {
$(".description").addClass("hidden");
} else {
$(".description").removeClass("hidden");
}
} | function hideDescriptions(hide) {
document.hide_descriptions = hide;
if (hide) {
$(".description").addClass("hidden");
} else {
$(".description").removeClass("hidden");
}
} |
JavaScript | function findMapLayerFromFeature(feature, map) {
var i = 0, j = 0, k = 0;
if (typeof map === "undefined") {
for (i; i < document.location_maps.length; i++) {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
for (k; k < document.location_maps[i].layers[j].features.length; k++) {
if (document.location_maps[i].layers[j].features[k] == feature) {
return document.location_maps[i].layers[j];
}
}
}
}
}
} else {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
for (k; k < document.location_maps[i].layers[j].features.length; k++) {
if (document.location_maps[i].layers[j].features[k] == feature) {
return document.location_maps[i].layers[j];
}
}
}
}
}
return null;
} | function findMapLayerFromFeature(feature, map) {
var i = 0, j = 0, k = 0;
if (typeof map === "undefined") {
for (i; i < document.location_maps.length; i++) {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
for (k; k < document.location_maps[i].layers[j].features.length; k++) {
if (document.location_maps[i].layers[j].features[k] == feature) {
return document.location_maps[i].layers[j];
}
}
}
}
}
} else {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
for (k; k < document.location_maps[i].layers[j].features.length; k++) {
if (document.location_maps[i].layers[j].features[k] == feature) {
return document.location_maps[i].layers[j];
}
}
}
}
}
return null;
} |
JavaScript | function findMapFromLayer(layer) {
var i = 0, j = 0, k = 0;
for (i; i < document.location_maps.length; i++) {
for (j; j < document.location_maps[i].layers.length; j++) {
if (document.location_maps[i].layers[j] == layer) {
return document.location_maps[i];
}
}
}
return null;
} | function findMapFromLayer(layer) {
var i = 0, j = 0, k = 0;
for (i; i < document.location_maps.length; i++) {
for (j; j < document.location_maps[i].layers.length; j++) {
if (document.location_maps[i].layers[j] == layer) {
return document.location_maps[i];
}
}
}
return null;
} |
JavaScript | function appendSequenceItem(add_link) {
deform.appendSequenceItem(add_link);
var fields = $(add_link.parentNode).children('ul').first().find("input[type=text].map_location");
fields[fields.length - 1].setAttribute("onblur", "locationTextModified(this);");
fields[fields.length - 1].map_div = $(add_link.parentNode).children(".location_map")[0];
var deleteLink = $(fields[fields.length - 1]).parents("li").children('.deformClosebutton')[0];
deleteLink.setAttribute("onclick", deleteLink.getAttribute("onclick") + " deleteFeature($(this.parentNode).find('input[type=text]')[1].feature);");
} | function appendSequenceItem(add_link) {
deform.appendSequenceItem(add_link);
var fields = $(add_link.parentNode).children('ul').first().find("input[type=text].map_location");
fields[fields.length - 1].setAttribute("onblur", "locationTextModified(this);");
fields[fields.length - 1].map_div = $(add_link.parentNode).children(".location_map")[0];
var deleteLink = $(fields[fields.length - 1]).parents("li").children('.deformClosebutton')[0];
deleteLink.setAttribute("onclick", deleteLink.getAttribute("onclick") + " deleteFeature($(this.parentNode).find('input[type=text]')[1].feature);");
} |
JavaScript | function addMapFeatures(oid) {
var fields = $("#" + oid).children('ul').first().find("input[type=text].map_location");
var map_div = $("#" + oid).children(".location_map")[0];
var i = 0;
for (i; i < fields.length; i++) {
var deleteLink = $(fields[i]).parents("li").children('.deformClosebutton')[0];
if (deleteLink) { // Check that this hasn't been removed for readonly display
deleteLink.setAttribute("onclick", deleteLink.getAttribute("onclick") + " deleteFeature($(this.parentNode).find('input[type=text]')[1].feature);");
}
fields[i].setAttribute("onblur", "locationTextModified(this);");
fields[i].map_div = map_div;
// console.log("Adding " + fields[i].value + " to " + map_div);
locationTextModified(fields[i]);
}
// console.log("Finished adding map features for " + oid);
} | function addMapFeatures(oid) {
var fields = $("#" + oid).children('ul').first().find("input[type=text].map_location");
var map_div = $("#" + oid).children(".location_map")[0];
var i = 0;
for (i; i < fields.length; i++) {
var deleteLink = $(fields[i]).parents("li").children('.deformClosebutton')[0];
if (deleteLink) { // Check that this hasn't been removed for readonly display
deleteLink.setAttribute("onclick", deleteLink.getAttribute("onclick") + " deleteFeature($(this.parentNode).find('input[type=text]')[1].feature);");
}
fields[i].setAttribute("onblur", "locationTextModified(this);");
fields[i].map_div = map_div;
// console.log("Adding " + fields[i].value + " to " + map_div);
locationTextModified(fields[i]);
}
// console.log("Finished adding map features for " + oid);
} |
JavaScript | function locationTextModified(input) {
if (input.original_background === undefined) {
input.original_background = input.style.backgroundColor;
}
var geometry_type = input.value.substr(0, input.value.indexOf("("));
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var newGeometry;
var point_match = /point\([+-]?\d*\.?\d* [+-]?\d*\.?\d*\)/i;
var poly_match = /polygon\(\(([+-]?\d*\.?\d*\s[+-]?\d*\.?\d*,?\s?)*\)\)/i;
var line_match = /linestring\(([+-]?\d*\.?\d*\s[+-]?\d*\.?\d*,?\s?)*\)/i;
var points, text_points, i = 0;
if (input.value.match(point_match)) {
points = input.value.trim().substring(geometry_type.length + 1, input.value.trim().length - 1).split(" ");
newGeometry = new OpenLayers.Geometry.Point(new Number(points[0]), new Number(points[1]));
} else if (input.value.match(poly_match)) {
text_points = input.value.trim().substring(geometry_type.length + 2, input.value.trim().length - 2).split(",");
points = [];
for (i; i < text_points.length; i++) {
points.push(new OpenLayers.Geometry.Point(new Number(text_points[i].split(" ")[0]), new Number(text_points[i].split(" ")[1])));
}
newGeometry = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(points));
} else if (input.value.match(line_match)) {
text_points = input.value.trim().substring(geometry_type.length + 1, input.value.trim().length - 1).split(",");
points = [];
for (i; i < text_points.length; i++) {
points.push(new OpenLayers.Geometry.Point(new Number(text_points[i].split(" ")[0]), new Number(text_points[i].split(" ")[1])));
}
newGeometry = new OpenLayers.Geometry.LineString(points);
} else {
input.style.background = "#ffaaaa";
return;
}
newGeometry.transform(displayProj, proj);
input.style.background = input.original_background;
var layer;
var j = 0, k = 0;
for (i = 0; i < document.location_maps.length; i++) {
if (document.location_maps[i].div == input.map_div) {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
layer = document.location_maps[i].layers[j];
break;
}
}
}
}
var new_feature = new OpenLayers.Feature.Vector(newGeometry);
if (input.hasOwnProperty('feature')) {
layer.destroyFeatures([input.feature]);
input.feature = new_feature;
layer.addFeatures([new_feature]);
} else {
input.feature = new_feature;
layer.addFeatures([new_feature]);
}
} | function locationTextModified(input) {
if (input.original_background === undefined) {
input.original_background = input.style.backgroundColor;
}
var geometry_type = input.value.substr(0, input.value.indexOf("("));
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var newGeometry;
var point_match = /point\([+-]?\d*\.?\d* [+-]?\d*\.?\d*\)/i;
var poly_match = /polygon\(\(([+-]?\d*\.?\d*\s[+-]?\d*\.?\d*,?\s?)*\)\)/i;
var line_match = /linestring\(([+-]?\d*\.?\d*\s[+-]?\d*\.?\d*,?\s?)*\)/i;
var points, text_points, i = 0;
if (input.value.match(point_match)) {
points = input.value.trim().substring(geometry_type.length + 1, input.value.trim().length - 1).split(" ");
newGeometry = new OpenLayers.Geometry.Point(new Number(points[0]), new Number(points[1]));
} else if (input.value.match(poly_match)) {
text_points = input.value.trim().substring(geometry_type.length + 2, input.value.trim().length - 2).split(",");
points = [];
for (i; i < text_points.length; i++) {
points.push(new OpenLayers.Geometry.Point(new Number(text_points[i].split(" ")[0]), new Number(text_points[i].split(" ")[1])));
}
newGeometry = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(points));
} else if (input.value.match(line_match)) {
text_points = input.value.trim().substring(geometry_type.length + 1, input.value.trim().length - 1).split(",");
points = [];
for (i; i < text_points.length; i++) {
points.push(new OpenLayers.Geometry.Point(new Number(text_points[i].split(" ")[0]), new Number(text_points[i].split(" ")[1])));
}
newGeometry = new OpenLayers.Geometry.LineString(points);
} else {
input.style.background = "#ffaaaa";
return;
}
newGeometry.transform(displayProj, proj);
input.style.background = input.original_background;
var layer;
var j = 0, k = 0;
for (i = 0; i < document.location_maps.length; i++) {
if (document.location_maps[i].div == input.map_div) {
for (j; j < document.location_maps[i].layers.length; j++) {
if ((OpenLayers.Layer.Vector.prototype.isPrototypeOf(document.location_maps[i].layers[j]))) {
layer = document.location_maps[i].layers[j];
break;
}
}
}
}
var new_feature = new OpenLayers.Feature.Vector(newGeometry);
if (input.hasOwnProperty('feature')) {
layer.destroyFeatures([input.feature]);
input.feature = new_feature;
layer.addFeatures([new_feature]);
} else {
input.feature = new_feature;
layer.addFeatures([new_feature]);
}
} |
JavaScript | function modifyFeature(object) {
var feature = object.feature;
var map = object.object.map;
var layer = findMapLayerFromFeature(feature, map);
var oid_node = $(map.div.parentNode);
var fields = oid_node.children('ul').first().find("input[type=text]");
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
var i = 0;
for (i; i < fields.length; i++) {
if (fields[i].feature == feature) {
fields[i].value = geometry;
}
}
} | function modifyFeature(object) {
var feature = object.feature;
var map = object.object.map;
var layer = findMapLayerFromFeature(feature, map);
var oid_node = $(map.div.parentNode);
var fields = oid_node.children('ul').first().find("input[type=text]");
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
var i = 0;
for (i; i < fields.length; i++) {
if (fields[i].feature == feature) {
fields[i].value = geometry;
}
}
} |
JavaScript | function deleteFeature(feature) {
var layer = findMapLayerFromFeature(feature);
var map = findMapFromLayer(layer);
var displayProj = new OpenLayers.Projection("EPSG:4326");
var oid_node = $(map.div.parentNode);
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
var fields = oid_node.children('ul').first().find("input[type=text]");
var i = 0;
for (i; i < fields.length; i++) {
if (fields[i].value == geometry.toString()) {
deform.removeSequenceItem($(fields[i].parentNode.parentNode.parentNode.parentNode.parentNode).find(".deformClosebutton"));
}
}
feature.destroy();
} | function deleteFeature(feature) {
var layer = findMapLayerFromFeature(feature);
var map = findMapFromLayer(layer);
var displayProj = new OpenLayers.Projection("EPSG:4326");
var oid_node = $(map.div.parentNode);
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
var fields = oid_node.children('ul').first().find("input[type=text]");
var i = 0;
for (i; i < fields.length; i++) {
if (fields[i].value == geometry.toString()) {
deform.removeSequenceItem($(fields[i].parentNode.parentNode.parentNode.parentNode.parentNode).find(".deformClosebutton"));
}
}
feature.destroy();
} |
JavaScript | function featureInserted(object) {
var feature = object.feature;
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var map = object.object.map;
var layer = feature.layer; //findMapLayerFromFeature(feature, map);
var oid_node = $(map.div.parentNode);
var fields = oid_node.children('ul').first().find("input[type=text].map_location");
// Check if this feature already has an associated input
var i = 0;
for (i; i < fields.length; i++) {
// var tmp = feature.geometry.clone();
// tmp.transform(map.getProjectionObject(), displayProj);
if (fields[i].feature == feature) {
return;
}
}
// var i = 0, j = 0;
// for (i; i < layer.features.length; i++) {
// /*alert((OpenLayers.Geometry.Polygon.prototype.isPrototypeOf(layer.features[i].geometry)));*/
// alert(layer.features[i].geometry);
// alert(displayProj + " : " + proj + " : " + map.getProjection() + " : " + map.getProjectionObject());
// for (j; j < layer.features[i].geometry.getVertices().length; j++) {
// vertices += layer.features[i].geometry.getVertices()[j].transform(map.getProjectionObject(),displayProj) + ", ";
// }
// }
/* alert(vertices);*/
// Only add a new feature if the last item in the list isn't blank
var last_field = fields[fields.length - 1];
var siblings = $(last_field.parentNode.parentNode).siblings().find("input[type=text]");
if (last_field.value != '' || last_field.feature !== undefined || siblings[0].value != '' || siblings[1].value != '') {
/* Add the feature */
appendSequenceItem(oid_node.children(".deformSeqAdd")[0]);
}
fields = oid_node.children('ul').first().find("input[type=text].map_location");
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
fields[fields.length - 1].value = geometry;
fields[fields.length - 1].feature = feature;
fields[fields.length - 1].className = fields[fields.length - 1].className.replace( /(?:^|\s)placeholder_text(?!\S)/g , '' );
} | function featureInserted(object) {
var feature = object.feature;
var displayProj = new OpenLayers.Projection("EPSG:4326");
var proj = new OpenLayers.Projection("EPSG:900913");
var map = object.object.map;
var layer = feature.layer; //findMapLayerFromFeature(feature, map);
var oid_node = $(map.div.parentNode);
var fields = oid_node.children('ul').first().find("input[type=text].map_location");
// Check if this feature already has an associated input
var i = 0;
for (i; i < fields.length; i++) {
// var tmp = feature.geometry.clone();
// tmp.transform(map.getProjectionObject(), displayProj);
if (fields[i].feature == feature) {
return;
}
}
// var i = 0, j = 0;
// for (i; i < layer.features.length; i++) {
// /*alert((OpenLayers.Geometry.Polygon.prototype.isPrototypeOf(layer.features[i].geometry)));*/
// alert(layer.features[i].geometry);
// alert(displayProj + " : " + proj + " : " + map.getProjection() + " : " + map.getProjectionObject());
// for (j; j < layer.features[i].geometry.getVertices().length; j++) {
// vertices += layer.features[i].geometry.getVertices()[j].transform(map.getProjectionObject(),displayProj) + ", ";
// }
// }
/* alert(vertices);*/
// Only add a new feature if the last item in the list isn't blank
var last_field = fields[fields.length - 1];
var siblings = $(last_field.parentNode.parentNode).siblings().find("input[type=text]");
if (last_field.value != '' || last_field.feature !== undefined || siblings[0].value != '' || siblings[1].value != '') {
/* Add the feature */
appendSequenceItem(oid_node.children(".deformSeqAdd")[0]);
}
fields = oid_node.children('ul').first().find("input[type=text].map_location");
var geometry = feature.geometry.clone();
geometry.transform(map.getProjectionObject(), displayProj);
fields[fields.length - 1].value = geometry;
fields[fields.length - 1].feature = feature;
fields[fields.length - 1].className = fields[fields.length - 1].className.replace( /(?:^|\s)placeholder_text(?!\S)/g , '' );
} |
JavaScript | function processJavascript(parentElement) {
var scripts = $(parentElement).find("script");
for (i = 0; i < scripts.length; i++) {
if (scripts[i].innerHTML.trim().length > 0) {
eval(scripts[i].innerHTML);
} else if (scripts[i].src.length > 0) {
$.getScript(scripts[i].src);
}
}
} | function processJavascript(parentElement) {
var scripts = $(parentElement).find("script");
for (i = 0; i < scripts.length; i++) {
if (scripts[i].innerHTML.trim().length > 0) {
eval(scripts[i].innerHTML);
} else if (scripts[i].src.length > 0) {
$.getScript(scripts[i].src);
}
}
} |
JavaScript | function buttonPressed(node) {
var oid_node = $(node).parent();
var id = oid_node.attr('id');
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
var fields = oid_node.children('ul').first().find("input[readonly='readonly']");
var text = third_select.options[third_select.selectedIndex].value;
if (text == "---Select One---") {
var text = second_select.options[second_select.selectedIndex].value;
}
fields[fields.length - 1].value = text;
fields[fields.length - 1].style.display = "inline";
var removeButton = $(fields[fields.length - 1]).parents('[id^="sequence"]').find(".deformClosebutton")[0];
removeButton.setAttribute("onclick","deform.removeSequenceItem(this);" + "showAdd('" + id + "', false);");
// removeButton.onclick = removeButton.onclick + "; showAdd(" + oid_node[0].id + ", false); ";
/* Delete duplicates */
var i = 0;
for (i; i < fields.length - 1; i++) {
if (fields[i].value == text) {
deform.removeSequenceItem($(fields[i]).parents('[id^="sequence"]').find(".deformClosebutton")[0]);
alert("Not Added: The selected FOR code is a duplicate");
}
}
/* Reset the FOR field select boxes */
first_select.selectedIndex = 0;
second_select.innerHTML = "";
second_select.style.display = "none";
$(second_select).next().hide();
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
showAdd(oid_node[0].id, false);
} | function buttonPressed(node) {
var oid_node = $(node).parent();
var id = oid_node.attr('id');
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
var fields = oid_node.children('ul').first().find("input[readonly='readonly']");
var text = third_select.options[third_select.selectedIndex].value;
if (text == "---Select One---") {
var text = second_select.options[second_select.selectedIndex].value;
}
fields[fields.length - 1].value = text;
fields[fields.length - 1].style.display = "inline";
var removeButton = $(fields[fields.length - 1]).parents('[id^="sequence"]').find(".deformClosebutton")[0];
removeButton.setAttribute("onclick","deform.removeSequenceItem(this);" + "showAdd('" + id + "', false);");
// removeButton.onclick = removeButton.onclick + "; showAdd(" + oid_node[0].id + ", false); ";
/* Delete duplicates */
var i = 0;
for (i; i < fields.length - 1; i++) {
if (fields[i].value == text) {
deform.removeSequenceItem($(fields[i]).parents('[id^="sequence"]').find(".deformClosebutton")[0]);
alert("Not Added: The selected FOR code is a duplicate");
}
}
/* Reset the FOR field select boxes */
first_select.selectedIndex = 0;
second_select.innerHTML = "";
second_select.style.display = "none";
$(second_select).next().hide();
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
showAdd(oid_node[0].id, false);
} |
JavaScript | function fix_multi_select_close(oid) {
var oid_node = $('#' + oid);
var close_buttons = oid_node.children('ul').first().find("span.deformClosebutton");
for (var i=0; i<close_buttons.length; i++) {
close_buttons[i].setAttribute("onclick","deform.removeSequenceItem(this);" + "showAdd('" + oid + "', false);");
}
} | function fix_multi_select_close(oid) {
var oid_node = $('#' + oid);
var close_buttons = oid_node.children('ul').first().find("span.deformClosebutton");
for (var i=0; i<close_buttons.length; i++) {
close_buttons[i].setAttribute("onclick","deform.removeSequenceItem(this);" + "showAdd('" + oid + "', false);");
}
} |
JavaScript | function showAdd(oid, show) {
var oid_node = $('#' + oid);
// alert(oid_node);
var $before_node = oid_node.children('ul').first().children('.deformInsertBefore').first();
var max_len = parseInt($before_node.attr('max_len')||'9999', 10);
var now_len = parseInt($before_node.attr('now_len')||'0', 10);
if (now_len >= max_len) {
oid_node.children("button").hide();
oid_node.children(".max_error").show();
return;
}
oid_node.children(".max_error").hide();
if (show) {
oid_node.children("button")[0].style.display = "inline";
var original_color = oid_node.children("button").first().css('backgroundColor');
oid_node.children("button").animate({ backgroundColor: "#F7931E"}, 100);
oid_node.children("button").animate({ backgroundColor: original_color}, 100);
oid_node.children("button").animate({ backgroundColor: "#F7931E"}, 100);
oid_node.children("button").animate({ backgroundColor: original_color}, 100);
// alert('show');
} else {
// alert('hide');
oid_node.children("button")[0].style.display = "none";
}
} | function showAdd(oid, show) {
var oid_node = $('#' + oid);
// alert(oid_node);
var $before_node = oid_node.children('ul').first().children('.deformInsertBefore').first();
var max_len = parseInt($before_node.attr('max_len')||'9999', 10);
var now_len = parseInt($before_node.attr('now_len')||'0', 10);
if (now_len >= max_len) {
oid_node.children("button").hide();
oid_node.children(".max_error").show();
return;
}
oid_node.children(".max_error").hide();
if (show) {
oid_node.children("button")[0].style.display = "inline";
var original_color = oid_node.children("button").first().css('backgroundColor');
oid_node.children("button").animate({ backgroundColor: "#F7931E"}, 100);
oid_node.children("button").animate({ backgroundColor: original_color}, 100);
oid_node.children("button").animate({ backgroundColor: "#F7931E"}, 100);
oid_node.children("button").animate({ backgroundColor: original_color}, 100);
// alert('show');
} else {
// alert('hide');
oid_node.children("button")[0].style.display = "none";
}
} |
JavaScript | function updateSecondFields(oid) {
var oid_node = $('#' + oid);
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
if (first_select.selectedIndex != 0) {
var options_class = "second_level_data-" + first_select.options[first_select.selectedIndex].value;
var second_level_options = document.getElementsByClassName(options_class)[0];
second_select.innerHTML = second_level_options.innerHTML;
second_select.style.display = "inline";
$(second_select).next().show();
} else {
second_select.innerHTML = "";
first_select.selectedIndex = 0;
second_select.style.display = "none";
$(second_select).next().hide();
showAdd(oid, false);
}
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
/* Make sure that the user can't have an invalid 3rd field selected when the first select is changed */
} | function updateSecondFields(oid) {
var oid_node = $('#' + oid);
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
if (first_select.selectedIndex != 0) {
var options_class = "second_level_data-" + first_select.options[first_select.selectedIndex].value;
var second_level_options = document.getElementsByClassName(options_class)[0];
second_select.innerHTML = second_level_options.innerHTML;
second_select.style.display = "inline";
$(second_select).next().show();
} else {
second_select.innerHTML = "";
first_select.selectedIndex = 0;
second_select.style.display = "none";
$(second_select).next().hide();
showAdd(oid, false);
}
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
/* Make sure that the user can't have an invalid 3rd field selected when the first select is changed */
} |
JavaScript | function updateThirdFields(oid) {
var oid_node = $('#' + oid);
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
if (second_select.selectedIndex != 0) {
var options_class = "third_level_data-" + second_select.options[second_select.selectedIndex].value;
var third_level_options = document.getElementsByClassName(options_class)[0];
third_select.innerHTML = third_level_options.innerHTML;
third_select.style.display = "inline";
$(third_select).next().show();
} else {
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
showAdd(oid, false)
}
} | function updateThirdFields(oid) {
var oid_node = $('#' + oid);
var first_select = oid_node.children(".first_field")[0];
var second_select = oid_node.children(".second_field")[0];
var third_select = oid_node.children(".third_field")[0];
if (second_select.selectedIndex != 0) {
var options_class = "third_level_data-" + second_select.options[second_select.selectedIndex].value;
var third_level_options = document.getElementsByClassName(options_class)[0];
third_select.innerHTML = third_level_options.innerHTML;
third_select.style.display = "inline";
$(third_select).next().show();
} else {
third_select.innerHTML = "";
third_select.style.display = "none";
$(third_select).next().hide();
showAdd(oid, false)
}
} |
Subsets and Splits