language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ClientAdapter extends Adapter { /** * Given a web socket, it makes a new adapter */ constructor(sock){ this._sock = sock; this._docs = {}; // The documents that are being monitored by the adapter var self = this; sock.on('ack', function(data){ var id = data.id; var doc = self._docs[id]; // TODO: Ensure non-null // TODO: Check version for missing operations doc.packets[data.v] = 'local'; if(data.v > doc.latest){ doc.latest = data.v }; doc._acked = true; doc._process(); console.log('ACK') }); // Called when the document has been changed by someone else connected to the server; sock.on('change', function(data){ var id = data.id; var doc = self._docs[id]; // TODO: Ensure non-null doc.packets[data.v] = data.ops; if(data.v > doc.latest){ doc.latest = data.v }; doc._process(); doc.emit('change') }); }; /** * Listen for remote events/changes to this document */ subscribe(doc){ this._docs[doc.id] = doc; this._sock.emit('subscribe', {id: doc.id, model: doc.model.name}); }; /** * Stop listening for remote events */ unsubscribe(doc){ if(!this._docs.hasOwnProperty(doc.id)){ console.warn('The document was never subscribed'); return; } this._sock.emit('unsubscribe', {id: doc.id, model: doc.model.name}); delete this._docs[doc.id]; }; /** * Send local changes to the server */ update(doc, callback){ // TODO: The document must be subscribed for this to work var self = this; if(!doc._lock){ // Cannot send while already sending. TODO: But, also the ack, other operations that are queued to update should also be sent doc._lock = true; setTimeout(function(){ // Compose operations and send them once done executing if(doc.local.length == 0){ doc._lock = false; callback(null); return; } doc._acked = false; doc._pending = doc.local.length; var data = {id: doc.id, model: doc.model.name, ops: doc.local, v: doc.v}; console.log("SEND: " + JSON.stringify(data)); self._sock.emit('update', data); }); } }; /** * Request that changes (operations) from version 'from' to version 'to' be looked up * */ history(doc, from, to, callback){ this._sock.emit('history', {id: doc.id, model: doc.model.name, from: from, to: to}); // Wait for the changes and callback when they are acknowledged }; }
JavaScript
class DelegateItems extends Base { constructor() { super(); // @ts-ignore this[itemsChangedListenerKey] = event => { /** @type {any} */ const cast = event.target; const delegateItems = cast.items; if (this.state.items !== delegateItems) { this.setState({ items: delegateItems }); } }; // @ts-ignore this[selectedIndexChangedListenerKey] = event => { /** @type {any} */ const cast = event; const delegateSelectedIndex = cast.detail.selectedIndex; if (this.state.selectedIndex !== delegateSelectedIndex) { this.setState({ selectedIndex: delegateSelectedIndex }); } }; } componentDidMount() { if (super.componentDidMount) { super.componentDidMount(); } listenToDelegateEvents(this); } componentDidUpdate(/** @type {PlainObject} */ changed) { if (super.componentDidUpdate) { super.componentDidUpdate(changed); } listenToDelegateEvents(this); } get defaultState() { return Object.assign(super.defaultState, { items: null }); } /** * The current set of items drawn from the element's current state. * * @returns {Element[]|null} the element's current items */ get items() { return this.state ? this.state.items : null; } [symbols.render](/** @type {PlainObject} */ changed) { if (super[symbols.render]) { super[symbols.render](changed); } if (changed.selectedIndex) { const itemsDelegate = this[symbols.itemsDelegate]; if (typeof itemsDelegate === 'undefined') { throw `To use DelegateItemsMixin, ${this.constructor.name} must define a getter for [symbols.itemsDelegate].`; } if ('selectedIndex' in itemsDelegate) { itemsDelegate.selectedIndex = this.state.selectedIndex; } } } }
JavaScript
class AcademicPlanCollection extends BaseSlugCollection { /** * Creates the AcademicPlan collection. */ constructor() { super('AcademicPlan', new SimpleSchema({ name: String, description: String, slugID: SimpleSchema.RegEx.Id, degreeID: SimpleSchema.RegEx.Id, effectiveSemesterID: SimpleSchema.RegEx.Id, semesterNumber: Number, year: Number, coursesPerSemester: { type: Array, minCount: 12, maxCount: 15 }, 'coursesPerSemester.$': Number, courseList: [String], retired: { type: Boolean, optional: true }, })); if (Meteor.server) { this._collection._ensureIndex({ _id: 1, degreeID: 1, effectiveSemesterID: 1 }); } } /** * Defines an AcademicPlan. * @example * AcademicPlans.define({ * slug: 'bs-cs-2016', * degreeSlug: 'bs-cs', * name: 'B.S. in Computer Science', * description: 'The BS in CS degree offers a solid foundation in computer science.', * semester: 'Spring-2016', * coursesPerSemester: [2, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0], * courseList: ['ics111-1', 'ics141-1, 'ics211-1', 'ics241-1', 'ics311-1', 'ics314-1', * 'ics212-1', 'ics321-1', 'ics313,ics361-1', 'ics312,ics331-1', 'ics332-1', * 'ics400+-1', 'ics400+-2', 'ics400+-3', 'ics400+-4', 'ics400+-5'] }) * @param slug The slug for the academic plan. * @param degreeSlug The slug for the desired degree. * @param name The name of the academic plan. * @param description The description of the academic plan. * @param semester the slug for the semester. * @param coursesPerSemester an array of the number of courses to take in each semester. * @param courseList an array of PlanChoices. The choices for each course. * @param retired optional, defaults to false, allows for retiring an academic plan. * @returns {*} */ define({ slug, degreeSlug, name, description, semester, coursesPerSemester, courseList, retired }) { const degreeID = Slugs.getEntityID(degreeSlug, 'DesiredDegree'); const effectiveSemesterID = Semesters.getID(semester); const doc = this._collection.findOne({ degreeID, name, effectiveSemesterID }); if (doc) { return doc._id; } // Get SlugID, throw error if found. const slugID = Slugs.define({ name: slug, entityName: this.getType() }); const semesterDoc = Semesters.findDoc(effectiveSemesterID); const semesterNumber = semesterDoc.semesterNumber; const year = semesterDoc.year; const planID = this._collection.insert({ slugID, degreeID, name, description, effectiveSemesterID, semesterNumber, year, coursesPerSemester, courseList, retired, }); // Connect the Slug to this AcademicPlan. Slugs.updateEntityID(slugID, planID); return planID; } /** * Updates the AcademicPlan, instance. * @param instance the docID or slug associated with this AcademicPlan. * @param degreeSlug the slug for the DesiredDegree that this plan satisfies. * @param name the name of this AcademicPlan. * @param semester the first semester this plan is effective. * @param coursesPerSemester an array of the number of courses per semester. * @param courseList an array of PlanChoices, the choices for each course. * @param retired a boolean true if the academic plan is retired. */ update(instance, { degreeSlug, name, semester, coursesPerSemester, courseList, retired }) { const docID = this.getID(instance); const updateData = {}; if (degreeSlug) { updateData.degreeID = DesiredDegrees.getID(degreeSlug); } if (name) { updateData.name = name; } if (semester) { const sem = Semesters.findDoc(Semesters.getID(semester)); updateData.effectiveSemesterID = sem._id; updateData.year = sem.year; updateData.semesterNumber = sem.semesterNumber; } if (coursesPerSemester) { if (!Array.isArray(coursesPerSemester)) { throw new Meteor.Error(`CoursesPerSemester ${coursesPerSemester} is not an Array.`, '', Error().stack); } _.forEach(coursesPerSemester, (cps) => { if (!_.isNumber(cps)) { throw new Meteor.Error(`CoursePerSemester ${cps} is not a Number.`, '', Error().stack); } }); updateData.coursesPerSemester = coursesPerSemester; } if (courseList) { if (!Array.isArray(courseList)) { throw new Meteor.Error(`CourseList ${courseList} is not an Array.`, '', Error().stack); } _.forEach(courseList, (pc) => { if (!_.isString(pc)) { throw new Meteor.Error(`CourseList ${pc} is not a PlanChoice.`, '', Error().stack); } }); updateData.courseList = courseList; } if (_.isBoolean(retired)) { updateData.retired = retired; } this._collection.update(docID, { $set: updateData }); } /** * Remove the AcademicPlan. * @param instance The docID or slug of the entity to be removed. * @throws { Meteor.Error } If docID is not an AcademicPlan, or if this plan is referenced by a User. */ removeIt(instance) { const academicPlanID = this.getID(instance); // Check that no student is using this AcademicPlan. const isReferenced = Users.someProfiles(profile => profile.academicPlanID === academicPlanID); if (isReferenced) { throw new Meteor.Error(`AcademicPlan ${instance} is referenced.`, '', Error().stack); } super.removeIt(academicPlanID); } /** * Returns an array of problems. Checks the semesterID and DesiredDegree ID. * @returns {Array} An array of problem messages. */ checkIntegrity() { // eslint-disable-line class-methods-use-this const problems = []; this.find().forEach(doc => { if (!Slugs.isDefined(doc.slugID)) { problems.push(`Bad slugID: ${doc.slugID}`); } if (!Semesters.isDefined(doc.effectiveSemesterID)) { problems.push(`Bad semesterID: ${doc.effectiveSemesterID}`); } if (!DesiredDegrees.isDefined(doc.degreeID)) { problems.push(`Bad desiredDegreeID: ${doc.degreeID}`); } let numCourses = 0; _.forEach(doc.coursesPerSemester, (n) => { numCourses += n; }); if (doc.courseList.length !== numCourses) { problems.push(`Mismatch between courseList.length ${doc.courseList.length} and sum of coursesPerSemester ${numCourses}`); // eslint-disable-line } }); return problems; } /** * Returns the AcademicPlans that are effective on or after semesterNumber for the given DesiredDegree. * @param degree the desired degree either a slug or id. * @param semesterNumber (optional) the semester number. if undefined returns the latest AcademicPlans. * @return {any} */ getPlansForDegree(degree, semesterNumber) { const degreeID = DesiredDegrees.getID(degree); if (!semesterNumber) { return this._collection.find({ degreeID, semesterNumber: this.getLatestSemesterNumber() }).fetch(); } return this._collection.find({ degreeID, semesterNumber: { $gte: semesterNumber } }).fetch(); } /** * Returns true if the give academic plan includes graduate classes. * @param {string} planID the id of the academic plan. * @returns {boolean} */ isGraduatePlan(planID) { const plan = this.findDoc(planID); return plan.coursesPerSemester.length > 12; } /** * Returns an array of the latest AcademicPlans. * @return {array} */ getLatestPlans() { const semesterNumber = this.getLatestSemesterNumber(); return this.findNonRetired({ semesterNumber }); } /** * Returns the largest semester number. * @return {number} */ getLatestSemesterNumber() { const plans = this.findNonRetired(); let max = 0; _.forEach(plans, (p) => { if (max < p.semesterNumber) { max = p.semesterNumber; } }); return max; } /** * Returns the plan name and year for the given plan id. * @param planID the id of the academic plan. * @return {string} */ toFullString(planID) { const plan = this.findDoc(planID); const semester = Semesters.findDoc(plan.effectiveSemesterID); return `${plan.name} (${semester.year})`; } /** * Returns an object representing the AcademicPlan docID in a format acceptable to define(). * @param docID The docID of a HelpMessage. * @returns { Object } An object representing the definition of docID. */ dumpOne(docID) { const doc = this.findDoc(docID); const slug = Slugs.getNameFromID(doc.slugID); const degree = DesiredDegrees.findDoc(doc.degreeID); const degreeSlug = Slugs.findDoc(degree.slugID).name; const name = doc.name; const description = doc.description; const semesterDoc = Semesters.findDoc(doc.effectiveSemesterID); const semester = Slugs.findDoc(semesterDoc.slugID).name; const coursesPerSemester = doc.coursesPerSemester; const courseList = doc.courseList; const retired = doc.retired; return { slug, degreeSlug, name, description, semester, coursesPerSemester, courseList, retired }; } }
JavaScript
class CategoriesRoute extends React.Component { render() { return ( <Layout> <Helmet title={"test"} /> <section className="section"> <div className="container"> <div className="columns"> <div className="column is-10 is-offset-1"> {/* <CategoriesGrid /> */} testing </div> </div> </div> </section> </Layout> ); } }
JavaScript
class MarkdownPage extends React.Component { // Refer this page https://www.npmjs.com/package/react-marked-markdown constructor(props) { super(props); this.state = { value: "", copySuccess: "Copy", }; } handleTextChange(e) { e.preventDefault(); this.setState({ value: e.target.value, copySuccess: "Copy" }) if (this.props.onTextChange) { this.props.onTextChange(e.target.value); } debounce(1000)(saveStateToLocalStorage("markdown", this.state.value)); // debounce(1000)(saveStateToLocalStorage("markdown", e.target.value)); } callDraftFromLocalStorage(e) { e.preventDefault(); const lastDraft = loadStateFromLocalStorage("markdown"); if (lastDraft !== undefined) { this.setState({ value: lastDraft, copySuccess: "Copy" }); } } clear() { this.setState({ value: "" }); } showExample() { this.setState({ value: exampleFromLatestPost, }); } copyToClipboardWithCode(value) { const textField = document.createElement("textarea"); const brRegex = /<br\s*[\/]?>/gi; const leftHTMLrapperRegex = /&lt;/g; const rightHTMLWrapperRegex = /&gt;/g; // [1] textField.innerText = value; // [2] document.body.appendChild(textField); // console.log(textField.innerHTML.replace(brRegex, "\r\n")); // [3] textField.value = textField.innerHTML.replace(brRegex, "\r\n").replace(leftHTMLrapperRegex, "<").replace(rightHTMLWrapperRegex, ">"); // [4] textField.select(); // select copies html value document.execCommand("copy"); textField.remove(); this.setState({ copySuccess: "Copied", }) } // copyToClipboard(value) { // const textField = document.createElement("textarea"); // const brRegex = /<br\s*[\/]?>/gi; // // [1] // textField.innerText = value; // document.body.appendChild(textField); // // console.log(textField.innerHTML.replace(brRegex, "\r\n")); // textField.value = textField.innerHTML.replace(brRegex, "\r\n"); // textField.select(); // select copies html value // document.execCommand("copy"); // textField.remove(); // this.setState({ // copySuccess: "Copied", // // value: "", // }) // } // simpleCopyToClipboard(value) { // const textField = document.createElement("textarea"); // textField.innerText = value; // document.body.appendChild(textField); // console.log(textField); // textField.select(); // document.execCommand("copy"); // textField.remove(); // this.setState({ // copySuccess: "Copied", // }) // } eventWithKeyDown = (e) => { if (this.state.value !== "" && e.keyCode === 82 && e.shiftKey) { e.preventDefault(); this.copyToClipboard(this.state.value); this.clear(); } } componentDidMount() { document.onkeydown = this.eventWithKeyDown; setTitle("Steadylearner Markdown Editor"); // this.setState({ // value: loadStateFromLocalStorage("markdown"), // }); } componentWillUnmount() { document.removeEventListener("keydown", this.eventWithKeyDown); } render() { const { placeholder } = { placeholder: "/* Write Markdown here(Escreve Markdown aqui) */", }; const { value, copySuccess } = this.state; const testDraft = loadStateFromLocalStorage("markdown"); return ( <> <MetaTags> <meta name="description" content="React Markdown Editor" /> <meta name="thumbnail" content={`https://www.steadylearner.com/static/images/page/markdown.png`} /> <meta name="keywords" content="React, Markdown Editor, React Markdown Editor, Steadylearner, steadylearner, www.steadylearner, steadylearner blog, Steadylearner blog" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:site_name" content="Steadylearner" /> <meta property="og:url" content="https://steadylearner.com/markdown" /> <meta property="og:title" content={`React Markdown Editor by www.steadylearner.com`} /> <meta property="og:description" content={`React Markdown Editor by Steadylearner - www.steadylearner.com`} /> <meta property="og:image" content={`https://www.steadylearner.com/static/images/page/markdown.png`} /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@steadylearner_p" /> <meta name="twitter:creator" content="www.steadylearner.com" /> <meta name="twitter:title" content={`React Markdown Editor by www.steadylearner.com`} /> <meta name="twitter:description" content={`React Markdown Editor by Steadylearner - www.steadylearner.com`} /> <meta name="twitter:image" content={`https://www.steadylearner.com/static/images/page/markdown.png`} /> {/* <meta id="markdown-description" name="description" content="React Markdown Editor" /> <meta id="markdown-keywords" name="keywords" content="React, Markdown Editor, React Markdown Editor, Steadylearner, steadylearner, www.steadylearner, steadylearner blog, Steadylearner blog" /> <meta id="markdown-og-url" property="og:url" content="https://steadylearner.com/markdown" /> <meta id={`markdown-og-title`} property="og:title" content={`React Markdown Editor by www.steadylearner.com`} /> <meta id={`markdown-og-description`} property="og:description" content={`React Markdown Editor by Steadylearner - www.steadylearner.com`} /> <meta id={`markdown-og-image`} property="og:image" content={`https://www.steadylearner.com/static/images/page/markdown.png`} /> <meta id={`markdown-twitter-title`} name="twitter:title" content={`React Markdown Editor by www.steadylearner.com`} /> <meta id={`markdown-twitter-description`} name="twitter:description" content={`React Markdown Editor by Steadylearner - www.steadylearner.com`} /> <meta id={`markdown-twitter-image`} name="twitter:image" content={`https://www.steadylearner.com/static/images/page/markdown.png`} /> */} </MetaTags> <ConverterCSS converter="markdown" > <section className=" converter-header white width-percent max-width " > <span className=" hover cursor-pointer margin-left-four " onClick={() => this.showExample()} title="Click this will show example to write markdown." > <i className="fas fa-hand-point-right " /> {" "}Example </span> <span className="center-auto" > {/* <span className="center-auto padding-right-four" > */} <Link exact to="/jsx"> <span className="hover cursor-pointer no-text-decoration jsx-link" > <i title="This is link to JSX Converter" className="fab fa-react white" /> </span> </Link> Markdown Converter <span className="fas fa-eraser eraser hover cursor-pointer" onClick={() => this.clear()} title="Clcik it to clear the draft." /> <span className={`hover cursor-pointer `} onClick={(e) => this.callDraftFromLocalStorage(e)} title="Clcik it to load your last draft." > <i className={`fas fa-database ${testDraft && "red-white"}`}></i> </span> </span> <span className={` hover cursor-pointer margin-right-four ${copySuccess === "Copied" && "link--active-blue"} `} onClick={() => this.copyToClipboardWithCode(value)} title="Click it or ⌨ Press shift+r to copy the text" // title="Click it or ⌨ Press shift+r to copy and then clear the text" > <span>{copySuccess}</span> <i className="fas fa-copy text-init" /> </span> </section> <section className="converter-container"> <MarkdownInput className="converter-input" value={value} placeholder={placeholder} onChange={e => this.handleTextChange(e)} /> <MarkdownCSS> <MarkdownResult value={value} /> </MarkdownCSS> </section> </ConverterCSS> </> ); } }
JavaScript
class YServo extends YFunction { constructor(obj_yapi, str_func) { //--- (YServo constructor) super(obj_yapi, str_func); /** @member {string} **/ this._className = 'Servo'; /** @member {number} **/ this._position = YServo.POSITION_INVALID; /** @member {number} **/ this._enabled = YServo.ENABLED_INVALID; /** @member {number} **/ this._range = YServo.RANGE_INVALID; /** @member {number} **/ this._neutral = YServo.NEUTRAL_INVALID; /** @member {YMove} **/ this._move = YServo.MOVE_INVALID; /** @member {number} **/ this._positionAtPowerOn = YServo.POSITIONATPOWERON_INVALID; /** @member {number} **/ this._enabledAtPowerOn = YServo.ENABLEDATPOWERON_INVALID; //--- (end of YServo constructor) } //--- (YServo implementation) imm_parseAttr(name, val) { switch(name) { case 'position': this._position = parseInt(val); return 1; case 'enabled': this._enabled = parseInt(val); return 1; case 'range': this._range = parseInt(val); return 1; case 'neutral': this._neutral = parseInt(val); return 1; case 'move': this._move = val; return 1; case 'positionAtPowerOn': this._positionAtPowerOn = parseInt(val); return 1; case 'enabledAtPowerOn': this._enabledAtPowerOn = parseInt(val); return 1; } return super.imm_parseAttr(name, val); } /** * Returns the current servo position. * * @return {number} an integer corresponding to the current servo position * * On failure, throws an exception or returns YServo.POSITION_INVALID. */ async get_position() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.POSITION_INVALID; } } res = this._position; return res; } /** * Changes immediately the servo driving position. * * @param newval {number} : an integer corresponding to immediately the servo driving position * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_position(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('position',rest_val); } /** * Returns the state of the servos. * * @return {number} either YServo.ENABLED_FALSE or YServo.ENABLED_TRUE, according to the state of the servos * * On failure, throws an exception or returns YServo.ENABLED_INVALID. */ async get_enabled() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.ENABLED_INVALID; } } res = this._enabled; return res; } /** * Stops or starts the servo. * * @param newval {number} : either YServo.ENABLED_FALSE or YServo.ENABLED_TRUE * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_enabled(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('enabled',rest_val); } /** * Returns the current range of use of the servo. * * @return {number} an integer corresponding to the current range of use of the servo * * On failure, throws an exception or returns YServo.RANGE_INVALID. */ async get_range() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.RANGE_INVALID; } } res = this._range; return res; } /** * Changes the range of use of the servo, specified in per cents. * A range of 100% corresponds to a standard control signal, that varies * from 1 [ms] to 2 [ms], When using a servo that supports a double range, * from 0.5 [ms] to 2.5 [ms], you can select a range of 200%. * Be aware that using a range higher than what is supported by the servo * is likely to damage the servo. Remember to call the matching module * saveToFlash() method, otherwise this call will have no effect. * * @param newval {number} : an integer corresponding to the range of use of the servo, specified in per cents * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_range(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('range',rest_val); } /** * Returns the duration in microseconds of a neutral pulse for the servo. * * @return {number} an integer corresponding to the duration in microseconds of a neutral pulse for the servo * * On failure, throws an exception or returns YServo.NEUTRAL_INVALID. */ async get_neutral() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.NEUTRAL_INVALID; } } res = this._neutral; return res; } /** * Changes the duration of the pulse corresponding to the neutral position of the servo. * The duration is specified in microseconds, and the standard value is 1500 [us]. * This setting makes it possible to shift the range of use of the servo. * Be aware that using a range higher than what is supported by the servo is * likely to damage the servo. Remember to call the matching module * saveToFlash() method, otherwise this call will have no effect. * * @param newval {number} : an integer corresponding to the duration of the pulse corresponding to the * neutral position of the servo * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_neutral(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('neutral',rest_val); } async get_move() { /** @type {YMove} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.MOVE_INVALID; } } res = this._move; return res; } async set_move(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval.target)+':'+String(newval.ms); return await this._setAttr('move',rest_val); } /** * Performs a smooth move at constant speed toward a given position. * * @param target : new position at the end of the move * @param ms_duration {number} : total duration of the move, in milliseconds * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async move(target,ms_duration) { /** @type {string} **/ let rest_val; rest_val = String(target)+':'+String(ms_duration); return await this._setAttr('move',rest_val); } /** * Returns the servo position at device power up. * * @return {number} an integer corresponding to the servo position at device power up * * On failure, throws an exception or returns YServo.POSITIONATPOWERON_INVALID. */ async get_positionAtPowerOn() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.POSITIONATPOWERON_INVALID; } } res = this._positionAtPowerOn; return res; } /** * Configure the servo position at device power up. Remember to call the matching * module saveToFlash() method, otherwise this call will have no effect. * * @param newval {number} : an integer * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_positionAtPowerOn(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('positionAtPowerOn',rest_val); } /** * Returns the servo signal generator state at power up. * * @return {number} either YServo.ENABLEDATPOWERON_FALSE or YServo.ENABLEDATPOWERON_TRUE, according to * the servo signal generator state at power up * * On failure, throws an exception or returns YServo.ENABLEDATPOWERON_INVALID. */ async get_enabledAtPowerOn() { /** @type {number} **/ let res; if (this._cacheExpiration <= this._yapi.GetTickCount()) { if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) { return YServo.ENABLEDATPOWERON_INVALID; } } res = this._enabledAtPowerOn; return res; } /** * Configure the servo signal generator state at power up. Remember to call the matching module saveToFlash() * method, otherwise this call will have no effect. * * @param newval {number} : either YServo.ENABLEDATPOWERON_FALSE or YServo.ENABLEDATPOWERON_TRUE * * @return {number} YAPI.SUCCESS if the call succeeds. * * On failure, throws an exception or returns a negative error code. */ async set_enabledAtPowerOn(newval) { /** @type {string} **/ let rest_val; rest_val = String(newval); return await this._setAttr('enabledAtPowerOn',rest_val); } /** * Retrieves a servo for a given identifier. * The identifier can be specified using several formats: * <ul> * <li>FunctionLogicalName</li> * <li>ModuleSerialNumber.FunctionIdentifier</li> * <li>ModuleSerialNumber.FunctionLogicalName</li> * <li>ModuleLogicalName.FunctionIdentifier</li> * <li>ModuleLogicalName.FunctionLogicalName</li> * </ul> * * This function does not require that the servo is online at the time * it is invoked. The returned object is nevertheless valid. * Use the method YServo.isOnline() to test if the servo is * indeed online at a given time. In case of ambiguity when looking for * a servo by logical name, no error is notified: the first instance * found is returned. The search is performed first by hardware name, * then by logical name. * * If a call to this object's is_online() method returns FALSE although * you are certain that the matching device is plugged, make sure that you did * call registerHub() at application initialization time. * * @param func {string} : a string that uniquely characterizes the servo * * @return {YServo} a YServo object allowing you to drive the servo. */ static FindServo(func) { /** @type {YFunction} **/ let obj; obj = YFunction._FindFromCache('Servo', func); if (obj == null) { obj = new YServo(YAPI, func); YFunction._AddToCache('Servo', func, obj); } return obj; } /** * Retrieves a servo for a given identifier in a YAPI context. * The identifier can be specified using several formats: * <ul> * <li>FunctionLogicalName</li> * <li>ModuleSerialNumber.FunctionIdentifier</li> * <li>ModuleSerialNumber.FunctionLogicalName</li> * <li>ModuleLogicalName.FunctionIdentifier</li> * <li>ModuleLogicalName.FunctionLogicalName</li> * </ul> * * This function does not require that the servo is online at the time * it is invoked. The returned object is nevertheless valid. * Use the method YServo.isOnline() to test if the servo is * indeed online at a given time. In case of ambiguity when looking for * a servo by logical name, no error is notified: the first instance * found is returned. The search is performed first by hardware name, * then by logical name. * * @param yctx {YAPIContext} : a YAPI context * @param func {string} : a string that uniquely characterizes the servo * * @return {YServo} a YServo object allowing you to drive the servo. */ static FindServoInContext(yctx,func) { /** @type {YFunction} **/ let obj; obj = YFunction._FindFromCacheInContext(yctx, 'Servo', func); if (obj == null) { obj = new YServo(yctx, func); YFunction._AddToCache('Servo', func, obj); } return obj; } /** * Continues the enumeration of servos started using yFirstServo(). * * @return {YServo} a pointer to a YServo object, corresponding to * a servo currently online, or a null pointer * if there are no more servos to enumerate. */ nextServo() { /** @type {object} **/ let resolve = this._yapi.imm_resolveFunction(this._className, this._func); if(resolve.errorType != YAPI.SUCCESS) return null; /** @type {string|null} **/ let next_hwid = this._yapi.imm_getNextHardwareId(this._className, resolve.result); if(next_hwid == null) return null; return YServo.FindServoInContext(this._yapi, next_hwid); } /** * Starts the enumeration of servos currently accessible. * Use the method YServo.nextServo() to iterate on * next servos. * * @return {YServo} a pointer to a YServo object, corresponding to * the first servo currently online, or a null pointer * if there are none. */ static FirstServo() { /** @type {string|null} **/ let next_hwid = YAPI.imm_getFirstHardwareId('Servo'); if(next_hwid == null) return null; return YServo.FindServo(next_hwid); } /** * Starts the enumeration of servos currently accessible. * Use the method YServo.nextServo() to iterate on * next servos. * * @param yctx {YAPIContext} : a YAPI context. * * @return {YServo} a pointer to a YServo object, corresponding to * the first servo currently online, or a null pointer * if there are none. */ static FirstServoInContext(yctx) { /** @type {string|null} **/ let next_hwid = yctx.imm_getFirstHardwareId('Servo'); if(next_hwid == null) return null; return YServo.FindServoInContext(yctx, next_hwid); } static imm_Const() { return Object.assign(super.imm_Const(), { POSITION_INVALID : YAPI.INVALID_INT, ENABLED_FALSE : 0, ENABLED_TRUE : 1, ENABLED_INVALID : -1, RANGE_INVALID : YAPI.INVALID_UINT, NEUTRAL_INVALID : YAPI.INVALID_UINT, POSITIONATPOWERON_INVALID : YAPI.INVALID_INT, ENABLEDATPOWERON_FALSE : 0, ENABLEDATPOWERON_TRUE : 1, ENABLEDATPOWERON_INVALID : -1 }); } //--- (end of YServo implementation) }
JavaScript
class WLVirtualKeyboardRoot extends WLRoot { /** * Create a new WLVirtualKeyboardRoot. * @param {Object} wlObject The object where the mesh will be added. * @param {Material} material The material to use for this root's mesh. The material will be cloned. * @param {VirtualKeyboardTemplate} [keyboardTemplate=defaultVirtualKeyboardTemplate] The virtual keyboard's layout template. Uses the US QWERTY layout by default. * @param {KeyboardDriver | null} [keyboardDriver=null] The KeyboardDriver to dispatch key events to. If null (default), WLRoot.keyboardDriver is used. * @param {Theme} [theme=new Theme()] The root's theme. If none is supplied, the default theme is used. * @param {number} [unitsPerPixel=0.01] The amount of world units per canvas pixel. Determines the pixel density of the mesh. * @param {number | null} [collisionGroup=1] The collision group that this root's collider will belong to. If null, collider and cursor-target will not be added. * @param {boolean} [registerPointerDriver=true] Register the default pointer driver to this root? If collisionGroup is null, this is forced to false. * @constructor */ constructor(wlObject, material, keyboardTemplate = defaultVirtualKeyboardTemplate, keyboardDriver = null, theme = new Theme(), unitsPerPixel = 0.01, collisionGroup = 1, registerPointerDriver = true) { if(keyboardDriver === null) keyboardDriver = WLRoot.keyboardDriver; super( wlObject, material, new Margin(new VirtualKeyboard(keyboardDriver, keyboardTemplate)), theme, unitsPerPixel, collisionGroup, registerPointerDriver, false, ); this.keyboardDriver = keyboardDriver; } /** * Automatically enables/disables this root if needed/unneeded. Call this * before calling update. */ updateVisibility() { if(!this.valid) return; // Update visibility of virtual keyboard this.enabled = this.keyboardDriver.getFocusedRoot() !== null; } }
JavaScript
class AutocompleteManyInput extends React.Component { initialFormattedValue = [] initialInputValue = this.props.dataStructure === DataStructures.REFERENCE_LIST ? [] : {} state = { dirty: false, inputValue: null, searchText: '', suggestions: [], } inputEl = null anchorEl = null getInputValue = inputValue => { if (inputValue === '') { this.lastFormattedValue = this.initialFormattedValue return this.initialInputValue } const { dataStructure } = this.props switch (dataStructure) { case DataStructures.REFERENCE_LIST: this.lastFormattedValue = inputValue break case DataStructures.REFERENCE_BOOLEAN_MAP: this.lastFormattedValue = Object.keys(inputValue) break case DataStructures.REFERENCE_NUMBER_MAP: this.lastFormattedValue = getSortedKeysByNumericValue(inputValue) break default: this.lastFormattedValue = inputValue } return inputValue } getSuggestions = (inputValue, choices) => { const { dataStructure, hideSelectedSuggestions } = this.props if (!hideSelectedSuggestions) { return choices } let selectedIds switch (dataStructure) { case DataStructures.REFERENCE_BOOLEAN_MAP: case DataStructures.REFERENCE_NUMBER_MAP: case DataStructures.REFERENCE_RECORD_MAP: selectedIds = keys(inputValue) break case DataStructures.REFERENCE_LIST: selectedIds = inputValue || [] break default: selectedIds = [] } if (selectedIds.length) { return choices.filter(item => selectedIds.indexOf(item.id) === -1) } return choices } componentWillMount() { const { choices } = this.props const { value } = this.props.input this.setState({ inputValue: this.getInputValue(value), suggestions: this.getSuggestions(value, choices), }) } componentWillReceiveProps(nextProps) { const { choices, input, inputValueMatcher } = nextProps if (this.props.input.value !== input.value) { this.getInputValue(input.value) } if (!isEqual(this.getInputValue(input.value), this.state.inputValue)) { this.setState({ inputValue: this.getInputValue(input.value), dirty: false, suggestions: this.getSuggestions(input.value, choices), }) // Ensure to reset the filter this.updateFilter('', input.value) } else if (!isEqual(choices, this.props.choices)) { this.setState(({ searchText }) => ({ suggestions: this.getSuggestions( input.value, choices ).filter(suggestion => inputValueMatcher(searchText, suggestion, this.getSuggestionText) ), })) } } getSuggestionValue = suggestion => get(suggestion, this.props.optionValue) getSuggestionText = suggestion => { if (!suggestion) { return '' } const { optionText, translate, translateChoice } = this.props const suggestionLabel = typeof optionText === 'function' ? optionText(suggestion) : get(suggestion, optionText) // We explicitly call toString here because AutoSuggest expect a string return translateChoice ? translate(suggestionLabel, { _: suggestionLabel }).toString() : suggestionLabel.toString() } handleSuggestionSelected = (event, { suggestion, method }) => { const { input } = this.props const choiceValue = this.getSuggestionValue(suggestion) if (this.isChoiceValueSelected(this.state.inputValue, choiceValue)) { return } const newValue = this.addSuggestionValueToCurrent( this.state.inputValue, choiceValue ) input.onChange(newValue) if (method === 'enter') { event.preventDefault() } } handleSuggestionsFetchRequested = () => { const { choices, input, inputValueMatcher } = this.props this.setState(({ searchText }) => ({ suggestions: this.getSuggestions( input.value, choices ).filter(suggestion => inputValueMatcher(searchText, suggestion, this.getSuggestionText) ), })) } handleSuggestionsClearRequested = () => { this.updateFilter('') } handleMatchSuggestionOrFilter = inputValue => { this.setState({ dirty: true, searchText: inputValue, }) this.updateFilter(inputValue) } handleChange = (event, { newValue, method }) => { if (method === 'type' || method === 'escape') { this.handleMatchSuggestionOrFilter(newValue) } } renderInput = inputProps => { const { autoFocus, className, classes, isRequired, label, meta, onChange, resource, source, value, ref, options: { InputProps, suggestionsContainerProps, ...options }, ...other } = inputProps if (typeof meta === 'undefined') { throw new Error( "The TextInput component wasn't called within a redux-form <Field>. Did you decorate it and forget to add the addField prop to your component? See https://marmelab.com/react-admin/Inputs.html#writing-your-own-input-component for details." ) } const { touched, error, helperText = false } = meta // We need to store the input reference for our Popper element containg the suggestions // but Autosuggest also needs this reference (it provides the ref prop) const storeInputRef = input => { this.inputEl = input this.updateAnchorEl() ref(input) } return ( <AutocompleteArrayInputChip clearInputValueOnChange onUpdateInput={onChange} onAdd={this.handleAdd} onDelete={this.handleDelete} value={this.lastFormattedValue} // eslint-disable-next-line inputRef={storeInputRef} error={touched && error} helperText={touched && error && helperText} chipRenderer={this.renderChip} label={ <FieldTitle label={label} source={source} resource={resource} isRequired={isRequired} /> } {...other} {...options} /> ) } renderChip = ( { value, isFocused, isDisabled, handleClick, handleDelete }, key ) => { const { classes = {}, choices, hideSelectedValues } = this.props if (hideSelectedValues) { return null } const suggestion = choices.find( choice => this.getSuggestionValue(choice) === value ) return ( <Chip key={key} className={classNames(classes.chip, { [classes.chipDisabled]: isDisabled, [classes.chipFocused]: isFocused, })} onClick={handleClick} onDelete={handleDelete} label={this.getSuggestionText(suggestion)} /> ) } handleAdd = chip => { const { choices, input, limitChoicesToValue, inputValueMatcher, } = this.props const filteredChoices = choices.filter(choice => inputValueMatcher(chip, choice, this.getSuggestionText) ) let choice = filteredChoices.length === 1 ? filteredChoices[0] : filteredChoices.find(c => this.getSuggestionValue(c) === chip) if (choice === undefined) { choice = filteredChoices[0] } if (choice) { const choiceValue = this.getSuggestionValue(choice) if (this.isChoiceValueSelected(this.state.inputValue, choiceValue)) { this.setState( { suggestions: this.getSuggestions(input.value, this.props.choices), }, () => this.updateFilter('') ) return } const newValue = this.addSuggestionValueToCurrent( this.state.inputValue, choiceValue ) return input.onChange(newValue) } if (limitChoicesToValue) { // Ensure to reset the filter this.updateFilter('') return } const newValue = this.addSuggestionValueToCurrent( this.state.inputValue, chip ) input.onChange(newValue) } handleDelete = chip => { const { input } = this.props const newValue = this.removeSuggesionValueFromCurrent( this.state.inputValue, chip ) input.onChange(newValue) } removeSuggesionValueFromCurrent = (currentValue, removedSuggestionValue) => { if (currentValue && removedSuggestionValue) { const { dataStructure } = this.props switch (dataStructure) { case DataStructures.REFERENCE_LIST: { const newValue = currentValue.filter( item => item !== removedSuggestionValue ) this.lastFormattedValue = newValue return newValue.length ? newValue : null } case DataStructures.REFERENCE_BOOLEAN_MAP: { const newValue = omit(currentValue, [removedSuggestionValue]) if (isEmpty(newValue)) { this.lastFormattedValue = [] return null } this.lastFormattedValue = Object.keys(newValue) return newValue } case DataStructures.REFERENCE_NUMBER_MAP: { const valueWithoutRemovedChoice = omit(currentValue, [ removedSuggestionValue, ]) this.lastFormattedValue = getSortedKeysByNumericValue( valueWithoutRemovedChoice ) return this.lastFormattedValue.length ? this.lastFormattedValue.reduce(function(out, id, index) { out[id] = index + 1 return out }, {}) : null } default: return null } } return null } addSuggestionValueToCurrent = (currentValue, selectedSuggestionValue) => { if (selectedSuggestionValue) { const { dataStructure } = this.props switch (dataStructure) { case DataStructures.REFERENCE_LIST: { const newValue = [ ...(currentValue ? currentValue : []), selectedSuggestionValue, ] this.lastFormattedValue = newValue return newValue } case DataStructures.REFERENCE_BOOLEAN_MAP: { const newValue = { ...(currentValue ? currentValue : {}), [selectedSuggestionValue]: true, } this.lastFormattedValue = Object.keys(newValue) return newValue } case DataStructures.REFERENCE_NUMBER_MAP: { let newValue if (!currentValue) { newValue = { [selectedSuggestionValue]: 1, } } else { const currentValuesIndices = Object.values(currentValue) if (!currentValuesIndices.length) { newValue = { [selectedSuggestionValue]: 1, } } else { const maxIndex = max(currentValuesIndices) newValue = { ...currentValue, [selectedSuggestionValue]: maxIndex + 1, } } } this.lastFormattedValue = getSortedKeysByNumericValue(newValue) return newValue } default: return null } } return null } isChoiceValueSelected = (currentValue, choiceValue) => { if (!currentValue) { return false } const { dataStructure } = this.props switch (dataStructure) { case DataStructures.REFERENCE_LIST: return currentValue.includes(choiceValue) case DataStructures.REFERENCE_BOOLEAN_MAP: case DataStructures.REFERENCE_NUMBER_MAP: return currentValue[choiceValue] || false default: return false } } updateAnchorEl() { if (!this.inputEl) { return } const inputPosition = this.inputEl.getBoundingClientRect() if (!this.anchorEl) { const nextPosition = { x: inputPosition.x, left: inputPosition.left, bottom: inputPosition.bottom, width: inputPosition.width, height: inputPosition.height, right: inputPosition.right, top: inputPosition.top + document.body.scrollTop, y: inputPosition.y + document.body.scrollTop, } this.anchorEl = { getBoundingClientRect: () => nextPosition } } else { const anchorPosition = this.anchorEl.getBoundingClientRect() const nextPosition = { x: inputPosition.x, left: inputPosition.left, bottom: inputPosition.bottom, width: inputPosition.width, height: inputPosition.height, right: inputPosition.right, top: inputPosition.top + document.body.scrollTop, y: inputPosition.y + document.body.scrollTop, } if ( anchorPosition.x !== inputPosition.x || anchorPosition.y !== inputPosition.y ) { this.anchorEl = { getBoundingClientRect: () => nextPosition } } } } renderSuggestionsContainer = autosuggestOptions => { const { containerProps: { className, ...containerProps }, children, } = autosuggestOptions const { classes = {}, options } = this.props // Force the Popper component to reposition the popup only when this.inputEl is moved to another location this.updateAnchorEl() return ( <Popper className={className} open={Boolean(children)} anchorEl={this.anchorEl} placement="top-start" {...options.suggestionsContainerProps} > <Paper square className={classes.suggestionsPaper} {...containerProps}> {children} </Paper> </Popper> ) } renderSuggestionComponent = ({ suggestion, query, isHighlighted, ...props }) => <div {...props} /> renderSuggestion = (suggestion, { query, isHighlighted }) => { const label = this.getSuggestionText(suggestion) const matches = match(label, query) const parts = parse(label, matches) const { classes = {}, suggestionComponent } = this.props return ( <MenuItem selected={isHighlighted} component={suggestionComponent || this.renderSuggestionComponent} suggestion={suggestion} query={query} isHighlighted={isHighlighted} > <div> {parts.map((part, index) => part.highlight ? ( <span key={index} className={classes.highlightedSuggestionText}> {part.text} </span> ) : ( <strong key={index} className={classes.suggestionText}> {part.text} </strong> ) )} </div> </MenuItem> ) } handleFocus = () => { const { input } = this.props input && input.onFocus && input.onFocus() } updateFilter = (value, inputValues) => { const { setFilter } = this.props // hack for calling this method in componentWillReceiveProps (should be replaced with componentDidUpdate) const selectedValues = inputValues || this.props.input.value const choices = this.getSuggestions(selectedValues, this.props.choices) if (this.previousFilterValue !== value) { if (setFilter) { this.setState({ searchText: value }, () => setFilter(value)) } else { this.setState({ searchText: value, suggestions: value === '' ? choices : choices.filter(choice => this.getSuggestionText(choice) .toLowerCase() .includes(value.toLowerCase()) ), }) } } this.previousFilterValue = value } shouldRenderSuggestions = val => { const { shouldRenderSuggestions } = this.props if ( shouldRenderSuggestions !== undefined && typeof shouldRenderSuggestions === 'function' ) { return shouldRenderSuggestions(val) } return true } render() { const { alwaysRenderSuggestions, classes = {}, isRequired, label, meta, resource, source, className, options, } = this.props const { suggestions, searchText } = this.state return ( <Autosuggest theme={{ container: classes.container, suggestionsContainerOpen: classes.suggestionsContainerOpen, suggestionsList: classes.suggestionsList, suggestion: classes.suggestion, }} renderInputComponent={this.renderInput} suggestions={suggestions} alwaysRenderSuggestions={alwaysRenderSuggestions} onSuggestionSelected={this.handleSuggestionSelected} onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested} onSuggestionsClearRequested={this.handleSuggestionsClearRequested} renderSuggestionsContainer={this.renderSuggestionsContainer} getSuggestionValue={this.getSuggestionText} renderSuggestion={this.renderSuggestion} shouldRenderSuggestions={this.shouldRenderSuggestions} inputProps={{ blurBehavior: 'add', className, classes, isRequired, label, meta, onChange: this.handleChange, resource, source, value: searchText, onFocus: this.handleFocus, options, }} /> ) } }
JavaScript
class Background { constructor() { this._port; this._mainTab; this.init(); } /** * Document Ready * @returns {void} */ init() { console.log("loaded BackgroundScripts"); //Redirect to google OAuth when extension installed ext.runtime.onInstalled.addListener(() => this.onInstalled()); //Add message listener in Browser. ext.runtime.onMessage.addListener((message, sender, reply) => this.onMessage(message, sender, reply) ); //Add message listener from Extension ext.extension.onConnect.addListener(port => this.onConnect(port)); //Add Update listener for tab ext.tabs.onUpdated.addListener((tabId, changeInfo, tab) => this.onUpdatedTab(tabId, changeInfo, tab) ); // //Add Listener for browser action // ext.browserAction.onClicked.addListener(tabId => // this.onClickedExtension(tabId) // ); } /** * Extension Installed Handler */ onInstalled() { console.log("Installed Palawan Extension! Redirect to Auth page!"); } /** * Clicked Extension ICON * * @param {*} tabId */ onClickedExtension(tabId) { console.log("Browser Action!", tabId); } /** * Message Handler Function * * @param { object } message * @param { object } sender * @param { object } reply */ onMessage(message, sender, reply) { console.log("Message from ContentScript", message); switch (message.type) { case MSG_CHECKAUTH: { //message for checking Auth axios .post(API_CHECK_AUTH) .then(function(res) { reply({ isAuth: true }); }) .catch(function(err) { reply({ isAuth: false }); }); break; } } return true; } /** * Connect with Extension * * @param {*} port */ onConnect(port) { this._port = port; console.log("Connected ....."); this._port.onMessage.addListener(msg => this.onMessageFromExtension(msg)); } /** * Message from Extension * * @param {*} msg */ onMessageFromExtension(msg) { console.log("message recieved:" + msg); } /** *Handle Updated Tab Info * * @param {*} tabId * @param {*} changeInfo * @param {*} tab */ onUpdatedTab(tabId, changeInfo, tab) { if (tab.url.indexOf("mail.google.com") > -1) { // Shows the page action ext.pageAction.show(tabId); } } }
JavaScript
class NumberSettingView extends SettingView { /** * Constructor */ constructor () { super() this._$input = null } /** * Retrieves value from model and updates it in view. * @return {SettingView} Fluent interface */ updateValue () { this._$input.value = this.getModel().getValue() return this } /** * Renders view. * @protected * @return {HTMLElement} */ render () { let $root = super.render() $root.classList.add('setting-number') return $root } /** * Renders field. * @protected * @return {?HTMLElement} */ renderField () { this._$input = document.createElement('input') this._$input.classList.add('setting-number__input') this._$input.setAttribute('type', 'number') this._$input.addEventListener('input', this.inputValueDidChange.bind(this), false) let $stepDown = document.createElement('a') $stepDown.classList.add('setting-number__btn-step-down') $stepDown.setAttribute('href', '#') $stepDown.innerText = 'Step Down' $stepDown.addEventListener('click', this.stepDownButtonDidClick.bind(this)) let $value = document.createElement('div') $value.classList.add('setting-number__value') $value.appendChild(this._$input) let $stepUp = document.createElement('a') $stepUp.classList.add('setting-number__btn-step-up') $stepUp.setAttribute('href', '#') $stepUp.innerText = 'Step Up' $stepUp.addEventListener('click', this.stepUpButtonDidClick.bind(this)) let $field = super.renderField() $field.classList.remove('setting__field') $field.classList.add('setting-number__field') $field.appendChild($stepDown) $field.appendChild($value) $field.appendChild($stepUp) return $field } /** * Triggered when input value has been changed. * @param {Event} evt */ inputValueDidChange (evt) { // notify model this.getModel().viewValueDidChange(this, this._$input.value) } /** * Triggered when step down button has been clicked. * @param {Event} evt */ stepDownButtonDidClick (evt) { this.getModel().stepDown() evt.preventDefault() return false } /** * Triggered when step up button has been clicked. * @param {Event} evt */ stepUpButtonDidClick (evt) { this.getModel().stepUp() evt.preventDefault() return false } }
JavaScript
class UniformPasswordSystemTable extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); this.state = { detail: { show: false } }; } getContentKey() { return 'acc:content.uniformPasswordSystem'; } getManager() { return manager; } getDefaultSearchParameters() { return this.getManager().getDefaultSearchParameters(); } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } cancelFilter(event) { if (event) { event.preventDefault(); } this.refs.table.cancelFilter(this.refs.filterForm); } showDetail(entity) { const { entityId } = this.props.match.params; if (!Utils.Entity.isNew(entity)) { this.context.store.dispatch(this.getManager().fetchPermissions(entity.id, `${this.getUiKey()}-detail`)); } else { entity.uniformPassword = entityId; } // super.showDetail(entity, () => { this.refs.system.focus(); }); } save(entity, event) { const formEntity = this.refs.form.getData(); // super.save(formEntity, event); } afterSave(entity, error) { if (!error) { this.addMessage({ message: this.i18n('save.success', { count: 1, record: this.getManager().getNiceLabel(entity) }) }); } // super.afterSave(entity, error); } render() { const { uiKey, columns, forceSearchParameters, className, _permissions } = this.props; const { showLoading, detail, _showLoading } = this.state; return ( <Basic.Div> <Basic.Row> <Basic.Col lg={ 12 } > <Basic.Confirm ref="confirm-delete" level="danger"/> <Advanced.Table ref="table" uiKey={ uiKey } manager={ this.getManager() } rowClass={ ({rowIndex, data}) => Utils.Ui.getRowClass(data[rowIndex]) } filterOpened forceSearchParameters={ forceSearchParameters } showRowSelection showLoading={ showLoading } buttons={[ <span> <Basic.Button level="success" key="add_button" className="btn-xs" onClick={ this.showDetail.bind(this, { }) } rendered={ Managers.SecurityManager.hasAuthority('UNIFORM_PASSWORD_CREATE') } icon="fa:plus"> { this.i18n('button.add') } </Basic.Button> </span> ]} actions={ [ { value: 'delete', niceLabel: this.i18n('action.delete.action'), action: this.onDelete.bind(this), disabled: false } ] } _searchParameters={ this.getSearchParameters() } className={ className }> <Advanced.Column header="" className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={ this.i18n('button.detail') } onClick={ this.showDetail.bind(this, data[rowIndex]) }/> ); } } sort={false}/> <Advanced.Column property="system" sortProperty="system.name" face="text" header={ this.i18n('acc:entity.UniformPasswordSystem.system') } sort cell={ ({ rowIndex, data }) => { const entity = data[rowIndex]; return ( <Advanced.EntityInfo entityType="system" entityIdentifier={ entity.system } entity={ entity._embedded.system } face="popover" showIcon/> ); } } rendered={_.includes(columns, 'system')}/> </Advanced.Table> </Basic.Col> </Basic.Row> <Basic.Modal bsSize="large" show={detail.show} onHide={this.closeDetail.bind(this)} backdrop="static" keyboard={!_showLoading}> <form onSubmit={this.save.bind(this, {})}> <Basic.Modal.Header icon="fa:list-alt" closeButton={ !_showLoading } text={ this.i18n('create.header')} rendered={ Utils.Entity.isNew(detail.entity) }/> <Basic.Modal.Header icon="fa:list-alt" closeButton={ !_showLoading } text={ this.i18n('edit.header', { name: this.getManager().getNiceLabel(detail.entity) }) } rendered={ !Utils.Entity.isNew(detail.entity) }/> <Basic.Modal.Body> <Basic.AbstractForm ref="form" data={ detail.entity } showLoading={ _showLoading } readOnly={ !this.getManager().canSave(detail.entity, _permissions) }> <Basic.SelectBox ref="uniformPassword" manager={ uniformPasswordManager } clearable={ false } label={ this.i18n('acc:entity.UniformPasswordSystem.uniformPassword') } required readOnly/> <Basic.SelectBox ref="system" manager={ systemManager } label={ this.i18n('acc:entity.UniformPasswordSystem.system') } required/> </Basic.AbstractForm> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={ this.closeDetail.bind(this) } showLoading={ _showLoading }> { this.i18n('button.close') } </Basic.Button> <Basic.Button type="submit" level="success" rendered={ manager.canSave(detail.entity, _permissions) } showLoading={ _showLoading} showLoadingIcon showLoadingText={ this.i18n('button.saving') }> {this.i18n('button.save')} </Basic.Button> </Basic.Modal.Footer> </form> </Basic.Modal> </Basic.Div> ); } }
JavaScript
class SingleSkill extends Component { constructor(props) { super(props); //SkillContainer holds all the required skills we need to render in skillData //Their data will be stored in retrievedData after it has been fetched this.state = { retrievedData: [], skillData: props.skillData, loading: true }; } componentDidMount(){ const { skillData } = this.state this._isMounted = true; axiosRetry(axios, { retries: 5 }); //Retries request up to 5 times if request fails //Execute call then store it in the state axios.get(`https://maplestory.io/api/GMS/${version}/job/skill/${skillData.id}`) .then(response => { if(this._isMounted){ const skillData = []; skillData.push(response.data); this.setState({ retrievedData: skillData, loading: false }); } }) .catch(err => console.log(err)); } componentWillUnmount(){ // Need to control isMounted value so we cancel the API call when component is unmounted this._isMounted = false; } render() { const { loading, retrievedData } = this.state return ( <div> { loading ? <div style={{margin: '2rem 40% 2rem 40%'}}><Image src={loadingImage}/><div style={{paddingLeft: '0.5rem'}}>Loading!</div></div> : <div> { retrievedData.map((skill, index) => <div key={skill.description.id}> <SkillInfo skillData={this.state.skillData} name={skill.description.name} desc={skill.description.desc} shortDesc={skill.description.shortDesc} properties={skill.properties} maxLevel={skill.properties.maxLevel}/> </div>) } </div> } </div> ); } }
JavaScript
class Square extends Rectangle{ constructor(side){ super(side,side); } }
JavaScript
class IncludeCodeTag { constructor(hexo, opts, highlighter) { this.hexo = hexo; this.opts = opts; this.highlighter = highlighter; } _tag = async (post, args) => { const { hexo, opts, highlighter } = this; const codeDir = hexo.config.code_dir; if (!opts.enable) return; args = args.filter(v => v); const path = args.shift(); // Exit if path is not defined if (!path) return; const src = pathFn.join(hexo.source_dir, codeDir, path); const code = await fs.readFile(src, 'utf-8'); const { rendered, allDeps } = highlighter.highlight(code, args); const post_deps = new Set([...post._prism_plus_deps, ...allDeps]); // make sure to modify inplace, the post object may be shadow copied around post._prism_plus_deps.splice(0, post._prism_plus_deps.length, ...post_deps); hexo.log.debug('Saved', allDeps, 'to post:', post._prism_plus_deps); return rendered; } register() { const self = this; this.hexo.extend.tag.register('includecode', function(args) { return self._tag(this, args); }, { async: true }); } }
JavaScript
class Dashboard { constructor(viewer, panels) { var _this = this; this._viewer = viewer; this._panels = panels; this._viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, (viewer) => { this.adjustLayout(); setTimeout(function () { _this._viewer.resize() }, 500); _this._viewer.resize(); _this.loadPanels(); }); } adjustLayout() { // this function may vary for layout to layout... // for learn forge tutorials, let's get the ROW and adjust the size of the // columns so it can fit the new dashboard column, also we added a smooth transition css class for a better user experience var row = $(".row").children(); if (row.length === 3) return; $(row[0]).removeClass('col-sm-4').addClass('col-sm-2 transition-width'); $(row[1]).removeClass('col-sm-8').addClass('col-sm-7 transition-width').after('<div class="col-sm-3 transition-width" id="dashboard"></div>'); } loadPanels() { var _this = this; var data = new ModelData(this._viewer); data.init(function () { $('#dashboard').empty(); _this._panels.forEach(function (panel) { // let's create a DIV with the Panel Function name and load it panel.load('dashboard', viewer, data); }); }); } }
JavaScript
class Suite { constructor({ testFiles, context, subTasks }) { this.context = context; this.subTasks = subTasks; this.tests = testFiles.map((testFile) => { return new Test({ testDef: testFile, suite: this }); }); } run() { this.tests.forEach((test) => { test.run(); }); } }
JavaScript
class Test { constructor({ testDef, suite }) { this.suite = suite; this.context = JSON.parse(JSON.stringify(suite.context)); this.testDef = testDef; this.subtasks = testDef.subtasks || {}; this.cases = testDef.cases.map((testCaseDef) => { return new TestCase({ testCaseDef, test: this, context: this.context }); }); } run() { describe(this.testDef.description, () => { if (this.testDef.disabled) { return; } if (this.testDef.disable) { if (this.testDef.disable.envs) { if (this.testDef.disable.envs.includes(this.context.config.env)) { utils.info('skipping test because it is disabled for env: ' + this.context.config.env); return; } } } // const defaultUrl = this.testDef.defaultUrl || '/'; this.cases.forEach((testCase) => { testCase.run(it); }); }); } }
JavaScript
class PolynomialGF256 { /** * Construct a polynomial in GF256 * @param coefficients */ constructor(coefficients) { this.coefficients = coefficients; this.degree = this.coefficients.length - 1; } /** * Evaluate the polynomial at point x * @param x * @returns result of the evaluation of the polynomial at point x */ evaluate(x) { GF256.checkRange(x); let res = this.coefficients[0]; for (let i = 1; i <= this.degree; ++i) { res = GF256.add(GF256.mul(x, res), this.coefficients[i]); } return res; } /** * Returns a (partly)random polynomial of degree `degree` initialized * with coefficients `coefficients` in GF256 * @param degree integer < 255 * @param coefficients array of Uint8 representing coefficients in GF256 used to * initialize the polynomial starting from the highest degree to the * lowest degree. If len(coefficients) < degree, the additional * coefficients will be randomly generated * @returns the polynomial */ static getRandomPoly(degree, coefficients) { if (degree > 255) { throw new RangeError("Cannot create a polynomial with degree bigger than the field"); } const providedCoeffsLength = coefficients !== undefined ? coefficients.length : 0; // generate random coefficients const randomCoeffs = new Uint8Array(degree + 1 - providedCoeffsLength) .fill(0) .map(() => { const b = randomBytes(1); return parseInt(b.toString("hex"), 16); }); const polyCoeffs = coefficients ? new Uint8Array([...randomCoeffs, ...coefficients]) : randomCoeffs; return new PolynomialGF256(polyCoeffs); } }
JavaScript
class GroupTransformer extends Stream.Transform { constructor(keySelector, description, silent) { super({ objectMode: true }); assert.argumentIsRequired(keySelector, 'keySelector', Function); assert.argumentIsOptional(description, 'description', String); assert.argumentIsOptional(silent, 'silent', Boolean); this._keySelector = keySelector; this._description = description || 'Group Transformer'; this._silent = is.boolean(silent) && silent; this._counter = 0; this._batch = null; this._key = null; } _transform(chunk, encoding, callback) { this._counter = this._counter + 1; let error = null; if (is.object(chunk)) { let key; try { key = this._keySelector(chunk); } catch (e) { error = e; } if (error === null) { if (!object.equals(this._key, key)) { publish.call(this); this._key = key; } this._batch.push(chunk); } } else { error = new Error(`Transformation [ ${this._counter} ] for [ ${this._description} ] failed, unexpected input type.`); } if (error === null) { callback(); } else { if (this._silent) { logger.warn(`Transformation [ ${this._counter} ] for [ ${this._description} ] failed.`); if (logger.isTraceEnabled() && chunk) { logger.trace(chunk); } error = null; } callback(error, null); } } _flush(callback) { publish.call(this); callback(); } toString() { return '[GroupTransformer]'; } }
JavaScript
class DTO { static get take() { return Projection; } static translate(source, dto, options) { return Translator.translate(source, dto, options); } static merge(target, source, options) { options = options || { isNullOverride: true, isMergeArrays: true }; return Hoek.merge(target, source, options.isNullOverride, options.isMergeArrays); } }
JavaScript
class MergeRequestChanges { /** * Constructs a new <code>MergeRequestChanges</code>. * Show the merge request changes * @alias module:model/MergeRequestChanges */ constructor() { MergeRequestChanges.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>MergeRequestChanges</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/MergeRequestChanges} obj Optional instance to populate. * @return {module:model/MergeRequestChanges} The populated <code>MergeRequestChanges</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new MergeRequestChanges(); if (data.hasOwnProperty('assignee')) { obj['assignee'] = UserBasic.constructFromObject(data['assignee']); } if (data.hasOwnProperty('author')) { obj['author'] = UserBasic.constructFromObject(data['author']); } if (data.hasOwnProperty('changes')) { obj['changes'] = RepoDiff.constructFromObject(data['changes']); } if (data.hasOwnProperty('created_at')) { obj['created_at'] = ApiClient.convertToType(data['created_at'], 'String'); } if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); } if (data.hasOwnProperty('downvotes')) { obj['downvotes'] = ApiClient.convertToType(data['downvotes'], 'String'); } if (data.hasOwnProperty('force_remove_source_branch')) { obj['force_remove_source_branch'] = ApiClient.convertToType(data['force_remove_source_branch'], 'String'); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('iid')) { obj['iid'] = ApiClient.convertToType(data['iid'], 'String'); } if (data.hasOwnProperty('labels')) { obj['labels'] = ApiClient.convertToType(data['labels'], 'String'); } if (data.hasOwnProperty('merge_commit_sha')) { obj['merge_commit_sha'] = ApiClient.convertToType(data['merge_commit_sha'], 'String'); } if (data.hasOwnProperty('merge_status')) { obj['merge_status'] = ApiClient.convertToType(data['merge_status'], 'String'); } if (data.hasOwnProperty('merge_when_build_succeeds')) { obj['merge_when_build_succeeds'] = ApiClient.convertToType(data['merge_when_build_succeeds'], 'String'); } if (data.hasOwnProperty('milestone')) { obj['milestone'] = Milestone.constructFromObject(data['milestone']); } if (data.hasOwnProperty('project_id')) { obj['project_id'] = ApiClient.convertToType(data['project_id'], 'String'); } if (data.hasOwnProperty('sha')) { obj['sha'] = ApiClient.convertToType(data['sha'], 'String'); } if (data.hasOwnProperty('should_remove_source_branch')) { obj['should_remove_source_branch'] = ApiClient.convertToType(data['should_remove_source_branch'], 'String'); } if (data.hasOwnProperty('source_branch')) { obj['source_branch'] = ApiClient.convertToType(data['source_branch'], 'String'); } if (data.hasOwnProperty('source_project_id')) { obj['source_project_id'] = ApiClient.convertToType(data['source_project_id'], 'String'); } if (data.hasOwnProperty('state')) { obj['state'] = ApiClient.convertToType(data['state'], 'String'); } if (data.hasOwnProperty('subscribed')) { obj['subscribed'] = ApiClient.convertToType(data['subscribed'], 'String'); } if (data.hasOwnProperty('target_branch')) { obj['target_branch'] = ApiClient.convertToType(data['target_branch'], 'String'); } if (data.hasOwnProperty('target_project_id')) { obj['target_project_id'] = ApiClient.convertToType(data['target_project_id'], 'String'); } if (data.hasOwnProperty('title')) { obj['title'] = ApiClient.convertToType(data['title'], 'String'); } if (data.hasOwnProperty('updated_at')) { obj['updated_at'] = ApiClient.convertToType(data['updated_at'], 'String'); } if (data.hasOwnProperty('upvotes')) { obj['upvotes'] = ApiClient.convertToType(data['upvotes'], 'String'); } if (data.hasOwnProperty('user_notes_count')) { obj['user_notes_count'] = ApiClient.convertToType(data['user_notes_count'], 'String'); } if (data.hasOwnProperty('web_url')) { obj['web_url'] = ApiClient.convertToType(data['web_url'], 'String'); } if (data.hasOwnProperty('work_in_progress')) { obj['work_in_progress'] = ApiClient.convertToType(data['work_in_progress'], 'String'); } } return obj; } }
JavaScript
class FKField extends BaseField { static NOT_FOUND_TEXT = '[Object not found]'; constructor(options) { super(options); this.valueField = this.props.value_field; this.viewField = this.props.view_field; this.usePrefetch = this.props.usePrefetch; this.makeLink = this.props.makeLink; this.dependence = this.props.dependence || {}; this.filters = this.props.filters || null; this.filterName = this.props.filter_name || this.valueField; this.filterFieldName = this.props.filter_field_name || this.valueField; if (hasOwnProp(this.props, 'fetchData')) { this.fetchData = this.props.fetchData; } else { this.fetchData = this.viewField !== this.valueField; } if (this.props.querysets instanceof Map) { this.querysets = this.props.querysets; } else { this.querysets = new Map(Object.entries(this.props.querysets || {})); } if (!this.fkModel && this.props.model) { registerHook('app.beforeInit', this.resolveModel.bind(this)); } } resolveModel() { this.fkModel = this.constructor.app.modelsResolver.bySchemaObject(this.props.model); } static get mixins() { return [FKFieldMixin]; } getEmptyValue() { return null; } toInner(data) { return this.getValueFieldValue(super.toInner(data)); } isSameValues(data1, data2) { let val1 = this.toInner(data1); if (val1 && typeof val1 === 'object') { val1 = val1[this.valueField]; } let val2 = this.toInner(data2); if (val2 && typeof val2 === 'object') { val2 = val2[this.valueField]; } return val1 === val2; } prepareFieldForView(path) { if (this.querysets.has(path)) return; let querysets; const { list_paths } = this.props; if (list_paths) { querysets = list_paths.map((listPath) => app.views.get(listPath).objects.clone()); if (!this.fkModel) { this.fkModel = querysets[0].getResponseModelClass(RequestTypes.LIST); } } else { querysets = [this.constructor.app.qsResolver.findQuerySet(this.fkModel.name, path)]; } this.querysets.set(path, querysets); } _formatQuerysets(querysets) { return querysets.map((qs) => this._formatQuerysetPath(qs)); } _formatQuerysetPath(queryset) { const params = this.constructor.app.application?.$route?.params || {}; return queryset.clone({ url: formatPath(queryset.url, params) }); } async afterInstancesFetched(instances, qs) { if (qs.prefetchEnabled && this.usePrefetch && this.fetchData) { const path = this.constructor.app.application.$refs.currentViewComponent?.view?.path || this.constructor.app.application.$route.name; return this.prefetchValues(instances, path); } } prefetchValues(instances, path) { const qs = this.getAppropriateQuerySet({ path }); if (!qs) return; return this._fetchRelated( instances.map((instance) => this._getValueFromData(instance._data)), qs, ).then((fetchedInstances) => { for (let i = 0; i < fetchedInstances.length; i++) { instances[i]._setFieldValue(this.name, fetchedInstances[i], true); } }); } /** * @param {Array<Object|number>} pks * @param {QuerySet} qs * @return {Promise<Model[]>} */ _fetchRelated(pks, qs) { const executor = new AggregatedQueriesExecutor( qs.clone({ prefetchEnabled: false }), this.filterName, this.filterFieldName, ); const promises = pks.map((pk) => pk ? executor.query(pk).catch(() => { const notFound = new this.fkModel({ [this.valueField]: pk, [this.viewField]: i18n.t(this.constructor.NOT_FOUND_TEXT), }); notFound.__notFound = true; return notFound; }) : Promise.resolve(pk), ); executor.execute(); return Promise.all(promises); } _resolveDependenceValue(key) { const foundTemplates = new Set( Array.from(key.matchAll(dependenceTemplateRegexp), (arr) => arr[0].slice(2, -2)).filter((el) => validAttrs.includes(el), ), ); if (foundTemplates.size === 0) { return; } for (const template of foundTemplates) { const handler = dependenceTemplates.get(template); try { key = template.replace( template, handler(this.constructor.app.application.$refs.currentViewComponent), ); } catch (error) { console.warn(error.message); return; } } return key; } /** * Method that returns dependence filters. If null is returned it means that at least one of required * and non nullable fields is empty and field should be disabled. * @param {Object} data * @return {Object|null} */ getDependenceFilters(data) { const filters = {}; for (const [fieldName, filter] of Object.entries(this.dependence)) { let dependenceValue = this._resolveDependenceValue(fieldName); if (dependenceValue !== undefined) { filters[filter] = dependenceValue; continue; } const field = this.model.fields.get(fieldName); dependenceValue = getDependenceValueAsString(field.toInner(data)); if (dependenceValue) { filters[filter] = dependenceValue; } else if (!field.nullable && field.required) { return null; } } return filters; } getValueFieldValue(val) { if (val !== null && typeof val === 'object') { if (val._data) { return val._data[this.valueField]; } else { return val.value; } } return val; } getViewFieldValue(val) { if (val !== null && typeof val === 'object') { return val[this.viewField]; } return val; } /** * Method, that selects one, the most appropriate queryset, from querysets array. * @param {object} data Object with instance data. * @param {array=} querysets Array with field QuerySets. * @param {string} path * @return {QuerySet|undefined} */ // eslint-disable-next-line no-unused-vars getAppropriateQuerySet({ data, querysets, path } = {}) { const [qs] = querysets || this.querysets.get(path) || []; if (qs) { return this._formatQuerysetPath(qs); } } getFallbackQs() { return this.constructor.app.qsResolver.findQuerySet(this.fkModel.name); } getAllQuerysets(path) { return this._formatQuerysets( this.querysets.get(path) || this.querysets.get(undefined) || [this.getFallbackQs()], ); } }
JavaScript
class Path extends Component { /** * Path constructor * @param {PositionDefinition} positionDefinition - Starting position of the Path * @param {Array<Instruction>|String} instructions - Set of instructions to follow to draw it * @param {Boolean} [isClosed=true] - Should the path close itself (add a line to the starting position) * @param {ComponentOptions|LineOptions} [options] - Drawing options */ constructor (positionDefinition, instructions, isClosed = true, options) { super(positionDefinition, options); if (!isClosed) { // Overrides options to work like a line if not closed this.options = (new Line(this.position, [], options)).options; } this.instructions = instructions; this.isClosed = isClosed; this.closing = Path.lineTo(new Position()); } /** * Draw the path * @param {Path2D} path - Current drawing path * @return {Path} Itself */ trace (path) { let lastPosition = new Position(); const instructions = this.instructions.slice(); if (Array.isArray(instructions)) { if (this.isClosed) { const lastTarget = this.instructions[this.instructions.length - 1].target; path.moveTo(lastTarget.x, lastTarget.y); instructions.unshift(this.closing); instructions.push(this.closing); lastPosition = lastTarget; } else { path.moveTo(0, 0); } instructions.forEach(instruction => lastPosition = instruction.execute(path, lastPosition)); } else if (typeof instructions === "string") { const svg = new window.Path2D(`M0 0 ${instructions}${this.isClosed ? " Z" : ""}`); path.addPath(svg); } return this; } /** * @inheritDoc */ isHover (positionDefinition, ctx) { return super.isHover(positionDefinition, ctx); } /** * @inheritDoc */ toJSON () { const { instructions, isClosed } = this; return { ...super.toJSON(), instructions, isClosed, }; } /** * @inheritDoc * @param {Object} definition - Path definition * @return {Path} */ static from (definition) { return new Path( definition.position, definition.instructions.map(instruction => Instruction.from(instruction)), definition.isClosed, definition.options, ); } /** * Draw a line to a position * @param {PositionDefinition} position - Any position * @return {Instruction} */ static lineTo (position) { return new Instruction((path, pos) => path.lineTo(pos.x, pos.y), position); } /** * Move the pencil without drawing * @param {PositionDefinition} position - Any position * @return {Instruction} */ static moveTo (position) { return new Instruction((path, pos) => path.moveTo(pos.x, pos.y), position); } /** * Draw an quarter circle arc to a position * @param {PositionDefinition} position - Any position * @param {Boolean} [clockwise=true] - Should the arc be clockwise or not * @return {Instruction} */ static quarterTo (position, clockwise) { return Path.arcTo(position, 0.25, (4 / 3) * (Math.sqrt(2) - 1), clockwise); } /** * Draw an quarter circle arc to a position * @param {PositionDefinition} position - Any position * @param {Boolean} [clockwise=true] - Should the arc be clockwise or not * @return {Instruction} */ static halfTo (position, clockwise) { return Path.arcTo(position, 0.5, 4 / 3, clockwise); } /** * Try to approximate an arc between two points * @param {PositionDefinition} position - Any position * @param {Number} angle - Arc angle in ratio of a full circle (should be less than 0.5) * @param {Number} magicRatio - Control points "openness" ratio * @param {Boolean} [clockwise=true] - Should the arc be clockwise or not * @return {Instruction} */ static arcTo (position, angle, magicRatio, clockwise = true) { return new Instruction((path, pos, lp) => { const distance = pos.distance(lp); const radius = distance / 2; const direction = clockwise ? 1 : -1; const alpha = (angle / 2) * direction; const ctrl1 = pos.clone() .subtract(lp).rotate(-alpha) .divide(distance) .multiply(magicRatio * radius) .add(lp); const ctrl2 = lp.clone() .subtract(pos).rotate(alpha) .divide(distance) .multiply(magicRatio * radius) .add(pos); // Approximate a arc with a bezier curve Path.bezierTo(pos, ctrl1, ctrl2).execute(path, lp); }, position); } /** * Draw a quadratic curve to a position * @param {PositionDefinition} position - Any position * @param {PositionDefinition} controlPoint - Point that control the curve * @return {Instruction} */ static quadTo (position, controlPoint) { const control = Position.from(controlPoint); return new Instruction((path, pos) => { path.quadraticCurveTo(control.x, control.y, pos.x, pos.y); }, position); } /** * Draw a bezier curve to a position * @param {PositionDefinition} position - Any position * @param {PositionDefinition} firstControlPoint - First point to control the curve * @param {PositionDefinition} secondControlPoint - Second point to control the curve * @return {Instruction} */ static bezierTo (position, firstControlPoint, secondControlPoint) { const control1 = Position.from(firstControlPoint); const control2 = Position.from(secondControlPoint); return new Instruction((path, pos) => { path.bezierCurveTo( control1.x, control1.y, control2.x, control2.y, pos.x, pos.y, ); }, position); } /** * * @param {Array<PositionDefinition>} points - Any set of positions * @param {Number} [tension] - Ratio of tension * @return {Instruction} */ static splineThrough (points, tension) { const controls = points.map(point => Position.from(point)); const last = controls[controls.length - 1]; return new Instruction((path, pos, lp) => { const relativePosition = Position.from(last).clone().subtract(pos); const corrected = controls.map(point => point.clone().subtract(relativePosition)); Spline.splineThrough(path, [lp].concat(corrected), tension); }, last); } /* eslint-disable */ /** * * @param {PositionDefinition} position - Any position * @param {Number} nbWaves - Number of waves to draw * @return {Instruction} */ static waveTo (position, nbWaves) { throw new ReferenceError("This function has yet to be implemented."); return new Instruction((path, pos, lp) => { // TODO }, position); } /** * * @param {PositionDefinition} position - Any position * @param {Number} nbSins - Number of sinusoid to draw * @param {Number} sinsHeight - Height of the sinusoid * @return {Instruction} */ static sinTo (position, nbSins, sinsHeight) { throw new ReferenceError("This function has yet to be implemented."); return new Instruction((path, pos, lp) => { // TODO }, position); } /* eslint-enable */ }
JavaScript
class CancelEvent { /** * Constructs the event arguments for the `cancel` event. * @param files - The list of the files that were going to be uploaded. */ constructor(files) { this.files = files; } }
JavaScript
class ClearEvent extends PreventableEvent { /** * Constructs the event arguments for the `clear` event. */ constructor() { super(); } }
JavaScript
class ErrorEvent { /** * Constructs the event arguments for the `error` event. * * @param files - The list of the files that failed to be uploaded or removed. * @param operation - The operation type (`upload` or `remove`). * @param response - The response object returned by the server. */ constructor(files, operation, response) { this.files = files; this.operation = operation; this.response = response; } }
JavaScript
class RemoveEvent extends PreventableEvent { /** * Constructs the event arguments for the `remove` event. * @param files - The list of the files that will be removed. * @param headers - The headers of the request. */ constructor(files, headers) { super(); this.files = files; this.headers = headers; } }
JavaScript
class SelectEvent extends PreventableEvent { /** * Constructs the event arguments for the `select` event. * @param files - The list of the selected files. */ constructor(files) { super(); this.files = files; } }
JavaScript
class SuccessEvent extends PreventableEvent { /** * Constructs the event arguments for the `success` event. * @param files - The list of the files that were uploaded or removed. * @param operation - The operation type (`upload` or `remove`). * @param response - The response object returned by the server. */ constructor(files, operation, response) { super(); this.files = files; this.operation = operation; this.response = response; } }
JavaScript
class UploadEvent extends PreventableEvent { /** * Constructs the event arguments for the `upload` event. * @param files - The list of the files that will be uploaded. * @param headers - The headers of the request. */ constructor(files, headers) { super(); this.files = files; this.headers = headers; } }
JavaScript
class UploadProgressEvent { /** * Constructs the event arguments for the `uploadprogress` event. * @param files - The list of files that are being uploaded. * @param percentComplete - The portion that has been uploaded. */ constructor(files, percentComplete) { this.files = files; this.percentComplete = percentComplete; } }
JavaScript
class FileTemplateDirective { constructor(templateRef) { this.templateRef = templateRef; } }
JavaScript
class UploadComponent { constructor(uploadService, localization, navigation, _ngZone, renderer, wrapper) { this.uploadService = uploadService; this.localization = localization; this.navigation = navigation; this._ngZone = _ngZone; this.renderer = renderer; /** * Enables the selection of multiple files * ([see example]({% slug fileprocessing_upload %}#toc-upload-of-sinlge-or-multiple-files)). * If set to `false`, only one file can be selected at a time. */ this.multiple = true; /** * Disables the Upload ([see example]({% slug disabledstate_upload %})). * The default value is `false`. */ this.disabled = false; /** * Toggles the visibility of the file list. */ this.showFileList = true; /** * Specifies the [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) of the component. */ this.tabindex = 0; /** * @hidden */ this.focusableId = `k-${guid()}`; /** * Fires when the user navigates outside the component. */ this.onBlur = new EventEmitter(); /** * Fires when the upload is canceled while in progress. */ this.cancel = new EventEmitter(); /** * Fires when the file list is about to be cleared. If prevented, the files will not be cleared. */ this.clear = new EventEmitter(); /** * Fires when all active uploads are completed either successfully or with errors. */ this.complete = new EventEmitter(); /** * Fires when an `upload` or `remove` operation has failed. */ this.error = new EventEmitter(); /** * Fires when the component is focused. */ this.onFocus = new EventEmitter(); /** * Fires when an uploaded file is about to be removed. If prevented, the files will remain in the list. */ this.remove = new EventEmitter(); /** * Fires when files are selected. If prevented, the selected files will not be added to the list. */ this.select = new EventEmitter(); /** * Fires when an `upload` or `remove` operation is successfully completed. */ this.success = new EventEmitter(); /** * Fires when one or more files are about to be uploaded. If prevented, the files will neither be uploaded, nor added to the file list. */ this.upload = new EventEmitter(); /** * Fires when one or more files are being uploaded. */ this.uploadProgress = new EventEmitter(); /** * Fires when the value of the component has changed as a result of a successful `upload`, `remove` or `clear` operation. */ this.valueChange = new EventEmitter(); /** * @hidden */ this.async = { autoUpload: true, batch: false, removeField: "fileNames", removeHeaders: new HttpHeaders(), removeMethod: "POST", removeUrl: "", responseType: "json", saveField: "files", saveHeaders: new HttpHeaders(), saveMethod: "POST", saveUrl: "", withCredentials: true }; /** * @hidden */ this._restrictions = { allowedExtensions: [], maxFileSize: 0, minFileSize: 0 }; this.onTouchedCallback = (_) => { }; this.onChangeCallback = (_) => { }; this.fileList = this.uploadService.files; this.localizationChangeSubscription = localization.changes.subscribe(({ rtl }) => { this.direction = rtl ? 'rtl' : 'ltr'; this.navigation.computeKeys(this.direction); }); this.direction = localization.rtl ? 'rtl' : 'ltr'; this.navigation.computeKeys(this.direction); this.wrapper = wrapper.nativeElement; this.subscribeBlur(); this.subscribeFocus(); this.onCancel(); this.onChange(); this.onClear(); this.onComplete(); this.onError(); this.onRemove(); this.onSelect(); this.onSuccess(); this.onUpload(); this.onUploadProgress(); } /** * By default, the selected files are immediately uploaded * ([see example]({% slug fileprocessing_upload %}#toc-automatic-upload-of-files)). * To change this behavior, set `autoUpload` to `false`. */ set autoUpload(autoUpload) { this.async.autoUpload = autoUpload; } get autoUpload() { return this.async.autoUpload; } /** * When enabled, all files in the selection are uploaded in one request * ([see example]({% slug fileprocessing_upload %}#toc-upload-of-batches-of-files)). * Any files that are selected one after the other are uploaded in separate requests. */ set batch(batch) { this.async.batch = batch; } get batch() { return this.async.batch; } /** * Configures whether credentials (cookies, headers) will be sent for cross-site requests * ([see example]({% slug credentials_upload %}#toc-attaching-credentials-to-requests)). * The default values is `true`. Setting `withCredentials` has no effect on same-site requests. * To add credentials to the request, use the `saveHeaders` or `removeHeaders` property, * or the [`upload`]({% slug api_upload_uploadevent %}) event. */ set withCredentials(withCredentials) { this.async.withCredentials = withCredentials; } get withCredentials() { return this.async.withCredentials; } /** * Sets the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) key which contains the files submitted to `saveUrl`. * The default value is `files`. */ set saveField(saveField) { this.async.saveField = saveField; } get saveField() { return this.async.saveField; } /** * Configures the [`HttpHeaders`](https://angular.io/api/common/http/HttpHeaders) * that are attached to each upload request. */ set saveHeaders(saveHeaders) { this.async.saveHeaders = saveHeaders; } get saveHeaders() { return this.async.saveHeaders; } /** * Sets the [`RequestMethod`](https://angular.io/api/http/RequestMethod) of the upload request. * The default value is `POST`. */ set saveMethod(saveMethod) { this.async.saveMethod = saveMethod; } get saveMethod() { return this.async.saveMethod; } /** * Sets the URL of the endpoint for the upload request. * The request [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) key is named after the `saveField` property. * It contains the list of files to be uploaded. */ set saveUrl(saveUrl) { this.async.saveUrl = saveUrl; } get saveUrl() { return this.async.saveUrl; } /** * Sets the expected [`response type`](https://angular.io/api/common/http/HttpRequest#responseType) of the server. * It is used to parse the response appropriately. * The default value is `json`. */ set responseType(responseType) { this.async.responseType = responseType; } get responseType() { return this.async.responseType; } /** * Sets the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) key * which contains the list of file names that are submitted to `removeUrl`. * The default value is `fileNames`. */ set removeField(removeField) { this.async.removeField = removeField; } get removeField() { return this.async.removeField; } /** * Configures the [`HttpHeaders`](https://angular.io/api/common/http/HttpHeaders) * that are attached to each `remove` request. */ set removeHeaders(removeHeaders) { this.async.removeHeaders = removeHeaders; } get removeHeaders() { return this.async.removeHeaders; } /** * Sets the [`RequestMethod`](https://angular.io/api/http/RequestMethod) of the `remove` request. * The default value is `POST`. */ set removeMethod(removeMethod) { this.async.removeMethod = removeMethod; } get removeMethod() { return this.async.removeMethod; } /** * Sets the URL of the endpoint for the `remove` request. * The [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) request key is named after the `removeField` property. * It contains the list of file names which will be removed. */ set removeUrl(removeUrl) { this.async.removeUrl = removeUrl; } get removeUrl() { return this.async.removeUrl; } /** * @hidden */ set tabIndex(tabIndex) { this.tabindex = tabIndex; } get tabIndex() { return this.tabindex; } /** * Sets the restrictions for selected files ([see example]({% slug api_upload_filerestrictions %})). */ set restrictions(restrictions) { let parsedRestrictions = Object.assign({}, this._restrictions, restrictions); this._restrictions = parsedRestrictions; } get restrictions() { return this._restrictions; } get dir() { return this.direction; } get hostDefaultClasses() { return true; } get hostDisabledClass() { return this.disabled; } ngOnInit() { this.renderer.removeAttribute(this.wrapper, "tabindex"); } ngOnDestroy() { this.fileList.clear(); if (this.blurSubscription) { this.blurSubscription.unsubscribe(); } if (this.wrapperFocusSubscription) { this.wrapperFocusSubscription.unsubscribe(); } if (this.selectButtonFocusSubscription) { this.selectButtonFocusSubscription.unsubscribe(); } if (this.cancelSubscription) { this.cancelSubscription.unsubscribe(); } if (this.changeSubscription) { this.changeSubscription.unsubscribe(); } if (this.clearSubscription) { this.clearSubscription.unsubscribe(); } if (this.completeSubscription) { this.completeSubscription.unsubscribe(); } if (this.errorSubscription) { this.errorSubscription.unsubscribe(); } if (this.removeSubscription) { this.removeSubscription.unsubscribe(); } if (this.selectSubscription) { this.selectSubscription.unsubscribe(); } if (this.successSubscription) { this.successSubscription.unsubscribe(); } if (this.successSubscription) { this.uploadSubscription.unsubscribe(); } if (this.uploadProgressSubscription) { this.uploadProgressSubscription.unsubscribe(); } if (this.localizationChangeSubscription) { this.localizationChangeSubscription.unsubscribe(); } } /** * @hidden */ handleKeydown(event) { if (this.disabled) { return; } if ((event.keyCode === Keys.Enter || event.keyCode === Keys.Space) && event.target === this.fileSelectButton.nativeElement) { event.preventDefault(); this.fileSelect.nativeElement.click(); return; } if (hasClasses(event.target, UPLOAD_CLASSES) || (!isFocusable(event.target) && !hasClasses(event.target, IGNORE_TARGET_CLASSES))) { this.navigation.process(event); } } /** * @hidden */ writeValue(newValue) { let isValid = true; if (newValue instanceof Array) { newValue.forEach((file) => { if (!validateInitialFileInfo(file)) { isValid = false; } }); if (isValid) { this.uploadService.addInitialFiles(newValue); } } } /** * @hidden */ registerOnChange(fn) { this.onChangeCallback = fn; } /** * @hidden */ registerOnTouched(fn) { this.onTouchedCallback = fn; } /** * @hidden */ setDisabledState(isDisabled) { this.disabled = isDisabled; } /** * @hidden */ get selectButtonClasses() { return { "k-button": true, "k-state-focused": this.fileSelectButton.nativeElement.focused, "k-upload-button": true }; } /** * @hidden */ get selectButtonTabIndex() { return this.disabled ? undefined : this.tabIndex; } /** * @hidden */ onFileSelectButtonFocus(_event) { if (!this.navigation.focused) { this.navigation.focusedIndex = -1; } } /** * @hidden */ showActionButtons() { const areVisible = this.fileList.filesToUpload.length > 0 && !this.async.autoUpload; this.navigation.actionButtonsVisible = areVisible; return areVisible; } /** * @hidden */ showTotalStatus() { const states = [ FileState.Uploaded, FileState.Uploading, FileState.Failed ]; if (this.fileList.count === 0) { return false; } if (this.fileList.hasFileWithState(states)) { return true; } return false; } /** * @hidden */ textFor(key) { return this.localization.get(key); } /** * Focuses the underlying input element. */ focus() { setTimeout(() => { this.fileSelectButton.nativeElement.focus(); }); } /** * @hidden * @deprecated */ focusComponent() { this.focus(); } /** * Blurs the Upload if it was previously focused. */ blur() { if (this.navigation.focused) { this.navigation.focused = false; document.activeElement.blur(); this.onBlur.emit(); } } /** * @hidden * @deprecated */ blurComponent() { this.blur(); } /** * Triggers the removal of a file or a batch of files. * @param uid - The `uid` of the file or a batch of files that will be removed. */ removeFilesByUid(uid) { this.uploadService.removeFiles(uid, this.async); } /** * Triggers another upload attempt of an unsuccessfully uploaded file or a batch of files. * @param uid - The `uid` of the file or a batch of files to be retried. */ retryUploadByUid(uid) { this.uploadService.retryFiles(uid, this.async); } /** * Cancels the upload of a file or a batch of files. * @param uid - The `uid` of the file or a batch of files that will be canceled. */ cancelUploadByUid(uid) { this.uploadService.cancelFiles(uid); } /** * Uploads the currently selected files which pass the set restrictions. */ uploadFiles() { if (this.fileList.filesToUpload.length) { this.uploadService.uploadFiles(this.async); } } /** * @hidden * Used by the TextBoxContainer to determine if the component is empty. */ isEmpty() { return false; } subscribeBlur() { if (!isDocumentAvailable()) { return; } this._ngZone.runOutsideAngular(() => { this.documentClick = fromEvent(document, 'click').pipe(filter((event) => { return !(this.wrapper !== event.target && this.wrapper.contains(event.target)); })); this.blurSubscription = merge(this.documentClick, this.navigation.onTab).subscribe(() => this._ngZone.run(() => { if (this.navigation.focused) { this.navigation.focused = false; this.onTouchedCallback(); this.onBlur.emit(); } })); }); } subscribeFocus() { this.wrapperFocusSubscription = this.navigation.onWrapperFocus.subscribe(() => { this.onFocus.emit(); }); this.selectButtonFocusSubscription = this.navigation.onSelectButtonFocus.subscribe(() => { this.fileSelectButton.nativeElement.focus(); }); } onCancel() { this.cancelSubscription = this.uploadService.cancelEvent.subscribe((args) => { this.cancel.emit(args); }); } onChange() { this.changeSubscription = this.uploadService.changeEvent.subscribe((files) => { this.onChangeCallback(files); this.valueChange.emit(files); }); } onClear() { this.clearSubscription = this.uploadService.clearEvent.subscribe((args) => { this.clear.emit(args); }); } onComplete() { this.completeSubscription = this.uploadService.completeEvent.subscribe(() => { this.complete.emit(); }); } onError() { this.errorSubscription = this.uploadService.errorEvent.subscribe((args) => { this.error.emit(args); }); } onRemove() { this.removeSubscription = this.uploadService.removeEvent.subscribe((args) => { this.remove.emit(args); }); } onSelect() { this.selectSubscription = this.uploadService.selectEvent.subscribe((args) => { this.select.emit(args); }); } onSuccess() { this.successSubscription = this.uploadService.successEvent.subscribe((args) => { this.success.emit(args); }); } onUpload() { this.uploadSubscription = this.uploadService.uploadEvent.subscribe((args) => { this.upload.emit(args); }); } onUploadProgress() { this.uploadProgressSubscription = this.uploadService.uploadProgressEvent.subscribe((args) => { this.uploadProgress.emit(args); }); } }
JavaScript
class CustomMessagesComponent extends Messages { constructor(service) { super(); this.service = service; } get override() { return true; } }
JavaScript
class HelloRest extends RestBundle { constructor(name = "greeting", options = {}) { super(name, options); this.greeting = "hello"; var handlers = [ this.resourceMethod("get", "hello", this.getHello, "text/html"), this.resourceMethod("post", "error", this.postDeath), this.resourceMethod("post", "hello", this.postHello), ].concat(super.handlers); Object.defineProperty(this, "handlers", { value: handlers, }); } getHello(req, res) { return this.greeting; } postHello(req, res) { return { post: req.body, } } postDeath(req, res) { throw new Error("Sadness"); } }
JavaScript
class Fulfillment { /** * @return {Fulfillment} */ static create() { return new Fulfillment(); } /** * @param {ConversationV3} conv */ [Action.SETUP_QUIZ](conv) { const defaultParams = conv.$helper.getDefaultSessionParams(); conv.session.params = {...conv.session.params, ...defaultParams}; const quizSettings = conv.$helper.getQuizSettings(); conv.$helper.updateSessionParamsQuizSettings(quizSettings); const convSettings = conv.session.params.quizSettings; conv.session.params.title = convSettings[Alias.QUIZ_SETTINGS.TITLE]; conv.session.params.hasCategory = !!( convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_SUGGESTION_CHIP_1] && convSettings[Alias.QUIZ_SETTINGS.DEFAULT_CATEGORY_OR_TOPIC] && convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_PROMPT] ); conv.session.params.hasDifficulty = !!( convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_SUGGESTION_CHIP_1] && convSettings[Alias.QUIZ_SETTINGS.DEFAULT_DIFFICULTY_OR_GRADE_LEVEL] && convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_PROMPT] ); if (conv.session.params.isReplay) { conv.session.params.category = null; conv.session.params.difficulty = null; conv.session.params.setCategory = false; conv.session.params.setDifficulty = false; } } /** * @param {ConversationV3} conv */ [Action.WELCOME](conv) { if (!conv.session.params.isReplay) { const introAudioUrl = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_GAME_INTRO); let greetings = Prompt.GREETING_PROMPTS_1; if (conv.user.lastSeenTime) greetings = Prompt.GREETING_PROMPTS_2; conv.add(util.ssml.merge([introAudioUrl, greetings])); } } /** * @param {ConversationV3} conv */ [Action.PROMPT_CATEGORY](conv) { const convSettings = conv.session.params.quizSettings; const responses = [convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_PROMPT]]; const chip1 = convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_SUGGESTION_CHIP_1]; const chip2 = convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_SUGGESTION_CHIP_2]; const chip3 = convSettings[Alias.QUIZ_SETTINGS.CATEGORY_OR_TOPIC_SUGGESTION_CHIP_3]; const availableChips = [chip1, chip2, chip3].filter(Boolean); const suggestions = conv.$helper.getRichSuggestions(...availableChips); if (!conv.device.capabilities.includes('RICH_RESPONSE')) { const suggestionsTts = conv.$helper.getSuggestionTts(suggestions); responses.push(suggestionsTts); } conv.$helper.setupSessionTypeAndSpeechBiasing(...availableChips.map((chip) => [chip])); conv.add(util.ssml.merge(responses)); conv.add(...suggestions); } /** * @param {ConversationV3} conv */ [Action.PROMPT_DIFFICULTY](conv) { const convSettings = conv.session.params.quizSettings; const responses = [convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_PROMPT]]; const chip1 = convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_SUGGESTION_CHIP_1]; const chip2 = convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_SUGGESTION_CHIP_2]; const chip3 = convSettings[Alias.QUIZ_SETTINGS.DIFFICULTY_OR_GRADE_LEVEL_SUGGESTION_CHIP_3]; const availableChips = [chip1, chip2, chip3].filter(Boolean); const suggestions = conv.$helper.getRichSuggestions(...availableChips); if (!conv.device.capabilities.includes('RICH_RESPONSE')) { const suggestionsTts = conv.$helper.getSuggestionTts(suggestions); responses.push(suggestionsTts); } conv.$helper.setupSessionTypeAndSpeechBiasing(...availableChips.map((chip) => [chip])); conv.add(util.ssml.merge(responses)); conv.add(...suggestions); } /** * @param {ConversationV3} conv */ [Action.SET_CATEGORY](conv) { conv.session.params.category = conv.intent.params.category.resolved; conv.session.params.selection = conv.session.params.category; conv.session.params.setCategory = true; conv.add(Prompt.SELECTION_CONFIRMATION_PROMPTS); } /** * @param {ConversationV3} conv */ [Action.SET_DIFFICULTY](conv) { conv.session.params.difficulty = conv.intent.params.difficulty.resolved; conv.session.params.selection = conv.session.params.difficulty; conv.session.params.setDifficulty = true; conv.add(Prompt.SELECTION_CONFIRMATION_PROMPTS); } /** * @param {ConversationV3} conv */ [Action.FINALIZE_SETUP](conv) { conv.session.params.difficulty = ( conv.session.params.difficulty || config.DEFAULT_DIFFICULTY ).toLowerCase(); conv.session.params.category = ( conv.session.params.category || config.DEFAULT_CATEGORY ).toLowerCase(); const initQuizState = conv.$helper.initSessionState( conv.session.params.quizSettings[Alias.QUIZ_SETTINGS.QUESTIONS_PER_GAME] ); conv.session.params = {...conv.session.params, ...initQuizState}; } /** * @param {ConversationV3} conv * @param {string} transition */ [Action.ASK_QUESTION](conv, transition) { const isRepeat = conv.session.params.isRepeat; conv.session.params.isRepeat = false; let transitionPrompt = util.ssml.merge([Prompt.LETS_PLAY_PROMPTS, Prompt.FIRST_ROUND_PROMPTS]); if (!isRepeat && conv.session.params.count > 0) { transitionPrompt = conv.session.params.count < conv.session.params.limit - 1 ? Prompt.NEXT_QUESTION_PROMPTS : Prompt.FINAL_ROUND_PROMPTS; // Last question } else if (isRepeat) { transitionPrompt = Prompt.REPEAT_PROMPTS; } const question = conv.$helper.getCurrentQuestion(); const questionStr = question.question; const responses = [transitionPrompt, Prompt.ROUND_PROMPTS, questionStr]; if (transition) responses.unshift(transition); conv.session.params.suggestions = isRepeat ? conv.session.params.suggestions : util.array.shuffle(conv.$helper.getQuestionSuggestions()); if (!conv.device.capabilities.includes('RICH_RESPONSE')) { const suggestionsTts = conv.$helper.getSuggestionTts(conv.session.params.suggestions); responses.push(suggestionsTts); } responses.push(conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_DING)); conv.session.params.currentQuestion = question; conv.session.params.correctAnswer = question[Alias.QUIZ_Q_A.CORRECT_ANSWER][0]; const correctAns = question[Alias.QUIZ_Q_A.CORRECT_ANSWER]; const incorrectAns1 = question[Alias.QUIZ_Q_A.INCORRECT_ANSWER_1]; const incorrectAns2 = question[Alias.QUIZ_Q_A.INCORRECT_ANSWER_2]; conv.$helper.setupSessionTypeAndSpeechBiasing(correctAns, incorrectAns1, incorrectAns2); const richSuggestions = conv.$helper.getRichSuggestions(...conv.session.params.suggestions); conv.add(util.ssml.merge(responses)); conv.add(...richSuggestions); } /** * @param {ConversationV3} conv */ [Action.QUESTION_REPEAT](conv) { conv.session.params.isRepeat = true; this[Action.ASK_QUESTION](conv); } /** * @param {ConversationV3} conv * @param {string} [answer] */ [Action.ANSWER](conv, answer) { if (conv.session.params.isSkip) { conv.session.params.isSkip = false; conv.add(Prompt.SKIP_PROMPTS); return; } answer = answer || conv.$helper.getAndClearUserAnswer(); const question = conv.$helper.getCurrentQuestion(); conv.session.params.count++; conv.session.params.questionNumber++; const correctAns = question[Alias.QUIZ_Q_A.CORRECT_ANSWER][0]; let isCorrect = String(answer).toLowerCase() === String(correctAns).toLowerCase(); const audioCalculating = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_CALCULATING); const responses = [audioCalculating]; if (isCorrect) { conv.session.params.correctCount++; const audioCorrect = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_CORRECT); const rightAnswer1 = Prompt.RIGHT_ANSWER_PROMPTS_1; const rightAnswer2 = Prompt.RIGHT_ANSWER_PROMPTS_2; responses.push(audioCorrect, rightAnswer1, rightAnswer2); } else { const audioIncorrect = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_INCORRECT); const wrongAnswer1 = Prompt.WRONG_ANSWER_PROMPTS_1; const wrongAnswer2 = Prompt.WRONG_ANSWER_PROMPTS_2; responses.push(audioIncorrect, wrongAnswer1, wrongAnswer2); } const followUp = question[Alias.QUIZ_Q_A.FOLLOW_UP]; if (followUp) responses.push(followUp); conv.add(util.ssml.merge(responses)); } /** * @param {ConversationV3} conv */ [Action.ANSWER_ORDINAL](conv) { if (!conv.intent.params[Type.COUNT] || !conv.intent.params[Type.COUNT].resolved) { this[Action.ANSWER_NO_MATCH_1](conv); return; } const ordinals = { [Answer.FIRST]: conv.session.params.suggestions[0], [Answer.SECOND]: conv.session.params.suggestions[1], [Answer.THIRD]: conv.session.params.suggestions[2] || conv.session.params.suggestions[1], }; this[Action.ANSWER](conv, ordinals[conv.intent.params[Type.COUNT].resolved]); } /** * @param {ConversationV3} conv */ [Action.ROUND_END](conv) { const gameOverPrompt1 = Prompt.GAME_OVER_PROMPTS_1; const gameOverPrompt2 = Prompt.GAME_OVER_PROMPTS_2; let prompt; const score = parseInt(conv.session.params.correctCount); if (score === 0) { prompt = Prompt.NONE_CORRECT_PROMPTS; } else if (score === conv.session.params.limit) { prompt = Prompt.ALL_CORRECT_PROMPTS; } else { prompt = Prompt.SOME_CORRECT_PROMPTS; } const audioRoundEnd = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_ROUND_END); const responses = [audioRoundEnd, gameOverPrompt1, gameOverPrompt2, prompt]; conv.add(util.ssml.merge(responses)); } /** * @param {ConversationV3} conv */ [Action.GIVE_SCORE](conv) { conv.session.params.isRepeat = true; this[Action.ASK_QUESTION](conv, Prompt.YOUR_SCORE_PROMPTS); } /** * @param {ConversationV3} conv */ [Action.ANSWER_HELP](conv) { conv.add(Prompt.HELP_PROMPTS); } /** * @param {ConversationV3} conv */ [Action.ANSWER_SKIP](conv) { conv.session.params.count++; conv.session.params.questionNumber++; conv.session.params.isSkip = true; } /** * @param {ConversationV3} conv */ [Action.RESTART_CONFIRMATION](conv) { conv.add(Prompt.RESTART_CONFIRMATION); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_YES})); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_NO})); } /** * @param {ConversationV3} conv */ [Action.RESTART_YES](conv) { conv.session.params.isReplay = true; conv.add(Prompt.RESTART_YES); } /** * @param {ConversationV3} conv */ [Action.RESTART_NO](conv) { conv.session.params.isRepeat = true; this[Action.QUIT_NO](conv); } /** * @param {ConversationV3} conv */ [Action.RESTART_REPEAT](conv) { this[Action.RESTART_CONFIRMATION](conv); } /** * @param {ConversationV3} conv */ [Action.ASK_PLAY_AGAIN](conv) { conv.add(Prompt.PLAY_AGAIN_QUESTION_PROMPTS); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_YES})); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_NO})); } /** * @param {ConversationV3} conv */ [Action.PLAY_AGAIN_YES](conv) { conv.session.params.isReplay = true; conv.session.params.count = 0; conv.session.params.questionNumber = 1; conv.session.params.correctCount = 0; conv.add(Prompt.RE_PROMPT); } /** * @param {ConversationV3} conv */ [Action.PLAY_AGAIN_NO](conv) { this[Action.QUIT_YES](conv); } /** * @param {ConversationV3} conv */ [Action.PLAY_AGAIN_REPEAT](conv) { this[Action.ASK_PLAY_AGAIN](conv); } /** * @param {ConversationV3} conv */ [Action.QUIT_CONFIRMATION](conv) { conv.add(Prompt.STOP_PROMPTS); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_YES})); conv.add(new Suggestion({title: Prompt.MISC_PROMPTS_NO})); } /** * @param {ConversationV3} conv */ [Action.QUIT_YES](conv) { const audioGameOutro = conv.$helper.getAudio(Alias.QUIZ_SETTINGS.AUDIO_GAME_OUTRO); const customQuitPrompt = conv.session.params.quizSettings[Alias.QUIZ_SETTINGS.QUIT_PROMPT]; const quitPrompt = customQuitPrompt || Prompt.QUIT_PROMPTS; conv.add(util.ssml.merge([quitPrompt, audioGameOutro])); } /** * @param {ConversationV3} conv */ [Action.QUIT_NO](conv) { conv.add(Prompt.RE_PROMPT); } /** * @param {ConversationV3} conv */ [Action.QUIT_REPEAT](conv) { this[Action.QUIT_CONFIRMATION](conv); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_MATCH_1](conv) { conv.add(Prompt.RAPID_REPROMPTS); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_MATCH_2](conv) { conv.add(Prompt.RAPID_REPROMPTS); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_MATCH_MAX](conv) { conv.add(Prompt.FALLBACK_PROMPT_2); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_INPUT_1](conv) { conv.add(Prompt.NO_INPUT_PROMPTS_1); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_INPUT_2](conv) { conv.add(Prompt.NO_INPUT_PROMPTS_2); } /** * @param {ConversationV3} conv */ [Action.GENERIC_NO_INPUT_MAX](conv) { conv.add(Prompt.NO_INPUT_PROMPTS_3); } }
JavaScript
@useTableActions class AppStore extends Store { sortKey = 'status_time'; defaultStatus = ['draft', 'active', 'suspended']; @observable apps = []; @observable homeApps = []; // menu apps @observable menuApps = []; // judje query menu apps @observable hasMeunApps = false; @observable appDetail = { name: '', abstraction: '', description: '', category_id: '', home: '', readme: '', tos: '', icon: '', screenshots: [] }; @observable summaryInfo = {}; // replace original statistic @observable categoryTitle = ''; @observable appId = ''; // current app_id @observable isLoading = false; @observable isProgressive = false; @observable appCount = 0; @observable repoId = ''; @observable categoryId = ''; @observable userId = ''; @observable isModalOpen = false; @observable isDeleteOpen = false; @observable operateType = ''; @observable appTitle = ''; @observable detailTab = ''; @observable currentPic = 1; @observable viewType = 'list'; @observable createStep = 1; @observable createReopId = ''; @observable uploadFile = ''; @observable createError = ''; @observable createResult = null; @observable hasMore = false; isEdit = true; resetAppDetail = {}; @observable iconShow = ''; @observable screenshotsShow = ''; // menu actions logic @observable handleApp = { action: '', // delete, modify selectedCategory: '' // category id }; @observable unCategoriedApps = []; @observable countStoreApps = 0; @observable showActiveApps = false; get clusterStore() { return this.getStore('cluster'); } @action fetchStoreAppsCount = async () => { const res = await this.request.get('active_apps', { display_columns: [''], status: 'active' }); this.countStoreApps = _.get(res, 'total_count', 0); }; @action fetchMenuApps = async () => { const userId = getCookie('user_id'); const menuApps = localStorage.getItem(`${userId}-apps`); if (!menuApps) { const params = { sort_key: 'status_time', limit: 5, status: defaultStatus }; const result = await this.request.get('apps', params); this.menuApps = get(result, 'app_set', []); localStorage.setItem(`${userId}-apps`, JSON.stringify(this.menuApps)); } else { this.menuApps = JSON.parse(menuApps); } }; @action fetchMeunApp = async (appId, isFetch) => { const userId = getCookie('user_id'); const menuApps = localStorage.getItem(`${userId}-apps`); const apps = JSON.parse(menuApps || '[]'); const appDetail = _.find(apps, { app_id: appId }); if (appDetail && !isFetch) { this.appDetail = appDetail; // modify info will change app info this.resetAppDetail = appDetail; } else { await this.fetch(appId); // if can't get app, should not storage app info if (!this.appDetail.app_id) { return; } if (appDetail) { const index = _.findIndex(apps, { app_id: appId }); apps.splice(index, 1, this.appDetail); } else { apps.unshift(this.appDetail); apps.splice(5, 1); } localStorage.setItem(`${userId}-apps`, JSON.stringify(apps)); this.menuApps = apps; } }; @action fetchActiveApps = async (params = {}) => { await this.fetchAll(Object.assign(params, { action: 'active_apps' })); }; @action fetchAll = async (params = {}) => { // dont mutate observables, just return results const noMutate = Boolean(params.noMutate); const fetchAction = params.action || 'apps'; params = this.normalizeParams(_.omit(params, ['noMutate', 'action'])); if (params.app_id) { delete params.status; } if (this.searchWord) { params.search_word = this.searchWord; } if (this.categoryId && !params.category_id) { params.category_id = this.categoryId; } // filter empty cate if (!params.category_id) { delete params.category_id; } if (this.repoId) { params.repo_id = this.repoId; } if (this.userId) { params.owner = this.userId; } if (!params.noLoading) { this.isLoading = true; } else { this.isProgressive = true; delete params.noLoading; } const result = await this.request.get(fetchAction, params); const apps = get(result, 'app_set', []); const totalCount = get(result, 'total_count', 0); this.hasMore = totalCount > apps.length; if (noMutate) { return { apps, totalCount }; } if (params.loadMore) { this.apps = _.concat(this.apps.slice(), apps); } else { this.apps = apps; } this.totalCount = totalCount; // appCount for show repo datail page "App Count" if (!this.searchWord && !this.selectStatus) { this.appCount = this.totalCount; } // query app deploy times if (this.attchDeployTotal && apps.length > 0) { const clusterStore = this.clusterStore; this.apps = []; await apps.forEach(async app => { await clusterStore.fetchAll({ app_id: app.app_id, display_columns: [''] }); this.apps.push( _.assign(app, { deploy_total: clusterStore.totalCount }) ); }); } this.isLoading = false; this.isProgressive = false; }; @action fetchStatistics = async () => { this.isLoading = true; const result = await this.request.get('apps/statistics'); this.summaryInfo = { name: 'Apps', iconName: 'appcenter', centerName: 'Repos', total: get(result, 'app_count', 0), progressTotal: get(result, 'repo_count', 0), progress: get(result, 'top_ten_repos', {}), histograms: get(result, 'last_two_week_created', {}), topRepos: getProgress(get(result, 'top_ten_repos', {})), // top repos appCount: get(result, 'app_count', 0), repoCount: get(result, 'repo_count', 0) }; this.isLoading = false; }; @action fetch = async (appId = '') => { this.isLoading = true; const result = await this.request.get(`apps`, { app_id: appId, isGlobalQuery: true }); const appDetail = get(result, 'app_set[0]', {}); this.appDetail = _.assign(appDetail, { category_id: get(appDetail, 'category_set[0].category_id', '') }); // set this variable for reset app info this.resetAppDetail = { ...this.appDetail }; this.isLoading = false; }; @action createOrModify = async (params = {}) => { const defaultParams = { repo_id: this.createReopId, package: this.uploadFile }; if (this.createAppId) { defaultParams.app_id = this.createAppId; await this.modify(assign(defaultParams, params)); } else { defaultParams.status = 'draft'; await this.create(assign(defaultParams, params)); } if (get(this.createResult, 'app_id')) { this.createAppId = get(this.createResult, 'app_id'); this.createStep = 3; // show application has been created page } else { const { err, errDetail } = this.createResult; this.createError = errDetail || err; } }; @action create = async (params = {}) => { this.isLoading = true; this.createResult = await this.request.post('apps', params); this.isLoading = false; }; @action modify = async (params = {}, hasNote) => { this.isLoading = true; this.createResult = await this.request.patch('apps', params); this.isLoading = false; if (hasNote && get(this.createResult, 'app_id')) { this.info('应用信息保存成功'); } }; @action modifyApp = async event => { if (event) { event.preventDefault(); } const data = _.pick(this.appDetail, [ 'name', 'abstraction', 'description', 'home', 'icon' ]); await this.modify( _.assign(data, { app_id: this.appDetail.app_id, category_id: this.appDetail.category_id, icon: this.appDetail.icon }), Boolean(event) ); // update the meun app show if (get(this.createResult, 'app_id')) { this.fetchMeunApp(this.appDetail.app_id, true); } }; @action changeApp = (event, type) => { this.appDetail[type] = event.target.value; }; @action changeCategory = value => { this.appDetail.category_id = value; }; @action saveAppInfo = async type => { await this.modify( { app_id: this.appDetail.app_id, [type]: this.appDetail[type] }, true ); }; @action attachment = async (params = {}) => { await this.request.patch('app/attachment', params); }; @action checkIcon = file => { if (!/\.(png)$/.test(file.name.toLocaleLowerCase())) { this.error(t('icon_format_note')); return false; } if (file.size > maxsize) { this.error(t('The file size cannot exceed 2M')); return false; } return true; }; @action uploadIcon = async (base64Str, file) => { const result = await this.attachment({ app_id: this.appDetail.app_id, type: 'icon', attachment_content: base64Str }); if (result && result.err) { return false; } this.appDetail.icon = base64Str; }; @action deleteIcon = () => { this.appDetail.icon = ''; }; @action checkScreenshot = file => { if (!/\.(png|jpg)$/.test(file.name.toLocaleLowerCase())) { this.error(t('screenshot_format_note')); return false; } if (file.size > maxsize) { this.error(t('The file size cannot exceed 2M')); return false; } return true; }; @action uploadScreenshot = async (base64Str, file) => { const { screenshots } = this.appDetail; const len = _.isArray(screenshots) ? screenshots.length : 0; if (len >= 6) { return this.error(t('最多只能上传6张界面截图')); } const result = await this.attachment({ app_id: this.appDetail.app_id, type: 'screenshot', attachment_content: base64Str, sequence }); if (result && result.errDetail) { return false; } sequence++; if (_.isArray(screenshots)) { this.appDetail.screenshots.push(base64Str); } else { this.appDetail.screenshots = [base64Str]; } }; @action deleteScreenshot = () => { this.appDetail.screenshots = []; }; @action remove = async () => { this.appId = this.appId ? this.appId : this.appDetail.app_id; const ids = this.operateType === 'multiple' ? this.selectIds.toJSON() : [this.appId]; const result = await this.request.delete('apps', { app_id: ids }); if (get(result, 'app_id')) { if (this.operateType !== 'detailDelete') { await this.fetchAll(); this.cancelSelected(); this.hideModal(); } this.success('Delete app successfully'); } else { return result; } }; @action changeAppCate = value => { this.handleApp.selectedCategory = value; }; @action modifyCategoryById = async () => { if (!this.handleApp.selectedCategory) { this.info('Please select a category'); return; } const result = await this.modify({ category_id: this.handleApp.selectedCategory, app_id: this.appId }); this.hideModal(); if (!result.err) { this.success('Modify category successfully'); await this.fetchAll(); } }; @action hideModal = () => { this.isDeleteOpen = false; this.isModalOpen = false; }; @action showDeleteApp = ids => { if (typeof ids === 'string') { this.appId = ids; this.operateType = 'single'; } else { this.operateType = 'multiple'; } this.isDeleteOpen = true; }; @action showModifyAppCate = (app_id, category_set = []) => { this.appId = app_id; if ('toJSON' in category_set) { category_set = category_set.toJSON(); } const availableCate = category_set.find( cate => cate.category_id && cate.status === 'enabled' ); this.handleApp.selectedCategory = get(availableCate, 'category_id', ''); this.isModalOpen = true; }; reset = () => { this.currentPage = 1; this.selectStatus = ''; this.searchWord = ''; this.categoryId = ''; this.repoId = ''; this.userId = ''; this.apps = []; this.appDetail = {}; this.showActiveApps = false; }; @action loadMore = async page => { this.currentPage = page; const fetchAction = this.showActiveApps ? 'fetchActiveApps' : 'fetchAll'; await this[fetchAction]({ loadMore: true }); }; @action resetBaseInfo = () => { _.assign(this.appDetail, this.resetAppDetail); }; @action setCreateStep = step => { this.createStep = step; }; }
JavaScript
class Jump { /** * * @param options * @param options.editor - The editor associated with the jump. * @param options.fileName - The absolute or relative file path. * @param options.position - The line and column number information. */ constructor({ editor, fileName, position, }) { this.editor = editor; this.fileName = fileName; this.position = position; } /** * Factory method for creating a Jump from a VimState's current cursor position. * @param vimState - State that contains the fileName and position for the jump */ static fromStateNow(vimState) { return new Jump({ editor: vimState.editor, fileName: vimState.editor.document.fileName, position: vimState.cursorStopPosition, }); } /** * Factory method for creating a Jump from a VimState's cursor position, * before any actions or commands were performed. * @param vimState - State that contains the fileName and prior position for the jump */ static fromStateBefore(vimState) { return new Jump({ editor: vimState.editor, fileName: vimState.editor.document.fileName, position: vimState.cursorsInitialState[0].stop, }); } /** * Determine whether another jump matches the same file path, line number, and character column. * @param other - Another Jump to compare against */ isSamePosition(other) { return (!other || (this.fileName === other.fileName && this.position.line === other.position.line && this.position.character === other.position.character)); } }
JavaScript
class FruitCakeOrderManager { // object representing the selected order order = ""; /***************************************** * Update arrays and displayed table ****************************************/ fillTable() { // sort the array this.nameSort(); // clear out the table var rows = table.getElementsByTagName("tr"); for (let j=rows.length-1; j>0; j--) { table.deleteRow(j); } // loop through the array for (let i=0; i<orders.length; i++) { // add a new row to the table var tableRow = table.insertRow(rows.length); tableRow.setAttribute("onclick","fruitCakeOrderManager.selectOrder(this)"); tableRow.insertCell(0).innerHTML = orders[i][0]; tableRow.insertCell(1).innerHTML = orders[i][2]; tableRow.insertCell(2).innerHTML = orders[i][3][2]; tableRow.insertCell(3).innerHTML = orders[i][3][3]; tableRow.insertCell(4).innerHTML = orders[i][3][4]; tableRow.insertCell(5).innerHTML = orders[i][5]; } } // end fillTable /*********************************************** * Select Order * * Called when the table row is clicked * @param {*} row **********************************************/ selectOrder(row){ var order = this.buildOrderForRow(row); this.populateForm(order); this.order = order; } // end selectOrder /*********************************************** * Adds the form values to the table as a new row ***********************************************/ add() { // check validity if(! form.checkValidity() ){ alert("form is not valid"); return; } // add a new row to the array orders.push(new Array(6)); orders[orders.length-1][3] = new Array(5); orders[orders.length-1][4] = new Array(0); // new up a order object var order = new Order(null); order.setRowIndex(orders.length - 1); // put the values from the form into the new order object this.updateOrderFromForm( order); // update the row in the orders array this.updateOrdersArrayRow(order); // resort and repopulate the table this.fillTable(); // clear the form and selected order this.cancel(); } // end add /*********************************************** * Replaces values for an existing row **********************************************/ replace() { // check validity if(! form.checkValidity() ){ alert("form is not valid"); return; } // propmt the user to confirm before deleting if( ! confirm("Are you sure you want to replace?") ){ return; } // put the values from the form into the selected order object this.updateOrderFromForm( this.order); // update the row in the orders array this.updateOrdersArrayRow(this.order); // resort and repopulate the table this.fillTable(); // clear the form and the selected order this.cancel(); } // end replace /*************************************************************** * Removes the selected property from properties array and from table ***************************************************************/ delete() { // propmt the user to confirm before deleting if( ! confirm("Are you sure you want to delete?") ){ return; } // remove the row from the table table.deleteRow( this.order.getRowIndex() + 1 ); orders.splice( this.order.getRowIndex(), 1); // clear the form and selected order this.cancel(); } // end deleteProperty /************************************************** * The Cancel Method * * clears the form and resets the selected property **************************************************/ cancel() { var inputElements = form.getElementsByTagName("input"); for (let i=0; i< inputElements.length; i++) { if("button" != inputElements[i].type ){ if("radio" == inputElements[i].type){ inputElements[i].checked = false; } else{ inputElements[i].value = ""; } } } var seletElements = form.getElementsByTagName("select"); for (let i=0; i< seletElements.length; i++) { for(let option of seletElements[i].options){ option.selected = false; } } // clear out the selected order this.order = ""; } // end cancel /* ##################################################### / ############ Internal Methods ################### / ####################################################*/ /**************************************** * sorts the array by first name ***************************************/ nameSort() { orders.sort( function(a,b) { return (a[0] < b[0]) ? -1 : (a[0] > b[0]) ? 1 : 0; } ); } // end nameSort /******************************************* * Updates the order with the form values * * @param {*} order ******************************************/ updateOrderFromForm(order){ // update the name order.setNameFirst ( form.elements.namedItem("nameFirst").value ); order.setNameMiddle( form.elements.namedItem("nameMiddle").value ); order.setNameLast( form.elements.namedItem("nameLast").value ); // update the areas of interest var areasOfInterestSelect = form.elements.namedItem("areasOfInterest"); var selectedItems = []; for (let i = 0; i < areasOfInterestSelect.length; i++) { if (areasOfInterestSelect.options[i].selected ){ selectedItems.push(areasOfInterestSelect.options[i].value); } } order.setAreasOfInterest(selectedItems); // get the fruitCake radio button value var elements = form.elements.namedItem("fruitCake"); for(let i = 0; i < elements.length; i++) { if(elements[i].checked){ order.setFruitCake( elements[i].value ); break; } } // end updateorderFromForm // set the address var address = order.getMailingAddress(); if(null == address){ address = new Address(); } address.setStreet1( form.elements.namedItem("street1").value ); address.setStreet2( form.elements.namedItem("street2").value ); address.setCity( form.elements.namedItem("city").value ); address.setState( form.elements.namedItem("state").value ); address.setZip( form.elements.namedItem("zip").value ); order.setMailingAddress( address ); } // end updateOrderFromForm /************************************************** * Populate Form * * Populates the form data in the form from data in * a order object * * @param order order **************************************************/ populateForm(order){ // populate the name fields form.elements.namedItem("nameFirst").value = order.getNameFirst(); form.elements.namedItem("nameMiddle").value = order.getNameMiddle(); form.elements.namedItem("nameLast").value = order.getNameLast(); // populate the address fields var mailingAddress = order.getMailingAddress(); form.elements.namedItem("street1").value = mailingAddress.getStreet1(); form.elements.namedItem("street2").value = mailingAddress.getStreet2(); form.elements.namedItem("city").value = mailingAddress.getCity(); form.elements.namedItem("state").value = mailingAddress.getState(); form.elements.namedItem("zip").value = mailingAddress.getZip(); // set the values of the listbox if(null != order.getAreasOfInterest() ){ var selectBox = form.elements.namedItem("areasOfInterest"); for(let option of selectBox.options){ if( order.getAreasOfInterest().includes(option.value) ) { option.selected = true; } else { option.selected = false; } } } // check the fruitCake radio button form.elements.namedItem( order.getFruitCake() ).checked = true; } // end populateForm /**************************************************** * Build order for Row * * Builds a order object from a row in the orders * array * * @param {*} row **************************************************/ buildOrderForRow(row){ // new up an instance of order var order = new Order(row); var rowIndex = order.getRowIndex(); // set properties from the row in the orders array order.setNameFirst ( orders[rowIndex][0] ); order.setNameMiddle( orders[rowIndex][1] ); order.setNameLast( orders[rowIndex][2] ); order.setAreasOfInterest( orders[rowIndex][4] ); order.setFruitCake( orders[rowIndex][5] ); var address = new Address(); address.setStreet1( orders[rowIndex][3][0] ); address.setStreet2( orders[rowIndex][3][1] ); address.setCity( orders[rowIndex][3][2] ); address.setState( orders[rowIndex][3][3] ); address.setZip( orders[rowIndex][3][4] ); order.setMailingAddress( address ); // return with the new order return order; } // end buildOrderForRow /************************************************** * Update orders Array Row * * Updates a row in the Contracts Array using the * values in a order object * * @param {*} order *************************************************/ updateOrdersArrayRow(order){ var rowIndex = order.getRowIndex(); var address = order.getMailingAddress(); orders[rowIndex][0] = order.getNameFirst(); orders[rowIndex][1] = order.getNameMiddle(); orders[rowIndex][2] = order.getNameLast(); orders[rowIndex][4] = order.getAreasOfInterest(); orders[rowIndex][5] = order.getFruitCake(); orders[rowIndex][3][0] = address.getStreet1(); orders[rowIndex][3][1] = address.getStreet2(); orders[rowIndex][3][2] = address.getCity(); orders[rowIndex][3][3] = address.getState(); orders[rowIndex][3][4] = address.getZip(); } // updateOrdersArrayRow }
JavaScript
class GraphAPI { /** * Just to be sure that correct user passed * @param {{ id: string, access_token?: string }} user */ static checkUser(user) { assert(user, 'No user provided'); assert(user.id, 'User must have `id`'); } /** * Creates test user with passed `props` * @param props * @returns {*} */ static createTestUser(props = {}) { return this.graphApi({ uri: `/${process.env.FACEBOOK_CLIENT_ID}/accounts/test-users`, method: 'POST', body: { installed: false, ...props, }, }); } /** * Deletes test user * @param facebook user * @returns {Promise<*>} */ static deleteTestUser(user) { this.checkUser(user); return this.graphApi({ uri: `${user.id}`, method: 'DELETE', }); } /** * Removes all Application permissions. * This only the way to De Authorize Application from user. * @param facebook user * @returns {Promise<*>} */ static deAuthApplication(user) { this.checkUser(user); return this.graphApi({ uri: `/${user.id}/permissions`, method: 'DELETE', }); } /** * Delete any Application permission from user. * @param {{ id: string }} user * @param {string} * @returns {Promise<*>} */ static deletePermission(user, permission) { this.checkUser(user); assert(permission, 'No `permission` provided'); return this.graphApi({ uri: `/${user.id}/permissions/${permission}`, method: 'DELETE', }); } /** * Associates user with facebook app and provides permissions * @param {{ id: string }} user * @param {string[]} permissions */ static associateUser(user, permissions = []) { this.checkUser(user); assert(Array.isArray(permissions)); return this.graphApi({ uri: `/${process.env.FACEBOOK_CLIENT_ID}/accounts/test-users`, method: 'POST', body: { uid: user.id, owner_access_token: process.env.FACEBOOK_APP_TOKEN, installed: permissions.length > 0, permissions: permissions.length > 0 ? permissions.join(',') : undefined, }, }); } /** * Returns existing test user with correct permissions or creates a new one * @param {string[]} permissions * @param {string} [next] - url for fetching test user data * @returns {Promise<{ id: string, access_token: string | undefined, login_url: string, email?: string }>} */ static async _getTestUserWithPermissions(permissions, next = `${baseOpts.baseUrl}/${process.env.FACEBOOK_CLIENT_ID}/accounts/test-users`) { const { data, paging: { next: nextPage } } = await this.graphApi({ baseUrl: '', uri: next, method: 'GET', }); if (data.length === 0) { return this.createTestUser({ installed: Array.isArray(permissions) && permissions.length > 0, permissions: Array.isArray(permissions) && permissions.length > 0 ? permissions.join(',') : undefined, }); } if (!Array.isArray(permissions) || permissions.length === 0) { const users = data.filter((x) => !x.access_token); const user = users[users.length * Math.random() | 0]; if (!user) { return this.getTestUserWithPermissions(permissions, nextPage); } return user; } const user = data[data.length * Math.random() | 0]; await this.deAuthApplication(user); return this.associateUser(user, permissions); } /** * ensures that every test user has email * @param {string[]} permissions */ static async getTestUserWithPermissions(permissions) { const user = await this._getTestUserWithPermissions(permissions); const hasPermission = Array.isArray(permissions) && permissions.length > 0; const needsEmail = hasPermission ? permissions.includes('email') : true; if (needsEmail && !user.email) { await this.deleteTestUser(user); return this.getTestUserWithPermissions(permissions); } return user; } }
JavaScript
class Keyboard { /** * {@link Keyboard} class constructor * @param nativeAdapter {@link NativeAdapter} instance which bundles access to mouse, keyboard and clipboard */ constructor(nativeAdapter) { this.nativeAdapter = nativeAdapter; /** * Config object for {@link Keyboard} class */ this.config = { /** * Configures the delay between single key events */ autoDelayMs: 300, }; this.nativeAdapter.setKeyboardDelay(this.config.autoDelayMs); } /** * {@link type} types a sequence of {@link String} or single {@link Key}s via system keyboard * @example * ```typescript * await keyboard.type(Key.A, Key.S, Key.D, Key.F); * await keyboard.type("Hello, world!"); * ``` * * @param input Sequence of {@link String} or {@link Key} to type */ type(...input) { return new Promise(async (resolve, reject) => { try { if (inputIsString(input)) { for (const char of input.join(' ').split('')) { await sleep_function_1.sleep(this.config.autoDelayMs); await this.nativeAdapter.type(char); } } else { await this.nativeAdapter.click(...input); } resolve(this); } catch (e) { reject(e); } }); } /** * {@link pressKey} presses and holds a single {@link Key} for {@link Key} combinations * Modifier {@link Key}s are to be given in "natural" ordering, so first modifier {@link Key}s, followed by the {@link Key} to press * @example * ```typescript * // Will press and hold key combination STRG + V * await keyboard.pressKey(Key.STRG, Key.A); * ``` * * @param keys Array of {@link Key}s to press and hold */ pressKey(...keys) { return new Promise(async (resolve, reject) => { try { await this.nativeAdapter.pressKey(...keys); resolve(this); } catch (e) { reject(e); } }); } /** * {@link pressKey} releases a single {@link Key} for {@link Key} combinations * Modifier {@link Key}s are to be given in "natural" ordering, so first modifier {@link Key}s, followed by the {@link Key} to press * @example * ```typescript * // Will release key combination STRG + V * await keyboard.releaseKey(Key.STRG, Key.A); * ``` * * @param keys Array of {@link Key}s to release */ releaseKey(...keys) { return new Promise(async (resolve, reject) => { try { await this.nativeAdapter.releaseKey(...keys); resolve(this); } catch (e) { reject(e); } }); } }
JavaScript
class GumpMap { /** * Converts the given object to a GumpMap. Nested objects are also * transformed into GumpMaps and nested arrays become GumpSets. * * @param {Object} o * The object to convert. * * @return {GumpMap} * The converted object. */ static fromObject(o) { const result = new GumpMap({ autoPurgeEmptyContainers: this.autoPurgeEmptyContainers }); for (let [k, v] of Object.entries(o)) { if (_.isArray(v)) { result.add(k, new GumpSet(v)); } else if (_.isPlainObject(v)) { result.add(k, GumpMap.fromObject(v)); } else { result.add(k, v); } } return result; } /** * @param {Object} obj * The configuration object. * * @param {Iterable} [obj.initialValues=[]] * An iterable object containing the initial values of this map. Each entry * in this array is expected to match [path, value], where path is the place * where the value should be added. * * @param {Boolean} [obj.autPurgeEmptyContainers=false] * Whether a container should be deleted when it becomes empty after one of * its entries was deleted. */ constructor({ initialValues = [], autoPurgeEmptyContainers = false } = {}) { /** * Stores the size of this map. * * @type {Number} */ this.size = 0; /** * Whether a container should be deleted when it becomes empty after one of * its entries was deleted. * * @type {Boolean} * @private */ this.autoPurgeEmptyContainers = autoPurgeEmptyContainers; /** * Stores the values of this map. * * @type {Map} * @private */ this.children = new Map(); /** * Maps from a direct child to the key used to access it. * * @type {Map} * @private */ this.childToKey = new Map(); /** * Handles listeners. * * @type {EventManager} * @private */ this.eventManager = new EventManager(); /** * Bubbles an add event. * * @type {Function} * @private */ this.bubbleAddEvent = (e) => { const value = e.data.value; if (value instanceof GumpMap || value instanceof GumpSet) { this.size += value.size; } else { this.size++; } this.bubbleEvent(e, { value }); }; /** * Bubbles a clear event. * * @type {Function} * @private */ this.bubbleClearEvent = (e) => { const deleted = e.data.deleted; this.size -= deleted.length; this.bubbleEvent(e, { deleted }); }; /** * Bubbles a delete event. * * @type {Function} * @private */ this.bubbleDeleteEvent = (e) => { const value = e.data.value; const deleted = e.data.deleted; this.size -= deleted.length; this.bubbleEvent(e, { value, deleted }); if (this.autoPurgeEmptyContainers && e.source.size === 0) { const key = this.childToKey.get(e.source); this.delete(key); } }; // Add initial values for (let [path, value] of initialValues) { this.add(path, value); } } /** * Adds the given value to this map under the given path. * * @param {*} path * Where the value should be added. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @param {*} value * The value to add. */ add(path, value) { path = GumpPath.toGumpPath(path); if (!path.isEmpty()) { const key = path.head(); const remainingPath = path.tail(); if (remainingPath.isEmpty()) { this.addHere(key, value); } else { this.addDeeper(key, remainingPath, value); } } return this; } /** * Adds a value directly under this map using the given key. * * @param {*} key * Where the value should be added. * * @param {*} value * The value to add. * * @private */ addHere(key, value) { if (this.children.has(key)) { this.addHereExisting(key, value); } else { this.addHereNew(key, value); } } /** * Adds the given value to the GumpSet accessible via the given key. If the * value under the key is no GumpSet, an error is thrown. * * @param {*} key * The key of the GumpSet. * * @param {*} value * The value to add to the GumpSet. * * @throws {Error} * If the value under the given key is no GumpSet. * * @private */ addHereExisting(key, value) { const nextLevel = this.children.get(key); if (nextLevel instanceof GumpSet) { nextLevel.add(value); } else { throw new Error(`Expected a GumpSet, but found ${nextLevel}.`); } } /** * Adds the given value to this map under the given key. If it is already * an instance of GumpMap or GumpSet the value is used directly, otherwise * it is wrapped in a GumpSet. * * @param {*} key * Where the value should be added. * * @param {*} value * The value to add. * * @emits {Event} * If the value is used directly a new event is fired. The source is this * map, the type is "add" and the data is an object containing the path to * the value and the value itself. * * @private */ addHereNew(key, value) { if (value instanceof GumpMap || value instanceof GumpSet) { this.setNextLevel(key, value); this.size += value.size; this.fireEvent(EventManager.makeEvent({ source: this, type: "add", data: { path: GumpPath.toGumpPath(key), value } })); } else { const nextLevel = new GumpSet(); this.setNextLevel(key, nextLevel); nextLevel.add(value); } } /** * Adds the value to a GumpMap listed under the given key. * * @param {*} key * The GumpMap to add the value to. * * @param {GumpPath} remainingPath * Where in that GumpMap the value should be placed. * * @param {*} value * The value to add. * * @private */ addDeeper(key, remainingPath, value) { if (this.children.has(key)) { this.addDeeperExisting(key, remainingPath, value); } else { this.addDeeperNew(key, remainingPath, value); } } /** * Adds the value to the GumpMap accessible via the given key. If the value * under this key is no GumpMap, an error is thrown. * * @param {*} key * The key of the GumpMap. * * @param {GumpPath} remainingPath * Where the value should be added in the GumpMap under key. * * @throw {Error} * If the value under key is no GumpMap. * * @private */ addDeeperExisting(key, remainingPath, value) { const nextLevel = this.children.get(key); if (nextLevel instanceof GumpMap) { nextLevel.add(remainingPath, value); } else { throw new Error(`Expected a GumpMap, but found ${nextLevel}.`); } } /** * Creates a new GumpMap under the given key and add the value at the * position specified by remainingPath. * * @param {*} key * The key of the GumpMap. * * @param {GumpPath} remainingPath * Where the value should be added in the GumpMap under key. * * @param {*} value * The value to add. * * @private */ addDeeperNew(key, remainingPath, value) { const nextLevel = new GumpMap({ autoPurgeEmptyContainers: this.autoPurgeEmptyContainers }); this.setNextLevel(key, nextLevel); nextLevel.add(remainingPath, value); } /** * A helper function that adds a GumpSet or GumpMap to this map under the * given key. * * @param {*} key * Where it should added. * * @param {GumpMap|GumpSet} nextLevel * What should be added. * * @private */ setNextLevel(key, nextLevel) { this.setupListeners(nextLevel); this.children.set(key, nextLevel); this.childToKey.set(nextLevel, key); } /** * Empties the container under the given path completely. * * @param {*} [path=[]] * Where to find the container to empty. It must be understood by the * {@link GumpPath.toGumpPath} method. */ clear(path = []) { path = GumpPath.toGumpPath(path); if (path.isEmpty()) { this.clearHere(); } else { this.clearDeeper(path); } } /** * Clears this map. * * @emits {Event} * If this map actually had any entries an event is fired. Its source is * this map, the type is "clear" and data is an object. That object has a * path property, which is the path from this map to the cleared data * structure (it is thus the empty path). It also has another property * deleted which lists the deleted entries. * * @private */ clearHere() { if (this.size > 0) { const deleted = [...this.entries()]; for (const v of this.values({resolveMaps: false, resolveSets: false})) { this.takeDownListeners(v); } this.children.clear(); this.size = 0; this.fireEvent(EventManager.makeEvent({ source: this, type: "clear", data: { path: GumpPath.toGumpPath([]), deleted } })); } } /** * Clears the container under the given path. * * @param {GumpPath} path * Where to find the container to delete. * * @private */ clearDeeper(path) { const finalLevel = this.get(path); if (finalLevel) { finalLevel.clear(); } } /** * Deletes the value under the given path. If no value is given, the * complete data structure found under path is removed. * * @param {*} path * Where to find the value or container to delete. It must be understood by * the {@link GumpPath.toGumpPath} method. * * @param {*} [value] * The value to delete. * * @return {Boolean} * Whether something was removed. */ delete(path, value = EMPTY) { path = GumpPath.toGumpPath(path); if (path.isEmpty()) { return false; } const key = path.head(); const remainingPath = path.tail(); if (remainingPath.isEmpty()) { return this.deleteHere(key, value); } else { return this.deleteDeeper(key, remainingPath, value); } } /** * Removes the value from the container found under the given key. If no * value is given, the complete container is removed. * * @param {*} key * The key of the container. * * @param {*} value * The value to delete. * * @return {Boolean} * Whether something was removed. * * @private */ deleteHere(key, value = EMPTY) { const nextLevel = this.children.get(key); if (nextLevel) { if (value === EMPTY) { return this.deleteHereContainer(key, nextLevel); } else if (nextLevel instanceof GumpSet) { return nextLevel.delete(value); } } return false; } /** * Removes the container nextLevel that can be under the given key. * * @param {*} key * The key of nextLevel. * * @param {GumpMap|GumpSet} nextLevel * The container to remove. * * @return {Boolean} * Whether the container was successfully removed. The return value * should always be true. * * @emits {Event} * The source is this map, the type is "delete" and the data is an object * with two properties. The first property path is a GumpPath containing * the given key. The second property deleted lists all entries/values of * the removed container, depending on whether it was a GumpMap or a * GumpSet. * * @private */ deleteHereContainer(key, nextLevel) { const deleted = nextLevel instanceof GumpMap ? [...nextLevel.entries()] : [...nextLevel.values()]; this.takeDownListeners(nextLevel); this.size -= deleted.length; this.fireEvent(EventManager.makeEvent({ source: this, type: "delete", data: { path: GumpPath.toGumpPath(key), deleted } })); return this.children.delete(key); } /** * Tries to delete the given value in the data structure listed under the * given key. The location relative to that child is specified by * remainingPath. * * @param {*} key * The key of the child. * * @param {GumpPath} remainingPath * The path relative to the child. * * @param {*} [value] * The value to delete. If it is left empty, the whole data structure is * removed. * * @return {Boolean} * Whether something was deleted. * * @private */ deleteDeeper(key, remainingPath, value = EMPTY) { let nextLevel = this.children.get(key); if (nextLevel instanceof GumpMap) { return nextLevel.delete(remainingPath, value); } return false; } /** * Deletes all references to empty GumpMaps or GumpSets in this map. */ purgeEmptyContainers() { for (const [path, v] of this.entries({resolveMaps: false, resolveSets: false})) { if (v.size === 0) { this.delete(path); } else if (v instanceof GumpMap) { v.purgeEmptyContainers(); } } } /** * Returns the value under the given path or undefined if the path leads nowhere. * * @param {*} path * Where to look for the value. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @return {*} * The found value. */ get(path) { path = GumpPath.toGumpPath(path); if (path.isEmpty()) { return this; } const key = path.head(); const remainingPath = path.tail(); const nextLevel = this.children.get(key); if (remainingPath.isEmpty()) { return nextLevel; } else if (nextLevel instanceof GumpMap) { return nextLevel.get(remainingPath); } else { return undefined; } } /** * Tests if the given value can be found under the given path. If no value * is specified the method just tests if the path leads somewhere. * * @param {*} path * Where to look for the value. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @param {*} [value] * The value to test. */ has(path, value = EMPTY) { path = GumpPath.toGumpPath(path); const finalLevel = this.get(path); if (value === EMPTY) { return finalLevel !== undefined; } else if (finalLevel instanceof GumpSet) { return finalLevel.has(value); } else { return false; } } /** * Yields all [path, value] entries of this GumpMap. The parameters control * what is considered a value. * * @param {Object} conf * The configuration object. * * @param {Boolean} [conf.resolveMaps=true] * If this parameter is true, nested GumpMaps are also traversed. Otherwise * they are regarded as basic values. * * @param {Boolean} [conf.resolveSets=true] * If this parameter is true, GumpSets are split into the values they * contain. Otherwise they are viewed as basic values. */ * entries({resolveMaps = true, resolveSets = true} = {}) { for (let [k, v] of this.children.entries()) { if (resolveMaps && v instanceof GumpMap) { yield* this.entriesResolveMap(k, v, {resolveMaps, resolveSets}); } else if (resolveSets && v instanceof GumpSet) { yield* this.entriesResolveSet(k, v); } else { yield [GumpPath.toGumpPath(k), v]; } } } /** * Yields all entries of the given map. They paths are prepended by the * given key so they are relative to this map. * * @param {*} key * The key of the GumpMap. * * @param {GumpMap} map * The GumpMap to traverse. * * @param {Object} conf * The configuration object. * * @private */ * entriesResolveMap(key, map, conf) { for (let [tail, primitive] of map.entries(conf)) { yield [tail.prepend(key), primitive]; } } /** * Loops over all values of the given set and returns [key, value] entries. * * @param {*} key * The key of the given GumpSet. * * @param {GumpSet} set * The GumpSet to resolve. * * @private */ * entriesResolveSet(key, set) { for (let primitive of set.values()) { yield [GumpPath.toGumpPath(key), primitive]; } } /** * Yields all keys of the top-level map. */ keys() { return this.children.keys(); } /** * Yields all paths of this map. * * @param {Boolean} [resolveMaps=true] * If this parameter is true, nested GumpMaps are also traversed and this * method yields the paths to the basic values. Otherwise only one level is * resolved and this method acts more like the keys method on normal maps. */ * paths(resolveMaps = true) { for (let [k, v] of this.children.entries()) { if (resolveMaps && v instanceof GumpMap) { yield* this.pathsResolveMap(k, v); } else { yield GumpPath.toGumpPath(k); } } } /** * Yields all paths to values of the given map. The given key is prepended * to each one so they are relative to this GumpMap. * * @param {*} key * The key of the given GumpMap. * * @param {GumpMap} map * The GumpMap to resolve. * * @private */ * pathsResolveMap(key, map) { for (let tail of map.paths(true)) { yield tail.prepend(key); } } /** * Yields all values of this map. The parameters configure what is * considered a value. * * @param {Object} [conf={}] * The configuration object. * * @param {Boolean} [conf.resolveMaps=true] * If this parameter is true, the values method of nested GumpMaps is used * to retrieve their values. Otherwise they are regarded as basic values. * * @param {Boolean} [conf.resolveSets=true] * If this parameter is true, the values method of nested GumpSets is used * to retrieve their values. Otherwise they are regarded as basic values. */ * values({resolveMaps = true, resolveSets = true} = {}) { for (let v of this.children.values()) { if (resolveMaps && v instanceof GumpMap) { yield* v.values({resolveMaps, resolveSets}); } else if (resolveSets && v instanceof GumpSet) { yield* v.values(); } else { yield v; } } } /** * Yields all path-value-pairs in the map. Nested GumpMaps and GumpSets are * resolved. */ [Symbol.iterator]() { return this.entries(); } /** * Replaces the given oldValue with the newValue. This change occurs at the * position specified by path. * * @param {*} newValue * The new value. * * @param {*} path * The location of the value. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @param {*} [oldValue] * The old value. * * @return {GumpMap} * This map to make the method chainable. */ updateWithLiteral(newValue, path, oldValue = EMPTY) { path = GumpPath.toGumpPath(path); if (this.delete(path, oldValue)) { this.add(path, newValue); } return this; } /** * Replaces the given value with the result of calling f on that value. * This change occurs at the position specified by path. * * @param {Function} f * The update function. * * @param {*} path * The location of the value. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @param {*} value * The value to update. * * @return {GumpMap} * This map to make the method chainable. */ updateWithFunction(f, path, value) { path = GumpPath.toGumpPath(path); return this.updateWithLiteral(f(value), path, value); } /** * Sets the value at the given location. If the entry exists already it is * replaced, otherwise a new entry is created. * * @param {*} path * Where to place the value. It must be understood by the * {@link GumpPath.toGumpPath} method. * * @param {*} value * The value of the new entry. * * @return {GumpMap} * This map to make the method chainable. */ set(path, value) { path = GumpPath.toGumpPath(path); this.delete(path); this.add(path, value); return this; } /** * Adds listeners to the given object. * * @param {Observable} obj * The object to add the listeners to. * * @private */ setupListeners(obj) { obj.addListener(this.bubbleAddEvent, "add"); obj.addListener(this.bubbleClearEvent, "clear"); obj.addListener(this.bubbleDeleteEvent, "delete"); } /** * Removes listeners from the given object. * * @param {Observable} obj * The object to remove the listeners from. * * @private */ takeDownListeners(obj) { obj.removeListener(this.bubbleAddEvent); obj.removeListener(this.bubbleClearEvent); obj.removeListener(this.bubbleDeleteEvent); } /** * The function used to handle events emitted by children of this map. * * @type {Function} * @private */ bubbleEvent(e, data) { const key = this.childToKey.get(e.source); const path = e.data.path ? e.data.path.prepend(key) : GumpPath.toGumpPath(key); this.fireEvent(EventManager.makeEvent({ source: this, type: e.type, data: { path, ...data} })); }; }
JavaScript
class ImageResampleDialog extends React.Component { static propTypes = { isOpen: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired }; state = { blockWidth: 1, blockWidthErrorMessage: "", blockHeight: 1, blockHeightErrorMessage: "" }; /** General listener for a change on the block width or height inputs */ onChange = ( e, valueStateName, errorMessageStateName, minPossibleValue, maxPossibleValue ) => { const value = Number.parseFloat(e.target.value); if (!isInRange(value, minPossibleValue, maxPossibleValue + 1)) { this.setState({ [valueStateName]: e.target.value, [errorMessageStateName]: `Required a number between ${minPossibleValue} and ${maxPossibleValue}` }); } else { this.setState({ [valueStateName]: value, [errorMessageStateName]: "" }); } }; /** Listener for when the user changes the block width input value */ onBlockWidthChange = e => { const { index } = this.props.appStore.selectedGridItem; const { versionsHistory, currentVersionIndex } = this.props.appStore.imagesInfos[index]; const { imageBuffer } = versionsHistory[currentVersionIndex]; this.onChange( e, "blockWidth", "blockWidthErrorMessage", 1, imageBuffer.width ); }; /** Listener for when the user changes the block height input value */ onBlockHeightChange = e => { const { index } = this.props.appStore.selectedGridItem; const { versionsHistory, currentVersionIndex } = this.props.appStore.imagesInfos[index]; const { imageBuffer } = versionsHistory[currentVersionIndex]; this.onChange( e, "blockHeight", "blockHeightErrorMessage", 1, imageBuffer.height ); }; onSubmit = () => { const { blockWidth, blockHeight } = this.state; const { appStore, enqueueSnackbar } = this.props; const { index, type } = this.props.appStore.selectedGridItem; if (type !== "image" || index < 0) { enqueueSnackbar("You first need to select an image", { variant: "warning" }); } else { const { versionsHistory, currentVersionIndex } = this.props.appStore.imagesInfos[index]; const { imageBuffer } = versionsHistory[currentVersionIndex]; appStore.addOperationResult( imageResampling( imageBuffer, blockWidth, blockHeight ) ); this.props.onClose(); } }; render() { return ( <Dialog open={this.props.isOpen} onClose={this.props.onClose} scroll="body" aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title">Image Resample</DialogTitle> <DialogContent> <DialogContentText> Please, enter the pixels block width and height </DialogContentText> <div className="center" style={styles.inputsContainer}> <TextField error={!!this.state.blockWidthErrorMessage} label={this.state.blockWidthErrorMessage} type="number" placeholder={String(this.state.blockWidth)} value={this.state.blockWidth} onChange={this.onBlockWidthChange} margin="dense" style={styles.input} InputProps={{ startAdornment: ( <InputAdornment position="start">Width: </InputAdornment> ) }} /> <TextField error={!!this.state.blockHeightErrorMessage} label={this.state.blockHeightErrorMessage} type="number" placeholder={String(this.state.blockHeight)} value={this.state.blockHeight} onChange={this.onBlockHeightChange} margin="dense" style={styles.input} InputProps={{ startAdornment: ( <InputAdornment position="start">Height: </InputAdornment> ) }} /> </div> </DialogContent> <DialogActions> <Button onClick={this.props.onClose} color="primary"> Cancel </Button> <Button onClick={this.onSubmit} color="primary"> Submit </Button> </DialogActions> </Dialog> ); } }
JavaScript
class BackgroundScript { /** * It creates a new Background Script class and initialize all the class properties. It will also bootstrap the actual connection. * * @param {string} scriptId A unique ID to identify this script * @param {Object} exposedData An object containing all properties and methods to be exposed to the background script * @param {Object} options * @param {string} options.context The context of this content script. It can have three values: * "content" - To be used in content scripts. * "devtools" - To be used in scripts that run from the devtools. * "tab-agnostic" - To be used in scripts that are not related to any tab, and are unique in your extension. */ constructor(scriptId, exposedData = {}, options = { context: "content" }) { this.scriptId = scriptId ?? this._uuidv4(); this.connection = null; this.exposedData = exposedData; this.context = options.context ?? "content"; this.connectBackgroundScript(); } /** * Creates a connection to the background script based on the script context. It initializes the "connection" property. */ connectBackgroundScript() { let completeScriptId = ""; switch (this.context) { case "content": completeScriptId = CONNECTION_PREFIX + this.scriptId; break; case "devtools": if (!chrome.devtools) throw "Cannot set context='devtools' when the script is not in a devtools window."; completeScriptId = CONNECTION_PREFIX_NOTAB + this.scriptId + "-" + chrome.devtools.inspectedWindow.tabId; break; case "tab-agnostic": completeScriptId = this.scriptId; break; } let port = chrome.runtime.connect( { name: completeScriptId } ); this.connection = new Connection(port, this.exposedData); this.connection.addListener("disconnect", () => { this.connection = null; }); window.addEventListener("beforeunload", () => { if (this.connection) { this.connection.disconnect(); } }); } /** * Function to retrieve the connection proxy. * * @async * @return {Promise<Proxy>} */ async getConnection() { if (!this.connection) { this.connectBackgroundScript(); } let proxy = await this.connection.getProxy(); return proxy; } /** * Function that returns a uuid version 4 formatted string. * * @return {string} the id. */ _uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } }
JavaScript
class SingleEventRule extends BaseRule { constructor(crules, levelId, config) { super(crules, levelId, config) if (this.config.eventType) { this.addEventType(this.config.eventType) } } /** * Returns number of rewards the user qualifies for, taking into account the rule's limit. * @param {string} ethAddress - User's account. * @param {Array<models.GrowthEvent>} events * @returns {number} * @private */ async _numRewards(ethAddress, events) { const tally = this._tallyEvents( ethAddress, this.eventTypes, events, // Filter using the customIDFilter function if it is defined. this.customIdFilter ? customId => this.customIdFilter(customId) : null ) return Object.keys(tally).length > 0 ? Math.min(Object.values(tally)[0], this.limit) : 0 } /** * Returns true if the rule passes, false otherwise. * @param {string} ethAddress - User's account. * @param {Array<models.GrowthEvent>} events * @returns {boolean} */ async _evaluate(ethAddress, events) { const tally = this._tallyEvents( ethAddress, this.eventTypes, events, // Filter using the customIDFilter function if it is defined. this.customIdFilter ? customId => this.customIdFilter(customId) : null ) return Object.keys(tally).length > 0 && Object.values(tally)[0] > 0 } }
JavaScript
class Page { constructor(title, path) { this.title = title; this.path = path; } open() { browser.url(this.path); } }
JavaScript
class ImageReference { /** * Create a ImageReference. * @property {string} [publisher] The publisher of the Azure Virtual Machines * Marketplace image. For example, Canonical or MicrosoftWindowsServer. * @property {string} [offer] The offer type of the Azure Virtual Machines * Marketplace image. For example, UbuntuServer or WindowsServer. * @property {string} [sku] The SKU of the Azure Virtual Machines Marketplace * image. For example, 18.04-LTS or 2019-Datacenter. * @property {string} [version] The version of the Azure Virtual Machines * Marketplace image. A value of 'latest' can be specified to select the * latest version of an image. If omitted, the default is 'latest'. * @property {string} [id] The ARM resource identifier of the Virtual Machine * Image or Shared Image Gallery Image. Compute Nodes of the Pool will be * created using this Image Id. This is of either the form * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName} * for Virtual Machine Image or * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{versionId} * for SIG image. This property is mutually exclusive with other properties. * For Virtual Machine Image it must be in the same region and subscription * as the Azure Batch account. For SIG image it must have replicas in the * same region as the Azure Batch account. For information about the firewall * settings for the Batch node agent to communicate with the Batch service * see * https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. */ constructor() { } /** * Defines the metadata of ImageReference * * @returns {object} metadata of ImageReference * */ mapper() { return { required: false, serializedName: 'ImageReference', type: { name: 'Composite', className: 'ImageReference', modelProperties: { publisher: { required: false, serializedName: 'publisher', type: { name: 'String' } }, offer: { required: false, serializedName: 'offer', type: { name: 'String' } }, sku: { required: false, serializedName: 'sku', type: { name: 'String' } }, version: { required: false, serializedName: 'version', type: { name: 'String' } }, id: { required: false, serializedName: 'id', type: { name: 'String' } } } } }; } }
JavaScript
class Emoji { /** * @param {string} path The path of emoji image * @param {EmojiSheet} sheet The emoji sheet * @param {string} emojiClass The emoji sheet */ constructor (path, sheet, emojiClass) { this.path = path this.sheet = sheet this.emojiClass = emojiClass } getSymbol () { return path.basename(this.path, path.extname(this.path)) } getRelativePath () { return path.relative(this.sheet.dirname(), this.path) } toString () { return template .replace('{emojiClass}', this.emojiClass) .replace('{emoji}', this.getSymbol()) .replace('{path}', this.getRelativePath()) } }
JavaScript
class FaultTolerant extends Node { constructor (wallet, genesis, network, delta) { super(wallet, genesis, network) this.delta = delta this.pendingTxs = {} this.seen = [] this.nonce = 0 } timeout(timestamp, numObservers) { return timestamp + numObservers * this.delta } addressesFromSigs(tx) { let addressSet = new Set() for (let i = 0; i < tx.sigs.length; i++) { const sig = tx.sigs[i] const slicedTx = { contents: tx.contents, sigs: tx.sigs.slice(0,i) } const messageHash = getTxHash(slicedTx) const address = EthCrypto.recover(sig, messageHash) if(i===0 && address !== tx.contents.from) throw new Error('Invalid first signature!') addressSet.add(address) } return addressSet } onReceive (tx) { if (this.seen.includes(tx.contents)) return const sigs = this.addressesFromSigs(tx) //TODO catch error if first signee is not tx sender if(this.network.time >= this.timeout(tx.contents.timestamp, sigs.size)) return this.addToPending(tx) //add signature tx.sigs.push(EthCrypto.sign(this.wallet.privateKey, getTxHash(tx))) this.network.broadcast(this.pid, tx) } addToPending(tx) { //seen tx this.seen.push(tx.contents) //TODO Check that each signee is actually a peer in the network //-possible attack: byzantine node signs a message 100 times with random Private Key const finalTimeout = this.timeout(tx.contents.timestamp, this.network.agents.length) if (!this.pendingTxs[finalTimeout]) this.pendingTxs[finalTimeout] = [] //add to pending ( we'll apply this transaction once we hit finalTimeout) this.pendingTxs[finalTimeout].push(tx) //Choice rule: if have two transactions with same sender, nonce, and timestamp apply the one with lower sig first this.pendingTxs[finalTimeout].sort((a, b)=>{ return a.sigs[0] - b.sigs[0] }) } sendTx(to, amount) { const tx = this.generateTx(to, amount) this.nonce++ this.addToPending(tx) this.network.broadcast(this.pid, tx) } tick () { const {time} = this.network const toApply = this.pendingTxs[time] if(!toApply) return for (let tx of toApply) { this.applyTransaction(tx) } delete this.pendingTxs[time] } generateTx (to, amount) { const unsignedTx = { type: 'send', amount: amount, from: this.wallet.address, to: to, nonce: this.nonce, timestamp: this.network.time } const tx = { contents: unsignedTx, sigs: [] } tx.sigs.push(EthCrypto.sign(this.wallet.privateKey, getTxHash(tx))) return tx } applyTransaction (tx) { console.log('~~~~~~~~~APPLY TRANSACTION~~~~~~~~~~', tx) // If we don't have a record for this address, create one if (!(tx.contents.to in this.state)) { this.state[tx.contents.to] = { balance: 0, nonce: 0 } } // Check that the nonce is correct for replay protection if (tx.contents.nonce > this.state[tx.contents.from].nonce) { if (!(tx.contents.from in this.invalidNonceTxs)) { this.invalidNonceTxs[tx.contents.from] = {} } this.invalidNonceTxs[tx.contents.from][tx.contents.nonce] = tx return } else if (tx.contents.nonce < this.state[tx.contents.from].nonce) { console.log('passed nonce tx rejected') return } //Apply send to balances if (tx.contents.type === 'send') { // Send coins if (this.state[tx.contents.from].balance - tx.contents.amount < 0) { throw new Error('Not enough money!') } this.state[tx.contents.from].balance -= tx.contents.amount this.state[tx.contents.to].balance += tx.contents.amount } else { throw new Error('Invalid transaction type!') } this.state[tx.contents.from].nonce += 1 this.setColor() } }
JavaScript
class Pushover extends Trigger { /** * Get the Trigger configuration schema. * @returns {*} */ getConfigurationSchema() { return this.joi.object().keys({ user: this.joi.string().required(), token: this.joi.string().required(), device: this.joi.string(), sound: this.joi.string().allow( 'alien', 'bike', 'bugle', 'cashregister', 'classical', 'climb', 'cosmic', 'echo', 'falling', 'gamelan', 'incoming', 'intermission', 'magic', 'mechanical', 'none', 'persistent', 'pianobar', 'pushover', 'siren', 'spacealarm', 'tugboat', 'updown', 'vibrate', ).default('pushover'), priority: this.joi .number() .integer() .min(-2) .max(2) .default(0), }); } /** * Sanitize sensitive data * @returns {*} */ maskConfiguration() { return { ...this.configuration, user: Pushover.mask(this.configuration.user), token: Pushover.mask(this.configuration.token), }; } /** * Send a Pushover notification with new container version details. * * @param container the container * @returns {Promise<void>} */ async trigger(container) { return this.sendMessage({ title: this.renderSimpleTitle(container), message: this.renderSimpleBody(container), sound: this.configuration.sound, device: this.configuration.device, priority: this.configuration.priority, }); } /** * Send a Pushover notification with new container versions details. * @param containers * @returns {Promise<unknown>} */ async triggerBatch(containers) { return this.sendMessage({ title: this.renderBatchTitle(containers), message: this.renderBatchBody(containers), sound: this.configuration.sound, device: this.configuration.device, priority: this.configuration.priority, }); } async sendMessage(message) { return new Promise((resolve, reject) => { const push = new Push({ user: this.configuration.user, token: this.configuration.token, }); push.onerror = (err) => { reject(new Error(err)); }; push.send(message, (err, res) => { if (err) { reject(new Error(err)); } else { resolve(res); } }); }); } /** * Render trigger body batch (override) to remove empty lines between containers. * @param containers * @returns {*} */ renderBatchBody(containers) { return containers.map((container) => `- ${this.renderSimpleBody(container)}`).join('\n'); } }
JavaScript
class WillyWonka { constructor() { this._chocolate = new Subject(); this.disableChocolateCheck = false; } get chocolate() { return this._chocolate.asObservable(); } ngAfterViewChecked() { if (!this.disableChocolateCheck) { this._chocolate.next(); } } }
JavaScript
class TocItem { /** * Create a table of contents item object. * * @param {object} a */ constructor(a) { // We expect that the number and text are the first two children of a <li> element. const textSpan = a.children[1]; const headline = textSpan.textContent; const anchor = a.getAttribute('href').slice(1); const li = a.parentNode; let [, level] = li.className.match(/\btoclevel-(\d+)/); level = Number(level); const number = a.children[0].textContent; Object.assign(this, { headline, anchor, level, number, $element: $(li), $link: $(a), $text: $(textSpan), }); } /** * Generate HTML to use it in the TOC for the section. Only a limited number of HTML elements is * allowed in TOC. * * @param {JQuery} $headline */ replaceText($headline) { const html = $headline .clone() .find('*') .each((i, el) => { if (['B', 'EM', 'I', 'S', 'STRIKE', 'STRONG', 'SUB', 'SUP'].includes(el.tagName)) { Array.from(el.attributes).forEach((attr) => { el.removeAttribute(attr.name); }); } else { Array.from(el.childNodes).forEach((child) => { el.parentNode.insertBefore(child, el); }); el.remove(); } }) .end() .html(); this.$text.html(html); this.headline = this.$text.text().trim(); } }
JavaScript
class Block { /** * constructor * @param {*} data * @param {number} [time=0] - the timestamp of when the Block was hashed * @param {number} [height=0] - the height of block on the chain * @param {string} [previousBlockHash=''] - previous Block hash */ constructor(data, time = 0, height = 0, previousBlockHash = '') { this.hash = ''; this.height = height; this.body = data //necessary to avoid errors when an empty block is created on LevelSandox.getLevelDBData() if (this.body.star != null) { this.body.star.story = Buffer.from(data.star.story, 'ascii').toString('hex') } this.time = time; this.previousBlockHash = previousBlockHash; } /** * add the field storyDecode to body.star. * Necessary to call before the Block is returned through a GET method */ decodeStory() { this.body.star.storyDecode = hex2ascii(this.body.star.story) } }
JavaScript
class HUD extends EventDispatcher { constructor(three, scene) { super(); this.three = three; if(!scene) { this.scene = new ThreeScene(); } else { this.scene = scene; } this.selectedItem = null; this.rotating = false; this.mouseover = false; this.tolerance = 10; this.height = 5; this.distance = 20; this.color = '#ffffff'; this.hoverColor = '#f1c40f'; this.activeObject = null; var scope = this; this.itemselectedevent = (o) => {scope.itemSelected(o.item);}; this.itemunselectedevent = () => {scope.itemUnselected();}; this.init(); } init() { // this.three.itemSelectedCallbacks.add(itemSelected); // this.three.itemUnselectedCallbacks.add(itemUnselected); this.three.addEventListener(EVENT_ITEM_SELECTED, this.itemselectedevent); this.three.addEventListener(EVENT_ITEM_UNSELECTED, this.itemunselectedevent); } getScene() { return this.scene; } getObject() { return this.activeObject; } resetSelectedItem() { this.selectedItem = null; if (this.activeObject) { this.scene.remove(this.activeObject); this.activeObject = null; } } itemSelected(item) { if (this.selectedItem != item) { this.resetSelectedItem(); if (item.allowRotate && !item.fixed) { this.selectedItem = item; this.activeObject = this.makeObject(this.selectedItem); this.scene.add(this.activeObject); } } } itemUnselected() { this.resetSelectedItem(); } setRotating(isRotating) { this.rotating = isRotating; this.setColor(); } setMouseover(isMousedOver) { this.mouseover = isMousedOver; this.setColor(); } setColor() { var scope = this; if (scope.activeObject) { scope.activeObject.children.forEach((obj) => {obj.material.color.set(scope.getColor());}); } // this.three.needsUpdate(); scope.three.ensureNeedsUpdate(); } getColor() { return (this.mouseover || this.rotating) ? this.hoverColor : this.color; } update() { if (this.activeObject) { this.activeObject.rotation.y = this.selectedItem.rotation.y; this.activeObject.position.x = this.selectedItem.position.x; this.activeObject.position.z = this.selectedItem.position.z; } } makeLineGeometry(item) { var geometry = new Geometry(); geometry.vertices.push(new Vector3(0, 0, 0),this.rotateVector(item)); return geometry; } rotateVector(item) { var vec = new Vector3(0, 0,Math.max(item.halfSize.x, item.halfSize.z) + 1.4 + this.distance); return vec; } makeLineMaterial() { var mat = new LineBasicMaterial({color: this.getColor(),linewidth: 3}); return mat; } makeCone(item) { var coneGeo = new CylinderGeometry(5, 0, 10); var coneMat = new MeshBasicMaterial({color: this.getColor()}); var cone = new Mesh(coneGeo, coneMat); cone.position.copy(this.rotateVector(item)); cone.rotation.x = -Math.PI / 2.0; return cone; } makeSphere() { var geometry = new SphereGeometry(4, 16, 16); var material = new MeshBasicMaterial({color: this.getColor()}); var sphere = new Mesh(geometry, material); return sphere; } makeObject(item) { var object = new Object3D(); var line = new LineSegments(this.makeLineGeometry(item),this.makeLineMaterial(this.rotating)); var cone = this.makeCone(item); var sphere = this.makeSphere(item); object.add(line); object.add(cone); object.add(sphere); object.rotation.y = item.rotation.y; object.position.x = item.position.x; object.position.z = item.position.z; object.position.y = this.height; return object; } }
JavaScript
class Fighter { constructor(name, lifeEnergy) { //constructor of class Fighter = Muster für den Aufbau with the parameters name and lifeEnergy this.name = name; this.life = lifeEnergy; } getAttack() { //method to get a random number return Math.floor(Math.random() * 6 + 2); } }
JavaScript
class CalendarScreen extends React.Component { constructor(props) { super(props); this.state = { date : '', dataName: '', dataHealth : '', }; } /** * * @param {*} req address of the server to send get request * Used to return a list of found users from a search */ getRequest = (req) =>{ console.log(req); fetch(req, { method: 'GET' }) .then((response) => response.json()) .then((responseJson) => { console.log("GET response: " + responseJson); if((responseJson || []).length === 0){ this.setState({searchResult : ['Not Found']}); }else{ var nameArr = []; var healthArr = []; var i; for(i = 0; i < responseJson.length; i++){ if(responseJson[i].date == this.state.date){ nameArr.push(responseJson[i].firstName + " " + responseJson[i].lastName); healthArr.push(responseJson[i].healthStatus); } } this.setState({ dataName: nameArr, dataHealth : healthArr, }) console.log("dataName" + this.state.dataName); } }) .catch((error) => { console.error(error); }); } render(){ const {navigation} = this.props; return ( <View style={styles.container} > <ImageBackground source={image} style={styles.image}> <Calendar onDayPress={day => { this.setState({ date: day.dateString }) const request = GLOBAL.serverURL+'/user/getTemporaryConnections?_id='+GLOBAL.userID; this.getRequest(request); }} enableSwipeMonths={true} markedDates={{ [this.state.date]: { selected: true }, }} theme={{ selectedDayBackgroundColor: '#ACD7CA', todayTextColor: '#ACD7CA', dotColor: '#ACD7CA', selectedDayTextColor: 'white', monthTextColor: '#ACD7CA', arrowColor: '#ACD7CA', }} /> <Icon.Button testID = 'add_tmp' name="account-plus" backgroundColor="#ACD7CA" onPress={() => { navigation.navigate('Add Temporary Connection',{ date: this.state.date, }) console.log("date: " + this.state.date); }} > Add Temporary Connection </Icon.Button> <View style={{flex: 1, flexDirection: 'row'}} > <FlatList data={this.state.dataName} renderItem={({item, index}) => { return <View style={{flex: 1, flexDirection: 'row'}} > <Text style={styles.item} >{item}</Text> </View> }} /> <FlatList data={this.state.dataHealth} renderItem={({item, index}) => { return <View style={{flex: 1, flexDirection: 'row',padding:5}} > <Image style = {styles.badge} source={badgeImages[item]}/> </View> }} /> </View> </ImageBackground> </View> ); } }
JavaScript
class Main extends Component { constructor(props) { super(props); this.state = { container: { containerId: 'org.optatask:optatask:1.0-SNAPSHOT', groupId: 'org.optatask', artifactId: 'optatask', version: '1.0-SNAPSHOT', }, solver: { id: 'solver1', configFilePath: 'org/optatask/solver/taskAssigningSolverConfig.xml', }, bestSolution: {}, }; this.onContainerChagne = this.onContainerChagne.bind(this); this.handleGetSolution = this.handleGetSolution.bind(this); this.updateBestSolution = this.updateBestSolution.bind(this); } onContainerChagne(container) { this.setState({ container }); } updateBestSolution() { fetch(`${constants.BASE_URI}/containers/${this.state.container.containerId}/solvers/${this.state.solver.id}/bestsolution`, { credentials: 'include', headers: { 'X-KIE-ContentType': 'xstream', }, }) .then((response) => { if (response.ok) { return response.text(); } const error = new Error(`${response.status}: ${response.statusText}`); error.response = response; throw error; }, (error) => { throw new Error(error.message); }) .then(response => (new DOMParser()).parseFromString(response, 'text/xml')) .then(response => JXON.build(response)) .then((response) => { if (Object.prototype.hasOwnProperty.call(response['solver-instance'], 'best-solution')) { this.setState({ bestSolution: response['solver-instance']['best-solution'] }); } else { alert('Solver is not solving'); } }) .catch(error => console.log(error)); } handleGetSolution(event) { event.preventDefault(); this.updateBestSolution(); } render() { const tasks = []; if (Object.prototype.hasOwnProperty.call(this.state.bestSolution, 'employeeList')) { this.state.bestSolution.employeeList.TaEmployee.forEach((employee) => { let currentTask = employee.nextTask; while (currentTask != null) { tasks.push(currentTask); currentTask = currentTask.nextTask; } }); } tasks.sort((t1, t2) => parseInt(t1.id, 10) > parseInt(t2.id, 10)); return ( <div> <Header /> <Switch> <Route path="/home" component={() => ( <Home container={this.state.container} onContainerChagne={this.onContainerChagne} bestSolution={this.state.bestSolution} handleGetSolution={this.handleGetSolution} /> )} /> <Route exact path="/tasks" component={() => ( <TaskPage tasks={tasks} container={this.state.container} solver={this.state.solver} updateBestSolution={this.updateBestSolution} /> )} /> <Redirect to="/home" /> </Switch> </div> ); } }
JavaScript
class CurrentUserNode extends ResourceNode { constructor({ clientSession }) { super({ clientSession, type: 'currentUser', }); this.api = '/api/user'; } // ************************ Helpers methods ************************ }
JavaScript
class ImageInput extends React.Component { constructor(props) { super(props) this.setImageState = this.setImageState.bind(this) } state = { image_default: '../../../public/images/recipeDefaultImage.png', image_passed: this.props.value, image_picked: null, } // setImageState and blobBase64 convert blob data to base64 and pass it to the state, see above docstring for more commentary. setImageState(base64data) { this.setState({ image_picked: base64data }) this.props.callback(base64data.split(',')[1]) } blobBase64(blobData, callback) { var reader = new FileReader() reader.readAsDataURL(blobData) reader.onloadend = function () { var base64data = reader.result callback(base64data) } } render() { let image if (this.state.image_passed == null || this.state.image_passed == 'null') { image = <img src={this.state.image_default} style={styles.image} /> } else { image = <img src={this.state.image_passed} style={styles.image} /> } if (this.state.image_picked != null) { image = <img src={this.state.image_picked} style={styles.image} /> } return ( <div style={{ height: 240 }}> {image} <label htmlFor="imageInput" style={styles.changeImage}> <img src="../../../public/images/cameraIcon.png" style={{ width: 50 }} /> <input type="file" accept="image/*" id="imageInput" name="imageInput" style={{ display: 'none' }} onChange={(event) => { if (event.target.value.length != 0) { alert('Images cannot be added at this time!') // we don't have a CDN, images are hardcoded at this time. } else { this.setState({ image_picked: null }) this.props.onChange(null) } }} /> </label> </div> ) } }
JavaScript
class MainNav extends React.Component { handleClickLogout = () => this.props.authStore .logout() .then(() => this.props.history.replace('/')); render(){ return ( <div> <LoggedOutView currentUser={this.props.userStore.currentUser} /> <LoggedInView currentUser={this.props.userStore.currentUser} onLogout={this.handleClickLogout} /> </div> ); } }
JavaScript
class Prompt extends Phaser.GameObjects.Container { /** * Creates prompt background. * * @param {Phaser.Scene} scene The scene this prompt belongs to. * @param {GameManager} game The game manager instance this belongs to. */ constructor(scene, game) { super(scene); this.game = game; this.promptGameObject = null; this.background = new Phaser.GameObjects.Rectangle(this.scene, 0, 0, this.scene.game.config.width, this.scene.game.config.height, 0x000000, 0.5); this.background.setOrigin(0); this.background.setVisible(false); this.isShowing = false; this.add([this.background]); } /** * Shows the game object in this prompt window and * applys a tween bounce effect as it flys in from * the bottom. * * @param {Phaser.GameObject} promptGameObject The game object to show in the prompt window. * @param {?Prompt~animationCallback} [cb=null] Callback invoked when animation completes. * @fires Prompt#show */ showWithAnim(promptGameObject, cb=null) { this.show(promptGameObject); this.promptGameObject.setPosition(this.scene.game.config.width / 2, this.scene.game.config.height * 2); const onComplete = () => { if(this.promptGameObject instanceof Card) { this.promptGameObject.setEnabled(true); } if(typeof cb === "function") { cb(); } this.emit("show"); }; if(this.promptGameObject instanceof Card) { this.promptGameObject.setEnabled(false); } this.scene.tweens.add({ targets: this.promptGameObject, ease: "Back.easeOut", y: this.scene.game.config.height / 2, onComplete: onComplete }); } /** * Tweens the prompt object out of view and then * closes this prompt view. * * @param {?Prompt~animationCallback} [cb=null] Callback invoked when animation completes. * @fires Prompt#close */ closeWithAnim(cb=null) { const onComplete = () => { this.close(); if(typeof cb === "function") { cb(); } this.emit("close"); }; if(this.promptGameObject instanceof Card) { this.promptGameObject.setEnabled(false); } this.scene.tweens.add({ targets: this.promptGameObject, ease: "Back.easeIn", y: this.scene.game.config.height * 2, onComplete: onComplete }); } /** * Adds the game object passed in to this container * and shows it instantly. * * Calling this will close the prompt first. * * @param {Phaser.GameObjects} promptGameObject The game object to show. */ show(promptGameObject) { if(this.isShowing) { this.close(); } this.promptGameObject = promptGameObject; this.add(this.promptGameObject); const x = (this.scene.game.config.width / 2) - (this.promptGameObject.width / 2); const y = (this.scene.game.config.height / 2) - (this.promptGameObject.height / 2); this.promptGameObject.setPosition(x, y); this.background.setVisible(true); this.isShowing = true; } /** * Hides the game object and this prompt and * then removes the game object from the container. */ close() { this.remove(this.promptGameObject); this.promptGameObject = null; this.background.setVisible(false); this.isShowing = false; } }
JavaScript
class RJSFReferencedDocument extends Component { responseSerializer = (record) => { const { edition, pid, publicationYear, document_type: documentType, title, } = record.metadata; const descriptions = []; edition && descriptions.push(`Edition: ${edition}`); publicationYear && descriptions.push(`Year: ${publicationYear}`); descriptions.push(`Type: ${documentType}`); descriptions.push(`PID: ${pid}`); return { key: pid, value: pid, text: title, content: ( <Header as="h5" content={title} subheader={descriptions.join(' - ')} /> ), }; }; query = async (searchQuery) => await documentApi.list(searchQuery); render() { const { options } = this.props; return ( <RJSFESSelector {...this.props} options={{ apiGetByValue: async (value) => (await documentApi.get(value)).data, apiGetByValueResponseSerializer: this.responseSerializer, apiQuery: async (searchQuery) => await documentApi.list(searchQuery), apiQueryResponseSerializer: this.responseSerializer, ...options, }} /> ); } }
JavaScript
class EditExpensePage extends React.Component { constructor(props) { super(props); } onSubmit = (expense) => { this.props.startEditExpense(this.props.expense.id, expense) this.props.history.push("/") } onClick = () => { this.props.startRemoveExpense({ id: this.props.expense.id }) this.props.history.push("/") } render() { return ( <div> <div className={"page-header"}> <div className={"content-container"}> <h1 className={"page-header__title"}>Edit Expense</h1> </div> </div> <div className={"content-container"}> <ExpenseForm expense={this.props.expense} onSubmit={this.onSubmit} /> <button className={"button button--secondary"} onClick={this.onClick}> Remove Expense </button> </div> </div> ) } }
JavaScript
class TetrisGame { /** * * @returns {TetrisGame} */ static init(config) { /** * Base config for game */ this.config = { rows: 10, mobileRows: 8, columnsMin: 6, columnsMax: 16, workingWordCount: 5, workingCountSimple : 4, workingCountMedium : 5, workingCountExpert : 6, charSpeed: 800, // 1 second - get division to level when making game harder useLowercase: false, simpleFallDownAnimateSpeed: 700, mediumFallDownAnimateSpeed: 500, expertFallDownAnimateSpeed: 200, successAnimationIterationDuration: 100, vibrationDuration: 200, do_shake: true, do_encryption: true, // Enables encryption when saving score encryptionKeySize: 16, // Size of key Used in encryption directionWordChecks: { ltr: true, // check left to right rtl: true, // check right to left ttd: true, // check top top down dtt: false // check down to top }, scoreCalculator: word => { return Math.pow(word.length, 1.3); // Larger words will have better score }, chooseedWordKind: {}, // user setting values playBackgroundSound: true, playEventsSound: true, level: 1, // Up to 3 - if it is big it is hard to play useAnimationFlag: true, // Make animate or not showGrids: true, // Show grids flag enable_special_characters: true, colorMode: (Helper.isDay() ? 0 : 1), // 0 = dayMode , 1 = nightMode do_vibrate: true }; // Extend config from user Object.assign(this.config, config); /** * We hold game values here */ this.setDefaultValues(true); /** * Global key codes config on window */ window.CONTROL_CODES = { DOWN: 40, LEFT: 37, RIGHT: 39 }; /** * Game play board */ this.playBoard = null; return this; } /** * Select editor element with class search emoji * @type {HTMLElement | null} */ static build() { const initValues = this.initValues; const config = this.config; if (config.do_encryption) { const encryptionKeySize = config.encryptionKeySize; for (let i=0; i<encryptionKeySize; ++i) initValues.encryptionKey.push(1+Math.floor(Math.random()*253)); Storage.setEncrypted('score', 0, initValues.encryptionKey); } else { Storage.set('score', '0'); } // blob for timer const blobTiming = new Blob([ Helper._('#workerTiming').textContent ], { type: 'text/javascript' }); // Shuffle words Helper.shuffleArray(window.TetrisWords); // set Timer instance to current TetrisGame.timer this.timer = new Timer({ blobTiming, onStart() { initValues.paused = false; }, workerOnMessage() { // Storage.set('seconds', event.data); }, onPause() { initValues.paused = true; }, onResume() { initValues.paused = false; } }); // set interval class this.interval = new Interval(); // control key codes // In LTR languages, Left and Right should be swapped this.controlCodes = { LEFT: (!window.lang.rtl) ? window.CONTROL_CODES.RIGHT : window.CONTROL_CODES.LEFT, RIGHT: (!window.lang.rtl) ? window.CONTROL_CODES.LEFT : window.CONTROL_CODES.RIGHT, DOWN: window.CONTROL_CODES.DOWN }; const ltrClass = (!window.lang.rtl) ? 'isLtr' : ''; if (initValues.isFirstRun) { initValues.bgSound = Sound.playByKey('background', true); initValues.isFirstRun = false; } // set game settings from local storage Settings.set(); // add main html to page Helper._('#container').innerHTML = ` <div class="gameHolder ${ltrClass}"> <div class="behindPlayBoard"> <div class="gamingKind" onclick="Gameplay.restartWholeGame();"><span class="persian">${config.chooseedWordKind.persianTitle}</span><span class="english">${config.chooseedWordKind.englishTitle}</span><span class="japanese">${config.chooseedWordKind.japaneseTitle}</span></div> <div class="showUpComingLetter" title="${window.lang.nextLetter}:"></div> <div class="gameControlButtons" > <div onclick="Gameplay.start();" class="startGame">${window.lang.startGame}</div> <div onclick="Gameplay.pause();" class="pauseGame" style="display: none">${window.lang.pauseGame}</div> <div onclick="Gameplay.resume();" class="resumeGame" style="display: none">${window.lang.resumeGame}</div> <div onclick="Gameplay.restart();" class="restartGame" style="display: none">${window.lang.restartGame}</div> </div> <div class="courseArea"> <div class="setting" onclick="Settings.show();"><i class="icon-setting"></i> ${window.lang.settings}</div> <div ><i class="icon-money"></i> ${window.lang.score} : <span class="scoreHolder"> 0 </span> &nbsp;|&nbsp; <span class="showScoresList" onclick="ScoreHandler.showScores();" ><i class="icon-bil"></i> ${window.lang.records}</span> </div> <div ><i class="icon-sibil"></i> ${window.lang.createdWords} : <span class="wordCounterHolder">0</span> </div> <div ><i class="icon-clock"></i> ${window.lang.spentTime} : <span class="timerDisplay">0</span></div> </div> </div> <div class="playBoard"><span class="emptyPlayBoard">${window.lang.clickStartGame}</span></div> </div> <!--Lazy load bomb Gif--> <img src="assets/img/bomb.gif" alt="bombChar" width="0" /> <img src="assets/img/skull.gif" alt="skull" width="0" /> <footer class="page-footer"> <div class="container"> <i class="icon-brain"></i> ${window.lang.copyRight} </div> </footer> `; const lazyLoadSounds = ['start', 'moveChar', 'explode', 'foundWord', 'finishGame']; for (const sound of lazyLoadSounds) { new Sound(sound); } } /** * Sets default values of this.initValues * @param firstCall */ static setDefaultValues(firstCall) { this.initValues = { paused: false, // is game paused comingWordIndex: 0, finished: false, // is game finished wordsFinished: false, // do we run out of words isFirstRun: firstCall, // it is not first run bgSound: (firstCall ? {} : this.initValues.bgSound), // is this my first run cachedRows: (firstCall ? {} : this.initValues.cachedRows), // cache rows here upComingCharEl: null, score: 0, // This is fake, We will never show anything related to this to user encryptionKey: [], // key of variables encryption validatedColumnsCount: 0, // Count of columns which are validated nextChar: '', // Next character activeChar: {}, // Active character [not stopped] charBlock object choosedWords: [], // Choosed words to work with them choosedWordsUsedChars: [], // Chars that used from choosed words wordsLengthTotal: 0, // Average length of words founded in games wordsFounded: 0, // Counter to hold count of words found in game wordDirectionCounter: { // Counter of founded word in each direction rtl: 0, ltr: 0, ttd: 0, dtp: 0, exploded: 0 }, isMobile: Helper.isMobile(), falledStack: new MapStack(), animateConfig: { animateClass: 'fallDownSimple', deleteTiming: TetrisGame.config.simpleFallDownAnimateSpeed } }; } /** * Get a valid column number [min-max] */ static validateColumnsNumber() { const config = this.config; let columnsNumber = config.columnsMin; for (let i = Object.keys(window.TetrisWords).length - 1; i >= 0; i--) { if (window.TetrisWords[i]) { const thisWordLength = window.TetrisWords[i].word.length; if (thisWordLength > columnsNumber) { columnsNumber = thisWordLength; } } } // plus 2 extra block than max word length columnsNumber += 2; columnsNumber = config.columnsMax < columnsNumber ? config.columnsMax : columnsNumber; const validatedColumns = columnsNumber % 2 === 0 ? columnsNumber : columnsNumber + 1; // add class to have playBoard columns TetrisGame.playBoard.classList.add( `is${validatedColumns}Column` ); TetrisGame.initValues.validatedColumnsCount = validatedColumns; return validatedColumns; } /** * Check if could find a success word * @param {Charblock} lastChar */ static checkWordSuccess(lastChar) { // pause game while checking and animating this.initValues.paused = true; // check word happens and then call checkWordsResult fn this.matrix.checkWords( window.TetrisWords, lastChar, this.config.directionWordChecks, this.checkWordsResult ); } /** * Calls after word success check * @param lastChar * @param successObject */ static checkWordsResult(lastChar, successObject) { const config = TetrisGame.config; const initValues = TetrisGame.initValues; initValues.paused = true; if (!successObject) { // no words has been found, resume the game TetrisGame.checkSuccessWordStack(); return; } else if (lastChar.type === 'bomb') { Helper.log('BOOOOOOM'); TetrisGame._animateExplode(successObject, lastChar); return; } const word = initValues.choosedWords[successObject.wordId].word; // Update score ScoreHandler._updateScoreAndStats(word, successObject.direction); TetrisGame._removeWordAndCharacters(word, successObject.wordId); // animate found word Animate.showFoundWordAnimated(word, successObject.wordCharacterPositions); Animate.animateFoundedCharacters(successObject.wordCharacterPositions, config.successAnimationIterationDuration); initValues.falledStack.merge(successObject.fallingCharacters); Timeout.request( () => { Animate.animateFallCharacters( successObject.fallingCharacters, // MapStack of falling characters config.successAnimationIterationDuration, // Delay between falling TetrisGame.checkSuccessWordStack ); // get new word WordsHelper.chooseWord(); // update top words bar TetrisGame.showShuffledWords(); }, // (successObject.fallingCharacters.length * 200) + config.successAnimationIterationDuration // successObject.wordCharacterPositions.length * config.successAnimationIterationDuration ((successObject.wordCharacterPositions.length-1)*(config.successAnimationIterationDuration)) + TetrisGame.initValues.animateConfig.deleteTiming ); } /** * Check words success of stack after an explosion success * we check if we have another completed words */ static checkSuccessWordStack() { const initValues = TetrisGame.initValues; const config = TetrisGame.config; const falledCharacter = initValues.falledStack.popItem(); if (falledCharacter === false || typeof falledCharacter !== 'undefined') { // Stack is empty, resume the game Helper.log("Stack is empty :|") initValues.paused = false; return; } const x = falledCharacter.x; const y = falledCharacter.newY; // console.log(`checking y: ${y} x: ${x}`); if (TetrisGame.matrix.isNotEmpty(y, x)) { TetrisGame.matrix.checkWords( initValues.choosedWords, { row: y, column: x, char: TetrisGame.matrix.getCharacter(y, x) }, config.directionWordChecks, TetrisGame.checkWordsResult ); } else { TetrisGame.checkSuccessWordStack(); } } /** * Adds current words to top of gamePlay * this words plus with random words of * current category */ static showShuffledWords() { const parent = Helper._('.currentWorkingWords'); const randomizeFn = () => { return 0.5 - Math.random(); }; const displayFiveWords = TetrisGame.initValues.choosedWords.slice(0, TetrisGame.config.workingWordCount).sort(randomizeFn); // make working words empty parent.innerHTML = ''; displayFiveWords.forEach(item => { const currentWord = document.createElement('span'); currentWord.innerText = item.word; currentWord.className = 'currentWords'; parent.appendChild(currentWord); }); } /** * Animate explode * @param successObject * @param lastChar */ static _animateExplode(successObject, lastChar) { const config = TetrisGame.config; // explode sound play Sound.playByKey('explode', config.playEventsSound); if (config.do_shake) { Animate.shake(TetrisGame.playBoard, lastChar.typeSize*16); } if (config.do_vibrate) { Helper.vibrate(config.vibrationDuration); } // Explode the characters successObject.explodedChars.map(item => { Animate.fallNodeAnimate(item.y, item.x, null, null); }); // Update score after other blocks falled down ScoreHandler._updateScoreAndStats(successObject.explodedChars, 'exploded'); TetrisGame.initValues.falledStack.merge(successObject.fallingCharacters); // Fall characters at top of exploded chars Animate.animateFallCharacters( successObject.fallingCharacters, config.successAnimationIterationDuration, () => { TetrisGame.checkSuccessWordStack(); } ); } /** * Remove words and characters which we found or explode * @param word * @param wordId */ static _removeWordAndCharacters(word, wordId) { // Remove word from choosed words TetrisGame.initValues.choosedWords.splice(wordId, 1); // Remove characters from choosed characters TetrisGame.initValues.choosedWordsUsedChar = ''; } }
JavaScript
class CfmNetworkSettings extends PolymerElement { static get is() { return 'cfm-network-settings'; } static get template() { return html`{__html_template__}`; } static get properties() { return { customItems_: { type: Array, notify: false, readOnly: true, } }; } constructor() { super(); /** @private {?CfmNetworkSettingsBrowserProxy} */ this.browserProxy_ = null; } /** @override */ connectedCallback() { super.connectedCallback(); this.browserProxy_ = CfmNetworkSettingsBrowserProxyImpl.getInstance(); } /** * Handles tap on a network entry in networks list. * @param {!CustomEvent<!OncMojo.NetworkStateProperties>} e * @private */ onNetworkItemSelected_(e) { const mojom = chromeos.networkConfig.mojom; const networkState = e.detail; const guid = networkState.guid; if (shouldShowNetworkDetails(networkState)) { this.browserProxy_.showNetworkDetails(guid); return; } if (!networkState.connectable || networkState.errorState) { this.browserProxy_.showNetworkConfig(guid); return; } const networkConfig = MojoInterfaceProviderImpl.getInstance().getMojoServiceRemote(); networkConfig.startConnect(guid).then(response => { switch (response.result) { case mojom.StartConnectResult.kSuccess: return; case mojom.StartConnectResult.kInvalidGuid: case mojom.StartConnectResult.kInvalidState: case mojom.StartConnectResult.kCanceled: return; case mojom.StartConnectResult.kNotConfigured: if (!OncMojo.networkTypeIsMobile(networkState.type)) { this.browserProxy_.showNetworkConfig(guid); } else { console.error('Cellular network is not configured: ' + guid); } return; case mojom.StartConnectResult.kBlocked: case mojom.StartConnectResult.kUnknown: console.error( 'startConnect failed for: ' + guid + ': ' + response.message); return; } }); } /** * The list of custom items to display after the list of networks. * See NetworkList for details. * @return {!Array<NetworkList.CustomItemState>} * @private */ get customItems_() { return [ { customItemType: NetworkList.CustomItemType.OOBE, customItemName: 'addWiFiListItemName', polymerIcon: 'cr:add', showBeforeNetworksList: false, customData: {onTap: proxy => proxy.showAddWifi()}, }, { customItemType: NetworkList.CustomItemType.OOBE, customItemName: 'proxySettingsListItemName', polymerIcon: 'cr:info-outline', showBeforeNetworksList: false, customData: {onTap: proxy => proxy.showNetworkDetails('')}, }, { customItemType: NetworkList.CustomItemType.OOBE, customItemName: 'manageCertsListItemName', polymerIcon: 'cfm-custom:manage-certs', showBeforeNetworksList: false, customData: {onTap: proxy => proxy.showManageCerts()}, }, ]; } /** * Handles tap on a custom item from the networks list. * @param {!CustomEvent<{customData:!networkCustomItemCustomData}>} event * @private */ onCustomItemSelected_(event) { let itemState = event.detail; itemState.customData.onTap(this.browserProxy_); } }
JavaScript
class Update extends FeathersSequelize.Service { constructor(options) { super(options); this.app = options.app; /* * Undefining some APIs which we don't want/need. */ this.update = undefined; this.remove = undefined; } isCurrentLevelPerInstanceTainted(id, level) { const Sequelize = this.app.get('sequelizeClient'); return Sequelize.query( `SELECT tainteds."updateId" FROM tainteds WHERE tainteds.uuid = ${Sequelize.escape(id)} AND tainteds."updateId" = ${Sequelize.escape(level)}`, { type: Sequelize.QueryTypes.SELECT}) .then(results => { const tainted = results.length > 0; logger.silly(`Is (${id}, ${level}) tainted? => ${tainted} (results=${JSON.stringify(results)})`); return tainted; }); } /* * Return the update level to serve to the requesting instance for the given parameters. * * The logic for finding the right update level (called UL below) is the following: * * 1) if the provided/current UL is untainted, then we look for the next UL available. * This means one that is the lowest > currentUL. * * 2) if the provided/current UL is tainted, *then we are triggering a rollback*. * This means we look for the highest UL that is < currentUL. * * 3) if *no* UL is provided, we jump directly to the latest UL available. */ async get(id, params) { const channel = params.query.channel || 'general'; const instance = await this.app.service('status').get(id); let level = params.query.level; const Sequelize = this.app.get('sequelizeClient'); const Op = Sequelize.Op; let gtOrLt = Op.gt; let orderByClause = 1; // ascending by default to take the next one available, not latest if (!level) { level = 0; orderByClause = -1; // take latest level gtOrLt = Op.gt; } else if (await this.isCurrentLevelPerInstanceTainted(id, level)) { orderByClause = -1; gtOrLt = Op.lt; } const query = { query: { $limit: 1, $sort: { id: orderByClause, }, channel: channel, tainted: false, id: { [gtOrLt]: level, $notIn: Sequelize.literal(` (SELECT "tainteds"."updateId" FROM "tainteds" WHERE "tainteds"."uuid" = ${Sequelize.escape(id)} )`), }, }, }; const records = await this.find(query); /* * If after all that we still have nothing, or we just got the same * update level back again, then there's no update for the client */ if ((records.length === 0) || (records[0].id === level)) { throw new NotModified('No updates presently available'); } const record = records[0]; const computed = { meta: { channel: record.channel, level: record.id, }, core: record.manifest.core, plugins: { updates: [ ], deletes: [ ], }, }; this.prepareManifestFromRecord(record, computed); /* * Last but not least, make sure that any flavor specific updates are * assigned to the computed update manifest */ await this.prepareManifestWithFlavor(instance, record, computed); await this.filterVersionsForClient(instance, computed); return computed; } /* * Use the latest versions from the client to filter out updates which are * not necessary * * @param {Instance} Hydrated Instance model for the given client * @param {Map} The work-in-progress update manifest to compute for the * client * @return {Boolean} True if we filtered everything properly */ async filterVersionsForClient(instance, computedManifest) { const clientVersions = await this.app.service('versions').find({ query: { uuid: instance.uuid, $sort: { id: -1, }, $limit: 1, }, }); /* * If we have a version (not guaranteed on a fresh installation) * then we need to merge the changes to make sure we're only sending the * client the updates they need */ if (clientVersions.length === 0) { logger.info('No client versions discovered for instance', instance.uuid); return false; } const latestClientVersion = clientVersions[0]; if (latestClientVersion.manifest.jenkins.core == computedManifest.core.checksum.signature) { computedManifest.core = {}; } const pluginsInVersion = Object.keys(latestClientVersion.manifest.jenkins.plugins); /* * Bail out early if there's no pre-existing plugins */ if (pluginsInVersion.length === 0) { return true; } const signatures = Object.values(latestClientVersion.manifest.jenkins.plugins); /* * Collect the base level of plugins in this update level */ const artifactIds = computedManifest.plugins.updates.map(p => p.artifactId); const updates = []; const deletes = []; computedManifest.plugins.updates.forEach((plugin) => { if (!signatures.includes(plugin.checksum.signature)) { updates.push(plugin); } }); /* * Look through all the plugins in the version reported by the client, and * mark anything which no longer exist in the current update level as * deleted */ pluginsInVersion.forEach((artifactId) => { if (!artifactIds.includes(artifactId)) { deletes.push(artifactId); } }); computedManifest.plugins.updates = updates; computedManifest.plugins.deletes = deletes; return true; } /* * Copy the appropriate members from an ingested update level record to the * computed update manifest which should be sent to the client */ prepareManifestFromRecord(record, computedManifest) { /* * When dealing with records which have empty manifests, we can just bail * out early. */ if ((!record.manifest) || (!record.manifest.plugins)) { return computedManifest; } record.manifest.plugins.forEach((plugin) => { computedManifest.plugins.updates.push({ url: plugin.url, artifactId: plugin.artifactId, checksum: plugin.checksum, }); }); return computedManifest; } /* * Prepares the manifest with the updates specific to the given instance's * flavor */ async prepareManifestWithFlavor(instance, record, computedManifest) { if (!instance) { return computedManifest; } if ((!instance.flavor) || (!record.manifest) || (!record.manifest.environments)) { return computedManifest; } const flavor = record.manifest.environments[instance.flavor]; if ((flavor) && (flavor.plugins)) { flavor.plugins.forEach((plugin) => { /* * In the case where a flavor has a newer version of the plugin, we * must replace that instead of adding */ let existingIndex = computedManifest.plugins.updates.findIndex((el) => el.artifactId == plugin.artifactId); let record = { url: plugin.url, artifactId: plugin.artifactId, checksum: plugin.checksum, }; if (existingIndex != -1) { computedManifest.plugins.updates[existingIndex] = record; } else { computedManifest.plugins.updates.push(record); } }); } return computedManifest; } }
JavaScript
class CreateAccountSteps extends Component { getClassName() { const SELF = this; const { stepNo } = SELF.props; let className = ''; if (!stepNo) { return className; } for (let i = 1; i <= stepNo; i += 1) { className = className.concat(`t-${i} `); } return className; } render() { const className = this.getClassName(); const { restoreAccount, backButtonDisable, nextButtonDisable } = this.props; const backButtonDisabled = backButtonDisable ? 'light' : null; const nextButtonDisabled = nextButtonDisable ? 'light' : null; return ( <React.Fragment> <section style={{ padding: '30px 0px ' }}> <Container> <Row id="account-process" className={`${className} ${ restoreAccount ? 'restore-account' : null }`} > <Col className="c-1"> <svg viewBox="0 0 929.93 683.19" width="929.93" height="683.19"> <path d="M726.32,683.19H56.63c-41.66,0-69-43.51-51-81.06l113.42-236a56.55,56.55,0,0,0,0-49L5.65,81.05c-18-37.54,9.32-81,51-81H726.32A76,76,0,0,1,794.8,43.07L922.44,308.69a76,76,0,0,1,0,65.81L794.8,640.12A76,76,0,0,1,726.32,683.19Z" /> <g className="ico"> <path fill="#fff" d="M472.1,462.5h-14.2c-0.7-0.2-1.4-0.3-2.1-0.4c-20-1.4-39.3-7.9-56.2-18.8c-41.6-26.6-62.8-76.2-53.4-124.6 c5.1-25.9,17.1-48,36.6-65.8c28-25.6,61.2-35.8,98.7-31.1c23.9,3,44.9,12.8,62.9,28.8c21.2,18.8,34.5,42.1,39.4,70.1 c0.8,4.5,1.2,9.1,1.9,13.7v14.2c-0.4,3.1-0.7,6.2-1.1,9.3c-3.4,24.1-13,45.4-29.1,63.6c-18.7,21.1-42,34.2-69.8,39.1 C481.2,461.4,476.7,461.9,472.1,462.5z M545.6,411c33.5-37.1,38.7-103.9-8.1-147.6c-42.8-40.1-109.9-37.9-150,4.9 c-1.6,1.7-3.2,3.5-4.7,5.4c-39,47.4-26.1,107.8,1.6,137.2c7.8-27.7,25.2-46.7,51.9-57.5c-28.1-20.1-27.5-56.7-8.4-77 c19.1-20.3,51.1-21.4,71.6-2.5c10.6,9.7,16.2,22,16.3,36.4c0.2,18-7.5,32.2-22.1,43C520.4,364.2,537.6,383.3,545.6,411L545.6,411z M466.9,448.3c2.5-0.2,6.9-0.4,11.2-1c20.3-2.5,38.3-10.3,54.1-23.1c0.6-0.6,0.9-1.4,0.9-2.3c-5.4-38.5-41.4-64.9-79.5-58.4 c-29.6,5-52.3,28.4-56.7,58.3c-0.1,0.9,0.3,1.8,1,2.5C417.5,440.1,439.9,448,466.9,448.3z M465.1,347.9 c20.2-0.1,36.7-16.6,36.6-36.7c-0.1-20.3-16.7-36.8-36.9-36.7c-20.2,0.1-36.6,16.6-36.6,36.7C428.3,331.5,444.8,347.9,465.1,347.9z " /> </g> </svg> <h2>Create Account</h2> </Col> {!restoreAccount ? ( <Col className="text-center c-2"> <svg viewBox="0 0 929.93 683.19" width="929.93" height="683.19" > <path d="M726.32,683.19H56.63c-41.66,0-69-43.51-51-81.06l113.42-236a56.55,56.55,0,0,0,0-49L5.65,81.05c-18-37.54,9.32-81,51-81H726.32A76,76,0,0,1,794.8,43.07L922.44,308.69a76,76,0,0,1,0,65.81L794.8,640.12A76,76,0,0,1,726.32,683.19Z" /> <g className="ico"> <path fill="#fff" d="M449.6,294.2c0.4,0.9,0.9,1.8,1.5,2.7c0.5,0.7,1.3,1.5,1.7,2.2c0.8,0.8,1.6,1.6,2.5,2.2c0.9,0.7,1.9,1.2,3,1.5 c1,0.5,2.1,0.8,3.2,1c1.1,0.2,2.2,0.3,3.2,0.3c1.1,0,2.2,0,3.2-0.3c1-0.2,1.9-0.5,2.7-1h0.3c1-0.5,2.1-1.1,3-1.7 c0.8-0.6,1.6-1.3,2.2-2l0.3-0.2c0.7-0.7,1.2-1.4,1.7-2.2c0.6-0.7,1-1.6,1.3-2.5c0-0.3,0-0.3,0.2-0.5c0.4-1,0.8-2.1,1-3.2 c0.3-2.1,0.3-4.3,0-6.5c-0.3-1.1-0.6-2.2-1-3.2c-0.7-1.7-1.7-3.2-3-4.5l-0.5-0.5c-0.8-0.7-1.6-1.4-2.5-2c-1-0.5-1.7-1-2.7-1.5 c-1-0.4-2-0.8-3-1c-1.1-0.2-2.2-0.3-3.2-0.2c-2.1-0.1-4.3,0.3-6.2,1.2h-0.2c-0.9,0.4-1.8,0.9-2.7,1.5c-0.9,0.6-1.7,1.3-2.5,2 c-0.7,0.7-1.4,1.4-2,2.2c-0.5,0.9-1,1.8-1.5,2.7c-0.4,1-0.8,2-1,3c-0.2,1.1-0.3,2.2-0.3,3.2c0,1.1,0,2.2,0.3,3.2 C448.8,291.6,449.1,292.9,449.6,294.2z" /> <path fill="#fff" d="M484.2,385.5h-5.7v-61.1c0-3.6-2.8-6.5-6.4-6.5c0,0-0.1,0-0.1,0h-26.2c-3.6,0-6.5,2.8-6.5,6.4c0,0,0,0.1,0,0.1 v13.5c0,3.6,2.8,6.5,6.4,6.5c0,0,0.1,0,0.1,0h5.2v41.4h-5.2c-3.6,0-6.5,2.8-6.5,6.4c0,0,0,0.1,0,0.1v13.5c0,3.6,2.8,6.5,6.4,6.5 c0,0,0.1,0,0.1,0h38.4c3.6,0,6.5-2.8,6.5-6.4c0,0,0-0.1,0-0.1v-13.5C490.7,388.5,487.8,385.6,484.2,385.5z" /> <path fill="#fff" d="M465,205.2c-75.3,0-136.3,61.1-136.3,136.3S389.7,477.9,465,477.9s136.3-61.1,136.3-136.3 S540.3,205.2,465,205.2z M465,460c-65.3,0-118.4-53.1-118.4-118.4S399.7,223.2,465,223.2s118.4,53.1,118.4,118.4S530.3,460,465,460 L465,460z" /> </g> </svg> <h2>Account Information</h2> </Col> ) : null} <Col className={`text-right ${restoreAccount ? 'c-2' : 'c-3'}`}> <svg viewBox="0 0 929.93 683.19" width="929.93" height="683.19"> <path d="M726.32,683.19H56.63c-41.66,0-69-43.51-51-81.06l113.42-236a56.55,56.55,0,0,0,0-49L5.65,81.05c-18-37.54,9.32-81,51-81H726.32A76,76,0,0,1,794.8,43.07L922.44,308.69a76,76,0,0,1,0,65.81L794.8,640.12A76,76,0,0,1,726.32,683.19Z" /> <g className="ico"> <path fill="#fff" d="M464.5,224.9c-64.1,0-116.6,52.5-116.6,116.7s52.5,116.7,116.6,116.7S581,405.7,581,341.6 S528.6,224.9,464.5,224.9z M464.5,443.7c-56.1,0-102-45.9-102-102.1s45.9-102.1,102-102.1s102,46,102,102.1 S520.6,443.7,464.5,443.7L464.5,443.7z" /> <path fill="#fff" d="M510.4,307.3l-60.5,60.5l-30.6-30.6c-2.9-2.7-7.5-2.6-10.2,0.3c-2.6,2.8-2.6,7.2,0,9.9l35.7,35.7 c2.7,2.8,7.1,2.9,9.9,0.3c0.1-0.1,0.2-0.2,0.3-0.3l65.6-65.6c2.7-2.9,2.6-7.5-0.3-10.2C517.5,304.7,513.2,304.7,510.4,307.3z" /> </g> </svg> <h2>Confirm</h2> </Col> <div className="process-bar"> <div className="holder"> <span className="element e-1" /> <span className="element e-2" /> {!restoreAccount ? ( <React.Fragment> <span className="element e-3" /> <span className="element e-4" /> </React.Fragment> ) : null} </div> </div> </Row> </Container> </section> {this.props.children} <section style={{ padding: '40px 0' }}> <Container> <Row className="back-next-btn"> <Col className="text-right"> <Button // onClick={event => this.onBack(event, isBackActive)} onClick={this.props.onPrev} className={backButtonDisabled} > <i className="fas fa-chevron-left" /> Back </Button> </Col> <Col> <Button className={nextButtonDisabled} // onClick={event => this.onNext(event, isNextActive)}> onClick={this.props.onNext} > Next <i className="fas fa-chevron-right" /> </Button> </Col> </Row> </Container> </section> </React.Fragment> ); } }
JavaScript
class MellatCheckout { constructor(config, soap) { this.config = config; this.soap = soap; } /** * Get payment token from bank * @param {Number} amount [amount on rials] * @param {Number} userId [user's id on your database] * @param {Number} orderId [unique order_id on your database] * @returns {Promise} Promis object of bank result */ requestPayment(amount, userId, orderId) { try { return new Promise((resolve, reject) => { const wsdl = this.config.wsdlUrl; const args = { terminalId: this.config.terminalId, // your mellat account terminal id userName: this.config.userName, // your mellat account user name userPassword: this.config.password, // your mellat account password orderId: orderId, amount: amount, localDate: this.getLocalDate(), localTime: this.getLocalTime(), additionalData: "", callBackUrl: this.config.callBackUrl, payerId: userId, }; this.soap.createClientAsync(wsdl).then((client) => { if (!client) throw "couldnt stablish connection with bank"; client.bpPayRequest(args, (err, result) => { if (err) throw err; if (result.return) { // check if request was successful const gatewayStatus = result.return.split(",")[0]; if (gatewayStatus == 0) { resolve({ status: true, token: result.return.split(",")[1], order_id: args.orderId, }); } else { reject({ status: false, code: gatewayStatus }); } } }); }); }); } catch (error) { console.log(error); } } /** * helper function to convert persian digits in string to english digits * some OS returns numbers in persian so you can use this function to covnert them * @param {number} number * @returns {number} */ toEnglishDigits(number) { return number.replace(/[۰-۹]/g, (d) => "۰۱۲۳۴۵۶۷۸۹".indexOf(d)); } /** * helper function to return current date * example: 20200602 * @param {string} date * @returns {string} */ formatDate(date) { (month = "" + (date.getMonth() + 1)), (day = "" + date.getDate()), (year = date.getFullYear()); if (month.length < 2) month = "0" + month; if (day.length < 2) day = "0" + day; return [year, month, day].join(""); } /** * helper function to return current date * example: 20200602 * @returns {string} */ getLocalDate() { return this.formatDate(new Date()); } /** * helper function to return current time in hh::mm::ss * example: 162930 * @returns {string} */ getLocalTime() { return this.toEnglishDigits( new Date() .toLocaleTimeString("fa-IR", { hour12: false }) .replace(/:/g, "") ); } }
JavaScript
class SettingsPage extends Component { /** * The constructor updates the User Settings Redux slice with the current language from the router. * @param {Object} props - Component props */ constructor(props) { super(props); /* istanbul ignore next */ if (props.match.params.lang !== props.lang) props.updateUserData({ settings: { lang: props.match.params.lang } }); } /** * This method renders the component. * @return {Array<React.Component>} returns an array of React elements */ render() { return [ <Helmet key="helmet"><title>{ languages[this.props.lang].settings }</title></Helmet>, <h1 key="h1">{ languages[this.props.lang].settings }</h1>, <LanguageToggle key="toggle" />, ]; } /** * This corrects the URL if there is a mismatch with the Redux state after an update. * @param {Object} prevProps - Previous props */ componentDidUpdate(prevProps) { if (prevProps.match.params.lang !== this.props.lang) this.props.history.replace(`/${this.props.lang}/settings`); } }
JavaScript
class DictionaryEntry { /** * Construct a Dictionary object * * @param {!string} headword - The Chinese headword, simplified or traditional * @param {!DictionarySource} source - The dictionary containing the entry * @param {!Array<WordSense>} senses - An array of word senses */ constructor(headword, source, senses, headwordId) { // console.log(`DictionaryEntry ${ headword }`); this.headword = headword; this.source = source; this.senses = senses; this.headwordId = headwordId; } /** * A convenience method that flattens the English equivalents for the term * into a single string with a ';' delimiter * @return {string} English equivalents for the term */ addWordSense(ws) { this.senses.push(ws); } /** * Get the Chinese, including the traditional form in Chinese brackets () * after the simplified, if it differs. * @return {string} The Chinese text for teh headword */ getChinese() { const s = this.getSimplified(); const t = this.getTraditional(); let chinese = s; if (s !== t) { chinese = `${s}(${t})`; } return chinese; } /** * A convenience method that flattens the English equivalents for the term * into a single string with a ';' delimiter * @return {string} English equivalents for the term */ getEnglish() { const r1 = new RegExp(" / ", "g"); const r2 = new RegExp("/", "g"); let english = ""; for (const sense of this.senses) { let eng = sense.getEnglish(); // console.log(`getEnglish before ${ eng }`); if (eng !== undefined) { eng = eng.replace(r1, ", "); eng = eng.replace(r2, ", "); english += eng + "; "; } } const re = new RegExp("; $"); // remove trailing semicolon return english.replace(re, ""); } /** * A convenience method that flattens the part of speech for the term. If * there is only one sense then use that for the part of speech. Otherwise, * return an empty string. * @return {string} part of speech for the term */ getGrammar() { if (this.senses.length === 1) { return this.senses[0].getGrammar(); } return ""; } /** * Gets the headword_id for the term * @return {string} headword_id - The headword id */ getHeadwordId() { return this.headwordId; } /** * A convenience method that flattens the pinyin for the term. Gives * a comma delimited list of unique values * @return {string} Mandarin pronunciation */ getPinyin() { const values = new Set(); for (const sense of this.senses) { const pinyin = sense.getPinyin(); if (pinyin !== undefined) { values.add(pinyin); } } let p = ""; for (const val of values.values()) { p += val + ", "; } const re = new RegExp(", $"); // remove trailing comma return p.replace(re, ""); } /** * Gets the word senses * @return {Array<WordSense>} an array of WordSense objects */ getSenses() { return this.senses; } /** * A convenience method that flattens the simplified Chinese for the term. * Gives a Chinese comma (、) delimited list of unique values * @return {string} Simplified Chinese */ getSimplified() { const values = new Set(); for (const sense of this.senses) { const simplified = sense.getSimplified(); values.add(simplified); } let p = ""; for (const val of values.values()) { p += val + "、"; } const re = new RegExp("、$"); // remove trailing comma return p.replace(re, ""); } /** * Gets the dictionary source * @return {DictionarySource} the source of the dictionary */ getSource() { return this.source; } /** * A convenience method that flattens the traditional Chinese for the term. * Gives a Chinese comma (、) delimited list of unique values * @return {string} Traditional Chinese */ getTraditional() { const values = new Set(); for (const sense of this.senses) { const trad = sense.getTraditional(); if (trad !== undefined) { values.add(trad); } } let p = ""; for (const val of values.values()) { p += val + "、"; } const re = new RegExp("、$"); // remove trailing comma return p.replace(re, ""); } }
JavaScript
class PaymentForm extends Component { static navigationOptions = { headerStyle: { backgroundColor: "#177EF0", height: 0, top: 0, left: 0, right: 0, borderBottomColor: "transparent" }, headerTintColor: "transparent" }; _onChange = formData => AsyncStorage.setItem("@creditCard", JSON.stringify(formData)); _onFocus = field => console.log("focusing", field); _setUseLiteCreditCardInput = useLiteCreditCardInput => this.setState({ useLiteCreditCardInput }); render() { const { navigate } = this.props.navigation; return ( <View style={{ flex: 1 }}> <Navbar toggle={true} title="Adicionar forma de pagamento" navigation={this.props.navigation} goTo="Products" /> <KeyboardAwareScrollView style={{marginBottom: 80,}}> <View style={styles.container}> <View style={styles.title}> <Text style={styles.titleText}>NOVO CARTÃO</Text> </View> <CreditCardInput requiresName requiresCPF autoFocus inputStyle={styles.input} validColor={"black"} invalidColor={"red"} placeholderColor={"darkgray"} onFocus={this._onFocus} onChange={this._onChange} labels={{ number: "NÚMERO DO CARTÃO", expiry: "DATA EXP", cvc: "CVV", name: "NOME NO CARTÃO" }} /> </View> </KeyboardAwareScrollView> <View style={styles.buttonWrapper}> <TouchableOpacity style={styles.button} onPress={() => navigate("CpfForm")} > <Text style={styles.buttonText}>Adicionar Cartão</Text> </TouchableOpacity> </View> </View> ); } }
JavaScript
class XMLWriter extends BaseWriter_1.BaseWriter { constructor() { super(...arguments); this._indentation = {}; this._lengthToLastNewline = 0; } /** * Produces an XML serialization of the given node. * * @param node - node to serialize * @param writerOptions - serialization options */ serialize(node, writerOptions) { // provide default options this._options = util_1.applyDefaults(writerOptions, { wellFormed: false, noDoubleEncoding: false, headless: false, prettyPrint: false, indent: " ", newline: "\n", offset: 0, width: 0, allowEmptyTags: false, indentTextOnlyNodes: false, spaceBeforeSlash: false }); this._refs = { suppressPretty: false, emptyNode: false, markup: "" }; // Serialize XML declaration since base serializer does not serialize it if (node.nodeType === interfaces_1.NodeType.Document && !this._options.headless) { this._beginLine(); this._refs.markup = "<?xml"; this._refs.markup += " version=\"" + this._builderOptions.version + "\""; if (this._builderOptions.encoding !== undefined) { this._refs.markup += " encoding=\"" + this._builderOptions.encoding + "\""; } if (this._builderOptions.standalone !== undefined) { this._refs.markup += " standalone=\"" + (this._builderOptions.standalone ? "yes" : "no") + "\""; } this._refs.markup += "?>"; this._endLine(); } this.serializeNode(node, this._options.wellFormed, this._options.noDoubleEncoding); // remove trailing newline if (this._options.prettyPrint && this._refs.markup.slice(-this._options.newline.length) === this._options.newline) { this._refs.markup = this._refs.markup.slice(0, -this._options.newline.length); } return this._refs.markup; } /** @inheritdoc */ docType(name, publicId, systemId) { this._beginLine(); if (publicId && systemId) { this._refs.markup += "<!DOCTYPE " + name + " PUBLIC \"" + publicId + "\" \"" + systemId + "\">"; } else if (publicId) { this._refs.markup += "<!DOCTYPE " + name + " PUBLIC \"" + publicId + "\">"; } else if (systemId) { this._refs.markup += "<!DOCTYPE " + name + " SYSTEM \"" + systemId + "\">"; } else { this._refs.markup += "<!DOCTYPE " + name + ">"; } this._endLine(); } /** @inheritdoc */ openTagBegin(name) { this._beginLine(); this._refs.markup += "<" + name; } /** @inheritdoc */ openTagEnd(name, selfClosing, voidElement) { // do not indent text only elements or elements with empty text nodes this._refs.suppressPretty = false; this._refs.emptyNode = false; if (this._options.prettyPrint && !selfClosing && !voidElement) { let textOnlyNode = true; let emptyNode = true; let childNode = this.currentNode.firstChild; let cdataCount = 0; let textCount = 0; while (childNode) { if (util_2.Guard.isExclusiveTextNode(childNode)) { textCount++; } else if (util_2.Guard.isCDATASectionNode(childNode)) { cdataCount++; } else { textOnlyNode = false; emptyNode = false; break; } if (childNode.data !== '') { emptyNode = false; } childNode = childNode.nextSibling; } this._refs.suppressPretty = !this._options.indentTextOnlyNodes && textOnlyNode && ((cdataCount <= 1 && textCount === 0) || cdataCount === 0); this._refs.emptyNode = emptyNode; } if ((voidElement || selfClosing || this._refs.emptyNode) && this._options.allowEmptyTags) { this._refs.markup += "></" + name + ">"; } else { this._refs.markup += voidElement ? " />" : (selfClosing || this._refs.emptyNode) ? (this._options.spaceBeforeSlash ? " />" : "/>") : ">"; } this._endLine(); } /** @inheritdoc */ closeTag(name) { if (!this._refs.emptyNode) { this._beginLine(); this._refs.markup += "</" + name + ">"; } this._refs.suppressPretty = false; this._refs.emptyNode = false; this._endLine(); } /** @inheritdoc */ attribute(name, value) { const str = name + "=\"" + value + "\""; if (this._options.prettyPrint && this._options.width > 0 && this._refs.markup.length - this._lengthToLastNewline + 1 + str.length > this._options.width) { this._endLine(); this._beginLine(); this._refs.markup += this._indent(1) + str; } else { this._refs.markup += " " + str; } } /** @inheritdoc */ text(data) { if (data !== '') { this._beginLine(); this._refs.markup += data; this._endLine(); } } /** @inheritdoc */ cdata(data) { if (data !== '') { this._beginLine(); this._refs.markup += "<![CDATA[" + data + "]]>"; this._endLine(); } } /** @inheritdoc */ comment(data) { this._beginLine(); this._refs.markup += "<!--" + data + "-->"; this._endLine(); } /** @inheritdoc */ instruction(target, data) { this._beginLine(); this._refs.markup += "<?" + (data === "" ? target : target + " " + data) + "?>"; this._endLine(); } /** * Produces characters to be prepended to a line of string in pretty-print * mode. */ _beginLine() { if (this._options.prettyPrint && !this._refs.suppressPretty) { this._refs.markup += this._indent(this._options.offset + this.level); } } /** * Produces characters to be appended to a line of string in pretty-print * mode. */ _endLine() { if (this._options.prettyPrint && !this._refs.suppressPretty) { this._refs.markup += this._options.newline; this._lengthToLastNewline = this._refs.markup.length; } } /** * Produces an indentation string. * * @param level - depth of the tree */ _indent(level) { if (level <= 0) { return ""; } else if (this._indentation[level] !== undefined) { return this._indentation[level]; } else { const str = this._options.indent.repeat(level); this._indentation[level] = str; return str; } } }
JavaScript
class InstanceGroupManager extends common.ServiceObject { constructor(zone, name) { const methods = { /** * Check if the instance group manager exists. * * @method InstanceGroupManager#exists * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {boolean} callback.exists - Whether the instance group manager exists or * not. * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * instanceGroupManager.exists(function(err, exists) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.exists().then(function(data) { * const exists = data[0]; * }); */ exists: true, /** * Get an instance group manager if it exists. * * You may optionally use this to "get or create" an object by providing an * object with `autoCreate` set to `true`. Any extra configuration that is * normally required for the `create` method must be contained within this * object as well. * * @method InstanceGroupManager#get * @param {options=} options - Configuration object. * @param {boolean} options.autoCreate - Automatically create the object if * it does not exist. Default: `false` * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * instanceGroupManager.get(function(err, instanceGroupManager, apiResponse) { * // `instanceGroupManager` is an InstanceGroupManager object. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.get().then(function(data) { * const instanceGroupManager = data[0]; * const apiResponse = data[1]; * }); */ get: true, /** * Get the instance group manager's metadata. * * @see [InstanceGroupManagers: get API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instanceGroupManagers/get} * @see [InstanceGroupManagers Resource]{@link https://cloud.google.com/compute/docs/reference/v1/instanceGroupManagers} * * @method InstanceGroupManager#getMetadata * @param {function=} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {object} callback.metadata - The instance group manager's metadata. * @param {object} callback.apiResponse - The full API response. * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * instanceGroupManager.getMetadata(function(err, metadata, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.getMetadata().then(function(data) { * const metadata = data[0]; * const apiResponse = data[1]; * }); */ getMetadata: true, }; super({ parent: zone, baseUrl: '/instanceGroupManagers', /** * @name InstanceGroupManager#id * @type {string} */ id: name, // createMethod: zone.createInstanceGroupManager.bind(zone), methods: methods, }); /** * The parent {@link Zone} instance of this {@link InstanceGroup} instance. * @name InstanceGroup#zone * @type {Zone} */ this.zone = zone; /** * @name InstanceGroup#name * @type {string} */ this.name = name; } /** * Flags the specified instances in the managed instance group for immediate deletion. * @see [InstanceGroupManagers: deleteInstances API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instanceGroupManagers/deleteInstances} * @param {VM|VM[]} vms - VM instances to delete from * this instance group manager. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request. * @param {Operation} callback.operation - An operation object * that can be used to check the status of the request. * @param {object} callback.apiResponse - The full API response. * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * const vms = [ * gce.zone('us-central1-a').vm('http-server'), * gce.zone('us-central1-a').vm('https-server') * ]; * * instanceGroupManager.deleteInstances(vms, function(err, operation, apiResponse) { * // `operation` is an Operation object that can be used to check the status * // of the request. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.deleteInstances(vms).then(function(data) { * const operation = data[0]; * const apiResponse = data[1]; * }); */ deleteInstances(vms, callback) { const self = this; this.request( { method: 'POST', uri: '/deleteInstances', json: { instances: arrify(vms).map(function(vm) { return vm.url; }), }, }, function(err, resp) { if (err) { callback(err, null, resp); return; } const operation = self.zone.operation(resp.name); operation.metadata = resp; callback(null, operation, resp); } ); } /** * Get a list of managed VM instances in this instance group manager. * * @see [InstanceGroupManagers: listManagedInstances API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instanceGroupManagers/listManagedInstances} * * @param {object=} options - Instance search options. * @param {boolean} options.autoPaginate - Have pagination handled * automatically. Default: true. * @param {string} options.filter - Search filter in the format of * `{name} {comparison} {filterString}`. * - **`name`**: the name of the field to compare * - **`comparison`**: the comparison operator, `eq` (equal) or `ne` * (not equal) * - **`filterString`**: the string to filter to. For string fields, this * can be a regular expression. * @param {number} options.maxApiCalls - Maximum number of API calls to make. * @param {number} options.maxResults - Maximum number of VMs to return. * @param {string} options.pageToken - A previously-returned page token * representing part of the larger set of results to view. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request. * @param {VM[]} callback.vms - VM objects from this instance * group. * @param {object} callback.apiResponse - The full API response. * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * instanceGroupManager.getManagedInstances(function(err, vms) { * // `vms` is an array of `VM` objects. * }); * * //- * // To control how many API requests are made and page through the results * // manually, set `autoPaginate` to `false`. * //- * function callback(err, vms, nextQuery, apiResponse) { * if (nextQuery) { * // More results exist. * instanceGroupManager.getManagedInstances(nextQuery, callback); * } * } * * instanceGroupManager.getManagedInstances({ * autoPaginate: false * }, callback); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.getManagedInstances().then(function(data) { * const vms = data[0]; * }); */ getManagedInstances(options, callback) { const self = this; if (is.fn(options)) { callback = options; options = {}; } options = options || {}; this.request( { method: 'POST', uri: '/listManagedInstances', qs: options, }, function(err, resp) { if (err) { callback(err, null, null, resp); return; } let nextQuery = null; if (resp.nextPageToken) { nextQuery = Object.assign({}, options, { pageToken: resp.nextPageToken, }); } const vms = arrify(resp.managedInstances).map(function(vm) { const vmInstance = self.zone.vm(vm.instance); vmInstance.metadata = vm; return vmInstance; }); callback(null, vms, nextQuery, resp); } ); } /** * Resizes the managed instance group. * * @see [InstanceGroupManagers: resize API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instanceGroupManagers/resize} * * @param {number} size - The number of running instances that the managed instance group should maintain at any given time. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request. * @param {Operation} callback.operation - An operation object * that can be used to check the status of the request. * @param {object} callback.apiResponse - The full API response. * * @example * const Compute = require('@google-cloud/compute'); * const compute = new Compute(); * const zone = compute.zone('us-central1-a'); * const instanceGroupManager = zone.instanceGroupManager('web-servers'); * * instanceGroupManager.resize(2, function(err, operation, apiResponse) { * // `operation` is an Operation object that can be used to check the status * // of the request. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * instanceGroupManager.resize(2).then(function(data) { * const operation = data[0]; * const apiResponse = data[1]; * }); */ resize(size, callback) { const self = this; this.request( { method: 'POST', uri: '/resize', qs: {size: size}, }, function(err, resp) { if (err) { callback(err, null, resp); return; } const operation = self.zone.operation(resp.name); operation.metadata = resp; callback(null, operation, resp); } ); } }
JavaScript
class MockerTest extends MockerCore { /** * Create mock app * @param {Object} options - Options for the app creation * @param {string} options.host - host app will be on. default = localhost * @param {string} options.port - port the app will listen to. default = 3001 * @param {object} options.services - services configuration, each `key` will be one service. To check options see MockerService class * @param {string} options.servicesPath - path to a folder containing a json file for each service, with configuration options. * @param {boolean} options.debug - debug mode. */ constructor(args) { super(args) this.faker = faker this.registerServices() this.seedServices() } }
JavaScript
class Location { /** * Gets the href part of the location. This is the full URL. * @type {string} */ static get href() { // Return the location's href value return window.location.href; } /** * Set the location's href. This will move to a different page. * @param {string} value The full URL href value. * @type {string} */ static set href(value) { // Set the location's href value window.location.href = value; } /** * Gets the protocol part of the location. This is the starting part including the : character (https:). * @type {string} */ static get protocol() { // Return the location's protocol value return window.location.protocol; } /** * Gets the host part of the location. This is the the domain name with port number if set (mysite.com, mysite.com:8081). * @type {string} */ static get host() { // Return the location's host value return window.location.host; } /** * Gets the hostname part of the location. This is the the domain name (mysite.com). * @type {string} */ static get hostname() { // Return the location's hostname value return window.location.hostname; } /** * Gets the port part of the location. This port value if given, 8081 in http://mysite.com:8081. * @type {string} */ static get port() { // Return the location's port value return window.location.port; } /** * Gets the pathname part of the URL. The pathname could be, * http://mysite.com/folder/page.html?search=123#middlePage == /folder/page.html * http://mysite.com/folder/spa/#!/route1?search=123#middlePage == /folder/spa/#!/route1 * http://mysite.com/folder/spa/#!/route1#middlePage == /folder/spa/#!/route1 * @type {string} */ static get pathname() { // If the location hash does not start with the route characters if (location.hash.startsWith('#!') === false) { // This is not a Route page therefore just return the location's pathname return window.location.pathname; } // Set the hash path let hashPath = location.hash; // Get the index of the start of the ? character const searchIndex = hashPath.indexOf('?'); // If there is a search part then remove it if (searchIndex !== -1) hashPath = hashPath.substring(0, searchIndex); // Look for non-route hash character const hashIndex = hashPath.indexOf('#', 2); // If there is a hash part then remove it if (hashIndex !== -1) hashPath = hashPath.substring(0, hashIndex); // Return the route pathname return window.location.pathname + hashPath; } /** * Gets the search part of the URL. The search could be, * http://mysite.com/folder/page.html?search=123#middlePage == search=123 * http://mysite.com/folder/spa/#!/route1?search=123#middlePage == search=123 * http://mysite.com/folder/spa/#!/route1#middlePage == '' * @type {string} */ static get search() { // If the location hash does not start with the route characters if (location.hash.startsWith('#!') === false) { // This is not a Route page therefore just return the location's search return window.location.search; } // Get the index of the start of the ? character const searchIndex = location.hash.indexOf('?'); // If no search character then return an empty string if (searchIndex === -1) return ''; // Set search let search = location.hash.substring(searchIndex); // Look for hash character const hashIndex = search.indexOf('#'); // If there is a hash part then remove it if (hashIndex !== -1) search = search.substring(0, hashIndex); // Return the search part return search; } /** * Gets the search parameters for the URL. * @return {Object} An object with the search properties and values. */ static searchParams() { // Get the search part or the URL let search = Location.search; // If nothing then return empty object if (search.length === 0) return {}; // The format of the search is ?param1=encodedValue1&param2=encodedValue2 // Set result object let result = {}; // Remove the first ? character search = search.substring(1); // Split the search into param=value items const paramValueList = search.split('&'); // For each param value item paramValueList.forEach((paramValue) => { // Split into a param and value parts const parts = paramValue.split('='); // Must have 2 parts if (parts.length !== 2) return; // Add param and value to result result[parts[0]] = decodeURIComponent(parts[1]); }); // Return the result object return result; } /** * Gets the hash part of the URL. The hash could be, * http://mysite.com/folder/page.html?search=123#middlePage == middlePage * http://mysite.com/folder/spa/#!/route1?search=123#middlePage == middlePage * http://mysite.com/folder/spa/#!/route1#middlePage == middlePage * @type {string} */ static get hash() { // If the location hash does not start with the route characters if (location.hash.startsWith('#!') === false) { // This is not a Route page therefore just return the location's hash return window.location.hash; } // Get the index of the non-route hash character const hashIndex = location.hash.indexOf('#', 2); // If no hash character then return empty string if (hashIndex === -1) return ''; // Return the hash part return location.hash.substring(hashIndex); } }
JavaScript
class LoaderVendor extends React.Component { /** * @param {LoaderProps} props */ constructor(props) { super(props); this.size = this.props.size || 200; } render() { const theme = this.props.themeType || this.props.theme || 'light'; return <div className={'vendor-logo-back logo-background-' + theme} style={{ display: 'flex', flexDirection: 'column', height: '100%', width: '10%', margin: 'auto' }}> <div style={{flexGrow: 1}}/> <CircularProgress color="secondary" size={200} thickness={5}/> <div style={{flexGrow: 1}}/> </div>; } }
JavaScript
class OneWayExerciseSolver extends ExerciseSolver { constructor (config) { super(config) this.Step = OneWayStep this.StepCollection = OneWayStepCollection } }
JavaScript
class ModelerExtension extends PureComponent { constructor(props) { super(props); this.props.subscribe("app.activeTabChanged", (event) => { const { activeTab } = event; if (activeTab.type === "bpmn") { pluginTabState.setActiveTab(activeTab.id); } else { pluginTabState.disablePlugin(); } }); } render() { // not needed for this kind of extension return null; } }
JavaScript
class Ingredient { constructor(options) { const defaults = {}; const actual = Object.assign({}, defaults, options); if (actual.id) this.id = actual.id; this.key = actual.key; this.name = actual.name; // 'sizes' should be an object of key -> quantity or string if (actual.sizes) { this.sizes = {}; Object.keys(actual.sizes).forEach((size) => { const quantity = actual.sizes[size]; this.sizes[size] = quantity instanceof Quantity ? quantity : new Quantity(quantity); }); } if (actual.quantity) { // Check for size match in quantity string this.quantity = new Quantity(actual.quantity); } if (actual.conversion) this.conversion = new Conversion(actual.conversion); if (actual.nutrition) this.nutrition = new Nutrition(actual.nutrition); if (actual.sizes) this.sizes = actual.sizes; if (actual.tags) this.tags = actual.tags; } hasTag(tag) { return this.tags.includes(tag); } toString() { return `${this.quantity ? this.quantity + ' ' : ''}${this.name}`; } }
JavaScript
class InternalServerError extends Error { constructor(message) { super(message); this.status = 500; } }
JavaScript
class App extends React.Component { render() { return ( <div> <Switch> <Route path="/login" component={LoginPage} /> <AuthRoute path="/dashboard" component={DashboardPage} /> <AuthRoute path="/editor" component={EditorPage} /> <AuthRoute path="/" component={DashboardPage} /> </Switch> </div> ); } }
JavaScript
class PizzaList extends Component { //on click of next button, directs user to customer info form next = () => { if (this.props.currentOrder.pizzas.length === 0) { swal('please select a pizza') return; } this.props.history.push("/customer-info"); //takes customer to next "page" }; // toggleSelected adds and removes pizzas from the current order toggleSelected = (pizza, selected) => { // if this pizza is currently selected we want to remove it from the order // if it's not selected, then we want to add it to the order if (selected === true) { // remove the pizza from the current order this.props.dispatch({ type: "REMOVE_PIZZA", payload: pizza }); } else { // otherwise, add the pizza to the order pizza.quantity = 1; // pizza quantity is required by the server this.props.dispatch({ type: "ADD_PIZZA", payload: pizza }); } }; // React render function render() { // destructuring props const { pizzas } = this.props; const selectedPizzas = this.props.currentOrder.pizzas; return ( <div> <h2>Step 1: Select Your Pizza</h2> <span className="total"> Total: $ {selectedPizzas && selectedPizzas .reduce((sum, cur) => { return sum + Number(cur.price); }, 0) .toFixed(2)} </span> {/* TODO: NEED TOTAL DISPLAYED ON THIS 'page' */} <Button id="next" variant="contained" color="primary" onClick={this.next} > NEXT </Button>{" "} <br /> {pizzas.map((pizza, index) => { return ( <PizzaListItem key={`pizza-list-${index}`} pizza={pizza} toggleSelected={this.toggleSelected} // selectedPizzas.some determines if pizza is included in the selectedPizzas array selected={selectedPizzas.some((cur) => cur.id === pizza.id)} /> ); })} </div> ); // end return } // end render } // end PizzaList
JavaScript
class User { #db; #privateFields = ['password']; /** * @param {database} db */ constructor(db) { this.#db = db; } toJSON = (user) => omit(user, this.#privateFields); }
JavaScript
class BaseMailThreadAllOf { /** * Constructs a new <code>BaseMailThreadAllOf</code>. * @alias module:model/BaseMailThreadAllOf */ constructor() { BaseMailThreadAllOf.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>BaseMailThreadAllOf</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/BaseMailThreadAllOf} obj Optional instance to populate. * @return {module:model/BaseMailThreadAllOf} The populated <code>BaseMailThreadAllOf</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new BaseMailThreadAllOf(); if (data.hasOwnProperty('parties')) { obj['parties'] = BaseMailThreadAllOfParties.constructFromObject(data['parties']); delete data['parties']; } if (data.hasOwnProperty('drafts_parties')) { obj['drafts_parties'] = ApiClient.convertToType(data['drafts_parties'], [Object]); delete data['drafts_parties']; } if (data.hasOwnProperty('folders')) { obj['folders'] = ApiClient.convertToType(data['folders'], ['String']); delete data['folders']; } if (data.hasOwnProperty('version')) { obj['version'] = ApiClient.convertToType(data['version'], 'Number'); delete data['version']; } if (data.hasOwnProperty('snippet_draft')) { obj['snippet_draft'] = ApiClient.convertToType(data['snippet_draft'], 'String'); delete data['snippet_draft']; } if (data.hasOwnProperty('snippet_sent')) { obj['snippet_sent'] = ApiClient.convertToType(data['snippet_sent'], 'String'); delete data['snippet_sent']; } if (data.hasOwnProperty('message_count')) { obj['message_count'] = ApiClient.convertToType(data['message_count'], 'Number'); delete data['message_count']; } if (data.hasOwnProperty('has_draft_flag')) { obj['has_draft_flag'] = ApiClient.convertToType(data['has_draft_flag'], NumberBooleanDefault0); delete data['has_draft_flag']; } if (data.hasOwnProperty('has_sent_flag')) { obj['has_sent_flag'] = ApiClient.convertToType(data['has_sent_flag'], NumberBooleanDefault0); delete data['has_sent_flag']; } if (data.hasOwnProperty('archived_flag')) { obj['archived_flag'] = ApiClient.convertToType(data['archived_flag'], NumberBooleanDefault0); delete data['archived_flag']; } if (data.hasOwnProperty('shared_flag')) { obj['shared_flag'] = ApiClient.convertToType(data['shared_flag'], NumberBooleanDefault0); delete data['shared_flag']; } if (data.hasOwnProperty('external_deleted_flag')) { obj['external_deleted_flag'] = ApiClient.convertToType(data['external_deleted_flag'], NumberBooleanDefault0); delete data['external_deleted_flag']; } if (data.hasOwnProperty('first_message_to_me_flag')) { obj['first_message_to_me_flag'] = ApiClient.convertToType(data['first_message_to_me_flag'], NumberBooleanDefault0); delete data['first_message_to_me_flag']; } if (data.hasOwnProperty('last_message_timestamp')) { obj['last_message_timestamp'] = ApiClient.convertToType(data['last_message_timestamp'], 'Date'); delete data['last_message_timestamp']; } if (data.hasOwnProperty('first_message_timestamp')) { obj['first_message_timestamp'] = ApiClient.convertToType(data['first_message_timestamp'], 'Date'); delete data['first_message_timestamp']; } if (data.hasOwnProperty('last_message_sent_timestamp')) { obj['last_message_sent_timestamp'] = ApiClient.convertToType(data['last_message_sent_timestamp'], 'Date'); delete data['last_message_sent_timestamp']; } if (data.hasOwnProperty('last_message_received_timestamp')) { obj['last_message_received_timestamp'] = ApiClient.convertToType(data['last_message_received_timestamp'], 'Date'); delete data['last_message_received_timestamp']; } if (data.hasOwnProperty('add_time')) { obj['add_time'] = ApiClient.convertToType(data['add_time'], 'Date'); delete data['add_time']; } if (data.hasOwnProperty('update_time')) { obj['update_time'] = ApiClient.convertToType(data['update_time'], 'Date'); delete data['update_time']; } if (data.hasOwnProperty('deal_id')) { obj['deal_id'] = ApiClient.convertToType(data['deal_id'], 'Number'); delete data['deal_id']; } if (data.hasOwnProperty('deal_status')) { obj['deal_status'] = ApiClient.convertToType(data['deal_status'], 'String'); delete data['deal_status']; } if (data.hasOwnProperty('lead_id')) { obj['lead_id'] = ApiClient.convertToType(data['lead_id'], 'String'); delete data['lead_id']; } if (data.hasOwnProperty('all_messages_sent_flag')) { obj['all_messages_sent_flag'] = ApiClient.convertToType(data['all_messages_sent_flag'], NumberBooleanDefault0); delete data['all_messages_sent_flag']; } if (Object.keys(data).length > 0) { Object.assign(obj, data); } } return obj; } }
JavaScript
class Operator { /** * Creates an instance of Operator. * * @param {*} value - The value. * @param {*} type - The type of operator. * @param {number} precedence - Priority to sort the operators with. * @class */ constructor(value, type, precedence) { this.value = value; this.type = type; this.precedence = precedence; } /** * Returns the value as is for JSON. * * @returns {*} value. */ toJSON() { return this.value; } /** * Returns the value as its string format. * * @returns {string} String representation of value. */ toString() { return `${this.value}`; } /** * Returns a type for a given string. * * @param {string} type - The type to lookup. * @returns {*} Either number of parameters or Unary Minus Symbol. * @static */ static type(type) { switch (type) { case 'unary': return OPERATOR_TYPE_UNARY; case 'binary': return OPERATOR_TYPE_BINARY; case 'ternary': return OPERATOR_TYPE_TERNARY; case 'unary-minus': return OPERATOR_UNARY_MINUS; default: throw new Error(`Unknown Operator Type: ${type}`); } } }
JavaScript
class VideosMove extends Component { constructor(props) { super(props); // console.log("Videos.constructor", props); this.state = { isAuthorized: false, playlistName: null, playlistId: props.match.params.playlistid, videos: null, playlists: null, moveToPlaylistId: null, filter: '', videosLoading: false, }; } static getDerivedStateFromProps(props, state) { // console.log("Videos.getDerivedStateFromProps", props); if (props.isAuthorized !== state.isAuthorized) { return { isAuthorized: props.isAuthorized, }; } // No state update necessary return null; } componentDidMount() { // console.log('Videos.componentDidMount'); this.refresh(); } componentDidUpdate(prevProps, prevState) { // console.log(`Videos.componentDidUpdate, playlistId=${this.state.playlistId}, prev=${prevState.playlistId}`, this.state); if (!this.state.isAuthorized) return; // At this point, we're in the "commit" phase, so it's safe to load the new data. // if (this.state.isAuthorized && this.state.playlistId && ((this.state.videos === null) || (this.state.videos.length === 0))) { if (this.state.playlistName === null) { // !!! only retrieve data if state.playlistName is empty; otherwise this will generate an endless loop. console.log('Videos.componentDidUpdate: call retrievePlaylistName'); this.retrievePlaylistName(); } if ( !this.state.videosLoading && this.state.playlistId && this.state.videos === null ) { // !!! only retrieve data if state.videos is empty; otherwise this will generate an endless loop. console.log('Videos.componentDidUpdate: call retrieveVideos'); this.retrieveVideos(); } if (this.state.playlists === null) { // !!! only retrieve data if state.playlists is empty; otherwise this will generate an endless loop. console.log('Videos.componentDidUpdate: call retrievePlaylists'); this.retrievePlaylists(); } } storePlaylists = data => { // console.log("Videos.storePlayLists", data.items); if (!data) return; let list = data.items; list.sort(snippetTitleSort); this.setState({ playlists: list }); }; storeVideos = (data, currentToken) => { // console.log('Videos.storeVideos', currentToken); if (!data) return; // console.log("Videos.storeVideos", data); let list = data.items; list.sort(snippetTitleSort); if (currentToken === undefined || !currentToken) { this.setState({ videos: list }); } else { this.setState(prevState => ({ videos: [...prevState.videos, ...list] })); } if (data.nextPageToken) { this.retrieveVideos(data.nextPageToken); } }; updatePlaylistName = playlistName => { this.setState({ playlistName }); }; retrievePlaylistName = () => { if (!this.state.playlistId) { console.warn('state.playlistId is empty'); return; } let req = buildPlaylistNameRequest(this.state.playlistId); if (!req) { console.warn('req is null'); return; } req.then( function(response) { try { this.updatePlaylistName( response.result.items[0].snippet.title ); } catch (e) { if (e instanceof TypeError) { console.log('buildPlaylistNameRequest incomplete response', e); } else { console.error('buildPlaylistNameRequest unexpected error', e); } } }, function() { // onRejected handler console.warn('buildPlaylistNameRequest rejected'); }, this ); }; retrieveVideos = nextPageToken => { // console.log(`Videos.retrieveVideos, playlistId=${this.state.playlistId}, pageToken=${nextPageToken}`); // console.log(`Videos.retrieveVideos set videosLoading=true`); this.setState({ videosLoading: true }); executeRequest( buildPlaylistItemsRequest(this.state.playlistId, nextPageToken), data => this.storeVideos(data, nextPageToken) ); }; retrievePlaylists = () => { // console.log("Videos.retrievePlayLists"); executeRequest(buildPlaylistsRequest(), this.storePlaylists); }; removeFromPlaylistState = videoItemId => { // console.log("Videos.removeFromPlaylistState", videoItemId); let videos = this.state.videos; let i = videos.findIndex(function f(e) { return e.id === videoItemId; }); // console.log("Videos.removeSuccess: video to delete: ", i, videos[i]); videos.splice(i, 1); this.setState({ videos }); }; removeError = error => { console.log('Videos.removeError', error.code, error.message); }; /** * Remove a video from the current playlist * @param videoItemId ID of the video-item in the current playlist */ remove = videoItemId => { // console.log('Videos.remove', videoItemId); if (!videoItemId) return; let request = buildApiRequest('DELETE', '/youtube/v3/playlistItems', { id: videoItemId, }); executeRequest( request, () => this.removeFromPlaylistState(videoItemId), this.removeError ); }; createError = error => { console.log('Videos.insertError', error); }; insertError = error => { console.log('Videos.insertError', error); }; /** * Move the video to another playlist. The video will be removed from the current playlist. * @param videoItemId ID of the video-item in the current playlist * @param videoId ID of the video */ move = (videoItemId, videoId, moveToPlaylistId) => { // console.log('Videos.move', videoItemId, videoId, moveToPlaylistId); if (!moveToPlaylistId) return; let insertRequest = buildApiRequest( 'POST', '/youtube/v3/playlistItems', { part: 'snippet', //, // 'onBehalfOfContentOwner': '' }, { 'snippet.playlistId': moveToPlaylistId, 'snippet.resourceId.kind': 'youtube#video', 'snippet.resourceId.videoId': videoId, //, // 'snippet.position': '' } ); let deleteRequest = buildApiRequest( 'DELETE', '/youtube/v3/playlistItems', { id: videoItemId, } ); //executeRequest(request, () => { this.insertSuccess(videoItemId) }, this.insertError); // executeRequest(request, () => { this.remove(videoItemId) }, this.insertError); // https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientbatch // https://developers.google.com/api-client-library/javascript/features/promises // gapi.client.Request.then(onFulfilled, onRejected, context) // response: // An object containing information about the HTTP response. // Name Type Description // result * The JSON-parsed result. false if not JSON-parseable. // body string The raw response string. // headers object | undefined The map of HTTP response headers. // status number | undefined HTTP status. // statusText string | undefined HTTP status text. /* insertRequest .then(function(response) { // onFulfilled handler: console.log("insertRequest promise onFulfilled handler", response); return deleteRequest //}, // // onRejected handler: // function () { // console.log("insertRequest onRejected handler"); // }, // // context: // this } // , function(reason) { // console.log("insertRequest promise onRejected handler", reason); // } ) .catch(function(error) { console.log("insert failed", error); throw error; // let the error flow through the full chain. }) .then(function(response) { console.log("deleteRequest promise onFulfilled handler", response); }, function(reason) { console.log("deleteRequest promise onRejected handler", reason); }) .catch(function(error) { console.log("delete failed", error); }); */ let r = null; // console.log('calling insertRequest'); insertRequest .then(function() { // console.log('calling deleteRequest'); return deleteRequest.then(function() { // console.log('deleteRequest.then'); r = 'OK'; }); }) .catch(function(reason) { // console.log('move failed', JSON.stringify(reason)); r = reason.result ? reason.result.error.message : 'unknow reason'; }); return r; // { // "result":{ // "error":{ // "errors":[ // {"domain":"youtube.playlistItem","reason":"playlistIdRequired", // "message":"Playlist id not specified."}], // "code":400, // "message":"Playlist id not specified."}}, // "body":"{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"youtube.playlistItem\",\n \"reason\": \"playlistIdRequired\",\n \"message\": \"Playlist id not specified.\"\n }\n ],\n \"code\": 400,\n \"message\": \"Playlist id not specified.\"\n }\n}\n", // "headers":{"date":"Thu, 17 Jan 2019 13:26:34 GMT","content-encoding":"gzip","server":"GSE","content-type":"application/json; charset=UTF-8","vary":"Origin, X-Origin","cache-control":"private, max-age=0","content-length":"150","expires":"Thu, 17 Jan 2019 13:26:34 GMT"}, // "status":400, // "statusText":null} }; movep = (videoItemId, videoId, moveToPlaylistId) => { // console.log('movep', videoItemId, videoId, moveToPlaylistId); // insertInPlaylist(videoId, moveToPlaylistId) // .then(function(response) { // console.log("movep.insertInPlaylist resovled", response); // }) // .catch(function(error) { // console.log("movep.insertInPlaylist rejected"); // }); // let r = moveIntoPlaylist(videoItemId, videoId, moveToPlaylistId); // console.log("movep, r", r); /* moveIntoPlaylist(videoItemId, videoId, moveToPlaylistId) .then(function(response) { console.log('movep.moveIntoPlaylist resolved', response); }) .catch(function(reason) { console.log( 'movep.moveIntoPlaylist rejected', reason, reason.result.error.message ); }); */ }; moveSuccess = ({ operation, data, videoId, videoItemId }) => { console.log('moveSuccess', operation, videoId, videoItemId, data); switch (operation) { case 'insert': // console.log("insert video ", videoId, data.result.snippet.resourceId.videoId); break; case 'delete': // console.log("delete video ", videoItemId); this.removeFromPlaylistState(videoItemId); break; default: console.error(`moveSuccess: unknown operation ${operation}`); } // result: // etag: ""XpPGQXPnxQJhLgs6enD_n8JR4Qk/-SMkaVE1qGHUDguCww7-fwlg5AY"" // id: "UExfeDhNcFV5cHhlYksyX0NwSmItT3ROZVVfNTY4eWZCMi41MzJCQjBCNDIyRkJDN0VD" // kind: "youtube#playlistItem" // snippet: // channelId: "UCE0q36_agQAeb4G3PXivkew" // channelTitle: "François Georgy" // description: "Now playing in select cities: gracejonesmovie.com↵↵This electrifying journey through the public and private worlds of pop culture mega-icon Grace Jones contrasts musical sequences with intimate personal footage, all the while brimming with Jones’s bold aesthetic. A larger-than-life entertainer, an androgynous glam-pop diva, an unpredictable media presence – Grace Jones is all these things and more. Sophie Fiennes’s documentary goes beyond the traditional music biography, offering a portrait as stylish and unconventional as its subject. Taking us home with her to Jamaica, into the studio with long-time collaborators Sly & Robbie, and backstage at gigs around the world, the film reveals Jones as lover, daughter, mother, and businesswoman. But the stage is the fixed point to which the film returns, with eye-popping performances of "Slave to the Rhythm," “Pull Up to the Bumper,” "Love is the Drug," and more. Jones herself has said watching the film “will be like seeing me almost naked” and, indeed, Fiennes’s treatment is every bit as definition-defying as its subject, untamed by either age or life itself." // playlistId: "PL_x8MpUypxebK2_CpJb-OtNeU_568yfB2" // publishedAt: "2019-01-18T12:35:59.000Z" // resourceId: {kind: "youtube#video", videoId: "ya7yeAXU_Cw"} // thumbnails: {default: {…}, medium: {…}, high: {…}, standard: {…}, maxres: {…}} // title: "Grace Jones: Bloodlight and Bami – Official U.S. Trailer" // __proto__: Object // __proto__: Object // status: 200 // statusText: null }; moveFailure = r => { console.log('moveFailure', r); }; moveVisible = () => { console.log('Videos.moveVisible'); let videoItemIds = []; let videoIds = []; this.state.videos .filter( video => video.snippet.title .toLowerCase() .indexOf(this.state.filter.toLowerCase()) > -1 ) .map(video => { videoItemIds.push(video.id); if (!videoIds.includes(video.contentDetails.videoId)) videoIds.push(video.contentDetails.videoId); // avoid pushing duplicates }); console.log('moveVisible', videoIds, videoItemIds); console.log('moveMultipleIntoPlaylist before'); // moveMultipleIntoPlaylist(videoItemIds, videoIds, this.state.moveToPlaylistId).then(this.moveSuccess, this.moveFailure); moveMultipleIntoPlaylist( videoItemIds, videoIds, this.state.moveToPlaylistId, this.moveSuccess, this.moveFailure ); console.log('moveMultipleIntoPlaylist after'); }; setMoveToList = event => { // console.log("Videos.setMoveToList", event.target.value); this.setState({ moveToPlaylistId: event.target.value }); }; updateFilter = event => { // console.log("Videos.updateFilter", event.target.value); let f = event.target.value; this.setState({ filter: f }); }; refresh = (clearFilter = false) => { console.log('refresh'); if (!this.state.isAuthorized) return; this.setState({ playlistName: null, videos: null, playlists: null, videosLoading: false, filter: clearFilter ? '' : this.state.filter, }); this.retrievePlaylistName(); this.retrieveVideos(); this.retrievePlaylists(); }; render() { const { isAuthorized, playlistId, playlistName, videos, playlists, moveToPlaylistId, filter, } = this.state; // console.log("Videos.render", videos); if (!isAuthorized) { return <div />; } else { if (videos) { let visibleVideos = videos.filter(video => video.snippet.title.toLowerCase().indexOf(filter.toLowerCase()) > -1); visibleVideos.sort(snippetTitleSort); return ( <div className="videos-main"> <div className="column"> <button onClick={this.refresh}>refresh</button> <div className="playlist-selector"> target playlist: {playlists && ( <select onChange={this.setMoveToList}> <option value=""> select list to move to </option> {playlists.map((p, i) => { return p.id === playlistId ? null : ( <option key={i} value={p.id}> {p.snippet.title} </option> ); })} </select> )} </div> {moveToPlaylistId && ( <div> <button onClick={this.moveVisible}> move visible to target playlist </button> </div> )} <div className="filter"> filter:{' '} <input type="text" defaultValue={filter} onKeyUp={this.updateFilter} /> </div> <div> {// videos.filter((video) => video.snippet.title.toLowerCase().indexOf(filter.toLowerCase()) > -1).map((video, index) => { visibleVideos.map((video, index) => { return ( <div key={index}> <a href={`https://www.youtube.com/watch?v=${video.contentDetails.videoId}`} target="_blank" rel="noopener noreferrer">{video.snippet.title}</a> {' '} <button onClick={() => this.remove(video.id)}>remove</button> {moveToPlaylistId && ( <button onClick={() => this.movep(video.id, video.contentDetails.videoId, moveToPlaylistId)}>move</button> )} </div> ); })} </div> </div> <div className="column"> <h2>Videos in {playlistName} :</h2> <h3>{videos.length} videos</h3> </div> </div> ); } else { return <div>Retrieving the list of videos...</div>; } } } /* { "kind": "youtube#playlistItem", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/1tCBTp6eGaB5-FomghShvhm_Vkc\"", "id": "UExfeDhNcFV5cHhlYlBlX1hZeWpKTUo1WVdlOTcyaU9Uci4yODlGNEE0NkRGMEEzMEQy", "snippet": { "publishedAt": "2018-06-19T10:55:25.000Z", "channelId": "UCE0q36_agQAeb4G3PXivkew", "title": "Urfaust - The Constellatory Practice (Full Album)", "description": "Country: The Netherlands | Year: 2018 | Genre: Atmospheric Doom/Black Metal\n\nLP & CD available here:\nhttp://www.van-records.de\n\nDigital Album available here:\nhttps://urfaust.bandcamp.com/album/the-constellatory-practice-2\n\n- Urfaust -\nWebshop: http://www.urfaust.bigcartel.com\nFacebook: https://www.facebook.com/urfaustofficial\nBandcamp: http://urfaust.bandcamp.com\nMetal Archives: http://www.metal-archives.com/bands/Urfaust/19596\n\n- Ván Records -\nWebsite: http://www.van-records.de\nFacebook: https://www.facebook.com/vanrecs\nBandcamp: http://vanrecords.bandcamp.com\nYouTube: https://www.youtube.com/vanrecords\nSoundcloud: https://soundcloud.com/v-n-records\n\nTracklist: \n1. Doctrine Of Spirit Obsession 00:00\n2. Behind The Veil Of The Trance Sleep 13:18\n3. A Course In Cosmic Meditation 21:06\n4. False Sensorial Impressions 25:40\n5. Trail Of The Conscience Of The Dead 31:42\n6. Eradication Through Hypnotic Suggestion 44:27\n\nThis video is for promotional use only!", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/ayCHct5hXPc/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/ayCHct5hXPc/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/ayCHct5hXPc/hqdefault.jpg", "width": 480, "height": 360 }, "standard": { "url": "https://i.ytimg.com/vi/ayCHct5hXPc/sddefault.jpg", "width": 640, "height": 480 }, "maxres": { "url": "https://i.ytimg.com/vi/ayCHct5hXPc/maxresdefault.jpg", "width": 1280, "height": 720 } }, "channelTitle": "François Georgy", "playlistId": "PL_x8MpUypxebPe_XYyjJMJ5YWe972iOTr", "position": 1, "resourceId": { "kind": "youtube#video", "videoId": "ayCHct5hXPc" } }, "contentDetails": { "videoId": "ayCHct5hXPc", "videoPublishedAt": "2018-05-04T10:59:02.000Z" } } */ }
JavaScript
class DomEventHandle extends EventHandle { /** * The constructor for `DomEventHandle`. * @param {!EventEmitter} emitter Emitter the event was subscribed to. * @param {string} event The name of the event that was subscribed to. * @param {!Function} listener The listener subscribed to the event. * @param {boolean} capture Flag indicating if listener should be triggered * during capture phase, instead of during the bubbling phase. Defaults to false. * @constructor */ constructor(emitter, event, listener, capture) { super(emitter, event, listener); this.capture_ = capture; } /** * @inheritDoc */ removeListener() { this.emitter_.removeEventListener( this.event_, this.listener_, this.capture_ ); } }
JavaScript
class Fact extends React.Component { /** * * Set the initial state * * @private */ constructor (props) { super(props); this.state = { post: { leadTitle: '', title: '', leadText: '', text: '', image: null, content: '' }, isLoading: true }; } componentDidMount () { const _this = this; getPageData('posts', 50, _this.successCallback.bind(_this), _this.errorCallback.bind(_this)); } successCallback (post) { this.setState({ post: post, isLoading: false }); } errorCallback () { this.setState({ isLoading: false }); } // ------------------------------------------------------------------------------------------------------------------ // Render methods // ------------------------------------------------------------------------------------------------------------------ /** * Renders the title * * @method renderTitle * @returns {XML} * @public */ renderTitle = (post) => ( <div className="row"> <div className="col-md-8 col-md-offset-2 text-center mb50"> <h1 className="font-size-normal color-light"> <small className="color-light">{post.leadTitle}</small> {post.title} </h1> </div> </div> ) /** * Renders the text * * @method renderText * @returns {XML} * @public */ renderText = (content) => ( <div className="row"> <div className="col-sm-8 col-sm-push-2 text-center"> <div dangerouslySetInnerHTML={{__html: content}} /> <a target="_blank" href="https://github.com/easingthemes/notamagic" className="button button-md button-gray hover-ripple-out" > <span className="color-primary">View it on GitHub <i className="fa fa-github"></i></span> </a> </div> </div> ) /** * Renders the component * * @method render * @returns {XML} * @public */ render () { const _this = this; return ( <div id="fact" className="bg-grad-stellar pt100 pb100"> <div className="container"> {this.renderTitle(_this.state.post)} <div className="row"> <div className="col-md-3"> <div className="row"> <div className="col-md-12 col-sm-6 col-xs-6"> <FactItem name={data.facts[0].name} id={0} number={data.facts[0].number} /> </div> <div className="col-md-12 col-sm-6 col-xs-6"> <FactItem name={data.facts[1].name} id={1} number={data.facts[1].number} /> </div> </div> </div> <div className="col-md-3 col-md-push-6"> <div className="row"> <div className="col-md-12 col-sm-6 col-xs-6"> <FactItem name={data.facts[2].name} id={2} number={data.facts[2].number} /> </div> <div className="col-md-12 col-sm-6 col-xs-6"> <FactItem name={data.facts[3].name} id={3} number={data.facts[3].number} /> </div> </div> </div> <div className="col-md-6 col-md-pull-3"> <img src={_this.state.post.image} alt="macbook" className="img-responsive" /> </div> </div> {this.renderText(_this.state.post.content)} </div> </div> ); } }
JavaScript
class WidthHandle extends React.Component { static propTypes = { /** callback function when currently __dragging__ the handle */ onChange: PropTypes.func, /** callback function when finished __dragging__ the handle to save selected width */ onSave: PropTypes.func, } state = { enabled: false, x: null, } componentDidMount() { document.addEventListener('mousemove', this.handleGlobalMouseMove) document.addEventListener('mouseup', this.handleGlobalMouseUp) } componentWillUnmount() { document.removeEventListener('mousemove', this.handleGlobalMouseMove) document.removeEventListener('mouseup', this.handleGlobalMouseUp) } /** * Tracks the distance dragged left or right if currently dragging * the handle otherwise do nothing * * @param {MouseEvent} event - used to calculate the dx mouse movement */ handleGlobalMouseMove = (event) => { if (!this.state.enabled) { return } if (this.state.x) { this.props.onChange(event.clientX - this.state.x) } this.setState({ x: event.clientX, }) } /** * Stop tracking changes and trigger the callback * function to save the width of the column * does nothing when the handle is not enabled * * @param {MouseEvent} event */ handleGlobalMouseUp = (event) => { if (!this.state.enabled) { return } this.setDisabled() this.props.onSave() } /** * Set the handle to enabled ie. the column is being resized */ setEnabled = () => { this.setState({ enabled: true, }) } /** * Set the handle to disabled. ie. the column is no longer being resized */ setDisabled() { this.setState({ enabled: false, x: null, }) } /** * Change hover state to add hover styles for visual feedback */ handleMouseOver = () => { this.setState(state => { state.hover = true return state }) } /** * Revert to default styles when not hovering */ handleMouseOut = () => { this.setState(state => { state.hover = false return state }) } setWidth(width) { this.props.onChange(width) } render() { return ( <span className={ClassNames('handle', {'hover': this.state.hover})} onMouseDown={this.setEnabled} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> ) } }
JavaScript
class XmlUsageVisitorSum extends BaseConvertionVisitor { /** * Constructs an instance of XmlUsageVisitor without a converter because all processing will be done here in the * visitor. Notice {@link BaseConversionVisitor#visit|BaseConversionVisitor.visit()} is overridden. * * @constructor */ constructor() { super(); this.uris = {}; this.tagCounts = {}; } get uris() { return this[uris_NAME]; } set uris(newUris) { this[uris_NAME] = newUris; } get tagCounts() { return this[tagCounts_NAME]; } set tagCounts(newTagCounts) { this[tagCounts_NAME] = newTagCounts; } addSchema(uri) { if (this.uris[uri] === undefined) { this.uris[uri] = { tagCounts: {} } } } addTag(xmlTag) { if (this.tagCounts[xmlTag] === undefined) { this.tagCounts[xmlTag] = 1; } else { this.tagCounts[xmlTag] += 1; } } visit(node, jsonSchema, xsd) { var uri = xsd.uri; this.addSchema(uri); this.addTag(XsdFile.getAttrValue(node, XsdAttributes.NAME)); return true; } onBegin(jsonSchema, xsd) { if (this.uris[xsd.uri] === undefined) { return true; } else { return false; } } dump() { debug('----------------------------'); debug('Overall XML Schema Tag Usage'); debug('----------------------------'); debug(Object.keys(this.uris)); debug('----------------------------'); Object.keys(this.tagCounts).sort().forEach(function (xmlTag, index, array) { debug(xmlTag + ' = ' + this.tagCounts[xmlTag]); }, this) debug(); } }
JavaScript
class ChessBoard { /** * The constructor of the ChessBoard class. * * @param {{two: Two, n: Number, size: Number, color: {board: String, tileB: String, tileW: String, queen: String, cross: String}}} options */ constructor(options) { // overwrite default settings with the options const settings = { two: new Two(), n: 8, size: 200, color: { board: '#4F2649', tileB: '#FCFCFC', tileW: '#080816', queen: '#88D317', cross: '#D31717' } }; this.settings = {...settings, ...options}; /** * @type {Set<String>} */ this.literals = new Set(); /** * @type {Array<Array<T>>} */ this.state = [[]]; this.tiles = []; this.queens = []; this.crosses = []; // create board and groups this.size = this.settings.size; this.board = this.settings.two.makeRectangle(this.settings.size / 2, this.settings.size / 2, this.settings.size, this.settings.size); this.board.fill = this.settings.color.board; this.board.noStroke(); this.tileLayer = this.settings.two.makeGroup(); this.queenLayer = this.settings.two.makeGroup(); this.crossLayer = this.settings.two.makeGroup(); this.n = this.settings.n; } /** * @returns {Number} */ get n() { return this.state.length; } /** * @param {Number} n - number of tiles for x and y axis of the chessboard */ set n(n) { this.literals = new Set(); // calculate sizes let padding = this.size * 0.1 / n; let slotSize = (this.size - padding * 2) / n; let tileSize = slotSize - padding * 2 / n; // remove old tiles and queenLayer from the scene this.tileLayer.remove(this.tiles); this.queenLayer.remove(this.queens); this.crossLayer.remove(this.crosses) // initialize reference arrays this.state = Array(n).fill(0).map(_ => Array(n).fill(' ')); this.tiles = Array(n * n).fill(null); this.queens = Array(n * n).fill(null); this.crosses = Array(n * n).fill(null); // set start vector to center of the first tile this.tileLayer.translation = new Two.Vector(slotSize / 2 + padding, slotSize / 2 + padding); this.queenLayer.translation = this.tileLayer.translation; this.crossLayer.translation = this.tileLayer.translation; // init all layers for (let i = 0; i < n * n; i++) { let x = i % n; let y = Math.floor(i / n); // create tile let tile = new Two.Rectangle(x * slotSize, y * slotSize, tileSize, tileSize); tile.fill = y % 2 == x % 2 ? this.settings.color.tileW : this.settings.color.tileB; this.tiles[i] = tile; // create queen let queen = new Two.Group(); queen.add(new Two.Circle(0 , 0, tileSize / 2 * 0.9)); queen.translation = new Two.Vector(x * slotSize, y * slotSize); queen.fill = this.settings.color.queen; queen.noStroke(); this.queens[i] = queen; // create cross let corner = tileSize * 0.75 / 2; let cross = new Two.Group(); cross.add(new Two.Line(-corner, -corner, corner, corner)); cross.add(new Two.Line(-corner, corner, corner, -corner)); cross.translation = new Two.Vector(x * slotSize, y * slotSize); cross.linewidth = tileSize * 0.1; cross.opacity = 0.8; cross.stroke = this.settings.color.cross; this.crosses[i] = cross; } this.tileLayer.add(this.tiles); this.tileLayer.noStroke(); } /** * Clears the current state of the chessboard. */ clear() { this.literals = new Set(); this.state.forEach((row, y) => row.forEach((_, x) => this.setClear(x, y))); } /** * Sets the state of the chessboard and changes the visual representation by removing and adding queens and crosses to the board. * * @param {Array<String>} state */ setState(state) { /** * @type {Set<String>} */ let _literals = new Set(state); // get removed literals let remove = this.literals.subtract(_literals).map(literal => (literal.substr(0, 1) == '!' ? literal.substr(1) : literal).split(',').map(n => Number(n) - 1)); // get new literals let add = _literals.subtract(this.literals); let queens = add.filter(literal => literal.substr(0, 1) != '!').map(literal => literal.split(',').map(n => Number(n) - 1)); let crosses = add.filter(literal => literal.substr(0, 1) == '!').map(literal => literal.substr(1).split(',').map(n => Number(n) - 1)); // overwrite old literals this.literals = _literals; // update the visuals remove.forEach(([x, y]) => this.setClear(x, y)); queens.forEach(([x, y]) => this.setQueen(x, y)); crosses.forEach(([x, y]) => this.setCross(x, y)); } /** * Clears the given tile of the chessboard by removing the queen and/or cross. * * @param {Number} x - column * @param {Number} y - row */ setClear(x, y) { this.state[y][x] = ' '; // remove queen only if not in literals if (!this.literals.contains((x + 1) + ',' + (y + 1))) this.queenLayer.remove(this.queens[x + y * this.n]); // remove cross only if not in literals if (!this.literals.contains('!' + (x + 1) + ',' + (y + 1))) this.crossLayer.remove(this.crosses[x + y * this.n]); } /** * Sets a queen at the given tile. * * @param {Number} x - column * @param {Number} y - row */ setQueen(x, y) { this.state[y][x] = 'Q'; this.queenLayer.add(this.queens[x + y * this.n]); } /** * Sets a cross at the given tile. * * @param {Number} x - column * @param {Number} y - row */ setCross(x, y) { this.state[y][x] = '.'; this.crossLayer.add(this.crosses[x + y * this.n]); } /** * Returns a ASCII representation of the state. * * @returns {String} */ toString() { let border = '+' + '---+'.repeat(this.n) + '\n'; return border + this.state.map(row => '| ' + row.join(' | ') + ' |\n').join(border) + border; } }
JavaScript
class Action { dispatch(dispatcher) { dispatcher.dispatch(this); } digest() { return { name: this.constructor.name }; } }
JavaScript
class SelectMark extends Action { /** * @param plotSegment plot segment where mark was selected * @param glyph glyph where mark was selected (on a glyph editor or on a chart) * @param mark selected mark * @param glyphIndex index of glyph */ constructor(plotSegment, glyph, mark, glyphIndex = null) { super(); this.plotSegment = plotSegment; this.glyph = glyph; this.mark = mark; this.glyphIndex = glyphIndex; } digest() { return { name: "SelectMark", plotSegment: objectDigest(this.plotSegment), glyph: objectDigest(this.glyph), mark: objectDigest(this.mark), glyphIndex: this.glyphIndex, }; } }
JavaScript
class ClearSelection extends Action { digest() { return { name: "ClearSelection", }; } }
JavaScript
class Scheduler { constructor(schedule) { this.schedule = schedule; } [Now]() { return Date.now(); } [Schedule](callback, delay) { var action = callback; if (delay) { action = async () => { await sleep(delay); callback(); } } this.schedule(action); } }
JavaScript
class AbortError extends Error { /** * @param {String} [msg] The error message */ constructor(msg = "Throttled function aborted") { super(msg) this.name = "AbortError" } }
JavaScript
class Network extends Type(FileType.NetworkFile) { // ## constructor() constructor(opts) { super(); new Unknown(this); this.crc = 0x00000000; this.mem = 0x00000000; this.major = 0x0008; this.minor = 0x0004; this.zot = 0x0000; this.unknown.byte(0x00); this.appearance = 0x05; this.unknown.dword(0xc772bf98); this.zMinTract = this.xMinTract = 0x00; this.zMaxTract = this.xMaxTract = 0x00; this.xTractSize = 0x0002; this.zTractSize = 0x0002; this.sgprops = []; this.GID = 0x00000000; this.TID = 0x00000000; this.IID = 0x00000000; this.unknown.byte(0x01); // Does this exist? Perhaps based on the flag above. // this.matrix3 = new Matrix3(); this.x = 0; this.y = 0; this.z = 0; // Find a way to set the color as 0xffdddbde. this.vertices = [ new Vertex(), new Vertex(), new Vertex(), new Vertex(), ]; this.textureId = 0x00000000; this.unknown.bytes([0, 0, 0, 0, 0]); this.orientation = 0x00; this.unknown.bytes([0x02, 0, 0]); this.networkType = 0x00; this.westConnection = 0x00; this.northConnection = 0x00; this.eastConnection = 0x00; this.southConnection = 0x00; this.crossing = 0; this.crossingBytes = []; this.unknown.bytes([0x00, 0x00, 0x00]); this.xMin = 0; this.xMax = 0; this.yMin = 0; this.yMax = 0; this.zMin = 0; this.zMax = 0; this.unknown.bytes([0x01, 0xa0, 0x00, 0x16]); repeat(4, () => this.unknown.dword(0x00000000)); this.unknown.dword(0x00000002); this.unknown.dword(0x00000000); Object.assign(this, opts); } // ## parse(rs) parse(rs) { let size = rs.dword(); new Unknown(this); this.crc = rs.dword(); this.mem = rs.dword(); this.major = rs.word(); this.minor = rs.word(); this.zot = rs.word(); this.unknown.byte(rs.byte()); this.appearance = rs.byte(); this.unknown.dword(rs.dword()); this.xMinTract = rs.byte(); this.zMinTract = rs.byte(); this.xMaxTract = rs.byte(); this.zMaxTract = rs.byte(); this.xTractSize = rs.word(); this.zTractSize = rs.word(); this.sgprops = rs.sgprops(); this.GID = rs.dword(); this.TID = rs.dword(); this.IID = rs.dword(); this.unknown.byte(rs.byte()); this.x = rs.float(); this.y = rs.float(); this.z = rs.float(); this.vertices = [ rs.vertex(), rs.vertex(), rs.vertex(), rs.vertex(), ]; this.textureId = rs.dword(); this.unknown.bytes(rs.read(5)); this.orientation = rs.byte(); this.unknown.bytes(rs.read(3)); this.networkType = rs.byte(); this.westConnection = rs.byte(); this.northConnection = rs.byte(); this.eastConnection = rs.byte(); this.southConnection = rs.byte(); let crossing = this.crossing = rs.byte(); if (crossing) { this.crossingBytes = rs.read(5); } this.unknown.bytes(rs.read(3)); this.xMin = rs.float(); this.xMax = rs.float(); this.yMin = rs.float(); this.yMax = rs.float(); this.zMin = rs.float(); this.zMax = rs.float(); this.unknown.bytes(rs.read(4)); repeat(4, () => this.unknown.dword(rs.dword())); this.unknown.dword(rs.dword()); this.unknown.dword(rs.dword()); rs.assert(); return this; } // ## toBuffer() toBuffer() { let ws = new WriteBuffer(); const unknown = this.unknown.generator(); ws.dword(this.mem); ws.word(this.major); ws.word(this.minor); ws.word(this.zot); ws.byte(unknown()); ws.byte(this.appearance); ws.dword(unknown()); ws.byte(this.xMinTract); ws.byte(this.zMinTract); ws.byte(this.xMaxTract); ws.byte(this.zMaxTract); ws.word(this.xTractSize); ws.word(this.zTractSize); ws.array(this.sgprops); ws.dword(this.GID); ws.dword(this.TID); ws.dword(this.IID); ws.byte(unknown()); ws.float(this.x); ws.float(this.y); ws.float(this.z); this.vertices.forEach(v => ws.vertex(v)); ws.dword(this.textureId); ws.write(unknown()); ws.byte(this.orientation); ws.write(unknown()); ws.byte(this.networkType); ws.byte(this.westConnection); ws.byte(this.northConnection); ws.byte(this.eastConnection); ws.byte(this.southConnection); ws.byte(this.crossing); if (this.crossing) { ws.write(this.crossingBytes); } ws.write(unknown()); ws.float(this.xMin); ws.float(this.xMax); ws.float(this.yMin); ws.float(this.yMax); ws.float(this.zMin); ws.float(this.zMax); ws.write(unknown()); repeat(4, () => ws.dword(unknown())); ws.dword(unknown()); ws.dword(unknown()); return ws.seal(); } }
JavaScript
class Manager extends Employee{ constructor(name, id, email, officeNumber){ super(name, id, email) this.officeNumber = officeNumber; } getOfficeNumber(){ return this.officeNumber; } getRole(){ return "Manager"; } }
JavaScript
class App { constructor() { this._showflashcard = this._showflashcard.bind(this); //document.addEventListener('title-clicked', this._showflashcard); this._showresult = this._showresult.bind(this); //document.addEventListener('flashcard-finished', this._showresult); this._toMenu = this._toMenu.bind(this); //document.addEventListener('toMenu', this._toMenu); //document.addEventListener('startOver', this._showflashcard); const menuElement = document.querySelector('#menu'); this.menu = new MenuScreen(menuElement, this._showflashcard); //const mainElement = document.querySelector('#main'); //this.flashcards = new FlashcardScreen(mainElement); const resultElement = document.querySelector('#results'); this.results = new ResultsScreen(resultElement, this._showflashcard, this._toMenu); } _showflashcard(title, answer) { // Uncomment this pair of lines to see the "flashcard" screen: if(title != null) this.title = title; var context; for (var val of FLASHCARD_DECKS) { if( val.title === this.title ){ context = val; break; } } const mainElement = document.querySelector('#main'); this.flashcards = new FlashcardScreen(mainElement, context, answer, this._showresult); this.menu.hide(); this.results.hide(); this.flashcards.show(); } _showresult(correct, wrong, answer) { // Uncomment this pair of lines to see the "results" screen: this.flashcards.hide(); this.results.show(correct, wrong, answer); } _toMenu() { this.results.hide(); this.menu.show(); } }
JavaScript
class LocalMappingsProvider extends BaseProvider { /** * @private */ _setup() { this.has.mappings = { read: true, create: true, update: true, delete: true, } this.queue = [] this.localStorageKey = "cocoda-mappings--" + this._path let oldLocalStorageKey = "mappings" // Function that adds URIs to all existing local mappings that don't yet have one let addUris = () => { return localforage.getItem(this.localStorageKey).then(mappings => { mappings = mappings || [] let adjusted = 0 for (let mapping of mappings.filter(m => !m.uri || !m.uri.startsWith(uriPrefix))) { if (mapping.uri) { // Keep previous URI in identifier if (!mapping.identifier) { mapping.identifier = [] } mapping.identifier.push(mapping.uri) } mapping.uri = `${uriPrefix}${uuid()}` adjusted += 1 } if (adjusted) { console.warn(`URIs added to ${adjusted} local mappings.`) } return localforage.setItem(this.localStorageKey, mappings) }) } // Show warning if there are mappings in local storage that use the old local storage key. localforage.getItem(oldLocalStorageKey).then(results => { if (results) { console.warn(`Warning: There is old data in local storage (or IndexedDB, depending on the ) with the key "${oldLocalStorageKey}". This data will not be used anymore. A manual export is necessary to get this data back.`) } }) // Put promise into queue so that getMappings requests are waiting for adjustments to finish this.queue.push( addUris().catch(error => { console.warn("Error when adding URIs to local mappings:", error) }), ) } isAuthorizedFor({ type, action }) { // Allow all for mappings if (type == "mappings" && action != "anonymous") { return true } return false } /** * Returns a Promise that returns an object { mappings, done } with the local mappings and a done function that is supposed to be called when the transaction is finished. * This prevents conflicts when saveMapping is called multiple times simultaneously. * * TODO: There might be a better solution for this... * * @private */ _getMappingsQueue() { let last = _.last(this.queue) || Promise.resolve() return new Promise((resolve) => { function defer() { var res, rej var promise = new Promise((resolve, reject) => { res = resolve rej = reject }) promise.resolve = res promise.reject = rej return promise } let promise = defer() let done = () => { promise.resolve() } this.queue.push(promise) last.then(() => { return localforage.getItem(this.localStorageKey) }).then(mappings => { resolve({ mappings, done }) }) }) } /** * Returns a single mapping. * * @param {Object} config * @param {Object} config.mapping JSKOS mapping * @returns {Object} JSKOS mapping object */ async getMapping({ mapping, ...config }) { config._raw = true if (!mapping || !mapping.uri) { throw new errors.InvalidOrMissingParameterError({ parameter: "mapping" }) } return (await this.getMappings({ ...config, uri: mapping.uri }))[0] } /** * Returns a list of local mappings. * * TODO: Add support for sort (`created` or `modified`) and order (`asc` or `desc`). * TODO: Clean up and use async/await * * @returns {Object[]} array of JSKOS mapping objects */ async getMappings({ from, fromScheme, to, toScheme, creator, type, partOf, offset, limit, direction, mode, identifier, uri } = {}) { let params = {} if (from) { params.from = _.isString(from) ? from : from.uri } if (fromScheme) { params.fromScheme = _.isString(fromScheme) ? { uri: fromScheme } : fromScheme } if (to) { params.to = _.isString(to) ? to : to.uri } if (toScheme) { params.toScheme = _.isString(toScheme) ? { uri: toScheme } : toScheme } if (creator) { params.creator = _.isString(creator) ? creator : jskos.prefLabel(creator) } if (type) { params.type = _.isString(type) ? type : type.uri } if (partOf) { params.partOf = _.isString(partOf) ? partOf : partOf.uri } if (offset) { params.offset = offset } if (limit) { params.limit = limit } if (direction) { params.direction = direction } if (mode) { params.mode = mode } if (identifier) { params.identifier = identifier } if (uri) { params.uri = uri } return this._getMappingsQueue().catch(relatedError => { throw new errors.CDKError({ message: "Could not get mappings from local storage", relatedError }) }).then(({ mappings, done }) => { done() // Check concept with param let checkConcept = (concept, param) => concept.uri == param || (param && concept.notation && concept.notation[0].toLowerCase() == param.toLowerCase()) // Filter mappings according to params (support for from + to) // TODO: - Support more parameters. // TODO: - Move to its own things. // TODO: - Clean all this up. if (params.from || params.to) { mappings = mappings.filter(mapping => { let fromInFrom = null != jskos.conceptsOfMapping(mapping, "from").find(concept => checkConcept(concept, params.from)) let fromInTo = null != jskos.conceptsOfMapping(mapping, "to").find(concept => checkConcept(concept, params.from)) let toInFrom = null != jskos.conceptsOfMapping(mapping, "from").find(concept => checkConcept(concept, params.to)) let toInTo = null != jskos.conceptsOfMapping(mapping, "to").find(concept => checkConcept(concept, params.to)) if (params.direction == "backward") { if (params.mode == "or") { return (params.from && fromInTo) || (params.to && toInFrom) } else { return (!params.from || fromInTo) && (!params.to || toInFrom) } } else if (params.direction == "both") { if (params.mode == "or") { return (params.from && (fromInFrom || fromInTo)) || (params.to && (toInFrom || toInTo)) } else { return ((!params.from || fromInFrom) && (!params.to || toInTo)) || ((!params.from || fromInTo) && (!params.to || toInFrom)) } } else { if (params.mode == "or") { return (params.from && fromInFrom) || (params.to && toInTo) } else { return (!params.from || fromInFrom) && (!params.to || toInTo) } } }) } if (params.fromScheme || params.toScheme) { mappings = mappings.filter(mapping => { let fromInFrom = jskos.compare(mapping.fromScheme, params.fromScheme) let fromInTo = jskos.compare(mapping.toScheme, params.fromScheme) let toInFrom = jskos.compare(mapping.fromScheme, params.toScheme) let toInTo = jskos.compare(mapping.toScheme, params.toScheme) if (params.direction == "backward") { if (params.mode == "or") { return (params.fromScheme && fromInTo) || (params.toScheme && toInFrom) } else { return (!params.fromScheme || fromInTo) && (!params.toScheme || toInFrom) } } else if (params.direction == "both") { if (params.mode == "or") { return (params.fromScheme && (fromInFrom || fromInTo)) || (params.toScheme && (toInFrom || toInTo)) } else { return ((!params.fromScheme || fromInFrom) && (!params.toScheme || toInTo)) || ((!params.fromScheme || fromInTo) && (!params.toScheme || toInFrom)) } } else { if (params.mode == "or") { return (params.fromScheme && fromInFrom) || (params.toScheme && toInTo) } else { return (!params.fromScheme || fromInFrom) && (!params.toScheme || toInTo) } } }) } // creator if (params.creator) { let creators = params.creator.split("|") mappings = mappings.filter(mapping => { return (mapping.creator && mapping.creator.find(creator => creators.includes(jskos.prefLabel(creator)) || creators.includes(creator.uri))) != null }) } // type if (params.type) { mappings = mappings.filter(mapping => (mapping.type || [jskos.defaultMappingType.uri]).includes(params.type)) } // concordance if (params.partOf) { mappings = mappings.filter(mapping => { return mapping.partOf != null && mapping.partOf.find(partOf => jskos.compare(partOf, { uri: params.partOf })) != null }) } // identifier if (params.identifier) { mappings = mappings.filter(mapping => { return params.identifier.split("|").map(identifier => { return (mapping.identifier || []).includes(identifier) || mapping.uri == identifier }).reduce((current, total) => current || total) }) } if (params.uri) { mappings = mappings.filter(mapping => mapping.uri == params.uri) } let totalCount = mappings.length // Sort mappings (default: modified/created date descending) mappings = mappings.sort((a, b) => { let aDate = a.modified || a.created let bDate = b.modified || b.created if (bDate == null) { return -1 } if (aDate == null) { return 1 } if (aDate > bDate) { return -1 } return 1 }) mappings = mappings.slice(params.offset || 0) mappings = mappings.slice(0, params.limit) mappings._totalCount = totalCount return mappings }) } /** * Creates a mapping. * * @param {Object} config * @param {Object} config.mapping JSKOS mapping * @returns {Object} JSKOS mapping object */ async postMapping({ mapping }) { if (!mapping) { throw new errors.InvalidOrMissingParameterError({ parameter: "mapping" }) } let { mappings: localMappings, done } = await this._getMappingsQueue() // Set URI if necessary if (!mapping.uri || !mapping.uri.startsWith(uriPrefix)) { if (mapping.uri) { // Keep previous URI in identifier if (!mapping.identifier) { mapping.identifier = [] } mapping.identifier.push(mapping.uri) } mapping.uri = `${uriPrefix}${uuid()}` } // Check if mapping already exists => throw error if (localMappings.find(m => m.uri == mapping.uri)) { done() throw new errors.InvalidOrMissingParameterError({ parameter: "mapping", message: "Duplicate URI" }) } // Set created/modified if (!mapping.created) { mapping.created = (new Date()).toISOString() } if (!mapping.modified) { mapping.modified = mapping.created } // Add to local mappings localMappings.push(mapping) // Minify mappings before saving back to local storage localMappings = localMappings.map(mapping => jskos.minifyMapping(mapping)) // Write local mappings try { await localforage.setItem(this.localStorageKey, localMappings) done() return mapping } catch (error) { done() throw error } } /** * Overwrites a mapping. * * @param {Object} config * @param {Object} config.mapping JSKOS mapping * @returns {Object} JSKOS mapping object */ async putMapping({ mapping }) { if (!mapping) { throw new errors.InvalidOrMissingParameterError({ parameter: "mapping" }) } let { mappings: localMappings, done } = await this._getMappingsQueue() // Check if mapping already exists => throw error if it doesn't const index = localMappings.findIndex(m => m.uri == mapping.uri) if (index == -1) { done() throw new errors.InvalidOrMissingParameterError({ parameter: "mapping", message: "Mapping not found" }) } // Set created/modified if (!mapping.created) { mapping.created = localMappings[index].created } mapping.modified = (new Date()).toISOString() // Add to local mappings localMappings[index] = mapping // Minify mappings before saving back to local storage localMappings = localMappings.map(mapping => jskos.minifyMapping(mapping)) // Write local mappings try { await localforage.setItem(this.localStorageKey, localMappings) done() return mapping } catch (error) { done() throw error } } /** * Patches a mapping. * * @param {Object} config * @param {Object} mapping JSKOS mapping (or part of mapping) * @returns {Object} JSKOS mapping object */ async patchMapping({ mapping }) { if (!mapping) { throw new errors.InvalidOrMissingParameterError({ parameter: "mapping" }) } let { mappings: localMappings, done } = await this._getMappingsQueue() // Check if mapping already exists => throw error if it doesn't const index = localMappings.findIndex(m => m.uri == mapping.uri) if (index == -1) { done() throw new errors.InvalidOrMissingParameterError({ parameter: "mapping", message: "Mapping not found" }) } // Set created/modified if (!mapping.created) { mapping.created = localMappings[index].created } mapping.modified = (new Date()).toISOString() // Add to local mappings localMappings[index] = Object.assign(localMappings[index], mapping) // Minify mappings before saving back to local storage localMappings = localMappings.map(mapping => jskos.minifyMapping(mapping)) // Write local mappings try { await localforage.setItem(this.localStorageKey, localMappings) done() return mapping } catch (error) { done() throw error } } /** * Removes a mapping from local storage. * * @param {Object} config * @param {Object} mapping JSKOS mapping * @returns {boolean} boolean whether deleting the mapping was successful */ async deleteMapping({ mapping }) { if (!mapping) { throw new errors.InvalidOrMissingParameterError({ parameter: "mapping" }) } let { mappings: localMappings, done } = await this._getMappingsQueue() try { // Remove by URI localMappings = localMappings.filter(m => m.uri != mapping.uri) // Minify mappings before saving back to local storage localMappings = localMappings.map(mapping => jskos.minifyMapping(mapping)) await localforage.setItem(this.localStorageKey, localMappings) done() return true } catch (error) { done() throw error } } }