language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class GregorianCalendar {
constructor (id) {
this.id = id;
}
eras = null // no era with the "real" proleptic Gregorian calendar.
canvas = "gregory"
stringFormat = "built-in" // formatting options start from canvas calendars values
partsFormat = {
era : { mode : "field" },
year : { mode : "field" }
}
// no clockwork, use standard Date routines
gregorianWeek = new WeekClock (
{
originWeekday : 4, // 1 Jan. 1970 ISO is Thursday
daysInYear : (year) => (Cbcce.isGregorianLeapYear ( year ) ? 366 : 365),
characDayIndex: (year) => ( Math.floor(this.counterFromFields({fullYear : year, month : 1, day : 4})/Milliseconds.DAY_UNIT) ),
startOfWeek : 1
// the rest of by default
}
) // set for gregorian week elements.
solveAskedFields (askedFields) {
var fields = {...askedFields};
if (fields.year != undefined && fields.fullYear != undefined)
{ if (fields.year != fields.fullYear) throw new TypeError ('Unconsistent year and fullYear fields: ' + fields.year + ', ' + fields.fullYear) }
else { if (fields.year != undefined) { fields.fullYear = fields.year } else if (fields.fullYear != undefined) fields.year = fields.fullYear };
return fields
}
fieldsFromCounter (timeStamp) {
let myDate = new ExtDate ("iso8601", timeStamp),
myFields = {
fullYear : myDate.getUTCFullYear(),
month : myDate.getUTCMonth() + 1,
day : myDate.getUTCDate(),
hours : myDate.getUTCHours(),
minutes : myDate.getUTCMinutes(),
seconds : myDate.getUTCSeconds(),
milliseconds : myDate.getUTCMilliseconds()
};
myFields.year = myFields.fullYear;
return myFields;
}
counterFromFields (fields) {
let myFields = { fullYear : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, this.solveAskedFields(fields));
let myDate = new ExtDate
("iso8601", ExtDate.fullUTC(myFields.fullYear, myFields.month, myFields.day, myFields.hours, myFields.minutes, myFields.seconds, myFields.milliseconds));
return myDate.valueOf()
}
buildDateFromFields (fields, construct = ExtDate) {
let myFields = { fullYear : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, this.solveAskedFields(fields));
return new construct (this, ExtDate.fullUTC(fields.fullYear, fields.month, fields.day, fields.hours, fields.minutes, fields.seconds, fields.milliseconds))
}
weekFieldsFromCounter (timeStamp) {
let myDate = new ExtDate ("iso8601", timeStamp),
fullYear = myDate.getUTCFullYear(),
myFigures = this.gregorianWeek.getWeekFigures (Math.floor(myDate.valueOf()/Milliseconds.DAY_UNIT), fullYear);
return {weekYearOffset : myFigures[2], weekYear : fullYear + myFigures[2], weekNumber : myFigures[0], weekday : myFigures[1], weeksInYear : myFigures[3]}
}
counterFromWeekFields (fields) {
let myFields = { weekYear : 0, weekNumber : 1, weekday : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, fields);
return this.gregorianWeek.getNumberFromWeek (myFields.weekYear, myFields.weekNumber, myFields.weekday) * Milliseconds.DAY_UNIT
+ myFields.hours * Milliseconds.HOUR_UNIT + myFields.minutes * Milliseconds.MINUTE_UNIT
+ myFields.seconds * Milliseconds.SECOND_UNIT + myFields.milliseconds;
}
inLeapYear (fields) {
return Cbcce.isGregorianLeapYear ( fields.fullYear )
}
} |
JavaScript | class JulianCalendar {
constructor (id, pldr) { // specific name, possible pldr for kabyle or so
this.id = id;
this.pldr = pldr;
}
/* Julian conversion mechanism, using the "shifted" julian calendar : year is full Year, a relative number; year begin in March, months counted from 3 to 14
*/
julianClockwork = new Cbcce ({
timeepoch : -62162208000000, // 1 March of year 0, Julian calendar, relative to Posix epoch
coeff : [
{cyclelength : 126230400000, ceiling : Infinity, subCycleShift : 0, multiplier : 4, target : "fullYear"}, // Olympiade
{cyclelength : 31536000000, ceiling : 3, subCycleShift : 0, multiplier : 1, target : "fullYear"}, // One 365-days year
{cyclelength : 13219200000, ceiling : Infinity, subCycleShift : 0, multiplier : 5, target : "month"}, // Five-months cycle
{cyclelength : 5270400000, ceiling : Infinity, subCycleShift : 0, multiplier : 2, target : "month"}, // 61-days bimester
{cyclelength : 2678400000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "month"}, // 31-days month
{cyclelength : 86400000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "day"}, // Date in month
{cyclelength : 3600000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "hours"},
{cyclelength : 60000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "minutes"},
{cyclelength : 1000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "seconds"},
{cyclelength : 1, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "milliseconds"}
],
canvas : [
{name : "fullYear", init : 0},
{name : "month", init : 3}, // Shifted year begins with month number 3 (March) and goes to month 14 (February of next tradional year)
{name : "day", init : 1},
{name : "hours", init : 0},
{name : "minutes", init : 0},
{name : "seconds", init : 0},
{name : "milliseconds", init : 0},
]
}) // end of calendRule
julianWeek = new WeekClock (
{ // ISO8601 rule applied to Julian calendar
originWeekday: 4, // Use day part of Posix timestamp, week of day of ISO 1970-01-01 is Thursday
daysInYear: (year) => (Cbcce.isJulianLeapYear( year ) ? 366 : 365), // leap year rule for this calendar
characDayIndex: (year) => ( Math.floor(this.counterFromFields({fullYear : year, month : 1, day : 4})/Milliseconds.DAY_UNIT) ),
startOfWeek : 1, // week start with 1 (Monday)
characWeekNumber : 1, // we have a week 1 and the characteristic day for this week is 4 January.
dayBase : 1, // use 1..7 display for weekday
weekBase : 1, // number of week begins with 1
weekLength : 7
}
)
/** Era codes: "BC" for backwards counted years before year 1, "AD" (Anno Domini) for years since Dionysos era.
*/
eras = ["BC", "AD"] // may be given other codes, the codes are purely external, only indexes are used
canvas = "gregory"
stringFormat = "fields" // prepare string parts based on value of fields, not on values computed with base calendars
partsFormat = null // format each part exactly as if it were a canvas calendar date
shiftYearStart (dateFields, shift, base) { // Shift start of fullYear to March, or back to January, for calendrical calculations
let shiftedFields = {...dateFields};
[ shiftedFields.fullYear, shiftedFields.month ] = Cbcce.shiftCycle (dateFields.fullYear, dateFields.month, 12, shift, base ); //+ dateEnvironment.monthBase);
return shiftedFields
}
fields (theFields) { // List of fields. add "era" if "year" is present and "era" is not.
let myFields = [...theFields]; // a brand new Array
if (myFields.indexOf ("year") >= 0 && myFields.indexOf("era") == -1) myFields.unshift("era");
return myFields;
}
solveAskedFields (askedFields) {
var fields = {...askedFields};
if (fields.era != undefined) {
// compute value from deemed existing fields, throw if NaN
if (fields.year <= 0) throw new RangeError ('If era is defined, year shall be > 0: ' + fields.year);
let fullYear = fields.era == this.eras [0] ? 1 - fields.year : fields.year;
if (fields.fullYear == undefined) { fields.fullYear = fullYear }
else if (fields.fullYear != fullYear)
throw new RangeError ('Existing fullYear field inconsistent with era and year:' + fields.era + ', ' + fields.year + ', ' + fields.fullYear);
}
else {
if (fields.year != undefined && fields.fullYear != undefined)
{ if (fields.year != fields.fullYear) throw new TypeError ('Unconsistent year and fullYear fields: ' + fields.year + ', ' + fields.fullYear) }
else { if (fields.year != undefined) { fields.fullYear = fields.year } else if (fields.fullYear != undefined) fields.year = fields.fullYear }
}
return fields;
}
fieldsFromCounter (timeStamp) { // from a date, give the compound object of the calendar, unshifted to date in January
let myFields = this.shiftYearStart(this.julianClockwork.getObject(timeStamp),-2,3);
if (myFields.fullYear < 1) {
myFields.year = 1 - myFields.fullYear;
myFields.era = this.eras[0];
} else {
myFields.year = myFields.fullYear;
myFields.era = this.eras[1];
}
return myFields
}
counterFromFields(fields) { // from the set of date fields, give time stamp. If no era specified, negative year is authorised
var myFields = { fullYear : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, this.solveAskedFields(fields));
switch (fields.era) {
case undefined: break;// year without era is fullYear
case this.eras[0]: case this.eras[1]:
if (fields.year < 1) throw new RangeError ("If era is specified, year shall be stricly positive: " + fields.year);
break;
default : throw new RangeError ("Invalid era value: " + fields.era); break;
}
return this.julianClockwork.getNumber(this.shiftYearStart(myFields,2,1));
}
buildDateFromFields (fields, construct = ExtDate) { // Construct an ExtDate object from the date in this calendar (deemed UTC)
let timeStamp = this.setCounterFromFields (fields);
return new construct (this, timeStamp)
}
weekFieldsFromCounter (timeStamp) { // week fields, from a timestamp deemed UTC
let year = this.fieldsFromCounter (timeStamp).fullYear,
myFigures = this.julianWeek.getWeekFigures (Math.floor(timeStamp/Milliseconds.DAY_UNIT), year);
return {weekYearOffset : myFigures[2], weekYear : year + myFigures[2], weekNumber : myFigures[0], weekday : myFigures[1], weeksInYear : myFigures[3]}
}
counterFromWeekFields (fields) { // Posix timestamp at UTC, from year, weekNumber, dayOfWeek and time
let myFields = { weekYear : 0, weekNumber : 1, weekday : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, fields);
return this.julianWeek.getNumberFromWeek (myFields.weekYear, myFields.weekNumber, myFields.weekday) * Milliseconds.DAY_UNIT
+ myFields.hours * Milliseconds.HOUR_UNIT + myFields.minutes * Milliseconds.MINUTE_UNIT
+ myFields.seconds * Milliseconds.SECOND_UNIT + myFields.milliseconds;
}
/* properties and other methods
*/
inLeapYear (fields) { //
return Cbcce.isJulianLeapYear(fields.fullYear)
}
} // end of calendar class |
JavaScript | class WesternCalendar {
constructor (id, switchingDate) {
this.id = id;
this.switchingDate = new Date(switchingDate); // first date where Gregorien calendar is used. switchingDate may be an ISO string
this.switchingDate.setUTCHours (0,0,0,0); // set to Oh UTC at switching date
if (this.switchingDate.valueOf() < Date.parse ("1582-10-15T00:00:00Z"))
throw new RangeError ("Switching date to Gregorian shall be not earlier than 1582-10-15: " + this.switchingDate.toISOString());
}
/** Era codes: "BC" for backwards counted years before year 1, "AS" (Ancien Style) for years since Dionysos era in Julian, "NS" (New Style) fot years in Gregorian.
*/
eras = ["BC", "AS", "NS"] // define before partsFormat in order to refer to it.
canvas = "gregory"
stringFormat = "fields" // formatting options differ from base calendars
// partsFormat = { era : { mode : "list", codes : this.eras, source : this.eras } } // by not defining this object, displayed eras are only BC and AD.
firstSwitchDate = new Date ("1582-10-15T00:00:00Z") // First date of A.S. or N.S. era
julianCalendar = new JulianCalendar (this.id)
gregorianCalendar = new GregorianCalendar (this.id)
solveAskedFields (askedFields) {
var fields = {...askedFields};
if (fields.era != undefined) {
// compute value from deemed existing fields, throw if NaN
if (fields.year <= 0) throw new RangeError ('If era is defined, year shall be > 0: ' + fields.year);
let fullYear = fields.era == this.eras [0] ? 1 - fields.year : fields.year;
if (fields.fullYear == undefined) { fields.fullYear = fullYear }
else if (fields.fullYear != fullYear)
throw new RangeError ('Existing fullYear field inconsistent with era and year:' + fields.era + ', ' + fields.year + ', ' + fields.fullYear);
}
else { // era is undefined -> leave it that way
if (fields.year != undefined && fields.fullYear != undefined)
{ if (fields.year != fields.fullYear) throw new TypeError ('Unconsistent year and fullYear fields: ' + fields.year + ', ' + fields.fullYear) }
else { if (fields.year != undefined) { fields.fullYear = fields.year } else if (fields.fullYear != undefined) fields.year = fields.fullYear }
}
return fields;
}
fieldsFromCounter (number) {
if (number < this.switchingDate.valueOf()) { // Julian calendar
var myFields = this.julianCalendar.fieldsFromCounter(number);
myFields.era = this.eras[this.julianCalendar.eras.indexOf(myFields.era)];
}
else {
let myDate = new Date (number);
var myFields = this.gregorianCalendar.fieldsFromCounter(number);
myFields.era = this.eras[2];
}
return myFields
}
counterFromFields(askedFields) { // given fields may be out of scope
var testDate, fields = { fullYear : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
fields = Object.assign (fields, this.solveAskedFields(askedFields));
switch (fields.era) {
case this.julianCalendar.eras[1] : // "A.D." weak indication, just year shall not be < 1, but similar to no indication at all
if (fields.year < 1) throw new RangeError ("If era is specified, year shall be stricly positive: " + fields.year);
case undefined: // here we have to guess. Oberve that year may be negative (astronomer's notation)
testDate = new Date (ExtDate.fullUTC(fields.year, fields.month, fields.day, fields.hours, fields.minutes, fields.seconds, fields.milliseconds));
if (testDate.valueOf() < this.switchingDate.valueOf()) // deemed Julian
return this.julianCalendar.counterFromFields(fields);
else return testDate.valueOf();
case this.eras[0]: case this.eras[1]: // Julian calendar, year field must be >=1
if (fields.year < 1) throw new RangeError ("If era is specified, year shall be stricly positive: " + fields.year);
fields.era = this.julianCalendar.eras[this.eras.indexOf(fields.era)] // set julianCalendar era code instead of this.
return this.julianCalendar.counterFromFields(fields);
case this.eras[2]: // Specified as New Style (Gregorian), but cannot be before 1582-10-15
if (fields.year < 1) throw new RangeError ("Era specified as Gregorian, year shall be stricly positive: " + fields.year);
testDate = new Date (ExtDate.fullUTC(fields.year, fields.month, fields.day, fields.hours, fields.minutes, fields.seconds, fields.milliseconds));
if (testDate.valueOf() < this.firstSwitchDate) throw new RangeError ("Gregorian era cannot match such date: " + testDate.toISOString());
return testDate.valueOf();
default : throw new RangeError ("Invalid era: " + fields.era);
}
}
buildDateFromFields (fields, construct = ExtDate) { // Construct an ExtDate object from the date in this calendar (deemed UTC)
let number = this.setCounterFromFields (fields);
return new construct (this, number)
}
weekFieldsFromCounter (timeStamp) {
if (timeStamp < this.switchingDate.valueOf())
return this.julianCalendar.weekFieldsFromCounter (timeStamp)
else return this.gregorianCalendar.weekFieldsFromCounter (timeStamp);
}
counterFromWeekFields (fields) {
let result = this.gregorianCalendar.counterFromWeekFields (fields);
if (result < this.switchingDate.valueOf()) result = this.julianCalendar.counterFromWeekFields (fields);
return result;
}
inLeapYear (fields) {
if (this.counterFromFields(fields) < this.switchingDate.valueOf()) return this.julianCalendar.inLeapYear(fields)
else return this.gregorianCalendar.inLeapYear (fields)
}
} // end of calendar class |
JavaScript | class FrenchRevCalendar {
constructor (id, pldr) {
this.id = id;
this.pldr = pldr;
}
/* Basic references
*/
canvas = "iso8601"
stringFormat = "fields"
/*
dayNames = ["primidi","duodi", "tridi", "quartidi", "quintidi", "sextidi", "septidi", "octidi", "nonidi", "décadi",
"jour de la Vertu", "jour du Génie", "jour du Travail", "jour de l'Opinion", "jour des Récompenses", "jour de la Révolution"]
monthNames = ["vendémiaire", "brumaire", "frimaire", "nivôse", "pluviôse", "ventôse", "germinal", "floréal", "prairial", "messidor", "thermidor", "fructidor","sans-culottides"]
eraNames = ["ère des Français"]
*/
/** One era code, "ef" for "ère des Français"
*/
eras = ["ef"] // list of code values for eras; one single era here.
partsFormat = {
// weekday: {mode : "list", source : this.dayNames}
weekday : { mode : "pldr",
key : i => i },
month : { mode : "pldr" }, // {mode : "list", source : this.monthNames},
year : {mode : "field" },
// era : {mode : "list", codes : this.eras, source : this.eraNames}
era : { mode : "pldr" }
}
frenchClockWork = new Cbcce ({ // To be used with a Unix timestamp in ms. Decompose into years, months, day, hours, minutes, seconds, ms
timeepoch : -6004454400000, // Unix timestamp of 3 10m 1779 00h00 UTC in ms, the origin for the algorithm
coeff : [
{cyclelength : 4039286400000, ceiling : Infinity, subCycleShift : 0, multiplier : 128, target : "year"}, // 128 (julian) years minus 1 day.
{cyclelength : 1041379200000, ceiling : 3, subCycleShift : -1, multiplier : 33, target : "year", notify : "inShortOctoCycle"}, // 33 years cycle. Last franciade is 5 years.
// The 33-years cycle contains 7 4-years franciades, and one 5-years.
// subCycleShift set to -1 means: if the 33-years is the last one of the 128-years cycle, i.e. number 3 starting from 0,
// then it turns into a 7 franciades cycle, the first 6 being 4-years, the 7th (instead of the 8th) is 5-years.
{cyclelength : 126230400000, ceiling : 7, subCycleShift : +1, multiplier : 4, target : "year", notify : "inLongFranciade"}, //The ordinary "Franciade" (4 years)
// Same principle as above: if franciade is the last one (#7 or #6 starting form #0) of upper cycle, then it is 5 years long instead of 4 years.
{cyclelength : 31536000000, ceiling : 3, subCycleShift : 0, multiplier : 1, target : "year", notify : "inSextileYear"}, //The ordinary year within the franciade
{cyclelength : 2592000000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "month"},
{cyclelength : 86400000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "day"},
{cyclelength : 3600000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "hours"},
{cyclelength : 60000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "minutes"},
{cyclelength : 1000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "seconds"},
{cyclelength : 1, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "milliseconds"}
],
canvas : [
{name : "year", init : -12},
{name : "month", init : 1},
{name : "day", init : 1},
{name : "hours", init : 0},
{name : "minutes", init : 0},
{name : "seconds", init : 0},
{name : "milliseconds", init : 0}
]
})
decade = new WeekClock (
{
originWeekday: 1, // Use day part of Posix timestamp, week of day of 1970-01-01 is Primidi (11 Nivôse 178)
daysInYear: (year) => (this.inLeapYear({ year : year, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 }) ? 366 : 365),
// leap year rule for this calendar
characDayIndex: (year) => ( Math.floor(this.counterFromFields({year : year, month : 1, day : 1})/Milliseconds.DAY_UNIT) ),
startOfWeek : 1, // week is decade, start with 1 (Primidi)
characWeekNumber : 1, // we have a decade 1 and the characteristic day for this first decade is 1 Vendémiaire.
dayBase : 1, // use 1..10 display for decade days
weekBase : 1, // number of decade begins with 1
weekLength : 10, // The length of week (decade) is 10 within a year.
weekReset : true, // decade cycle is reset to startOfWeek at at the beginning of each year
uncappedWeeks : [36] // sans-culottides days are assigned to last decade.
}
)
solveAskedFields (askedFields) {
var fields = {...askedFields};
if (fields.year != undefined && fields.fullYear != undefined)
{ if (fields.year != fields.fullYear) throw new TypeError ('Unconsistent year and fullYear fields: ' + fields.year + ', ' + fields.fullYear) }
else { if (fields.year != undefined) { fields.fullYear = fields.year } else if (fields.fullYear != undefined) fields.year = fields.fullYear };
return fields
}
counterFromFields (fields) {
let myFields = { year : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, this.solveAskedFields(fields));
return this.frenchClockWork.getNumber (myFields)
}
fieldsFromCounter (timeStamp) {
let fields = this.frenchClockWork.getObject (timeStamp);
fields.fullYear = fields.year; fields.era = this.eras[0];
return fields
}
weekFieldsFromCounter (timeStamp) { // week fields, from a timestamp deemed UTC
let year = this.frenchClockWork.getObject (timeStamp).year,
myFigures = this.decade.getWeekFigures (Math.floor(timeStamp/Milliseconds.DAY_UNIT), year);
return {weekYearOffset : myFigures[2], weekYear : year + myFigures[2], weekNumber : myFigures[0], weekday : myFigures[1], weeksInYear : myFigures[3]}
}
counterFromWeekFields (fields) { // Posix timestamp at UTC, from year, weekNumber, dayOfWeek and time
let myFields = { weekYear : 0, weekNumber : 1, weekday : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 };
myFields = Object.assign (myFields, fields);
return this.decade.getNumberFromWeek (myFields.weekYear, myFields.weekNumber, myFields.weekday) * Milliseconds.DAY_UNIT
+ myFields.hours * Milliseconds.HOUR_UNIT + myFields.minutes * Milliseconds.MINUTE_UNIT
+ myFields.seconds * Milliseconds.SECOND_UNIT + myFields.milliseconds;
}
inLeapYear (fields) {
let myFields = {...fields};
if (myFields.inSextileYear == undefined) myFields = this.frenchClockWork.getObject (this.frenchClockWork.getNumber (fields));
return myFields.inSextileYear
}
valid (fields) { // enforced at date expressed by those fields
let counter = this.counterFromFields (fields);
return counter >= -5594227200000 && counter < -5175360000000
}
} |
JavaScript | class DataLayers extends Component {
// init
constructor(props) {
super(props);
const { active, headers } = this.props;
this.state = {
active,
headers,
height: this.getHeight(),
};
}
// receive props
componentWillReceiveProps(nextProps) {
const { active, headers } = nextProps;
this.setState({
active,
headers,
});
}
// mount add resize listener
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
}
// unmount remove listener
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
// call update dimensions
updateDimensions = () => {
this.setState({
height: this.getHeight()
});
}
// getter for the table height
getHeight = () => {
if (this.props.getHeight) return this.props.getHeight();
return this.props.height;
}
// save click
handleSaveClick = (event) => {
this.props.onSave(this.state.headers);
}
// visibility click
handleVisibilityClick = (index) => {
const nextHeaders = this.state.headers;
nextHeaders[index].visible = !nextHeaders[index].visible;
this.setState({
headers: nextHeaders,
});
}
// close
handleClose = () => {
if (this.props.onClose) {
this.props.onClose();
return;
}
this.setState({
active: false,
});
}
// sort the item from the new headers
handleSort = (newHeaders) => {
const headers = newHeaders.map(header => {
return header.item;
});
this.setState({
headers,
});
}
renderVisibilityIcon = (visible) => {
let icon = <VisibilityIcon />
if (!visible) {
icon = <VisibilityOffIcon />
}
return (
icon
);
}
// render the list
renderList = () => {
let list = [];
this.state.headers.forEach((header, index) => {
const className = classNames({
'layers-row': true,
'fx-grd': true,
'visible': header.visible
});
const iconStyle = {
color: `#${header.iconColor}`,
};
const icon = (
<FontAwesomeIcon icon={header.icon} style={iconStyle} />
);
list.push({
content: (
<div className={className} key={index}>
<span className="drag-icon">
<MoreVertIcon />
</span>
<div className="col col-3 col-label">
{icon}
{header.label}
</div>
<div className="col col-3 col-key-name">
{header.path.replace('$._source.', '')}
</div>
<div className="col col-1 col-display">
<IconButton
aria-label="Toggle Visibility"
onClick={this.handleVisibilityClick.bind(null, index)}
index={index}
size="small"
>
{this.renderVisibilityIcon(header.visible)}
</IconButton>
</div>
</div>
),
item: header,
});
});
return list;
}
// main render method
render() {
const { height, active } = this.state;
const style = {
minHeight: height,
height,
maxHeight: height,
};
const className = classNames({
'data-layers': true,
'active': active,
});
const list = this.renderList();
const placeholder = (
<div className="placeholder"></div>
);
return (
<div className={className} style={style}>
<div className="layers-headers fx-grd">
<div className="col col-3 col-label">Label</div>
<div className="col col-3 col-key-name">Key Name</div>
<Button onClick={this.handleClose} className="col col-1 col-display close">Close</Button>
<Button onClick={this.handleSaveClick} className="col col-1 col-display save">Apply</Button>
</div>
<div className="layers-rows">
<DragSortableList items={list} placeholder={placeholder} onSort={this.handleSort} type="vertical" />
</div>
</div>
);
}
} |
JavaScript | class ServiceElementPrice {
/**
* Constructs a new <code>ServiceElementPrice</code>.
* @alias module:model/ServiceElementPrice
*/
constructor() {
ServiceElementPrice.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>ServiceElementPrice</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ServiceElementPrice} obj Optional instance to populate.
* @return {module:model/ServiceElementPrice} The populated <code>ServiceElementPrice</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ServiceElementPrice();
if (data.hasOwnProperty('oneTimePrice')) {
obj['oneTimePrice'] = ApiClient.convertToType(data['oneTimePrice'], 'String');
}
if (data.hasOwnProperty('periodicPrice')) {
obj['periodicPrice'] = ApiClient.convertToType(data['periodicPrice'], 'String');
}
if (data.hasOwnProperty('timePeriod')) {
obj['timePeriod'] = ApiClient.convertToType(data['timePeriod'], 'String');
}
if (data.hasOwnProperty('unitOfMeasure')) {
obj['unitOfMeasure'] = ApiClient.convertToType(data['unitOfMeasure'], 'String');
}
if (data.hasOwnProperty('includedQuantity')) {
obj['includedQuantity'] = ApiClient.convertToType(data['includedQuantity'], 'Number');
}
if (data.hasOwnProperty('additionalOneTimePrice')) {
obj['additionalOneTimePrice'] = ApiClient.convertToType(data['additionalOneTimePrice'], 'String');
}
if (data.hasOwnProperty('additionalPeriodicPrice')) {
obj['additionalPeriodicPrice'] = ApiClient.convertToType(data['additionalPeriodicPrice'], 'String');
}
if (data.hasOwnProperty('additionalQuantity')) {
obj['additionalQuantity'] = ApiClient.convertToType(data['additionalQuantity'], 'Number');
}
}
return obj;
}
} |
JavaScript | class Route {
constructor(baseURL, apiVersion, routePath, method='GET', options={}) {
this.rawPath = routePath
this.baseURL = baseURL
this.route = routeMatcher(`/api/${apiVersion}${routePath}`)
this.method = method
this.options = options
}
/**
* generates an absolute url string for this route, substituting in any
* given named variables (as defined by the route path) and adding on
* any given named parameters.
*
* @param {object} [variables] - named variables required by this route
* @param {object} [params] - named params to be added as url parameters
*
* @returns {string} an url string
*/
url = (variables, params) => {
const urlString = this.baseURL + this.route.stringify(variables)
return _isEmpty(params) ?
urlString :
`${urlString}?${QueryString.stringify(params)}`
}
} |
JavaScript | class Card extends GameObject {
/**
* Construct a card.
* @param {object} opts Options to use to create the card.
* @param {string} opts.text The card's text.
* @param {string} opts.font The font that this card should use.
* @param {string} opts.bgcolor The card's background color.
* @param {string} opts.fgcolor The card's foreground (text) color.
* @param {string} opts.expcode The expansion code to display on this card.
*/
constructor(opts) {
super(opts);
this.text = opts.text;
this.font = opts.font;
this.bgcolor = opts.bgcolor;
this.fgcolor = opts.fgcolor;
this.expcode = opts.expcode;
}
/**
* The text of the card.
* Blanks are denoted with a single underscore (_).
* @type {string}
*/
get text() {
return this._text;
}
// eslint-disable-next-line require-jsdoc
set text(value) {
if(!value) {
throw new CardError(this.__('errors.card.no-card-text'));
}
this._text = value;
}
/**
* The font this card will be displayed using.
* @type {string}
* @default Helvetica
*/
get font() {
return this._font;
}
// eslint-disable-next-line require-jsdoc
set font(value) {
this._font = value || 'Helvetica';
}
/**
* The background color to use when displaying this card.
* @type {string}
* @default #FFFFFF
*/
get bgcolor() {
return this._bgcolor;
}
// eslint-disable-next-line require-jsdoc
set bgcolor(value) {
this._bgcolor = value || '#FFFFFF';
}
/**
* The foreground (text) color to use when displaying this card.
* @type {string}
* @default #000000
*/
get fgcolor() {
return this._fgcolor;
}
// eslint-disable-next-line require-jsdoc
set fgcolor(value) {
this._fgcolor = value || '#000000';
}
/**
* The expansion code to display on this card.
* @type {string}
* @default
*/
get expcode() {
return this._expcode;
}
// eslint-disable-next-line require-jsdoc
set expcode(value) {
this._expcode = value || '';
}
} |
JavaScript | class DemoFuroUi5MessageStripDisplay extends FBP(LitElement) {
/**
* Themable Styles
* @private
* @return {CSSResult}
*/
static get styles() {
// language=CSS
return (
Theme.getThemeForComponent('DemoFuroUi5MessageStripDisplay') ||
css`
:host {
display: block;
height: 100%;
padding-right: var(--spacing);
}
:host([hidden]) {
display: none;
}
`
);
}
/**
*@private
*/
static get properties() {
return {};
}
/**
* @private
* @returns {TemplateResult}
*/
render() {
// eslint-disable-next-line lit/no-invalid-html
return html`
<furo-vertical-flex>
<div>
<h2>Demo furo-ui5-message-strip-display</h2>
</div>
<furo-demo-snippet flex>
<template>
<furo-ui5-message-strip-display autofocus></furo-ui5-message-strip-display>
</br>
<furo-ui5-message-strip
message="Static message from attribute ' message '"
ƒ-show-error="--staticError, --errorReady"
ƒ-show-information="--staticInformation, --informationReady"
ƒ-show-warning="--staticWarning, --warningReady"
ƒ-show-success="--staticSuccess, --successReady"
ƒ-show-grpc-localized-message="--grpcReady"
@-message-strip-closed="--closed"
></furo-ui5-message-strip>
<h4>Message strips with static message</h4>
<furo-ui5-button-bar>
<furo-ui5-button @-click="--staticError" design="Negative">show static error message</furo-ui5-button>
<furo-ui5-button @-click="--staticInformation" design="Informative">show static information message</furo-ui5-button>
<furo-ui5-button @-click="--staticWarning" design="Attention">show static warning message</furo-ui5-button>
<furo-ui5-button @-click="--staticSuccess" design="Positive">show static success message</furo-ui5-button>
</furo-ui5-button-bar>
<h4>Message strips with dynamic message</h4>
<notification-producer ƒ-get-information-message="--information"
@-information-msg-ready="--informationReady"
ƒ-get-error-message="--error"
@-error-msg-ready="--errorReady"
ƒ-get-success-message="--success"
@-success-msg-ready="--successReady"
ƒ-get-warning-message="--warning"
@-warning-msg-ready="--warningReady"
ƒ-get-grpc-status="--grpc"
@-grpc-status-ready="--grpcReady"></notification-producer>
<furo-ui5-button-bar>
<furo-ui5-button @-click="--error" design="Negative">show error message</furo-ui5-button>
<furo-ui5-button @-click="--information" design="Informative">show information message</furo-ui5-button>
<furo-ui5-button @-click="--warning" design="Attention">show warning message</furo-ui5-button>
<furo-ui5-button @-click="--success" design="Positive">show success message</furo-ui5-button>
</furo-ui5-button-bar>
<h4>Message strips with gRPC status</h4>
<furo-ui5-button-bar>
<furo-ui5-button @-click="--grpc" design="Emphasized">show grpc localized messages</furo-ui5-button>
</furo-ui5-button-bar>
</template>
</furo-demo-snippet>
</furo-vertical-flex>
`;
}
} |
JavaScript | class HomeScreen extends Component {
static propTypes = {
navigation: PropTypes.object.isRequired,
locations: PropTypes.array.isRequired,
loadLocations: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
tempLocation: null,
};
}
componentDidMount() {
this.props.loadLocations();
}
removeTempMarker = () => {
this.setState({
tempLocation: null
});
};
handlePressOnMap = (event) => {
const coordinate = event.nativeEvent.coordinate;
this.setState({
tempLocation: {
lng: coordinate.longitude,
lat: coordinate.latitude,
}
});
};
handlePressOnCallout = (location) => {
this.props.navigation.navigate('Details', { location });
};
handleOpenList = () => {
this.props.navigation.navigate('LocationsList');
};
handleAddNew = () => {
this.props.navigation.navigate('NewLocation', { coordinates: this.state.tempLocation });
this.removeTempMarker();
};
render() {
const initialRegion = {
latitude: -33.860178,
longitude: 151.212706,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
};
return (
<View style={styles.container}>
<Button
onPress={this.handleOpenList}
title="Open list"
/>
<MapView
provider={PROVIDER_GOOGLE}
initialRegion={initialRegion}
style={styles.maps}
onPress={this.handlePressOnMap}
onMarkerPress={this.removeTempMarker}
>
{this.props.locations.map(location => (
<MarkerComponent
key={location.name}
location={location}
onCalloutPress={this.handlePressOnCallout}
/>
))}
{this.renderTempLocation()}
</MapView>
<Button
onPress={this.handleAddNew}
title="Add"
disabled={!this.state.tempLocation}
/>
</View>
);
}
renderTempLocation = () => {
if (this.state.tempLocation) {
const coordinate = {
latitude: this.state.tempLocation.lat,
longitude: this.state.tempLocation.lng,
};
return (
<Marker
coordinate={coordinate}
pinColor={colors.tempMarker}
/>
);
}
return null;
}
} |
JavaScript | class GridProEditCheckbox extends Checkbox {
static get is() {
return 'vaadin-grid-pro-edit-checkbox';
}
} |
JavaScript | class App extends Component {
render() {
const personEnglish = {
avatar:
'https://es.gravatar.com/userimage/19167007/631baacc80a5219a3ad17eee332cbe4e.jpg?size=700',
name: 'Santiago Mendoza',
profession: 'Software Engineer',
bio:
'Frontend Developer at Yuxi Global. Christian. Passionate about God, Digital Marketing and Personal Finances.',
address: 'Cartagena, Colombia.',
email: '[email protected]',
social: [
{
name: 'facebook',
url: 'https://facebook.com/SantiagoMendozaOficial'
},
{ name: 'twitter', url: 'https://twitter.com/sanmen1593' },
{ name: 'github', url: 'https://github.com/santimendoza' },
{
name: 'linkedin',
url: 'https://www.linkedin.com/in/santiagomendoza/'
}
],
experience: [
{
jobTitle: 'Frontend Developer',
company: 'Yuxi Global',
startDate: 'Jan 2021',
endDate: 'Present',
jobDescription: `Software Development using:
Node.js, React.js, Wordpress, MySQL, Git
Following Scrum framework`
},
{
jobTitle: 'Software Engineer',
company: 'Condor Labs',
startDate: 'Jan 2017',
endDate: 'Dec 2020',
jobDescription: `Software Development using:
Node.js, React.js, Oracle, MongoDB, ElasticSearch, Git, Github.
Following Scrum framework`
},
{
jobTitle: 'Tech Leader',
company: 'Universidad Tecnológica de Bolívar',
startDate: 'Jul 2015',
endDate: 'Dec 2016',
jobDescription: `Linux SysAdm. Web-apps development using JavaScript, HTML5, CSS3, JavaScript, PHP, and Frameworks like Laravel and AngularJS.
LMS Moodle Support and administration.`
},
{
jobTitle: 'Systems Engineering Practitioner',
company: 'Intertug',
startDate: 'Dec 2014',
endDate: 'Jun 2015',
jobDescription: `A Tracking Web-app development. Scripts development for remote Raspberries administration and maintenance.`
},
{
jobTitle: 'Teacher',
company: 'Interlat',
startDate: 'Apr 2016',
endDate: 'Nov 2016',
jobDescription: `Teacher of the course SEO: Search Engine Optimization of the Diploma in Digital Marketing of Interlat in agreement with the Universidad Pontificia Bolivariana.`
}
],
education: [
{
degree: 'Minor, Cloud Computing Infrastructure',
institution: 'Universidad Tecnológica de Bolívar',
startDate: '2014',
endDate: '2014',
description: `Server Administration. Virtualization. Networking.`
},
{
degree: 'Systems Engineer',
institution: 'Universidad Tecnológica de Bolívar',
startDate: 'Feb 2011',
endDate: 'Oct 2015',
description: `Algorithm Monitor 2P-2014.
Student Representative to the Curricular Committee of Systems Engineering 2014 - 2015`
}
],
courses: [
{
name: 'Learn and Understand NodeJS',
institution: 'Udemy',
date: 'Jan 2017',
tags: 'javascript, nodejs, backend, fullstack',
description:
'Dive deep under the hood of NodeJS. Learn V8, Express, the MEAN stack, core Javascript concepts, and more.'
},
{
name: 'ES6 for Everyone',
institution: 'WesBos',
date: 'Aug 2017',
tags: 'javascript, frontend, backend, fullstack',
description: 'Modern JavaScript'
},
{
name: 'Modern React with Redux',
institution: 'Udemy',
date: 'Jan 2017',
tags: 'javascript, react, redux, frontend, fullstack',
description:
'Master the fundamentals of React and Redux with this tutorial as you develop apps supported by NPM, Webpack, and ES6'
},
{
name: 'M101JS: MongoDB for Node.js Developers',
institution: 'MongoDB University',
date: 'May 2017',
tags: 'mongodb, javascript, nodejs, backend, fullstack',
description:
'Learn everything you need to know to get started building a MongoDB-based app.'
},
{
name: 'Fundamentos en la gestion de proyectos',
institution: 'Platzi',
date: 'Mar 2018',
tags: 'project-management',
description:
'Understand how to manage successful projects following the PMI methodology'
},
{
name: 'Introducción a las metodologías ágiles',
institution: 'Platzi',
date: 'Apr 2018',
tags: 'project-management',
description: ''
},
{
name: 'Finanzas Personales',
institution: 'Platzi',
date: 'Mar 2018',
tags: 'finances',
description: ''
},
{
name: 'Liderazgo Empresarial',
institution: 'TAB University',
date: 'Aug 2017',
tags: 'leadership',
description:
'Know the personality type and bring the whole team through the change curve.'
},
{
name: 'Writing for the web',
institution: 'Open2Study',
date: 'Sep 2017',
tags: 'blogging, digital marketing, seo',
description:
'Explore how writing style, web design and structure can grab the attention of and engage online readers.'
},
{
name: 'LFS101x.2 Introduction to Linux',
institution: 'EdX',
date: 'Feb 2015',
tags: 'linux, sysadm',
description: ''
},
{
name: 'Inbound Certified',
institution: 'HubSpot',
date: 'Mar 2017 - May 2019',
tags: 'digital marketing',
description: 'Inbound Marketing Certification'
},
{
name: 'Carrera de Administración de Servidores y DevOps',
institution: 'Platzi',
date: 'Mar 2016 - Mar 2017',
tags: 'sysadm, devops',
description: ''
},
{
name: 'Curso básico de Marketing Digital',
institution: 'IAB Spain',
date: 'Jul 2014',
tags: 'digital marketing',
description: ''
},
{
name: 'Academia de Obreros',
institution: 'Iglesia Cristiana Rios De Vida',
date: 'Apr 2014',
tags: 'christian',
description: ''
},
{
name: 'Academia Avanzada',
institution: 'Iglesia Cristiana Rios De Vida',
date: 'Nov 2015',
tags: 'christian',
description: ''
},
{
name: 'FrontEnd Developer',
institution: 'Platzi',
date: 'Jan 2015',
tags: 'javascript, frontend, fullstack',
description: ''
},
{
name: 'Backend Developer',
institution: 'Platzi',
date: 'Jan 2016',
tags: 'backend, fullstack, php',
description: ''
},
{
name: 'Diploma in Management in Cloud Technologies for Companies',
institution: 'Unipymes',
date: 'Apr 2015',
tags: 'sysadm, devops',
description: '30 hours'
}
]
// skills: [
// { name: 'HTML5', percentage: '95%' },
// { name: 'CSS', percentage: '90%' },
// { name: 'JavaScript', percentage: '75%' },
// { name: 'PHP', percentage: '50%' }
// ]
};
return (
<header>
<div className="wrapper">
<div className="sidebar">
<About
avatar={personEnglish.avatar}
name={personEnglish.name}
profession={personEnglish.profession}
bio={personEnglish.bio}
address={personEnglish.address}
social={personEnglish.social}
email={personEnglish.email}
/>
</div>
<div className="content-wrapper">
<div className="content">
<Experience experience={personEnglish.experience} />
<Education education={personEnglish.education} />
<Course courses={personEnglish.courses} />
{/*<Skills skills={personEnglish.skills} />*/}
</div>
</div>
</div>
</header>
);
}
} |
JavaScript | class WeatherData {
constructor(temp, current, date, iconData) {
this.temp = temp;
this.wind = current.wind_speed;
this.humidity = current.humidity;
this.uvi = current.uvi;
this.date = this.formatDate(date);
this.icon = `${iconData.icon}.png`;
this.iconDescription = iconData.description;
}
formatDate(date) {
if (date instanceof moment) {
return date.format(DATE_FORMAT);
} else {
return moment(date).format(DATE_FORMAT);
}
}
} |
JavaScript | class BeepCmdLeaf {
constructor(line) {
line = line.split(' ');
for(let i = 0; i < line.length; i++){
if(line[i].startsWith('$')){
let name = line[i].substring(1);
if(definedVars[name] !== undefined) {
line[i] = definedVars[name];
} else {
throw 'Parse encountered an undefined variable with the name "' + name + '"';
}
}
}
this.reps = 1;
this.delay = 100;
this.delayAfterLast = false;
this.freq = 440;
this.len = 200;
line = line.filter(function (el) {
return el.trim().length > 0;
});
let out = [];
for(let i = 0; i < line.length; i ++){
if(line[i].startsWith('-') && line[i].length > 2){
out.push(line[i].substring(0, 2));
out.push(line[i].substring(2));
} else {
out.push(line[i]);
}
}
out.push('null');
for(let i = 0; i < out.length - 1; i += 2){
switch(out[i]){
case '-f':
this.freq = parseFloat(out[i+1]);
break;
case '-v':
i--; // This flag takes no args
bootstrap_alert.info('web-beep version 0 and should be interoperable with latest beep');
break;
case '-h':
i--; // This flag takes no args
bootstrap_alert.info('See <a href="https://linux.die.net/man/1/beep">the man page</a> for help.');
break;
case '-l':
this.len = parseInt(out[i+1]);
break;
case '-r':
this.reps = parseInt(out[i+1]);
break;
case '-d':
this.delayAfterLast = false;
this.delay = parseInt(out[i+1]);
break;
case '-D':
this.delayAfterLast = true;
this.delay = parseInt(out[i+1]);
break;
default:
throw 'Undefined flag for beep with name"' + out[i] + '"';
}
}
}
play() {
if(this.reps === 0){ // 0 reps we just return
return Promise.resolve();
}
return new Promise(resolve => {
this.reps--;
resolve(this.playOnce(this.reps > 0 || this.delayAfterLast).then(() => {
return this.play()
}));
});
}
playOnce(shouldDelay){
return new Promise((resolve => {
console.log(this);
synth.triggerAttackRelease(this.freq, this.len / 1000);
setTimeout(() => {
resolve();
}, this.len + (shouldDelay ? this.delay : 0))
}));
}
} |
JavaScript | class CopyResourcesTask extends IncrementalFileTask {
/**
* Constructs a new processing task.
*
* @param {Object} options Configuration object for this task.
* @param {String} [options.name='copy-resources'] Name for the task.
* @param {String} options.incrementalDirectory Path to a folder where incremental task data will be stored.
* @param {Map<string,FileInfo>} options.files Map of input files to file info
* @param {Object} [options.logger] The logger instance used by this task.
* @param {Object} options.builder Builder instance.
*/
constructor(options) {
options.name = options.name || 'copy-resources';
options.inputFiles = [];
options.files.forEach((info, _file) => options.inputFiles.push(info.src));
super(options);
this.files = options.files;
this.builder = options.builder;
this.platform = this.builder.cli.argv.platform;
if (this.platform === 'ios') {
this.forceCleanBuildPropertyName = 'forceCleanBuild';
this.symlinkFiles = this.builder.symlinkFilesOnCopy; // NOTE: That this is always false!
// We also would check this regexp below, but since symlinking was always false, it was useless to do that
// const unsymlinkableFileRegExp = /^Default.*\.png|.+\.(otf|ttf)$/;
} else {
this.forceCleanBuildPropertyName = 'forceRebuild';
this.symlinkFiles = process.platform !== 'win32' && this.builder.config.get('android.symlinkResources', true);
}
}
/**
* Function that will be called after the task run finished.
*
* Used to tell iOS build not to wipe our incremental state files
*/
async afterTaskAction() {
await super.afterTaskAction();
// don't let iOS build delete our incremental state files!
this.builder.unmarkBuildDirFiles(this.incrementalDirectory);
// don't let iOS build delete any of the output files
this.files.forEach((info, _file) => this.builder.unmarkBuildDirFile(info.dest));
}
/**
* List or files that this task generates
*
* Each path will passed to {@link #ChangeManager#monitorOutputPath|ChangeManager.monitorOutputPath}
* to determine if the output files of a task have changed.
*
* @return {Array.<String>}
*/
get incrementalOutputs() {
const outputFiles = [];
this.files.forEach((info, _file) => outputFiles.push(info.dest));
return outputFiles;
}
/**
* Override to define the action on a full task run
*
* @return {Promise}
*/
doFullTaskRun() {
return Promise.all(Array.from(this.inputFiles).map(filePath => limit(() => this.processFile(filePath))));
}
/**
* Override to define the action on an incremental task run
*
* @param {Map.<String, String>} changedFiles Map of changed files and their state (created, changed, deleted)
* @return {Promise}
*/
doIncrementalTaskRun(changedFiles) {
if (this.requiresFullBuild()) {
return this.doFullTaskRun();
}
const deletedFiles = this.filterFilesByStatus(changedFiles, 'deleted');
const deletedPromise = Promise.all(deletedFiles.map(filePath => limit(() => this.handleDeletedFile(filePath))));
const updatedFiles = this.filterFilesByStatus(changedFiles, [ 'created', 'changed' ]);
const updatedPromise = Promise.all(updatedFiles.map(filePath => limit(() => this.processFile(filePath))));
return Promise.all([ deletedPromise, updatedPromise ]);
}
/**
* Performs some sanity checks if we can safely perform an incremental build
* or need to fallback to a full build.
*
* @return {Boolean} True if a full build is required, false if not.
*/
requiresFullBuild() {
if (this.builder[this.forceCleanBuildPropertyName]) {
this.logger.trace('Full build required, force clean build flag is set.');
return true;
}
return false;
}
/**
* Filters the given map of changed files for specific states and returns a
* list of matchings paths.
*
* @param {Map<String, String>} changedFiles Map of changed file paths and their state
* @param {String|String[]} states Single state string or array of states to filter
* @return {Array<String>}
*/
filterFilesByStatus(changedFiles, states) {
states = Array.isArray(states) ? states : [ states ];
const filteredFiles = [];
changedFiles.forEach((fileState, filePath) => {
if (states.includes(fileState)) {
filteredFiles.push(filePath);
}
});
return filteredFiles;
}
/**
* Handle deleted input file
*
* @param {String} filePathAndName Full path to the deleted file
* @return {Promise<void>}
*/
async handleDeletedFile(filePathAndName) {
this.logger.info(`DELETED ${filePathAndName}`);
// FIXME: If the file is deleted, how do we know the destination path to remove?
// Either we need to track the src -> dest map ourselves, or appc-tasks needs to supply the last output state so we can find the matching file somehow
// i.e. same sha/size?
const relativePathKey = this.resolveRelativePath(filePathAndName);
const info = this.files.get(relativePathKey);
if (info) {
this.logger.debug(`Removing ${info.dest.cyan}`);
this.files.delete(relativePathKey);
return fs.remove(info.dest);
}
}
/**
* Resolves the given full path to a relative path under it will be available in the app.
*
* @param {String} fullPath Full path used to resolve the relative path.
* @param {Map<string,FileInfo>} [files=this.files] Optional lookup object. Defaults to this.files.
* @return {String}
*/
resolveRelativePath(fullPath, files) {
files = files || this.files;
for (let [ key, value ] of files) {
if (value.src === fullPath) {
return key;
}
}
return null;
}
/**
* Processes a single file by copying it to
* its destination path.
*
* @param {String} filePathAndName Full path to the file
* @return {Promise}
*/
async processFile(filePathAndName) {
const file = this.resolveRelativePath(filePathAndName);
if (!file) {
throw new Error(`Unable to resolve relative path for ${filePathAndName}.`);
}
const info = this.files.get(file);
// NOTE: That we used to fire a build.platform.copyResource for each file
// - but that ultimately iOS never did fire it
// - we don't use it for hyperloop anymore so no need for Android to do so
return this.copyFile(info);
}
/**
* Note that this is a heavily modified async rewrite of Builder.copyFileSync from node-titanium-sdk!
* @param {FileInfo} info information about the file being copied
*/
async copyFile(info) {
const dest = info.dest;
const src = info.src;
// iOS specific logic here!
if (this.platform === 'ios' && this.builder.useAppThinning && info.isImage && !this.builder.forceRebuild) {
this.logger.info(__('Forcing rebuild: image was updated, recompiling asset catalog'));
this.builder.forceRebuild = true;
}
const exists = await fs.exists(dest);
if (!exists) {
const parent = path.dirname(dest);
await fs.ensureDir(parent);
}
// copy files
if (!this.symlinkFiles) {
if (exists) {
this.logger.debug(__('Overwriting %s => %s', src.cyan, dest.cyan));
await fs.unlink(dest);
} else {
this.logger.debug(__('Copying %s => %s', src.cyan, dest.cyan));
}
return fs.copyFile(src, dest);
}
// Try to symlink files!
// destination doesn't exist or symbolic link isn't pointing at src
if (!exists) {
this.logger.debug(__('Symlinking %s => %s', src.cyan, dest.cyan));
return fs.symlink(src, dest);
}
const symlinkOutdated = (await fs.realpath(dest)) !== src;
// I don't think we need to check if it's a symbolic link first, do we?
// const symlinkOutdated = (fs.lstatSync(dest).isSymbolicLink() && fs.realpathSync(dest) !== src);
if (symlinkOutdated) {
await fs.unlink(dest);
this.logger.debug(__('Symlinking %s => %s', src.cyan, dest.cyan));
return fs.symlink(src, dest);
}
}
} |
JavaScript | class AuthenticationError extends BaseError {
/**
* Creates a new AuthenticationError.
*
* @param {string} message - The error message.
* @param {Error} inner - An optional error that caused the AuthenticationError.
*/
constructor(message, inner) {
super(message, inner);
this.name = 'AuthenticationError';
this.status = 401;
this.statusCode = 401;
}
} |
JavaScript | class FailoverProvider extends FXProvider_1.FXProvider {
constructor(config) {
super(config);
this.providers = config.providers;
}
get name() {
return 'Failover Provider';
}
supportsPair(pair) {
return promises_1.tryUntil(this.providers, (provider) => {
return provider.supportsPair(pair);
});
}
downloadCurrentRate(pair) {
return promises_1.tryUntil(this.providers, (provider) => {
return provider.fetchCurrentRate(pair).then((result) => {
return result && result.rate && result.rate.isFinite() ? result : false;
}).catch(() => {
return false;
});
}).then((result) => {
if (result === false) {
return Promise.reject(new FXProvider_1.EFXRateUnavailable(`None of the providers could offer a rate for ${FXProvider_1.pairAsString(pair)}`, this.name));
}
return Promise.resolve(result);
});
}
} |
JavaScript | class Matrix {
/**
* Creates a new Matrix instance.
*
* @param array sources
* @param string|array namespace
* @param function getter
* @param MatrixInterface carry
*
* @return this
*/
constructor(sources, namespace, getter, carry = null) {
this.sources = _arrFrom(sources);
this.namespace = _arrFrom(namespace);
this.getter = getter;
this.carry = carry;
this.collections = {};
this.value;
}
/**
* Enters into a sub collection if exists.
*
* @param string name
*
* @return MatrixInterface
*/
enter(name) {
if (!(name in this.collections)) {
this.collections[name] = new Matrix(
this.sources,
this.namespace.concat(name),
this.getter,
this
);
}
return this.collections[name];
}
/**
* Leaves the current current collection into the super collection if exists.
*
* @return MatrixInterface
*/
leave() {
return this.carry;
}
/**
* Lazy-loads a property from sources.
*
* @return mixed
*/
get() {
if (!this.value) {
var namespace = this.namespace.slice();
var value = this.carry ? this.carry.get() : null;
this.sources.forEach((source, i) => {
if (value = this.getter.call(null, source, namespace, value, i)) {
this.value = value;
}
});
}
return this.value;
}
/**
* Finds the most-specific module for the given namespace from sources.
*
* @param sting namespace
*
* @return object
*/
find(namespace) {
var nsArray = namespace.split('/');
var subMatrix, nsKey, nsDrill = this;
while((nsKey = nsArray.shift()) && (nsDrill = nsDrill.enter(nsKey))) {
subMatrix = nsDrill;
}
// Clone now...
var el = subMatrix.get();
if (el) {
return el.cloneNode(true);
}
}
} |
JavaScript | class Treemap extends Visualization{
constructor(parentElement, settings){
super(parentElement, settings);
this.name = "Treemap";
}
_putDefaultSettings(){
this.settings.labelVAlign = "top";
this.settings.labelHAlign = "left";
this.settings.paddingTopHierarchies = 15;
this.settings.paddingBottomHierarchies = 2;
this.settings.paddingLeftHierarchies = 2;
this.settings.paddingRightHierarchies = 2;
this.settings.paddingTop = this.settings.paddingBottom
= this.settings.paddingLeft = this.settings.paddingRight = 20;
}
resize(){
_makeHierarchy.call(this, this.d_h);
this.redraw();
return this;
}
data(d){
super.data(d);
for(let k of this.keys){
if(this.domainType[k] === "Categorical"){
}
if(this.domainType[k] === "Numeric"){
console.log(this.domain[k]);
let values= [];
for (let i = 0; i <d.length ; i++) {
values.push(d[i][k]);
}
values = [...new Set(values)];
this.domain[k] = values;
}
if(this.domainType[k] === "Time"){
}
}
if(this.settings.hierarchies){
_hierarchy.call(this, this.settings.hierarchies);
}else{
let root = {_name_:"root", children: d};
if(this.settings.size){
let size = this.settings.size;
this.d_h = d3.hierarchy(root).sum(function(d) {return d[size]}).sort(function(a, b) { return b.height - a.height || b.value - a.value; });
}else{
this.d_h = d3.hierarchy(root).count();
}
}
_makeHierarchy.call(this, this.d_h);
this.d_parents = [];
this.d_h.each((d) => {
if(d.height !== 0)
this.d_parents.push(d);
});
}
redraw(){
//let t0 = performance.now();
let treemap = this;
console.log("th",this.d_h);
let updateParents = this.foreground
.selectAll(".data-parent")
.data(this.d_parents);
updateParents.exit().remove();
let enterParents = updateParents.enter()
.append("g")
.attr("class", "data-parent")
.attr('id', d=>d.data._name_)
;
let rectEnter = enterParents.append("rect")
.style("fill", "gray")
.style("stroke", "black")
.style("stroke-width", "0.5px");
treemap._bindDataMouseEvents(rectEnter, "ancestor");
enterParents.append("text")
.style("fill", "black")
.style("font-family", "monospace");
let mergeParents = enterParents.merge(updateParents)
.attr("transform", (d)=>{return "translate("+d.x0+","+d.y0+")";});
mergeParents.select("rect")
.attr("width", (d)=>{return d.x1 - d.x0;})
.attr("height", (d)=>{return d.y1 - d.y0;});
mergeParents.select("text")
.text((d)=>{return d.data._name_;})
.attr("x", 2)
.attr("y", function(){ return this.getBoundingClientRect().height - 3; });
let updateSelection = this.foreground.selectAll(".data")
.data(this.d_h.leaves());
updateSelection.exit().remove();
let enterSelection = updateSelection.enter().append("rect")
.attr("class", "data")
.attr("data-index", function(d, i){return i; })
.attr("parent",d=>d._name_)
.style("fill", this.settings.color)
.style("stroke", "black")
.style("stroke-width", "0.5px");
this._bindDataMouseEvents(enterSelection);
enterSelection.merge(updateSelection)
.attr('parent', d=>d.parent.data._name_)
.attr("x", (d)=>{return d.x0;})
.attr("y", (d)=>{return d.y0;})
.style("fill", this.settings.color)
.attr("width", (d)=>{return d.x1 - d.x0;})
.attr("height", (d)=>{return d.y1 - d.y0;});
let foreground = this.foreground
foreground.selectAll('rect.data').attr('parent', d=>d.parent.data._name_)
.each(function(){
let rect = d3.select(this)
.attr("x", (d)=>{return d.x0;})
.attr("y", (d)=>{return d.y0;}).remove()
let parentName = rect.attr("parent")
foreground.append(()=>
rect.node()
)
})
if(this.settings.label) {
console.log(this.settings.label);
_setLabel.call(this, this.settings.label);
}
//let t1 = performance.now();
//console.log("TIme: "+(t1-t0));
return super.redraw();
}
detail(...args){
let details;
let dataItens = this.d_h.leaves();
let obj = Object.entries(args[0].data);
let text = "";
for (let j = 0; j < args[2].length; j++) {
for (let i = 0; i < obj.length; i++) {
if(args[2][j]===obj[i][0]){
text+= obj[i][0]+" : "+ obj[i][1]+"\n";
}
}
}
if(args[0] instanceof SVGElement){
}else if(typeof args[1] === "number" && args[1] >= 0 && args[1] < dataItens.length){
let d = dataItens[args[1]];
this.annotations.selectAll("rect.data-details").remove();
details = this.annotations.append("rect")
.attr("class", "data-details")
.attr("x", d.x0)
.attr("y", d.y0)
.attr("width", d.x1 - d.x0)
.attr("height", d.y1 - d.y0)
.style("fill","white")
.attr("opacity",0.1)
.style("stroke", this.settings.highlightColorColor)
.append(":title")
.text(text);
}
}
highlight(...args){
let highlighted;
let dataItens = this.d_h.leaves();
if(args[0] instanceof SVGElement){
}else if(typeof args[1] === "number" && args[1] >= 0 && args[1] < dataItens.length){
let d = dataItens[args[1]];
this.highlightLayer.selectAll("rect.data-highlight").remove();
highlighted = this.highlightLayer.append("rect")
.attr("class", "data-highlight")
.attr("x", d.x0)
.attr("y", d.y0)
.attr("width", d.x1 - d.x0)
.attr("height", d.y1 - d.y0)
.style("fill", "none")
.style("stroke", this.settings.highlightColor);
}
if(highlighted)
super.highlight(highlighted.nodes(), args[0], args[1], args[2]);
}
removeHighlight(...args){
if(typeof args[1] === "number" && args[1] >= 0 && args[1] < this.d.length){
this.highlightLayer.selectAll("rect.data-highlight").remove();
super.removeHighlight(this.foreground
.select('rect.data[data-index="'+args[1]+'"]').node(),
this.d[args[1]], args[1]);
}
}
getHighlightElement(i){
let d = this.d_h.children[i];
let group = document.createElementNS("http://www.w3.org/2000/svg", "g");
d3.select(group).attr("class", "groupHighlight");
let rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
d3.select(rect)
.attr("class", "rectHighlight")
.attr("x", d.x0)
.attr("y", d.y0)
.attr("width", d.x1 - d.x0)
.attr("height", d.y1 - d.y0)
.style("fill", "none")
.style("stroke", this.settings.highlightColor);
group.appendChild(rect);
return group;
}
select(selection){
if(Array.isArray(selection)){
//selection[0]
}
}
setSize(attrs){
this.settings.size = attrs;
}
hierarchy(attrs){
this.settings.hierarchies = attrs;
if(this.domain)
_hierarchy.call(this, attrs);
return this;
}
setLabel(func){
this.settings.label = func;
return this;
}
} |
JavaScript | class ConfigurationRepository {
constructor({ log, ssmRepository, secretsRepository }) {
ac.assertFunction(ssmRepository.getParameter, argName({ ssmRepository }))
ac.assertFunction(
secretsRepository.getSecret,
argName({ secretsRepository })
)
this._log = log.child({ class: argName({ ConfigurationRepository }) })
this._ssmRepository = ssmRepository
this._secretsRepository = secretsRepository
}
_getValue(configurationRequest) {
if (configurationRequest.type === ConfigurationRequestTypes.local) {
return configurationRequest.key
}
if (configurationRequest.type === ConfigurationRequestTypes.secret) {
return this._secretsRepository.getSecret(configurationRequest.key)
}
if (configurationRequest.type === ConfigurationRequestTypes.ssm) {
return this._ssmRepository.getParameter(configurationRequest.key)
}
throw new Error(
`Unsupported ConfigurationRequestTypes ${configurationRequest.type}`
)
}
async _handlerConfigurationRequest(configurationRequest) {
const log = this._log.child({
meta: {
key: configurationRequest.key,
propertyName: configurationRequest.propertyName,
type: configurationRequest.type
}
})
try {
log.info('start: _handlerConfigurationRequest')
const value = await this._getValue(configurationRequest)
log.debug('end: _handlerConfigurationRequest')
return {
propertyName: configurationRequest.propertyName,
value: configurationRequest.adapter(value)
}
} catch (err) {
log.error({ err }, 'fail: _handlerConfigurationRequest')
throw err
}
}
/**
* Get a configuration object based on a provided array of configuration requests
*
* @param {Array<ConfigurationRequest>} arrayOfConfigurationRequests
* @returns {object} - An object with properties based on the ConfigurationRequest objects provided and values of the adapter configuration responses
*/
async getConfiguration(arrayOfConfigurationRequests) {
try {
this._log.info('start: getConfiguration')
validateConfigurationRequests(arrayOfConfigurationRequests)
const allRequests = arrayOfConfigurationRequests.map(
this._handlerConfigurationRequest.bind(this)
)
const configuration = {}
const allResponses = await Promise.all(allRequests)
allResponses.forEach((response) => {
configuration[response.propertyName] = response.value
})
this._log.debug('end: getConfiguration')
return configuration
} catch (err) {
this._log.error({ err }, 'fail: getConfiguration')
throw err
}
}
} |
JavaScript | class MemoryCache {
static instance = null;
static tdmap = {
's': 1,
'm': 60,
'h': 3600,
'd': 86400
};
constructor() {
// singleton
if (MemoryCache.instance) {
return MemoryCache.instance;
}
MemoryCache.instance = this;
this._storage = new Map();
setInterval(() => this._cleanOutdated(), 600 * 1000); // every 10min
return MemoryCache.instance;
}
_cleanOutdated() {
const now = new Date().getTime();
for (const [key, value] of this._storage.entries()) {
if (value.expire < now) {
this.delete(key);
}
}
}
static keyFromArgs(...args) {
return args.join();
}
get(key, default_ = null) {
if (!this._storage.has(key)) {
return default_;
}
const item = this._storage.get(key);
if (item.expire < new Date().getTime()) {
return default_;
}
return item.data;
}
set(key, data, valid) {
let expire = parseInt(valid.slice(0, -1));
expire *= MemoryCache.tdmap[valid.slice(-1)];
expire *= 1000; // ms
expire += new Date().getTime();
this._storage.set(key, {
data,
expire
});
}
delete(key) {
if (this._storage.has(key)) {
this._storage.delete(key);
}
}
clear() {
this._storage.clear();
}
} |
JavaScript | class FakeString {
constructor(gen){
if (typeof(gen) === 'function'){
this.gen = gen();
this.buffer = '';
}
else {
this.setLoop(gen);
}
}
setLoop(content){
this.buffer = '';
this[0] = undefined;
this.gen = (function* (){
while (true) {
yield content;
}
})();
}
requireMore(){
var next = this.gen.next();
if (!next.done) {
this.buffer = this.buffer + next.value;
}
this[0] = this.buffer[0];
}
checkLen() {
if (this.buffer.trim().length == 0){
this.requireMore();
}
}
get length() {
this.checkLen();
return this.buffer.length;
}
indexOf(s){
this.checkLen();
return this.buffer.indexOf(s);
}
substr(s, e){
this.checkLen();
if (e === undefined){
this.buffer = this.buffer.substr(s);
//this.checkLen();
this[0] = this.buffer[0];
return this;
}
else{
return this.buffer.substr(s, e);
}
}
replace(src, target){
this.checkLen();
this.buffer = this.buffer.replace(src, target);
//this.checkLen();
this[0] = this.buffer[0];
return this;
}
match(s){
this.checkLen();
return this.buffer.match(s);
}
} |
JavaScript | class OrderStatusUpdateElement {
/**
* Constructs a new <code>OrderStatusUpdateElement</code>.
* @alias module:models/OrderStatusUpdateElement
* @class
*/
constructor() {
/**
*
* @member {String} code
*/
this.code = undefined
/**
*
* @member {String} status
*/
this.status = undefined
/**
*
* @member {String} baseSiteId
*/
this.baseSiteId = undefined
}
/**
* Constructs a <code>OrderStatusUpdateElement</code> from a plain
* JavaScript object, optionally creating a new instance. Copies all relevant
* properties from <code>data</code> to <code>obj</code> if supplied or a new
* instance if not.
* @param {Object} data The plain JavaScript object bearing properties of
* interest.
* @param {module:models/OrderStatusUpdateElement} obj Optional instance
* to populate.
* @return {module:models/OrderStatusUpdateElement} The populated
* <code>OrderStatusUpdateElement</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new OrderStatusUpdateElement()
if (data.hasOwnProperty('code')) {
obj.code = ApiClient.convertToType(data.code, 'String')
}
if (data.hasOwnProperty('status')) {
obj.status = ApiClient.convertToType(data.status, 'String')
}
if (data.hasOwnProperty('baseSiteId')) {
obj.baseSiteId = ApiClient.convertToType(data.baseSiteId, 'String')
}
}
return obj
}
} |
JavaScript | class AbstractScreen extends Component {
/**
*
*/
constructor(props) {
super(props);
this.state = {
loadingScreen: true,
loadingAction: false
}
}
/**
*
*/
initState = (newState) => {
this.state = {
...this.state,
...newState
}
}
/**
*
*/
loadFontsAsync = async () => {
await Font.loadAsync({
'Roboto': require("native-base/Fonts/Roboto.ttf"),
'Roboto_medium': require("native-base/Fonts/Roboto_medium.ttf"),
'Ionicons': require("@expo/vector-icons/fonts/Ionicons.ttf"),
'AntDesign': require("@expo/vector-icons/fonts/AntDesign.ttf")
});
}
/**
*
*/
isLoadingScreen = () => {
return this.state.loadingScreen;
}
/**
*
*/
setLoadingScreen = (flag) => {
this.setState({
loadingScreen: flag && flag === true
});
}
/**
*
*/
getProp = (name, defaultValue) => {
let result;
if (name) {
if (this.props) {
result = this.props[name];
}
if (result === undefined && this.props.navigation) {
result = this.props.navigation.getParam(name);
}
if (result === undefined && this.props.screenProps) {
result = this.props.screenProps[name];
}
}
if (result === undefined && defaultValue) {
result = defaultValue;
}
return result;
}
/**
*
*/
navigate = (route, params) => {
const navigation = this.getProp('navigation');
navigation.navigate(route, params);
}
} |
JavaScript | class ConfigStep extends AbstractWizardStep {
/**
* Constructor.
* @param {angular.$compile=} opt_compile Angular compile function
*/
constructor(opt_compile) {
super(opt_compile);
this.template = `<${stepUi}></${stepUi}>`;
this.title = 'Configuration';
}
/**
* @inheritDoc
*/
finalize(config) {
try {
config.updatePreview();
var features = config['preview'].slice(0, 24);
if ((!config['mappings'] || config['mappings'].length <= 0) && features && features.length > 0) {
// no mappings have been set yet, so try to auto detect them
var mm = MappingManager.getInstance();
var mappings = mm.autoDetect(features);
if (mappings && mappings.length > 0) {
config['mappings'] = mappings;
}
}
} catch (e) {
}
}
} |
JavaScript | class WheelsContainer {
constructor(defaultWheels) {
this.wheels = [];
this.wheelCount = 1;
this.rapWheel = new RecordWheel();
this.wheelsParentContainer = document.getElementById(
appReferences.wheelsContainer
);
this.numberOfWheelsSelect = document.getElementById(
appReferences.numOfWheels
);
this.initWheels(defaultWheels);
}
/**
* Initialize the wheels container with new wheels.
*
* @param {Object} opts Object containing an initial default state for the wheels.
*/
initWheels(opts) {
for (let i = 0; i < TOTAL_WHEEL_COUNT; i++) {
this.wheels.push(new Wheel(this.wheels.length));
this.wheelsParentContainer.appendChild(this.wheels[i].container);
}
//Add event listener to container: On change, update the number of wheels visible on the screen
this.numberOfWheelsSelect.addEventListener("change", (event) => {
rw.stopRhythm();
this.setVisibleWheelCount(event.target.value);
this.updateContainer();
});
// If given a wheel configuration, load it. Otherwise, just return.
if (typeof opts === "undefined") return;
this.setWheelConfiguration(opts);
}
/**
* Sets the wheels to a desired configuration on wheel container creation.
*
* (I kind of wanted to try something complicated, but this can probably be handled better ... )
* @param {object} opts Processes an object that includes an array of nodes strings (i.e hihat1, rest), and repeat value.
*
*/
setWheelConfiguration(opts) {
// First, get the wheels (max is three, might redo later...)
const { wheel1, wheel2, wheel3 } = opts;
// Then, set the visible wheels based on either the number of wheels in config, or the total wheel count.
// Whichever is lower.
this.setVisibleWheelCount(
Math.min(Object.keys(opts).length, TOTAL_WHEEL_COUNT)
);
// Update the container to make those changes.
this.updateContainer();
// Then, iterate through the wheels, setting the nodes and repeats for each.
for (let i = 0; i < this.wheelCount; i++) {
// Evaluate if the wheel exists, or just move on
let current = eval(`wheel${i + 1}`);
if (!current) continue;
// Set the number of beats based on the node array given in config
this.wheels[i].setNumOfBeats(current.nodes.length);
// Iterate through the nodes, setting each type of beat
for (let j = 0; j < current.nodes.length; j++) {
this.wheels[i].nodes[j].setNodeType(current.nodes[j]);
}
// Set the repeat count
this.wheels[i].setLoopCount(current.repeat);
}
}
/**
* Sets which wheels are visible based on the current wheel count.
*
* @param {integer} num The number of wheels to be shown
*/
setVisibleWheelCount(num) {
this.wheelCount = num;
this.wheelControlPanels = document.querySelectorAll(
`${appReferences.wheelControlsClass}:not(#recording-controls)`
);
// inactive wheels are just hidden
for (let i = 0; i < this.wheelCount; i++) {
this.wheels[i].container.style.display = "flex";
this.wheelControlPanels[i].style.display = "block";
}
console.log(this.wheelControlPanels);
for (let i = this.wheelCount; i < this.wheels.length; i++) {
this.wheels[i].container.style.display = "none";
this.wheelControlPanels[i].style.display = "none";
}
this.rapWheel.controlPanel.style.display =
globals.outgoingAudio == "" ? "none" : "block";
}
/**
* When called, update all wheels inside container
*/
updateContainer() {
// update the recorded audio Wheel
this.rapWheel.update();
for (let i = 0; i < this.wheels.length; i++) {
this.wheels[i].update();
}
}
} |
JavaScript | class Kanban {
constructor(root) {
this.root = root;
Kanban.columns().forEach(column => {
/* todo: create an instance of column class
- basically this means that we need to have a new javascript class to define the user interface for an individual column that is displayed to the user.
- this will be done by creating a new js file called Columns.js
*/
const columnView = new Column(column.id, column.title);
this.root.appendChild(columnView.elements.root);
});
}
static columns(){
return [
{
id: 1,
title: "Brain Board"
},
{
id: 2,
title: "Not Started"
},
{
id: 3,
title: "In Progress"
},
{
id: 4,
title: "Completed"
}
];
}
} |
JavaScript | class ScheduledMessageCard extends Component{
constructor(props) {
super(props);
this.state = {
collapse: false,
success: '',
message: {
id: '',
title: '',
to: '',
body: '',
approved: false,
date: '',
scheduled: true,
template: false,
sent: false,
group_id: '',
approved_text:'',
},
submitting: false,
error: false,
modal: true,
collapseScheduler: false,
};
this.toggleApprove = this.toggleApprove.bind(this);
this.toggle = this.toggle.bind(this);
this.toggleCal = this.toggleCal.bind(this);
this.toggleScheduler = this.toggleScheduler.bind(this);
this.toggleNested = this.toggleNested.bind(this);
this.toggleSuccess = this.toggleSuccess.bind(this);
this.toggleRemove = this.toggleRemove.bind(this);
}
toggle() {
this.setState(prevState => ({
modal: !prevState.modal,
}));
}
toggleCal() {
this.setState(state => ({ collapse: !state.collapse }));
}
toggleSuccess() {
this.setState(state => ({
success: '',
}));
}
toggleScheduler() {
this.setState(state => ({ collapseScheduler: !state.collapseScheduler }));
}
toggleNested() {
this.setState({
nestedModal: !this.state.nestedModal,
});
}
fetchReminder = id => {
axios
.get(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`)
.then(response => {
let approved_text;
if (response.data.approved) {
approved_text = "Scheduled to be sent "
} else if (!this.state.message.approved) {
approved_text = "Needs approval to be sent "
}
this.setState(() => ({ message:{
title: response.data.name,
to: response.data.phone_send,
body: response.data.description,
approved: response.data.approved,
date: response.data.scheduled_date,
scheduled: response.data.scheduled,
template: response.data.template,
sent: response.data.sent,
id:response.data.id,
approved_text: approved_text,
}}));
})
.catch(err => {
console.log(err)
});
}
componentDidMount() {
console.log(this)
const id = this.props.id
this.fetchReminder(id);
}
dateConverter = date => {
if (!date) {return `TBD`}
date = date.split(/\W+/);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
let yr = date[0];
let month = months[parseInt(date[1]) - 1];
let day = date[2];
let hr = date[3];
let min = date[4];
return `${month} ${day}, ${yr} ${hr}:${min}`
}
getProfile = (cb) => {
this.auth0.client.userInfo(this.accessToken, (err, profile) => {
if (profile) {
this.userProfile = profile;
this.userProfile.user_id = 1;
}
cb(err, profile);
});
}
handleChange = () => {
const id = this.props.id
const editObj ={approved:this.state.message.approved, scheduled_date: this.state.message.date};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({ message: response.data})
})
.catch(error => console.log(error))
}
toggleApprove(event) {
const id = this.props.id
const editObj ={approved:event.target.checked};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({success: 'Success!', message: response.data});
toast.info('Message approved.', {
position: "top-center",
autoClose: 2500,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
})
.catch(error => console.log(error))
if (this.state.success){
this.toggleSuccess()
}
}
onTemplate= (event) => {
const id = this.props.id
const editObj ={template:event.target.checked};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({success: 'Success!', message: response.data});
toast.info('Successfully saved to templates.', {
position: "top-center",
autoClose: 2500,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
})
.catch(error => console.log(error))
if (this.state.success){
this.toggleSuccess()
}
}
onDatePicker = (event) => {
const new_date = event
const date_format = moment(new_date).format('YYYY-MM-DD HH:mm:ss')
const id = this.props.id
const editObj ={scheduled_date:date_format};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({success: 'Success!', message: response.data});
this.props.group_reminders_call();
// this.fetchReminder(id);
})
.catch(error => console.log(error))
}
editReminder = id => {
console.log("editReminder ID", id)
const editObj ={name: this.state.message.title, description: this.state.message.body};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({ success: 'Success!', message: response.data})
this.fetchReminder(id);
})
.catch(error => console.log(error))
}
toggleRemove(event) {
console.log("DELETE", event.target)
const id = this.props.id
const editObj ={scheduled: false};
axios
.put(`${process.env.REACT_APP_BACKEND}/api/reminders/${id}`, editObj)
.then(response => {
console.log("PUT RESPONSE:", response.data)
this.setState({ message: response.data})
this.setState({success_delete: 'Success! The message will go "poof!" as soon as you leave this tab',})
this.fetchReminder(id);
toast.info('Successfully removed from scheduled.', {
position: "top-center",
autoClose: 2500,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
this.props.group_reminders_call();
})
.catch(err => {
console.log(err);
})
}
render(){
return (
<div className="schedule-card card bg-light mb-3">
<div className="message w-65" >
<div className = "card-header messagedetails">
<div className = "messagetitle">{this.props.title}</div>
<SchedMessageModal id={this.props.id} buttonLabel="Edit Group Message" isOpen={this.state.message}
toggle={this.toggle} group_reminders_call={this.props.group_reminders_call}> </SchedMessageModal>
</div>
<div className = "card-body">
<div className = "messagebody"><strong> Message to be sent: </strong> {this.props.message}</div>
<div className = "messagebody"> <strong> {this.state.message.approved_text} on:</strong> {this.dateConverter(this.props.date)}</div>
</div>
</div>
<div className = "card messageoptions">
<div className = "card-controls">
<Button color="link" onClick={this.toggleCal} > <strong>Edit Calendar</strong></Button>
<Collapse isOpen={this.state.collapse}>
<DayPickerInput className="calendar"
onDayChange={this.onDatePicker}
onDayMouseEnter={this.onDatePicker}
formatDate={formatDate}
parseDate={parseDate}
placeholder={`${formatDate(new Date())}`}/>
</Collapse>
<div className = "messagecheckboxes">
<FormGroup>
<Label inline="check">
<Input type="checkbox" onClick={this.toggleApprove} />
Approve
</Label>
</FormGroup>
<FormGroup>
<Label inline check>
<Input type="checkbox" onClick={this.onTemplate} />
Add to templates
</Label>
</FormGroup>
<FormGroup>
{/* <Label inline check> */}
<Button color="danger" onClick={this.toggleRemove}>Delete</Button>
{/* <Input type="checkbox" onClick={this.onDelete} /> */}
{/* Delete */}
{/* </Label> */}
</FormGroup>
<span><p>{this.state.success_delete}</p>
{/* <p>{this.state.success}</p> */}
</span>
</div>
</div>
</div>
</div>
);
};
} |
JavaScript | class Module {
constructor(app) {
}
} |
JavaScript | class VolumeSlider extends React.PureComponent {
// eslint-disable-line react/prefer-stateless-function
componentDidMount() {
this.closeMenuController = new CloseMenuFunctions(
this.ref,
this.props.onCloseFunction,
{ volume: 'volume' },
);
this.closeMenuController.onMenuMount();
}
componentWillReceiveProps(nextProps) {
if (
this.ref &&
nextProps.active &&
nextProps.active !== this.props.active
) {
this.closeMenuController.onMenuUnmount();
this.closeMenuController.onMenuMount();
}
}
componentWillUnmount() {
this.closeMenuController.onMenuUnmount();
}
setRef = (el) => (this.ref = el);
handleChange = (value) => {
this.props.updateVolume(value / 100 || 0);
};
get activeClassName() {
return this.props.activeClassNames || 'volume-slider-container active';
}
get inactiveClassName() {
return this.props.inactiveClassNames || 'volume-slider-container';
}
get railStyle() {
return this.props.railStyle || { backgroundColor: '#111', height: '2px' };
}
get trackStyle() {
return (
this.props.trackStyle || {
backgroundColor: Colors.sliderGreen,
height: '2px',
}
);
}
get handleStyle() {
return (
this.props.handleStyle || {
border: 'none',
backgroundColor: Colors.sliderGreen,
top: '4px',
}
);
}
render() {
const {
volume,
active,
vertical,
sliderClassName,
sliderContainerClassName,
} = this.props;
return (
<div
ref={this.setRef}
className={active ? this.activeClassName : this.inactiveClassName}
>
<div className={sliderContainerClassName || 'volume-slider'}>
<Slider
className={sliderClassName || 'slider'}
onChange={this.handleChange}
handleStyle={this.handleStyle}
railStyle={this.railStyle}
trackStyle={this.trackStyle}
defaultValue={volume * 100}
value={volume * 100}
vertical={vertical}
min={0}
max={100}
/>
</div>
</div>
);
}
} |
JavaScript | class Node {
constructor(value) {
this.value = value;
this.next = null;
}
} |
JavaScript | class Teleport {
constructor(map) {
this.map = map
}
} |
JavaScript | class Cards extends React.Component {
render() {
return (
<Col lg={this.props.data.size}>
<Card
className="card-lift--hover shadow border-0"
style={{
margin: "10px 0",
height: "100%",
backgroundImage: `url(${require("assets/img/theme/" +
this.props.data.img)})`,
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
backgroundPosition: "center center",
}}
>
<CardBody className="py-5">
<div className="icon icon-shape icon-shape-warning rounded-circle mb-4">
<i className="ni ni-planet" />
</div>
<h6 className="text-warning text-uppercase">Prepare Launch</h6>
<p className="description mt-3">
Argon is a great free UI package based
</p>
<div></div>
<Button
className="mt-4 btn-sm"
color="success"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
Learn more
</Button>
</CardBody>
</Card>
</Col>
);
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [], selectedVideo: null };
YTSearch({ key: API_KEY, term: 'surfboards'}, (videos) => {
this.setState({ videos: videos, selectedVideo: videos[0] });
});
}
render() {
return (
<div>
<SearchBar />
<VideoDetail video = {this.state.selectedVideo }/>
<VideoList
onVideoSelect = { selectedVideo => this.setState({ selectedVideo })}
videos = { this.state.videos } />
</div>
);
}
} |
JavaScript | class OverlayProvider extends LockedProvider {
/**
* @param writable The file system to write modified files to.
* @param readable The file system that initially populates this file system.
*/
constructor(writable, readable) {
super(new UnlockedOverlayProvider(writable, readable));
}
/**
* Constructs and initializes an OverlayProviderinstance with the given options.
*/
static Create(opts, cb) {
try {
const fs = new OverlayProvider(opts.writable, opts.readable);
fs._initialize((e) => {
cb(e, fs);
});
}
catch (e) {
cb(e);
}
}
static isAvailable() {
return UnlockedOverlayProvider.isAvailable();
}
getOverlayedProviders() {
return super.getFSUnlocked().getOverlayedProviders();
}
unwrap() {
return super.getFSUnlocked();
}
_initialize(cb) {
super.getFSUnlocked()._initialize(cb);
}
} |
JavaScript | class CarPhysicsBody {
constructor({
pos,
size,
speed = 0,
angle = 0,
steerAngle = toRadians(0),
maxSpeed = 3,
maxSteerAngle = toRadians(45),
}) {
this.pos = pos;
this.size = size;
// speed is scalar, velocity should be vector
this.speed = speed;
this.maxSpeed = maxSpeed;
// angle of whole car
this.angle = angle;
this.maxSteerAngle = maxSteerAngle;
// angle of front wheels
this.steerAngle = steerAngle;
// wheel / axles constants
this.wheelSize = getPreferredWheelSize(size);
this.wheelBase = size.h * 0.6; // disance between front axis and back axis
// mass center is center of car, relative to this
// point wheels positions are calculated
// todo: change it to no constant?
this.massCenter = vec2(size.w / 2, size.h / 2);
// array of wheels position added to mass center
this.wheels = this.getWheels();
}
/**
* Picks all corners of rotated rectangle,
* it is slow, many Math.sin() or Math.cos() calls,
* do not use it in rendering.
*
* @see
* CarIntersectRays::update()
*
* @returns {Vec2[]}
*/
get corners() {
const {size} = this;
return {
topLeft: this.createBodyRelativeVector({
x: -size.w / 2,
y: -size.h / 2,
}),
topRight: this.createBodyRelativeVector({
x: size.w / 2,
y: -size.h / 2,
}),
bottomLeft: this.createBodyRelativeVector({
x: -size.w / 2,
y: size.h / 2,
}),
bottomRight: this.createBodyRelativeVector({
x: size.w / 2,
y: size.h / 2,
}),
};
}
/**
* Returns array of connected together corners lines
*
* @returns {Line[]}
*/
get cornersLines() {
return extractRectCornersLines(this.corners);
}
/**
* Creates vector that is relative to center of car but
* coordinates are relative to root canvas size(not car)
*
* @see
* transforms local(relative to center car) coordinates to global coordinates
*
* @param {Vec2} v
*/
createBodyRelativeVector(v) {
const {pos, angle} = this;
return addVec2(
rotateVec2(
angle,
v,
),
pos,
);
}
/**
* Inverse of createBodyRelativeVector
*
* @see
* transforms global vector to body cebter relative vector
*
* @param {Vec2} v
*/
toBodyRelativeVector(v) {
const {pos, angle} = this;
return rotateVec2(
-angle,
subVec2(
v,
pos,
),
);
}
/**
* Creates new wheels based on whole car position
*
* @todo
* Optimize performance if its slow
*/
getWheels() {
const {
massCenter,
wheelBase,
steerAngle,
angle,
} = this;
return [
// front left
createWheel(
angle + steerAngle,
this.createBodyRelativeVector({
x: -massCenter.x,
y: -(wheelBase / 2),
}),
),
// front right
createWheel(
angle + steerAngle,
this.createBodyRelativeVector(
{
x: massCenter.x,
y: -(wheelBase / 2),
},
),
),
// back left
createWheel(
angle,
this.createBodyRelativeVector(
{
x: -massCenter.x,
y: (wheelBase / 2),
},
),
),
// back right
createWheel(
angle,
this.createBodyRelativeVector(
{
x: massCenter.x,
y: (wheelBase / 2),
},
),
),
];
}
update(delta) {
const {
wheels,
speed,
} = this;
// Math.PI / 2 - because wheels are rotated relative to landscape
// but they are really rectangles rotated -90*
const renderWheelAngle = Math.PI / 2;
// update wheels pos
for (let i = wheels.length - 1; i >= 0; --i) {
const wheel = wheels[i];
const velocity = scalarToVec2(
wheel.angle - renderWheelAngle,
speed * delta,
);
addVec2To(
velocity,
wheel.pos,
1,
);
}
this.pos = vec2Center(
wheels[0].pos,
wheels[3].pos,
);
// angle between points
const angle = angleBetweenPoints(wheels[0].pos, wheels[2].pos) - renderWheelAngle;
// angle
this.angleDelta = angle - this.angle;
this.angle = angle;
this.wheels = this.getWheels();
}
} |
JavaScript | class EzyHandshakeHandler {
/**
* Automatically call this function when client receives HANDSHAKE command
* from server.
* @param data [encryptedServerPublicKey, token, sessionId]
*/
handle(data) {
this.startPing();
this.handleLogin();
this.postHandle(data);
}
/**
* This function need to be manually defined to specify
* what to do after sending login request
* @param data: [encryptedServerPublicKey, token, sessionId]
*/
postHandle(data) {}
/**
* Send loginRequest to server
*/
handleLogin() {
var loginRequest = this.getLoginRequest();
this.client.sendRequest(Const.EzyCommand.LOGIN, loginRequest);
}
/**
* This function need to be manually defined to specify
* needed login information
* @returns [zonename, username, password, data]
*/
getLoginRequest() {
return ['test', 'test', 'test', []];
}
/**
* Start sending ping request
*/
startPing() {
this.client.pingSchedule.start();
}
} |
JavaScript | class EzyLoginSuccessHandler {
/**
* Automatically call this function when client receives LOGIN command
* from server
* @param data [zoneId, zoneName, userId, username, responseData=null]
*/
handle(data) {
var zoneId = data[0];
var zoneName = data[1];
var userId = data[2];
var username = data[3];
var responseData = data[4];
var zone = new Entity.EzyZone(this.client, zoneId, zoneName);
var user = new Entity.EzyUser(userId, username);
this.client.me = user;
this.client.zone = zone;
this.handleLoginSuccess(responseData);
Util.EzyLogger.console(
'user: ' + user.name + ' logged in successfully'
);
}
/**
* This function need to be manually defined to specify what to
* do after successful login
* @param responseData Additional data received from server
*/
handleLoginSuccess(responseData) {}
} |
JavaScript | class EzyLoginErrorHandler {
/**
* Automatically call this function when client receives LOGIN_ERROR command
* from server
* @param data [errorId, errorMessage]
*/
handle(data) {
this.client.disconnect(401);
this.handleLoginError(data);
}
/**
* This function need to be manually defined to specify what to
* do after unsuccessful login
* @param data [errorId, errorMessage]
*/
handleLoginError(data) {}
} |
JavaScript | class EzyAppAccessHandler {
/**
* Automatically call this function when client receives APP_ACCESS command
* from server
* @param data [appId, appName, data=[]]
*/
handle(data) {
var zone = this.client.zone;
var appManager = zone.appManager;
var app = this.newApp(zone, data);
appManager.addApp(app);
this.postHandle(app, data);
Util.EzyLogger.console('access app: ' + app.name + ' successfully');
}
/**
* Create an EzyApp entity for client
* @param zone {EzyZone}
* @param data {array} [appId, appName, data=[]]
* @returns {EzyApp} Created app
*/
newApp(zone, data) {
var appId = data[0];
var appName = data[1];
var app = new Entity.EzyApp(this.client, zone, appId, appName);
return app;
}
/**
* This function need to be manually defined to specify what to
* do after server allows client to access the app
* @param app {EzyApp} App has just been created
* @param data {array} [appId, appName, data=[]]
*/
postHandle(app, data) {}
} |
JavaScript | class EzyAppExitHandler {
/**
* Automatically call this function when client receives APP_EXIT command
* from server
* @param data {array} [appId, reasonId]
*/
handle(data) {
var zone = this.client.zone;
var appManager = zone.appManager;
var appId = data[0];
var reasonId = data[1];
var app = appManager.removeApp(appId);
if (app) {
this.postHandle(app, data);
Util.EzyLogger.console(
'user exit app: ' + app.name + ', reason: ' + reasonId
);
}
}
/**
* This function need to be manually defined to specify what to
* do after server allows client to access the app
* @param app {EzyApp} App has just been removed
* @param data {array} [appId, reasonId]
*/
postHandle(app, data) {}
} |
JavaScript | class EzyAppResponseHandler {
/**
* Automatically call this function when client receives APP_REQUEST command
* from server
* @param data {array} [appId, responseData=[command, commandData]]
*/
handle(data) {
var appId = data[0];
var responseData = data[1];
var cmd = responseData[0];
var commandData = responseData[1];
var app = this.client.getAppById(appId);
if (!app) {
Util.EzyLogger.console(
'receive message when has not joined app yet'
);
return;
}
var handler = app.getDataHandler(cmd);
if (handler) handler(app, commandData);
else
Util.EzyLogger.console(
'app: ' + app.name + ' has no handler for command: ' + cmd
);
}
} |
JavaScript | class EzyPluginResponseHandler {
/**
* Automatically call this function when client receives PLUGIN_REQUEST command
* from server
* @param data {array} [pluginId, responseData=[command, commandData]]
*/
handle(data) {
var pluginId = data[0];
var responseData = data[1];
var cmd = responseData[0];
var commandData = responseData[1];
var plugin = this.client.getPluginById(pluginId);
var handler = plugin.getDataHandler(cmd);
if (handler) handler(plugin, commandData);
else
Util.EzyLogger.console(
'plugin: ' + plugin.name + ' has no handler for command: ' + cmd
);
}
} |
JavaScript | class EzyDataHandlers {
/**
* @param client {EzyClient}
*/
constructor(client) {
this.handlers = {};
this.client = client;
this.pingSchedule = client.pingSchedule;
}
/**
* Map a handler to a specific command
* @param cmd {{name: string, id: number}}
* @param handler
*/
addHandler(cmd, handler) {
handler.client = this.client;
handler.pingSchedule = this.pingSchedule;
this.handlers[cmd.id] = handler;
}
/**
* Get a handle by command
* @param cmd {{name: string, id: number}}
* @returns {*}
*/
getHandler(cmd) {
var handler = this.handlers[cmd.id];
return handler;
}
} |
JavaScript | class EzyAppDataHandlers {
constructor() {
this.handlers = {};
}
/**
* Map a user-defined handler to a user-defined command
* @param cmd {string} User-defined command
* @param handler {function} User-defined handler
*/
addHandler(cmd, handler) {
this.handlers[cmd] = handler;
}
/**
* Get handler by command
* @param cmd {string}
* @returns {function}
*/
getHandler(cmd) {
var handler = this.handlers[cmd];
return handler;
}
} |
JavaScript | class EzyPluginDataHandlers {
constructor() {
this.handlers = {};
}
/**
* Map a user-defined handler to a user-defined command
* @param cmd {string} User-defined command
* @param handler {function} User-defined handler
*/
addHandler(cmd, handler) {
this.handlers[cmd] = handler;
}
/**
* Get handler by command
* @param cmd {string}
* @returns {function}
*/
getHandler(cmd) {
var handler = this.handlers[cmd];
return handler;
}
} |
JavaScript | class AboutController {
/*@ngInject*/
constructor($scope) {
this.$scope = $scope;
this._init_();
this._destroy_();
}
_init_() {}
_destroy_() {
this.$scope.$on('$destroy', function() {});
}
} |
JavaScript | class ToolBar extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.state = {
checkedList: this.props.device,
indeterminate: true,
checkAll: false
}
}
onChange(checkedList) {
const uid = this.props.areaUid;
checkedList.forEach((item) => {
this.props[`onGet${item}`](uid);
});
this.props.onChangeDevice(checkedList);
this.setState({
checkedList,
indeterminate: !!checkedList.length && (checkedList.length < plainOptions.length),
checkAll: checkedList.length === plainOptions.length,
});
}
render() {
return (
<div className="toolBar ibox-content" style={{ marginBottom: '10px' }}>
<CheckboxGroup options={plainOptions} defaultValue={this.props.device} onChange={this.onChange} />
</div>
);
}
} |
JavaScript | class Snake extends Actor {
/**
* Creates an instance of Snake.
*
* @param {World} world The world of the actor.
* @param {string} position The actor's position as a comma separated string.
* @memberof Snake
*/
constructor(world, position) {
super(world, position);
this.char = '𝐬';
this.name = 'Snake';
this.health = 2;
this.damage = 1;
this.speed = 2;
this.animal = true;
this.world.scheduler.add(this, true);
}
/**
* The function that determines the actor's next action. Called by the engine.
*
* @memberof Snake
*/
act() {
if (this.target &&
Math.abs(this.target[0] - this.x) < 2 &&
Math.abs(this.target[1] - this.y) < 2) {
this.moveToTarget();
}
}
/**
* Kills the actor.
*
* @param {boolean} hero
* @memberof Actor
*/
kill(hero) {
super.kill();
if (!hero) {
return;
}
this.world.scene.game.snakesound.play();
this.world.stats.kills.snake += 1;
this.world.stats.point += 4;
}
} |
JavaScript | class Button extends Component {
constructor(props, ...args){
super(props, ...args);
// Bind context to methods
this._getEvents = this._getEvent.bind(this);
this._getHTMLClasses = this._getHTMLClasses.bind(this);
}
render(){
return(
h('button', {
id: this.props.id,
"data-cell-id": this.props.id,
"data-cell-type": "Button",
class: this._getHTMLClasses(),
onclick: this._getEvent('onclick')
}, [this.getReplacementElementFor('contents')]
)
);
}
_getEvent(eventName) {
return this.props.extraData.events[eventName];
}
_getHTMLClasses(){
let classString = this.props.extraData.classes.join(" ");
// remember to trim the class string due to a maquette bug
return classString.trim();
}
} |
JavaScript | class Endpoint {
constructor (method = 'GET', url = '#', data = {}, headers = [], ...args) {
headers = (headers instanceof Array) ? headers : [headers];
this.method = method;
this.url = url;
this.data = data;
this.headers = headers;
this.args = Object.assign({}, ...args);
};
options(...additionalArgs) {
return Object.assign({
method: this.method,
url: this.url,
data: this.data,
headers: this.headers,
}, this.args, ...additionalArgs);
}
} |
JavaScript | class Switch extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
var views = this.props.views;
var state = this.props.currentView || this.props.defaultView || (Object.keys(this.props.views)[0]);
if(!views.hasOwnProperty(state))
state = this.props.defaultView;
if(!views.hasOwnProperty(state))
throw new Error('Unknown view state '+state+' not found in '+Object.keys(this.props.views)+'!');
var ret = this.props.$parser.parse(views[state], this.props.$context);
if(Array.isArray(ret))
ret = React.createElement('span',null, ret);
return ret;
}
} |
JavaScript | class Runner extends Component {
constructor( props ) {
super( props );
this.state = {};
}
componentDidMount() {
if ( this.props.active ) {
if ( this.props.interval ) {
this.intervalID = window.setInterval( this.props.onEvaluate, this.props.interval );
} else {
this.props.onEvaluate();
}
}
}
componentDidUpdate( prevProps ) {
if ( prevProps.active && !this.props.active ) {
if ( this.intervalID ) {
window.clearInterval( this.intervalID );
this.intervalID = null;
}
}
else if ( !prevProps.active && this.props.active ) {
if ( this.props.interval ) {
this.intervalID = window.setInterval( this.props.onEvaluate, this.props.interval );
} else {
this.props.onEvaluate();
}
}
}
componentWillUnmount() {
if ( this.intervalID ) {
window.clearInterval( this.intervalID );
}
}
render() {
return null;
}
} |
JavaScript | class VoteChart {
constructor() {
// data values for chart
this.chartData = [0, 0, 0];
// instantiate a new chart
this.chart = this.barChart();
}
// method to create a new chart
barChart() {
let context = document.getElementById("voteChart").getContext("2d");
return new Chart(context, {
type: "bar",
data: {
labels: ["Basketball", "Cricket", "Football"],
datasets: [
{
label: "Count",
data: this.chartData,
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)"
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)"
],
borderWidth: 1,
barPercentage: 0.4
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
}
// method to destroy and re-render chart with new values
updateChart(data) {
this.chart.destroy();
this.chartData = Object.values(data);
this.barChart();
}
} |
JavaScript | class Circle extends BaseShape {
/**
* Creates a new Circle shape
* @param {CircleOptions} [opts]
* @return {Circle}
*/
constructor(opts) {
super(opts)
this._radius = 10
if (typeof opts.radius !== "undefined") {
this.radius = opts.radius
}
AABox2d.initCenterExtents(this._aabox, Point2d.create(0, 0), [
this._radius,
this._radius
])
}
/**
* Sets the radius of the circle
* @param {number} radius Radius of circle in world-space coordinates
* @return {Circle} this
* @fires {Shape#geomChanged}
* @throws {Error} If radius is not a valid number
*/
set radius(radius) {
if (typeof radius !== "number") {
throw new Error("Radius must be a number")
}
if (radius !== this._radius) {
const prev = this._radius
this._radius = radius
this._geomDirty = true // dirty needs to be set before firing event
this.fire("changed:geom", {
attr: "radius",
prevVal: prev,
currVal: this._radius
})
}
return this
}
/**
* Gets the current radius of the circle
* @return {number}
*/
get radius() {
return this._radius
}
/**
* Gets the untransformed width/height of the circle
* @return {Vec2d} Width/height of the circle, untransformed
*/
getDimensions() {
const diameter = this.radius * 2
return [diameter, diameter]
}
/**
* Gets the untransformed width of the circle
* @return {number}
*/
get width() {
return this.radius * 2
}
/**
* Gets the untransformed height of the circle
* @return {number}
*/
get height() {
return this.radius * 2
}
/**
* Called when the bounding box requires updating
* @private
* @override
*/
_updateAABox() {
if (this._geomDirty || this._boundsOutOfDate) {
const pos = this._pos
const scale = this._scale
const rot = Math.DEG_TO_RAD * this._rotDeg
const cossqr = Math.pow(Math.cos(rot), 2)
const sinsqr = Math.pow(Math.sin(rot), 2)
const asqr = Math.pow(scale[0] * this._radius, 2)
const bsqr = Math.pow(scale[1] * this._radius, 2)
const A = Math.sqrt(bsqr * sinsqr + asqr * cossqr)
const B = Math.sqrt(asqr * sinsqr + bsqr * cossqr)
AABox2d.initCenterExtents(this._aabox, pos, [A, B])
this._geomDirty = false
this._boundsOutOfDate = false
}
}
/**
* Draws the circle using a 2d rendering context. Called by the BaseShape
* class
* @param {CanvasRenderingContext2d} ctx 2d rendering context
* @override
*/
_draw(ctx) {
// NOTE: CanvasRenderingContext2d::setTransform
// (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform)
// only has 32-bits of precision when doing matrix multiplication. If you need a higher level
// of precision, then this is going to be prone to instability.
// The only way to counter the inprecision is to draw the circle ourselves, probably by rendering
// a dynamic line-segmented circle, which is doable, but could be tricky to get the proper amount
// of resolution for the circle dynamically. So keeping the 32-bit precision for now.
ctx.setTransform(
this._fullXform[0],
this._fullXform[1],
this._fullXform[2],
this._fullXform[3],
this._fullXform[4],
this._fullXform[5]
)
ctx.arc(0, 0, this._radius, 0, Math.TWO_PI, false)
}
/**
* Called to convert the shape to a serializable JSON object
* @return {object}
* @override
*/
toJSON() {
return Object.assign(
{
type: "Circle", // NOTE: this much match the name of the class
radius: this.radius
},
super.toJSON()
)
}
} |
JavaScript | class WindowInterruptSource extends EventTargetInterruptSource {
constructor(events, options) {
super(window, events, options);
}
} |
JavaScript | class App extends React.Component {
state = {
};
constructor(props) {
super(props);
window.demo = this;
window.refs = this.refs;
window.rc = this.refs.rc;
}
get extraView(){
return (
<div className="extra">
EXTEA
</div>
)
}
render() {
return (
<div className="hello-react-scroll-x">
<ReactScrollX ref='rc' extra={this.extraView}>
{
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(item => {
return (
<div key={item} className="item">
<img src="http://placeholder.qiniudn.com/80x80" alt="" />
</div>
)
})
}
</ReactScrollX>
</div>
);
}
} |
JavaScript | class WorkerParentPostMessageStream extends BasePostMessageStream_1.BasePostMessageStream {
/**
* Creates a stream for communicating with a dedicated web worker.
*
* @param args.worker - The Web Worker to exchange messages with. The worker
* must instantiate a WorkerPostMessageStream.
*/
constructor({ worker }) {
if (!worker) {
throw new Error('Invalid input.');
}
super();
this._target = enums_1.DEDICATED_WORKER_NAME;
this._worker = worker;
this._worker.onmessage = this._onMessage.bind(this);
this._handshake();
}
_postMessage(data) {
this._worker.postMessage({
target: this._target,
data,
});
}
_onMessage(event) {
const message = event.data;
// validate message
if (typeof message !== 'object' || !message.data) {
return;
}
this._onData(message.data);
}
_destroy() {
this._worker.onmessage = null;
this._worker = null;
}
} |
JavaScript | class Route {
/** @param {string} path */
constructor(path) {
/** @type {string} */
this.path = path;
/** @type {?settings.Route} */
this.parent = null;
/** @type {number} */
this.depth = 0;
/**
* @type {boolean} Whether this route corresponds to a navigable
* dialog. Those routes don't belong to a "section".
*/
this.isNavigableDialog = false;
// Below are all legacy properties to provide compatibility with the old
// routing system.
/** @type {string} */
this.section = '';
}
/**
* Returns a new Route instance that's a child of this route.
* @param {string} path Extends this route's path if it doesn't contain a
* leading slash.
* @return {!settings.Route}
* @private
*/
createChild(path) {
assert(path);
// |path| extends this route's path if it doesn't have a leading slash.
// If it does have a leading slash, it's just set as the new route's URL.
const newUrl = path[0] == '/' ? path : `${this.path}/${path}`;
const route = new Route(newUrl);
route.parent = this;
route.section = this.section;
route.depth = this.depth + 1;
return route;
}
/**
* Returns a new Route instance that's a child section of this route.
* TODO(tommycli): Remove once we've obsoleted the concept of sections.
* @param {string} path
* @param {string} section
* @return {!settings.Route}
* @private
*/
createSection(path, section) {
const route = this.createChild(path);
route.section = section;
return route;
}
/**
* Returns the absolute path string for this Route, assuming this function
* has been called from within chrome://settings.
* @return {string}
*/
getAbsolutePath() {
return window.location.origin + this.path;
}
/**
* Returns true if this route matches or is an ancestor of the parameter.
* @param {!settings.Route} route
* @return {boolean}
*/
contains(route) {
for (let r = route; r != null; r = r.parent) {
if (this == r)
return true;
}
return false;
}
/**
* Returns true if this route is a subpage of a section.
* @return {boolean}
*/
isSubpage() {
return !!this.parent && !!this.section &&
this.parent.section == this.section;
}
} |
JavaScript | class GenGroup {
/**
*
* @param {GData[]} items
*/
constructor( items ){
this.items= items.filter( v=>!v.unique&&!v.noproc );
/**
* Data split/grouped by a variable/subcategory of the data
* @property {.<string,<string,Array>>} groupBy
*/
this.filterBy = {};
}
subgroup(){
}
/**
* Get a random item at or below the given level.
* @property {number} level - max item level.
* @property {(object)=>boolean} pred - optional filter predicate.
* @returns {GData}
*/
randBelow( max=1, pred) {
let levels = this.filterBy.level;
let st = 1 + Math.floor( Math.random()*max );
let lvl = st;
do {
let list = levels[lvl];
let it;
if ( list ) {
it = pred ? randWhere( list, pred ) : randElm( list );
if ( it ) return it;
}
if ( --lvl < 0 ) lvl = max;
} while ( lvl !== st );
return null;
}
/**
*
* @param {number} level
* @param {boolean} fallback - if item of given level not found,
* fall back to a lower level.
*/
randAt( level, fallback=true ) {
let levels = this.filterBy.level;
let a = levels[level];
if ( !a || a.length===0 ) {
return fallback ? this.randBelow(level-1) : null;
}
return randElm(a);
}
/**
* Get random item with no restriction.
* @returns {object}
*/
rand(){
if ( this.items.length === 0) return null;
return this.items[Math.floor(Math.random()*this.items.length)];
}
/**
* Get a filtered sublist.
* @param {string} filter - filter type 'level', 'biome' etc.
* @param {string} match - property value to match.
* @param {boolean} allowBlank - accept items with null value on property. e.g. biome:null
* @returns {Array}
*/
filtered( filter, match, allowBlank=false ) {
let f = this.filterBy[filter];
let res = f[match] || [];
if ( allowBlank && f.hasOwnProperty(BLANK_CATEGORY) ) return res.concat( f[BLANK_CATEGORY ] );
return res;
}
/**
* Get an array of categories under a filter.
* @param {string} filter
* @param {string|string[]} matches
* @param {boolean} allowBlank
* @returns {Array[]}
*/
getCategories( filter, matches, allowBlank ) {
const subs = this.filterBy[filter];
let res = [];
if ( subs === undefined ) return res;
if ( allowBlank && subs.hasOwnProperty(BLANK_CATEGORY)) res.push( subs[BLANK_CATEGORY]);
if ( typeof matches === 'string') {
if ( subs.hasOwnProperty(matches) ) res.push( subs[matches]);
} else if ( Array.isArray(matches)) {
for( let i = matches.length-1; i>= 0; i--) {
var sub = subs[matches[i] ];
if ( sub ) res.push(sub);
}
}
return res;
}
/**
* Get a random item from a filtered subcategory.
* @param {string} filter - level/biome, etc.
* @param {string} matches - valid property matches.
* @param {boolean} allowBlank - accept items with no prop value on filter. e.g. biome:null
*/
randBy( filter, matches, allowBlank=false ) {
var subs = this.filterBy[filter];
if ( subs === undefined ) return null;
if ( Array.isArray( matches ) ) {
return randFrom( this.getCategories(filter, matches, allowBlank) );
} else {
return randElm( this.filtered( filter, matches, allowBlank) );
}
}
/**
* Create a new named item category based on the 'prop' property
* of the items.
* @param {string} name - category name.
* @param {?string} prop - prop to sort on. defaults to name.
* @param {?string} [sortBy=level] property to sort filtered lists by.
*/
makeFilter( name, prop, sortBy='level') {
const group = this.filterBy[name] = {};
prop = prop || name;
for( let i = this.items.length-1; i>= 0; i-- ) {
var it = this.items[i];
var cat = it[prop] || BLANK_CATEGORY;
var list = group[ cat ];
if ( list === undefined ) {
group[ cat ] = [ it ];
} else {
list.push( it );
}
}
// sort all lists.
if ( sortBy && sortBy !== prop) {
for( let p in group ) {
propSort( group[p], sortBy );
}
}
}
} |
JavaScript | class ChartTitle extends ErrorHandler {
constructor(el) {
super();
this.el = el;
this.tooltip = new Tooltip('chart-title', el, function (d) {
return '<p>' + _.escape(d.label) + '</p>';
});
}
/**
* Renders chart titles
*
* @method render
* @returns {D3.Selection|D3.Transition.Transition} DOM element with chart titles
*/
render() {
const el = d3.select(this.el).select('.chart-title').node();
const width = el ? el.clientWidth : 0;
const height = el ? el.clientHeight : 0;
return d3.select(this.el).selectAll('.chart-title').call(this.draw(width, height));
};
/**
* Truncates chart title text
*
* @method truncate
* @param size {Number} Height or width of the HTML Element
* @returns {Function} Truncates text
*/
truncate(size) {
const self = this;
return function (selection) {
selection.each(function () {
const text = d3.select(this);
const n = text[0].length;
const maxWidth = size / n * 0.9;
const length = this.getComputedTextLength();
let str;
let avg;
let end;
if (length > maxWidth) {
str = text.text();
avg = length / str.length;
end = Math.floor(maxWidth / avg) - 5;
str = str.substr(0, end) + '...';
self.addMouseEvents(text);
return text.text(str);
}
return text.text();
});
};
};
/**
* Adds tooltip events on truncated chart titles
*
* @method addMouseEvents
* @param target {HTMLElement} DOM element to attach event listeners
* @returns {*} DOM element with event listeners attached
*/
addMouseEvents(target) {
if (this.tooltip) {
return target.call(this.tooltip.render());
}
};
/**
* Appends chart titles to the visualization
*
* @method draw
* @returns {Function} Appends chart titles to a D3 selection
*/
draw(width, height) {
const self = this;
return function (selection) {
selection.each(function () {
const div = d3.select(this);
const dataType = this.parentNode.__data__.rows ? 'rows' : 'columns';
const size = dataType === 'rows' ? height : width;
const txtHtOffset = 11;
self.validateWidthandHeight(width, height);
div.append('svg')
.attr('width', width)
.attr('height', height)
.append('text')
.attr('transform', function () {
if (dataType === 'rows') {
return 'translate(' + txtHtOffset + ',' + height / 2 + ')rotate(270)';
}
return 'translate(' + width / 2 + ',' + txtHtOffset + ')';
})
.attr('text-anchor', 'middle')
.text(function (d) {
return d.label;
});
// truncate long chart titles
div.selectAll('text')
.call(self.truncate(size));
});
};
};
} |
JavaScript | class qModal extends ViewModel {
@Property(String) animation = null;
@Property closeOnEsc = true;
@Property closeOnClick = true;
@Property disableScroll = true;
@Property(String) id;
render() {
return window.document.createComment('[modal]');
}
created() {
var slots = this.$slots;
if (!slots || !slots.default) throw new Error('<modal> requires a content!');
var self = this;
this.modal = new Modal('qute-modal-'+(modal_id++), slots.default, {
animation: this.animation,
closeOnEsc:this.closeOnEsc,
closeOnClick: this.closeOnClick,
disableScroll: this.disableScroll,
open: function(modal) {
self.onOpen && self.onOpen(modal);
self.emit("open", self);
},
close: function(modal) {
self.onClose && self.onClose(modal);
self.emit("close", self);
},
ready: function(modal) {
self.onReady && self.onReady(modal);
self.emit("ready", self);
},
action: function(action, target) {
self.onAction && self.onAction(action, target);
self.emit("action", {modal: self, name: action, target: target});
}
});
this.id && this.publish(this.id);
}
connected() {
window.document.body.appendChild(this.modal.el);
}
disconnected() {
window.document.body.removeChild(this.modal.el);
}
open(now) {
this.modal.open();
}
openAsync() {
var modal = this.modal;
window.setTimeout(function() {
modal.open();
}, 0);
}
close() {
this.modal.close();
}
get isOpen() {
return this.isOpen();
}
@Watch('animation')
onAnimationChanged(value) {
this.modal.animation(value);
return false;
}
@Watch('closeOnEsc')
onCloseOnExecChanged(value) {
this.modal.opts.closeOnEsc = !!value;
return false;
}
@Watch('closeOnClick')
onCloseOnClickChanged(value) {
this.modal.opts.closeOnClick = !!value;
return false;
}
@Watch('disableScroll')
onDisableScrollChanged(value) {
this.modal.opts.disableScroll = !!value;
return false;
}
element() {
return this.modal.el;
}
find(selector) {
return this.modal.el && this.modal.el.querySelector(selector);
}
} |
JavaScript | class Rover extends Container {
/**
* @param {Object} config The rover configuration
*/
constructor(config) {
super();
this._config = config;
/**
* @type {PIXI.Container}
* @public
*/
this.shield = null;
/**
* @type {PIXI.Container}
* @public
*/
this.vehicle = null;
/**
* @type {PIXI.Container}
* @public
*/
this.rocket = null;
/**
* @type {PIXI.Sprite}
* @public
*/
this._shadow = null;
/**
* @type {Boolean}
* @private
*/
this._animationIsPlaying = false;
/**
* @type {PIXI.Container}
* @private
*/
this._explosion = null;
this._init();
}
/**
* @private
*/
_init() {
this._createRoverVehicle();
this._createRoverShadow();
this._createRocket();
this._createShied();
this._createExplosion();
this._addEventListeners();
}
/**
* @private
*/
_createRoverVehicle() {
const vehicle = new Vehicle();
this.vehicle = vehicle;
this.addChild(this.vehicle);
}
/**
* @private
*/
_createRoverShadow() {
const shadow = new Sprite.from('roverShadow');
shadow.anchor.set(0.5);
shadow.y = 80;
this._shadow = shadow;
this.addChild(this._shadow);
}
/**
* @private
*/
_createRocket() {
const rocket = new Rocket(this._config.rocket);
rocket.pivot.x = rocket.width / 2;
rocket.pivot.y = rocket.height / 2;
rocket.x = -150;
rocket.y = -30;
rocket.alpha = 0;
this.rocket = rocket;
this.addChild(this.rocket);
}
/**
* @private
*/
_createShied() {
const shield = new Shield();
this.shield = shield;
this.addChild(this.shield);
}
/**
* @private
*/
_createExplosion() {
const explosion = new Explosion();
explosion.x = -10;
explosion.y = -65;
this._explosion = explosion;
this.addChild(this._explosion);
}
/**
* Rover explosion animation
* @public
*/
async explode() {
const tl = new gsap.timeline();
await tl.fromTo(
this.vehicle.scale,
{
x: '0.9',
y: '0.9',
},
{
x: '1.1',
y: '1.1',
duration: 0.08,
yoyo: true,
repeat: 10,
onComplete: () => this._hideRoverParts(),
}
);
Assets.sounds.roverExplosion.play();
this._explosion.play();
}
/**
* @private
*/
_hideRoverParts() {
this.vehicle.alpha = 0;
this.shield.alpha = 0;
this._shadow.alpha = 0;
}
/**
* @private
*/
_addEventListeners() {
this.rocket.on(Rocket.events.RESET, () => {
this.vehicle.toggleVehicleGlowFilter();
});
}
} |
JavaScript | class GameScene extends Phaser.Scene {
constructor() {
super('Game');
this.gameOver = false;
this.score = 0;
this.userName;
}
preload() {
// load images
this.load.image('logo', '../../assets/logo.png');
this.load.image('sky', '../../assets/sky.png');
this.load.image('ground', '../../assets/platform.png');
this.load.image('coin', '../../assets/coin.png');
this.load.image('bomb', '../../assets/bomb.png');
this.load.image('player', '../../assets/player.png');
this.load.html('userInput', '../../assets/inputUser.html');
}
create() {
this.add.image(0, 0, 'sky').setOrigin(0, 0);
this.createPlatforms();
this.createPlayer();
this.createCoin();
this.createBombs();
const style = { font: '20px Arial', fill: '#fff' };
this.scoreText = this.add.text(20, 20, `score: ${this.score}`, style);
this.arrow = this.input.keyboard.createCursorKeys();
this.gameOverText = this.add.text(400, 250, 'Game Over', { fontSize: '32px', fill: '#000' });
this.gameOverText.visible = false;
}
createPlatforms() {
this.platforms = this.physics.add.staticGroup();
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
}
createPlayer() {
this.player = this.physics.add.sprite(100, 450, 'player');
this.player.setBounce(0.2);
this.player.setCollideWorldBounds(true);
this.physics.add.collider(this.player, this.platforms);
}
createCoin() {
this.coin = this.physics.add.sprite(200, 450, 'coin');
this.physics.add.collider(this.coin, this.platforms);
this.coin.setBounce(0.2);
this.coin.setCollideWorldBounds(true);
}
createBombs() {
this.bombs = this.physics.add.group();
const bomb = this.bombs.create(200, 16, 'bomb');
bomb.setBounce(1);
bomb.setGravity(200);
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-300, 400), 20);
this.physics.add.collider(this.bombs, this.platforms);
this.physics.add.collider(this.player, this.bombs, this.hitBomb, null, this);
}
hitBomb(player) {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
this.gameOver = true;
this.gameOverText.visible = true;
this.inputForm();
this.uploadScore();
}
inputForm() {
this.userName = prompt('Enter your name:');
}
async uploadScore() {
const playerScore = {
user: this.userName,
score: this.score,
};
try {
const result = await fetch('https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/quDNZqIoDEWvWqkfQrOG/scores/', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(playerScore),
});
const apiresult = await result.json();
if (apiresult) {
this.scene.start('Score');
}
return apiresult;
// eslint-disable-next-line no-empty
} catch (error) {
}
return undefined;
}
update() {
if (this.physics.overlap(this.player, this.coin)) {
this.collect();
}
if (this.arrow.right.isDown) {
this.player.x += 3;
} else if (this.arrow.left.isDown) {
this.player.x -= 3;
}
if (this.arrow.down.isDown) {
this.player.y += 3;
} else if (this.arrow.up.isDown) {
this.player.y -= 3;
}
}
collect() {
this.coin.x = Phaser.Math.Between(100, 600);
this.coin.y = Phaser.Math.Between(100, 200);
this.score += 10;
this.scoreText.setText(`score: ${this.score}`);
}
} |
JavaScript | class ProxySession {
constructor(testName, clientAddress) {
this.testName = testName;
this.clientAddress = clientAddress;
this.recordedActivities = null;
this.activityIndex = 0;
this.replyIndex = 0;
this.startDate = Date();
}
response() {
const recordedActivity = this.recordedActivities[this.activityIndex];
const reply = recordedActivity.replies[this.replyIndex];
return reply.response;
}
reply() {
const recordedActivity = this.recordedActivities[this.activityIndex];
const reply = recordedActivity.replies[this.replyIndex];
return reply;
}
activity() {
return this.recordedActivities[this.activityIndex];
}
} |
JavaScript | class App extends Component {
// constructor is always called with props
constructor(props) {
super(props);
// Component level state, so App and SearchBar have their own states that solely belong to them uniquely (whenever we change searchbar state using search state, it only triggers a change on searchbar)
this.state = {
videos: [],
selectedVideo: null
}; // array because it will contain a list of videos/objects
// This is the default search, without it NOTHING ELSE will trigger
this.videoSearch('Swedish House Mafia');
}
// term is the user input string
// passing videoSearch down to SearchBar
videoSearch(term) {
// Instead of , function(data) {, use arrow function
// On rendering App, the list of videos length will very quickly flash '0' because this network request is not instantaneous
// YTSearch({key: API_KEY, term: 'Swedish House Mafia'}, (videos) => { this was originally used for searching a video with default term, now we are recreating it for user input
YTSearch({key: API_KEY, term: term}, (videos) => {
// console.log(data); // data changing over time is perfect for using state
// key of videos, value of data (the word data can be any word); whenever key and value is the same exact string, with ES6 you can use just the word once instead of ({ videos: videos })
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
// while YTSearch is firing, it will still attempt to render in the middle of it, which this.state.videos is receiving undefined until it completes, which gives an error
// some parent objects sometimes cant fetch information fast enough to satify needs of child object
render() {
// throttles videoSearch(term) to run once every 300ms
const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
// <SearchBar onSearchTermChange={term => this.videoSearch(term)} /> refactored with lodash above
// When searchbar calls on onSearchTermChange that will due so with term, and it will be sent with this.videoSearch to videoSearch function back above
// VideoList takes a video (selectedVideo) and defines it on App's state and updates App's state with new video; and passing onVideoSelect as a property to videolist, so videolist has a property on props
// <VideoDetail video={this.state.videos[0]} /> instead of this, we want to show currently selected but we will get stuck on loading, so we need to add to YTSearch function
// App is parent to VideoList, so we need to pass data from the parent component to the child (app to videolist)
// data can be passed with jsx property, also known as passing props (pass prop videos to VideoList)
// anytime app re renders, like when we setState on component, videoList will get the new list of videos
);
}
} |
JavaScript | class InlineResponse2005DataCouponTriggerLevel {
/**
* Constructs a new <code>InlineResponse2005DataCouponTriggerLevel</code>.
* Value ranges related to the coupon trigger level.
* @alias module:model/InlineResponse2005DataCouponTriggerLevel
*/
constructor() {
InlineResponse2005DataCouponTriggerLevel.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>InlineResponse2005DataCouponTriggerLevel</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/InlineResponse2005DataCouponTriggerLevel} obj Optional instance to populate.
* @return {module:model/InlineResponse2005DataCouponTriggerLevel} The populated <code>InlineResponse2005DataCouponTriggerLevel</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse2005DataCouponTriggerLevel();
if (data.hasOwnProperty('value')) {
obj['value'] = InlineResponse2005DataCouponTriggerLevelValue.constructFromObject(data['value']);
}
if (data.hasOwnProperty('distance')) {
obj['distance'] = InlineResponse2005DataCouponTriggerLevelDistance.constructFromObject(data['distance']);
}
if (data.hasOwnProperty('cashFlow')) {
obj['cashFlow'] = InlineResponse2005DataCapCashFlow.constructFromObject(data['cashFlow']);
}
}
return obj;
}
} |
JavaScript | class Generator {
// manager card
managerGenerator = (team) => {
return `
<div class="card">
<div class="cardHeader">
<h2> ${team.name} </h2>
<h3> Manager </h3>
</div>
<div class="cardBody">
<ul>
<li> <span> ID: </span> ${team.id} </li>
<li> <span> Email: </span> <a href="mailto:${team.email}">${team.email}</a> </li>
<li> <span> Office Number: </span> ${team.officeNumber} </li>
</ul>
</div>
</div>`;
};
// engineer card
engineerGenerator = (team) => {
return `
<div class="card">
<div class="cardHeader">
<h2> ${team.name} </h2>
<h3> Engineer </h3>
</div>
<div class="cardBody">
<ul>
<li> <span> ID: </span> ${team.id} </li>
<li> <span> Email: </span> <a href="mailto:${team.email}">${team.email}</a> </li>
<li> <span> Github: </span> <a target="_blank" href="https://github.com/${team.github}">${team.github}</a> </li>
</ul>
</div>
</div>`;
};
// intern card
internGenerator = (team) => {
return `
<div class="card">
<div class="cardHeader">
<h2> ${team.name} </h2>
<h3> Intern </h3>
</div>
<div class="cardBody">
<ul>
<li> <span> ID: </span> ${team.id} </li>
<li> <span> Email: </span> <a href="mailto:${team.email}">${team.email}</a> </li>
<li> <span> School: </span> ${team.school} </li>
</ul>
</div>
</div>`;
};
} |
JavaScript | class Stack {
constructor() {
this.items = [];
this.top = null;
}
getTop() {
if (this.items.length == 0) {
return null;
}
return this.top;
}
isEmpty() {
return this.items.length == 0;
}
size() {
return this.items.length;
}
push(element) {
this.items.push(element);
this.top = element;
}
pop() {
if (this.items.length !== 0) {
if (this.items.length == 1) {
this.top = null;
return this.items.pop();
} else {
this.top = this.items[this.items.length - 2];
return this.items.pop();
}
} else {
return null;
}
}
} |
JavaScript | class Mnemonic {
/**
* @param {cryptography.Mnemonic} mnemonic
* @hideconstructor
* @private
*/
constructor(mnemonic) {
this._mnemonic = mnemonic;
}
/**
* Returns a new random 24-word mnemonic from the BIP-39
* standard English word list.
*
* @returns {Promise<Mnemonic>}
*/
static async generate() {
return new Mnemonic(await cryptography.Mnemonic._generate(24));
}
/**
* Returns a new random 12-word mnemonic from the BIP-39
* standard English word list.
*
* @returns {Promise<Mnemonic>}
*/
static async generate12() {
return new Mnemonic(await cryptography.Mnemonic._generate(12));
}
/**
* Construct a mnemonic from a list of words. Handles 12, 22 (legacy), and 24 words.
*
* An exception of BadMnemonicError will be thrown if the mnemonic
* contains unknown words or fails the checksum. An invalid mnemonic
* can still be used to create private keys, the exception will
* contain the failing mnemonic in case you wish to ignore the
* validation error and continue.
*
* @param {string[]} words
* @throws {BadMnemonicError}
* @returns {Promise<Mnemonic>}
*/
static async fromWords(words) {
return new Mnemonic(await cryptography.Mnemonic.fromWords(words));
}
/**
* Recover a private key from this mnemonic phrase, with an
* optional passphrase.
*
* @param {string} [passphrase]
* @returns {Promise<PrivateKey>}
*/
async toPrivateKey(passphrase = "") {
if (CACHE.privateKeyConstructor == null) {
throw new Error("`PrivateKey` has not been loaded");
}
return CACHE.privateKeyConstructor(
await this._mnemonic.toPrivateKey(passphrase)
);
}
/**
* Recover a mnemonic phrase from a string, splitting on spaces. Handles 12, 22 (legacy), and 24 words.
*
* @param {string} mnemonic
* @returns {Promise<Mnemonic>}
*/
static async fromString(mnemonic) {
return new Mnemonic(await cryptography.Mnemonic.fromString(mnemonic));
}
/**
* @returns {Promise<PrivateKey>}
*/
async toLegacyPrivateKey() {
if (CACHE.privateKeyConstructor == null) {
throw new Error("`PrivateKey` has not been loaded");
}
return CACHE.privateKeyConstructor(
await this._mnemonic.toLegacyPrivateKey()
);
}
/**
* @returns {string}
*/
toString() {
return this._mnemonic.toString();
}
} |
JavaScript | class ThunderDiagnosticService extends Lightning.Component {
_construct() {
this.config = {
host: '127.0.0.1',
port: '9998'
}
this.device = []
try {
this.thunderJS = ThunderJS(this.config)
} catch (err) {
Log.error(err)
}
}
/**
* Function to call device Info thunder call
*/
_diagnostic() {
let diagObj = this;
console.log('Enter diagnostics');
return new Promise(function (resolve, reject) {
diagObj.thunderJS.call('DeviceInfo', 'systeminfo',
(err, result) => {
if (err) {
Log.info('\n Diagnostic error');
reject();
} else {
Log.info('Diagnostic success', result)
Log.info('Diagnostic success', result.version)
let totalram=diagObj._bytesToSize(result.totalram);
let freeram=diagObj._bytesToSize(result.freeram);
let serialnumber=diagObj._ConvertStringToHex(result.serialnumber);
let diagInfo = "Serial No : \n" + serialnumber + "\n " + "\nTime : " + result.time
+ "\n " + "\nUp Time : " + result.uptime + "Sec\n"+ "\nTotal RAM : \t" + totalram + "\n " + "\nFree RAM : " + freeram + "\n " + " \nDevice Name : " + result.devicename + "\n " + "\nCPU Load : " + result.cpuload + " %"
console.log("@@@inside_dignostic",diagInfo)
resolve(diagInfo)
}
}
);
})
}
_diagnosticVersion() {
let diagObj = this;
return new Promise(function (resolve, reject) {
diagObj.thunderJS.call('org.rdk.System', 'getSystemVersions',
(err,result)=>{
if(err){
Log.info('\n Dtag: getSystemVersions Version error', err)
reject()
}else{
Log.info('Dtag: getSystemVersions Version success',result)
Log.info('Dtag: getSystemVersions Version success',result.stbVersion)
Log.info('Dtag: getSystemVersions Version success',result.stbTimestamp)
let diagVers1="\n" + result.stbVersion + " \n" + result.stbTimestamp + " \n\n"
Log.info('Dtag: getSystemVersions VersionLabel obtained : ', diagVers1)
resolve(diagVers1)
}
}
)
})
}
_diagnosticResolution() {
let diagObj = this;
return new Promise(function (resolve, reject) {
diagObj.thunderJS.call('org.rdk.DisplaySettings','getCurrentResolution',{"videoDisplay":"HDMI0"},
(err, result) => {
if (err) {
Log.info('\n Dtag: Display settings getCurrentResolution error')
reject()
} else {
let current_resolution=result.resolution
let diagResl="\n Current Resolution : \t" + current_resolution
Log.info('\n Dtag: Display settings getCurrentResolution(result.resolution) DiagnosticResolutionLabel',diagResl)
resolve(diagResl)
}
})
})
}
/**
* function to convert bytes to GB
*/
_bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
/**
* function to convert string to hexa-dec
*/
_ConvertStringToHex(str) {
var arrayy = [];
for (var i = 0; i < str.length; i++) {
arrayy[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
}
return arrayy.join(" ");
}
} |
JavaScript | class SnakeNode {
constructor(parent) {
this.parent = parent;
}
} |
JavaScript | class UsersController {
/**
* @static
* @method signup
* @description Posts a new user
* @param {object} request - HTTP Request object
* @param {object} response - HTTP Response object
* @returns {object} status, message
*/
static signup(request, response) {
const {
firstName,
lastName,
email,
password
} = request.body;
UsersDBQueries.getUserByEmail(email)
.then(user => (user ? Promise.reject() : bcrypt.hash(password, 10)))
.then(hash => UsersDBQueries.createUser(firstName, lastName, email, hash))
.then((newUser) => {
jwt.sign(
{ userId: newUser.user_id, userRole: newUser.user_role },
process.env.JWT_KEY,
(error, token) => {
response.status(201);
return response
.json({
status: 201,
message: 'Successfully signed up',
data: { token, userId: newUser.user_id }
});
}
);
})
.catch(() => {
response.status(409);
return response
.json({ status: 409, message: 'Unsuccessful. Email already in use' });
});
}
/**
* @static
* @method login
* @description Posts a new user
* @param {object} request - HTTP Request object
* @param {object} response - HTTP Response object
* @returns {object} status, message
*/
static login(request, response) {
const {
email,
password
} = request.body;
UsersDBQueries.getUserByEmail(email)
.then(user => (!user ? Promise.reject() : Promise.resolve(user)))
.then(user => bcrypt.compare(password, user.password)
.then(isMatch => (!isMatch ? Promise.reject() : Promise.resolve()))
.then(() => {
jwt.sign(
{ userId: user.user_id, userRole: user.user_role },
process.env.JWT_KEY,
(error, token) => {
response.status(200);
return response
.json({
status: 200,
message: 'Successfully logged in',
data: { token, userId: user.user_id }
});
}
);
}))
.catch(() => {
response.status(401);
return response
.json({ status: 401, message: 'Unsuccessful. Invalid credentials' });
});
}
} |
JavaScript | class NzSpaceItemLegacyComponent {
constructor(renderer, elementRef) {
this.renderer = renderer;
this.elementRef = elementRef;
}
setDirectionAndSize(direction, size) {
if (direction === 'horizontal') {
this.renderer.removeStyle(this.elementRef.nativeElement, 'margin-bottom');
this.renderer.setStyle(this.elementRef.nativeElement, 'margin-right', `${size}px`);
}
else {
this.renderer.removeStyle(this.elementRef.nativeElement, 'margin-right');
this.renderer.setStyle(this.elementRef.nativeElement, 'margin-bottom', `${size}px`);
}
}
ngOnInit() { }
} |
JavaScript | class FormAdd extends React.Component {
constructor(props) {
super(props);
this.state = {
title:'',
description: false
}
}
render() {
return (
<>
<form onSubmit={this.props.addNewBook}>
<div className="mb-3" controlId="formBasicEmail">
<label>Book title</label>
<input type="text" name="title" placeholder="Enter book title" />
</div>
<div className="mb-3" controlId="formBasicPassword">
<label>Description</label>
<input type="text" name="description" placeholder="Description" />
</div>
<div className="mb-3" controlId="formBasicCheckbox">
<label>Status</label>
<select name="status" aria-label="Floating label select example">
<option value="">Open this select menu</option>
<option value="Life Changing">Life Changing</option>
<option value="Favorite Five">Favorite Five</option>
<option value="Recommended To Me">Reccomended To Me</option>
</select>
</div>
</form>
</>
)
}
} |
JavaScript | class MsgSubmitParameterChangeProposal {
constructor(params) {
this.type = 'irishub/gov/MsgSubmitProposal';
params.proposal_type = ProposalType[ProposalType.Parameter];
this.value = params;
}
getSignBytes() {
return this.value;
}
marshal() {
return {
type: this.type,
value: {
proposal_type: ProposalType.Parameter,
title: this.value.title,
description: this.value.description,
proposer: this.value.proposer,
initial_deposit: this.value.initial_deposit,
params: this.value.params,
},
};
}
} |
JavaScript | class MsgSubmitPlainTextProposal {
constructor(params) {
this.type = 'irishub/gov/MsgSubmitProposal';
params.proposal_type = ProposalType[ProposalType.PlainText];
params.params = null; // TODO: Historical issue: Proposals except `ParameterChange` must specify the `params` to be null
this.value = params;
}
getSignBytes() {
return this.value;
}
marshal() {
return {
type: this.type,
value: {
proposal_type: ProposalType.PlainText,
title: this.value.title,
description: this.value.description,
proposer: this.value.proposer,
initial_deposit: this.value.initial_deposit,
},
};
}
} |
JavaScript | class MsgSubmitCommunityTaxUsageProposal {
constructor(params) {
this.type = 'irishub/gov/MsgSubmitCommunityTaxUsageProposal';
params.proposal_type = ProposalType[ProposalType.CommunityTaxUsage];
params.params = null; // TODO: Historical issue: Proposals except `ParameterChange` must specify the `params` to be null
this.value = params;
}
getSignBytes() {
return this.value;
}
marshal() {
return {
type: this.type,
value: {
proposal_type: ProposalType.CommunityTaxUsage,
title: this.value.title,
description: this.value.description,
proposer: this.value.proposer,
initial_deposit: this.value.initial_deposit,
},
};
}
} |
JavaScript | class MsgDeposit {
constructor(proposalID, depositor, amount) {
this.type = 'irishub/gov/MsgDeposit';
this.value = {
proposal_id: proposalID,
depositor: depositor,
amount: amount,
};
}
getSignBytes() {
return this.value;
}
} |
JavaScript | class MsgVote {
constructor(proposalID, voter, option) {
this.type = 'irishub/gov/MsgVote';
this.value = {
proposal_id: proposalID,
voter: voter,
option: VoteOption[option],
};
}
getSignBytes() {
return this.value;
}
marshal() {
return {
type: this.type,
value: {
proposal_id: this.value.proposal_id,
voter: this.value.voter,
option: VoteOption[this.value.option],
},
};
}
} |
JavaScript | class Window_ScreenshotHooker extends Window_Base {
constructor() {
super(0, 0, Graphics.boxWidth, Graphics.boxHeight);
this._isWindow = false;
this.opacity = 0;
this.setVisible(false);
}
setVisible(value) {
this.children.forEach(e => {
if(e.constructor.name.contains("_window")) {
e.visible = value;
}
});
}
on(canvas, filename) {
this.setVisible(true);
this._screenshot = PIXI.Sprite.from(canvas);
const style = {
"dropShadow": true,
"dropShadowAlpha": 0.4,
"dropShadowDistance": 1,
"stroke": "white",
"strokeThickness": 2
};
this._text = new PIXI.Text(`${filename}.${$.fileFormat}`, style);
this._screenshot.addChild(this._text);
this.addChildAt(this._screenshot, 1);
this._updateContents();
this.visible = true;
}
off() {
this.setVisible(false);
if(this._screenshot) {
this._windowContentsSprite.removeChild(this._screenshot);
}
this.visible = false;
}
update() {
super.update();
if(Input.isTriggered("ok") || Input.isTriggered("escape")) {
if(this.visible) {
this.off();
}
}
}
} |
JavaScript | class Post {
constructor(title, author) {
this.title = title;
this.author = author;
}
toString() {
return this.title + ', by ' + this.author;
}
} |
JavaScript | class StatusError extends Error {
/**
* Create a new StatusError.
*
* @protected
* @param {!number} statusCode - The HTTP status code this error belongs to
* @param {...any} params - The Error constructor params to pass on
* @see {Error}
*/
constructor(statusCode, ...params) {
super(...params);
this._statusCode = statusCode;
}
/**
* Returns the HTTP status code.
*
* @returns {number} The HTTP status code this error belongs to
*/
get statusCode() {
return this._statusCode;
}
} |
JavaScript | class Debt {
constructor(data) {
this.data = data;
this.dataMap = new Map();
this.init();
}
/*
* Normalize the data based on Debt ID
* then create key/value pair for easier access
*/
init() {
const data = this.data;
const dataMap = this.dataMap;
for (const debt of data) {
dataMap.set(debt.id, debt);
}
}
get(id) {
return this.dataMap.get(id);
}
set(id, data) {
this.dataMap.set(id, data);
}
getAllDebtIDs() {
return [...this.dataMap.keys()];
}
getAllDebts() {
return [...this.dataMap.values()];
}
} |
JavaScript | class LyricsPane extends Component {
renderWord = (word) => {
return (<Word i={word.i} key={word.i} raw={word.raw}
focus={this.props.highlights.get(word.i) || 0}
hover_cb={this.props.hover_cb}
/>);
}
renderLine = (line, idx) => {
var words = line.map(this.renderWord);
var x = [];
// Hack to put spaces between word spans. We could just put them in the spans
// themselves, but then we get funny underlining behaviour.
for (let word of words) {
x.push(word);
x.push(" ");
}
return <div className="line" key={idx}>{x.slice(0,-1)}</div>;
}
componentWillUnmount() {
this.props.hover_cb(NOINDEX);
}
render() {
var lines = this.props.verse.lines.map(this.renderLine);
return (
<div className="words lyrics"
onClick={this.props.verse && this.props.verse.isCustom() && this.props.onEditButton}
>
{this.props.loading &&
<h3>Loading...</h3>
}
{lines}
</div>
);
}
} |
JavaScript | class Alien {
constructor(info) {
// Get all of the properties from the object
for(let key in info) {
this[key] = info[key];
}
// Set up this element
this.makeElement();
}
makeElement() {
// Create an element and add it to the DOM
this.el = document.createElement('div');
this.el.classList.add('alien-card');
this.el.innerHTML = `
<h1>${this.name}</h1>
<img src="${this.image}">`;
// setup clicks on this element
// this.el.onclick = this.click.bind(this);
this.el.onclick = (e) => {
this.click(e);
};
}
click(e) {
// Handle clicks on this element
console.log(this.name);
// Your job is to display the data in the overlay...
}
} |
JavaScript | class Analyser extends ToneAudioNode {
constructor() {
super(optionsFromArguments(Analyser.getDefaults(), arguments, ["type", "size"]));
this.name = "Analyser";
/**
* The analyser node.
*/
this._analysers = [];
/**
* The buffer that the FFT data is written to
*/
this._buffers = [];
const options = optionsFromArguments(Analyser.getDefaults(), arguments, ["type", "size"]);
this.input = this.output = this._gain = new Gain({ context: this.context });
this._split = new Split({
context: this.context,
channels: options.channels,
});
this.input.connect(this._split);
assertRange(options.channels, 1);
// create the analysers
for (let channel = 0; channel < options.channels; channel++) {
this._analysers[channel] = this.context.createAnalyser();
this._split.connect(this._analysers[channel], channel, 0);
}
// set the values initially
this.size = options.size;
this.type = options.type;
}
static getDefaults() {
return Object.assign(ToneAudioNode.getDefaults(), {
size: 1024,
smoothing: 0.8,
type: "fft",
channels: 1,
});
}
/**
* Run the analysis given the current settings. If [[channels]] = 1,
* it will return a Float32Array. If [[channels]] > 1, it will
* return an array of Float32Arrays where each index in the array
* represents the analysis done on a channel.
*/
getValue() {
this._analysers.forEach((analyser, index) => {
const buffer = this._buffers[index];
if (this._type === "fft") {
analyser.getFloatFrequencyData(buffer);
}
else if (this._type === "waveform") {
analyser.getFloatTimeDomainData(buffer);
}
});
if (this.channels === 1) {
return this._buffers[0];
}
else {
return this._buffers;
}
}
/**
* The size of analysis. This must be a power of two in the range 16 to 16384.
*/
get size() {
return this._analysers[0].frequencyBinCount;
}
set size(size) {
this._analysers.forEach((analyser, index) => {
analyser.fftSize = size * 2;
this._buffers[index] = new Float32Array(size);
});
}
/**
* The number of channels the analyser does the analysis on. Channel
* separation is done using [[Split]]
*/
get channels() {
return this._analysers.length;
}
/**
* The analysis function returned by analyser.getValue(), either "fft" or "waveform".
*/
get type() {
return this._type;
}
set type(type) {
assert(type === "waveform" || type === "fft", `Analyser: invalid type: ${type}`);
this._type = type;
}
/**
* 0 represents no time averaging with the last analysis frame.
*/
get smoothing() {
return this._analysers[0].smoothingTimeConstant;
}
set smoothing(val) {
this._analysers.forEach(a => a.smoothingTimeConstant = val);
}
/**
* Clean up.
*/
dispose() {
super.dispose();
this._analysers.forEach(a => a.disconnect());
this._split.dispose();
this._gain.dispose();
return this;
}
} |
JavaScript | class Info extends Component {
constructor(props) {
super(props)
this.state = {
toggleLan: this.props.location.pathname === '/info'
}
this.onToggle = this.onToggle.bind(this);
}
onToggle() {
this.setState({ toggleLan: !this.state.toggleLan });
}
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.props.location.pathname !== prevProps.location.pathname)
this.setState({
toggleLan: this.props.location.pathname === '/info'
})
}
render() {
return (
<div className="page" id="p2">
<li className="icon fa fa-info">
<span className="title">
{/*<Toggle*/}
{/*className="cursor-pointer"*/}
{/*onClick={this.onToggle}*/}
{/*on={'Zu den Vereinsinfos'}*/}
{/*off={'Zu den Laninfos'}*/}
{/*size="m"*/}
{/*active={this.state.toggleLan}*/}
{/*width={240}*/}
{/*onClassName="btn-primary"*/}
{/*onstyle="primary"*/}
{/*offClassName="btn-primary"*/}
{/*offstyle="primary"*/}
{/*/>*/}
</span>
<div className="container">
<div className="row">
{
this.state.toggleLan ?
<InfoLan /> :
<InfoVerein />
}
</div>
</div>
</li>
</div>
)
}
} |
JavaScript | class CWidgetClock extends CWidget {
_init() {
super._init();
this._time_offset = 0;
this._interval_id = null;
this._has_contents = false;
}
_doActivate() {
super._doActivate();
this._startClock();
}
_doDeactivate() {
super._doDeactivate();
this._stopClock();
}
_processUpdateResponse(response) {
super._processUpdateResponse(response);
this._stopClock();
if (response.clock_data !== undefined) {
this._has_contents = true;
this._time_offset = 0;
const now = new Date();
if (response.clock_data.time !== null) {
this._time_offset = now.getTime() - response.clock_data.time * 1000;
}
if (response.clock_data.time_zone_offset !== null) {
this._time_offset -= (now.getTimezoneOffset() * 60 + response.clock_data.time_zone_offset) * 1000;
}
this._startClock();
}
else {
this._time = null;
this._time_zone_offset = null;
this._has_contents = false;
}
}
_startClock() {
if (this._has_contents) {
this._interval_id = setInterval(() => this._clockHandsRotate(), 1000);
this._clockHandsRotate();
}
}
_stopClock() {
if (this._interval_id !== null) {
clearTimeout(this._interval_id);
this._interval_id = null;
}
}
_clockHandsRotate() {
const clock_svg = this._target.querySelector('.clock-svg');
if (clock_svg !== null) {
const now = new Date();
now.setTime(now.getTime() - this._time_offset);
let h = now.getHours() % 12;
let m = now.getMinutes();
let s = now.getSeconds();
if (clock_svg !== null && !clock_svg.classList.contains('disabled')) {
this._clockHandRotate(clock_svg.querySelector('.clock-hand-h'), 30 * (h + m / 60 + s / 3600));
this._clockHandRotate(clock_svg.querySelector('.clock-hand-m'), 6 * (m + s / 60));
this._clockHandRotate(clock_svg.querySelector('.clock-hand-s'), 6 * s);
}
}
}
_clockHandRotate(clock_hand, degree) {
clock_hand.setAttribute('transform', `rotate(${degree} 50 50)`);
}
} |
JavaScript | class DileButton extends LitElement {
static get styles() {
return css`
* {
box-sizing: border-box;
}
:host {
display: inline-block;
user-select: none;
}
.undefined {
background-color: #868e96;
}
.primary {
background-color: #007bff;
}
.danger {
background-color: #dc3545;
}
.success {
background-color: #28a745;
}
.warning {
background-color: #ffc107;
}
div {
display: inline-block;
color: #fff;
background-color: #888;
border-radius: 5px;
border: var(--dile-button-border-width) solid var(--dile-button-border-color);
padding: var(--dile-button-padding, 10px);
cursor:pointer;
outline:none;
-webkit-animation-duration: 0.3s;
animation-duration: 0.3s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
div:active{
-webkit-animation-name: anim;
animation-name: anim;
}
@keyframes anim {
0% {transform: scale(1);}
10%, 30% {transform: scale(0.9) rotate(-2deg);}
100% {transform: scale(1) rotate(0);}
}
div.disabled {
opacity: 0.5;
}
.disabled:active {
-webkit-animation-name: none;
animation-name: none;
}
`;
}
render() {
return html`
<div @click="${this._onClick}" class="${this._getClass(this.role, this.disabled)}">
<slot></slot>
</div>
`;
}
static get properties() {
return {
/**
* The role of the button. This property configures the button color
* Values accepted: 'undefined', 'primary', 'danger', 'warning', 'success'.
* Default: 'undefined'.
* @type {String}
*/
role: { type: String },
/**
* Disabled property disables the button (disabled buttons stops click propagation events).
* @type {Boolean}
*/
disabled: { type: Boolean }
};
}
constructor() {
super();
this.role = 'undefined';
}
_getClass(role, disabled) {
return role + (disabled ? ' disabled' : '');
}
_onClick(e) {
if(this.disabled) {
e.stopPropagation();
}
}
} |
JavaScript | class TableViewer extends Component {
constructor(props) {
super(props);
this.generateAndDownloadCSV = this.generateAndDownloadCSV.bind(this);
this.state = {
currentPage: 1,
searchResults: null,
};
if (this.props.content && this.props.sortColumn) {
this.sortTable();
}
}
highlightSyntax(json) {
if (json) {
json = json
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
(match) => {
let cls = 'hljs-number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'hljs-key';
} else {
cls = 'hljs-string';
}
} else if (/true|false/.test(match)) {
cls = 'hljs-boolean';
} else if (/null/.test(match)) {
cls = 'hljs-null';
}
return `<span class="${cls}">${match}</span>`;
},
);
}
return '';
}
componentDidUpdate(prevProps) {
if (prevProps.content !== this.props.content && this.props.sortColumn) {
this.sortTable();
}
}
sortTable() {
const criteria = this.props.sortColumn;
if (criteria) {
this.props.content.sort(this.compare(criteria));
}
}
compare(criteria) {
return (a, b) => {
if (a[criteria] < b[criteria]) { return -1; }
if (a[criteria] > b[criteria]) { return 1; }
return 0;
};
}
generateAndDownloadCSV() {
const encoding = this.props.encoding ? this.props.encoding : 'UTF-8';
const csvType = { encoding, type: `text/plain;charset=${encoding}` };
const filename = this.props.filename ? this.props.filename : 'logResults.csv';
let csvContent = '';
const data = this.props.content;
const headers = [];
this.props.content.forEach((rowObj) => {
if (headers === undefined || headers.length === 0) {
for (const property in rowObj) {
if (rowObj.hasOwnProperty(property)) {
headers.push(property);
}
}
} else {
for (const property in rowObj) {
if (rowObj.hasOwnProperty(property)) {
if (headers.indexOf(property) == -1) {
headers.push(property);
}
}
}
}
const rowData = [];
for (const i in headers) {
let data = rowObj[headers[i]];
if (data && typeof data === 'string' && data.indexOf(',') >= 0) {
data = `"${data.replace(/"/g, '""')}"`;
}
rowData.push(data);
}
const row = rowData.join(',');
csvContent += `${row}\r\n`;
});
const row = headers.join(',');
csvContent = `${row}\r\n${csvContent}`;
const blob = new Blob([csvContent], csvType);
FileSaver.saveAs(blob, filename);
}
renderDownload() {
if (this.props.activateDownloadButton) {
const buttonStyle = this.props.downloadButtonStyle ? this.props.downloadButtonStyle : {};
return (
<div className="csvFileDownloader">
<button
style={buttonStyle}
download={this.props.csvFileName}
onClick={this.generateAndDownloadCSV}
>
<MdFileDownload
size={30}
color="green"/>
{this.props.downloadName ? this.props.downloadName : 'Download Table Data'}
</button>
</div>
);
}
return null;
}
renderTitle() {
const titleStyle = this.props.titleStyle ? this.props.titleStyle : {};
if (Array.isArray(this.props.content) && this.props.content.length > 0) {
return (
<h2 className="tableTitle" style={titleStyle}>{this.props.title}</h2>
);
}
return null;
}
render() {
const tableStyle = this.props.tableStyle ? this.props.tableStyle : {};
const height = { maxHeight: this.props.maxHeight, ...tableStyle };
return (
<div className="tableWithCSV" >
{this.renderTitle()}
{this.renderStats()}
<div className="titleContainer">
{this.renderDownload()}
{this.renderTopPagination()}
<div className="search-container">
{this.renderSearch()}
</div>
</div>
<div className="divTableContainer" >
<div className="divTable" style={height}>
<div className="divTableHeading">{this.renderHeaders()}</div>
<div className="divTableBody">{this.renderBody()}</div>
</div>
</div>
{this.renderPagination()}
</div>
);
}
onSearch(term, elements) {
if (term.length > 0) {
this.setState({ searchResults: elements });
} else {
this.setState({ searchResults: null });
}
this.pageChange(1);
}
renderSearch() {
if (this.props.searchEnabled) {
let search = 'Search...';
if (this.props.placeholderSearchText) {
search = this.props.placeholderSearchText;
}
const caseInsensitive = !!this.props.caseInsensitive;
return (
<SearchBar
onSearchTextChange={(b, e) => { this.onSearch(b, e); }}
onSearchButtonClick={(b, e) => { this.onSearch(b, e); }}
placeHolderText={search}
data={this.props.content}
caseInsensitive={caseInsensitive}
/>
);
}
return null;
}
renderTopPagination() {
if (this.props.topPagination) {
return this.renderPagination(true);
}
return null;
}
renderPagination(isTop = false) {
if (this.props.pagination || isTop) {
const boxStyle = this.props.pageBoxStyle ? this.props.pageBoxStyle : {};
const activeStyle = this.props.activePageBoxStyle ? this.props.activePageBoxStyle : {};
const pagesDisplay = this.props.maxPagesToDisplay ? this.props.maxPagesToDisplay : 5;
if (this.props.content.length <= this.props.pagination) {
return null;
}
let totalElements = this.props.content.length;
if (this.state.searchResults) {
totalElements = this.state.searchResults.length;
}
return (
<Paginator
pageSize={this.props.pagination}
totalElements={totalElements}
onPageChangeCallback={(e) => { this.pageChange(e); }}
pageBoxStyle={boxStyle}
activePageBoxStyle={activeStyle}
maxPagesToDisplay={pagesDisplay}
/>
);
}
return null;
}
pageChange(page) {
this.setState({ currentPage: page });
}
renderAllRows() {
const rows = this.props.content;
const { headers } = this.props;
return rows.map((row, i) => this.getRow(row, i));
}
renderRowPage(rows) {
const rowsContent = [];
const pageStart = (this.state.currentPage - 1) * this.props.pagination;
const rowQty = rows.length;
const { headers } = this.props;
for (let i = pageStart; i < pageStart + this.props.pagination && rows[i]; i++) {
rowsContent.push(this.getRow(rows[i], i));
}
return rowsContent;
}
renderBody() {
const rows = this.state.searchResults || this.props.content;
if (rows !== null) {
if (this.props.pagination) {
return this.renderRowPage(rows);
}
return this.renderAllRows(rows);
}
return (null);
}
getRow(row, i) {
const isWarning = row.warning || false;
const isSucccess = row.success;
let fontColor = '#000000';
if (isSucccess === false) { // because can be undefined
fontColor = (this.props.errorColor) ? this.props.errorColor : '#b30009';
} else if (isWarning) {
fontColor = (this.props.warningColor) ? this.props.warningColor : '#ba8722';
} else if (isSucccess === true) {
fontColor = (this.props.successColor) ? this.props.successColor : '#0b7012';
}
return (
<div
key={`table_row_${i} `}
className={'divTableRow'}
style={{ ...this.props.bodyCss, ...{ color: fontColor } } }
>
{this.renderRow(row, i)}
</div>
);
}
renderLineNumber(i) {
return (
<div
key={`table_row_number_${i}`}
className="divTableCell">
{i}
</div>
);
}
renderNumberHeader(headerCss) {
if (this.props.renderLineNumber) {
return (
<div key={'table_header_line'} className="divTableCell" style={headerCss}>
Line
</div>
);
}
return null;
}
isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
renderRow(row, i) {
const { headers } = this.props;
if (row) {
const rowData = [];
// Render line number
if (this.props.renderLineNumber) {
let number = i + 1;
if (this.props.reverseLineNumber) {
number = this.props.content.length - i;
}
rowData.push(this.renderLineNumber(number));
}
// Create content
const rowContent = headers.map((header, element) => {
let content = row[header];
let isJson = false;
try {
if (isNaN(content)) {
content = JSON.parse(content);
isJson = true;
}
} catch (e) {
content = row[header];
isJson = false;
try{
if (this.isFunction(content)){
content = content();
}
}
catch (e){
if (content) {
content = content.split('\n').map((item, i) => (<div key={`part-${i}`}>{item}</div>));
}
}
}
if (isJson) {
return this.renderJsonContent(content,i, element);
}
return (
<div
key={`table_row_${i}_cell_${element}`}
className="divTableCell">
{ content }
</div>
);
});
return [...rowData, ...rowContent];
}
return null;
}
renderJsonContent(content,i,element){
const jsonText = JSON.stringify(content, undefined, 2);
const highlight = this.highlightSyntax(jsonText);
const parsedHtml = ReactHtmlParser(highlight, true);
return (
<div
key={`table_row_${i}_cell_${element}`}
className="divTableCell">
<pre>
{parsedHtml}
</pre>
</div>
);
}
renderHeaders() {
const { headers } = this.props;
const { headerCss } = this.props;
if (headers) {
return (
<div className="divTableRow">
{this.renderNumberHeader(headerCss)}
{headers.map((header, index) => (
<div key={`table_header_${index}`} className="divTableCell" style={headerCss}>
{header}
</div>
))}
</div>
);
}
return null;
}
renderStats() {
if (this.props.renderStats) {
return (
<div>
<label>{this.props.title}</label>
<br />
<label className="tableWithCSVSuccess_true">
Success: {this.props.successRows}
</label>
<br />
<label className="tableWithCSVSuccess_false">
Error: {this.props.errorsRows}
</label>
<br />
<label>-----------------------------</label>
<br />
<label>Total: {this.props.totalRows}</label>
<br />
</div>
);
}
return null;
}
} |
JavaScript | class Searcher {
/**
* Create a Searcher object.
*
* @param repoUri The URI of the NPM registry to use.
* @param cdnUri The URI of the CDN to use for fetching full package data.
*/
constructor(repoUri = 'https://registry.npmjs.org/', cdnUri = 'https://unpkg.com') {
this.repoUri = repoUri;
this.cdnUri = cdnUri;
}
/**
* Search for a jupyterlab extension.
*
* @param query The query to send. `keywords:"jupyterlab-extension"` will be appended to the query.
* @param page The page of results to fetch.
* @param pageination The pagination size to use. See registry API documentation for acceptable values.
*/
searchExtensions(query, page = 0, pageination = 250) {
const uri = new URL('/-/v1/search', this.repoUri);
// Note: Spaces are encoded to '+' signs!
let text = `${query} keywords:"jupyterlab-extension"`;
uri.searchParams.append('text', text);
uri.searchParams.append('size', pageination.toString());
uri.searchParams.append('from', (pageination * page).toString());
return fetch(uri.toString()).then((response) => {
if (response.ok) {
return response.json();
}
return [];
});
}
/**
* Fetch package.json of a package
*
* @param name The package name.
* @param version The version of the package to fetch.
*/
fetchPackageData(name, version) {
const uri = new URL(`/${name}@${version}/package.json`, this.cdnUri);
return fetch(uri.toString()).then((response) => {
if (response.ok) {
return response.json();
}
return null;
});
}
} |
JavaScript | class FlowEdge extends Edge {
/**
* Creates an instance of FlowEdge.
* @param {number} from ID of start Node of edge.
* @param {number} to ID of end Node of edge.
* @param {number} capacity The capacity of edge.
* @param {number} flow The flow of edge.
* @memberof FlowEdge
*/
constructor(from, to, capacity, flow) {
super(from, to);
this.capacity = capacity;
this.flow = flow;
if (flow > capacity) {
this.flow = this.capacity;
} else if (flow < 0) {
this.flow = 0;
}
}
/**
* Increases the flow in the edge.
* @param {number} addedFlow The amount of flow to increase in the edge.
* @memberof FlowEdge
*/
increaseFlow(addedFlow) {
this.flow = this.flow + addedFlow;
if (this.flow > this.capacity) {
this.flow = this.capacity;
}
}
/**
* Decreases the flow in the edge.
* @param {number} reducedFlow The amount of flow to reduce in the edge.
* @memberof FlowEdge
*/
decreaseFlow(reducedFlow) {
this.flow = this.flow - reducedFlow;
if (this.flow < this.capacity) {
this.flow = 0;
}
}
/**
* Reset the flow in the edge.
* @memberof FlowEdge
*/
resetFlow() {
this.flow = 0;
}
/**
* Replaces the flow in the edge with new value.
* @param {number} flow The new value of flow.
* @memberof FlowEdge
*/
changeFlowTo(flow) {
this.flow = flow;
if (this.flow > this.capacity) {
this.flow = this.capacity;
} else if (this.flow < 0) {
this.flow = 0;
}
}
/**
* Replaces the capacity in the edge with new value.
* @param {number} capacity the new value of capacity.
* @memberof FlowEdge
*/
changeCapacityTo(capacity) {
this.capacity = capacity;
if (this.capacity < 0) {
this.capacity = 0;
}
}
/**
* Checks if the capacity is full.
* @returns {boolean} True if capacity of the edge is full. Otherwise, return false.
* @memberof FlowEdge
*/
isCapacityFull() {
if (this.flow == this.capacity) return true;
return false;
}
/**
* Checks if the capacity is zero.
* @returns {boolean} True if capacity of the edge is zero. Otherwise, return false.
* @memberof FlowEdge
*/
isCapacityZero() {
if (this.capacity == 0) return true;
return false;
}
/**
* checks if it empty (zero flow).
* @returns {boolean} True if it empty. Otherwise, return false.
* @memberof FlowEdge
*/
isEmpty() {
if (this.flow == 0) return true;
return false;
}
/**
* clones a FlowEdge object.
* @return {FlowEdge} cloned FlowEdge.
* @memberof FlowEdge
*/
clone() {
let clonedEdge = new FlowEdge(this.from, this.to, this.capacity, this.flow);
return clonedEdge;
}
/**
* Returns string with the data of edge.
* @returns {string}
* @memberof FlowEdge
*/
toString() {
return `${super.toString()} with capacity: ${this.capacity} and flow: ${this.flow}`;
}
} |
JavaScript | class Jobs extends Events {
constructor() {
super();
this._jobsInProgress = {};
}
/**
* Adds a new job. The specified function will be returned when the
* job is finished.
*
* @param {Function} fn - A function to be stored for this job.
* @returns {string} Returns a job id
* @example
* ```javascript
* const jobId = editor.jobs.start(() => console.log('job was finished'));
* editor.jobs.finish(jobId)(); // prints 'job was finished'
* ```
*/
start(fn) {
const jobId = Guid.create().substring(0, 8);
this._jobsInProgress[jobId] = fn;
this.emit('start', jobId);
return jobId;
}
/**
* Notifies that a job has finished. The specified job
* id is removed and the callback stored when the job was
* started is returned.
*
* @param {string} jobId - The job id
* @returns {Function} The function stored when the job was started
* @example
* ```javascript
* const jobId = editor.jobs.start(() => console.log('job was finished'));
* editor.jobs.finish(jobId)(); // prints 'job was finished'
* ```
*/
finish(jobId) {
const callback = this._jobsInProgress[jobId];
delete this._jobsInProgress[jobId];
this.emit('finish', jobId);
return callback;
}
} |
JavaScript | class chain {
constructor(...templators) {
this.templators = templators;
}
resolve(arg) {
// or use reduce()
let current = arg;
templators.forEach( t => {
current = t.resolve(current);
});
return current;
}
generate(arg) {
let current = arg;
templators.forEach( t => {
current = t.resolve(current);
});
return current;
/*
for(let i = 0; i < this.templators.length; ++i) {
const t = templators[i];
current = t.generate(i);
}
return current;
*/
}
} |
JavaScript | class TranslatorFactory {
/**
* This function get the provider and instantiate the right translator class
* @returns a translater instance based on the configuration class
*/
static createTranslator() {
const config = TranslatorConfiguration.getConfig();
let translator;
if (config.providerName === ProviderTypes.Google) {
translator = new GoogleTranslator(config);
}
if (config.providerName === ProviderTypes.Microsoft) {
translator = new MicrosoftTranslator(config);
}
return translator;
}
} |
JavaScript | class ContainerHttpGet {
/**
* Create a ContainerHttpGet.
* @member {string} [path] The path to probe.
* @member {number} port The port number to probe.
* @member {string} [scheme] The scheme. Possible values include: 'http',
* 'https'
*/
constructor() {
}
/**
* Defines the metadata of ContainerHttpGet
*
* @returns {object} metadata of ContainerHttpGet
*
*/
mapper() {
return {
required: false,
serializedName: 'ContainerHttpGet',
type: {
name: 'Composite',
className: 'ContainerHttpGet',
modelProperties: {
path: {
required: false,
serializedName: 'path',
type: {
name: 'String'
}
},
port: {
required: true,
serializedName: 'port',
type: {
name: 'Number'
}
},
scheme: {
required: false,
serializedName: 'scheme',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class SliceTransformer {
constructor (firstChunkSize, restChunkSize) {
this.chunkSize = firstChunkSize
this.restChunkSize = restChunkSize || firstChunkSize
this.partialChunk = new Uint8Array(this.chunkSize)
this.offset = 0 // offset into `partialChunk`
}
send (record, controller) {
controller.enqueue(record)
this.chunkSize = this.restChunkSize
this.partialChunk = new Uint8Array(this.chunkSize)
this.offset = 0
}
transform (chunk, controller) {
let i = 0 // offset into `chunk`
if (this.offset > 0) {
const len = Math.min(chunk.byteLength, this.chunkSize - this.offset)
this.partialChunk.set(chunk.subarray(0, len), this.offset)
this.offset += len
i += len
if (this.offset === this.chunkSize) {
this.send(this.partialChunk, controller)
}
}
while (i < chunk.byteLength) {
const remainingBytes = chunk.byteLength - i
if (remainingBytes >= this.chunkSize) {
const record = chunk.slice(i, i + this.chunkSize)
i += this.chunkSize
this.send(record, controller)
} else {
const end = chunk.slice(i, i + remainingBytes)
i += end.byteLength
this.partialChunk.set(end)
this.offset = end.byteLength
}
}
}
flush (controller) {
if (this.offset > 0) {
controller.enqueue(this.partialChunk.subarray(0, this.offset))
}
}
} |
JavaScript | class RedirectionService extends BaseService {
constructor(db) {
super(db, Redirection.RedirectionModel, Redirection.RedirectionCollection);
}
/**
* Returns whether there are other entities that have the same longUrl
* @private
* @param entity
* @returns {Promise<boolean>}
*/
async _hasTwins(entity) {
// ensure there are no existing entries with the same longUrl
const entityTwins = await this.find({
query: {
shortUrl: {
$ne: entity.get('shortUrl')
},
longUrl: entity.get('longUrl')
}
});
return !!entityTwins.length;
}
/**
* Ensures that current operation does not result in duplicate entities
* @private
* @param data
* @param id
* @returns {Promise<void>}
*/
async _preventTwins(data, id = null) {
const entity = this._makeEntityFromData(data);
if (id) {
entity.set('id', id);
}
if (await this._hasTwins(entity)) {
throw new errors.Conflict('Unable to register redirection due to prior registration!');
}
}
/**
* @swagger
*
* /redirections/:
* get:
* summary: 'Returns all registered redirections.'
* responses:
* 302:
* description: 'Redirection to target URL.'
* 400:
* description: 'Unable to redirect due to missing parameters.'
* 404:
* description: 'Requested redirection has not been registered.'
* tags:
* - admin
*/
async find(params) {
return super.find(params);
}
/**
* @swagger
*
* /redirections/:
* post:
* summary: 'Registers a redirection to the target URL for the specified short URL.'
* parameters:
* - $ref: '#/parameters/RegistrationPayloadParam'
* responses:
* 201:
* description: 'Redirection successfully registered.'
* 400:
* description: 'Unable to register redirection due to missing parameters.'
* 409:
* description: 'Unable to register redirection due to prior registration.'
* tags:
* - admin
*/
async create(data, params) {
await this._preventTwins(data);
return super.create(data, params);
}
/**
* @swagger
*
* /redirections/{shortUrl}:
* get:
* summary: 'Returns the specified redirection based on the short URL parameter.'
* parameters:
* - $ref: '#/parameters/ShortUrlPathParam'
* responses:
* 200:
* description: 'Redirection to target URL.'
* 400:
* description: 'Unable to redirect due to missing parameters.'
* 404:
* description: 'Requested redirection has not been registered.'
* tags:
* - admin
*/
async get(id, params) {
return super.get(id, params);
}
/**
* @swagger
*
* /redirections/{shortUrl}:
* put:
* summary: 'Updates the target URL for the specified redirection short URL.'
* parameters:
* - $ref: '#/parameters/ShortUrlPathParam'
* - $ref: '#/parameters/RegistrationPayloadParam'
* responses:
* 200:
* description: 'Redirection successfully updated.'
* 400:
* description: 'Unable to update redirection due to missing parameters.'
* 404:
* description: 'Unable to update non-existent redirection.'
* 409:
* description: 'Unable to update redirection due to prior registration.'
* tags:
* - admin
*/
async update(id, data, params) {
await this._preventTwins(data, id);
return super.update(id, data, params);
}
/**
* @swagger
*
* /redirections/{shortUrl}:
* delete:
* summary: 'Removes redirection for the specified short URL.'
* parameters:
* - $ref: '#/parameters/ShortUrlPathParam'
* responses:
* 200:
* description: 'OK'
* 400:
* description: 'Unable to delete redirection due to missing parameters.'
* 404:
* description: 'Unable to delete non-existent redirection.'
* tags:
* - admin
*/
async remove(id, params) {
return super.remove(id, params);
}
} |
JavaScript | class NumberFormat extends Formatter {
//<debug>
constructor(options) {
super(options);
this.parse('0'); // throw away parse just to get us freezable
Object.freeze(this.is);
Object.freeze(this);
}
//</debug>
initialize() {
this.is = {
decimal : false,
currency : false,
percent : false,
null : true,
from : null
};
}
configure(options) {
const me = this;
if (typeof options !== 'string') {
Object.assign(me, options);
}
else {
me.template = options;
}
// Do not remove. Assertion strings for Localization sanity check.
// 'L{NumberFormat.locale}'
// 'L{NumberFormat.currency}'
const
config = {},
loc = me.locale ? LocaleManager.locales[me.locale] : LocaleManager.locale,
defaults = loc && loc.NumberFormat,
template = me.template;
if (defaults) {
for (const key in defaults) {
if (me[key] == null && typeof defaults[key] !== 'function') {
me[key] = defaults[key];
}
}
}
if (template) {
const
match = numFormatRe.exec(template),
m2 = match[2],
m4 = match[4];
me.useGrouping = !!match[3];
me.style = match[1] ? 'currency' : (match[6] ? 'percent' : 'decimal');
if (m2) {
me.integer = +m2;
}
if (m4 === '*') {
me.fraction = [0, 20];
}
else if (m4 != null) {
me.fraction = [match[5].length, m4.length];
}
}
me._minMax('fraction', true, true);
me._minMax('integer', true, false);
me._minMax('significant', false, true);
for (const key in me.defaults) {
if (me[key] != null) {
config[key] = me[key];
}
}
me.is.from = me.from && me.from.is;
me.is[me.style] = !(me.is.null = false);
me.formatter = newFormatter(me.locale, config);
}
/**
* Creates a derived `NumberFormat` from this instance, with a different `style`. This
* is useful for processing currency and percentage styles without the symbols being
* injected in the formatting.
*
* @param {String|Object} change The new style (if a string) or a set of properties to
* update.
* @returns {Core.helper.util.NumberFormat}
*/
as(change) {
const config = this.resolvedOptions() || { template : '9.*' };
if (typeof change === 'string') {
config.style = change;
}
else {
Object.assign(config, change);
}
config.from = this;
return new NumberFormat(config);
}
defaultParse(value, strict) {
return (value == null) ? value : (strict ? Number(value) : parseFloat(value));
}
/**
* Returns the given `value` formatted in accordance with the specified locale and
* formatting options.
*
* @param {Number} value
* @returns {String}
*/
format(value) {
if (typeof value === 'string') {
const v = Number(value);
value = isNaN(v) ? this.parse(value) : v;
}
return super.format(value);
}
// The parse() method is inherited but the base class implementation
// cannot properly document the parameter and return types:
/**
* Returns a `Number` parsed from the given, formatted `value`, in accordance with the
* specified locale and formatting options.
*
* If the `value` cannot be parsed, `NaN` is returned.
*
* Pass `strict` as `true` to require all text to convert. In essence, the default is
* in line with JavaScript's `parseFloat` while `strict=true` behaves like the `Number`
* constructor:
*```
* parseFloat('1.2xx'); // = 1.2
* Number('1.2xx') // = NaN
*```
* @method parse
* @param {String} value
* @param {Boolean} [strict=false]
* @returns {Number}
*/
/**
* Returns a `Number` parsed from the given, formatted `value`, in accordance with the
* specified locale and formatting options.
*
* If the `value` cannot be parsed, `NaN` is returned.
*
* This method simply passes the `value` to `parse()` and passes `true` for the second
* argument.
*
* @method parseStrict
* @param {String} value
* @returns {Number}
*/
/**
* Returns the given `Number` rounded in accordance with the specified locale and
* formatting options.
*
* @param {Number|String} value
* @returns {Number}
*/
round(value) {
return this.parse(this.format(value));
}
/**
* Returns the given `Number` truncated to the `maximumFractionDigits` in accordance
* with the specified locale and formatting options.
*
* @param {Number|String} value
* @returns {Number}
*/
truncate(value) {
let scale = this.maximumFractionDigits,
v = this.parse(value);
if (scale != null) {
scale = 10 ** scale;
v = Math.floor(v * scale) / scale;
}
return v;
}
resolvedOptions() {
const options = super.resolvedOptions();
for (const key in options) {
// For some reason, on TeamCity, tests get undefined for some properties...
// maybe a locale issue?
if (options[key] === undefined) {
options[key] = this[key];
}
}
return options;
}
/**
* Expands the provided shorthand into the "minimum*Digits" and "maximum*Digits".
* @param {String} name
* @param {Boolean} setMin
* @param {Boolean} setMax
* @private
*/
_minMax(name, setMin, setMax) {
const
me = this,
value = me[name];
if (value != null) {
const
capName = StringHelper.capitalize(name),
max = `maximum${capName}Digits`,
min = `minimum${capName}Digits`;
if (typeof value === 'number') {
if (setMin) {
me[min] = value;
}
if (setMax) {
me[max] = value;
}
}
else {
me[min] = value[0];
me[max] = value[1];
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.